StagefrightRecorder.cpp revision 6b0795009b8f53ab771e0074b76381977d016f4b
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 <inttypes.h>
20#include <utils/Log.h>
21
22#include "WebmWriter.h"
23#include "StagefrightRecorder.h"
24
25#include <binder/IPCThreadState.h>
26#include <binder/IServiceManager.h>
27
28#include <media/IMediaPlayerService.h>
29#include <media/stagefright/foundation/ABuffer.h>
30#include <media/stagefright/foundation/ADebug.h>
31#include <media/stagefright/foundation/AMessage.h>
32#include <media/stagefright/foundation/ALooper.h>
33#include <media/stagefright/ACodec.h>
34#include <media/stagefright/AudioSource.h>
35#include <media/stagefright/AMRWriter.h>
36#include <media/stagefright/AACWriter.h>
37#include <media/stagefright/CameraSource.h>
38#include <media/stagefright/CameraSourceTimeLapse.h>
39#include <media/stagefright/MPEG2TSWriter.h>
40#include <media/stagefright/MPEG4Writer.h>
41#include <media/stagefright/MediaDefs.h>
42#include <media/stagefright/MetaData.h>
43#include <media/stagefright/MediaCodecSource.h>
44#include <media/MediaProfiles.h>
45#include <camera/ICamera.h>
46#include <camera/CameraParameters.h>
47
48#include <utils/Errors.h>
49#include <sys/types.h>
50#include <ctype.h>
51#include <unistd.h>
52
53#include <system/audio.h>
54
55#include "ARTPWriter.h"
56
57namespace android {
58
59// To collect the encoder usage for the battery app
60static void addBatteryData(uint32_t params) {
61    sp<IBinder> binder =
62        defaultServiceManager()->getService(String16("media.player"));
63    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
64    CHECK(service.get() != NULL);
65
66    service->addBatteryData(params);
67}
68
69
70StagefrightRecorder::StagefrightRecorder(const String16 &opPackageName)
71    : MediaRecorderBase(opPackageName),
72      mWriter(NULL),
73      mOutputFd(-1),
74      mAudioSource(AUDIO_SOURCE_CNT),
75      mVideoSource(VIDEO_SOURCE_LIST_END),
76      mStarted(false) {
77
78    ALOGV("Constructor");
79    reset();
80}
81
82StagefrightRecorder::~StagefrightRecorder() {
83    ALOGV("Destructor");
84    stop();
85
86    if (mLooper != NULL) {
87        mLooper->stop();
88    }
89}
90
91status_t StagefrightRecorder::init() {
92    ALOGV("init");
93
94    mLooper = new ALooper;
95    mLooper->setName("recorder_looper");
96    mLooper->start();
97
98    return OK;
99}
100
101// The client side of mediaserver asks it to creat a SurfaceMediaSource
102// and return a interface reference. The client side will use that
103// while encoding GL Frames
104sp<IGraphicBufferProducer> StagefrightRecorder::querySurfaceMediaSource() const {
105    ALOGV("Get SurfaceMediaSource");
106    return mGraphicBufferProducer;
107}
108
109status_t StagefrightRecorder::setAudioSource(audio_source_t as) {
110    ALOGV("setAudioSource: %d", as);
111    if (as < AUDIO_SOURCE_DEFAULT ||
112        (as >= AUDIO_SOURCE_CNT && as != AUDIO_SOURCE_FM_TUNER)) {
113        ALOGE("Invalid audio source: %d", as);
114        return BAD_VALUE;
115    }
116
117    if (as == AUDIO_SOURCE_DEFAULT) {
118        mAudioSource = AUDIO_SOURCE_MIC;
119    } else {
120        mAudioSource = as;
121    }
122
123    return OK;
124}
125
126status_t StagefrightRecorder::setVideoSource(video_source vs) {
127    ALOGV("setVideoSource: %d", vs);
128    if (vs < VIDEO_SOURCE_DEFAULT ||
129        vs >= VIDEO_SOURCE_LIST_END) {
130        ALOGE("Invalid video source: %d", vs);
131        return BAD_VALUE;
132    }
133
134    if (vs == VIDEO_SOURCE_DEFAULT) {
135        mVideoSource = VIDEO_SOURCE_CAMERA;
136    } else {
137        mVideoSource = vs;
138    }
139
140    return OK;
141}
142
143status_t StagefrightRecorder::setOutputFormat(output_format of) {
144    ALOGV("setOutputFormat: %d", of);
145    if (of < OUTPUT_FORMAT_DEFAULT ||
146        of >= OUTPUT_FORMAT_LIST_END) {
147        ALOGE("Invalid output format: %d", of);
148        return BAD_VALUE;
149    }
150
151    if (of == OUTPUT_FORMAT_DEFAULT) {
152        mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
153    } else {
154        mOutputFormat = of;
155    }
156
157    return OK;
158}
159
160status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
161    ALOGV("setAudioEncoder: %d", ae);
162    if (ae < AUDIO_ENCODER_DEFAULT ||
163        ae >= AUDIO_ENCODER_LIST_END) {
164        ALOGE("Invalid audio encoder: %d", ae);
165        return BAD_VALUE;
166    }
167
168    if (ae == AUDIO_ENCODER_DEFAULT) {
169        mAudioEncoder = AUDIO_ENCODER_AMR_NB;
170    } else {
171        mAudioEncoder = ae;
172    }
173
174    return OK;
175}
176
177status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
178    ALOGV("setVideoEncoder: %d", ve);
179    if (ve < VIDEO_ENCODER_DEFAULT ||
180        ve >= VIDEO_ENCODER_LIST_END) {
181        ALOGE("Invalid video encoder: %d", ve);
182        return BAD_VALUE;
183    }
184
185    mVideoEncoder = ve;
186
187    return OK;
188}
189
190status_t StagefrightRecorder::setVideoSize(int width, int height) {
191    ALOGV("setVideoSize: %dx%d", width, height);
192    if (width <= 0 || height <= 0) {
193        ALOGE("Invalid video size: %dx%d", width, height);
194        return BAD_VALUE;
195    }
196
197    // Additional check on the dimension will be performed later
198    mVideoWidth = width;
199    mVideoHeight = height;
200
201    return OK;
202}
203
204status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
205    ALOGV("setVideoFrameRate: %d", frames_per_second);
206    if ((frames_per_second <= 0 && frames_per_second != -1) ||
207        frames_per_second > kMaxHighSpeedFps) {
208        ALOGE("Invalid video frame rate: %d", frames_per_second);
209        return BAD_VALUE;
210    }
211
212    // Additional check on the frame rate will be performed later
213    mFrameRate = frames_per_second;
214
215    return OK;
216}
217
218status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera,
219                                        const sp<ICameraRecordingProxy> &proxy) {
220    ALOGV("setCamera");
221    if (camera == 0) {
222        ALOGE("camera is NULL");
223        return BAD_VALUE;
224    }
225    if (proxy == 0) {
226        ALOGE("camera proxy is NULL");
227        return BAD_VALUE;
228    }
229
230    mCamera = camera;
231    mCameraProxy = proxy;
232    return OK;
233}
234
235status_t StagefrightRecorder::setPreviewSurface(const sp<IGraphicBufferProducer> &surface) {
236    ALOGV("setPreviewSurface: %p", surface.get());
237    mPreviewSurface = surface;
238
239    return OK;
240}
241
242status_t StagefrightRecorder::setInputSurface(
243        const sp<IGraphicBufferConsumer>& surface) {
244    mPersistentSurface = surface;
245
246    return OK;
247}
248
249status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
250    ALOGV("setOutputFile: %d, %lld, %lld", fd, offset, length);
251    // These don't make any sense, do they?
252    CHECK_EQ(offset, 0ll);
253    CHECK_EQ(length, 0ll);
254
255    if (fd < 0) {
256        ALOGE("Invalid file descriptor: %d", fd);
257        return -EBADF;
258    }
259
260    // start with a clean, empty file
261    ftruncate(fd, 0);
262
263    if (mOutputFd >= 0) {
264        ::close(mOutputFd);
265    }
266    mOutputFd = dup(fd);
267
268    return OK;
269}
270
271// Attempt to parse an float literal optionally surrounded by whitespace,
272// returns true on success, false otherwise.
273static bool safe_strtof(const char *s, float *val) {
274    char *end;
275
276    // It is lame, but according to man page, we have to set errno to 0
277    // before calling strtof().
278    errno = 0;
279    *val = strtof(s, &end);
280
281    if (end == s || errno == ERANGE) {
282        return false;
283    }
284
285    // Skip trailing whitespace
286    while (isspace(*end)) {
287        ++end;
288    }
289
290    // For a successful return, the string must contain nothing but a valid
291    // float literal optionally surrounded by whitespace.
292
293    return *end == '\0';
294}
295
296// Attempt to parse an int64 literal optionally surrounded by whitespace,
297// returns true on success, false otherwise.
298static bool safe_strtoi64(const char *s, int64_t *val) {
299    char *end;
300
301    // It is lame, but according to man page, we have to set errno to 0
302    // before calling strtoll().
303    errno = 0;
304    *val = strtoll(s, &end, 10);
305
306    if (end == s || errno == ERANGE) {
307        return false;
308    }
309
310    // Skip trailing whitespace
311    while (isspace(*end)) {
312        ++end;
313    }
314
315    // For a successful return, the string must contain nothing but a valid
316    // int64 literal optionally surrounded by whitespace.
317
318    return *end == '\0';
319}
320
321// Return true if the value is in [0, 0x007FFFFFFF]
322static bool safe_strtoi32(const char *s, int32_t *val) {
323    int64_t temp;
324    if (safe_strtoi64(s, &temp)) {
325        if (temp >= 0 && temp <= 0x007FFFFFFF) {
326            *val = static_cast<int32_t>(temp);
327            return true;
328        }
329    }
330    return false;
331}
332
333// Trim both leading and trailing whitespace from the given string.
334static void TrimString(String8 *s) {
335    size_t num_bytes = s->bytes();
336    const char *data = s->string();
337
338    size_t leading_space = 0;
339    while (leading_space < num_bytes && isspace(data[leading_space])) {
340        ++leading_space;
341    }
342
343    size_t i = num_bytes;
344    while (i > leading_space && isspace(data[i - 1])) {
345        --i;
346    }
347
348    s->setTo(String8(&data[leading_space], i - leading_space));
349}
350
351status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
352    ALOGV("setParamAudioSamplingRate: %d", sampleRate);
353    if (sampleRate <= 0) {
354        ALOGE("Invalid audio sampling rate: %d", sampleRate);
355        return BAD_VALUE;
356    }
357
358    // Additional check on the sample rate will be performed later.
359    mSampleRate = sampleRate;
360    return OK;
361}
362
363status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
364    ALOGV("setParamAudioNumberOfChannels: %d", channels);
365    if (channels <= 0 || channels >= 3) {
366        ALOGE("Invalid number of audio channels: %d", channels);
367        return BAD_VALUE;
368    }
369
370    // Additional check on the number of channels will be performed later.
371    mAudioChannels = channels;
372    return OK;
373}
374
375status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
376    ALOGV("setParamAudioEncodingBitRate: %d", bitRate);
377    if (bitRate <= 0) {
378        ALOGE("Invalid audio encoding bit rate: %d", bitRate);
379        return BAD_VALUE;
380    }
381
382    // The target bit rate may not be exactly the same as the requested.
383    // It depends on many factors, such as rate control, and the bit rate
384    // range that a specific encoder supports. The mismatch between the
385    // the target and requested bit rate will NOT be treated as an error.
386    mAudioBitRate = bitRate;
387    return OK;
388}
389
390status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
391    ALOGV("setParamVideoEncodingBitRate: %d", bitRate);
392    if (bitRate <= 0) {
393        ALOGE("Invalid video encoding bit rate: %d", bitRate);
394        return BAD_VALUE;
395    }
396
397    // The target bit rate may not be exactly the same as the requested.
398    // It depends on many factors, such as rate control, and the bit rate
399    // range that a specific encoder supports. The mismatch between the
400    // the target and requested bit rate will NOT be treated as an error.
401    mVideoBitRate = bitRate;
402    return OK;
403}
404
405// Always rotate clockwise, and only support 0, 90, 180 and 270 for now.
406status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) {
407    ALOGV("setParamVideoRotation: %d", degrees);
408    if (degrees < 0 || degrees % 90 != 0) {
409        ALOGE("Unsupported video rotation angle: %d", degrees);
410        return BAD_VALUE;
411    }
412    mRotationDegrees = degrees % 360;
413    return OK;
414}
415
416status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
417    ALOGV("setParamMaxFileDurationUs: %lld us", timeUs);
418
419    // This is meant for backward compatibility for MediaRecorder.java
420    if (timeUs <= 0) {
421        ALOGW("Max file duration is not positive: %lld us. Disabling duration limit.", timeUs);
422        timeUs = 0; // Disable the duration limit for zero or negative values.
423    } else if (timeUs <= 100000LL) {  // XXX: 100 milli-seconds
424        ALOGE("Max file duration is too short: %lld us", timeUs);
425        return BAD_VALUE;
426    }
427
428    if (timeUs <= 15 * 1000000LL) {
429        ALOGW("Target duration (%lld us) too short to be respected", timeUs);
430    }
431    mMaxFileDurationUs = timeUs;
432    return OK;
433}
434
435status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
436    ALOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
437
438    // This is meant for backward compatibility for MediaRecorder.java
439    if (bytes <= 0) {
440        ALOGW("Max file size is not positive: %lld bytes. "
441             "Disabling file size limit.", bytes);
442        bytes = 0; // Disable the file size limit for zero or negative values.
443    } else if (bytes <= 1024) {  // XXX: 1 kB
444        ALOGE("Max file size is too small: %lld bytes", bytes);
445        return BAD_VALUE;
446    }
447
448    if (bytes <= 100 * 1024) {
449        ALOGW("Target file size (%lld bytes) is too small to be respected", bytes);
450    }
451
452    mMaxFileSizeBytes = bytes;
453    return OK;
454}
455
456status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
457    ALOGV("setParamInterleaveDuration: %d", durationUs);
458    if (durationUs <= 500000) {           //  500 ms
459        // If interleave duration is too small, it is very inefficient to do
460        // interleaving since the metadata overhead will count for a significant
461        // portion of the saved contents
462        ALOGE("Audio/video interleave duration is too small: %d us", durationUs);
463        return BAD_VALUE;
464    } else if (durationUs >= 10000000) {  // 10 seconds
465        // If interleaving duration is too large, it can cause the recording
466        // session to use too much memory since we have to save the output
467        // data before we write them out
468        ALOGE("Audio/video interleave duration is too large: %d us", durationUs);
469        return BAD_VALUE;
470    }
471    mInterleaveDurationUs = durationUs;
472    return OK;
473}
474
475// If seconds <  0, only the first frame is I frame, and rest are all P frames
476// If seconds == 0, all frames are encoded as I frames. No P frames
477// If seconds >  0, it is the time spacing (seconds) between 2 neighboring I frames
478status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) {
479    ALOGV("setParamVideoIFramesInterval: %d seconds", seconds);
480    mIFramesIntervalSec = seconds;
481    return OK;
482}
483
484status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
485    ALOGV("setParam64BitFileOffset: %s",
486        use64Bit? "use 64 bit file offset": "use 32 bit file offset");
487    mUse64BitFileOffset = use64Bit;
488    return OK;
489}
490
491status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
492    ALOGV("setParamVideoCameraId: %d", cameraId);
493    if (cameraId < 0) {
494        return BAD_VALUE;
495    }
496    mCameraId = cameraId;
497    return OK;
498}
499
500status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
501    ALOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
502    if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
503        ALOGE("Tracking time duration too short: %lld us", timeDurationUs);
504        return BAD_VALUE;
505    }
506    mTrackEveryTimeDurationUs = timeDurationUs;
507    return OK;
508}
509
510status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) {
511    ALOGV("setParamVideoEncoderProfile: %d", profile);
512
513    // Additional check will be done later when we load the encoder.
514    // For now, we are accepting values defined in OpenMAX IL.
515    mVideoEncoderProfile = profile;
516    return OK;
517}
518
519status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) {
520    ALOGV("setParamVideoEncoderLevel: %d", level);
521
522    // Additional check will be done later when we load the encoder.
523    // For now, we are accepting values defined in OpenMAX IL.
524    mVideoEncoderLevel = level;
525    return OK;
526}
527
528status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) {
529    ALOGV("setParamMovieTimeScale: %d", timeScale);
530
531    // The range is set to be the same as the audio's time scale range
532    // since audio's time scale has a wider range.
533    if (timeScale < 600 || timeScale > 96000) {
534        ALOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
535        return BAD_VALUE;
536    }
537    mMovieTimeScale = timeScale;
538    return OK;
539}
540
541status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) {
542    ALOGV("setParamVideoTimeScale: %d", timeScale);
543
544    // 60000 is chosen to make sure that each video frame from a 60-fps
545    // video has 1000 ticks.
546    if (timeScale < 600 || timeScale > 60000) {
547        ALOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
548        return BAD_VALUE;
549    }
550    mVideoTimeScale = timeScale;
551    return OK;
552}
553
554status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) {
555    ALOGV("setParamAudioTimeScale: %d", timeScale);
556
557    // 96000 Hz is the highest sampling rate support in AAC.
558    if (timeScale < 600 || timeScale > 96000) {
559        ALOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
560        return BAD_VALUE;
561    }
562    mAudioTimeScale = timeScale;
563    return OK;
564}
565
566status_t StagefrightRecorder::setParamCaptureFpsEnable(int32_t captureFpsEnable) {
567    ALOGV("setParamCaptureFpsEnable: %d", captureFpsEnable);
568
569    if(captureFpsEnable == 0) {
570        mCaptureFpsEnable = false;
571    } else if (captureFpsEnable == 1) {
572        mCaptureFpsEnable = true;
573    } else {
574        return BAD_VALUE;
575    }
576    return OK;
577}
578
579status_t StagefrightRecorder::setParamCaptureFps(float fps) {
580    ALOGV("setParamCaptureFps: %.2f", fps);
581
582    int64_t timeUs = (int64_t) (1000000.0 / fps + 0.5f);
583
584    // Not allowing time more than a day
585    if (timeUs <= 0 || timeUs > 86400*1E6) {
586        ALOGE("Time between frame capture (%lld) is out of range [0, 1 Day]", timeUs);
587        return BAD_VALUE;
588    }
589
590    mCaptureFps = fps;
591    mTimeBetweenCaptureUs = timeUs;
592    return OK;
593}
594
595status_t StagefrightRecorder::setParamGeoDataLongitude(
596    int64_t longitudex10000) {
597
598    if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
599        return BAD_VALUE;
600    }
601    mLongitudex10000 = longitudex10000;
602    return OK;
603}
604
605status_t StagefrightRecorder::setParamGeoDataLatitude(
606    int64_t latitudex10000) {
607
608    if (latitudex10000 > 900000 || latitudex10000 < -900000) {
609        return BAD_VALUE;
610    }
611    mLatitudex10000 = latitudex10000;
612    return OK;
613}
614
615status_t StagefrightRecorder::setParameter(
616        const String8 &key, const String8 &value) {
617    ALOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
618    if (key == "max-duration") {
619        int64_t max_duration_ms;
620        if (safe_strtoi64(value.string(), &max_duration_ms)) {
621            return setParamMaxFileDurationUs(1000LL * max_duration_ms);
622        }
623    } else if (key == "max-filesize") {
624        int64_t max_filesize_bytes;
625        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
626            return setParamMaxFileSizeBytes(max_filesize_bytes);
627        }
628    } else if (key == "interleave-duration-us") {
629        int32_t durationUs;
630        if (safe_strtoi32(value.string(), &durationUs)) {
631            return setParamInterleaveDuration(durationUs);
632        }
633    } else if (key == "param-movie-time-scale") {
634        int32_t timeScale;
635        if (safe_strtoi32(value.string(), &timeScale)) {
636            return setParamMovieTimeScale(timeScale);
637        }
638    } else if (key == "param-use-64bit-offset") {
639        int32_t use64BitOffset;
640        if (safe_strtoi32(value.string(), &use64BitOffset)) {
641            return setParam64BitFileOffset(use64BitOffset != 0);
642        }
643    } else if (key == "param-geotag-longitude") {
644        int64_t longitudex10000;
645        if (safe_strtoi64(value.string(), &longitudex10000)) {
646            return setParamGeoDataLongitude(longitudex10000);
647        }
648    } else if (key == "param-geotag-latitude") {
649        int64_t latitudex10000;
650        if (safe_strtoi64(value.string(), &latitudex10000)) {
651            return setParamGeoDataLatitude(latitudex10000);
652        }
653    } else if (key == "param-track-time-status") {
654        int64_t timeDurationUs;
655        if (safe_strtoi64(value.string(), &timeDurationUs)) {
656            return setParamTrackTimeStatus(timeDurationUs);
657        }
658    } else if (key == "audio-param-sampling-rate") {
659        int32_t sampling_rate;
660        if (safe_strtoi32(value.string(), &sampling_rate)) {
661            return setParamAudioSamplingRate(sampling_rate);
662        }
663    } else if (key == "audio-param-number-of-channels") {
664        int32_t number_of_channels;
665        if (safe_strtoi32(value.string(), &number_of_channels)) {
666            return setParamAudioNumberOfChannels(number_of_channels);
667        }
668    } else if (key == "audio-param-encoding-bitrate") {
669        int32_t audio_bitrate;
670        if (safe_strtoi32(value.string(), &audio_bitrate)) {
671            return setParamAudioEncodingBitRate(audio_bitrate);
672        }
673    } else if (key == "audio-param-time-scale") {
674        int32_t timeScale;
675        if (safe_strtoi32(value.string(), &timeScale)) {
676            return setParamAudioTimeScale(timeScale);
677        }
678    } else if (key == "video-param-encoding-bitrate") {
679        int32_t video_bitrate;
680        if (safe_strtoi32(value.string(), &video_bitrate)) {
681            return setParamVideoEncodingBitRate(video_bitrate);
682        }
683    } else if (key == "video-param-rotation-angle-degrees") {
684        int32_t degrees;
685        if (safe_strtoi32(value.string(), &degrees)) {
686            return setParamVideoRotation(degrees);
687        }
688    } else if (key == "video-param-i-frames-interval") {
689        int32_t seconds;
690        if (safe_strtoi32(value.string(), &seconds)) {
691            return setParamVideoIFramesInterval(seconds);
692        }
693    } else if (key == "video-param-encoder-profile") {
694        int32_t profile;
695        if (safe_strtoi32(value.string(), &profile)) {
696            return setParamVideoEncoderProfile(profile);
697        }
698    } else if (key == "video-param-encoder-level") {
699        int32_t level;
700        if (safe_strtoi32(value.string(), &level)) {
701            return setParamVideoEncoderLevel(level);
702        }
703    } else if (key == "video-param-camera-id") {
704        int32_t cameraId;
705        if (safe_strtoi32(value.string(), &cameraId)) {
706            return setParamVideoCameraId(cameraId);
707        }
708    } else if (key == "video-param-time-scale") {
709        int32_t timeScale;
710        if (safe_strtoi32(value.string(), &timeScale)) {
711            return setParamVideoTimeScale(timeScale);
712        }
713    } else if (key == "time-lapse-enable") {
714        int32_t captureFpsEnable;
715        if (safe_strtoi32(value.string(), &captureFpsEnable)) {
716            return setParamCaptureFpsEnable(captureFpsEnable);
717        }
718    } else if (key == "time-lapse-fps") {
719        float fps;
720        if (safe_strtof(value.string(), &fps)) {
721            return setParamCaptureFps(fps);
722        }
723    } else {
724        ALOGE("setParameter: failed to find key %s", key.string());
725    }
726    return BAD_VALUE;
727}
728
729status_t StagefrightRecorder::setParameters(const String8 &params) {
730    ALOGV("setParameters: %s", params.string());
731    const char *cparams = params.string();
732    const char *key_start = cparams;
733    for (;;) {
734        const char *equal_pos = strchr(key_start, '=');
735        if (equal_pos == NULL) {
736            ALOGE("Parameters %s miss a value", cparams);
737            return BAD_VALUE;
738        }
739        String8 key(key_start, equal_pos - key_start);
740        TrimString(&key);
741        if (key.length() == 0) {
742            ALOGE("Parameters %s contains an empty key", cparams);
743            return BAD_VALUE;
744        }
745        const char *value_start = equal_pos + 1;
746        const char *semicolon_pos = strchr(value_start, ';');
747        String8 value;
748        if (semicolon_pos == NULL) {
749            value.setTo(value_start);
750        } else {
751            value.setTo(value_start, semicolon_pos - value_start);
752        }
753        if (setParameter(key, value) != OK) {
754            return BAD_VALUE;
755        }
756        if (semicolon_pos == NULL) {
757            break;  // Reaches the end
758        }
759        key_start = semicolon_pos + 1;
760    }
761    return OK;
762}
763
764status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
765    mListener = listener;
766
767    return OK;
768}
769
770status_t StagefrightRecorder::setClientName(const String16& clientName) {
771    mClientName = clientName;
772
773    return OK;
774}
775
776status_t StagefrightRecorder::prepareInternal() {
777    ALOGV("prepare");
778    if (mOutputFd < 0) {
779        ALOGE("Output file descriptor is invalid");
780        return INVALID_OPERATION;
781    }
782
783    // Get UID and PID here for permission checking
784    mClientUid = IPCThreadState::self()->getCallingUid();
785    mClientPid = IPCThreadState::self()->getCallingPid();
786
787    status_t status = OK;
788
789    switch (mOutputFormat) {
790        case OUTPUT_FORMAT_DEFAULT:
791        case OUTPUT_FORMAT_THREE_GPP:
792        case OUTPUT_FORMAT_MPEG_4:
793        case OUTPUT_FORMAT_WEBM:
794            status = setupMPEG4orWEBMRecording();
795            break;
796
797        case OUTPUT_FORMAT_AMR_NB:
798        case OUTPUT_FORMAT_AMR_WB:
799            status = setupAMRRecording();
800            break;
801
802        case OUTPUT_FORMAT_AAC_ADIF:
803        case OUTPUT_FORMAT_AAC_ADTS:
804            status = setupAACRecording();
805            break;
806
807        case OUTPUT_FORMAT_RTP_AVP:
808            status = setupRTPRecording();
809            break;
810
811        case OUTPUT_FORMAT_MPEG2TS:
812            status = setupMPEG2TSRecording();
813            break;
814
815        default:
816            ALOGE("Unsupported output file format: %d", mOutputFormat);
817            status = UNKNOWN_ERROR;
818            break;
819    }
820
821    return status;
822}
823
824status_t StagefrightRecorder::prepare() {
825    if (mVideoSource == VIDEO_SOURCE_SURFACE) {
826        return prepareInternal();
827    }
828    return OK;
829}
830
831status_t StagefrightRecorder::start() {
832    ALOGV("start");
833    if (mOutputFd < 0) {
834        ALOGE("Output file descriptor is invalid");
835        return INVALID_OPERATION;
836    }
837
838    status_t status = OK;
839
840    if (mVideoSource != VIDEO_SOURCE_SURFACE) {
841        status = prepareInternal();
842        if (status != OK) {
843            return status;
844        }
845    }
846
847    if (mWriter == NULL) {
848        ALOGE("File writer is not avaialble");
849        return UNKNOWN_ERROR;
850    }
851
852    switch (mOutputFormat) {
853        case OUTPUT_FORMAT_DEFAULT:
854        case OUTPUT_FORMAT_THREE_GPP:
855        case OUTPUT_FORMAT_MPEG_4:
856        case OUTPUT_FORMAT_WEBM:
857        {
858            bool isMPEG4 = true;
859            if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
860                isMPEG4 = false;
861            }
862            sp<MetaData> meta = new MetaData;
863            setupMPEG4orWEBMMetaData(&meta);
864            status = mWriter->start(meta.get());
865            break;
866        }
867
868        case OUTPUT_FORMAT_AMR_NB:
869        case OUTPUT_FORMAT_AMR_WB:
870        case OUTPUT_FORMAT_AAC_ADIF:
871        case OUTPUT_FORMAT_AAC_ADTS:
872        case OUTPUT_FORMAT_RTP_AVP:
873        case OUTPUT_FORMAT_MPEG2TS:
874        {
875            status = mWriter->start();
876            break;
877        }
878
879        default:
880        {
881            ALOGE("Unsupported output file format: %d", mOutputFormat);
882            status = UNKNOWN_ERROR;
883            break;
884        }
885    }
886
887    if (status != OK) {
888        mWriter.clear();
889        mWriter = NULL;
890    }
891
892    if ((status == OK) && (!mStarted)) {
893        mStarted = true;
894
895        uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted;
896        if (mAudioSource != AUDIO_SOURCE_CNT) {
897            params |= IMediaPlayerService::kBatteryDataTrackAudio;
898        }
899        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
900            params |= IMediaPlayerService::kBatteryDataTrackVideo;
901        }
902
903        addBatteryData(params);
904    }
905
906    return status;
907}
908
909sp<MediaCodecSource> StagefrightRecorder::createAudioSource() {
910    int32_t sourceSampleRate = mSampleRate;
911
912    if (mCaptureFpsEnable && mCaptureFps >= mFrameRate) {
913        // Upscale the sample rate for slow motion recording.
914        // Fail audio source creation if source sample rate is too high, as it could
915        // cause out-of-memory due to large input buffer size. And audio recording
916        // probably doesn't make sense in the scenario, since the slow-down factor
917        // is probably huge (eg. mSampleRate=48K, mCaptureFps=240, mFrameRate=1).
918        const static int32_t SAMPLE_RATE_HZ_MAX = 192000;
919        sourceSampleRate =
920                (mSampleRate * mCaptureFps + mFrameRate / 2) / mFrameRate;
921        if (sourceSampleRate < mSampleRate || sourceSampleRate > SAMPLE_RATE_HZ_MAX) {
922            ALOGE("source sample rate out of range! "
923                    "(mSampleRate %d, mCaptureFps %.2f, mFrameRate %d",
924                    mSampleRate, mCaptureFps, mFrameRate);
925            return NULL;
926        }
927    }
928
929    sp<AudioSource> audioSource =
930        new AudioSource(
931                mAudioSource,
932                mOpPackageName,
933                sourceSampleRate,
934                mAudioChannels,
935                mSampleRate);
936
937    status_t err = audioSource->initCheck();
938
939    if (err != OK) {
940        ALOGE("audio source is not initialized");
941        return NULL;
942    }
943
944    sp<AMessage> format = new AMessage;
945    switch (mAudioEncoder) {
946        case AUDIO_ENCODER_AMR_NB:
947        case AUDIO_ENCODER_DEFAULT:
948            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_NB);
949            break;
950        case AUDIO_ENCODER_AMR_WB:
951            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_WB);
952            break;
953        case AUDIO_ENCODER_AAC:
954            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
955            format->setInt32("aac-profile", OMX_AUDIO_AACObjectLC);
956            break;
957        case AUDIO_ENCODER_HE_AAC:
958            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
959            format->setInt32("aac-profile", OMX_AUDIO_AACObjectHE);
960            break;
961        case AUDIO_ENCODER_AAC_ELD:
962            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
963            format->setInt32("aac-profile", OMX_AUDIO_AACObjectELD);
964            break;
965
966        default:
967            ALOGE("Unknown audio encoder: %d", mAudioEncoder);
968            return NULL;
969    }
970
971    int32_t maxInputSize;
972    CHECK(audioSource->getFormat()->findInt32(
973                kKeyMaxInputSize, &maxInputSize));
974
975    format->setInt32("max-input-size", maxInputSize);
976    format->setInt32("channel-count", mAudioChannels);
977    format->setInt32("sample-rate", mSampleRate);
978    format->setInt32("bitrate", mAudioBitRate);
979    if (mAudioTimeScale > 0) {
980        format->setInt32("time-scale", mAudioTimeScale);
981    }
982    format->setInt32("priority", 0 /* realtime */);
983
984    sp<MediaCodecSource> audioEncoder =
985            MediaCodecSource::Create(mLooper, format, audioSource);
986    mAudioSourceNode = audioSource;
987
988    if (audioEncoder == NULL) {
989        ALOGE("Failed to create audio encoder");
990    }
991
992    return audioEncoder;
993}
994
995status_t StagefrightRecorder::setupAACRecording() {
996    // FIXME:
997    // Add support for OUTPUT_FORMAT_AAC_ADIF
998    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS);
999
1000    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC ||
1001          mAudioEncoder == AUDIO_ENCODER_HE_AAC ||
1002          mAudioEncoder == AUDIO_ENCODER_AAC_ELD);
1003    CHECK(mAudioSource != AUDIO_SOURCE_CNT);
1004
1005    mWriter = new AACWriter(mOutputFd);
1006    return setupRawAudioRecording();
1007}
1008
1009status_t StagefrightRecorder::setupAMRRecording() {
1010    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
1011          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
1012
1013    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
1014        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
1015            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
1016            ALOGE("Invalid encoder %d used for AMRNB recording",
1017                    mAudioEncoder);
1018            return BAD_VALUE;
1019        }
1020    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
1021        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
1022            ALOGE("Invlaid encoder %d used for AMRWB recording",
1023                    mAudioEncoder);
1024            return BAD_VALUE;
1025        }
1026    }
1027
1028    mWriter = new AMRWriter(mOutputFd);
1029    return setupRawAudioRecording();
1030}
1031
1032status_t StagefrightRecorder::setupRawAudioRecording() {
1033    if (mAudioSource >= AUDIO_SOURCE_CNT && mAudioSource != AUDIO_SOURCE_FM_TUNER) {
1034        ALOGE("Invalid audio source: %d", mAudioSource);
1035        return BAD_VALUE;
1036    }
1037
1038    status_t status = BAD_VALUE;
1039    if (OK != (status = checkAudioEncoderCapabilities())) {
1040        return status;
1041    }
1042
1043    sp<MediaCodecSource> audioEncoder = createAudioSource();
1044    if (audioEncoder == NULL) {
1045        return UNKNOWN_ERROR;
1046    }
1047
1048    CHECK(mWriter != 0);
1049    mWriter->addSource(audioEncoder);
1050    mAudioEncoderSource = audioEncoder;
1051
1052    if (mMaxFileDurationUs != 0) {
1053        mWriter->setMaxFileDuration(mMaxFileDurationUs);
1054    }
1055    if (mMaxFileSizeBytes != 0) {
1056        mWriter->setMaxFileSize(mMaxFileSizeBytes);
1057    }
1058    mWriter->setListener(mListener);
1059
1060    return OK;
1061}
1062
1063status_t StagefrightRecorder::setupRTPRecording() {
1064    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
1065
1066    if ((mAudioSource != AUDIO_SOURCE_CNT
1067                && mVideoSource != VIDEO_SOURCE_LIST_END)
1068            || (mAudioSource == AUDIO_SOURCE_CNT
1069                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
1070        // Must have exactly one source.
1071        return BAD_VALUE;
1072    }
1073
1074    if (mOutputFd < 0) {
1075        return BAD_VALUE;
1076    }
1077
1078    sp<MediaCodecSource> source;
1079
1080    if (mAudioSource != AUDIO_SOURCE_CNT) {
1081        source = createAudioSource();
1082        mAudioEncoderSource = source;
1083    } else {
1084        setDefaultVideoEncoderIfNecessary();
1085
1086        sp<MediaSource> mediaSource;
1087        status_t err = setupMediaSource(&mediaSource);
1088        if (err != OK) {
1089            return err;
1090        }
1091
1092        err = setupVideoEncoder(mediaSource, &source);
1093        if (err != OK) {
1094            return err;
1095        }
1096        mVideoEncoderSource = source;
1097    }
1098
1099    mWriter = new ARTPWriter(mOutputFd);
1100    mWriter->addSource(source);
1101    mWriter->setListener(mListener);
1102
1103    return OK;
1104}
1105
1106status_t StagefrightRecorder::setupMPEG2TSRecording() {
1107    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
1108
1109    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
1110
1111    if (mAudioSource != AUDIO_SOURCE_CNT) {
1112        if (mAudioEncoder != AUDIO_ENCODER_AAC &&
1113            mAudioEncoder != AUDIO_ENCODER_HE_AAC &&
1114            mAudioEncoder != AUDIO_ENCODER_AAC_ELD) {
1115            return ERROR_UNSUPPORTED;
1116        }
1117
1118        status_t err = setupAudioEncoder(writer);
1119
1120        if (err != OK) {
1121            return err;
1122        }
1123    }
1124
1125    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1126        if (mVideoEncoder != VIDEO_ENCODER_H264) {
1127            ALOGE("MPEG2TS recording only supports H.264 encoding!");
1128            return ERROR_UNSUPPORTED;
1129        }
1130
1131        sp<MediaSource> mediaSource;
1132        status_t err = setupMediaSource(&mediaSource);
1133        if (err != OK) {
1134            return err;
1135        }
1136
1137        sp<MediaCodecSource> encoder;
1138        err = setupVideoEncoder(mediaSource, &encoder);
1139
1140        if (err != OK) {
1141            return err;
1142        }
1143
1144        writer->addSource(encoder);
1145        mVideoEncoderSource = encoder;
1146    }
1147
1148    if (mMaxFileDurationUs != 0) {
1149        writer->setMaxFileDuration(mMaxFileDurationUs);
1150    }
1151
1152    if (mMaxFileSizeBytes != 0) {
1153        writer->setMaxFileSize(mMaxFileSizeBytes);
1154    }
1155
1156    mWriter = writer;
1157
1158    return OK;
1159}
1160
1161void StagefrightRecorder::clipVideoFrameRate() {
1162    ALOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1163    if (mFrameRate == -1) {
1164        mFrameRate = mEncoderProfiles->getCamcorderProfileParamByName(
1165                "vid.fps", mCameraId, CAMCORDER_QUALITY_LOW);
1166        ALOGW("Using default video fps %d", mFrameRate);
1167    }
1168
1169    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1170                        "enc.vid.fps.min", mVideoEncoder);
1171    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1172                        "enc.vid.fps.max", mVideoEncoder);
1173    if (mFrameRate < minFrameRate && minFrameRate != -1) {
1174        ALOGW("Intended video encoding frame rate (%d fps) is too small"
1175             " and will be set to (%d fps)", mFrameRate, minFrameRate);
1176        mFrameRate = minFrameRate;
1177    } else if (mFrameRate > maxFrameRate && maxFrameRate != -1) {
1178        ALOGW("Intended video encoding frame rate (%d fps) is too large"
1179             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1180        mFrameRate = maxFrameRate;
1181    }
1182}
1183
1184void StagefrightRecorder::clipVideoBitRate() {
1185    ALOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1186    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1187                        "enc.vid.bps.min", mVideoEncoder);
1188    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1189                        "enc.vid.bps.max", mVideoEncoder);
1190    if (mVideoBitRate < minBitRate && minBitRate != -1) {
1191        ALOGW("Intended video encoding bit rate (%d bps) is too small"
1192             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1193        mVideoBitRate = minBitRate;
1194    } else if (mVideoBitRate > maxBitRate && maxBitRate != -1) {
1195        ALOGW("Intended video encoding bit rate (%d bps) is too large"
1196             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1197        mVideoBitRate = maxBitRate;
1198    }
1199}
1200
1201void StagefrightRecorder::clipVideoFrameWidth() {
1202    ALOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1203    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1204                        "enc.vid.width.min", mVideoEncoder);
1205    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1206                        "enc.vid.width.max", mVideoEncoder);
1207    if (mVideoWidth < minFrameWidth && minFrameWidth != -1) {
1208        ALOGW("Intended video encoding frame width (%d) is too small"
1209             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1210        mVideoWidth = minFrameWidth;
1211    } else if (mVideoWidth > maxFrameWidth && maxFrameWidth != -1) {
1212        ALOGW("Intended video encoding frame width (%d) is too large"
1213             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1214        mVideoWidth = maxFrameWidth;
1215    }
1216}
1217
1218status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1219    if (!mCaptureFpsEnable) {
1220        // Dont clip for time lapse capture as encoder will have enough
1221        // time to encode because of slow capture rate of time lapse.
1222        clipVideoBitRate();
1223        clipVideoFrameRate();
1224        clipVideoFrameWidth();
1225        clipVideoFrameHeight();
1226        setDefaultProfileIfNecessary();
1227    }
1228    return OK;
1229}
1230
1231// Set to use AVC baseline profile if the encoding parameters matches
1232// CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service.
1233void StagefrightRecorder::setDefaultProfileIfNecessary() {
1234    ALOGV("setDefaultProfileIfNecessary");
1235
1236    camcorder_quality quality = CAMCORDER_QUALITY_LOW;
1237
1238    int64_t durationUs   = mEncoderProfiles->getCamcorderProfileParamByName(
1239                                "duration", mCameraId, quality) * 1000000LL;
1240
1241    int fileFormat       = mEncoderProfiles->getCamcorderProfileParamByName(
1242                                "file.format", mCameraId, quality);
1243
1244    int videoCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1245                                "vid.codec", mCameraId, quality);
1246
1247    int videoBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1248                                "vid.bps", mCameraId, quality);
1249
1250    int videoFrameRate   = mEncoderProfiles->getCamcorderProfileParamByName(
1251                                "vid.fps", mCameraId, quality);
1252
1253    int videoFrameWidth  = mEncoderProfiles->getCamcorderProfileParamByName(
1254                                "vid.width", mCameraId, quality);
1255
1256    int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName(
1257                                "vid.height", mCameraId, quality);
1258
1259    int audioCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1260                                "aud.codec", mCameraId, quality);
1261
1262    int audioBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1263                                "aud.bps", mCameraId, quality);
1264
1265    int audioSampleRate  = mEncoderProfiles->getCamcorderProfileParamByName(
1266                                "aud.hz", mCameraId, quality);
1267
1268    int audioChannels    = mEncoderProfiles->getCamcorderProfileParamByName(
1269                                "aud.ch", mCameraId, quality);
1270
1271    if (durationUs == mMaxFileDurationUs &&
1272        fileFormat == mOutputFormat &&
1273        videoCodec == mVideoEncoder &&
1274        videoBitRate == mVideoBitRate &&
1275        videoFrameRate == mFrameRate &&
1276        videoFrameWidth == mVideoWidth &&
1277        videoFrameHeight == mVideoHeight &&
1278        audioCodec == mAudioEncoder &&
1279        audioBitRate == mAudioBitRate &&
1280        audioSampleRate == mSampleRate &&
1281        audioChannels == mAudioChannels) {
1282        if (videoCodec == VIDEO_ENCODER_H264) {
1283            ALOGI("Force to use AVC baseline profile");
1284            setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline);
1285            // set 0 for invalid levels - this will be rejected by the
1286            // codec if it cannot handle it during configure
1287            setParamVideoEncoderLevel(ACodec::getAVCLevelFor(
1288                    videoFrameWidth, videoFrameHeight, videoFrameRate, videoBitRate));
1289        }
1290    }
1291}
1292
1293void StagefrightRecorder::setDefaultVideoEncoderIfNecessary() {
1294    if (mVideoEncoder == VIDEO_ENCODER_DEFAULT) {
1295        if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1296            // default to VP8 for WEBM recording
1297            mVideoEncoder = VIDEO_ENCODER_VP8;
1298        } else {
1299            // pick the default encoder for CAMCORDER_QUALITY_LOW
1300            int videoCodec = mEncoderProfiles->getCamcorderProfileParamByName(
1301                    "vid.codec", mCameraId, CAMCORDER_QUALITY_LOW);
1302
1303            if (videoCodec > VIDEO_ENCODER_DEFAULT &&
1304                videoCodec < VIDEO_ENCODER_LIST_END) {
1305                mVideoEncoder = (video_encoder)videoCodec;
1306            } else {
1307                // default to H.264 if camcorder profile not available
1308                mVideoEncoder = VIDEO_ENCODER_H264;
1309            }
1310        }
1311    }
1312}
1313
1314status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1315    clipAudioBitRate();
1316    clipAudioSampleRate();
1317    clipNumberOfAudioChannels();
1318    return OK;
1319}
1320
1321void StagefrightRecorder::clipAudioBitRate() {
1322    ALOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1323
1324    int minAudioBitRate =
1325            mEncoderProfiles->getAudioEncoderParamByName(
1326                "enc.aud.bps.min", mAudioEncoder);
1327    if (minAudioBitRate != -1 && mAudioBitRate < minAudioBitRate) {
1328        ALOGW("Intended audio encoding bit rate (%d) is too small"
1329            " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1330        mAudioBitRate = minAudioBitRate;
1331    }
1332
1333    int maxAudioBitRate =
1334            mEncoderProfiles->getAudioEncoderParamByName(
1335                "enc.aud.bps.max", mAudioEncoder);
1336    if (maxAudioBitRate != -1 && mAudioBitRate > maxAudioBitRate) {
1337        ALOGW("Intended audio encoding bit rate (%d) is too large"
1338            " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1339        mAudioBitRate = maxAudioBitRate;
1340    }
1341}
1342
1343void StagefrightRecorder::clipAudioSampleRate() {
1344    ALOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1345
1346    int minSampleRate =
1347            mEncoderProfiles->getAudioEncoderParamByName(
1348                "enc.aud.hz.min", mAudioEncoder);
1349    if (minSampleRate != -1 && mSampleRate < minSampleRate) {
1350        ALOGW("Intended audio sample rate (%d) is too small"
1351            " and will be set to (%d)", mSampleRate, minSampleRate);
1352        mSampleRate = minSampleRate;
1353    }
1354
1355    int maxSampleRate =
1356            mEncoderProfiles->getAudioEncoderParamByName(
1357                "enc.aud.hz.max", mAudioEncoder);
1358    if (maxSampleRate != -1 && mSampleRate > maxSampleRate) {
1359        ALOGW("Intended audio sample rate (%d) is too large"
1360            " and will be set to (%d)", mSampleRate, maxSampleRate);
1361        mSampleRate = maxSampleRate;
1362    }
1363}
1364
1365void StagefrightRecorder::clipNumberOfAudioChannels() {
1366    ALOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1367
1368    int minChannels =
1369            mEncoderProfiles->getAudioEncoderParamByName(
1370                "enc.aud.ch.min", mAudioEncoder);
1371    if (minChannels != -1 && mAudioChannels < minChannels) {
1372        ALOGW("Intended number of audio channels (%d) is too small"
1373            " and will be set to (%d)", mAudioChannels, minChannels);
1374        mAudioChannels = minChannels;
1375    }
1376
1377    int maxChannels =
1378            mEncoderProfiles->getAudioEncoderParamByName(
1379                "enc.aud.ch.max", mAudioEncoder);
1380    if (maxChannels != -1 && mAudioChannels > maxChannels) {
1381        ALOGW("Intended number of audio channels (%d) is too large"
1382            " and will be set to (%d)", mAudioChannels, maxChannels);
1383        mAudioChannels = maxChannels;
1384    }
1385}
1386
1387void StagefrightRecorder::clipVideoFrameHeight() {
1388    ALOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1389    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1390                        "enc.vid.height.min", mVideoEncoder);
1391    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1392                        "enc.vid.height.max", mVideoEncoder);
1393    if (minFrameHeight != -1 && mVideoHeight < minFrameHeight) {
1394        ALOGW("Intended video encoding frame height (%d) is too small"
1395             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1396        mVideoHeight = minFrameHeight;
1397    } else if (maxFrameHeight != -1 && mVideoHeight > maxFrameHeight) {
1398        ALOGW("Intended video encoding frame height (%d) is too large"
1399             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1400        mVideoHeight = maxFrameHeight;
1401    }
1402}
1403
1404// Set up the appropriate MediaSource depending on the chosen option
1405status_t StagefrightRecorder::setupMediaSource(
1406                      sp<MediaSource> *mediaSource) {
1407    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1408            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1409        sp<CameraSource> cameraSource;
1410        status_t err = setupCameraSource(&cameraSource);
1411        if (err != OK) {
1412            return err;
1413        }
1414        *mediaSource = cameraSource;
1415    } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1416        *mediaSource = NULL;
1417    } else {
1418        return INVALID_OPERATION;
1419    }
1420    return OK;
1421}
1422
1423status_t StagefrightRecorder::setupCameraSource(
1424        sp<CameraSource> *cameraSource) {
1425    status_t err = OK;
1426    if ((err = checkVideoEncoderCapabilities()) != OK) {
1427        return err;
1428    }
1429    Size videoSize;
1430    videoSize.width = mVideoWidth;
1431    videoSize.height = mVideoHeight;
1432    if (mCaptureFpsEnable) {
1433        if (mTimeBetweenCaptureUs < 0) {
1434            ALOGE("Invalid mTimeBetweenTimeLapseFrameCaptureUs value: %lld",
1435                mTimeBetweenCaptureUs);
1436            return BAD_VALUE;
1437        }
1438
1439        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1440                mCamera, mCameraProxy, mCameraId, mClientName, mClientUid, mClientPid,
1441                videoSize, mFrameRate, mPreviewSurface,
1442                mTimeBetweenCaptureUs);
1443        *cameraSource = mCameraSourceTimeLapse;
1444    } else {
1445        *cameraSource = CameraSource::CreateFromCamera(
1446                mCamera, mCameraProxy, mCameraId, mClientName, mClientUid, mClientPid,
1447                videoSize, mFrameRate,
1448                mPreviewSurface);
1449    }
1450    mCamera.clear();
1451    mCameraProxy.clear();
1452    if (*cameraSource == NULL) {
1453        return UNKNOWN_ERROR;
1454    }
1455
1456    if ((*cameraSource)->initCheck() != OK) {
1457        (*cameraSource).clear();
1458        *cameraSource = NULL;
1459        return NO_INIT;
1460    }
1461
1462    // When frame rate is not set, the actual frame rate will be set to
1463    // the current frame rate being used.
1464    if (mFrameRate == -1) {
1465        int32_t frameRate = 0;
1466        CHECK ((*cameraSource)->getFormat()->findInt32(
1467                    kKeyFrameRate, &frameRate));
1468        ALOGI("Frame rate is not explicitly set. Use the current frame "
1469             "rate (%d fps)", frameRate);
1470        mFrameRate = frameRate;
1471    }
1472
1473    CHECK(mFrameRate != -1);
1474
1475    mIsMetaDataStoredInVideoBuffers =
1476        (*cameraSource)->isMetaDataStoredInVideoBuffers();
1477
1478    return OK;
1479}
1480
1481status_t StagefrightRecorder::setupVideoEncoder(
1482        sp<MediaSource> cameraSource,
1483        sp<MediaCodecSource> *source) {
1484    source->clear();
1485
1486    sp<AMessage> format = new AMessage();
1487
1488    switch (mVideoEncoder) {
1489        case VIDEO_ENCODER_H263:
1490            format->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
1491            break;
1492
1493        case VIDEO_ENCODER_MPEG_4_SP:
1494            format->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
1495            break;
1496
1497        case VIDEO_ENCODER_H264:
1498            format->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
1499            break;
1500
1501        case VIDEO_ENCODER_VP8:
1502            format->setString("mime", MEDIA_MIMETYPE_VIDEO_VP8);
1503            break;
1504
1505        case VIDEO_ENCODER_HEVC:
1506            format->setString("mime", MEDIA_MIMETYPE_VIDEO_HEVC);
1507            break;
1508
1509        default:
1510            CHECK(!"Should not be here, unsupported video encoding.");
1511            break;
1512    }
1513
1514    if (cameraSource != NULL) {
1515        sp<MetaData> meta = cameraSource->getFormat();
1516
1517        int32_t width, height, stride, sliceHeight, colorFormat;
1518        CHECK(meta->findInt32(kKeyWidth, &width));
1519        CHECK(meta->findInt32(kKeyHeight, &height));
1520        CHECK(meta->findInt32(kKeyStride, &stride));
1521        CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1522        CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1523
1524        format->setInt32("width", width);
1525        format->setInt32("height", height);
1526        format->setInt32("stride", stride);
1527        format->setInt32("slice-height", sliceHeight);
1528        format->setInt32("color-format", colorFormat);
1529    } else {
1530        format->setInt32("width", mVideoWidth);
1531        format->setInt32("height", mVideoHeight);
1532        format->setInt32("stride", mVideoWidth);
1533        format->setInt32("slice-height", mVideoHeight);
1534        format->setInt32("color-format", OMX_COLOR_FormatAndroidOpaque);
1535
1536        // set up time lapse/slow motion for surface source
1537        if (mCaptureFpsEnable) {
1538            if (mTimeBetweenCaptureUs <= 0) {
1539                ALOGE("Invalid mTimeBetweenCaptureUs value: %lld",
1540                        mTimeBetweenCaptureUs);
1541                return BAD_VALUE;
1542            }
1543            format->setInt64("time-lapse", mTimeBetweenCaptureUs);
1544        }
1545    }
1546
1547    format->setInt32("bitrate", mVideoBitRate);
1548    format->setInt32("frame-rate", mFrameRate);
1549    format->setInt32("i-frame-interval", mIFramesIntervalSec);
1550
1551    if (mVideoTimeScale > 0) {
1552        format->setInt32("time-scale", mVideoTimeScale);
1553    }
1554    if (mVideoEncoderProfile != -1) {
1555        format->setInt32("profile", mVideoEncoderProfile);
1556    }
1557    if (mVideoEncoderLevel != -1) {
1558        format->setInt32("level", mVideoEncoderLevel);
1559    }
1560
1561    format->setInt32("priority", 0 /* realtime */);
1562    if (mCaptureFpsEnable) {
1563        format->setFloat("operating-rate", mCaptureFps);
1564    }
1565
1566    uint32_t flags = 0;
1567    if (mIsMetaDataStoredInVideoBuffers) {
1568        flags |= MediaCodecSource::FLAG_USE_METADATA_INPUT;
1569    }
1570
1571    if (cameraSource == NULL) {
1572        flags |= MediaCodecSource::FLAG_USE_SURFACE_INPUT;
1573    }
1574
1575    sp<MediaCodecSource> encoder = MediaCodecSource::Create(
1576            mLooper, format, cameraSource, mPersistentSurface, flags);
1577    if (encoder == NULL) {
1578        ALOGE("Failed to create video encoder");
1579        // When the encoder fails to be created, we need
1580        // release the camera source due to the camera's lock
1581        // and unlock mechanism.
1582        if (cameraSource != NULL) {
1583            cameraSource->stop();
1584        }
1585        return UNKNOWN_ERROR;
1586    }
1587
1588    if (cameraSource == NULL) {
1589        mGraphicBufferProducer = encoder->getGraphicBufferProducer();
1590    }
1591
1592    *source = encoder;
1593
1594    return OK;
1595}
1596
1597status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1598    status_t status = BAD_VALUE;
1599    if (OK != (status = checkAudioEncoderCapabilities())) {
1600        return status;
1601    }
1602
1603    switch(mAudioEncoder) {
1604        case AUDIO_ENCODER_AMR_NB:
1605        case AUDIO_ENCODER_AMR_WB:
1606        case AUDIO_ENCODER_AAC:
1607        case AUDIO_ENCODER_HE_AAC:
1608        case AUDIO_ENCODER_AAC_ELD:
1609            break;
1610
1611        default:
1612            ALOGE("Unsupported audio encoder: %d", mAudioEncoder);
1613            return UNKNOWN_ERROR;
1614    }
1615
1616    sp<MediaCodecSource> audioEncoder = createAudioSource();
1617    if (audioEncoder == NULL) {
1618        return UNKNOWN_ERROR;
1619    }
1620
1621    writer->addSource(audioEncoder);
1622    mAudioEncoderSource = audioEncoder;
1623    return OK;
1624}
1625
1626status_t StagefrightRecorder::setupMPEG4orWEBMRecording() {
1627    mWriter.clear();
1628    mTotalBitRate = 0;
1629
1630    status_t err = OK;
1631    sp<MediaWriter> writer;
1632    sp<MPEG4Writer> mp4writer;
1633    if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1634        writer = new WebmWriter(mOutputFd);
1635    } else {
1636        writer = mp4writer = new MPEG4Writer(mOutputFd);
1637    }
1638
1639    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1640        setDefaultVideoEncoderIfNecessary();
1641
1642        sp<MediaSource> mediaSource;
1643        err = setupMediaSource(&mediaSource);
1644        if (err != OK) {
1645            return err;
1646        }
1647
1648        sp<MediaCodecSource> encoder;
1649        err = setupVideoEncoder(mediaSource, &encoder);
1650        if (err != OK) {
1651            return err;
1652        }
1653
1654        writer->addSource(encoder);
1655        mVideoEncoderSource = encoder;
1656        mTotalBitRate += mVideoBitRate;
1657    }
1658
1659    if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1660        // Audio source is added at the end if it exists.
1661        // This help make sure that the "recoding" sound is suppressed for
1662        // camcorder applications in the recorded files.
1663        // TODO Audio source is currently unsupported for webm output; vorbis encoder needed.
1664        // disable audio for time lapse recording
1665        bool disableAudio = mCaptureFpsEnable && mCaptureFps < mFrameRate;
1666        if (!disableAudio && mAudioSource != AUDIO_SOURCE_CNT) {
1667            err = setupAudioEncoder(writer);
1668            if (err != OK) return err;
1669            mTotalBitRate += mAudioBitRate;
1670        }
1671
1672        if (mCaptureFpsEnable) {
1673            mp4writer->setCaptureRate(mCaptureFps);
1674        }
1675
1676        if (mInterleaveDurationUs > 0) {
1677            mp4writer->setInterleaveDuration(mInterleaveDurationUs);
1678        }
1679        if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1680            mp4writer->setGeoData(mLatitudex10000, mLongitudex10000);
1681        }
1682    }
1683    if (mMaxFileDurationUs != 0) {
1684        writer->setMaxFileDuration(mMaxFileDurationUs);
1685    }
1686    if (mMaxFileSizeBytes != 0) {
1687        writer->setMaxFileSize(mMaxFileSizeBytes);
1688    }
1689    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1690            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1691        mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1692    } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1693        // surface source doesn't need large initial delay
1694        mStartTimeOffsetMs = 200;
1695    }
1696    if (mStartTimeOffsetMs > 0) {
1697        writer->setStartTimeOffsetMs(mStartTimeOffsetMs);
1698    }
1699
1700    writer->setListener(mListener);
1701    mWriter = writer;
1702    return OK;
1703}
1704
1705void StagefrightRecorder::setupMPEG4orWEBMMetaData(sp<MetaData> *meta) {
1706    int64_t startTimeUs = systemTime() / 1000;
1707    (*meta)->setInt64(kKeyTime, startTimeUs);
1708    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1709    (*meta)->setInt32(kKeyBitRate, mTotalBitRate);
1710    if (mMovieTimeScale > 0) {
1711        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1712    }
1713    if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1714        (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1715        if (mTrackEveryTimeDurationUs > 0) {
1716            (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1717        }
1718        if (mRotationDegrees != 0) {
1719            (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1720        }
1721    }
1722}
1723
1724status_t StagefrightRecorder::pause() {
1725    ALOGV("pause");
1726    if (!mStarted) {
1727        return INVALID_OPERATION;
1728    }
1729
1730    // Already paused --- no-op.
1731    if (mPauseStartTimeUs != 0) {
1732        return OK;
1733    }
1734
1735    if (mAudioEncoderSource != NULL) {
1736        mAudioEncoderSource->pause();
1737    }
1738    if (mVideoEncoderSource != NULL) {
1739        mVideoEncoderSource->pause();
1740    }
1741
1742    mPauseStartTimeUs = systemTime() / 1000;
1743
1744    return OK;
1745}
1746
1747status_t StagefrightRecorder::resume() {
1748    ALOGV("resume");
1749    if (!mStarted) {
1750        return INVALID_OPERATION;
1751    }
1752
1753    // Not paused --- no-op.
1754    if (mPauseStartTimeUs == 0) {
1755        return OK;
1756    }
1757
1758    // 30 ms buffer to avoid timestamp overlap
1759    mTotalPausedDurationUs += (systemTime() / 1000) - mPauseStartTimeUs - 30000;
1760    if (mAudioEncoderSource != NULL) {
1761        mAudioEncoderSource->setInputBufferTimeOffset(-mTotalPausedDurationUs);
1762        mAudioEncoderSource->start();
1763    }
1764    if (mVideoEncoderSource != NULL) {
1765        mVideoEncoderSource->setInputBufferTimeOffset(-mTotalPausedDurationUs);
1766        mVideoEncoderSource->start();
1767    }
1768    mPauseStartTimeUs = 0;
1769
1770    return OK;
1771}
1772
1773status_t StagefrightRecorder::stop() {
1774    ALOGV("stop");
1775    status_t err = OK;
1776
1777    if (mCaptureFpsEnable && mCameraSourceTimeLapse != NULL) {
1778        mCameraSourceTimeLapse->startQuickReadReturns();
1779        mCameraSourceTimeLapse = NULL;
1780    }
1781
1782    if (mWriter != NULL) {
1783        err = mWriter->stop();
1784        mWriter.clear();
1785    }
1786    mTotalPausedDurationUs = 0;
1787
1788    mGraphicBufferProducer.clear();
1789    mPersistentSurface.clear();
1790    mAudioEncoderSource.clear();
1791    mVideoEncoderSource.clear();
1792
1793    if (mOutputFd >= 0) {
1794        ::close(mOutputFd);
1795        mOutputFd = -1;
1796    }
1797
1798    if (mStarted) {
1799        mStarted = false;
1800
1801        uint32_t params = 0;
1802        if (mAudioSource != AUDIO_SOURCE_CNT) {
1803            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1804        }
1805        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1806            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1807        }
1808
1809        addBatteryData(params);
1810    }
1811
1812    return err;
1813}
1814
1815status_t StagefrightRecorder::close() {
1816    ALOGV("close");
1817    stop();
1818
1819    return OK;
1820}
1821
1822status_t StagefrightRecorder::reset() {
1823    ALOGV("reset");
1824    stop();
1825
1826    // No audio or video source by default
1827    mAudioSource = AUDIO_SOURCE_CNT;
1828    mVideoSource = VIDEO_SOURCE_LIST_END;
1829
1830    // Default parameters
1831    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1832    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1833    mVideoEncoder  = VIDEO_ENCODER_DEFAULT;
1834    mVideoWidth    = 176;
1835    mVideoHeight   = 144;
1836    mFrameRate     = -1;
1837    mVideoBitRate  = 192000;
1838    mSampleRate    = 8000;
1839    mAudioChannels = 1;
1840    mAudioBitRate  = 12200;
1841    mInterleaveDurationUs = 0;
1842    mIFramesIntervalSec = 1;
1843    mAudioSourceNode = 0;
1844    mUse64BitFileOffset = false;
1845    mMovieTimeScale  = -1;
1846    mAudioTimeScale  = -1;
1847    mVideoTimeScale  = -1;
1848    mCameraId        = 0;
1849    mStartTimeOffsetMs = -1;
1850    mVideoEncoderProfile = -1;
1851    mVideoEncoderLevel   = -1;
1852    mMaxFileDurationUs = 0;
1853    mMaxFileSizeBytes = 0;
1854    mTrackEveryTimeDurationUs = 0;
1855    mCaptureFpsEnable = false;
1856    mCaptureFps = 0.0f;
1857    mTimeBetweenCaptureUs = -1;
1858    mCameraSourceTimeLapse = NULL;
1859    mIsMetaDataStoredInVideoBuffers = false;
1860    mEncoderProfiles = MediaProfiles::getInstance();
1861    mRotationDegrees = 0;
1862    mLatitudex10000 = -3600000;
1863    mLongitudex10000 = -3600000;
1864    mTotalBitRate = 0;
1865
1866    mOutputFd = -1;
1867    mPauseStartTimeUs = 0;
1868
1869    return OK;
1870}
1871
1872status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1873    ALOGV("getMaxAmplitude");
1874
1875    if (max == NULL) {
1876        ALOGE("Null pointer argument");
1877        return BAD_VALUE;
1878    }
1879
1880    if (mAudioSourceNode != 0) {
1881        *max = mAudioSourceNode->getMaxAmplitude();
1882    } else {
1883        *max = 0;
1884    }
1885
1886    return OK;
1887}
1888
1889status_t StagefrightRecorder::dump(
1890        int fd, const Vector<String16>& args) const {
1891    ALOGV("dump");
1892    const size_t SIZE = 256;
1893    char buffer[SIZE];
1894    String8 result;
1895    if (mWriter != 0) {
1896        mWriter->dump(fd, args);
1897    } else {
1898        snprintf(buffer, SIZE, "   No file writer\n");
1899        result.append(buffer);
1900    }
1901    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1902    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1903    result.append(buffer);
1904    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1905    result.append(buffer);
1906    snprintf(buffer, SIZE, "     Max file size (bytes): %" PRId64 "\n", mMaxFileSizeBytes);
1907    result.append(buffer);
1908    snprintf(buffer, SIZE, "     Max file duration (us): %" PRId64 "\n", mMaxFileDurationUs);
1909    result.append(buffer);
1910    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1911    result.append(buffer);
1912    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1913    result.append(buffer);
1914    snprintf(buffer, SIZE, "     Progress notification: %" PRId64 " us\n", mTrackEveryTimeDurationUs);
1915    result.append(buffer);
1916    snprintf(buffer, SIZE, "   Audio\n");
1917    result.append(buffer);
1918    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1919    result.append(buffer);
1920    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1921    result.append(buffer);
1922    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1923    result.append(buffer);
1924    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1925    result.append(buffer);
1926    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1927    result.append(buffer);
1928    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1929    result.append(buffer);
1930    snprintf(buffer, SIZE, "   Video\n");
1931    result.append(buffer);
1932    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1933    result.append(buffer);
1934    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1935    result.append(buffer);
1936    snprintf(buffer, SIZE, "     Start time offset (ms): %d\n", mStartTimeOffsetMs);
1937    result.append(buffer);
1938    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1939    result.append(buffer);
1940    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1941    result.append(buffer);
1942    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1943    result.append(buffer);
1944    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1945    result.append(buffer);
1946    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1947    result.append(buffer);
1948    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1949    result.append(buffer);
1950    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1951    result.append(buffer);
1952    ::write(fd, result.string(), result.size());
1953    return OK;
1954}
1955}  // namespace android
1956