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