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