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