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