StagefrightRecorder.cpp revision 7a42770f47225483a885b168d05e81b6a81189c0
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 <media/stagefright/AudioSource.h> 25#include <media/stagefright/AMRWriter.h> 26#include <media/stagefright/CameraSource.h> 27#include <media/stagefright/CameraSourceTimeLapse.h> 28#include <media/stagefright/MPEG4Writer.h> 29#include <media/stagefright/MediaDebug.h> 30#include <media/stagefright/MediaDefs.h> 31#include <media/stagefright/MetaData.h> 32#include <media/stagefright/OMXClient.h> 33#include <media/stagefright/OMXCodec.h> 34#include <media/MediaProfiles.h> 35#include <camera/ICamera.h> 36#include <camera/Camera.h> 37#include <camera/CameraParameters.h> 38#include <surfaceflinger/ISurface.h> 39#include <utils/Errors.h> 40#include <sys/types.h> 41#include <unistd.h> 42#include <ctype.h> 43 44namespace android { 45 46StagefrightRecorder::StagefrightRecorder() 47 : mWriter(NULL), 48 mOutputFd(-1) { 49 50 LOGV("Constructor"); 51 reset(); 52} 53 54StagefrightRecorder::~StagefrightRecorder() { 55 LOGV("Destructor"); 56 stop(); 57 58 if (mOutputFd >= 0) { 59 ::close(mOutputFd); 60 mOutputFd = -1; 61 } 62} 63 64status_t StagefrightRecorder::init() { 65 LOGV("init"); 66 return OK; 67} 68 69status_t StagefrightRecorder::setAudioSource(audio_source as) { 70 LOGV("setAudioSource: %d", as); 71 if (as < AUDIO_SOURCE_DEFAULT || 72 as >= AUDIO_SOURCE_LIST_END) { 73 LOGE("Invalid audio source: %d", as); 74 return BAD_VALUE; 75 } 76 77 if (as == AUDIO_SOURCE_DEFAULT) { 78 mAudioSource = AUDIO_SOURCE_MIC; 79 } else { 80 mAudioSource = as; 81 } 82 83 return OK; 84} 85 86status_t StagefrightRecorder::setVideoSource(video_source vs) { 87 LOGV("setVideoSource: %d", vs); 88 if (vs < VIDEO_SOURCE_DEFAULT || 89 vs >= VIDEO_SOURCE_LIST_END) { 90 LOGE("Invalid video source: %d", vs); 91 return BAD_VALUE; 92 } 93 94 if (vs == VIDEO_SOURCE_DEFAULT) { 95 mVideoSource = VIDEO_SOURCE_CAMERA; 96 } else { 97 mVideoSource = vs; 98 } 99 100 return OK; 101} 102 103status_t StagefrightRecorder::setOutputFormat(output_format of) { 104 LOGV("setOutputFormat: %d", of); 105 if (of < OUTPUT_FORMAT_DEFAULT || 106 of >= OUTPUT_FORMAT_LIST_END) { 107 LOGE("Invalid output format: %d", of); 108 return BAD_VALUE; 109 } 110 111 if (of == OUTPUT_FORMAT_DEFAULT) { 112 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 113 } else { 114 mOutputFormat = of; 115 } 116 117 return OK; 118} 119 120status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) { 121 LOGV("setAudioEncoder: %d", ae); 122 if (ae < AUDIO_ENCODER_DEFAULT || 123 ae >= AUDIO_ENCODER_LIST_END) { 124 LOGE("Invalid audio encoder: %d", ae); 125 return BAD_VALUE; 126 } 127 128 if (ae == AUDIO_ENCODER_DEFAULT) { 129 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 130 } else { 131 mAudioEncoder = ae; 132 } 133 134 return OK; 135} 136 137status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) { 138 LOGV("setVideoEncoder: %d", ve); 139 if (ve < VIDEO_ENCODER_DEFAULT || 140 ve >= VIDEO_ENCODER_LIST_END) { 141 LOGE("Invalid video encoder: %d", ve); 142 return BAD_VALUE; 143 } 144 145 if (ve == VIDEO_ENCODER_DEFAULT) { 146 mVideoEncoder = VIDEO_ENCODER_H263; 147 } else { 148 mVideoEncoder = ve; 149 } 150 151 return OK; 152} 153 154status_t StagefrightRecorder::setVideoSize(int width, int height) { 155 LOGV("setVideoSize: %dx%d", width, height); 156 if (width <= 0 || height <= 0) { 157 LOGE("Invalid video size: %dx%d", width, height); 158 return BAD_VALUE; 159 } 160 161 // Additional check on the dimension will be performed later 162 mVideoWidth = width; 163 mVideoHeight = height; 164 165 return OK; 166} 167 168status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) { 169 LOGV("setVideoFrameRate: %d", frames_per_second); 170 if (frames_per_second <= 0 || frames_per_second > 30) { 171 LOGE("Invalid video frame rate: %d", frames_per_second); 172 return BAD_VALUE; 173 } 174 175 // Additional check on the frame rate will be performed later 176 mFrameRate = frames_per_second; 177 178 return OK; 179} 180 181status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera) { 182 LOGV("setCamera"); 183 if (camera == 0) { 184 LOGE("camera is NULL"); 185 return BAD_VALUE; 186 } 187 188 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 189 mFlags &= ~FLAGS_HOT_CAMERA; 190 mCamera = Camera::create(camera); 191 if (mCamera == 0) { 192 LOGE("Unable to connect to camera"); 193 IPCThreadState::self()->restoreCallingIdentity(token); 194 return -EBUSY; 195 } 196 197 LOGV("Connected to camera"); 198 if (mCamera->previewEnabled()) { 199 LOGV("camera is hot"); 200 mFlags |= FLAGS_HOT_CAMERA; 201 } 202 IPCThreadState::self()->restoreCallingIdentity(token); 203 204 return OK; 205} 206 207status_t StagefrightRecorder::setPreviewSurface(const sp<ISurface> &surface) { 208 LOGV("setPreviewSurface: %p", surface.get()); 209 mPreviewSurface = surface; 210 211 return OK; 212} 213 214status_t StagefrightRecorder::setOutputFile(const char *path) { 215 LOGE("setOutputFile(const char*) must not be called"); 216 // We don't actually support this at all, as the media_server process 217 // no longer has permissions to create files. 218 219 return -EPERM; 220} 221 222status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) { 223 LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length); 224 // These don't make any sense, do they? 225 CHECK_EQ(offset, 0); 226 CHECK_EQ(length, 0); 227 228 if (fd < 0) { 229 LOGE("Invalid file descriptor: %d", fd); 230 return -EBADF; 231 } 232 233 if (mOutputFd >= 0) { 234 ::close(mOutputFd); 235 } 236 mOutputFd = dup(fd); 237 238 return OK; 239} 240 241// Attempt to parse an int64 literal optionally surrounded by whitespace, 242// returns true on success, false otherwise. 243static bool safe_strtoi64(const char *s, int64_t *val) { 244 char *end; 245 *val = strtoll(s, &end, 10); 246 247 if (end == s || errno == ERANGE) { 248 return false; 249 } 250 251 // Skip trailing whitespace 252 while (isspace(*end)) { 253 ++end; 254 } 255 256 // For a successful return, the string must contain nothing but a valid 257 // int64 literal optionally surrounded by whitespace. 258 259 return *end == '\0'; 260} 261 262// Return true if the value is in [0, 0x007FFFFFFF] 263static bool safe_strtoi32(const char *s, int32_t *val) { 264 int64_t temp; 265 if (safe_strtoi64(s, &temp)) { 266 if (temp >= 0 && temp <= 0x007FFFFFFF) { 267 *val = static_cast<int32_t>(temp); 268 return true; 269 } 270 } 271 return false; 272} 273 274// Trim both leading and trailing whitespace from the given string. 275static void TrimString(String8 *s) { 276 size_t num_bytes = s->bytes(); 277 const char *data = s->string(); 278 279 size_t leading_space = 0; 280 while (leading_space < num_bytes && isspace(data[leading_space])) { 281 ++leading_space; 282 } 283 284 size_t i = num_bytes; 285 while (i > leading_space && isspace(data[i - 1])) { 286 --i; 287 } 288 289 s->setTo(String8(&data[leading_space], i - leading_space)); 290} 291 292status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) { 293 LOGV("setParamAudioSamplingRate: %d", sampleRate); 294 if (sampleRate <= 0) { 295 LOGE("Invalid audio sampling rate: %d", sampleRate); 296 return BAD_VALUE; 297 } 298 299 // Additional check on the sample rate will be performed later. 300 mSampleRate = sampleRate; 301 return OK; 302} 303 304status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) { 305 LOGV("setParamAudioNumberOfChannels: %d", channels); 306 if (channels <= 0 || channels >= 3) { 307 LOGE("Invalid number of audio channels: %d", channels); 308 return BAD_VALUE; 309 } 310 311 // Additional check on the number of channels will be performed later. 312 mAudioChannels = channels; 313 return OK; 314} 315 316status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) { 317 LOGV("setParamAudioEncodingBitRate: %d", bitRate); 318 if (bitRate <= 0) { 319 LOGE("Invalid audio encoding bit rate: %d", bitRate); 320 return BAD_VALUE; 321 } 322 323 // The target bit rate may not be exactly the same as the requested. 324 // It depends on many factors, such as rate control, and the bit rate 325 // range that a specific encoder supports. The mismatch between the 326 // the target and requested bit rate will NOT be treated as an error. 327 mAudioBitRate = bitRate; 328 return OK; 329} 330 331status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) { 332 LOGV("setParamVideoEncodingBitRate: %d", bitRate); 333 if (bitRate <= 0) { 334 LOGE("Invalid video encoding bit rate: %d", bitRate); 335 return BAD_VALUE; 336 } 337 338 // The target bit rate may not be exactly the same as the requested. 339 // It depends on many factors, such as rate control, and the bit rate 340 // range that a specific encoder supports. The mismatch between the 341 // the target and requested bit rate will NOT be treated as an error. 342 mVideoBitRate = bitRate; 343 return OK; 344} 345 346status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) { 347 LOGV("setParamMaxFileDurationUs: %lld us", timeUs); 348 if (timeUs <= 1000000LL) { // XXX: 1 second 349 LOGE("Max file duration is too short: %lld us", timeUs); 350 return BAD_VALUE; 351 } 352 mMaxFileDurationUs = timeUs; 353 return OK; 354} 355 356status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) { 357 LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes); 358 if (bytes <= 1024) { // XXX: 1 kB 359 LOGE("Max file size is too small: %lld bytes", bytes); 360 return BAD_VALUE; 361 } 362 mMaxFileSizeBytes = bytes; 363 return OK; 364} 365 366status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) { 367 LOGV("setParamInterleaveDuration: %d", durationUs); 368 if (durationUs <= 500000) { // 500 ms 369 // If interleave duration is too small, it is very inefficient to do 370 // interleaving since the metadata overhead will count for a significant 371 // portion of the saved contents 372 LOGE("Audio/video interleave duration is too small: %d us", durationUs); 373 return BAD_VALUE; 374 } else if (durationUs >= 10000000) { // 10 seconds 375 // If interleaving duration is too large, it can cause the recording 376 // session to use too much memory since we have to save the output 377 // data before we write them out 378 LOGE("Audio/video interleave duration is too large: %d us", durationUs); 379 return BAD_VALUE; 380 } 381 mInterleaveDurationUs = durationUs; 382 return OK; 383} 384 385// If seconds < 0, only the first frame is I frame, and rest are all P frames 386// If seconds == 0, all frames are encoded as I frames. No P frames 387// If seconds > 0, it is the time spacing (seconds) between 2 neighboring I frames 388status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) { 389 LOGV("setParamVideoIFramesInterval: %d seconds", seconds); 390 mIFramesIntervalSec = seconds; 391 return OK; 392} 393 394status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) { 395 LOGV("setParam64BitFileOffset: %s", 396 use64Bit? "use 64 bit file offset": "use 32 bit file offset"); 397 mUse64BitFileOffset = use64Bit; 398 return OK; 399} 400 401status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) { 402 LOGV("setParamVideoCameraId: %d", cameraId); 403 if (cameraId < 0) { 404 return BAD_VALUE; 405 } 406 mCameraId = cameraId; 407 return OK; 408} 409 410status_t StagefrightRecorder::setParamTrackFrameStatus(int32_t nFrames) { 411 LOGV("setParamTrackFrameStatus: %d", nFrames); 412 if (nFrames <= 0) { 413 LOGE("Invalid number of frames to track: %d", nFrames); 414 return BAD_VALUE; 415 } 416 mTrackEveryNumberOfFrames = nFrames; 417 return OK; 418} 419 420status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) { 421 LOGV("setParamTrackTimeStatus: %lld", timeDurationUs); 422 if (timeDurationUs < 20000) { // Infeasible if shorter than 20 ms? 423 LOGE("Tracking time duration too short: %lld us", timeDurationUs); 424 return BAD_VALUE; 425 } 426 mTrackEveryTimeDurationUs = timeDurationUs; 427 return OK; 428} 429 430status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) { 431 LOGV("setParamVideoEncoderProfile: %d", profile); 432 433 // Additional check will be done later when we load the encoder. 434 // For now, we are accepting values defined in OpenMAX IL. 435 mVideoEncoderProfile = profile; 436 return OK; 437} 438 439status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) { 440 LOGV("setParamVideoEncoderLevel: %d", level); 441 442 // Additional check will be done later when we load the encoder. 443 // For now, we are accepting values defined in OpenMAX IL. 444 mVideoEncoderLevel = level; 445 return OK; 446} 447 448status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) { 449 LOGV("setParamMovieTimeScale: %d", timeScale); 450 451 // The range is set to be the same as the audio's time scale range 452 // since audio's time scale has a wider range. 453 if (timeScale < 600 || timeScale > 96000) { 454 LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale); 455 return BAD_VALUE; 456 } 457 mMovieTimeScale = timeScale; 458 return OK; 459} 460 461status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) { 462 LOGV("setParamVideoTimeScale: %d", timeScale); 463 464 // 60000 is chosen to make sure that each video frame from a 60-fps 465 // video has 1000 ticks. 466 if (timeScale < 600 || timeScale > 60000) { 467 LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale); 468 return BAD_VALUE; 469 } 470 mVideoTimeScale = timeScale; 471 return OK; 472} 473 474status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) { 475 LOGV("setParamAudioTimeScale: %d", timeScale); 476 477 // 96000 Hz is the highest sampling rate support in AAC. 478 if (timeScale < 600 || timeScale > 96000) { 479 LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale); 480 return BAD_VALUE; 481 } 482 mAudioTimeScale = timeScale; 483 return OK; 484} 485 486status_t StagefrightRecorder::setParameter( 487 const String8 &key, const String8 &value) { 488 LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string()); 489 if (key == "max-duration") { 490 int64_t max_duration_ms; 491 if (safe_strtoi64(value.string(), &max_duration_ms)) { 492 return setParamMaxFileDurationUs(1000LL * max_duration_ms); 493 } 494 } else if (key == "max-filesize") { 495 int64_t max_filesize_bytes; 496 if (safe_strtoi64(value.string(), &max_filesize_bytes)) { 497 return setParamMaxFileSizeBytes(max_filesize_bytes); 498 } 499 } else if (key == "interleave-duration-us") { 500 int32_t durationUs; 501 if (safe_strtoi32(value.string(), &durationUs)) { 502 return setParamInterleaveDuration(durationUs); 503 } 504 } else if (key == "param-movie-time-scale") { 505 int32_t timeScale; 506 if (safe_strtoi32(value.string(), &timeScale)) { 507 return setParamMovieTimeScale(timeScale); 508 } 509 } else if (key == "param-use-64bit-offset") { 510 int32_t use64BitOffset; 511 if (safe_strtoi32(value.string(), &use64BitOffset)) { 512 return setParam64BitFileOffset(use64BitOffset != 0); 513 } 514 } else if (key == "param-track-frame-status") { 515 int32_t nFrames; 516 if (safe_strtoi32(value.string(), &nFrames)) { 517 return setParamTrackFrameStatus(nFrames); 518 } 519 } else if (key == "param-track-time-status") { 520 int64_t timeDurationUs; 521 if (safe_strtoi64(value.string(), &timeDurationUs)) { 522 return setParamTrackTimeStatus(timeDurationUs); 523 } 524 } else if (key == "audio-param-sampling-rate") { 525 int32_t sampling_rate; 526 if (safe_strtoi32(value.string(), &sampling_rate)) { 527 return setParamAudioSamplingRate(sampling_rate); 528 } 529 } else if (key == "audio-param-number-of-channels") { 530 int32_t number_of_channels; 531 if (safe_strtoi32(value.string(), &number_of_channels)) { 532 return setParamAudioNumberOfChannels(number_of_channels); 533 } 534 } else if (key == "audio-param-encoding-bitrate") { 535 int32_t audio_bitrate; 536 if (safe_strtoi32(value.string(), &audio_bitrate)) { 537 return setParamAudioEncodingBitRate(audio_bitrate); 538 } 539 } else if (key == "audio-param-time-scale") { 540 int32_t timeScale; 541 if (safe_strtoi32(value.string(), &timeScale)) { 542 return setParamAudioTimeScale(timeScale); 543 } 544 } else if (key == "video-param-encoding-bitrate") { 545 int32_t video_bitrate; 546 if (safe_strtoi32(value.string(), &video_bitrate)) { 547 return setParamVideoEncodingBitRate(video_bitrate); 548 } 549 } else if (key == "video-param-i-frames-interval") { 550 int32_t seconds; 551 if (safe_strtoi32(value.string(), &seconds)) { 552 return setParamVideoIFramesInterval(seconds); 553 } 554 } else if (key == "video-param-encoder-profile") { 555 int32_t profile; 556 if (safe_strtoi32(value.string(), &profile)) { 557 return setParamVideoEncoderProfile(profile); 558 } 559 } else if (key == "video-param-encoder-level") { 560 int32_t level; 561 if (safe_strtoi32(value.string(), &level)) { 562 return setParamVideoEncoderLevel(level); 563 } 564 } else if (key == "video-param-camera-id") { 565 int32_t cameraId; 566 if (safe_strtoi32(value.string(), &cameraId)) { 567 return setParamVideoCameraId(cameraId); 568 } 569 } else if (key == "video-param-time-scale") { 570 int32_t timeScale; 571 if (safe_strtoi32(value.string(), &timeScale)) { 572 return setParamVideoTimeScale(timeScale); 573 } 574 } else { 575 LOGE("setParameter: failed to find key %s", key.string()); 576 } 577 return BAD_VALUE; 578} 579 580status_t StagefrightRecorder::setParameters(const String8 ¶ms) { 581 LOGV("setParameters: %s", params.string()); 582 const char *cparams = params.string(); 583 const char *key_start = cparams; 584 for (;;) { 585 const char *equal_pos = strchr(key_start, '='); 586 if (equal_pos == NULL) { 587 LOGE("Parameters %s miss a value", cparams); 588 return BAD_VALUE; 589 } 590 String8 key(key_start, equal_pos - key_start); 591 TrimString(&key); 592 if (key.length() == 0) { 593 LOGE("Parameters %s contains an empty key", cparams); 594 return BAD_VALUE; 595 } 596 const char *value_start = equal_pos + 1; 597 const char *semicolon_pos = strchr(value_start, ';'); 598 String8 value; 599 if (semicolon_pos == NULL) { 600 value.setTo(value_start); 601 } else { 602 value.setTo(value_start, semicolon_pos - value_start); 603 } 604 if (setParameter(key, value) != OK) { 605 return BAD_VALUE; 606 } 607 if (semicolon_pos == NULL) { 608 break; // Reaches the end 609 } 610 key_start = semicolon_pos + 1; 611 } 612 return OK; 613} 614 615status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) { 616 mListener = listener; 617 618 return OK; 619} 620 621status_t StagefrightRecorder::prepare() { 622 return OK; 623} 624 625status_t StagefrightRecorder::start() { 626 CHECK(mOutputFd >= 0); 627 628 if (mWriter != NULL) { 629 LOGE("File writer is not avaialble"); 630 return UNKNOWN_ERROR; 631 } 632 633 switch (mOutputFormat) { 634 case OUTPUT_FORMAT_DEFAULT: 635 case OUTPUT_FORMAT_THREE_GPP: 636 case OUTPUT_FORMAT_MPEG_4: 637 return startMPEG4Recording(); 638 639 case OUTPUT_FORMAT_AMR_NB: 640 case OUTPUT_FORMAT_AMR_WB: 641 return startAMRRecording(); 642 643 case OUTPUT_FORMAT_AAC_ADIF: 644 case OUTPUT_FORMAT_AAC_ADTS: 645 return startAACRecording(); 646 647 default: 648 LOGE("Unsupported output file format: %d", mOutputFormat); 649 return UNKNOWN_ERROR; 650 } 651} 652 653sp<MediaSource> StagefrightRecorder::createAudioSource() { 654 sp<AudioSource> audioSource = 655 new AudioSource( 656 mAudioSource, 657 mSampleRate, 658 mAudioChannels); 659 660 status_t err = audioSource->initCheck(); 661 662 if (err != OK) { 663 LOGE("audio source is not initialized"); 664 return NULL; 665 } 666 667 sp<MetaData> encMeta = new MetaData; 668 const char *mime; 669 switch (mAudioEncoder) { 670 case AUDIO_ENCODER_AMR_NB: 671 case AUDIO_ENCODER_DEFAULT: 672 mime = MEDIA_MIMETYPE_AUDIO_AMR_NB; 673 break; 674 case AUDIO_ENCODER_AMR_WB: 675 mime = MEDIA_MIMETYPE_AUDIO_AMR_WB; 676 break; 677 case AUDIO_ENCODER_AAC: 678 mime = MEDIA_MIMETYPE_AUDIO_AAC; 679 break; 680 default: 681 LOGE("Unknown audio encoder: %d", mAudioEncoder); 682 return NULL; 683 } 684 encMeta->setCString(kKeyMIMEType, mime); 685 686 int32_t maxInputSize; 687 CHECK(audioSource->getFormat()->findInt32( 688 kKeyMaxInputSize, &maxInputSize)); 689 690 encMeta->setInt32(kKeyMaxInputSize, maxInputSize); 691 encMeta->setInt32(kKeyChannelCount, mAudioChannels); 692 encMeta->setInt32(kKeySampleRate, mSampleRate); 693 encMeta->setInt32(kKeyBitRate, mAudioBitRate); 694 encMeta->setInt32(kKeyTimeScale, mAudioTimeScale); 695 696 OMXClient client; 697 CHECK_EQ(client.connect(), OK); 698 699 sp<MediaSource> audioEncoder = 700 OMXCodec::Create(client.interface(), encMeta, 701 true /* createEncoder */, audioSource); 702 mAudioSourceNode = audioSource; 703 704 return audioEncoder; 705} 706 707status_t StagefrightRecorder::startAACRecording() { 708 CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF || 709 mOutputFormat == OUTPUT_FORMAT_AAC_ADTS); 710 711 CHECK(mAudioEncoder == AUDIO_ENCODER_AAC); 712 CHECK(mAudioSource != AUDIO_SOURCE_LIST_END); 713 714 CHECK(0 == "AACWriter is not implemented yet"); 715 716 return OK; 717} 718 719status_t StagefrightRecorder::startAMRRecording() { 720 CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB || 721 mOutputFormat == OUTPUT_FORMAT_AMR_WB); 722 723 if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) { 724 if (mAudioEncoder != AUDIO_ENCODER_DEFAULT && 725 mAudioEncoder != AUDIO_ENCODER_AMR_NB) { 726 LOGE("Invalid encoder %d used for AMRNB recording", 727 mAudioEncoder); 728 return BAD_VALUE; 729 } 730 if (mSampleRate != 8000) { 731 LOGE("Invalid sampling rate %d used for AMRNB recording", 732 mSampleRate); 733 return BAD_VALUE; 734 } 735 } else { // mOutputFormat must be OUTPUT_FORMAT_AMR_WB 736 if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) { 737 LOGE("Invlaid encoder %d used for AMRWB recording", 738 mAudioEncoder); 739 return BAD_VALUE; 740 } 741 if (mSampleRate != 16000) { 742 LOGE("Invalid sample rate %d used for AMRWB recording", 743 mSampleRate); 744 return BAD_VALUE; 745 } 746 } 747 if (mAudioChannels != 1) { 748 LOGE("Invalid number of audio channels %d used for amr recording", 749 mAudioChannels); 750 return BAD_VALUE; 751 } 752 753 if (mAudioSource >= AUDIO_SOURCE_LIST_END) { 754 LOGE("Invalid audio source: %d", mAudioSource); 755 return BAD_VALUE; 756 } 757 758 sp<MediaSource> audioEncoder = createAudioSource(); 759 760 if (audioEncoder == NULL) { 761 return UNKNOWN_ERROR; 762 } 763 764 mWriter = new AMRWriter(dup(mOutputFd)); 765 mWriter->addSource(audioEncoder); 766 767 if (mMaxFileDurationUs != 0) { 768 mWriter->setMaxFileDuration(mMaxFileDurationUs); 769 } 770 if (mMaxFileSizeBytes != 0) { 771 mWriter->setMaxFileSize(mMaxFileSizeBytes); 772 } 773 mWriter->setListener(mListener); 774 mWriter->start(); 775 776 return OK; 777} 778 779void StagefrightRecorder::clipVideoFrameRate() { 780 LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder); 781 int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 782 "enc.vid.fps.min", mVideoEncoder); 783 int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 784 "enc.vid.fps.max", mVideoEncoder); 785 if (mFrameRate < minFrameRate) { 786 LOGW("Intended video encoding frame rate (%d fps) is too small" 787 " and will be set to (%d fps)", mFrameRate, minFrameRate); 788 mFrameRate = minFrameRate; 789 } else if (mFrameRate > maxFrameRate) { 790 LOGW("Intended video encoding frame rate (%d fps) is too large" 791 " and will be set to (%d fps)", mFrameRate, maxFrameRate); 792 mFrameRate = maxFrameRate; 793 } 794} 795 796void StagefrightRecorder::clipVideoBitRate() { 797 LOGV("clipVideoBitRate: encoder %d", mVideoEncoder); 798 int minBitRate = mEncoderProfiles->getVideoEncoderParamByName( 799 "enc.vid.bps.min", mVideoEncoder); 800 int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName( 801 "enc.vid.bps.max", mVideoEncoder); 802 if (mVideoBitRate < minBitRate) { 803 LOGW("Intended video encoding bit rate (%d bps) is too small" 804 " and will be set to (%d bps)", mVideoBitRate, minBitRate); 805 mVideoBitRate = minBitRate; 806 } else if (mVideoBitRate > maxBitRate) { 807 LOGW("Intended video encoding bit rate (%d bps) is too large" 808 " and will be set to (%d bps)", mVideoBitRate, maxBitRate); 809 mVideoBitRate = maxBitRate; 810 } 811} 812 813void StagefrightRecorder::clipVideoFrameWidth() { 814 LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder); 815 int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 816 "enc.vid.width.min", mVideoEncoder); 817 int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 818 "enc.vid.width.max", mVideoEncoder); 819 if (mVideoWidth < minFrameWidth) { 820 LOGW("Intended video encoding frame width (%d) is too small" 821 " and will be set to (%d)", mVideoWidth, minFrameWidth); 822 mVideoWidth = minFrameWidth; 823 } else if (mVideoWidth > maxFrameWidth) { 824 LOGW("Intended video encoding frame width (%d) is too large" 825 " and will be set to (%d)", mVideoWidth, maxFrameWidth); 826 mVideoWidth = maxFrameWidth; 827 } 828} 829 830status_t StagefrightRecorder::setupCameraSource() { 831 clipVideoBitRate(); 832 clipVideoFrameRate(); 833 clipVideoFrameWidth(); 834 clipVideoFrameHeight(); 835 836 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 837 if (mCamera == 0) { 838 mCamera = Camera::connect(mCameraId); 839 if (mCamera == 0) { 840 LOGE("Camera connection could not be established."); 841 return -EBUSY; 842 } 843 mFlags &= ~FLAGS_HOT_CAMERA; 844 mCamera->lock(); 845 } 846 847 // Set the actual video recording frame size 848 CameraParameters params(mCamera->getParameters()); 849 params.setPreviewSize(mVideoWidth, mVideoHeight); 850 params.setPreviewFrameRate(mFrameRate); 851 String8 s = params.flatten(); 852 CHECK_EQ(OK, mCamera->setParameters(s)); 853 CameraParameters newCameraParams(mCamera->getParameters()); 854 855 // Check on video frame size 856 int frameWidth = 0, frameHeight = 0; 857 newCameraParams.getPreviewSize(&frameWidth, &frameHeight); 858 if (frameWidth < 0 || frameWidth != mVideoWidth || 859 frameHeight < 0 || frameHeight != mVideoHeight) { 860 LOGE("Failed to set the video frame size to %dx%d", 861 mVideoWidth, mVideoHeight); 862 IPCThreadState::self()->restoreCallingIdentity(token); 863 return UNKNOWN_ERROR; 864 } 865 866 // Check on video frame rate 867 int frameRate = newCameraParams.getPreviewFrameRate(); 868 if (frameRate < 0 || (frameRate - mFrameRate) != 0) { 869 LOGE("Failed to set frame rate to %d fps. The actual " 870 "frame rate is %d", mFrameRate, frameRate); 871 } 872 873 CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface)); 874 IPCThreadState::self()->restoreCallingIdentity(token); 875 return OK; 876} 877 878void StagefrightRecorder::clipVideoFrameHeight() { 879 LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder); 880 int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 881 "enc.vid.height.min", mVideoEncoder); 882 int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 883 "enc.vid.height.max", mVideoEncoder); 884 if (mVideoHeight < minFrameHeight) { 885 LOGW("Intended video encoding frame height (%d) is too small" 886 " and will be set to (%d)", mVideoHeight, minFrameHeight); 887 mVideoHeight = minFrameHeight; 888 } else if (mVideoHeight > maxFrameHeight) { 889 LOGW("Intended video encoding frame height (%d) is too large" 890 " and will be set to (%d)", mVideoHeight, maxFrameHeight); 891 mVideoHeight = maxFrameHeight; 892 } 893} 894 895status_t StagefrightRecorder::setupVideoEncoder(const sp<MediaWriter>& writer) { 896 status_t err = setupCameraSource(); 897 if (err != OK) return err; 898 899 sp<CameraSource> cameraSource = (mCaptureTimeLapse) ? 900 CameraSourceTimeLapse::CreateFromCamera(mCamera, true, 3E6, mFrameRate): 901 CameraSource::CreateFromCamera(mCamera); 902 CHECK(cameraSource != NULL); 903 904 sp<MetaData> enc_meta = new MetaData; 905 enc_meta->setInt32(kKeyBitRate, mVideoBitRate); 906 enc_meta->setInt32(kKeySampleRate, mFrameRate); 907 908 switch (mVideoEncoder) { 909 case VIDEO_ENCODER_H263: 910 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 911 break; 912 913 case VIDEO_ENCODER_MPEG_4_SP: 914 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 915 break; 916 917 case VIDEO_ENCODER_H264: 918 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 919 break; 920 921 default: 922 CHECK(!"Should not be here, unsupported video encoding."); 923 break; 924 } 925 926 sp<MetaData> meta = cameraSource->getFormat(); 927 928 int32_t width, height, stride, sliceHeight, colorFormat; 929 CHECK(meta->findInt32(kKeyWidth, &width)); 930 CHECK(meta->findInt32(kKeyHeight, &height)); 931 CHECK(meta->findInt32(kKeyStride, &stride)); 932 CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); 933 CHECK(meta->findInt32(kKeyColorFormat, &colorFormat)); 934 935 enc_meta->setInt32(kKeyWidth, width); 936 enc_meta->setInt32(kKeyHeight, height); 937 enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec); 938 enc_meta->setInt32(kKeyStride, stride); 939 enc_meta->setInt32(kKeySliceHeight, sliceHeight); 940 enc_meta->setInt32(kKeyColorFormat, colorFormat); 941 enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale); 942 if (mVideoEncoderProfile != -1) { 943 enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile); 944 } 945 if (mVideoEncoderLevel != -1) { 946 enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel); 947 } 948 949 OMXClient client; 950 CHECK_EQ(client.connect(), OK); 951 952 uint32_t encoder_flags = (mCaptureTimeLapse) ? OMXCodec::kPreferSoftwareCodecs : 0; 953 sp<MediaSource> encoder = OMXCodec::Create( 954 client.interface(), enc_meta, 955 true /* createEncoder */, cameraSource, 956 NULL, encoder_flags); 957 if (encoder == NULL) { 958 return UNKNOWN_ERROR; 959 } 960 961 writer->addSource(encoder); 962 return OK; 963} 964 965status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) { 966 sp<MediaSource> audioEncoder; 967 switch(mAudioEncoder) { 968 case AUDIO_ENCODER_AMR_NB: 969 case AUDIO_ENCODER_AMR_WB: 970 case AUDIO_ENCODER_AAC: 971 audioEncoder = createAudioSource(); 972 break; 973 default: 974 LOGE("Unsupported audio encoder: %d", mAudioEncoder); 975 return UNKNOWN_ERROR; 976 } 977 978 if (audioEncoder == NULL) { 979 return UNKNOWN_ERROR; 980 } 981 982 writer->addSource(audioEncoder); 983 return OK; 984} 985 986status_t StagefrightRecorder::startMPEG4Recording() { 987 int32_t totalBitRate = 0; 988 status_t err = OK; 989 sp<MediaWriter> writer = new MPEG4Writer(dup(mOutputFd)); 990 991 // Add audio source first if it exists 992 if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_LIST_END)) { 993 err = setupAudioEncoder(writer); 994 if (err != OK) return err; 995 totalBitRate += mAudioBitRate; 996 } 997 if (mVideoSource == VIDEO_SOURCE_DEFAULT 998 || mVideoSource == VIDEO_SOURCE_CAMERA) { 999 err = setupVideoEncoder(writer); 1000 if (err != OK) return err; 1001 totalBitRate += mVideoBitRate; 1002 } 1003 1004 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1005 setInterleaveDuration(mInterleaveDurationUs); 1006 1007 if (mMaxFileDurationUs != 0) { 1008 writer->setMaxFileDuration(mMaxFileDurationUs); 1009 } 1010 if (mMaxFileSizeBytes != 0) { 1011 writer->setMaxFileSize(mMaxFileSizeBytes); 1012 } 1013 sp<MetaData> meta = new MetaData; 1014 meta->setInt64(kKeyTime, systemTime() / 1000); 1015 meta->setInt32(kKeyFileType, mOutputFormat); 1016 meta->setInt32(kKeyBitRate, totalBitRate); 1017 meta->setInt32(kKey64BitFileOffset, mUse64BitFileOffset); 1018 meta->setInt32(kKeyTimeScale, mMovieTimeScale); 1019 if (mTrackEveryNumberOfFrames > 0) { 1020 meta->setInt32(kKeyTrackFrameStatus, mTrackEveryNumberOfFrames); 1021 } 1022 if (mTrackEveryTimeDurationUs > 0) { 1023 meta->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs); 1024 } 1025 writer->setListener(mListener); 1026 mWriter = writer; 1027 return mWriter->start(meta.get()); 1028} 1029 1030status_t StagefrightRecorder::pause() { 1031 LOGV("pause"); 1032 if (mWriter == NULL) { 1033 return UNKNOWN_ERROR; 1034 } 1035 mWriter->pause(); 1036 return OK; 1037} 1038 1039status_t StagefrightRecorder::stop() { 1040 LOGV("stop"); 1041 if (mWriter != NULL) { 1042 mWriter->stop(); 1043 mWriter.clear(); 1044 } 1045 1046 if (mCamera != 0) { 1047 LOGV("Disconnect camera"); 1048 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 1049 if ((mFlags & FLAGS_HOT_CAMERA) == 0) { 1050 LOGV("Camera was cold when we started, stopping preview"); 1051 mCamera->stopPreview(); 1052 } 1053 mCamera->unlock(); 1054 mCamera.clear(); 1055 IPCThreadState::self()->restoreCallingIdentity(token); 1056 mFlags = 0; 1057 } 1058 1059 return OK; 1060} 1061 1062status_t StagefrightRecorder::close() { 1063 LOGV("close"); 1064 stop(); 1065 1066 return OK; 1067} 1068 1069status_t StagefrightRecorder::reset() { 1070 LOGV("reset"); 1071 stop(); 1072 1073 // No audio or video source by default 1074 mAudioSource = AUDIO_SOURCE_LIST_END; 1075 mVideoSource = VIDEO_SOURCE_LIST_END; 1076 1077 // Default parameters 1078 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 1079 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 1080 mVideoEncoder = VIDEO_ENCODER_H263; 1081 mVideoWidth = 176; 1082 mVideoHeight = 144; 1083 mFrameRate = 20; 1084 mVideoBitRate = 192000; 1085 mSampleRate = 8000; 1086 mAudioChannels = 1; 1087 mAudioBitRate = 12200; 1088 mInterleaveDurationUs = 0; 1089 mIFramesIntervalSec = 1; 1090 mAudioSourceNode = 0; 1091 mUse64BitFileOffset = false; 1092 mMovieTimeScale = 1000; 1093 mAudioTimeScale = 1000; 1094 mVideoTimeScale = 1000; 1095 mCameraId = 0; 1096 mVideoEncoderProfile = -1; 1097 mVideoEncoderLevel = -1; 1098 mMaxFileDurationUs = 0; 1099 mMaxFileSizeBytes = 0; 1100 mTrackEveryNumberOfFrames = 0; 1101 mTrackEveryTimeDurationUs = 0; 1102 mCaptureTimeLapse = false; 1103 mEncoderProfiles = MediaProfiles::getInstance(); 1104 1105 mOutputFd = -1; 1106 mFlags = 0; 1107 1108 return OK; 1109} 1110 1111status_t StagefrightRecorder::getMaxAmplitude(int *max) { 1112 LOGV("getMaxAmplitude"); 1113 1114 if (max == NULL) { 1115 LOGE("Null pointer argument"); 1116 return BAD_VALUE; 1117 } 1118 1119 if (mAudioSourceNode != 0) { 1120 *max = mAudioSourceNode->getMaxAmplitude(); 1121 } else { 1122 *max = 0; 1123 } 1124 1125 return OK; 1126} 1127 1128status_t StagefrightRecorder::dump(int fd, const Vector<String16>& args) const { 1129 const size_t SIZE = 256; 1130 char buffer[SIZE]; 1131 String8 result; 1132 snprintf(buffer, SIZE, " Recorder: %p", this); 1133 snprintf(buffer, SIZE, " Output file (fd %d):\n", mOutputFd); 1134 result.append(buffer); 1135 snprintf(buffer, SIZE, " File format: %d\n", mOutputFormat); 1136 result.append(buffer); 1137 snprintf(buffer, SIZE, " Max file size (bytes): %lld\n", mMaxFileSizeBytes); 1138 result.append(buffer); 1139 snprintf(buffer, SIZE, " Max file duration (us): %lld\n", mMaxFileDurationUs); 1140 result.append(buffer); 1141 snprintf(buffer, SIZE, " File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32); 1142 result.append(buffer); 1143 snprintf(buffer, SIZE, " Interleave duration (us): %d\n", mInterleaveDurationUs); 1144 result.append(buffer); 1145 snprintf(buffer, SIZE, " Progress notification: %d frames\n", mTrackEveryNumberOfFrames); 1146 result.append(buffer); 1147 snprintf(buffer, SIZE, " Progress notification: %lld us\n", mTrackEveryTimeDurationUs); 1148 result.append(buffer); 1149 snprintf(buffer, SIZE, " Audio\n"); 1150 result.append(buffer); 1151 snprintf(buffer, SIZE, " Source: %d\n", mAudioSource); 1152 result.append(buffer); 1153 snprintf(buffer, SIZE, " Encoder: %d\n", mAudioEncoder); 1154 result.append(buffer); 1155 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mAudioBitRate); 1156 result.append(buffer); 1157 snprintf(buffer, SIZE, " Sampling rate (hz): %d\n", mSampleRate); 1158 result.append(buffer); 1159 snprintf(buffer, SIZE, " Number of channels: %d\n", mAudioChannels); 1160 result.append(buffer); 1161 snprintf(buffer, SIZE, " Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude()); 1162 result.append(buffer); 1163 snprintf(buffer, SIZE, " Video\n"); 1164 result.append(buffer); 1165 snprintf(buffer, SIZE, " Source: %d\n", mVideoSource); 1166 result.append(buffer); 1167 snprintf(buffer, SIZE, " Camera Id: %d\n", mCameraId); 1168 result.append(buffer); 1169 snprintf(buffer, SIZE, " Camera flags: %d\n", mFlags); 1170 result.append(buffer); 1171 snprintf(buffer, SIZE, " Encoder: %d\n", mVideoEncoder); 1172 result.append(buffer); 1173 snprintf(buffer, SIZE, " Encoder profile: %d\n", mVideoEncoderProfile); 1174 result.append(buffer); 1175 snprintf(buffer, SIZE, " Encoder level: %d\n", mVideoEncoderLevel); 1176 result.append(buffer); 1177 snprintf(buffer, SIZE, " I frames interval (s): %d\n", mIFramesIntervalSec); 1178 result.append(buffer); 1179 snprintf(buffer, SIZE, " Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight); 1180 result.append(buffer); 1181 snprintf(buffer, SIZE, " Frame rate (fps): %d\n", mFrameRate); 1182 result.append(buffer); 1183 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mVideoBitRate); 1184 result.append(buffer); 1185 ::write(fd, result.string(), result.size()); 1186 return OK; 1187} 1188} // namespace android 1189