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