StagefrightRecorder.cpp revision df712ea86e6350f7005a02ab0e1c60c28a343ed0
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 "StagefrightRecorder" 19#include <utils/Log.h> 20 21#include "StagefrightRecorder.h" 22 23#include <binder/IPCThreadState.h> 24#include <binder/IServiceManager.h> 25 26#include <media/IMediaPlayerService.h> 27#include <media/stagefright/foundation/ADebug.h> 28#include <media/stagefright/AudioSource.h> 29#include <media/stagefright/AMRWriter.h> 30#include <media/stagefright/AACWriter.h> 31#include <media/stagefright/CameraSource.h> 32#include <media/stagefright/CameraSourceTimeLapse.h> 33#include <media/stagefright/MPEG2TSWriter.h> 34#include <media/stagefright/MPEG4Writer.h> 35#include <media/stagefright/MediaDefs.h> 36#include <media/stagefright/MetaData.h> 37#include <media/stagefright/OMXClient.h> 38#include <media/stagefright/OMXCodec.h> 39#include <media/stagefright/SurfaceMediaSource.h> 40#include <media/MediaProfiles.h> 41#include <camera/ICamera.h> 42#include <camera/CameraParameters.h> 43#include <gui/Surface.h> 44 45#include <utils/Errors.h> 46#include <sys/types.h> 47#include <ctype.h> 48#include <unistd.h> 49 50#include <system/audio.h> 51 52#include "ARTPWriter.h" 53 54namespace android { 55 56// To collect the encoder usage for the battery app 57static void addBatteryData(uint32_t params) { 58 sp<IBinder> binder = 59 defaultServiceManager()->getService(String16("media.player")); 60 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder); 61 CHECK(service.get() != NULL); 62 63 service->addBatteryData(params); 64} 65 66 67StagefrightRecorder::StagefrightRecorder() 68 : mWriter(NULL), 69 mOutputFd(-1), 70 mAudioSource(AUDIO_SOURCE_CNT), 71 mVideoSource(VIDEO_SOURCE_LIST_END), 72 mStarted(false), mSurfaceMediaSource(NULL) { 73 74 ALOGV("Constructor"); 75 reset(); 76} 77 78StagefrightRecorder::~StagefrightRecorder() { 79 ALOGV("Destructor"); 80 stop(); 81} 82 83status_t StagefrightRecorder::init() { 84 ALOGV("init"); 85 return OK; 86} 87 88// The client side of mediaserver asks it to creat a SurfaceMediaSource 89// and return a interface reference. The client side will use that 90// while encoding GL Frames 91sp<ISurfaceTexture> StagefrightRecorder::querySurfaceMediaSource() const { 92 ALOGV("Get SurfaceMediaSource"); 93 return mSurfaceMediaSource; 94} 95 96status_t StagefrightRecorder::setAudioSource(audio_source_t as) { 97 ALOGV("setAudioSource: %d", as); 98 if (as < AUDIO_SOURCE_DEFAULT || 99 as >= AUDIO_SOURCE_CNT) { 100 ALOGE("Invalid audio source: %d", as); 101 return BAD_VALUE; 102 } 103 104 if (as == AUDIO_SOURCE_DEFAULT) { 105 mAudioSource = AUDIO_SOURCE_MIC; 106 } else { 107 mAudioSource = as; 108 } 109 110 return OK; 111} 112 113status_t StagefrightRecorder::setVideoSource(video_source vs) { 114 ALOGV("setVideoSource: %d", vs); 115 if (vs < VIDEO_SOURCE_DEFAULT || 116 vs >= VIDEO_SOURCE_LIST_END) { 117 ALOGE("Invalid video source: %d", vs); 118 return BAD_VALUE; 119 } 120 121 if (vs == VIDEO_SOURCE_DEFAULT) { 122 mVideoSource = VIDEO_SOURCE_CAMERA; 123 } else { 124 mVideoSource = vs; 125 } 126 127 return OK; 128} 129 130status_t StagefrightRecorder::setOutputFormat(output_format of) { 131 ALOGV("setOutputFormat: %d", of); 132 if (of < OUTPUT_FORMAT_DEFAULT || 133 of >= OUTPUT_FORMAT_LIST_END) { 134 ALOGE("Invalid output format: %d", of); 135 return BAD_VALUE; 136 } 137 138 if (of == OUTPUT_FORMAT_DEFAULT) { 139 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 140 } else { 141 mOutputFormat = of; 142 } 143 144 return OK; 145} 146 147status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) { 148 ALOGV("setAudioEncoder: %d", ae); 149 if (ae < AUDIO_ENCODER_DEFAULT || 150 ae >= AUDIO_ENCODER_LIST_END) { 151 ALOGE("Invalid audio encoder: %d", ae); 152 return BAD_VALUE; 153 } 154 155 if (ae == AUDIO_ENCODER_DEFAULT) { 156 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 157 } else { 158 mAudioEncoder = ae; 159 } 160 161 return OK; 162} 163 164status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) { 165 ALOGV("setVideoEncoder: %d", ve); 166 if (ve < VIDEO_ENCODER_DEFAULT || 167 ve >= VIDEO_ENCODER_LIST_END) { 168 ALOGE("Invalid video encoder: %d", ve); 169 return BAD_VALUE; 170 } 171 172 if (ve == VIDEO_ENCODER_DEFAULT) { 173 mVideoEncoder = VIDEO_ENCODER_H263; 174 } else { 175 mVideoEncoder = ve; 176 } 177 178 return OK; 179} 180 181status_t StagefrightRecorder::setVideoSize(int width, int height) { 182 ALOGV("setVideoSize: %dx%d", width, height); 183 if (width <= 0 || height <= 0) { 184 ALOGE("Invalid video size: %dx%d", width, height); 185 return BAD_VALUE; 186 } 187 188 // Additional check on the dimension will be performed later 189 mVideoWidth = width; 190 mVideoHeight = height; 191 192 return OK; 193} 194 195status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) { 196 ALOGV("setVideoFrameRate: %d", frames_per_second); 197 if ((frames_per_second <= 0 && frames_per_second != -1) || 198 frames_per_second > 120) { 199 ALOGE("Invalid video frame rate: %d", frames_per_second); 200 return BAD_VALUE; 201 } 202 203 // Additional check on the frame rate will be performed later 204 mFrameRate = frames_per_second; 205 206 return OK; 207} 208 209status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera, 210 const sp<ICameraRecordingProxy> &proxy) { 211 ALOGV("setCamera"); 212 if (camera == 0) { 213 ALOGE("camera is NULL"); 214 return BAD_VALUE; 215 } 216 if (proxy == 0) { 217 ALOGE("camera proxy is NULL"); 218 return BAD_VALUE; 219 } 220 221 mCamera = camera; 222 mCameraProxy = proxy; 223 return OK; 224} 225 226status_t StagefrightRecorder::setPreviewSurface(const sp<Surface> &surface) { 227 ALOGV("setPreviewSurface: %p", surface.get()); 228 mPreviewSurface = surface; 229 230 return OK; 231} 232 233status_t StagefrightRecorder::setOutputFile(const char *path) { 234 ALOGE("setOutputFile(const char*) must not be called"); 235 // We don't actually support this at all, as the media_server process 236 // no longer has permissions to create files. 237 238 return -EPERM; 239} 240 241status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) { 242 ALOGV("setOutputFile: %d, %lld, %lld", fd, offset, length); 243 // These don't make any sense, do they? 244 CHECK_EQ(offset, 0ll); 245 CHECK_EQ(length, 0ll); 246 247 if (fd < 0) { 248 ALOGE("Invalid file descriptor: %d", fd); 249 return -EBADF; 250 } 251 252 if (mOutputFd >= 0) { 253 ::close(mOutputFd); 254 } 255 mOutputFd = dup(fd); 256 257 return OK; 258} 259 260// Attempt to parse an int64 literal optionally surrounded by whitespace, 261// returns true on success, false otherwise. 262static bool safe_strtoi64(const char *s, int64_t *val) { 263 char *end; 264 265 // It is lame, but according to man page, we have to set errno to 0 266 // before calling strtoll(). 267 errno = 0; 268 *val = strtoll(s, &end, 10); 269 270 if (end == s || errno == ERANGE) { 271 return false; 272 } 273 274 // Skip trailing whitespace 275 while (isspace(*end)) { 276 ++end; 277 } 278 279 // For a successful return, the string must contain nothing but a valid 280 // int64 literal optionally surrounded by whitespace. 281 282 return *end == '\0'; 283} 284 285// Return true if the value is in [0, 0x007FFFFFFF] 286static bool safe_strtoi32(const char *s, int32_t *val) { 287 int64_t temp; 288 if (safe_strtoi64(s, &temp)) { 289 if (temp >= 0 && temp <= 0x007FFFFFFF) { 290 *val = static_cast<int32_t>(temp); 291 return true; 292 } 293 } 294 return false; 295} 296 297// Trim both leading and trailing whitespace from the given string. 298static void TrimString(String8 *s) { 299 size_t num_bytes = s->bytes(); 300 const char *data = s->string(); 301 302 size_t leading_space = 0; 303 while (leading_space < num_bytes && isspace(data[leading_space])) { 304 ++leading_space; 305 } 306 307 size_t i = num_bytes; 308 while (i > leading_space && isspace(data[i - 1])) { 309 --i; 310 } 311 312 s->setTo(String8(&data[leading_space], i - leading_space)); 313} 314 315status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) { 316 ALOGV("setParamAudioSamplingRate: %d", sampleRate); 317 if (sampleRate <= 0) { 318 ALOGE("Invalid audio sampling rate: %d", sampleRate); 319 return BAD_VALUE; 320 } 321 322 // Additional check on the sample rate will be performed later. 323 mSampleRate = sampleRate; 324 return OK; 325} 326 327status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) { 328 ALOGV("setParamAudioNumberOfChannels: %d", channels); 329 if (channels <= 0 || channels >= 3) { 330 ALOGE("Invalid number of audio channels: %d", channels); 331 return BAD_VALUE; 332 } 333 334 // Additional check on the number of channels will be performed later. 335 mAudioChannels = channels; 336 return OK; 337} 338 339status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) { 340 ALOGV("setParamAudioEncodingBitRate: %d", bitRate); 341 if (bitRate <= 0) { 342 ALOGE("Invalid audio encoding bit rate: %d", bitRate); 343 return BAD_VALUE; 344 } 345 346 // The target bit rate may not be exactly the same as the requested. 347 // It depends on many factors, such as rate control, and the bit rate 348 // range that a specific encoder supports. The mismatch between the 349 // the target and requested bit rate will NOT be treated as an error. 350 mAudioBitRate = bitRate; 351 return OK; 352} 353 354status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) { 355 ALOGV("setParamVideoEncodingBitRate: %d", bitRate); 356 if (bitRate <= 0) { 357 ALOGE("Invalid video encoding bit rate: %d", bitRate); 358 return BAD_VALUE; 359 } 360 361 // The target bit rate may not be exactly the same as the requested. 362 // It depends on many factors, such as rate control, and the bit rate 363 // range that a specific encoder supports. The mismatch between the 364 // the target and requested bit rate will NOT be treated as an error. 365 mVideoBitRate = bitRate; 366 return OK; 367} 368 369// Always rotate clockwise, and only support 0, 90, 180 and 270 for now. 370status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) { 371 ALOGV("setParamVideoRotation: %d", degrees); 372 if (degrees < 0 || degrees % 90 != 0) { 373 ALOGE("Unsupported video rotation angle: %d", degrees); 374 return BAD_VALUE; 375 } 376 mRotationDegrees = degrees % 360; 377 return OK; 378} 379 380status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) { 381 ALOGV("setParamMaxFileDurationUs: %lld us", timeUs); 382 383 // This is meant for backward compatibility for MediaRecorder.java 384 if (timeUs <= 0) { 385 ALOGW("Max file duration is not positive: %lld us. Disabling duration limit.", timeUs); 386 timeUs = 0; // Disable the duration limit for zero or negative values. 387 } else if (timeUs <= 100000LL) { // XXX: 100 milli-seconds 388 ALOGE("Max file duration is too short: %lld us", timeUs); 389 return BAD_VALUE; 390 } 391 392 if (timeUs <= 15 * 1000000LL) { 393 ALOGW("Target duration (%lld us) too short to be respected", timeUs); 394 } 395 mMaxFileDurationUs = timeUs; 396 return OK; 397} 398 399status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) { 400 ALOGV("setParamMaxFileSizeBytes: %lld bytes", bytes); 401 402 // This is meant for backward compatibility for MediaRecorder.java 403 if (bytes <= 0) { 404 ALOGW("Max file size is not positive: %lld bytes. " 405 "Disabling file size limit.", bytes); 406 bytes = 0; // Disable the file size limit for zero or negative values. 407 } else if (bytes <= 1024) { // XXX: 1 kB 408 ALOGE("Max file size is too small: %lld bytes", bytes); 409 return BAD_VALUE; 410 } 411 412 if (bytes <= 100 * 1024) { 413 ALOGW("Target file size (%lld bytes) is too small to be respected", bytes); 414 } 415 416 mMaxFileSizeBytes = bytes; 417 return OK; 418} 419 420status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) { 421 ALOGV("setParamInterleaveDuration: %d", durationUs); 422 if (durationUs <= 500000) { // 500 ms 423 // If interleave duration is too small, it is very inefficient to do 424 // interleaving since the metadata overhead will count for a significant 425 // portion of the saved contents 426 ALOGE("Audio/video interleave duration is too small: %d us", durationUs); 427 return BAD_VALUE; 428 } else if (durationUs >= 10000000) { // 10 seconds 429 // If interleaving duration is too large, it can cause the recording 430 // session to use too much memory since we have to save the output 431 // data before we write them out 432 ALOGE("Audio/video interleave duration is too large: %d us", durationUs); 433 return BAD_VALUE; 434 } 435 mInterleaveDurationUs = durationUs; 436 return OK; 437} 438 439// If seconds < 0, only the first frame is I frame, and rest are all P frames 440// If seconds == 0, all frames are encoded as I frames. No P frames 441// If seconds > 0, it is the time spacing (seconds) between 2 neighboring I frames 442status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) { 443 ALOGV("setParamVideoIFramesInterval: %d seconds", seconds); 444 mIFramesIntervalSec = seconds; 445 return OK; 446} 447 448status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) { 449 ALOGV("setParam64BitFileOffset: %s", 450 use64Bit? "use 64 bit file offset": "use 32 bit file offset"); 451 mUse64BitFileOffset = use64Bit; 452 return OK; 453} 454 455status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) { 456 ALOGV("setParamVideoCameraId: %d", cameraId); 457 if (cameraId < 0) { 458 return BAD_VALUE; 459 } 460 mCameraId = cameraId; 461 return OK; 462} 463 464status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) { 465 ALOGV("setParamTrackTimeStatus: %lld", timeDurationUs); 466 if (timeDurationUs < 20000) { // Infeasible if shorter than 20 ms? 467 ALOGE("Tracking time duration too short: %lld us", timeDurationUs); 468 return BAD_VALUE; 469 } 470 mTrackEveryTimeDurationUs = timeDurationUs; 471 return OK; 472} 473 474status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) { 475 ALOGV("setParamVideoEncoderProfile: %d", profile); 476 477 // Additional check will be done later when we load the encoder. 478 // For now, we are accepting values defined in OpenMAX IL. 479 mVideoEncoderProfile = profile; 480 return OK; 481} 482 483status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) { 484 ALOGV("setParamVideoEncoderLevel: %d", level); 485 486 // Additional check will be done later when we load the encoder. 487 // For now, we are accepting values defined in OpenMAX IL. 488 mVideoEncoderLevel = level; 489 return OK; 490} 491 492status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) { 493 ALOGV("setParamMovieTimeScale: %d", timeScale); 494 495 // The range is set to be the same as the audio's time scale range 496 // since audio's time scale has a wider range. 497 if (timeScale < 600 || timeScale > 96000) { 498 ALOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale); 499 return BAD_VALUE; 500 } 501 mMovieTimeScale = timeScale; 502 return OK; 503} 504 505status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) { 506 ALOGV("setParamVideoTimeScale: %d", timeScale); 507 508 // 60000 is chosen to make sure that each video frame from a 60-fps 509 // video has 1000 ticks. 510 if (timeScale < 600 || timeScale > 60000) { 511 ALOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale); 512 return BAD_VALUE; 513 } 514 mVideoTimeScale = timeScale; 515 return OK; 516} 517 518status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) { 519 ALOGV("setParamAudioTimeScale: %d", timeScale); 520 521 // 96000 Hz is the highest sampling rate support in AAC. 522 if (timeScale < 600 || timeScale > 96000) { 523 ALOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale); 524 return BAD_VALUE; 525 } 526 mAudioTimeScale = timeScale; 527 return OK; 528} 529 530status_t StagefrightRecorder::setParamTimeLapseEnable(int32_t timeLapseEnable) { 531 ALOGV("setParamTimeLapseEnable: %d", timeLapseEnable); 532 533 if(timeLapseEnable == 0) { 534 mCaptureTimeLapse = false; 535 } else if (timeLapseEnable == 1) { 536 mCaptureTimeLapse = true; 537 } else { 538 return BAD_VALUE; 539 } 540 return OK; 541} 542 543status_t StagefrightRecorder::setParamTimeBetweenTimeLapseFrameCapture(int64_t timeUs) { 544 ALOGV("setParamTimeBetweenTimeLapseFrameCapture: %lld us", timeUs); 545 546 // Not allowing time more than a day 547 if (timeUs <= 0 || timeUs > 86400*1E6) { 548 ALOGE("Time between time lapse frame capture (%lld) is out of range [0, 1 Day]", timeUs); 549 return BAD_VALUE; 550 } 551 552 mTimeBetweenTimeLapseFrameCaptureUs = timeUs; 553 return OK; 554} 555 556status_t StagefrightRecorder::setParamGeoDataLongitude( 557 int64_t longitudex10000) { 558 559 if (longitudex10000 > 1800000 || longitudex10000 < -1800000) { 560 return BAD_VALUE; 561 } 562 mLongitudex10000 = longitudex10000; 563 return OK; 564} 565 566status_t StagefrightRecorder::setParamGeoDataLatitude( 567 int64_t latitudex10000) { 568 569 if (latitudex10000 > 900000 || latitudex10000 < -900000) { 570 return BAD_VALUE; 571 } 572 mLatitudex10000 = latitudex10000; 573 return OK; 574} 575 576status_t StagefrightRecorder::setParameter( 577 const String8 &key, const String8 &value) { 578 ALOGV("setParameter: key (%s) => value (%s)", key.string(), value.string()); 579 if (key == "max-duration") { 580 int64_t max_duration_ms; 581 if (safe_strtoi64(value.string(), &max_duration_ms)) { 582 return setParamMaxFileDurationUs(1000LL * max_duration_ms); 583 } 584 } else if (key == "max-filesize") { 585 int64_t max_filesize_bytes; 586 if (safe_strtoi64(value.string(), &max_filesize_bytes)) { 587 return setParamMaxFileSizeBytes(max_filesize_bytes); 588 } 589 } else if (key == "interleave-duration-us") { 590 int32_t durationUs; 591 if (safe_strtoi32(value.string(), &durationUs)) { 592 return setParamInterleaveDuration(durationUs); 593 } 594 } else if (key == "param-movie-time-scale") { 595 int32_t timeScale; 596 if (safe_strtoi32(value.string(), &timeScale)) { 597 return setParamMovieTimeScale(timeScale); 598 } 599 } else if (key == "param-use-64bit-offset") { 600 int32_t use64BitOffset; 601 if (safe_strtoi32(value.string(), &use64BitOffset)) { 602 return setParam64BitFileOffset(use64BitOffset != 0); 603 } 604 } else if (key == "param-geotag-longitude") { 605 int64_t longitudex10000; 606 if (safe_strtoi64(value.string(), &longitudex10000)) { 607 return setParamGeoDataLongitude(longitudex10000); 608 } 609 } else if (key == "param-geotag-latitude") { 610 int64_t latitudex10000; 611 if (safe_strtoi64(value.string(), &latitudex10000)) { 612 return setParamGeoDataLatitude(latitudex10000); 613 } 614 } else if (key == "param-track-time-status") { 615 int64_t timeDurationUs; 616 if (safe_strtoi64(value.string(), &timeDurationUs)) { 617 return setParamTrackTimeStatus(timeDurationUs); 618 } 619 } else if (key == "audio-param-sampling-rate") { 620 int32_t sampling_rate; 621 if (safe_strtoi32(value.string(), &sampling_rate)) { 622 return setParamAudioSamplingRate(sampling_rate); 623 } 624 } else if (key == "audio-param-number-of-channels") { 625 int32_t number_of_channels; 626 if (safe_strtoi32(value.string(), &number_of_channels)) { 627 return setParamAudioNumberOfChannels(number_of_channels); 628 } 629 } else if (key == "audio-param-encoding-bitrate") { 630 int32_t audio_bitrate; 631 if (safe_strtoi32(value.string(), &audio_bitrate)) { 632 return setParamAudioEncodingBitRate(audio_bitrate); 633 } 634 } else if (key == "audio-param-time-scale") { 635 int32_t timeScale; 636 if (safe_strtoi32(value.string(), &timeScale)) { 637 return setParamAudioTimeScale(timeScale); 638 } 639 } else if (key == "video-param-encoding-bitrate") { 640 int32_t video_bitrate; 641 if (safe_strtoi32(value.string(), &video_bitrate)) { 642 return setParamVideoEncodingBitRate(video_bitrate); 643 } 644 } else if (key == "video-param-rotation-angle-degrees") { 645 int32_t degrees; 646 if (safe_strtoi32(value.string(), °rees)) { 647 return setParamVideoRotation(degrees); 648 } 649 } else if (key == "video-param-i-frames-interval") { 650 int32_t seconds; 651 if (safe_strtoi32(value.string(), &seconds)) { 652 return setParamVideoIFramesInterval(seconds); 653 } 654 } else if (key == "video-param-encoder-profile") { 655 int32_t profile; 656 if (safe_strtoi32(value.string(), &profile)) { 657 return setParamVideoEncoderProfile(profile); 658 } 659 } else if (key == "video-param-encoder-level") { 660 int32_t level; 661 if (safe_strtoi32(value.string(), &level)) { 662 return setParamVideoEncoderLevel(level); 663 } 664 } else if (key == "video-param-camera-id") { 665 int32_t cameraId; 666 if (safe_strtoi32(value.string(), &cameraId)) { 667 return setParamVideoCameraId(cameraId); 668 } 669 } else if (key == "video-param-time-scale") { 670 int32_t timeScale; 671 if (safe_strtoi32(value.string(), &timeScale)) { 672 return setParamVideoTimeScale(timeScale); 673 } 674 } else if (key == "time-lapse-enable") { 675 int32_t timeLapseEnable; 676 if (safe_strtoi32(value.string(), &timeLapseEnable)) { 677 return setParamTimeLapseEnable(timeLapseEnable); 678 } 679 } else if (key == "time-between-time-lapse-frame-capture") { 680 int64_t timeBetweenTimeLapseFrameCaptureMs; 681 if (safe_strtoi64(value.string(), &timeBetweenTimeLapseFrameCaptureMs)) { 682 return setParamTimeBetweenTimeLapseFrameCapture( 683 1000LL * timeBetweenTimeLapseFrameCaptureMs); 684 } 685 } else { 686 ALOGE("setParameter: failed to find key %s", key.string()); 687 } 688 return BAD_VALUE; 689} 690 691status_t StagefrightRecorder::setParameters(const String8 ¶ms) { 692 ALOGV("setParameters: %s", params.string()); 693 const char *cparams = params.string(); 694 const char *key_start = cparams; 695 for (;;) { 696 const char *equal_pos = strchr(key_start, '='); 697 if (equal_pos == NULL) { 698 ALOGE("Parameters %s miss a value", cparams); 699 return BAD_VALUE; 700 } 701 String8 key(key_start, equal_pos - key_start); 702 TrimString(&key); 703 if (key.length() == 0) { 704 ALOGE("Parameters %s contains an empty key", cparams); 705 return BAD_VALUE; 706 } 707 const char *value_start = equal_pos + 1; 708 const char *semicolon_pos = strchr(value_start, ';'); 709 String8 value; 710 if (semicolon_pos == NULL) { 711 value.setTo(value_start); 712 } else { 713 value.setTo(value_start, semicolon_pos - value_start); 714 } 715 if (setParameter(key, value) != OK) { 716 return BAD_VALUE; 717 } 718 if (semicolon_pos == NULL) { 719 break; // Reaches the end 720 } 721 key_start = semicolon_pos + 1; 722 } 723 return OK; 724} 725 726status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) { 727 mListener = listener; 728 729 return OK; 730} 731 732status_t StagefrightRecorder::prepare() { 733 return OK; 734} 735 736status_t StagefrightRecorder::start() { 737 CHECK_GE(mOutputFd, 0); 738 739 if (mWriter != NULL) { 740 ALOGE("File writer is not avaialble"); 741 return UNKNOWN_ERROR; 742 } 743 744 status_t status = OK; 745 746 switch (mOutputFormat) { 747 case OUTPUT_FORMAT_DEFAULT: 748 case OUTPUT_FORMAT_THREE_GPP: 749 case OUTPUT_FORMAT_MPEG_4: 750 status = startMPEG4Recording(); 751 break; 752 753 case OUTPUT_FORMAT_AMR_NB: 754 case OUTPUT_FORMAT_AMR_WB: 755 status = startAMRRecording(); 756 break; 757 758 case OUTPUT_FORMAT_AAC_ADIF: 759 case OUTPUT_FORMAT_AAC_ADTS: 760 status = startAACRecording(); 761 break; 762 763 case OUTPUT_FORMAT_RTP_AVP: 764 status = startRTPRecording(); 765 break; 766 767 case OUTPUT_FORMAT_MPEG2TS: 768 status = startMPEG2TSRecording(); 769 break; 770 771 default: 772 ALOGE("Unsupported output file format: %d", mOutputFormat); 773 status = UNKNOWN_ERROR; 774 break; 775 } 776 777 if ((status == OK) && (!mStarted)) { 778 mStarted = true; 779 780 uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted; 781 if (mAudioSource != AUDIO_SOURCE_CNT) { 782 params |= IMediaPlayerService::kBatteryDataTrackAudio; 783 } 784 if (mVideoSource != VIDEO_SOURCE_LIST_END) { 785 params |= IMediaPlayerService::kBatteryDataTrackVideo; 786 } 787 788 addBatteryData(params); 789 } 790 791 return status; 792} 793 794sp<MediaSource> StagefrightRecorder::createAudioSource() { 795 sp<AudioSource> audioSource = 796 new AudioSource( 797 mAudioSource, 798 mSampleRate, 799 mAudioChannels); 800 801 status_t err = audioSource->initCheck(); 802 803 if (err != OK) { 804 ALOGE("audio source is not initialized"); 805 return NULL; 806 } 807 808 sp<MetaData> encMeta = new MetaData; 809 const char *mime; 810 switch (mAudioEncoder) { 811 case AUDIO_ENCODER_AMR_NB: 812 case AUDIO_ENCODER_DEFAULT: 813 mime = MEDIA_MIMETYPE_AUDIO_AMR_NB; 814 break; 815 case AUDIO_ENCODER_AMR_WB: 816 mime = MEDIA_MIMETYPE_AUDIO_AMR_WB; 817 break; 818 case AUDIO_ENCODER_AAC: 819 mime = MEDIA_MIMETYPE_AUDIO_AAC; 820 break; 821 default: 822 ALOGE("Unknown audio encoder: %d", mAudioEncoder); 823 return NULL; 824 } 825 encMeta->setCString(kKeyMIMEType, mime); 826 827 int32_t maxInputSize; 828 CHECK(audioSource->getFormat()->findInt32( 829 kKeyMaxInputSize, &maxInputSize)); 830 831 encMeta->setInt32(kKeyMaxInputSize, maxInputSize); 832 encMeta->setInt32(kKeyChannelCount, mAudioChannels); 833 encMeta->setInt32(kKeySampleRate, mSampleRate); 834 encMeta->setInt32(kKeyBitRate, mAudioBitRate); 835 if (mAudioTimeScale > 0) { 836 encMeta->setInt32(kKeyTimeScale, mAudioTimeScale); 837 } 838 839 OMXClient client; 840 CHECK_EQ(client.connect(), (status_t)OK); 841 842 sp<MediaSource> audioEncoder = 843 OMXCodec::Create(client.interface(), encMeta, 844 true /* createEncoder */, audioSource); 845 mAudioSourceNode = audioSource; 846 847 return audioEncoder; 848} 849 850status_t StagefrightRecorder::startAACRecording() { 851 // FIXME: 852 // Add support for OUTPUT_FORMAT_AAC_ADIF 853 CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS); 854 855 CHECK_EQ(mAudioEncoder, AUDIO_ENCODER_AAC); 856 CHECK(mAudioSource != AUDIO_SOURCE_CNT); 857 858 mWriter = new AACWriter(mOutputFd); 859 status_t status = startRawAudioRecording(); 860 if (status != OK) { 861 mWriter.clear(); 862 mWriter = NULL; 863 } 864 865 return status; 866} 867 868status_t StagefrightRecorder::startAMRRecording() { 869 CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB || 870 mOutputFormat == OUTPUT_FORMAT_AMR_WB); 871 872 if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) { 873 if (mAudioEncoder != AUDIO_ENCODER_DEFAULT && 874 mAudioEncoder != AUDIO_ENCODER_AMR_NB) { 875 ALOGE("Invalid encoder %d used for AMRNB recording", 876 mAudioEncoder); 877 return BAD_VALUE; 878 } 879 } else { // mOutputFormat must be OUTPUT_FORMAT_AMR_WB 880 if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) { 881 ALOGE("Invlaid encoder %d used for AMRWB recording", 882 mAudioEncoder); 883 return BAD_VALUE; 884 } 885 } 886 887 mWriter = new AMRWriter(mOutputFd); 888 status_t status = startRawAudioRecording(); 889 if (status != OK) { 890 mWriter.clear(); 891 mWriter = NULL; 892 } 893 return status; 894} 895 896status_t StagefrightRecorder::startRawAudioRecording() { 897 if (mAudioSource >= AUDIO_SOURCE_CNT) { 898 ALOGE("Invalid audio source: %d", mAudioSource); 899 return BAD_VALUE; 900 } 901 902 status_t status = BAD_VALUE; 903 if (OK != (status = checkAudioEncoderCapabilities())) { 904 return status; 905 } 906 907 sp<MediaSource> audioEncoder = createAudioSource(); 908 if (audioEncoder == NULL) { 909 return UNKNOWN_ERROR; 910 } 911 912 CHECK(mWriter != 0); 913 mWriter->addSource(audioEncoder); 914 915 if (mMaxFileDurationUs != 0) { 916 mWriter->setMaxFileDuration(mMaxFileDurationUs); 917 } 918 if (mMaxFileSizeBytes != 0) { 919 mWriter->setMaxFileSize(mMaxFileSizeBytes); 920 } 921 mWriter->setListener(mListener); 922 mWriter->start(); 923 924 return OK; 925} 926 927status_t StagefrightRecorder::startRTPRecording() { 928 CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP); 929 930 if ((mAudioSource != AUDIO_SOURCE_CNT 931 && mVideoSource != VIDEO_SOURCE_LIST_END) 932 || (mAudioSource == AUDIO_SOURCE_CNT 933 && mVideoSource == VIDEO_SOURCE_LIST_END)) { 934 // Must have exactly one source. 935 return BAD_VALUE; 936 } 937 938 if (mOutputFd < 0) { 939 return BAD_VALUE; 940 } 941 942 sp<MediaSource> source; 943 944 if (mAudioSource != AUDIO_SOURCE_CNT) { 945 source = createAudioSource(); 946 } else { 947 948 sp<MediaSource> mediaSource; 949 status_t err = setupMediaSource(&mediaSource); 950 if (err != OK) { 951 return err; 952 } 953 954 err = setupVideoEncoder(mediaSource, mVideoBitRate, &source); 955 if (err != OK) { 956 return err; 957 } 958 } 959 960 mWriter = new ARTPWriter(mOutputFd); 961 mWriter->addSource(source); 962 mWriter->setListener(mListener); 963 964 return mWriter->start(); 965} 966 967status_t StagefrightRecorder::startMPEG2TSRecording() { 968 CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS); 969 970 sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd); 971 972 if (mAudioSource != AUDIO_SOURCE_CNT) { 973 if (mAudioEncoder != AUDIO_ENCODER_AAC) { 974 return ERROR_UNSUPPORTED; 975 } 976 977 status_t err = setupAudioEncoder(writer); 978 979 if (err != OK) { 980 return err; 981 } 982 } 983 984 if (mVideoSource < VIDEO_SOURCE_LIST_END) { 985 if (mVideoEncoder != VIDEO_ENCODER_H264) { 986 return ERROR_UNSUPPORTED; 987 } 988 989 sp<MediaSource> mediaSource; 990 status_t err = setupMediaSource(&mediaSource); 991 if (err != OK) { 992 return err; 993 } 994 995 sp<MediaSource> encoder; 996 err = setupVideoEncoder(mediaSource, mVideoBitRate, &encoder); 997 998 if (err != OK) { 999 return err; 1000 } 1001 1002 writer->addSource(encoder); 1003 } 1004 1005 if (mMaxFileDurationUs != 0) { 1006 writer->setMaxFileDuration(mMaxFileDurationUs); 1007 } 1008 1009 if (mMaxFileSizeBytes != 0) { 1010 writer->setMaxFileSize(mMaxFileSizeBytes); 1011 } 1012 1013 mWriter = writer; 1014 1015 return mWriter->start(); 1016} 1017 1018void StagefrightRecorder::clipVideoFrameRate() { 1019 ALOGV("clipVideoFrameRate: encoder %d", mVideoEncoder); 1020 int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 1021 "enc.vid.fps.min", mVideoEncoder); 1022 int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 1023 "enc.vid.fps.max", mVideoEncoder); 1024 if (mFrameRate < minFrameRate && mFrameRate != -1) { 1025 ALOGW("Intended video encoding frame rate (%d fps) is too small" 1026 " and will be set to (%d fps)", mFrameRate, minFrameRate); 1027 mFrameRate = minFrameRate; 1028 } else if (mFrameRate > maxFrameRate) { 1029 ALOGW("Intended video encoding frame rate (%d fps) is too large" 1030 " and will be set to (%d fps)", mFrameRate, maxFrameRate); 1031 mFrameRate = maxFrameRate; 1032 } 1033} 1034 1035void StagefrightRecorder::clipVideoBitRate() { 1036 ALOGV("clipVideoBitRate: encoder %d", mVideoEncoder); 1037 int minBitRate = mEncoderProfiles->getVideoEncoderParamByName( 1038 "enc.vid.bps.min", mVideoEncoder); 1039 int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName( 1040 "enc.vid.bps.max", mVideoEncoder); 1041 if (mVideoBitRate < minBitRate) { 1042 ALOGW("Intended video encoding bit rate (%d bps) is too small" 1043 " and will be set to (%d bps)", mVideoBitRate, minBitRate); 1044 mVideoBitRate = minBitRate; 1045 } else if (mVideoBitRate > maxBitRate) { 1046 ALOGW("Intended video encoding bit rate (%d bps) is too large" 1047 " and will be set to (%d bps)", mVideoBitRate, maxBitRate); 1048 mVideoBitRate = maxBitRate; 1049 } 1050} 1051 1052void StagefrightRecorder::clipVideoFrameWidth() { 1053 ALOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder); 1054 int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 1055 "enc.vid.width.min", mVideoEncoder); 1056 int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 1057 "enc.vid.width.max", mVideoEncoder); 1058 if (mVideoWidth < minFrameWidth) { 1059 ALOGW("Intended video encoding frame width (%d) is too small" 1060 " and will be set to (%d)", mVideoWidth, minFrameWidth); 1061 mVideoWidth = minFrameWidth; 1062 } else if (mVideoWidth > maxFrameWidth) { 1063 ALOGW("Intended video encoding frame width (%d) is too large" 1064 " and will be set to (%d)", mVideoWidth, maxFrameWidth); 1065 mVideoWidth = maxFrameWidth; 1066 } 1067} 1068 1069status_t StagefrightRecorder::checkVideoEncoderCapabilities() { 1070 if (!mCaptureTimeLapse) { 1071 // Dont clip for time lapse capture as encoder will have enough 1072 // time to encode because of slow capture rate of time lapse. 1073 clipVideoBitRate(); 1074 clipVideoFrameRate(); 1075 clipVideoFrameWidth(); 1076 clipVideoFrameHeight(); 1077 setDefaultProfileIfNecessary(); 1078 } 1079 return OK; 1080} 1081 1082// Set to use AVC baseline profile if the encoding parameters matches 1083// CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service. 1084void StagefrightRecorder::setDefaultProfileIfNecessary() { 1085 ALOGV("setDefaultProfileIfNecessary"); 1086 1087 camcorder_quality quality = CAMCORDER_QUALITY_LOW; 1088 1089 int64_t durationUs = mEncoderProfiles->getCamcorderProfileParamByName( 1090 "duration", mCameraId, quality) * 1000000LL; 1091 1092 int fileFormat = mEncoderProfiles->getCamcorderProfileParamByName( 1093 "file.format", mCameraId, quality); 1094 1095 int videoCodec = mEncoderProfiles->getCamcorderProfileParamByName( 1096 "vid.codec", mCameraId, quality); 1097 1098 int videoBitRate = mEncoderProfiles->getCamcorderProfileParamByName( 1099 "vid.bps", mCameraId, quality); 1100 1101 int videoFrameRate = mEncoderProfiles->getCamcorderProfileParamByName( 1102 "vid.fps", mCameraId, quality); 1103 1104 int videoFrameWidth = mEncoderProfiles->getCamcorderProfileParamByName( 1105 "vid.width", mCameraId, quality); 1106 1107 int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName( 1108 "vid.height", mCameraId, quality); 1109 1110 int audioCodec = mEncoderProfiles->getCamcorderProfileParamByName( 1111 "aud.codec", mCameraId, quality); 1112 1113 int audioBitRate = mEncoderProfiles->getCamcorderProfileParamByName( 1114 "aud.bps", mCameraId, quality); 1115 1116 int audioSampleRate = mEncoderProfiles->getCamcorderProfileParamByName( 1117 "aud.hz", mCameraId, quality); 1118 1119 int audioChannels = mEncoderProfiles->getCamcorderProfileParamByName( 1120 "aud.ch", mCameraId, quality); 1121 1122 if (durationUs == mMaxFileDurationUs && 1123 fileFormat == mOutputFormat && 1124 videoCodec == mVideoEncoder && 1125 videoBitRate == mVideoBitRate && 1126 videoFrameRate == mFrameRate && 1127 videoFrameWidth == mVideoWidth && 1128 videoFrameHeight == mVideoHeight && 1129 audioCodec == mAudioEncoder && 1130 audioBitRate == mAudioBitRate && 1131 audioSampleRate == mSampleRate && 1132 audioChannels == mAudioChannels) { 1133 if (videoCodec == VIDEO_ENCODER_H264) { 1134 ALOGI("Force to use AVC baseline profile"); 1135 setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline); 1136 } 1137 } 1138} 1139 1140status_t StagefrightRecorder::checkAudioEncoderCapabilities() { 1141 clipAudioBitRate(); 1142 clipAudioSampleRate(); 1143 clipNumberOfAudioChannels(); 1144 return OK; 1145} 1146 1147void StagefrightRecorder::clipAudioBitRate() { 1148 ALOGV("clipAudioBitRate: encoder %d", mAudioEncoder); 1149 1150 int minAudioBitRate = 1151 mEncoderProfiles->getAudioEncoderParamByName( 1152 "enc.aud.bps.min", mAudioEncoder); 1153 if (mAudioBitRate < minAudioBitRate) { 1154 ALOGW("Intended audio encoding bit rate (%d) is too small" 1155 " and will be set to (%d)", mAudioBitRate, minAudioBitRate); 1156 mAudioBitRate = minAudioBitRate; 1157 } 1158 1159 int maxAudioBitRate = 1160 mEncoderProfiles->getAudioEncoderParamByName( 1161 "enc.aud.bps.max", mAudioEncoder); 1162 if (mAudioBitRate > maxAudioBitRate) { 1163 ALOGW("Intended audio encoding bit rate (%d) is too large" 1164 " and will be set to (%d)", mAudioBitRate, maxAudioBitRate); 1165 mAudioBitRate = maxAudioBitRate; 1166 } 1167} 1168 1169void StagefrightRecorder::clipAudioSampleRate() { 1170 ALOGV("clipAudioSampleRate: encoder %d", mAudioEncoder); 1171 1172 int minSampleRate = 1173 mEncoderProfiles->getAudioEncoderParamByName( 1174 "enc.aud.hz.min", mAudioEncoder); 1175 if (mSampleRate < minSampleRate) { 1176 ALOGW("Intended audio sample rate (%d) is too small" 1177 " and will be set to (%d)", mSampleRate, minSampleRate); 1178 mSampleRate = minSampleRate; 1179 } 1180 1181 int maxSampleRate = 1182 mEncoderProfiles->getAudioEncoderParamByName( 1183 "enc.aud.hz.max", mAudioEncoder); 1184 if (mSampleRate > maxSampleRate) { 1185 ALOGW("Intended audio sample rate (%d) is too large" 1186 " and will be set to (%d)", mSampleRate, maxSampleRate); 1187 mSampleRate = maxSampleRate; 1188 } 1189} 1190 1191void StagefrightRecorder::clipNumberOfAudioChannels() { 1192 ALOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder); 1193 1194 int minChannels = 1195 mEncoderProfiles->getAudioEncoderParamByName( 1196 "enc.aud.ch.min", mAudioEncoder); 1197 if (mAudioChannels < minChannels) { 1198 ALOGW("Intended number of audio channels (%d) is too small" 1199 " and will be set to (%d)", mAudioChannels, minChannels); 1200 mAudioChannels = minChannels; 1201 } 1202 1203 int maxChannels = 1204 mEncoderProfiles->getAudioEncoderParamByName( 1205 "enc.aud.ch.max", mAudioEncoder); 1206 if (mAudioChannels > maxChannels) { 1207 ALOGW("Intended number of audio channels (%d) is too large" 1208 " and will be set to (%d)", mAudioChannels, maxChannels); 1209 mAudioChannels = maxChannels; 1210 } 1211} 1212 1213void StagefrightRecorder::clipVideoFrameHeight() { 1214 ALOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder); 1215 int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 1216 "enc.vid.height.min", mVideoEncoder); 1217 int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 1218 "enc.vid.height.max", mVideoEncoder); 1219 if (mVideoHeight < minFrameHeight) { 1220 ALOGW("Intended video encoding frame height (%d) is too small" 1221 " and will be set to (%d)", mVideoHeight, minFrameHeight); 1222 mVideoHeight = minFrameHeight; 1223 } else if (mVideoHeight > maxFrameHeight) { 1224 ALOGW("Intended video encoding frame height (%d) is too large" 1225 " and will be set to (%d)", mVideoHeight, maxFrameHeight); 1226 mVideoHeight = maxFrameHeight; 1227 } 1228} 1229 1230// Set up the appropriate MediaSource depending on the chosen option 1231status_t StagefrightRecorder::setupMediaSource( 1232 sp<MediaSource> *mediaSource) { 1233 if (mVideoSource == VIDEO_SOURCE_DEFAULT 1234 || mVideoSource == VIDEO_SOURCE_CAMERA) { 1235 sp<CameraSource> cameraSource; 1236 status_t err = setupCameraSource(&cameraSource); 1237 if (err != OK) { 1238 return err; 1239 } 1240 *mediaSource = cameraSource; 1241 } else if (mVideoSource == VIDEO_SOURCE_GRALLOC_BUFFER) { 1242 // If using GRAlloc buffers, setup surfacemediasource. 1243 // Later a handle to that will be passed 1244 // to the client side when queried 1245 status_t err = setupSurfaceMediaSource(); 1246 if (err != OK) { 1247 return err; 1248 } 1249 *mediaSource = mSurfaceMediaSource; 1250 } else { 1251 return INVALID_OPERATION; 1252 } 1253 return OK; 1254} 1255 1256// setupSurfaceMediaSource creates a source with the given 1257// width and height and framerate. 1258// TODO: This could go in a static function inside SurfaceMediaSource 1259// similar to that in CameraSource 1260status_t StagefrightRecorder::setupSurfaceMediaSource() { 1261 status_t err = OK; 1262 mSurfaceMediaSource = new SurfaceMediaSource(mVideoWidth, mVideoHeight); 1263 if (mSurfaceMediaSource == NULL) { 1264 return NO_INIT; 1265 } 1266 1267 if (mFrameRate == -1) { 1268 int32_t frameRate = 0; 1269 CHECK (mSurfaceMediaSource->getFormat()->findInt32( 1270 kKeyFrameRate, &frameRate)); 1271 ALOGI("Frame rate is not explicitly set. Use the current frame " 1272 "rate (%d fps)", frameRate); 1273 mFrameRate = frameRate; 1274 } else { 1275 err = mSurfaceMediaSource->setFrameRate(mFrameRate); 1276 } 1277 CHECK(mFrameRate != -1); 1278 1279 mIsMetaDataStoredInVideoBuffers = 1280 mSurfaceMediaSource->isMetaDataStoredInVideoBuffers(); 1281 return err; 1282} 1283 1284status_t StagefrightRecorder::setupCameraSource( 1285 sp<CameraSource> *cameraSource) { 1286 status_t err = OK; 1287 if ((err = checkVideoEncoderCapabilities()) != OK) { 1288 return err; 1289 } 1290 Size videoSize; 1291 videoSize.width = mVideoWidth; 1292 videoSize.height = mVideoHeight; 1293 if (mCaptureTimeLapse) { 1294 if (mTimeBetweenTimeLapseFrameCaptureUs < 0) { 1295 ALOGE("Invalid mTimeBetweenTimeLapseFrameCaptureUs value: %lld", 1296 mTimeBetweenTimeLapseFrameCaptureUs); 1297 return BAD_VALUE; 1298 } 1299 1300 mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera( 1301 mCamera, mCameraProxy, mCameraId, 1302 videoSize, mFrameRate, mPreviewSurface, 1303 mTimeBetweenTimeLapseFrameCaptureUs); 1304 *cameraSource = mCameraSourceTimeLapse; 1305 } else { 1306 *cameraSource = CameraSource::CreateFromCamera( 1307 mCamera, mCameraProxy, mCameraId, videoSize, mFrameRate, 1308 mPreviewSurface, true /*storeMetaDataInVideoBuffers*/); 1309 } 1310 mCamera.clear(); 1311 mCameraProxy.clear(); 1312 if (*cameraSource == NULL) { 1313 return UNKNOWN_ERROR; 1314 } 1315 1316 if ((*cameraSource)->initCheck() != OK) { 1317 (*cameraSource).clear(); 1318 *cameraSource = NULL; 1319 return NO_INIT; 1320 } 1321 1322 // When frame rate is not set, the actual frame rate will be set to 1323 // the current frame rate being used. 1324 if (mFrameRate == -1) { 1325 int32_t frameRate = 0; 1326 CHECK ((*cameraSource)->getFormat()->findInt32( 1327 kKeyFrameRate, &frameRate)); 1328 ALOGI("Frame rate is not explicitly set. Use the current frame " 1329 "rate (%d fps)", frameRate); 1330 mFrameRate = frameRate; 1331 } 1332 1333 CHECK(mFrameRate != -1); 1334 1335 mIsMetaDataStoredInVideoBuffers = 1336 (*cameraSource)->isMetaDataStoredInVideoBuffers(); 1337 1338 return OK; 1339} 1340 1341status_t StagefrightRecorder::setupVideoEncoder( 1342 sp<MediaSource> cameraSource, 1343 int32_t videoBitRate, 1344 sp<MediaSource> *source) { 1345 source->clear(); 1346 1347 sp<MetaData> enc_meta = new MetaData; 1348 enc_meta->setInt32(kKeyBitRate, videoBitRate); 1349 enc_meta->setInt32(kKeyFrameRate, mFrameRate); 1350 1351 switch (mVideoEncoder) { 1352 case VIDEO_ENCODER_H263: 1353 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 1354 break; 1355 1356 case VIDEO_ENCODER_MPEG_4_SP: 1357 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 1358 break; 1359 1360 case VIDEO_ENCODER_H264: 1361 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 1362 break; 1363 1364 default: 1365 CHECK(!"Should not be here, unsupported video encoding."); 1366 break; 1367 } 1368 1369 sp<MetaData> meta = cameraSource->getFormat(); 1370 1371 int32_t width, height, stride, sliceHeight, colorFormat; 1372 CHECK(meta->findInt32(kKeyWidth, &width)); 1373 CHECK(meta->findInt32(kKeyHeight, &height)); 1374 CHECK(meta->findInt32(kKeyStride, &stride)); 1375 CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); 1376 CHECK(meta->findInt32(kKeyColorFormat, &colorFormat)); 1377 1378 enc_meta->setInt32(kKeyWidth, width); 1379 enc_meta->setInt32(kKeyHeight, height); 1380 enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec); 1381 enc_meta->setInt32(kKeyStride, stride); 1382 enc_meta->setInt32(kKeySliceHeight, sliceHeight); 1383 enc_meta->setInt32(kKeyColorFormat, colorFormat); 1384 if (mVideoTimeScale > 0) { 1385 enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale); 1386 } 1387 if (mVideoEncoderProfile != -1) { 1388 enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile); 1389 } 1390 if (mVideoEncoderLevel != -1) { 1391 enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel); 1392 } 1393 1394 OMXClient client; 1395 CHECK_EQ(client.connect(), (status_t)OK); 1396 1397 uint32_t encoder_flags = 0; 1398 if (mIsMetaDataStoredInVideoBuffers) { 1399 encoder_flags |= OMXCodec::kHardwareCodecsOnly; 1400 encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers; 1401 } 1402 1403 // Do not wait for all the input buffers to become available. 1404 // This give timelapse video recording faster response in 1405 // receiving output from video encoder component. 1406 if (mCaptureTimeLapse) { 1407 encoder_flags |= OMXCodec::kOnlySubmitOneInputBufferAtOneTime; 1408 } 1409 1410 sp<MediaSource> encoder = OMXCodec::Create( 1411 client.interface(), enc_meta, 1412 true /* createEncoder */, cameraSource, 1413 NULL, encoder_flags); 1414 if (encoder == NULL) { 1415 ALOGW("Failed to create the encoder"); 1416 // When the encoder fails to be created, we need 1417 // release the camera source due to the camera's lock 1418 // and unlock mechanism. 1419 cameraSource->stop(); 1420 return UNKNOWN_ERROR; 1421 } 1422 1423 *source = encoder; 1424 1425 return OK; 1426} 1427 1428status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) { 1429 status_t status = BAD_VALUE; 1430 if (OK != (status = checkAudioEncoderCapabilities())) { 1431 return status; 1432 } 1433 1434 switch(mAudioEncoder) { 1435 case AUDIO_ENCODER_AMR_NB: 1436 case AUDIO_ENCODER_AMR_WB: 1437 case AUDIO_ENCODER_AAC: 1438 break; 1439 1440 default: 1441 ALOGE("Unsupported audio encoder: %d", mAudioEncoder); 1442 return UNKNOWN_ERROR; 1443 } 1444 1445 sp<MediaSource> audioEncoder = createAudioSource(); 1446 if (audioEncoder == NULL) { 1447 return UNKNOWN_ERROR; 1448 } 1449 1450 writer->addSource(audioEncoder); 1451 return OK; 1452} 1453 1454status_t StagefrightRecorder::setupMPEG4Recording( 1455 int outputFd, 1456 int32_t videoWidth, int32_t videoHeight, 1457 int32_t videoBitRate, 1458 int32_t *totalBitRate, 1459 sp<MediaWriter> *mediaWriter) { 1460 mediaWriter->clear(); 1461 *totalBitRate = 0; 1462 status_t err = OK; 1463 sp<MediaWriter> writer = new MPEG4Writer(outputFd); 1464 1465 if (mVideoSource < VIDEO_SOURCE_LIST_END) { 1466 1467 sp<MediaSource> mediaSource; 1468 err = setupMediaSource(&mediaSource); 1469 if (err != OK) { 1470 return err; 1471 } 1472 1473 sp<MediaSource> encoder; 1474 err = setupVideoEncoder(mediaSource, videoBitRate, &encoder); 1475 if (err != OK) { 1476 return err; 1477 } 1478 1479 writer->addSource(encoder); 1480 *totalBitRate += videoBitRate; 1481 } 1482 1483 // Audio source is added at the end if it exists. 1484 // This help make sure that the "recoding" sound is suppressed for 1485 // camcorder applications in the recorded files. 1486 if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_CNT)) { 1487 err = setupAudioEncoder(writer); 1488 if (err != OK) return err; 1489 *totalBitRate += mAudioBitRate; 1490 } 1491 1492 if (mInterleaveDurationUs > 0) { 1493 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1494 setInterleaveDuration(mInterleaveDurationUs); 1495 } 1496 if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) { 1497 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1498 setGeoData(mLatitudex10000, mLongitudex10000); 1499 } 1500 if (mMaxFileDurationUs != 0) { 1501 writer->setMaxFileDuration(mMaxFileDurationUs); 1502 } 1503 if (mMaxFileSizeBytes != 0) { 1504 writer->setMaxFileSize(mMaxFileSizeBytes); 1505 } 1506 1507 mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId); 1508 if (mStartTimeOffsetMs > 0) { 1509 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1510 setStartTimeOffsetMs(mStartTimeOffsetMs); 1511 } 1512 1513 writer->setListener(mListener); 1514 *mediaWriter = writer; 1515 return OK; 1516} 1517 1518void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate, 1519 sp<MetaData> *meta) { 1520 (*meta)->setInt64(kKeyTime, startTimeUs); 1521 (*meta)->setInt32(kKeyFileType, mOutputFormat); 1522 (*meta)->setInt32(kKeyBitRate, totalBitRate); 1523 (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset); 1524 if (mMovieTimeScale > 0) { 1525 (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale); 1526 } 1527 if (mTrackEveryTimeDurationUs > 0) { 1528 (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs); 1529 } 1530 if (mRotationDegrees != 0) { 1531 (*meta)->setInt32(kKeyRotation, mRotationDegrees); 1532 } 1533} 1534 1535status_t StagefrightRecorder::startMPEG4Recording() { 1536 int32_t totalBitRate; 1537 status_t err = setupMPEG4Recording( 1538 mOutputFd, mVideoWidth, mVideoHeight, 1539 mVideoBitRate, &totalBitRate, &mWriter); 1540 if (err != OK) { 1541 return err; 1542 } 1543 1544 int64_t startTimeUs = systemTime() / 1000; 1545 sp<MetaData> meta = new MetaData; 1546 setupMPEG4MetaData(startTimeUs, totalBitRate, &meta); 1547 1548 err = mWriter->start(meta.get()); 1549 if (err != OK) { 1550 return err; 1551 } 1552 1553 return OK; 1554} 1555 1556status_t StagefrightRecorder::pause() { 1557 ALOGV("pause"); 1558 if (mWriter == NULL) { 1559 return UNKNOWN_ERROR; 1560 } 1561 mWriter->pause(); 1562 1563 if (mStarted) { 1564 mStarted = false; 1565 1566 uint32_t params = 0; 1567 if (mAudioSource != AUDIO_SOURCE_CNT) { 1568 params |= IMediaPlayerService::kBatteryDataTrackAudio; 1569 } 1570 if (mVideoSource != VIDEO_SOURCE_LIST_END) { 1571 params |= IMediaPlayerService::kBatteryDataTrackVideo; 1572 } 1573 1574 addBatteryData(params); 1575 } 1576 1577 1578 return OK; 1579} 1580 1581status_t StagefrightRecorder::stop() { 1582 ALOGV("stop"); 1583 status_t err = OK; 1584 1585 if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) { 1586 mCameraSourceTimeLapse->startQuickReadReturns(); 1587 mCameraSourceTimeLapse = NULL; 1588 } 1589 1590 if (mWriter != NULL) { 1591 err = mWriter->stop(); 1592 mWriter.clear(); 1593 } 1594 1595 if (mOutputFd >= 0) { 1596 ::close(mOutputFd); 1597 mOutputFd = -1; 1598 } 1599 1600 if (mStarted) { 1601 mStarted = false; 1602 1603 uint32_t params = 0; 1604 if (mAudioSource != AUDIO_SOURCE_CNT) { 1605 params |= IMediaPlayerService::kBatteryDataTrackAudio; 1606 } 1607 if (mVideoSource != VIDEO_SOURCE_LIST_END) { 1608 params |= IMediaPlayerService::kBatteryDataTrackVideo; 1609 } 1610 1611 addBatteryData(params); 1612 } 1613 1614 1615 return err; 1616} 1617 1618status_t StagefrightRecorder::close() { 1619 ALOGV("close"); 1620 stop(); 1621 1622 return OK; 1623} 1624 1625status_t StagefrightRecorder::reset() { 1626 ALOGV("reset"); 1627 stop(); 1628 1629 // No audio or video source by default 1630 mAudioSource = AUDIO_SOURCE_CNT; 1631 mVideoSource = VIDEO_SOURCE_LIST_END; 1632 1633 // Default parameters 1634 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 1635 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 1636 mVideoEncoder = VIDEO_ENCODER_H263; 1637 mVideoWidth = 176; 1638 mVideoHeight = 144; 1639 mFrameRate = -1; 1640 mVideoBitRate = 192000; 1641 mSampleRate = 8000; 1642 mAudioChannels = 1; 1643 mAudioBitRate = 12200; 1644 mInterleaveDurationUs = 0; 1645 mIFramesIntervalSec = 1; 1646 mAudioSourceNode = 0; 1647 mUse64BitFileOffset = false; 1648 mMovieTimeScale = -1; 1649 mAudioTimeScale = -1; 1650 mVideoTimeScale = -1; 1651 mCameraId = 0; 1652 mStartTimeOffsetMs = -1; 1653 mVideoEncoderProfile = -1; 1654 mVideoEncoderLevel = -1; 1655 mMaxFileDurationUs = 0; 1656 mMaxFileSizeBytes = 0; 1657 mTrackEveryTimeDurationUs = 0; 1658 mCaptureTimeLapse = false; 1659 mTimeBetweenTimeLapseFrameCaptureUs = -1; 1660 mCameraSourceTimeLapse = NULL; 1661 mIsMetaDataStoredInVideoBuffers = false; 1662 mEncoderProfiles = MediaProfiles::getInstance(); 1663 mRotationDegrees = 0; 1664 mLatitudex10000 = -3600000; 1665 mLongitudex10000 = -3600000; 1666 1667 mOutputFd = -1; 1668 1669 return OK; 1670} 1671 1672status_t StagefrightRecorder::getMaxAmplitude(int *max) { 1673 ALOGV("getMaxAmplitude"); 1674 1675 if (max == NULL) { 1676 ALOGE("Null pointer argument"); 1677 return BAD_VALUE; 1678 } 1679 1680 if (mAudioSourceNode != 0) { 1681 *max = mAudioSourceNode->getMaxAmplitude(); 1682 } else { 1683 *max = 0; 1684 } 1685 1686 return OK; 1687} 1688 1689status_t StagefrightRecorder::dump( 1690 int fd, const Vector<String16>& args) const { 1691 ALOGV("dump"); 1692 const size_t SIZE = 256; 1693 char buffer[SIZE]; 1694 String8 result; 1695 if (mWriter != 0) { 1696 mWriter->dump(fd, args); 1697 } else { 1698 snprintf(buffer, SIZE, " No file writer\n"); 1699 result.append(buffer); 1700 } 1701 snprintf(buffer, SIZE, " Recorder: %p\n", this); 1702 snprintf(buffer, SIZE, " Output file (fd %d):\n", mOutputFd); 1703 result.append(buffer); 1704 snprintf(buffer, SIZE, " File format: %d\n", mOutputFormat); 1705 result.append(buffer); 1706 snprintf(buffer, SIZE, " Max file size (bytes): %lld\n", mMaxFileSizeBytes); 1707 result.append(buffer); 1708 snprintf(buffer, SIZE, " Max file duration (us): %lld\n", mMaxFileDurationUs); 1709 result.append(buffer); 1710 snprintf(buffer, SIZE, " File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32); 1711 result.append(buffer); 1712 snprintf(buffer, SIZE, " Interleave duration (us): %d\n", mInterleaveDurationUs); 1713 result.append(buffer); 1714 snprintf(buffer, SIZE, " Progress notification: %lld us\n", mTrackEveryTimeDurationUs); 1715 result.append(buffer); 1716 snprintf(buffer, SIZE, " Audio\n"); 1717 result.append(buffer); 1718 snprintf(buffer, SIZE, " Source: %d\n", mAudioSource); 1719 result.append(buffer); 1720 snprintf(buffer, SIZE, " Encoder: %d\n", mAudioEncoder); 1721 result.append(buffer); 1722 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mAudioBitRate); 1723 result.append(buffer); 1724 snprintf(buffer, SIZE, " Sampling rate (hz): %d\n", mSampleRate); 1725 result.append(buffer); 1726 snprintf(buffer, SIZE, " Number of channels: %d\n", mAudioChannels); 1727 result.append(buffer); 1728 snprintf(buffer, SIZE, " Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude()); 1729 result.append(buffer); 1730 snprintf(buffer, SIZE, " Video\n"); 1731 result.append(buffer); 1732 snprintf(buffer, SIZE, " Source: %d\n", mVideoSource); 1733 result.append(buffer); 1734 snprintf(buffer, SIZE, " Camera Id: %d\n", mCameraId); 1735 result.append(buffer); 1736 snprintf(buffer, SIZE, " Start time offset (ms): %d\n", mStartTimeOffsetMs); 1737 result.append(buffer); 1738 snprintf(buffer, SIZE, " Encoder: %d\n", mVideoEncoder); 1739 result.append(buffer); 1740 snprintf(buffer, SIZE, " Encoder profile: %d\n", mVideoEncoderProfile); 1741 result.append(buffer); 1742 snprintf(buffer, SIZE, " Encoder level: %d\n", mVideoEncoderLevel); 1743 result.append(buffer); 1744 snprintf(buffer, SIZE, " I frames interval (s): %d\n", mIFramesIntervalSec); 1745 result.append(buffer); 1746 snprintf(buffer, SIZE, " Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight); 1747 result.append(buffer); 1748 snprintf(buffer, SIZE, " Frame rate (fps): %d\n", mFrameRate); 1749 result.append(buffer); 1750 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mVideoBitRate); 1751 result.append(buffer); 1752 ::write(fd, result.string(), result.size()); 1753 return OK; 1754} 1755} // namespace android 1756