SurfaceMediaSource.h revision df7e6ea0c755fb95a77d21010105e3a2eac69ff8
1/* 2 * Copyright (C) 2011 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_SURFACEMEDIASOURCE_H 18#define ANDROID_GUI_SURFACEMEDIASOURCE_H 19 20#include <gui/ISurfaceTexture.h> 21 22#include <utils/threads.h> 23#include <utils/Vector.h> 24#include <media/stagefright/MediaSource.h> 25#include <media/stagefright/MediaBuffer.h> 26 27namespace android { 28// ---------------------------------------------------------------------------- 29 30class IGraphicBufferAlloc; 31class String8; 32class GraphicBuffer; 33 34class SurfaceMediaSource : public BnSurfaceTexture, public MediaSource, 35 public MediaBufferObserver { 36public: 37 enum { MIN_UNDEQUEUED_BUFFERS = 4 }; 38 enum { 39 MIN_ASYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1, 40 MIN_SYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS 41 }; 42 enum { NUM_BUFFER_SLOTS = 32 }; 43 enum { NO_CONNECTED_API = 0 }; 44 45 struct FrameAvailableListener : public virtual RefBase { 46 // onFrameAvailable() is called from queueBuffer() is the FIFO is 47 // empty. You can use SurfaceMediaSource::getQueuedCount() to 48 // figure out if there are more frames waiting. 49 // This is called without any lock held can be called concurrently by 50 // multiple threads. 51 virtual void onFrameAvailable() = 0; 52 }; 53 54 SurfaceMediaSource(uint32_t bufW, uint32_t bufH); 55 56 virtual ~SurfaceMediaSource(); 57 58 59 // For the MediaSource interface for use by StageFrightRecorder: 60 virtual status_t start(MetaData *params = NULL); 61 virtual status_t stop() { return reset(); } 62 virtual status_t read( 63 MediaBuffer **buffer, const ReadOptions *options = NULL); 64 virtual sp<MetaData> getFormat(); 65 66 // Pass the metadata over to the buffer, call when you have the lock 67 void passMetadataBufferLocked(MediaBuffer **buffer); 68 bool checkBufferMatchesSlot(int slot, MediaBuffer *buffer); 69 70 // Get / Set the frame rate used for encoding. Default fps = 30 71 status_t setFrameRate(int32_t fps) ; 72 int32_t getFrameRate( ) const; 73 74 // The call for the StageFrightRecorder to tell us that 75 // it is done using the MediaBuffer data so that its state 76 // can be set to FREE for dequeuing 77 virtual void signalBufferReturned(MediaBuffer* buffer); 78 // end of MediaSource interface 79 80 uint32_t getBufferCount( ) const { return mBufferCount;} 81 82 83 // setBufferCount updates the number of available buffer slots. After 84 // calling this all buffer slots are both unallocated and owned by the 85 // SurfaceMediaSource object (i.e. they are not owned by the client). 86 virtual status_t setBufferCount(int bufferCount); 87 88 virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf); 89 90 // dequeueBuffer gets the next buffer slot index for the client to use. If a 91 // buffer slot is available then that slot index is written to the location 92 // pointed to by the buf argument and a status of OK is returned. If no 93 // slot is available then a status of -EBUSY is returned and buf is 94 // unmodified. 95 virtual status_t dequeueBuffer(int *buf, uint32_t w, uint32_t h, 96 uint32_t format, uint32_t usage); 97 98 // queueBuffer returns a filled buffer to the SurfaceMediaSource. In addition, a 99 // timestamp must be provided for the buffer. The timestamp is in 100 // nanoseconds, and must be monotonically increasing. Its other semantics 101 // (zero point, etc) are client-dependent and should be documented by the 102 // client. 103 virtual status_t queueBuffer(int buf, int64_t timestamp, 104 const Rect& crop, int scalingMode, uint32_t transform, 105 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform); 106 virtual void cancelBuffer(int buf); 107 108 // onFrameReceivedLocked informs the buffer consumers (StageFrightRecorder) 109 // or listeners that a frame has been received 110 // The buffer is not made available for dequeueing immediately. We need to 111 // wait to hear from StageFrightRecorder to set the buffer FREE 112 // Make sure this is called when the mutex is locked 113 virtual status_t onFrameReceivedLocked(); 114 115 virtual int query(int what, int* value); 116 117 // setSynchronousMode set whether dequeueBuffer is synchronous or 118 // asynchronous. In synchronous mode, dequeueBuffer blocks until 119 // a buffer is available, the currently bound buffer can be dequeued and 120 // queued buffers will be retired in order. 121 // The default mode is synchronous. 122 // TODO: Clarify the minute differences bet sycn /async 123 // modes (S.Encoder vis-a-vis SurfaceTexture) 124 virtual status_t setSynchronousMode(bool enabled); 125 126 // connect attempts to connect a client API to the SurfaceMediaSource. This 127 // must be called before any other ISurfaceTexture methods are called except 128 // for getAllocator. 129 // 130 // This method will fail if the connect was previously called on the 131 // SurfaceMediaSource and no corresponding disconnect call was made. 132 virtual status_t connect(int api, 133 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform); 134 135 // disconnect attempts to disconnect a client API from the SurfaceMediaSource. 136 // Calling this method will cause any subsequent calls to other 137 // ISurfaceTexture methods to fail except for getAllocator and connect. 138 // Successfully calling connect after this will allow the other methods to 139 // succeed again. 140 // 141 // This method will fail if the the SurfaceMediaSource is not currently 142 // connected to the specified client API. 143 virtual status_t disconnect(int api); 144 145 // getqueuedCount returns the number of queued frames waiting in the 146 // FIFO. In asynchronous mode, this always returns 0 or 1 since 147 // frames are not accumulating in the FIFO. 148 size_t getQueuedCount() const; 149 150 // setBufferCountServer set the buffer count. If the client has requested 151 // a buffer count using setBufferCount, the server-buffer count will 152 // take effect once the client sets the count back to zero. 153 status_t setBufferCountServer(int bufferCount); 154 155 // getTimestamp retrieves the timestamp associated with the image 156 // set by the most recent call to read() 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 // getCurrentBuffer returns the buffer associated with the current image. 168 sp<GraphicBuffer> getCurrentBuffer() const; 169 170 // dump our state in a String 171 void dump(String8& result) const; 172 void dump(String8& result, const char* prefix, char* buffer, 173 size_t SIZE) const; 174 175 // isMetaDataStoredInVideoBuffers tells the encoder whether we will 176 // pass metadata through the buffers. Currently, it is force set to true 177 bool isMetaDataStoredInVideoBuffers() const; 178 179protected: 180 181 // freeAllBuffersLocked frees the resources (both GraphicBuffer and EGLImage) for 182 // all slots. 183 void freeAllBuffersLocked(); 184 static bool isExternalFormat(uint32_t format); 185 186private: 187 188 status_t setBufferCountServerLocked(int bufferCount); 189 190 enum { INVALID_BUFFER_SLOT = -1 }; 191 192 struct BufferSlot { 193 194 BufferSlot() 195 : mBufferState(BufferSlot::FREE), 196 mRequestBufferCalled(false), 197 mTimestamp(0) { 198 } 199 200 // mGraphicBuffer points to the buffer allocated for this slot or is 201 // NULL if no buffer has been allocated. 202 sp<GraphicBuffer> mGraphicBuffer; 203 204 // BufferState represents the different states in which a buffer slot 205 // can be. 206 enum BufferState { 207 // FREE indicates that the buffer is not currently being used and 208 // will not be used in the future until it gets dequeued and 209 // subseqently queued by the client. 210 FREE = 0, 211 212 // DEQUEUED indicates that the buffer has been dequeued by the 213 // client, but has not yet been queued or canceled. The buffer is 214 // considered 'owned' by the client, and the server should not use 215 // it for anything. 216 // 217 // Note that when in synchronous-mode (mSynchronousMode == true), 218 // the buffer that's currently attached to the texture may be 219 // dequeued by the client. That means that the current buffer can 220 // be in either the DEQUEUED or QUEUED state. In asynchronous mode, 221 // however, the current buffer is always in the QUEUED state. 222 DEQUEUED = 1, 223 224 // QUEUED indicates that the buffer has been queued by the client, 225 // and has not since been made available for the client to dequeue. 226 // Attaching the buffer to the texture does NOT transition the 227 // buffer away from the QUEUED state. However, in Synchronous mode 228 // the current buffer may be dequeued by the client under some 229 // circumstances. See the note about the current buffer in the 230 // documentation for DEQUEUED. 231 QUEUED = 2, 232 }; 233 234 // mBufferState is the current state of this buffer slot. 235 BufferState mBufferState; 236 237 // mRequestBufferCalled is used for validating that the client did 238 // call requestBuffer() when told to do so. Technically this is not 239 // needed but useful for debugging and catching client bugs. 240 bool mRequestBufferCalled; 241 242 // mTimestamp is the current timestamp for this buffer slot. This gets 243 // to set by queueBuffer each time this slot is queued. 244 int64_t mTimestamp; 245 }; 246 247 // mSlots is the array of buffer slots that must be mirrored on the client 248 // side. This allows buffer ownership to be transferred between the client 249 // and server without sending a GraphicBuffer over binder. The entire array 250 // is initialized to NULL at construction time, and buffers are allocated 251 // for a slot when requestBuffer is called with that slot's index. 252 BufferSlot mSlots[NUM_BUFFER_SLOTS]; 253 254 // mDefaultWidth holds the default width of allocated buffers. It is used 255 // in requestBuffers() if a width and height of zero is specified. 256 uint32_t mDefaultWidth; 257 258 // mDefaultHeight holds the default height of allocated buffers. It is used 259 // in requestBuffers() if a width and height of zero is specified. 260 uint32_t mDefaultHeight; 261 262 // mPixelFormat holds the pixel format of allocated buffers. It is used 263 // in requestBuffers() if a format of zero is specified. 264 uint32_t mPixelFormat; 265 266 // mBufferCount is the number of buffer slots that the client and server 267 // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed 268 // by calling setBufferCount or setBufferCountServer 269 int mBufferCount; 270 271 // mClientBufferCount is the number of buffer slots requested by the 272 // client. The default is zero, which means the client doesn't care how 273 // many buffers there are 274 int mClientBufferCount; 275 276 // mServerBufferCount buffer count requested by the server-side 277 int mServerBufferCount; 278 279 // mCurrentSlot is the buffer slot index of the buffer that is currently 280 // being used by buffer consumer 281 // (e.g. StageFrightRecorder in the case of SurfaceMediaSource or GLTexture 282 // in the case of SurfaceTexture). 283 // It is initialized to INVALID_BUFFER_SLOT, 284 // indicating that no buffer slot is currently bound to the texture. Note, 285 // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean 286 // that no buffer is bound to the texture. A call to setBufferCount will 287 // reset mCurrentTexture to INVALID_BUFFER_SLOT. 288 int mCurrentSlot; 289 290 291 // mCurrentBuf is the graphic buffer of the current slot to be used by 292 // buffer consumer. It's possible that this buffer is not associated 293 // with any buffer slot, so we must track it separately in order to 294 // properly use IGraphicBufferAlloc::freeAllGraphicBuffersExcept. 295 sp<GraphicBuffer> mCurrentBuf; 296 297 298 // mCurrentTimestamp is the timestamp for the current texture. It 299 // gets set to mLastQueuedTimestamp each time updateTexImage is called. 300 int64_t mCurrentTimestamp; 301 302 // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to 303 // allocate new GraphicBuffer objects. 304 sp<IGraphicBufferAlloc> mGraphicBufferAlloc; 305 306 // mFrameAvailableListener is the listener object that will be called when a 307 // new frame becomes available. If it is not NULL it will be called from 308 // queueBuffer. 309 sp<FrameAvailableListener> mFrameAvailableListener; 310 311 // mSynchronousMode whether we're in synchronous mode or not 312 bool mSynchronousMode; 313 314 // mConnectedApi indicates the API that is currently connected to this 315 // SurfaceTexture. It defaults to NO_CONNECTED_API (= 0), and gets updated 316 // by the connect and disconnect methods. 317 int mConnectedApi; 318 319 // mDequeueCondition condition used for dequeueBuffer in synchronous mode 320 mutable Condition mDequeueCondition; 321 322 323 // mQueue is a FIFO of queued buffers used in synchronous mode 324 typedef Vector<int> Fifo; 325 Fifo mQueue; 326 327 // mMutex is the mutex used to prevent concurrent access to the member 328 // variables of SurfaceMediaSource objects. It must be locked whenever the 329 // member variables are accessed. 330 mutable Mutex mMutex; 331 332 ////////////////////////// For MediaSource 333 // Set to a default of 30 fps if not specified by the client side 334 int32_t mFrameRate; 335 336 // mStopped is a flag to check if the recording is going on 337 bool mStopped; 338 339 // mNumFramesReceived indicates the number of frames recieved from 340 // the client side 341 int mNumFramesReceived; 342 // mNumFramesEncoded indicates the number of frames passed on to the 343 // encoder 344 int mNumFramesEncoded; 345 346 // mFirstFrameTimestamp is the timestamp of the first received frame. 347 // It is used to offset the output timestamps so recording starts at time 0. 348 int64_t mFirstFrameTimestamp; 349 // mStartTimeNs is the start time passed into the source at start, used to 350 // offset timestamps. 351 int64_t mStartTimeNs; 352 353 // mFrameAvailableCondition condition used to indicate whether there 354 // is a frame available for dequeuing 355 Condition mFrameAvailableCondition; 356 Condition mFrameCompleteCondition; 357 358 status_t reset(); 359 360 // Avoid copying and equating and default constructor 361 DISALLOW_IMPLICIT_CONSTRUCTORS(SurfaceMediaSource); 362}; 363 364// ---------------------------------------------------------------------------- 365}; // namespace android 366 367#endif // ANDROID_GUI_SURFACEMEDIASOURCE_H 368