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