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