blob: 9357c3bb0428d6832e75007b0b855460eb258ea3 [file] [log] [blame]
Jason Sams423ebcb2012-08-10 15:40:53 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.renderscript;
18
Yang Ni18314ca2015-04-17 16:51:55 -070019import android.util.Log;
20import android.util.Pair;
Jason Sams08a81582012-09-18 12:32:10 -070021import java.util.ArrayList;
Yang Ni18314ca2015-04-17 16:51:55 -070022import java.util.HashMap;
23import java.util.List;
24import java.util.Map;
Jason Sams423ebcb2012-08-10 15:40:53 -070025
26/**
Yang Ni18314ca2015-04-17 16:51:55 -070027 * A group of kernels that are executed
28 * together with one execution call as if they were a single kernel
Jason Sams08a81582012-09-18 12:32:10 -070029 * <p>
Yang Ni18314ca2015-04-17 16:51:55 -070030 * In addition to kernels, a script group may contain invocable functions as well.
31 * A script group may take inputs and generate outputs, which are consumed and
32 * produced by its member kernels.
33 * Inside a script group, outputs from one kernel can be passed to another kernel as inputs.
34 * The API disallows cyclic dependencies among kernels in a script group,
35 * effectively making it a directed acyclic graph (DAG) of kernels.
Tim Murray2a603892012-10-10 14:21:46 -070036 * <p>
Yang Ni18314ca2015-04-17 16:51:55 -070037 * Grouping kernels together allows for more efficient execution. For example,
38 * runtime and compiler optimization can be applied to reduce computation and
39 * communication overhead, and to make better use of the CPU and the GPU.
Jason Sams423ebcb2012-08-10 15:40:53 -070040 **/
Jason Sams08a81582012-09-18 12:32:10 -070041public final class ScriptGroup extends BaseObj {
Yang Ni18314ca2015-04-17 16:51:55 -070042 private static final String TAG = "ScriptGroup";
Jason Sams423ebcb2012-08-10 15:40:53 -070043 IO mOutputs[];
44 IO mInputs[];
45
46 static class IO {
Jason Sams08a81582012-09-18 12:32:10 -070047 Script.KernelID mKID;
Jason Sams423ebcb2012-08-10 15:40:53 -070048 Allocation mAllocation;
Jason Sams423ebcb2012-08-10 15:40:53 -070049
Jason Sams08a81582012-09-18 12:32:10 -070050 IO(Script.KernelID s) {
51 mKID = s;
Jason Sams423ebcb2012-08-10 15:40:53 -070052 }
53 }
54
Jason Sams08a81582012-09-18 12:32:10 -070055 static class ConnectLine {
56 ConnectLine(Type t, Script.KernelID from, Script.KernelID to) {
57 mFrom = from;
58 mToK = to;
Jason Sams423ebcb2012-08-10 15:40:53 -070059 mAllocationType = t;
60 }
61
Jason Sams08a81582012-09-18 12:32:10 -070062 ConnectLine(Type t, Script.KernelID from, Script.FieldID to) {
63 mFrom = from;
64 mToF = to;
65 mAllocationType = t;
Jason Sams423ebcb2012-08-10 15:40:53 -070066 }
Jason Sams08a81582012-09-18 12:32:10 -070067
68 Script.FieldID mToF;
69 Script.KernelID mToK;
70 Script.KernelID mFrom;
71 Type mAllocationType;
Jason Sams423ebcb2012-08-10 15:40:53 -070072 }
73
74 static class Node {
75 Script mScript;
Jason Sams08a81582012-09-18 12:32:10 -070076 ArrayList<Script.KernelID> mKernels = new ArrayList<Script.KernelID>();
77 ArrayList<ConnectLine> mInputs = new ArrayList<ConnectLine>();
78 ArrayList<ConnectLine> mOutputs = new ArrayList<ConnectLine>();
Tim Murray2a603892012-10-10 14:21:46 -070079 int dagNumber;
Jason Sams423ebcb2012-08-10 15:40:53 -070080
81 Node mNext;
82
83 Node(Script s) {
84 mScript = s;
85 }
Jason Sams423ebcb2012-08-10 15:40:53 -070086 }
87
88
Yang Ni18314ca2015-04-17 16:51:55 -070089 /**
90 * An opaque class for closures
91 * <p>
92 * A closure represents a function call to a kernel or invocable function,
93 * combined with arguments and values for global variables. A closure is
94 * created using the {@link android.renderscript.ScriptGroup.Builder2#addKernel} or
95 * {@link android.renderscript.ScriptGroup.Builder2#addInvoke}
96 * method.
97 */
98
99 public static final class Closure extends BaseObj {
100 private Object[] mArgs;
101 private Allocation mReturnValue;
102 private Map<Script.FieldID, Object> mBindings;
103
104 private Future mReturnFuture;
105 private Map<Script.FieldID, Future> mGlobalFuture;
106
107 private FieldPacker mFP;
108
109 private static final String TAG = "Closure";
110
111 Closure(long id, RenderScript rs) {
112 super(id, rs);
113 }
114
115 Closure(RenderScript rs, Script.KernelID kernelID, Type returnType,
116 Object[] args, Map<Script.FieldID, Object> globals) {
117 super(0, rs);
118
119 mArgs = args;
120 mReturnValue = Allocation.createTyped(rs, returnType);
121 mBindings = globals;
122 mGlobalFuture = new HashMap<Script.FieldID, Future>();
123
124 int numValues = args.length + globals.size();
125
126 long[] fieldIDs = new long[numValues];
127 long[] values = new long[numValues];
128 int[] sizes = new int[numValues];
129 long[] depClosures = new long[numValues];
130 long[] depFieldIDs = new long[numValues];
131
132 int i;
133 for (i = 0; i < args.length; i++) {
Yang Ni18314ca2015-04-17 16:51:55 -0700134 fieldIDs[i] = 0;
Yang Ni870767e2015-05-18 10:56:47 -0700135 retrieveValueAndDependenceInfo(rs, i, null, args[i],
136 values, sizes, depClosures, depFieldIDs);
Yang Ni18314ca2015-04-17 16:51:55 -0700137 }
Yang Ni18314ca2015-04-17 16:51:55 -0700138 for (Map.Entry<Script.FieldID, Object> entry : globals.entrySet()) {
139 Object obj = entry.getValue();
140 Script.FieldID fieldID = entry.getKey();
141 fieldIDs[i] = fieldID.getID(rs);
Yang Ni870767e2015-05-18 10:56:47 -0700142 retrieveValueAndDependenceInfo(rs, i, fieldID, obj,
143 values, sizes, depClosures, depFieldIDs);
Yang Ni18314ca2015-04-17 16:51:55 -0700144 i++;
145 }
146
147 long id = rs.nClosureCreate(kernelID.getID(rs), mReturnValue.getID(rs),
148 fieldIDs, values, sizes, depClosures, depFieldIDs);
149
150 setID(id);
151 }
152
153 Closure(RenderScript rs, Script.InvokeID invokeID,
154 Object[] args, Map<Script.FieldID, Object> globals) {
155 super(0, rs);
156 mFP = FieldPacker.createFromArray(args);
157
158 mArgs = args;
159 mBindings = globals;
160 mGlobalFuture = new HashMap<Script.FieldID, Future>();
161
162 int numValues = globals.size();
163
164 long[] fieldIDs = new long[numValues];
165 long[] values = new long[numValues];
166 int[] sizes = new int[numValues];
167 long[] depClosures = new long[numValues];
168 long[] depFieldIDs = new long[numValues];
169
170 int i = 0;
171 for (Map.Entry<Script.FieldID, Object> entry : globals.entrySet()) {
172 Object obj = entry.getValue();
173 Script.FieldID fieldID = entry.getKey();
174 fieldIDs[i] = fieldID.getID(rs);
Yang Ni870767e2015-05-18 10:56:47 -0700175 retrieveValueAndDependenceInfo(rs, i, fieldID, obj, values,
176 sizes, depClosures, depFieldIDs);
Yang Ni18314ca2015-04-17 16:51:55 -0700177 i++;
178 }
179
180 long id = rs.nInvokeClosureCreate(invokeID.getID(rs), mFP.getData(), fieldIDs,
181 values, sizes);
182
183 setID(id);
184 }
185
Yang Ni870767e2015-05-18 10:56:47 -0700186 private void retrieveValueAndDependenceInfo(RenderScript rs,
187 int index, Script.FieldID fid, Object obj,
Yang Ni18314ca2015-04-17 16:51:55 -0700188 long[] values, int[] sizes,
189 long[] depClosures,
190 long[] depFieldIDs) {
191
192 if (obj instanceof Future) {
193 Future f = (Future)obj;
194 obj = f.getValue();
195 depClosures[index] = f.getClosure().getID(rs);
196 Script.FieldID fieldID = f.getFieldID();
197 depFieldIDs[index] = fieldID != null ? fieldID.getID(rs) : 0;
Yang Ni18314ca2015-04-17 16:51:55 -0700198 } else {
199 depClosures[index] = 0;
200 depFieldIDs[index] = 0;
201 }
202
Yang Ni870767e2015-05-18 10:56:47 -0700203 if (obj instanceof Input) {
204 Input unbound = (Input)obj;
205 if (index < mArgs.length) {
206 unbound.addReference(this, index);
207 } else {
208 unbound.addReference(this, fid);
209 }
210 values[index] = 0;
211 sizes[index] = 0;
212 } else {
213 ValueAndSize vs = new ValueAndSize(rs, obj);
214 values[index] = vs.value;
215 sizes[index] = vs.size;
216 }
Yang Ni18314ca2015-04-17 16:51:55 -0700217 }
218
219 /**
220 * Returns the future for the return value
221 *
222 * @return a future
223 */
224
225 public Future getReturn() {
226 if (mReturnFuture == null) {
227 mReturnFuture = new Future(this, null, mReturnValue);
228 }
229
230 return mReturnFuture;
231 }
232
233 /**
234 * Returns the future for a global variable
235 *
236 * @param field the field ID for the global variable
237 * @return a future
238 */
239
240 public Future getGlobal(Script.FieldID field) {
241 Future f = mGlobalFuture.get(field);
242
243 if (f == null) {
244 // If the field is not bound to this closure, this will return a future
245 // without an associated value (reference). So this is not working for
246 // cross-module (cross-script) linking in this case where a field not
247 // explicitly bound.
Yang Ni870767e2015-05-18 10:56:47 -0700248 Object obj = mBindings.get(field);
249 if (obj instanceof Future) {
250 obj = ((Future)obj).getValue();
251 }
252 f = new Future(this, field, obj);
Yang Ni18314ca2015-04-17 16:51:55 -0700253 mGlobalFuture.put(field, f);
254 }
255
256 return f;
257 }
258
259 void setArg(int index, Object obj) {
Yang Ni870767e2015-05-18 10:56:47 -0700260 if (obj instanceof Future) {
261 obj = ((Future)obj).getValue();
262 }
Yang Ni18314ca2015-04-17 16:51:55 -0700263 mArgs[index] = obj;
264 ValueAndSize vs = new ValueAndSize(mRS, obj);
265 mRS.nClosureSetArg(getID(mRS), index, vs.value, vs.size);
266 }
267
268 void setGlobal(Script.FieldID fieldID, Object obj) {
Yang Ni870767e2015-05-18 10:56:47 -0700269 if (obj instanceof Future) {
270 obj = ((Future)obj).getValue();
271 }
Yang Ni18314ca2015-04-17 16:51:55 -0700272 mBindings.put(fieldID, obj);
273 ValueAndSize vs = new ValueAndSize(mRS, obj);
274 mRS.nClosureSetGlobal(getID(mRS), fieldID.getID(mRS), vs.value, vs.size);
275 }
276
277 private static final class ValueAndSize {
278 public ValueAndSize(RenderScript rs, Object obj) {
279 if (obj instanceof Allocation) {
280 value = ((Allocation)obj).getID(rs);
Yang Ni263cc902015-11-10 13:27:04 -0800281 // Special value for size to tell the runtime and driver that
282 // the value is an Allocation
Yang Ni18314ca2015-04-17 16:51:55 -0700283 size = -1;
284 } else if (obj instanceof Boolean) {
285 value = ((Boolean)obj).booleanValue() ? 1 : 0;
286 size = 4;
287 } else if (obj instanceof Integer) {
288 value = ((Integer)obj).longValue();
289 size = 4;
290 } else if (obj instanceof Long) {
291 value = ((Long)obj).longValue();
292 size = 8;
293 } else if (obj instanceof Float) {
Yang Ni263cc902015-11-10 13:27:04 -0800294 value = Float.floatToRawIntBits(((Float)obj).floatValue());
Yang Ni18314ca2015-04-17 16:51:55 -0700295 size = 4;
296 } else if (obj instanceof Double) {
Yang Ni263cc902015-11-10 13:27:04 -0800297 value = Double.doubleToRawLongBits(((Double)obj).doubleValue());
Yang Ni18314ca2015-04-17 16:51:55 -0700298 size = 8;
299 }
300 }
301 public long value;
302 public int size;
303 }
304 }
305
306 /**
307 * An opaque class for futures
308 * <p>
309 * A future represents an output of a closure, either the return value of
310 * the function, or the value of a global variable written by the function.
311 * A future is created by calling the {@link Closure#getReturn} or
312 * {@link Closure#getGlobal} method.
313 */
314
315 public static final class Future {
316 Closure mClosure;
317 Script.FieldID mFieldID;
318 Object mValue;
319
320 Future(Closure closure, Script.FieldID fieldID, Object value) {
321 mClosure = closure;
322 mFieldID = fieldID;
323 mValue = value;
324 }
325
326 Closure getClosure() { return mClosure; }
327 Script.FieldID getFieldID() { return mFieldID; }
328 Object getValue() { return mValue; }
329 }
330
331 /**
332 * An opaque class for script group inputs
333 * <p>
334 * Created by calling the {@link Builder2#addInput} method. The value
335 * is assigned in {@link ScriptGroup#execute(Object...)} method as
336 * one of its arguments. Arguments to the execute method should be in
337 * the same order as intputs are added using the addInput method.
338 */
339
340 public static final class Input {
341 // Either mFieldID or mArgIndex should be set but not both.
342 List<Pair<Closure, Script.FieldID>> mFieldID;
343 // -1 means unset. Legal values are 0 .. n-1, where n is the number of
344 // arguments for the referencing closure.
345 List<Pair<Closure, Integer>> mArgIndex;
Yang Ni870767e2015-05-18 10:56:47 -0700346 Object mValue;
Yang Ni18314ca2015-04-17 16:51:55 -0700347
348 Input() {
349 mFieldID = new ArrayList<Pair<Closure, Script.FieldID>>();
350 mArgIndex = new ArrayList<Pair<Closure, Integer>>();
351 }
352
353 void addReference(Closure closure, int index) {
354 mArgIndex.add(Pair.create(closure, Integer.valueOf(index)));
355 }
356
357 void addReference(Closure closure, Script.FieldID fieldID) {
358 mFieldID.add(Pair.create(closure, fieldID));
359 }
360
361 void set(Object value) {
Yang Ni870767e2015-05-18 10:56:47 -0700362 mValue = value;
Yang Ni18314ca2015-04-17 16:51:55 -0700363 for (Pair<Closure, Integer> p : mArgIndex) {
364 Closure closure = p.first;
365 int index = p.second.intValue();
366 closure.setArg(index, value);
367 }
368 for (Pair<Closure, Script.FieldID> p : mFieldID) {
369 Closure closure = p.first;
370 Script.FieldID fieldID = p.second;
371 closure.setGlobal(fieldID, value);
372 }
373 }
Yang Ni870767e2015-05-18 10:56:47 -0700374
375 Object get() { return mValue; }
Yang Ni18314ca2015-04-17 16:51:55 -0700376 }
377
378 private String mName;
379 private List<Closure> mClosures;
380 private List<Input> mInputs2;
381 private Future[] mOutputs2;
382
Tim Murray460a0492013-11-19 12:45:54 -0800383 ScriptGroup(long id, RenderScript rs) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700384 super(id, rs);
385 }
386
Yang Ni18314ca2015-04-17 16:51:55 -0700387 ScriptGroup(RenderScript rs, String name, List<Closure> closures,
388 List<Input> inputs, Future[] outputs) {
389 super(0, rs);
390 mName = name;
391 mClosures = closures;
392 mInputs2 = inputs;
393 mOutputs2 = outputs;
394
395 long[] closureIDs = new long[closures.size()];
396 for (int i = 0; i < closureIDs.length; i++) {
397 closureIDs[i] = closures.get(i).getID(rs);
398 }
Yang Ni15fcf612016-03-10 16:12:31 -0800399 long id = rs.nScriptGroup2Create(name, RenderScript.getCachePath(), closureIDs);
Yang Ni18314ca2015-04-17 16:51:55 -0700400 setID(id);
401 }
402
403 /**
404 * Executes a script group
405 *
Yang Ni43563892015-05-12 13:53:38 -0700406 * @param inputs Values for inputs to the script group, in the order as the
407 * inputs are added via {@link Builder2#addInput}.
408 * @return Outputs of the script group as an array of objects, in the order
409 * as futures are passed to {@link Builder2#create}.
Yang Ni18314ca2015-04-17 16:51:55 -0700410 */
411
412 public Object[] execute(Object... inputs) {
413 if (inputs.length < mInputs2.size()) {
414 Log.e(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
415 "less than expected " + mInputs2.size());
416 return null;
417 }
418
419 if (inputs.length > mInputs2.size()) {
420 Log.i(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
421 "more than expected " + mInputs2.size());
422 }
423
424 for (int i = 0; i < mInputs2.size(); i++) {
425 Object obj = inputs[i];
426 if (obj instanceof Future || obj instanceof Input) {
427 Log.e(TAG, this.toString() + ": input " + i +
428 " is a future or unbound value");
429 return null;
430 }
431 Input unbound = mInputs2.get(i);
432 unbound.set(obj);
433 }
434
435 mRS.nScriptGroup2Execute(getID(mRS));
436
437 Object[] outputObjs = new Object[mOutputs2.length];
438 int i = 0;
439 for (Future f : mOutputs2) {
Yang Ni870767e2015-05-18 10:56:47 -0700440 Object output = f.getValue();
441 if (output instanceof Input) {
442 output = ((Input)output).get();
443 }
444 outputObjs[i++] = output;
Yang Ni18314ca2015-04-17 16:51:55 -0700445 }
446 return outputObjs;
447 }
448
Jason Sams08a81582012-09-18 12:32:10 -0700449 /**
450 * Sets an input of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700451 * Allocation to be used for kernels that require an input
452 * Allocation provided from outside of the ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700453 *
Yang Ni18314ca2015-04-17 16:51:55 -0700454 * @deprecated Set arguments to {@link #execute(Object...)} instead.
455 *
Jason Sams08a81582012-09-18 12:32:10 -0700456 * @param s The ID of the kernel where the allocation should be
457 * connected.
458 * @param a The allocation to connect.
459 */
460 public void setInput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700461 for (int ct=0; ct < mInputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700462 if (mInputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700463 mInputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700464 mRS.nScriptGroupSetInput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700465 return;
466 }
467 }
468 throw new RSIllegalArgumentException("Script not found");
469 }
470
Jason Sams08a81582012-09-18 12:32:10 -0700471 /**
472 * Sets an output of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700473 * Allocation to be used for the kernels that require an output
474 * Allocation visible after the ScriptGroup is executed.
Jason Sams08a81582012-09-18 12:32:10 -0700475 *
Yang Ni18314ca2015-04-17 16:51:55 -0700476 * @deprecated Use return value of {@link #execute(Object...)} instead.
477 *
Jason Sams08a81582012-09-18 12:32:10 -0700478 * @param s The ID of the kernel where the allocation should be
479 * connected.
480 * @param a The allocation to connect.
481 */
482 public void setOutput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700483 for (int ct=0; ct < mOutputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700484 if (mOutputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700485 mOutputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700486 mRS.nScriptGroupSetOutput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700487 return;
488 }
489 }
490 throw new RSIllegalArgumentException("Script not found");
491 }
492
Jason Sams08a81582012-09-18 12:32:10 -0700493 /**
494 * Execute the ScriptGroup. This will run all the kernels in
Tim Murrayc11e25c2013-04-09 11:01:01 -0700495 * the ScriptGroup. No internal connection results will be visible
496 * after execution of the ScriptGroup.
Yang Ni18314ca2015-04-17 16:51:55 -0700497 *
498 * @deprecated Use {@link #execute} instead.
499 *
Jason Sams08a81582012-09-18 12:32:10 -0700500 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700501 public void execute() {
Jason Sams08a81582012-09-18 12:32:10 -0700502 mRS.nScriptGroupExecute(getID(mRS));
Jason Sams423ebcb2012-08-10 15:40:53 -0700503 }
504
505
Jason Sams08a81582012-09-18 12:32:10 -0700506 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700507 * Helper class to build a ScriptGroup. A ScriptGroup is
508 * created in two steps.
Jason Sams08a81582012-09-18 12:32:10 -0700509 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700510 * First, all kernels to be used by the ScriptGroup should be added.
Jason Sams08a81582012-09-18 12:32:10 -0700511 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700512 * Second, add connections between kernels. There are two types
513 * of connections: kernel to kernel and kernel to field.
514 * Kernel to kernel allows a kernel's output to be passed to
515 * another kernel as input. Kernel to field allows the output of
516 * one kernel to be bound as a script global. Kernel to kernel is
517 * higher performance and should be used where possible.
Jason Sams08a81582012-09-18 12:32:10 -0700518 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700519 * A ScriptGroup must contain a single directed acyclic graph (DAG); it
520 * cannot contain cycles. Currently, all kernels used in a ScriptGroup
521 * must come from different Script objects. Additionally, all kernels
522 * in a ScriptGroup must have at least one input, output, or internal
523 * connection.
524 * <p>
525 * Once all connections are made, a call to {@link #create} will
Jason Sams08a81582012-09-18 12:32:10 -0700526 * return the ScriptGroup object.
527 *
Yang Ni18314ca2015-04-17 16:51:55 -0700528 * @deprecated Use {@link Builder2} instead.
529 *
Jason Sams08a81582012-09-18 12:32:10 -0700530 */
531 public static final class Builder {
532 private RenderScript mRS;
533 private ArrayList<Node> mNodes = new ArrayList<Node>();
534 private ArrayList<ConnectLine> mLines = new ArrayList<ConnectLine>();
535 private int mKernelCount;
Jason Sams423ebcb2012-08-10 15:40:53 -0700536
Jason Sams08a81582012-09-18 12:32:10 -0700537 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700538 * Create a Builder for generating a ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700539 *
540 *
Tim Murrayc11e25c2013-04-09 11:01:01 -0700541 * @param rs The RenderScript context.
Jason Sams08a81582012-09-18 12:32:10 -0700542 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700543 public Builder(RenderScript rs) {
544 mRS = rs;
545 }
546
Tim Murray091f7cc2012-10-12 12:02:18 -0700547 // do a DFS from original node, looking for original node
548 // any cycle that could be created must contain original node
549 private void validateCycle(Node target, Node original) {
550 for (int ct = 0; ct < target.mOutputs.size(); ct++) {
551 final ConnectLine cl = target.mOutputs.get(ct);
Jason Sams08a81582012-09-18 12:32:10 -0700552 if (cl.mToK != null) {
553 Node tn = findNode(cl.mToK.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700554 if (tn.equals(original)) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700555 throw new RSInvalidStateException("Loops in group not allowed.");
556 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700557 validateCycle(tn, original);
Jason Sams08a81582012-09-18 12:32:10 -0700558 }
559 if (cl.mToF != null) {
560 Node tn = findNode(cl.mToF.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700561 if (tn.equals(original)) {
Jason Sams08a81582012-09-18 12:32:10 -0700562 throw new RSInvalidStateException("Loops in group not allowed.");
563 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700564 validateCycle(tn, original);
Tim Murray2a603892012-10-10 14:21:46 -0700565 }
566 }
567 }
568
569 private void mergeDAGs(int valueUsed, int valueKilled) {
570 for (int ct=0; ct < mNodes.size(); ct++) {
571 if (mNodes.get(ct).dagNumber == valueKilled)
572 mNodes.get(ct).dagNumber = valueUsed;
573 }
574 }
575
576 private void validateDAGRecurse(Node n, int dagNumber) {
577 // combine DAGs if this node has been seen already
578 if (n.dagNumber != 0 && n.dagNumber != dagNumber) {
579 mergeDAGs(n.dagNumber, dagNumber);
580 return;
581 }
582
583 n.dagNumber = dagNumber;
584 for (int ct=0; ct < n.mOutputs.size(); ct++) {
585 final ConnectLine cl = n.mOutputs.get(ct);
586 if (cl.mToK != null) {
587 Node tn = findNode(cl.mToK.mScript);
588 validateDAGRecurse(tn, dagNumber);
589 }
590 if (cl.mToF != null) {
591 Node tn = findNode(cl.mToF.mScript);
592 validateDAGRecurse(tn, dagNumber);
593 }
594 }
595 }
596
597 private void validateDAG() {
598 for (int ct=0; ct < mNodes.size(); ct++) {
599 Node n = mNodes.get(ct);
600 if (n.mInputs.size() == 0) {
601 if (n.mOutputs.size() == 0 && mNodes.size() > 1) {
Yang Ni870767e2015-05-18 10:56:47 -0700602 String msg = "Groups cannot contain unconnected scripts";
603 throw new RSInvalidStateException(msg);
Tim Murray2a603892012-10-10 14:21:46 -0700604 }
605 validateDAGRecurse(n, ct+1);
606 }
607 }
608 int dagNumber = mNodes.get(0).dagNumber;
609 for (int ct=0; ct < mNodes.size(); ct++) {
610 if (mNodes.get(ct).dagNumber != dagNumber) {
611 throw new RSInvalidStateException("Multiple DAGs in group not allowed.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700612 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700613 }
614 }
615
Jason Sams08a81582012-09-18 12:32:10 -0700616 private Node findNode(Script s) {
617 for (int ct=0; ct < mNodes.size(); ct++) {
618 if (s == mNodes.get(ct).mScript) {
619 return mNodes.get(ct);
Jason Sams423ebcb2012-08-10 15:40:53 -0700620 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700621 }
622 return null;
623 }
624
Jason Sams08a81582012-09-18 12:32:10 -0700625 private Node findNode(Script.KernelID k) {
626 for (int ct=0; ct < mNodes.size(); ct++) {
627 Node n = mNodes.get(ct);
628 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
629 if (k == n.mKernels.get(ct2)) {
630 return n;
Jason Sams423ebcb2012-08-10 15:40:53 -0700631 }
632 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700633 }
Jason Sams08a81582012-09-18 12:32:10 -0700634 return null;
635 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700636
Jason Sams08a81582012-09-18 12:32:10 -0700637 /**
638 * Adds a Kernel to the group.
639 *
640 *
641 * @param k The kernel to add.
642 *
643 * @return Builder Returns this.
644 */
645 public Builder addKernel(Script.KernelID k) {
646 if (mLines.size() != 0) {
647 throw new RSInvalidStateException(
648 "Kernels may not be added once connections exist.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700649 }
Jason Sams08a81582012-09-18 12:32:10 -0700650
651 //android.util.Log.v("RSR", "addKernel 1 k=" + k);
652 if (findNode(k) != null) {
653 return this;
654 }
655 //android.util.Log.v("RSR", "addKernel 2 ");
656 mKernelCount++;
657 Node n = findNode(k.mScript);
658 if (n == null) {
659 //android.util.Log.v("RSR", "addKernel 3 ");
660 n = new Node(k.mScript);
661 mNodes.add(n);
662 }
663 n.mKernels.add(k);
664 return this;
665 }
666
667 /**
668 * Adds a connection to the group.
669 *
670 *
671 * @param t The type of the connection. This is used to
672 * determine the kernel launch sizes on the source side
673 * of this connection.
674 * @param from The source for the connection.
675 * @param to The destination of the connection.
676 *
677 * @return Builder Returns this
678 */
679 public Builder addConnection(Type t, Script.KernelID from, Script.FieldID to) {
680 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
681
682 Node nf = findNode(from);
683 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700684 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700685 }
686
687 Node nt = findNode(to.mScript);
688 if (nt == null) {
689 throw new RSInvalidStateException("To script not found.");
690 }
691
692 ConnectLine cl = new ConnectLine(t, from, to);
693 mLines.add(new ConnectLine(t, from, to));
694
695 nf.mOutputs.add(cl);
696 nt.mInputs.add(cl);
Jason Sams423ebcb2012-08-10 15:40:53 -0700697
Tim Murray091f7cc2012-10-12 12:02:18 -0700698 validateCycle(nf, nf);
Jason Sams423ebcb2012-08-10 15:40:53 -0700699 return this;
700 }
701
Jason Sams08a81582012-09-18 12:32:10 -0700702 /**
703 * Adds a connection to the group.
704 *
705 *
706 * @param t The type of the connection. This is used to
707 * determine the kernel launch sizes for both sides of
708 * this connection.
709 * @param from The source for the connection.
710 * @param to The destination of the connection.
711 *
712 * @return Builder Returns this
713 */
714 public Builder addConnection(Type t, Script.KernelID from, Script.KernelID to) {
715 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
716
717 Node nf = findNode(from);
718 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700719 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700720 }
721
722 Node nt = findNode(to);
723 if (nt == null) {
724 throw new RSInvalidStateException("To script not found.");
725 }
726
727 ConnectLine cl = new ConnectLine(t, from, to);
728 mLines.add(new ConnectLine(t, from, to));
729
730 nf.mOutputs.add(cl);
731 nt.mInputs.add(cl);
732
Tim Murray091f7cc2012-10-12 12:02:18 -0700733 validateCycle(nf, nf);
Jason Sams08a81582012-09-18 12:32:10 -0700734 return this;
735 }
736
737
738
739 /**
740 * Creates the Script group.
741 *
742 *
743 * @return ScriptGroup The new ScriptGroup
744 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700745 public ScriptGroup create() {
Tim Murray2a603892012-10-10 14:21:46 -0700746
747 if (mNodes.size() == 0) {
748 throw new RSInvalidStateException("Empty script groups are not allowed");
749 }
750
751 // reset DAG numbers in case we're building a second group
752 for (int ct=0; ct < mNodes.size(); ct++) {
753 mNodes.get(ct).dagNumber = 0;
754 }
755 validateDAG();
756
Jason Sams08a81582012-09-18 12:32:10 -0700757 ArrayList<IO> inputs = new ArrayList<IO>();
758 ArrayList<IO> outputs = new ArrayList<IO>();
Jason Sams423ebcb2012-08-10 15:40:53 -0700759
Ashok Bhat98071552014-02-12 09:54:43 +0000760 long[] kernels = new long[mKernelCount];
Jason Sams08a81582012-09-18 12:32:10 -0700761 int idx = 0;
762 for (int ct=0; ct < mNodes.size(); ct++) {
763 Node n = mNodes.get(ct);
764 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
765 final Script.KernelID kid = n.mKernels.get(ct2);
Ashok Bhat98071552014-02-12 09:54:43 +0000766 kernels[idx++] = kid.getID(mRS);
Jason Sams423ebcb2012-08-10 15:40:53 -0700767
Jason Sams08a81582012-09-18 12:32:10 -0700768 boolean hasInput = false;
769 boolean hasOutput = false;
770 for (int ct3=0; ct3 < n.mInputs.size(); ct3++) {
771 if (n.mInputs.get(ct3).mToK == kid) {
772 hasInput = true;
773 }
774 }
775 for (int ct3=0; ct3 < n.mOutputs.size(); ct3++) {
776 if (n.mOutputs.get(ct3).mFrom == kid) {
777 hasOutput = true;
778 }
779 }
780 if (!hasInput) {
781 inputs.add(new IO(kid));
782 }
783 if (!hasOutput) {
784 outputs.add(new IO(kid));
785 }
786
787 }
788 }
789 if (idx != mKernelCount) {
790 throw new RSRuntimeException("Count mismatch, should not happen.");
791 }
792
Ashok Bhat98071552014-02-12 09:54:43 +0000793 long[] src = new long[mLines.size()];
794 long[] dstk = new long[mLines.size()];
795 long[] dstf = new long[mLines.size()];
796 long[] types = new long[mLines.size()];
Jason Sams08a81582012-09-18 12:32:10 -0700797
798 for (int ct=0; ct < mLines.size(); ct++) {
799 ConnectLine cl = mLines.get(ct);
Ashok Bhat98071552014-02-12 09:54:43 +0000800 src[ct] = cl.mFrom.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700801 if (cl.mToK != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000802 dstk[ct] = cl.mToK.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700803 }
804 if (cl.mToF != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000805 dstf[ct] = cl.mToF.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700806 }
Ashok Bhat98071552014-02-12 09:54:43 +0000807 types[ct] = cl.mAllocationType.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700808 }
809
Tim Murray460a0492013-11-19 12:45:54 -0800810 long id = mRS.nScriptGroupCreate(kernels, src, dstk, dstf, types);
Jason Sams08a81582012-09-18 12:32:10 -0700811 if (id == 0) {
812 throw new RSRuntimeException("Object creation error, should not happen.");
813 }
814
815 ScriptGroup sg = new ScriptGroup(id, mRS);
816 sg.mOutputs = new IO[outputs.size()];
817 for (int ct=0; ct < outputs.size(); ct++) {
818 sg.mOutputs[ct] = outputs.get(ct);
819 }
820
821 sg.mInputs = new IO[inputs.size()];
822 for (int ct=0; ct < inputs.size(); ct++) {
823 sg.mInputs[ct] = inputs.get(ct);
824 }
825
Jason Sams423ebcb2012-08-10 15:40:53 -0700826 return sg;
827 }
828
829 }
830
Yang Ni18314ca2015-04-17 16:51:55 -0700831 /**
832 * Represents a binding of a value to a global variable in a
833 * kernel or invocable function. Used in closure creation.
834 */
835
836 public static final class Binding {
837 private final Script.FieldID mField;
838 private final Object mValue;
839
840 /**
841 * Returns a Binding object that binds value to field
842 *
843 * @param field the Script.FieldID of the global variable
844 * @param value the value
845 */
846
847 public Binding(Script.FieldID field, Object value) {
848 mField = field;
849 mValue = value;
850 }
851
852 /**
853 * Returns the field ID
854 */
855
Yang Ni77eba482015-05-15 09:56:49 -0700856 Script.FieldID getField() { return mField; }
Yang Ni18314ca2015-04-17 16:51:55 -0700857
858 /**
859 * Returns the value
860 */
861
Yang Ni77eba482015-05-15 09:56:49 -0700862 Object getValue() { return mValue; }
Yang Ni18314ca2015-04-17 16:51:55 -0700863 }
864
865 /**
866 * The builder class for creating script groups
867 * <p>
868 * A script group is created using closures (see class {@link Closure}).
869 * A closure is a function call to a kernel or
870 * invocable function. Each function argument or global variable accessed inside
871 * the function is bound to 1) a known value, 2) a script group input
872 * (see class {@link Input}), or 3) a
873 * future (see class {@link Future}).
874 * A future is the output of a closure, either the return value of the
875 * function or a global variable written by that function.
876 * <p>
877 * Closures are created using the {@link #addKernel} or {@link #addInvoke}
878 * methods.
879 * When a closure is created, futures from previously created closures
880 * can be used as its inputs.
881 * External script group inputs can be used as inputs to individual closures as well.
882 * An external script group input is created using the {@link #addInput} method.
883 * A script group is created by a call to the {@link #create} method, which
884 * accepts an array of futures as the outputs for the script group.
885 * <p>
886 * Closures in a script group can be evaluated in any order as long as the
887 * following conditions are met:
888 * 1) a closure must be evaluated before any other closures that take its
889 * futures as inputs;
890 * 2) all closures added before an invoke closure must be evaluated
891 * before it;
892 * and 3) all closures added after an invoke closure must be evaluated after
893 * it.
894 * As a special case, the order that the closures are added is a legal
895 * evaluation order. However, other evaluation orders are possible, including
896 * concurrently evaluating independent closures.
897 */
898
899 public static final class Builder2 {
900 RenderScript mRS;
901 List<Closure> mClosures;
902 List<Input> mInputs;
903 private static final String TAG = "ScriptGroup.Builder2";
904
905 /**
906 * Returns a Builder object
907 *
908 * @param rs the RenderScript context
909 */
910 public Builder2(RenderScript rs) {
911 mRS = rs;
912 mClosures = new ArrayList<Closure>();
913 mInputs = new ArrayList<Input>();
914 }
915
916 /**
917 * Adds a closure for a kernel
918 *
919 * @param k Kernel ID for the kernel function
920 * @param returnType Allocation type for the return value
921 * @param args arguments to the kernel function
922 * @param globalBindings bindings for global variables
923 * @return a closure
924 */
925
926 private Closure addKernelInternal(Script.KernelID k, Type returnType, Object[] args,
927 Map<Script.FieldID, Object> globalBindings) {
928 Closure c = new Closure(mRS, k, returnType, args, globalBindings);
929 mClosures.add(c);
930 return c;
931 }
932
933 /**
934 * Adds a closure for an invocable function
935 *
936 * @param invoke Invoke ID for the invocable function
937 * @param args arguments to the invocable function
938 * @param globalBindings bindings for global variables
939 * @return a closure
940 */
941
942 private Closure addInvokeInternal(Script.InvokeID invoke, Object[] args,
943 Map<Script.FieldID, Object> globalBindings) {
944 Closure c = new Closure(mRS, invoke, args, globalBindings);
945 mClosures.add(c);
946 return c;
947 }
948
949 /**
950 * Adds a script group input
951 *
952 * @return a script group input, which can be used as an argument or a value to
953 * a global variable for creating closures
954 */
955 public Input addInput() {
956 Input unbound = new Input();
957 mInputs.add(unbound);
958 return unbound;
959 }
960
961 /**
962 * Adds a closure for a kernel
963 *
964 * @param k Kernel ID for the kernel function
965 * @param argsAndBindings arguments followed by bindings for global variables
966 * @return a closure
967 */
968
969 public Closure addKernel(Script.KernelID k, Type returnType, Object... argsAndBindings) {
970 ArrayList<Object> args = new ArrayList<Object>();
971 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
972 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
973 return null;
974 }
975 return addKernelInternal(k, returnType, args.toArray(), bindingMap);
976 }
977
978 /**
979 * Adds a closure for an invocable function
980 *
981 * @param invoke Invoke ID for the invocable function
982 * @param argsAndBindings arguments followed by bindings for global variables
983 * @return a closure
984 */
985
986 public Closure addInvoke(Script.InvokeID invoke, Object... argsAndBindings) {
987 ArrayList<Object> args = new ArrayList<Object>();
988 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
989 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
990 return null;
991 }
992 return addInvokeInternal(invoke, args.toArray(), bindingMap);
993 }
994
995 /**
996 * Creates a script group
997 *
998 * @param name name for the script group. Legal names can only contain letters, digits,
999 * '-', or '_'. The name can be no longer than 100 characters.
Yang Nidbb6fd52015-06-24 17:06:10 -07001000 * Try to use unique names, to avoid name conflicts and reduce
1001 * the cost of group creation.
Yang Ni18314ca2015-04-17 16:51:55 -07001002 * @param outputs futures intended as outputs of the script group
1003 * @return a script group
1004 */
1005
1006 public ScriptGroup create(String name, Future... outputs) {
1007 if (name == null || name.isEmpty() || name.length() > 100 ||
1008 !name.equals(name.replaceAll("[^a-zA-Z0-9-]", "_"))) {
1009 throw new RSIllegalArgumentException("invalid script group name");
1010 }
1011 ScriptGroup ret = new ScriptGroup(mRS, name, mClosures, mInputs, outputs);
1012 return ret;
1013 }
1014
1015 private boolean seperateArgsAndBindings(Object[] argsAndBindings,
1016 ArrayList<Object> args,
1017 Map<Script.FieldID, Object> bindingMap) {
1018 int i;
1019 for (i = 0; i < argsAndBindings.length; i++) {
1020 if (argsAndBindings[i] instanceof Binding) {
1021 break;
1022 }
1023 args.add(argsAndBindings[i]);
1024 }
1025
1026 for (; i < argsAndBindings.length; i++) {
1027 if (!(argsAndBindings[i] instanceof Binding)) {
1028 return false;
1029 }
1030 Binding b = (Binding)argsAndBindings[i];
1031 bindingMap.put(b.getField(), b.getValue());
1032 }
1033
1034 return true;
1035 }
1036
1037 }
Jason Sams423ebcb2012-08-10 15:40:53 -07001038
1039}