1 /*
2  * Copyright (C) 2008-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 
17 package android.renderscript;
18 
19 import android.compat.annotation.UnsupportedAppUsage;
20 import android.content.Context;
21 import android.content.res.AssetManager;
22 import android.graphics.Bitmap;
23 import android.graphics.SurfaceTexture;
24 import android.os.SystemProperties;
25 import android.os.Trace;
26 import android.util.Log;
27 import android.view.Surface;
28 
29 import java.io.File;
30 import java.lang.reflect.Method;
31 import java.nio.ByteBuffer;
32 import java.util.ArrayList;
33 import java.util.concurrent.locks.ReentrantReadWriteLock;
34 
35 // TODO: Clean up the whitespace that separates methods in this class.
36 
37 /**
38  * This class provides access to a RenderScript context, which controls RenderScript
39  * initialization, resource management, and teardown. An instance of the RenderScript
40  * class must be created before any other RS objects can be created.
41  *
42  * <div class="special reference">
43  * <h3>Developer Guides</h3>
44  * <p>For more information about creating an application that uses RenderScript, read the
45  * <a href="{@docRoot}guide/topics/renderscript/index.html">RenderScript</a> developer guide.</p>
46  * </div>
47  *
48  * @deprecated Renderscript has been deprecated in API level 31. Please refer to the <a
49  * href="https://developer.android.com/guide/topics/renderscript/migration-guide">migration
50  * guide</a> for the proposed alternatives.
51  **/
52 @Deprecated
53 public class RenderScript {
54     static final long TRACE_TAG = Trace.TRACE_TAG_RS;
55 
56     static final String LOG_TAG = "RenderScript_jni";
57     static final boolean DEBUG  = false;
58     @SuppressWarnings({"UnusedDeclaration", "deprecation"})
59     static final boolean LOG_ENABLED = false;
60 
61     static private ArrayList<RenderScript> mProcessContextList = new ArrayList<RenderScript>();
62     private boolean mIsProcessContext = false;
63     private int mContextFlags = 0;
64     private int mContextSdkVersion = 0;
65 
66 
67     private Context mApplicationContext;
68 
69     /*
70      * We use a class initializer to allow the native code to cache some
71      * field offsets.
72      */
73     @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) // TODO: now used locally; remove?
74     static boolean sInitialized;
_nInit()75     native static void _nInit();
76 
77     static Object sRuntime;
78     static Method registerNativeAllocation;
79     static Method registerNativeFree;
80 
81     /*
82      * Context creation flag that specifies a normal context.
83     */
84     public static final int CREATE_FLAG_NONE = 0x0000;
85 
86     /*
87      * Context creation flag which specifies a context optimized for low
88      * latency over peak performance. This is a hint and may have no effect
89      * on some implementations.
90     */
91     public static final int CREATE_FLAG_LOW_LATENCY = 0x0002;
92 
93     /*
94      * Context creation flag which specifies a context optimized for long
95      * battery life over peak performance. This is a hint and may have no effect
96      * on some implementations.
97     */
98     public static final int CREATE_FLAG_LOW_POWER = 0x0004;
99 
100     /**
101      * @hide
102      * Context creation flag which instructs the implementation to wait for
103      * a debugger to be attached before continuing execution.
104     */
105     public static final int CREATE_FLAG_WAIT_FOR_ATTACH = 0x0008;
106 
107 
108     /*
109      * Detect the bitness of the VM to allow FieldPacker to do the right thing.
110      */
rsnSystemGetPointerSize()111     static native int rsnSystemGetPointerSize();
112     @UnsupportedAppUsage
113     static int sPointerSize;
114 
115     static {
116         sInitialized = false;
117         if (!SystemProperties.getBoolean("config.disable_renderscript", false)) {
118             try {
119                 Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
120                 Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
121                 sRuntime = get_runtime.invoke(null);
122                 registerNativeAllocation =
123                         vm_runtime.getDeclaredMethod("registerNativeAllocation", Long.TYPE);
124                 registerNativeFree = vm_runtime.getDeclaredMethod("registerNativeFree", Long.TYPE);
125             } catch (Exception e) {
126                 Log.e(LOG_TAG, "Error loading GC methods: " + e);
127                 throw new RSRuntimeException("Error loading GC methods: " + e);
128             }
129             try {
130                 System.loadLibrary("rs_jni");
_nInit()131                 _nInit();
132                 sInitialized = true;
133                 sPointerSize = rsnSystemGetPointerSize();
134             } catch (UnsatisfiedLinkError e) {
135                 Log.e(LOG_TAG, "Error loading RS jni library: " + e);
136                 throw new RSRuntimeException("Error loading RS jni library: " + e);
137             }
138         }
139     }
140 
141     // Non-threadsafe functions.
nDeviceCreate()142     native long  nDeviceCreate();
nDeviceDestroy(long dev)143     native void nDeviceDestroy(long dev);
nDeviceSetConfig(long dev, int param, int value)144     native void nDeviceSetConfig(long dev, int param, int value);
nContextGetUserMessage(long con, int[] data)145     native int nContextGetUserMessage(long con, int[] data);
nContextGetErrorMessage(long con)146     native String nContextGetErrorMessage(long con);
nContextPeekMessage(long con, int[] subID)147     native int  nContextPeekMessage(long con, int[] subID);
nContextInitToClient(long con)148     native void nContextInitToClient(long con);
nContextDeinitToClient(long con)149     native void nContextDeinitToClient(long con);
150 
151     // this should be a monotonically increasing ID
152     // used in conjunction with the API version of a device
153     static final long sMinorVersion = 1;
154 
155     /**
156      * @hide
157      *
158      * Only exist to be compatible with old version RenderScript Support lib.
159      * Will eventually be removed.
160      *
161      * @return Always return 1
162      *
163      */
164     @UnsupportedAppUsage
getMinorID()165     public static long getMinorID() {
166         return 1;
167     }
168 
169 
170     /**
171      * Returns an identifier that can be used to identify a particular
172      * minor version of RS.
173      *
174      * @return The minor RenderScript version number
175      *
176      */
getMinorVersion()177     public static long getMinorVersion() {
178         return sMinorVersion;
179     }
180 
181     /**
182      * ContextType specifies the specific type of context to be created.
183      *
184      */
185     public enum ContextType {
186         /**
187          * NORMAL context, this is the default and what shipping apps should
188          * use.
189          */
190         NORMAL (0),
191 
192         /**
193          * DEBUG context, perform extra runtime checks to validate the
194          * kernels and APIs are being used as intended.  Get and SetElementAt
195          * will be bounds checked in this mode.
196          */
197         DEBUG (1),
198 
199         /**
200          * PROFILE context, Intended to be used once the first time an
201          * application is run on a new device.  This mode allows the runtime to
202          * do additional testing and performance tuning.
203          */
204         PROFILE (2);
205 
206         int mID;
ContextType(int id)207         ContextType(int id) {
208             mID = id;
209         }
210     }
211 
212     ContextType mContextType;
213     ReentrantReadWriteLock mRWLock;
214 
215     // Methods below are wrapped to protect the non-threadsafe
216     // lockless fifo.
rsnContextCreateGL(long dev, int ver, int sdkVer, int colorMin, int colorPref, int alphaMin, int alphaPref, int depthMin, int depthPref, int stencilMin, int stencilPref, int samplesMin, int samplesPref, float samplesQ, int dpi)217     native long  rsnContextCreateGL(long dev, int ver, int sdkVer,
218                  int colorMin, int colorPref,
219                  int alphaMin, int alphaPref,
220                  int depthMin, int depthPref,
221                  int stencilMin, int stencilPref,
222                  int samplesMin, int samplesPref, float samplesQ, int dpi);
nContextCreateGL(long dev, int ver, int sdkVer, int colorMin, int colorPref, int alphaMin, int alphaPref, int depthMin, int depthPref, int stencilMin, int stencilPref, int samplesMin, int samplesPref, float samplesQ, int dpi)223     synchronized long nContextCreateGL(long dev, int ver, int sdkVer,
224                  int colorMin, int colorPref,
225                  int alphaMin, int alphaPref,
226                  int depthMin, int depthPref,
227                  int stencilMin, int stencilPref,
228                  int samplesMin, int samplesPref, float samplesQ, int dpi) {
229         return rsnContextCreateGL(dev, ver, sdkVer, colorMin, colorPref,
230                                   alphaMin, alphaPref, depthMin, depthPref,
231                                   stencilMin, stencilPref,
232                                   samplesMin, samplesPref, samplesQ, dpi);
233     }
rsnContextCreate(long dev, int ver, int sdkVer, int contextType)234     native long  rsnContextCreate(long dev, int ver, int sdkVer, int contextType);
nContextCreate(long dev, int ver, int sdkVer, int contextType)235     synchronized long nContextCreate(long dev, int ver, int sdkVer, int contextType) {
236         return rsnContextCreate(dev, ver, sdkVer, contextType);
237     }
rsnContextDestroy(long con)238     native void rsnContextDestroy(long con);
nContextDestroy()239     synchronized void nContextDestroy() {
240         validate();
241 
242         // take teardown lock
243         // teardown lock can only be taken when no objects are being destroyed
244         ReentrantReadWriteLock.WriteLock wlock = mRWLock.writeLock();
245         wlock.lock();
246 
247         long curCon = mContext;
248         // context is considered dead as of this point
249         mContext = 0;
250 
251         wlock.unlock();
252         rsnContextDestroy(curCon);
253     }
rsnContextSetSurface(long con, int w, int h, Surface sur)254     native void rsnContextSetSurface(long con, int w, int h, Surface sur);
nContextSetSurface(int w, int h, Surface sur)255     synchronized void nContextSetSurface(int w, int h, Surface sur) {
256         validate();
257         rsnContextSetSurface(mContext, w, h, sur);
258     }
rsnContextSetSurfaceTexture(long con, int w, int h, SurfaceTexture sur)259     native void rsnContextSetSurfaceTexture(long con, int w, int h, SurfaceTexture sur);
nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur)260     synchronized void nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur) {
261         validate();
262         rsnContextSetSurfaceTexture(mContext, w, h, sur);
263     }
rsnContextSetPriority(long con, int p)264     native void rsnContextSetPriority(long con, int p);
nContextSetPriority(int p)265     synchronized void nContextSetPriority(int p) {
266         validate();
267         rsnContextSetPriority(mContext, p);
268     }
rsnContextSetCacheDir(long con, String cacheDir)269     native void rsnContextSetCacheDir(long con, String cacheDir);
nContextSetCacheDir(String cacheDir)270     synchronized void nContextSetCacheDir(String cacheDir) {
271         validate();
272         rsnContextSetCacheDir(mContext, cacheDir);
273     }
rsnContextDump(long con, int bits)274     native void rsnContextDump(long con, int bits);
nContextDump(int bits)275     synchronized void nContextDump(int bits) {
276         validate();
277         rsnContextDump(mContext, bits);
278     }
rsnContextFinish(long con)279     native void rsnContextFinish(long con);
nContextFinish()280     synchronized void nContextFinish() {
281         validate();
282         rsnContextFinish(mContext);
283     }
284 
rsnContextSendMessage(long con, int id, int[] data)285     native void rsnContextSendMessage(long con, int id, int[] data);
nContextSendMessage(int id, int[] data)286     synchronized void nContextSendMessage(int id, int[] data) {
287         validate();
288         rsnContextSendMessage(mContext, id, data);
289     }
290 
rsnContextBindRootScript(long con, long script)291     native void rsnContextBindRootScript(long con, long script);
nContextBindRootScript(long script)292     synchronized void nContextBindRootScript(long script) {
293         validate();
294         rsnContextBindRootScript(mContext, script);
295     }
rsnContextBindSampler(long con, int sampler, int slot)296     native void rsnContextBindSampler(long con, int sampler, int slot);
nContextBindSampler(int sampler, int slot)297     synchronized void nContextBindSampler(int sampler, int slot) {
298         validate();
299         rsnContextBindSampler(mContext, sampler, slot);
300     }
rsnContextBindProgramStore(long con, long pfs)301     native void rsnContextBindProgramStore(long con, long pfs);
nContextBindProgramStore(long pfs)302     synchronized void nContextBindProgramStore(long pfs) {
303         validate();
304         rsnContextBindProgramStore(mContext, pfs);
305     }
rsnContextBindProgramFragment(long con, long pf)306     native void rsnContextBindProgramFragment(long con, long pf);
nContextBindProgramFragment(long pf)307     synchronized void nContextBindProgramFragment(long pf) {
308         validate();
309         rsnContextBindProgramFragment(mContext, pf);
310     }
rsnContextBindProgramVertex(long con, long pv)311     native void rsnContextBindProgramVertex(long con, long pv);
nContextBindProgramVertex(long pv)312     synchronized void nContextBindProgramVertex(long pv) {
313         validate();
314         rsnContextBindProgramVertex(mContext, pv);
315     }
rsnContextBindProgramRaster(long con, long pr)316     native void rsnContextBindProgramRaster(long con, long pr);
nContextBindProgramRaster(long pr)317     synchronized void nContextBindProgramRaster(long pr) {
318         validate();
319         rsnContextBindProgramRaster(mContext, pr);
320     }
rsnContextPause(long con)321     native void rsnContextPause(long con);
nContextPause()322     synchronized void nContextPause() {
323         validate();
324         rsnContextPause(mContext);
325     }
rsnContextResume(long con)326     native void rsnContextResume(long con);
nContextResume()327     synchronized void nContextResume() {
328         validate();
329         rsnContextResume(mContext);
330     }
331 
rsnClosureCreate(long con, long kernelID, long returnValue, long[] fieldIDs, long[] values, int[] sizes, long[] depClosures, long[] depFieldIDs)332     native long rsnClosureCreate(long con, long kernelID, long returnValue,
333         long[] fieldIDs, long[] values, int[] sizes, long[] depClosures,
334         long[] depFieldIDs);
nClosureCreate(long kernelID, long returnValue, long[] fieldIDs, long[] values, int[] sizes, long[] depClosures, long[] depFieldIDs)335     synchronized long nClosureCreate(long kernelID, long returnValue,
336         long[] fieldIDs, long[] values, int[] sizes, long[] depClosures,
337         long[] depFieldIDs) {
338       validate();
339       long c = rsnClosureCreate(mContext, kernelID, returnValue, fieldIDs, values,
340           sizes, depClosures, depFieldIDs);
341       if (c == 0) {
342           throw new RSRuntimeException("Failed creating closure.");
343       }
344       return c;
345     }
346 
rsnInvokeClosureCreate(long con, long invokeID, byte[] params, long[] fieldIDs, long[] values, int[] sizes)347     native long rsnInvokeClosureCreate(long con, long invokeID, byte[] params,
348         long[] fieldIDs, long[] values, int[] sizes);
nInvokeClosureCreate(long invokeID, byte[] params, long[] fieldIDs, long[] values, int[] sizes)349     synchronized long nInvokeClosureCreate(long invokeID, byte[] params,
350         long[] fieldIDs, long[] values, int[] sizes) {
351       validate();
352       long c = rsnInvokeClosureCreate(mContext, invokeID, params, fieldIDs,
353           values, sizes);
354       if (c == 0) {
355           throw new RSRuntimeException("Failed creating closure.");
356       }
357       return c;
358     }
359 
rsnClosureSetArg(long con, long closureID, int index, long value, int size)360     native void rsnClosureSetArg(long con, long closureID, int index,
361       long value, int size);
nClosureSetArg(long closureID, int index, long value, int size)362     synchronized void nClosureSetArg(long closureID, int index, long value,
363         int size) {
364       validate();
365       rsnClosureSetArg(mContext, closureID, index, value, size);
366     }
367 
rsnClosureSetGlobal(long con, long closureID, long fieldID, long value, int size)368     native void rsnClosureSetGlobal(long con, long closureID, long fieldID,
369         long value, int size);
370     // Does this have to be synchronized?
nClosureSetGlobal(long closureID, long fieldID, long value, int size)371     synchronized void nClosureSetGlobal(long closureID, long fieldID,
372         long value, int size) {
373       validate(); // TODO: is this necessary?
374       rsnClosureSetGlobal(mContext, closureID, fieldID, value, size);
375     }
376 
rsnScriptGroup2Create(long con, String name, String cachePath, long[] closures)377     native long rsnScriptGroup2Create(long con, String name, String cachePath,
378                                       long[] closures);
nScriptGroup2Create(String name, String cachePath, long[] closures)379     synchronized long nScriptGroup2Create(String name, String cachePath,
380                                           long[] closures) {
381       validate();
382       long g = rsnScriptGroup2Create(mContext, name, cachePath, closures);
383       if (g == 0) {
384           throw new RSRuntimeException("Failed creating script group.");
385       }
386       return g;
387     }
388 
rsnScriptGroup2Execute(long con, long groupID)389     native void rsnScriptGroup2Execute(long con, long groupID);
nScriptGroup2Execute(long groupID)390     synchronized void nScriptGroup2Execute(long groupID) {
391       validate();
392       rsnScriptGroup2Execute(mContext, groupID);
393     }
394 
rsnAssignName(long con, long obj, byte[] name)395     native void rsnAssignName(long con, long obj, byte[] name);
nAssignName(long obj, byte[] name)396     synchronized void nAssignName(long obj, byte[] name) {
397         validate();
398         rsnAssignName(mContext, obj, name);
399     }
rsnGetName(long con, long obj)400     native String rsnGetName(long con, long obj);
nGetName(long obj)401     synchronized String nGetName(long obj) {
402         validate();
403         return rsnGetName(mContext, obj);
404     }
405 
406     // nObjDestroy is explicitly _not_ synchronous to prevent crashes in finalizers
rsnObjDestroy(long con, long id)407     native void rsnObjDestroy(long con, long id);
nObjDestroy(long id)408     void nObjDestroy(long id) {
409         // There is a race condition here.  The calling code may be run
410         // by the gc while teardown is occuring.  This protects againts
411         // deleting dead objects.
412         if (mContext != 0) {
413             rsnObjDestroy(mContext, id);
414         }
415     }
416 
rsnElementCreate(long con, long type, int kind, boolean norm, int vecSize)417     native long rsnElementCreate(long con, long type, int kind, boolean norm, int vecSize);
nElementCreate(long type, int kind, boolean norm, int vecSize)418     synchronized long nElementCreate(long type, int kind, boolean norm, int vecSize) {
419         validate();
420         return rsnElementCreate(mContext, type, kind, norm, vecSize);
421     }
rsnElementCreate2(long con, long[] elements, String[] names, int[] arraySizes)422     native long rsnElementCreate2(long con, long[] elements, String[] names, int[] arraySizes);
nElementCreate2(long[] elements, String[] names, int[] arraySizes)423     synchronized long nElementCreate2(long[] elements, String[] names, int[] arraySizes) {
424         validate();
425         return rsnElementCreate2(mContext, elements, names, arraySizes);
426     }
rsnElementGetNativeData(long con, long id, int[] elementData)427     native void rsnElementGetNativeData(long con, long id, int[] elementData);
nElementGetNativeData(long id, int[] elementData)428     synchronized void nElementGetNativeData(long id, int[] elementData) {
429         validate();
430         rsnElementGetNativeData(mContext, id, elementData);
431     }
rsnElementGetSubElements(long con, long id, long[] IDs, String[] names, int[] arraySizes)432     native void rsnElementGetSubElements(long con, long id,
433                                          long[] IDs, String[] names, int[] arraySizes);
nElementGetSubElements(long id, long[] IDs, String[] names, int[] arraySizes)434     synchronized void nElementGetSubElements(long id, long[] IDs, String[] names, int[] arraySizes) {
435         validate();
436         rsnElementGetSubElements(mContext, id, IDs, names, arraySizes);
437     }
438 
rsnTypeCreate(long con, long eid, int x, int y, int z, boolean mips, boolean faces, int yuv)439     native long rsnTypeCreate(long con, long eid, int x, int y, int z, boolean mips, boolean faces, int yuv);
nTypeCreate(long eid, int x, int y, int z, boolean mips, boolean faces, int yuv)440     synchronized long nTypeCreate(long eid, int x, int y, int z, boolean mips, boolean faces, int yuv) {
441         validate();
442         return rsnTypeCreate(mContext, eid, x, y, z, mips, faces, yuv);
443     }
rsnTypeGetNativeData(long con, long id, long[] typeData)444     native void rsnTypeGetNativeData(long con, long id, long[] typeData);
nTypeGetNativeData(long id, long[] typeData)445     synchronized void nTypeGetNativeData(long id, long[] typeData) {
446         validate();
447         rsnTypeGetNativeData(mContext, id, typeData);
448     }
449 
rsnAllocationCreateTyped(long con, long type, int mip, int usage, long pointer)450     native long rsnAllocationCreateTyped(long con, long type, int mip, int usage, long pointer);
nAllocationCreateTyped(long type, int mip, int usage, long pointer)451     synchronized long nAllocationCreateTyped(long type, int mip, int usage, long pointer) {
452         validate();
453         return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer);
454     }
455 
rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage)456     native long rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp,
457                 int usage);
nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage)458     synchronized long nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
459         validate();
460         return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
461     }
462 
rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp, int usage)463     native long rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp,
464                 int usage);
nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp, int usage)465     synchronized long nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp,
466                 int usage) {
467         validate();
468         return rsnAllocationCreateBitmapBackedAllocation(mContext, type, mip, bmp, usage);
469     }
470 
rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage)471     native long rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp,
472                 int usage);
nAllocationCubeCreateFromBitmap(long type, int mip, Bitmap bmp, int usage)473     synchronized long nAllocationCubeCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
474         validate();
475         return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage);
476     }
477 
rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp)478     native void  rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp);
nAllocationCopyToBitmap(long alloc, Bitmap bmp)479     synchronized void nAllocationCopyToBitmap(long alloc, Bitmap bmp) {
480         validate();
481         rsnAllocationCopyToBitmap(mContext, alloc, bmp);
482     }
483 
rsnAllocationSyncAll(long con, long alloc, int src)484     native void rsnAllocationSyncAll(long con, long alloc, int src);
nAllocationSyncAll(long alloc, int src)485     synchronized void nAllocationSyncAll(long alloc, int src) {
486         validate();
487         rsnAllocationSyncAll(mContext, alloc, src);
488     }
489 
rsnAllocationGetByteBuffer(long con, long alloc, long[] stride, int xBytesSize, int dimY, int dimZ)490     native ByteBuffer rsnAllocationGetByteBuffer(long con, long alloc, long[] stride,
491                 int xBytesSize, int dimY, int dimZ);
nAllocationGetByteBuffer(long alloc, long[] stride, int xBytesSize, int dimY, int dimZ)492     synchronized ByteBuffer nAllocationGetByteBuffer(long alloc, long[] stride, int xBytesSize,
493                 int dimY, int dimZ) {
494         validate();
495         return rsnAllocationGetByteBuffer(mContext, alloc, stride, xBytesSize, dimY, dimZ);
496     }
497 
rsnAllocationSetupBufferQueue(long con, long alloc, int numAlloc)498     native void rsnAllocationSetupBufferQueue(long con, long alloc, int numAlloc);
nAllocationSetupBufferQueue(long alloc, int numAlloc)499     synchronized void nAllocationSetupBufferQueue(long alloc, int numAlloc) {
500         validate();
501         rsnAllocationSetupBufferQueue(mContext, alloc, numAlloc);
502     }
rsnAllocationShareBufferQueue(long con, long alloc1, long alloc2)503     native void rsnAllocationShareBufferQueue(long con, long alloc1, long alloc2);
nAllocationShareBufferQueue(long alloc1, long alloc2)504     synchronized void nAllocationShareBufferQueue(long alloc1, long alloc2) {
505         validate();
506         rsnAllocationShareBufferQueue(mContext, alloc1, alloc2);
507     }
rsnAllocationGetSurface(long con, long alloc)508     native Surface rsnAllocationGetSurface(long con, long alloc);
nAllocationGetSurface(long alloc)509     synchronized Surface nAllocationGetSurface(long alloc) {
510         validate();
511         return rsnAllocationGetSurface(mContext, alloc);
512     }
rsnAllocationSetSurface(long con, long alloc, Surface sur)513     native void rsnAllocationSetSurface(long con, long alloc, Surface sur);
nAllocationSetSurface(long alloc, Surface sur)514     synchronized void nAllocationSetSurface(long alloc, Surface sur) {
515         validate();
516         rsnAllocationSetSurface(mContext, alloc, sur);
517     }
rsnAllocationIoSend(long con, long alloc)518     native void rsnAllocationIoSend(long con, long alloc);
nAllocationIoSend(long alloc)519     synchronized void nAllocationIoSend(long alloc) {
520         validate();
521         rsnAllocationIoSend(mContext, alloc);
522     }
rsnAllocationIoReceive(long con, long alloc)523     native long rsnAllocationIoReceive(long con, long alloc);
nAllocationIoReceive(long alloc)524     synchronized long nAllocationIoReceive(long alloc) {
525         validate();
526         return rsnAllocationIoReceive(mContext, alloc);
527     }
528 
rsnAllocationGenerateMipmaps(long con, long alloc)529     native void rsnAllocationGenerateMipmaps(long con, long alloc);
nAllocationGenerateMipmaps(long alloc)530     synchronized void nAllocationGenerateMipmaps(long alloc) {
531         validate();
532         rsnAllocationGenerateMipmaps(mContext, alloc);
533     }
rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp)534     native void  rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp);
nAllocationCopyFromBitmap(long alloc, Bitmap bmp)535     synchronized void nAllocationCopyFromBitmap(long alloc, Bitmap bmp) {
536         validate();
537         rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
538     }
539 
540 
rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)541     native void rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt,
542                                     int mSize, boolean usePadding);
nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)543     synchronized void nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt,
544                                         int mSize, boolean usePadding) {
545         validate();
546         rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
547     }
548 
rsnAllocationElementData(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes)549     native void rsnAllocationElementData(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes);
nAllocationElementData(long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes)550     synchronized void nAllocationElementData(long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes) {
551         validate();
552         rsnAllocationElementData(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
553     }
554 
rsnAllocationData2D(long con, long dstAlloc, int dstXoff, int dstYoff, int dstMip, int dstFace, int width, int height, long srcAlloc, int srcXoff, int srcYoff, int srcMip, int srcFace)555     native void rsnAllocationData2D(long con,
556                                     long dstAlloc, int dstXoff, int dstYoff,
557                                     int dstMip, int dstFace,
558                                     int width, int height,
559                                     long srcAlloc, int srcXoff, int srcYoff,
560                                     int srcMip, int srcFace);
nAllocationData2D(long dstAlloc, int dstXoff, int dstYoff, int dstMip, int dstFace, int width, int height, long srcAlloc, int srcXoff, int srcYoff, int srcMip, int srcFace)561     synchronized void nAllocationData2D(long dstAlloc, int dstXoff, int dstYoff,
562                                         int dstMip, int dstFace,
563                                         int width, int height,
564                                         long srcAlloc, int srcXoff, int srcYoff,
565                                         int srcMip, int srcFace) {
566         validate();
567         rsnAllocationData2D(mContext,
568                             dstAlloc, dstXoff, dstYoff,
569                             dstMip, dstFace,
570                             width, height,
571                             srcAlloc, srcXoff, srcYoff,
572                             srcMip, srcFace);
573     }
574 
rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, int w, int h, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)575     native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face,
576                                     int w, int h, Object d, int sizeBytes, int dt,
577                                     int mSize, boolean usePadding);
nAllocationData2D(long id, int xoff, int yoff, int mip, int face, int w, int h, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)578     synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face,
579                                         int w, int h, Object d, int sizeBytes, Element.DataType dt,
580                                         int mSize, boolean usePadding) {
581         validate();
582         rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
583     }
584 
rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, Bitmap b)585     native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, Bitmap b);
nAllocationData2D(long id, int xoff, int yoff, int mip, int face, Bitmap b)586     synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face, Bitmap b) {
587         validate();
588         rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
589     }
590 
rsnAllocationData3D(long con, long dstAlloc, int dstXoff, int dstYoff, int dstZoff, int dstMip, int width, int height, int depth, long srcAlloc, int srcXoff, int srcYoff, int srcZoff, int srcMip)591     native void rsnAllocationData3D(long con,
592                                     long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
593                                     int dstMip,
594                                     int width, int height, int depth,
595                                     long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
596                                     int srcMip);
nAllocationData3D(long dstAlloc, int dstXoff, int dstYoff, int dstZoff, int dstMip, int width, int height, int depth, long srcAlloc, int srcXoff, int srcYoff, int srcZoff, int srcMip)597     synchronized void nAllocationData3D(long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
598                                         int dstMip,
599                                         int width, int height, int depth,
600                                         long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
601                                         int srcMip) {
602         validate();
603         rsnAllocationData3D(mContext,
604                             dstAlloc, dstXoff, dstYoff, dstZoff,
605                             dstMip, width, height, depth,
606                             srcAlloc, srcXoff, srcYoff, srcZoff, srcMip);
607     }
608 
rsnAllocationData3D(long con, long id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)609     native void rsnAllocationData3D(long con, long id, int xoff, int yoff, int zoff, int mip,
610                                     int w, int h, int depth, Object d, int sizeBytes, int dt,
611                                     int mSize, boolean usePadding);
nAllocationData3D(long id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)612     synchronized void nAllocationData3D(long id, int xoff, int yoff, int zoff, int mip,
613                                         int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
614                                         int mSize, boolean usePadding) {
615         validate();
616         rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes,
617                             dt.mID, mSize, usePadding);
618     }
619 
rsnAllocationRead(long con, long id, Object d, int dt, int mSize, boolean usePadding)620     native void rsnAllocationRead(long con, long id, Object d, int dt, int mSize, boolean usePadding);
nAllocationRead(long id, Object d, Element.DataType dt, int mSize, boolean usePadding)621     synchronized void nAllocationRead(long id, Object d, Element.DataType dt, int mSize, boolean usePadding) {
622         validate();
623         rsnAllocationRead(mContext, id, d, dt.mID, mSize, usePadding);
624     }
625 
rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)626     native void rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d,
627                                     int sizeBytes, int dt, int mSize, boolean usePadding);
nAllocationRead1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)628     synchronized void nAllocationRead1D(long id, int off, int mip, int count, Object d,
629                                         int sizeBytes, Element.DataType dt, int mSize, boolean usePadding) {
630         validate();
631         rsnAllocationRead1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
632     }
633 
rsnAllocationElementRead(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes)634     native void rsnAllocationElementRead(long con,long id, int xoff, int yoff, int zoff,
635                                          int mip, int compIdx, byte[] d, int sizeBytes);
nAllocationElementRead(long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes)636     synchronized void nAllocationElementRead(long id, int xoff, int yoff, int zoff,
637                                              int mip, int compIdx, byte[] d, int sizeBytes) {
638         validate();
639         rsnAllocationElementRead(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
640     }
641 
rsnAllocationRead2D(long con, long id, int xoff, int yoff, int mip, int face, int w, int h, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)642     native void rsnAllocationRead2D(long con, long id, int xoff, int yoff, int mip, int face,
643                                     int w, int h, Object d, int sizeBytes, int dt,
644                                     int mSize, boolean usePadding);
nAllocationRead2D(long id, int xoff, int yoff, int mip, int face, int w, int h, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)645     synchronized void nAllocationRead2D(long id, int xoff, int yoff, int mip, int face,
646                                         int w, int h, Object d, int sizeBytes, Element.DataType dt,
647                                         int mSize, boolean usePadding) {
648         validate();
649         rsnAllocationRead2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
650     }
651 
rsnAllocationRead3D(long con, long id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)652     native void rsnAllocationRead3D(long con, long id, int xoff, int yoff, int zoff, int mip,
653                                     int w, int h, int depth, Object d, int sizeBytes, int dt,
654                                     int mSize, boolean usePadding);
nAllocationRead3D(long id, int xoff, int yoff, int zoff, int mip, int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)655     synchronized void nAllocationRead3D(long id, int xoff, int yoff, int zoff, int mip,
656                                         int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
657                                         int mSize, boolean usePadding) {
658         validate();
659         rsnAllocationRead3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes, dt.mID, mSize, usePadding);
660     }
661 
rsnAllocationGetType(long con, long id)662     native long  rsnAllocationGetType(long con, long id);
nAllocationGetType(long id)663     synchronized long nAllocationGetType(long id) {
664         validate();
665         return rsnAllocationGetType(mContext, id);
666     }
667 
rsnAllocationResize1D(long con, long id, int dimX)668     native void rsnAllocationResize1D(long con, long id, int dimX);
nAllocationResize1D(long id, int dimX)669     synchronized void nAllocationResize1D(long id, int dimX) {
670         validate();
671         rsnAllocationResize1D(mContext, id, dimX);
672     }
673 
rsnAllocationAdapterCreate(long con, long allocId, long typeId)674     native long  rsnAllocationAdapterCreate(long con, long allocId, long typeId);
nAllocationAdapterCreate(long allocId, long typeId)675     synchronized long nAllocationAdapterCreate(long allocId, long typeId) {
676         validate();
677         return rsnAllocationAdapterCreate(mContext, allocId, typeId);
678     }
679 
rsnAllocationAdapterOffset(long con, long id, int x, int y, int z, int mip, int face, int a1, int a2, int a3, int a4)680     native void  rsnAllocationAdapterOffset(long con, long id, int x, int y, int z,
681                                             int mip, int face, int a1, int a2, int a3, int a4);
nAllocationAdapterOffset(long id, int x, int y, int z, int mip, int face, int a1, int a2, int a3, int a4)682     synchronized void nAllocationAdapterOffset(long id, int x, int y, int z,
683                                                int mip, int face, int a1, int a2, int a3, int a4) {
684         validate();
685         rsnAllocationAdapterOffset(mContext, id, x, y, z, mip, face, a1, a2, a3, a4);
686     }
687 
rsnFileA3DCreateFromAssetStream(long con, long assetStream)688     native long rsnFileA3DCreateFromAssetStream(long con, long assetStream);
nFileA3DCreateFromAssetStream(long assetStream)689     synchronized long nFileA3DCreateFromAssetStream(long assetStream) {
690         validate();
691         return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
692     }
rsnFileA3DCreateFromFile(long con, String path)693     native long rsnFileA3DCreateFromFile(long con, String path);
nFileA3DCreateFromFile(String path)694     synchronized long nFileA3DCreateFromFile(String path) {
695         validate();
696         return rsnFileA3DCreateFromFile(mContext, path);
697     }
rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path)698     native long rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path);
nFileA3DCreateFromAsset(AssetManager mgr, String path)699     synchronized long nFileA3DCreateFromAsset(AssetManager mgr, String path) {
700         validate();
701         return rsnFileA3DCreateFromAsset(mContext, mgr, path);
702     }
rsnFileA3DGetNumIndexEntries(long con, long fileA3D)703     native int  rsnFileA3DGetNumIndexEntries(long con, long fileA3D);
nFileA3DGetNumIndexEntries(long fileA3D)704     synchronized int nFileA3DGetNumIndexEntries(long fileA3D) {
705         validate();
706         return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
707     }
rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names)708     native void rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names);
nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names)709     synchronized void nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names) {
710         validate();
711         rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
712     }
rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index)713     native long rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index);
nFileA3DGetEntryByIndex(long fileA3D, int index)714     synchronized long nFileA3DGetEntryByIndex(long fileA3D, int index) {
715         validate();
716         return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
717     }
718 
rsnFontCreateFromFile(long con, String fileName, float size, int dpi)719     native long rsnFontCreateFromFile(long con, String fileName, float size, int dpi);
nFontCreateFromFile(String fileName, float size, int dpi)720     synchronized long nFontCreateFromFile(String fileName, float size, int dpi) {
721         validate();
722         return rsnFontCreateFromFile(mContext, fileName, size, dpi);
723     }
rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream)724     native long rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream);
nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream)725     synchronized long nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream) {
726         validate();
727         return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
728     }
rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi)729     native long rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi);
nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi)730     synchronized long nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
731         validate();
732         return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
733     }
734 
735 
rsnScriptBindAllocation(long con, long script, long alloc, int slot)736     native void rsnScriptBindAllocation(long con, long script, long alloc, int slot);
nScriptBindAllocation(long script, long alloc, int slot)737     synchronized void nScriptBindAllocation(long script, long alloc, int slot) {
738         validate();
739         rsnScriptBindAllocation(mContext, script, alloc, slot);
740     }
rsnScriptSetTimeZone(long con, long script, byte[] timeZone)741     native void rsnScriptSetTimeZone(long con, long script, byte[] timeZone);
nScriptSetTimeZone(long script, byte[] timeZone)742     synchronized void nScriptSetTimeZone(long script, byte[] timeZone) {
743         validate();
744         rsnScriptSetTimeZone(mContext, script, timeZone);
745     }
rsnScriptInvoke(long con, long id, int slot)746     native void rsnScriptInvoke(long con, long id, int slot);
nScriptInvoke(long id, int slot)747     synchronized void nScriptInvoke(long id, int slot) {
748         validate();
749         rsnScriptInvoke(mContext, id, slot);
750     }
751 
rsnScriptForEach(long con, long id, int slot, long[] ains, long aout, byte[] params, int[] limits)752     native void rsnScriptForEach(long con, long id, int slot, long[] ains,
753                                  long aout, byte[] params, int[] limits);
754 
nScriptForEach(long id, int slot, long[] ains, long aout, byte[] params, int[] limits)755     synchronized void nScriptForEach(long id, int slot, long[] ains, long aout,
756                                      byte[] params, int[] limits) {
757         validate();
758         rsnScriptForEach(mContext, id, slot, ains, aout, params, limits);
759     }
760 
rsnScriptReduce(long con, long id, int slot, long[] ains, long aout, int[] limits)761     native void rsnScriptReduce(long con, long id, int slot, long[] ains,
762                                 long aout, int[] limits);
nScriptReduce(long id, int slot, long ains[], long aout, int[] limits)763     synchronized void nScriptReduce(long id, int slot, long ains[], long aout,
764                                     int[] limits) {
765         validate();
766         rsnScriptReduce(mContext, id, slot, ains, aout, limits);
767     }
768 
rsnScriptInvokeV(long con, long id, int slot, byte[] params)769     native void rsnScriptInvokeV(long con, long id, int slot, byte[] params);
nScriptInvokeV(long id, int slot, byte[] params)770     synchronized void nScriptInvokeV(long id, int slot, byte[] params) {
771         validate();
772         rsnScriptInvokeV(mContext, id, slot, params);
773     }
774 
rsnScriptSetVarI(long con, long id, int slot, int val)775     native void rsnScriptSetVarI(long con, long id, int slot, int val);
nScriptSetVarI(long id, int slot, int val)776     synchronized void nScriptSetVarI(long id, int slot, int val) {
777         validate();
778         rsnScriptSetVarI(mContext, id, slot, val);
779     }
rsnScriptGetVarI(long con, long id, int slot)780     native int rsnScriptGetVarI(long con, long id, int slot);
nScriptGetVarI(long id, int slot)781     synchronized int nScriptGetVarI(long id, int slot) {
782         validate();
783         return rsnScriptGetVarI(mContext, id, slot);
784     }
785 
rsnScriptSetVarJ(long con, long id, int slot, long val)786     native void rsnScriptSetVarJ(long con, long id, int slot, long val);
nScriptSetVarJ(long id, int slot, long val)787     synchronized void nScriptSetVarJ(long id, int slot, long val) {
788         validate();
789         rsnScriptSetVarJ(mContext, id, slot, val);
790     }
rsnScriptGetVarJ(long con, long id, int slot)791     native long rsnScriptGetVarJ(long con, long id, int slot);
nScriptGetVarJ(long id, int slot)792     synchronized long nScriptGetVarJ(long id, int slot) {
793         validate();
794         return rsnScriptGetVarJ(mContext, id, slot);
795     }
796 
rsnScriptSetVarF(long con, long id, int slot, float val)797     native void rsnScriptSetVarF(long con, long id, int slot, float val);
nScriptSetVarF(long id, int slot, float val)798     synchronized void nScriptSetVarF(long id, int slot, float val) {
799         validate();
800         rsnScriptSetVarF(mContext, id, slot, val);
801     }
rsnScriptGetVarF(long con, long id, int slot)802     native float rsnScriptGetVarF(long con, long id, int slot);
nScriptGetVarF(long id, int slot)803     synchronized float nScriptGetVarF(long id, int slot) {
804         validate();
805         return rsnScriptGetVarF(mContext, id, slot);
806     }
rsnScriptSetVarD(long con, long id, int slot, double val)807     native void rsnScriptSetVarD(long con, long id, int slot, double val);
nScriptSetVarD(long id, int slot, double val)808     synchronized void nScriptSetVarD(long id, int slot, double val) {
809         validate();
810         rsnScriptSetVarD(mContext, id, slot, val);
811     }
rsnScriptGetVarD(long con, long id, int slot)812     native double rsnScriptGetVarD(long con, long id, int slot);
nScriptGetVarD(long id, int slot)813     synchronized double nScriptGetVarD(long id, int slot) {
814         validate();
815         return rsnScriptGetVarD(mContext, id, slot);
816     }
rsnScriptSetVarV(long con, long id, int slot, byte[] val)817     native void rsnScriptSetVarV(long con, long id, int slot, byte[] val);
nScriptSetVarV(long id, int slot, byte[] val)818     synchronized void nScriptSetVarV(long id, int slot, byte[] val) {
819         validate();
820         rsnScriptSetVarV(mContext, id, slot, val);
821     }
rsnScriptGetVarV(long con, long id, int slot, byte[] val)822     native void rsnScriptGetVarV(long con, long id, int slot, byte[] val);
nScriptGetVarV(long id, int slot, byte[] val)823     synchronized void nScriptGetVarV(long id, int slot, byte[] val) {
824         validate();
825         rsnScriptGetVarV(mContext, id, slot, val);
826     }
rsnScriptSetVarVE(long con, long id, int slot, byte[] val, long e, int[] dims)827     native void rsnScriptSetVarVE(long con, long id, int slot, byte[] val,
828                                   long e, int[] dims);
nScriptSetVarVE(long id, int slot, byte[] val, long e, int[] dims)829     synchronized void nScriptSetVarVE(long id, int slot, byte[] val,
830                                       long e, int[] dims) {
831         validate();
832         rsnScriptSetVarVE(mContext, id, slot, val, e, dims);
833     }
rsnScriptSetVarObj(long con, long id, int slot, long val)834     native void rsnScriptSetVarObj(long con, long id, int slot, long val);
nScriptSetVarObj(long id, int slot, long val)835     synchronized void nScriptSetVarObj(long id, int slot, long val) {
836         validate();
837         rsnScriptSetVarObj(mContext, id, slot, val);
838     }
839 
rsnScriptCCreate(long con, String resName, String cacheDir, byte[] script, int length)840     native long rsnScriptCCreate(long con, String resName, String cacheDir,
841                                  byte[] script, int length);
842     @UnsupportedAppUsage
nScriptCCreate(String resName, String cacheDir, byte[] script, int length)843     synchronized long nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
844         validate();
845         return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
846     }
847 
rsnScriptIntrinsicCreate(long con, int id, long eid)848     native long rsnScriptIntrinsicCreate(long con, int id, long eid);
nScriptIntrinsicCreate(int id, long eid)849     synchronized long nScriptIntrinsicCreate(int id, long eid) {
850         validate();
851         return rsnScriptIntrinsicCreate(mContext, id, eid);
852     }
853 
rsnScriptKernelIDCreate(long con, long sid, int slot, int sig)854     native long  rsnScriptKernelIDCreate(long con, long sid, int slot, int sig);
nScriptKernelIDCreate(long sid, int slot, int sig)855     synchronized long nScriptKernelIDCreate(long sid, int slot, int sig) {
856         validate();
857         return rsnScriptKernelIDCreate(mContext, sid, slot, sig);
858     }
859 
rsnScriptInvokeIDCreate(long con, long sid, int slot)860     native long  rsnScriptInvokeIDCreate(long con, long sid, int slot);
nScriptInvokeIDCreate(long sid, int slot)861     synchronized long nScriptInvokeIDCreate(long sid, int slot) {
862         validate();
863         return rsnScriptInvokeIDCreate(mContext, sid, slot);
864     }
865 
rsnScriptFieldIDCreate(long con, long sid, int slot)866     native long  rsnScriptFieldIDCreate(long con, long sid, int slot);
nScriptFieldIDCreate(long sid, int slot)867     synchronized long nScriptFieldIDCreate(long sid, int slot) {
868         validate();
869         return rsnScriptFieldIDCreate(mContext, sid, slot);
870     }
871 
rsnScriptGroupCreate(long con, long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types)872     native long rsnScriptGroupCreate(long con, long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types);
nScriptGroupCreate(long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types)873     synchronized long nScriptGroupCreate(long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types) {
874         validate();
875         return rsnScriptGroupCreate(mContext, kernels, src, dstk, dstf, types);
876     }
877 
rsnScriptGroupSetInput(long con, long group, long kernel, long alloc)878     native void rsnScriptGroupSetInput(long con, long group, long kernel, long alloc);
nScriptGroupSetInput(long group, long kernel, long alloc)879     synchronized void nScriptGroupSetInput(long group, long kernel, long alloc) {
880         validate();
881         rsnScriptGroupSetInput(mContext, group, kernel, alloc);
882     }
883 
rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc)884     native void rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc);
nScriptGroupSetOutput(long group, long kernel, long alloc)885     synchronized void nScriptGroupSetOutput(long group, long kernel, long alloc) {
886         validate();
887         rsnScriptGroupSetOutput(mContext, group, kernel, alloc);
888     }
889 
rsnScriptGroupExecute(long con, long group)890     native void rsnScriptGroupExecute(long con, long group);
nScriptGroupExecute(long group)891     synchronized void nScriptGroupExecute(long group) {
892         validate();
893         rsnScriptGroupExecute(mContext, group);
894     }
895 
rsnSamplerCreate(long con, int magFilter, int minFilter, int wrapS, int wrapT, int wrapR, float aniso)896     native long  rsnSamplerCreate(long con, int magFilter, int minFilter,
897                                  int wrapS, int wrapT, int wrapR, float aniso);
nSamplerCreate(int magFilter, int minFilter, int wrapS, int wrapT, int wrapR, float aniso)898     synchronized long nSamplerCreate(int magFilter, int minFilter,
899                                  int wrapS, int wrapT, int wrapR, float aniso) {
900         validate();
901         return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
902     }
903 
rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a, boolean depthMask, boolean dither, int srcMode, int dstMode, int depthFunc)904     native long rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a,
905                                       boolean depthMask, boolean dither,
906                                       int srcMode, int dstMode, int depthFunc);
nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a, boolean depthMask, boolean dither, int srcMode, int dstMode, int depthFunc)907     synchronized long nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
908                                          boolean depthMask, boolean dither,
909                                          int srcMode, int dstMode, int depthFunc) {
910         validate();
911         return rsnProgramStoreCreate(mContext, r, g, b, a, depthMask, dither, srcMode,
912                                      dstMode, depthFunc);
913     }
914 
rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode)915     native long rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode);
nProgramRasterCreate(boolean pointSprite, int cullMode)916     synchronized long nProgramRasterCreate(boolean pointSprite, int cullMode) {
917         validate();
918         return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
919     }
920 
rsnProgramBindConstants(long con, long pv, int slot, long mID)921     native void rsnProgramBindConstants(long con, long pv, int slot, long mID);
nProgramBindConstants(long pv, int slot, long mID)922     synchronized void nProgramBindConstants(long pv, int slot, long mID) {
923         validate();
924         rsnProgramBindConstants(mContext, pv, slot, mID);
925     }
rsnProgramBindTexture(long con, long vpf, int slot, long a)926     native void rsnProgramBindTexture(long con, long vpf, int slot, long a);
nProgramBindTexture(long vpf, int slot, long a)927     synchronized void nProgramBindTexture(long vpf, int slot, long a) {
928         validate();
929         rsnProgramBindTexture(mContext, vpf, slot, a);
930     }
rsnProgramBindSampler(long con, long vpf, int slot, long s)931     native void rsnProgramBindSampler(long con, long vpf, int slot, long s);
nProgramBindSampler(long vpf, int slot, long s)932     synchronized void nProgramBindSampler(long vpf, int slot, long s) {
933         validate();
934         rsnProgramBindSampler(mContext, vpf, slot, s);
935     }
rsnProgramFragmentCreate(long con, String shader, String[] texNames, long[] params)936     native long rsnProgramFragmentCreate(long con, String shader, String[] texNames, long[] params);
nProgramFragmentCreate(String shader, String[] texNames, long[] params)937     synchronized long nProgramFragmentCreate(String shader, String[] texNames, long[] params) {
938         validate();
939         return rsnProgramFragmentCreate(mContext, shader, texNames, params);
940     }
rsnProgramVertexCreate(long con, String shader, String[] texNames, long[] params)941     native long rsnProgramVertexCreate(long con, String shader, String[] texNames, long[] params);
nProgramVertexCreate(String shader, String[] texNames, long[] params)942     synchronized long nProgramVertexCreate(String shader, String[] texNames, long[] params) {
943         validate();
944         return rsnProgramVertexCreate(mContext, shader, texNames, params);
945     }
946 
rsnMeshCreate(long con, long[] vtx, long[] idx, int[] prim)947     native long rsnMeshCreate(long con, long[] vtx, long[] idx, int[] prim);
nMeshCreate(long[] vtx, long[] idx, int[] prim)948     synchronized long nMeshCreate(long[] vtx, long[] idx, int[] prim) {
949         validate();
950         return rsnMeshCreate(mContext, vtx, idx, prim);
951     }
rsnMeshGetVertexBufferCount(long con, long id)952     native int  rsnMeshGetVertexBufferCount(long con, long id);
nMeshGetVertexBufferCount(long id)953     synchronized int nMeshGetVertexBufferCount(long id) {
954         validate();
955         return rsnMeshGetVertexBufferCount(mContext, id);
956     }
rsnMeshGetIndexCount(long con, long id)957     native int  rsnMeshGetIndexCount(long con, long id);
nMeshGetIndexCount(long id)958     synchronized int nMeshGetIndexCount(long id) {
959         validate();
960         return rsnMeshGetIndexCount(mContext, id);
961     }
rsnMeshGetVertices(long con, long id, long[] vtxIds, int vtxIdCount)962     native void rsnMeshGetVertices(long con, long id, long[] vtxIds, int vtxIdCount);
nMeshGetVertices(long id, long[] vtxIds, int vtxIdCount)963     synchronized void nMeshGetVertices(long id, long[] vtxIds, int vtxIdCount) {
964         validate();
965         rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
966     }
rsnMeshGetIndices(long con, long id, long[] idxIds, int[] primitives, int vtxIdCount)967     native void rsnMeshGetIndices(long con, long id, long[] idxIds, int[] primitives, int vtxIdCount);
nMeshGetIndices(long id, long[] idxIds, int[] primitives, int vtxIdCount)968     synchronized void nMeshGetIndices(long id, long[] idxIds, int[] primitives, int vtxIdCount) {
969         validate();
970         rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
971     }
972 
rsnScriptIntrinsicBLAS_Single(long con, long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, float alpha, long A, long B, float beta, long C, int incX, int incY, int KL, int KU)973     native void rsnScriptIntrinsicBLAS_Single(long con, long id, int func, int TransA,
974                                               int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
975                                               float alpha, long A, long B, float beta, long C, int incX, int incY,
976                                               int KL, int KU);
nScriptIntrinsicBLAS_Single(long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, float alpha, long A, long B, float beta, long C, int incX, int incY, int KL, int KU)977     synchronized void nScriptIntrinsicBLAS_Single(long id, int func, int TransA,
978                                                   int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
979                                                   float alpha, long A, long B, float beta, long C, int incX, int incY,
980                                                   int KL, int KU) {
981         validate();
982         rsnScriptIntrinsicBLAS_Single(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
983     }
984 
rsnScriptIntrinsicBLAS_Double(long con, long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, double alpha, long A, long B, double beta, long C, int incX, int incY, int KL, int KU)985     native void rsnScriptIntrinsicBLAS_Double(long con, long id, int func, int TransA,
986                                               int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
987                                               double alpha, long A, long B, double beta, long C, int incX, int incY,
988                                               int KL, int KU);
nScriptIntrinsicBLAS_Double(long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, double alpha, long A, long B, double beta, long C, int incX, int incY, int KL, int KU)989     synchronized void nScriptIntrinsicBLAS_Double(long id, int func, int TransA,
990                                                   int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
991                                                   double alpha, long A, long B, double beta, long C, int incX, int incY,
992                                                   int KL, int KU) {
993         validate();
994         rsnScriptIntrinsicBLAS_Double(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
995     }
996 
rsnScriptIntrinsicBLAS_Complex(long con, long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY, int KL, int KU)997     native void rsnScriptIntrinsicBLAS_Complex(long con, long id, int func, int TransA,
998                                                int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
999                                                float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
1000                                                int KL, int KU);
nScriptIntrinsicBLAS_Complex(long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY, int KL, int KU)1001     synchronized void nScriptIntrinsicBLAS_Complex(long id, int func, int TransA,
1002                                                    int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
1003                                                    float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
1004                                                    int KL, int KU) {
1005         validate();
1006         rsnScriptIntrinsicBLAS_Complex(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
1007     }
1008 
rsnScriptIntrinsicBLAS_Z(long con, long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY, int KL, int KU)1009     native void rsnScriptIntrinsicBLAS_Z(long con, long id, int func, int TransA,
1010                                          int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
1011                                          double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
1012                                          int KL, int KU);
nScriptIntrinsicBLAS_Z(long id, int func, int TransA, int TransB, int Side, int Uplo, int Diag, int M, int N, int K, double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY, int KL, int KU)1013     synchronized void nScriptIntrinsicBLAS_Z(long id, int func, int TransA,
1014                                              int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
1015                                              double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
1016                                              int KL, int KU) {
1017         validate();
1018         rsnScriptIntrinsicBLAS_Z(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
1019     }
1020 
rsnScriptIntrinsicBLAS_BNNM(long con, long id, int M, int N, int K, long A, int a_offset, long B, int b_offset, long C, int c_offset, int c_mult_int)1021     native void rsnScriptIntrinsicBLAS_BNNM(long con, long id, int M, int N, int K,
1022                                              long A, int a_offset, long B, int b_offset, long C, int c_offset,
1023                                              int c_mult_int);
nScriptIntrinsicBLAS_BNNM(long id, int M, int N, int K, long A, int a_offset, long B, int b_offset, long C, int c_offset, int c_mult_int)1024     synchronized void nScriptIntrinsicBLAS_BNNM(long id, int M, int N, int K,
1025                                              long A, int a_offset, long B, int b_offset, long C, int c_offset,
1026                                              int c_mult_int) {
1027         validate();
1028         rsnScriptIntrinsicBLAS_BNNM(mContext, id, M, N, K, A, a_offset, B, b_offset, C, c_offset, c_mult_int);
1029     }
1030 
1031 
1032 
1033     long     mContext;
1034     private boolean mDestroyed = false;
1035 
1036     @SuppressWarnings({"FieldCanBeLocal"})
1037     MessageThread mMessageThread;
1038 
1039     volatile Element mElement_U8;
1040     volatile Element mElement_I8;
1041     volatile Element mElement_U16;
1042     volatile Element mElement_I16;
1043     volatile Element mElement_U32;
1044     volatile Element mElement_I32;
1045     volatile Element mElement_U64;
1046     volatile Element mElement_I64;
1047     volatile Element mElement_F16;
1048     volatile Element mElement_F32;
1049     volatile Element mElement_F64;
1050     volatile Element mElement_BOOLEAN;
1051 
1052     volatile Element mElement_ELEMENT;
1053     volatile Element mElement_TYPE;
1054     volatile Element mElement_ALLOCATION;
1055     volatile Element mElement_SAMPLER;
1056     volatile Element mElement_SCRIPT;
1057     volatile Element mElement_MESH;
1058     volatile Element mElement_PROGRAM_FRAGMENT;
1059     volatile Element mElement_PROGRAM_VERTEX;
1060     volatile Element mElement_PROGRAM_RASTER;
1061     volatile Element mElement_PROGRAM_STORE;
1062     volatile Element mElement_FONT;
1063 
1064     volatile Element mElement_A_8;
1065     volatile Element mElement_RGB_565;
1066     volatile Element mElement_RGB_888;
1067     volatile Element mElement_RGBA_5551;
1068     volatile Element mElement_RGBA_4444;
1069     volatile Element mElement_RGBA_8888;
1070 
1071     volatile Element mElement_HALF_2;
1072     volatile Element mElement_HALF_3;
1073     volatile Element mElement_HALF_4;
1074 
1075     volatile Element mElement_FLOAT_2;
1076     volatile Element mElement_FLOAT_3;
1077     volatile Element mElement_FLOAT_4;
1078 
1079     volatile Element mElement_DOUBLE_2;
1080     volatile Element mElement_DOUBLE_3;
1081     volatile Element mElement_DOUBLE_4;
1082 
1083     volatile Element mElement_UCHAR_2;
1084     volatile Element mElement_UCHAR_3;
1085     volatile Element mElement_UCHAR_4;
1086 
1087     volatile Element mElement_CHAR_2;
1088     volatile Element mElement_CHAR_3;
1089     volatile Element mElement_CHAR_4;
1090 
1091     volatile Element mElement_USHORT_2;
1092     volatile Element mElement_USHORT_3;
1093     volatile Element mElement_USHORT_4;
1094 
1095     volatile Element mElement_SHORT_2;
1096     volatile Element mElement_SHORT_3;
1097     volatile Element mElement_SHORT_4;
1098 
1099     volatile Element mElement_UINT_2;
1100     volatile Element mElement_UINT_3;
1101     volatile Element mElement_UINT_4;
1102 
1103     volatile Element mElement_INT_2;
1104     volatile Element mElement_INT_3;
1105     volatile Element mElement_INT_4;
1106 
1107     volatile Element mElement_ULONG_2;
1108     volatile Element mElement_ULONG_3;
1109     volatile Element mElement_ULONG_4;
1110 
1111     volatile Element mElement_LONG_2;
1112     volatile Element mElement_LONG_3;
1113     volatile Element mElement_LONG_4;
1114 
1115     volatile Element mElement_YUV;
1116 
1117     volatile Element mElement_MATRIX_4X4;
1118     volatile Element mElement_MATRIX_3X3;
1119     volatile Element mElement_MATRIX_2X2;
1120 
1121     volatile Sampler mSampler_CLAMP_NEAREST;
1122     volatile Sampler mSampler_CLAMP_LINEAR;
1123     volatile Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
1124     volatile Sampler mSampler_WRAP_NEAREST;
1125     volatile Sampler mSampler_WRAP_LINEAR;
1126     volatile Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
1127     volatile Sampler mSampler_MIRRORED_REPEAT_NEAREST;
1128     volatile Sampler mSampler_MIRRORED_REPEAT_LINEAR;
1129     volatile Sampler mSampler_MIRRORED_REPEAT_LINEAR_MIP_LINEAR;
1130 
1131     ProgramStore mProgramStore_BLEND_NONE_DEPTH_TEST;
1132     ProgramStore mProgramStore_BLEND_NONE_DEPTH_NO_DEPTH;
1133     ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_TEST;
1134     ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_NO_DEPTH;
1135 
1136     ProgramRaster mProgramRaster_CULL_BACK;
1137     ProgramRaster mProgramRaster_CULL_FRONT;
1138     ProgramRaster mProgramRaster_CULL_NONE;
1139 
1140     ///////////////////////////////////////////////////////////////////////////////////
1141     //
1142 
1143     /**
1144      * The base class from which an application should derive in order
1145      * to receive RS messages from scripts. When a script calls {@code
1146      * rsSendToClient}, the data fields will be filled, and the run
1147      * method will be called on a separate thread.  This will occur
1148      * some time after {@code rsSendToClient} completes in the script,
1149      * as {@code rsSendToClient} is asynchronous. Message handlers are
1150      * not guaranteed to have completed when {@link
1151      * android.renderscript.RenderScript#finish} returns.
1152      *
1153      */
1154     public static class RSMessageHandler implements Runnable {
1155         protected int[] mData;
1156         protected int mID;
1157         protected int mLength;
run()1158         public void run() {
1159         }
1160     }
1161     /**
1162      * If an application is expecting messages, it should set this
1163      * field to an instance of {@link RSMessageHandler}.  This
1164      * instance will receive all the user messages sent from {@code
1165      * sendToClient} by scripts from this context.
1166      *
1167      */
1168     @UnsupportedAppUsage
1169     RSMessageHandler mMessageCallback = null;
1170 
setMessageHandler(RSMessageHandler msg)1171     public void setMessageHandler(RSMessageHandler msg) {
1172         mMessageCallback = msg;
1173     }
getMessageHandler()1174     public RSMessageHandler getMessageHandler() {
1175         return mMessageCallback;
1176     }
1177 
1178     /**
1179      * Place a message into the message queue to be sent back to the message
1180      * handler once all previous commands have been executed.
1181      *
1182      * @param id
1183      * @param data
1184      */
sendMessage(int id, int[] data)1185     public void sendMessage(int id, int[] data) {
1186         nContextSendMessage(id, data);
1187     }
1188 
1189     /**
1190      * The runtime error handler base class.  An application should derive from this class
1191      * if it wishes to install an error handler.  When errors occur at runtime,
1192      * the fields in this class will be filled, and the run method will be called.
1193      *
1194      */
1195     public static class RSErrorHandler implements Runnable {
1196         protected String mErrorMessage;
1197         protected int mErrorNum;
run()1198         public void run() {
1199         }
1200     }
1201 
1202     /**
1203      * Application Error handler.  All runtime errors will be dispatched to the
1204      * instance of RSAsyncError set here.  If this field is null a
1205      * {@link RSRuntimeException} will instead be thrown with details about the error.
1206      * This will cause program termaination.
1207      *
1208      */
1209     RSErrorHandler mErrorCallback = null;
1210 
setErrorHandler(RSErrorHandler msg)1211     public void setErrorHandler(RSErrorHandler msg) {
1212         mErrorCallback = msg;
1213     }
getErrorHandler()1214     public RSErrorHandler getErrorHandler() {
1215         return mErrorCallback;
1216     }
1217 
1218     /**
1219      * RenderScript worker thread priority enumeration.  The default value is
1220      * NORMAL.  Applications wishing to do background processing should set
1221      * their priority to LOW to avoid starving forground processes.
1222      */
1223     public enum Priority {
1224         // These values used to represent official thread priority values
1225         // now they are simply enums to be used by the runtime side
1226         LOW (15),
1227         NORMAL (-8);
1228 
1229         int mID;
Priority(int id)1230         Priority(int id) {
1231             mID = id;
1232         }
1233     }
1234 
validateObject(BaseObj o)1235     void validateObject(BaseObj o) {
1236         if (o != null) {
1237             if (o.mRS != this) {
1238                 throw new RSIllegalArgumentException("Attempting to use an object across contexts.");
1239             }
1240         }
1241     }
1242 
1243     @UnsupportedAppUsage
validate()1244     void validate() {
1245         if (mContext == 0) {
1246             throw new RSInvalidStateException("Calling RS with no Context active.");
1247         }
1248     }
1249 
1250 
1251     /**
1252      * Change the priority of the worker threads for this context.
1253      *
1254      * @param p New priority to be set.
1255      */
setPriority(Priority p)1256     public void setPriority(Priority p) {
1257         validate();
1258         nContextSetPriority(p.mID);
1259     }
1260 
1261     static class MessageThread extends Thread {
1262         RenderScript mRS;
1263         boolean mRun = true;
1264         int[] mAuxData = new int[2];
1265 
1266         static final int RS_MESSAGE_TO_CLIENT_NONE = 0;
1267         static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1;
1268         static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2;
1269         static final int RS_MESSAGE_TO_CLIENT_ERROR = 3;
1270         static final int RS_MESSAGE_TO_CLIENT_USER = 4;
1271         static final int RS_MESSAGE_TO_CLIENT_NEW_BUFFER = 5;
1272 
1273         static final int RS_ERROR_FATAL_DEBUG = 0x0800;
1274         static final int RS_ERROR_FATAL_UNKNOWN = 0x1000;
1275 
MessageThread(RenderScript rs)1276         MessageThread(RenderScript rs) {
1277             super("RSMessageThread");
1278             mRS = rs;
1279 
1280         }
1281 
run()1282         public void run() {
1283             // This function is a temporary solution.  The final solution will
1284             // used typed allocations where the message id is the type indicator.
1285             int[] rbuf = new int[16];
1286             mRS.nContextInitToClient(mRS.mContext);
1287             while(mRun) {
1288                 rbuf[0] = 0;
1289                 int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData);
1290                 int size = mAuxData[1];
1291                 int subID = mAuxData[0];
1292 
1293                 if (msg == RS_MESSAGE_TO_CLIENT_USER) {
1294                     if ((size>>2) >= rbuf.length) {
1295                         rbuf = new int[(size + 3) >> 2];
1296                     }
1297                     if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1298                         RS_MESSAGE_TO_CLIENT_USER) {
1299                         throw new RSDriverException("Error processing message from RenderScript.");
1300                     }
1301 
1302                     if(mRS.mMessageCallback != null) {
1303                         mRS.mMessageCallback.mData = rbuf;
1304                         mRS.mMessageCallback.mID = subID;
1305                         mRS.mMessageCallback.mLength = size;
1306                         mRS.mMessageCallback.run();
1307                     } else {
1308                         throw new RSInvalidStateException("Received a message from the script with no message handler installed.");
1309                     }
1310                     continue;
1311                 }
1312 
1313                 if (msg == RS_MESSAGE_TO_CLIENT_ERROR) {
1314                     String e = mRS.nContextGetErrorMessage(mRS.mContext);
1315 
1316                     // Throw RSRuntimeException under the following conditions:
1317                     //
1318                     // 1) It is an unknown fatal error.
1319                     // 2) It is a debug fatal error, and we are not in a
1320                     //    debug context.
1321                     // 3) It is a debug fatal error, and we do not have an
1322                     //    error callback.
1323                     if (subID >= RS_ERROR_FATAL_UNKNOWN ||
1324                         (subID >= RS_ERROR_FATAL_DEBUG &&
1325                          (mRS.mContextType != ContextType.DEBUG ||
1326                           mRS.mErrorCallback == null))) {
1327                         throw new RSRuntimeException("Fatal error " + subID + ", details: " + e);
1328                     }
1329 
1330                     if(mRS.mErrorCallback != null) {
1331                         mRS.mErrorCallback.mErrorMessage = e;
1332                         mRS.mErrorCallback.mErrorNum = subID;
1333                         mRS.mErrorCallback.run();
1334                     } else {
1335                         android.util.Log.e(LOG_TAG, "non fatal RS error, " + e);
1336                         // Do not throw here. In these cases, we do not have
1337                         // a fatal error.
1338                     }
1339                     continue;
1340                 }
1341 
1342                 if (msg == RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1343                     if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1344                         RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1345                         throw new RSDriverException("Error processing message from RenderScript.");
1346                     }
1347                     long bufferID = ((long)rbuf[1] << 32L) + ((long)rbuf[0] & 0xffffffffL);
1348                     Allocation.sendBufferNotification(bufferID);
1349                     continue;
1350                 }
1351 
1352                 // 2: teardown.
1353                 // But we want to avoid starving other threads during
1354                 // teardown by yielding until the next line in the destructor
1355                 // can execute to set mRun = false
1356                 try {
1357                     sleep(1, 0);
1358                 } catch(InterruptedException e) {
1359                 }
1360             }
1361             //Log.d(LOG_TAG, "MessageThread exiting.");
1362         }
1363     }
1364 
RenderScript(Context ctx)1365     RenderScript(Context ctx) {
1366         mContextType = ContextType.NORMAL;
1367         if (ctx != null) {
1368             mApplicationContext = ctx.getApplicationContext();
1369         }
1370         mRWLock = new ReentrantReadWriteLock();
1371     }
1372 
1373     /**
1374      * Gets the application context associated with the RenderScript context.
1375      *
1376      * @return The application context.
1377      */
getApplicationContext()1378     public final Context getApplicationContext() {
1379         return mApplicationContext;
1380     }
1381 
1382     /**
1383      * Name of the file that holds the object cache.
1384      */
1385     private static String mCachePath;
1386 
1387     /**
1388      * Gets the path to the code cache.
1389      */
getCachePath()1390     static synchronized String getCachePath() {
1391         if (mCachePath == null) {
1392             final String CACHE_PATH = "com.android.renderscript.cache";
1393             if (RenderScriptCacheDir.mCacheDir == null) {
1394                 throw new RSRuntimeException("RenderScript code cache directory uninitialized.");
1395             }
1396             File f = new File(RenderScriptCacheDir.mCacheDir, CACHE_PATH);
1397             mCachePath = f.getAbsolutePath();
1398             f.mkdirs();
1399         }
1400         return mCachePath;
1401     }
1402 
1403     /**
1404      * Create a RenderScript context.
1405      *
1406      * @param ctx The context.
1407      * @return RenderScript
1408      */
internalCreate(Context ctx, int sdkVersion, ContextType ct, int flags)1409     private static RenderScript internalCreate(Context ctx, int sdkVersion, ContextType ct, int flags) {
1410         if (!sInitialized) {
1411             Log.e(LOG_TAG, "RenderScript.create() called when disabled; someone is likely to crash");
1412             return null;
1413         }
1414 
1415         if ((flags & ~(CREATE_FLAG_LOW_LATENCY | CREATE_FLAG_LOW_POWER |
1416                        CREATE_FLAG_WAIT_FOR_ATTACH)) != 0) {
1417             throw new RSIllegalArgumentException("Invalid flags passed.");
1418         }
1419 
1420         RenderScript rs = new RenderScript(ctx);
1421 
1422         long device = rs.nDeviceCreate();
1423         rs.mContext = rs.nContextCreate(device, flags, sdkVersion, ct.mID);
1424         rs.mContextType = ct;
1425         rs.mContextFlags = flags;
1426         rs.mContextSdkVersion = sdkVersion;
1427         if (rs.mContext == 0) {
1428             throw new RSDriverException("Failed to create RS context.");
1429         }
1430 
1431         // set up cache directory for entire context
1432         rs.nContextSetCacheDir(RenderScript.getCachePath());
1433 
1434         rs.mMessageThread = new MessageThread(rs);
1435         rs.mMessageThread.start();
1436         return rs;
1437     }
1438 
1439     /**
1440      * calls create(ctx, ContextType.NORMAL, CREATE_FLAG_NONE)
1441      *
1442      * See documentation for @create for details
1443      *
1444      * @param ctx The context.
1445      * @return RenderScript
1446      */
create(Context ctx)1447     public static RenderScript create(Context ctx) {
1448         return create(ctx, ContextType.NORMAL);
1449     }
1450 
1451     /**
1452      * calls create(ctx, ct, CREATE_FLAG_NONE)
1453      *
1454      * See documentation for @create for details
1455      *
1456      * @param ctx The context.
1457      * @param ct The type of context to be created.
1458      * @return RenderScript
1459      */
create(Context ctx, ContextType ct)1460     public static RenderScript create(Context ctx, ContextType ct) {
1461         return create(ctx, ct, CREATE_FLAG_NONE);
1462     }
1463 
1464 
1465     /**
1466      * Gets or creates a RenderScript context of the specified type.
1467      *
1468      * The returned context will be cached for future reuse within
1469      * the process. When an application is finished using
1470      * RenderScript it should call releaseAllContexts()
1471      *
1472      * A process context is a context designed for easy creation and
1473      * lifecycle management.  Multiple calls to this function will
1474      * return the same object provided they are called with the same
1475      * options.  This allows it to be used any time a RenderScript
1476      * context is needed.
1477      *
1478      * Prior to API 23 this always created a new context.
1479      *
1480      * @param ctx The context.
1481      * @param ct The type of context to be created.
1482      * @param flags The OR of the CREATE_FLAG_* options desired
1483      * @return RenderScript
1484      */
create(Context ctx, ContextType ct, int flags)1485     public static RenderScript create(Context ctx, ContextType ct, int flags) {
1486         int v = ctx.getApplicationInfo().targetSdkVersion;
1487         return create(ctx, v, ct, flags);
1488     }
1489 
1490     /**
1491      * calls create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE)
1492      *
1493      * Used by the RenderScriptThunker to maintain backward compatibility.
1494      *
1495      * @hide
1496      * @param ctx The context.
1497      * @param sdkVersion The target SDK Version.
1498      * @return RenderScript
1499      */
1500     @UnsupportedAppUsage
create(Context ctx, int sdkVersion)1501     public static RenderScript create(Context ctx, int sdkVersion) {
1502         return create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE);
1503     }
1504 
1505      /**
1506      * Gets or creates a RenderScript context of the specified type.
1507      *
1508      * @param ctx The context.
1509      * @param ct The type of context to be created.
1510      * @param sdkVersion The target SDK Version.
1511      * @param flags The OR of the CREATE_FLAG_* options desired
1512      * @return RenderScript
1513      */
1514     @UnsupportedAppUsage
create(Context ctx, int sdkVersion, ContextType ct, int flags)1515     private static RenderScript create(Context ctx, int sdkVersion, ContextType ct, int flags) {
1516         if (sdkVersion < 23) {
1517             return internalCreate(ctx, sdkVersion, ct, flags);
1518         }
1519 
1520         synchronized (mProcessContextList) {
1521             for (RenderScript prs : mProcessContextList) {
1522                 if ((prs.mContextType == ct) &&
1523                     (prs.mContextFlags == flags) &&
1524                     (prs.mContextSdkVersion == sdkVersion)) {
1525 
1526                     return prs;
1527                 }
1528             }
1529 
1530             RenderScript prs = internalCreate(ctx, sdkVersion, ct, flags);
1531             prs.mIsProcessContext = true;
1532             mProcessContextList.add(prs);
1533             return prs;
1534         }
1535     }
1536 
1537     /**
1538      * Releases all the process contexts.  This is the same as
1539      * calling .destroy() on each unique context retreived with
1540      * create(...). If no contexts have been created this
1541      * function does nothing.
1542      *
1543      * Typically you call this when your application is losing focus
1544      * and will not be using a context for some time.
1545      *
1546      * This has no effect on a context created with
1547      * createMultiContext()
1548      */
releaseAllContexts()1549     public static void releaseAllContexts() {
1550         ArrayList<RenderScript> oldList;
1551         synchronized (mProcessContextList) {
1552             oldList = mProcessContextList;
1553             mProcessContextList = new ArrayList<RenderScript>();
1554         }
1555 
1556         for (RenderScript prs : oldList) {
1557             prs.mIsProcessContext = false;
1558             prs.destroy();
1559         }
1560         oldList.clear();
1561     }
1562 
1563 
1564 
1565     /**
1566      * Create a RenderScript context.
1567      *
1568      * This is an advanced function intended for applications which
1569      * need to create more than one RenderScript context to be used
1570      * at the same time.
1571      *
1572      * If you need a single context please use create()
1573      *
1574      * @param ctx The context.
1575      * @return RenderScript
1576      */
createMultiContext(Context ctx, ContextType ct, int flags, int API_number)1577     public static RenderScript createMultiContext(Context ctx, ContextType ct, int flags, int API_number) {
1578         return internalCreate(ctx, API_number, ct, flags);
1579     }
1580 
1581 
1582     /**
1583      * Print the currently available debugging information about the state of
1584      * the RS context to the log.
1585      *
1586      */
contextDump()1587     public void contextDump() {
1588         validate();
1589         nContextDump(0);
1590     }
1591 
1592     /**
1593      * Wait for any pending asynchronous opeations (such as copies to a RS
1594      * allocation or RS script executions) to complete.
1595      *
1596      */
finish()1597     public void finish() {
1598         nContextFinish();
1599     }
1600 
helpDestroy()1601     private void helpDestroy() {
1602         boolean shouldDestroy = false;
1603         synchronized(this) {
1604             if (!mDestroyed) {
1605                 shouldDestroy = true;
1606                 mDestroyed = true;
1607             }
1608         }
1609 
1610         if (shouldDestroy) {
1611             nContextFinish();
1612 
1613             nContextDeinitToClient(mContext);
1614             mMessageThread.mRun = false;
1615             // Interrupt mMessageThread so it gets to see immediately that mRun is false
1616             // and exit rightaway.
1617             mMessageThread.interrupt();
1618 
1619             // Wait for mMessageThread to join.  Try in a loop, in case this thread gets interrupted
1620             // during the wait.  If interrupted, set the "interrupted" status of the current thread.
1621             boolean hasJoined = false, interrupted = false;
1622             while (!hasJoined) {
1623                 try {
1624                     mMessageThread.join();
1625                     hasJoined = true;
1626                 } catch (InterruptedException e) {
1627                     interrupted = true;
1628                 }
1629             }
1630             if (interrupted) {
1631                 Log.v(LOG_TAG, "Interrupted during wait for MessageThread to join");
1632                 Thread.currentThread().interrupt();
1633             }
1634 
1635             nContextDestroy();
1636         }
1637     }
1638 
finalize()1639     protected void finalize() throws Throwable {
1640         helpDestroy();
1641         super.finalize();
1642     }
1643 
1644 
1645     /**
1646      * Destroys this RenderScript context.  Once this function is called,
1647      * using this context or any objects belonging to this context is
1648      * illegal.
1649      *
1650      * API 23+, this function is a NOP if the context was created
1651      * with create().  Please use releaseAllContexts() to clean up
1652      * contexts created with the create function.
1653      *
1654      */
destroy()1655     public void destroy() {
1656         if (mIsProcessContext) {
1657             // users cannot destroy a process context
1658             return;
1659         }
1660         validate();
1661         helpDestroy();
1662     }
1663 
isAlive()1664     boolean isAlive() {
1665         return mContext != 0;
1666     }
1667 
safeID(BaseObj o)1668     long safeID(BaseObj o) {
1669         if(o != null) {
1670             return o.getID(this);
1671         }
1672         return 0;
1673     }
1674 }
1675