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