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