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