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