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