StagefrightRecorder.cpp revision 0d1ed381fde5dac12dd84fcf3da66dac46699378
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 here for permission checking
784    mClientUid = IPCThreadState::self()->getCallingUid();
785
786    status_t status = OK;
787
788    switch (mOutputFormat) {
789        case OUTPUT_FORMAT_DEFAULT:
790        case OUTPUT_FORMAT_THREE_GPP:
791        case OUTPUT_FORMAT_MPEG_4:
792        case OUTPUT_FORMAT_WEBM:
793            status = setupMPEG4orWEBMRecording();
794            break;
795
796        case OUTPUT_FORMAT_AMR_NB:
797        case OUTPUT_FORMAT_AMR_WB:
798            status = setupAMRRecording();
799            break;
800
801        case OUTPUT_FORMAT_AAC_ADIF:
802        case OUTPUT_FORMAT_AAC_ADTS:
803            status = setupAACRecording();
804            break;
805
806        case OUTPUT_FORMAT_RTP_AVP:
807            status = setupRTPRecording();
808            break;
809
810        case OUTPUT_FORMAT_MPEG2TS:
811            status = setupMPEG2TSRecording();
812            break;
813
814        default:
815            ALOGE("Unsupported output file format: %d", mOutputFormat);
816            status = UNKNOWN_ERROR;
817            break;
818    }
819
820    return status;
821}
822
823status_t StagefrightRecorder::prepare() {
824    if (mVideoSource == VIDEO_SOURCE_SURFACE) {
825        return prepareInternal();
826    }
827    return OK;
828}
829
830status_t StagefrightRecorder::start() {
831    ALOGV("start");
832    if (mOutputFd < 0) {
833        ALOGE("Output file descriptor is invalid");
834        return INVALID_OPERATION;
835    }
836
837    status_t status = OK;
838
839    if (mVideoSource != VIDEO_SOURCE_SURFACE) {
840        status = prepareInternal();
841        if (status != OK) {
842            return status;
843        }
844    }
845
846    if (mWriter == NULL) {
847        ALOGE("File writer is not avaialble");
848        return UNKNOWN_ERROR;
849    }
850
851    switch (mOutputFormat) {
852        case OUTPUT_FORMAT_DEFAULT:
853        case OUTPUT_FORMAT_THREE_GPP:
854        case OUTPUT_FORMAT_MPEG_4:
855        case OUTPUT_FORMAT_WEBM:
856        {
857            bool isMPEG4 = true;
858            if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
859                isMPEG4 = false;
860            }
861            sp<MetaData> meta = new MetaData;
862            setupMPEG4orWEBMMetaData(&meta);
863            status = mWriter->start(meta.get());
864            break;
865        }
866
867        case OUTPUT_FORMAT_AMR_NB:
868        case OUTPUT_FORMAT_AMR_WB:
869        case OUTPUT_FORMAT_AAC_ADIF:
870        case OUTPUT_FORMAT_AAC_ADTS:
871        case OUTPUT_FORMAT_RTP_AVP:
872        case OUTPUT_FORMAT_MPEG2TS:
873        {
874            status = mWriter->start();
875            break;
876        }
877
878        default:
879        {
880            ALOGE("Unsupported output file format: %d", mOutputFormat);
881            status = UNKNOWN_ERROR;
882            break;
883        }
884    }
885
886    if (status != OK) {
887        mWriter.clear();
888        mWriter = NULL;
889    }
890
891    if ((status == OK) && (!mStarted)) {
892        mStarted = true;
893
894        uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted;
895        if (mAudioSource != AUDIO_SOURCE_CNT) {
896            params |= IMediaPlayerService::kBatteryDataTrackAudio;
897        }
898        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
899            params |= IMediaPlayerService::kBatteryDataTrackVideo;
900        }
901
902        addBatteryData(params);
903    }
904
905    return status;
906}
907
908sp<MediaSource> StagefrightRecorder::createAudioSource() {
909    int32_t sourceSampleRate = mSampleRate;
910
911    if (mCaptureFpsEnable && mCaptureFps >= mFrameRate) {
912        // Upscale the sample rate for slow motion recording.
913        // Fail audio source creation if source sample rate is too high, as it could
914        // cause out-of-memory due to large input buffer size. And audio recording
915        // probably doesn't make sense in the scenario, since the slow-down factor
916        // is probably huge (eg. mSampleRate=48K, mCaptureFps=240, mFrameRate=1).
917        const static int32_t SAMPLE_RATE_HZ_MAX = 192000;
918        sourceSampleRate =
919                (mSampleRate * mCaptureFps + mFrameRate / 2) / mFrameRate;
920        if (sourceSampleRate < mSampleRate || sourceSampleRate > SAMPLE_RATE_HZ_MAX) {
921            ALOGE("source sample rate out of range! "
922                    "(mSampleRate %d, mCaptureFps %.2f, mFrameRate %d",
923                    mSampleRate, mCaptureFps, mFrameRate);
924            return NULL;
925        }
926    }
927
928    sp<AudioSource> audioSource =
929        new AudioSource(
930                mAudioSource,
931                mOpPackageName,
932                sourceSampleRate,
933                mAudioChannels,
934                mSampleRate);
935
936    status_t err = audioSource->initCheck();
937
938    if (err != OK) {
939        ALOGE("audio source is not initialized");
940        return NULL;
941    }
942
943    sp<AMessage> format = new AMessage;
944    switch (mAudioEncoder) {
945        case AUDIO_ENCODER_AMR_NB:
946        case AUDIO_ENCODER_DEFAULT:
947            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_NB);
948            break;
949        case AUDIO_ENCODER_AMR_WB:
950            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_WB);
951            break;
952        case AUDIO_ENCODER_AAC:
953            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
954            format->setInt32("aac-profile", OMX_AUDIO_AACObjectLC);
955            break;
956        case AUDIO_ENCODER_HE_AAC:
957            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
958            format->setInt32("aac-profile", OMX_AUDIO_AACObjectHE);
959            break;
960        case AUDIO_ENCODER_AAC_ELD:
961            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
962            format->setInt32("aac-profile", OMX_AUDIO_AACObjectELD);
963            break;
964
965        default:
966            ALOGE("Unknown audio encoder: %d", mAudioEncoder);
967            return NULL;
968    }
969
970    int32_t maxInputSize;
971    CHECK(audioSource->getFormat()->findInt32(
972                kKeyMaxInputSize, &maxInputSize));
973
974    format->setInt32("max-input-size", maxInputSize);
975    format->setInt32("channel-count", mAudioChannels);
976    format->setInt32("sample-rate", mSampleRate);
977    format->setInt32("bitrate", mAudioBitRate);
978    if (mAudioTimeScale > 0) {
979        format->setInt32("time-scale", mAudioTimeScale);
980    }
981    format->setInt32("priority", 0 /* realtime */);
982
983    sp<MediaSource> audioEncoder =
984            MediaCodecSource::Create(mLooper, format, audioSource);
985    mAudioSourceNode = audioSource;
986
987    if (audioEncoder == NULL) {
988        ALOGE("Failed to create audio encoder");
989    }
990
991    return audioEncoder;
992}
993
994status_t StagefrightRecorder::setupAACRecording() {
995    // FIXME:
996    // Add support for OUTPUT_FORMAT_AAC_ADIF
997    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS);
998
999    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC ||
1000          mAudioEncoder == AUDIO_ENCODER_HE_AAC ||
1001          mAudioEncoder == AUDIO_ENCODER_AAC_ELD);
1002    CHECK(mAudioSource != AUDIO_SOURCE_CNT);
1003
1004    mWriter = new AACWriter(mOutputFd);
1005    return setupRawAudioRecording();
1006}
1007
1008status_t StagefrightRecorder::setupAMRRecording() {
1009    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
1010          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
1011
1012    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
1013        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
1014            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
1015            ALOGE("Invalid encoder %d used for AMRNB recording",
1016                    mAudioEncoder);
1017            return BAD_VALUE;
1018        }
1019    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
1020        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
1021            ALOGE("Invlaid encoder %d used for AMRWB recording",
1022                    mAudioEncoder);
1023            return BAD_VALUE;
1024        }
1025    }
1026
1027    mWriter = new AMRWriter(mOutputFd);
1028    return setupRawAudioRecording();
1029}
1030
1031status_t StagefrightRecorder::setupRawAudioRecording() {
1032    if (mAudioSource >= AUDIO_SOURCE_CNT && mAudioSource != AUDIO_SOURCE_FM_TUNER) {
1033        ALOGE("Invalid audio source: %d", mAudioSource);
1034        return BAD_VALUE;
1035    }
1036
1037    status_t status = BAD_VALUE;
1038    if (OK != (status = checkAudioEncoderCapabilities())) {
1039        return status;
1040    }
1041
1042    sp<MediaSource> audioEncoder = createAudioSource();
1043    if (audioEncoder == NULL) {
1044        return UNKNOWN_ERROR;
1045    }
1046
1047    CHECK(mWriter != 0);
1048    mWriter->addSource(audioEncoder);
1049
1050    if (mMaxFileDurationUs != 0) {
1051        mWriter->setMaxFileDuration(mMaxFileDurationUs);
1052    }
1053    if (mMaxFileSizeBytes != 0) {
1054        mWriter->setMaxFileSize(mMaxFileSizeBytes);
1055    }
1056    mWriter->setListener(mListener);
1057
1058    return OK;
1059}
1060
1061status_t StagefrightRecorder::setupRTPRecording() {
1062    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
1063
1064    if ((mAudioSource != AUDIO_SOURCE_CNT
1065                && mVideoSource != VIDEO_SOURCE_LIST_END)
1066            || (mAudioSource == AUDIO_SOURCE_CNT
1067                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
1068        // Must have exactly one source.
1069        return BAD_VALUE;
1070    }
1071
1072    if (mOutputFd < 0) {
1073        return BAD_VALUE;
1074    }
1075
1076    sp<MediaSource> source;
1077
1078    if (mAudioSource != AUDIO_SOURCE_CNT) {
1079        source = createAudioSource();
1080    } else {
1081        setDefaultVideoEncoderIfNecessary();
1082
1083        sp<MediaSource> mediaSource;
1084        status_t err = setupMediaSource(&mediaSource);
1085        if (err != OK) {
1086            return err;
1087        }
1088
1089        err = setupVideoEncoder(mediaSource, &source);
1090        if (err != OK) {
1091            return err;
1092        }
1093    }
1094
1095    mWriter = new ARTPWriter(mOutputFd);
1096    mWriter->addSource(source);
1097    mWriter->setListener(mListener);
1098
1099    return OK;
1100}
1101
1102status_t StagefrightRecorder::setupMPEG2TSRecording() {
1103    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
1104
1105    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
1106
1107    if (mAudioSource != AUDIO_SOURCE_CNT) {
1108        if (mAudioEncoder != AUDIO_ENCODER_AAC &&
1109            mAudioEncoder != AUDIO_ENCODER_HE_AAC &&
1110            mAudioEncoder != AUDIO_ENCODER_AAC_ELD) {
1111            return ERROR_UNSUPPORTED;
1112        }
1113
1114        status_t err = setupAudioEncoder(writer);
1115
1116        if (err != OK) {
1117            return err;
1118        }
1119    }
1120
1121    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1122        if (mVideoEncoder != VIDEO_ENCODER_H264) {
1123            ALOGE("MPEG2TS recording only supports H.264 encoding!");
1124            return ERROR_UNSUPPORTED;
1125        }
1126
1127        sp<MediaSource> mediaSource;
1128        status_t err = setupMediaSource(&mediaSource);
1129        if (err != OK) {
1130            return err;
1131        }
1132
1133        sp<MediaSource> encoder;
1134        err = setupVideoEncoder(mediaSource, &encoder);
1135
1136        if (err != OK) {
1137            return err;
1138        }
1139
1140        writer->addSource(encoder);
1141    }
1142
1143    if (mMaxFileDurationUs != 0) {
1144        writer->setMaxFileDuration(mMaxFileDurationUs);
1145    }
1146
1147    if (mMaxFileSizeBytes != 0) {
1148        writer->setMaxFileSize(mMaxFileSizeBytes);
1149    }
1150
1151    mWriter = writer;
1152
1153    return OK;
1154}
1155
1156void StagefrightRecorder::clipVideoFrameRate() {
1157    ALOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1158    if (mFrameRate == -1) {
1159        mFrameRate = mEncoderProfiles->getCamcorderProfileParamByName(
1160                "vid.fps", mCameraId, CAMCORDER_QUALITY_LOW);
1161        ALOGW("Using default video fps %d", mFrameRate);
1162    }
1163
1164    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1165                        "enc.vid.fps.min", mVideoEncoder);
1166    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1167                        "enc.vid.fps.max", mVideoEncoder);
1168    if (mFrameRate < minFrameRate && minFrameRate != -1) {
1169        ALOGW("Intended video encoding frame rate (%d fps) is too small"
1170             " and will be set to (%d fps)", mFrameRate, minFrameRate);
1171        mFrameRate = minFrameRate;
1172    } else if (mFrameRate > maxFrameRate && maxFrameRate != -1) {
1173        ALOGW("Intended video encoding frame rate (%d fps) is too large"
1174             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1175        mFrameRate = maxFrameRate;
1176    }
1177}
1178
1179void StagefrightRecorder::clipVideoBitRate() {
1180    ALOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1181    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1182                        "enc.vid.bps.min", mVideoEncoder);
1183    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1184                        "enc.vid.bps.max", mVideoEncoder);
1185    if (mVideoBitRate < minBitRate && minBitRate != -1) {
1186        ALOGW("Intended video encoding bit rate (%d bps) is too small"
1187             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1188        mVideoBitRate = minBitRate;
1189    } else if (mVideoBitRate > maxBitRate && maxBitRate != -1) {
1190        ALOGW("Intended video encoding bit rate (%d bps) is too large"
1191             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1192        mVideoBitRate = maxBitRate;
1193    }
1194}
1195
1196void StagefrightRecorder::clipVideoFrameWidth() {
1197    ALOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1198    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1199                        "enc.vid.width.min", mVideoEncoder);
1200    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1201                        "enc.vid.width.max", mVideoEncoder);
1202    if (mVideoWidth < minFrameWidth && minFrameWidth != -1) {
1203        ALOGW("Intended video encoding frame width (%d) is too small"
1204             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1205        mVideoWidth = minFrameWidth;
1206    } else if (mVideoWidth > maxFrameWidth && maxFrameWidth != -1) {
1207        ALOGW("Intended video encoding frame width (%d) is too large"
1208             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1209        mVideoWidth = maxFrameWidth;
1210    }
1211}
1212
1213status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1214    if (!mCaptureFpsEnable) {
1215        // Dont clip for time lapse capture as encoder will have enough
1216        // time to encode because of slow capture rate of time lapse.
1217        clipVideoBitRate();
1218        clipVideoFrameRate();
1219        clipVideoFrameWidth();
1220        clipVideoFrameHeight();
1221        setDefaultProfileIfNecessary();
1222    }
1223    return OK;
1224}
1225
1226// Set to use AVC baseline profile if the encoding parameters matches
1227// CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service.
1228void StagefrightRecorder::setDefaultProfileIfNecessary() {
1229    ALOGV("setDefaultProfileIfNecessary");
1230
1231    camcorder_quality quality = CAMCORDER_QUALITY_LOW;
1232
1233    int64_t durationUs   = mEncoderProfiles->getCamcorderProfileParamByName(
1234                                "duration", mCameraId, quality) * 1000000LL;
1235
1236    int fileFormat       = mEncoderProfiles->getCamcorderProfileParamByName(
1237                                "file.format", mCameraId, quality);
1238
1239    int videoCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1240                                "vid.codec", mCameraId, quality);
1241
1242    int videoBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1243                                "vid.bps", mCameraId, quality);
1244
1245    int videoFrameRate   = mEncoderProfiles->getCamcorderProfileParamByName(
1246                                "vid.fps", mCameraId, quality);
1247
1248    int videoFrameWidth  = mEncoderProfiles->getCamcorderProfileParamByName(
1249                                "vid.width", mCameraId, quality);
1250
1251    int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName(
1252                                "vid.height", mCameraId, quality);
1253
1254    int audioCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1255                                "aud.codec", mCameraId, quality);
1256
1257    int audioBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1258                                "aud.bps", mCameraId, quality);
1259
1260    int audioSampleRate  = mEncoderProfiles->getCamcorderProfileParamByName(
1261                                "aud.hz", mCameraId, quality);
1262
1263    int audioChannels    = mEncoderProfiles->getCamcorderProfileParamByName(
1264                                "aud.ch", mCameraId, quality);
1265
1266    if (durationUs == mMaxFileDurationUs &&
1267        fileFormat == mOutputFormat &&
1268        videoCodec == mVideoEncoder &&
1269        videoBitRate == mVideoBitRate &&
1270        videoFrameRate == mFrameRate &&
1271        videoFrameWidth == mVideoWidth &&
1272        videoFrameHeight == mVideoHeight &&
1273        audioCodec == mAudioEncoder &&
1274        audioBitRate == mAudioBitRate &&
1275        audioSampleRate == mSampleRate &&
1276        audioChannels == mAudioChannels) {
1277        if (videoCodec == VIDEO_ENCODER_H264) {
1278            ALOGI("Force to use AVC baseline profile");
1279            setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline);
1280            // set 0 for invalid levels - this will be rejected by the
1281            // codec if it cannot handle it during configure
1282            setParamVideoEncoderLevel(ACodec::getAVCLevelFor(
1283                    videoFrameWidth, videoFrameHeight, videoFrameRate, videoBitRate));
1284        }
1285    }
1286}
1287
1288void StagefrightRecorder::setDefaultVideoEncoderIfNecessary() {
1289    if (mVideoEncoder == VIDEO_ENCODER_DEFAULT) {
1290        if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1291            // default to VP8 for WEBM recording
1292            mVideoEncoder = VIDEO_ENCODER_VP8;
1293        } else {
1294            // pick the default encoder for CAMCORDER_QUALITY_LOW
1295            int videoCodec = mEncoderProfiles->getCamcorderProfileParamByName(
1296                    "vid.codec", mCameraId, CAMCORDER_QUALITY_LOW);
1297
1298            if (videoCodec > VIDEO_ENCODER_DEFAULT &&
1299                videoCodec < VIDEO_ENCODER_LIST_END) {
1300                mVideoEncoder = (video_encoder)videoCodec;
1301            } else {
1302                // default to H.264 if camcorder profile not available
1303                mVideoEncoder = VIDEO_ENCODER_H264;
1304            }
1305        }
1306    }
1307}
1308
1309status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1310    clipAudioBitRate();
1311    clipAudioSampleRate();
1312    clipNumberOfAudioChannels();
1313    return OK;
1314}
1315
1316void StagefrightRecorder::clipAudioBitRate() {
1317    ALOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1318
1319    int minAudioBitRate =
1320            mEncoderProfiles->getAudioEncoderParamByName(
1321                "enc.aud.bps.min", mAudioEncoder);
1322    if (minAudioBitRate != -1 && mAudioBitRate < minAudioBitRate) {
1323        ALOGW("Intended audio encoding bit rate (%d) is too small"
1324            " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1325        mAudioBitRate = minAudioBitRate;
1326    }
1327
1328    int maxAudioBitRate =
1329            mEncoderProfiles->getAudioEncoderParamByName(
1330                "enc.aud.bps.max", mAudioEncoder);
1331    if (maxAudioBitRate != -1 && mAudioBitRate > maxAudioBitRate) {
1332        ALOGW("Intended audio encoding bit rate (%d) is too large"
1333            " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1334        mAudioBitRate = maxAudioBitRate;
1335    }
1336}
1337
1338void StagefrightRecorder::clipAudioSampleRate() {
1339    ALOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1340
1341    int minSampleRate =
1342            mEncoderProfiles->getAudioEncoderParamByName(
1343                "enc.aud.hz.min", mAudioEncoder);
1344    if (minSampleRate != -1 && mSampleRate < minSampleRate) {
1345        ALOGW("Intended audio sample rate (%d) is too small"
1346            " and will be set to (%d)", mSampleRate, minSampleRate);
1347        mSampleRate = minSampleRate;
1348    }
1349
1350    int maxSampleRate =
1351            mEncoderProfiles->getAudioEncoderParamByName(
1352                "enc.aud.hz.max", mAudioEncoder);
1353    if (maxSampleRate != -1 && mSampleRate > maxSampleRate) {
1354        ALOGW("Intended audio sample rate (%d) is too large"
1355            " and will be set to (%d)", mSampleRate, maxSampleRate);
1356        mSampleRate = maxSampleRate;
1357    }
1358}
1359
1360void StagefrightRecorder::clipNumberOfAudioChannels() {
1361    ALOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1362
1363    int minChannels =
1364            mEncoderProfiles->getAudioEncoderParamByName(
1365                "enc.aud.ch.min", mAudioEncoder);
1366    if (minChannels != -1 && mAudioChannels < minChannels) {
1367        ALOGW("Intended number of audio channels (%d) is too small"
1368            " and will be set to (%d)", mAudioChannels, minChannels);
1369        mAudioChannels = minChannels;
1370    }
1371
1372    int maxChannels =
1373            mEncoderProfiles->getAudioEncoderParamByName(
1374                "enc.aud.ch.max", mAudioEncoder);
1375    if (maxChannels != -1 && mAudioChannels > maxChannels) {
1376        ALOGW("Intended number of audio channels (%d) is too large"
1377            " and will be set to (%d)", mAudioChannels, maxChannels);
1378        mAudioChannels = maxChannels;
1379    }
1380}
1381
1382void StagefrightRecorder::clipVideoFrameHeight() {
1383    ALOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1384    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1385                        "enc.vid.height.min", mVideoEncoder);
1386    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1387                        "enc.vid.height.max", mVideoEncoder);
1388    if (minFrameHeight != -1 && mVideoHeight < minFrameHeight) {
1389        ALOGW("Intended video encoding frame height (%d) is too small"
1390             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1391        mVideoHeight = minFrameHeight;
1392    } else if (maxFrameHeight != -1 && mVideoHeight > maxFrameHeight) {
1393        ALOGW("Intended video encoding frame height (%d) is too large"
1394             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1395        mVideoHeight = maxFrameHeight;
1396    }
1397}
1398
1399// Set up the appropriate MediaSource depending on the chosen option
1400status_t StagefrightRecorder::setupMediaSource(
1401                      sp<MediaSource> *mediaSource) {
1402    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1403            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1404        sp<CameraSource> cameraSource;
1405        status_t err = setupCameraSource(&cameraSource);
1406        if (err != OK) {
1407            return err;
1408        }
1409        *mediaSource = cameraSource;
1410    } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1411        *mediaSource = NULL;
1412    } else {
1413        return INVALID_OPERATION;
1414    }
1415    return OK;
1416}
1417
1418status_t StagefrightRecorder::setupCameraSource(
1419        sp<CameraSource> *cameraSource) {
1420    status_t err = OK;
1421    if ((err = checkVideoEncoderCapabilities()) != OK) {
1422        return err;
1423    }
1424    Size videoSize;
1425    videoSize.width = mVideoWidth;
1426    videoSize.height = mVideoHeight;
1427    if (mCaptureFpsEnable) {
1428        if (mTimeBetweenCaptureUs < 0) {
1429            ALOGE("Invalid mTimeBetweenTimeLapseFrameCaptureUs value: %lld",
1430                mTimeBetweenCaptureUs);
1431            return BAD_VALUE;
1432        }
1433
1434        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1435                mCamera, mCameraProxy, mCameraId, mClientName, mClientUid,
1436                videoSize, mFrameRate, mPreviewSurface,
1437                mTimeBetweenCaptureUs);
1438        *cameraSource = mCameraSourceTimeLapse;
1439    } else {
1440        *cameraSource = CameraSource::CreateFromCamera(
1441                mCamera, mCameraProxy, mCameraId, mClientName, mClientUid,
1442                videoSize, mFrameRate,
1443                mPreviewSurface);
1444    }
1445    mCamera.clear();
1446    mCameraProxy.clear();
1447    if (*cameraSource == NULL) {
1448        return UNKNOWN_ERROR;
1449    }
1450
1451    if ((*cameraSource)->initCheck() != OK) {
1452        (*cameraSource).clear();
1453        *cameraSource = NULL;
1454        return NO_INIT;
1455    }
1456
1457    // When frame rate is not set, the actual frame rate will be set to
1458    // the current frame rate being used.
1459    if (mFrameRate == -1) {
1460        int32_t frameRate = 0;
1461        CHECK ((*cameraSource)->getFormat()->findInt32(
1462                    kKeyFrameRate, &frameRate));
1463        ALOGI("Frame rate is not explicitly set. Use the current frame "
1464             "rate (%d fps)", frameRate);
1465        mFrameRate = frameRate;
1466    }
1467
1468    CHECK(mFrameRate != -1);
1469
1470    mIsMetaDataStoredInVideoBuffers =
1471        (*cameraSource)->isMetaDataStoredInVideoBuffers();
1472
1473    return OK;
1474}
1475
1476status_t StagefrightRecorder::setupVideoEncoder(
1477        const sp<MediaSource> &cameraSource,
1478        sp<MediaSource> *source) {
1479    source->clear();
1480
1481    sp<AMessage> format = new AMessage();
1482
1483    switch (mVideoEncoder) {
1484        case VIDEO_ENCODER_H263:
1485            format->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
1486            break;
1487
1488        case VIDEO_ENCODER_MPEG_4_SP:
1489            format->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
1490            break;
1491
1492        case VIDEO_ENCODER_H264:
1493            format->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
1494            break;
1495
1496        case VIDEO_ENCODER_VP8:
1497            format->setString("mime", MEDIA_MIMETYPE_VIDEO_VP8);
1498            break;
1499
1500        default:
1501            CHECK(!"Should not be here, unsupported video encoding.");
1502            break;
1503    }
1504
1505    if (cameraSource != NULL) {
1506        sp<MetaData> meta = cameraSource->getFormat();
1507
1508        int32_t width, height, stride, sliceHeight, colorFormat;
1509        CHECK(meta->findInt32(kKeyWidth, &width));
1510        CHECK(meta->findInt32(kKeyHeight, &height));
1511        CHECK(meta->findInt32(kKeyStride, &stride));
1512        CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1513        CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1514
1515        format->setInt32("width", width);
1516        format->setInt32("height", height);
1517        format->setInt32("stride", stride);
1518        format->setInt32("slice-height", sliceHeight);
1519        format->setInt32("color-format", colorFormat);
1520    } else {
1521        format->setInt32("width", mVideoWidth);
1522        format->setInt32("height", mVideoHeight);
1523        format->setInt32("stride", mVideoWidth);
1524        format->setInt32("slice-height", mVideoHeight);
1525        format->setInt32("color-format", OMX_COLOR_FormatAndroidOpaque);
1526
1527        // set up time lapse/slow motion for surface source
1528        if (mCaptureFpsEnable) {
1529            if (mTimeBetweenCaptureUs <= 0) {
1530                ALOGE("Invalid mTimeBetweenCaptureUs value: %lld",
1531                        mTimeBetweenCaptureUs);
1532                return BAD_VALUE;
1533            }
1534            format->setInt64("time-lapse", mTimeBetweenCaptureUs);
1535        }
1536    }
1537
1538    format->setInt32("bitrate", mVideoBitRate);
1539    format->setInt32("frame-rate", mFrameRate);
1540    format->setInt32("i-frame-interval", mIFramesIntervalSec);
1541
1542    if (mVideoTimeScale > 0) {
1543        format->setInt32("time-scale", mVideoTimeScale);
1544    }
1545    if (mVideoEncoderProfile != -1) {
1546        format->setInt32("profile", mVideoEncoderProfile);
1547    }
1548    if (mVideoEncoderLevel != -1) {
1549        format->setInt32("level", mVideoEncoderLevel);
1550    }
1551
1552    format->setInt32("priority", 0 /* realtime */);
1553    if (mCaptureFpsEnable) {
1554        format->setFloat("operating-rate", mCaptureFps);
1555    }
1556
1557    uint32_t flags = 0;
1558    if (mIsMetaDataStoredInVideoBuffers) {
1559        flags |= MediaCodecSource::FLAG_USE_METADATA_INPUT;
1560    }
1561
1562    if (cameraSource == NULL) {
1563        flags |= MediaCodecSource::FLAG_USE_SURFACE_INPUT;
1564    }
1565
1566    sp<MediaCodecSource> encoder = MediaCodecSource::Create(
1567            mLooper, format, cameraSource, mPersistentSurface, flags);
1568    if (encoder == NULL) {
1569        ALOGE("Failed to create video encoder");
1570        // When the encoder fails to be created, we need
1571        // release the camera source due to the camera's lock
1572        // and unlock mechanism.
1573        if (cameraSource != NULL) {
1574            cameraSource->stop();
1575        }
1576        return UNKNOWN_ERROR;
1577    }
1578
1579    if (cameraSource == NULL) {
1580        mGraphicBufferProducer = encoder->getGraphicBufferProducer();
1581    }
1582
1583    *source = encoder;
1584
1585    return OK;
1586}
1587
1588status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1589    status_t status = BAD_VALUE;
1590    if (OK != (status = checkAudioEncoderCapabilities())) {
1591        return status;
1592    }
1593
1594    switch(mAudioEncoder) {
1595        case AUDIO_ENCODER_AMR_NB:
1596        case AUDIO_ENCODER_AMR_WB:
1597        case AUDIO_ENCODER_AAC:
1598        case AUDIO_ENCODER_HE_AAC:
1599        case AUDIO_ENCODER_AAC_ELD:
1600            break;
1601
1602        default:
1603            ALOGE("Unsupported audio encoder: %d", mAudioEncoder);
1604            return UNKNOWN_ERROR;
1605    }
1606
1607    sp<MediaSource> audioEncoder = createAudioSource();
1608    if (audioEncoder == NULL) {
1609        return UNKNOWN_ERROR;
1610    }
1611
1612    writer->addSource(audioEncoder);
1613    return OK;
1614}
1615
1616status_t StagefrightRecorder::setupMPEG4orWEBMRecording() {
1617    mWriter.clear();
1618    mTotalBitRate = 0;
1619
1620    status_t err = OK;
1621    sp<MediaWriter> writer;
1622    sp<MPEG4Writer> mp4writer;
1623    if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1624        writer = new WebmWriter(mOutputFd);
1625    } else {
1626        writer = mp4writer = new MPEG4Writer(mOutputFd);
1627    }
1628
1629    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1630        setDefaultVideoEncoderIfNecessary();
1631
1632        sp<MediaSource> mediaSource;
1633        err = setupMediaSource(&mediaSource);
1634        if (err != OK) {
1635            return err;
1636        }
1637
1638        sp<MediaSource> encoder;
1639        err = setupVideoEncoder(mediaSource, &encoder);
1640        if (err != OK) {
1641            return err;
1642        }
1643
1644        writer->addSource(encoder);
1645        mTotalBitRate += mVideoBitRate;
1646    }
1647
1648    if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1649        // Audio source is added at the end if it exists.
1650        // This help make sure that the "recoding" sound is suppressed for
1651        // camcorder applications in the recorded files.
1652        // TODO Audio source is currently unsupported for webm output; vorbis encoder needed.
1653        // disable audio for time lapse recording
1654        bool disableAudio = mCaptureFpsEnable && mCaptureFps < mFrameRate;
1655        if (!disableAudio && mAudioSource != AUDIO_SOURCE_CNT) {
1656            err = setupAudioEncoder(writer);
1657            if (err != OK) return err;
1658            mTotalBitRate += mAudioBitRate;
1659        }
1660
1661        if (mCaptureFpsEnable) {
1662            mp4writer->setCaptureRate(mCaptureFps);
1663        }
1664
1665        if (mInterleaveDurationUs > 0) {
1666            mp4writer->setInterleaveDuration(mInterleaveDurationUs);
1667        }
1668        if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1669            mp4writer->setGeoData(mLatitudex10000, mLongitudex10000);
1670        }
1671    }
1672    if (mMaxFileDurationUs != 0) {
1673        writer->setMaxFileDuration(mMaxFileDurationUs);
1674    }
1675    if (mMaxFileSizeBytes != 0) {
1676        writer->setMaxFileSize(mMaxFileSizeBytes);
1677    }
1678    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1679            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1680        mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1681    } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1682        // surface source doesn't need large initial delay
1683        mStartTimeOffsetMs = 200;
1684    }
1685    if (mStartTimeOffsetMs > 0) {
1686        writer->setStartTimeOffsetMs(mStartTimeOffsetMs);
1687    }
1688
1689    writer->setListener(mListener);
1690    mWriter = writer;
1691    return OK;
1692}
1693
1694void StagefrightRecorder::setupMPEG4orWEBMMetaData(sp<MetaData> *meta) {
1695    int64_t startTimeUs = systemTime() / 1000;
1696    (*meta)->setInt64(kKeyTime, startTimeUs);
1697    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1698    (*meta)->setInt32(kKeyBitRate, mTotalBitRate);
1699    if (mMovieTimeScale > 0) {
1700        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1701    }
1702    if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1703        (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1704        if (mTrackEveryTimeDurationUs > 0) {
1705            (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1706        }
1707        if (mRotationDegrees != 0) {
1708            (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1709        }
1710    }
1711}
1712
1713status_t StagefrightRecorder::pause() {
1714    ALOGV("pause");
1715    if (mWriter == NULL) {
1716        return UNKNOWN_ERROR;
1717    }
1718    mWriter->pause();
1719
1720    if (mStarted) {
1721        mStarted = false;
1722
1723        uint32_t params = 0;
1724        if (mAudioSource != AUDIO_SOURCE_CNT) {
1725            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1726        }
1727        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1728            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1729        }
1730
1731        addBatteryData(params);
1732    }
1733
1734
1735    return OK;
1736}
1737
1738status_t StagefrightRecorder::stop() {
1739    ALOGV("stop");
1740    status_t err = OK;
1741
1742    if (mCaptureFpsEnable && mCameraSourceTimeLapse != NULL) {
1743        mCameraSourceTimeLapse->startQuickReadReturns();
1744        mCameraSourceTimeLapse = NULL;
1745    }
1746
1747    if (mWriter != NULL) {
1748        err = mWriter->stop();
1749        mWriter.clear();
1750    }
1751
1752    mGraphicBufferProducer.clear();
1753    mPersistentSurface.clear();
1754
1755    if (mOutputFd >= 0) {
1756        ::close(mOutputFd);
1757        mOutputFd = -1;
1758    }
1759
1760    if (mStarted) {
1761        mStarted = false;
1762
1763        uint32_t params = 0;
1764        if (mAudioSource != AUDIO_SOURCE_CNT) {
1765            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1766        }
1767        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1768            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1769        }
1770
1771        addBatteryData(params);
1772    }
1773
1774    return err;
1775}
1776
1777status_t StagefrightRecorder::close() {
1778    ALOGV("close");
1779    stop();
1780
1781    return OK;
1782}
1783
1784status_t StagefrightRecorder::reset() {
1785    ALOGV("reset");
1786    stop();
1787
1788    // No audio or video source by default
1789    mAudioSource = AUDIO_SOURCE_CNT;
1790    mVideoSource = VIDEO_SOURCE_LIST_END;
1791
1792    // Default parameters
1793    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1794    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1795    mVideoEncoder  = VIDEO_ENCODER_DEFAULT;
1796    mVideoWidth    = 176;
1797    mVideoHeight   = 144;
1798    mFrameRate     = -1;
1799    mVideoBitRate  = 192000;
1800    mSampleRate    = 8000;
1801    mAudioChannels = 1;
1802    mAudioBitRate  = 12200;
1803    mInterleaveDurationUs = 0;
1804    mIFramesIntervalSec = 1;
1805    mAudioSourceNode = 0;
1806    mUse64BitFileOffset = false;
1807    mMovieTimeScale  = -1;
1808    mAudioTimeScale  = -1;
1809    mVideoTimeScale  = -1;
1810    mCameraId        = 0;
1811    mStartTimeOffsetMs = -1;
1812    mVideoEncoderProfile = -1;
1813    mVideoEncoderLevel   = -1;
1814    mMaxFileDurationUs = 0;
1815    mMaxFileSizeBytes = 0;
1816    mTrackEveryTimeDurationUs = 0;
1817    mCaptureFpsEnable = false;
1818    mCaptureFps = 0.0f;
1819    mTimeBetweenCaptureUs = -1;
1820    mCameraSourceTimeLapse = NULL;
1821    mIsMetaDataStoredInVideoBuffers = false;
1822    mEncoderProfiles = MediaProfiles::getInstance();
1823    mRotationDegrees = 0;
1824    mLatitudex10000 = -3600000;
1825    mLongitudex10000 = -3600000;
1826    mTotalBitRate = 0;
1827
1828    mOutputFd = -1;
1829
1830    return OK;
1831}
1832
1833status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1834    ALOGV("getMaxAmplitude");
1835
1836    if (max == NULL) {
1837        ALOGE("Null pointer argument");
1838        return BAD_VALUE;
1839    }
1840
1841    if (mAudioSourceNode != 0) {
1842        *max = mAudioSourceNode->getMaxAmplitude();
1843    } else {
1844        *max = 0;
1845    }
1846
1847    return OK;
1848}
1849
1850status_t StagefrightRecorder::dump(
1851        int fd, const Vector<String16>& args) const {
1852    ALOGV("dump");
1853    const size_t SIZE = 256;
1854    char buffer[SIZE];
1855    String8 result;
1856    if (mWriter != 0) {
1857        mWriter->dump(fd, args);
1858    } else {
1859        snprintf(buffer, SIZE, "   No file writer\n");
1860        result.append(buffer);
1861    }
1862    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1863    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1864    result.append(buffer);
1865    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1866    result.append(buffer);
1867    snprintf(buffer, SIZE, "     Max file size (bytes): %" PRId64 "\n", mMaxFileSizeBytes);
1868    result.append(buffer);
1869    snprintf(buffer, SIZE, "     Max file duration (us): %" PRId64 "\n", mMaxFileDurationUs);
1870    result.append(buffer);
1871    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1872    result.append(buffer);
1873    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1874    result.append(buffer);
1875    snprintf(buffer, SIZE, "     Progress notification: %" PRId64 " us\n", mTrackEveryTimeDurationUs);
1876    result.append(buffer);
1877    snprintf(buffer, SIZE, "   Audio\n");
1878    result.append(buffer);
1879    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1880    result.append(buffer);
1881    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1882    result.append(buffer);
1883    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1884    result.append(buffer);
1885    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1886    result.append(buffer);
1887    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1888    result.append(buffer);
1889    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1890    result.append(buffer);
1891    snprintf(buffer, SIZE, "   Video\n");
1892    result.append(buffer);
1893    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1894    result.append(buffer);
1895    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1896    result.append(buffer);
1897    snprintf(buffer, SIZE, "     Start time offset (ms): %d\n", mStartTimeOffsetMs);
1898    result.append(buffer);
1899    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1900    result.append(buffer);
1901    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1902    result.append(buffer);
1903    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1904    result.append(buffer);
1905    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1906    result.append(buffer);
1907    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1908    result.append(buffer);
1909    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1910    result.append(buffer);
1911    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1912    result.append(buffer);
1913    ::write(fd, result.string(), result.size());
1914    return OK;
1915}
1916}  // namespace android
1917