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