StagefrightRecorder.cpp revision 4ca2c7c913f8bd4ada13aca56d36045d42d1e00f
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 <binder/IServiceManager.h>
25
26#include <media/IMediaPlayerService.h>
27#include <media/stagefright/AudioSource.h>
28#include <media/stagefright/AMRWriter.h>
29#include <media/stagefright/AACWriter.h>
30#include <media/stagefright/CameraSource.h>
31#include <media/stagefright/VideoSourceDownSampler.h>
32#include <media/stagefright/CameraSourceTimeLapse.h>
33#include <media/stagefright/MediaSourceSplitter.h>
34#include <media/stagefright/MPEG2TSWriter.h>
35#include <media/stagefright/MPEG4Writer.h>
36#include <media/stagefright/MediaDebug.h>
37#include <media/stagefright/MediaDefs.h>
38#include <media/stagefright/MetaData.h>
39#include <media/stagefright/OMXClient.h>
40#include <media/stagefright/OMXCodec.h>
41#include <media/MediaProfiles.h>
42#include <camera/ICamera.h>
43#include <camera/CameraParameters.h>
44#include <surfaceflinger/Surface.h>
45#include <utils/Errors.h>
46#include <sys/types.h>
47#include <ctype.h>
48#include <unistd.h>
49
50#include <system/audio.h>
51
52#include "ARTPWriter.h"
53
54namespace android {
55
56// To collect the encoder usage for the battery app
57static void addBatteryData(uint32_t params) {
58    sp<IBinder> binder =
59        defaultServiceManager()->getService(String16("media.player"));
60    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
61    CHECK(service.get() != NULL);
62
63    service->addBatteryData(params);
64}
65
66
67StagefrightRecorder::StagefrightRecorder()
68    : mWriter(NULL), mWriterAux(NULL),
69      mOutputFd(-1), mOutputFdAux(-1),
70      mAudioSource(AUDIO_SOURCE_CNT),
71      mVideoSource(VIDEO_SOURCE_LIST_END),
72      mStarted(false) {
73
74    LOGV("Constructor");
75    reset();
76}
77
78StagefrightRecorder::~StagefrightRecorder() {
79    LOGV("Destructor");
80    stop();
81}
82
83status_t StagefrightRecorder::init() {
84    LOGV("init");
85    return OK;
86}
87
88status_t StagefrightRecorder::setAudioSource(audio_source_t as) {
89    LOGV("setAudioSource: %d", as);
90    if (as < AUDIO_SOURCE_DEFAULT ||
91        as >= AUDIO_SOURCE_CNT) {
92        LOGE("Invalid audio source: %d", as);
93        return BAD_VALUE;
94    }
95
96    if (as == AUDIO_SOURCE_DEFAULT) {
97        mAudioSource = AUDIO_SOURCE_MIC;
98    } else {
99        mAudioSource = as;
100    }
101
102    return OK;
103}
104
105status_t StagefrightRecorder::setVideoSource(video_source vs) {
106    LOGV("setVideoSource: %d", vs);
107    if (vs < VIDEO_SOURCE_DEFAULT ||
108        vs >= VIDEO_SOURCE_LIST_END) {
109        LOGE("Invalid video source: %d", vs);
110        return BAD_VALUE;
111    }
112
113    if (vs == VIDEO_SOURCE_DEFAULT) {
114        mVideoSource = VIDEO_SOURCE_CAMERA;
115    } else {
116        mVideoSource = vs;
117    }
118
119    return OK;
120}
121
122status_t StagefrightRecorder::setOutputFormat(output_format of) {
123    LOGV("setOutputFormat: %d", of);
124    if (of < OUTPUT_FORMAT_DEFAULT ||
125        of >= OUTPUT_FORMAT_LIST_END) {
126        LOGE("Invalid output format: %d", of);
127        return BAD_VALUE;
128    }
129
130    if (of == OUTPUT_FORMAT_DEFAULT) {
131        mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
132    } else {
133        mOutputFormat = of;
134    }
135
136    return OK;
137}
138
139status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
140    LOGV("setAudioEncoder: %d", ae);
141    if (ae < AUDIO_ENCODER_DEFAULT ||
142        ae >= AUDIO_ENCODER_LIST_END) {
143        LOGE("Invalid audio encoder: %d", ae);
144        return BAD_VALUE;
145    }
146
147    if (ae == AUDIO_ENCODER_DEFAULT) {
148        mAudioEncoder = AUDIO_ENCODER_AMR_NB;
149    } else {
150        mAudioEncoder = ae;
151    }
152
153    return OK;
154}
155
156status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
157    LOGV("setVideoEncoder: %d", ve);
158    if (ve < VIDEO_ENCODER_DEFAULT ||
159        ve >= VIDEO_ENCODER_LIST_END) {
160        LOGE("Invalid video encoder: %d", ve);
161        return BAD_VALUE;
162    }
163
164    if (ve == VIDEO_ENCODER_DEFAULT) {
165        mVideoEncoder = VIDEO_ENCODER_H263;
166    } else {
167        mVideoEncoder = ve;
168    }
169
170    return OK;
171}
172
173status_t StagefrightRecorder::setVideoSize(int width, int height) {
174    LOGV("setVideoSize: %dx%d", width, height);
175    if (width <= 0 || height <= 0) {
176        LOGE("Invalid video size: %dx%d", width, height);
177        return BAD_VALUE;
178    }
179
180    // Additional check on the dimension will be performed later
181    mVideoWidth = width;
182    mVideoHeight = height;
183
184    return OK;
185}
186
187status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
188    LOGV("setVideoFrameRate: %d", frames_per_second);
189    if ((frames_per_second <= 0 && frames_per_second != -1) ||
190        frames_per_second > 120) {
191        LOGE("Invalid video frame rate: %d", frames_per_second);
192        return BAD_VALUE;
193    }
194
195    // Additional check on the frame rate will be performed later
196    mFrameRate = frames_per_second;
197
198    return OK;
199}
200
201status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera,
202                                        const sp<ICameraRecordingProxy> &proxy) {
203    LOGV("setCamera");
204    if (camera == 0) {
205        LOGE("camera is NULL");
206        return BAD_VALUE;
207    }
208    if (proxy == 0) {
209        LOGE("camera proxy is NULL");
210        return BAD_VALUE;
211    }
212
213    mCamera = camera;
214    mCameraProxy = proxy;
215    return OK;
216}
217
218status_t StagefrightRecorder::setPreviewSurface(const sp<Surface> &surface) {
219    LOGV("setPreviewSurface: %p", surface.get());
220    mPreviewSurface = surface;
221
222    return OK;
223}
224
225status_t StagefrightRecorder::setOutputFile(const char *path) {
226    LOGE("setOutputFile(const char*) must not be called");
227    // We don't actually support this at all, as the media_server process
228    // no longer has permissions to create files.
229
230    return -EPERM;
231}
232
233status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
234    LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length);
235    // These don't make any sense, do they?
236    CHECK_EQ(offset, 0);
237    CHECK_EQ(length, 0);
238
239    if (fd < 0) {
240        LOGE("Invalid file descriptor: %d", fd);
241        return -EBADF;
242    }
243
244    if (mOutputFd >= 0) {
245        ::close(mOutputFd);
246    }
247    mOutputFd = dup(fd);
248
249    return OK;
250}
251
252status_t StagefrightRecorder::setOutputFileAuxiliary(int fd) {
253    LOGV("setOutputFileAuxiliary: %d", fd);
254
255    if (fd < 0) {
256        LOGE("Invalid file descriptor: %d", fd);
257        return -EBADF;
258    }
259
260    mCaptureAuxVideo = true;
261
262    if (mOutputFdAux >= 0) {
263        ::close(mOutputFdAux);
264    }
265    mOutputFdAux = dup(fd);
266
267    return OK;
268}
269
270// Attempt to parse an int64 literal optionally surrounded by whitespace,
271// returns true on success, false otherwise.
272static bool safe_strtoi64(const char *s, int64_t *val) {
273    char *end;
274
275    // It is lame, but according to man page, we have to set errno to 0
276    // before calling strtoll().
277    errno = 0;
278    *val = strtoll(s, &end, 10);
279
280    if (end == s || errno == ERANGE) {
281        return false;
282    }
283
284    // Skip trailing whitespace
285    while (isspace(*end)) {
286        ++end;
287    }
288
289    // For a successful return, the string must contain nothing but a valid
290    // int64 literal optionally surrounded by whitespace.
291
292    return *end == '\0';
293}
294
295// Return true if the value is in [0, 0x007FFFFFFF]
296static bool safe_strtoi32(const char *s, int32_t *val) {
297    int64_t temp;
298    if (safe_strtoi64(s, &temp)) {
299        if (temp >= 0 && temp <= 0x007FFFFFFF) {
300            *val = static_cast<int32_t>(temp);
301            return true;
302        }
303    }
304    return false;
305}
306
307// Trim both leading and trailing whitespace from the given string.
308static void TrimString(String8 *s) {
309    size_t num_bytes = s->bytes();
310    const char *data = s->string();
311
312    size_t leading_space = 0;
313    while (leading_space < num_bytes && isspace(data[leading_space])) {
314        ++leading_space;
315    }
316
317    size_t i = num_bytes;
318    while (i > leading_space && isspace(data[i - 1])) {
319        --i;
320    }
321
322    s->setTo(String8(&data[leading_space], i - leading_space));
323}
324
325status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
326    LOGV("setParamAudioSamplingRate: %d", sampleRate);
327    if (sampleRate <= 0) {
328        LOGE("Invalid audio sampling rate: %d", sampleRate);
329        return BAD_VALUE;
330    }
331
332    // Additional check on the sample rate will be performed later.
333    mSampleRate = sampleRate;
334    return OK;
335}
336
337status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
338    LOGV("setParamAudioNumberOfChannels: %d", channels);
339    if (channels <= 0 || channels >= 3) {
340        LOGE("Invalid number of audio channels: %d", channels);
341        return BAD_VALUE;
342    }
343
344    // Additional check on the number of channels will be performed later.
345    mAudioChannels = channels;
346    return OK;
347}
348
349status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
350    LOGV("setParamAudioEncodingBitRate: %d", bitRate);
351    if (bitRate <= 0) {
352        LOGE("Invalid audio encoding bit rate: %d", bitRate);
353        return BAD_VALUE;
354    }
355
356    // The target bit rate may not be exactly the same as the requested.
357    // It depends on many factors, such as rate control, and the bit rate
358    // range that a specific encoder supports. The mismatch between the
359    // the target and requested bit rate will NOT be treated as an error.
360    mAudioBitRate = bitRate;
361    return OK;
362}
363
364status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
365    LOGV("setParamVideoEncodingBitRate: %d", bitRate);
366    if (bitRate <= 0) {
367        LOGE("Invalid video encoding bit rate: %d", bitRate);
368        return BAD_VALUE;
369    }
370
371    // The target bit rate may not be exactly the same as the requested.
372    // It depends on many factors, such as rate control, and the bit rate
373    // range that a specific encoder supports. The mismatch between the
374    // the target and requested bit rate will NOT be treated as an error.
375    mVideoBitRate = bitRate;
376    return OK;
377}
378
379// Always rotate clockwise, and only support 0, 90, 180 and 270 for now.
380status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) {
381    LOGV("setParamVideoRotation: %d", degrees);
382    if (degrees < 0 || degrees % 90 != 0) {
383        LOGE("Unsupported video rotation angle: %d", degrees);
384        return BAD_VALUE;
385    }
386    mRotationDegrees = degrees % 360;
387    return OK;
388}
389
390status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
391    LOGV("setParamMaxFileDurationUs: %lld us", timeUs);
392
393    // This is meant for backward compatibility for MediaRecorder.java
394    if (timeUs <= 0) {
395        LOGW("Max file duration is not positive: %lld us. Disabling duration limit.", timeUs);
396        timeUs = 0; // Disable the duration limit for zero or negative values.
397    } else if (timeUs <= 100000LL) {  // XXX: 100 milli-seconds
398        LOGE("Max file duration is too short: %lld us", timeUs);
399        return BAD_VALUE;
400    }
401
402    if (timeUs <= 15 * 1000000LL) {
403        LOGW("Target duration (%lld us) too short to be respected", timeUs);
404    }
405    mMaxFileDurationUs = timeUs;
406    return OK;
407}
408
409status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
410    LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
411
412    // This is meant for backward compatibility for MediaRecorder.java
413    if (bytes <= 0) {
414        LOGW("Max file size is not positive: %lld bytes. "
415             "Disabling file size limit.", bytes);
416        bytes = 0; // Disable the file size limit for zero or negative values.
417    } else if (bytes <= 1024) {  // XXX: 1 kB
418        LOGE("Max file size is too small: %lld bytes", bytes);
419        return BAD_VALUE;
420    }
421
422    if (bytes <= 100 * 1024) {
423        LOGW("Target file size (%lld bytes) is too small to be respected", bytes);
424    }
425
426    mMaxFileSizeBytes = bytes;
427    return OK;
428}
429
430status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
431    LOGV("setParamInterleaveDuration: %d", durationUs);
432    if (durationUs <= 500000) {           //  500 ms
433        // If interleave duration is too small, it is very inefficient to do
434        // interleaving since the metadata overhead will count for a significant
435        // portion of the saved contents
436        LOGE("Audio/video interleave duration is too small: %d us", durationUs);
437        return BAD_VALUE;
438    } else if (durationUs >= 10000000) {  // 10 seconds
439        // If interleaving duration is too large, it can cause the recording
440        // session to use too much memory since we have to save the output
441        // data before we write them out
442        LOGE("Audio/video interleave duration is too large: %d us", durationUs);
443        return BAD_VALUE;
444    }
445    mInterleaveDurationUs = durationUs;
446    return OK;
447}
448
449// If seconds <  0, only the first frame is I frame, and rest are all P frames
450// If seconds == 0, all frames are encoded as I frames. No P frames
451// If seconds >  0, it is the time spacing (seconds) between 2 neighboring I frames
452status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) {
453    LOGV("setParamVideoIFramesInterval: %d seconds", seconds);
454    mIFramesIntervalSec = seconds;
455    return OK;
456}
457
458status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
459    LOGV("setParam64BitFileOffset: %s",
460        use64Bit? "use 64 bit file offset": "use 32 bit file offset");
461    mUse64BitFileOffset = use64Bit;
462    return OK;
463}
464
465status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
466    LOGV("setParamVideoCameraId: %d", cameraId);
467    if (cameraId < 0) {
468        return BAD_VALUE;
469    }
470    mCameraId = cameraId;
471    return OK;
472}
473
474status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
475    LOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
476    if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
477        LOGE("Tracking time duration too short: %lld us", timeDurationUs);
478        return BAD_VALUE;
479    }
480    mTrackEveryTimeDurationUs = timeDurationUs;
481    return OK;
482}
483
484status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) {
485    LOGV("setParamVideoEncoderProfile: %d", profile);
486
487    // Additional check will be done later when we load the encoder.
488    // For now, we are accepting values defined in OpenMAX IL.
489    mVideoEncoderProfile = profile;
490    return OK;
491}
492
493status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) {
494    LOGV("setParamVideoEncoderLevel: %d", level);
495
496    // Additional check will be done later when we load the encoder.
497    // For now, we are accepting values defined in OpenMAX IL.
498    mVideoEncoderLevel = level;
499    return OK;
500}
501
502status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) {
503    LOGV("setParamMovieTimeScale: %d", timeScale);
504
505    // The range is set to be the same as the audio's time scale range
506    // since audio's time scale has a wider range.
507    if (timeScale < 600 || timeScale > 96000) {
508        LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
509        return BAD_VALUE;
510    }
511    mMovieTimeScale = timeScale;
512    return OK;
513}
514
515status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) {
516    LOGV("setParamVideoTimeScale: %d", timeScale);
517
518    // 60000 is chosen to make sure that each video frame from a 60-fps
519    // video has 1000 ticks.
520    if (timeScale < 600 || timeScale > 60000) {
521        LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
522        return BAD_VALUE;
523    }
524    mVideoTimeScale = timeScale;
525    return OK;
526}
527
528status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) {
529    LOGV("setParamAudioTimeScale: %d", timeScale);
530
531    // 96000 Hz is the highest sampling rate support in AAC.
532    if (timeScale < 600 || timeScale > 96000) {
533        LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
534        return BAD_VALUE;
535    }
536    mAudioTimeScale = timeScale;
537    return OK;
538}
539
540status_t StagefrightRecorder::setParamTimeLapseEnable(int32_t timeLapseEnable) {
541    LOGV("setParamTimeLapseEnable: %d", timeLapseEnable);
542
543    if(timeLapseEnable == 0) {
544        mCaptureTimeLapse = false;
545    } else if (timeLapseEnable == 1) {
546        mCaptureTimeLapse = true;
547    } else {
548        return BAD_VALUE;
549    }
550    return OK;
551}
552
553status_t StagefrightRecorder::setParamTimeBetweenTimeLapseFrameCapture(int64_t timeUs) {
554    LOGV("setParamTimeBetweenTimeLapseFrameCapture: %lld us", timeUs);
555
556    // Not allowing time more than a day
557    if (timeUs <= 0 || timeUs > 86400*1E6) {
558        LOGE("Time between time lapse frame capture (%lld) is out of range [0, 1 Day]", timeUs);
559        return BAD_VALUE;
560    }
561
562    mTimeBetweenTimeLapseFrameCaptureUs = timeUs;
563    return OK;
564}
565
566status_t StagefrightRecorder::setParamAuxVideoWidth(int32_t width) {
567    LOGV("setParamAuxVideoWidth : %d", width);
568
569    if (width <= 0) {
570        LOGE("Width (%d) is not positive", width);
571        return BAD_VALUE;
572    }
573
574    mAuxVideoWidth = width;
575    return OK;
576}
577
578status_t StagefrightRecorder::setParamAuxVideoHeight(int32_t height) {
579    LOGV("setParamAuxVideoHeight : %d", height);
580
581    if (height <= 0) {
582        LOGE("Height (%d) is not positive", height);
583        return BAD_VALUE;
584    }
585
586    mAuxVideoHeight = height;
587    return OK;
588}
589
590status_t StagefrightRecorder::setParamAuxVideoEncodingBitRate(int32_t bitRate) {
591    LOGV("StagefrightRecorder::setParamAuxVideoEncodingBitRate: %d", bitRate);
592
593    if (bitRate <= 0) {
594        LOGE("Invalid video encoding bit rate: %d", bitRate);
595        return BAD_VALUE;
596    }
597
598    mAuxVideoBitRate = bitRate;
599    return OK;
600}
601
602status_t StagefrightRecorder::setParamGeoDataLongitude(
603    int32_t longitudex10000) {
604
605    if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
606        return BAD_VALUE;
607    }
608    mLongitudex10000 = longitudex10000;
609    return OK;
610}
611
612status_t StagefrightRecorder::setParamGeoDataLatitude(
613    int32_t latitudex10000) {
614
615    if (latitudex10000 > 900000 || latitudex10000 < -900000) {
616        return BAD_VALUE;
617    }
618    mLatitudex10000 = latitudex10000;
619    return OK;
620}
621
622status_t StagefrightRecorder::setParameter(
623        const String8 &key, const String8 &value) {
624    LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
625    if (key == "max-duration") {
626        int64_t max_duration_ms;
627        if (safe_strtoi64(value.string(), &max_duration_ms)) {
628            return setParamMaxFileDurationUs(1000LL * max_duration_ms);
629        }
630    } else if (key == "max-filesize") {
631        int64_t max_filesize_bytes;
632        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
633            return setParamMaxFileSizeBytes(max_filesize_bytes);
634        }
635    } else if (key == "interleave-duration-us") {
636        int32_t durationUs;
637        if (safe_strtoi32(value.string(), &durationUs)) {
638            return setParamInterleaveDuration(durationUs);
639        }
640    } else if (key == "param-movie-time-scale") {
641        int32_t timeScale;
642        if (safe_strtoi32(value.string(), &timeScale)) {
643            return setParamMovieTimeScale(timeScale);
644        }
645    } else if (key == "param-use-64bit-offset") {
646        int32_t use64BitOffset;
647        if (safe_strtoi32(value.string(), &use64BitOffset)) {
648            return setParam64BitFileOffset(use64BitOffset != 0);
649        }
650    } else if (key == "param-geotag-longitude") {
651        int32_t longitudex10000;
652        if (safe_strtoi32(value.string(), &longitudex10000)) {
653            return setParamGeoDataLongitude(longitudex10000);
654        }
655    } else if (key == "param-geotag-latitude") {
656        int32_t latitudex10000;
657        if (safe_strtoi32(value.string(), &latitudex10000)) {
658            return setParamGeoDataLatitude(latitudex10000);
659        }
660    } else if (key == "param-track-time-status") {
661        int64_t timeDurationUs;
662        if (safe_strtoi64(value.string(), &timeDurationUs)) {
663            return setParamTrackTimeStatus(timeDurationUs);
664        }
665    } else if (key == "audio-param-sampling-rate") {
666        int32_t sampling_rate;
667        if (safe_strtoi32(value.string(), &sampling_rate)) {
668            return setParamAudioSamplingRate(sampling_rate);
669        }
670    } else if (key == "audio-param-number-of-channels") {
671        int32_t number_of_channels;
672        if (safe_strtoi32(value.string(), &number_of_channels)) {
673            return setParamAudioNumberOfChannels(number_of_channels);
674        }
675    } else if (key == "audio-param-encoding-bitrate") {
676        int32_t audio_bitrate;
677        if (safe_strtoi32(value.string(), &audio_bitrate)) {
678            return setParamAudioEncodingBitRate(audio_bitrate);
679        }
680    } else if (key == "audio-param-time-scale") {
681        int32_t timeScale;
682        if (safe_strtoi32(value.string(), &timeScale)) {
683            return setParamAudioTimeScale(timeScale);
684        }
685    } else if (key == "video-param-encoding-bitrate") {
686        int32_t video_bitrate;
687        if (safe_strtoi32(value.string(), &video_bitrate)) {
688            return setParamVideoEncodingBitRate(video_bitrate);
689        }
690    } else if (key == "video-param-rotation-angle-degrees") {
691        int32_t degrees;
692        if (safe_strtoi32(value.string(), &degrees)) {
693            return setParamVideoRotation(degrees);
694        }
695    } else if (key == "video-param-i-frames-interval") {
696        int32_t seconds;
697        if (safe_strtoi32(value.string(), &seconds)) {
698            return setParamVideoIFramesInterval(seconds);
699        }
700    } else if (key == "video-param-encoder-profile") {
701        int32_t profile;
702        if (safe_strtoi32(value.string(), &profile)) {
703            return setParamVideoEncoderProfile(profile);
704        }
705    } else if (key == "video-param-encoder-level") {
706        int32_t level;
707        if (safe_strtoi32(value.string(), &level)) {
708            return setParamVideoEncoderLevel(level);
709        }
710    } else if (key == "video-param-camera-id") {
711        int32_t cameraId;
712        if (safe_strtoi32(value.string(), &cameraId)) {
713            return setParamVideoCameraId(cameraId);
714        }
715    } else if (key == "video-param-time-scale") {
716        int32_t timeScale;
717        if (safe_strtoi32(value.string(), &timeScale)) {
718            return setParamVideoTimeScale(timeScale);
719        }
720    } else if (key == "time-lapse-enable") {
721        int32_t timeLapseEnable;
722        if (safe_strtoi32(value.string(), &timeLapseEnable)) {
723            return setParamTimeLapseEnable(timeLapseEnable);
724        }
725    } else if (key == "time-between-time-lapse-frame-capture") {
726        int64_t timeBetweenTimeLapseFrameCaptureMs;
727        if (safe_strtoi64(value.string(), &timeBetweenTimeLapseFrameCaptureMs)) {
728            return setParamTimeBetweenTimeLapseFrameCapture(
729                    1000LL * timeBetweenTimeLapseFrameCaptureMs);
730        }
731    } else if (key == "video-aux-param-width") {
732        int32_t auxWidth;
733        if (safe_strtoi32(value.string(), &auxWidth)) {
734            return setParamAuxVideoWidth(auxWidth);
735        }
736    } else if (key == "video-aux-param-height") {
737        int32_t auxHeight;
738        if (safe_strtoi32(value.string(), &auxHeight)) {
739            return setParamAuxVideoHeight(auxHeight);
740        }
741    } else if (key == "video-aux-param-encoding-bitrate") {
742        int32_t auxVideoBitRate;
743        if (safe_strtoi32(value.string(), &auxVideoBitRate)) {
744            return setParamAuxVideoEncodingBitRate(auxVideoBitRate);
745        }
746    } else {
747        LOGE("setParameter: failed to find key %s", key.string());
748    }
749    return BAD_VALUE;
750}
751
752status_t StagefrightRecorder::setParameters(const String8 &params) {
753    LOGV("setParameters: %s", params.string());
754    const char *cparams = params.string();
755    const char *key_start = cparams;
756    for (;;) {
757        const char *equal_pos = strchr(key_start, '=');
758        if (equal_pos == NULL) {
759            LOGE("Parameters %s miss a value", cparams);
760            return BAD_VALUE;
761        }
762        String8 key(key_start, equal_pos - key_start);
763        TrimString(&key);
764        if (key.length() == 0) {
765            LOGE("Parameters %s contains an empty key", cparams);
766            return BAD_VALUE;
767        }
768        const char *value_start = equal_pos + 1;
769        const char *semicolon_pos = strchr(value_start, ';');
770        String8 value;
771        if (semicolon_pos == NULL) {
772            value.setTo(value_start);
773        } else {
774            value.setTo(value_start, semicolon_pos - value_start);
775        }
776        if (setParameter(key, value) != OK) {
777            return BAD_VALUE;
778        }
779        if (semicolon_pos == NULL) {
780            break;  // Reaches the end
781        }
782        key_start = semicolon_pos + 1;
783    }
784    return OK;
785}
786
787status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
788    mListener = listener;
789
790    return OK;
791}
792
793status_t StagefrightRecorder::prepare() {
794    return OK;
795}
796
797status_t StagefrightRecorder::start() {
798    CHECK(mOutputFd >= 0);
799
800    if (mWriter != NULL) {
801        LOGE("File writer is not avaialble");
802        return UNKNOWN_ERROR;
803    }
804
805    status_t status = OK;
806
807    switch (mOutputFormat) {
808        case OUTPUT_FORMAT_DEFAULT:
809        case OUTPUT_FORMAT_THREE_GPP:
810        case OUTPUT_FORMAT_MPEG_4:
811            status = startMPEG4Recording();
812            break;
813
814        case OUTPUT_FORMAT_AMR_NB:
815        case OUTPUT_FORMAT_AMR_WB:
816            status = startAMRRecording();
817            break;
818
819        case OUTPUT_FORMAT_AAC_ADIF:
820        case OUTPUT_FORMAT_AAC_ADTS:
821            status = startAACRecording();
822            break;
823
824        case OUTPUT_FORMAT_RTP_AVP:
825            status = startRTPRecording();
826            break;
827
828        case OUTPUT_FORMAT_MPEG2TS:
829            status = startMPEG2TSRecording();
830            break;
831
832        default:
833            LOGE("Unsupported output file format: %d", mOutputFormat);
834            status = UNKNOWN_ERROR;
835            break;
836    }
837
838    if ((status == OK) && (!mStarted)) {
839        mStarted = true;
840
841        uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted;
842        if (mAudioSource != AUDIO_SOURCE_CNT) {
843            params |= IMediaPlayerService::kBatteryDataTrackAudio;
844        }
845        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
846            params |= IMediaPlayerService::kBatteryDataTrackVideo;
847        }
848
849        addBatteryData(params);
850    }
851
852    return status;
853}
854
855sp<MediaSource> StagefrightRecorder::createAudioSource() {
856    sp<AudioSource> audioSource =
857        new AudioSource(
858                mAudioSource,
859                mSampleRate,
860                mAudioChannels);
861
862    status_t err = audioSource->initCheck();
863
864    if (err != OK) {
865        LOGE("audio source is not initialized");
866        return NULL;
867    }
868
869    sp<MetaData> encMeta = new MetaData;
870    const char *mime;
871    switch (mAudioEncoder) {
872        case AUDIO_ENCODER_AMR_NB:
873        case AUDIO_ENCODER_DEFAULT:
874            mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
875            break;
876        case AUDIO_ENCODER_AMR_WB:
877            mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
878            break;
879        case AUDIO_ENCODER_AAC:
880            mime = MEDIA_MIMETYPE_AUDIO_AAC;
881            break;
882        default:
883            LOGE("Unknown audio encoder: %d", mAudioEncoder);
884            return NULL;
885    }
886    encMeta->setCString(kKeyMIMEType, mime);
887
888    int32_t maxInputSize;
889    CHECK(audioSource->getFormat()->findInt32(
890                kKeyMaxInputSize, &maxInputSize));
891
892    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
893    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
894    encMeta->setInt32(kKeySampleRate, mSampleRate);
895    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
896    if (mAudioTimeScale > 0) {
897        encMeta->setInt32(kKeyTimeScale, mAudioTimeScale);
898    }
899
900    OMXClient client;
901    CHECK_EQ(client.connect(), OK);
902
903    sp<MediaSource> audioEncoder =
904        OMXCodec::Create(client.interface(), encMeta,
905                         true /* createEncoder */, audioSource);
906    mAudioSourceNode = audioSource;
907
908    return audioEncoder;
909}
910
911status_t StagefrightRecorder::startAACRecording() {
912    // FIXME:
913    // Add support for OUTPUT_FORMAT_AAC_ADIF
914    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
915
916    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
917    CHECK(mAudioSource != AUDIO_SOURCE_CNT);
918
919    mWriter = new AACWriter(mOutputFd);
920    status_t status = startRawAudioRecording();
921    if (status != OK) {
922        mWriter.clear();
923        mWriter = NULL;
924    }
925
926    return status;
927}
928
929status_t StagefrightRecorder::startAMRRecording() {
930    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
931          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
932
933    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
934        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
935            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
936            LOGE("Invalid encoder %d used for AMRNB recording",
937                    mAudioEncoder);
938            return BAD_VALUE;
939        }
940    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
941        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
942            LOGE("Invlaid encoder %d used for AMRWB recording",
943                    mAudioEncoder);
944            return BAD_VALUE;
945        }
946    }
947
948    mWriter = new AMRWriter(mOutputFd);
949    status_t status = startRawAudioRecording();
950    if (status != OK) {
951        mWriter.clear();
952        mWriter = NULL;
953    }
954    return status;
955}
956
957status_t StagefrightRecorder::startRawAudioRecording() {
958    if (mAudioSource >= AUDIO_SOURCE_CNT) {
959        LOGE("Invalid audio source: %d", mAudioSource);
960        return BAD_VALUE;
961    }
962
963    status_t status = BAD_VALUE;
964    if (OK != (status = checkAudioEncoderCapabilities())) {
965        return status;
966    }
967
968    sp<MediaSource> audioEncoder = createAudioSource();
969    if (audioEncoder == NULL) {
970        return UNKNOWN_ERROR;
971    }
972
973    CHECK(mWriter != 0);
974    mWriter->addSource(audioEncoder);
975
976    if (mMaxFileDurationUs != 0) {
977        mWriter->setMaxFileDuration(mMaxFileDurationUs);
978    }
979    if (mMaxFileSizeBytes != 0) {
980        mWriter->setMaxFileSize(mMaxFileSizeBytes);
981    }
982    mWriter->setListener(mListener);
983    mWriter->start();
984
985    return OK;
986}
987
988status_t StagefrightRecorder::startRTPRecording() {
989    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
990
991    if ((mAudioSource != AUDIO_SOURCE_CNT
992                && mVideoSource != VIDEO_SOURCE_LIST_END)
993            || (mAudioSource == AUDIO_SOURCE_CNT
994                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
995        // Must have exactly one source.
996        return BAD_VALUE;
997    }
998
999    if (mOutputFd < 0) {
1000        return BAD_VALUE;
1001    }
1002
1003    sp<MediaSource> source;
1004
1005    if (mAudioSource != AUDIO_SOURCE_CNT) {
1006        source = createAudioSource();
1007    } else {
1008
1009        sp<CameraSource> cameraSource;
1010        status_t err = setupCameraSource(&cameraSource);
1011        if (err != OK) {
1012            return err;
1013        }
1014
1015        err = setupVideoEncoder(cameraSource, mVideoBitRate, &source);
1016        if (err != OK) {
1017            return err;
1018        }
1019    }
1020
1021    mWriter = new ARTPWriter(mOutputFd);
1022    mWriter->addSource(source);
1023    mWriter->setListener(mListener);
1024
1025    return mWriter->start();
1026}
1027
1028status_t StagefrightRecorder::startMPEG2TSRecording() {
1029    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
1030
1031    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
1032
1033    if (mAudioSource != AUDIO_SOURCE_CNT) {
1034        if (mAudioEncoder != AUDIO_ENCODER_AAC) {
1035            return ERROR_UNSUPPORTED;
1036        }
1037
1038        status_t err = setupAudioEncoder(writer);
1039
1040        if (err != OK) {
1041            return err;
1042        }
1043    }
1044
1045    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1046            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1047        if (mVideoEncoder != VIDEO_ENCODER_H264) {
1048            return ERROR_UNSUPPORTED;
1049        }
1050
1051        sp<CameraSource> cameraSource;
1052        status_t err = setupCameraSource(&cameraSource);
1053        if (err != OK) {
1054            return err;
1055        }
1056
1057        sp<MediaSource> encoder;
1058        err = setupVideoEncoder(cameraSource, mVideoBitRate, &encoder);
1059
1060        if (err != OK) {
1061            return err;
1062        }
1063
1064        writer->addSource(encoder);
1065    }
1066
1067    if (mMaxFileDurationUs != 0) {
1068        writer->setMaxFileDuration(mMaxFileDurationUs);
1069    }
1070
1071    if (mMaxFileSizeBytes != 0) {
1072        writer->setMaxFileSize(mMaxFileSizeBytes);
1073    }
1074
1075    mWriter = writer;
1076
1077    return mWriter->start();
1078}
1079
1080void StagefrightRecorder::clipVideoFrameRate() {
1081    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1082    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1083                        "enc.vid.fps.min", mVideoEncoder);
1084    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1085                        "enc.vid.fps.max", mVideoEncoder);
1086    if (mFrameRate < minFrameRate && mFrameRate != -1) {
1087        LOGW("Intended video encoding frame rate (%d fps) is too small"
1088             " and will be set to (%d fps)", mFrameRate, minFrameRate);
1089        mFrameRate = minFrameRate;
1090    } else if (mFrameRate > maxFrameRate) {
1091        LOGW("Intended video encoding frame rate (%d fps) is too large"
1092             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1093        mFrameRate = maxFrameRate;
1094    }
1095}
1096
1097void StagefrightRecorder::clipVideoBitRate() {
1098    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1099    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1100                        "enc.vid.bps.min", mVideoEncoder);
1101    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1102                        "enc.vid.bps.max", mVideoEncoder);
1103    if (mVideoBitRate < minBitRate) {
1104        LOGW("Intended video encoding bit rate (%d bps) is too small"
1105             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1106        mVideoBitRate = minBitRate;
1107    } else if (mVideoBitRate > maxBitRate) {
1108        LOGW("Intended video encoding bit rate (%d bps) is too large"
1109             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1110        mVideoBitRate = maxBitRate;
1111    }
1112}
1113
1114void StagefrightRecorder::clipVideoFrameWidth() {
1115    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1116    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1117                        "enc.vid.width.min", mVideoEncoder);
1118    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1119                        "enc.vid.width.max", mVideoEncoder);
1120    if (mVideoWidth < minFrameWidth) {
1121        LOGW("Intended video encoding frame width (%d) is too small"
1122             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1123        mVideoWidth = minFrameWidth;
1124    } else if (mVideoWidth > maxFrameWidth) {
1125        LOGW("Intended video encoding frame width (%d) is too large"
1126             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1127        mVideoWidth = maxFrameWidth;
1128    }
1129}
1130
1131status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1132    if (!mCaptureTimeLapse) {
1133        // Dont clip for time lapse capture as encoder will have enough
1134        // time to encode because of slow capture rate of time lapse.
1135        clipVideoBitRate();
1136        clipVideoFrameRate();
1137        clipVideoFrameWidth();
1138        clipVideoFrameHeight();
1139    }
1140    return OK;
1141}
1142
1143status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1144    clipAudioBitRate();
1145    clipAudioSampleRate();
1146    clipNumberOfAudioChannels();
1147    return OK;
1148}
1149
1150void StagefrightRecorder::clipAudioBitRate() {
1151    LOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1152
1153    int minAudioBitRate =
1154            mEncoderProfiles->getAudioEncoderParamByName(
1155                "enc.aud.bps.min", mAudioEncoder);
1156    if (mAudioBitRate < minAudioBitRate) {
1157        LOGW("Intended audio encoding bit rate (%d) is too small"
1158            " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1159        mAudioBitRate = minAudioBitRate;
1160    }
1161
1162    int maxAudioBitRate =
1163            mEncoderProfiles->getAudioEncoderParamByName(
1164                "enc.aud.bps.max", mAudioEncoder);
1165    if (mAudioBitRate > maxAudioBitRate) {
1166        LOGW("Intended audio encoding bit rate (%d) is too large"
1167            " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1168        mAudioBitRate = maxAudioBitRate;
1169    }
1170}
1171
1172void StagefrightRecorder::clipAudioSampleRate() {
1173    LOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1174
1175    int minSampleRate =
1176            mEncoderProfiles->getAudioEncoderParamByName(
1177                "enc.aud.hz.min", mAudioEncoder);
1178    if (mSampleRate < minSampleRate) {
1179        LOGW("Intended audio sample rate (%d) is too small"
1180            " and will be set to (%d)", mSampleRate, minSampleRate);
1181        mSampleRate = minSampleRate;
1182    }
1183
1184    int maxSampleRate =
1185            mEncoderProfiles->getAudioEncoderParamByName(
1186                "enc.aud.hz.max", mAudioEncoder);
1187    if (mSampleRate > maxSampleRate) {
1188        LOGW("Intended audio sample rate (%d) is too large"
1189            " and will be set to (%d)", mSampleRate, maxSampleRate);
1190        mSampleRate = maxSampleRate;
1191    }
1192}
1193
1194void StagefrightRecorder::clipNumberOfAudioChannels() {
1195    LOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1196
1197    int minChannels =
1198            mEncoderProfiles->getAudioEncoderParamByName(
1199                "enc.aud.ch.min", mAudioEncoder);
1200    if (mAudioChannels < minChannels) {
1201        LOGW("Intended number of audio channels (%d) is too small"
1202            " and will be set to (%d)", mAudioChannels, minChannels);
1203        mAudioChannels = minChannels;
1204    }
1205
1206    int maxChannels =
1207            mEncoderProfiles->getAudioEncoderParamByName(
1208                "enc.aud.ch.max", mAudioEncoder);
1209    if (mAudioChannels > maxChannels) {
1210        LOGW("Intended number of audio channels (%d) is too large"
1211            " and will be set to (%d)", mAudioChannels, maxChannels);
1212        mAudioChannels = maxChannels;
1213    }
1214}
1215
1216void StagefrightRecorder::clipVideoFrameHeight() {
1217    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1218    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1219                        "enc.vid.height.min", mVideoEncoder);
1220    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1221                        "enc.vid.height.max", mVideoEncoder);
1222    if (mVideoHeight < minFrameHeight) {
1223        LOGW("Intended video encoding frame height (%d) is too small"
1224             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1225        mVideoHeight = minFrameHeight;
1226    } else if (mVideoHeight > maxFrameHeight) {
1227        LOGW("Intended video encoding frame height (%d) is too large"
1228             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1229        mVideoHeight = maxFrameHeight;
1230    }
1231}
1232
1233status_t StagefrightRecorder::setupCameraSource(
1234        sp<CameraSource> *cameraSource) {
1235    status_t err = OK;
1236    if ((err = checkVideoEncoderCapabilities()) != OK) {
1237        return err;
1238    }
1239    Size videoSize;
1240    videoSize.width = mVideoWidth;
1241    videoSize.height = mVideoHeight;
1242    if (mCaptureTimeLapse) {
1243        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1244                mCamera, mCameraProxy, mCameraId,
1245                videoSize, mFrameRate, mPreviewSurface,
1246                mTimeBetweenTimeLapseFrameCaptureUs);
1247        *cameraSource = mCameraSourceTimeLapse;
1248    } else {
1249        *cameraSource = CameraSource::CreateFromCamera(
1250                mCamera, mCameraProxy, mCameraId, videoSize, mFrameRate,
1251                mPreviewSurface, true /*storeMetaDataInVideoBuffers*/);
1252    }
1253    mCamera.clear();
1254    mCameraProxy.clear();
1255    if (*cameraSource == NULL) {
1256        return UNKNOWN_ERROR;
1257    }
1258
1259    if ((*cameraSource)->initCheck() != OK) {
1260        (*cameraSource).clear();
1261        *cameraSource = NULL;
1262        return NO_INIT;
1263    }
1264
1265    // When frame rate is not set, the actual frame rate will be set to
1266    // the current frame rate being used.
1267    if (mFrameRate == -1) {
1268        int32_t frameRate = 0;
1269        CHECK ((*cameraSource)->getFormat()->findInt32(
1270                    kKeyFrameRate, &frameRate));
1271        LOGI("Frame rate is not explicitly set. Use the current frame "
1272             "rate (%d fps)", frameRate);
1273        mFrameRate = frameRate;
1274    }
1275
1276    CHECK(mFrameRate != -1);
1277
1278    mIsMetaDataStoredInVideoBuffers =
1279        (*cameraSource)->isMetaDataStoredInVideoBuffers();
1280
1281    return OK;
1282}
1283
1284status_t StagefrightRecorder::setupVideoEncoder(
1285        sp<MediaSource> cameraSource,
1286        int32_t videoBitRate,
1287        sp<MediaSource> *source) {
1288    source->clear();
1289
1290    sp<MetaData> enc_meta = new MetaData;
1291    enc_meta->setInt32(kKeyBitRate, videoBitRate);
1292    enc_meta->setInt32(kKeyFrameRate, mFrameRate);
1293
1294    switch (mVideoEncoder) {
1295        case VIDEO_ENCODER_H263:
1296            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
1297            break;
1298
1299        case VIDEO_ENCODER_MPEG_4_SP:
1300            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
1301            break;
1302
1303        case VIDEO_ENCODER_H264:
1304            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
1305            break;
1306
1307        default:
1308            CHECK(!"Should not be here, unsupported video encoding.");
1309            break;
1310    }
1311
1312    sp<MetaData> meta = cameraSource->getFormat();
1313
1314    int32_t width, height, stride, sliceHeight, colorFormat;
1315    CHECK(meta->findInt32(kKeyWidth, &width));
1316    CHECK(meta->findInt32(kKeyHeight, &height));
1317    CHECK(meta->findInt32(kKeyStride, &stride));
1318    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1319    CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1320
1321    enc_meta->setInt32(kKeyWidth, width);
1322    enc_meta->setInt32(kKeyHeight, height);
1323    enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
1324    enc_meta->setInt32(kKeyStride, stride);
1325    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
1326    enc_meta->setInt32(kKeyColorFormat, colorFormat);
1327    if (mVideoTimeScale > 0) {
1328        enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
1329    }
1330    if (mVideoEncoderProfile != -1) {
1331        enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
1332    }
1333    if (mVideoEncoderLevel != -1) {
1334        enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
1335    }
1336
1337    OMXClient client;
1338    CHECK_EQ(client.connect(), OK);
1339
1340    uint32_t encoder_flags = 0;
1341    if (mIsMetaDataStoredInVideoBuffers) {
1342        encoder_flags |= OMXCodec::kHardwareCodecsOnly;
1343        encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers;
1344    }
1345
1346    // Do not wait for all the input buffers to become available.
1347    // This give timelapse video recording faster response in
1348    // receiving output from video encoder component.
1349    if (mCaptureTimeLapse) {
1350        encoder_flags |= OMXCodec::kOnlySubmitOneInputBufferAtOneTime;
1351    }
1352
1353    sp<MediaSource> encoder = OMXCodec::Create(
1354            client.interface(), enc_meta,
1355            true /* createEncoder */, cameraSource,
1356            NULL, encoder_flags);
1357    if (encoder == NULL) {
1358        LOGW("Failed to create the encoder");
1359        // When the encoder fails to be created, we need
1360        // release the camera source due to the camera's lock
1361        // and unlock mechanism.
1362        cameraSource->stop();
1363        return UNKNOWN_ERROR;
1364    }
1365
1366    *source = encoder;
1367
1368    return OK;
1369}
1370
1371status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1372    status_t status = BAD_VALUE;
1373    if (OK != (status = checkAudioEncoderCapabilities())) {
1374        return status;
1375    }
1376
1377    switch(mAudioEncoder) {
1378        case AUDIO_ENCODER_AMR_NB:
1379        case AUDIO_ENCODER_AMR_WB:
1380        case AUDIO_ENCODER_AAC:
1381            break;
1382
1383        default:
1384            LOGE("Unsupported audio encoder: %d", mAudioEncoder);
1385            return UNKNOWN_ERROR;
1386    }
1387
1388    sp<MediaSource> audioEncoder = createAudioSource();
1389    if (audioEncoder == NULL) {
1390        return UNKNOWN_ERROR;
1391    }
1392
1393    writer->addSource(audioEncoder);
1394    return OK;
1395}
1396
1397status_t StagefrightRecorder::setupMPEG4Recording(
1398        bool useSplitCameraSource,
1399        int outputFd,
1400        int32_t videoWidth, int32_t videoHeight,
1401        int32_t videoBitRate,
1402        int32_t *totalBitRate,
1403        sp<MediaWriter> *mediaWriter) {
1404    mediaWriter->clear();
1405    *totalBitRate = 0;
1406    status_t err = OK;
1407    sp<MediaWriter> writer = new MPEG4Writer(outputFd);
1408
1409    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1410            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1411
1412        sp<MediaSource> cameraMediaSource;
1413        if (useSplitCameraSource) {
1414            LOGV("Using Split camera source");
1415            cameraMediaSource = mCameraSourceSplitter->createClient();
1416        } else {
1417            sp<CameraSource> cameraSource;
1418            err = setupCameraSource(&cameraSource);
1419            cameraMediaSource = cameraSource;
1420        }
1421        if ((videoWidth != mVideoWidth) || (videoHeight != mVideoHeight)) {
1422            // Use downsampling from the original source.
1423            cameraMediaSource =
1424                new VideoSourceDownSampler(cameraMediaSource, videoWidth, videoHeight);
1425        }
1426        if (err != OK) {
1427            return err;
1428        }
1429
1430        sp<MediaSource> encoder;
1431        err = setupVideoEncoder(cameraMediaSource, videoBitRate, &encoder);
1432        if (err != OK) {
1433            return err;
1434        }
1435
1436        writer->addSource(encoder);
1437        *totalBitRate += videoBitRate;
1438    }
1439
1440    // Audio source is added at the end if it exists.
1441    // This help make sure that the "recoding" sound is suppressed for
1442    // camcorder applications in the recorded files.
1443    if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_CNT)) {
1444        err = setupAudioEncoder(writer);
1445        if (err != OK) return err;
1446        *totalBitRate += mAudioBitRate;
1447    }
1448
1449    if (mInterleaveDurationUs > 0) {
1450        reinterpret_cast<MPEG4Writer *>(writer.get())->
1451            setInterleaveDuration(mInterleaveDurationUs);
1452    }
1453    if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1454        reinterpret_cast<MPEG4Writer *>(writer.get())->
1455            setGeoData(mLatitudex10000, mLongitudex10000);
1456    }
1457    if (mMaxFileDurationUs != 0) {
1458        writer->setMaxFileDuration(mMaxFileDurationUs);
1459    }
1460    if (mMaxFileSizeBytes != 0) {
1461        writer->setMaxFileSize(mMaxFileSizeBytes);
1462    }
1463
1464    mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1465    if (mStartTimeOffsetMs > 0) {
1466        reinterpret_cast<MPEG4Writer *>(writer.get())->
1467            setStartTimeOffsetMs(mStartTimeOffsetMs);
1468    }
1469
1470    writer->setListener(mListener);
1471    *mediaWriter = writer;
1472    return OK;
1473}
1474
1475void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate,
1476        sp<MetaData> *meta) {
1477    (*meta)->setInt64(kKeyTime, startTimeUs);
1478    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1479    (*meta)->setInt32(kKeyBitRate, totalBitRate);
1480    (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1481    if (mMovieTimeScale > 0) {
1482        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1483    }
1484    if (mTrackEveryTimeDurationUs > 0) {
1485        (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1486    }
1487    if (mRotationDegrees != 0) {
1488        (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1489    }
1490}
1491
1492status_t StagefrightRecorder::startMPEG4Recording() {
1493    if (mCaptureAuxVideo) {
1494        if (!mCaptureTimeLapse) {
1495            LOGE("Auxiliary video can be captured only in time lapse mode");
1496            return UNKNOWN_ERROR;
1497        }
1498        LOGV("Creating MediaSourceSplitter");
1499        sp<CameraSource> cameraSource;
1500        status_t err = setupCameraSource(&cameraSource);
1501        if (err != OK) {
1502            return err;
1503        }
1504        mCameraSourceSplitter = new MediaSourceSplitter(cameraSource);
1505    } else {
1506        mCameraSourceSplitter = NULL;
1507    }
1508
1509    int32_t totalBitRate;
1510    status_t err = setupMPEG4Recording(mCaptureAuxVideo,
1511            mOutputFd, mVideoWidth, mVideoHeight,
1512            mVideoBitRate, &totalBitRate, &mWriter);
1513    if (err != OK) {
1514        return err;
1515    }
1516
1517    int64_t startTimeUs = systemTime() / 1000;
1518    sp<MetaData> meta = new MetaData;
1519    setupMPEG4MetaData(startTimeUs, totalBitRate, &meta);
1520
1521    err = mWriter->start(meta.get());
1522    if (err != OK) {
1523        return err;
1524    }
1525
1526    if (mCaptureAuxVideo) {
1527        CHECK(mOutputFdAux >= 0);
1528        if (mWriterAux != NULL) {
1529            LOGE("Auxiliary File writer is not avaialble");
1530            return UNKNOWN_ERROR;
1531        }
1532        if ((mAuxVideoWidth > mVideoWidth) || (mAuxVideoHeight > mVideoHeight) ||
1533                ((mAuxVideoWidth == mVideoWidth) && mAuxVideoHeight == mVideoHeight)) {
1534            LOGE("Auxiliary video size (%d x %d) same or larger than the main video size (%d x %d)",
1535                    mAuxVideoWidth, mAuxVideoHeight, mVideoWidth, mVideoHeight);
1536            return UNKNOWN_ERROR;
1537        }
1538
1539        int32_t totalBitrateAux;
1540        err = setupMPEG4Recording(mCaptureAuxVideo,
1541                mOutputFdAux, mAuxVideoWidth, mAuxVideoHeight,
1542                mAuxVideoBitRate, &totalBitrateAux, &mWriterAux);
1543        if (err != OK) {
1544            return err;
1545        }
1546
1547        sp<MetaData> metaAux = new MetaData;
1548        setupMPEG4MetaData(startTimeUs, totalBitrateAux, &metaAux);
1549
1550        return mWriterAux->start(metaAux.get());
1551    }
1552
1553    return OK;
1554}
1555
1556status_t StagefrightRecorder::pause() {
1557    LOGV("pause");
1558    if (mWriter == NULL) {
1559        return UNKNOWN_ERROR;
1560    }
1561    mWriter->pause();
1562
1563    if (mCaptureAuxVideo) {
1564        if (mWriterAux == NULL) {
1565            return UNKNOWN_ERROR;
1566        }
1567        mWriterAux->pause();
1568    }
1569
1570    if (mStarted) {
1571        mStarted = false;
1572
1573        uint32_t params = 0;
1574        if (mAudioSource != AUDIO_SOURCE_CNT) {
1575            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1576        }
1577        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1578            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1579        }
1580
1581        addBatteryData(params);
1582    }
1583
1584
1585    return OK;
1586}
1587
1588status_t StagefrightRecorder::stop() {
1589    LOGV("stop");
1590    status_t err = OK;
1591
1592    if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) {
1593        mCameraSourceTimeLapse->startQuickReadReturns();
1594        mCameraSourceTimeLapse = NULL;
1595    }
1596
1597    if (mCaptureAuxVideo) {
1598        if (mWriterAux != NULL) {
1599            mWriterAux->stop();
1600            mWriterAux.clear();
1601        }
1602    }
1603
1604    if (mWriter != NULL) {
1605        err = mWriter->stop();
1606        mWriter.clear();
1607    }
1608
1609    if (mOutputFd >= 0) {
1610        ::close(mOutputFd);
1611        mOutputFd = -1;
1612    }
1613
1614    if (mCaptureAuxVideo) {
1615        if (mOutputFdAux >= 0) {
1616            ::close(mOutputFdAux);
1617            mOutputFdAux = -1;
1618        }
1619    }
1620
1621    if (mStarted) {
1622        mStarted = false;
1623
1624        uint32_t params = 0;
1625        if (mAudioSource != AUDIO_SOURCE_CNT) {
1626            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1627        }
1628        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1629            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1630        }
1631
1632        addBatteryData(params);
1633    }
1634
1635
1636    return err;
1637}
1638
1639status_t StagefrightRecorder::close() {
1640    LOGV("close");
1641    stop();
1642
1643    return OK;
1644}
1645
1646status_t StagefrightRecorder::reset() {
1647    LOGV("reset");
1648    stop();
1649
1650    // No audio or video source by default
1651    mAudioSource = AUDIO_SOURCE_CNT;
1652    mVideoSource = VIDEO_SOURCE_LIST_END;
1653
1654    // Default parameters
1655    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1656    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1657    mVideoEncoder  = VIDEO_ENCODER_H263;
1658    mVideoWidth    = 176;
1659    mVideoHeight   = 144;
1660    mAuxVideoWidth    = 176;
1661    mAuxVideoHeight   = 144;
1662    mFrameRate     = -1;
1663    mVideoBitRate  = 192000;
1664    mAuxVideoBitRate = 192000;
1665    mSampleRate    = 8000;
1666    mAudioChannels = 1;
1667    mAudioBitRate  = 12200;
1668    mInterleaveDurationUs = 0;
1669    mIFramesIntervalSec = 1;
1670    mAudioSourceNode = 0;
1671    mUse64BitFileOffset = false;
1672    mMovieTimeScale  = -1;
1673    mAudioTimeScale  = -1;
1674    mVideoTimeScale  = -1;
1675    mCameraId        = 0;
1676    mStartTimeOffsetMs = -1;
1677    mVideoEncoderProfile = -1;
1678    mVideoEncoderLevel   = -1;
1679    mMaxFileDurationUs = 0;
1680    mMaxFileSizeBytes = 0;
1681    mTrackEveryTimeDurationUs = 0;
1682    mCaptureTimeLapse = false;
1683    mTimeBetweenTimeLapseFrameCaptureUs = -1;
1684    mCaptureAuxVideo = false;
1685    mCameraSourceSplitter = NULL;
1686    mCameraSourceTimeLapse = NULL;
1687    mIsMetaDataStoredInVideoBuffers = false;
1688    mEncoderProfiles = MediaProfiles::getInstance();
1689    mRotationDegrees = 0;
1690    mLatitudex10000 = -3600000;
1691    mLongitudex10000 = -3600000;
1692
1693    mOutputFd = -1;
1694    mOutputFdAux = -1;
1695
1696    return OK;
1697}
1698
1699status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1700    LOGV("getMaxAmplitude");
1701
1702    if (max == NULL) {
1703        LOGE("Null pointer argument");
1704        return BAD_VALUE;
1705    }
1706
1707    if (mAudioSourceNode != 0) {
1708        *max = mAudioSourceNode->getMaxAmplitude();
1709    } else {
1710        *max = 0;
1711    }
1712
1713    return OK;
1714}
1715
1716status_t StagefrightRecorder::dump(
1717        int fd, const Vector<String16>& args) const {
1718    LOGV("dump");
1719    const size_t SIZE = 256;
1720    char buffer[SIZE];
1721    String8 result;
1722    if (mWriter != 0) {
1723        mWriter->dump(fd, args);
1724    } else {
1725        snprintf(buffer, SIZE, "   No file writer\n");
1726        result.append(buffer);
1727    }
1728    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1729    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1730    result.append(buffer);
1731    snprintf(buffer, SIZE, "   Output file Auxiliary (fd %d):\n", mOutputFdAux);
1732    result.append(buffer);
1733    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1734    result.append(buffer);
1735    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1736    result.append(buffer);
1737    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
1738    result.append(buffer);
1739    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1740    result.append(buffer);
1741    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1742    result.append(buffer);
1743    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1744    result.append(buffer);
1745    snprintf(buffer, SIZE, "   Audio\n");
1746    result.append(buffer);
1747    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1748    result.append(buffer);
1749    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1750    result.append(buffer);
1751    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1752    result.append(buffer);
1753    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1754    result.append(buffer);
1755    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1756    result.append(buffer);
1757    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1758    result.append(buffer);
1759    snprintf(buffer, SIZE, "   Video\n");
1760    result.append(buffer);
1761    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1762    result.append(buffer);
1763    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1764    result.append(buffer);
1765    snprintf(buffer, SIZE, "     Start time offset (ms): %d\n", mStartTimeOffsetMs);
1766    result.append(buffer);
1767    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1768    result.append(buffer);
1769    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1770    result.append(buffer);
1771    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1772    result.append(buffer);
1773    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1774    result.append(buffer);
1775    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1776    result.append(buffer);
1777    snprintf(buffer, SIZE, "     Aux Frame size (pixels): %dx%d\n", mAuxVideoWidth, mAuxVideoHeight);
1778    result.append(buffer);
1779    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1780    result.append(buffer);
1781    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1782    result.append(buffer);
1783    snprintf(buffer, SIZE, "     Aux Bit rate (bps): %d\n", mAuxVideoBitRate);
1784    result.append(buffer);
1785    ::write(fd, result.string(), result.size());
1786    return OK;
1787}
1788}  // namespace android
1789