StagefrightRecorder.cpp revision fc20aab463f527ab3b0664986f0381a86b375884
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::setParameter( 430 const String8 &key, const String8 &value) { 431 LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string()); 432 if (key == "max-duration") { 433 int64_t max_duration_ms; 434 if (safe_strtoi64(value.string(), &max_duration_ms)) { 435 return setParamMaxFileDurationUs(1000LL * max_duration_ms); 436 } 437 } else if (key == "max-filesize") { 438 int64_t max_filesize_bytes; 439 if (safe_strtoi64(value.string(), &max_filesize_bytes)) { 440 return setParamMaxFileSizeBytes(max_filesize_bytes); 441 } 442 } else if (key == "interleave-duration-us") { 443 int32_t durationUs; 444 if (safe_strtoi32(value.string(), &durationUs)) { 445 return setParamInterleaveDuration(durationUs); 446 } 447 } else if (key == "param-use-64bit-offset") { 448 int32_t use64BitOffset; 449 if (safe_strtoi32(value.string(), &use64BitOffset)) { 450 return setParam64BitFileOffset(use64BitOffset != 0); 451 } 452 } else if (key == "param-track-frame-status") { 453 int32_t nFrames; 454 if (safe_strtoi32(value.string(), &nFrames)) { 455 return setParamTrackFrameStatus(nFrames); 456 } 457 } else if (key == "param-track-time-status") { 458 int64_t timeDurationUs; 459 if (safe_strtoi64(value.string(), &timeDurationUs)) { 460 return setParamTrackTimeStatus(timeDurationUs); 461 } 462 } else if (key == "audio-param-sampling-rate") { 463 int32_t sampling_rate; 464 if (safe_strtoi32(value.string(), &sampling_rate)) { 465 return setParamAudioSamplingRate(sampling_rate); 466 } 467 } else if (key == "audio-param-number-of-channels") { 468 int32_t number_of_channels; 469 if (safe_strtoi32(value.string(), &number_of_channels)) { 470 return setParamAudioNumberOfChannels(number_of_channels); 471 } 472 } else if (key == "audio-param-encoding-bitrate") { 473 int32_t audio_bitrate; 474 if (safe_strtoi32(value.string(), &audio_bitrate)) { 475 return setParamAudioEncodingBitRate(audio_bitrate); 476 } 477 } else if (key == "video-param-encoding-bitrate") { 478 int32_t video_bitrate; 479 if (safe_strtoi32(value.string(), &video_bitrate)) { 480 return setParamVideoEncodingBitRate(video_bitrate); 481 } 482 } else if (key == "video-param-i-frames-interval") { 483 int32_t interval; 484 if (safe_strtoi32(value.string(), &interval)) { 485 return setParamVideoIFramesInterval(interval); 486 } 487 } else if (key == "video-param-camera-id") { 488 int32_t cameraId; 489 if (safe_strtoi32(value.string(), &cameraId)) { 490 return setParamVideoCameraId(cameraId); 491 } 492 } else { 493 LOGE("setParameter: failed to find key %s", key.string()); 494 } 495 return BAD_VALUE; 496} 497 498status_t StagefrightRecorder::setParameters(const String8 ¶ms) { 499 LOGV("setParameters: %s", params.string()); 500 const char *cparams = params.string(); 501 const char *key_start = cparams; 502 for (;;) { 503 const char *equal_pos = strchr(key_start, '='); 504 if (equal_pos == NULL) { 505 LOGE("Parameters %s miss a value", cparams); 506 return BAD_VALUE; 507 } 508 String8 key(key_start, equal_pos - key_start); 509 TrimString(&key); 510 if (key.length() == 0) { 511 LOGE("Parameters %s contains an empty key", cparams); 512 return BAD_VALUE; 513 } 514 const char *value_start = equal_pos + 1; 515 const char *semicolon_pos = strchr(value_start, ';'); 516 String8 value; 517 if (semicolon_pos == NULL) { 518 value.setTo(value_start); 519 } else { 520 value.setTo(value_start, semicolon_pos - value_start); 521 } 522 if (setParameter(key, value) != OK) { 523 return BAD_VALUE; 524 } 525 if (semicolon_pos == NULL) { 526 break; // Reaches the end 527 } 528 key_start = semicolon_pos + 1; 529 } 530 return OK; 531} 532 533status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) { 534 mListener = listener; 535 536 return OK; 537} 538 539status_t StagefrightRecorder::prepare() { 540 return OK; 541} 542 543status_t StagefrightRecorder::start() { 544 CHECK(mOutputFd >= 0); 545 546 if (mWriter != NULL) { 547 LOGE("File writer is not avaialble"); 548 return UNKNOWN_ERROR; 549 } 550 551 switch (mOutputFormat) { 552 case OUTPUT_FORMAT_DEFAULT: 553 case OUTPUT_FORMAT_THREE_GPP: 554 case OUTPUT_FORMAT_MPEG_4: 555 return startMPEG4Recording(); 556 557 case OUTPUT_FORMAT_AMR_NB: 558 case OUTPUT_FORMAT_AMR_WB: 559 return startAMRRecording(); 560 561 case OUTPUT_FORMAT_AAC_ADIF: 562 case OUTPUT_FORMAT_AAC_ADTS: 563 return startAACRecording(); 564 565 default: 566 LOGE("Unsupported output file format: %d", mOutputFormat); 567 return UNKNOWN_ERROR; 568 } 569} 570 571sp<MediaSource> StagefrightRecorder::createAudioSource() { 572 sp<AudioSource> audioSource = 573 new AudioSource( 574 mAudioSource, 575 mSampleRate, 576 mAudioChannels); 577 578 status_t err = audioSource->initCheck(); 579 580 if (err != OK) { 581 LOGE("audio source is not initialized"); 582 return NULL; 583 } 584 585 sp<MetaData> encMeta = new MetaData; 586 const char *mime; 587 switch (mAudioEncoder) { 588 case AUDIO_ENCODER_AMR_NB: 589 case AUDIO_ENCODER_DEFAULT: 590 mime = MEDIA_MIMETYPE_AUDIO_AMR_NB; 591 break; 592 case AUDIO_ENCODER_AMR_WB: 593 mime = MEDIA_MIMETYPE_AUDIO_AMR_WB; 594 break; 595 case AUDIO_ENCODER_AAC: 596 mime = MEDIA_MIMETYPE_AUDIO_AAC; 597 break; 598 default: 599 LOGE("Unknown audio encoder: %d", mAudioEncoder); 600 return NULL; 601 } 602 encMeta->setCString(kKeyMIMEType, mime); 603 604 int32_t maxInputSize; 605 CHECK(audioSource->getFormat()->findInt32( 606 kKeyMaxInputSize, &maxInputSize)); 607 608 encMeta->setInt32(kKeyMaxInputSize, maxInputSize); 609 encMeta->setInt32(kKeyChannelCount, mAudioChannels); 610 encMeta->setInt32(kKeySampleRate, mSampleRate); 611 encMeta->setInt32(kKeyBitRate, mAudioBitRate); 612 613 OMXClient client; 614 CHECK_EQ(client.connect(), OK); 615 616 sp<MediaSource> audioEncoder = 617 OMXCodec::Create(client.interface(), encMeta, 618 true /* createEncoder */, audioSource); 619 mAudioSourceNode = audioSource; 620 621 return audioEncoder; 622} 623 624status_t StagefrightRecorder::startAACRecording() { 625 CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF || 626 mOutputFormat == OUTPUT_FORMAT_AAC_ADTS); 627 628 CHECK(mAudioEncoder == AUDIO_ENCODER_AAC); 629 CHECK(mAudioSource != AUDIO_SOURCE_LIST_END); 630 631 CHECK(0 == "AACWriter is not implemented yet"); 632 633 return OK; 634} 635 636status_t StagefrightRecorder::startAMRRecording() { 637 CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB || 638 mOutputFormat == OUTPUT_FORMAT_AMR_WB); 639 640 if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) { 641 if (mAudioEncoder != AUDIO_ENCODER_DEFAULT && 642 mAudioEncoder != AUDIO_ENCODER_AMR_NB) { 643 LOGE("Invalid encoder %d used for AMRNB recording", 644 mAudioEncoder); 645 return BAD_VALUE; 646 } 647 if (mSampleRate != 8000) { 648 LOGE("Invalid sampling rate %d used for AMRNB recording", 649 mSampleRate); 650 return BAD_VALUE; 651 } 652 } else { // mOutputFormat must be OUTPUT_FORMAT_AMR_WB 653 if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) { 654 LOGE("Invlaid encoder %d used for AMRWB recording", 655 mAudioEncoder); 656 return BAD_VALUE; 657 } 658 if (mSampleRate != 16000) { 659 LOGE("Invalid sample rate %d used for AMRWB recording", 660 mSampleRate); 661 return BAD_VALUE; 662 } 663 } 664 if (mAudioChannels != 1) { 665 LOGE("Invalid number of audio channels %d used for amr recording", 666 mAudioChannels); 667 return BAD_VALUE; 668 } 669 670 if (mAudioSource >= AUDIO_SOURCE_LIST_END) { 671 LOGE("Invalid audio source: %d", mAudioSource); 672 return BAD_VALUE; 673 } 674 675 sp<MediaSource> audioEncoder = createAudioSource(); 676 677 if (audioEncoder == NULL) { 678 return UNKNOWN_ERROR; 679 } 680 681 mWriter = new AMRWriter(dup(mOutputFd)); 682 mWriter->addSource(audioEncoder); 683 684 if (mMaxFileDurationUs != 0) { 685 mWriter->setMaxFileDuration(mMaxFileDurationUs); 686 } 687 if (mMaxFileSizeBytes != 0) { 688 mWriter->setMaxFileSize(mMaxFileSizeBytes); 689 } 690 mWriter->setListener(mListener); 691 mWriter->start(); 692 693 return OK; 694} 695 696void StagefrightRecorder::clipVideoFrameRate() { 697 LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder); 698 int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 699 "enc.vid.fps.min", mVideoEncoder); 700 int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 701 "enc.vid.fps.max", mVideoEncoder); 702 if (mFrameRate < minFrameRate) { 703 LOGW("Intended video encoding frame rate (%d fps) is too small" 704 " and will be set to (%d fps)", mFrameRate, minFrameRate); 705 mFrameRate = minFrameRate; 706 } else if (mFrameRate > maxFrameRate) { 707 LOGW("Intended video encoding frame rate (%d fps) is too large" 708 " and will be set to (%d fps)", mFrameRate, maxFrameRate); 709 mFrameRate = maxFrameRate; 710 } 711} 712 713void StagefrightRecorder::clipVideoBitRate() { 714 LOGV("clipVideoBitRate: encoder %d", mVideoEncoder); 715 int minBitRate = mEncoderProfiles->getVideoEncoderParamByName( 716 "enc.vid.bps.min", mVideoEncoder); 717 int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName( 718 "enc.vid.bps.max", mVideoEncoder); 719 if (mVideoBitRate < minBitRate) { 720 LOGW("Intended video encoding bit rate (%d bps) is too small" 721 " and will be set to (%d bps)", mVideoBitRate, minBitRate); 722 mVideoBitRate = minBitRate; 723 } else if (mVideoBitRate > maxBitRate) { 724 LOGW("Intended video encoding bit rate (%d bps) is too large" 725 " and will be set to (%d bps)", mVideoBitRate, maxBitRate); 726 mVideoBitRate = maxBitRate; 727 } 728} 729 730void StagefrightRecorder::clipVideoFrameWidth() { 731 LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder); 732 int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 733 "enc.vid.width.min", mVideoEncoder); 734 int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 735 "enc.vid.width.max", mVideoEncoder); 736 if (mVideoWidth < minFrameWidth) { 737 LOGW("Intended video encoding frame width (%d) is too small" 738 " and will be set to (%d)", mVideoWidth, minFrameWidth); 739 mVideoWidth = minFrameWidth; 740 } else if (mVideoWidth > maxFrameWidth) { 741 LOGW("Intended video encoding frame width (%d) is too large" 742 " and will be set to (%d)", mVideoWidth, maxFrameWidth); 743 mVideoWidth = maxFrameWidth; 744 } 745} 746 747status_t StagefrightRecorder::setupCameraSource() { 748 clipVideoBitRate(); 749 clipVideoFrameRate(); 750 clipVideoFrameWidth(); 751 clipVideoFrameHeight(); 752 753 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 754 if (mCamera == 0) { 755 mCamera = Camera::connect(mCameraId); 756 if (mCamera == 0) { 757 LOGE("Camera connection could not be established."); 758 return -EBUSY; 759 } 760 mFlags &= ~FLAGS_HOT_CAMERA; 761 mCamera->lock(); 762 } 763 764 // Set the actual video recording frame size 765 CameraParameters params(mCamera->getParameters()); 766 params.setPreviewSize(mVideoWidth, mVideoHeight); 767 params.setPreviewFrameRate(mFrameRate); 768 String8 s = params.flatten(); 769 CHECK_EQ(OK, mCamera->setParameters(s)); 770 CameraParameters newCameraParams(mCamera->getParameters()); 771 772 // Check on video frame size 773 int frameWidth = 0, frameHeight = 0; 774 newCameraParams.getPreviewSize(&frameWidth, &frameHeight); 775 if (frameWidth < 0 || frameWidth != mVideoWidth || 776 frameHeight < 0 || frameHeight != mVideoHeight) { 777 LOGE("Failed to set the video frame size to %dx%d", 778 mVideoWidth, mVideoHeight); 779 IPCThreadState::self()->restoreCallingIdentity(token); 780 return UNKNOWN_ERROR; 781 } 782 783 // Check on video frame rate 784 int frameRate = newCameraParams.getPreviewFrameRate(); 785 if (frameRate < 0 || (frameRate - mFrameRate) != 0) { 786 LOGE("Failed to set frame rate to %d fps. The actual " 787 "frame rate is %d", mFrameRate, frameRate); 788 } 789 790 CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface)); 791 IPCThreadState::self()->restoreCallingIdentity(token); 792 return OK; 793} 794 795void StagefrightRecorder::clipVideoFrameHeight() { 796 LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder); 797 int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 798 "enc.vid.height.min", mVideoEncoder); 799 int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 800 "enc.vid.height.max", mVideoEncoder); 801 if (mVideoHeight < minFrameHeight) { 802 LOGW("Intended video encoding frame height (%d) is too small" 803 " and will be set to (%d)", mVideoHeight, minFrameHeight); 804 mVideoHeight = minFrameHeight; 805 } else if (mVideoHeight > maxFrameHeight) { 806 LOGW("Intended video encoding frame height (%d) is too large" 807 " and will be set to (%d)", mVideoHeight, maxFrameHeight); 808 mVideoHeight = maxFrameHeight; 809 } 810} 811 812status_t StagefrightRecorder::setupVideoEncoder(const sp<MediaWriter>& writer) { 813 status_t err = setupCameraSource(); 814 if (err != OK) return err; 815 816 sp<CameraSource> cameraSource = CameraSource::CreateFromCamera(mCamera); 817 CHECK(cameraSource != NULL); 818 if(mCaptureTimeLapse) { 819 cameraSource->enableTimeLapseMode(1E6, mFrameRate); 820 } 821 822 sp<MetaData> enc_meta = new MetaData; 823 enc_meta->setInt32(kKeyBitRate, mVideoBitRate); 824 enc_meta->setInt32(kKeySampleRate, mFrameRate); 825 826 switch (mVideoEncoder) { 827 case VIDEO_ENCODER_H263: 828 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 829 break; 830 831 case VIDEO_ENCODER_MPEG_4_SP: 832 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 833 break; 834 835 case VIDEO_ENCODER_H264: 836 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 837 break; 838 839 default: 840 CHECK(!"Should not be here, unsupported video encoding."); 841 break; 842 } 843 844 sp<MetaData> meta = cameraSource->getFormat(); 845 846 int32_t width, height, stride, sliceHeight; 847 CHECK(meta->findInt32(kKeyWidth, &width)); 848 CHECK(meta->findInt32(kKeyHeight, &height)); 849 CHECK(meta->findInt32(kKeyStride, &stride)); 850 CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); 851 852 enc_meta->setInt32(kKeyWidth, width); 853 enc_meta->setInt32(kKeyHeight, height); 854 enc_meta->setInt32(kKeyIFramesInterval, mIFramesInterval); 855 enc_meta->setInt32(kKeyStride, stride); 856 enc_meta->setInt32(kKeySliceHeight, sliceHeight); 857 858 OMXClient client; 859 CHECK_EQ(client.connect(), OK); 860 861 sp<MediaSource> encoder = OMXCodec::Create( 862 client.interface(), enc_meta, 863 true /* createEncoder */, cameraSource); 864 if (encoder == NULL) { 865 return UNKNOWN_ERROR; 866 } 867 868 writer->addSource(encoder); 869 return OK; 870} 871 872status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) { 873 sp<MediaSource> audioEncoder; 874 switch(mAudioEncoder) { 875 case AUDIO_ENCODER_AMR_NB: 876 case AUDIO_ENCODER_AMR_WB: 877 case AUDIO_ENCODER_AAC: 878 audioEncoder = createAudioSource(); 879 break; 880 default: 881 LOGE("Unsupported audio encoder: %d", mAudioEncoder); 882 return UNKNOWN_ERROR; 883 } 884 885 if (audioEncoder == NULL) { 886 return UNKNOWN_ERROR; 887 } 888 writer->addSource(audioEncoder); 889 return OK; 890} 891 892status_t StagefrightRecorder::startMPEG4Recording() { 893 int32_t totalBitRate = 0; 894 status_t err = OK; 895 sp<MediaWriter> writer = new MPEG4Writer(dup(mOutputFd)); 896 897 // Add audio source first if it exists 898 if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_LIST_END)) { 899 err = setupAudioEncoder(writer); 900 if (err != OK) return err; 901 totalBitRate += mAudioBitRate; 902 } 903 if (mVideoSource == VIDEO_SOURCE_DEFAULT 904 || mVideoSource == VIDEO_SOURCE_CAMERA) { 905 err = setupVideoEncoder(writer); 906 if (err != OK) return err; 907 totalBitRate += mVideoBitRate; 908 } 909 910 reinterpret_cast<MPEG4Writer *>(writer.get())-> 911 setInterleaveDuration(mInterleaveDurationUs); 912 913 if (mMaxFileDurationUs != 0) { 914 writer->setMaxFileDuration(mMaxFileDurationUs); 915 } 916 if (mMaxFileSizeBytes != 0) { 917 writer->setMaxFileSize(mMaxFileSizeBytes); 918 } 919 sp<MetaData> meta = new MetaData; 920 meta->setInt64(kKeyTime, systemTime() / 1000); 921 meta->setInt32(kKeyFileType, mOutputFormat); 922 meta->setInt32(kKeyBitRate, totalBitRate); 923 meta->setInt32(kKey64BitFileOffset, mUse64BitFileOffset); 924 if (mTrackEveryNumberOfFrames > 0) { 925 meta->setInt32(kKeyTrackFrameStatus, mTrackEveryNumberOfFrames); 926 } 927 if (mTrackEveryTimeDurationUs > 0) { 928 meta->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs); 929 } 930 writer->setListener(mListener); 931 mWriter = writer; 932 return mWriter->start(meta.get()); 933} 934 935status_t StagefrightRecorder::pause() { 936 LOGV("pause"); 937 if (mWriter == NULL) { 938 return UNKNOWN_ERROR; 939 } 940 mWriter->pause(); 941 return OK; 942} 943 944status_t StagefrightRecorder::stop() { 945 LOGV("stop"); 946 if (mWriter != NULL) { 947 mWriter->stop(); 948 mWriter.clear(); 949 } 950 951 if (mCamera != 0) { 952 LOGV("Disconnect camera"); 953 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 954 if ((mFlags & FLAGS_HOT_CAMERA) == 0) { 955 LOGV("Camera was cold when we started, stopping preview"); 956 mCamera->stopPreview(); 957 } 958 mCamera->unlock(); 959 mCamera.clear(); 960 IPCThreadState::self()->restoreCallingIdentity(token); 961 mFlags = 0; 962 } 963 964 return OK; 965} 966 967status_t StagefrightRecorder::close() { 968 LOGV("close"); 969 stop(); 970 971 return OK; 972} 973 974status_t StagefrightRecorder::reset() { 975 LOGV("reset"); 976 stop(); 977 978 // No audio or video source by default 979 mAudioSource = AUDIO_SOURCE_LIST_END; 980 mVideoSource = VIDEO_SOURCE_LIST_END; 981 982 // Default parameters 983 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 984 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 985 mVideoEncoder = VIDEO_ENCODER_H263; 986 mVideoWidth = 176; 987 mVideoHeight = 144; 988 mFrameRate = 20; 989 mVideoBitRate = 192000; 990 mSampleRate = 8000; 991 mAudioChannels = 1; 992 mAudioBitRate = 12200; 993 mInterleaveDurationUs = 0; 994 mIFramesInterval = 1; 995 mAudioSourceNode = 0; 996 mUse64BitFileOffset = false; 997 mCameraId = 0; 998 mTrackEveryNumberOfFrames = 0; 999 mTrackEveryTimeDurationUs = 0; 1000 mCaptureTimeLapse = false; 1001 mEncoderProfiles = MediaProfiles::getInstance(); 1002 1003 mOutputFd = -1; 1004 mFlags = 0; 1005 1006 return OK; 1007} 1008 1009status_t StagefrightRecorder::getMaxAmplitude(int *max) { 1010 LOGV("getMaxAmplitude"); 1011 1012 if (max == NULL) { 1013 LOGE("Null pointer argument"); 1014 return BAD_VALUE; 1015 } 1016 1017 if (mAudioSourceNode != 0) { 1018 *max = mAudioSourceNode->getMaxAmplitude(); 1019 } else { 1020 *max = 0; 1021 } 1022 1023 return OK; 1024} 1025 1026} // namespace android 1027