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