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