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