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/CameraSourceTimeLapse.h> 32 #include <media/stagefright/MPEG2TSWriter.h> 33 #include <media/stagefright/MPEG4Writer.h> 34 #include <media/stagefright/MediaDebug.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 <surfaceflinger/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 54 namespace android { 55 56 // To collect the encoder usage for the battery app 57 static 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 67 StagefrightRecorder::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 LOGV("Constructor"); 75 reset(); 76 } 77 78 StagefrightRecorder::~StagefrightRecorder() { 79 LOGV("Destructor"); 80 stop(); 81 } 82 83 status_t StagefrightRecorder::init() { 84 LOGV("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 91 sp<ISurfaceTexture> StagefrightRecorder::querySurfaceMediaSource() const { 92 LOGV("Get SurfaceMediaSource"); 93 return mSurfaceMediaSource; 94 } 95 96 status_t StagefrightRecorder::setAudioSource(audio_source_t as) { 97 LOGV("setAudioSource: %d", as); 98 if (as < AUDIO_SOURCE_DEFAULT || 99 as >= AUDIO_SOURCE_CNT) { 100 LOGE("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 113 status_t StagefrightRecorder::setVideoSource(video_source vs) { 114 LOGV("setVideoSource: %d", vs); 115 if (vs < VIDEO_SOURCE_DEFAULT || 116 vs >= VIDEO_SOURCE_LIST_END) { 117 LOGE("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 130 status_t StagefrightRecorder::setOutputFormat(output_format of) { 131 LOGV("setOutputFormat: %d", of); 132 if (of < OUTPUT_FORMAT_DEFAULT || 133 of >= OUTPUT_FORMAT_LIST_END) { 134 LOGE("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 147 status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) { 148 LOGV("setAudioEncoder: %d", ae); 149 if (ae < AUDIO_ENCODER_DEFAULT || 150 ae >= AUDIO_ENCODER_LIST_END) { 151 LOGE("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 164 status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) { 165 LOGV("setVideoEncoder: %d", ve); 166 if (ve < VIDEO_ENCODER_DEFAULT || 167 ve >= VIDEO_ENCODER_LIST_END) { 168 LOGE("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 181 status_t StagefrightRecorder::setVideoSize(int width, int height) { 182 LOGV("setVideoSize: %dx%d", width, height); 183 if (width <= 0 || height <= 0) { 184 LOGE("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 195 status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) { 196 LOGV("setVideoFrameRate: %d", frames_per_second); 197 if ((frames_per_second <= 0 && frames_per_second != -1) || 198 frames_per_second > 120) { 199 LOGE("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 209 status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera, 210 const sp<ICameraRecordingProxy> &proxy) { 211 LOGV("setCamera"); 212 if (camera == 0) { 213 LOGE("camera is NULL"); 214 return BAD_VALUE; 215 } 216 if (proxy == 0) { 217 LOGE("camera proxy is NULL"); 218 return BAD_VALUE; 219 } 220 221 mCamera = camera; 222 mCameraProxy = proxy; 223 return OK; 224 } 225 226 status_t StagefrightRecorder::setPreviewSurface(const sp<Surface> &surface) { 227 LOGV("setPreviewSurface: %p", surface.get()); 228 mPreviewSurface = surface; 229 230 return OK; 231 } 232 233 status_t StagefrightRecorder::setOutputFile(const char *path) { 234 LOGE("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 241 status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) { 242 LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length); 243 // These don't make any sense, do they? 244 CHECK_EQ(offset, 0); 245 CHECK_EQ(length, 0); 246 247 if (fd < 0) { 248 LOGE("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. 262 static 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] 286 static 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. 298 static 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 315 status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) { 316 LOGV("setParamAudioSamplingRate: %d", sampleRate); 317 if (sampleRate <= 0) { 318 LOGE("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 327 status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) { 328 LOGV("setParamAudioNumberOfChannels: %d", channels); 329 if (channels <= 0 || channels >= 3) { 330 LOGE("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 339 status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) { 340 LOGV("setParamAudioEncodingBitRate: %d", bitRate); 341 if (bitRate <= 0) { 342 LOGE("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 354 status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) { 355 LOGV("setParamVideoEncodingBitRate: %d", bitRate); 356 if (bitRate <= 0) { 357 LOGE("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. 370 status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) { 371 LOGV("setParamVideoRotation: %d", degrees); 372 if (degrees < 0 || degrees % 90 != 0) { 373 LOGE("Unsupported video rotation angle: %d", degrees); 374 return BAD_VALUE; 375 } 376 mRotationDegrees = degrees % 360; 377 return OK; 378 } 379 380 status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) { 381 LOGV("setParamMaxFileDurationUs: %lld us", timeUs); 382 383 // This is meant for backward compatibility for MediaRecorder.java 384 if (timeUs <= 0) { 385 LOGW("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 LOGE("Max file duration is too short: %lld us", timeUs); 389 return BAD_VALUE; 390 } 391 392 if (timeUs <= 15 * 1000000LL) { 393 LOGW("Target duration (%lld us) too short to be respected", timeUs); 394 } 395 mMaxFileDurationUs = timeUs; 396 return OK; 397 } 398 399 status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) { 400 LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes); 401 402 // This is meant for backward compatibility for MediaRecorder.java 403 if (bytes <= 0) { 404 LOGW("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 LOGE("Max file size is too small: %lld bytes", bytes); 409 return BAD_VALUE; 410 } 411 412 if (bytes <= 100 * 1024) { 413 LOGW("Target file size (%lld bytes) is too small to be respected", bytes); 414 } 415 416 mMaxFileSizeBytes = bytes; 417 return OK; 418 } 419 420 status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) { 421 LOGV("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 LOGE("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 LOGE("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 442 status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) { 443 LOGV("setParamVideoIFramesInterval: %d seconds", seconds); 444 mIFramesIntervalSec = seconds; 445 return OK; 446 } 447 448 status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) { 449 LOGV("setParam64BitFileOffset: %s", 450 use64Bit? "use 64 bit file offset": "use 32 bit file offset"); 451 mUse64BitFileOffset = use64Bit; 452 return OK; 453 } 454 455 status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) { 456 LOGV("setParamVideoCameraId: %d", cameraId); 457 if (cameraId < 0) { 458 return BAD_VALUE; 459 } 460 mCameraId = cameraId; 461 return OK; 462 } 463 464 status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) { 465 LOGV("setParamTrackTimeStatus: %lld", timeDurationUs); 466 if (timeDurationUs < 20000) { // Infeasible if shorter than 20 ms? 467 LOGE("Tracking time duration too short: %lld us", timeDurationUs); 468 return BAD_VALUE; 469 } 470 mTrackEveryTimeDurationUs = timeDurationUs; 471 return OK; 472 } 473 474 status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) { 475 LOGV("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 483 status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) { 484 LOGV("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 492 status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) { 493 LOGV("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 LOGE("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 505 status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) { 506 LOGV("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 LOGE("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 518 status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) { 519 LOGV("setParamAudioTimeScale: %d", timeScale); 520 521 // 96000 Hz is the highest sampling rate support in AAC. 522 if (timeScale < 600 || timeScale > 96000) { 523 LOGE("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 530 status_t StagefrightRecorder::setParamTimeLapseEnable(int32_t timeLapseEnable) { 531 LOGV("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 543 status_t StagefrightRecorder::setParamTimeBetweenTimeLapseFrameCapture(int64_t timeUs) { 544 LOGV("setParamTimeBetweenTimeLapseFrameCapture: %lld us", timeUs); 545 546 // Not allowing time more than a day 547 if (timeUs <= 0 || timeUs > 86400*1E6) { 548 LOGE("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 556 status_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 566 status_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 576 status_t StagefrightRecorder::setParameter( 577 const String8 &key, const String8 &value) { 578 LOGV("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 LOGE("setParameter: failed to find key %s", key.string()); 687 } 688 return BAD_VALUE; 689 } 690 691 status_t StagefrightRecorder::setParameters(const String8 ¶ms) { 692 LOGV("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 LOGE("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 LOGE("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 726 status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) { 727 mListener = listener; 728 729 return OK; 730 } 731 732 status_t StagefrightRecorder::prepare() { 733 return OK; 734 } 735 736 status_t StagefrightRecorder::start() { 737 CHECK(mOutputFd >= 0); 738 739 if (mWriter != NULL) { 740 LOGE("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 LOGE("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 794 sp<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 LOGE("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 LOGE("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(), 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 850 status_t StagefrightRecorder::startAACRecording() { 851 // FIXME: 852 // Add support for OUTPUT_FORMAT_AAC_ADIF 853 CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADTS); 854 855 CHECK(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 868 status_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 LOGE("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 LOGE("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 896 status_t StagefrightRecorder::startRawAudioRecording() { 897 if (mAudioSource >= AUDIO_SOURCE_CNT) { 898 LOGE("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 927 status_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 967 status_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 1018 void StagefrightRecorder::clipVideoFrameRate() { 1019 LOGV("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 LOGW("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 LOGW("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 1035 void StagefrightRecorder::clipVideoBitRate() { 1036 LOGV("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 LOGW("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 LOGW("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 1052 void StagefrightRecorder::clipVideoFrameWidth() { 1053 LOGV("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 LOGW("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 LOGW("Intended video encoding frame width (%d) is too large" 1064 " and will be set to (%d)", mVideoWidth, maxFrameWidth); 1065 mVideoWidth = maxFrameWidth; 1066 } 1067 } 1068 1069 status_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. 1084 void StagefrightRecorder::setDefaultProfileIfNecessary() { 1085 LOGV("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 LOGI("Force to use AVC baseline profile"); 1135 setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline); 1136 } 1137 } 1138 } 1139 1140 status_t StagefrightRecorder::checkAudioEncoderCapabilities() { 1141 clipAudioBitRate(); 1142 clipAudioSampleRate(); 1143 clipNumberOfAudioChannels(); 1144 return OK; 1145 } 1146 1147 void StagefrightRecorder::clipAudioBitRate() { 1148 LOGV("clipAudioBitRate: encoder %d", mAudioEncoder); 1149 1150 int minAudioBitRate = 1151 mEncoderProfiles->getAudioEncoderParamByName( 1152 "enc.aud.bps.min", mAudioEncoder); 1153 if (mAudioBitRate < minAudioBitRate) { 1154 LOGW("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 LOGW("Intended audio encoding bit rate (%d) is too large" 1164 " and will be set to (%d)", mAudioBitRate, maxAudioBitRate); 1165 mAudioBitRate = maxAudioBitRate; 1166 } 1167 } 1168 1169 void StagefrightRecorder::clipAudioSampleRate() { 1170 LOGV("clipAudioSampleRate: encoder %d", mAudioEncoder); 1171 1172 int minSampleRate = 1173 mEncoderProfiles->getAudioEncoderParamByName( 1174 "enc.aud.hz.min", mAudioEncoder); 1175 if (mSampleRate < minSampleRate) { 1176 LOGW("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 LOGW("Intended audio sample rate (%d) is too large" 1186 " and will be set to (%d)", mSampleRate, maxSampleRate); 1187 mSampleRate = maxSampleRate; 1188 } 1189 } 1190 1191 void StagefrightRecorder::clipNumberOfAudioChannels() { 1192 LOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder); 1193 1194 int minChannels = 1195 mEncoderProfiles->getAudioEncoderParamByName( 1196 "enc.aud.ch.min", mAudioEncoder); 1197 if (mAudioChannels < minChannels) { 1198 LOGW("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 LOGW("Intended number of audio channels (%d) is too large" 1208 " and will be set to (%d)", mAudioChannels, maxChannels); 1209 mAudioChannels = maxChannels; 1210 } 1211 } 1212 1213 void StagefrightRecorder::clipVideoFrameHeight() { 1214 LOGV("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 LOGW("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 LOGW("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 1231 status_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 1260 status_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 LOGI("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 1284 status_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 mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera( 1295 mCamera, mCameraProxy, mCameraId, 1296 videoSize, mFrameRate, mPreviewSurface, 1297 mTimeBetweenTimeLapseFrameCaptureUs); 1298 *cameraSource = mCameraSourceTimeLapse; 1299 } else { 1300 *cameraSource = CameraSource::CreateFromCamera( 1301 mCamera, mCameraProxy, mCameraId, videoSize, mFrameRate, 1302 mPreviewSurface, true /*storeMetaDataInVideoBuffers*/); 1303 } 1304 mCamera.clear(); 1305 mCameraProxy.clear(); 1306 if (*cameraSource == NULL) { 1307 return UNKNOWN_ERROR; 1308 } 1309 1310 if ((*cameraSource)->initCheck() != OK) { 1311 (*cameraSource).clear(); 1312 *cameraSource = NULL; 1313 return NO_INIT; 1314 } 1315 1316 // When frame rate is not set, the actual frame rate will be set to 1317 // the current frame rate being used. 1318 if (mFrameRate == -1) { 1319 int32_t frameRate = 0; 1320 CHECK ((*cameraSource)->getFormat()->findInt32( 1321 kKeyFrameRate, &frameRate)); 1322 LOGI("Frame rate is not explicitly set. Use the current frame " 1323 "rate (%d fps)", frameRate); 1324 mFrameRate = frameRate; 1325 } 1326 1327 CHECK(mFrameRate != -1); 1328 1329 mIsMetaDataStoredInVideoBuffers = 1330 (*cameraSource)->isMetaDataStoredInVideoBuffers(); 1331 1332 return OK; 1333 } 1334 1335 status_t StagefrightRecorder::setupVideoEncoder( 1336 sp<MediaSource> cameraSource, 1337 int32_t videoBitRate, 1338 sp<MediaSource> *source) { 1339 source->clear(); 1340 1341 sp<MetaData> enc_meta = new MetaData; 1342 enc_meta->setInt32(kKeyBitRate, videoBitRate); 1343 enc_meta->setInt32(kKeyFrameRate, mFrameRate); 1344 1345 switch (mVideoEncoder) { 1346 case VIDEO_ENCODER_H263: 1347 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 1348 break; 1349 1350 case VIDEO_ENCODER_MPEG_4_SP: 1351 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 1352 break; 1353 1354 case VIDEO_ENCODER_H264: 1355 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 1356 break; 1357 1358 default: 1359 CHECK(!"Should not be here, unsupported video encoding."); 1360 break; 1361 } 1362 1363 sp<MetaData> meta = cameraSource->getFormat(); 1364 1365 int32_t width, height, stride, sliceHeight, colorFormat; 1366 CHECK(meta->findInt32(kKeyWidth, &width)); 1367 CHECK(meta->findInt32(kKeyHeight, &height)); 1368 CHECK(meta->findInt32(kKeyStride, &stride)); 1369 CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); 1370 CHECK(meta->findInt32(kKeyColorFormat, &colorFormat)); 1371 1372 enc_meta->setInt32(kKeyWidth, width); 1373 enc_meta->setInt32(kKeyHeight, height); 1374 enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec); 1375 enc_meta->setInt32(kKeyStride, stride); 1376 enc_meta->setInt32(kKeySliceHeight, sliceHeight); 1377 enc_meta->setInt32(kKeyColorFormat, colorFormat); 1378 if (mVideoTimeScale > 0) { 1379 enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale); 1380 } 1381 if (mVideoEncoderProfile != -1) { 1382 enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile); 1383 } 1384 if (mVideoEncoderLevel != -1) { 1385 enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel); 1386 } 1387 1388 OMXClient client; 1389 CHECK_EQ(client.connect(), OK); 1390 1391 uint32_t encoder_flags = 0; 1392 if (mIsMetaDataStoredInVideoBuffers) { 1393 encoder_flags |= OMXCodec::kHardwareCodecsOnly; 1394 encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers; 1395 } 1396 1397 // Do not wait for all the input buffers to become available. 1398 // This give timelapse video recording faster response in 1399 // receiving output from video encoder component. 1400 if (mCaptureTimeLapse) { 1401 encoder_flags |= OMXCodec::kOnlySubmitOneInputBufferAtOneTime; 1402 } 1403 1404 sp<MediaSource> encoder = OMXCodec::Create( 1405 client.interface(), enc_meta, 1406 true /* createEncoder */, cameraSource, 1407 NULL, encoder_flags); 1408 if (encoder == NULL) { 1409 LOGW("Failed to create the encoder"); 1410 // When the encoder fails to be created, we need 1411 // release the camera source due to the camera's lock 1412 // and unlock mechanism. 1413 cameraSource->stop(); 1414 return UNKNOWN_ERROR; 1415 } 1416 1417 *source = encoder; 1418 1419 return OK; 1420 } 1421 1422 status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) { 1423 status_t status = BAD_VALUE; 1424 if (OK != (status = checkAudioEncoderCapabilities())) { 1425 return status; 1426 } 1427 1428 switch(mAudioEncoder) { 1429 case AUDIO_ENCODER_AMR_NB: 1430 case AUDIO_ENCODER_AMR_WB: 1431 case AUDIO_ENCODER_AAC: 1432 break; 1433 1434 default: 1435 LOGE("Unsupported audio encoder: %d", mAudioEncoder); 1436 return UNKNOWN_ERROR; 1437 } 1438 1439 sp<MediaSource> audioEncoder = createAudioSource(); 1440 if (audioEncoder == NULL) { 1441 return UNKNOWN_ERROR; 1442 } 1443 1444 writer->addSource(audioEncoder); 1445 return OK; 1446 } 1447 1448 status_t StagefrightRecorder::setupMPEG4Recording( 1449 int outputFd, 1450 int32_t videoWidth, int32_t videoHeight, 1451 int32_t videoBitRate, 1452 int32_t *totalBitRate, 1453 sp<MediaWriter> *mediaWriter) { 1454 mediaWriter->clear(); 1455 *totalBitRate = 0; 1456 status_t err = OK; 1457 sp<MediaWriter> writer = new MPEG4Writer(outputFd); 1458 1459 if (mVideoSource < VIDEO_SOURCE_LIST_END) { 1460 1461 sp<MediaSource> mediaSource; 1462 err = setupMediaSource(&mediaSource); 1463 if (err != OK) { 1464 return err; 1465 } 1466 1467 sp<MediaSource> encoder; 1468 err = setupVideoEncoder(mediaSource, videoBitRate, &encoder); 1469 if (err != OK) { 1470 return err; 1471 } 1472 1473 writer->addSource(encoder); 1474 *totalBitRate += videoBitRate; 1475 } 1476 1477 // Audio source is added at the end if it exists. 1478 // This help make sure that the "recoding" sound is suppressed for 1479 // camcorder applications in the recorded files. 1480 if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_CNT)) { 1481 err = setupAudioEncoder(writer); 1482 if (err != OK) return err; 1483 *totalBitRate += mAudioBitRate; 1484 } 1485 1486 if (mInterleaveDurationUs > 0) { 1487 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1488 setInterleaveDuration(mInterleaveDurationUs); 1489 } 1490 if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) { 1491 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1492 setGeoData(mLatitudex10000, mLongitudex10000); 1493 } 1494 if (mMaxFileDurationUs != 0) { 1495 writer->setMaxFileDuration(mMaxFileDurationUs); 1496 } 1497 if (mMaxFileSizeBytes != 0) { 1498 writer->setMaxFileSize(mMaxFileSizeBytes); 1499 } 1500 1501 mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId); 1502 if (mStartTimeOffsetMs > 0) { 1503 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1504 setStartTimeOffsetMs(mStartTimeOffsetMs); 1505 } 1506 1507 writer->setListener(mListener); 1508 *mediaWriter = writer; 1509 return OK; 1510 } 1511 1512 void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate, 1513 sp<MetaData> *meta) { 1514 (*meta)->setInt64(kKeyTime, startTimeUs); 1515 (*meta)->setInt32(kKeyFileType, mOutputFormat); 1516 (*meta)->setInt32(kKeyBitRate, totalBitRate); 1517 (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset); 1518 if (mMovieTimeScale > 0) { 1519 (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale); 1520 } 1521 if (mTrackEveryTimeDurationUs > 0) { 1522 (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs); 1523 } 1524 if (mRotationDegrees != 0) { 1525 (*meta)->setInt32(kKeyRotation, mRotationDegrees); 1526 } 1527 } 1528 1529 status_t StagefrightRecorder::startMPEG4Recording() { 1530 int32_t totalBitRate; 1531 status_t err = setupMPEG4Recording( 1532 mOutputFd, mVideoWidth, mVideoHeight, 1533 mVideoBitRate, &totalBitRate, &mWriter); 1534 if (err != OK) { 1535 return err; 1536 } 1537 1538 int64_t startTimeUs = systemTime() / 1000; 1539 sp<MetaData> meta = new MetaData; 1540 setupMPEG4MetaData(startTimeUs, totalBitRate, &meta); 1541 1542 err = mWriter->start(meta.get()); 1543 if (err != OK) { 1544 return err; 1545 } 1546 1547 return OK; 1548 } 1549 1550 status_t StagefrightRecorder::pause() { 1551 LOGV("pause"); 1552 if (mWriter == NULL) { 1553 return UNKNOWN_ERROR; 1554 } 1555 mWriter->pause(); 1556 1557 if (mStarted) { 1558 mStarted = false; 1559 1560 uint32_t params = 0; 1561 if (mAudioSource != AUDIO_SOURCE_CNT) { 1562 params |= IMediaPlayerService::kBatteryDataTrackAudio; 1563 } 1564 if (mVideoSource != VIDEO_SOURCE_LIST_END) { 1565 params |= IMediaPlayerService::kBatteryDataTrackVideo; 1566 } 1567 1568 addBatteryData(params); 1569 } 1570 1571 1572 return OK; 1573 } 1574 1575 status_t StagefrightRecorder::stop() { 1576 LOGV("stop"); 1577 status_t err = OK; 1578 1579 if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) { 1580 mCameraSourceTimeLapse->startQuickReadReturns(); 1581 mCameraSourceTimeLapse = NULL; 1582 } 1583 1584 if (mWriter != NULL) { 1585 err = mWriter->stop(); 1586 mWriter.clear(); 1587 } 1588 1589 if (mOutputFd >= 0) { 1590 ::close(mOutputFd); 1591 mOutputFd = -1; 1592 } 1593 1594 if (mStarted) { 1595 mStarted = false; 1596 1597 uint32_t params = 0; 1598 if (mAudioSource != AUDIO_SOURCE_CNT) { 1599 params |= IMediaPlayerService::kBatteryDataTrackAudio; 1600 } 1601 if (mVideoSource != VIDEO_SOURCE_LIST_END) { 1602 params |= IMediaPlayerService::kBatteryDataTrackVideo; 1603 } 1604 1605 addBatteryData(params); 1606 } 1607 1608 1609 return err; 1610 } 1611 1612 status_t StagefrightRecorder::close() { 1613 LOGV("close"); 1614 stop(); 1615 1616 return OK; 1617 } 1618 1619 status_t StagefrightRecorder::reset() { 1620 LOGV("reset"); 1621 stop(); 1622 1623 // No audio or video source by default 1624 mAudioSource = AUDIO_SOURCE_CNT; 1625 mVideoSource = VIDEO_SOURCE_LIST_END; 1626 1627 // Default parameters 1628 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 1629 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 1630 mVideoEncoder = VIDEO_ENCODER_H263; 1631 mVideoWidth = 176; 1632 mVideoHeight = 144; 1633 mFrameRate = -1; 1634 mVideoBitRate = 192000; 1635 mSampleRate = 8000; 1636 mAudioChannels = 1; 1637 mAudioBitRate = 12200; 1638 mInterleaveDurationUs = 0; 1639 mIFramesIntervalSec = 1; 1640 mAudioSourceNode = 0; 1641 mUse64BitFileOffset = false; 1642 mMovieTimeScale = -1; 1643 mAudioTimeScale = -1; 1644 mVideoTimeScale = -1; 1645 mCameraId = 0; 1646 mStartTimeOffsetMs = -1; 1647 mVideoEncoderProfile = -1; 1648 mVideoEncoderLevel = -1; 1649 mMaxFileDurationUs = 0; 1650 mMaxFileSizeBytes = 0; 1651 mTrackEveryTimeDurationUs = 0; 1652 mCaptureTimeLapse = false; 1653 mTimeBetweenTimeLapseFrameCaptureUs = -1; 1654 mCameraSourceTimeLapse = NULL; 1655 mIsMetaDataStoredInVideoBuffers = false; 1656 mEncoderProfiles = MediaProfiles::getInstance(); 1657 mRotationDegrees = 0; 1658 mLatitudex10000 = -3600000; 1659 mLongitudex10000 = -3600000; 1660 1661 mOutputFd = -1; 1662 1663 return OK; 1664 } 1665 1666 status_t StagefrightRecorder::getMaxAmplitude(int *max) { 1667 LOGV("getMaxAmplitude"); 1668 1669 if (max == NULL) { 1670 LOGE("Null pointer argument"); 1671 return BAD_VALUE; 1672 } 1673 1674 if (mAudioSourceNode != 0) { 1675 *max = mAudioSourceNode->getMaxAmplitude(); 1676 } else { 1677 *max = 0; 1678 } 1679 1680 return OK; 1681 } 1682 1683 status_t StagefrightRecorder::dump( 1684 int fd, const Vector<String16>& args) const { 1685 LOGV("dump"); 1686 const size_t SIZE = 256; 1687 char buffer[SIZE]; 1688 String8 result; 1689 if (mWriter != 0) { 1690 mWriter->dump(fd, args); 1691 } else { 1692 snprintf(buffer, SIZE, " No file writer\n"); 1693 result.append(buffer); 1694 } 1695 snprintf(buffer, SIZE, " Recorder: %p\n", this); 1696 snprintf(buffer, SIZE, " Output file (fd %d):\n", mOutputFd); 1697 result.append(buffer); 1698 snprintf(buffer, SIZE, " File format: %d\n", mOutputFormat); 1699 result.append(buffer); 1700 snprintf(buffer, SIZE, " Max file size (bytes): %lld\n", mMaxFileSizeBytes); 1701 result.append(buffer); 1702 snprintf(buffer, SIZE, " Max file duration (us): %lld\n", mMaxFileDurationUs); 1703 result.append(buffer); 1704 snprintf(buffer, SIZE, " File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32); 1705 result.append(buffer); 1706 snprintf(buffer, SIZE, " Interleave duration (us): %d\n", mInterleaveDurationUs); 1707 result.append(buffer); 1708 snprintf(buffer, SIZE, " Progress notification: %lld us\n", mTrackEveryTimeDurationUs); 1709 result.append(buffer); 1710 snprintf(buffer, SIZE, " Audio\n"); 1711 result.append(buffer); 1712 snprintf(buffer, SIZE, " Source: %d\n", mAudioSource); 1713 result.append(buffer); 1714 snprintf(buffer, SIZE, " Encoder: %d\n", mAudioEncoder); 1715 result.append(buffer); 1716 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mAudioBitRate); 1717 result.append(buffer); 1718 snprintf(buffer, SIZE, " Sampling rate (hz): %d\n", mSampleRate); 1719 result.append(buffer); 1720 snprintf(buffer, SIZE, " Number of channels: %d\n", mAudioChannels); 1721 result.append(buffer); 1722 snprintf(buffer, SIZE, " Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude()); 1723 result.append(buffer); 1724 snprintf(buffer, SIZE, " Video\n"); 1725 result.append(buffer); 1726 snprintf(buffer, SIZE, " Source: %d\n", mVideoSource); 1727 result.append(buffer); 1728 snprintf(buffer, SIZE, " Camera Id: %d\n", mCameraId); 1729 result.append(buffer); 1730 snprintf(buffer, SIZE, " Start time offset (ms): %d\n", mStartTimeOffsetMs); 1731 result.append(buffer); 1732 snprintf(buffer, SIZE, " Encoder: %d\n", mVideoEncoder); 1733 result.append(buffer); 1734 snprintf(buffer, SIZE, " Encoder profile: %d\n", mVideoEncoderProfile); 1735 result.append(buffer); 1736 snprintf(buffer, SIZE, " Encoder level: %d\n", mVideoEncoderLevel); 1737 result.append(buffer); 1738 snprintf(buffer, SIZE, " I frames interval (s): %d\n", mIFramesIntervalSec); 1739 result.append(buffer); 1740 snprintf(buffer, SIZE, " Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight); 1741 result.append(buffer); 1742 snprintf(buffer, SIZE, " Frame rate (fps): %d\n", mFrameRate); 1743 result.append(buffer); 1744 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mVideoBitRate); 1745 result.append(buffer); 1746 ::write(fd, result.string(), result.size()); 1747 return OK; 1748 } 1749 } // namespace android 1750