1/* 2 * Copyright (C) 2009 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 CAMERA_SOURCE_H_ 18 19#define CAMERA_SOURCE_H_ 20 21#include <deque> 22#include <media/stagefright/MediaBuffer.h> 23#include <media/stagefright/MediaSource.h> 24#include <camera/android/hardware/ICamera.h> 25#include <camera/ICameraRecordingProxy.h> 26#include <camera/ICameraRecordingProxyListener.h> 27#include <camera/CameraParameters.h> 28#include <gui/BufferItemConsumer.h> 29#include <utils/List.h> 30#include <utils/RefBase.h> 31#include <utils/String16.h> 32#include <MetadataBufferType.h> 33 34namespace android { 35 36class IMemory; 37class Camera; 38class Surface; 39 40class CameraSource : public MediaSource, public MediaBufferObserver { 41public: 42 /** 43 * Factory method to create a new CameraSource using the current 44 * settings (such as video size, frame rate, color format, etc) 45 * from the default camera. 46 * 47 * @param clientName The package/process name of the client application. 48 * This is used for permissions checking. 49 * @return NULL on error. 50 */ 51 static CameraSource *Create(const String16 &clientName); 52 53 /** 54 * Factory method to create a new CameraSource. 55 * 56 * @param camera the video input frame data source. If it is NULL, 57 * we will try to connect to the camera with the given 58 * cameraId. 59 * 60 * @param cameraId the id of the camera that the source will connect 61 * to if camera is NULL; otherwise ignored. 62 * @param clientName the package/process name of the camera-using 63 * application if camera is NULL; otherwise ignored. Used for 64 * permissions checking. 65 * @param clientUid the UID of the camera-using application if camera is 66 * NULL; otherwise ignored. Used for permissions checking. 67 * @param clientPid the PID of the camera-using application if camera is 68 * NULL; otherwise ignored. Used for permissions checking. 69 * @param videoSize the dimension (in pixels) of the video frame 70 * @param frameRate the target frames per second 71 * @param surface the preview surface for display where preview 72 * frames are sent to 73 * @param storeMetaDataInVideoBuffers true to request the camera 74 * source to store meta data in video buffers; false to 75 * request the camera source to store real YUV frame data 76 * in the video buffers. The camera source may not support 77 * storing meta data in video buffers, if so, a request 78 * to do that will NOT be honored. To find out whether 79 * meta data is actually being stored in video buffers 80 * during recording, call isMetaDataStoredInVideoBuffers(). 81 * 82 * @return NULL on error. 83 */ 84 static CameraSource *CreateFromCamera(const sp<hardware::ICamera> &camera, 85 const sp<ICameraRecordingProxy> &proxy, 86 int32_t cameraId, 87 const String16& clientName, 88 uid_t clientUid, 89 pid_t clientPid, 90 Size videoSize, 91 int32_t frameRate, 92 const sp<IGraphicBufferProducer>& surface, 93 bool storeMetaDataInVideoBuffers = true); 94 95 virtual ~CameraSource(); 96 97 virtual status_t start(MetaData *params = NULL); 98 virtual status_t stop() { return reset(); } 99 virtual status_t read( 100 MediaBuffer **buffer, const ReadOptions *options = NULL); 101 102 /** 103 * Check whether a CameraSource object is properly initialized. 104 * Must call this method before stop(). 105 * @return OK if initialization has successfully completed. 106 */ 107 virtual status_t initCheck() const; 108 109 /** 110 * Returns the MetaData associated with the CameraSource, 111 * including: 112 * kKeyColorFormat: YUV color format of the video frames 113 * kKeyWidth, kKeyHeight: dimension (in pixels) of the video frames 114 * kKeySampleRate: frame rate in frames per second 115 * kKeyMIMEType: always fixed to be MEDIA_MIMETYPE_VIDEO_RAW 116 */ 117 virtual sp<MetaData> getFormat(); 118 119 /** 120 * Tell whether this camera source stores meta data or real YUV 121 * frame data in video buffers. 122 * 123 * @return a valid type if meta data is stored in the video 124 * buffers; kMetadataBufferTypeInvalid if real YUV data is stored in 125 * the video buffers. 126 */ 127 MetadataBufferType metaDataStoredInVideoBuffers() const; 128 129 virtual void signalBufferReturned(MediaBuffer* buffer); 130 131protected: 132 133 /** 134 * The class for listening to BnCameraRecordingProxyListener. This is used to receive video 135 * buffers in VIDEO_BUFFER_MODE_DATA_CALLBACK_YUV and VIDEO_BUFFER_MODE_DATA_CALLBACK_METADATA 136 * mode. When a frame is available, CameraSource::dataCallbackTimestamp() will be called. 137 */ 138 class ProxyListener: public BnCameraRecordingProxyListener { 139 public: 140 ProxyListener(const sp<CameraSource>& source); 141 virtual void dataCallbackTimestamp(int64_t timestampUs, int32_t msgType, 142 const sp<IMemory> &data); 143 virtual void recordingFrameHandleCallbackTimestamp(int64_t timestampUs, 144 native_handle_t* handle); 145 virtual void recordingFrameHandleCallbackTimestampBatch( 146 const std::vector<int64_t>& timestampsUs, 147 const std::vector<native_handle_t*>& handles); 148 149 private: 150 sp<CameraSource> mSource; 151 }; 152 153 /** 154 * The class for listening to BufferQueue's onFrameAvailable. This is used to receive video 155 * buffers in VIDEO_BUFFER_MODE_BUFFER_QUEUE mode. When a frame is available, 156 * CameraSource::processBufferQueueFrame() will be called. 157 */ 158 class BufferQueueListener : public Thread, public BufferItemConsumer::FrameAvailableListener { 159 public: 160 BufferQueueListener(const sp<BufferItemConsumer> &consumer, 161 const sp<CameraSource> &cameraSource); 162 virtual void onFrameAvailable(const BufferItem& item); 163 virtual bool threadLoop(); 164 private: 165 static const nsecs_t kFrameAvailableTimeout = 50000000; // 50ms 166 167 sp<BufferItemConsumer> mConsumer; 168 sp<CameraSource> mCameraSource; 169 170 Mutex mLock; 171 Condition mFrameAvailableSignal; 172 bool mFrameAvailable; 173 }; 174 175 // isBinderAlive needs linkToDeath to work. 176 class DeathNotifier: public IBinder::DeathRecipient { 177 public: 178 DeathNotifier() {} 179 virtual void binderDied(const wp<IBinder>& who); 180 }; 181 182 enum CameraFlags { 183 FLAGS_SET_CAMERA = 1L << 0, 184 FLAGS_HOT_CAMERA = 1L << 1, 185 }; 186 187 int32_t mCameraFlags; 188 Size mVideoSize; 189 int32_t mNumInputBuffers; 190 int32_t mVideoFrameRate; 191 int32_t mColorFormat; 192 int32_t mEncoderFormat; 193 int32_t mEncoderDataSpace; 194 status_t mInitCheck; 195 196 sp<Camera> mCamera; 197 sp<ICameraRecordingProxy> mCameraRecordingProxy; 198 sp<DeathNotifier> mDeathNotifier; 199 sp<IGraphicBufferProducer> mSurface; 200 sp<MetaData> mMeta; 201 202 int64_t mStartTimeUs; 203 int32_t mNumFramesReceived; 204 int64_t mLastFrameTimestampUs; 205 bool mStarted; 206 int32_t mNumFramesEncoded; 207 208 // Time between capture of two frames. 209 int64_t mTimeBetweenFrameCaptureUs; 210 211 CameraSource(const sp<hardware::ICamera>& camera, const sp<ICameraRecordingProxy>& proxy, 212 int32_t cameraId, const String16& clientName, uid_t clientUid, pid_t clientPid, 213 Size videoSize, int32_t frameRate, 214 const sp<IGraphicBufferProducer>& surface, 215 bool storeMetaDataInVideoBuffers); 216 217 virtual status_t startCameraRecording(); 218 virtual void releaseRecordingFrame(const sp<IMemory>& frame); 219 virtual void releaseRecordingFrameHandle(native_handle_t* handle); 220 // stagefright recorder not using this for now 221 virtual void releaseRecordingFrameHandleBatch(const std::vector<native_handle_t*>& handles); 222 223 // Returns true if need to skip the current frame. 224 // Called from dataCallbackTimestamp. 225 virtual bool skipCurrentFrame(int64_t /*timestampUs*/) {return false;} 226 227 // Callback called when still camera raw data is available. 228 virtual void dataCallback(int32_t /*msgType*/, const sp<IMemory>& /*data*/) {} 229 230 virtual void dataCallbackTimestamp(int64_t timestampUs, int32_t msgType, 231 const sp<IMemory> &data); 232 233 virtual void recordingFrameHandleCallbackTimestamp(int64_t timestampUs, 234 native_handle_t* handle); 235 236 virtual void recordingFrameHandleCallbackTimestampBatch( 237 const std::vector<int64_t>& timestampsUs, 238 const std::vector<native_handle_t*>& handles); 239 240 // Process a buffer item received in BufferQueueListener. 241 virtual void processBufferQueueFrame(BufferItem& buffer); 242 243 void releaseCamera(); 244 245private: 246 friend struct CameraSourceListener; 247 248 Mutex mLock; 249 Condition mFrameAvailableCondition; 250 Condition mFrameCompleteCondition; 251 List<sp<IMemory> > mFramesReceived; 252 List<sp<IMemory> > mFramesBeingEncoded; 253 List<int64_t> mFrameTimes; 254 255 int64_t mFirstFrameTimeUs; 256 int32_t mNumFramesDropped; 257 int32_t mNumGlitches; 258 int64_t mGlitchDurationThresholdUs; 259 bool mCollectStats; 260 261 // The mode video buffers are received from camera. One of VIDEO_BUFFER_MODE_*. 262 int32_t mVideoBufferMode; 263 264 static const uint32_t kDefaultVideoBufferCount = 32; 265 266 /** 267 * The following variables are used in VIDEO_BUFFER_MODE_BUFFER_QUEUE mode. 268 */ 269 static const size_t kConsumerBufferCount = 8; 270 static const nsecs_t kMemoryBaseAvailableTimeoutNs = 200000000; // 200ms 271 // Consumer and producer of the buffer queue between this class and camera. 272 sp<BufferItemConsumer> mVideoBufferConsumer; 273 sp<IGraphicBufferProducer> mVideoBufferProducer; 274 // Memory used to send the buffers to encoder, where sp<IMemory> stores VideoNativeMetadata. 275 sp<IMemoryHeap> mMemoryHeapBase; 276 List<sp<IMemory>> mMemoryBases; 277 // The condition that will be signaled when there is an entry available in mMemoryBases. 278 Condition mMemoryBaseAvailableCond; 279 // A mapping from ANativeWindowBuffer sent to encoder to BufferItem received from camera. 280 // This is protected by mLock. 281 KeyedVector<ANativeWindowBuffer*, BufferItem> mReceivedBufferItemMap; 282 sp<BufferQueueListener> mBufferQueueListener; 283 284 Mutex mBatchLock; // protecting access to mInflightXXXXX members below 285 // Start of members protected by mBatchLock 286 std::deque<uint32_t> mInflightBatchSizes; 287 std::vector<native_handle_t*> mInflightReturnedHandles; 288 std::vector<const sp<IMemory>> mInflightReturnedMemorys; 289 // End of members protected by mBatchLock 290 291 void releaseQueuedFrames(); 292 void releaseOneRecordingFrame(const sp<IMemory>& frame); 293 void createVideoBufferMemoryHeap(size_t size, uint32_t bufferCount); 294 295 status_t init(const sp<hardware::ICamera>& camera, const sp<ICameraRecordingProxy>& proxy, 296 int32_t cameraId, const String16& clientName, uid_t clientUid, pid_t clientPid, 297 Size videoSize, int32_t frameRate, bool storeMetaDataInVideoBuffers); 298 299 status_t initWithCameraAccess( 300 const sp<hardware::ICamera>& camera, const sp<ICameraRecordingProxy>& proxy, 301 int32_t cameraId, const String16& clientName, uid_t clientUid, pid_t clientPid, 302 Size videoSize, int32_t frameRate, bool storeMetaDataInVideoBuffers); 303 304 // Initialize the buffer queue used in VIDEO_BUFFER_MODE_BUFFER_QUEUE mode. 305 status_t initBufferQueue(uint32_t width, uint32_t height, uint32_t format, 306 android_dataspace dataSpace, uint32_t bufferCount); 307 308 status_t isCameraAvailable(const sp<hardware::ICamera>& camera, 309 const sp<ICameraRecordingProxy>& proxy, 310 int32_t cameraId, 311 const String16& clientName, 312 uid_t clientUid, 313 pid_t clientPid); 314 315 status_t isCameraColorFormatSupported(const CameraParameters& params); 316 status_t configureCamera(CameraParameters* params, 317 int32_t width, int32_t height, 318 int32_t frameRate); 319 320 status_t checkVideoSize(const CameraParameters& params, 321 int32_t width, int32_t height); 322 323 status_t checkFrameRate(const CameraParameters& params, 324 int32_t frameRate); 325 326 // Check if this frame should be skipped based on the frame's timestamp in microsecond. 327 // mLock must be locked before calling this function. 328 bool shouldSkipFrameLocked(int64_t timestampUs); 329 330 void stopCameraRecording(); 331 status_t reset(); 332 333 CameraSource(const CameraSource &); 334 CameraSource &operator=(const CameraSource &); 335}; 336 337} // namespace android 338 339#endif // CAMERA_SOURCE_H_ 340