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     }
450 
rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage)451     native long rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp,
452                 int usage);
nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage)453     synchronized long nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
454         validate();
455         return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
456     }
457 
rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp, int usage)458     native long rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp,
459                 int usage);
nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp, int usage)460     synchronized long nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp,
461                 int usage) {
462         validate();
463         return rsnAllocationCreateBitmapBackedAllocation(mContext, type, mip, bmp, usage);
464     }
465 
rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage)466     native long rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp,
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, usage);
471     }
472 
rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp)473     native void  rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp);
nAllocationCopyToBitmap(long alloc, Bitmap bmp)474     synchronized void nAllocationCopyToBitmap(long alloc, Bitmap bmp) {
475         validate();
476         rsnAllocationCopyToBitmap(mContext, alloc, bmp);
477     }
478 
rsnAllocationSyncAll(long con, long alloc, int src)479     native void rsnAllocationSyncAll(long con, long alloc, int src);
nAllocationSyncAll(long alloc, int src)480     synchronized void nAllocationSyncAll(long alloc, int src) {
481         validate();
482         rsnAllocationSyncAll(mContext, alloc, src);
483     }
484 
rsnAllocationGetByteBuffer(long con, long alloc, long[] stride, int xBytesSize, int dimY, int dimZ)485     native ByteBuffer rsnAllocationGetByteBuffer(long con, long alloc, long[] stride,
486                 int xBytesSize, int dimY, int dimZ);
nAllocationGetByteBuffer(long alloc, long[] stride, int xBytesSize, int dimY, int dimZ)487     synchronized ByteBuffer nAllocationGetByteBuffer(long alloc, long[] stride, int xBytesSize,
488                 int dimY, int dimZ) {
489         validate();
490         return rsnAllocationGetByteBuffer(mContext, alloc, stride, xBytesSize, dimY, dimZ);
491     }
492 
rsnAllocationSetupBufferQueue(long con, long alloc, int numAlloc)493     native void rsnAllocationSetupBufferQueue(long con, long alloc, int numAlloc);
nAllocationSetupBufferQueue(long alloc, int numAlloc)494     synchronized void nAllocationSetupBufferQueue(long alloc, int numAlloc) {
495         validate();
496         rsnAllocationSetupBufferQueue(mContext, alloc, numAlloc);
497     }
rsnAllocationShareBufferQueue(long con, long alloc1, long alloc2)498     native void rsnAllocationShareBufferQueue(long con, long alloc1, long alloc2);
nAllocationShareBufferQueue(long alloc1, long alloc2)499     synchronized void nAllocationShareBufferQueue(long alloc1, long alloc2) {
500         validate();
501         rsnAllocationShareBufferQueue(mContext, alloc1, alloc2);
502     }
rsnAllocationGetSurface(long con, long alloc)503     native Surface rsnAllocationGetSurface(long con, long alloc);
nAllocationGetSurface(long alloc)504     synchronized Surface nAllocationGetSurface(long alloc) {
505         validate();
506         return rsnAllocationGetSurface(mContext, alloc);
507     }
rsnAllocationSetSurface(long con, long alloc, Surface sur)508     native void rsnAllocationSetSurface(long con, long alloc, Surface sur);
nAllocationSetSurface(long alloc, Surface sur)509     synchronized void nAllocationSetSurface(long alloc, Surface sur) {
510         validate();
511         rsnAllocationSetSurface(mContext, alloc, sur);
512     }
rsnAllocationIoSend(long con, long alloc)513     native void rsnAllocationIoSend(long con, long alloc);
nAllocationIoSend(long alloc)514     synchronized void nAllocationIoSend(long alloc) {
515         validate();
516         rsnAllocationIoSend(mContext, alloc);
517     }
rsnAllocationIoReceive(long con, long alloc)518     native long rsnAllocationIoReceive(long con, long alloc);
nAllocationIoReceive(long alloc)519     synchronized long nAllocationIoReceive(long alloc) {
520         validate();
521         return rsnAllocationIoReceive(mContext, alloc);
522     }
523 
rsnAllocationGenerateMipmaps(long con, long alloc)524     native void rsnAllocationGenerateMipmaps(long con, long alloc);
nAllocationGenerateMipmaps(long alloc)525     synchronized void nAllocationGenerateMipmaps(long alloc) {
526         validate();
527         rsnAllocationGenerateMipmaps(mContext, alloc);
528     }
rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp)529     native void  rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp);
nAllocationCopyFromBitmap(long alloc, Bitmap bmp)530     synchronized void nAllocationCopyFromBitmap(long alloc, Bitmap bmp) {
531         validate();
532         rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
533     }
534 
535 
rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)536     native void rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt,
537                                     int mSize, boolean usePadding);
nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt, int mSize, boolean usePadding)538     synchronized void nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt,
539                                         int mSize, boolean usePadding) {
540         validate();
541         rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
542     }
543 
rsnAllocationElementData(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes)544     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)545     synchronized void nAllocationElementData(long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes) {
546         validate();
547         rsnAllocationElementData(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
548     }
549 
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)550     native void rsnAllocationData2D(long con,
551                                     long dstAlloc, int dstXoff, int dstYoff,
552                                     int dstMip, int dstFace,
553                                     int width, int height,
554                                     long srcAlloc, int srcXoff, int srcYoff,
555                                     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)556     synchronized void nAllocationData2D(long dstAlloc, int dstXoff, int dstYoff,
557                                         int dstMip, int dstFace,
558                                         int width, int height,
559                                         long srcAlloc, int srcXoff, int srcYoff,
560                                         int srcMip, int srcFace) {
561         validate();
562         rsnAllocationData2D(mContext,
563                             dstAlloc, dstXoff, dstYoff,
564                             dstMip, dstFace,
565                             width, height,
566                             srcAlloc, srcXoff, srcYoff,
567                             srcMip, srcFace);
568     }
569 
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)570     native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face,
571                                     int w, int h, Object d, int sizeBytes, int dt,
572                                     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)573     synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face,
574                                         int w, int h, Object d, int sizeBytes, Element.DataType dt,
575                                         int mSize, boolean usePadding) {
576         validate();
577         rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
578     }
579 
rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, Bitmap b)580     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)581     synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face, Bitmap b) {
582         validate();
583         rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
584     }
585 
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)586     native void rsnAllocationData3D(long con,
587                                     long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
588                                     int dstMip,
589                                     int width, int height, int depth,
590                                     long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
591                                     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)592     synchronized void nAllocationData3D(long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
593                                         int dstMip,
594                                         int width, int height, int depth,
595                                         long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
596                                         int srcMip) {
597         validate();
598         rsnAllocationData3D(mContext,
599                             dstAlloc, dstXoff, dstYoff, dstZoff,
600                             dstMip, width, height, depth,
601                             srcAlloc, srcXoff, srcYoff, srcZoff, srcMip);
602     }
603 
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)604     native void rsnAllocationData3D(long con, long id, int xoff, int yoff, int zoff, int mip,
605                                     int w, int h, int depth, Object d, int sizeBytes, int dt,
606                                     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)607     synchronized void nAllocationData3D(long id, int xoff, int yoff, int zoff, int mip,
608                                         int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
609                                         int mSize, boolean usePadding) {
610         validate();
611         rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes,
612                             dt.mID, mSize, usePadding);
613     }
614 
rsnAllocationRead(long con, long id, Object d, int dt, int mSize, boolean usePadding)615     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)616     synchronized void nAllocationRead(long id, Object d, Element.DataType dt, int mSize, boolean usePadding) {
617         validate();
618         rsnAllocationRead(mContext, id, d, dt.mID, mSize, usePadding);
619     }
620 
rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt, int mSize, boolean usePadding)621     native void rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d,
622                                     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)623     synchronized void nAllocationRead1D(long id, int off, int mip, int count, Object d,
624                                         int sizeBytes, Element.DataType dt, int mSize, boolean usePadding) {
625         validate();
626         rsnAllocationRead1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
627     }
628 
rsnAllocationElementRead(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes)629     native void rsnAllocationElementRead(long con,long id, int xoff, int yoff, int zoff,
630                                          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)631     synchronized void nAllocationElementRead(long id, int xoff, int yoff, int zoff,
632                                              int mip, int compIdx, byte[] d, int sizeBytes) {
633         validate();
634         rsnAllocationElementRead(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
635     }
636 
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)637     native void rsnAllocationRead2D(long con, long id, int xoff, int yoff, int mip, int face,
638                                     int w, int h, Object d, int sizeBytes, int dt,
639                                     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)640     synchronized void nAllocationRead2D(long id, int xoff, int yoff, int mip, int face,
641                                         int w, int h, Object d, int sizeBytes, Element.DataType dt,
642                                         int mSize, boolean usePadding) {
643         validate();
644         rsnAllocationRead2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
645     }
646 
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)647     native void rsnAllocationRead3D(long con, long id, int xoff, int yoff, int zoff, int mip,
648                                     int w, int h, int depth, Object d, int sizeBytes, int dt,
649                                     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)650     synchronized void nAllocationRead3D(long id, int xoff, int yoff, int zoff, int mip,
651                                         int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
652                                         int mSize, boolean usePadding) {
653         validate();
654         rsnAllocationRead3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes, dt.mID, mSize, usePadding);
655     }
656 
rsnAllocationGetType(long con, long id)657     native long  rsnAllocationGetType(long con, long id);
nAllocationGetType(long id)658     synchronized long nAllocationGetType(long id) {
659         validate();
660         return rsnAllocationGetType(mContext, id);
661     }
662 
rsnAllocationResize1D(long con, long id, int dimX)663     native void rsnAllocationResize1D(long con, long id, int dimX);
nAllocationResize1D(long id, int dimX)664     synchronized void nAllocationResize1D(long id, int dimX) {
665         validate();
666         rsnAllocationResize1D(mContext, id, dimX);
667     }
668 
rsnAllocationAdapterCreate(long con, long allocId, long typeId)669     native long  rsnAllocationAdapterCreate(long con, long allocId, long typeId);
nAllocationAdapterCreate(long allocId, long typeId)670     synchronized long nAllocationAdapterCreate(long allocId, long typeId) {
671         validate();
672         return rsnAllocationAdapterCreate(mContext, allocId, typeId);
673     }
674 
rsnAllocationAdapterOffset(long con, long id, int x, int y, int z, int mip, int face, int a1, int a2, int a3, int a4)675     native void  rsnAllocationAdapterOffset(long con, long id, int x, int y, int z,
676                                             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)677     synchronized void nAllocationAdapterOffset(long id, int x, int y, int z,
678                                                int mip, int face, int a1, int a2, int a3, int a4) {
679         validate();
680         rsnAllocationAdapterOffset(mContext, id, x, y, z, mip, face, a1, a2, a3, a4);
681     }
682 
rsnFileA3DCreateFromAssetStream(long con, long assetStream)683     native long rsnFileA3DCreateFromAssetStream(long con, long assetStream);
nFileA3DCreateFromAssetStream(long assetStream)684     synchronized long nFileA3DCreateFromAssetStream(long assetStream) {
685         validate();
686         return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
687     }
rsnFileA3DCreateFromFile(long con, String path)688     native long rsnFileA3DCreateFromFile(long con, String path);
nFileA3DCreateFromFile(String path)689     synchronized long nFileA3DCreateFromFile(String path) {
690         validate();
691         return rsnFileA3DCreateFromFile(mContext, path);
692     }
rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path)693     native long rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path);
nFileA3DCreateFromAsset(AssetManager mgr, String path)694     synchronized long nFileA3DCreateFromAsset(AssetManager mgr, String path) {
695         validate();
696         return rsnFileA3DCreateFromAsset(mContext, mgr, path);
697     }
rsnFileA3DGetNumIndexEntries(long con, long fileA3D)698     native int  rsnFileA3DGetNumIndexEntries(long con, long fileA3D);
nFileA3DGetNumIndexEntries(long fileA3D)699     synchronized int nFileA3DGetNumIndexEntries(long fileA3D) {
700         validate();
701         return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
702     }
rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names)703     native void rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names);
nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names)704     synchronized void nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names) {
705         validate();
706         rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
707     }
rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index)708     native long rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index);
nFileA3DGetEntryByIndex(long fileA3D, int index)709     synchronized long nFileA3DGetEntryByIndex(long fileA3D, int index) {
710         validate();
711         return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
712     }
713 
rsnFontCreateFromFile(long con, String fileName, float size, int dpi)714     native long rsnFontCreateFromFile(long con, String fileName, float size, int dpi);
nFontCreateFromFile(String fileName, float size, int dpi)715     synchronized long nFontCreateFromFile(String fileName, float size, int dpi) {
716         validate();
717         return rsnFontCreateFromFile(mContext, fileName, size, dpi);
718     }
rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream)719     native long rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream);
nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream)720     synchronized long nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream) {
721         validate();
722         return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
723     }
rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi)724     native long rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi);
nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi)725     synchronized long nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
726         validate();
727         return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
728     }
729 
730 
rsnScriptBindAllocation(long con, long script, long alloc, int slot)731     native void rsnScriptBindAllocation(long con, long script, long alloc, int slot);
nScriptBindAllocation(long script, long alloc, int slot)732     synchronized void nScriptBindAllocation(long script, long alloc, int slot) {
733         validate();
734         rsnScriptBindAllocation(mContext, script, alloc, slot);
735     }
rsnScriptSetTimeZone(long con, long script, byte[] timeZone)736     native void rsnScriptSetTimeZone(long con, long script, byte[] timeZone);
nScriptSetTimeZone(long script, byte[] timeZone)737     synchronized void nScriptSetTimeZone(long script, byte[] timeZone) {
738         validate();
739         rsnScriptSetTimeZone(mContext, script, timeZone);
740     }
rsnScriptInvoke(long con, long id, int slot)741     native void rsnScriptInvoke(long con, long id, int slot);
nScriptInvoke(long id, int slot)742     synchronized void nScriptInvoke(long id, int slot) {
743         validate();
744         rsnScriptInvoke(mContext, id, slot);
745     }
746 
rsnScriptForEach(long con, long id, int slot, long[] ains, long aout, byte[] params, int[] limits)747     native void rsnScriptForEach(long con, long id, int slot, long[] ains,
748                                  long aout, byte[] params, int[] limits);
749 
nScriptForEach(long id, int slot, long[] ains, long aout, byte[] params, int[] limits)750     synchronized void nScriptForEach(long id, int slot, long[] ains, long aout,
751                                      byte[] params, int[] limits) {
752         validate();
753         rsnScriptForEach(mContext, id, slot, ains, aout, params, limits);
754     }
755 
rsnScriptReduce(long con, long id, int slot, long[] ains, long aout, int[] limits)756     native void rsnScriptReduce(long con, long id, int slot, long[] ains,
757                                 long aout, int[] limits);
nScriptReduce(long id, int slot, long ains[], long aout, int[] limits)758     synchronized void nScriptReduce(long id, int slot, long ains[], long aout,
759                                     int[] limits) {
760         validate();
761         rsnScriptReduce(mContext, id, slot, ains, aout, limits);
762     }
763 
rsnScriptInvokeV(long con, long id, int slot, byte[] params)764     native void rsnScriptInvokeV(long con, long id, int slot, byte[] params);
nScriptInvokeV(long id, int slot, byte[] params)765     synchronized void nScriptInvokeV(long id, int slot, byte[] params) {
766         validate();
767         rsnScriptInvokeV(mContext, id, slot, params);
768     }
769 
rsnScriptSetVarI(long con, long id, int slot, int val)770     native void rsnScriptSetVarI(long con, long id, int slot, int val);
nScriptSetVarI(long id, int slot, int val)771     synchronized void nScriptSetVarI(long id, int slot, int val) {
772         validate();
773         rsnScriptSetVarI(mContext, id, slot, val);
774     }
rsnScriptGetVarI(long con, long id, int slot)775     native int rsnScriptGetVarI(long con, long id, int slot);
nScriptGetVarI(long id, int slot)776     synchronized int nScriptGetVarI(long id, int slot) {
777         validate();
778         return rsnScriptGetVarI(mContext, id, slot);
779     }
780 
rsnScriptSetVarJ(long con, long id, int slot, long val)781     native void rsnScriptSetVarJ(long con, long id, int slot, long val);
nScriptSetVarJ(long id, int slot, long val)782     synchronized void nScriptSetVarJ(long id, int slot, long val) {
783         validate();
784         rsnScriptSetVarJ(mContext, id, slot, val);
785     }
rsnScriptGetVarJ(long con, long id, int slot)786     native long rsnScriptGetVarJ(long con, long id, int slot);
nScriptGetVarJ(long id, int slot)787     synchronized long nScriptGetVarJ(long id, int slot) {
788         validate();
789         return rsnScriptGetVarJ(mContext, id, slot);
790     }
791 
rsnScriptSetVarF(long con, long id, int slot, float val)792     native void rsnScriptSetVarF(long con, long id, int slot, float val);
nScriptSetVarF(long id, int slot, float val)793     synchronized void nScriptSetVarF(long id, int slot, float val) {
794         validate();
795         rsnScriptSetVarF(mContext, id, slot, val);
796     }
rsnScriptGetVarF(long con, long id, int slot)797     native float rsnScriptGetVarF(long con, long id, int slot);
nScriptGetVarF(long id, int slot)798     synchronized float nScriptGetVarF(long id, int slot) {
799         validate();
800         return rsnScriptGetVarF(mContext, id, slot);
801     }
rsnScriptSetVarD(long con, long id, int slot, double val)802     native void rsnScriptSetVarD(long con, long id, int slot, double val);
nScriptSetVarD(long id, int slot, double val)803     synchronized void nScriptSetVarD(long id, int slot, double val) {
804         validate();
805         rsnScriptSetVarD(mContext, id, slot, val);
806     }
rsnScriptGetVarD(long con, long id, int slot)807     native double rsnScriptGetVarD(long con, long id, int slot);
nScriptGetVarD(long id, int slot)808     synchronized double nScriptGetVarD(long id, int slot) {
809         validate();
810         return rsnScriptGetVarD(mContext, id, slot);
811     }
rsnScriptSetVarV(long con, long id, int slot, byte[] val)812     native void rsnScriptSetVarV(long con, long id, int slot, byte[] val);
nScriptSetVarV(long id, int slot, byte[] val)813     synchronized void nScriptSetVarV(long id, int slot, byte[] val) {
814         validate();
815         rsnScriptSetVarV(mContext, id, slot, val);
816     }
rsnScriptGetVarV(long con, long id, int slot, byte[] val)817     native void rsnScriptGetVarV(long con, long id, int slot, byte[] val);
nScriptGetVarV(long id, int slot, byte[] val)818     synchronized void nScriptGetVarV(long id, int slot, byte[] val) {
819         validate();
820         rsnScriptGetVarV(mContext, id, slot, val);
821     }
rsnScriptSetVarVE(long con, long id, int slot, byte[] val, long e, int[] dims)822     native void rsnScriptSetVarVE(long con, long id, int slot, byte[] val,
823                                   long e, int[] dims);
nScriptSetVarVE(long id, int slot, byte[] val, long e, int[] dims)824     synchronized void nScriptSetVarVE(long id, int slot, byte[] val,
825                                       long e, int[] dims) {
826         validate();
827         rsnScriptSetVarVE(mContext, id, slot, val, e, dims);
828     }
rsnScriptSetVarObj(long con, long id, int slot, long val)829     native void rsnScriptSetVarObj(long con, long id, int slot, long val);
nScriptSetVarObj(long id, int slot, long val)830     synchronized void nScriptSetVarObj(long id, int slot, long val) {
831         validate();
832         rsnScriptSetVarObj(mContext, id, slot, val);
833     }
834 
rsnScriptCCreate(long con, String resName, String cacheDir, byte[] script, int length)835     native long rsnScriptCCreate(long con, String resName, String cacheDir,
836                                  byte[] script, int length);
837     @UnsupportedAppUsage
nScriptCCreate(String resName, String cacheDir, byte[] script, int length)838     synchronized long nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
839         validate();
840         return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
841     }
842 
rsnScriptIntrinsicCreate(long con, int id, long eid)843     native long rsnScriptIntrinsicCreate(long con, int id, long eid);
nScriptIntrinsicCreate(int id, long eid)844     synchronized long nScriptIntrinsicCreate(int id, long eid) {
845         validate();
846         return rsnScriptIntrinsicCreate(mContext, id, eid);
847     }
848 
rsnScriptKernelIDCreate(long con, long sid, int slot, int sig)849     native long  rsnScriptKernelIDCreate(long con, long sid, int slot, int sig);
nScriptKernelIDCreate(long sid, int slot, int sig)850     synchronized long nScriptKernelIDCreate(long sid, int slot, int sig) {
851         validate();
852         return rsnScriptKernelIDCreate(mContext, sid, slot, sig);
853     }
854 
rsnScriptInvokeIDCreate(long con, long sid, int slot)855     native long  rsnScriptInvokeIDCreate(long con, long sid, int slot);
nScriptInvokeIDCreate(long sid, int slot)856     synchronized long nScriptInvokeIDCreate(long sid, int slot) {
857         validate();
858         return rsnScriptInvokeIDCreate(mContext, sid, slot);
859     }
860 
rsnScriptFieldIDCreate(long con, long sid, int slot)861     native long  rsnScriptFieldIDCreate(long con, long sid, int slot);
nScriptFieldIDCreate(long sid, int slot)862     synchronized long nScriptFieldIDCreate(long sid, int slot) {
863         validate();
864         return rsnScriptFieldIDCreate(mContext, sid, slot);
865     }
866 
rsnScriptGroupCreate(long con, long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types)867     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)868     synchronized long nScriptGroupCreate(long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types) {
869         validate();
870         return rsnScriptGroupCreate(mContext, kernels, src, dstk, dstf, types);
871     }
872 
rsnScriptGroupSetInput(long con, long group, long kernel, long alloc)873     native void rsnScriptGroupSetInput(long con, long group, long kernel, long alloc);
nScriptGroupSetInput(long group, long kernel, long alloc)874     synchronized void nScriptGroupSetInput(long group, long kernel, long alloc) {
875         validate();
876         rsnScriptGroupSetInput(mContext, group, kernel, alloc);
877     }
878 
rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc)879     native void rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc);
nScriptGroupSetOutput(long group, long kernel, long alloc)880     synchronized void nScriptGroupSetOutput(long group, long kernel, long alloc) {
881         validate();
882         rsnScriptGroupSetOutput(mContext, group, kernel, alloc);
883     }
884 
rsnScriptGroupExecute(long con, long group)885     native void rsnScriptGroupExecute(long con, long group);
nScriptGroupExecute(long group)886     synchronized void nScriptGroupExecute(long group) {
887         validate();
888         rsnScriptGroupExecute(mContext, group);
889     }
890 
rsnSamplerCreate(long con, int magFilter, int minFilter, int wrapS, int wrapT, int wrapR, float aniso)891     native long  rsnSamplerCreate(long con, int magFilter, int minFilter,
892                                  int wrapS, int wrapT, int wrapR, float aniso);
nSamplerCreate(int magFilter, int minFilter, int wrapS, int wrapT, int wrapR, float aniso)893     synchronized long nSamplerCreate(int magFilter, int minFilter,
894                                  int wrapS, int wrapT, int wrapR, float aniso) {
895         validate();
896         return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
897     }
898 
rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a, boolean depthMask, boolean dither, int srcMode, int dstMode, int depthFunc)899     native long rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a,
900                                       boolean depthMask, boolean dither,
901                                       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)902     synchronized long nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
903                                          boolean depthMask, boolean dither,
904                                          int srcMode, int dstMode, int depthFunc) {
905         validate();
906         return rsnProgramStoreCreate(mContext, r, g, b, a, depthMask, dither, srcMode,
907                                      dstMode, depthFunc);
908     }
909 
rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode)910     native long rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode);
nProgramRasterCreate(boolean pointSprite, int cullMode)911     synchronized long nProgramRasterCreate(boolean pointSprite, int cullMode) {
912         validate();
913         return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
914     }
915 
rsnProgramBindConstants(long con, long pv, int slot, long mID)916     native void rsnProgramBindConstants(long con, long pv, int slot, long mID);
nProgramBindConstants(long pv, int slot, long mID)917     synchronized void nProgramBindConstants(long pv, int slot, long mID) {
918         validate();
919         rsnProgramBindConstants(mContext, pv, slot, mID);
920     }
rsnProgramBindTexture(long con, long vpf, int slot, long a)921     native void rsnProgramBindTexture(long con, long vpf, int slot, long a);
nProgramBindTexture(long vpf, int slot, long a)922     synchronized void nProgramBindTexture(long vpf, int slot, long a) {
923         validate();
924         rsnProgramBindTexture(mContext, vpf, slot, a);
925     }
rsnProgramBindSampler(long con, long vpf, int slot, long s)926     native void rsnProgramBindSampler(long con, long vpf, int slot, long s);
nProgramBindSampler(long vpf, int slot, long s)927     synchronized void nProgramBindSampler(long vpf, int slot, long s) {
928         validate();
929         rsnProgramBindSampler(mContext, vpf, slot, s);
930     }
rsnProgramFragmentCreate(long con, String shader, String[] texNames, long[] params)931     native long rsnProgramFragmentCreate(long con, String shader, String[] texNames, long[] params);
nProgramFragmentCreate(String shader, String[] texNames, long[] params)932     synchronized long nProgramFragmentCreate(String shader, String[] texNames, long[] params) {
933         validate();
934         return rsnProgramFragmentCreate(mContext, shader, texNames, params);
935     }
rsnProgramVertexCreate(long con, String shader, String[] texNames, long[] params)936     native long rsnProgramVertexCreate(long con, String shader, String[] texNames, long[] params);
nProgramVertexCreate(String shader, String[] texNames, long[] params)937     synchronized long nProgramVertexCreate(String shader, String[] texNames, long[] params) {
938         validate();
939         return rsnProgramVertexCreate(mContext, shader, texNames, params);
940     }
941 
rsnMeshCreate(long con, long[] vtx, long[] idx, int[] prim)942     native long rsnMeshCreate(long con, long[] vtx, long[] idx, int[] prim);
nMeshCreate(long[] vtx, long[] idx, int[] prim)943     synchronized long nMeshCreate(long[] vtx, long[] idx, int[] prim) {
944         validate();
945         return rsnMeshCreate(mContext, vtx, idx, prim);
946     }
rsnMeshGetVertexBufferCount(long con, long id)947     native int  rsnMeshGetVertexBufferCount(long con, long id);
nMeshGetVertexBufferCount(long id)948     synchronized int nMeshGetVertexBufferCount(long id) {
949         validate();
950         return rsnMeshGetVertexBufferCount(mContext, id);
951     }
rsnMeshGetIndexCount(long con, long id)952     native int  rsnMeshGetIndexCount(long con, long id);
nMeshGetIndexCount(long id)953     synchronized int nMeshGetIndexCount(long id) {
954         validate();
955         return rsnMeshGetIndexCount(mContext, id);
956     }
rsnMeshGetVertices(long con, long id, long[] vtxIds, int vtxIdCount)957     native void rsnMeshGetVertices(long con, long id, long[] vtxIds, int vtxIdCount);
nMeshGetVertices(long id, long[] vtxIds, int vtxIdCount)958     synchronized void nMeshGetVertices(long id, long[] vtxIds, int vtxIdCount) {
959         validate();
960         rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
961     }
rsnMeshGetIndices(long con, long id, long[] idxIds, int[] primitives, int vtxIdCount)962     native void rsnMeshGetIndices(long con, long id, long[] idxIds, int[] primitives, int vtxIdCount);
nMeshGetIndices(long id, long[] idxIds, int[] primitives, int vtxIdCount)963     synchronized void nMeshGetIndices(long id, long[] idxIds, int[] primitives, int vtxIdCount) {
964         validate();
965         rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
966     }
967 
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)968     native void rsnScriptIntrinsicBLAS_Single(long con, long id, int func, int TransA,
969                                               int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
970                                               float alpha, long A, long B, float beta, long C, int incX, int incY,
971                                               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)972     synchronized void nScriptIntrinsicBLAS_Single(long id, int func, int TransA,
973                                                   int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
974                                                   float alpha, long A, long B, float beta, long C, int incX, int incY,
975                                                   int KL, int KU) {
976         validate();
977         rsnScriptIntrinsicBLAS_Single(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
978     }
979 
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)980     native void rsnScriptIntrinsicBLAS_Double(long con, long id, int func, int TransA,
981                                               int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
982                                               double alpha, long A, long B, double beta, long C, int incX, int incY,
983                                               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)984     synchronized void nScriptIntrinsicBLAS_Double(long id, int func, int TransA,
985                                                   int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
986                                                   double alpha, long A, long B, double beta, long C, int incX, int incY,
987                                                   int KL, int KU) {
988         validate();
989         rsnScriptIntrinsicBLAS_Double(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
990     }
991 
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)992     native void rsnScriptIntrinsicBLAS_Complex(long con, long id, int func, int TransA,
993                                                int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
994                                                float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
995                                                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)996     synchronized void nScriptIntrinsicBLAS_Complex(long id, int func, int TransA,
997                                                    int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
998                                                    float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
999                                                    int KL, int KU) {
1000         validate();
1001         rsnScriptIntrinsicBLAS_Complex(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
1002     }
1003 
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)1004     native void rsnScriptIntrinsicBLAS_Z(long con, long id, int func, int TransA,
1005                                          int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
1006                                          double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
1007                                          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)1008     synchronized void nScriptIntrinsicBLAS_Z(long id, int func, int TransA,
1009                                              int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
1010                                              double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
1011                                              int KL, int KU) {
1012         validate();
1013         rsnScriptIntrinsicBLAS_Z(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
1014     }
1015 
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)1016     native void rsnScriptIntrinsicBLAS_BNNM(long con, long id, int M, int N, int K,
1017                                              long A, int a_offset, long B, int b_offset, long C, int c_offset,
1018                                              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)1019     synchronized void nScriptIntrinsicBLAS_BNNM(long id, int M, int N, int K,
1020                                              long A, int a_offset, long B, int b_offset, long C, int c_offset,
1021                                              int c_mult_int) {
1022         validate();
1023         rsnScriptIntrinsicBLAS_BNNM(mContext, id, M, N, K, A, a_offset, B, b_offset, C, c_offset, c_mult_int);
1024     }
1025 
1026 
1027 
1028     long     mContext;
1029     private boolean mDestroyed = false;
1030 
1031     @SuppressWarnings({"FieldCanBeLocal"})
1032     MessageThread mMessageThread;
1033 
1034     volatile Element mElement_U8;
1035     volatile Element mElement_I8;
1036     volatile Element mElement_U16;
1037     volatile Element mElement_I16;
1038     volatile Element mElement_U32;
1039     volatile Element mElement_I32;
1040     volatile Element mElement_U64;
1041     volatile Element mElement_I64;
1042     volatile Element mElement_F16;
1043     volatile Element mElement_F32;
1044     volatile Element mElement_F64;
1045     volatile Element mElement_BOOLEAN;
1046 
1047     volatile Element mElement_ELEMENT;
1048     volatile Element mElement_TYPE;
1049     volatile Element mElement_ALLOCATION;
1050     volatile Element mElement_SAMPLER;
1051     volatile Element mElement_SCRIPT;
1052     volatile Element mElement_MESH;
1053     volatile Element mElement_PROGRAM_FRAGMENT;
1054     volatile Element mElement_PROGRAM_VERTEX;
1055     volatile Element mElement_PROGRAM_RASTER;
1056     volatile Element mElement_PROGRAM_STORE;
1057     volatile Element mElement_FONT;
1058 
1059     volatile Element mElement_A_8;
1060     volatile Element mElement_RGB_565;
1061     volatile Element mElement_RGB_888;
1062     volatile Element mElement_RGBA_5551;
1063     volatile Element mElement_RGBA_4444;
1064     volatile Element mElement_RGBA_8888;
1065 
1066     volatile Element mElement_HALF_2;
1067     volatile Element mElement_HALF_3;
1068     volatile Element mElement_HALF_4;
1069 
1070     volatile Element mElement_FLOAT_2;
1071     volatile Element mElement_FLOAT_3;
1072     volatile Element mElement_FLOAT_4;
1073 
1074     volatile Element mElement_DOUBLE_2;
1075     volatile Element mElement_DOUBLE_3;
1076     volatile Element mElement_DOUBLE_4;
1077 
1078     volatile Element mElement_UCHAR_2;
1079     volatile Element mElement_UCHAR_3;
1080     volatile Element mElement_UCHAR_4;
1081 
1082     volatile Element mElement_CHAR_2;
1083     volatile Element mElement_CHAR_3;
1084     volatile Element mElement_CHAR_4;
1085 
1086     volatile Element mElement_USHORT_2;
1087     volatile Element mElement_USHORT_3;
1088     volatile Element mElement_USHORT_4;
1089 
1090     volatile Element mElement_SHORT_2;
1091     volatile Element mElement_SHORT_3;
1092     volatile Element mElement_SHORT_4;
1093 
1094     volatile Element mElement_UINT_2;
1095     volatile Element mElement_UINT_3;
1096     volatile Element mElement_UINT_4;
1097 
1098     volatile Element mElement_INT_2;
1099     volatile Element mElement_INT_3;
1100     volatile Element mElement_INT_4;
1101 
1102     volatile Element mElement_ULONG_2;
1103     volatile Element mElement_ULONG_3;
1104     volatile Element mElement_ULONG_4;
1105 
1106     volatile Element mElement_LONG_2;
1107     volatile Element mElement_LONG_3;
1108     volatile Element mElement_LONG_4;
1109 
1110     volatile Element mElement_YUV;
1111 
1112     volatile Element mElement_MATRIX_4X4;
1113     volatile Element mElement_MATRIX_3X3;
1114     volatile Element mElement_MATRIX_2X2;
1115 
1116     volatile Sampler mSampler_CLAMP_NEAREST;
1117     volatile Sampler mSampler_CLAMP_LINEAR;
1118     volatile Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
1119     volatile Sampler mSampler_WRAP_NEAREST;
1120     volatile Sampler mSampler_WRAP_LINEAR;
1121     volatile Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
1122     volatile Sampler mSampler_MIRRORED_REPEAT_NEAREST;
1123     volatile Sampler mSampler_MIRRORED_REPEAT_LINEAR;
1124     volatile Sampler mSampler_MIRRORED_REPEAT_LINEAR_MIP_LINEAR;
1125 
1126     ProgramStore mProgramStore_BLEND_NONE_DEPTH_TEST;
1127     ProgramStore mProgramStore_BLEND_NONE_DEPTH_NO_DEPTH;
1128     ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_TEST;
1129     ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_NO_DEPTH;
1130 
1131     ProgramRaster mProgramRaster_CULL_BACK;
1132     ProgramRaster mProgramRaster_CULL_FRONT;
1133     ProgramRaster mProgramRaster_CULL_NONE;
1134 
1135     ///////////////////////////////////////////////////////////////////////////////////
1136     //
1137 
1138     /**
1139      * The base class from which an application should derive in order
1140      * to receive RS messages from scripts. When a script calls {@code
1141      * rsSendToClient}, the data fields will be filled, and the run
1142      * method will be called on a separate thread.  This will occur
1143      * some time after {@code rsSendToClient} completes in the script,
1144      * as {@code rsSendToClient} is asynchronous. Message handlers are
1145      * not guaranteed to have completed when {@link
1146      * android.renderscript.RenderScript#finish} returns.
1147      *
1148      */
1149     public static class RSMessageHandler implements Runnable {
1150         protected int[] mData;
1151         protected int mID;
1152         protected int mLength;
run()1153         public void run() {
1154         }
1155     }
1156     /**
1157      * If an application is expecting messages, it should set this
1158      * field to an instance of {@link RSMessageHandler}.  This
1159      * instance will receive all the user messages sent from {@code
1160      * sendToClient} by scripts from this context.
1161      *
1162      */
1163     @UnsupportedAppUsage
1164     RSMessageHandler mMessageCallback = null;
1165 
setMessageHandler(RSMessageHandler msg)1166     public void setMessageHandler(RSMessageHandler msg) {
1167         mMessageCallback = msg;
1168     }
getMessageHandler()1169     public RSMessageHandler getMessageHandler() {
1170         return mMessageCallback;
1171     }
1172 
1173     /**
1174      * Place a message into the message queue to be sent back to the message
1175      * handler once all previous commands have been executed.
1176      *
1177      * @param id
1178      * @param data
1179      */
sendMessage(int id, int[] data)1180     public void sendMessage(int id, int[] data) {
1181         nContextSendMessage(id, data);
1182     }
1183 
1184     /**
1185      * The runtime error handler base class.  An application should derive from this class
1186      * if it wishes to install an error handler.  When errors occur at runtime,
1187      * the fields in this class will be filled, and the run method will be called.
1188      *
1189      */
1190     public static class RSErrorHandler implements Runnable {
1191         protected String mErrorMessage;
1192         protected int mErrorNum;
run()1193         public void run() {
1194         }
1195     }
1196 
1197     /**
1198      * Application Error handler.  All runtime errors will be dispatched to the
1199      * instance of RSAsyncError set here.  If this field is null a
1200      * {@link RSRuntimeException} will instead be thrown with details about the error.
1201      * This will cause program termaination.
1202      *
1203      */
1204     RSErrorHandler mErrorCallback = null;
1205 
setErrorHandler(RSErrorHandler msg)1206     public void setErrorHandler(RSErrorHandler msg) {
1207         mErrorCallback = msg;
1208     }
getErrorHandler()1209     public RSErrorHandler getErrorHandler() {
1210         return mErrorCallback;
1211     }
1212 
1213     /**
1214      * RenderScript worker thread priority enumeration.  The default value is
1215      * NORMAL.  Applications wishing to do background processing should set
1216      * their priority to LOW to avoid starving forground processes.
1217      */
1218     public enum Priority {
1219         // These values used to represent official thread priority values
1220         // now they are simply enums to be used by the runtime side
1221         LOW (15),
1222         NORMAL (-8);
1223 
1224         int mID;
Priority(int id)1225         Priority(int id) {
1226             mID = id;
1227         }
1228     }
1229 
validateObject(BaseObj o)1230     void validateObject(BaseObj o) {
1231         if (o != null) {
1232             if (o.mRS != this) {
1233                 throw new RSIllegalArgumentException("Attempting to use an object across contexts.");
1234             }
1235         }
1236     }
1237 
1238     @UnsupportedAppUsage
validate()1239     void validate() {
1240         if (mContext == 0) {
1241             throw new RSInvalidStateException("Calling RS with no Context active.");
1242         }
1243     }
1244 
1245 
1246     /**
1247      * Change the priority of the worker threads for this context.
1248      *
1249      * @param p New priority to be set.
1250      */
setPriority(Priority p)1251     public void setPriority(Priority p) {
1252         validate();
1253         nContextSetPriority(p.mID);
1254     }
1255 
1256     static class MessageThread extends Thread {
1257         RenderScript mRS;
1258         boolean mRun = true;
1259         int[] mAuxData = new int[2];
1260 
1261         static final int RS_MESSAGE_TO_CLIENT_NONE = 0;
1262         static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1;
1263         static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2;
1264         static final int RS_MESSAGE_TO_CLIENT_ERROR = 3;
1265         static final int RS_MESSAGE_TO_CLIENT_USER = 4;
1266         static final int RS_MESSAGE_TO_CLIENT_NEW_BUFFER = 5;
1267 
1268         static final int RS_ERROR_FATAL_DEBUG = 0x0800;
1269         static final int RS_ERROR_FATAL_UNKNOWN = 0x1000;
1270 
MessageThread(RenderScript rs)1271         MessageThread(RenderScript rs) {
1272             super("RSMessageThread");
1273             mRS = rs;
1274 
1275         }
1276 
run()1277         public void run() {
1278             // This function is a temporary solution.  The final solution will
1279             // used typed allocations where the message id is the type indicator.
1280             int[] rbuf = new int[16];
1281             mRS.nContextInitToClient(mRS.mContext);
1282             while(mRun) {
1283                 rbuf[0] = 0;
1284                 int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData);
1285                 int size = mAuxData[1];
1286                 int subID = mAuxData[0];
1287 
1288                 if (msg == RS_MESSAGE_TO_CLIENT_USER) {
1289                     if ((size>>2) >= rbuf.length) {
1290                         rbuf = new int[(size + 3) >> 2];
1291                     }
1292                     if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1293                         RS_MESSAGE_TO_CLIENT_USER) {
1294                         throw new RSDriverException("Error processing message from RenderScript.");
1295                     }
1296 
1297                     if(mRS.mMessageCallback != null) {
1298                         mRS.mMessageCallback.mData = rbuf;
1299                         mRS.mMessageCallback.mID = subID;
1300                         mRS.mMessageCallback.mLength = size;
1301                         mRS.mMessageCallback.run();
1302                     } else {
1303                         throw new RSInvalidStateException("Received a message from the script with no message handler installed.");
1304                     }
1305                     continue;
1306                 }
1307 
1308                 if (msg == RS_MESSAGE_TO_CLIENT_ERROR) {
1309                     String e = mRS.nContextGetErrorMessage(mRS.mContext);
1310 
1311                     // Throw RSRuntimeException under the following conditions:
1312                     //
1313                     // 1) It is an unknown fatal error.
1314                     // 2) It is a debug fatal error, and we are not in a
1315                     //    debug context.
1316                     // 3) It is a debug fatal error, and we do not have an
1317                     //    error callback.
1318                     if (subID >= RS_ERROR_FATAL_UNKNOWN ||
1319                         (subID >= RS_ERROR_FATAL_DEBUG &&
1320                          (mRS.mContextType != ContextType.DEBUG ||
1321                           mRS.mErrorCallback == null))) {
1322                         throw new RSRuntimeException("Fatal error " + subID + ", details: " + e);
1323                     }
1324 
1325                     if(mRS.mErrorCallback != null) {
1326                         mRS.mErrorCallback.mErrorMessage = e;
1327                         mRS.mErrorCallback.mErrorNum = subID;
1328                         mRS.mErrorCallback.run();
1329                     } else {
1330                         android.util.Log.e(LOG_TAG, "non fatal RS error, " + e);
1331                         // Do not throw here. In these cases, we do not have
1332                         // a fatal error.
1333                     }
1334                     continue;
1335                 }
1336 
1337                 if (msg == RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1338                     if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1339                         RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1340                         throw new RSDriverException("Error processing message from RenderScript.");
1341                     }
1342                     long bufferID = ((long)rbuf[1] << 32L) + ((long)rbuf[0] & 0xffffffffL);
1343                     Allocation.sendBufferNotification(bufferID);
1344                     continue;
1345                 }
1346 
1347                 // 2: teardown.
1348                 // But we want to avoid starving other threads during
1349                 // teardown by yielding until the next line in the destructor
1350                 // can execute to set mRun = false
1351                 try {
1352                     sleep(1, 0);
1353                 } catch(InterruptedException e) {
1354                 }
1355             }
1356             //Log.d(LOG_TAG, "MessageThread exiting.");
1357         }
1358     }
1359 
RenderScript(Context ctx)1360     RenderScript(Context ctx) {
1361         mContextType = ContextType.NORMAL;
1362         if (ctx != null) {
1363             mApplicationContext = ctx.getApplicationContext();
1364         }
1365         mRWLock = new ReentrantReadWriteLock();
1366         try {
1367             registerNativeAllocation.invoke(sRuntime, 4 * 1024 * 1024); // 4MB for GC sake
1368         } catch (Exception e) {
1369             Log.e(RenderScript.LOG_TAG, "Couldn't invoke registerNativeAllocation:" + e);
1370             throw new RSRuntimeException("Couldn't invoke registerNativeAllocation:" + e);
1371         }
1372 
1373     }
1374 
1375     /**
1376      * Gets the application context associated with the RenderScript context.
1377      *
1378      * @return The application context.
1379      */
getApplicationContext()1380     public final Context getApplicationContext() {
1381         return mApplicationContext;
1382     }
1383 
1384     /**
1385      * Name of the file that holds the object cache.
1386      */
1387     private static String mCachePath;
1388 
1389     /**
1390      * Gets the path to the code cache.
1391      */
getCachePath()1392     static synchronized String getCachePath() {
1393         if (mCachePath == null) {
1394             final String CACHE_PATH = "com.android.renderscript.cache";
1395             if (RenderScriptCacheDir.mCacheDir == null) {
1396                 throw new RSRuntimeException("RenderScript code cache directory uninitialized.");
1397             }
1398             File f = new File(RenderScriptCacheDir.mCacheDir, CACHE_PATH);
1399             mCachePath = f.getAbsolutePath();
1400             f.mkdirs();
1401         }
1402         return mCachePath;
1403     }
1404 
1405     /**
1406      * Create a RenderScript context.
1407      *
1408      * @param ctx The context.
1409      * @return RenderScript
1410      */
internalCreate(Context ctx, int sdkVersion, ContextType ct, int flags)1411     private static RenderScript internalCreate(Context ctx, int sdkVersion, ContextType ct, int flags) {
1412         if (!sInitialized) {
1413             Log.e(LOG_TAG, "RenderScript.create() called when disabled; someone is likely to crash");
1414             return null;
1415         }
1416 
1417         if ((flags & ~(CREATE_FLAG_LOW_LATENCY | CREATE_FLAG_LOW_POWER |
1418                        CREATE_FLAG_WAIT_FOR_ATTACH)) != 0) {
1419             throw new RSIllegalArgumentException("Invalid flags passed.");
1420         }
1421 
1422         RenderScript rs = new RenderScript(ctx);
1423 
1424         long device = rs.nDeviceCreate();
1425         rs.mContext = rs.nContextCreate(device, flags, sdkVersion, ct.mID);
1426         rs.mContextType = ct;
1427         rs.mContextFlags = flags;
1428         rs.mContextSdkVersion = sdkVersion;
1429         if (rs.mContext == 0) {
1430             throw new RSDriverException("Failed to create RS context.");
1431         }
1432 
1433         // set up cache directory for entire context
1434         rs.nContextSetCacheDir(RenderScript.getCachePath());
1435 
1436         rs.mMessageThread = new MessageThread(rs);
1437         rs.mMessageThread.start();
1438         return rs;
1439     }
1440 
1441     /**
1442      * calls create(ctx, ContextType.NORMAL, CREATE_FLAG_NONE)
1443      *
1444      * See documentation for @create for details
1445      *
1446      * @param ctx The context.
1447      * @return RenderScript
1448      */
create(Context ctx)1449     public static RenderScript create(Context ctx) {
1450         return create(ctx, ContextType.NORMAL);
1451     }
1452 
1453     /**
1454      * calls create(ctx, ct, CREATE_FLAG_NONE)
1455      *
1456      * See documentation for @create for details
1457      *
1458      * @param ctx The context.
1459      * @param ct The type of context to be created.
1460      * @return RenderScript
1461      */
create(Context ctx, ContextType ct)1462     public static RenderScript create(Context ctx, ContextType ct) {
1463         return create(ctx, ct, CREATE_FLAG_NONE);
1464     }
1465 
1466 
1467     /**
1468      * Gets or creates a RenderScript context of the specified type.
1469      *
1470      * The returned context will be cached for future reuse within
1471      * the process. When an application is finished using
1472      * RenderScript it should call releaseAllContexts()
1473      *
1474      * A process context is a context designed for easy creation and
1475      * lifecycle management.  Multiple calls to this function will
1476      * return the same object provided they are called with the same
1477      * options.  This allows it to be used any time a RenderScript
1478      * context is needed.
1479      *
1480      * Prior to API 23 this always created a new context.
1481      *
1482      * @param ctx The context.
1483      * @param ct The type of context to be created.
1484      * @param flags The OR of the CREATE_FLAG_* options desired
1485      * @return RenderScript
1486      */
create(Context ctx, ContextType ct, int flags)1487     public static RenderScript create(Context ctx, ContextType ct, int flags) {
1488         int v = ctx.getApplicationInfo().targetSdkVersion;
1489         return create(ctx, v, ct, flags);
1490     }
1491 
1492     /**
1493      * calls create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE)
1494      *
1495      * Used by the RenderScriptThunker to maintain backward compatibility.
1496      *
1497      * @hide
1498      * @param ctx The context.
1499      * @param sdkVersion The target SDK Version.
1500      * @return RenderScript
1501      */
1502     @UnsupportedAppUsage
create(Context ctx, int sdkVersion)1503     public static RenderScript create(Context ctx, int sdkVersion) {
1504         return create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE);
1505     }
1506 
1507      /**
1508      * Gets or creates a RenderScript context of the specified type.
1509      *
1510      * @param ctx The context.
1511      * @param ct The type of context to be created.
1512      * @param sdkVersion The target SDK Version.
1513      * @param flags The OR of the CREATE_FLAG_* options desired
1514      * @return RenderScript
1515      */
1516     @UnsupportedAppUsage
create(Context ctx, int sdkVersion, ContextType ct, int flags)1517     private static RenderScript create(Context ctx, int sdkVersion, ContextType ct, int flags) {
1518         if (sdkVersion < 23) {
1519             return internalCreate(ctx, sdkVersion, ct, flags);
1520         }
1521 
1522         synchronized (mProcessContextList) {
1523             for (RenderScript prs : mProcessContextList) {
1524                 if ((prs.mContextType == ct) &&
1525                     (prs.mContextFlags == flags) &&
1526                     (prs.mContextSdkVersion == sdkVersion)) {
1527 
1528                     return prs;
1529                 }
1530             }
1531 
1532             RenderScript prs = internalCreate(ctx, sdkVersion, ct, flags);
1533             prs.mIsProcessContext = true;
1534             mProcessContextList.add(prs);
1535             return prs;
1536         }
1537     }
1538 
1539     /**
1540      * Releases all the process contexts.  This is the same as
1541      * calling .destroy() on each unique context retreived with
1542      * create(...). If no contexts have been created this
1543      * function does nothing.
1544      *
1545      * Typically you call this when your application is losing focus
1546      * and will not be using a context for some time.
1547      *
1548      * This has no effect on a context created with
1549      * createMultiContext()
1550      */
releaseAllContexts()1551     public static void releaseAllContexts() {
1552         ArrayList<RenderScript> oldList;
1553         synchronized (mProcessContextList) {
1554             oldList = mProcessContextList;
1555             mProcessContextList = new ArrayList<RenderScript>();
1556         }
1557 
1558         for (RenderScript prs : oldList) {
1559             prs.mIsProcessContext = false;
1560             prs.destroy();
1561         }
1562         oldList.clear();
1563     }
1564 
1565 
1566 
1567     /**
1568      * Create a RenderScript context.
1569      *
1570      * This is an advanced function intended for applications which
1571      * need to create more than one RenderScript context to be used
1572      * at the same time.
1573      *
1574      * If you need a single context please use create()
1575      *
1576      * @param ctx The context.
1577      * @return RenderScript
1578      */
createMultiContext(Context ctx, ContextType ct, int flags, int API_number)1579     public static RenderScript createMultiContext(Context ctx, ContextType ct, int flags, int API_number) {
1580         return internalCreate(ctx, API_number, ct, flags);
1581     }
1582 
1583 
1584     /**
1585      * Print the currently available debugging information about the state of
1586      * the RS context to the log.
1587      *
1588      */
contextDump()1589     public void contextDump() {
1590         validate();
1591         nContextDump(0);
1592     }
1593 
1594     /**
1595      * Wait for any pending asynchronous opeations (such as copies to a RS
1596      * allocation or RS script executions) to complete.
1597      *
1598      */
finish()1599     public void finish() {
1600         nContextFinish();
1601     }
1602 
helpDestroy()1603     private void helpDestroy() {
1604         boolean shouldDestroy = false;
1605         synchronized(this) {
1606             if (!mDestroyed) {
1607                 shouldDestroy = true;
1608                 mDestroyed = true;
1609             }
1610         }
1611 
1612         if (shouldDestroy) {
1613             nContextFinish();
1614 
1615             nContextDeinitToClient(mContext);
1616             mMessageThread.mRun = false;
1617             // Interrupt mMessageThread so it gets to see immediately that mRun is false
1618             // and exit rightaway.
1619             mMessageThread.interrupt();
1620 
1621             // Wait for mMessageThread to join.  Try in a loop, in case this thread gets interrupted
1622             // during the wait.  If interrupted, set the "interrupted" status of the current thread.
1623             boolean hasJoined = false, interrupted = false;
1624             while (!hasJoined) {
1625                 try {
1626                     mMessageThread.join();
1627                     hasJoined = true;
1628                 } catch (InterruptedException e) {
1629                     interrupted = true;
1630                 }
1631             }
1632             if (interrupted) {
1633                 Log.v(LOG_TAG, "Interrupted during wait for MessageThread to join");
1634                 Thread.currentThread().interrupt();
1635             }
1636 
1637             nContextDestroy();
1638         }
1639     }
1640 
finalize()1641     protected void finalize() throws Throwable {
1642         helpDestroy();
1643         super.finalize();
1644     }
1645 
1646 
1647     /**
1648      * Destroys this RenderScript context.  Once this function is called,
1649      * using this context or any objects belonging to this context is
1650      * illegal.
1651      *
1652      * API 23+, this function is a NOP if the context was created
1653      * with create().  Please use releaseAllContexts() to clean up
1654      * contexts created with the create function.
1655      *
1656      */
destroy()1657     public void destroy() {
1658         if (mIsProcessContext) {
1659             // users cannot destroy a process context
1660             return;
1661         }
1662         validate();
1663         helpDestroy();
1664     }
1665 
isAlive()1666     boolean isAlive() {
1667         return mContext != 0;
1668     }
1669 
safeID(BaseObj o)1670     long safeID(BaseObj o) {
1671         if(o != null) {
1672             return o.getID(this);
1673         }
1674         return 0;
1675     }
1676 }
1677