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