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 17 package android.graphics; 18 19 import android.annotation.Nullable; 20 import android.annotation.SuppressLint; 21 import android.compat.annotation.UnsupportedAppUsage; 22 import android.hardware.DataSpace.NamedDataSpace; 23 import android.os.Build; 24 import android.os.Handler; 25 import android.os.Looper; 26 import android.os.Message; 27 import android.view.Surface; 28 29 import java.lang.ref.WeakReference; 30 31 /** 32 * Captures frames from an image stream as an OpenGL ES texture. 33 * 34 * <p>The image stream may come from either camera preview or video decode. A 35 * {@link android.view.Surface} created from a SurfaceTexture can be used as an output 36 * destination for the {@link android.hardware.camera2}, {@link android.media.MediaCodec}, 37 * {@link android.media.MediaPlayer}, and {@link android.renderscript.Allocation} APIs. 38 * When {@link #updateTexImage} is called, the contents of the texture object specified 39 * when the SurfaceTexture was created are updated to contain the most recent image from the image 40 * stream. This may cause some frames of the stream to be skipped. 41 * 42 * <p>A SurfaceTexture may also be used in place of a SurfaceHolder when specifying the output 43 * destination of the older {@link android.hardware.Camera} API. Doing so will cause all the 44 * frames from the image stream to be sent to the SurfaceTexture object rather than to the device's 45 * display. 46 * 47 * <p>When sampling from the texture one should first transform the texture coordinates using the 48 * matrix queried via {@link #getTransformMatrix(float[])}. The transform matrix may change each 49 * time {@link #updateTexImage} is called, so it should be re-queried each time the texture image 50 * is updated. 51 * This matrix transforms traditional 2D OpenGL ES texture coordinate column vectors of the form (s, 52 * t, 0, 1) where s and t are on the inclusive interval [0, 1] to the proper sampling location in 53 * the streamed texture. This transform compensates for any properties of the image stream source 54 * that cause it to appear different from a traditional OpenGL ES texture. For example, sampling 55 * from the bottom left corner of the image can be accomplished by transforming the column vector 56 * (0, 0, 0, 1) using the queried matrix, while sampling from the top right corner of the image can 57 * be done by transforming (1, 1, 0, 1). 58 * 59 * <p>The texture object uses the GL_TEXTURE_EXTERNAL_OES texture target, which is defined by the 60 * <a href="http://www.khronos.org/registry/gles/extensions/OES/OES_EGL_image_external.txt"> 61 * GL_OES_EGL_image_external</a> OpenGL ES extension. This limits how the texture may be used. 62 * Each time the texture is bound it must be bound to the GL_TEXTURE_EXTERNAL_OES target rather than 63 * the GL_TEXTURE_2D target. Additionally, any OpenGL ES 2.0 shader that samples from the texture 64 * must declare its use of this extension using, for example, an "#extension 65 * GL_OES_EGL_image_external : require" directive. Such shaders must also access the texture using 66 * the samplerExternalOES GLSL sampler type. 67 * 68 * <p>SurfaceTexture objects may be created on any thread. {@link #updateTexImage} may only be 69 * called on the thread with the OpenGL ES context that contains the texture object. The 70 * frame-available callback is called on an arbitrary thread, so unless special care is taken {@link 71 * #updateTexImage} should not be called directly from the callback. 72 */ 73 public class SurfaceTexture { 74 private final Looper mCreatorLooper; 75 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 76 private Handler mOnFrameAvailableHandler; 77 78 /** 79 * These fields are used by native code, do not access or modify. 80 */ 81 @UnsupportedAppUsage(trackingBug = 176388660) 82 private long mSurfaceTexture; 83 @UnsupportedAppUsage(trackingBug = 176388660) 84 private long mProducer; 85 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 86 private long mFrameAvailableListener; 87 88 private boolean mIsSingleBuffered; 89 90 /** 91 * Callback interface for being notified that a new stream frame is available. 92 */ 93 public interface OnFrameAvailableListener { onFrameAvailable(SurfaceTexture surfaceTexture)94 void onFrameAvailable(SurfaceTexture surfaceTexture); 95 } 96 97 /** 98 * Exception thrown when a SurfaceTexture couldn't be created or resized. 99 * 100 * @deprecated No longer thrown. {@link android.view.Surface.OutOfResourcesException} 101 * is used instead. 102 */ 103 @SuppressWarnings("serial") 104 @Deprecated 105 public static class OutOfResourcesException extends Exception { OutOfResourcesException()106 public OutOfResourcesException() { 107 } OutOfResourcesException(String name)108 public OutOfResourcesException(String name) { 109 super(name); 110 } 111 } 112 113 /** 114 * Construct a new SurfaceTexture to stream images to a given OpenGL texture. 115 * 116 * @param texName the OpenGL texture object name (e.g. generated via glGenTextures) 117 * 118 * @throws android.view.Surface.OutOfResourcesException If the SurfaceTexture cannot be created. 119 */ SurfaceTexture(int texName)120 public SurfaceTexture(int texName) { 121 this(texName, false); 122 } 123 124 /** 125 * Construct a new SurfaceTexture to stream images to a given OpenGL texture. 126 * <p> 127 * In single buffered mode the application is responsible for serializing access to the image 128 * content buffer. Each time the image content is to be updated, the 129 * {@link #releaseTexImage()} method must be called before the image content producer takes 130 * ownership of the buffer. For example, when producing image content with the NDK 131 * ANativeWindow_lock and ANativeWindow_unlockAndPost functions, {@link #releaseTexImage()} 132 * must be called before each ANativeWindow_lock, or that call will fail. When producing 133 * image content with OpenGL ES, {@link #releaseTexImage()} must be called before the first 134 * OpenGL ES function call each frame. 135 * 136 * @param texName the OpenGL texture object name (e.g. generated via glGenTextures) 137 * @param singleBufferMode whether the SurfaceTexture will be in single buffered mode. 138 * 139 * @throws android.view.Surface.OutOfResourcesException If the SurfaceTexture cannot be created. 140 */ SurfaceTexture(int texName, boolean singleBufferMode)141 public SurfaceTexture(int texName, boolean singleBufferMode) { 142 mCreatorLooper = Looper.myLooper(); 143 mIsSingleBuffered = singleBufferMode; 144 nativeInit(false, texName, singleBufferMode, new WeakReference<SurfaceTexture>(this)); 145 } 146 147 /** 148 * Construct a new SurfaceTexture to stream images to a given OpenGL texture. 149 * <p> 150 * In single buffered mode the application is responsible for serializing access to the image 151 * content buffer. Each time the image content is to be updated, the 152 * {@link #releaseTexImage()} method must be called before the image content producer takes 153 * ownership of the buffer. For example, when producing image content with the NDK 154 * ANativeWindow_lock and ANativeWindow_unlockAndPost functions, {@link #releaseTexImage()} 155 * must be called before each ANativeWindow_lock, or that call will fail. When producing 156 * image content with OpenGL ES, {@link #releaseTexImage()} must be called before the first 157 * OpenGL ES function call each frame. 158 * <p> 159 * Unlike {@link #SurfaceTexture(int, boolean)}, which takes an OpenGL texture object name, 160 * this constructor creates the SurfaceTexture in detached mode. A texture name must be passed 161 * in using {@link #attachToGLContext} before calling {@link #releaseTexImage()} and producing 162 * image content using OpenGL ES. 163 * 164 * @param singleBufferMode whether the SurfaceTexture will be in single buffered mode. 165 * 166 * @throws android.view.Surface.OutOfResourcesException If the SurfaceTexture cannot be created. 167 */ SurfaceTexture(boolean singleBufferMode)168 public SurfaceTexture(boolean singleBufferMode) { 169 mCreatorLooper = Looper.myLooper(); 170 mIsSingleBuffered = singleBufferMode; 171 nativeInit(true, 0, singleBufferMode, new WeakReference<SurfaceTexture>(this)); 172 } 173 174 /** 175 * Register a callback to be invoked when a new image frame becomes available to the 176 * SurfaceTexture. 177 * <p> 178 * The callback may be called on an arbitrary thread, so it is not 179 * safe to call {@link #updateTexImage} without first binding the OpenGL ES context to the 180 * thread invoking the callback. 181 * </p> 182 * 183 * @param listener The listener to use, or null to remove the listener. 184 */ setOnFrameAvailableListener(@ullable OnFrameAvailableListener listener)185 public void setOnFrameAvailableListener(@Nullable OnFrameAvailableListener listener) { 186 setOnFrameAvailableListener(listener, null); 187 } 188 189 /** 190 * Register a callback to be invoked when a new image frame becomes available to the 191 * SurfaceTexture. 192 * <p> 193 * If a handler is specified, the callback will be invoked on that handler's thread. 194 * If no handler is specified, then the callback may be called on an arbitrary thread, 195 * so it is not safe to call {@link #updateTexImage} without first binding the OpenGL ES 196 * context to the thread invoking the callback. 197 * </p> 198 * 199 * @param listener The listener to use, or null to remove the listener. 200 * @param handler The handler on which the listener should be invoked, or null 201 * to use an arbitrary thread. 202 */ setOnFrameAvailableListener(@ullable final OnFrameAvailableListener listener, @Nullable Handler handler)203 public void setOnFrameAvailableListener(@Nullable final OnFrameAvailableListener listener, 204 @Nullable Handler handler) { 205 if (listener != null) { 206 // Although we claim the thread is arbitrary, earlier implementation would 207 // prefer to send the callback on the creating looper or the main looper 208 // so we preserve this behavior here. 209 Looper looper = handler != null ? handler.getLooper() : 210 mCreatorLooper != null ? mCreatorLooper : Looper.getMainLooper(); 211 mOnFrameAvailableHandler = new Handler(looper, null, true /*async*/) { 212 @Override 213 public void handleMessage(Message msg) { 214 listener.onFrameAvailable(SurfaceTexture.this); 215 } 216 }; 217 } else { 218 mOnFrameAvailableHandler = null; 219 } 220 } 221 222 /** 223 * Set the default size of the image buffers. The image producer may override the buffer size, 224 * in which case the producer-set buffer size will be used, not the default size set by this 225 * method. Both video and camera based image producers do override the size. This method may 226 * be used to set the image size when producing images with {@link android.graphics.Canvas} (via 227 * {@link android.view.Surface#lockCanvas}), or OpenGL ES (via an EGLSurface). 228 * <p> 229 * The new default buffer size will take effect the next time the image producer requests a 230 * buffer to fill. For {@link android.graphics.Canvas} this will be the next time {@link 231 * android.view.Surface#lockCanvas} is called. For OpenGL ES, the EGLSurface should be 232 * destroyed (via eglDestroySurface), made not-current (via eglMakeCurrent), and then recreated 233 * (via {@code eglCreateWindowSurface}) to ensure that the new default size has taken effect. 234 * <p> 235 * The width and height parameters must be no greater than the minimum of 236 * {@code GL_MAX_VIEWPORT_DIMS} and {@code GL_MAX_TEXTURE_SIZE} (see 237 * {@link javax.microedition.khronos.opengles.GL10#glGetIntegerv glGetIntegerv}). 238 * An error due to invalid dimensions might not be reported until 239 * updateTexImage() is called. 240 */ setDefaultBufferSize(int width, int height)241 public void setDefaultBufferSize(int width, int height) { 242 nativeSetDefaultBufferSize(width, height); 243 } 244 245 /** 246 * Update the texture image to the most recent frame from the image stream. This may only be 247 * called while the OpenGL ES context that owns the texture is current on the calling thread. 248 * It will implicitly bind its texture to the {@code GL_TEXTURE_EXTERNAL_OES} texture target. 249 */ updateTexImage()250 public void updateTexImage() { 251 nativeUpdateTexImage(); 252 } 253 254 /** 255 * Releases the the texture content. This is needed in single buffered mode to allow the image 256 * content producer to take ownership of the image buffer. 257 * <p> 258 * For more information see {@link #SurfaceTexture(int, boolean)}. 259 */ releaseTexImage()260 public void releaseTexImage() { 261 nativeReleaseTexImage(); 262 } 263 264 /** 265 * Detach the SurfaceTexture from the OpenGL ES context that owns the OpenGL ES texture object. 266 * This call must be made with the OpenGL ES context current on the calling thread. The OpenGL 267 * ES texture object will be deleted as a result of this call. After calling this method all 268 * calls to {@link #updateTexImage} will throw an {@link java.lang.IllegalStateException} until 269 * a successful call to {@link #attachToGLContext} is made. 270 * <p> 271 * This can be used to access the SurfaceTexture image contents from multiple OpenGL ES 272 * contexts. Note, however, that the image contents are only accessible from one OpenGL ES 273 * context at a time. 274 */ detachFromGLContext()275 public void detachFromGLContext() { 276 int err = nativeDetachFromGLContext(); 277 if (err != 0) { 278 throw new RuntimeException("Error during detachFromGLContext (see logcat for details)"); 279 } 280 } 281 282 /** 283 * Attach the SurfaceTexture to the OpenGL ES context that is current on the calling thread. A 284 * new OpenGL ES texture object is created and populated with the SurfaceTexture image frame 285 * that was current at the time of the last call to {@link #detachFromGLContext}. This new 286 * texture is bound to the {@code GL_TEXTURE_EXTERNAL_OES} texture target. 287 * <p> 288 * This can be used to access the SurfaceTexture image contents from multiple OpenGL ES 289 * contexts. Note, however, that the image contents are only accessible from one OpenGL ES 290 * context at a time. 291 * 292 * @param texName The name of the OpenGL ES texture that will be created. This texture name 293 * must be unused in the OpenGL ES context that is current on the calling thread. 294 */ attachToGLContext(int texName)295 public void attachToGLContext(int texName) { 296 int err = nativeAttachToGLContext(texName); 297 if (err != 0) { 298 throw new RuntimeException("Error during attachToGLContext (see logcat for details)"); 299 } 300 } 301 302 /** 303 * Retrieve the 4x4 texture coordinate transform matrix associated with the texture image set by 304 * the most recent call to {@link #updateTexImage}. 305 * <p> 306 * This transform matrix maps 2D homogeneous texture coordinates of the form (s, t, 0, 1) with s 307 * and t in the inclusive range [0, 1] to the texture coordinate that should be used to sample 308 * that location from the texture. Sampling the texture outside of the range of this transform 309 * is undefined. 310 * <p> 311 * The matrix is stored in column-major order so that it may be passed directly to OpenGL ES via 312 * the {@code glLoadMatrixf} or {@code glUniformMatrix4fv} functions. 313 * <p> 314 * If the underlying buffer has a crop associated with it, the transformation will also include 315 * a slight scale to cut off a 1-texel border around the edge of the crop. This ensures that 316 * when the texture is bilinear sampled that no texels outside of the buffer's valid region 317 * are accessed by the GPU, avoiding any sampling artifacts when scaling. 318 * 319 * @param mtx the array into which the 4x4 matrix will be stored. The array must have exactly 320 * 16 elements. 321 */ getTransformMatrix(float[] mtx)322 public void getTransformMatrix(float[] mtx) { 323 // Note we intentionally don't check mtx for null, so this will result in a 324 // NullPointerException. But it's safe because it happens before the call to native. 325 if (mtx.length != 16) { 326 throw new IllegalArgumentException(); 327 } 328 nativeGetTransformMatrix(mtx); 329 } 330 331 /** 332 * Retrieve the timestamp associated with the texture image set by the most recent call to 333 * {@link #updateTexImage}. 334 * 335 * <p>This timestamp is in nanoseconds, and is normally monotonically increasing. The timestamp 336 * should be unaffected by time-of-day adjustments. The specific meaning and zero point of the 337 * timestamp depends on the source providing images to the SurfaceTexture. Unless otherwise 338 * specified by the image source, timestamps cannot generally be compared across SurfaceTexture 339 * instances, or across multiple program invocations. It is mostly useful for determining time 340 * offsets between subsequent frames.</p> 341 * 342 * <p>For camera sources, timestamps should be strictly monotonic. Timestamps from MediaPlayer 343 * sources may be reset when the playback position is set. For EGL and Vulkan producers, the 344 * timestamp is the desired present time set with the {@code EGL_ANDROID_presentation_time} or 345 * {@code VK_GOOGLE_display_timing} extensions.</p> 346 */ 347 getTimestamp()348 public long getTimestamp() { 349 return nativeGetTimestamp(); 350 } 351 352 /** 353 * Retrieve the dataspace associated with the texture image. 354 */ 355 @SuppressLint("MethodNameUnits") getDataSpace()356 public @NamedDataSpace int getDataSpace() { 357 return nativeGetDataSpace(); 358 } 359 360 /** 361 * {@code release()} frees all the buffers and puts the SurfaceTexture into the 362 * 'abandoned' state. Once put in this state the SurfaceTexture can never 363 * leave it. When in the 'abandoned' state, all methods of the 364 * {@code IGraphicBufferProducer} interface will fail with the {@code NO_INIT} 365 * error. 366 * <p> 367 * Note that while calling this method causes all the buffers to be freed 368 * from the perspective of the the SurfaceTexture, if there are additional 369 * references on the buffers (e.g. if a buffer is referenced by a client or 370 * by OpenGL ES as a texture) then those buffer will remain allocated. 371 * <p> 372 * Always call this method when you are done with SurfaceTexture. Failing 373 * to do so may delay resource deallocation for a significant amount of 374 * time. 375 * 376 * @see #isReleased() 377 */ release()378 public void release() { 379 nativeRelease(); 380 } 381 382 /** 383 * Returns {@code true} if the SurfaceTexture was released. 384 * 385 * @see #release() 386 */ isReleased()387 public boolean isReleased() { 388 return nativeIsReleased(); 389 } 390 391 @Override finalize()392 protected void finalize() throws Throwable { 393 try { 394 nativeFinalize(); 395 } finally { 396 super.finalize(); 397 } 398 } 399 400 /** 401 * This method is invoked from native code only. 402 */ 403 @SuppressWarnings({"UnusedDeclaration"}) 404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) postEventFromNative(WeakReference<SurfaceTexture> weakSelf)405 private static void postEventFromNative(WeakReference<SurfaceTexture> weakSelf) { 406 SurfaceTexture st = weakSelf.get(); 407 if (st != null) { 408 Handler handler = st.mOnFrameAvailableHandler; 409 if (handler != null) { 410 handler.sendEmptyMessage(0); 411 } 412 } 413 } 414 415 /** 416 * Returns {@code true} if the SurfaceTexture is single-buffered. 417 * @hide 418 */ isSingleBuffered()419 public boolean isSingleBuffered() { 420 return mIsSingleBuffered; 421 } 422 nativeInit(boolean isDetached, int texName, boolean singleBufferMode, WeakReference<SurfaceTexture> weakSelf)423 private native void nativeInit(boolean isDetached, int texName, 424 boolean singleBufferMode, WeakReference<SurfaceTexture> weakSelf) 425 throws Surface.OutOfResourcesException; nativeFinalize()426 private native void nativeFinalize(); nativeGetTransformMatrix(float[] mtx)427 private native void nativeGetTransformMatrix(float[] mtx); nativeGetTimestamp()428 private native long nativeGetTimestamp(); nativeGetDataSpace()429 private native int nativeGetDataSpace(); nativeSetDefaultBufferSize(int width, int height)430 private native void nativeSetDefaultBufferSize(int width, int height); nativeUpdateTexImage()431 private native void nativeUpdateTexImage(); nativeReleaseTexImage()432 private native void nativeReleaseTexImage(); 433 @UnsupportedAppUsage nativeDetachFromGLContext()434 private native int nativeDetachFromGLContext(); nativeAttachToGLContext(int texName)435 private native int nativeAttachToGLContext(int texName); nativeRelease()436 private native void nativeRelease(); nativeIsReleased()437 private native boolean nativeIsReleased(); 438 } 439