blob: 5a0897d4139b63870b463138f66447f64555704e [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 Niead1af82015-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 Niead1af82015-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 Niead1af82015-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 Niead1af82015-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 Niead1af82015-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 Niead1af82015-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 Niead1af82015-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 Niead1af82015-04-17 16:51:55 -0700134 fieldIDs[i] = 0;
Yang Nid9f5f022015-05-18 10:56:47 -0700135 retrieveValueAndDependenceInfo(rs, i, null, args[i],
136 values, sizes, depClosures, depFieldIDs);
Yang Niead1af82015-04-17 16:51:55 -0700137 }
Yang Niead1af82015-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 Nid9f5f022015-05-18 10:56:47 -0700142 retrieveValueAndDependenceInfo(rs, i, fieldID, obj,
143 values, sizes, depClosures, depFieldIDs);
Yang Niead1af82015-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 Nid9f5f022015-05-18 10:56:47 -0700175 retrieveValueAndDependenceInfo(rs, i, fieldID, obj, values,
176 sizes, depClosures, depFieldIDs);
Yang Niead1af82015-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 Nid9f5f022015-05-18 10:56:47 -0700186 private void retrieveValueAndDependenceInfo(RenderScript rs,
187 int index, Script.FieldID fid, Object obj,
Yang Niead1af82015-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 Niead1af82015-04-17 16:51:55 -0700198 } else {
199 depClosures[index] = 0;
200 depFieldIDs[index] = 0;
201 }
202
Yang Nid9f5f022015-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 Niead1af82015-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 Nid9f5f022015-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 Niead1af82015-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 Nid9f5f022015-05-18 10:56:47 -0700260 if (obj instanceof Future) {
261 obj = ((Future)obj).getValue();
262 }
Yang Niead1af82015-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 Nid9f5f022015-05-18 10:56:47 -0700269 if (obj instanceof Future) {
270 obj = ((Future)obj).getValue();
271 }
Yang Niead1af82015-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);
281 size = -1;
282 } else if (obj instanceof Boolean) {
283 value = ((Boolean)obj).booleanValue() ? 1 : 0;
284 size = 4;
285 } else if (obj instanceof Integer) {
286 value = ((Integer)obj).longValue();
287 size = 4;
288 } else if (obj instanceof Long) {
289 value = ((Long)obj).longValue();
290 size = 8;
291 } else if (obj instanceof Float) {
292 value = ((Float)obj).longValue();
293 size = 4;
294 } else if (obj instanceof Double) {
295 value = ((Double)obj).longValue();
296 size = 8;
297 }
298 }
299 public long value;
300 public int size;
301 }
302 }
303
304 /**
305 * An opaque class for futures
306 * <p>
307 * A future represents an output of a closure, either the return value of
308 * the function, or the value of a global variable written by the function.
309 * A future is created by calling the {@link Closure#getReturn} or
310 * {@link Closure#getGlobal} method.
311 */
312
313 public static final class Future {
314 Closure mClosure;
315 Script.FieldID mFieldID;
316 Object mValue;
317
318 Future(Closure closure, Script.FieldID fieldID, Object value) {
319 mClosure = closure;
320 mFieldID = fieldID;
321 mValue = value;
322 }
323
324 Closure getClosure() { return mClosure; }
325 Script.FieldID getFieldID() { return mFieldID; }
326 Object getValue() { return mValue; }
327 }
328
329 /**
330 * An opaque class for script group inputs
331 * <p>
332 * Created by calling the {@link Builder2#addInput} method. The value
333 * is assigned in {@link ScriptGroup#execute(Object...)} method as
334 * one of its arguments. Arguments to the execute method should be in
335 * the same order as intputs are added using the addInput method.
336 */
337
338 public static final class Input {
339 // Either mFieldID or mArgIndex should be set but not both.
340 List<Pair<Closure, Script.FieldID>> mFieldID;
341 // -1 means unset. Legal values are 0 .. n-1, where n is the number of
342 // arguments for the referencing closure.
343 List<Pair<Closure, Integer>> mArgIndex;
Yang Nid9f5f022015-05-18 10:56:47 -0700344 Object mValue;
Yang Niead1af82015-04-17 16:51:55 -0700345
346 Input() {
347 mFieldID = new ArrayList<Pair<Closure, Script.FieldID>>();
348 mArgIndex = new ArrayList<Pair<Closure, Integer>>();
349 }
350
351 void addReference(Closure closure, int index) {
352 mArgIndex.add(Pair.create(closure, Integer.valueOf(index)));
353 }
354
355 void addReference(Closure closure, Script.FieldID fieldID) {
356 mFieldID.add(Pair.create(closure, fieldID));
357 }
358
359 void set(Object value) {
Yang Nid9f5f022015-05-18 10:56:47 -0700360 mValue = value;
Yang Niead1af82015-04-17 16:51:55 -0700361 for (Pair<Closure, Integer> p : mArgIndex) {
362 Closure closure = p.first;
363 int index = p.second.intValue();
364 closure.setArg(index, value);
365 }
366 for (Pair<Closure, Script.FieldID> p : mFieldID) {
367 Closure closure = p.first;
368 Script.FieldID fieldID = p.second;
369 closure.setGlobal(fieldID, value);
370 }
371 }
Yang Nid9f5f022015-05-18 10:56:47 -0700372
373 Object get() { return mValue; }
Yang Niead1af82015-04-17 16:51:55 -0700374 }
375
376 private String mName;
377 private List<Closure> mClosures;
378 private List<Input> mInputs2;
379 private Future[] mOutputs2;
380
Tim Murray460a0492013-11-19 12:45:54 -0800381 ScriptGroup(long id, RenderScript rs) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700382 super(id, rs);
383 }
384
Yang Niead1af82015-04-17 16:51:55 -0700385 ScriptGroup(RenderScript rs, String name, List<Closure> closures,
386 List<Input> inputs, Future[] outputs) {
387 super(0, rs);
388 mName = name;
389 mClosures = closures;
390 mInputs2 = inputs;
391 mOutputs2 = outputs;
392
393 long[] closureIDs = new long[closures.size()];
394 for (int i = 0; i < closureIDs.length; i++) {
395 closureIDs[i] = closures.get(i).getID(rs);
396 }
397 long id = rs.nScriptGroup2Create(name, ScriptC.mCachePath, closureIDs);
398 setID(id);
399 }
400
401 /**
402 * Executes a script group
403 *
404 * @param inputs inputs to the script group
405 * @return outputs of the script group as an array of objects
406 */
407
408 public Object[] execute(Object... inputs) {
409 if (inputs.length < mInputs2.size()) {
410 Log.e(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
411 "less than expected " + mInputs2.size());
412 return null;
413 }
414
415 if (inputs.length > mInputs2.size()) {
416 Log.i(TAG, this.toString() + " receives " + inputs.length + " inputs, " +
417 "more than expected " + mInputs2.size());
418 }
419
420 for (int i = 0; i < mInputs2.size(); i++) {
421 Object obj = inputs[i];
422 if (obj instanceof Future || obj instanceof Input) {
423 Log.e(TAG, this.toString() + ": input " + i +
424 " is a future or unbound value");
425 return null;
426 }
427 Input unbound = mInputs2.get(i);
428 unbound.set(obj);
429 }
430
431 mRS.nScriptGroup2Execute(getID(mRS));
432
433 Object[] outputObjs = new Object[mOutputs2.length];
434 int i = 0;
435 for (Future f : mOutputs2) {
Yang Nid9f5f022015-05-18 10:56:47 -0700436 Object output = f.getValue();
437 if (output instanceof Input) {
438 output = ((Input)output).get();
439 }
440 outputObjs[i++] = output;
Yang Niead1af82015-04-17 16:51:55 -0700441 }
442 return outputObjs;
443 }
444
Jason Sams08a81582012-09-18 12:32:10 -0700445 /**
446 * Sets an input of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700447 * Allocation to be used for kernels that require an input
448 * Allocation provided from outside of the ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700449 *
Yang Niead1af82015-04-17 16:51:55 -0700450 * @deprecated Set arguments to {@link #execute(Object...)} instead.
451 *
Jason Sams08a81582012-09-18 12:32:10 -0700452 * @param s The ID of the kernel where the allocation should be
453 * connected.
454 * @param a The allocation to connect.
455 */
456 public void setInput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700457 for (int ct=0; ct < mInputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700458 if (mInputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700459 mInputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700460 mRS.nScriptGroupSetInput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700461 return;
462 }
463 }
464 throw new RSIllegalArgumentException("Script not found");
465 }
466
Jason Sams08a81582012-09-18 12:32:10 -0700467 /**
468 * Sets an output of the ScriptGroup. This specifies an
Tim Murrayc11e25c2013-04-09 11:01:01 -0700469 * Allocation to be used for the kernels that require an output
470 * Allocation visible after the ScriptGroup is executed.
Jason Sams08a81582012-09-18 12:32:10 -0700471 *
Yang Niead1af82015-04-17 16:51:55 -0700472 * @deprecated Use return value of {@link #execute(Object...)} instead.
473 *
Jason Sams08a81582012-09-18 12:32:10 -0700474 * @param s The ID of the kernel where the allocation should be
475 * connected.
476 * @param a The allocation to connect.
477 */
478 public void setOutput(Script.KernelID s, Allocation a) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700479 for (int ct=0; ct < mOutputs.length; ct++) {
Jason Sams08a81582012-09-18 12:32:10 -0700480 if (mOutputs[ct].mKID == s) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700481 mOutputs[ct].mAllocation = a;
Jason Sams08a81582012-09-18 12:32:10 -0700482 mRS.nScriptGroupSetOutput(getID(mRS), s.getID(mRS), mRS.safeID(a));
Jason Sams423ebcb2012-08-10 15:40:53 -0700483 return;
484 }
485 }
486 throw new RSIllegalArgumentException("Script not found");
487 }
488
Jason Sams08a81582012-09-18 12:32:10 -0700489 /**
490 * Execute the ScriptGroup. This will run all the kernels in
Tim Murrayc11e25c2013-04-09 11:01:01 -0700491 * the ScriptGroup. No internal connection results will be visible
492 * after execution of the ScriptGroup.
Yang Niead1af82015-04-17 16:51:55 -0700493 *
494 * @deprecated Use {@link #execute} instead.
495 *
Jason Sams08a81582012-09-18 12:32:10 -0700496 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700497 public void execute() {
Jason Sams08a81582012-09-18 12:32:10 -0700498 mRS.nScriptGroupExecute(getID(mRS));
Jason Sams423ebcb2012-08-10 15:40:53 -0700499 }
500
501
Jason Sams08a81582012-09-18 12:32:10 -0700502 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700503 * Helper class to build a ScriptGroup. A ScriptGroup is
504 * created in two steps.
Jason Sams08a81582012-09-18 12:32:10 -0700505 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700506 * First, all kernels to be used by the ScriptGroup should be added.
Jason Sams08a81582012-09-18 12:32:10 -0700507 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700508 * Second, add connections between kernels. There are two types
509 * of connections: kernel to kernel and kernel to field.
510 * Kernel to kernel allows a kernel's output to be passed to
511 * another kernel as input. Kernel to field allows the output of
512 * one kernel to be bound as a script global. Kernel to kernel is
513 * higher performance and should be used where possible.
Jason Sams08a81582012-09-18 12:32:10 -0700514 * <p>
Tim Murrayc11e25c2013-04-09 11:01:01 -0700515 * A ScriptGroup must contain a single directed acyclic graph (DAG); it
516 * cannot contain cycles. Currently, all kernels used in a ScriptGroup
517 * must come from different Script objects. Additionally, all kernels
518 * in a ScriptGroup must have at least one input, output, or internal
519 * connection.
520 * <p>
521 * Once all connections are made, a call to {@link #create} will
Jason Sams08a81582012-09-18 12:32:10 -0700522 * return the ScriptGroup object.
523 *
Yang Niead1af82015-04-17 16:51:55 -0700524 * @deprecated Use {@link Builder2} instead.
525 *
Jason Sams08a81582012-09-18 12:32:10 -0700526 */
527 public static final class Builder {
528 private RenderScript mRS;
529 private ArrayList<Node> mNodes = new ArrayList<Node>();
530 private ArrayList<ConnectLine> mLines = new ArrayList<ConnectLine>();
531 private int mKernelCount;
Jason Sams423ebcb2012-08-10 15:40:53 -0700532
Jason Sams08a81582012-09-18 12:32:10 -0700533 /**
Tim Murrayc11e25c2013-04-09 11:01:01 -0700534 * Create a Builder for generating a ScriptGroup.
Jason Sams08a81582012-09-18 12:32:10 -0700535 *
536 *
Tim Murrayc11e25c2013-04-09 11:01:01 -0700537 * @param rs The RenderScript context.
Jason Sams08a81582012-09-18 12:32:10 -0700538 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700539 public Builder(RenderScript rs) {
540 mRS = rs;
541 }
542
Tim Murray091f7cc2012-10-12 12:02:18 -0700543 // do a DFS from original node, looking for original node
544 // any cycle that could be created must contain original node
545 private void validateCycle(Node target, Node original) {
546 for (int ct = 0; ct < target.mOutputs.size(); ct++) {
547 final ConnectLine cl = target.mOutputs.get(ct);
Jason Sams08a81582012-09-18 12:32:10 -0700548 if (cl.mToK != null) {
549 Node tn = findNode(cl.mToK.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700550 if (tn.equals(original)) {
Jason Sams423ebcb2012-08-10 15:40:53 -0700551 throw new RSInvalidStateException("Loops in group not allowed.");
552 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700553 validateCycle(tn, original);
Jason Sams08a81582012-09-18 12:32:10 -0700554 }
555 if (cl.mToF != null) {
556 Node tn = findNode(cl.mToF.mScript);
Tim Murray091f7cc2012-10-12 12:02:18 -0700557 if (tn.equals(original)) {
Jason Sams08a81582012-09-18 12:32:10 -0700558 throw new RSInvalidStateException("Loops in group not allowed.");
559 }
Tim Murray091f7cc2012-10-12 12:02:18 -0700560 validateCycle(tn, original);
Tim Murray2a603892012-10-10 14:21:46 -0700561 }
562 }
563 }
564
565 private void mergeDAGs(int valueUsed, int valueKilled) {
566 for (int ct=0; ct < mNodes.size(); ct++) {
567 if (mNodes.get(ct).dagNumber == valueKilled)
568 mNodes.get(ct).dagNumber = valueUsed;
569 }
570 }
571
572 private void validateDAGRecurse(Node n, int dagNumber) {
573 // combine DAGs if this node has been seen already
574 if (n.dagNumber != 0 && n.dagNumber != dagNumber) {
575 mergeDAGs(n.dagNumber, dagNumber);
576 return;
577 }
578
579 n.dagNumber = dagNumber;
580 for (int ct=0; ct < n.mOutputs.size(); ct++) {
581 final ConnectLine cl = n.mOutputs.get(ct);
582 if (cl.mToK != null) {
583 Node tn = findNode(cl.mToK.mScript);
584 validateDAGRecurse(tn, dagNumber);
585 }
586 if (cl.mToF != null) {
587 Node tn = findNode(cl.mToF.mScript);
588 validateDAGRecurse(tn, dagNumber);
589 }
590 }
591 }
592
593 private void validateDAG() {
594 for (int ct=0; ct < mNodes.size(); ct++) {
595 Node n = mNodes.get(ct);
596 if (n.mInputs.size() == 0) {
597 if (n.mOutputs.size() == 0 && mNodes.size() > 1) {
Yang Nid9f5f022015-05-18 10:56:47 -0700598 String msg = "Groups cannot contain unconnected scripts";
599 throw new RSInvalidStateException(msg);
Tim Murray2a603892012-10-10 14:21:46 -0700600 }
601 validateDAGRecurse(n, ct+1);
602 }
603 }
604 int dagNumber = mNodes.get(0).dagNumber;
605 for (int ct=0; ct < mNodes.size(); ct++) {
606 if (mNodes.get(ct).dagNumber != dagNumber) {
607 throw new RSInvalidStateException("Multiple DAGs in group not allowed.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700608 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700609 }
610 }
611
Jason Sams08a81582012-09-18 12:32:10 -0700612 private Node findNode(Script s) {
613 for (int ct=0; ct < mNodes.size(); ct++) {
614 if (s == mNodes.get(ct).mScript) {
615 return mNodes.get(ct);
Jason Sams423ebcb2012-08-10 15:40:53 -0700616 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700617 }
618 return null;
619 }
620
Jason Sams08a81582012-09-18 12:32:10 -0700621 private Node findNode(Script.KernelID k) {
622 for (int ct=0; ct < mNodes.size(); ct++) {
623 Node n = mNodes.get(ct);
624 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
625 if (k == n.mKernels.get(ct2)) {
626 return n;
Jason Sams423ebcb2012-08-10 15:40:53 -0700627 }
628 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700629 }
Jason Sams08a81582012-09-18 12:32:10 -0700630 return null;
631 }
Jason Sams423ebcb2012-08-10 15:40:53 -0700632
Jason Sams08a81582012-09-18 12:32:10 -0700633 /**
634 * Adds a Kernel to the group.
635 *
636 *
637 * @param k The kernel to add.
638 *
639 * @return Builder Returns this.
640 */
641 public Builder addKernel(Script.KernelID k) {
642 if (mLines.size() != 0) {
643 throw new RSInvalidStateException(
644 "Kernels may not be added once connections exist.");
Jason Sams423ebcb2012-08-10 15:40:53 -0700645 }
Jason Sams08a81582012-09-18 12:32:10 -0700646
647 //android.util.Log.v("RSR", "addKernel 1 k=" + k);
648 if (findNode(k) != null) {
649 return this;
650 }
651 //android.util.Log.v("RSR", "addKernel 2 ");
652 mKernelCount++;
653 Node n = findNode(k.mScript);
654 if (n == null) {
655 //android.util.Log.v("RSR", "addKernel 3 ");
656 n = new Node(k.mScript);
657 mNodes.add(n);
658 }
659 n.mKernels.add(k);
660 return this;
661 }
662
663 /**
664 * Adds a connection to the group.
665 *
666 *
667 * @param t The type of the connection. This is used to
668 * determine the kernel launch sizes on the source side
669 * of this connection.
670 * @param from The source for the connection.
671 * @param to The destination of the connection.
672 *
673 * @return Builder Returns this
674 */
675 public Builder addConnection(Type t, Script.KernelID from, Script.FieldID to) {
676 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
677
678 Node nf = findNode(from);
679 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700680 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700681 }
682
683 Node nt = findNode(to.mScript);
684 if (nt == null) {
685 throw new RSInvalidStateException("To script not found.");
686 }
687
688 ConnectLine cl = new ConnectLine(t, from, to);
689 mLines.add(new ConnectLine(t, from, to));
690
691 nf.mOutputs.add(cl);
692 nt.mInputs.add(cl);
Jason Sams423ebcb2012-08-10 15:40:53 -0700693
Tim Murray091f7cc2012-10-12 12:02:18 -0700694 validateCycle(nf, nf);
Jason Sams423ebcb2012-08-10 15:40:53 -0700695 return this;
696 }
697
Jason Sams08a81582012-09-18 12:32:10 -0700698 /**
699 * Adds a connection to the group.
700 *
701 *
702 * @param t The type of the connection. This is used to
703 * determine the kernel launch sizes for both sides of
704 * this connection.
705 * @param from The source for the connection.
706 * @param to The destination of the connection.
707 *
708 * @return Builder Returns this
709 */
710 public Builder addConnection(Type t, Script.KernelID from, Script.KernelID to) {
711 //android.util.Log.v("RSR", "addConnection " + t +", " + from + ", " + to);
712
713 Node nf = findNode(from);
714 if (nf == null) {
Tim Murray091f7cc2012-10-12 12:02:18 -0700715 throw new RSInvalidStateException("From script not found.");
Jason Sams08a81582012-09-18 12:32:10 -0700716 }
717
718 Node nt = findNode(to);
719 if (nt == null) {
720 throw new RSInvalidStateException("To script not found.");
721 }
722
723 ConnectLine cl = new ConnectLine(t, from, to);
724 mLines.add(new ConnectLine(t, from, to));
725
726 nf.mOutputs.add(cl);
727 nt.mInputs.add(cl);
728
Tim Murray091f7cc2012-10-12 12:02:18 -0700729 validateCycle(nf, nf);
Jason Sams08a81582012-09-18 12:32:10 -0700730 return this;
731 }
732
733
734
735 /**
736 * Creates the Script group.
737 *
738 *
739 * @return ScriptGroup The new ScriptGroup
740 */
Jason Sams423ebcb2012-08-10 15:40:53 -0700741 public ScriptGroup create() {
Tim Murray2a603892012-10-10 14:21:46 -0700742
743 if (mNodes.size() == 0) {
744 throw new RSInvalidStateException("Empty script groups are not allowed");
745 }
746
747 // reset DAG numbers in case we're building a second group
748 for (int ct=0; ct < mNodes.size(); ct++) {
749 mNodes.get(ct).dagNumber = 0;
750 }
751 validateDAG();
752
Jason Sams08a81582012-09-18 12:32:10 -0700753 ArrayList<IO> inputs = new ArrayList<IO>();
754 ArrayList<IO> outputs = new ArrayList<IO>();
Jason Sams423ebcb2012-08-10 15:40:53 -0700755
Ashok Bhat98071552014-02-12 09:54:43 +0000756 long[] kernels = new long[mKernelCount];
Jason Sams08a81582012-09-18 12:32:10 -0700757 int idx = 0;
758 for (int ct=0; ct < mNodes.size(); ct++) {
759 Node n = mNodes.get(ct);
760 for (int ct2=0; ct2 < n.mKernels.size(); ct2++) {
761 final Script.KernelID kid = n.mKernels.get(ct2);
Ashok Bhat98071552014-02-12 09:54:43 +0000762 kernels[idx++] = kid.getID(mRS);
Jason Sams423ebcb2012-08-10 15:40:53 -0700763
Jason Sams08a81582012-09-18 12:32:10 -0700764 boolean hasInput = false;
765 boolean hasOutput = false;
766 for (int ct3=0; ct3 < n.mInputs.size(); ct3++) {
767 if (n.mInputs.get(ct3).mToK == kid) {
768 hasInput = true;
769 }
770 }
771 for (int ct3=0; ct3 < n.mOutputs.size(); ct3++) {
772 if (n.mOutputs.get(ct3).mFrom == kid) {
773 hasOutput = true;
774 }
775 }
776 if (!hasInput) {
777 inputs.add(new IO(kid));
778 }
779 if (!hasOutput) {
780 outputs.add(new IO(kid));
781 }
782
783 }
784 }
785 if (idx != mKernelCount) {
786 throw new RSRuntimeException("Count mismatch, should not happen.");
787 }
788
Ashok Bhat98071552014-02-12 09:54:43 +0000789 long[] src = new long[mLines.size()];
790 long[] dstk = new long[mLines.size()];
791 long[] dstf = new long[mLines.size()];
792 long[] types = new long[mLines.size()];
Jason Sams08a81582012-09-18 12:32:10 -0700793
794 for (int ct=0; ct < mLines.size(); ct++) {
795 ConnectLine cl = mLines.get(ct);
Ashok Bhat98071552014-02-12 09:54:43 +0000796 src[ct] = cl.mFrom.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700797 if (cl.mToK != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000798 dstk[ct] = cl.mToK.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700799 }
800 if (cl.mToF != null) {
Ashok Bhat98071552014-02-12 09:54:43 +0000801 dstf[ct] = cl.mToF.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700802 }
Ashok Bhat98071552014-02-12 09:54:43 +0000803 types[ct] = cl.mAllocationType.getID(mRS);
Jason Sams08a81582012-09-18 12:32:10 -0700804 }
805
Tim Murray460a0492013-11-19 12:45:54 -0800806 long id = mRS.nScriptGroupCreate(kernels, src, dstk, dstf, types);
Jason Sams08a81582012-09-18 12:32:10 -0700807 if (id == 0) {
808 throw new RSRuntimeException("Object creation error, should not happen.");
809 }
810
811 ScriptGroup sg = new ScriptGroup(id, mRS);
812 sg.mOutputs = new IO[outputs.size()];
813 for (int ct=0; ct < outputs.size(); ct++) {
814 sg.mOutputs[ct] = outputs.get(ct);
815 }
816
817 sg.mInputs = new IO[inputs.size()];
818 for (int ct=0; ct < inputs.size(); ct++) {
819 sg.mInputs[ct] = inputs.get(ct);
820 }
821
Jason Sams423ebcb2012-08-10 15:40:53 -0700822 return sg;
823 }
824
825 }
826
Yang Niead1af82015-04-17 16:51:55 -0700827 /**
828 * Represents a binding of a value to a global variable in a
829 * kernel or invocable function. Used in closure creation.
830 */
831
832 public static final class Binding {
833 private final Script.FieldID mField;
834 private final Object mValue;
835
836 /**
837 * Returns a Binding object that binds value to field
838 *
839 * @param field the Script.FieldID of the global variable
840 * @param value the value
841 */
842
843 public Binding(Script.FieldID field, Object value) {
844 mField = field;
845 mValue = value;
846 }
847
848 /**
849 * Returns the field ID
850 */
851
852 public Script.FieldID getField() { return mField; }
853
854 /**
855 * Returns the value
856 */
857
858 public Object getValue() { return mValue; }
859 }
860
861 /**
862 * The builder class for creating script groups
863 * <p>
864 * A script group is created using closures (see class {@link Closure}).
865 * A closure is a function call to a kernel or
866 * invocable function. Each function argument or global variable accessed inside
867 * the function is bound to 1) a known value, 2) a script group input
868 * (see class {@link Input}), or 3) a
869 * future (see class {@link Future}).
870 * A future is the output of a closure, either the return value of the
871 * function or a global variable written by that function.
872 * <p>
873 * Closures are created using the {@link #addKernel} or {@link #addInvoke}
874 * methods.
875 * When a closure is created, futures from previously created closures
876 * can be used as its inputs.
877 * External script group inputs can be used as inputs to individual closures as well.
878 * An external script group input is created using the {@link #addInput} method.
879 * A script group is created by a call to the {@link #create} method, which
880 * accepts an array of futures as the outputs for the script group.
881 * <p>
882 * Closures in a script group can be evaluated in any order as long as the
883 * following conditions are met:
884 * 1) a closure must be evaluated before any other closures that take its
885 * futures as inputs;
886 * 2) all closures added before an invoke closure must be evaluated
887 * before it;
888 * and 3) all closures added after an invoke closure must be evaluated after
889 * it.
890 * As a special case, the order that the closures are added is a legal
891 * evaluation order. However, other evaluation orders are possible, including
892 * concurrently evaluating independent closures.
893 */
894
895 public static final class Builder2 {
896 RenderScript mRS;
897 List<Closure> mClosures;
898 List<Input> mInputs;
899 private static final String TAG = "ScriptGroup.Builder2";
900
901 /**
902 * Returns a Builder object
903 *
904 * @param rs the RenderScript context
905 */
906 public Builder2(RenderScript rs) {
907 mRS = rs;
908 mClosures = new ArrayList<Closure>();
909 mInputs = new ArrayList<Input>();
910 }
911
912 /**
913 * Adds a closure for a kernel
914 *
915 * @param k Kernel ID for the kernel function
916 * @param returnType Allocation type for the return value
917 * @param args arguments to the kernel function
918 * @param globalBindings bindings for global variables
919 * @return a closure
920 */
921
922 private Closure addKernelInternal(Script.KernelID k, Type returnType, Object[] args,
923 Map<Script.FieldID, Object> globalBindings) {
924 Closure c = new Closure(mRS, k, returnType, args, globalBindings);
925 mClosures.add(c);
926 return c;
927 }
928
929 /**
930 * Adds a closure for an invocable function
931 *
932 * @param invoke Invoke ID for the invocable function
933 * @param args arguments to the invocable function
934 * @param globalBindings bindings for global variables
935 * @return a closure
936 */
937
938 private Closure addInvokeInternal(Script.InvokeID invoke, Object[] args,
939 Map<Script.FieldID, Object> globalBindings) {
940 Closure c = new Closure(mRS, invoke, args, globalBindings);
941 mClosures.add(c);
942 return c;
943 }
944
945 /**
946 * Adds a script group input
947 *
948 * @return a script group input, which can be used as an argument or a value to
949 * a global variable for creating closures
950 */
951 public Input addInput() {
952 Input unbound = new Input();
953 mInputs.add(unbound);
954 return unbound;
955 }
956
957 /**
958 * Adds a closure for a kernel
959 *
960 * @param k Kernel ID for the kernel function
961 * @param argsAndBindings arguments followed by bindings for global variables
962 * @return a closure
963 */
964
965 public Closure addKernel(Script.KernelID k, Type returnType, Object... argsAndBindings) {
966 ArrayList<Object> args = new ArrayList<Object>();
967 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
968 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
969 return null;
970 }
971 return addKernelInternal(k, returnType, args.toArray(), bindingMap);
972 }
973
974 /**
975 * Adds a closure for an invocable function
976 *
977 * @param invoke Invoke ID for the invocable function
978 * @param argsAndBindings arguments followed by bindings for global variables
979 * @return a closure
980 */
981
982 public Closure addInvoke(Script.InvokeID invoke, Object... argsAndBindings) {
983 ArrayList<Object> args = new ArrayList<Object>();
984 Map<Script.FieldID, Object> bindingMap = new HashMap<Script.FieldID, Object>();
985 if (!seperateArgsAndBindings(argsAndBindings, args, bindingMap)) {
986 return null;
987 }
988 return addInvokeInternal(invoke, args.toArray(), bindingMap);
989 }
990
991 /**
992 * Creates a script group
993 *
994 * @param name name for the script group. Legal names can only contain letters, digits,
995 * '-', or '_'. The name can be no longer than 100 characters.
996 * @param outputs futures intended as outputs of the script group
997 * @return a script group
998 */
999
1000 public ScriptGroup create(String name, Future... outputs) {
1001 if (name == null || name.isEmpty() || name.length() > 100 ||
1002 !name.equals(name.replaceAll("[^a-zA-Z0-9-]", "_"))) {
1003 throw new RSIllegalArgumentException("invalid script group name");
1004 }
1005 ScriptGroup ret = new ScriptGroup(mRS, name, mClosures, mInputs, outputs);
1006 return ret;
1007 }
1008
1009 private boolean seperateArgsAndBindings(Object[] argsAndBindings,
1010 ArrayList<Object> args,
1011 Map<Script.FieldID, Object> bindingMap) {
1012 int i;
1013 for (i = 0; i < argsAndBindings.length; i++) {
1014 if (argsAndBindings[i] instanceof Binding) {
1015 break;
1016 }
1017 args.add(argsAndBindings[i]);
1018 }
1019
1020 for (; i < argsAndBindings.length; i++) {
1021 if (!(argsAndBindings[i] instanceof Binding)) {
1022 return false;
1023 }
1024 Binding b = (Binding)argsAndBindings[i];
1025 bindingMap.put(b.getField(), b.getValue());
1026 }
1027
1028 return true;
1029 }
1030
1031 }
Jason Sams423ebcb2012-08-10 15:40:53 -07001032
1033}