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