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