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