2 * Copyright (C) 2008-2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.renderscript;
20 import java.lang.reflect.Method;
21 import java.util.concurrent.locks.ReentrantReadWriteLock;
23 import android.content.Context;
24 import android.content.res.AssetManager;
25 import android.graphics.Bitmap;
26 import android.graphics.SurfaceTexture;
27 import android.util.Log;
28 import android.view.Surface;
29 import android.os.SystemProperties;
30 import android.os.Trace;
31 import java.util.ArrayList;
33 // TODO: Clean up the whitespace that separates methods in this class.
36 * This class provides access to a RenderScript context, which controls RenderScript
37 * initialization, resource management, and teardown. An instance of the RenderScript
38 * class must be created before any other RS objects can be created.
40 * <div class="special reference">
41 * <h3>Developer Guides</h3>
42 * <p>For more information about creating an application that uses RenderScript, read the
43 * <a href="{@docRoot}guide/topics/renderscript/index.html">RenderScript</a> developer guide.</p>
46 public class RenderScript {
47 static final long TRACE_TAG = Trace.TRACE_TAG_RS;
49 static final String LOG_TAG = "RenderScript_jni";
50 static final boolean DEBUG = false;
51 @SuppressWarnings({"UnusedDeclaration", "deprecation"})
52 static final boolean LOG_ENABLED = false;
54 static private ArrayList<RenderScript> mProcessContextList = new ArrayList<RenderScript>();
55 private boolean mIsProcessContext = false;
56 private int mContextFlags = 0;
57 private int mContextSdkVersion = 0;
60 private Context mApplicationContext;
63 * We use a class initializer to allow the native code to cache some
66 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) // TODO: now used locally; remove?
67 static boolean sInitialized;
68 native static void _nInit();
70 static Object sRuntime;
71 static Method registerNativeAllocation;
72 static Method registerNativeFree;
75 * Context creation flag that specifies a normal context.
77 public static final int CREATE_FLAG_NONE = 0x0000;
80 * Context creation flag which specifies a context optimized for low
81 * latency over peak performance. This is a hint and may have no effect
82 * on some implementations.
84 public static final int CREATE_FLAG_LOW_LATENCY = 0x0002;
87 * Context creation flag which specifies a context optimized for long
88 * battery life over peak performance. This is a hint and may have no effect
89 * on some implementations.
91 public static final int CREATE_FLAG_LOW_POWER = 0x0004;
95 * Context creation flag which instructs the implementation to wait for
96 * a debugger to be attached before continuing execution.
98 public static final int CREATE_FLAG_WAIT_FOR_ATTACH = 0x0008;
102 * Context creation flag which specifies that optimization level 0 is
103 * passed to the device compiler upon execution of the RenderScript kernel.
104 * The default optimization level is 3.
106 public static final int CREATE_FLAG_OPT_LEVEL_0 = 0x0010;
109 * Detect the bitness of the VM to allow FieldPacker to do the right thing.
111 static native int rsnSystemGetPointerSize();
112 static int sPointerSize;
115 sInitialized = false;
116 if (!SystemProperties.getBoolean("config.disable_renderscript", false)) {
118 Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
119 Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
120 sRuntime = get_runtime.invoke(null);
121 registerNativeAllocation = vm_runtime.getDeclaredMethod("registerNativeAllocation", Integer.TYPE);
122 registerNativeFree = vm_runtime.getDeclaredMethod("registerNativeFree", Integer.TYPE);
123 } catch (Exception e) {
124 Log.e(LOG_TAG, "Error loading GC methods: " + e);
125 throw new RSRuntimeException("Error loading GC methods: " + e);
128 System.loadLibrary("rs_jni");
131 sPointerSize = rsnSystemGetPointerSize();
132 } catch (UnsatisfiedLinkError e) {
133 Log.e(LOG_TAG, "Error loading RS jni library: " + e);
134 throw new RSRuntimeException("Error loading RS jni library: " + e);
139 // Non-threadsafe functions.
140 native long nDeviceCreate();
141 native void nDeviceDestroy(long dev);
142 native void nDeviceSetConfig(long dev, int param, int value);
143 native int nContextGetUserMessage(long con, int[] data);
144 native String nContextGetErrorMessage(long con);
145 native int nContextPeekMessage(long con, int[] subID);
146 native void nContextInitToClient(long con);
147 native void nContextDeinitToClient(long con);
149 // this should be a monotonically increasing ID
150 // used in conjunction with the API version of a device
151 static final long sMinorVersion = 1;
156 * Only exist to be compatible with old version RenderScript Support lib.
157 * Will eventually be removed.
159 * @return Always return 1
162 public static long getMinorID() {
168 * Returns an identifier that can be used to identify a particular
169 * minor version of RS.
171 * @return The minor RenderScript version number
174 public static long getMinorVersion() {
175 return sMinorVersion;
179 * ContextType specifies the specific type of context to be created.
182 public enum ContextType {
184 * NORMAL context, this is the default and what shipping apps should
190 * DEBUG context, perform extra runtime checks to validate the
191 * kernels and APIs are being used as intended. Get and SetElementAt
192 * will be bounds checked in this mode.
197 * PROFILE context, Intended to be used once the first time an
198 * application is run on a new device. This mode allows the runtime to
199 * do additional testing and performance tuning.
204 ContextType(int id) {
209 ContextType mContextType;
210 ReentrantReadWriteLock mRWLock;
212 // Methods below are wrapped to protect the non-threadsafe
214 native long rsnContextCreateGL(long dev, int ver, int sdkVer,
215 int colorMin, int colorPref,
216 int alphaMin, int alphaPref,
217 int depthMin, int depthPref,
218 int stencilMin, int stencilPref,
219 int samplesMin, int samplesPref, float samplesQ, int dpi);
220 synchronized long nContextCreateGL(long dev, int ver, int sdkVer,
221 int colorMin, int colorPref,
222 int alphaMin, int alphaPref,
223 int depthMin, int depthPref,
224 int stencilMin, int stencilPref,
225 int samplesMin, int samplesPref, float samplesQ, int dpi) {
226 return rsnContextCreateGL(dev, ver, sdkVer, colorMin, colorPref,
227 alphaMin, alphaPref, depthMin, depthPref,
228 stencilMin, stencilPref,
229 samplesMin, samplesPref, samplesQ, dpi);
231 native long rsnContextCreate(long dev, int ver, int sdkVer, int contextType);
232 synchronized long nContextCreate(long dev, int ver, int sdkVer, int contextType) {
233 return rsnContextCreate(dev, ver, sdkVer, contextType);
235 native void rsnContextDestroy(long con);
236 synchronized void nContextDestroy() {
239 // take teardown lock
240 // teardown lock can only be taken when no objects are being destroyed
241 ReentrantReadWriteLock.WriteLock wlock = mRWLock.writeLock();
244 long curCon = mContext;
245 // context is considered dead as of this point
249 rsnContextDestroy(curCon);
251 native void rsnContextSetSurface(long con, int w, int h, Surface sur);
252 synchronized void nContextSetSurface(int w, int h, Surface sur) {
254 rsnContextSetSurface(mContext, w, h, sur);
256 native void rsnContextSetSurfaceTexture(long con, int w, int h, SurfaceTexture sur);
257 synchronized void nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur) {
259 rsnContextSetSurfaceTexture(mContext, w, h, sur);
261 native void rsnContextSetPriority(long con, int p);
262 synchronized void nContextSetPriority(int p) {
264 rsnContextSetPriority(mContext, p);
266 native void rsnContextSetCacheDir(long con, String cacheDir);
267 synchronized void nContextSetCacheDir(String cacheDir) {
269 rsnContextSetCacheDir(mContext, cacheDir);
271 native void rsnContextDump(long con, int bits);
272 synchronized void nContextDump(int bits) {
274 rsnContextDump(mContext, bits);
276 native void rsnContextFinish(long con);
277 synchronized void nContextFinish() {
279 rsnContextFinish(mContext);
282 native void rsnContextSendMessage(long con, int id, int[] data);
283 synchronized void nContextSendMessage(int id, int[] data) {
285 rsnContextSendMessage(mContext, id, data);
288 native void rsnContextBindRootScript(long con, long script);
289 synchronized void nContextBindRootScript(long script) {
291 rsnContextBindRootScript(mContext, script);
293 native void rsnContextBindSampler(long con, int sampler, int slot);
294 synchronized void nContextBindSampler(int sampler, int slot) {
296 rsnContextBindSampler(mContext, sampler, slot);
298 native void rsnContextBindProgramStore(long con, long pfs);
299 synchronized void nContextBindProgramStore(long pfs) {
301 rsnContextBindProgramStore(mContext, pfs);
303 native void rsnContextBindProgramFragment(long con, long pf);
304 synchronized void nContextBindProgramFragment(long pf) {
306 rsnContextBindProgramFragment(mContext, pf);
308 native void rsnContextBindProgramVertex(long con, long pv);
309 synchronized void nContextBindProgramVertex(long pv) {
311 rsnContextBindProgramVertex(mContext, pv);
313 native void rsnContextBindProgramRaster(long con, long pr);
314 synchronized void nContextBindProgramRaster(long pr) {
316 rsnContextBindProgramRaster(mContext, pr);
318 native void rsnContextPause(long con);
319 synchronized void nContextPause() {
321 rsnContextPause(mContext);
323 native void rsnContextResume(long con);
324 synchronized void nContextResume() {
326 rsnContextResume(mContext);
329 native long rsnClosureCreate(long con, long kernelID, long returnValue,
330 long[] fieldIDs, long[] values, int[] sizes, long[] depClosures,
332 synchronized long nClosureCreate(long kernelID, long returnValue,
333 long[] fieldIDs, long[] values, int[] sizes, long[] depClosures,
334 long[] depFieldIDs) {
336 long c = rsnClosureCreate(mContext, kernelID, returnValue, fieldIDs, values,
337 sizes, depClosures, depFieldIDs);
339 throw new RSRuntimeException("Failed creating closure.");
344 native long rsnInvokeClosureCreate(long con, long invokeID, byte[] params,
345 long[] fieldIDs, long[] values, int[] sizes);
346 synchronized long nInvokeClosureCreate(long invokeID, byte[] params,
347 long[] fieldIDs, long[] values, int[] sizes) {
349 long c = rsnInvokeClosureCreate(mContext, invokeID, params, fieldIDs,
352 throw new RSRuntimeException("Failed creating closure.");
357 native void rsnClosureSetArg(long con, long closureID, int index,
358 long value, int size);
359 synchronized void nClosureSetArg(long closureID, int index, long value,
362 rsnClosureSetArg(mContext, closureID, index, value, size);
365 native void rsnClosureSetGlobal(long con, long closureID, long fieldID,
366 long value, int size);
367 // Does this have to be synchronized?
368 synchronized void nClosureSetGlobal(long closureID, long fieldID,
369 long value, int size) {
370 validate(); // TODO: is this necessary?
371 rsnClosureSetGlobal(mContext, closureID, fieldID, value, size);
374 native long rsnScriptGroup2Create(long con, String name, String cachePath,
376 synchronized long nScriptGroup2Create(String name, String cachePath,
379 long g = rsnScriptGroup2Create(mContext, name, cachePath, closures);
381 throw new RSRuntimeException("Failed creating script group.");
386 native void rsnScriptGroup2Execute(long con, long groupID);
387 synchronized void nScriptGroup2Execute(long groupID) {
389 rsnScriptGroup2Execute(mContext, groupID);
392 native void rsnAssignName(long con, long obj, byte[] name);
393 synchronized void nAssignName(long obj, byte[] name) {
395 rsnAssignName(mContext, obj, name);
397 native String rsnGetName(long con, long obj);
398 synchronized String nGetName(long obj) {
400 return rsnGetName(mContext, obj);
403 // nObjDestroy is explicitly _not_ synchronous to prevent crashes in finalizers
404 native void rsnObjDestroy(long con, long id);
405 void nObjDestroy(long id) {
406 // There is a race condition here. The calling code may be run
407 // by the gc while teardown is occuring. This protects againts
408 // deleting dead objects.
410 rsnObjDestroy(mContext, id);
414 native long rsnElementCreate(long con, long type, int kind, boolean norm, int vecSize);
415 synchronized long nElementCreate(long type, int kind, boolean norm, int vecSize) {
417 return rsnElementCreate(mContext, type, kind, norm, vecSize);
419 native long rsnElementCreate2(long con, long[] elements, String[] names, int[] arraySizes);
420 synchronized long nElementCreate2(long[] elements, String[] names, int[] arraySizes) {
422 return rsnElementCreate2(mContext, elements, names, arraySizes);
424 native void rsnElementGetNativeData(long con, long id, int[] elementData);
425 synchronized void nElementGetNativeData(long id, int[] elementData) {
427 rsnElementGetNativeData(mContext, id, elementData);
429 native void rsnElementGetSubElements(long con, long id,
430 long[] IDs, String[] names, int[] arraySizes);
431 synchronized void nElementGetSubElements(long id, long[] IDs, String[] names, int[] arraySizes) {
433 rsnElementGetSubElements(mContext, id, IDs, names, arraySizes);
436 native long rsnTypeCreate(long con, long eid, int x, int y, int z, boolean mips, boolean faces, int yuv);
437 synchronized long nTypeCreate(long eid, int x, int y, int z, boolean mips, boolean faces, int yuv) {
439 return rsnTypeCreate(mContext, eid, x, y, z, mips, faces, yuv);
441 native void rsnTypeGetNativeData(long con, long id, long[] typeData);
442 synchronized void nTypeGetNativeData(long id, long[] typeData) {
444 rsnTypeGetNativeData(mContext, id, typeData);
447 native long rsnAllocationCreateTyped(long con, long type, int mip, int usage, long pointer);
448 synchronized long nAllocationCreateTyped(long type, int mip, int usage, long pointer) {
450 return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer);
452 native long rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage);
453 synchronized long nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
455 return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
458 native long rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp, int usage);
459 synchronized long nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp, int usage) {
461 return rsnAllocationCreateBitmapBackedAllocation(mContext, type, mip, bmp, usage);
464 native long rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage);
465 synchronized long nAllocationCubeCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
467 return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage);
469 native long rsnAllocationCreateBitmapRef(long con, long type, Bitmap bmp);
470 synchronized long nAllocationCreateBitmapRef(long type, Bitmap bmp) {
472 return rsnAllocationCreateBitmapRef(mContext, type, bmp);
474 native long rsnAllocationCreateFromAssetStream(long con, int mips, int assetStream, int usage);
475 synchronized long nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) {
477 return rsnAllocationCreateFromAssetStream(mContext, mips, assetStream, usage);
480 native void rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp);
481 synchronized void nAllocationCopyToBitmap(long alloc, Bitmap bmp) {
483 rsnAllocationCopyToBitmap(mContext, alloc, bmp);
487 native void rsnAllocationSyncAll(long con, long alloc, int src);
488 synchronized void nAllocationSyncAll(long alloc, int src) {
490 rsnAllocationSyncAll(mContext, alloc, src);
492 native Surface rsnAllocationGetSurface(long con, long alloc);
493 synchronized Surface nAllocationGetSurface(long alloc) {
495 return rsnAllocationGetSurface(mContext, alloc);
497 native void rsnAllocationSetSurface(long con, long alloc, Surface sur);
498 synchronized void nAllocationSetSurface(long alloc, Surface sur) {
500 rsnAllocationSetSurface(mContext, alloc, sur);
502 native void rsnAllocationIoSend(long con, long alloc);
503 synchronized void nAllocationIoSend(long alloc) {
505 rsnAllocationIoSend(mContext, alloc);
507 native void rsnAllocationIoReceive(long con, long alloc);
508 synchronized void nAllocationIoReceive(long alloc) {
510 rsnAllocationIoReceive(mContext, alloc);
514 native void rsnAllocationGenerateMipmaps(long con, long alloc);
515 synchronized void nAllocationGenerateMipmaps(long alloc) {
517 rsnAllocationGenerateMipmaps(mContext, alloc);
519 native void rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp);
520 synchronized void nAllocationCopyFromBitmap(long alloc, Bitmap bmp) {
522 rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
526 native void rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt,
527 int mSize, boolean usePadding);
528 synchronized void nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt,
529 int mSize, boolean usePadding) {
531 rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
534 native void rsnAllocationElementData(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes);
535 synchronized void nAllocationElementData(long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes) {
537 rsnAllocationElementData(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
540 native void rsnAllocationData2D(long con,
541 long dstAlloc, int dstXoff, int dstYoff,
542 int dstMip, int dstFace,
543 int width, int height,
544 long srcAlloc, int srcXoff, int srcYoff,
545 int srcMip, int srcFace);
546 synchronized void nAllocationData2D(long dstAlloc, int dstXoff, int dstYoff,
547 int dstMip, int dstFace,
548 int width, int height,
549 long srcAlloc, int srcXoff, int srcYoff,
550 int srcMip, int srcFace) {
552 rsnAllocationData2D(mContext,
553 dstAlloc, dstXoff, dstYoff,
556 srcAlloc, srcXoff, srcYoff,
560 native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face,
561 int w, int h, Object d, int sizeBytes, int dt,
562 int mSize, boolean usePadding);
563 synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face,
564 int w, int h, Object d, int sizeBytes, Element.DataType dt,
565 int mSize, boolean usePadding) {
567 rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
570 native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, Bitmap b);
571 synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face, Bitmap b) {
573 rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
576 native void rsnAllocationData3D(long con,
577 long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
579 int width, int height, int depth,
580 long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
582 synchronized void nAllocationData3D(long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
584 int width, int height, int depth,
585 long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
588 rsnAllocationData3D(mContext,
589 dstAlloc, dstXoff, dstYoff, dstZoff,
590 dstMip, width, height, depth,
591 srcAlloc, srcXoff, srcYoff, srcZoff, srcMip);
594 native void rsnAllocationData3D(long con, long id, int xoff, int yoff, int zoff, int mip,
595 int w, int h, int depth, Object d, int sizeBytes, int dt,
596 int mSize, boolean usePadding);
597 synchronized void nAllocationData3D(long id, int xoff, int yoff, int zoff, int mip,
598 int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
599 int mSize, boolean usePadding) {
601 rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes,
602 dt.mID, mSize, usePadding);
605 native void rsnAllocationRead(long con, long id, Object d, int dt, int mSize, boolean usePadding);
606 synchronized void nAllocationRead(long id, Object d, Element.DataType dt, int mSize, boolean usePadding) {
608 rsnAllocationRead(mContext, id, d, dt.mID, mSize, usePadding);
611 native void rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d,
612 int sizeBytes, int dt, int mSize, boolean usePadding);
613 synchronized void nAllocationRead1D(long id, int off, int mip, int count, Object d,
614 int sizeBytes, Element.DataType dt, int mSize, boolean usePadding) {
616 rsnAllocationRead1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
619 native void rsnAllocationElementRead(long con,long id, int xoff, int yoff, int zoff,
620 int mip, int compIdx, byte[] d, int sizeBytes);
621 synchronized void nAllocationElementRead(long id, int xoff, int yoff, int zoff,
622 int mip, int compIdx, byte[] d, int sizeBytes) {
624 rsnAllocationElementRead(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
627 native void rsnAllocationRead2D(long con, long id, int xoff, int yoff, int mip, int face,
628 int w, int h, Object d, int sizeBytes, int dt,
629 int mSize, boolean usePadding);
630 synchronized void nAllocationRead2D(long id, int xoff, int yoff, int mip, int face,
631 int w, int h, Object d, int sizeBytes, Element.DataType dt,
632 int mSize, boolean usePadding) {
634 rsnAllocationRead2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
637 native void rsnAllocationRead3D(long con, long id, int xoff, int yoff, int zoff, int mip,
638 int w, int h, int depth, Object d, int sizeBytes, int dt,
639 int mSize, boolean usePadding);
640 synchronized void nAllocationRead3D(long id, int xoff, int yoff, int zoff, int mip,
641 int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
642 int mSize, boolean usePadding) {
644 rsnAllocationRead3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes, dt.mID, mSize, usePadding);
647 native long rsnAllocationGetType(long con, long id);
648 synchronized long nAllocationGetType(long id) {
650 return rsnAllocationGetType(mContext, id);
653 native void rsnAllocationResize1D(long con, long id, int dimX);
654 synchronized void nAllocationResize1D(long id, int dimX) {
656 rsnAllocationResize1D(mContext, id, dimX);
659 native long rsnAllocationAdapterCreate(long con, long allocId, long typeId);
660 synchronized long nAllocationAdapterCreate(long allocId, long typeId) {
662 return rsnAllocationAdapterCreate(mContext, allocId, typeId);
665 native void rsnAllocationAdapterOffset(long con, long id, int x, int y, int z,
666 int mip, int face, int a1, int a2, int a3, int a4);
667 synchronized void nAllocationAdapterOffset(long id, int x, int y, int z,
668 int mip, int face, int a1, int a2, int a3, int a4) {
670 rsnAllocationAdapterOffset(mContext, id, x, y, z, mip, face, a1, a2, a3, a4);
673 native long rsnFileA3DCreateFromAssetStream(long con, long assetStream);
674 synchronized long nFileA3DCreateFromAssetStream(long assetStream) {
676 return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
678 native long rsnFileA3DCreateFromFile(long con, String path);
679 synchronized long nFileA3DCreateFromFile(String path) {
681 return rsnFileA3DCreateFromFile(mContext, path);
683 native long rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path);
684 synchronized long nFileA3DCreateFromAsset(AssetManager mgr, String path) {
686 return rsnFileA3DCreateFromAsset(mContext, mgr, path);
688 native int rsnFileA3DGetNumIndexEntries(long con, long fileA3D);
689 synchronized int nFileA3DGetNumIndexEntries(long fileA3D) {
691 return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
693 native void rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names);
694 synchronized void nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names) {
696 rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
698 native long rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index);
699 synchronized long nFileA3DGetEntryByIndex(long fileA3D, int index) {
701 return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
704 native long rsnFontCreateFromFile(long con, String fileName, float size, int dpi);
705 synchronized long nFontCreateFromFile(String fileName, float size, int dpi) {
707 return rsnFontCreateFromFile(mContext, fileName, size, dpi);
709 native long rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream);
710 synchronized long nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream) {
712 return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
714 native long rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi);
715 synchronized long nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
717 return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
721 native void rsnScriptBindAllocation(long con, long script, long alloc, int slot);
722 synchronized void nScriptBindAllocation(long script, long alloc, int slot) {
724 rsnScriptBindAllocation(mContext, script, alloc, slot);
726 native void rsnScriptSetTimeZone(long con, long script, byte[] timeZone);
727 synchronized void nScriptSetTimeZone(long script, byte[] timeZone) {
729 rsnScriptSetTimeZone(mContext, script, timeZone);
731 native void rsnScriptInvoke(long con, long id, int slot);
732 synchronized void nScriptInvoke(long id, int slot) {
734 rsnScriptInvoke(mContext, id, slot);
737 native void rsnScriptForEach(long con, long id, int slot, long[] ains,
738 long aout, byte[] params, int[] limits);
740 synchronized void nScriptForEach(long id, int slot, long[] ains, long aout,
741 byte[] params, int[] limits) {
743 rsnScriptForEach(mContext, id, slot, ains, aout, params, limits);
746 native void rsnScriptReduce(long con, long id, int slot, long ain,
747 long aout, int[] limits);
748 synchronized void nScriptReduce(long id, int slot, long ain, long aout,
751 rsnScriptReduce(mContext, id, slot, ain, aout, limits);
754 native void rsnScriptInvokeV(long con, long id, int slot, byte[] params);
755 synchronized void nScriptInvokeV(long id, int slot, byte[] params) {
757 rsnScriptInvokeV(mContext, id, slot, params);
760 native void rsnScriptSetVarI(long con, long id, int slot, int val);
761 synchronized void nScriptSetVarI(long id, int slot, int val) {
763 rsnScriptSetVarI(mContext, id, slot, val);
765 native int rsnScriptGetVarI(long con, long id, int slot);
766 synchronized int nScriptGetVarI(long id, int slot) {
768 return rsnScriptGetVarI(mContext, id, slot);
771 native void rsnScriptSetVarJ(long con, long id, int slot, long val);
772 synchronized void nScriptSetVarJ(long id, int slot, long val) {
774 rsnScriptSetVarJ(mContext, id, slot, val);
776 native long rsnScriptGetVarJ(long con, long id, int slot);
777 synchronized long nScriptGetVarJ(long id, int slot) {
779 return rsnScriptGetVarJ(mContext, id, slot);
782 native void rsnScriptSetVarF(long con, long id, int slot, float val);
783 synchronized void nScriptSetVarF(long id, int slot, float val) {
785 rsnScriptSetVarF(mContext, id, slot, val);
787 native float rsnScriptGetVarF(long con, long id, int slot);
788 synchronized float nScriptGetVarF(long id, int slot) {
790 return rsnScriptGetVarF(mContext, id, slot);
792 native void rsnScriptSetVarD(long con, long id, int slot, double val);
793 synchronized void nScriptSetVarD(long id, int slot, double val) {
795 rsnScriptSetVarD(mContext, id, slot, val);
797 native double rsnScriptGetVarD(long con, long id, int slot);
798 synchronized double nScriptGetVarD(long id, int slot) {
800 return rsnScriptGetVarD(mContext, id, slot);
802 native void rsnScriptSetVarV(long con, long id, int slot, byte[] val);
803 synchronized void nScriptSetVarV(long id, int slot, byte[] val) {
805 rsnScriptSetVarV(mContext, id, slot, val);
807 native void rsnScriptGetVarV(long con, long id, int slot, byte[] val);
808 synchronized void nScriptGetVarV(long id, int slot, byte[] val) {
810 rsnScriptGetVarV(mContext, id, slot, val);
812 native void rsnScriptSetVarVE(long con, long id, int slot, byte[] val,
814 synchronized void nScriptSetVarVE(long id, int slot, byte[] val,
815 long e, int[] dims) {
817 rsnScriptSetVarVE(mContext, id, slot, val, e, dims);
819 native void rsnScriptSetVarObj(long con, long id, int slot, long val);
820 synchronized void nScriptSetVarObj(long id, int slot, long val) {
822 rsnScriptSetVarObj(mContext, id, slot, val);
825 native long rsnScriptCCreate(long con, String resName, String cacheDir,
826 byte[] script, int length);
827 synchronized long nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
829 return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
832 native long rsnScriptIntrinsicCreate(long con, int id, long eid);
833 synchronized long nScriptIntrinsicCreate(int id, long eid) {
835 return rsnScriptIntrinsicCreate(mContext, id, eid);
838 native long rsnScriptKernelIDCreate(long con, long sid, int slot, int sig);
839 synchronized long nScriptKernelIDCreate(long sid, int slot, int sig) {
841 return rsnScriptKernelIDCreate(mContext, sid, slot, sig);
844 native long rsnScriptInvokeIDCreate(long con, long sid, int slot);
845 synchronized long nScriptInvokeIDCreate(long sid, int slot) {
847 return rsnScriptInvokeIDCreate(mContext, sid, slot);
850 native long rsnScriptFieldIDCreate(long con, long sid, int slot);
851 synchronized long nScriptFieldIDCreate(long sid, int slot) {
853 return rsnScriptFieldIDCreate(mContext, sid, slot);
856 native long rsnScriptGroupCreate(long con, long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types);
857 synchronized long nScriptGroupCreate(long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types) {
859 return rsnScriptGroupCreate(mContext, kernels, src, dstk, dstf, types);
862 native void rsnScriptGroupSetInput(long con, long group, long kernel, long alloc);
863 synchronized void nScriptGroupSetInput(long group, long kernel, long alloc) {
865 rsnScriptGroupSetInput(mContext, group, kernel, alloc);
868 native void rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc);
869 synchronized void nScriptGroupSetOutput(long group, long kernel, long alloc) {
871 rsnScriptGroupSetOutput(mContext, group, kernel, alloc);
874 native void rsnScriptGroupExecute(long con, long group);
875 synchronized void nScriptGroupExecute(long group) {
877 rsnScriptGroupExecute(mContext, group);
880 native long rsnSamplerCreate(long con, int magFilter, int minFilter,
881 int wrapS, int wrapT, int wrapR, float aniso);
882 synchronized long nSamplerCreate(int magFilter, int minFilter,
883 int wrapS, int wrapT, int wrapR, float aniso) {
885 return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
888 native long rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a,
889 boolean depthMask, boolean dither,
890 int srcMode, int dstMode, int depthFunc);
891 synchronized long nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
892 boolean depthMask, boolean dither,
893 int srcMode, int dstMode, int depthFunc) {
895 return rsnProgramStoreCreate(mContext, r, g, b, a, depthMask, dither, srcMode,
899 native long rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode);
900 synchronized long nProgramRasterCreate(boolean pointSprite, int cullMode) {
902 return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
905 native void rsnProgramBindConstants(long con, long pv, int slot, long mID);
906 synchronized void nProgramBindConstants(long pv, int slot, long mID) {
908 rsnProgramBindConstants(mContext, pv, slot, mID);
910 native void rsnProgramBindTexture(long con, long vpf, int slot, long a);
911 synchronized void nProgramBindTexture(long vpf, int slot, long a) {
913 rsnProgramBindTexture(mContext, vpf, slot, a);
915 native void rsnProgramBindSampler(long con, long vpf, int slot, long s);
916 synchronized void nProgramBindSampler(long vpf, int slot, long s) {
918 rsnProgramBindSampler(mContext, vpf, slot, s);
920 native long rsnProgramFragmentCreate(long con, String shader, String[] texNames, long[] params);
921 synchronized long nProgramFragmentCreate(String shader, String[] texNames, long[] params) {
923 return rsnProgramFragmentCreate(mContext, shader, texNames, params);
925 native long rsnProgramVertexCreate(long con, String shader, String[] texNames, long[] params);
926 synchronized long nProgramVertexCreate(String shader, String[] texNames, long[] params) {
928 return rsnProgramVertexCreate(mContext, shader, texNames, params);
931 native long rsnMeshCreate(long con, long[] vtx, long[] idx, int[] prim);
932 synchronized long nMeshCreate(long[] vtx, long[] idx, int[] prim) {
934 return rsnMeshCreate(mContext, vtx, idx, prim);
936 native int rsnMeshGetVertexBufferCount(long con, long id);
937 synchronized int nMeshGetVertexBufferCount(long id) {
939 return rsnMeshGetVertexBufferCount(mContext, id);
941 native int rsnMeshGetIndexCount(long con, long id);
942 synchronized int nMeshGetIndexCount(long id) {
944 return rsnMeshGetIndexCount(mContext, id);
946 native void rsnMeshGetVertices(long con, long id, long[] vtxIds, int vtxIdCount);
947 synchronized void nMeshGetVertices(long id, long[] vtxIds, int vtxIdCount) {
949 rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
951 native void rsnMeshGetIndices(long con, long id, long[] idxIds, int[] primitives, int vtxIdCount);
952 synchronized void nMeshGetIndices(long id, long[] idxIds, int[] primitives, int vtxIdCount) {
954 rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
957 native void rsnScriptIntrinsicBLAS_Single(long con, long id, int func, int TransA,
958 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
959 float alpha, long A, long B, float beta, long C, int incX, int incY,
961 synchronized void nScriptIntrinsicBLAS_Single(long id, int func, int TransA,
962 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
963 float alpha, long A, long B, float beta, long C, int incX, int incY,
966 rsnScriptIntrinsicBLAS_Single(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
969 native void rsnScriptIntrinsicBLAS_Double(long con, long id, int func, int TransA,
970 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
971 double alpha, long A, long B, double beta, long C, int incX, int incY,
973 synchronized void nScriptIntrinsicBLAS_Double(long id, int func, int TransA,
974 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
975 double alpha, long A, long B, double beta, long C, int incX, int incY,
978 rsnScriptIntrinsicBLAS_Double(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
981 native void rsnScriptIntrinsicBLAS_Complex(long con, long id, int func, int TransA,
982 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
983 float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
985 synchronized void nScriptIntrinsicBLAS_Complex(long id, int func, int TransA,
986 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
987 float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
990 rsnScriptIntrinsicBLAS_Complex(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
993 native void rsnScriptIntrinsicBLAS_Z(long con, long id, int func, int TransA,
994 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
995 double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
997 synchronized void nScriptIntrinsicBLAS_Z(long id, int func, int TransA,
998 int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
999 double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
1002 rsnScriptIntrinsicBLAS_Z(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
1005 native void rsnScriptIntrinsicBLAS_BNNM(long con, long id, int M, int N, int K,
1006 long A, int a_offset, long B, int b_offset, long C, int c_offset,
1008 synchronized void nScriptIntrinsicBLAS_BNNM(long id, int M, int N, int K,
1009 long A, int a_offset, long B, int b_offset, long C, int c_offset,
1012 rsnScriptIntrinsicBLAS_BNNM(mContext, id, M, N, K, A, a_offset, B, b_offset, C, c_offset, c_mult_int);
1019 private boolean mDestroyed = false;
1021 @SuppressWarnings({"FieldCanBeLocal"})
1022 MessageThread mMessageThread;
1024 Element mElement_U8;
1025 Element mElement_I8;
1026 Element mElement_U16;
1027 Element mElement_I16;
1028 Element mElement_U32;
1029 Element mElement_I32;
1030 Element mElement_U64;
1031 Element mElement_I64;
1032 Element mElement_F16;
1033 Element mElement_F32;
1034 Element mElement_F64;
1035 Element mElement_BOOLEAN;
1037 Element mElement_ELEMENT;
1038 Element mElement_TYPE;
1039 Element mElement_ALLOCATION;
1040 Element mElement_SAMPLER;
1041 Element mElement_SCRIPT;
1042 Element mElement_MESH;
1043 Element mElement_PROGRAM_FRAGMENT;
1044 Element mElement_PROGRAM_VERTEX;
1045 Element mElement_PROGRAM_RASTER;
1046 Element mElement_PROGRAM_STORE;
1047 Element mElement_FONT;
1049 Element mElement_A_8;
1050 Element mElement_RGB_565;
1051 Element mElement_RGB_888;
1052 Element mElement_RGBA_5551;
1053 Element mElement_RGBA_4444;
1054 Element mElement_RGBA_8888;
1056 Element mElement_HALF_2;
1057 Element mElement_HALF_3;
1058 Element mElement_HALF_4;
1060 Element mElement_FLOAT_2;
1061 Element mElement_FLOAT_3;
1062 Element mElement_FLOAT_4;
1064 Element mElement_DOUBLE_2;
1065 Element mElement_DOUBLE_3;
1066 Element mElement_DOUBLE_4;
1068 Element mElement_UCHAR_2;
1069 Element mElement_UCHAR_3;
1070 Element mElement_UCHAR_4;
1072 Element mElement_CHAR_2;
1073 Element mElement_CHAR_3;
1074 Element mElement_CHAR_4;
1076 Element mElement_USHORT_2;
1077 Element mElement_USHORT_3;
1078 Element mElement_USHORT_4;
1080 Element mElement_SHORT_2;
1081 Element mElement_SHORT_3;
1082 Element mElement_SHORT_4;
1084 Element mElement_UINT_2;
1085 Element mElement_UINT_3;
1086 Element mElement_UINT_4;
1088 Element mElement_INT_2;
1089 Element mElement_INT_3;
1090 Element mElement_INT_4;
1092 Element mElement_ULONG_2;
1093 Element mElement_ULONG_3;
1094 Element mElement_ULONG_4;
1096 Element mElement_LONG_2;
1097 Element mElement_LONG_3;
1098 Element mElement_LONG_4;
1100 Element mElement_YUV;
1102 Element mElement_MATRIX_4X4;
1103 Element mElement_MATRIX_3X3;
1104 Element mElement_MATRIX_2X2;
1106 Sampler mSampler_CLAMP_NEAREST;
1107 Sampler mSampler_CLAMP_LINEAR;
1108 Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
1109 Sampler mSampler_WRAP_NEAREST;
1110 Sampler mSampler_WRAP_LINEAR;
1111 Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
1112 Sampler mSampler_MIRRORED_REPEAT_NEAREST;
1113 Sampler mSampler_MIRRORED_REPEAT_LINEAR;
1114 Sampler mSampler_MIRRORED_REPEAT_LINEAR_MIP_LINEAR;
1116 ProgramStore mProgramStore_BLEND_NONE_DEPTH_TEST;
1117 ProgramStore mProgramStore_BLEND_NONE_DEPTH_NO_DEPTH;
1118 ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_TEST;
1119 ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_NO_DEPTH;
1121 ProgramRaster mProgramRaster_CULL_BACK;
1122 ProgramRaster mProgramRaster_CULL_FRONT;
1123 ProgramRaster mProgramRaster_CULL_NONE;
1125 ///////////////////////////////////////////////////////////////////////////////////
1129 * The base class from which an application should derive in order
1130 * to receive RS messages from scripts. When a script calls {@code
1131 * rsSendToClient}, the data fields will be filled, and the run
1132 * method will be called on a separate thread. This will occur
1133 * some time after {@code rsSendToClient} completes in the script,
1134 * as {@code rsSendToClient} is asynchronous. Message handlers are
1135 * not guaranteed to have completed when {@link
1136 * android.renderscript.RenderScript#finish} returns.
1139 public static class RSMessageHandler implements Runnable {
1140 protected int[] mData;
1142 protected int mLength;
1147 * If an application is expecting messages, it should set this
1148 * field to an instance of {@link RSMessageHandler}. This
1149 * instance will receive all the user messages sent from {@code
1150 * sendToClient} by scripts from this context.
1153 RSMessageHandler mMessageCallback = null;
1155 public void setMessageHandler(RSMessageHandler msg) {
1156 mMessageCallback = msg;
1158 public RSMessageHandler getMessageHandler() {
1159 return mMessageCallback;
1163 * Place a message into the message queue to be sent back to the message
1164 * handler once all previous commands have been executed.
1169 public void sendMessage(int id, int[] data) {
1170 nContextSendMessage(id, data);
1174 * The runtime error handler base class. An application should derive from this class
1175 * if it wishes to install an error handler. When errors occur at runtime,
1176 * the fields in this class will be filled, and the run method will be called.
1179 public static class RSErrorHandler implements Runnable {
1180 protected String mErrorMessage;
1181 protected int mErrorNum;
1187 * Application Error handler. All runtime errors will be dispatched to the
1188 * instance of RSAsyncError set here. If this field is null a
1189 * {@link RSRuntimeException} will instead be thrown with details about the error.
1190 * This will cause program termaination.
1193 RSErrorHandler mErrorCallback = null;
1195 public void setErrorHandler(RSErrorHandler msg) {
1196 mErrorCallback = msg;
1198 public RSErrorHandler getErrorHandler() {
1199 return mErrorCallback;
1203 * RenderScript worker thread priority enumeration. The default value is
1204 * NORMAL. Applications wishing to do background processing should set
1205 * their priority to LOW to avoid starving forground processes.
1207 public enum Priority {
1208 // These values used to represent official thread priority values
1209 // now they are simply enums to be used by the runtime side
1219 void validateObject(BaseObj o) {
1221 if (o.mRS != this) {
1222 throw new RSIllegalArgumentException("Attempting to use an object across contexts.");
1228 if (mContext == 0) {
1229 throw new RSInvalidStateException("Calling RS with no Context active.");
1235 * Change the priority of the worker threads for this context.
1237 * @param p New priority to be set.
1239 public void setPriority(Priority p) {
1241 nContextSetPriority(p.mID);
1244 static class MessageThread extends Thread {
1246 boolean mRun = true;
1247 int[] mAuxData = new int[2];
1249 static final int RS_MESSAGE_TO_CLIENT_NONE = 0;
1250 static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1;
1251 static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2;
1252 static final int RS_MESSAGE_TO_CLIENT_ERROR = 3;
1253 static final int RS_MESSAGE_TO_CLIENT_USER = 4;
1254 static final int RS_MESSAGE_TO_CLIENT_NEW_BUFFER = 5;
1256 static final int RS_ERROR_FATAL_DEBUG = 0x0800;
1257 static final int RS_ERROR_FATAL_UNKNOWN = 0x1000;
1259 MessageThread(RenderScript rs) {
1260 super("RSMessageThread");
1266 // This function is a temporary solution. The final solution will
1267 // used typed allocations where the message id is the type indicator.
1268 int[] rbuf = new int[16];
1269 mRS.nContextInitToClient(mRS.mContext);
1272 int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData);
1273 int size = mAuxData[1];
1274 int subID = mAuxData[0];
1276 if (msg == RS_MESSAGE_TO_CLIENT_USER) {
1277 if ((size>>2) >= rbuf.length) {
1278 rbuf = new int[(size + 3) >> 2];
1280 if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1281 RS_MESSAGE_TO_CLIENT_USER) {
1282 throw new RSDriverException("Error processing message from RenderScript.");
1285 if(mRS.mMessageCallback != null) {
1286 mRS.mMessageCallback.mData = rbuf;
1287 mRS.mMessageCallback.mID = subID;
1288 mRS.mMessageCallback.mLength = size;
1289 mRS.mMessageCallback.run();
1291 throw new RSInvalidStateException("Received a message from the script with no message handler installed.");
1296 if (msg == RS_MESSAGE_TO_CLIENT_ERROR) {
1297 String e = mRS.nContextGetErrorMessage(mRS.mContext);
1299 // Throw RSRuntimeException under the following conditions:
1301 // 1) It is an unknown fatal error.
1302 // 2) It is a debug fatal error, and we are not in a
1304 // 3) It is a debug fatal error, and we do not have an
1306 if (subID >= RS_ERROR_FATAL_UNKNOWN ||
1307 (subID >= RS_ERROR_FATAL_DEBUG &&
1308 (mRS.mContextType != ContextType.DEBUG ||
1309 mRS.mErrorCallback == null))) {
1310 throw new RSRuntimeException("Fatal error " + subID + ", details: " + e);
1313 if(mRS.mErrorCallback != null) {
1314 mRS.mErrorCallback.mErrorMessage = e;
1315 mRS.mErrorCallback.mErrorNum = subID;
1316 mRS.mErrorCallback.run();
1318 android.util.Log.e(LOG_TAG, "non fatal RS error, " + e);
1319 // Do not throw here. In these cases, we do not have
1325 if (msg == RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1326 if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1327 RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1328 throw new RSDriverException("Error processing message from RenderScript.");
1330 long bufferID = ((long)rbuf[1] << 32L) + ((long)rbuf[0] & 0xffffffffL);
1331 Allocation.sendBufferNotification(bufferID);
1336 // But we want to avoid starving other threads during
1337 // teardown by yielding until the next line in the destructor
1338 // can execute to set mRun = false
1341 } catch(InterruptedException e) {
1344 //Log.d(LOG_TAG, "MessageThread exiting.");
1348 RenderScript(Context ctx) {
1349 mContextType = ContextType.NORMAL;
1351 mApplicationContext = ctx.getApplicationContext();
1353 mRWLock = new ReentrantReadWriteLock();
1355 registerNativeAllocation.invoke(sRuntime, 4 * 1024 * 1024); // 4MB for GC sake
1356 } catch (Exception e) {
1357 Log.e(RenderScript.LOG_TAG, "Couldn't invoke registerNativeAllocation:" + e);
1358 throw new RSRuntimeException("Couldn't invoke registerNativeAllocation:" + e);
1364 * Gets the application context associated with the RenderScript context.
1366 * @return The application context.
1368 public final Context getApplicationContext() {
1369 return mApplicationContext;
1373 * Create a RenderScript context.
1375 * @param ctx The context.
1376 * @return RenderScript
1378 private static RenderScript internalCreate(Context ctx, int sdkVersion, ContextType ct, int flags) {
1379 if (!sInitialized) {
1380 Log.e(LOG_TAG, "RenderScript.create() called when disabled; someone is likely to crash");
1384 if ((flags & ~(CREATE_FLAG_LOW_LATENCY | CREATE_FLAG_LOW_POWER |
1385 CREATE_FLAG_WAIT_FOR_ATTACH | CREATE_FLAG_OPT_LEVEL_0)) != 0) {
1386 throw new RSIllegalArgumentException("Invalid flags passed.");
1389 RenderScript rs = new RenderScript(ctx);
1391 rs.mDev = rs.nDeviceCreate();
1392 rs.mContext = rs.nContextCreate(rs.mDev, flags, sdkVersion, ct.mID);
1393 rs.mContextType = ct;
1394 rs.mContextFlags = flags;
1395 rs.mContextSdkVersion = sdkVersion;
1396 if (rs.mContext == 0) {
1397 throw new RSDriverException("Failed to create RS context.");
1400 // set up cache directory for entire context
1401 final String CACHE_PATH = "com.android.renderscript.cache";
1402 File f = new File(RenderScriptCacheDir.mCacheDir, CACHE_PATH);
1403 String mCachePath = f.getAbsolutePath();
1405 rs.nContextSetCacheDir(mCachePath);
1407 rs.mMessageThread = new MessageThread(rs);
1408 rs.mMessageThread.start();
1413 * calls create(ctx, ContextType.NORMAL, CREATE_FLAG_NONE)
1415 * See documentation for @create for details
1417 * @param ctx The context.
1418 * @return RenderScript
1420 public static RenderScript create(Context ctx) {
1421 return create(ctx, ContextType.NORMAL);
1425 * calls create(ctx, ct, CREATE_FLAG_NONE)
1427 * See documentation for @create for details
1429 * @param ctx The context.
1430 * @param ct The type of context to be created.
1431 * @return RenderScript
1433 public static RenderScript create(Context ctx, ContextType ct) {
1434 return create(ctx, ct, CREATE_FLAG_NONE);
1439 * Gets or creates a RenderScript context of the specified type.
1441 * The returned context will be cached for future reuse within
1442 * the process. When an application is finished using
1443 * RenderScript it should call releaseAllContexts()
1445 * A process context is a context designed for easy creation and
1446 * lifecycle management. Multiple calls to this function will
1447 * return the same object provided they are called with the same
1448 * options. This allows it to be used any time a RenderScript
1449 * context is needed.
1451 * Prior to API 23 this always created a new context.
1453 * @param ctx The context.
1454 * @param ct The type of context to be created.
1455 * @param flags The OR of the CREATE_FLAG_* options desired
1456 * @return RenderScript
1458 public static RenderScript create(Context ctx, ContextType ct, int flags) {
1459 int v = ctx.getApplicationInfo().targetSdkVersion;
1460 return create(ctx, v, ct, flags);
1464 * calls create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE)
1466 * Used by the RenderScriptThunker to maintain backward compatibility.
1469 * @param ctx The context.
1470 * @param sdkVersion The target SDK Version.
1471 * @return RenderScript
1473 public static RenderScript create(Context ctx, int sdkVersion) {
1474 return create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE);
1478 * Gets or creates a RenderScript context of the specified type.
1480 * @param ctx The context.
1481 * @param ct The type of context to be created.
1482 * @param sdkVersion The target SDK Version.
1483 * @param flags The OR of the CREATE_FLAG_* options desired
1484 * @return RenderScript
1486 private static RenderScript create(Context ctx, int sdkVersion, ContextType ct, int flags) {
1487 if (sdkVersion < 23) {
1488 return internalCreate(ctx, sdkVersion, ct, flags);
1491 synchronized (mProcessContextList) {
1492 for (RenderScript prs : mProcessContextList) {
1493 if ((prs.mContextType == ct) &&
1494 (prs.mContextFlags == flags) &&
1495 (prs.mContextSdkVersion == sdkVersion)) {
1501 RenderScript prs = internalCreate(ctx, sdkVersion, ct, flags);
1502 prs.mIsProcessContext = true;
1503 mProcessContextList.add(prs);
1509 * Releases all the process contexts. This is the same as
1510 * calling .destroy() on each unique context retreived with
1511 * create(...). If no contexts have been created this
1512 * function does nothing.
1514 * Typically you call this when your application is losing focus
1515 * and will not be using a context for some time.
1517 * This has no effect on a context created with
1518 * createMultiContext()
1520 public static void releaseAllContexts() {
1521 ArrayList<RenderScript> oldList;
1522 synchronized (mProcessContextList) {
1523 oldList = mProcessContextList;
1524 mProcessContextList = new ArrayList<RenderScript>();
1527 for (RenderScript prs : oldList) {
1528 prs.mIsProcessContext = false;
1537 * Create a RenderScript context.
1539 * This is an advanced function intended for applications which
1540 * need to create more than one RenderScript context to be used
1543 * If you need a single context please use create()
1545 * @param ctx The context.
1546 * @return RenderScript
1548 public static RenderScript createMultiContext(Context ctx, ContextType ct, int flags, int API_number) {
1549 return internalCreate(ctx, API_number, ct, flags);
1554 * Print the currently available debugging information about the state of
1555 * the RS context to the log.
1558 public void contextDump() {
1564 * Wait for any pending asynchronous opeations (such as copies to a RS
1565 * allocation or RS script executions) to complete.
1568 public void finish() {
1572 private void helpDestroy() {
1573 boolean shouldDestroy = false;
1574 synchronized(this) {
1576 shouldDestroy = true;
1581 if (shouldDestroy) {
1584 nContextDeinitToClient(mContext);
1585 mMessageThread.mRun = false;
1587 mMessageThread.join();
1588 } catch(InterruptedException e) {
1593 nDeviceDestroy(mDev);
1598 protected void finalize() throws Throwable {
1605 * Destroys this RenderScript context. Once this function is called,
1606 * using this context or any objects belonging to this context is
1609 * API 23+, this function is a NOP if the context was created
1610 * with create(). Please use releaseAllContexts() to clean up
1611 * contexts created with the create function.
1614 public void destroy() {
1615 if (mIsProcessContext) {
1616 // users cannot destroy a process context
1624 return mContext != 0;
1627 long safeID(BaseObj o) {
1629 return o.getID(this);