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