CameraSource.cpp revision 0a1b9dcf0106731e1b8113fb77e933ffaf70bd0b
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//#define LOG_NDEBUG 0 18#define LOG_TAG "CameraSource" 19#include <utils/Log.h> 20 21#include <OMX_Component.h> 22#include <binder/IPCThreadState.h> 23#include <media/stagefright/CameraSource.h> 24#include <media/stagefright/MediaDebug.h> 25#include <media/stagefright/MediaDefs.h> 26#include <media/stagefright/MediaErrors.h> 27#include <media/stagefright/MetaData.h> 28#include <camera/Camera.h> 29#include <camera/CameraParameters.h> 30#include <utils/String8.h> 31#include <cutils/properties.h> 32 33namespace android { 34 35struct CameraSourceListener : public CameraListener { 36 CameraSourceListener(const sp<CameraSource> &source); 37 38 virtual void notify(int32_t msgType, int32_t ext1, int32_t ext2); 39 virtual void postData(int32_t msgType, const sp<IMemory> &dataPtr); 40 41 virtual void postDataTimestamp( 42 nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr); 43 44protected: 45 virtual ~CameraSourceListener(); 46 47private: 48 wp<CameraSource> mSource; 49 50 CameraSourceListener(const CameraSourceListener &); 51 CameraSourceListener &operator=(const CameraSourceListener &); 52}; 53 54CameraSourceListener::CameraSourceListener(const sp<CameraSource> &source) 55 : mSource(source) { 56} 57 58CameraSourceListener::~CameraSourceListener() { 59} 60 61void CameraSourceListener::notify(int32_t msgType, int32_t ext1, int32_t ext2) { 62 LOGV("notify(%d, %d, %d)", msgType, ext1, ext2); 63} 64 65void CameraSourceListener::postData(int32_t msgType, const sp<IMemory> &dataPtr) { 66 LOGV("postData(%d, ptr:%p, size:%d)", 67 msgType, dataPtr->pointer(), dataPtr->size()); 68 69 sp<CameraSource> source = mSource.promote(); 70 if (source.get() != NULL) { 71 source->dataCallback(msgType, dataPtr); 72 } 73} 74 75void CameraSourceListener::postDataTimestamp( 76 nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr) { 77 78 sp<CameraSource> source = mSource.promote(); 79 if (source.get() != NULL) { 80 source->dataCallbackTimestamp(timestamp/1000, msgType, dataPtr); 81 } 82} 83 84static int32_t getColorFormat(const char* colorFormat) { 85 if (!strcmp(colorFormat, CameraParameters::PIXEL_FORMAT_YUV422SP)) { 86 return OMX_COLOR_FormatYUV422SemiPlanar; 87 } 88 89 if (!strcmp(colorFormat, CameraParameters::PIXEL_FORMAT_YUV420SP)) { 90 return OMX_COLOR_FormatYUV420SemiPlanar; 91 } 92 93 if (!strcmp(colorFormat, CameraParameters::PIXEL_FORMAT_YUV422I)) { 94 return OMX_COLOR_FormatYCbYCr; 95 } 96 97 if (!strcmp(colorFormat, CameraParameters::PIXEL_FORMAT_RGB565)) { 98 return OMX_COLOR_Format16bitRGB565; 99 } 100 101 LOGE("Uknown color format (%s), please add it to " 102 "CameraSource::getColorFormat", colorFormat); 103 104 CHECK_EQ(0, "Unknown color format"); 105} 106 107// static 108CameraSource *CameraSource::Create() { 109 sp<Camera> camera = Camera::connect(0); 110 111 if (camera.get() == NULL) { 112 return NULL; 113 } 114 115 return new CameraSource(camera); 116} 117 118// static 119CameraSource *CameraSource::CreateFromCamera(const sp<Camera> &camera) { 120 if (camera.get() == NULL) { 121 return NULL; 122 } 123 124 return new CameraSource(camera); 125} 126 127CameraSource::CameraSource(const sp<Camera> &camera) 128 : mCamera(camera), 129 mNumFramesReceived(0), 130 mLastFrameTimestampUs(0), 131 mStarted(false), 132 mFirstFrameTimeUs(0), 133 mNumFramesEncoded(0), 134 mNumFramesDropped(0), 135 mNumGlitches(0), 136 mGlitchDurationThresholdUs(200000), 137 mCollectStats(false) { 138 139 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 140 String8 s = mCamera->getParameters(); 141 IPCThreadState::self()->restoreCallingIdentity(token); 142 143 printf("params: \"%s\"\n", s.string()); 144 145 int32_t width, height, stride, sliceHeight; 146 CameraParameters params(s); 147 params.getPreviewSize(&width, &height); 148 149 // Calculate glitch duraton threshold based on frame rate 150 int32_t frameRate = params.getPreviewFrameRate(); 151 int64_t glitchDurationUs = (1000000LL / frameRate); 152 if (glitchDurationUs > mGlitchDurationThresholdUs) { 153 mGlitchDurationThresholdUs = glitchDurationUs; 154 } 155 156 const char *colorFormatStr = params.get(CameraParameters::KEY_VIDEO_FRAME_FORMAT); 157 CHECK(colorFormatStr != NULL); 158 int32_t colorFormat = getColorFormat(colorFormatStr); 159 160 // XXX: query camera for the stride and slice height 161 // when the capability becomes available. 162 stride = width; 163 sliceHeight = height; 164 165 mMeta = new MetaData; 166 mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 167 mMeta->setInt32(kKeyColorFormat, colorFormat); 168 mMeta->setInt32(kKeyWidth, width); 169 mMeta->setInt32(kKeyHeight, height); 170 mMeta->setInt32(kKeyStride, stride); 171 mMeta->setInt32(kKeySliceHeight, sliceHeight); 172} 173 174CameraSource::~CameraSource() { 175 if (mStarted) { 176 stop(); 177 } 178} 179 180void CameraSource::startCameraRecording() { 181 CHECK_EQ(OK, mCamera->startRecording()); 182} 183 184status_t CameraSource::start(MetaData *meta) { 185 CHECK(!mStarted); 186 187 char value[PROPERTY_VALUE_MAX]; 188 if (property_get("media.stagefright.record-stats", value, NULL) 189 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) { 190 mCollectStats = true; 191 } 192 193 mStartTimeUs = 0; 194 int64_t startTimeUs; 195 if (meta && meta->findInt64(kKeyTime, &startTimeUs)) { 196 mStartTimeUs = startTimeUs; 197 } 198 199 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 200 mCamera->setListener(new CameraSourceListener(this)); 201 startCameraRecording(); 202 IPCThreadState::self()->restoreCallingIdentity(token); 203 204 mStarted = true; 205 return OK; 206} 207 208void CameraSource::stopCameraRecording() { 209 mCamera->stopRecording(); 210} 211 212status_t CameraSource::stop() { 213 LOGV("stop"); 214 Mutex::Autolock autoLock(mLock); 215 mStarted = false; 216 mFrameAvailableCondition.signal(); 217 218 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 219 mCamera->setListener(NULL); 220 stopCameraRecording(); 221 releaseQueuedFrames(); 222 while (!mFramesBeingEncoded.empty()) { 223 LOGI("Waiting for outstanding frames being encoded: %d", 224 mFramesBeingEncoded.size()); 225 mFrameCompleteCondition.wait(mLock); 226 } 227 mCamera = NULL; 228 IPCThreadState::self()->restoreCallingIdentity(token); 229 230 if (mCollectStats) { 231 LOGI("Frames received/encoded/dropped: %d/%d/%d in %lld us", 232 mNumFramesReceived, mNumFramesEncoded, mNumFramesDropped, 233 mLastFrameTimestampUs - mFirstFrameTimeUs); 234 } 235 236 CHECK_EQ(mNumFramesReceived, mNumFramesEncoded + mNumFramesDropped); 237 return OK; 238} 239 240void CameraSource::releaseRecordingFrame(const sp<IMemory>& frame) { 241 mCamera->releaseRecordingFrame(frame); 242} 243 244void CameraSource::releaseQueuedFrames() { 245 List<sp<IMemory> >::iterator it; 246 while (!mFramesReceived.empty()) { 247 it = mFramesReceived.begin(); 248 releaseRecordingFrame(*it); 249 mFramesReceived.erase(it); 250 ++mNumFramesDropped; 251 } 252} 253 254sp<MetaData> CameraSource::getFormat() { 255 return mMeta; 256} 257 258void CameraSource::releaseOneRecordingFrame(const sp<IMemory>& frame) { 259 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 260 releaseRecordingFrame(frame); 261 IPCThreadState::self()->restoreCallingIdentity(token); 262} 263 264void CameraSource::signalBufferReturned(MediaBuffer *buffer) { 265 LOGV("signalBufferReturned: %p", buffer->data()); 266 Mutex::Autolock autoLock(mLock); 267 for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin(); 268 it != mFramesBeingEncoded.end(); ++it) { 269 if ((*it)->pointer() == buffer->data()) { 270 releaseOneRecordingFrame((*it)); 271 mFramesBeingEncoded.erase(it); 272 ++mNumFramesEncoded; 273 buffer->setObserver(0); 274 buffer->release(); 275 mFrameCompleteCondition.signal(); 276 return; 277 } 278 } 279 CHECK_EQ(0, "signalBufferReturned: bogus buffer"); 280} 281 282status_t CameraSource::read( 283 MediaBuffer **buffer, const ReadOptions *options) { 284 LOGV("read"); 285 286 *buffer = NULL; 287 288 int64_t seekTimeUs; 289 ReadOptions::SeekMode mode; 290 if (options && options->getSeekTo(&seekTimeUs, &mode)) { 291 return ERROR_UNSUPPORTED; 292 } 293 294 sp<IMemory> frame; 295 int64_t frameTime; 296 297 { 298 Mutex::Autolock autoLock(mLock); 299 while (mStarted) { 300 while(mFramesReceived.empty()) { 301 mFrameAvailableCondition.wait(mLock); 302 } 303 304 if (!mStarted) { 305 return OK; 306 } 307 308 frame = *mFramesReceived.begin(); 309 mFramesReceived.erase(mFramesReceived.begin()); 310 311 frameTime = *mFrameTimes.begin(); 312 mFrameTimes.erase(mFrameTimes.begin()); 313 int64_t skipTimeUs; 314 if (!options || !options->getSkipFrame(&skipTimeUs)) { 315 skipTimeUs = frameTime; 316 } 317 if (skipTimeUs > frameTime) { 318 LOGV("skipTimeUs: %lld us > frameTime: %lld us", 319 skipTimeUs, frameTime); 320 releaseOneRecordingFrame(frame); 321 ++mNumFramesDropped; 322 // Safeguard against the abuse of the kSkipFrame_Option. 323 if (skipTimeUs - frameTime >= 1E6) { 324 LOGE("Frame skipping requested is way too long: %lld us", 325 skipTimeUs - frameTime); 326 return UNKNOWN_ERROR; 327 } 328 } else { 329 mFramesBeingEncoded.push_back(frame); 330 *buffer = new MediaBuffer(frame->pointer(), frame->size()); 331 (*buffer)->setObserver(this); 332 (*buffer)->add_ref(); 333 (*buffer)->meta_data()->setInt64(kKeyTime, frameTime); 334 335 return OK; 336 } 337 } 338 } 339 return OK; 340} 341 342void CameraSource::dataCallbackTimestamp(int64_t timestampUs, 343 int32_t msgType, const sp<IMemory> &data) { 344 LOGV("dataCallbackTimestamp: timestamp %lld us", timestampUs); 345 Mutex::Autolock autoLock(mLock); 346 if (!mStarted) { 347 releaseOneRecordingFrame(data); 348 ++mNumFramesReceived; 349 ++mNumFramesDropped; 350 return; 351 } 352 353 if (mNumFramesReceived > 0 && 354 timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) { 355 if (mNumGlitches % 10 == 0) { // Don't spam the log 356 LOGW("Long delay detected in video recording"); 357 } 358 ++mNumGlitches; 359 } 360 361 // May need to skip frame or modify timestamp. Currently implemented 362 // by the subclass CameraSourceTimeLapse. 363 if(skipCurrentFrame(timestampUs)) { 364 releaseOneRecordingFrame(data); 365 return; 366 } 367 368 mLastFrameTimestampUs = timestampUs; 369 if (mNumFramesReceived == 0) { 370 mFirstFrameTimeUs = timestampUs; 371 // Initial delay 372 if (mStartTimeUs > 0) { 373 if (timestampUs < mStartTimeUs) { 374 // Frame was captured before recording was started 375 // Drop it without updating the statistical data. 376 releaseOneRecordingFrame(data); 377 return; 378 } 379 mStartTimeUs = timestampUs - mStartTimeUs; 380 } 381 } 382 ++mNumFramesReceived; 383 384 mFramesReceived.push_back(data); 385 int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs); 386 mFrameTimes.push_back(timeUs); 387 LOGV("initial delay: %lld, current time stamp: %lld", 388 mStartTimeUs, timeUs); 389 mFrameAvailableCondition.signal(); 390} 391 392} // namespace android 393