SurfaceTexture.java revision 0dc146be5a6cd0c33910d5b18885df46873a93cb
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.graphics; 18 19import java.lang.ref.WeakReference; 20 21import android.os.Handler; 22import android.os.Looper; 23import android.os.Message; 24import android.view.Surface; 25 26/** 27 * Captures frames from an image stream as an OpenGL ES texture. 28 * 29 * <p>The image stream may come from either camera preview or video decode. A SurfaceTexture 30 * may be used in place of a SurfaceHolder when specifying the output destination of a 31 * {@link android.hardware.Camera} or {@link android.media.MediaPlayer} 32 * object. Doing so will cause all the frames from the image stream to be sent to the 33 * SurfaceTexture object rather than to the device's display. When {@link #updateTexImage} is 34 * called, the contents of the texture object specified when the SurfaceTexture was created are 35 * updated to contain the most recent image from the image stream. This may cause some frames of 36 * the stream to be skipped. 37 * 38 * <p>When sampling from the texture one should first transform the texture coordinates using the 39 * matrix queried via {@link #getTransformMatrix(float[])}. The transform matrix may change each 40 * time {@link #updateTexImage} is called, so it should be re-queried each time the texture image 41 * is updated. 42 * This matrix transforms traditional 2D OpenGL ES texture coordinate column vectors of the form (s, 43 * t, 0, 1) where s and t are on the inclusive interval [0, 1] to the proper sampling location in 44 * the streamed texture. This transform compensates for any properties of the image stream source 45 * that cause it to appear different from a traditional OpenGL ES texture. For example, sampling 46 * from the bottom left corner of the image can be accomplished by transforming the column vector 47 * (0, 0, 0, 1) using the queried matrix, while sampling from the top right corner of the image can 48 * be done by transforming (1, 1, 0, 1). 49 * 50 * <p>The texture object uses the GL_TEXTURE_EXTERNAL_OES texture target, which is defined by the 51 * <a href="http://www.khronos.org/registry/gles/extensions/OES/OES_EGL_image_external.txt"> 52 * GL_OES_EGL_image_external</a> OpenGL ES extension. This limits how the texture may be used. 53 * Each time the texture is bound it must be bound to the GL_TEXTURE_EXTERNAL_OES target rather than 54 * the GL_TEXTURE_2D target. Additionally, any OpenGL ES 2.0 shader that samples from the texture 55 * must declare its use of this extension using, for example, an "#extension 56 * GL_OES_EGL_image_external : require" directive. Such shaders must also access the texture using 57 * the samplerExternalOES GLSL sampler type. 58 * 59 * <p>SurfaceTexture objects may be created on any thread. {@link #updateTexImage} may only be 60 * called on the thread with the OpenGL ES context that contains the texture object. The 61 * frame-available callback is called on an arbitrary thread, so unless special care is taken {@link 62 * #updateTexImage} should not be called directly from the callback. 63 */ 64public class SurfaceTexture { 65 66 private EventHandler mEventHandler; 67 private OnFrameAvailableListener mOnFrameAvailableListener; 68 69 /** 70 * These fields are used by native code, do not access or modify. 71 */ 72 private long mSurfaceTexture; 73 private long mProducer; 74 private long mFrameAvailableListener; 75 76 /** 77 * Callback interface for being notified that a new stream frame is available. 78 */ 79 public interface OnFrameAvailableListener { 80 void onFrameAvailable(SurfaceTexture surfaceTexture); 81 } 82 83 /** 84 * Exception thrown when a SurfaceTexture couldn't be created or resized. 85 * 86 * @deprecated No longer thrown. {@link Surface.OutOfResourcesException} is used instead. 87 */ 88 @SuppressWarnings("serial") 89 @Deprecated 90 public static class OutOfResourcesException extends Exception { 91 public OutOfResourcesException() { 92 } 93 public OutOfResourcesException(String name) { 94 super(name); 95 } 96 } 97 98 /** 99 * Construct a new SurfaceTexture to stream images to a given OpenGL texture. 100 * 101 * @param texName the OpenGL texture object name (e.g. generated via glGenTextures) 102 * 103 * @throws OutOfResourcesException If the SurfaceTexture cannot be created. 104 */ 105 public SurfaceTexture(int texName) { 106 init(texName, false); 107 } 108 109 /** 110 * Construct a new SurfaceTexture to stream images to a given OpenGL texture. 111 * 112 * In single buffered mode the application is responsible for serializing access to the image 113 * content buffer. Each time the image content is to be updated, the 114 * {@link #releaseTexImage()} method must be called before the image content producer takes 115 * ownership of the buffer. For example, when producing image content with the NDK 116 * ANativeWindow_lock and ANativeWindow_unlockAndPost functions, {@link #releaseTexImage()} 117 * must be called before each ANativeWindow_lock, or that call will fail. When producing 118 * image content with OpenGL ES, {@link #releaseTexImage()} must be called before the first 119 * OpenGL ES function call each frame. 120 * 121 * @param texName the OpenGL texture object name (e.g. generated via glGenTextures) 122 * @param singleBufferMode whether the SurfaceTexture will be in single buffered mode. 123 * 124 * @throws throws OutOfResourcesException If the SurfaceTexture cannot be created. 125 */ 126 public SurfaceTexture(int texName, boolean singleBufferMode) { 127 init(texName, singleBufferMode); 128 } 129 130 /** 131 * Register a callback to be invoked when a new image frame becomes available to the 132 * SurfaceTexture. Note that this callback may be called on an arbitrary thread, so it is not 133 * safe to call {@link #updateTexImage} without first binding the OpenGL ES context to the 134 * thread invoking the callback. 135 */ 136 public void setOnFrameAvailableListener(OnFrameAvailableListener l) { 137 mOnFrameAvailableListener = l; 138 } 139 140 /** 141 * Set the default size of the image buffers. The image producer may override the buffer size, 142 * in which case the producer-set buffer size will be used, not the default size set by this 143 * method. Both video and camera based image producers do override the size. This method may 144 * be used to set the image size when producing images with {@link android.graphics.Canvas} (via 145 * {@link android.view.Surface#lockCanvas}), or OpenGL ES (via an EGLSurface). 146 * 147 * The new default buffer size will take effect the next time the image producer requests a 148 * buffer to fill. For {@link android.graphics.Canvas} this will be the next time {@link 149 * android.view.Surface#lockCanvas} is called. For OpenGL ES, the EGLSurface should be 150 * destroyed (via eglDestroySurface), made not-current (via eglMakeCurrent), and then recreated 151 * (via eglCreateWindowSurface) to ensure that the new default size has taken effect. 152 * 153 * The width and height parameters must be no greater than the minimum of 154 * GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see 155 * {@link javax.microedition.khronos.opengles.GL10#glGetIntegerv glGetIntegerv}). 156 * An error due to invalid dimensions might not be reported until 157 * updateTexImage() is called. 158 */ 159 public void setDefaultBufferSize(int width, int height) { 160 nativeSetDefaultBufferSize(width, height); 161 } 162 163 /** 164 * Update the texture image to the most recent frame from the image stream. This may only be 165 * called while the OpenGL ES context that owns the texture is current on the calling thread. 166 * It will implicitly bind its texture to the GL_TEXTURE_EXTERNAL_OES texture target. 167 */ 168 public void updateTexImage() { 169 nativeUpdateTexImage(); 170 } 171 172 /** 173 * Releases the the texture content. This is needed in single buffered mode to allow the image 174 * content producer to take ownership of the image buffer. 175 * For more information see {@link #SurfaceTexture(int, boolean)}. 176 */ 177 public void releaseTexImage() { 178 nativeReleaseTexImage(); 179 } 180 181 /** 182 * Detach the SurfaceTexture from the OpenGL ES context that owns the OpenGL ES texture object. 183 * This call must be made with the OpenGL ES context current on the calling thread. The OpenGL 184 * ES texture object will be deleted as a result of this call. After calling this method all 185 * calls to {@link #updateTexImage} will throw an {@link java.lang.IllegalStateException} until 186 * a successful call to {@link #attachToGLContext} is made. 187 * 188 * This can be used to access the SurfaceTexture image contents from multiple OpenGL ES 189 * contexts. Note, however, that the image contents are only accessible from one OpenGL ES 190 * context at a time. 191 */ 192 public void detachFromGLContext() { 193 int err = nativeDetachFromGLContext(); 194 if (err != 0) { 195 throw new RuntimeException("Error during detachFromGLContext (see logcat for details)"); 196 } 197 } 198 199 /** 200 * Attach the SurfaceTexture to the OpenGL ES context that is current on the calling thread. A 201 * new OpenGL ES texture object is created and populated with the SurfaceTexture image frame 202 * that was current at the time of the last call to {@link #detachFromGLContext}. This new 203 * texture is bound to the GL_TEXTURE_EXTERNAL_OES texture target. 204 * 205 * This can be used to access the SurfaceTexture image contents from multiple OpenGL ES 206 * contexts. Note, however, that the image contents are only accessible from one OpenGL ES 207 * context at a time. 208 * 209 * @param texName The name of the OpenGL ES texture that will be created. This texture name 210 * must be unusued in the OpenGL ES context that is current on the calling thread. 211 */ 212 public void attachToGLContext(int texName) { 213 int err = nativeAttachToGLContext(texName); 214 if (err != 0) { 215 throw new RuntimeException("Error during attachToGLContext (see logcat for details)"); 216 } 217 } 218 219 /** 220 * Retrieve the 4x4 texture coordinate transform matrix associated with the texture image set by 221 * the most recent call to updateTexImage. 222 * 223 * This transform matrix maps 2D homogeneous texture coordinates of the form (s, t, 0, 1) with s 224 * and t in the inclusive range [0, 1] to the texture coordinate that should be used to sample 225 * that location from the texture. Sampling the texture outside of the range of this transform 226 * is undefined. 227 * 228 * The matrix is stored in column-major order so that it may be passed directly to OpenGL ES via 229 * the glLoadMatrixf or glUniformMatrix4fv functions. 230 * 231 * @param mtx the array into which the 4x4 matrix will be stored. The array must have exactly 232 * 16 elements. 233 */ 234 public void getTransformMatrix(float[] mtx) { 235 // Note we intentionally don't check mtx for null, so this will result in a 236 // NullPointerException. But it's safe because it happens before the call to native. 237 if (mtx.length != 16) { 238 throw new IllegalArgumentException(); 239 } 240 nativeGetTransformMatrix(mtx); 241 } 242 243 /** 244 * Retrieve the timestamp associated with the texture image set by the most recent call to 245 * updateTexImage. 246 * 247 * This timestamp is in nanoseconds, and is normally monotonically increasing. The timestamp 248 * should be unaffected by time-of-day adjustments, and for a camera should be strictly 249 * monotonic but for a MediaPlayer may be reset when the position is set. The 250 * specific meaning and zero point of the timestamp depends on the source providing images to 251 * the SurfaceTexture. Unless otherwise specified by the image source, timestamps cannot 252 * generally be compared across SurfaceTexture instances, or across multiple program 253 * invocations. It is mostly useful for determining time offsets between subsequent frames. 254 */ 255 256 public long getTimestamp() { 257 return nativeGetTimestamp(); 258 } 259 260 /** 261 * release() frees all the buffers and puts the SurfaceTexture into the 262 * 'abandoned' state. Once put in this state the SurfaceTexture can never 263 * leave it. When in the 'abandoned' state, all methods of the 264 * IGraphicBufferProducer interface will fail with the NO_INIT error. 265 * 266 * Note that while calling this method causes all the buffers to be freed 267 * from the perspective of the the SurfaceTexture, if there are additional 268 * references on the buffers (e.g. if a buffer is referenced by a client or 269 * by OpenGL ES as a texture) then those buffer will remain allocated. 270 * 271 * Always call this method when you are done with SurfaceTexture. Failing 272 * to do so may delay resource deallocation for a significant amount of 273 * time. 274 */ 275 public void release() { 276 nativeRelease(); 277 } 278 279 @Override 280 protected void finalize() throws Throwable { 281 try { 282 nativeFinalize(); 283 } finally { 284 super.finalize(); 285 } 286 } 287 288 private class EventHandler extends Handler { 289 public EventHandler(Looper looper) { 290 super(looper); 291 } 292 293 @Override 294 public void handleMessage(Message msg) { 295 if (mOnFrameAvailableListener != null) { 296 mOnFrameAvailableListener.onFrameAvailable(SurfaceTexture.this); 297 } 298 } 299 } 300 301 /** 302 * This method is invoked from native code only. 303 */ 304 @SuppressWarnings({"UnusedDeclaration"}) 305 private static void postEventFromNative(Object selfRef) { 306 WeakReference weakSelf = (WeakReference)selfRef; 307 SurfaceTexture st = (SurfaceTexture)weakSelf.get(); 308 if (st == null) { 309 return; 310 } 311 312 if (st.mEventHandler != null) { 313 Message m = st.mEventHandler.obtainMessage(); 314 st.mEventHandler.sendMessage(m); 315 } 316 } 317 318 private void init(int texName, boolean singleBufferMode) throws Surface.OutOfResourcesException { 319 Looper looper; 320 if ((looper = Looper.myLooper()) != null) { 321 mEventHandler = new EventHandler(looper); 322 } else if ((looper = Looper.getMainLooper()) != null) { 323 mEventHandler = new EventHandler(looper); 324 } else { 325 mEventHandler = null; 326 } 327 nativeInit(texName, singleBufferMode, new WeakReference<SurfaceTexture>(this)); 328 } 329 330 private native void nativeInit(int texName, boolean singleBufferMode, Object weakSelf) 331 throws Surface.OutOfResourcesException; 332 private native void nativeFinalize(); 333 private native void nativeGetTransformMatrix(float[] mtx); 334 private native long nativeGetTimestamp(); 335 private native void nativeSetDefaultBufferSize(int width, int height); 336 private native void nativeUpdateTexImage(); 337 private native void nativeReleaseTexImage(); 338 private native int nativeDetachFromGLContext(); 339 private native int nativeAttachToGLContext(int texName); 340 private native int nativeGetQueuedCount(); 341 private native void nativeRelease(); 342 343 /* 344 * We use a class initializer to allow the native code to cache some 345 * field offsets. 346 */ 347 private static native void nativeClassInit(); 348 static { nativeClassInit(); } 349} 350