blob: be8b0fd7791170f5872ae79075cf9a2522fc4140 [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++) {
134 Object obj = args[i];
135 fieldIDs[i] = 0;
136 if (obj instanceof Input) {
137 Input unbound = (Input)obj;
138 unbound.addReference(this, i);
139 } else {
140 retrieveValueAndDependenceInfo(rs, i, args[i], values, sizes,
141 depClosures, depFieldIDs);
142 }
143 }
144
145 for (Map.Entry<Script.FieldID, Object> entry : globals.entrySet()) {
146 Object obj = entry.getValue();
147 Script.FieldID fieldID = entry.getKey();
148 fieldIDs[i] = fieldID.getID(rs);
149 if (obj instanceof Input) {
150 Input unbound = (Input)obj;
151 unbound.addReference(this, fieldID);
152 } else {
153 retrieveValueAndDependenceInfo(rs, i, obj, values,
154 sizes, depClosures, depFieldIDs);
155 }
156 i++;
157 }
158
159 long id = rs.nClosureCreate(kernelID.getID(rs), mReturnValue.getID(rs),
160 fieldIDs, values, sizes, depClosures, depFieldIDs);
161
162 setID(id);
163 }
164
165 Closure(RenderScript rs, Script.InvokeID invokeID,
166 Object[] args, Map<Script.FieldID, Object> globals) {
167 super(0, rs);
168 mFP = FieldPacker.createFromArray(args);
169
170 mArgs = args;
171 mBindings = globals;
172 mGlobalFuture = new HashMap<Script.FieldID, Future>();
173
174 int numValues = globals.size();
175
176 long[] fieldIDs = new long[numValues];
177 long[] values = new long[numValues];
178 int[] sizes = new int[numValues];
179 long[] depClosures = new long[numValues];
180 long[] depFieldIDs = new long[numValues];
181
182 int i = 0;
183 for (Map.Entry<Script.FieldID, Object> entry : globals.entrySet()) {
184 Object obj = entry.getValue();
185 Script.FieldID fieldID = entry.getKey();
186 fieldIDs[i] = fieldID.getID(rs);
187 if (obj instanceof Input) {
188 Input unbound = (Input)obj;
189 unbound.addReference(this, fieldID);
190 } else {
191 retrieveValueAndDependenceInfo(rs, i, obj, values,
192 sizes, depClosures, depFieldIDs);
193 }
194 i++;
195 }
196
197 long id = rs.nInvokeClosureCreate(invokeID.getID(rs), mFP.getData(), fieldIDs,
198 values, sizes);
199
200 setID(id);
201 }
202
203 private static
204 void retrieveValueAndDependenceInfo(RenderScript rs,
205 int index, Object obj,
206 long[] values, int[] sizes,
207 long[] depClosures,
208 long[] depFieldIDs) {
209
210 if (obj instanceof Future) {
211 Future f = (Future)obj;
212 obj = f.getValue();
213 depClosures[index] = f.getClosure().getID(rs);
214 Script.FieldID fieldID = f.getFieldID();
215 depFieldIDs[index] = fieldID != null ? fieldID.getID(rs) : 0;
216 if (obj == null) {
217 // Value is originally created by the owner closure
218 values[index] = 0;
219 sizes[index] = 0;
220 return;
221 }
222 } else {
223 depClosures[index] = 0;
224 depFieldIDs[index] = 0;
225 }
226
227 ValueAndSize vs = new ValueAndSize(rs, obj);
228 values[index] = vs.value;
229 sizes[index] = vs.size;
230 }
231
232 /**
233 * Returns the future for the return value
234 *
235 * @return a future
236 */
237
238 public Future getReturn() {
239 if (mReturnFuture == null) {
240 mReturnFuture = new Future(this, null, mReturnValue);
241 }
242
243 return mReturnFuture;
244 }
245
246 /**
247 * Returns the future for a global variable
248 *
249 * @param field the field ID for the global variable
250 * @return a future
251 */
252
253 public Future getGlobal(Script.FieldID field) {
254 Future f = mGlobalFuture.get(field);
255
256 if (f == null) {
257 // If the field is not bound to this closure, this will return a future
258 // without an associated value (reference). So this is not working for
259 // cross-module (cross-script) linking in this case where a field not
260 // explicitly bound.
261 f = new Future(this, field, mBindings.get(field));
262 mGlobalFuture.put(field, f);
263 }
264
265 return f;
266 }
267
268 void setArg(int index, Object obj) {
269 mArgs[index] = obj;
270 ValueAndSize vs = new ValueAndSize(mRS, obj);
271 mRS.nClosureSetArg(getID(mRS), index, vs.value, vs.size);
272 }
273
274 void setGlobal(Script.FieldID fieldID, Object obj) {
275 mBindings.put(fieldID, obj);
276 ValueAndSize vs = new ValueAndSize(mRS, obj);
277 mRS.nClosureSetGlobal(getID(mRS), fieldID.getID(mRS), vs.value, vs.size);
278 }
279
280 private static final class ValueAndSize {
281 public ValueAndSize(RenderScript rs, Object obj) {
282 if (obj instanceof Allocation) {
283 value = ((Allocation)obj).getID(rs);
284 size = -1;
285 } else if (obj instanceof Boolean) {
286 value = ((Boolean)obj).booleanValue() ? 1 : 0;
287 size = 4;
288 } else if (obj instanceof Integer) {
289 value = ((Integer)obj).longValue();
290 size = 4;
291 } else if (obj instanceof Long) {
292 value = ((Long)obj).longValue();
293 size = 8;
294 } else if (obj instanceof Float) {
295 value = ((Float)obj).longValue();
296 size = 4;
297 } else if (obj instanceof Double) {
298 value = ((Double)obj).longValue();
299 size = 8;
300 }
301 }
302 public long value;
303 public int size;
304 }
305 }
306
307 /**
308 * An opaque class for futures
309 * <p>
310 * A future represents an output of a closure, either the return value of
311 * the function, or the value of a global variable written by the function.
312 * A future is created by calling the {@link Closure#getReturn} or
313 * {@link Closure#getGlobal} method.
314 */
315
316 public static final class Future {
317 Closure mClosure;
318 Script.FieldID mFieldID;
319 Object mValue;
320
321 Future(Closure closure, Script.FieldID fieldID, Object value) {
322 mClosure = closure;
323 mFieldID = fieldID;
324 mValue = value;
325 }
326
327 Closure getClosure() { return mClosure; }
328 Script.FieldID getFieldID() { return mFieldID; }
329 Object getValue() { return mValue; }
330 }
331
332 /**
333 * An opaque class for script group inputs
334 * <p>
335 * Created by calling the {@link Builder2#addInput} method. The value
336 * is assigned in {@link ScriptGroup#execute(Object...)} method as
337 * one of its arguments. Arguments to the execute method should be in
338 * the same order as intputs are added using the addInput method.
339 */
340
341 public static final class Input {
342 // Either mFieldID or mArgIndex should be set but not both.
343 List<Pair<Closure, Script.FieldID>> mFieldID;
344 // -1 means unset. Legal values are 0 .. n-1, where n is the number of
345 // arguments for the referencing closure.
346 List<Pair<Closure, Integer>> mArgIndex;
347
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) {
362 for (Pair<Closure, Integer> p : mArgIndex) {
363 Closure closure = p.first;
364 int index = p.second.intValue();
365 closure.setArg(index, value);
366 }
367 for (Pair<Closure, Script.FieldID> p : mFieldID) {
368 Closure closure = p.first;
369 Script.FieldID fieldID = p.second;
370 closure.setGlobal(fieldID, value);
371 }
372 }
373 }
374
375 private String mName;
376 private List<Closure> mClosures;
377 private List<Input> mInputs2;
378 private Future[] mOutputs2;
379
Tim Murray460a0492013-11-19 12:45:54 -0800380 ScriptGroup(long id, RenderScript rs) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700381 super(id, rs);
382 }
383
Yang Ni18314ca2015-04-17 16:51:55 -0700384 ScriptGroup(RenderScript rs, String name, List<Closure> closures,
385 List<Input> inputs, Future[] outputs) {
386 super(0, rs);
387 mName = name;
388 mClosures = closures;
389 mInputs2 = inputs;
390 mOutputs2 = outputs;
391
392 long[] closureIDs = new long[closures.size()];
393 for (int i = 0; i < closureIDs.length; i++) {
394 closureIDs[i] = closures.get(i).getID(rs);
395 }
396 long id = rs.nScriptGroup2Create(name, ScriptC.mCachePath, closureIDs);
397 setID(id);
398 }
399
400 /**
401 * Executes a script group
402 *
403 * @param inputs inputs to the script group
404 * @return outputs of the script group as an array of objects
405 */
406
407 public Object[] execute(Object... inputs) {
408 if (inputs.length < mInputs2.size()) {
409 Log.e(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
410 "less than expected " + mInputs2.size());
411 return null;
412 }
413
414 if (inputs.length > mInputs2.size()) {
415 Log.i(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
416 "more than expected " + mInputs2.size());
417 }
418
419 for (int i = 0; i < mInputs2.size(); i++) {
420 Object obj = inputs[i];
421 if (obj instanceof Future || obj instanceof Input) {
422 Log.e(TAG, this.toString() + ": input " + i +
423 " is a future or unbound value");
424 return null;
425 }
426 Input unbound = mInputs2.get(i);
427 unbound.set(obj);
428 }
429
430 mRS.nScriptGroup2Execute(getID(mRS));
431
432 Object[] outputObjs = new Object[mOutputs2.length];
433 int i = 0;
434 for (Future f : mOutputs2) {
435 outputObjs[i++] = f.getValue();
436 }
437 return outputObjs;
438 }
439
Jason Sams08a81582012-09-18 12:32:10 -0700440 /**
441 * Sets an input of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700442 * Allocation to be used for kernels that require an input
443 * Allocation provided from outside of the ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700444 *
Yang Ni18314ca2015-04-17 16:51:55 -0700445 * @deprecated Set arguments to {@link #execute(Object...)} instead.
446 *
Jason Sams08a81582012-09-18 12:32:10 -0700447 * @param s The ID of the kernel where the allocation should be
448 * connected.
449 * @param a The allocation to connect.
450 */
451 public void setInput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700452 for (int ct=0; ct < mInputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700453 if (mInputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700454 mInputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700455 mRS.nScriptGroupSetInput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700456 return;
457 }
458 }
459 throw new RSIllegalArgumentException("Script not found");
460 }
461
Jason Sams08a81582012-09-18 12:32:10 -0700462 /**
463 * Sets an output of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700464 * Allocation to be used for the kernels that require an output
465 * Allocation visible after the ScriptGroup is executed.
Jason Sams08a81582012-09-18 12:32:10 -0700466 *
Yang Ni18314ca2015-04-17 16:51:55 -0700467 * @deprecated Use return value of {@link #execute(Object...)} instead.
468 *
Jason Sams08a81582012-09-18 12:32:10 -0700469 * @param s The ID of the kernel where the allocation should be
470 * connected.
471 * @param a The allocation to connect.
472 */
473 public void setOutput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700474 for (int ct=0; ct < mOutputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700475 if (mOutputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700476 mOutputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700477 mRS.nScriptGroupSetOutput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700478 return;
479 }
480 }
481 throw new RSIllegalArgumentException("Script not found");
482 }
483
Jason Sams08a81582012-09-18 12:32:10 -0700484 /**
485 * Execute the ScriptGroup. This will run all the kernels in
Tim Murrayc11e25c2013-04-09 11:01:01 -0700486 * the ScriptGroup. No internal connection results will be visible
487 * after execution of the ScriptGroup.
Yang Ni18314ca2015-04-17 16:51:55 -0700488 *
489 * @deprecated Use {@link #execute} instead.
490 *
Jason Sams08a81582012-09-18 12:32:10 -0700491 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700492 public void execute() {
Jason Sams08a81582012-09-18 12:32:10 -0700493 mRS.nScriptGroupExecute(getID(mRS));
Jason Sams423ebcb2012-08-10 15:40:53 -0700494 }
495
496
Jason Sams08a81582012-09-18 12:32:10 -0700497 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700498 * Helper class to build a ScriptGroup. A ScriptGroup is
499 * created in two steps.
Jason Sams08a81582012-09-18 12:32:10 -0700500 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700501 * First, all kernels to be used by the ScriptGroup should be added.
Jason Sams08a81582012-09-18 12:32:10 -0700502 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700503 * Second, add connections between kernels. There are two types
504 * of connections: kernel to kernel and kernel to field.
505 * Kernel to kernel allows a kernel's output to be passed to
506 * another kernel as input. Kernel to field allows the output of
507 * one kernel to be bound as a script global. Kernel to kernel is
508 * higher performance and should be used where possible.
Jason Sams08a81582012-09-18 12:32:10 -0700509 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700510 * A ScriptGroup must contain a single directed acyclic graph (DAG); it
511 * cannot contain cycles. Currently, all kernels used in a ScriptGroup
512 * must come from different Script objects. Additionally, all kernels
513 * in a ScriptGroup must have at least one input, output, or internal
514 * connection.
515 * <p>
516 * Once all connections are made, a call to {@link #create} will
Jason Sams08a81582012-09-18 12:32:10 -0700517 * return the ScriptGroup object.
518 *
Yang Ni18314ca2015-04-17 16:51:55 -0700519 * @deprecated Use {@link Builder2} instead.
520 *
Jason Sams08a81582012-09-18 12:32:10 -0700521 */
522 public static final class Builder {
523 private RenderScript mRS;
524 private ArrayList<Node> mNodes = new ArrayList<Node>();
525 private ArrayList<ConnectLine> mLines = new ArrayList<ConnectLine>();
526 private int mKernelCount;
Jason Sams423ebcb2012-08-10 15:40:53 -0700527
Jason Sams08a81582012-09-18 12:32:10 -0700528 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700529 * Create a Builder for generating a ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700530 *
531 *
Tim Murrayc11e25c2013-04-09 11:01:01 -0700532 * @param rs The RenderScript context.
Jason Sams08a81582012-09-18 12:32:10 -0700533 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700534 public Builder(RenderScript rs) {
535 mRS = rs;
536 }
537
Tim Murray091f7cc2012-10-12 12:02:18 -0700538 // do a DFS from original node, looking for original node
539 // any cycle that could be created must contain original node
540 private void validateCycle(Node target, Node original) {
541 for (int ct = 0; ct < target.mOutputs.size(); ct++) {
542 final ConnectLine cl = target.mOutputs.get(ct);
Jason Sams08a81582012-09-18 12:32:10 -0700543 if (cl.mToK != null) {
544 Node tn = findNode(cl.mToK.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700545 if (tn.equals(original)) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700546 throw new RSInvalidStateException("Loops in group not allowed.");
547 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700548 validateCycle(tn, original);
Jason Sams08a81582012-09-18 12:32:10 -0700549 }
550 if (cl.mToF != null) {
551 Node tn = findNode(cl.mToF.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700552 if (tn.equals(original)) {
Jason Sams08a81582012-09-18 12:32:10 -0700553 throw new RSInvalidStateException("Loops in group not allowed.");
554 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700555 validateCycle(tn, original);
Tim Murray2a603892012-10-10 14:21:46 -0700556 }
557 }
558 }
559
560 private void mergeDAGs(int valueUsed, int valueKilled) {
561 for (int ct=0; ct < mNodes.size(); ct++) {
562 if (mNodes.get(ct).dagNumber == valueKilled)
563 mNodes.get(ct).dagNumber = valueUsed;
564 }
565 }
566
567 private void validateDAGRecurse(Node n, int dagNumber) {
568 // combine DAGs if this node has been seen already
569 if (n.dagNumber != 0 && n.dagNumber != dagNumber) {
570 mergeDAGs(n.dagNumber, dagNumber);
571 return;
572 }
573
574 n.dagNumber = dagNumber;
575 for (int ct=0; ct < n.mOutputs.size(); ct++) {
576 final ConnectLine cl = n.mOutputs.get(ct);
577 if (cl.mToK != null) {
578 Node tn = findNode(cl.mToK.mScript);
579 validateDAGRecurse(tn, dagNumber);
580 }
581 if (cl.mToF != null) {
582 Node tn = findNode(cl.mToF.mScript);
583 validateDAGRecurse(tn, dagNumber);
584 }
585 }
586 }
587
588 private void validateDAG() {
589 for (int ct=0; ct < mNodes.size(); ct++) {
590 Node n = mNodes.get(ct);
591 if (n.mInputs.size() == 0) {
592 if (n.mOutputs.size() == 0 && mNodes.size() > 1) {
593 throw new RSInvalidStateException("Groups cannot contain unconnected scripts");
594 }
595 validateDAGRecurse(n, ct+1);
596 }
597 }
598 int dagNumber = mNodes.get(0).dagNumber;
599 for (int ct=0; ct < mNodes.size(); ct++) {
600 if (mNodes.get(ct).dagNumber != dagNumber) {
601 throw new RSInvalidStateException("Multiple DAGs in group not allowed.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700602 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700603 }
604 }
605
Jason Sams08a81582012-09-18 12:32:10 -0700606 private Node findNode(Script s) {
607 for (int ct=0; ct < mNodes.size(); ct++) {
608 if (s == mNodes.get(ct).mScript) {
609 return mNodes.get(ct);
Jason Sams423ebcb2012-08-10 15:40:53 -0700610 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700611 }
612 return null;
613 }
614
Jason Sams08a81582012-09-18 12:32:10 -0700615 private Node findNode(Script.KernelID k) {
616 for (int ct=0; ct < mNodes.size(); ct++) {
617 Node n = mNodes.get(ct);
618 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
619 if (k == n.mKernels.get(ct2)) {
620 return n;
Jason Sams423ebcb2012-08-10 15:40:53 -0700621 }
622 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700623 }
Jason Sams08a81582012-09-18 12:32:10 -0700624 return null;
625 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700626
Jason Sams08a81582012-09-18 12:32:10 -0700627 /**
628 * Adds a Kernel to the group.
629 *
630 *
631 * @param k The kernel to add.
632 *
633 * @return Builder Returns this.
634 */
635 public Builder addKernel(Script.KernelID k) {
636 if (mLines.size() != 0) {
637 throw new RSInvalidStateException(
638 "Kernels may not be added once connections exist.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700639 }
Jason Sams08a81582012-09-18 12:32:10 -0700640
641 //android.util.Log.v("RSR", "addKernel 1 k=" + k);
642 if (findNode(k) != null) {
643 return this;
644 }
645 //android.util.Log.v("RSR", "addKernel 2 ");
646 mKernelCount++;
647 Node n = findNode(k.mScript);
648 if (n == null) {
649 //android.util.Log.v("RSR", "addKernel 3 ");
650 n = new Node(k.mScript);
651 mNodes.add(n);
652 }
653 n.mKernels.add(k);
654 return this;
655 }
656
657 /**
658 * Adds a connection to the group.
659 *
660 *
661 * @param t The type of the connection. This is used to
662 * determine the kernel launch sizes on the source side
663 * of this connection.
664 * @param from The source for the connection.
665 * @param to The destination of the connection.
666 *
667 * @return Builder Returns this
668 */
669 public Builder addConnection(Type t, Script.KernelID from, Script.FieldID to) {
670 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
671
672 Node nf = findNode(from);
673 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700674 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700675 }
676
677 Node nt = findNode(to.mScript);
678 if (nt == null) {
679 throw new RSInvalidStateException("To script not found.");
680 }
681
682 ConnectLine cl = new ConnectLine(t, from, to);
683 mLines.add(new ConnectLine(t, from, to));
684
685 nf.mOutputs.add(cl);
686 nt.mInputs.add(cl);
Jason Sams423ebcb2012-08-10 15:40:53 -0700687
Tim Murray091f7cc2012-10-12 12:02:18 -0700688 validateCycle(nf, nf);
Jason Sams423ebcb2012-08-10 15:40:53 -0700689 return this;
690 }
691
Jason Sams08a81582012-09-18 12:32:10 -0700692 /**
693 * Adds a connection to the group.
694 *
695 *
696 * @param t The type of the connection. This is used to
697 * determine the kernel launch sizes for both sides of
698 * this connection.
699 * @param from The source for the connection.
700 * @param to The destination of the connection.
701 *
702 * @return Builder Returns this
703 */
704 public Builder addConnection(Type t, Script.KernelID from, Script.KernelID to) {
705 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
706
707 Node nf = findNode(from);
708 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700709 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700710 }
711
712 Node nt = findNode(to);
713 if (nt == null) {
714 throw new RSInvalidStateException("To script not found.");
715 }
716
717 ConnectLine cl = new ConnectLine(t, from, to);
718 mLines.add(new ConnectLine(t, from, to));
719
720 nf.mOutputs.add(cl);
721 nt.mInputs.add(cl);
722
Tim Murray091f7cc2012-10-12 12:02:18 -0700723 validateCycle(nf, nf);
Jason Sams08a81582012-09-18 12:32:10 -0700724 return this;
725 }
726
727
728
729 /**
730 * Creates the Script group.
731 *
732 *
733 * @return ScriptGroup The new ScriptGroup
734 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700735 public ScriptGroup create() {
Tim Murray2a603892012-10-10 14:21:46 -0700736
737 if (mNodes.size() == 0) {
738 throw new RSInvalidStateException("Empty script groups are not allowed");
739 }
740
741 // reset DAG numbers in case we're building a second group
742 for (int ct=0; ct < mNodes.size(); ct++) {
743 mNodes.get(ct).dagNumber = 0;
744 }
745 validateDAG();
746
Jason Sams08a81582012-09-18 12:32:10 -0700747 ArrayList<IO> inputs = new ArrayList<IO>();
748 ArrayList<IO> outputs = new ArrayList<IO>();
Jason Sams423ebcb2012-08-10 15:40:53 -0700749
Ashok Bhat98071552014-02-12 09:54:43 +0000750 long[] kernels = new long[mKernelCount];
Jason Sams08a81582012-09-18 12:32:10 -0700751 int idx = 0;
752 for (int ct=0; ct < mNodes.size(); ct++) {
753 Node n = mNodes.get(ct);
754 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
755 final Script.KernelID kid = n.mKernels.get(ct2);
Ashok Bhat98071552014-02-12 09:54:43 +0000756 kernels[idx++] = kid.getID(mRS);
Jason Sams423ebcb2012-08-10 15:40:53 -0700757
Jason Sams08a81582012-09-18 12:32:10 -0700758 boolean hasInput = false;
759 boolean hasOutput = false;
760 for (int ct3=0; ct3 < n.mInputs.size(); ct3++) {
761 if (n.mInputs.get(ct3).mToK == kid) {
762 hasInput = true;
763 }
764 }
765 for (int ct3=0; ct3 < n.mOutputs.size(); ct3++) {
766 if (n.mOutputs.get(ct3).mFrom == kid) {
767 hasOutput = true;
768 }
769 }
770 if (!hasInput) {
771 inputs.add(new IO(kid));
772 }
773 if (!hasOutput) {
774 outputs.add(new IO(kid));
775 }
776
777 }
778 }
779 if (idx != mKernelCount) {
780 throw new RSRuntimeException("Count mismatch, should not happen.");
781 }
782
Ashok Bhat98071552014-02-12 09:54:43 +0000783 long[] src = new long[mLines.size()];
784 long[] dstk = new long[mLines.size()];
785 long[] dstf = new long[mLines.size()];
786 long[] types = new long[mLines.size()];
Jason Sams08a81582012-09-18 12:32:10 -0700787
788 for (int ct=0; ct < mLines.size(); ct++) {
789 ConnectLine cl = mLines.get(ct);
Ashok Bhat98071552014-02-12 09:54:43 +0000790 src[ct] = cl.mFrom.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700791 if (cl.mToK != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000792 dstk[ct] = cl.mToK.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700793 }
794 if (cl.mToF != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000795 dstf[ct] = cl.mToF.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700796 }
Ashok Bhat98071552014-02-12 09:54:43 +0000797 types[ct] = cl.mAllocationType.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700798 }
799
Tim Murray460a0492013-11-19 12:45:54 -0800800 long id = mRS.nScriptGroupCreate(kernels, src, dstk, dstf, types);
Jason Sams08a81582012-09-18 12:32:10 -0700801 if (id == 0) {
802 throw new RSRuntimeException("Object creation error, should not happen.");
803 }
804
805 ScriptGroup sg = new ScriptGroup(id, mRS);
806 sg.mOutputs = new IO[outputs.size()];
807 for (int ct=0; ct < outputs.size(); ct++) {
808 sg.mOutputs[ct] = outputs.get(ct);
809 }
810
811 sg.mInputs = new IO[inputs.size()];
812 for (int ct=0; ct < inputs.size(); ct++) {
813 sg.mInputs[ct] = inputs.get(ct);
814 }
815
Jason Sams423ebcb2012-08-10 15:40:53 -0700816 return sg;
817 }
818
819 }
820
Yang Ni18314ca2015-04-17 16:51:55 -0700821 /**
822 * Represents a binding of a value to a global variable in a
823 * kernel or invocable function. Used in closure creation.
824 */
825
826 public static final class Binding {
827 private final Script.FieldID mField;
828 private final Object mValue;
829
830 /**
831 * Returns a Binding object that binds value to field
832 *
833 * @param field the Script.FieldID of the global variable
834 * @param value the value
835 */
836
837 public Binding(Script.FieldID field, Object value) {
838 mField = field;
839 mValue = value;
840 }
841
842 /**
843 * Returns the field ID
844 */
845
846 public Script.FieldID getField() { return mField; }
847
848 /**
849 * Returns the value
850 */
851
852 public Object getValue() { return mValue; }
853 }
854
855 /**
856 * The builder class for creating script groups
857 * <p>
858 * A script group is created using closures (see class {@link Closure}).
859 * A closure is a function call to a kernel or
860 * invocable function. Each function argument or global variable accessed inside
861 * the function is bound to 1) a known value, 2) a script group input
862 * (see class {@link Input}), or 3) a
863 * future (see class {@link Future}).
864 * A future is the output of a closure, either the return value of the
865 * function or a global variable written by that function.
866 * <p>
867 * Closures are created using the {@link #addKernel} or {@link #addInvoke}
868 * methods.
869 * When a closure is created, futures from previously created closures
870 * can be used as its inputs.
871 * External script group inputs can be used as inputs to individual closures as well.
872 * An external script group input is created using the {@link #addInput} method.
873 * A script group is created by a call to the {@link #create} method, which
874 * accepts an array of futures as the outputs for the script group.
875 * <p>
876 * Closures in a script group can be evaluated in any order as long as the
877 * following conditions are met:
878 * 1) a closure must be evaluated before any other closures that take its
879 * futures as inputs;
880 * 2) all closures added before an invoke closure must be evaluated
881 * before it;
882 * and 3) all closures added after an invoke closure must be evaluated after
883 * it.
884 * As a special case, the order that the closures are added is a legal
885 * evaluation order. However, other evaluation orders are possible, including
886 * concurrently evaluating independent closures.
887 */
888
889 public static final class Builder2 {
890 RenderScript mRS;
891 List<Closure> mClosures;
892 List<Input> mInputs;
893 private static final String TAG = "ScriptGroup.Builder2";
894
895 /**
896 * Returns a Builder object
897 *
898 * @param rs the RenderScript context
899 */
900 public Builder2(RenderScript rs) {
901 mRS = rs;
902 mClosures = new ArrayList<Closure>();
903 mInputs = new ArrayList<Input>();
904 }
905
906 /**
907 * Adds a closure for a kernel
908 *
909 * @param k Kernel ID for the kernel function
910 * @param returnType Allocation type for the return value
911 * @param args arguments to the kernel function
912 * @param globalBindings bindings for global variables
913 * @return a closure
914 */
915
916 private Closure addKernelInternal(Script.KernelID k, Type returnType, Object[] args,
917 Map<Script.FieldID, Object> globalBindings) {
918 Closure c = new Closure(mRS, k, returnType, args, globalBindings);
919 mClosures.add(c);
920 return c;
921 }
922
923 /**
924 * Adds a closure for an invocable function
925 *
926 * @param invoke Invoke ID for the invocable function
927 * @param args arguments to the invocable function
928 * @param globalBindings bindings for global variables
929 * @return a closure
930 */
931
932 private Closure addInvokeInternal(Script.InvokeID invoke, Object[] args,
933 Map<Script.FieldID, Object> globalBindings) {
934 Closure c = new Closure(mRS, invoke, args, globalBindings);
935 mClosures.add(c);
936 return c;
937 }
938
939 /**
940 * Adds a script group input
941 *
942 * @return a script group input, which can be used as an argument or a value to
943 * a global variable for creating closures
944 */
945 public Input addInput() {
946 Input unbound = new Input();
947 mInputs.add(unbound);
948 return unbound;
949 }
950
951 /**
952 * Adds a closure for a kernel
953 *
954 * @param k Kernel ID for the kernel function
955 * @param argsAndBindings arguments followed by bindings for global variables
956 * @return a closure
957 */
958
959 public Closure addKernel(Script.KernelID k, Type returnType, Object... argsAndBindings) {
960 ArrayList<Object> args = new ArrayList<Object>();
961 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
962 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
963 return null;
964 }
965 return addKernelInternal(k, returnType, args.toArray(), bindingMap);
966 }
967
968 /**
969 * Adds a closure for an invocable function
970 *
971 * @param invoke Invoke ID for the invocable function
972 * @param argsAndBindings arguments followed by bindings for global variables
973 * @return a closure
974 */
975
976 public Closure addInvoke(Script.InvokeID invoke, Object... argsAndBindings) {
977 ArrayList<Object> args = new ArrayList<Object>();
978 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
979 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
980 return null;
981 }
982 return addInvokeInternal(invoke, args.toArray(), bindingMap);
983 }
984
985 /**
986 * Creates a script group
987 *
988 * @param name name for the script group. Legal names can only contain letters, digits,
989 * '-', or '_'. The name can be no longer than 100 characters.
990 * @param outputs futures intended as outputs of the script group
991 * @return a script group
992 */
993
994 public ScriptGroup create(String name, Future... outputs) {
995 if (name == null || name.isEmpty() || name.length() > 100 ||
996 !name.equals(name.replaceAll("[^a-zA-Z0-9-]", "_"))) {
997 throw new RSIllegalArgumentException("invalid script group name");
998 }
999 ScriptGroup ret = new ScriptGroup(mRS, name, mClosures, mInputs, outputs);
1000 return ret;
1001 }
1002
1003 private boolean seperateArgsAndBindings(Object[] argsAndBindings,
1004 ArrayList<Object> args,
1005 Map<Script.FieldID, Object> bindingMap) {
1006 int i;
1007 for (i = 0; i < argsAndBindings.length; i++) {
1008 if (argsAndBindings[i] instanceof Binding) {
1009 break;
1010 }
1011 args.add(argsAndBindings[i]);
1012 }
1013
1014 for (; i < argsAndBindings.length; i++) {
1015 if (!(argsAndBindings[i] instanceof Binding)) {
1016 return false;
1017 }
1018 Binding b = (Binding)argsAndBindings[i];
1019 bindingMap.put(b.getField(), b.getValue());
1020 }
1021
1022 return true;
1023 }
1024
1025 }
Jason Sams423ebcb2012-08-10 15:40:53 -07001026
1027}