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