StagefrightRecorder.cpp revision 5a4a0a1e4a44b8e48aff8e74df56d37dc6d7129c
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    ALOGV("Recording frameRate: %d captureFps: %f",
824            mFrameRate, mCaptureFps);
825
826    return status;
827}
828
829status_t StagefrightRecorder::prepare() {
830    if (mVideoSource == VIDEO_SOURCE_SURFACE) {
831        return prepareInternal();
832    }
833    return OK;
834}
835
836status_t StagefrightRecorder::start() {
837    ALOGV("start");
838    if (mOutputFd < 0) {
839        ALOGE("Output file descriptor is invalid");
840        return INVALID_OPERATION;
841    }
842
843    status_t status = OK;
844
845    if (mVideoSource != VIDEO_SOURCE_SURFACE) {
846        status = prepareInternal();
847        if (status != OK) {
848            return status;
849        }
850    }
851
852    if (mWriter == NULL) {
853        ALOGE("File writer is not avaialble");
854        return UNKNOWN_ERROR;
855    }
856
857    switch (mOutputFormat) {
858        case OUTPUT_FORMAT_DEFAULT:
859        case OUTPUT_FORMAT_THREE_GPP:
860        case OUTPUT_FORMAT_MPEG_4:
861        case OUTPUT_FORMAT_WEBM:
862        {
863            bool isMPEG4 = true;
864            if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
865                isMPEG4 = false;
866            }
867            sp<MetaData> meta = new MetaData;
868            setupMPEG4orWEBMMetaData(&meta);
869            status = mWriter->start(meta.get());
870            break;
871        }
872
873        case OUTPUT_FORMAT_AMR_NB:
874        case OUTPUT_FORMAT_AMR_WB:
875        case OUTPUT_FORMAT_AAC_ADIF:
876        case OUTPUT_FORMAT_AAC_ADTS:
877        case OUTPUT_FORMAT_RTP_AVP:
878        case OUTPUT_FORMAT_MPEG2TS:
879        {
880            status = mWriter->start();
881            break;
882        }
883
884        default:
885        {
886            ALOGE("Unsupported output file format: %d", mOutputFormat);
887            status = UNKNOWN_ERROR;
888            break;
889        }
890    }
891
892    if (status != OK) {
893        mWriter.clear();
894        mWriter = NULL;
895    }
896
897    if ((status == OK) && (!mStarted)) {
898        mStarted = true;
899
900        uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted;
901        if (mAudioSource != AUDIO_SOURCE_CNT) {
902            params |= IMediaPlayerService::kBatteryDataTrackAudio;
903        }
904        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
905            params |= IMediaPlayerService::kBatteryDataTrackVideo;
906        }
907
908        addBatteryData(params);
909    }
910
911    return status;
912}
913
914sp<MediaCodecSource> StagefrightRecorder::createAudioSource() {
915    int32_t sourceSampleRate = mSampleRate;
916
917    if (mCaptureFpsEnable && mCaptureFps >= mFrameRate) {
918        // Upscale the sample rate for slow motion recording.
919        // Fail audio source creation if source sample rate is too high, as it could
920        // cause out-of-memory due to large input buffer size. And audio recording
921        // probably doesn't make sense in the scenario, since the slow-down factor
922        // is probably huge (eg. mSampleRate=48K, mCaptureFps=240, mFrameRate=1).
923        const static int32_t SAMPLE_RATE_HZ_MAX = 192000;
924        sourceSampleRate =
925                (mSampleRate * mCaptureFps + mFrameRate / 2) / mFrameRate;
926        if (sourceSampleRate < mSampleRate || sourceSampleRate > SAMPLE_RATE_HZ_MAX) {
927            ALOGE("source sample rate out of range! "
928                    "(mSampleRate %d, mCaptureFps %.2f, mFrameRate %d",
929                    mSampleRate, mCaptureFps, mFrameRate);
930            return NULL;
931        }
932    }
933
934    sp<AudioSource> audioSource =
935        new AudioSource(
936                mAudioSource,
937                mOpPackageName,
938                sourceSampleRate,
939                mAudioChannels,
940                mSampleRate,
941                mClientUid,
942                mClientPid);
943
944    status_t err = audioSource->initCheck();
945
946    if (err != OK) {
947        ALOGE("audio source is not initialized");
948        return NULL;
949    }
950
951    sp<AMessage> format = new AMessage;
952    switch (mAudioEncoder) {
953        case AUDIO_ENCODER_AMR_NB:
954        case AUDIO_ENCODER_DEFAULT:
955            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_NB);
956            break;
957        case AUDIO_ENCODER_AMR_WB:
958            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_WB);
959            break;
960        case AUDIO_ENCODER_AAC:
961            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
962            format->setInt32("aac-profile", OMX_AUDIO_AACObjectLC);
963            break;
964        case AUDIO_ENCODER_HE_AAC:
965            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
966            format->setInt32("aac-profile", OMX_AUDIO_AACObjectHE);
967            break;
968        case AUDIO_ENCODER_AAC_ELD:
969            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
970            format->setInt32("aac-profile", OMX_AUDIO_AACObjectELD);
971            break;
972
973        default:
974            ALOGE("Unknown audio encoder: %d", mAudioEncoder);
975            return NULL;
976    }
977
978    int32_t maxInputSize;
979    CHECK(audioSource->getFormat()->findInt32(
980                kKeyMaxInputSize, &maxInputSize));
981
982    format->setInt32("max-input-size", maxInputSize);
983    format->setInt32("channel-count", mAudioChannels);
984    format->setInt32("sample-rate", mSampleRate);
985    format->setInt32("bitrate", mAudioBitRate);
986    if (mAudioTimeScale > 0) {
987        format->setInt32("time-scale", mAudioTimeScale);
988    }
989    format->setInt32("priority", 0 /* realtime */);
990
991    sp<MediaCodecSource> audioEncoder =
992            MediaCodecSource::Create(mLooper, format, audioSource);
993    mAudioSourceNode = audioSource;
994
995    if (audioEncoder == NULL) {
996        ALOGE("Failed to create audio encoder");
997    }
998
999    return audioEncoder;
1000}
1001
1002status_t StagefrightRecorder::setupAACRecording() {
1003    // FIXME:
1004    // Add support for OUTPUT_FORMAT_AAC_ADIF
1005    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS);
1006
1007    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC ||
1008          mAudioEncoder == AUDIO_ENCODER_HE_AAC ||
1009          mAudioEncoder == AUDIO_ENCODER_AAC_ELD);
1010    CHECK(mAudioSource != AUDIO_SOURCE_CNT);
1011
1012    mWriter = new AACWriter(mOutputFd);
1013    return setupRawAudioRecording();
1014}
1015
1016status_t StagefrightRecorder::setupAMRRecording() {
1017    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
1018          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
1019
1020    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
1021        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
1022            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
1023            ALOGE("Invalid encoder %d used for AMRNB recording",
1024                    mAudioEncoder);
1025            return BAD_VALUE;
1026        }
1027    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
1028        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
1029            ALOGE("Invlaid encoder %d used for AMRWB recording",
1030                    mAudioEncoder);
1031            return BAD_VALUE;
1032        }
1033    }
1034
1035    mWriter = new AMRWriter(mOutputFd);
1036    return setupRawAudioRecording();
1037}
1038
1039status_t StagefrightRecorder::setupRawAudioRecording() {
1040    if (mAudioSource >= AUDIO_SOURCE_CNT && mAudioSource != AUDIO_SOURCE_FM_TUNER) {
1041        ALOGE("Invalid audio source: %d", mAudioSource);
1042        return BAD_VALUE;
1043    }
1044
1045    status_t status = BAD_VALUE;
1046    if (OK != (status = checkAudioEncoderCapabilities())) {
1047        return status;
1048    }
1049
1050    sp<MediaCodecSource> audioEncoder = createAudioSource();
1051    if (audioEncoder == NULL) {
1052        return UNKNOWN_ERROR;
1053    }
1054
1055    CHECK(mWriter != 0);
1056    mWriter->addSource(audioEncoder);
1057    mAudioEncoderSource = audioEncoder;
1058
1059    if (mMaxFileDurationUs != 0) {
1060        mWriter->setMaxFileDuration(mMaxFileDurationUs);
1061    }
1062    if (mMaxFileSizeBytes != 0) {
1063        mWriter->setMaxFileSize(mMaxFileSizeBytes);
1064    }
1065    mWriter->setListener(mListener);
1066
1067    return OK;
1068}
1069
1070status_t StagefrightRecorder::setupRTPRecording() {
1071    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
1072
1073    if ((mAudioSource != AUDIO_SOURCE_CNT
1074                && mVideoSource != VIDEO_SOURCE_LIST_END)
1075            || (mAudioSource == AUDIO_SOURCE_CNT
1076                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
1077        // Must have exactly one source.
1078        return BAD_VALUE;
1079    }
1080
1081    if (mOutputFd < 0) {
1082        return BAD_VALUE;
1083    }
1084
1085    sp<MediaCodecSource> source;
1086
1087    if (mAudioSource != AUDIO_SOURCE_CNT) {
1088        source = createAudioSource();
1089        mAudioEncoderSource = source;
1090    } else {
1091        setDefaultVideoEncoderIfNecessary();
1092
1093        sp<MediaSource> mediaSource;
1094        status_t err = setupMediaSource(&mediaSource);
1095        if (err != OK) {
1096            return err;
1097        }
1098
1099        err = setupVideoEncoder(mediaSource, &source);
1100        if (err != OK) {
1101            return err;
1102        }
1103        mVideoEncoderSource = source;
1104    }
1105
1106    mWriter = new ARTPWriter(mOutputFd);
1107    mWriter->addSource(source);
1108    mWriter->setListener(mListener);
1109
1110    return OK;
1111}
1112
1113status_t StagefrightRecorder::setupMPEG2TSRecording() {
1114    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
1115
1116    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
1117
1118    if (mAudioSource != AUDIO_SOURCE_CNT) {
1119        if (mAudioEncoder != AUDIO_ENCODER_AAC &&
1120            mAudioEncoder != AUDIO_ENCODER_HE_AAC &&
1121            mAudioEncoder != AUDIO_ENCODER_AAC_ELD) {
1122            return ERROR_UNSUPPORTED;
1123        }
1124
1125        status_t err = setupAudioEncoder(writer);
1126
1127        if (err != OK) {
1128            return err;
1129        }
1130    }
1131
1132    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1133        if (mVideoEncoder != VIDEO_ENCODER_H264) {
1134            ALOGE("MPEG2TS recording only supports H.264 encoding!");
1135            return ERROR_UNSUPPORTED;
1136        }
1137
1138        sp<MediaSource> mediaSource;
1139        status_t err = setupMediaSource(&mediaSource);
1140        if (err != OK) {
1141            return err;
1142        }
1143
1144        sp<MediaCodecSource> encoder;
1145        err = setupVideoEncoder(mediaSource, &encoder);
1146
1147        if (err != OK) {
1148            return err;
1149        }
1150
1151        writer->addSource(encoder);
1152        mVideoEncoderSource = encoder;
1153    }
1154
1155    if (mMaxFileDurationUs != 0) {
1156        writer->setMaxFileDuration(mMaxFileDurationUs);
1157    }
1158
1159    if (mMaxFileSizeBytes != 0) {
1160        writer->setMaxFileSize(mMaxFileSizeBytes);
1161    }
1162
1163    mWriter = writer;
1164
1165    return OK;
1166}
1167
1168void StagefrightRecorder::clipVideoFrameRate() {
1169    ALOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1170    if (mFrameRate == -1) {
1171        mFrameRate = mEncoderProfiles->getCamcorderProfileParamByName(
1172                "vid.fps", mCameraId, CAMCORDER_QUALITY_LOW);
1173        ALOGW("Using default video fps %d", mFrameRate);
1174    }
1175
1176    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1177                        "enc.vid.fps.min", mVideoEncoder);
1178    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1179                        "enc.vid.fps.max", mVideoEncoder);
1180    if (mFrameRate < minFrameRate && minFrameRate != -1) {
1181        ALOGW("Intended video encoding frame rate (%d fps) is too small"
1182             " and will be set to (%d fps)", mFrameRate, minFrameRate);
1183        mFrameRate = minFrameRate;
1184    } else if (mFrameRate > maxFrameRate && maxFrameRate != -1) {
1185        ALOGW("Intended video encoding frame rate (%d fps) is too large"
1186             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1187        mFrameRate = maxFrameRate;
1188    }
1189}
1190
1191void StagefrightRecorder::clipVideoBitRate() {
1192    ALOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1193    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1194                        "enc.vid.bps.min", mVideoEncoder);
1195    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1196                        "enc.vid.bps.max", mVideoEncoder);
1197    if (mVideoBitRate < minBitRate && minBitRate != -1) {
1198        ALOGW("Intended video encoding bit rate (%d bps) is too small"
1199             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1200        mVideoBitRate = minBitRate;
1201    } else if (mVideoBitRate > maxBitRate && maxBitRate != -1) {
1202        ALOGW("Intended video encoding bit rate (%d bps) is too large"
1203             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1204        mVideoBitRate = maxBitRate;
1205    }
1206}
1207
1208void StagefrightRecorder::clipVideoFrameWidth() {
1209    ALOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1210    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1211                        "enc.vid.width.min", mVideoEncoder);
1212    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1213                        "enc.vid.width.max", mVideoEncoder);
1214    if (mVideoWidth < minFrameWidth && minFrameWidth != -1) {
1215        ALOGW("Intended video encoding frame width (%d) is too small"
1216             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1217        mVideoWidth = minFrameWidth;
1218    } else if (mVideoWidth > maxFrameWidth && maxFrameWidth != -1) {
1219        ALOGW("Intended video encoding frame width (%d) is too large"
1220             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1221        mVideoWidth = maxFrameWidth;
1222    }
1223}
1224
1225status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1226    if (!mCaptureFpsEnable) {
1227        // Dont clip for time lapse capture as encoder will have enough
1228        // time to encode because of slow capture rate of time lapse.
1229        clipVideoBitRate();
1230        clipVideoFrameRate();
1231        clipVideoFrameWidth();
1232        clipVideoFrameHeight();
1233        setDefaultProfileIfNecessary();
1234    }
1235    return OK;
1236}
1237
1238// Set to use AVC baseline profile if the encoding parameters matches
1239// CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service.
1240void StagefrightRecorder::setDefaultProfileIfNecessary() {
1241    ALOGV("setDefaultProfileIfNecessary");
1242
1243    camcorder_quality quality = CAMCORDER_QUALITY_LOW;
1244
1245    int64_t durationUs   = mEncoderProfiles->getCamcorderProfileParamByName(
1246                                "duration", mCameraId, quality) * 1000000LL;
1247
1248    int fileFormat       = mEncoderProfiles->getCamcorderProfileParamByName(
1249                                "file.format", mCameraId, quality);
1250
1251    int videoCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1252                                "vid.codec", mCameraId, quality);
1253
1254    int videoBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1255                                "vid.bps", mCameraId, quality);
1256
1257    int videoFrameRate   = mEncoderProfiles->getCamcorderProfileParamByName(
1258                                "vid.fps", mCameraId, quality);
1259
1260    int videoFrameWidth  = mEncoderProfiles->getCamcorderProfileParamByName(
1261                                "vid.width", mCameraId, quality);
1262
1263    int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName(
1264                                "vid.height", mCameraId, quality);
1265
1266    int audioCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1267                                "aud.codec", mCameraId, quality);
1268
1269    int audioBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1270                                "aud.bps", mCameraId, quality);
1271
1272    int audioSampleRate  = mEncoderProfiles->getCamcorderProfileParamByName(
1273                                "aud.hz", mCameraId, quality);
1274
1275    int audioChannels    = mEncoderProfiles->getCamcorderProfileParamByName(
1276                                "aud.ch", mCameraId, quality);
1277
1278    if (durationUs == mMaxFileDurationUs &&
1279        fileFormat == mOutputFormat &&
1280        videoCodec == mVideoEncoder &&
1281        videoBitRate == mVideoBitRate &&
1282        videoFrameRate == mFrameRate &&
1283        videoFrameWidth == mVideoWidth &&
1284        videoFrameHeight == mVideoHeight &&
1285        audioCodec == mAudioEncoder &&
1286        audioBitRate == mAudioBitRate &&
1287        audioSampleRate == mSampleRate &&
1288        audioChannels == mAudioChannels) {
1289        if (videoCodec == VIDEO_ENCODER_H264) {
1290            ALOGI("Force to use AVC baseline profile");
1291            setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline);
1292            // set 0 for invalid levels - this will be rejected by the
1293            // codec if it cannot handle it during configure
1294            setParamVideoEncoderLevel(ACodec::getAVCLevelFor(
1295                    videoFrameWidth, videoFrameHeight, videoFrameRate, videoBitRate));
1296        }
1297    }
1298}
1299
1300void StagefrightRecorder::setDefaultVideoEncoderIfNecessary() {
1301    if (mVideoEncoder == VIDEO_ENCODER_DEFAULT) {
1302        if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1303            // default to VP8 for WEBM recording
1304            mVideoEncoder = VIDEO_ENCODER_VP8;
1305        } else {
1306            // pick the default encoder for CAMCORDER_QUALITY_LOW
1307            int videoCodec = mEncoderProfiles->getCamcorderProfileParamByName(
1308                    "vid.codec", mCameraId, CAMCORDER_QUALITY_LOW);
1309
1310            if (videoCodec > VIDEO_ENCODER_DEFAULT &&
1311                videoCodec < VIDEO_ENCODER_LIST_END) {
1312                mVideoEncoder = (video_encoder)videoCodec;
1313            } else {
1314                // default to H.264 if camcorder profile not available
1315                mVideoEncoder = VIDEO_ENCODER_H264;
1316            }
1317        }
1318    }
1319}
1320
1321status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1322    clipAudioBitRate();
1323    clipAudioSampleRate();
1324    clipNumberOfAudioChannels();
1325    return OK;
1326}
1327
1328void StagefrightRecorder::clipAudioBitRate() {
1329    ALOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1330
1331    int minAudioBitRate =
1332            mEncoderProfiles->getAudioEncoderParamByName(
1333                "enc.aud.bps.min", mAudioEncoder);
1334    if (minAudioBitRate != -1 && mAudioBitRate < minAudioBitRate) {
1335        ALOGW("Intended audio encoding bit rate (%d) is too small"
1336            " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1337        mAudioBitRate = minAudioBitRate;
1338    }
1339
1340    int maxAudioBitRate =
1341            mEncoderProfiles->getAudioEncoderParamByName(
1342                "enc.aud.bps.max", mAudioEncoder);
1343    if (maxAudioBitRate != -1 && mAudioBitRate > maxAudioBitRate) {
1344        ALOGW("Intended audio encoding bit rate (%d) is too large"
1345            " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1346        mAudioBitRate = maxAudioBitRate;
1347    }
1348}
1349
1350void StagefrightRecorder::clipAudioSampleRate() {
1351    ALOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1352
1353    int minSampleRate =
1354            mEncoderProfiles->getAudioEncoderParamByName(
1355                "enc.aud.hz.min", mAudioEncoder);
1356    if (minSampleRate != -1 && mSampleRate < minSampleRate) {
1357        ALOGW("Intended audio sample rate (%d) is too small"
1358            " and will be set to (%d)", mSampleRate, minSampleRate);
1359        mSampleRate = minSampleRate;
1360    }
1361
1362    int maxSampleRate =
1363            mEncoderProfiles->getAudioEncoderParamByName(
1364                "enc.aud.hz.max", mAudioEncoder);
1365    if (maxSampleRate != -1 && mSampleRate > maxSampleRate) {
1366        ALOGW("Intended audio sample rate (%d) is too large"
1367            " and will be set to (%d)", mSampleRate, maxSampleRate);
1368        mSampleRate = maxSampleRate;
1369    }
1370}
1371
1372void StagefrightRecorder::clipNumberOfAudioChannels() {
1373    ALOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1374
1375    int minChannels =
1376            mEncoderProfiles->getAudioEncoderParamByName(
1377                "enc.aud.ch.min", mAudioEncoder);
1378    if (minChannels != -1 && mAudioChannels < minChannels) {
1379        ALOGW("Intended number of audio channels (%d) is too small"
1380            " and will be set to (%d)", mAudioChannels, minChannels);
1381        mAudioChannels = minChannels;
1382    }
1383
1384    int maxChannels =
1385            mEncoderProfiles->getAudioEncoderParamByName(
1386                "enc.aud.ch.max", mAudioEncoder);
1387    if (maxChannels != -1 && mAudioChannels > maxChannels) {
1388        ALOGW("Intended number of audio channels (%d) is too large"
1389            " and will be set to (%d)", mAudioChannels, maxChannels);
1390        mAudioChannels = maxChannels;
1391    }
1392}
1393
1394void StagefrightRecorder::clipVideoFrameHeight() {
1395    ALOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1396    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1397                        "enc.vid.height.min", mVideoEncoder);
1398    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1399                        "enc.vid.height.max", mVideoEncoder);
1400    if (minFrameHeight != -1 && mVideoHeight < minFrameHeight) {
1401        ALOGW("Intended video encoding frame height (%d) is too small"
1402             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1403        mVideoHeight = minFrameHeight;
1404    } else if (maxFrameHeight != -1 && mVideoHeight > maxFrameHeight) {
1405        ALOGW("Intended video encoding frame height (%d) is too large"
1406             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1407        mVideoHeight = maxFrameHeight;
1408    }
1409}
1410
1411// Set up the appropriate MediaSource depending on the chosen option
1412status_t StagefrightRecorder::setupMediaSource(
1413                      sp<MediaSource> *mediaSource) {
1414    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1415            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1416        sp<CameraSource> cameraSource;
1417        status_t err = setupCameraSource(&cameraSource);
1418        if (err != OK) {
1419            return err;
1420        }
1421        *mediaSource = cameraSource;
1422    } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1423        *mediaSource = NULL;
1424    } else {
1425        return INVALID_OPERATION;
1426    }
1427    return OK;
1428}
1429
1430status_t StagefrightRecorder::setupCameraSource(
1431        sp<CameraSource> *cameraSource) {
1432    status_t err = OK;
1433    if ((err = checkVideoEncoderCapabilities()) != OK) {
1434        return err;
1435    }
1436    Size videoSize;
1437    videoSize.width = mVideoWidth;
1438    videoSize.height = mVideoHeight;
1439    if (mCaptureFpsEnable) {
1440        if (mTimeBetweenCaptureUs < 0) {
1441            ALOGE("Invalid mTimeBetweenTimeLapseFrameCaptureUs value: %lld",
1442                    (long long)mTimeBetweenCaptureUs);
1443            return BAD_VALUE;
1444        }
1445
1446        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1447                mCamera, mCameraProxy, mCameraId, mClientName, mClientUid, mClientPid,
1448                videoSize, mFrameRate, mPreviewSurface,
1449                mTimeBetweenCaptureUs);
1450        *cameraSource = mCameraSourceTimeLapse;
1451    } else {
1452        *cameraSource = CameraSource::CreateFromCamera(
1453                mCamera, mCameraProxy, mCameraId, mClientName, mClientUid, mClientPid,
1454                videoSize, mFrameRate,
1455                mPreviewSurface);
1456    }
1457    mCamera.clear();
1458    mCameraProxy.clear();
1459    if (*cameraSource == NULL) {
1460        return UNKNOWN_ERROR;
1461    }
1462
1463    if ((*cameraSource)->initCheck() != OK) {
1464        (*cameraSource).clear();
1465        *cameraSource = NULL;
1466        return NO_INIT;
1467    }
1468
1469    // When frame rate is not set, the actual frame rate will be set to
1470    // the current frame rate being used.
1471    if (mFrameRate == -1) {
1472        int32_t frameRate = 0;
1473        CHECK ((*cameraSource)->getFormat()->findInt32(
1474                    kKeyFrameRate, &frameRate));
1475        ALOGI("Frame rate is not explicitly set. Use the current frame "
1476             "rate (%d fps)", frameRate);
1477        mFrameRate = frameRate;
1478    }
1479
1480    CHECK(mFrameRate != -1);
1481
1482    mMetaDataStoredInVideoBuffers =
1483        (*cameraSource)->metaDataStoredInVideoBuffers();
1484
1485    return OK;
1486}
1487
1488status_t StagefrightRecorder::setupVideoEncoder(
1489        sp<MediaSource> cameraSource,
1490        sp<MediaCodecSource> *source) {
1491    source->clear();
1492
1493    sp<AMessage> format = new AMessage();
1494
1495    switch (mVideoEncoder) {
1496        case VIDEO_ENCODER_H263:
1497            format->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
1498            break;
1499
1500        case VIDEO_ENCODER_MPEG_4_SP:
1501            format->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
1502            break;
1503
1504        case VIDEO_ENCODER_H264:
1505            format->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
1506            break;
1507
1508        case VIDEO_ENCODER_VP8:
1509            format->setString("mime", MEDIA_MIMETYPE_VIDEO_VP8);
1510            break;
1511
1512        case VIDEO_ENCODER_HEVC:
1513            format->setString("mime", MEDIA_MIMETYPE_VIDEO_HEVC);
1514            break;
1515
1516        default:
1517            CHECK(!"Should not be here, unsupported video encoding.");
1518            break;
1519    }
1520
1521    if (cameraSource != NULL) {
1522        sp<MetaData> meta = cameraSource->getFormat();
1523
1524        int32_t width, height, stride, sliceHeight, colorFormat;
1525        CHECK(meta->findInt32(kKeyWidth, &width));
1526        CHECK(meta->findInt32(kKeyHeight, &height));
1527        CHECK(meta->findInt32(kKeyStride, &stride));
1528        CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1529        CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1530
1531        format->setInt32("width", width);
1532        format->setInt32("height", height);
1533        format->setInt32("stride", stride);
1534        format->setInt32("slice-height", sliceHeight);
1535        format->setInt32("color-format", colorFormat);
1536    } else {
1537        format->setInt32("width", mVideoWidth);
1538        format->setInt32("height", mVideoHeight);
1539        format->setInt32("stride", mVideoWidth);
1540        format->setInt32("slice-height", mVideoHeight);
1541        format->setInt32("color-format", OMX_COLOR_FormatAndroidOpaque);
1542
1543        // set up time lapse/slow motion for surface source
1544        if (mCaptureFpsEnable) {
1545            if (mTimeBetweenCaptureUs <= 0) {
1546                ALOGE("Invalid mTimeBetweenCaptureUs value: %lld",
1547                        (long long)mTimeBetweenCaptureUs);
1548                return BAD_VALUE;
1549            }
1550            format->setInt64("time-lapse", mTimeBetweenCaptureUs);
1551        }
1552    }
1553
1554    format->setInt32("bitrate", mVideoBitRate);
1555    format->setInt32("frame-rate", mFrameRate);
1556    format->setInt32("i-frame-interval", mIFramesIntervalSec);
1557
1558    if (mVideoTimeScale > 0) {
1559        format->setInt32("time-scale", mVideoTimeScale);
1560    }
1561    if (mVideoEncoderProfile != -1) {
1562        format->setInt32("profile", mVideoEncoderProfile);
1563    }
1564    if (mVideoEncoderLevel != -1) {
1565        format->setInt32("level", mVideoEncoderLevel);
1566    }
1567
1568    format->setInt32("priority", 0 /* realtime */);
1569    if (mCaptureFpsEnable) {
1570        format->setFloat("operating-rate", mCaptureFps);
1571    }
1572
1573    if (mMetaDataStoredInVideoBuffers != kMetadataBufferTypeInvalid) {
1574        format->setInt32("android._input-metadata-buffer-type", mMetaDataStoredInVideoBuffers);
1575    }
1576
1577    uint32_t flags = 0;
1578    if (cameraSource == NULL) {
1579        flags |= MediaCodecSource::FLAG_USE_SURFACE_INPUT;
1580    } else {
1581        // require dataspace setup even if not using surface input
1582        format->setInt32("android._using-recorder", 1);
1583    }
1584
1585    sp<MediaCodecSource> encoder = MediaCodecSource::Create(
1586            mLooper, format, cameraSource, mPersistentSurface, flags);
1587    if (encoder == NULL) {
1588        ALOGE("Failed to create video encoder");
1589        // When the encoder fails to be created, we need
1590        // release the camera source due to the camera's lock
1591        // and unlock mechanism.
1592        if (cameraSource != NULL) {
1593            cameraSource->stop();
1594        }
1595        return UNKNOWN_ERROR;
1596    }
1597
1598    if (cameraSource == NULL) {
1599        mGraphicBufferProducer = encoder->getGraphicBufferProducer();
1600    }
1601
1602    *source = encoder;
1603
1604    return OK;
1605}
1606
1607status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1608    status_t status = BAD_VALUE;
1609    if (OK != (status = checkAudioEncoderCapabilities())) {
1610        return status;
1611    }
1612
1613    switch(mAudioEncoder) {
1614        case AUDIO_ENCODER_AMR_NB:
1615        case AUDIO_ENCODER_AMR_WB:
1616        case AUDIO_ENCODER_AAC:
1617        case AUDIO_ENCODER_HE_AAC:
1618        case AUDIO_ENCODER_AAC_ELD:
1619            break;
1620
1621        default:
1622            ALOGE("Unsupported audio encoder: %d", mAudioEncoder);
1623            return UNKNOWN_ERROR;
1624    }
1625
1626    sp<MediaCodecSource> audioEncoder = createAudioSource();
1627    if (audioEncoder == NULL) {
1628        return UNKNOWN_ERROR;
1629    }
1630
1631    writer->addSource(audioEncoder);
1632    mAudioEncoderSource = audioEncoder;
1633    return OK;
1634}
1635
1636status_t StagefrightRecorder::setupMPEG4orWEBMRecording() {
1637    mWriter.clear();
1638    mTotalBitRate = 0;
1639
1640    status_t err = OK;
1641    sp<MediaWriter> writer;
1642    sp<MPEG4Writer> mp4writer;
1643    if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1644        writer = new WebmWriter(mOutputFd);
1645    } else {
1646        writer = mp4writer = new MPEG4Writer(mOutputFd);
1647    }
1648
1649    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1650        setDefaultVideoEncoderIfNecessary();
1651
1652        sp<MediaSource> mediaSource;
1653        err = setupMediaSource(&mediaSource);
1654        if (err != OK) {
1655            return err;
1656        }
1657
1658        sp<MediaCodecSource> encoder;
1659        err = setupVideoEncoder(mediaSource, &encoder);
1660        if (err != OK) {
1661            return err;
1662        }
1663
1664        writer->addSource(encoder);
1665        mVideoEncoderSource = encoder;
1666        mTotalBitRate += mVideoBitRate;
1667    }
1668
1669    if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1670        // Audio source is added at the end if it exists.
1671        // This help make sure that the "recoding" sound is suppressed for
1672        // camcorder applications in the recorded files.
1673        // TODO Audio source is currently unsupported for webm output; vorbis encoder needed.
1674        // disable audio for time lapse recording
1675        bool disableAudio = mCaptureFpsEnable && mCaptureFps < mFrameRate;
1676        if (!disableAudio && mAudioSource != AUDIO_SOURCE_CNT) {
1677            err = setupAudioEncoder(writer);
1678            if (err != OK) return err;
1679            mTotalBitRate += mAudioBitRate;
1680        }
1681
1682        if (mCaptureFpsEnable) {
1683            mp4writer->setCaptureRate(mCaptureFps);
1684        }
1685
1686        if (mInterleaveDurationUs > 0) {
1687            mp4writer->setInterleaveDuration(mInterleaveDurationUs);
1688        }
1689        if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1690            mp4writer->setGeoData(mLatitudex10000, mLongitudex10000);
1691        }
1692    }
1693    if (mMaxFileDurationUs != 0) {
1694        writer->setMaxFileDuration(mMaxFileDurationUs);
1695    }
1696    if (mMaxFileSizeBytes != 0) {
1697        writer->setMaxFileSize(mMaxFileSizeBytes);
1698    }
1699    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1700            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1701        mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1702    } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1703        // surface source doesn't need large initial delay
1704        mStartTimeOffsetMs = 200;
1705    }
1706    if (mStartTimeOffsetMs > 0) {
1707        writer->setStartTimeOffsetMs(mStartTimeOffsetMs);
1708    }
1709
1710    writer->setListener(mListener);
1711    mWriter = writer;
1712    return OK;
1713}
1714
1715void StagefrightRecorder::setupMPEG4orWEBMMetaData(sp<MetaData> *meta) {
1716    int64_t startTimeUs = systemTime() / 1000;
1717    (*meta)->setInt64(kKeyTime, startTimeUs);
1718    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1719    (*meta)->setInt32(kKeyBitRate, mTotalBitRate);
1720    if (mMovieTimeScale > 0) {
1721        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1722    }
1723    if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1724        (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1725        if (mTrackEveryTimeDurationUs > 0) {
1726            (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1727        }
1728        if (mRotationDegrees != 0) {
1729            (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1730        }
1731    }
1732}
1733
1734status_t StagefrightRecorder::pause() {
1735    ALOGV("pause");
1736    if (!mStarted) {
1737        return INVALID_OPERATION;
1738    }
1739
1740    // Already paused --- no-op.
1741    if (mPauseStartTimeUs != 0) {
1742        return OK;
1743    }
1744
1745    if (mAudioEncoderSource != NULL) {
1746        mAudioEncoderSource->pause();
1747    }
1748    if (mVideoEncoderSource != NULL) {
1749        mVideoEncoderSource->pause();
1750    }
1751
1752    mPauseStartTimeUs = systemTime() / 1000;
1753
1754    return OK;
1755}
1756
1757status_t StagefrightRecorder::resume() {
1758    ALOGV("resume");
1759    if (!mStarted) {
1760        return INVALID_OPERATION;
1761    }
1762
1763    // Not paused --- no-op.
1764    if (mPauseStartTimeUs == 0) {
1765        return OK;
1766    }
1767
1768    // 30 ms buffer to avoid timestamp overlap
1769    mTotalPausedDurationUs += (systemTime() / 1000) - mPauseStartTimeUs - 30000;
1770    double timeOffset = -mTotalPausedDurationUs;
1771    if (mCaptureFpsEnable) {
1772        timeOffset *= mCaptureFps / mFrameRate;
1773    }
1774    if (mAudioEncoderSource != NULL) {
1775        mAudioEncoderSource->setInputBufferTimeOffset((int64_t)timeOffset);
1776        mAudioEncoderSource->start();
1777    }
1778    if (mVideoEncoderSource != NULL) {
1779        mVideoEncoderSource->setInputBufferTimeOffset((int64_t)timeOffset);
1780        mVideoEncoderSource->start();
1781    }
1782    mPauseStartTimeUs = 0;
1783
1784    return OK;
1785}
1786
1787status_t StagefrightRecorder::stop() {
1788    ALOGV("stop");
1789    status_t err = OK;
1790
1791    if (mCaptureFpsEnable && mCameraSourceTimeLapse != NULL) {
1792        mCameraSourceTimeLapse->startQuickReadReturns();
1793        mCameraSourceTimeLapse = NULL;
1794    }
1795
1796    if (mWriter != NULL) {
1797        err = mWriter->stop();
1798        mWriter.clear();
1799    }
1800    mTotalPausedDurationUs = 0;
1801    mPauseStartTimeUs = 0;
1802
1803    mGraphicBufferProducer.clear();
1804    mPersistentSurface.clear();
1805    mAudioEncoderSource.clear();
1806    mVideoEncoderSource.clear();
1807
1808    if (mOutputFd >= 0) {
1809        ::close(mOutputFd);
1810        mOutputFd = -1;
1811    }
1812
1813    if (mStarted) {
1814        mStarted = false;
1815
1816        uint32_t params = 0;
1817        if (mAudioSource != AUDIO_SOURCE_CNT) {
1818            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1819        }
1820        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1821            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1822        }
1823
1824        addBatteryData(params);
1825    }
1826
1827    return err;
1828}
1829
1830status_t StagefrightRecorder::close() {
1831    ALOGV("close");
1832    stop();
1833
1834    return OK;
1835}
1836
1837status_t StagefrightRecorder::reset() {
1838    ALOGV("reset");
1839    stop();
1840
1841    // No audio or video source by default
1842    mAudioSource = AUDIO_SOURCE_CNT;
1843    mVideoSource = VIDEO_SOURCE_LIST_END;
1844
1845    // Default parameters
1846    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1847    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1848    mVideoEncoder  = VIDEO_ENCODER_DEFAULT;
1849    mVideoWidth    = 176;
1850    mVideoHeight   = 144;
1851    mFrameRate     = -1;
1852    mVideoBitRate  = 192000;
1853    mSampleRate    = 8000;
1854    mAudioChannels = 1;
1855    mAudioBitRate  = 12200;
1856    mInterleaveDurationUs = 0;
1857    mIFramesIntervalSec = 1;
1858    mAudioSourceNode = 0;
1859    mUse64BitFileOffset = false;
1860    mMovieTimeScale  = -1;
1861    mAudioTimeScale  = -1;
1862    mVideoTimeScale  = -1;
1863    mCameraId        = 0;
1864    mStartTimeOffsetMs = -1;
1865    mVideoEncoderProfile = -1;
1866    mVideoEncoderLevel   = -1;
1867    mMaxFileDurationUs = 0;
1868    mMaxFileSizeBytes = 0;
1869    mTrackEveryTimeDurationUs = 0;
1870    mCaptureFpsEnable = false;
1871    mCaptureFps = 0.0f;
1872    mTimeBetweenCaptureUs = -1;
1873    mCameraSourceTimeLapse = NULL;
1874    mMetaDataStoredInVideoBuffers = kMetadataBufferTypeInvalid;
1875    mEncoderProfiles = MediaProfiles::getInstance();
1876    mRotationDegrees = 0;
1877    mLatitudex10000 = -3600000;
1878    mLongitudex10000 = -3600000;
1879    mTotalBitRate = 0;
1880
1881    mOutputFd = -1;
1882
1883    return OK;
1884}
1885
1886status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1887    ALOGV("getMaxAmplitude");
1888
1889    if (max == NULL) {
1890        ALOGE("Null pointer argument");
1891        return BAD_VALUE;
1892    }
1893
1894    if (mAudioSourceNode != 0) {
1895        *max = mAudioSourceNode->getMaxAmplitude();
1896    } else {
1897        *max = 0;
1898    }
1899
1900    return OK;
1901}
1902
1903status_t StagefrightRecorder::dump(
1904        int fd, const Vector<String16>& args) const {
1905    ALOGV("dump");
1906    const size_t SIZE = 256;
1907    char buffer[SIZE];
1908    String8 result;
1909    if (mWriter != 0) {
1910        mWriter->dump(fd, args);
1911    } else {
1912        snprintf(buffer, SIZE, "   No file writer\n");
1913        result.append(buffer);
1914    }
1915    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1916    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1917    result.append(buffer);
1918    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1919    result.append(buffer);
1920    snprintf(buffer, SIZE, "     Max file size (bytes): %" PRId64 "\n", mMaxFileSizeBytes);
1921    result.append(buffer);
1922    snprintf(buffer, SIZE, "     Max file duration (us): %" PRId64 "\n", mMaxFileDurationUs);
1923    result.append(buffer);
1924    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1925    result.append(buffer);
1926    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1927    result.append(buffer);
1928    snprintf(buffer, SIZE, "     Progress notification: %" PRId64 " us\n", mTrackEveryTimeDurationUs);
1929    result.append(buffer);
1930    snprintf(buffer, SIZE, "   Audio\n");
1931    result.append(buffer);
1932    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1933    result.append(buffer);
1934    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1935    result.append(buffer);
1936    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1937    result.append(buffer);
1938    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1939    result.append(buffer);
1940    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1941    result.append(buffer);
1942    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1943    result.append(buffer);
1944    snprintf(buffer, SIZE, "   Video\n");
1945    result.append(buffer);
1946    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1947    result.append(buffer);
1948    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1949    result.append(buffer);
1950    snprintf(buffer, SIZE, "     Start time offset (ms): %d\n", mStartTimeOffsetMs);
1951    result.append(buffer);
1952    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1953    result.append(buffer);
1954    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1955    result.append(buffer);
1956    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1957    result.append(buffer);
1958    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1959    result.append(buffer);
1960    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1961    result.append(buffer);
1962    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1963    result.append(buffer);
1964    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1965    result.append(buffer);
1966    ::write(fd, result.string(), result.size());
1967    return OK;
1968}
1969}  // namespace android
1970