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