SurfaceTexture.h revision fa28c35c21d1bf8b38f541758c291bc17a2d7270
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#ifndef ANDROID_GUI_SURFACETEXTURE_H 18#define ANDROID_GUI_SURFACETEXTURE_H 19 20#include <EGL/egl.h> 21#include <EGL/eglext.h> 22#include <GLES2/gl2.h> 23 24#include <gui/ISurfaceTexture.h> 25 26#include <ui/GraphicBuffer.h> 27 28#include <utils/String8.h> 29#include <utils/Vector.h> 30#include <utils/threads.h> 31 32#define ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID "mSurfaceTexture" 33 34namespace android { 35// ---------------------------------------------------------------------------- 36 37class IGraphicBufferAlloc; 38class String8; 39 40class SurfaceTexture : public BnSurfaceTexture { 41public: 42 enum { MIN_UNDEQUEUED_BUFFERS = 2 }; 43 enum { 44 MIN_ASYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1, 45 MIN_SYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS 46 }; 47 enum { NUM_BUFFER_SLOTS = 32 }; 48 enum { NO_CONNECTED_API = 0 }; 49 50 struct FrameAvailableListener : public virtual RefBase { 51 // onFrameAvailable() is called from queueBuffer() each time an 52 // additional frame becomes available for consumption. This means that 53 // frames that are queued while in asynchronous mode only trigger the 54 // callback if no previous frames are pending. Frames queued while in 55 // synchronous mode always trigger the callback. 56 // 57 // This is called without any lock held and can be called concurrently 58 // by multiple threads. 59 virtual void onFrameAvailable() = 0; 60 }; 61 62 // tex indicates the name OpenGL texture to which images are to be streamed. 63 // This texture name cannot be changed once the SurfaceTexture is created. 64 SurfaceTexture(GLuint tex, bool allowSynchronousMode = true); 65 66 virtual ~SurfaceTexture(); 67 68 // setBufferCount updates the number of available buffer slots. After 69 // calling this all buffer slots are both unallocated and owned by the 70 // SurfaceTexture object (i.e. they are not owned by the client). 71 virtual status_t setBufferCount(int bufferCount); 72 73 virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf); 74 75 // dequeueBuffer gets the next buffer slot index for the client to use. If a 76 // buffer slot is available then that slot index is written to the location 77 // pointed to by the buf argument and a status of OK is returned. If no 78 // slot is available then a status of -EBUSY is returned and buf is 79 // unmodified. 80 virtual status_t dequeueBuffer(int *buf, uint32_t w, uint32_t h, 81 uint32_t format, uint32_t usage); 82 83 // queueBuffer returns a filled buffer to the SurfaceTexture. In addition, a 84 // timestamp must be provided for the buffer. The timestamp is in 85 // nanoseconds, and must be monotonically increasing. Its other semantics 86 // (zero point, etc) are client-dependent and should be documented by the 87 // client. 88 virtual status_t queueBuffer(int buf, int64_t timestamp, 89 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform); 90 virtual void cancelBuffer(int buf); 91 virtual status_t setCrop(const Rect& reg); 92 virtual status_t setTransform(uint32_t transform); 93 virtual status_t setScalingMode(int mode); 94 95 virtual int query(int what, int* value); 96 97 // setSynchronousMode set whether dequeueBuffer is synchronous or 98 // asynchronous. In synchronous mode, dequeueBuffer blocks until 99 // a buffer is available, the currently bound buffer can be dequeued and 100 // queued buffers will be retired in order. 101 // The default mode is asynchronous. 102 virtual status_t setSynchronousMode(bool enabled); 103 104 // connect attempts to connect a client API to the SurfaceTexture. This 105 // must be called before any other ISurfaceTexture methods are called except 106 // for getAllocator. 107 // 108 // This method will fail if the connect was previously called on the 109 // SurfaceTexture and no corresponding disconnect call was made. 110 virtual status_t connect(int api, 111 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform); 112 113 // disconnect attempts to disconnect a client API from the SurfaceTexture. 114 // Calling this method will cause any subsequent calls to other 115 // ISurfaceTexture methods to fail except for getAllocator and connect. 116 // Successfully calling connect after this will allow the other methods to 117 // succeed again. 118 // 119 // This method will fail if the the SurfaceTexture is not currently 120 // connected to the specified client API. 121 virtual status_t disconnect(int api); 122 123 // updateTexImage sets the image contents of the target texture to that of 124 // the most recently queued buffer. 125 // 126 // This call may only be made while the OpenGL ES context to which the 127 // target texture belongs is bound to the calling thread. 128 status_t updateTexImage(); 129 130 // setBufferCountServer set the buffer count. If the client has requested 131 // a buffer count using setBufferCount, the server-buffer count will 132 // take effect once the client sets the count back to zero. 133 status_t setBufferCountServer(int bufferCount); 134 135 // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix 136 // associated with the texture image set by the most recent call to 137 // updateTexImage. 138 // 139 // This transform matrix maps 2D homogeneous texture coordinates of the form 140 // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture 141 // coordinate that should be used to sample that location from the texture. 142 // Sampling the texture outside of the range of this transform is undefined. 143 // 144 // This transform is necessary to compensate for transforms that the stream 145 // content producer may implicitly apply to the content. By forcing users of 146 // a SurfaceTexture to apply this transform we avoid performing an extra 147 // copy of the data that would be needed to hide the transform from the 148 // user. 149 // 150 // The matrix is stored in column-major order so that it may be passed 151 // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv 152 // functions. 153 void getTransformMatrix(float mtx[16]); 154 155 // getTimestamp retrieves the timestamp associated with the texture image 156 // set by the most recent call to updateTexImage. 157 // 158 // The timestamp is in nanoseconds, and is monotonically increasing. Its 159 // other semantics (zero point, etc) are source-dependent and should be 160 // documented by the source. 161 int64_t getTimestamp(); 162 163 // setFrameAvailableListener sets the listener object that will be notified 164 // when a new frame becomes available. 165 void setFrameAvailableListener(const sp<FrameAvailableListener>& listener); 166 167 // getAllocator retrieves the binder object that must be referenced as long 168 // as the GraphicBuffers dequeued from this SurfaceTexture are referenced. 169 // Holding this binder reference prevents SurfaceFlinger from freeing the 170 // buffers before the client is done with them. 171 sp<IBinder> getAllocator(); 172 173 // setDefaultBufferSize is used to set the size of buffers returned by 174 // requestBuffers when a with and height of zero is requested. 175 // A call to setDefaultBufferSize() may trigger requestBuffers() to 176 // be called from the client. 177 status_t setDefaultBufferSize(uint32_t w, uint32_t h); 178 179 // getCurrentBuffer returns the buffer associated with the current image. 180 sp<GraphicBuffer> getCurrentBuffer() const; 181 182 // getCurrentTextureTarget returns the texture target of the current 183 // texture as returned by updateTexImage(). 184 GLenum getCurrentTextureTarget() const; 185 186 // getCurrentCrop returns the cropping rectangle of the current buffer 187 Rect getCurrentCrop() const; 188 189 // getCurrentTransform returns the transform of the current buffer 190 uint32_t getCurrentTransform() const; 191 192 // getCurrentScalingMode returns the scaling mode of the current buffer 193 uint32_t getCurrentScalingMode() const; 194 195 // abandon frees all the buffers and puts the SurfaceTexture into the 196 // 'abandoned' state. Once put in this state the SurfaceTexture can never 197 // leave it. When in the 'abandoned' state, all methods of the 198 // ISurfaceTexture interface will fail with the NO_INIT error. 199 // 200 // Note that while calling this method causes all the buffers to be freed 201 // from the perspective of the the SurfaceTexture, if there are additional 202 // references on the buffers (e.g. if a buffer is referenced by a client or 203 // by OpenGL ES as a texture) then those buffer will remain allocated. 204 void abandon(); 205 206 // set the name of the SurfaceTexture that will be used to identify it in 207 // log messages. 208 void setName(const String8& name); 209 210 // dump our state in a String 211 void dump(String8& result) const; 212 void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const; 213 214protected: 215 216 // freeBufferLocked frees the resources (both GraphicBuffer and EGLImage) 217 // for the given slot. 218 void freeBufferLocked(int index); 219 220 // freeAllBuffersLocked frees the resources (both GraphicBuffer and 221 // EGLImage) for all slots. 222 void freeAllBuffersLocked(); 223 224 // freeAllBuffersExceptHeadLocked frees the resources (both GraphicBuffer 225 // and EGLImage) for all slots except the head of mQueue 226 void freeAllBuffersExceptHeadLocked(); 227 228 // drainQueueLocked drains the buffer queue if we're in synchronous mode 229 // returns immediately otherwise. return NO_INIT if SurfaceTexture 230 // became abandoned or disconnected during this call. 231 status_t drainQueueLocked(); 232 233 // drainQueueAndFreeBuffersLocked drains the buffer queue if we're in 234 // synchronous mode and free all buffers. In asynchronous mode, all buffers 235 // are freed except the current buffer. 236 status_t drainQueueAndFreeBuffersLocked(); 237 238 static bool isExternalFormat(uint32_t format); 239 240private: 241 242 // createImage creates a new EGLImage from a GraphicBuffer. 243 EGLImageKHR createImage(EGLDisplay dpy, 244 const sp<GraphicBuffer>& graphicBuffer); 245 246 status_t setBufferCountServerLocked(int bufferCount); 247 248 // computeCurrentTransformMatrix computes the transform matrix for the 249 // current texture. It uses mCurrentTransform and the current GraphicBuffer 250 // to compute this matrix and stores it in mCurrentTransformMatrix. 251 void computeCurrentTransformMatrix(); 252 253 enum { INVALID_BUFFER_SLOT = -1 }; 254 255 struct BufferSlot { 256 257 BufferSlot() 258 : mEglImage(EGL_NO_IMAGE_KHR), 259 mEglDisplay(EGL_NO_DISPLAY), 260 mBufferState(BufferSlot::FREE), 261 mRequestBufferCalled(false), 262 mTransform(0), 263 mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 264 mTimestamp(0) { 265 mCrop.makeInvalid(); 266 } 267 268 // mGraphicBuffer points to the buffer allocated for this slot or is NULL 269 // if no buffer has been allocated. 270 sp<GraphicBuffer> mGraphicBuffer; 271 272 // mEglImage is the EGLImage created from mGraphicBuffer. 273 EGLImageKHR mEglImage; 274 275 // mEglDisplay is the EGLDisplay used to create mEglImage. 276 EGLDisplay mEglDisplay; 277 278 // BufferState represents the different states in which a buffer slot 279 // can be. 280 enum BufferState { 281 // FREE indicates that the buffer is not currently being used and 282 // will not be used in the future until it gets dequeued and 283 // subsequently queued by the client. 284 FREE = 0, 285 286 // DEQUEUED indicates that the buffer has been dequeued by the 287 // client, but has not yet been queued or canceled. The buffer is 288 // considered 'owned' by the client, and the server should not use 289 // it for anything. 290 // 291 // Note that when in synchronous-mode (mSynchronousMode == true), 292 // the buffer that's currently attached to the texture may be 293 // dequeued by the client. That means that the current buffer can 294 // be in either the DEQUEUED or QUEUED state. In asynchronous mode, 295 // however, the current buffer is always in the QUEUED state. 296 DEQUEUED = 1, 297 298 // QUEUED indicates that the buffer has been queued by the client, 299 // and has not since been made available for the client to dequeue. 300 // Attaching the buffer to the texture does NOT transition the 301 // buffer away from the QUEUED state. However, in Synchronous mode 302 // the current buffer may be dequeued by the client under some 303 // circumstances. See the note about the current buffer in the 304 // documentation for DEQUEUED. 305 QUEUED = 2, 306 }; 307 308 // mBufferState is the current state of this buffer slot. 309 BufferState mBufferState; 310 311 // mRequestBufferCalled is used for validating that the client did 312 // call requestBuffer() when told to do so. Technically this is not 313 // needed but useful for debugging and catching client bugs. 314 bool mRequestBufferCalled; 315 316 // mCrop is the current crop rectangle for this buffer slot. This gets 317 // set to mNextCrop each time queueBuffer gets called for this buffer. 318 Rect mCrop; 319 320 // mTransform is the current transform flags for this buffer slot. This 321 // gets set to mNextTransform each time queueBuffer gets called for this 322 // slot. 323 uint32_t mTransform; 324 325 // mScalingMode is the current scaling mode for this buffer slot. This 326 // gets set to mNextScalingMode each time queueBuffer gets called for 327 // this slot. 328 uint32_t mScalingMode; 329 330 // mTimestamp is the current timestamp for this buffer slot. This gets 331 // to set by queueBuffer each time this slot is queued. 332 int64_t mTimestamp; 333 }; 334 335 // mSlots is the array of buffer slots that must be mirrored on the client 336 // side. This allows buffer ownership to be transferred between the client 337 // and server without sending a GraphicBuffer over binder. The entire array 338 // is initialized to NULL at construction time, and buffers are allocated 339 // for a slot when requestBuffer is called with that slot's index. 340 BufferSlot mSlots[NUM_BUFFER_SLOTS]; 341 342 // mDefaultWidth holds the default width of allocated buffers. It is used 343 // in requestBuffers() if a width and height of zero is specified. 344 uint32_t mDefaultWidth; 345 346 // mDefaultHeight holds the default height of allocated buffers. It is used 347 // in requestBuffers() if a width and height of zero is specified. 348 uint32_t mDefaultHeight; 349 350 // mPixelFormat holds the pixel format of allocated buffers. It is used 351 // in requestBuffers() if a format of zero is specified. 352 uint32_t mPixelFormat; 353 354 // mBufferCount is the number of buffer slots that the client and server 355 // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed 356 // by calling setBufferCount or setBufferCountServer 357 int mBufferCount; 358 359 // mClientBufferCount is the number of buffer slots requested by the client. 360 // The default is zero, which means the client doesn't care how many buffers 361 // there is. 362 int mClientBufferCount; 363 364 // mServerBufferCount buffer count requested by the server-side 365 int mServerBufferCount; 366 367 // mCurrentTexture is the buffer slot index of the buffer that is currently 368 // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT, 369 // indicating that no buffer slot is currently bound to the texture. Note, 370 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean 371 // that no buffer is bound to the texture. A call to setBufferCount will 372 // reset mCurrentTexture to INVALID_BUFFER_SLOT. 373 int mCurrentTexture; 374 375 // mCurrentTextureBuf is the graphic buffer of the current texture. It's 376 // possible that this buffer is not associated with any buffer slot, so we 377 // must track it separately in order to support the getCurrentBuffer method. 378 sp<GraphicBuffer> mCurrentTextureBuf; 379 380 // mCurrentCrop is the crop rectangle that applies to the current texture. 381 // It gets set each time updateTexImage is called. 382 Rect mCurrentCrop; 383 384 // mCurrentTransform is the transform identifier for the current texture. It 385 // gets set each time updateTexImage is called. 386 uint32_t mCurrentTransform; 387 388 // mCurrentScalingMode is the scaling mode for the current texture. It gets 389 // set to each time updateTexImage is called. 390 uint32_t mCurrentScalingMode; 391 392 // mCurrentTransformMatrix is the transform matrix for the current texture. 393 // It gets computed by computeTransformMatrix each time updateTexImage is 394 // called. 395 float mCurrentTransformMatrix[16]; 396 397 // mCurrentTimestamp is the timestamp for the current texture. It 398 // gets set each time updateTexImage is called. 399 int64_t mCurrentTimestamp; 400 401 // mNextCrop is the crop rectangle that will be used for the next buffer 402 // that gets queued. It is set by calling setCrop. 403 Rect mNextCrop; 404 405 // mNextTransform is the transform identifier that will be used for the next 406 // buffer that gets queued. It is set by calling setTransform. 407 uint32_t mNextTransform; 408 409 // mNextScalingMode is the scaling mode that will be used for the next 410 // buffers that get queued. It is set by calling setScalingMode. 411 int mNextScalingMode; 412 413 // mTexName is the name of the OpenGL texture to which streamed images will 414 // be bound when updateTexImage is called. It is set at construction time 415 // changed with a call to setTexName. 416 const GLuint mTexName; 417 418 // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to 419 // allocate new GraphicBuffer objects. 420 sp<IGraphicBufferAlloc> mGraphicBufferAlloc; 421 422 // mFrameAvailableListener is the listener object that will be called when a 423 // new frame becomes available. If it is not NULL it will be called from 424 // queueBuffer. 425 sp<FrameAvailableListener> mFrameAvailableListener; 426 427 // mSynchronousMode whether we're in synchronous mode or not 428 bool mSynchronousMode; 429 430 // mAllowSynchronousMode whether we allow synchronous mode or not 431 const bool mAllowSynchronousMode; 432 433 // mConnectedApi indicates the API that is currently connected to this 434 // SurfaceTexture. It defaults to NO_CONNECTED_API (= 0), and gets updated 435 // by the connect and disconnect methods. 436 int mConnectedApi; 437 438 // mDequeueCondition condition used for dequeueBuffer in synchronous mode 439 mutable Condition mDequeueCondition; 440 441 // mQueue is a FIFO of queued buffers used in synchronous mode 442 typedef Vector<int> Fifo; 443 Fifo mQueue; 444 445 // mAbandoned indicates that the SurfaceTexture will no longer be used to 446 // consume images buffers pushed to it using the ISurfaceTexture interface. 447 // It is initialized to false, and set to true in the abandon method. A 448 // SurfaceTexture that has been abandoned will return the NO_INIT error from 449 // all ISurfaceTexture methods capable of returning an error. 450 bool mAbandoned; 451 452 // mName is a string used to identify the SurfaceTexture in log messages. 453 // It is set by the setName method. 454 String8 mName; 455 456 // mMutex is the mutex used to prevent concurrent access to the member 457 // variables of SurfaceTexture objects. It must be locked whenever the 458 // member variables are accessed. 459 mutable Mutex mMutex; 460 461}; 462 463// ---------------------------------------------------------------------------- 464}; // namespace android 465 466#endif // ANDROID_GUI_SURFACETEXTURE_H 467