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