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