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