StagefrightRecorder.cpp revision 8f5f2fcee5c12d08df71d17017410c50951fc2e3
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 seconds < 0, only the first frame is I frame, and rest are all P frames 385// If seconds == 0, all frames are encoded as I frames. No P frames 386// If seconds > 0, it is the time spacing (seconds) between 2 neighboring I frames 387status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) { 388 LOGV("setParamVideoIFramesInterval: %d seconds", seconds); 389 mIFramesIntervalSec = seconds; 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::setParamMovieTimeScale(int32_t timeScale) { 448 LOGV("setParamMovieTimeScale: %d", timeScale); 449 450 // The range is set to be the same as the audio's time scale range 451 // since audio's time scale has a wider range. 452 if (timeScale < 600 || timeScale > 96000) { 453 LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale); 454 return BAD_VALUE; 455 } 456 mMovieTimeScale = timeScale; 457 return OK; 458} 459 460status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) { 461 LOGV("setParamVideoTimeScale: %d", timeScale); 462 463 // 60000 is chosen to make sure that each video frame from a 60-fps 464 // video has 1000 ticks. 465 if (timeScale < 600 || timeScale > 60000) { 466 LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale); 467 return BAD_VALUE; 468 } 469 mVideoTimeScale = timeScale; 470 return OK; 471} 472 473status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) { 474 LOGV("setParamAudioTimeScale: %d", timeScale); 475 476 // 96000 Hz is the highest sampling rate support in AAC. 477 if (timeScale < 600 || timeScale > 96000) { 478 LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale); 479 return BAD_VALUE; 480 } 481 mAudioTimeScale = timeScale; 482 return OK; 483} 484 485status_t StagefrightRecorder::setParameter( 486 const String8 &key, const String8 &value) { 487 LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string()); 488 if (key == "max-duration") { 489 int64_t max_duration_ms; 490 if (safe_strtoi64(value.string(), &max_duration_ms)) { 491 return setParamMaxFileDurationUs(1000LL * max_duration_ms); 492 } 493 } else if (key == "max-filesize") { 494 int64_t max_filesize_bytes; 495 if (safe_strtoi64(value.string(), &max_filesize_bytes)) { 496 return setParamMaxFileSizeBytes(max_filesize_bytes); 497 } 498 } else if (key == "interleave-duration-us") { 499 int32_t durationUs; 500 if (safe_strtoi32(value.string(), &durationUs)) { 501 return setParamInterleaveDuration(durationUs); 502 } 503 } else if (key == "param-movie-time-scale") { 504 int32_t timeScale; 505 if (safe_strtoi32(value.string(), &timeScale)) { 506 return setParamMovieTimeScale(timeScale); 507 } 508 } else if (key == "param-use-64bit-offset") { 509 int32_t use64BitOffset; 510 if (safe_strtoi32(value.string(), &use64BitOffset)) { 511 return setParam64BitFileOffset(use64BitOffset != 0); 512 } 513 } else if (key == "param-track-frame-status") { 514 int32_t nFrames; 515 if (safe_strtoi32(value.string(), &nFrames)) { 516 return setParamTrackFrameStatus(nFrames); 517 } 518 } else if (key == "param-track-time-status") { 519 int64_t timeDurationUs; 520 if (safe_strtoi64(value.string(), &timeDurationUs)) { 521 return setParamTrackTimeStatus(timeDurationUs); 522 } 523 } else if (key == "audio-param-sampling-rate") { 524 int32_t sampling_rate; 525 if (safe_strtoi32(value.string(), &sampling_rate)) { 526 return setParamAudioSamplingRate(sampling_rate); 527 } 528 } else if (key == "audio-param-number-of-channels") { 529 int32_t number_of_channels; 530 if (safe_strtoi32(value.string(), &number_of_channels)) { 531 return setParamAudioNumberOfChannels(number_of_channels); 532 } 533 } else if (key == "audio-param-encoding-bitrate") { 534 int32_t audio_bitrate; 535 if (safe_strtoi32(value.string(), &audio_bitrate)) { 536 return setParamAudioEncodingBitRate(audio_bitrate); 537 } 538 } else if (key == "audio-param-time-scale") { 539 int32_t timeScale; 540 if (safe_strtoi32(value.string(), &timeScale)) { 541 return setParamAudioTimeScale(timeScale); 542 } 543 } else if (key == "video-param-encoding-bitrate") { 544 int32_t video_bitrate; 545 if (safe_strtoi32(value.string(), &video_bitrate)) { 546 return setParamVideoEncodingBitRate(video_bitrate); 547 } 548 } else if (key == "video-param-i-frames-interval") { 549 int32_t seconds; 550 if (safe_strtoi32(value.string(), &seconds)) { 551 return setParamVideoIFramesInterval(seconds); 552 } 553 } else if (key == "video-param-encoder-profile") { 554 int32_t profile; 555 if (safe_strtoi32(value.string(), &profile)) { 556 return setParamVideoEncoderProfile(profile); 557 } 558 } else if (key == "video-param-encoder-level") { 559 int32_t level; 560 if (safe_strtoi32(value.string(), &level)) { 561 return setParamVideoEncoderLevel(level); 562 } 563 } else if (key == "video-param-camera-id") { 564 int32_t cameraId; 565 if (safe_strtoi32(value.string(), &cameraId)) { 566 return setParamVideoCameraId(cameraId); 567 } 568 } else if (key == "video-param-time-scale") { 569 int32_t timeScale; 570 if (safe_strtoi32(value.string(), &timeScale)) { 571 return setParamVideoTimeScale(timeScale); 572 } 573 } else { 574 LOGE("setParameter: failed to find key %s", key.string()); 575 } 576 return BAD_VALUE; 577} 578 579status_t StagefrightRecorder::setParameters(const String8 ¶ms) { 580 LOGV("setParameters: %s", params.string()); 581 const char *cparams = params.string(); 582 const char *key_start = cparams; 583 for (;;) { 584 const char *equal_pos = strchr(key_start, '='); 585 if (equal_pos == NULL) { 586 LOGE("Parameters %s miss a value", cparams); 587 return BAD_VALUE; 588 } 589 String8 key(key_start, equal_pos - key_start); 590 TrimString(&key); 591 if (key.length() == 0) { 592 LOGE("Parameters %s contains an empty key", cparams); 593 return BAD_VALUE; 594 } 595 const char *value_start = equal_pos + 1; 596 const char *semicolon_pos = strchr(value_start, ';'); 597 String8 value; 598 if (semicolon_pos == NULL) { 599 value.setTo(value_start); 600 } else { 601 value.setTo(value_start, semicolon_pos - value_start); 602 } 603 if (setParameter(key, value) != OK) { 604 return BAD_VALUE; 605 } 606 if (semicolon_pos == NULL) { 607 break; // Reaches the end 608 } 609 key_start = semicolon_pos + 1; 610 } 611 return OK; 612} 613 614status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) { 615 mListener = listener; 616 617 return OK; 618} 619 620status_t StagefrightRecorder::prepare() { 621 return OK; 622} 623 624status_t StagefrightRecorder::start() { 625 CHECK(mOutputFd >= 0); 626 627 if (mWriter != NULL) { 628 LOGE("File writer is not avaialble"); 629 return UNKNOWN_ERROR; 630 } 631 632 switch (mOutputFormat) { 633 case OUTPUT_FORMAT_DEFAULT: 634 case OUTPUT_FORMAT_THREE_GPP: 635 case OUTPUT_FORMAT_MPEG_4: 636 return startMPEG4Recording(); 637 638 case OUTPUT_FORMAT_AMR_NB: 639 case OUTPUT_FORMAT_AMR_WB: 640 return startAMRRecording(); 641 642 case OUTPUT_FORMAT_AAC_ADIF: 643 case OUTPUT_FORMAT_AAC_ADTS: 644 return startAACRecording(); 645 646 default: 647 LOGE("Unsupported output file format: %d", mOutputFormat); 648 return UNKNOWN_ERROR; 649 } 650} 651 652sp<MediaSource> StagefrightRecorder::createAudioSource() { 653 sp<AudioSource> audioSource = 654 new AudioSource( 655 mAudioSource, 656 mSampleRate, 657 mAudioChannels); 658 659 status_t err = audioSource->initCheck(); 660 661 if (err != OK) { 662 LOGE("audio source is not initialized"); 663 return NULL; 664 } 665 666 sp<MetaData> encMeta = new MetaData; 667 const char *mime; 668 switch (mAudioEncoder) { 669 case AUDIO_ENCODER_AMR_NB: 670 case AUDIO_ENCODER_DEFAULT: 671 mime = MEDIA_MIMETYPE_AUDIO_AMR_NB; 672 break; 673 case AUDIO_ENCODER_AMR_WB: 674 mime = MEDIA_MIMETYPE_AUDIO_AMR_WB; 675 break; 676 case AUDIO_ENCODER_AAC: 677 mime = MEDIA_MIMETYPE_AUDIO_AAC; 678 break; 679 default: 680 LOGE("Unknown audio encoder: %d", mAudioEncoder); 681 return NULL; 682 } 683 encMeta->setCString(kKeyMIMEType, mime); 684 685 int32_t maxInputSize; 686 CHECK(audioSource->getFormat()->findInt32( 687 kKeyMaxInputSize, &maxInputSize)); 688 689 encMeta->setInt32(kKeyMaxInputSize, maxInputSize); 690 encMeta->setInt32(kKeyChannelCount, mAudioChannels); 691 encMeta->setInt32(kKeySampleRate, mSampleRate); 692 encMeta->setInt32(kKeyBitRate, mAudioBitRate); 693 encMeta->setInt32(kKeyTimeScale, mAudioTimeScale); 694 695 OMXClient client; 696 CHECK_EQ(client.connect(), OK); 697 698 sp<MediaSource> audioEncoder = 699 OMXCodec::Create(client.interface(), encMeta, 700 true /* createEncoder */, audioSource); 701 mAudioSourceNode = audioSource; 702 703 return audioEncoder; 704} 705 706status_t StagefrightRecorder::startAACRecording() { 707 CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF || 708 mOutputFormat == OUTPUT_FORMAT_AAC_ADTS); 709 710 CHECK(mAudioEncoder == AUDIO_ENCODER_AAC); 711 CHECK(mAudioSource != AUDIO_SOURCE_LIST_END); 712 713 CHECK(0 == "AACWriter is not implemented yet"); 714 715 return OK; 716} 717 718status_t StagefrightRecorder::startAMRRecording() { 719 CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB || 720 mOutputFormat == OUTPUT_FORMAT_AMR_WB); 721 722 if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) { 723 if (mAudioEncoder != AUDIO_ENCODER_DEFAULT && 724 mAudioEncoder != AUDIO_ENCODER_AMR_NB) { 725 LOGE("Invalid encoder %d used for AMRNB recording", 726 mAudioEncoder); 727 return BAD_VALUE; 728 } 729 if (mSampleRate != 8000) { 730 LOGE("Invalid sampling rate %d used for AMRNB recording", 731 mSampleRate); 732 return BAD_VALUE; 733 } 734 } else { // mOutputFormat must be OUTPUT_FORMAT_AMR_WB 735 if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) { 736 LOGE("Invlaid encoder %d used for AMRWB recording", 737 mAudioEncoder); 738 return BAD_VALUE; 739 } 740 if (mSampleRate != 16000) { 741 LOGE("Invalid sample rate %d used for AMRWB recording", 742 mSampleRate); 743 return BAD_VALUE; 744 } 745 } 746 if (mAudioChannels != 1) { 747 LOGE("Invalid number of audio channels %d used for amr recording", 748 mAudioChannels); 749 return BAD_VALUE; 750 } 751 752 if (mAudioSource >= AUDIO_SOURCE_LIST_END) { 753 LOGE("Invalid audio source: %d", mAudioSource); 754 return BAD_VALUE; 755 } 756 757 sp<MediaSource> audioEncoder = createAudioSource(); 758 759 if (audioEncoder == NULL) { 760 return UNKNOWN_ERROR; 761 } 762 763 mWriter = new AMRWriter(dup(mOutputFd)); 764 mWriter->addSource(audioEncoder); 765 766 if (mMaxFileDurationUs != 0) { 767 mWriter->setMaxFileDuration(mMaxFileDurationUs); 768 } 769 if (mMaxFileSizeBytes != 0) { 770 mWriter->setMaxFileSize(mMaxFileSizeBytes); 771 } 772 mWriter->setListener(mListener); 773 mWriter->start(); 774 775 return OK; 776} 777 778void StagefrightRecorder::clipVideoFrameRate() { 779 LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder); 780 int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 781 "enc.vid.fps.min", mVideoEncoder); 782 int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName( 783 "enc.vid.fps.max", mVideoEncoder); 784 if (mFrameRate < minFrameRate) { 785 LOGW("Intended video encoding frame rate (%d fps) is too small" 786 " and will be set to (%d fps)", mFrameRate, minFrameRate); 787 mFrameRate = minFrameRate; 788 } else if (mFrameRate > maxFrameRate) { 789 LOGW("Intended video encoding frame rate (%d fps) is too large" 790 " and will be set to (%d fps)", mFrameRate, maxFrameRate); 791 mFrameRate = maxFrameRate; 792 } 793} 794 795void StagefrightRecorder::clipVideoBitRate() { 796 LOGV("clipVideoBitRate: encoder %d", mVideoEncoder); 797 int minBitRate = mEncoderProfiles->getVideoEncoderParamByName( 798 "enc.vid.bps.min", mVideoEncoder); 799 int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName( 800 "enc.vid.bps.max", mVideoEncoder); 801 if (mVideoBitRate < minBitRate) { 802 LOGW("Intended video encoding bit rate (%d bps) is too small" 803 " and will be set to (%d bps)", mVideoBitRate, minBitRate); 804 mVideoBitRate = minBitRate; 805 } else if (mVideoBitRate > maxBitRate) { 806 LOGW("Intended video encoding bit rate (%d bps) is too large" 807 " and will be set to (%d bps)", mVideoBitRate, maxBitRate); 808 mVideoBitRate = maxBitRate; 809 } 810} 811 812void StagefrightRecorder::clipVideoFrameWidth() { 813 LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder); 814 int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 815 "enc.vid.width.min", mVideoEncoder); 816 int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName( 817 "enc.vid.width.max", mVideoEncoder); 818 if (mVideoWidth < minFrameWidth) { 819 LOGW("Intended video encoding frame width (%d) is too small" 820 " and will be set to (%d)", mVideoWidth, minFrameWidth); 821 mVideoWidth = minFrameWidth; 822 } else if (mVideoWidth > maxFrameWidth) { 823 LOGW("Intended video encoding frame width (%d) is too large" 824 " and will be set to (%d)", mVideoWidth, maxFrameWidth); 825 mVideoWidth = maxFrameWidth; 826 } 827} 828 829status_t StagefrightRecorder::setupCameraSource() { 830 clipVideoBitRate(); 831 clipVideoFrameRate(); 832 clipVideoFrameWidth(); 833 clipVideoFrameHeight(); 834 835 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 836 if (mCamera == 0) { 837 mCamera = Camera::connect(mCameraId); 838 if (mCamera == 0) { 839 LOGE("Camera connection could not be established."); 840 return -EBUSY; 841 } 842 mFlags &= ~FLAGS_HOT_CAMERA; 843 mCamera->lock(); 844 } 845 846 // Set the actual video recording frame size 847 CameraParameters params(mCamera->getParameters()); 848 params.setPreviewSize(mVideoWidth, mVideoHeight); 849 params.setPreviewFrameRate(mFrameRate); 850 String8 s = params.flatten(); 851 CHECK_EQ(OK, mCamera->setParameters(s)); 852 CameraParameters newCameraParams(mCamera->getParameters()); 853 854 // Check on video frame size 855 int frameWidth = 0, frameHeight = 0; 856 newCameraParams.getPreviewSize(&frameWidth, &frameHeight); 857 if (frameWidth < 0 || frameWidth != mVideoWidth || 858 frameHeight < 0 || frameHeight != mVideoHeight) { 859 LOGE("Failed to set the video frame size to %dx%d", 860 mVideoWidth, mVideoHeight); 861 IPCThreadState::self()->restoreCallingIdentity(token); 862 return UNKNOWN_ERROR; 863 } 864 865 // Check on video frame rate 866 int frameRate = newCameraParams.getPreviewFrameRate(); 867 if (frameRate < 0 || (frameRate - mFrameRate) != 0) { 868 LOGE("Failed to set frame rate to %d fps. The actual " 869 "frame rate is %d", mFrameRate, frameRate); 870 } 871 872 CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface)); 873 IPCThreadState::self()->restoreCallingIdentity(token); 874 return OK; 875} 876 877void StagefrightRecorder::clipVideoFrameHeight() { 878 LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder); 879 int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 880 "enc.vid.height.min", mVideoEncoder); 881 int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName( 882 "enc.vid.height.max", mVideoEncoder); 883 if (mVideoHeight < minFrameHeight) { 884 LOGW("Intended video encoding frame height (%d) is too small" 885 " and will be set to (%d)", mVideoHeight, minFrameHeight); 886 mVideoHeight = minFrameHeight; 887 } else if (mVideoHeight > maxFrameHeight) { 888 LOGW("Intended video encoding frame height (%d) is too large" 889 " and will be set to (%d)", mVideoHeight, maxFrameHeight); 890 mVideoHeight = maxFrameHeight; 891 } 892} 893 894status_t StagefrightRecorder::setupVideoEncoder(const sp<MediaWriter>& writer) { 895 status_t err = setupCameraSource(); 896 if (err != OK) return err; 897 898 sp<CameraSource> cameraSource = CameraSource::CreateFromCamera(mCamera); 899 CHECK(cameraSource != NULL); 900 901 sp<MetaData> enc_meta = new MetaData; 902 enc_meta->setInt32(kKeyBitRate, mVideoBitRate); 903 enc_meta->setInt32(kKeySampleRate, mFrameRate); 904 905 switch (mVideoEncoder) { 906 case VIDEO_ENCODER_H263: 907 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 908 break; 909 910 case VIDEO_ENCODER_MPEG_4_SP: 911 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 912 break; 913 914 case VIDEO_ENCODER_H264: 915 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 916 break; 917 918 default: 919 CHECK(!"Should not be here, unsupported video encoding."); 920 break; 921 } 922 923 sp<MetaData> meta = cameraSource->getFormat(); 924 925 int32_t width, height, stride, sliceHeight, colorFormat; 926 CHECK(meta->findInt32(kKeyWidth, &width)); 927 CHECK(meta->findInt32(kKeyHeight, &height)); 928 CHECK(meta->findInt32(kKeyStride, &stride)); 929 CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); 930 CHECK(meta->findInt32(kKeyColorFormat, &colorFormat)); 931 932 enc_meta->setInt32(kKeyWidth, width); 933 enc_meta->setInt32(kKeyHeight, height); 934 enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec); 935 enc_meta->setInt32(kKeyStride, stride); 936 enc_meta->setInt32(kKeySliceHeight, sliceHeight); 937 enc_meta->setInt32(kKeyColorFormat, colorFormat); 938 enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale); 939 if (mVideoEncoderProfile != -1) { 940 enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile); 941 } 942 if (mVideoEncoderLevel != -1) { 943 enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel); 944 } 945 946 OMXClient client; 947 CHECK_EQ(client.connect(), OK); 948 949 sp<MediaSource> encoder = OMXCodec::Create( 950 client.interface(), enc_meta, 951 true /* createEncoder */, cameraSource); 952 if (encoder == NULL) { 953 return UNKNOWN_ERROR; 954 } 955 956 writer->addSource(encoder); 957 return OK; 958} 959 960status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) { 961 sp<MediaSource> audioEncoder; 962 switch(mAudioEncoder) { 963 case AUDIO_ENCODER_AMR_NB: 964 case AUDIO_ENCODER_AMR_WB: 965 case AUDIO_ENCODER_AAC: 966 audioEncoder = createAudioSource(); 967 break; 968 default: 969 LOGE("Unsupported audio encoder: %d", mAudioEncoder); 970 return UNKNOWN_ERROR; 971 } 972 973 if (audioEncoder == NULL) { 974 return UNKNOWN_ERROR; 975 } 976 977 writer->addSource(audioEncoder); 978 return OK; 979} 980 981status_t StagefrightRecorder::startMPEG4Recording() { 982 int32_t totalBitRate = 0; 983 status_t err = OK; 984 sp<MediaWriter> writer = new MPEG4Writer(dup(mOutputFd)); 985 986 // Add audio source first if it exists 987 if (mAudioSource != AUDIO_SOURCE_LIST_END) { 988 err = setupAudioEncoder(writer); 989 if (err != OK) return err; 990 totalBitRate += mAudioBitRate; 991 } 992 if (mVideoSource == VIDEO_SOURCE_DEFAULT 993 || mVideoSource == VIDEO_SOURCE_CAMERA) { 994 err = setupVideoEncoder(writer); 995 if (err != OK) return err; 996 totalBitRate += mVideoBitRate; 997 } 998 999 reinterpret_cast<MPEG4Writer *>(writer.get())-> 1000 setInterleaveDuration(mInterleaveDurationUs); 1001 1002 if (mMaxFileDurationUs != 0) { 1003 writer->setMaxFileDuration(mMaxFileDurationUs); 1004 } 1005 if (mMaxFileSizeBytes != 0) { 1006 writer->setMaxFileSize(mMaxFileSizeBytes); 1007 } 1008 sp<MetaData> meta = new MetaData; 1009 meta->setInt64(kKeyTime, systemTime() / 1000); 1010 meta->setInt32(kKeyFileType, mOutputFormat); 1011 meta->setInt32(kKeyBitRate, totalBitRate); 1012 meta->setInt32(kKey64BitFileOffset, mUse64BitFileOffset); 1013 meta->setInt32(kKeyTimeScale, mMovieTimeScale); 1014 if (mTrackEveryNumberOfFrames > 0) { 1015 meta->setInt32(kKeyTrackFrameStatus, mTrackEveryNumberOfFrames); 1016 } 1017 if (mTrackEveryTimeDurationUs > 0) { 1018 meta->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs); 1019 } 1020 writer->setListener(mListener); 1021 mWriter = writer; 1022 return mWriter->start(meta.get()); 1023} 1024 1025status_t StagefrightRecorder::pause() { 1026 LOGV("pause"); 1027 if (mWriter == NULL) { 1028 return UNKNOWN_ERROR; 1029 } 1030 mWriter->pause(); 1031 return OK; 1032} 1033 1034status_t StagefrightRecorder::stop() { 1035 LOGV("stop"); 1036 if (mWriter != NULL) { 1037 mWriter->stop(); 1038 mWriter.clear(); 1039 } 1040 1041 if (mCamera != 0) { 1042 LOGV("Disconnect camera"); 1043 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 1044 if ((mFlags & FLAGS_HOT_CAMERA) == 0) { 1045 LOGV("Camera was cold when we started, stopping preview"); 1046 mCamera->stopPreview(); 1047 } 1048 mCamera->unlock(); 1049 mCamera.clear(); 1050 IPCThreadState::self()->restoreCallingIdentity(token); 1051 mFlags = 0; 1052 } 1053 1054 return OK; 1055} 1056 1057status_t StagefrightRecorder::close() { 1058 LOGV("close"); 1059 stop(); 1060 1061 return OK; 1062} 1063 1064status_t StagefrightRecorder::reset() { 1065 LOGV("reset"); 1066 stop(); 1067 1068 // No audio or video source by default 1069 mAudioSource = AUDIO_SOURCE_LIST_END; 1070 mVideoSource = VIDEO_SOURCE_LIST_END; 1071 1072 // Default parameters 1073 mOutputFormat = OUTPUT_FORMAT_THREE_GPP; 1074 mAudioEncoder = AUDIO_ENCODER_AMR_NB; 1075 mVideoEncoder = VIDEO_ENCODER_H263; 1076 mVideoWidth = 176; 1077 mVideoHeight = 144; 1078 mFrameRate = 20; 1079 mVideoBitRate = 192000; 1080 mSampleRate = 8000; 1081 mAudioChannels = 1; 1082 mAudioBitRate = 12200; 1083 mInterleaveDurationUs = 0; 1084 mIFramesIntervalSec = 1; 1085 mAudioSourceNode = 0; 1086 mUse64BitFileOffset = false; 1087 mMovieTimeScale = 1000; 1088 mAudioTimeScale = 1000; 1089 mVideoTimeScale = 1000; 1090 mCameraId = 0; 1091 mVideoEncoderProfile = -1; 1092 mVideoEncoderLevel = -1; 1093 mMaxFileDurationUs = 0; 1094 mMaxFileSizeBytes = 0; 1095 mTrackEveryNumberOfFrames = 0; 1096 mTrackEveryTimeDurationUs = 0; 1097 mEncoderProfiles = MediaProfiles::getInstance(); 1098 1099 mOutputFd = -1; 1100 mFlags = 0; 1101 1102 return OK; 1103} 1104 1105status_t StagefrightRecorder::getMaxAmplitude(int *max) { 1106 LOGV("getMaxAmplitude"); 1107 1108 if (max == NULL) { 1109 LOGE("Null pointer argument"); 1110 return BAD_VALUE; 1111 } 1112 1113 if (mAudioSourceNode != 0) { 1114 *max = mAudioSourceNode->getMaxAmplitude(); 1115 } else { 1116 *max = 0; 1117 } 1118 1119 return OK; 1120} 1121 1122status_t StagefrightRecorder::dump(int fd, const Vector<String16>& args) const { 1123 const size_t SIZE = 256; 1124 char buffer[SIZE]; 1125 String8 result; 1126 snprintf(buffer, SIZE, " Recorder: %p", this); 1127 snprintf(buffer, SIZE, " Output file (fd %d):\n", mOutputFd); 1128 result.append(buffer); 1129 snprintf(buffer, SIZE, " File format: %d\n", mOutputFormat); 1130 result.append(buffer); 1131 snprintf(buffer, SIZE, " Max file size (bytes): %lld\n", mMaxFileSizeBytes); 1132 result.append(buffer); 1133 snprintf(buffer, SIZE, " Max file duration (us): %lld\n", mMaxFileDurationUs); 1134 result.append(buffer); 1135 snprintf(buffer, SIZE, " File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32); 1136 result.append(buffer); 1137 snprintf(buffer, SIZE, " Interleave duration (us): %d\n", mInterleaveDurationUs); 1138 result.append(buffer); 1139 snprintf(buffer, SIZE, " Progress notification: %d frames\n", mTrackEveryNumberOfFrames); 1140 result.append(buffer); 1141 snprintf(buffer, SIZE, " Progress notification: %lld us\n", mTrackEveryTimeDurationUs); 1142 result.append(buffer); 1143 snprintf(buffer, SIZE, " Audio\n"); 1144 result.append(buffer); 1145 snprintf(buffer, SIZE, " Source: %d\n", mAudioSource); 1146 result.append(buffer); 1147 snprintf(buffer, SIZE, " Encoder: %d\n", mAudioEncoder); 1148 result.append(buffer); 1149 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mAudioBitRate); 1150 result.append(buffer); 1151 snprintf(buffer, SIZE, " Sampling rate (hz): %d\n", mSampleRate); 1152 result.append(buffer); 1153 snprintf(buffer, SIZE, " Number of channels: %d\n", mAudioChannels); 1154 result.append(buffer); 1155 snprintf(buffer, SIZE, " Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude()); 1156 result.append(buffer); 1157 snprintf(buffer, SIZE, " Video\n"); 1158 result.append(buffer); 1159 snprintf(buffer, SIZE, " Source: %d\n", mVideoSource); 1160 result.append(buffer); 1161 snprintf(buffer, SIZE, " Camera Id: %d\n", mCameraId); 1162 result.append(buffer); 1163 snprintf(buffer, SIZE, " Camera flags: %d\n", mFlags); 1164 result.append(buffer); 1165 snprintf(buffer, SIZE, " Encoder: %d\n", mVideoEncoder); 1166 result.append(buffer); 1167 snprintf(buffer, SIZE, " Encoder profile: %d\n", mVideoEncoderProfile); 1168 result.append(buffer); 1169 snprintf(buffer, SIZE, " Encoder level: %d\n", mVideoEncoderLevel); 1170 result.append(buffer); 1171 snprintf(buffer, SIZE, " I frames interval (s): %d\n", mIFramesIntervalSec); 1172 result.append(buffer); 1173 snprintf(buffer, SIZE, " Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight); 1174 result.append(buffer); 1175 snprintf(buffer, SIZE, " Frame rate (fps): %d\n", mFrameRate); 1176 result.append(buffer); 1177 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mVideoBitRate); 1178 result.append(buffer); 1179 ::write(fd, result.string(), result.size()); 1180 return OK; 1181} 1182} // namespace android 1183