blob: d1a12f9643086aac8342ba9dc07e006858223f6d [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 *
Yang Ni43563892015-05-12 13:53:38 -0700403 * @param inputs Values for inputs to the script group, in the order as the
404 * inputs are added via {@link Builder2#addInput}.
405 * @return Outputs of the script group as an array of objects, in the order
406 * as futures are passed to {@link Builder2#create}.
Yang Ni18314ca2015-04-17 16:51:55 -0700407 */
408
409 public Object[] execute(Object... inputs) {
410 if (inputs.length < mInputs2.size()) {
411 Log.e(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
412 "less than expected " + mInputs2.size());
413 return null;
414 }
415
416 if (inputs.length > mInputs2.size()) {
417 Log.i(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
418 "more than expected " + mInputs2.size());
419 }
420
421 for (int i = 0; i < mInputs2.size(); i++) {
422 Object obj = inputs[i];
423 if (obj instanceof Future || obj instanceof Input) {
424 Log.e(TAG, this.toString() + ": input " + i +
425 " is a future or unbound value");
426 return null;
427 }
428 Input unbound = mInputs2.get(i);
429 unbound.set(obj);
430 }
431
432 mRS.nScriptGroup2Execute(getID(mRS));
433
434 Object[] outputObjs = new Object[mOutputs2.length];
435 int i = 0;
436 for (Future f : mOutputs2) {
437 outputObjs[i++] = f.getValue();
438 }
439 return outputObjs;
440 }
441
Jason Sams08a81582012-09-18 12:32:10 -0700442 /**
443 * Sets an input of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700444 * Allocation to be used for kernels that require an input
445 * Allocation provided from outside of the ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700446 *
Yang Ni18314ca2015-04-17 16:51:55 -0700447 * @deprecated Set arguments to {@link #execute(Object...)} instead.
448 *
Jason Sams08a81582012-09-18 12:32:10 -0700449 * @param s The ID of the kernel where the allocation should be
450 * connected.
451 * @param a The allocation to connect.
452 */
453 public void setInput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700454 for (int ct=0; ct < mInputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700455 if (mInputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700456 mInputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700457 mRS.nScriptGroupSetInput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700458 return;
459 }
460 }
461 throw new RSIllegalArgumentException("Script not found");
462 }
463
Jason Sams08a81582012-09-18 12:32:10 -0700464 /**
465 * Sets an output of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700466 * Allocation to be used for the kernels that require an output
467 * Allocation visible after the ScriptGroup is executed.
Jason Sams08a81582012-09-18 12:32:10 -0700468 *
Yang Ni18314ca2015-04-17 16:51:55 -0700469 * @deprecated Use return value of {@link #execute(Object...)} instead.
470 *
Jason Sams08a81582012-09-18 12:32:10 -0700471 * @param s The ID of the kernel where the allocation should be
472 * connected.
473 * @param a The allocation to connect.
474 */
475 public void setOutput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700476 for (int ct=0; ct < mOutputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700477 if (mOutputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700478 mOutputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700479 mRS.nScriptGroupSetOutput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700480 return;
481 }
482 }
483 throw new RSIllegalArgumentException("Script not found");
484 }
485
Jason Sams08a81582012-09-18 12:32:10 -0700486 /**
487 * Execute the ScriptGroup. This will run all the kernels in
Tim Murrayc11e25c2013-04-09 11:01:01 -0700488 * the ScriptGroup. No internal connection results will be visible
489 * after execution of the ScriptGroup.
Yang Ni18314ca2015-04-17 16:51:55 -0700490 *
491 * @deprecated Use {@link #execute} instead.
492 *
Jason Sams08a81582012-09-18 12:32:10 -0700493 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700494 public void execute() {
Jason Sams08a81582012-09-18 12:32:10 -0700495 mRS.nScriptGroupExecute(getID(mRS));
Jason Sams423ebcb2012-08-10 15:40:53 -0700496 }
497
498
Jason Sams08a81582012-09-18 12:32:10 -0700499 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700500 * Helper class to build a ScriptGroup. A ScriptGroup is
501 * created in two steps.
Jason Sams08a81582012-09-18 12:32:10 -0700502 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700503 * First, all kernels to be used by the ScriptGroup should be added.
Jason Sams08a81582012-09-18 12:32:10 -0700504 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700505 * Second, add connections between kernels. There are two types
506 * of connections: kernel to kernel and kernel to field.
507 * Kernel to kernel allows a kernel's output to be passed to
508 * another kernel as input. Kernel to field allows the output of
509 * one kernel to be bound as a script global. Kernel to kernel is
510 * higher performance and should be used where possible.
Jason Sams08a81582012-09-18 12:32:10 -0700511 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700512 * A ScriptGroup must contain a single directed acyclic graph (DAG); it
513 * cannot contain cycles. Currently, all kernels used in a ScriptGroup
514 * must come from different Script objects. Additionally, all kernels
515 * in a ScriptGroup must have at least one input, output, or internal
516 * connection.
517 * <p>
518 * Once all connections are made, a call to {@link #create} will
Jason Sams08a81582012-09-18 12:32:10 -0700519 * return the ScriptGroup object.
520 *
Yang Ni18314ca2015-04-17 16:51:55 -0700521 * @deprecated Use {@link Builder2} instead.
522 *
Jason Sams08a81582012-09-18 12:32:10 -0700523 */
524 public static final class Builder {
525 private RenderScript mRS;
526 private ArrayList<Node> mNodes = new ArrayList<Node>();
527 private ArrayList<ConnectLine> mLines = new ArrayList<ConnectLine>();
528 private int mKernelCount;
Jason Sams423ebcb2012-08-10 15:40:53 -0700529
Jason Sams08a81582012-09-18 12:32:10 -0700530 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700531 * Create a Builder for generating a ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700532 *
533 *
Tim Murrayc11e25c2013-04-09 11:01:01 -0700534 * @param rs The RenderScript context.
Jason Sams08a81582012-09-18 12:32:10 -0700535 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700536 public Builder(RenderScript rs) {
537 mRS = rs;
538 }
539
Tim Murray091f7cc2012-10-12 12:02:18 -0700540 // do a DFS from original node, looking for original node
541 // any cycle that could be created must contain original node
542 private void validateCycle(Node target, Node original) {
543 for (int ct = 0; ct < target.mOutputs.size(); ct++) {
544 final ConnectLine cl = target.mOutputs.get(ct);
Jason Sams08a81582012-09-18 12:32:10 -0700545 if (cl.mToK != null) {
546 Node tn = findNode(cl.mToK.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700547 if (tn.equals(original)) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700548 throw new RSInvalidStateException("Loops in group not allowed.");
549 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700550 validateCycle(tn, original);
Jason Sams08a81582012-09-18 12:32:10 -0700551 }
552 if (cl.mToF != null) {
553 Node tn = findNode(cl.mToF.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700554 if (tn.equals(original)) {
Jason Sams08a81582012-09-18 12:32:10 -0700555 throw new RSInvalidStateException("Loops in group not allowed.");
556 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700557 validateCycle(tn, original);
Tim Murray2a603892012-10-10 14:21:46 -0700558 }
559 }
560 }
561
562 private void mergeDAGs(int valueUsed, int valueKilled) {
563 for (int ct=0; ct < mNodes.size(); ct++) {
564 if (mNodes.get(ct).dagNumber == valueKilled)
565 mNodes.get(ct).dagNumber = valueUsed;
566 }
567 }
568
569 private void validateDAGRecurse(Node n, int dagNumber) {
570 // combine DAGs if this node has been seen already
571 if (n.dagNumber != 0 && n.dagNumber != dagNumber) {
572 mergeDAGs(n.dagNumber, dagNumber);
573 return;
574 }
575
576 n.dagNumber = dagNumber;
577 for (int ct=0; ct < n.mOutputs.size(); ct++) {
578 final ConnectLine cl = n.mOutputs.get(ct);
579 if (cl.mToK != null) {
580 Node tn = findNode(cl.mToK.mScript);
581 validateDAGRecurse(tn, dagNumber);
582 }
583 if (cl.mToF != null) {
584 Node tn = findNode(cl.mToF.mScript);
585 validateDAGRecurse(tn, dagNumber);
586 }
587 }
588 }
589
590 private void validateDAG() {
591 for (int ct=0; ct < mNodes.size(); ct++) {
592 Node n = mNodes.get(ct);
593 if (n.mInputs.size() == 0) {
594 if (n.mOutputs.size() == 0 && mNodes.size() > 1) {
595 throw new RSInvalidStateException("Groups cannot contain unconnected scripts");
596 }
597 validateDAGRecurse(n, ct+1);
598 }
599 }
600 int dagNumber = mNodes.get(0).dagNumber;
601 for (int ct=0; ct < mNodes.size(); ct++) {
602 if (mNodes.get(ct).dagNumber != dagNumber) {
603 throw new RSInvalidStateException("Multiple DAGs in group not allowed.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700604 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700605 }
606 }
607
Jason Sams08a81582012-09-18 12:32:10 -0700608 private Node findNode(Script s) {
609 for (int ct=0; ct < mNodes.size(); ct++) {
610 if (s == mNodes.get(ct).mScript) {
611 return mNodes.get(ct);
Jason Sams423ebcb2012-08-10 15:40:53 -0700612 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700613 }
614 return null;
615 }
616
Jason Sams08a81582012-09-18 12:32:10 -0700617 private Node findNode(Script.KernelID k) {
618 for (int ct=0; ct < mNodes.size(); ct++) {
619 Node n = mNodes.get(ct);
620 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
621 if (k == n.mKernels.get(ct2)) {
622 return n;
Jason Sams423ebcb2012-08-10 15:40:53 -0700623 }
624 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700625 }
Jason Sams08a81582012-09-18 12:32:10 -0700626 return null;
627 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700628
Jason Sams08a81582012-09-18 12:32:10 -0700629 /**
630 * Adds a Kernel to the group.
631 *
632 *
633 * @param k The kernel to add.
634 *
635 * @return Builder Returns this.
636 */
637 public Builder addKernel(Script.KernelID k) {
638 if (mLines.size() != 0) {
639 throw new RSInvalidStateException(
640 "Kernels may not be added once connections exist.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700641 }
Jason Sams08a81582012-09-18 12:32:10 -0700642
643 //android.util.Log.v("RSR", "addKernel 1 k=" + k);
644 if (findNode(k) != null) {
645 return this;
646 }
647 //android.util.Log.v("RSR", "addKernel 2 ");
648 mKernelCount++;
649 Node n = findNode(k.mScript);
650 if (n == null) {
651 //android.util.Log.v("RSR", "addKernel 3 ");
652 n = new Node(k.mScript);
653 mNodes.add(n);
654 }
655 n.mKernels.add(k);
656 return this;
657 }
658
659 /**
660 * Adds a connection to the group.
661 *
662 *
663 * @param t The type of the connection. This is used to
664 * determine the kernel launch sizes on the source side
665 * of this connection.
666 * @param from The source for the connection.
667 * @param to The destination of the connection.
668 *
669 * @return Builder Returns this
670 */
671 public Builder addConnection(Type t, Script.KernelID from, Script.FieldID to) {
672 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
673
674 Node nf = findNode(from);
675 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700676 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700677 }
678
679 Node nt = findNode(to.mScript);
680 if (nt == null) {
681 throw new RSInvalidStateException("To script not found.");
682 }
683
684 ConnectLine cl = new ConnectLine(t, from, to);
685 mLines.add(new ConnectLine(t, from, to));
686
687 nf.mOutputs.add(cl);
688 nt.mInputs.add(cl);
Jason Sams423ebcb2012-08-10 15:40:53 -0700689
Tim Murray091f7cc2012-10-12 12:02:18 -0700690 validateCycle(nf, nf);
Jason Sams423ebcb2012-08-10 15:40:53 -0700691 return this;
692 }
693
Jason Sams08a81582012-09-18 12:32:10 -0700694 /**
695 * Adds a connection to the group.
696 *
697 *
698 * @param t The type of the connection. This is used to
699 * determine the kernel launch sizes for both sides of
700 * this connection.
701 * @param from The source for the connection.
702 * @param to The destination of the connection.
703 *
704 * @return Builder Returns this
705 */
706 public Builder addConnection(Type t, Script.KernelID from, Script.KernelID to) {
707 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
708
709 Node nf = findNode(from);
710 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700711 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700712 }
713
714 Node nt = findNode(to);
715 if (nt == null) {
716 throw new RSInvalidStateException("To script not found.");
717 }
718
719 ConnectLine cl = new ConnectLine(t, from, to);
720 mLines.add(new ConnectLine(t, from, to));
721
722 nf.mOutputs.add(cl);
723 nt.mInputs.add(cl);
724
Tim Murray091f7cc2012-10-12 12:02:18 -0700725 validateCycle(nf, nf);
Jason Sams08a81582012-09-18 12:32:10 -0700726 return this;
727 }
728
729
730
731 /**
732 * Creates the Script group.
733 *
734 *
735 * @return ScriptGroup The new ScriptGroup
736 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700737 public ScriptGroup create() {
Tim Murray2a603892012-10-10 14:21:46 -0700738
739 if (mNodes.size() == 0) {
740 throw new RSInvalidStateException("Empty script groups are not allowed");
741 }
742
743 // reset DAG numbers in case we're building a second group
744 for (int ct=0; ct < mNodes.size(); ct++) {
745 mNodes.get(ct).dagNumber = 0;
746 }
747 validateDAG();
748
Jason Sams08a81582012-09-18 12:32:10 -0700749 ArrayList<IO> inputs = new ArrayList<IO>();
750 ArrayList<IO> outputs = new ArrayList<IO>();
Jason Sams423ebcb2012-08-10 15:40:53 -0700751
Ashok Bhat98071552014-02-12 09:54:43 +0000752 long[] kernels = new long[mKernelCount];
Jason Sams08a81582012-09-18 12:32:10 -0700753 int idx = 0;
754 for (int ct=0; ct < mNodes.size(); ct++) {
755 Node n = mNodes.get(ct);
756 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
757 final Script.KernelID kid = n.mKernels.get(ct2);
Ashok Bhat98071552014-02-12 09:54:43 +0000758 kernels[idx++] = kid.getID(mRS);
Jason Sams423ebcb2012-08-10 15:40:53 -0700759
Jason Sams08a81582012-09-18 12:32:10 -0700760 boolean hasInput = false;
761 boolean hasOutput = false;
762 for (int ct3=0; ct3 < n.mInputs.size(); ct3++) {
763 if (n.mInputs.get(ct3).mToK == kid) {
764 hasInput = true;
765 }
766 }
767 for (int ct3=0; ct3 < n.mOutputs.size(); ct3++) {
768 if (n.mOutputs.get(ct3).mFrom == kid) {
769 hasOutput = true;
770 }
771 }
772 if (!hasInput) {
773 inputs.add(new IO(kid));
774 }
775 if (!hasOutput) {
776 outputs.add(new IO(kid));
777 }
778
779 }
780 }
781 if (idx != mKernelCount) {
782 throw new RSRuntimeException("Count mismatch, should not happen.");
783 }
784
Ashok Bhat98071552014-02-12 09:54:43 +0000785 long[] src = new long[mLines.size()];
786 long[] dstk = new long[mLines.size()];
787 long[] dstf = new long[mLines.size()];
788 long[] types = new long[mLines.size()];
Jason Sams08a81582012-09-18 12:32:10 -0700789
790 for (int ct=0; ct < mLines.size(); ct++) {
791 ConnectLine cl = mLines.get(ct);
Ashok Bhat98071552014-02-12 09:54:43 +0000792 src[ct] = cl.mFrom.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700793 if (cl.mToK != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000794 dstk[ct] = cl.mToK.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700795 }
796 if (cl.mToF != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000797 dstf[ct] = cl.mToF.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700798 }
Ashok Bhat98071552014-02-12 09:54:43 +0000799 types[ct] = cl.mAllocationType.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700800 }
801
Tim Murray460a0492013-11-19 12:45:54 -0800802 long id = mRS.nScriptGroupCreate(kernels, src, dstk, dstf, types);
Jason Sams08a81582012-09-18 12:32:10 -0700803 if (id == 0) {
804 throw new RSRuntimeException("Object creation error, should not happen.");
805 }
806
807 ScriptGroup sg = new ScriptGroup(id, mRS);
808 sg.mOutputs = new IO[outputs.size()];
809 for (int ct=0; ct < outputs.size(); ct++) {
810 sg.mOutputs[ct] = outputs.get(ct);
811 }
812
813 sg.mInputs = new IO[inputs.size()];
814 for (int ct=0; ct < inputs.size(); ct++) {
815 sg.mInputs[ct] = inputs.get(ct);
816 }
817
Jason Sams423ebcb2012-08-10 15:40:53 -0700818 return sg;
819 }
820
821 }
822
Yang Ni18314ca2015-04-17 16:51:55 -0700823 /**
824 * Represents a binding of a value to a global variable in a
825 * kernel or invocable function. Used in closure creation.
826 */
827
828 public static final class Binding {
829 private final Script.FieldID mField;
830 private final Object mValue;
831
832 /**
833 * Returns a Binding object that binds value to field
834 *
835 * @param field the Script.FieldID of the global variable
836 * @param value the value
837 */
838
839 public Binding(Script.FieldID field, Object value) {
840 mField = field;
841 mValue = value;
842 }
843
844 /**
845 * Returns the field ID
846 */
847
848 public Script.FieldID getField() { return mField; }
849
850 /**
851 * Returns the value
852 */
853
854 public Object getValue() { return mValue; }
855 }
856
857 /**
858 * The builder class for creating script groups
859 * <p>
860 * A script group is created using closures (see class {@link Closure}).
861 * A closure is a function call to a kernel or
862 * invocable function. Each function argument or global variable accessed inside
863 * the function is bound to 1) a known value, 2) a script group input
864 * (see class {@link Input}), or 3) a
865 * future (see class {@link Future}).
866 * A future is the output of a closure, either the return value of the
867 * function or a global variable written by that function.
868 * <p>
869 * Closures are created using the {@link #addKernel} or {@link #addInvoke}
870 * methods.
871 * When a closure is created, futures from previously created closures
872 * can be used as its inputs.
873 * External script group inputs can be used as inputs to individual closures as well.
874 * An external script group input is created using the {@link #addInput} method.
875 * A script group is created by a call to the {@link #create} method, which
876 * accepts an array of futures as the outputs for the script group.
877 * <p>
878 * Closures in a script group can be evaluated in any order as long as the
879 * following conditions are met:
880 * 1) a closure must be evaluated before any other closures that take its
881 * futures as inputs;
882 * 2) all closures added before an invoke closure must be evaluated
883 * before it;
884 * and 3) all closures added after an invoke closure must be evaluated after
885 * it.
886 * As a special case, the order that the closures are added is a legal
887 * evaluation order. However, other evaluation orders are possible, including
888 * concurrently evaluating independent closures.
889 */
890
891 public static final class Builder2 {
892 RenderScript mRS;
893 List<Closure> mClosures;
894 List<Input> mInputs;
895 private static final String TAG = "ScriptGroup.Builder2";
896
897 /**
898 * Returns a Builder object
899 *
900 * @param rs the RenderScript context
901 */
902 public Builder2(RenderScript rs) {
903 mRS = rs;
904 mClosures = new ArrayList<Closure>();
905 mInputs = new ArrayList<Input>();
906 }
907
908 /**
909 * Adds a closure for a kernel
910 *
911 * @param k Kernel ID for the kernel function
912 * @param returnType Allocation type for the return value
913 * @param args arguments to the kernel function
914 * @param globalBindings bindings for global variables
915 * @return a closure
916 */
917
918 private Closure addKernelInternal(Script.KernelID k, Type returnType, Object[] args,
919 Map<Script.FieldID, Object> globalBindings) {
920 Closure c = new Closure(mRS, k, returnType, args, globalBindings);
921 mClosures.add(c);
922 return c;
923 }
924
925 /**
926 * Adds a closure for an invocable function
927 *
928 * @param invoke Invoke ID for the invocable function
929 * @param args arguments to the invocable function
930 * @param globalBindings bindings for global variables
931 * @return a closure
932 */
933
934 private Closure addInvokeInternal(Script.InvokeID invoke, Object[] args,
935 Map<Script.FieldID, Object> globalBindings) {
936 Closure c = new Closure(mRS, invoke, args, globalBindings);
937 mClosures.add(c);
938 return c;
939 }
940
941 /**
942 * Adds a script group input
943 *
944 * @return a script group input, which can be used as an argument or a value to
945 * a global variable for creating closures
946 */
947 public Input addInput() {
948 Input unbound = new Input();
949 mInputs.add(unbound);
950 return unbound;
951 }
952
953 /**
954 * Adds a closure for a kernel
955 *
956 * @param k Kernel ID for the kernel function
957 * @param argsAndBindings arguments followed by bindings for global variables
958 * @return a closure
959 */
960
961 public Closure addKernel(Script.KernelID k, Type returnType, Object... argsAndBindings) {
962 ArrayList<Object> args = new ArrayList<Object>();
963 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
964 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
965 return null;
966 }
967 return addKernelInternal(k, returnType, args.toArray(), bindingMap);
968 }
969
970 /**
971 * Adds a closure for an invocable function
972 *
973 * @param invoke Invoke ID for the invocable function
974 * @param argsAndBindings arguments followed by bindings for global variables
975 * @return a closure
976 */
977
978 public Closure addInvoke(Script.InvokeID invoke, Object... argsAndBindings) {
979 ArrayList<Object> args = new ArrayList<Object>();
980 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
981 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
982 return null;
983 }
984 return addInvokeInternal(invoke, args.toArray(), bindingMap);
985 }
986
987 /**
988 * Creates a script group
989 *
990 * @param name name for the script group. Legal names can only contain letters, digits,
991 * '-', or '_'. The name can be no longer than 100 characters.
992 * @param outputs futures intended as outputs of the script group
993 * @return a script group
994 */
995
996 public ScriptGroup create(String name, Future... outputs) {
997 if (name == null || name.isEmpty() || name.length() > 100 ||
998 !name.equals(name.replaceAll("[^a-zA-Z0-9-]", "_"))) {
999 throw new RSIllegalArgumentException("invalid script group name");
1000 }
1001 ScriptGroup ret = new ScriptGroup(mRS, name, mClosures, mInputs, outputs);
1002 return ret;
1003 }
1004
1005 private boolean seperateArgsAndBindings(Object[] argsAndBindings,
1006 ArrayList<Object> args,
1007 Map<Script.FieldID, Object> bindingMap) {
1008 int i;
1009 for (i = 0; i < argsAndBindings.length; i++) {
1010 if (argsAndBindings[i] instanceof Binding) {
1011 break;
1012 }
1013 args.add(argsAndBindings[i]);
1014 }
1015
1016 for (; i < argsAndBindings.length; i++) {
1017 if (!(argsAndBindings[i] instanceof Binding)) {
1018 return false;
1019 }
1020 Binding b = (Binding)argsAndBindings[i];
1021 bindingMap.put(b.getField(), b.getValue());
1022 }
1023
1024 return true;
1025 }
1026
1027 }
Jason Sams423ebcb2012-08-10 15:40:53 -07001028
1029}