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