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