Backout a74bd5095902, Bug 959405 - Please update the Buri Moz-central, 1.3, 1.2 with...
[gecko.git] / dom / camera / GonkRecorder.cpp
blob39f5c0dfe3c1330a41c193872803d7ad1b865fcf
1 /*
2 * Copyright (C) 2009 The Android Open Source Project
3 * Copyright (C) 2013 Mozilla Foundation
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include "nsDebug.h"
19 #define DOM_CAMERA_LOG_LEVEL 3
20 #include "CameraCommon.h"
21 #include "GonkCameraSource.h"
22 #include "GonkRecorder.h"
24 #define RE_LOGD(fmt, ...) DOM_CAMERA_LOGA("[%s:%d]" fmt,__FILE__,__LINE__, ## __VA_ARGS__)
25 #define RE_LOGV(fmt, ...) DOM_CAMERA_LOGI("[%s:%d]" fmt,__FILE__,__LINE__, ## __VA_ARGS__)
26 #define RE_LOGI(fmt, ...) DOM_CAMERA_LOGI("[%s:%d]" fmt,__FILE__,__LINE__, ## __VA_ARGS__)
27 #define RE_LOGW(fmt, ...) DOM_CAMERA_LOGW("[%s:%d]" fmt,__FILE__,__LINE__, ## __VA_ARGS__)
28 #define RE_LOGE(fmt, ...) DOM_CAMERA_LOGE("[%s:%d]" fmt,__FILE__,__LINE__, ## __VA_ARGS__)
30 #include <binder/IPCThreadState.h>
31 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
32 # include <media/openmax/OMX_Audio.h>
33 #endif
34 #include <media/stagefright/foundation/ADebug.h>
35 #include <media/stagefright/AudioSource.h>
36 #include <media/stagefright/AMRWriter.h>
37 #include <media/stagefright/AACWriter.h>
38 #include <media/stagefright/MPEG2TSWriter.h>
39 #include <media/stagefright/MPEG4Writer.h>
40 #include <media/stagefright/MediaDefs.h>
41 #include <media/stagefright/MetaData.h>
42 #include <media/stagefright/OMXClient.h>
43 #include <media/stagefright/OMXCodec.h>
44 #include <media/MediaProfiles.h>
46 #include <utils/Errors.h>
47 #include <sys/types.h>
48 #include <ctype.h>
49 #include <unistd.h>
51 #include <cutils/properties.h>
52 #include <system/audio.h>
54 namespace android {
56 GonkRecorder::GonkRecorder()
57 : mWriter(NULL),
58 mOutputFd(-1),
59 mAudioSource(AUDIO_SOURCE_CNT),
60 mVideoSource(VIDEO_SOURCE_LIST_END),
61 mStarted(false) {
63 RE_LOGV("Constructor");
64 reset();
67 GonkRecorder::~GonkRecorder() {
68 RE_LOGV("Destructor");
69 stop();
72 status_t GonkRecorder::init() {
73 RE_LOGV("init");
74 return OK;
77 status_t GonkRecorder::setAudioSource(audio_source_t as) {
78 RE_LOGV("setAudioSource: %d", as);
79 if (as < AUDIO_SOURCE_DEFAULT ||
80 as >= AUDIO_SOURCE_CNT) {
81 RE_LOGE("Invalid audio source: %d", as);
82 return BAD_VALUE;
85 if (as == AUDIO_SOURCE_DEFAULT) {
86 mAudioSource = AUDIO_SOURCE_MIC;
87 } else {
88 mAudioSource = as;
91 return OK;
94 status_t GonkRecorder::setVideoSource(video_source vs) {
95 RE_LOGV("setVideoSource: %d", vs);
96 if (vs < VIDEO_SOURCE_DEFAULT ||
97 vs >= VIDEO_SOURCE_LIST_END) {
98 RE_LOGE("Invalid video source: %d", vs);
99 return BAD_VALUE;
102 if (vs == VIDEO_SOURCE_DEFAULT) {
103 mVideoSource = VIDEO_SOURCE_CAMERA;
104 } else {
105 mVideoSource = vs;
108 return OK;
111 status_t GonkRecorder::setOutputFormat(output_format of) {
112 RE_LOGV("setOutputFormat: %d", of);
113 if (of < OUTPUT_FORMAT_DEFAULT ||
114 of >= OUTPUT_FORMAT_LIST_END) {
115 RE_LOGE("Invalid output format: %d", of);
116 return BAD_VALUE;
119 if (of == OUTPUT_FORMAT_DEFAULT) {
120 mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
121 } else {
122 mOutputFormat = of;
125 return OK;
128 status_t GonkRecorder::setAudioEncoder(audio_encoder ae) {
129 RE_LOGV("setAudioEncoder: %d", ae);
130 if (ae < AUDIO_ENCODER_DEFAULT ||
131 ae >= AUDIO_ENCODER_LIST_END) {
132 RE_LOGE("Invalid audio encoder: %d", ae);
133 return BAD_VALUE;
136 if (ae == AUDIO_ENCODER_DEFAULT) {
137 mAudioEncoder = AUDIO_ENCODER_AMR_NB;
138 } else {
139 mAudioEncoder = ae;
142 return OK;
145 status_t GonkRecorder::setVideoEncoder(video_encoder ve) {
146 RE_LOGV("setVideoEncoder: %d", ve);
147 if (ve < VIDEO_ENCODER_DEFAULT ||
148 ve >= VIDEO_ENCODER_LIST_END) {
149 RE_LOGE("Invalid video encoder: %d", ve);
150 return BAD_VALUE;
153 if (ve == VIDEO_ENCODER_DEFAULT) {
154 mVideoEncoder = VIDEO_ENCODER_H263;
155 } else {
156 mVideoEncoder = ve;
159 return OK;
162 status_t GonkRecorder::setVideoSize(int width, int height) {
163 RE_LOGV("setVideoSize: %dx%d", width, height);
164 if (width <= 0 || height <= 0) {
165 RE_LOGE("Invalid video size: %dx%d", width, height);
166 return BAD_VALUE;
169 // Additional check on the dimension will be performed later
170 mVideoWidth = width;
171 mVideoHeight = height;
173 return OK;
176 status_t GonkRecorder::setVideoFrameRate(int frames_per_second) {
177 RE_LOGV("setVideoFrameRate: %d", frames_per_second);
178 if ((frames_per_second <= 0 && frames_per_second != -1) ||
179 frames_per_second > 120) {
180 RE_LOGE("Invalid video frame rate: %d", frames_per_second);
181 return BAD_VALUE;
184 // Additional check on the frame rate will be performed later
185 mFrameRate = frames_per_second;
187 return OK;
190 status_t GonkRecorder::setOutputFile(const char *path) {
191 RE_LOGE("setOutputFile(const char*) must not be called");
192 // We don't actually support this at all, as the media_server process
193 // no longer has permissions to create files.
195 return -EPERM;
198 status_t GonkRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
199 RE_LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length);
200 // These don't make any sense, do they?
201 CHECK_EQ(offset, 0ll);
202 CHECK_EQ(length, 0ll);
204 if (fd < 0) {
205 RE_LOGE("Invalid file descriptor: %d", fd);
206 return -EBADF;
209 if (mOutputFd >= 0) {
210 ::close(mOutputFd);
212 mOutputFd = dup(fd);
214 return OK;
217 // Attempt to parse an int64 literal optionally surrounded by whitespace,
218 // returns true on success, false otherwise.
219 static bool safe_strtoi64(const char *s, int64_t *val) {
220 char *end;
222 // It is lame, but according to man page, we have to set errno to 0
223 // before calling strtoll().
224 errno = 0;
225 *val = strtoll(s, &end, 10);
227 if (end == s || errno == ERANGE) {
228 return false;
231 // Skip trailing whitespace
232 while (isspace(*end)) {
233 ++end;
236 // For a successful return, the string must contain nothing but a valid
237 // int64 literal optionally surrounded by whitespace.
239 return *end == '\0';
242 // Return true if the value is in [0, 0x007FFFFFFF]
243 static bool safe_strtoi32(const char *s, int32_t *val) {
244 int64_t temp;
245 if (safe_strtoi64(s, &temp)) {
246 if (temp >= 0 && temp <= 0x007FFFFFFF) {
247 *val = static_cast<int32_t>(temp);
248 return true;
251 return false;
254 // Trim both leading and trailing whitespace from the given string.
255 static void TrimString(String8 *s) {
256 size_t num_bytes = s->bytes();
257 const char *data = s->string();
259 size_t leading_space = 0;
260 while (leading_space < num_bytes && isspace(data[leading_space])) {
261 ++leading_space;
264 size_t i = num_bytes;
265 while (i > leading_space && isspace(data[i - 1])) {
266 --i;
269 s->setTo(String8(&data[leading_space], i - leading_space));
272 status_t GonkRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
273 RE_LOGV("setParamAudioSamplingRate: %d", sampleRate);
274 if (sampleRate <= 0) {
275 RE_LOGE("Invalid audio sampling rate: %d", sampleRate);
276 return BAD_VALUE;
279 // Additional check on the sample rate will be performed later.
280 mSampleRate = sampleRate;
281 return OK;
284 status_t GonkRecorder::setParamAudioNumberOfChannels(int32_t channels) {
285 RE_LOGV("setParamAudioNumberOfChannels: %d", channels);
286 if (channels <= 0 || channels >= 3) {
287 RE_LOGE("Invalid number of audio channels: %d", channels);
288 return BAD_VALUE;
291 // Additional check on the number of channels will be performed later.
292 mAudioChannels = channels;
293 return OK;
296 status_t GonkRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
297 RE_LOGV("setParamAudioEncodingBitRate: %d", bitRate);
298 if (bitRate <= 0) {
299 RE_LOGE("Invalid audio encoding bit rate: %d", bitRate);
300 return BAD_VALUE;
303 // The target bit rate may not be exactly the same as the requested.
304 // It depends on many factors, such as rate control, and the bit rate
305 // range that a specific encoder supports. The mismatch between the
306 // the target and requested bit rate will NOT be treated as an error.
307 mAudioBitRate = bitRate;
308 return OK;
311 status_t GonkRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
312 RE_LOGV("setParamVideoEncodingBitRate: %d", bitRate);
313 if (bitRate <= 0) {
314 RE_LOGE("Invalid video encoding bit rate: %d", bitRate);
315 return BAD_VALUE;
318 // The target bit rate may not be exactly the same as the requested.
319 // It depends on many factors, such as rate control, and the bit rate
320 // range that a specific encoder supports. The mismatch between the
321 // the target and requested bit rate will NOT be treated as an error.
322 mVideoBitRate = bitRate;
323 return OK;
326 // Always rotate clockwise, and only support 0, 90, 180 and 270 for now.
327 status_t GonkRecorder::setParamVideoRotation(int32_t degrees) {
328 RE_LOGV("setParamVideoRotation: %d", degrees);
329 if (degrees < 0 || degrees % 90 != 0) {
330 RE_LOGE("Unsupported video rotation angle: %d", degrees);
331 return BAD_VALUE;
333 mRotationDegrees = degrees % 360;
334 return OK;
337 status_t GonkRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
338 RE_LOGV("setParamMaxFileDurationUs: %lld us", timeUs);
340 // This is meant for backward compatibility for MediaRecorder.java
341 if (timeUs <= 0) {
342 RE_LOGW("Max file duration is not positive: %lld us. Disabling duration limit.", timeUs);
343 timeUs = 0; // Disable the duration limit for zero or negative values.
344 } else if (timeUs <= 100000LL) { // XXX: 100 milli-seconds
345 RE_LOGE("Max file duration is too short: %lld us", timeUs);
346 return BAD_VALUE;
349 if (timeUs <= 15 * 1000000LL) {
350 RE_LOGW("Target duration (%lld us) too short to be respected", timeUs);
352 mMaxFileDurationUs = timeUs;
353 return OK;
356 status_t GonkRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
357 RE_LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
359 // This is meant for backward compatibility for MediaRecorder.java
360 if (bytes <= 0) {
361 RE_LOGW("Max file size is not positive: %lld bytes. "
362 "Disabling file size limit.", bytes);
363 bytes = 0; // Disable the file size limit for zero or negative values.
364 } else if (bytes <= 1024) { // XXX: 1 kB
365 RE_LOGE("Max file size is too small: %lld bytes", bytes);
366 return BAD_VALUE;
369 if (bytes <= 100 * 1024) {
370 RE_LOGW("Target file size (%lld bytes) is too small to be respected", bytes);
373 mMaxFileSizeBytes = bytes;
374 return OK;
377 status_t GonkRecorder::setParamInterleaveDuration(int32_t durationUs) {
378 RE_LOGV("setParamInterleaveDuration: %d", durationUs);
379 if (durationUs <= 500000) { // 500 ms
380 // If interleave duration is too small, it is very inefficient to do
381 // interleaving since the metadata overhead will count for a significant
382 // portion of the saved contents
383 RE_LOGE("Audio/video interleave duration is too small: %d us", durationUs);
384 return BAD_VALUE;
385 } else if (durationUs >= 10000000) { // 10 seconds
386 // If interleaving duration is too large, it can cause the recording
387 // session to use too much memory since we have to save the output
388 // data before we write them out
389 RE_LOGE("Audio/video interleave duration is too large: %d us", durationUs);
390 return BAD_VALUE;
392 mInterleaveDurationUs = durationUs;
393 return OK;
396 // If seconds < 0, only the first frame is I frame, and rest are all P frames
397 // If seconds == 0, all frames are encoded as I frames. No P frames
398 // If seconds > 0, it is the time spacing (seconds) between 2 neighboring I frames
399 status_t GonkRecorder::setParamVideoIFramesInterval(int32_t seconds) {
400 RE_LOGV("setParamVideoIFramesInterval: %d seconds", seconds);
401 mIFramesIntervalSec = seconds;
402 return OK;
405 status_t GonkRecorder::setParam64BitFileOffset(bool use64Bit) {
406 RE_LOGV("setParam64BitFileOffset: %s",
407 use64Bit? "use 64 bit file offset": "use 32 bit file offset");
408 mUse64BitFileOffset = use64Bit;
409 return OK;
412 status_t GonkRecorder::setParamVideoCameraId(int32_t cameraId) {
413 RE_LOGV("setParamVideoCameraId: %d", cameraId);
414 if (cameraId < 0) {
415 return BAD_VALUE;
417 mCameraId = cameraId;
418 return OK;
421 status_t GonkRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
422 RE_LOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
423 if (timeDurationUs < 20000) { // Infeasible if shorter than 20 ms?
424 RE_LOGE("Tracking time duration too short: %lld us", timeDurationUs);
425 return BAD_VALUE;
427 mTrackEveryTimeDurationUs = timeDurationUs;
428 return OK;
431 status_t GonkRecorder::setParamVideoEncoderProfile(int32_t profile) {
432 RE_LOGV("setParamVideoEncoderProfile: %d", profile);
434 // Additional check will be done later when we load the encoder.
435 // For now, we are accepting values defined in OpenMAX IL.
436 mVideoEncoderProfile = profile;
437 return OK;
440 status_t GonkRecorder::setParamVideoEncoderLevel(int32_t level) {
441 RE_LOGV("setParamVideoEncoderLevel: %d", level);
443 // Additional check will be done later when we load the encoder.
444 // For now, we are accepting values defined in OpenMAX IL.
445 mVideoEncoderLevel = level;
446 return OK;
449 status_t GonkRecorder::setParamMovieTimeScale(int32_t timeScale) {
450 RE_LOGV("setParamMovieTimeScale: %d", timeScale);
452 // The range is set to be the same as the audio's time scale range
453 // since audio's time scale has a wider range.
454 if (timeScale < 600 || timeScale > 96000) {
455 RE_LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
456 return BAD_VALUE;
458 mMovieTimeScale = timeScale;
459 return OK;
462 status_t GonkRecorder::setParamVideoTimeScale(int32_t timeScale) {
463 RE_LOGV("setParamVideoTimeScale: %d", timeScale);
465 // 60000 is chosen to make sure that each video frame from a 60-fps
466 // video has 1000 ticks.
467 if (timeScale < 600 || timeScale > 60000) {
468 RE_LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
469 return BAD_VALUE;
471 mVideoTimeScale = timeScale;
472 return OK;
475 status_t GonkRecorder::setParamAudioTimeScale(int32_t timeScale) {
476 RE_LOGV("setParamAudioTimeScale: %d", timeScale);
478 // 96000 Hz is the highest sampling rate support in AAC.
479 if (timeScale < 600 || timeScale > 96000) {
480 RE_LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
481 return BAD_VALUE;
483 mAudioTimeScale = timeScale;
484 return OK;
487 status_t GonkRecorder::setParamGeoDataLongitude(
488 int64_t longitudex10000) {
490 if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
491 return BAD_VALUE;
493 mLongitudex10000 = longitudex10000;
494 return OK;
497 status_t GonkRecorder::setParamGeoDataLatitude(
498 int64_t latitudex10000) {
500 if (latitudex10000 > 900000 || latitudex10000 < -900000) {
501 return BAD_VALUE;
503 mLatitudex10000 = latitudex10000;
504 return OK;
507 status_t GonkRecorder::setParameter(
508 const String8 &key, const String8 &value) {
509 RE_LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
510 if (key == "max-duration") {
511 int64_t max_duration_ms;
512 if (safe_strtoi64(value.string(), &max_duration_ms)) {
513 return setParamMaxFileDurationUs(1000LL * max_duration_ms);
515 } else if (key == "max-filesize") {
516 int64_t max_filesize_bytes;
517 if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
518 return setParamMaxFileSizeBytes(max_filesize_bytes);
520 } else if (key == "interleave-duration-us") {
521 int32_t durationUs;
522 if (safe_strtoi32(value.string(), &durationUs)) {
523 return setParamInterleaveDuration(durationUs);
525 } else if (key == "param-movie-time-scale") {
526 int32_t timeScale;
527 if (safe_strtoi32(value.string(), &timeScale)) {
528 return setParamMovieTimeScale(timeScale);
530 } else if (key == "param-use-64bit-offset") {
531 int32_t use64BitOffset;
532 if (safe_strtoi32(value.string(), &use64BitOffset)) {
533 return setParam64BitFileOffset(use64BitOffset != 0);
535 } else if (key == "param-geotag-longitude") {
536 int64_t longitudex10000;
537 if (safe_strtoi64(value.string(), &longitudex10000)) {
538 return setParamGeoDataLongitude(longitudex10000);
540 } else if (key == "param-geotag-latitude") {
541 int64_t latitudex10000;
542 if (safe_strtoi64(value.string(), &latitudex10000)) {
543 return setParamGeoDataLatitude(latitudex10000);
545 } else if (key == "param-track-time-status") {
546 int64_t timeDurationUs;
547 if (safe_strtoi64(value.string(), &timeDurationUs)) {
548 return setParamTrackTimeStatus(timeDurationUs);
550 } else if (key == "audio-param-sampling-rate") {
551 int32_t sampling_rate;
552 if (safe_strtoi32(value.string(), &sampling_rate)) {
553 return setParamAudioSamplingRate(sampling_rate);
555 } else if (key == "audio-param-number-of-channels") {
556 int32_t number_of_channels;
557 if (safe_strtoi32(value.string(), &number_of_channels)) {
558 return setParamAudioNumberOfChannels(number_of_channels);
560 } else if (key == "audio-param-encoding-bitrate") {
561 int32_t audio_bitrate;
562 if (safe_strtoi32(value.string(), &audio_bitrate)) {
563 return setParamAudioEncodingBitRate(audio_bitrate);
565 } else if (key == "audio-param-time-scale") {
566 int32_t timeScale;
567 if (safe_strtoi32(value.string(), &timeScale)) {
568 return setParamAudioTimeScale(timeScale);
570 } else if (key == "video-param-encoding-bitrate") {
571 int32_t video_bitrate;
572 if (safe_strtoi32(value.string(), &video_bitrate)) {
573 return setParamVideoEncodingBitRate(video_bitrate);
575 } else if (key == "video-param-rotation-angle-degrees") {
576 int32_t degrees;
577 if (safe_strtoi32(value.string(), &degrees)) {
578 return setParamVideoRotation(degrees);
580 } else if (key == "video-param-i-frames-interval") {
581 int32_t seconds;
582 if (safe_strtoi32(value.string(), &seconds)) {
583 return setParamVideoIFramesInterval(seconds);
585 } else if (key == "video-param-encoder-profile") {
586 int32_t profile;
587 if (safe_strtoi32(value.string(), &profile)) {
588 return setParamVideoEncoderProfile(profile);
590 } else if (key == "video-param-encoder-level") {
591 int32_t level;
592 if (safe_strtoi32(value.string(), &level)) {
593 return setParamVideoEncoderLevel(level);
595 } else if (key == "video-param-camera-id") {
596 int32_t cameraId;
597 if (safe_strtoi32(value.string(), &cameraId)) {
598 return setParamVideoCameraId(cameraId);
600 } else if (key == "video-param-time-scale") {
601 int32_t timeScale;
602 if (safe_strtoi32(value.string(), &timeScale)) {
603 return setParamVideoTimeScale(timeScale);
605 } else {
606 RE_LOGE("setParameter: failed to find key %s", key.string());
608 return BAD_VALUE;
611 status_t GonkRecorder::setParameters(const String8 &params) {
612 RE_LOGV("setParameters: %s", params.string());
613 const char *cparams = params.string();
614 const char *key_start = cparams;
615 for (;;) {
616 const char *equal_pos = strchr(key_start, '=');
617 if (equal_pos == NULL) {
618 RE_LOGE("Parameters %s miss a value", cparams);
619 return BAD_VALUE;
621 String8 key(key_start, equal_pos - key_start);
622 TrimString(&key);
623 if (key.length() == 0) {
624 RE_LOGE("Parameters %s contains an empty key", cparams);
625 return BAD_VALUE;
627 const char *value_start = equal_pos + 1;
628 const char *semicolon_pos = strchr(value_start, ';');
629 String8 value;
630 if (semicolon_pos == NULL) {
631 value.setTo(value_start);
632 } else {
633 value.setTo(value_start, semicolon_pos - value_start);
635 if (setParameter(key, value) != OK) {
636 return BAD_VALUE;
638 if (semicolon_pos == NULL) {
639 break; // Reaches the end
641 key_start = semicolon_pos + 1;
643 return OK;
646 status_t GonkRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
647 mListener = listener;
649 return OK;
652 status_t GonkRecorder::setClientName(const String16& clientName) {
653 mClientName = clientName;
655 return OK;
658 status_t GonkRecorder::prepare() {
659 return OK;
662 status_t GonkRecorder::start() {
663 CHECK_GE(mOutputFd, 0);
665 // Get UID here for permission checking
666 mClientUid = IPCThreadState::self()->getCallingUid();
667 if (mWriter != NULL) {
668 RE_LOGE("File writer is not avaialble");
669 return UNKNOWN_ERROR;
672 status_t status = OK;
674 switch (mOutputFormat) {
675 case OUTPUT_FORMAT_DEFAULT:
676 case OUTPUT_FORMAT_THREE_GPP:
677 case OUTPUT_FORMAT_MPEG_4:
678 status = startMPEG4Recording();
679 break;
681 case OUTPUT_FORMAT_AMR_NB:
682 case OUTPUT_FORMAT_AMR_WB:
683 status = startAMRRecording();
684 break;
686 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
687 case OUTPUT_FORMAT_AAC_ADIF:
688 case OUTPUT_FORMAT_AAC_ADTS:
689 status = startAACRecording();
690 break;
691 #endif
693 case OUTPUT_FORMAT_RTP_AVP:
694 status = startRTPRecording();
695 break;
697 case OUTPUT_FORMAT_MPEG2TS:
698 status = startMPEG2TSRecording();
699 break;
701 default:
702 RE_LOGE("Unsupported output file format: %d", mOutputFormat);
703 status = UNKNOWN_ERROR;
704 break;
707 if ((status == OK) && (!mStarted)) {
708 mStarted = true;
711 return status;
714 sp<MediaSource> GonkRecorder::createAudioSource() {
715 sp<AudioSource> audioSource =
716 new AudioSource(
717 mAudioSource,
718 mSampleRate,
719 mAudioChannels);
721 status_t err = audioSource->initCheck();
723 if (err != OK) {
724 RE_LOGE("audio source is not initialized");
725 return NULL;
728 sp<MetaData> encMeta = new MetaData;
729 const char *mime;
730 switch (mAudioEncoder) {
731 case AUDIO_ENCODER_AMR_NB:
732 case AUDIO_ENCODER_DEFAULT:
733 mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
734 break;
735 case AUDIO_ENCODER_AMR_WB:
736 mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
737 break;
738 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
739 case AUDIO_ENCODER_AAC:
740 mime = MEDIA_MIMETYPE_AUDIO_AAC;
741 encMeta->setInt32(kKeyAACProfile, OMX_AUDIO_AACObjectLC);
742 break;
743 case AUDIO_ENCODER_HE_AAC:
744 mime = MEDIA_MIMETYPE_AUDIO_AAC;
745 encMeta->setInt32(kKeyAACProfile, OMX_AUDIO_AACObjectHE);
746 break;
747 case AUDIO_ENCODER_AAC_ELD:
748 mime = MEDIA_MIMETYPE_AUDIO_AAC;
749 encMeta->setInt32(kKeyAACProfile, OMX_AUDIO_AACObjectELD);
750 break;
751 #endif
752 default:
753 RE_LOGE("Unknown audio encoder: %d", mAudioEncoder);
754 return NULL;
756 encMeta->setCString(kKeyMIMEType, mime);
758 int32_t maxInputSize;
759 CHECK(audioSource->getFormat()->findInt32(
760 kKeyMaxInputSize, &maxInputSize));
762 encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
763 encMeta->setInt32(kKeyChannelCount, mAudioChannels);
764 encMeta->setInt32(kKeySampleRate, mSampleRate);
765 encMeta->setInt32(kKeyBitRate, mAudioBitRate);
766 if (mAudioTimeScale > 0) {
767 encMeta->setInt32(kKeyTimeScale, mAudioTimeScale);
770 // OMXClient::connect() always returns OK and abort's fatally if
771 // it can't connect.
772 OMXClient client;
773 // CHECK_EQ causes an abort if the given condition fails.
774 CHECK_EQ(client.connect(), (status_t)OK);
775 sp<MediaSource> audioEncoder =
776 OMXCodec::Create(client.interface(), encMeta,
777 true /* createEncoder */, audioSource);
778 mAudioSourceNode = audioSource;
780 return audioEncoder;
783 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
784 status_t GonkRecorder::startAACRecording() {
785 // FIXME:
786 // Add support for OUTPUT_FORMAT_AAC_ADIF
787 CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS);
789 CHECK(mAudioEncoder == AUDIO_ENCODER_AAC ||
790 mAudioEncoder == AUDIO_ENCODER_HE_AAC ||
791 mAudioEncoder == AUDIO_ENCODER_AAC_ELD);
792 CHECK(mAudioSource != AUDIO_SOURCE_CNT);
794 mWriter = new AACWriter(mOutputFd);
795 status_t status = startRawAudioRecording();
796 if (status != OK) {
797 mWriter.clear();
798 mWriter = NULL;
801 return status;
803 #endif
805 status_t GonkRecorder::startAMRRecording() {
806 CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
807 mOutputFormat == OUTPUT_FORMAT_AMR_WB);
809 if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
810 if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
811 mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
812 RE_LOGE("Invalid encoder %d used for AMRNB recording",
813 mAudioEncoder);
814 return BAD_VALUE;
816 } else { // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
817 if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
818 RE_LOGE("Invlaid encoder %d used for AMRWB recording",
819 mAudioEncoder);
820 return BAD_VALUE;
824 mWriter = new AMRWriter(mOutputFd);
825 status_t status = startRawAudioRecording();
826 if (status != OK) {
827 mWriter.clear();
828 mWriter = NULL;
830 return status;
833 status_t GonkRecorder::startRawAudioRecording() {
834 if (mAudioSource >= AUDIO_SOURCE_CNT) {
835 RE_LOGE("Invalid audio source: %d", mAudioSource);
836 return BAD_VALUE;
839 status_t status = BAD_VALUE;
840 if (OK != (status = checkAudioEncoderCapabilities())) {
841 return status;
844 sp<MediaSource> audioEncoder = createAudioSource();
845 if (audioEncoder == NULL) {
846 return UNKNOWN_ERROR;
849 CHECK(mWriter != 0);
850 mWriter->addSource(audioEncoder);
852 if (mMaxFileDurationUs != 0) {
853 mWriter->setMaxFileDuration(mMaxFileDurationUs);
855 if (mMaxFileSizeBytes != 0) {
856 mWriter->setMaxFileSize(mMaxFileSizeBytes);
858 mWriter->setListener(mListener);
859 mWriter->start();
861 return OK;
864 status_t GonkRecorder::startRTPRecording() {
865 return INVALID_OPERATION;
868 status_t GonkRecorder::startMPEG2TSRecording() {
869 CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
871 sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
873 if (mAudioSource != AUDIO_SOURCE_CNT) {
874 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
875 if (mAudioEncoder != AUDIO_ENCODER_AAC &&
876 mAudioEncoder != AUDIO_ENCODER_HE_AAC &&
877 mAudioEncoder != AUDIO_ENCODER_AAC_ELD) {
878 return ERROR_UNSUPPORTED;
880 #endif
881 status_t err = setupAudioEncoder(writer);
883 if (err != OK) {
884 return err;
888 if (mVideoSource < VIDEO_SOURCE_LIST_END) {
889 if (mVideoEncoder != VIDEO_ENCODER_H264) {
890 return ERROR_UNSUPPORTED;
893 sp<MediaSource> mediaSource;
894 status_t err = setupMediaSource(&mediaSource);
895 if (err != OK) {
896 return err;
899 sp<MediaSource> encoder;
900 err = setupVideoEncoder(mediaSource, mVideoBitRate, &encoder);
902 if (err != OK) {
903 return err;
906 writer->addSource(encoder);
909 if (mMaxFileDurationUs != 0) {
910 writer->setMaxFileDuration(mMaxFileDurationUs);
913 if (mMaxFileSizeBytes != 0) {
914 writer->setMaxFileSize(mMaxFileSizeBytes);
917 mWriter = writer;
919 return mWriter->start();
922 void GonkRecorder::clipVideoFrameRate() {
923 RE_LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
924 int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
925 "enc.vid.fps.min", mVideoEncoder);
926 int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
927 "enc.vid.fps.max", mVideoEncoder);
928 if (mFrameRate < minFrameRate && minFrameRate != -1) {
929 RE_LOGW("Intended video encoding frame rate (%d fps) is too small"
930 " and will be set to (%d fps)", mFrameRate, minFrameRate);
931 mFrameRate = minFrameRate;
932 } else if (mFrameRate > maxFrameRate && maxFrameRate != -1) {
933 RE_LOGW("Intended video encoding frame rate (%d fps) is too large"
934 " and will be set to (%d fps)", mFrameRate, maxFrameRate);
935 mFrameRate = maxFrameRate;
939 void GonkRecorder::clipVideoBitRate() {
940 RE_LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
941 int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
942 "enc.vid.bps.min", mVideoEncoder);
943 int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
944 "enc.vid.bps.max", mVideoEncoder);
945 if (mVideoBitRate < minBitRate && minBitRate != -1) {
946 RE_LOGW("Intended video encoding bit rate (%d bps) is too small"
947 " and will be set to (%d bps)", mVideoBitRate, minBitRate);
948 mVideoBitRate = minBitRate;
949 } else if (mVideoBitRate > maxBitRate && maxBitRate != -1) {
950 RE_LOGW("Intended video encoding bit rate (%d bps) is too large"
951 " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
952 mVideoBitRate = maxBitRate;
956 void GonkRecorder::clipVideoFrameWidth() {
957 RE_LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
958 int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
959 "enc.vid.width.min", mVideoEncoder);
960 int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
961 "enc.vid.width.max", mVideoEncoder);
962 if (mVideoWidth < minFrameWidth && minFrameWidth != -1) {
963 RE_LOGW("Intended video encoding frame width (%d) is too small"
964 " and will be set to (%d)", mVideoWidth, minFrameWidth);
965 mVideoWidth = minFrameWidth;
966 } else if (mVideoWidth > maxFrameWidth && maxFrameWidth != -1) {
967 RE_LOGW("Intended video encoding frame width (%d) is too large"
968 " and will be set to (%d)", mVideoWidth, maxFrameWidth);
969 mVideoWidth = maxFrameWidth;
973 status_t GonkRecorder::checkVideoEncoderCapabilities() {
975 // Dont clip for time lapse capture as encoder will have enough
976 // time to encode because of slow capture rate of time lapse.
977 clipVideoBitRate();
978 clipVideoFrameRate();
979 clipVideoFrameWidth();
980 clipVideoFrameHeight();
981 setDefaultProfileIfNecessary();
982 return OK;
985 // Set to use AVC baseline profile if the encoding parameters matches
986 // CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service.
987 void GonkRecorder::setDefaultProfileIfNecessary() {
988 RE_LOGV("setDefaultProfileIfNecessary");
990 camcorder_quality quality = CAMCORDER_QUALITY_LOW;
992 int64_t durationUs = mEncoderProfiles->getCamcorderProfileParamByName(
993 "duration", mCameraId, quality) * 1000000LL;
995 int fileFormat = mEncoderProfiles->getCamcorderProfileParamByName(
996 "file.format", mCameraId, quality);
998 int videoCodec = mEncoderProfiles->getCamcorderProfileParamByName(
999 "vid.codec", mCameraId, quality);
1001 int videoBitRate = mEncoderProfiles->getCamcorderProfileParamByName(
1002 "vid.bps", mCameraId, quality);
1004 int videoFrameRate = mEncoderProfiles->getCamcorderProfileParamByName(
1005 "vid.fps", mCameraId, quality);
1007 int videoFrameWidth = mEncoderProfiles->getCamcorderProfileParamByName(
1008 "vid.width", mCameraId, quality);
1010 int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName(
1011 "vid.height", mCameraId, quality);
1013 int audioCodec = mEncoderProfiles->getCamcorderProfileParamByName(
1014 "aud.codec", mCameraId, quality);
1016 int audioBitRate = mEncoderProfiles->getCamcorderProfileParamByName(
1017 "aud.bps", mCameraId, quality);
1019 int audioSampleRate = mEncoderProfiles->getCamcorderProfileParamByName(
1020 "aud.hz", mCameraId, quality);
1022 int audioChannels = mEncoderProfiles->getCamcorderProfileParamByName(
1023 "aud.ch", mCameraId, quality);
1025 if (durationUs == mMaxFileDurationUs &&
1026 fileFormat == mOutputFormat &&
1027 videoCodec == mVideoEncoder &&
1028 videoBitRate == mVideoBitRate &&
1029 videoFrameRate == mFrameRate &&
1030 videoFrameWidth == mVideoWidth &&
1031 videoFrameHeight == mVideoHeight &&
1032 audioCodec == mAudioEncoder &&
1033 audioBitRate == mAudioBitRate &&
1034 audioSampleRate == mSampleRate &&
1035 audioChannels == mAudioChannels) {
1036 if (videoCodec == VIDEO_ENCODER_H264) {
1037 RE_LOGI("Force to use AVC baseline profile");
1038 setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline);
1043 status_t GonkRecorder::checkAudioEncoderCapabilities() {
1044 clipAudioBitRate();
1045 clipAudioSampleRate();
1046 clipNumberOfAudioChannels();
1047 return OK;
1050 void GonkRecorder::clipAudioBitRate() {
1051 RE_LOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1053 int minAudioBitRate =
1054 mEncoderProfiles->getAudioEncoderParamByName(
1055 "enc.aud.bps.min", mAudioEncoder);
1056 if (minAudioBitRate != -1 && mAudioBitRate < minAudioBitRate) {
1057 RE_LOGW("Intended audio encoding bit rate (%d) is too small"
1058 " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1059 mAudioBitRate = minAudioBitRate;
1062 int maxAudioBitRate =
1063 mEncoderProfiles->getAudioEncoderParamByName(
1064 "enc.aud.bps.max", mAudioEncoder);
1065 if (maxAudioBitRate != -1 && mAudioBitRate > maxAudioBitRate) {
1066 RE_LOGW("Intended audio encoding bit rate (%d) is too large"
1067 " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1068 mAudioBitRate = maxAudioBitRate;
1072 void GonkRecorder::clipAudioSampleRate() {
1073 RE_LOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1075 int minSampleRate =
1076 mEncoderProfiles->getAudioEncoderParamByName(
1077 "enc.aud.hz.min", mAudioEncoder);
1078 if (minSampleRate != -1 && mSampleRate < minSampleRate) {
1079 RE_LOGW("Intended audio sample rate (%d) is too small"
1080 " and will be set to (%d)", mSampleRate, minSampleRate);
1081 mSampleRate = minSampleRate;
1084 int maxSampleRate =
1085 mEncoderProfiles->getAudioEncoderParamByName(
1086 "enc.aud.hz.max", mAudioEncoder);
1087 if (maxSampleRate != -1 && mSampleRate > maxSampleRate) {
1088 RE_LOGW("Intended audio sample rate (%d) is too large"
1089 " and will be set to (%d)", mSampleRate, maxSampleRate);
1090 mSampleRate = maxSampleRate;
1094 void GonkRecorder::clipNumberOfAudioChannels() {
1095 RE_LOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1097 int minChannels =
1098 mEncoderProfiles->getAudioEncoderParamByName(
1099 "enc.aud.ch.min", mAudioEncoder);
1100 if (minChannels != -1 && mAudioChannels < minChannels) {
1101 RE_LOGW("Intended number of audio channels (%d) is too small"
1102 " and will be set to (%d)", mAudioChannels, minChannels);
1103 mAudioChannels = minChannels;
1106 int maxChannels =
1107 mEncoderProfiles->getAudioEncoderParamByName(
1108 "enc.aud.ch.max", mAudioEncoder);
1109 if (maxChannels != -1 && mAudioChannels > maxChannels) {
1110 RE_LOGW("Intended number of audio channels (%d) is too large"
1111 " and will be set to (%d)", mAudioChannels, maxChannels);
1112 mAudioChannels = maxChannels;
1116 void GonkRecorder::clipVideoFrameHeight() {
1117 RE_LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1118 int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1119 "enc.vid.height.min", mVideoEncoder);
1120 int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1121 "enc.vid.height.max", mVideoEncoder);
1122 if (minFrameHeight != -1 && mVideoHeight < minFrameHeight) {
1123 RE_LOGW("Intended video encoding frame height (%d) is too small"
1124 " and will be set to (%d)", mVideoHeight, minFrameHeight);
1125 mVideoHeight = minFrameHeight;
1126 } else if (maxFrameHeight != -1 && mVideoHeight > maxFrameHeight) {
1127 RE_LOGW("Intended video encoding frame height (%d) is too large"
1128 " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1129 mVideoHeight = maxFrameHeight;
1133 // Set up the appropriate MediaSource depending on the chosen option
1134 status_t GonkRecorder::setupMediaSource(
1135 sp<MediaSource> *mediaSource) {
1136 if (mVideoSource == VIDEO_SOURCE_DEFAULT
1137 || mVideoSource == VIDEO_SOURCE_CAMERA) {
1138 sp<GonkCameraSource> cameraSource;
1139 status_t err = setupCameraSource(&cameraSource);
1140 if (err != OK) {
1141 return err;
1143 *mediaSource = cameraSource;
1144 } else if (mVideoSource == VIDEO_SOURCE_GRALLOC_BUFFER) {
1145 return BAD_VALUE;
1146 } else {
1147 return INVALID_OPERATION;
1149 return OK;
1152 status_t GonkRecorder::setupCameraSource(
1153 sp<GonkCameraSource> *cameraSource) {
1154 status_t err = OK;
1155 if ((err = checkVideoEncoderCapabilities()) != OK) {
1156 return err;
1158 Size videoSize;
1159 videoSize.width = mVideoWidth;
1160 videoSize.height = mVideoHeight;
1161 bool useMeta = true;
1162 char value[PROPERTY_VALUE_MAX];
1163 if (property_get("debug.camcorder.disablemeta", value, NULL) &&
1164 atoi(value)) {
1165 useMeta = false;
1168 *cameraSource = GonkCameraSource::Create(
1169 mCameraHw, videoSize, mFrameRate, useMeta);
1170 if (*cameraSource == NULL) {
1171 return UNKNOWN_ERROR;
1174 if ((*cameraSource)->initCheck() != OK) {
1175 (*cameraSource).clear();
1176 *cameraSource = NULL;
1177 return NO_INIT;
1180 // When frame rate is not set, the actual frame rate will be set to
1181 // the current frame rate being used.
1182 if (mFrameRate == -1) {
1183 int32_t frameRate = 0;
1184 CHECK ((*cameraSource)->getFormat()->findInt32(
1185 kKeyFrameRate, &frameRate));
1186 RE_LOGI("Frame rate is not explicitly set. Use the current frame "
1187 "rate (%d fps)", frameRate);
1188 mFrameRate = frameRate;
1191 CHECK(mFrameRate != -1);
1193 mIsMetaDataStoredInVideoBuffers =
1194 (*cameraSource)->isMetaDataStoredInVideoBuffers();
1196 return OK;
1199 status_t GonkRecorder::setupVideoEncoder(
1200 sp<MediaSource> cameraSource,
1201 int32_t videoBitRate,
1202 sp<MediaSource> *source) {
1203 source->clear();
1205 sp<MetaData> enc_meta = new MetaData;
1206 enc_meta->setInt32(kKeyBitRate, videoBitRate);
1207 enc_meta->setInt32(kKeyFrameRate, mFrameRate);
1209 switch (mVideoEncoder) {
1210 case VIDEO_ENCODER_H263:
1211 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
1212 break;
1214 case VIDEO_ENCODER_MPEG_4_SP:
1215 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
1216 break;
1218 case VIDEO_ENCODER_H264:
1219 enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
1220 break;
1222 default:
1223 CHECK(!"Should not be here, unsupported video encoding.");
1224 break;
1227 sp<MetaData> meta = cameraSource->getFormat();
1229 int32_t width, height, stride, sliceHeight, colorFormat;
1230 CHECK(meta->findInt32(kKeyWidth, &width));
1231 CHECK(meta->findInt32(kKeyHeight, &height));
1232 CHECK(meta->findInt32(kKeyStride, &stride));
1233 CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1234 CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1236 enc_meta->setInt32(kKeyWidth, width);
1237 enc_meta->setInt32(kKeyHeight, height);
1238 enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
1239 enc_meta->setInt32(kKeyStride, stride);
1240 enc_meta->setInt32(kKeySliceHeight, sliceHeight);
1241 enc_meta->setInt32(kKeyColorFormat, colorFormat);
1242 if (mVideoTimeScale > 0) {
1243 enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
1245 if (mVideoEncoderProfile != -1) {
1246 enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
1248 if (mVideoEncoderLevel != -1) {
1249 enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
1252 // OMXClient::connect() always returns OK and abort's fatally if
1253 // it can't connect.
1254 OMXClient client;
1255 // CHECK_EQ causes an abort if the given condition fails.
1256 CHECK_EQ(client.connect(), (status_t)OK);
1258 uint32_t encoder_flags = 0;
1259 if (mIsMetaDataStoredInVideoBuffers) {
1260 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
1261 encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers;
1262 #else
1263 encoder_flags |= OMXCodec::kHardwareCodecsOnly;
1264 encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers;
1265 encoder_flags |= OMXCodec::kOnlySubmitOneInputBufferAtOneTime;
1266 #endif
1269 sp<MediaSource> encoder = OMXCodec::Create(
1270 client.interface(), enc_meta,
1271 true /* createEncoder */, cameraSource,
1272 NULL, encoder_flags);
1273 if (encoder == NULL) {
1274 RE_LOGW("Failed to create the encoder");
1275 // When the encoder fails to be created, we need
1276 // release the camera source due to the camera's lock
1277 // and unlock mechanism.
1278 cameraSource->stop();
1279 return UNKNOWN_ERROR;
1282 *source = encoder;
1284 return OK;
1287 status_t GonkRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1288 status_t status = BAD_VALUE;
1289 if (OK != (status = checkAudioEncoderCapabilities())) {
1290 return status;
1293 switch(mAudioEncoder) {
1294 case AUDIO_ENCODER_AMR_NB:
1295 case AUDIO_ENCODER_AMR_WB:
1296 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
1297 case AUDIO_ENCODER_AAC:
1298 case AUDIO_ENCODER_HE_AAC:
1299 case AUDIO_ENCODER_AAC_ELD:
1300 #endif
1301 break;
1303 default:
1304 RE_LOGE("Unsupported audio encoder: %d", mAudioEncoder);
1305 return UNKNOWN_ERROR;
1308 sp<MediaSource> audioEncoder = createAudioSource();
1309 if (audioEncoder == NULL) {
1310 return UNKNOWN_ERROR;
1313 writer->addSource(audioEncoder);
1314 return OK;
1317 status_t GonkRecorder::setupMPEG4Recording(
1318 int outputFd,
1319 int32_t videoWidth, int32_t videoHeight,
1320 int32_t videoBitRate,
1321 int32_t *totalBitRate,
1322 sp<MediaWriter> *mediaWriter) {
1323 mediaWriter->clear();
1324 *totalBitRate = 0;
1325 status_t err = OK;
1326 sp<MediaWriter> writer = new MPEG4Writer(outputFd);
1328 if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1330 sp<MediaSource> mediaSource;
1331 err = setupMediaSource(&mediaSource);
1332 if (err != OK) {
1333 return err;
1336 sp<MediaSource> encoder;
1337 err = setupVideoEncoder(mediaSource, videoBitRate, &encoder);
1338 if (err != OK) {
1339 return err;
1342 writer->addSource(encoder);
1343 *totalBitRate += videoBitRate;
1346 // Audio source is added at the end if it exists.
1347 // This help make sure that the "recoding" sound is suppressed for
1348 // camcorder applications in the recorded files.
1349 if (mAudioSource != AUDIO_SOURCE_CNT) {
1350 err = setupAudioEncoder(writer);
1351 if (err != OK) return err;
1352 *totalBitRate += mAudioBitRate;
1355 if (mInterleaveDurationUs > 0) {
1356 reinterpret_cast<MPEG4Writer *>(writer.get())->
1357 setInterleaveDuration(mInterleaveDurationUs);
1359 if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1360 reinterpret_cast<MPEG4Writer *>(writer.get())->
1361 setGeoData(mLatitudex10000, mLongitudex10000);
1363 if (mMaxFileDurationUs != 0) {
1364 writer->setMaxFileDuration(mMaxFileDurationUs);
1366 if (mMaxFileSizeBytes != 0) {
1367 writer->setMaxFileSize(mMaxFileSizeBytes);
1370 mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1371 if (mStartTimeOffsetMs > 0) {
1372 reinterpret_cast<MPEG4Writer *>(writer.get())->
1373 setStartTimeOffsetMs(mStartTimeOffsetMs);
1376 writer->setListener(mListener);
1377 *mediaWriter = writer;
1378 return OK;
1381 void GonkRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate,
1382 sp<MetaData> *meta) {
1383 (*meta)->setInt64(kKeyTime, startTimeUs);
1384 (*meta)->setInt32(kKeyFileType, mOutputFormat);
1385 (*meta)->setInt32(kKeyBitRate, totalBitRate);
1386 (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1387 if (mMovieTimeScale > 0) {
1388 (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1390 if (mTrackEveryTimeDurationUs > 0) {
1391 (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1394 char value[PROPERTY_VALUE_MAX];
1395 if (property_get("debug.camcorder.rotation", value, 0) > 0 && atoi(value) >= 0) {
1396 mRotationDegrees = atoi(value);
1397 RE_LOGI("Setting rotation to %d", mRotationDegrees );
1400 if (mRotationDegrees != 0) {
1401 (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1405 status_t GonkRecorder::startMPEG4Recording() {
1406 int32_t totalBitRate;
1407 status_t err = setupMPEG4Recording(
1408 mOutputFd, mVideoWidth, mVideoHeight,
1409 mVideoBitRate, &totalBitRate, &mWriter);
1410 if (err != OK) {
1411 return err;
1414 //systemTime() doesn't give correct time because
1415 //HAVE_POSIX_CLOCKS is not defined for utils/Timers.cpp
1416 //so, using clock_gettime directly
1417 #include <time.h>
1418 struct timespec t;
1419 clock_gettime(CLOCK_MONOTONIC, &t);
1420 int64_t startTimeUs = int64_t(t.tv_sec)*1000000000LL + t.tv_nsec;
1421 startTimeUs = startTimeUs / 1000;
1422 sp<MetaData> meta = new MetaData;
1423 setupMPEG4MetaData(startTimeUs, totalBitRate, &meta);
1425 err = mWriter->start(meta.get());
1426 if (err != OK) {
1427 return err;
1430 return OK;
1433 status_t GonkRecorder::pause() {
1434 RE_LOGV("pause");
1435 if (mWriter == NULL) {
1436 return UNKNOWN_ERROR;
1438 mWriter->pause();
1440 if (mStarted) {
1441 mStarted = false;
1445 return OK;
1448 status_t GonkRecorder::stop() {
1449 RE_LOGV("stop");
1450 status_t err = OK;
1452 if (mWriter != NULL) {
1453 err = mWriter->stop();
1454 mWriter.clear();
1457 if (mOutputFd >= 0) {
1458 ::close(mOutputFd);
1459 mOutputFd = -1;
1462 if (mStarted) {
1463 mStarted = false;
1467 return err;
1470 status_t GonkRecorder::close() {
1471 RE_LOGV("close");
1472 stop();
1474 return OK;
1477 status_t GonkRecorder::reset() {
1478 RE_LOGV("reset");
1479 stop();
1481 // No audio or video source by default
1482 mAudioSource = AUDIO_SOURCE_CNT;
1483 mVideoSource = VIDEO_SOURCE_LIST_END;
1485 // Default parameters
1486 mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
1487 mAudioEncoder = AUDIO_ENCODER_AMR_NB;
1488 mVideoEncoder = VIDEO_ENCODER_H263;
1489 mVideoWidth = 176;
1490 mVideoHeight = 144;
1491 mFrameRate = -1;
1492 mVideoBitRate = 192000;
1493 mSampleRate = 8000;
1494 mAudioChannels = 1;
1495 mAudioBitRate = 12200;
1496 mInterleaveDurationUs = 0;
1497 mIFramesIntervalSec = 1;
1498 mAudioSourceNode = 0;
1499 mUse64BitFileOffset = false;
1500 mMovieTimeScale = -1;
1501 mAudioTimeScale = -1;
1502 mVideoTimeScale = -1;
1503 mCameraId = 0;
1504 mStartTimeOffsetMs = -1;
1505 mVideoEncoderProfile = -1;
1506 mVideoEncoderLevel = -1;
1507 mMaxFileDurationUs = 0;
1508 mMaxFileSizeBytes = 0;
1509 mTrackEveryTimeDurationUs = 0;
1510 mIsMetaDataStoredInVideoBuffers = false;
1511 mEncoderProfiles = MediaProfiles::getInstance();
1512 mRotationDegrees = 0;
1513 mLatitudex10000 = -3600000;
1514 mLongitudex10000 = -3600000;
1516 mOutputFd = -1;
1517 mCameraHw.clear();
1518 //TODO: May need to register a listener eventually
1519 //if someone is interested in recorder events for now
1520 //default to no listener registered
1521 mListener = NULL;
1523 return OK;
1526 status_t GonkRecorder::getMaxAmplitude(int *max) {
1527 RE_LOGV("getMaxAmplitude");
1529 if (max == NULL) {
1530 RE_LOGE("Null pointer argument");
1531 return BAD_VALUE;
1534 if (mAudioSourceNode != 0) {
1535 *max = mAudioSourceNode->getMaxAmplitude();
1536 } else {
1537 *max = 0;
1540 return OK;
1543 status_t GonkRecorder::dump(
1544 int fd, const Vector<String16>& args) const {
1545 RE_LOGV("dump");
1546 const size_t SIZE = 256;
1547 char buffer[SIZE];
1548 String8 result;
1549 if (mWriter != 0) {
1550 mWriter->dump(fd, args);
1551 } else {
1552 snprintf(buffer, SIZE, " No file writer\n");
1553 result.append(buffer);
1555 snprintf(buffer, SIZE, " Recorder: %p\n", this);
1556 snprintf(buffer, SIZE, " Output file (fd %d):\n", mOutputFd);
1557 result.append(buffer);
1558 snprintf(buffer, SIZE, " File format: %d\n", mOutputFormat);
1559 result.append(buffer);
1560 snprintf(buffer, SIZE, " Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1561 result.append(buffer);
1562 snprintf(buffer, SIZE, " Max file duration (us): %lld\n", mMaxFileDurationUs);
1563 result.append(buffer);
1564 snprintf(buffer, SIZE, " File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1565 result.append(buffer);
1566 snprintf(buffer, SIZE, " Interleave duration (us): %d\n", mInterleaveDurationUs);
1567 result.append(buffer);
1568 snprintf(buffer, SIZE, " Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1569 result.append(buffer);
1570 snprintf(buffer, SIZE, " Audio\n");
1571 result.append(buffer);
1572 snprintf(buffer, SIZE, " Source: %d\n", mAudioSource);
1573 result.append(buffer);
1574 snprintf(buffer, SIZE, " Encoder: %d\n", mAudioEncoder);
1575 result.append(buffer);
1576 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mAudioBitRate);
1577 result.append(buffer);
1578 snprintf(buffer, SIZE, " Sampling rate (hz): %d\n", mSampleRate);
1579 result.append(buffer);
1580 snprintf(buffer, SIZE, " Number of channels: %d\n", mAudioChannels);
1581 result.append(buffer);
1582 snprintf(buffer, SIZE, " Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1583 result.append(buffer);
1584 snprintf(buffer, SIZE, " Video\n");
1585 result.append(buffer);
1586 snprintf(buffer, SIZE, " Source: %d\n", mVideoSource);
1587 result.append(buffer);
1588 snprintf(buffer, SIZE, " Camera Id: %d\n", mCameraId);
1589 result.append(buffer);
1590 snprintf(buffer, SIZE, " Camera object address: %p\n", mCameraHw.get());
1591 result.append(buffer);
1592 snprintf(buffer, SIZE, " Start time offset (ms): %d\n", mStartTimeOffsetMs);
1593 result.append(buffer);
1594 snprintf(buffer, SIZE, " Encoder: %d\n", mVideoEncoder);
1595 result.append(buffer);
1596 snprintf(buffer, SIZE, " Encoder profile: %d\n", mVideoEncoderProfile);
1597 result.append(buffer);
1598 snprintf(buffer, SIZE, " Encoder level: %d\n", mVideoEncoderLevel);
1599 result.append(buffer);
1600 snprintf(buffer, SIZE, " I frames interval (s): %d\n", mIFramesIntervalSec);
1601 result.append(buffer);
1602 snprintf(buffer, SIZE, " Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1603 result.append(buffer);
1604 snprintf(buffer, SIZE, " Frame rate (fps): %d\n", mFrameRate);
1605 result.append(buffer);
1606 snprintf(buffer, SIZE, " Bit rate (bps): %d\n", mVideoBitRate);
1607 result.append(buffer);
1608 ::write(fd, result.string(), result.size());
1609 return OK;
1612 status_t GonkRecorder::setCamera(const sp<GonkCameraHardware>& aCameraHw) {
1613 mCameraHw = aCameraHw;
1614 return OK;
1617 } // namespace android