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