StagefrightRecorder.cpp revision 1cc73922339a110d7ffc47e8842f958492dd85bf
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
348// Always rotate clockwise, and only support 0, 90, 180 and 270 for now.
349status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) {
350    LOGV("setParamVideoRotation: %d", degrees);
351    if (degrees < 0 || degrees % 90 != 0) {
352        LOGE("Unsupported video rotation angle: %d", degrees);
353        return BAD_VALUE;
354    }
355    mRotationDegrees = degrees % 360;
356    return OK;
357}
358
359status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
360    LOGV("setParamMaxFileDurationUs: %lld us", timeUs);
361    if (timeUs <= 0) {
362        LOGW("Max file duration is not positive: %lld us. Disabling duration limit.", timeUs);
363        timeUs = 0; // Disable the duration limit for zero or negative values.
364    } else if (timeUs <= 100000LL) {  // XXX: 100 milli-seconds
365        LOGE("Max file duration is too short: %lld us", timeUs);
366        return BAD_VALUE;
367    }
368
369    if (timeUs <= 15 * 1000000LL) {
370        LOGW("Target duration (%lld us) too short to be respected", timeUs);
371    }
372    mMaxFileDurationUs = timeUs;
373    return OK;
374}
375
376status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
377    LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
378    if (bytes <= 1024) {  // XXX: 1 kB
379        LOGE("Max file size is too small: %lld bytes", bytes);
380        return BAD_VALUE;
381    }
382
383    if (bytes <= 100 * 1024) {
384        LOGW("Target file size (%lld bytes) is too small to be respected", bytes);
385    }
386
387    mMaxFileSizeBytes = bytes;
388    return OK;
389}
390
391status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
392    LOGV("setParamInterleaveDuration: %d", durationUs);
393    if (durationUs <= 500000) {           //  500 ms
394        // If interleave duration is too small, it is very inefficient to do
395        // interleaving since the metadata overhead will count for a significant
396        // portion of the saved contents
397        LOGE("Audio/video interleave duration is too small: %d us", durationUs);
398        return BAD_VALUE;
399    } else if (durationUs >= 10000000) {  // 10 seconds
400        // If interleaving duration is too large, it can cause the recording
401        // session to use too much memory since we have to save the output
402        // data before we write them out
403        LOGE("Audio/video interleave duration is too large: %d us", durationUs);
404        return BAD_VALUE;
405    }
406    mInterleaveDurationUs = durationUs;
407    return OK;
408}
409
410// If seconds <  0, only the first frame is I frame, and rest are all P frames
411// If seconds == 0, all frames are encoded as I frames. No P frames
412// If seconds >  0, it is the time spacing (seconds) between 2 neighboring I frames
413status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) {
414    LOGV("setParamVideoIFramesInterval: %d seconds", seconds);
415    mIFramesIntervalSec = seconds;
416    return OK;
417}
418
419status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
420    LOGV("setParam64BitFileOffset: %s",
421        use64Bit? "use 64 bit file offset": "use 32 bit file offset");
422    mUse64BitFileOffset = use64Bit;
423    return OK;
424}
425
426status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
427    LOGV("setParamVideoCameraId: %d", cameraId);
428    if (cameraId < 0) {
429        return BAD_VALUE;
430    }
431    mCameraId = cameraId;
432    return OK;
433}
434
435status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
436    LOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
437    if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
438        LOGE("Tracking time duration too short: %lld us", timeDurationUs);
439        return BAD_VALUE;
440    }
441    mTrackEveryTimeDurationUs = timeDurationUs;
442    return OK;
443}
444
445status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) {
446    LOGV("setParamVideoEncoderProfile: %d", profile);
447
448    // Additional check will be done later when we load the encoder.
449    // For now, we are accepting values defined in OpenMAX IL.
450    mVideoEncoderProfile = profile;
451    return OK;
452}
453
454status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) {
455    LOGV("setParamVideoEncoderLevel: %d", level);
456
457    // Additional check will be done later when we load the encoder.
458    // For now, we are accepting values defined in OpenMAX IL.
459    mVideoEncoderLevel = level;
460    return OK;
461}
462
463status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) {
464    LOGV("setParamMovieTimeScale: %d", timeScale);
465
466    // The range is set to be the same as the audio's time scale range
467    // since audio's time scale has a wider range.
468    if (timeScale < 600 || timeScale > 96000) {
469        LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
470        return BAD_VALUE;
471    }
472    mMovieTimeScale = timeScale;
473    return OK;
474}
475
476status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) {
477    LOGV("setParamVideoTimeScale: %d", timeScale);
478
479    // 60000 is chosen to make sure that each video frame from a 60-fps
480    // video has 1000 ticks.
481    if (timeScale < 600 || timeScale > 60000) {
482        LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
483        return BAD_VALUE;
484    }
485    mVideoTimeScale = timeScale;
486    return OK;
487}
488
489status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) {
490    LOGV("setParamAudioTimeScale: %d", timeScale);
491
492    // 96000 Hz is the highest sampling rate support in AAC.
493    if (timeScale < 600 || timeScale > 96000) {
494        LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
495        return BAD_VALUE;
496    }
497    mAudioTimeScale = timeScale;
498    return OK;
499}
500
501status_t StagefrightRecorder::setParamTimeLapseEnable(int32_t timeLapseEnable) {
502    LOGV("setParamTimeLapseEnable: %d", timeLapseEnable);
503
504    if(timeLapseEnable == 0) {
505        mCaptureTimeLapse = false;
506    } else if (timeLapseEnable == 1) {
507        mCaptureTimeLapse = true;
508    } else {
509        return BAD_VALUE;
510    }
511    return OK;
512}
513
514status_t StagefrightRecorder::setParamTimeBetweenTimeLapseFrameCapture(int64_t timeUs) {
515    LOGV("setParamTimeBetweenTimeLapseFrameCapture: %lld us", timeUs);
516
517    // Not allowing time more than a day
518    if (timeUs <= 0 || timeUs > 86400*1E6) {
519        LOGE("Time between time lapse frame capture (%lld) is out of range [0, 1 Day]", timeUs);
520        return BAD_VALUE;
521    }
522
523    mTimeBetweenTimeLapseFrameCaptureUs = timeUs;
524    return OK;
525}
526
527status_t StagefrightRecorder::setParamAuxVideoWidth(int32_t width) {
528    LOGV("setParamAuxVideoWidth : %d", width);
529
530    if (width <= 0) {
531        LOGE("Width (%d) is not positive", width);
532        return BAD_VALUE;
533    }
534
535    mAuxVideoWidth = width;
536    return OK;
537}
538
539status_t StagefrightRecorder::setParamAuxVideoHeight(int32_t height) {
540    LOGV("setParamAuxVideoHeight : %d", height);
541
542    if (height <= 0) {
543        LOGE("Height (%d) is not positive", height);
544        return BAD_VALUE;
545    }
546
547    mAuxVideoHeight = height;
548    return OK;
549}
550
551status_t StagefrightRecorder::setParamAuxVideoEncodingBitRate(int32_t bitRate) {
552    LOGV("StagefrightRecorder::setParamAuxVideoEncodingBitRate: %d", bitRate);
553
554    if (bitRate <= 0) {
555        LOGE("Invalid video encoding bit rate: %d", bitRate);
556        return BAD_VALUE;
557    }
558
559    mAuxVideoBitRate = bitRate;
560    return OK;
561}
562
563status_t StagefrightRecorder::setParameter(
564        const String8 &key, const String8 &value) {
565    LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
566    if (key == "max-duration") {
567        int64_t max_duration_ms;
568        if (safe_strtoi64(value.string(), &max_duration_ms)) {
569            return setParamMaxFileDurationUs(1000LL * max_duration_ms);
570        }
571    } else if (key == "max-filesize") {
572        int64_t max_filesize_bytes;
573        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
574            return setParamMaxFileSizeBytes(max_filesize_bytes);
575        }
576    } else if (key == "interleave-duration-us") {
577        int32_t durationUs;
578        if (safe_strtoi32(value.string(), &durationUs)) {
579            return setParamInterleaveDuration(durationUs);
580        }
581    } else if (key == "param-movie-time-scale") {
582        int32_t timeScale;
583        if (safe_strtoi32(value.string(), &timeScale)) {
584            return setParamMovieTimeScale(timeScale);
585        }
586    } else if (key == "param-use-64bit-offset") {
587        int32_t use64BitOffset;
588        if (safe_strtoi32(value.string(), &use64BitOffset)) {
589            return setParam64BitFileOffset(use64BitOffset != 0);
590        }
591    } else if (key == "param-track-time-status") {
592        int64_t timeDurationUs;
593        if (safe_strtoi64(value.string(), &timeDurationUs)) {
594            return setParamTrackTimeStatus(timeDurationUs);
595        }
596    } else if (key == "audio-param-sampling-rate") {
597        int32_t sampling_rate;
598        if (safe_strtoi32(value.string(), &sampling_rate)) {
599            return setParamAudioSamplingRate(sampling_rate);
600        }
601    } else if (key == "audio-param-number-of-channels") {
602        int32_t number_of_channels;
603        if (safe_strtoi32(value.string(), &number_of_channels)) {
604            return setParamAudioNumberOfChannels(number_of_channels);
605        }
606    } else if (key == "audio-param-encoding-bitrate") {
607        int32_t audio_bitrate;
608        if (safe_strtoi32(value.string(), &audio_bitrate)) {
609            return setParamAudioEncodingBitRate(audio_bitrate);
610        }
611    } else if (key == "audio-param-time-scale") {
612        int32_t timeScale;
613        if (safe_strtoi32(value.string(), &timeScale)) {
614            return setParamAudioTimeScale(timeScale);
615        }
616    } else if (key == "video-param-encoding-bitrate") {
617        int32_t video_bitrate;
618        if (safe_strtoi32(value.string(), &video_bitrate)) {
619            return setParamVideoEncodingBitRate(video_bitrate);
620        }
621    } else if (key == "video-param-rotation-angle-degrees") {
622        int32_t degrees;
623        if (safe_strtoi32(value.string(), &degrees)) {
624            return setParamVideoRotation(degrees);
625        }
626    } else if (key == "video-param-i-frames-interval") {
627        int32_t seconds;
628        if (safe_strtoi32(value.string(), &seconds)) {
629            return setParamVideoIFramesInterval(seconds);
630        }
631    } else if (key == "video-param-encoder-profile") {
632        int32_t profile;
633        if (safe_strtoi32(value.string(), &profile)) {
634            return setParamVideoEncoderProfile(profile);
635        }
636    } else if (key == "video-param-encoder-level") {
637        int32_t level;
638        if (safe_strtoi32(value.string(), &level)) {
639            return setParamVideoEncoderLevel(level);
640        }
641    } else if (key == "video-param-camera-id") {
642        int32_t cameraId;
643        if (safe_strtoi32(value.string(), &cameraId)) {
644            return setParamVideoCameraId(cameraId);
645        }
646    } else if (key == "video-param-time-scale") {
647        int32_t timeScale;
648        if (safe_strtoi32(value.string(), &timeScale)) {
649            return setParamVideoTimeScale(timeScale);
650        }
651    } else if (key == "time-lapse-enable") {
652        int32_t timeLapseEnable;
653        if (safe_strtoi32(value.string(), &timeLapseEnable)) {
654            return setParamTimeLapseEnable(timeLapseEnable);
655        }
656    } else if (key == "time-between-time-lapse-frame-capture") {
657        int64_t timeBetweenTimeLapseFrameCaptureMs;
658        if (safe_strtoi64(value.string(), &timeBetweenTimeLapseFrameCaptureMs)) {
659            return setParamTimeBetweenTimeLapseFrameCapture(
660                    1000LL * timeBetweenTimeLapseFrameCaptureMs);
661        }
662    } else if (key == "video-aux-param-width") {
663        int32_t auxWidth;
664        if (safe_strtoi32(value.string(), &auxWidth)) {
665            return setParamAuxVideoWidth(auxWidth);
666        }
667    } else if (key == "video-aux-param-height") {
668        int32_t auxHeight;
669        if (safe_strtoi32(value.string(), &auxHeight)) {
670            return setParamAuxVideoHeight(auxHeight);
671        }
672    } else if (key == "video-aux-param-encoding-bitrate") {
673        int32_t auxVideoBitRate;
674        if (safe_strtoi32(value.string(), &auxVideoBitRate)) {
675            return setParamAuxVideoEncodingBitRate(auxVideoBitRate);
676        }
677    } else {
678        LOGE("setParameter: failed to find key %s", key.string());
679    }
680    return BAD_VALUE;
681}
682
683status_t StagefrightRecorder::setParameters(const String8 &params) {
684    LOGV("setParameters: %s", params.string());
685    const char *cparams = params.string();
686    const char *key_start = cparams;
687    for (;;) {
688        const char *equal_pos = strchr(key_start, '=');
689        if (equal_pos == NULL) {
690            LOGE("Parameters %s miss a value", cparams);
691            return BAD_VALUE;
692        }
693        String8 key(key_start, equal_pos - key_start);
694        TrimString(&key);
695        if (key.length() == 0) {
696            LOGE("Parameters %s contains an empty key", cparams);
697            return BAD_VALUE;
698        }
699        const char *value_start = equal_pos + 1;
700        const char *semicolon_pos = strchr(value_start, ';');
701        String8 value;
702        if (semicolon_pos == NULL) {
703            value.setTo(value_start);
704        } else {
705            value.setTo(value_start, semicolon_pos - value_start);
706        }
707        if (setParameter(key, value) != OK) {
708            return BAD_VALUE;
709        }
710        if (semicolon_pos == NULL) {
711            break;  // Reaches the end
712        }
713        key_start = semicolon_pos + 1;
714    }
715    return OK;
716}
717
718status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
719    mListener = listener;
720
721    return OK;
722}
723
724status_t StagefrightRecorder::prepare() {
725    return OK;
726}
727
728status_t StagefrightRecorder::start() {
729    CHECK(mOutputFd >= 0);
730
731    if (mWriter != NULL) {
732        LOGE("File writer is not avaialble");
733        return UNKNOWN_ERROR;
734    }
735
736    switch (mOutputFormat) {
737        case OUTPUT_FORMAT_DEFAULT:
738        case OUTPUT_FORMAT_THREE_GPP:
739        case OUTPUT_FORMAT_MPEG_4:
740            return startMPEG4Recording();
741
742        case OUTPUT_FORMAT_AMR_NB:
743        case OUTPUT_FORMAT_AMR_WB:
744            return startAMRRecording();
745
746        case OUTPUT_FORMAT_AAC_ADIF:
747        case OUTPUT_FORMAT_AAC_ADTS:
748            return startAACRecording();
749
750        case OUTPUT_FORMAT_RTP_AVP:
751            return startRTPRecording();
752
753        case OUTPUT_FORMAT_MPEG2TS:
754            return startMPEG2TSRecording();
755
756        default:
757            LOGE("Unsupported output file format: %d", mOutputFormat);
758            return UNKNOWN_ERROR;
759    }
760}
761
762sp<MediaSource> StagefrightRecorder::createAudioSource() {
763    sp<AudioSource> audioSource =
764        new AudioSource(
765                mAudioSource,
766                mSampleRate,
767                mAudioChannels);
768
769    status_t err = audioSource->initCheck();
770
771    if (err != OK) {
772        LOGE("audio source is not initialized");
773        return NULL;
774    }
775
776    sp<MetaData> encMeta = new MetaData;
777    const char *mime;
778    switch (mAudioEncoder) {
779        case AUDIO_ENCODER_AMR_NB:
780        case AUDIO_ENCODER_DEFAULT:
781            mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
782            break;
783        case AUDIO_ENCODER_AMR_WB:
784            mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
785            break;
786        case AUDIO_ENCODER_AAC:
787            mime = MEDIA_MIMETYPE_AUDIO_AAC;
788            break;
789        default:
790            LOGE("Unknown audio encoder: %d", mAudioEncoder);
791            return NULL;
792    }
793    encMeta->setCString(kKeyMIMEType, mime);
794
795    int32_t maxInputSize;
796    CHECK(audioSource->getFormat()->findInt32(
797                kKeyMaxInputSize, &maxInputSize));
798
799    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
800    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
801    encMeta->setInt32(kKeySampleRate, mSampleRate);
802    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
803    if (mAudioTimeScale > 0) {
804        encMeta->setInt32(kKeyTimeScale, mAudioTimeScale);
805    }
806
807    OMXClient client;
808    CHECK_EQ(client.connect(), OK);
809
810    sp<MediaSource> audioEncoder =
811        OMXCodec::Create(client.interface(), encMeta,
812                         true /* createEncoder */, audioSource);
813    mAudioSourceNode = audioSource;
814
815    return audioEncoder;
816}
817
818status_t StagefrightRecorder::startAACRecording() {
819    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF ||
820          mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
821
822    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
823    CHECK(mAudioSource != AUDIO_SOURCE_LIST_END);
824
825    CHECK(0 == "AACWriter is not implemented yet");
826
827    return OK;
828}
829
830status_t StagefrightRecorder::startAMRRecording() {
831    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
832          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
833
834    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
835        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
836            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
837            LOGE("Invalid encoder %d used for AMRNB recording",
838                    mAudioEncoder);
839            return BAD_VALUE;
840        }
841        if (mSampleRate != 8000) {
842            LOGE("Invalid sampling rate %d used for AMRNB recording",
843                    mSampleRate);
844            return BAD_VALUE;
845        }
846    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
847        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
848            LOGE("Invlaid encoder %d used for AMRWB recording",
849                    mAudioEncoder);
850            return BAD_VALUE;
851        }
852        if (mSampleRate != 16000) {
853            LOGE("Invalid sample rate %d used for AMRWB recording",
854                    mSampleRate);
855            return BAD_VALUE;
856        }
857    }
858    if (mAudioChannels != 1) {
859        LOGE("Invalid number of audio channels %d used for amr recording",
860                mAudioChannels);
861        return BAD_VALUE;
862    }
863
864    if (mAudioSource >= AUDIO_SOURCE_LIST_END) {
865        LOGE("Invalid audio source: %d", mAudioSource);
866        return BAD_VALUE;
867    }
868
869    sp<MediaSource> audioEncoder = createAudioSource();
870
871    if (audioEncoder == NULL) {
872        return UNKNOWN_ERROR;
873    }
874
875    mWriter = new AMRWriter(mOutputFd);
876    mWriter->addSource(audioEncoder);
877
878    if (mMaxFileDurationUs != 0) {
879        mWriter->setMaxFileDuration(mMaxFileDurationUs);
880    }
881    if (mMaxFileSizeBytes != 0) {
882        mWriter->setMaxFileSize(mMaxFileSizeBytes);
883    }
884    mWriter->setListener(mListener);
885    mWriter->start();
886
887    return OK;
888}
889
890status_t StagefrightRecorder::startRTPRecording() {
891    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
892
893    if ((mAudioSource != AUDIO_SOURCE_LIST_END
894                && mVideoSource != VIDEO_SOURCE_LIST_END)
895            || (mAudioSource == AUDIO_SOURCE_LIST_END
896                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
897        // Must have exactly one source.
898        return BAD_VALUE;
899    }
900
901    if (mOutputFd < 0) {
902        return BAD_VALUE;
903    }
904
905    sp<MediaSource> source;
906
907    if (mAudioSource != AUDIO_SOURCE_LIST_END) {
908        source = createAudioSource();
909    } else {
910
911        sp<CameraSource> cameraSource;
912        status_t err = setupCameraSource(&cameraSource);
913        if (err != OK) {
914            return err;
915        }
916
917        err = setupVideoEncoder(cameraSource, mVideoBitRate, &source);
918        if (err != OK) {
919            return err;
920        }
921    }
922
923    mWriter = new ARTPWriter(mOutputFd);
924    mWriter->addSource(source);
925    mWriter->setListener(mListener);
926
927    return mWriter->start();
928}
929
930status_t StagefrightRecorder::startMPEG2TSRecording() {
931    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
932
933    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
934
935    if (mAudioSource != AUDIO_SOURCE_LIST_END) {
936        if (mAudioEncoder != AUDIO_ENCODER_AAC) {
937            return ERROR_UNSUPPORTED;
938        }
939
940        status_t err = setupAudioEncoder(writer);
941
942        if (err != OK) {
943            return err;
944        }
945    }
946
947    if (mVideoSource == VIDEO_SOURCE_DEFAULT
948            || mVideoSource == VIDEO_SOURCE_CAMERA) {
949        if (mVideoEncoder != VIDEO_ENCODER_H264) {
950            return ERROR_UNSUPPORTED;
951        }
952
953        sp<CameraSource> cameraSource;
954        status_t err = setupCameraSource(&cameraSource);
955        if (err != OK) {
956            return err;
957        }
958
959        sp<MediaSource> encoder;
960        err = setupVideoEncoder(cameraSource, mVideoBitRate, &encoder);
961
962        if (err != OK) {
963            return err;
964        }
965
966        writer->addSource(encoder);
967    }
968
969    if (mMaxFileDurationUs != 0) {
970        writer->setMaxFileDuration(mMaxFileDurationUs);
971    }
972
973    if (mMaxFileSizeBytes != 0) {
974        writer->setMaxFileSize(mMaxFileSizeBytes);
975    }
976
977    mWriter = writer;
978
979    return mWriter->start();
980}
981
982void StagefrightRecorder::clipVideoFrameRate() {
983    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
984    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
985                        "enc.vid.fps.min", mVideoEncoder);
986    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
987                        "enc.vid.fps.max", mVideoEncoder);
988    if (mFrameRate < minFrameRate && mFrameRate != -1) {
989        LOGW("Intended video encoding frame rate (%d fps) is too small"
990             " and will be set to (%d fps)", mFrameRate, minFrameRate);
991        mFrameRate = minFrameRate;
992    } else if (mFrameRate > maxFrameRate) {
993        LOGW("Intended video encoding frame rate (%d fps) is too large"
994             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
995        mFrameRate = maxFrameRate;
996    }
997}
998
999void StagefrightRecorder::clipVideoBitRate() {
1000    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1001    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1002                        "enc.vid.bps.min", mVideoEncoder);
1003    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1004                        "enc.vid.bps.max", mVideoEncoder);
1005    if (mVideoBitRate < minBitRate) {
1006        LOGW("Intended video encoding bit rate (%d bps) is too small"
1007             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1008        mVideoBitRate = minBitRate;
1009    } else if (mVideoBitRate > maxBitRate) {
1010        LOGW("Intended video encoding bit rate (%d bps) is too large"
1011             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1012        mVideoBitRate = maxBitRate;
1013    }
1014}
1015
1016void StagefrightRecorder::clipVideoFrameWidth() {
1017    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1018    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1019                        "enc.vid.width.min", mVideoEncoder);
1020    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1021                        "enc.vid.width.max", mVideoEncoder);
1022    if (mVideoWidth < minFrameWidth) {
1023        LOGW("Intended video encoding frame width (%d) is too small"
1024             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1025        mVideoWidth = minFrameWidth;
1026    } else if (mVideoWidth > maxFrameWidth) {
1027        LOGW("Intended video encoding frame width (%d) is too large"
1028             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1029        mVideoWidth = maxFrameWidth;
1030    }
1031}
1032
1033status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1034    if (!mCaptureTimeLapse) {
1035        // Dont clip for time lapse capture as encoder will have enough
1036        // time to encode because of slow capture rate of time lapse.
1037        clipVideoBitRate();
1038        clipVideoFrameRate();
1039        clipVideoFrameWidth();
1040        clipVideoFrameHeight();
1041    }
1042    return OK;
1043}
1044
1045void StagefrightRecorder::clipVideoFrameHeight() {
1046    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1047    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1048                        "enc.vid.height.min", mVideoEncoder);
1049    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1050                        "enc.vid.height.max", mVideoEncoder);
1051    if (mVideoHeight < minFrameHeight) {
1052        LOGW("Intended video encoding frame height (%d) is too small"
1053             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1054        mVideoHeight = minFrameHeight;
1055    } else if (mVideoHeight > maxFrameHeight) {
1056        LOGW("Intended video encoding frame height (%d) is too large"
1057             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1058        mVideoHeight = maxFrameHeight;
1059    }
1060}
1061
1062status_t StagefrightRecorder::setupCameraSource(
1063        sp<CameraSource> *cameraSource) {
1064    status_t err = OK;
1065    if ((err = checkVideoEncoderCapabilities()) != OK) {
1066        return err;
1067    }
1068    Size videoSize;
1069    videoSize.width = mVideoWidth;
1070    videoSize.height = mVideoHeight;
1071    if (mCaptureTimeLapse) {
1072        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1073                mCamera, mCameraId,
1074                videoSize, mFrameRate, mPreviewSurface,
1075                mTimeBetweenTimeLapseFrameCaptureUs);
1076        *cameraSource = mCameraSourceTimeLapse;
1077    } else {
1078        *cameraSource = CameraSource::CreateFromCamera(
1079                mCamera, mCameraId, videoSize, mFrameRate,
1080                mPreviewSurface, true /*storeMetaDataInVideoBuffers*/);
1081    }
1082    CHECK(*cameraSource != NULL);
1083
1084    // When frame rate is not set, the actual frame rate will be set to
1085    // the current frame rate being used.
1086    if (mFrameRate == -1) {
1087        int32_t frameRate = 0;
1088        CHECK ((*cameraSource)->getFormat()->findInt32(
1089                    kKeyFrameRate, &frameRate));
1090        LOGI("Frame rate is not explicitly set. Use the current frame "
1091             "rate (%d fps)", frameRate);
1092        mFrameRate = frameRate;
1093    }
1094
1095    CHECK(mFrameRate != -1);
1096
1097    mIsMetaDataStoredInVideoBuffers =
1098        (*cameraSource)->isMetaDataStoredInVideoBuffers();
1099
1100    return OK;
1101}
1102
1103status_t StagefrightRecorder::setupVideoEncoder(
1104        sp<MediaSource> cameraSource,
1105        int32_t videoBitRate,
1106        sp<MediaSource> *source) {
1107    source->clear();
1108
1109    sp<MetaData> enc_meta = new MetaData;
1110    enc_meta->setInt32(kKeyBitRate, videoBitRate);
1111    enc_meta->setInt32(kKeyFrameRate, mFrameRate);
1112
1113    switch (mVideoEncoder) {
1114        case VIDEO_ENCODER_H263:
1115            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
1116            break;
1117
1118        case VIDEO_ENCODER_MPEG_4_SP:
1119            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
1120            break;
1121
1122        case VIDEO_ENCODER_H264:
1123            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
1124            break;
1125
1126        default:
1127            CHECK(!"Should not be here, unsupported video encoding.");
1128            break;
1129    }
1130
1131    sp<MetaData> meta = cameraSource->getFormat();
1132
1133    int32_t width, height, stride, sliceHeight, colorFormat;
1134    CHECK(meta->findInt32(kKeyWidth, &width));
1135    CHECK(meta->findInt32(kKeyHeight, &height));
1136    CHECK(meta->findInt32(kKeyStride, &stride));
1137    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1138    CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1139
1140    enc_meta->setInt32(kKeyWidth, width);
1141    enc_meta->setInt32(kKeyHeight, height);
1142    enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
1143    enc_meta->setInt32(kKeyStride, stride);
1144    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
1145    enc_meta->setInt32(kKeyColorFormat, colorFormat);
1146    if (mVideoTimeScale > 0) {
1147        enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
1148    }
1149    if (mVideoEncoderProfile != -1) {
1150        enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
1151    }
1152    if (mVideoEncoderLevel != -1) {
1153        enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
1154    } else if (mCaptureTimeLapse) {
1155        // Check if we are using high resolution and/or high bitrate and
1156        // set appropriate level for the software AVCEncoder.
1157        if ((width * height >= 921600) // 720p
1158                || (videoBitRate >= 20000000)) {
1159            enc_meta->setInt32(kKeyVideoLevel, 50);
1160        }
1161    }
1162
1163    OMXClient client;
1164    CHECK_EQ(client.connect(), OK);
1165
1166    // Use software codec for time lapse
1167    uint32_t encoder_flags = 0;
1168    if (mCaptureTimeLapse) {
1169        encoder_flags |= OMXCodec::kPreferSoftwareCodecs;
1170    } else if (mIsMetaDataStoredInVideoBuffers) {
1171        encoder_flags |= OMXCodec::kHardwareCodecsOnly;
1172        encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers;
1173    }
1174    sp<MediaSource> encoder = OMXCodec::Create(
1175            client.interface(), enc_meta,
1176            true /* createEncoder */, cameraSource,
1177            NULL, encoder_flags);
1178    if (encoder == NULL) {
1179        LOGW("Failed to create the encoder");
1180        // When the encoder fails to be created, we need
1181        // release the camera source due to the camera's lock
1182        // and unlock mechanism.
1183        cameraSource->stop();
1184        return UNKNOWN_ERROR;
1185    }
1186
1187    *source = encoder;
1188
1189    return OK;
1190}
1191
1192status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1193    sp<MediaSource> audioEncoder;
1194    switch(mAudioEncoder) {
1195        case AUDIO_ENCODER_AMR_NB:
1196        case AUDIO_ENCODER_AMR_WB:
1197        case AUDIO_ENCODER_AAC:
1198            audioEncoder = createAudioSource();
1199            break;
1200        default:
1201            LOGE("Unsupported audio encoder: %d", mAudioEncoder);
1202            return UNKNOWN_ERROR;
1203    }
1204
1205    if (audioEncoder == NULL) {
1206        return UNKNOWN_ERROR;
1207    }
1208
1209    writer->addSource(audioEncoder);
1210    return OK;
1211}
1212
1213status_t StagefrightRecorder::setupMPEG4Recording(
1214        bool useSplitCameraSource,
1215        int outputFd,
1216        int32_t videoWidth, int32_t videoHeight,
1217        int32_t videoBitRate,
1218        int32_t *totalBitRate,
1219        sp<MediaWriter> *mediaWriter) {
1220    mediaWriter->clear();
1221    *totalBitRate = 0;
1222    status_t err = OK;
1223    sp<MediaWriter> writer = new MPEG4Writer(outputFd);
1224
1225    // Add audio source first if it exists
1226    if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_LIST_END)) {
1227        err = setupAudioEncoder(writer);
1228        if (err != OK) return err;
1229        *totalBitRate += mAudioBitRate;
1230    }
1231    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1232            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1233
1234        sp<MediaSource> cameraMediaSource;
1235        if (useSplitCameraSource) {
1236            LOGV("Using Split camera source");
1237            cameraMediaSource = mCameraSourceSplitter->createClient();
1238        } else {
1239            sp<CameraSource> cameraSource;
1240            err = setupCameraSource(&cameraSource);
1241            cameraMediaSource = cameraSource;
1242        }
1243        if ((videoWidth != mVideoWidth) || (videoHeight != mVideoHeight)) {
1244            // Use downsampling from the original source.
1245            cameraMediaSource =
1246                new VideoSourceDownSampler(cameraMediaSource, videoWidth, videoHeight);
1247        }
1248        if (err != OK) {
1249            return err;
1250        }
1251
1252        sp<MediaSource> encoder;
1253        err = setupVideoEncoder(cameraMediaSource, videoBitRate, &encoder);
1254        if (err != OK) {
1255            return err;
1256        }
1257
1258        writer->addSource(encoder);
1259        *totalBitRate += videoBitRate;
1260    }
1261
1262    if (mInterleaveDurationUs > 0) {
1263        reinterpret_cast<MPEG4Writer *>(writer.get())->
1264            setInterleaveDuration(mInterleaveDurationUs);
1265    }
1266    if (mMaxFileDurationUs != 0) {
1267        writer->setMaxFileDuration(mMaxFileDurationUs);
1268    }
1269    if (mMaxFileSizeBytes != 0) {
1270        writer->setMaxFileSize(mMaxFileSizeBytes);
1271    }
1272
1273    writer->setListener(mListener);
1274    *mediaWriter = writer;
1275    return OK;
1276}
1277
1278void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate,
1279        sp<MetaData> *meta) {
1280    (*meta)->setInt64(kKeyTime, startTimeUs);
1281    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1282    (*meta)->setInt32(kKeyBitRate, totalBitRate);
1283    (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1284    if (mMovieTimeScale > 0) {
1285        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1286    }
1287    if (mTrackEveryTimeDurationUs > 0) {
1288        (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1289    }
1290    if (mRotationDegrees != 0) {
1291        (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1292    }
1293}
1294
1295status_t StagefrightRecorder::startMPEG4Recording() {
1296    if (mCaptureAuxVideo) {
1297        if (!mCaptureTimeLapse) {
1298            LOGE("Auxiliary video can be captured only in time lapse mode");
1299            return UNKNOWN_ERROR;
1300        }
1301        LOGV("Creating MediaSourceSplitter");
1302        sp<CameraSource> cameraSource;
1303        status_t err = setupCameraSource(&cameraSource);
1304        if (err != OK) {
1305            return err;
1306        }
1307        mCameraSourceSplitter = new MediaSourceSplitter(cameraSource);
1308    } else {
1309        mCameraSourceSplitter = NULL;
1310    }
1311
1312    int32_t totalBitRate;
1313    status_t err = setupMPEG4Recording(mCaptureAuxVideo,
1314            mOutputFd, mVideoWidth, mVideoHeight,
1315            mVideoBitRate, &totalBitRate, &mWriter);
1316    if (err != OK) {
1317        return err;
1318    }
1319
1320    int64_t startTimeUs = systemTime() / 1000;
1321    sp<MetaData> meta = new MetaData;
1322    setupMPEG4MetaData(startTimeUs, totalBitRate, &meta);
1323
1324    err = mWriter->start(meta.get());
1325    if (err != OK) {
1326        return err;
1327    }
1328
1329    if (mCaptureAuxVideo) {
1330        CHECK(mOutputFdAux >= 0);
1331        if (mWriterAux != NULL) {
1332            LOGE("Auxiliary File writer is not avaialble");
1333            return UNKNOWN_ERROR;
1334        }
1335        if ((mAuxVideoWidth > mVideoWidth) || (mAuxVideoHeight > mVideoHeight) ||
1336                ((mAuxVideoWidth == mVideoWidth) && mAuxVideoHeight == mVideoHeight)) {
1337            LOGE("Auxiliary video size (%d x %d) same or larger than the main video size (%d x %d)",
1338                    mAuxVideoWidth, mAuxVideoHeight, mVideoWidth, mVideoHeight);
1339            return UNKNOWN_ERROR;
1340        }
1341
1342        int32_t totalBitrateAux;
1343        err = setupMPEG4Recording(mCaptureAuxVideo,
1344                mOutputFdAux, mAuxVideoWidth, mAuxVideoHeight,
1345                mAuxVideoBitRate, &totalBitrateAux, &mWriterAux);
1346        if (err != OK) {
1347            return err;
1348        }
1349
1350        sp<MetaData> metaAux = new MetaData;
1351        setupMPEG4MetaData(startTimeUs, totalBitrateAux, &metaAux);
1352
1353        return mWriterAux->start(metaAux.get());
1354    }
1355
1356    return OK;
1357}
1358
1359status_t StagefrightRecorder::pause() {
1360    LOGV("pause");
1361    if (mWriter == NULL) {
1362        return UNKNOWN_ERROR;
1363    }
1364    mWriter->pause();
1365
1366    if (mCaptureAuxVideo) {
1367        if (mWriterAux == NULL) {
1368            return UNKNOWN_ERROR;
1369        }
1370        mWriterAux->pause();
1371    }
1372
1373    return OK;
1374}
1375
1376status_t StagefrightRecorder::stop() {
1377    LOGV("stop");
1378    status_t err = OK;
1379
1380    if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) {
1381        mCameraSourceTimeLapse->startQuickReadReturns();
1382        mCameraSourceTimeLapse = NULL;
1383    }
1384
1385    if (mCaptureAuxVideo) {
1386        if (mWriterAux != NULL) {
1387            mWriterAux->stop();
1388            mWriterAux.clear();
1389        }
1390    }
1391
1392    if (mWriter != NULL) {
1393        err = mWriter->stop();
1394        mWriter.clear();
1395    }
1396
1397    if (mOutputFd >= 0) {
1398        ::close(mOutputFd);
1399        mOutputFd = -1;
1400    }
1401
1402    if (mCaptureAuxVideo) {
1403        if (mOutputFdAux >= 0) {
1404            ::close(mOutputFdAux);
1405            mOutputFdAux = -1;
1406        }
1407    }
1408
1409    return err;
1410}
1411
1412status_t StagefrightRecorder::close() {
1413    LOGV("close");
1414    stop();
1415
1416    return OK;
1417}
1418
1419status_t StagefrightRecorder::reset() {
1420    LOGV("reset");
1421    stop();
1422
1423    // No audio or video source by default
1424    mAudioSource = AUDIO_SOURCE_LIST_END;
1425    mVideoSource = VIDEO_SOURCE_LIST_END;
1426
1427    // Default parameters
1428    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1429    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1430    mVideoEncoder  = VIDEO_ENCODER_H263;
1431    mVideoWidth    = 176;
1432    mVideoHeight   = 144;
1433    mAuxVideoWidth    = 176;
1434    mAuxVideoHeight   = 144;
1435    mFrameRate     = -1;
1436    mVideoBitRate  = 192000;
1437    mAuxVideoBitRate = 192000;
1438    mSampleRate    = 8000;
1439    mAudioChannels = 1;
1440    mAudioBitRate  = 12200;
1441    mInterleaveDurationUs = 0;
1442    mIFramesIntervalSec = 1;
1443    mAudioSourceNode = 0;
1444    mUse64BitFileOffset = false;
1445    mMovieTimeScale  = -1;
1446    mAudioTimeScale  = -1;
1447    mVideoTimeScale  = -1;
1448    mCameraId        = 0;
1449    mVideoEncoderProfile = -1;
1450    mVideoEncoderLevel   = -1;
1451    mMaxFileDurationUs = 0;
1452    mMaxFileSizeBytes = 0;
1453    mTrackEveryTimeDurationUs = 0;
1454    mCaptureTimeLapse = false;
1455    mTimeBetweenTimeLapseFrameCaptureUs = -1;
1456    mCaptureAuxVideo = false;
1457    mCameraSourceSplitter = NULL;
1458    mCameraSourceTimeLapse = NULL;
1459    mIsMetaDataStoredInVideoBuffers = false;
1460    mEncoderProfiles = MediaProfiles::getInstance();
1461    mRotationDegrees = 0;
1462
1463    mOutputFd = -1;
1464    mOutputFdAux = -1;
1465
1466    return OK;
1467}
1468
1469status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1470    LOGV("getMaxAmplitude");
1471
1472    if (max == NULL) {
1473        LOGE("Null pointer argument");
1474        return BAD_VALUE;
1475    }
1476
1477    if (mAudioSourceNode != 0) {
1478        *max = mAudioSourceNode->getMaxAmplitude();
1479    } else {
1480        *max = 0;
1481    }
1482
1483    return OK;
1484}
1485
1486status_t StagefrightRecorder::dump(
1487        int fd, const Vector<String16>& args) const {
1488    LOGV("dump");
1489    const size_t SIZE = 256;
1490    char buffer[SIZE];
1491    String8 result;
1492    if (mWriter != 0) {
1493        mWriter->dump(fd, args);
1494    } else {
1495        snprintf(buffer, SIZE, "   No file writer\n");
1496        result.append(buffer);
1497    }
1498    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1499    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1500    result.append(buffer);
1501    snprintf(buffer, SIZE, "   Output file Auxiliary (fd %d):\n", mOutputFdAux);
1502    result.append(buffer);
1503    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1504    result.append(buffer);
1505    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1506    result.append(buffer);
1507    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
1508    result.append(buffer);
1509    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1510    result.append(buffer);
1511    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1512    result.append(buffer);
1513    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1514    result.append(buffer);
1515    snprintf(buffer, SIZE, "   Audio\n");
1516    result.append(buffer);
1517    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1518    result.append(buffer);
1519    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1520    result.append(buffer);
1521    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1522    result.append(buffer);
1523    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1524    result.append(buffer);
1525    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1526    result.append(buffer);
1527    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1528    result.append(buffer);
1529    snprintf(buffer, SIZE, "   Video\n");
1530    result.append(buffer);
1531    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1532    result.append(buffer);
1533    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1534    result.append(buffer);
1535    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1536    result.append(buffer);
1537    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1538    result.append(buffer);
1539    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1540    result.append(buffer);
1541    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1542    result.append(buffer);
1543    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1544    result.append(buffer);
1545    snprintf(buffer, SIZE, "     Aux Frame size (pixels): %dx%d\n", mAuxVideoWidth, mAuxVideoHeight);
1546    result.append(buffer);
1547    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1548    result.append(buffer);
1549    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1550    result.append(buffer);
1551    snprintf(buffer, SIZE, "     Aux Bit rate (bps): %d\n", mAuxVideoBitRate);
1552    result.append(buffer);
1553    ::write(fd, result.string(), result.size());
1554    return OK;
1555}
1556}  // namespace android
1557