StagefrightRecorder.cpp revision 635730831e08c32a5fe7c59125e0919b7e7899cd
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(sp<CameraSource> *cameraSource) {
1039    status_t err = OK;
1040    if ((err = checkVideoEncoderCapabilities()) != OK) {
1041        return err;
1042    }
1043    Size videoSize;
1044    videoSize.width = mVideoWidth;
1045    videoSize.height = mVideoHeight;
1046    if (mCaptureTimeLapse) {
1047        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1048                mCamera, mCameraId,
1049                videoSize, mFrameRate, mPreviewSurface,
1050                mTimeBetweenTimeLapseFrameCaptureUs);
1051        *cameraSource = mCameraSourceTimeLapse;
1052    } else {
1053        *cameraSource = CameraSource::CreateFromCamera(
1054                mCamera, mCameraId, videoSize, mFrameRate, mPreviewSurface);
1055    }
1056    CHECK(*cameraSource != NULL);
1057
1058    // When frame rate is not set, the actual frame rate will be set to
1059    // the current frame rate being used.
1060    if (mFrameRate == -1) {
1061        int32_t frameRate = 0;
1062        CHECK ((*cameraSource)->getFormat()->findInt32(
1063                    kKeySampleRate, &frameRate));
1064        LOGI("Frame rate is not explicitly set. Use the current frame "
1065             "rate (%d fps)", frameRate);
1066        mFrameRate = frameRate;
1067    }
1068
1069    CHECK(mFrameRate != -1);
1070    return OK;
1071}
1072
1073status_t StagefrightRecorder::setupVideoEncoder(
1074        sp<MediaSource> cameraSource,
1075        int32_t videoBitRate,
1076        sp<MediaSource> *source) {
1077    source->clear();
1078
1079    sp<MetaData> enc_meta = new MetaData;
1080    enc_meta->setInt32(kKeyBitRate, videoBitRate);
1081    enc_meta->setInt32(kKeySampleRate, mFrameRate);
1082
1083    switch (mVideoEncoder) {
1084        case VIDEO_ENCODER_H263:
1085            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
1086            break;
1087
1088        case VIDEO_ENCODER_MPEG_4_SP:
1089            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
1090            break;
1091
1092        case VIDEO_ENCODER_H264:
1093            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
1094            break;
1095
1096        default:
1097            CHECK(!"Should not be here, unsupported video encoding.");
1098            break;
1099    }
1100
1101    sp<MetaData> meta = cameraSource->getFormat();
1102
1103    int32_t width, height, stride, sliceHeight, colorFormat;
1104    CHECK(meta->findInt32(kKeyWidth, &width));
1105    CHECK(meta->findInt32(kKeyHeight, &height));
1106    CHECK(meta->findInt32(kKeyStride, &stride));
1107    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1108    CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1109
1110    enc_meta->setInt32(kKeyWidth, width);
1111    enc_meta->setInt32(kKeyHeight, height);
1112    enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
1113    enc_meta->setInt32(kKeyStride, stride);
1114    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
1115    enc_meta->setInt32(kKeyColorFormat, colorFormat);
1116    if (mVideoTimeScale > 0) {
1117        enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
1118    }
1119    if (mVideoEncoderProfile != -1) {
1120        enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
1121    }
1122    if (mVideoEncoderLevel != -1) {
1123        enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
1124    } else if (mCaptureTimeLapse) {
1125        // Check if we are using high resolution and/or high bitrate and
1126        // set appropriate level for the software AVCEncoder.
1127        if ((width * height >= 921600) // 720p
1128                || (videoBitRate >= 20000000)) {
1129            enc_meta->setInt32(kKeyVideoLevel, 50);
1130        }
1131    }
1132
1133    OMXClient client;
1134    CHECK_EQ(client.connect(), OK);
1135
1136    // Use software codec for time lapse
1137    uint32_t encoder_flags = (mCaptureTimeLapse) ? OMXCodec::kPreferSoftwareCodecs : 0;
1138    sp<MediaSource> encoder = OMXCodec::Create(
1139            client.interface(), enc_meta,
1140            true /* createEncoder */, cameraSource,
1141            NULL, encoder_flags);
1142    if (encoder == NULL) {
1143        return UNKNOWN_ERROR;
1144    }
1145
1146    *source = encoder;
1147
1148    return OK;
1149}
1150
1151status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1152    sp<MediaSource> audioEncoder;
1153    switch(mAudioEncoder) {
1154        case AUDIO_ENCODER_AMR_NB:
1155        case AUDIO_ENCODER_AMR_WB:
1156        case AUDIO_ENCODER_AAC:
1157            audioEncoder = createAudioSource();
1158            break;
1159        default:
1160            LOGE("Unsupported audio encoder: %d", mAudioEncoder);
1161            return UNKNOWN_ERROR;
1162    }
1163
1164    if (audioEncoder == NULL) {
1165        return UNKNOWN_ERROR;
1166    }
1167
1168    writer->addSource(audioEncoder);
1169    return OK;
1170}
1171
1172status_t StagefrightRecorder::setupMPEG4Recording(
1173        bool useSplitCameraSource,
1174        int outputFd,
1175        int32_t videoWidth, int32_t videoHeight,
1176        int32_t videoBitRate,
1177        int32_t *totalBitRate,
1178        sp<MediaWriter> *mediaWriter) {
1179    mediaWriter->clear();
1180    *totalBitRate = 0;
1181    status_t err = OK;
1182    sp<MediaWriter> writer = new MPEG4Writer(dup(outputFd));
1183
1184    // Add audio source first if it exists
1185    if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_LIST_END)) {
1186        err = setupAudioEncoder(writer);
1187        if (err != OK) return err;
1188        *totalBitRate += mAudioBitRate;
1189    }
1190    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1191            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1192
1193        sp<MediaSource> cameraMediaSource;
1194        if (useSplitCameraSource) {
1195            LOGV("Using Split camera source");
1196            cameraMediaSource = mCameraSourceSplitter->createClient();
1197        } else {
1198            sp<CameraSource> cameraSource;
1199            err = setupCameraSource(&cameraSource);
1200            cameraMediaSource = cameraSource;
1201        }
1202        if ((videoWidth != mVideoWidth) || (videoHeight != mVideoHeight)) {
1203            // Use downsampling from the original source.
1204            cameraMediaSource =
1205                new VideoSourceDownSampler(cameraMediaSource, videoWidth, videoHeight);
1206        }
1207        if (err != OK) {
1208            return err;
1209        }
1210
1211        sp<MediaSource> encoder;
1212        err = setupVideoEncoder(cameraMediaSource, videoBitRate, &encoder);
1213        if (err != OK) {
1214            return err;
1215        }
1216
1217        writer->addSource(encoder);
1218        *totalBitRate += videoBitRate;
1219    }
1220
1221    if (mInterleaveDurationUs > 0) {
1222        reinterpret_cast<MPEG4Writer *>(writer.get())->
1223            setInterleaveDuration(mInterleaveDurationUs);
1224    }
1225    if (mMaxFileDurationUs != 0) {
1226        writer->setMaxFileDuration(mMaxFileDurationUs);
1227    }
1228    if (mMaxFileSizeBytes != 0) {
1229        writer->setMaxFileSize(mMaxFileSizeBytes);
1230    }
1231
1232    writer->setListener(mListener);
1233    *mediaWriter = writer;
1234    return OK;
1235}
1236
1237void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate,
1238        sp<MetaData> *meta) {
1239    (*meta)->setInt64(kKeyTime, startTimeUs);
1240    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1241    (*meta)->setInt32(kKeyBitRate, totalBitRate);
1242    (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1243    if (mMovieTimeScale > 0) {
1244        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1245    }
1246    if (mTrackEveryTimeDurationUs > 0) {
1247        (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1248    }
1249}
1250
1251status_t StagefrightRecorder::startMPEG4Recording() {
1252    if (mCaptureAuxVideo) {
1253        if (!mCaptureTimeLapse) {
1254            LOGE("Auxiliary video can be captured only in time lapse mode");
1255            return UNKNOWN_ERROR;
1256        }
1257        LOGV("Creating MediaSourceSplitter");
1258        sp<CameraSource> cameraSource;
1259        status_t err = setupCameraSource(&cameraSource);
1260        if (err != OK) {
1261            return err;
1262        }
1263        mCameraSourceSplitter = new MediaSourceSplitter(cameraSource);
1264    } else {
1265        mCameraSourceSplitter = NULL;
1266    }
1267
1268    int32_t totalBitRate;
1269    status_t err = setupMPEG4Recording(mCaptureAuxVideo,
1270            mOutputFd, mVideoWidth, mVideoHeight,
1271            mVideoBitRate, &totalBitRate, &mWriter);
1272    if (err != OK) {
1273        return err;
1274    }
1275
1276    int64_t startTimeUs = systemTime() / 1000;
1277    sp<MetaData> meta = new MetaData;
1278    setupMPEG4MetaData(startTimeUs, totalBitRate, &meta);
1279
1280    err = mWriter->start(meta.get());
1281    if (err != OK) {
1282        return err;
1283    }
1284
1285    if (mCaptureAuxVideo) {
1286        CHECK(mOutputFdAux >= 0);
1287        if (mWriterAux != NULL) {
1288            LOGE("Auxiliary File writer is not avaialble");
1289            return UNKNOWN_ERROR;
1290        }
1291        if ((mAuxVideoWidth > mVideoWidth) || (mAuxVideoHeight > mVideoHeight) ||
1292                ((mAuxVideoWidth == mVideoWidth) && mAuxVideoHeight == mVideoHeight)) {
1293            LOGE("Auxiliary video size (%d x %d) same or larger than the main video size (%d x %d)",
1294                    mAuxVideoWidth, mAuxVideoHeight, mVideoWidth, mVideoHeight);
1295            return UNKNOWN_ERROR;
1296        }
1297
1298        int32_t totalBitrateAux;
1299        err = setupMPEG4Recording(mCaptureAuxVideo,
1300                mOutputFdAux, mAuxVideoWidth, mAuxVideoHeight,
1301                mAuxVideoBitRate, &totalBitrateAux, &mWriterAux);
1302        if (err != OK) {
1303            return err;
1304        }
1305
1306        sp<MetaData> metaAux = new MetaData;
1307        setupMPEG4MetaData(startTimeUs, totalBitrateAux, &metaAux);
1308
1309        return mWriterAux->start(metaAux.get());
1310    }
1311
1312    return OK;
1313}
1314
1315status_t StagefrightRecorder::pause() {
1316    LOGV("pause");
1317    if (mWriter == NULL) {
1318        return UNKNOWN_ERROR;
1319    }
1320    mWriter->pause();
1321
1322    if (mCaptureAuxVideo) {
1323        if (mWriterAux == NULL) {
1324            return UNKNOWN_ERROR;
1325        }
1326        mWriterAux->pause();
1327    }
1328
1329    return OK;
1330}
1331
1332status_t StagefrightRecorder::stop() {
1333    LOGV("stop");
1334    status_t err = OK;
1335
1336    if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) {
1337        mCameraSourceTimeLapse->startQuickReadReturns();
1338        mCameraSourceTimeLapse = NULL;
1339    }
1340
1341    if (mCaptureAuxVideo) {
1342        if (mWriterAux != NULL) {
1343            mWriterAux->stop();
1344            mWriterAux.clear();
1345        }
1346    }
1347
1348    if (mWriter != NULL) {
1349        err = mWriter->stop();
1350        mWriter.clear();
1351    }
1352
1353    if (mOutputFd >= 0) {
1354        ::close(mOutputFd);
1355        mOutputFd = -1;
1356    }
1357
1358    if (mCaptureAuxVideo) {
1359        if (mOutputFdAux >= 0) {
1360            ::close(mOutputFdAux);
1361            mOutputFdAux = -1;
1362        }
1363    }
1364
1365    return err;
1366}
1367
1368status_t StagefrightRecorder::close() {
1369    LOGV("close");
1370    stop();
1371
1372    return OK;
1373}
1374
1375status_t StagefrightRecorder::reset() {
1376    LOGV("reset");
1377    stop();
1378
1379    // No audio or video source by default
1380    mAudioSource = AUDIO_SOURCE_LIST_END;
1381    mVideoSource = VIDEO_SOURCE_LIST_END;
1382
1383    // Default parameters
1384    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1385    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1386    mVideoEncoder  = VIDEO_ENCODER_H263;
1387    mVideoWidth    = 176;
1388    mVideoHeight   = 144;
1389    mAuxVideoWidth    = 176;
1390    mAuxVideoHeight   = 144;
1391    mFrameRate     = -1;
1392    mVideoBitRate  = 192000;
1393    mAuxVideoBitRate = 192000;
1394    mSampleRate    = 8000;
1395    mAudioChannels = 1;
1396    mAudioBitRate  = 12200;
1397    mInterleaveDurationUs = 0;
1398    mIFramesIntervalSec = 1;
1399    mAudioSourceNode = 0;
1400    mUse64BitFileOffset = false;
1401    mMovieTimeScale  = -1;
1402    mAudioTimeScale  = -1;
1403    mVideoTimeScale  = -1;
1404    mCameraId        = 0;
1405    mVideoEncoderProfile = -1;
1406    mVideoEncoderLevel   = -1;
1407    mMaxFileDurationUs = 0;
1408    mMaxFileSizeBytes = 0;
1409    mTrackEveryTimeDurationUs = 0;
1410    mCaptureTimeLapse = false;
1411    mTimeBetweenTimeLapseFrameCaptureUs = -1;
1412    mCaptureAuxVideo = false;
1413    mCameraSourceSplitter = NULL;
1414    mCameraSourceTimeLapse = NULL;
1415    mEncoderProfiles = MediaProfiles::getInstance();
1416
1417    mOutputFd = -1;
1418    mOutputFdAux = -1;
1419
1420    return OK;
1421}
1422
1423status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1424    LOGV("getMaxAmplitude");
1425
1426    if (max == NULL) {
1427        LOGE("Null pointer argument");
1428        return BAD_VALUE;
1429    }
1430
1431    if (mAudioSourceNode != 0) {
1432        *max = mAudioSourceNode->getMaxAmplitude();
1433    } else {
1434        *max = 0;
1435    }
1436
1437    return OK;
1438}
1439
1440status_t StagefrightRecorder::dump(
1441        int fd, const Vector<String16>& args) const {
1442    LOGV("dump");
1443    const size_t SIZE = 256;
1444    char buffer[SIZE];
1445    String8 result;
1446    if (mWriter != 0) {
1447        mWriter->dump(fd, args);
1448    } else {
1449        snprintf(buffer, SIZE, "   No file writer\n");
1450        result.append(buffer);
1451    }
1452    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1453    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1454    result.append(buffer);
1455    snprintf(buffer, SIZE, "   Output file Auxiliary (fd %d):\n", mOutputFdAux);
1456    result.append(buffer);
1457    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1458    result.append(buffer);
1459    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1460    result.append(buffer);
1461    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
1462    result.append(buffer);
1463    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1464    result.append(buffer);
1465    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1466    result.append(buffer);
1467    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1468    result.append(buffer);
1469    snprintf(buffer, SIZE, "   Audio\n");
1470    result.append(buffer);
1471    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1472    result.append(buffer);
1473    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1474    result.append(buffer);
1475    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1476    result.append(buffer);
1477    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1478    result.append(buffer);
1479    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1480    result.append(buffer);
1481    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1482    result.append(buffer);
1483    snprintf(buffer, SIZE, "   Video\n");
1484    result.append(buffer);
1485    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1486    result.append(buffer);
1487    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1488    result.append(buffer);
1489    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1490    result.append(buffer);
1491    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1492    result.append(buffer);
1493    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1494    result.append(buffer);
1495    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1496    result.append(buffer);
1497    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1498    result.append(buffer);
1499    snprintf(buffer, SIZE, "     Aux Frame size (pixels): %dx%d\n", mAuxVideoWidth, mAuxVideoHeight);
1500    result.append(buffer);
1501    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1502    result.append(buffer);
1503    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1504    result.append(buffer);
1505    snprintf(buffer, SIZE, "     Aux Bit rate (bps): %d\n", mAuxVideoBitRate);
1506    result.append(buffer);
1507    ::write(fd, result.string(), result.size());
1508    return OK;
1509}
1510}  // namespace android
1511