StagefrightRecorder.cpp revision 07b1bb529a1ae76c46a71b01338c166f9490629d
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 <utils/Log.h>
20
21#include "StagefrightRecorder.h"
22
23#include <binder/IPCThreadState.h>
24#include <binder/IServiceManager.h>
25
26#include <media/IMediaPlayerService.h>
27#include <media/stagefright/AudioSource.h>
28#include <media/stagefright/AMRWriter.h>
29#include <media/stagefright/AACWriter.h>
30#include <media/stagefright/CameraSource.h>
31#include <media/stagefright/VideoSourceDownSampler.h>
32#include <media/stagefright/CameraSourceTimeLapse.h>
33#include <media/stagefright/MediaSourceSplitter.h>
34#include <media/stagefright/MPEG2TSWriter.h>
35#include <media/stagefright/MPEG4Writer.h>
36#include <media/stagefright/MediaDebug.h>
37#include <media/stagefright/MediaDefs.h>
38#include <media/stagefright/MetaData.h>
39#include <media/stagefright/OMXClient.h>
40#include <media/stagefright/OMXCodec.h>
41#include <media/MediaProfiles.h>
42#include <camera/ICamera.h>
43#include <camera/CameraParameters.h>
44#include <surfaceflinger/Surface.h>
45#include <utils/Errors.h>
46#include <sys/types.h>
47#include <ctype.h>
48#include <unistd.h>
49
50#include <system/audio.h>
51
52#include "ARTPWriter.h"
53
54namespace android {
55
56// To collect the encoder usage for the battery app
57static void addBatteryData(uint32_t params) {
58    sp<IBinder> binder =
59        defaultServiceManager()->getService(String16("media.player"));
60    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
61    CHECK(service.get() != NULL);
62
63    service->addBatteryData(params);
64}
65
66
67StagefrightRecorder::StagefrightRecorder()
68    : mWriter(NULL), mWriterAux(NULL),
69      mOutputFd(-1), mOutputFdAux(-1),
70      mAudioSource(AUDIO_SOURCE_CNT),
71      mVideoSource(VIDEO_SOURCE_LIST_END),
72      mStarted(false) {
73
74    LOGV("Constructor");
75    reset();
76}
77
78StagefrightRecorder::~StagefrightRecorder() {
79    LOGV("Destructor");
80    stop();
81}
82
83status_t StagefrightRecorder::init() {
84    LOGV("init");
85    return OK;
86}
87
88status_t StagefrightRecorder::setAudioSource(audio_source_t as) {
89    LOGV("setAudioSource: %d", as);
90    if (as < AUDIO_SOURCE_DEFAULT ||
91        as >= AUDIO_SOURCE_CNT) {
92        LOGE("Invalid audio source: %d", as);
93        return BAD_VALUE;
94    }
95
96    if (as == AUDIO_SOURCE_DEFAULT) {
97        mAudioSource = AUDIO_SOURCE_MIC;
98    } else {
99        mAudioSource = as;
100    }
101
102    return OK;
103}
104
105status_t StagefrightRecorder::setVideoSource(video_source vs) {
106    LOGV("setVideoSource: %d", vs);
107    if (vs < VIDEO_SOURCE_DEFAULT ||
108        vs >= VIDEO_SOURCE_LIST_END) {
109        LOGE("Invalid video source: %d", vs);
110        return BAD_VALUE;
111    }
112
113    if (vs == VIDEO_SOURCE_DEFAULT) {
114        mVideoSource = VIDEO_SOURCE_CAMERA;
115    } else {
116        mVideoSource = vs;
117    }
118
119    return OK;
120}
121
122status_t StagefrightRecorder::setOutputFormat(output_format of) {
123    LOGV("setOutputFormat: %d", of);
124    if (of < OUTPUT_FORMAT_DEFAULT ||
125        of >= OUTPUT_FORMAT_LIST_END) {
126        LOGE("Invalid output format: %d", of);
127        return BAD_VALUE;
128    }
129
130    if (of == OUTPUT_FORMAT_DEFAULT) {
131        mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
132    } else {
133        mOutputFormat = of;
134    }
135
136    return OK;
137}
138
139status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
140    LOGV("setAudioEncoder: %d", ae);
141    if (ae < AUDIO_ENCODER_DEFAULT ||
142        ae >= AUDIO_ENCODER_LIST_END) {
143        LOGE("Invalid audio encoder: %d", ae);
144        return BAD_VALUE;
145    }
146
147    if (ae == AUDIO_ENCODER_DEFAULT) {
148        mAudioEncoder = AUDIO_ENCODER_AMR_NB;
149    } else {
150        mAudioEncoder = ae;
151    }
152
153    return OK;
154}
155
156status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
157    LOGV("setVideoEncoder: %d", ve);
158    if (ve < VIDEO_ENCODER_DEFAULT ||
159        ve >= VIDEO_ENCODER_LIST_END) {
160        LOGE("Invalid video encoder: %d", ve);
161        return BAD_VALUE;
162    }
163
164    if (ve == VIDEO_ENCODER_DEFAULT) {
165        mVideoEncoder = VIDEO_ENCODER_H263;
166    } else {
167        mVideoEncoder = ve;
168    }
169
170    return OK;
171}
172
173status_t StagefrightRecorder::setVideoSize(int width, int height) {
174    LOGV("setVideoSize: %dx%d", width, height);
175    if (width <= 0 || height <= 0) {
176        LOGE("Invalid video size: %dx%d", width, height);
177        return BAD_VALUE;
178    }
179
180    // Additional check on the dimension will be performed later
181    mVideoWidth = width;
182    mVideoHeight = height;
183
184    return OK;
185}
186
187status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
188    LOGV("setVideoFrameRate: %d", frames_per_second);
189    if ((frames_per_second <= 0 && frames_per_second != -1) ||
190        frames_per_second > 120) {
191        LOGE("Invalid video frame rate: %d", frames_per_second);
192        return BAD_VALUE;
193    }
194
195    // Additional check on the frame rate will be performed later
196    mFrameRate = frames_per_second;
197
198    return OK;
199}
200
201status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera) {
202    LOGV("setCamera");
203    if (camera == 0) {
204        LOGE("camera is NULL");
205        return BAD_VALUE;
206    }
207
208    mCamera = camera;
209    return OK;
210}
211
212status_t StagefrightRecorder::setPreviewSurface(const sp<Surface> &surface) {
213    LOGV("setPreviewSurface: %p", surface.get());
214    mPreviewSurface = surface;
215
216    return OK;
217}
218
219status_t StagefrightRecorder::setOutputFile(const char *path) {
220    LOGE("setOutputFile(const char*) must not be called");
221    // We don't actually support this at all, as the media_server process
222    // no longer has permissions to create files.
223
224    return -EPERM;
225}
226
227status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
228    LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length);
229    // These don't make any sense, do they?
230    CHECK_EQ(offset, 0);
231    CHECK_EQ(length, 0);
232
233    if (fd < 0) {
234        LOGE("Invalid file descriptor: %d", fd);
235        return -EBADF;
236    }
237
238    if (mOutputFd >= 0) {
239        ::close(mOutputFd);
240    }
241    mOutputFd = dup(fd);
242
243    return OK;
244}
245
246status_t StagefrightRecorder::setOutputFileAuxiliary(int fd) {
247    LOGV("setOutputFileAuxiliary: %d", fd);
248
249    if (fd < 0) {
250        LOGE("Invalid file descriptor: %d", fd);
251        return -EBADF;
252    }
253
254    mCaptureAuxVideo = true;
255
256    if (mOutputFdAux >= 0) {
257        ::close(mOutputFdAux);
258    }
259    mOutputFdAux = dup(fd);
260
261    return OK;
262}
263
264// Attempt to parse an int64 literal optionally surrounded by whitespace,
265// returns true on success, false otherwise.
266static bool safe_strtoi64(const char *s, int64_t *val) {
267    char *end;
268
269    // It is lame, but according to man page, we have to set errno to 0
270    // before calling strtoll().
271    errno = 0;
272    *val = strtoll(s, &end, 10);
273
274    if (end == s || errno == ERANGE) {
275        return false;
276    }
277
278    // Skip trailing whitespace
279    while (isspace(*end)) {
280        ++end;
281    }
282
283    // For a successful return, the string must contain nothing but a valid
284    // int64 literal optionally surrounded by whitespace.
285
286    return *end == '\0';
287}
288
289// Return true if the value is in [0, 0x007FFFFFFF]
290static bool safe_strtoi32(const char *s, int32_t *val) {
291    int64_t temp;
292    if (safe_strtoi64(s, &temp)) {
293        if (temp >= 0 && temp <= 0x007FFFFFFF) {
294            *val = static_cast<int32_t>(temp);
295            return true;
296        }
297    }
298    return false;
299}
300
301// Trim both leading and trailing whitespace from the given string.
302static void TrimString(String8 *s) {
303    size_t num_bytes = s->bytes();
304    const char *data = s->string();
305
306    size_t leading_space = 0;
307    while (leading_space < num_bytes && isspace(data[leading_space])) {
308        ++leading_space;
309    }
310
311    size_t i = num_bytes;
312    while (i > leading_space && isspace(data[i - 1])) {
313        --i;
314    }
315
316    s->setTo(String8(&data[leading_space], i - leading_space));
317}
318
319status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
320    LOGV("setParamAudioSamplingRate: %d", sampleRate);
321    if (sampleRate <= 0) {
322        LOGE("Invalid audio sampling rate: %d", sampleRate);
323        return BAD_VALUE;
324    }
325
326    // Additional check on the sample rate will be performed later.
327    mSampleRate = sampleRate;
328    return OK;
329}
330
331status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
332    LOGV("setParamAudioNumberOfChannels: %d", channels);
333    if (channels <= 0 || channels >= 3) {
334        LOGE("Invalid number of audio channels: %d", channels);
335        return BAD_VALUE;
336    }
337
338    // Additional check on the number of channels will be performed later.
339    mAudioChannels = channels;
340    return OK;
341}
342
343status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
344    LOGV("setParamAudioEncodingBitRate: %d", bitRate);
345    if (bitRate <= 0) {
346        LOGE("Invalid audio encoding bit rate: %d", bitRate);
347        return BAD_VALUE;
348    }
349
350    // The target bit rate may not be exactly the same as the requested.
351    // It depends on many factors, such as rate control, and the bit rate
352    // range that a specific encoder supports. The mismatch between the
353    // the target and requested bit rate will NOT be treated as an error.
354    mAudioBitRate = bitRate;
355    return OK;
356}
357
358status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
359    LOGV("setParamVideoEncodingBitRate: %d", bitRate);
360    if (bitRate <= 0) {
361        LOGE("Invalid video encoding bit rate: %d", bitRate);
362        return BAD_VALUE;
363    }
364
365    // The target bit rate may not be exactly the same as the requested.
366    // It depends on many factors, such as rate control, and the bit rate
367    // range that a specific encoder supports. The mismatch between the
368    // the target and requested bit rate will NOT be treated as an error.
369    mVideoBitRate = bitRate;
370    return OK;
371}
372
373// Always rotate clockwise, and only support 0, 90, 180 and 270 for now.
374status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) {
375    LOGV("setParamVideoRotation: %d", degrees);
376    if (degrees < 0 || degrees % 90 != 0) {
377        LOGE("Unsupported video rotation angle: %d", degrees);
378        return BAD_VALUE;
379    }
380    mRotationDegrees = degrees % 360;
381    return OK;
382}
383
384status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
385    LOGV("setParamMaxFileDurationUs: %lld us", timeUs);
386
387    // This is meant for backward compatibility for MediaRecorder.java
388    if (timeUs <= 0) {
389        LOGW("Max file duration is not positive: %lld us. Disabling duration limit.", timeUs);
390        timeUs = 0; // Disable the duration limit for zero or negative values.
391    } else if (timeUs <= 100000LL) {  // XXX: 100 milli-seconds
392        LOGE("Max file duration is too short: %lld us", timeUs);
393        return BAD_VALUE;
394    }
395
396    if (timeUs <= 15 * 1000000LL) {
397        LOGW("Target duration (%lld us) too short to be respected", timeUs);
398    }
399    mMaxFileDurationUs = timeUs;
400    return OK;
401}
402
403status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
404    LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
405
406    // This is meant for backward compatibility for MediaRecorder.java
407    if (bytes <= 0) {
408        LOGW("Max file size is not positive: %lld bytes. "
409             "Disabling file size limit.", bytes);
410        bytes = 0; // Disable the file size limit for zero or negative values.
411    } else if (bytes <= 1024) {  // XXX: 1 kB
412        LOGE("Max file size is too small: %lld bytes", bytes);
413        return BAD_VALUE;
414    }
415
416    if (bytes <= 100 * 1024) {
417        LOGW("Target file size (%lld bytes) is too small to be respected", bytes);
418    }
419
420    mMaxFileSizeBytes = bytes;
421    return OK;
422}
423
424status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
425    LOGV("setParamInterleaveDuration: %d", durationUs);
426    if (durationUs <= 500000) {           //  500 ms
427        // If interleave duration is too small, it is very inefficient to do
428        // interleaving since the metadata overhead will count for a significant
429        // portion of the saved contents
430        LOGE("Audio/video interleave duration is too small: %d us", durationUs);
431        return BAD_VALUE;
432    } else if (durationUs >= 10000000) {  // 10 seconds
433        // If interleaving duration is too large, it can cause the recording
434        // session to use too much memory since we have to save the output
435        // data before we write them out
436        LOGE("Audio/video interleave duration is too large: %d us", durationUs);
437        return BAD_VALUE;
438    }
439    mInterleaveDurationUs = durationUs;
440    return OK;
441}
442
443// If seconds <  0, only the first frame is I frame, and rest are all P frames
444// If seconds == 0, all frames are encoded as I frames. No P frames
445// If seconds >  0, it is the time spacing (seconds) between 2 neighboring I frames
446status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) {
447    LOGV("setParamVideoIFramesInterval: %d seconds", seconds);
448    mIFramesIntervalSec = seconds;
449    return OK;
450}
451
452status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
453    LOGV("setParam64BitFileOffset: %s",
454        use64Bit? "use 64 bit file offset": "use 32 bit file offset");
455    mUse64BitFileOffset = use64Bit;
456    return OK;
457}
458
459status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
460    LOGV("setParamVideoCameraId: %d", cameraId);
461    if (cameraId < 0) {
462        return BAD_VALUE;
463    }
464    mCameraId = cameraId;
465    return OK;
466}
467
468status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
469    LOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
470    if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
471        LOGE("Tracking time duration too short: %lld us", timeDurationUs);
472        return BAD_VALUE;
473    }
474    mTrackEveryTimeDurationUs = timeDurationUs;
475    return OK;
476}
477
478status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) {
479    LOGV("setParamVideoEncoderProfile: %d", profile);
480
481    // Additional check will be done later when we load the encoder.
482    // For now, we are accepting values defined in OpenMAX IL.
483    mVideoEncoderProfile = profile;
484    return OK;
485}
486
487status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) {
488    LOGV("setParamVideoEncoderLevel: %d", level);
489
490    // Additional check will be done later when we load the encoder.
491    // For now, we are accepting values defined in OpenMAX IL.
492    mVideoEncoderLevel = level;
493    return OK;
494}
495
496status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) {
497    LOGV("setParamMovieTimeScale: %d", timeScale);
498
499    // The range is set to be the same as the audio's time scale range
500    // since audio's time scale has a wider range.
501    if (timeScale < 600 || timeScale > 96000) {
502        LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
503        return BAD_VALUE;
504    }
505    mMovieTimeScale = timeScale;
506    return OK;
507}
508
509status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) {
510    LOGV("setParamVideoTimeScale: %d", timeScale);
511
512    // 60000 is chosen to make sure that each video frame from a 60-fps
513    // video has 1000 ticks.
514    if (timeScale < 600 || timeScale > 60000) {
515        LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
516        return BAD_VALUE;
517    }
518    mVideoTimeScale = timeScale;
519    return OK;
520}
521
522status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) {
523    LOGV("setParamAudioTimeScale: %d", timeScale);
524
525    // 96000 Hz is the highest sampling rate support in AAC.
526    if (timeScale < 600 || timeScale > 96000) {
527        LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
528        return BAD_VALUE;
529    }
530    mAudioTimeScale = timeScale;
531    return OK;
532}
533
534status_t StagefrightRecorder::setParamTimeLapseEnable(int32_t timeLapseEnable) {
535    LOGV("setParamTimeLapseEnable: %d", timeLapseEnable);
536
537    if(timeLapseEnable == 0) {
538        mCaptureTimeLapse = false;
539    } else if (timeLapseEnable == 1) {
540        mCaptureTimeLapse = true;
541    } else {
542        return BAD_VALUE;
543    }
544    return OK;
545}
546
547status_t StagefrightRecorder::setParamTimeBetweenTimeLapseFrameCapture(int64_t timeUs) {
548    LOGV("setParamTimeBetweenTimeLapseFrameCapture: %lld us", timeUs);
549
550    // Not allowing time more than a day
551    if (timeUs <= 0 || timeUs > 86400*1E6) {
552        LOGE("Time between time lapse frame capture (%lld) is out of range [0, 1 Day]", timeUs);
553        return BAD_VALUE;
554    }
555
556    mTimeBetweenTimeLapseFrameCaptureUs = timeUs;
557    return OK;
558}
559
560status_t StagefrightRecorder::setParamAuxVideoWidth(int32_t width) {
561    LOGV("setParamAuxVideoWidth : %d", width);
562
563    if (width <= 0) {
564        LOGE("Width (%d) is not positive", width);
565        return BAD_VALUE;
566    }
567
568    mAuxVideoWidth = width;
569    return OK;
570}
571
572status_t StagefrightRecorder::setParamAuxVideoHeight(int32_t height) {
573    LOGV("setParamAuxVideoHeight : %d", height);
574
575    if (height <= 0) {
576        LOGE("Height (%d) is not positive", height);
577        return BAD_VALUE;
578    }
579
580    mAuxVideoHeight = height;
581    return OK;
582}
583
584status_t StagefrightRecorder::setParamAuxVideoEncodingBitRate(int32_t bitRate) {
585    LOGV("StagefrightRecorder::setParamAuxVideoEncodingBitRate: %d", bitRate);
586
587    if (bitRate <= 0) {
588        LOGE("Invalid video encoding bit rate: %d", bitRate);
589        return BAD_VALUE;
590    }
591
592    mAuxVideoBitRate = bitRate;
593    return OK;
594}
595
596status_t StagefrightRecorder::setParamGeoDataLongitude(
597    int32_t longitudex10000) {
598
599    if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
600        return BAD_VALUE;
601    }
602    mLongitudex10000 = longitudex10000;
603    return OK;
604}
605
606status_t StagefrightRecorder::setParamGeoDataLatitude(
607    int32_t latitudex10000) {
608
609    if (latitudex10000 > 900000 || latitudex10000 < -900000) {
610        return BAD_VALUE;
611    }
612    mLatitudex10000 = latitudex10000;
613    return OK;
614}
615
616status_t StagefrightRecorder::setParameter(
617        const String8 &key, const String8 &value) {
618    LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
619    if (key == "max-duration") {
620        int64_t max_duration_ms;
621        if (safe_strtoi64(value.string(), &max_duration_ms)) {
622            return setParamMaxFileDurationUs(1000LL * max_duration_ms);
623        }
624    } else if (key == "max-filesize") {
625        int64_t max_filesize_bytes;
626        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
627            return setParamMaxFileSizeBytes(max_filesize_bytes);
628        }
629    } else if (key == "interleave-duration-us") {
630        int32_t durationUs;
631        if (safe_strtoi32(value.string(), &durationUs)) {
632            return setParamInterleaveDuration(durationUs);
633        }
634    } else if (key == "param-movie-time-scale") {
635        int32_t timeScale;
636        if (safe_strtoi32(value.string(), &timeScale)) {
637            return setParamMovieTimeScale(timeScale);
638        }
639    } else if (key == "param-use-64bit-offset") {
640        int32_t use64BitOffset;
641        if (safe_strtoi32(value.string(), &use64BitOffset)) {
642            return setParam64BitFileOffset(use64BitOffset != 0);
643        }
644    } else if (key == "param-geotag-longitude") {
645        int32_t longitudex10000;
646        if (safe_strtoi32(value.string(), &longitudex10000)) {
647            return setParamGeoDataLongitude(longitudex10000);
648        }
649    } else if (key == "param-geotag-latitude") {
650        int32_t latitudex10000;
651        if (safe_strtoi32(value.string(), &latitudex10000)) {
652            return setParamGeoDataLatitude(latitudex10000);
653        }
654    } else if (key == "param-track-time-status") {
655        int64_t timeDurationUs;
656        if (safe_strtoi64(value.string(), &timeDurationUs)) {
657            return setParamTrackTimeStatus(timeDurationUs);
658        }
659    } else if (key == "audio-param-sampling-rate") {
660        int32_t sampling_rate;
661        if (safe_strtoi32(value.string(), &sampling_rate)) {
662            return setParamAudioSamplingRate(sampling_rate);
663        }
664    } else if (key == "audio-param-number-of-channels") {
665        int32_t number_of_channels;
666        if (safe_strtoi32(value.string(), &number_of_channels)) {
667            return setParamAudioNumberOfChannels(number_of_channels);
668        }
669    } else if (key == "audio-param-encoding-bitrate") {
670        int32_t audio_bitrate;
671        if (safe_strtoi32(value.string(), &audio_bitrate)) {
672            return setParamAudioEncodingBitRate(audio_bitrate);
673        }
674    } else if (key == "audio-param-time-scale") {
675        int32_t timeScale;
676        if (safe_strtoi32(value.string(), &timeScale)) {
677            return setParamAudioTimeScale(timeScale);
678        }
679    } else if (key == "video-param-encoding-bitrate") {
680        int32_t video_bitrate;
681        if (safe_strtoi32(value.string(), &video_bitrate)) {
682            return setParamVideoEncodingBitRate(video_bitrate);
683        }
684    } else if (key == "video-param-rotation-angle-degrees") {
685        int32_t degrees;
686        if (safe_strtoi32(value.string(), &degrees)) {
687            return setParamVideoRotation(degrees);
688        }
689    } else if (key == "video-param-i-frames-interval") {
690        int32_t seconds;
691        if (safe_strtoi32(value.string(), &seconds)) {
692            return setParamVideoIFramesInterval(seconds);
693        }
694    } else if (key == "video-param-encoder-profile") {
695        int32_t profile;
696        if (safe_strtoi32(value.string(), &profile)) {
697            return setParamVideoEncoderProfile(profile);
698        }
699    } else if (key == "video-param-encoder-level") {
700        int32_t level;
701        if (safe_strtoi32(value.string(), &level)) {
702            return setParamVideoEncoderLevel(level);
703        }
704    } else if (key == "video-param-camera-id") {
705        int32_t cameraId;
706        if (safe_strtoi32(value.string(), &cameraId)) {
707            return setParamVideoCameraId(cameraId);
708        }
709    } else if (key == "video-param-time-scale") {
710        int32_t timeScale;
711        if (safe_strtoi32(value.string(), &timeScale)) {
712            return setParamVideoTimeScale(timeScale);
713        }
714    } else if (key == "time-lapse-enable") {
715        int32_t timeLapseEnable;
716        if (safe_strtoi32(value.string(), &timeLapseEnable)) {
717            return setParamTimeLapseEnable(timeLapseEnable);
718        }
719    } else if (key == "time-between-time-lapse-frame-capture") {
720        int64_t timeBetweenTimeLapseFrameCaptureMs;
721        if (safe_strtoi64(value.string(), &timeBetweenTimeLapseFrameCaptureMs)) {
722            return setParamTimeBetweenTimeLapseFrameCapture(
723                    1000LL * timeBetweenTimeLapseFrameCaptureMs);
724        }
725    } else if (key == "video-aux-param-width") {
726        int32_t auxWidth;
727        if (safe_strtoi32(value.string(), &auxWidth)) {
728            return setParamAuxVideoWidth(auxWidth);
729        }
730    } else if (key == "video-aux-param-height") {
731        int32_t auxHeight;
732        if (safe_strtoi32(value.string(), &auxHeight)) {
733            return setParamAuxVideoHeight(auxHeight);
734        }
735    } else if (key == "video-aux-param-encoding-bitrate") {
736        int32_t auxVideoBitRate;
737        if (safe_strtoi32(value.string(), &auxVideoBitRate)) {
738            return setParamAuxVideoEncodingBitRate(auxVideoBitRate);
739        }
740    } else {
741        LOGE("setParameter: failed to find key %s", key.string());
742    }
743    return BAD_VALUE;
744}
745
746status_t StagefrightRecorder::setParameters(const String8 &params) {
747    LOGV("setParameters: %s", params.string());
748    const char *cparams = params.string();
749    const char *key_start = cparams;
750    for (;;) {
751        const char *equal_pos = strchr(key_start, '=');
752        if (equal_pos == NULL) {
753            LOGE("Parameters %s miss a value", cparams);
754            return BAD_VALUE;
755        }
756        String8 key(key_start, equal_pos - key_start);
757        TrimString(&key);
758        if (key.length() == 0) {
759            LOGE("Parameters %s contains an empty key", cparams);
760            return BAD_VALUE;
761        }
762        const char *value_start = equal_pos + 1;
763        const char *semicolon_pos = strchr(value_start, ';');
764        String8 value;
765        if (semicolon_pos == NULL) {
766            value.setTo(value_start);
767        } else {
768            value.setTo(value_start, semicolon_pos - value_start);
769        }
770        if (setParameter(key, value) != OK) {
771            return BAD_VALUE;
772        }
773        if (semicolon_pos == NULL) {
774            break;  // Reaches the end
775        }
776        key_start = semicolon_pos + 1;
777    }
778    return OK;
779}
780
781status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
782    mListener = listener;
783
784    return OK;
785}
786
787status_t StagefrightRecorder::prepare() {
788    return OK;
789}
790
791status_t StagefrightRecorder::start() {
792    CHECK(mOutputFd >= 0);
793
794    if (mWriter != NULL) {
795        LOGE("File writer is not avaialble");
796        return UNKNOWN_ERROR;
797    }
798
799    status_t status = OK;
800
801    switch (mOutputFormat) {
802        case OUTPUT_FORMAT_DEFAULT:
803        case OUTPUT_FORMAT_THREE_GPP:
804        case OUTPUT_FORMAT_MPEG_4:
805            status = startMPEG4Recording();
806            break;
807
808        case OUTPUT_FORMAT_AMR_NB:
809        case OUTPUT_FORMAT_AMR_WB:
810            status = startAMRRecording();
811            break;
812
813        case OUTPUT_FORMAT_AAC_ADIF:
814        case OUTPUT_FORMAT_AAC_ADTS:
815            status = startAACRecording();
816            break;
817
818        case OUTPUT_FORMAT_RTP_AVP:
819            status = startRTPRecording();
820            break;
821
822        case OUTPUT_FORMAT_MPEG2TS:
823            status = startMPEG2TSRecording();
824            break;
825
826        default:
827            LOGE("Unsupported output file format: %d", mOutputFormat);
828            status = UNKNOWN_ERROR;
829            break;
830    }
831
832    if ((status == OK) && (!mStarted)) {
833        mStarted = true;
834
835        uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted;
836        if (mAudioSource != AUDIO_SOURCE_CNT) {
837            params |= IMediaPlayerService::kBatteryDataTrackAudio;
838        }
839        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
840            params |= IMediaPlayerService::kBatteryDataTrackVideo;
841        }
842
843        addBatteryData(params);
844    }
845
846    return status;
847}
848
849sp<MediaSource> StagefrightRecorder::createAudioSource() {
850    sp<AudioSource> audioSource =
851        new AudioSource(
852                mAudioSource,
853                mSampleRate,
854                mAudioChannels);
855
856    status_t err = audioSource->initCheck();
857
858    if (err != OK) {
859        LOGE("audio source is not initialized");
860        return NULL;
861    }
862
863    sp<MetaData> encMeta = new MetaData;
864    const char *mime;
865    switch (mAudioEncoder) {
866        case AUDIO_ENCODER_AMR_NB:
867        case AUDIO_ENCODER_DEFAULT:
868            mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
869            break;
870        case AUDIO_ENCODER_AMR_WB:
871            mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
872            break;
873        case AUDIO_ENCODER_AAC:
874            mime = MEDIA_MIMETYPE_AUDIO_AAC;
875            break;
876        default:
877            LOGE("Unknown audio encoder: %d", mAudioEncoder);
878            return NULL;
879    }
880    encMeta->setCString(kKeyMIMEType, mime);
881
882    int32_t maxInputSize;
883    CHECK(audioSource->getFormat()->findInt32(
884                kKeyMaxInputSize, &maxInputSize));
885
886    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
887    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
888    encMeta->setInt32(kKeySampleRate, mSampleRate);
889    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
890    if (mAudioTimeScale > 0) {
891        encMeta->setInt32(kKeyTimeScale, mAudioTimeScale);
892    }
893
894    OMXClient client;
895    CHECK_EQ(client.connect(), OK);
896
897    sp<MediaSource> audioEncoder =
898        OMXCodec::Create(client.interface(), encMeta,
899                         true /* createEncoder */, audioSource);
900    mAudioSourceNode = audioSource;
901
902    return audioEncoder;
903}
904
905status_t StagefrightRecorder::startAACRecording() {
906    // FIXME:
907    // Add support for OUTPUT_FORMAT_AAC_ADIF
908    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
909
910    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
911    CHECK(mAudioSource != AUDIO_SOURCE_CNT);
912
913    mWriter = new AACWriter(mOutputFd);
914    status_t status = startRawAudioRecording();
915    if (status != OK) {
916        mWriter.clear();
917        mWriter = NULL;
918    }
919
920    return status;
921}
922
923status_t StagefrightRecorder::startAMRRecording() {
924    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
925          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
926
927    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
928        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
929            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
930            LOGE("Invalid encoder %d used for AMRNB recording",
931                    mAudioEncoder);
932            return BAD_VALUE;
933        }
934    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
935        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
936            LOGE("Invlaid encoder %d used for AMRWB recording",
937                    mAudioEncoder);
938            return BAD_VALUE;
939        }
940    }
941
942    mWriter = new AMRWriter(mOutputFd);
943    status_t status = startRawAudioRecording();
944    if (status != OK) {
945        mWriter.clear();
946        mWriter = NULL;
947    }
948    return status;
949}
950
951status_t StagefrightRecorder::startRawAudioRecording() {
952    if (mAudioSource >= AUDIO_SOURCE_CNT) {
953        LOGE("Invalid audio source: %d", mAudioSource);
954        return BAD_VALUE;
955    }
956
957    status_t status = BAD_VALUE;
958    if (OK != (status = checkAudioEncoderCapabilities())) {
959        return status;
960    }
961
962    sp<MediaSource> audioEncoder = createAudioSource();
963    if (audioEncoder == NULL) {
964        return UNKNOWN_ERROR;
965    }
966
967    CHECK(mWriter != 0);
968    mWriter->addSource(audioEncoder);
969
970    if (mMaxFileDurationUs != 0) {
971        mWriter->setMaxFileDuration(mMaxFileDurationUs);
972    }
973    if (mMaxFileSizeBytes != 0) {
974        mWriter->setMaxFileSize(mMaxFileSizeBytes);
975    }
976    mWriter->setListener(mListener);
977    mWriter->start();
978
979    return OK;
980}
981
982status_t StagefrightRecorder::startRTPRecording() {
983    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
984
985    if ((mAudioSource != AUDIO_SOURCE_CNT
986                && mVideoSource != VIDEO_SOURCE_LIST_END)
987            || (mAudioSource == AUDIO_SOURCE_CNT
988                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
989        // Must have exactly one source.
990        return BAD_VALUE;
991    }
992
993    if (mOutputFd < 0) {
994        return BAD_VALUE;
995    }
996
997    sp<MediaSource> source;
998
999    if (mAudioSource != AUDIO_SOURCE_CNT) {
1000        source = createAudioSource();
1001    } else {
1002
1003        sp<CameraSource> cameraSource;
1004        status_t err = setupCameraSource(&cameraSource);
1005        if (err != OK) {
1006            return err;
1007        }
1008
1009        err = setupVideoEncoder(cameraSource, mVideoBitRate, &source);
1010        if (err != OK) {
1011            return err;
1012        }
1013    }
1014
1015    mWriter = new ARTPWriter(mOutputFd);
1016    mWriter->addSource(source);
1017    mWriter->setListener(mListener);
1018
1019    return mWriter->start();
1020}
1021
1022status_t StagefrightRecorder::startMPEG2TSRecording() {
1023    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
1024
1025    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
1026
1027    if (mAudioSource != AUDIO_SOURCE_CNT) {
1028        if (mAudioEncoder != AUDIO_ENCODER_AAC) {
1029            return ERROR_UNSUPPORTED;
1030        }
1031
1032        status_t err = setupAudioEncoder(writer);
1033
1034        if (err != OK) {
1035            return err;
1036        }
1037    }
1038
1039    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1040            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1041        if (mVideoEncoder != VIDEO_ENCODER_H264) {
1042            return ERROR_UNSUPPORTED;
1043        }
1044
1045        sp<CameraSource> cameraSource;
1046        status_t err = setupCameraSource(&cameraSource);
1047        if (err != OK) {
1048            return err;
1049        }
1050
1051        sp<MediaSource> encoder;
1052        err = setupVideoEncoder(cameraSource, mVideoBitRate, &encoder);
1053
1054        if (err != OK) {
1055            return err;
1056        }
1057
1058        writer->addSource(encoder);
1059    }
1060
1061    if (mMaxFileDurationUs != 0) {
1062        writer->setMaxFileDuration(mMaxFileDurationUs);
1063    }
1064
1065    if (mMaxFileSizeBytes != 0) {
1066        writer->setMaxFileSize(mMaxFileSizeBytes);
1067    }
1068
1069    mWriter = writer;
1070
1071    return mWriter->start();
1072}
1073
1074void StagefrightRecorder::clipVideoFrameRate() {
1075    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1076    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1077                        "enc.vid.fps.min", mVideoEncoder);
1078    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1079                        "enc.vid.fps.max", mVideoEncoder);
1080    if (mFrameRate < minFrameRate && mFrameRate != -1) {
1081        LOGW("Intended video encoding frame rate (%d fps) is too small"
1082             " and will be set to (%d fps)", mFrameRate, minFrameRate);
1083        mFrameRate = minFrameRate;
1084    } else if (mFrameRate > maxFrameRate) {
1085        LOGW("Intended video encoding frame rate (%d fps) is too large"
1086             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1087        mFrameRate = maxFrameRate;
1088    }
1089}
1090
1091void StagefrightRecorder::clipVideoBitRate() {
1092    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1093    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1094                        "enc.vid.bps.min", mVideoEncoder);
1095    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1096                        "enc.vid.bps.max", mVideoEncoder);
1097    if (mVideoBitRate < minBitRate) {
1098        LOGW("Intended video encoding bit rate (%d bps) is too small"
1099             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1100        mVideoBitRate = minBitRate;
1101    } else if (mVideoBitRate > maxBitRate) {
1102        LOGW("Intended video encoding bit rate (%d bps) is too large"
1103             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1104        mVideoBitRate = maxBitRate;
1105    }
1106}
1107
1108void StagefrightRecorder::clipVideoFrameWidth() {
1109    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1110    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1111                        "enc.vid.width.min", mVideoEncoder);
1112    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1113                        "enc.vid.width.max", mVideoEncoder);
1114    if (mVideoWidth < minFrameWidth) {
1115        LOGW("Intended video encoding frame width (%d) is too small"
1116             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1117        mVideoWidth = minFrameWidth;
1118    } else if (mVideoWidth > maxFrameWidth) {
1119        LOGW("Intended video encoding frame width (%d) is too large"
1120             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1121        mVideoWidth = maxFrameWidth;
1122    }
1123}
1124
1125status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1126    if (!mCaptureTimeLapse) {
1127        // Dont clip for time lapse capture as encoder will have enough
1128        // time to encode because of slow capture rate of time lapse.
1129        clipVideoBitRate();
1130        clipVideoFrameRate();
1131        clipVideoFrameWidth();
1132        clipVideoFrameHeight();
1133    }
1134    return OK;
1135}
1136
1137status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1138    clipAudioBitRate();
1139    clipAudioSampleRate();
1140    clipNumberOfAudioChannels();
1141    return OK;
1142}
1143
1144void StagefrightRecorder::clipAudioBitRate() {
1145    LOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1146
1147    int minAudioBitRate =
1148            mEncoderProfiles->getAudioEncoderParamByName(
1149                "enc.aud.bps.min", mAudioEncoder);
1150    if (mAudioBitRate < minAudioBitRate) {
1151        LOGW("Intended audio encoding bit rate (%d) is too small"
1152            " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1153        mAudioBitRate = minAudioBitRate;
1154    }
1155
1156    int maxAudioBitRate =
1157            mEncoderProfiles->getAudioEncoderParamByName(
1158                "enc.aud.bps.max", mAudioEncoder);
1159    if (mAudioBitRate > maxAudioBitRate) {
1160        LOGW("Intended audio encoding bit rate (%d) is too large"
1161            " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1162        mAudioBitRate = maxAudioBitRate;
1163    }
1164}
1165
1166void StagefrightRecorder::clipAudioSampleRate() {
1167    LOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1168
1169    int minSampleRate =
1170            mEncoderProfiles->getAudioEncoderParamByName(
1171                "enc.aud.hz.min", mAudioEncoder);
1172    if (mSampleRate < minSampleRate) {
1173        LOGW("Intended audio sample rate (%d) is too small"
1174            " and will be set to (%d)", mSampleRate, minSampleRate);
1175        mSampleRate = minSampleRate;
1176    }
1177
1178    int maxSampleRate =
1179            mEncoderProfiles->getAudioEncoderParamByName(
1180                "enc.aud.hz.max", mAudioEncoder);
1181    if (mSampleRate > maxSampleRate) {
1182        LOGW("Intended audio sample rate (%d) is too large"
1183            " and will be set to (%d)", mSampleRate, maxSampleRate);
1184        mSampleRate = maxSampleRate;
1185    }
1186}
1187
1188void StagefrightRecorder::clipNumberOfAudioChannels() {
1189    LOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1190
1191    int minChannels =
1192            mEncoderProfiles->getAudioEncoderParamByName(
1193                "enc.aud.ch.min", mAudioEncoder);
1194    if (mAudioChannels < minChannels) {
1195        LOGW("Intended number of audio channels (%d) is too small"
1196            " and will be set to (%d)", mAudioChannels, minChannels);
1197        mAudioChannels = minChannels;
1198    }
1199
1200    int maxChannels =
1201            mEncoderProfiles->getAudioEncoderParamByName(
1202                "enc.aud.ch.max", mAudioEncoder);
1203    if (mAudioChannels > maxChannels) {
1204        LOGW("Intended number of audio channels (%d) is too large"
1205            " and will be set to (%d)", mAudioChannels, maxChannels);
1206        mAudioChannels = maxChannels;
1207    }
1208}
1209
1210void StagefrightRecorder::clipVideoFrameHeight() {
1211    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1212    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1213                        "enc.vid.height.min", mVideoEncoder);
1214    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1215                        "enc.vid.height.max", mVideoEncoder);
1216    if (mVideoHeight < minFrameHeight) {
1217        LOGW("Intended video encoding frame height (%d) is too small"
1218             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1219        mVideoHeight = minFrameHeight;
1220    } else if (mVideoHeight > maxFrameHeight) {
1221        LOGW("Intended video encoding frame height (%d) is too large"
1222             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1223        mVideoHeight = maxFrameHeight;
1224    }
1225}
1226
1227status_t StagefrightRecorder::setupCameraSource(
1228        sp<CameraSource> *cameraSource) {
1229    status_t err = OK;
1230    if ((err = checkVideoEncoderCapabilities()) != OK) {
1231        return err;
1232    }
1233    Size videoSize;
1234    videoSize.width = mVideoWidth;
1235    videoSize.height = mVideoHeight;
1236    if (mCaptureTimeLapse) {
1237        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1238                mCamera, mCameraId,
1239                videoSize, mFrameRate, mPreviewSurface,
1240                mTimeBetweenTimeLapseFrameCaptureUs);
1241        *cameraSource = mCameraSourceTimeLapse;
1242    } else {
1243        *cameraSource = CameraSource::CreateFromCamera(
1244                mCamera, mCameraId, videoSize, mFrameRate,
1245                mPreviewSurface, true /*storeMetaDataInVideoBuffers*/);
1246    }
1247    if (*cameraSource == NULL) {
1248        return UNKNOWN_ERROR;
1249    }
1250
1251    if ((*cameraSource)->initCheck() != OK) {
1252        (*cameraSource).clear();
1253        *cameraSource = NULL;
1254        return NO_INIT;
1255    }
1256
1257    // When frame rate is not set, the actual frame rate will be set to
1258    // the current frame rate being used.
1259    if (mFrameRate == -1) {
1260        int32_t frameRate = 0;
1261        CHECK ((*cameraSource)->getFormat()->findInt32(
1262                    kKeyFrameRate, &frameRate));
1263        LOGI("Frame rate is not explicitly set. Use the current frame "
1264             "rate (%d fps)", frameRate);
1265        mFrameRate = frameRate;
1266    }
1267
1268    CHECK(mFrameRate != -1);
1269
1270    mIsMetaDataStoredInVideoBuffers =
1271        (*cameraSource)->isMetaDataStoredInVideoBuffers();
1272
1273    return OK;
1274}
1275
1276status_t StagefrightRecorder::setupVideoEncoder(
1277        sp<MediaSource> cameraSource,
1278        int32_t videoBitRate,
1279        sp<MediaSource> *source) {
1280    source->clear();
1281
1282    sp<MetaData> enc_meta = new MetaData;
1283    enc_meta->setInt32(kKeyBitRate, videoBitRate);
1284    enc_meta->setInt32(kKeyFrameRate, mFrameRate);
1285
1286    switch (mVideoEncoder) {
1287        case VIDEO_ENCODER_H263:
1288            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
1289            break;
1290
1291        case VIDEO_ENCODER_MPEG_4_SP:
1292            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
1293            break;
1294
1295        case VIDEO_ENCODER_H264:
1296            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
1297            break;
1298
1299        default:
1300            CHECK(!"Should not be here, unsupported video encoding.");
1301            break;
1302    }
1303
1304    sp<MetaData> meta = cameraSource->getFormat();
1305
1306    int32_t width, height, stride, sliceHeight, colorFormat;
1307    CHECK(meta->findInt32(kKeyWidth, &width));
1308    CHECK(meta->findInt32(kKeyHeight, &height));
1309    CHECK(meta->findInt32(kKeyStride, &stride));
1310    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1311    CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1312
1313    enc_meta->setInt32(kKeyWidth, width);
1314    enc_meta->setInt32(kKeyHeight, height);
1315    enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
1316    enc_meta->setInt32(kKeyStride, stride);
1317    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
1318    enc_meta->setInt32(kKeyColorFormat, colorFormat);
1319    if (mVideoTimeScale > 0) {
1320        enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
1321    }
1322    if (mVideoEncoderProfile != -1) {
1323        enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
1324    }
1325    if (mVideoEncoderLevel != -1) {
1326        enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
1327    }
1328
1329    OMXClient client;
1330    CHECK_EQ(client.connect(), OK);
1331
1332    uint32_t encoder_flags = 0;
1333    if (mIsMetaDataStoredInVideoBuffers) {
1334        encoder_flags |= OMXCodec::kHardwareCodecsOnly;
1335        encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers;
1336    }
1337
1338    // Do not wait for all the input buffers to become available.
1339    // This give timelapse video recording faster response in
1340    // receiving output from video encoder component.
1341    if (mCaptureTimeLapse) {
1342        encoder_flags |= OMXCodec::kOnlySubmitOneInputBufferAtOneTime;
1343    }
1344
1345    sp<MediaSource> encoder = OMXCodec::Create(
1346            client.interface(), enc_meta,
1347            true /* createEncoder */, cameraSource,
1348            NULL, encoder_flags);
1349    if (encoder == NULL) {
1350        LOGW("Failed to create the encoder");
1351        // When the encoder fails to be created, we need
1352        // release the camera source due to the camera's lock
1353        // and unlock mechanism.
1354        cameraSource->stop();
1355        return UNKNOWN_ERROR;
1356    }
1357
1358    *source = encoder;
1359
1360    return OK;
1361}
1362
1363status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1364    status_t status = BAD_VALUE;
1365    if (OK != (status = checkAudioEncoderCapabilities())) {
1366        return status;
1367    }
1368
1369    switch(mAudioEncoder) {
1370        case AUDIO_ENCODER_AMR_NB:
1371        case AUDIO_ENCODER_AMR_WB:
1372        case AUDIO_ENCODER_AAC:
1373            break;
1374
1375        default:
1376            LOGE("Unsupported audio encoder: %d", mAudioEncoder);
1377            return UNKNOWN_ERROR;
1378    }
1379
1380    sp<MediaSource> audioEncoder = createAudioSource();
1381    if (audioEncoder == NULL) {
1382        return UNKNOWN_ERROR;
1383    }
1384
1385    writer->addSource(audioEncoder);
1386    return OK;
1387}
1388
1389status_t StagefrightRecorder::setupMPEG4Recording(
1390        bool useSplitCameraSource,
1391        int outputFd,
1392        int32_t videoWidth, int32_t videoHeight,
1393        int32_t videoBitRate,
1394        int32_t *totalBitRate,
1395        sp<MediaWriter> *mediaWriter) {
1396    mediaWriter->clear();
1397    *totalBitRate = 0;
1398    status_t err = OK;
1399    sp<MediaWriter> writer = new MPEG4Writer(outputFd);
1400
1401    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1402            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1403
1404        sp<MediaSource> cameraMediaSource;
1405        if (useSplitCameraSource) {
1406            LOGV("Using Split camera source");
1407            cameraMediaSource = mCameraSourceSplitter->createClient();
1408        } else {
1409            sp<CameraSource> cameraSource;
1410            err = setupCameraSource(&cameraSource);
1411            cameraMediaSource = cameraSource;
1412        }
1413        if ((videoWidth != mVideoWidth) || (videoHeight != mVideoHeight)) {
1414            // Use downsampling from the original source.
1415            cameraMediaSource =
1416                new VideoSourceDownSampler(cameraMediaSource, videoWidth, videoHeight);
1417        }
1418        if (err != OK) {
1419            return err;
1420        }
1421
1422        sp<MediaSource> encoder;
1423        err = setupVideoEncoder(cameraMediaSource, videoBitRate, &encoder);
1424        if (err != OK) {
1425            return err;
1426        }
1427
1428        writer->addSource(encoder);
1429        *totalBitRate += videoBitRate;
1430    }
1431
1432    // Audio source is added at the end if it exists.
1433    // This help make sure that the "recoding" sound is suppressed for
1434    // camcorder applications in the recorded files.
1435    if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_CNT)) {
1436        err = setupAudioEncoder(writer);
1437        if (err != OK) return err;
1438        *totalBitRate += mAudioBitRate;
1439    }
1440
1441    if (mInterleaveDurationUs > 0) {
1442        reinterpret_cast<MPEG4Writer *>(writer.get())->
1443            setInterleaveDuration(mInterleaveDurationUs);
1444    }
1445    if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1446        reinterpret_cast<MPEG4Writer *>(writer.get())->
1447            setGeoData(mLatitudex10000, mLongitudex10000);
1448    }
1449    if (mMaxFileDurationUs != 0) {
1450        writer->setMaxFileDuration(mMaxFileDurationUs);
1451    }
1452    if (mMaxFileSizeBytes != 0) {
1453        writer->setMaxFileSize(mMaxFileSizeBytes);
1454    }
1455
1456    writer->setListener(mListener);
1457    *mediaWriter = writer;
1458    return OK;
1459}
1460
1461void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate,
1462        sp<MetaData> *meta) {
1463    (*meta)->setInt64(kKeyTime, startTimeUs);
1464    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1465    (*meta)->setInt32(kKeyBitRate, totalBitRate);
1466    (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1467    if (mMovieTimeScale > 0) {
1468        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1469    }
1470    if (mTrackEveryTimeDurationUs > 0) {
1471        (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1472    }
1473    if (mRotationDegrees != 0) {
1474        (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1475    }
1476}
1477
1478status_t StagefrightRecorder::startMPEG4Recording() {
1479    if (mCaptureAuxVideo) {
1480        if (!mCaptureTimeLapse) {
1481            LOGE("Auxiliary video can be captured only in time lapse mode");
1482            return UNKNOWN_ERROR;
1483        }
1484        LOGV("Creating MediaSourceSplitter");
1485        sp<CameraSource> cameraSource;
1486        status_t err = setupCameraSource(&cameraSource);
1487        if (err != OK) {
1488            return err;
1489        }
1490        mCameraSourceSplitter = new MediaSourceSplitter(cameraSource);
1491    } else {
1492        mCameraSourceSplitter = NULL;
1493    }
1494
1495    int32_t totalBitRate;
1496    status_t err = setupMPEG4Recording(mCaptureAuxVideo,
1497            mOutputFd, mVideoWidth, mVideoHeight,
1498            mVideoBitRate, &totalBitRate, &mWriter);
1499    if (err != OK) {
1500        return err;
1501    }
1502
1503    int64_t startTimeUs = systemTime() / 1000;
1504    sp<MetaData> meta = new MetaData;
1505    setupMPEG4MetaData(startTimeUs, totalBitRate, &meta);
1506
1507    err = mWriter->start(meta.get());
1508    if (err != OK) {
1509        return err;
1510    }
1511
1512    if (mCaptureAuxVideo) {
1513        CHECK(mOutputFdAux >= 0);
1514        if (mWriterAux != NULL) {
1515            LOGE("Auxiliary File writer is not avaialble");
1516            return UNKNOWN_ERROR;
1517        }
1518        if ((mAuxVideoWidth > mVideoWidth) || (mAuxVideoHeight > mVideoHeight) ||
1519                ((mAuxVideoWidth == mVideoWidth) && mAuxVideoHeight == mVideoHeight)) {
1520            LOGE("Auxiliary video size (%d x %d) same or larger than the main video size (%d x %d)",
1521                    mAuxVideoWidth, mAuxVideoHeight, mVideoWidth, mVideoHeight);
1522            return UNKNOWN_ERROR;
1523        }
1524
1525        int32_t totalBitrateAux;
1526        err = setupMPEG4Recording(mCaptureAuxVideo,
1527                mOutputFdAux, mAuxVideoWidth, mAuxVideoHeight,
1528                mAuxVideoBitRate, &totalBitrateAux, &mWriterAux);
1529        if (err != OK) {
1530            return err;
1531        }
1532
1533        sp<MetaData> metaAux = new MetaData;
1534        setupMPEG4MetaData(startTimeUs, totalBitrateAux, &metaAux);
1535
1536        return mWriterAux->start(metaAux.get());
1537    }
1538
1539    return OK;
1540}
1541
1542status_t StagefrightRecorder::pause() {
1543    LOGV("pause");
1544    if (mWriter == NULL) {
1545        return UNKNOWN_ERROR;
1546    }
1547    mWriter->pause();
1548
1549    if (mCaptureAuxVideo) {
1550        if (mWriterAux == NULL) {
1551            return UNKNOWN_ERROR;
1552        }
1553        mWriterAux->pause();
1554    }
1555
1556    if (mStarted) {
1557        mStarted = false;
1558
1559        uint32_t params = 0;
1560        if (mAudioSource != AUDIO_SOURCE_CNT) {
1561            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1562        }
1563        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1564            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1565        }
1566
1567        addBatteryData(params);
1568    }
1569
1570
1571    return OK;
1572}
1573
1574status_t StagefrightRecorder::stop() {
1575    LOGV("stop");
1576    status_t err = OK;
1577
1578    if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) {
1579        mCameraSourceTimeLapse->startQuickReadReturns();
1580        mCameraSourceTimeLapse = NULL;
1581    }
1582
1583    if (mCaptureAuxVideo) {
1584        if (mWriterAux != NULL) {
1585            mWriterAux->stop();
1586            mWriterAux.clear();
1587        }
1588    }
1589
1590    if (mWriter != NULL) {
1591        err = mWriter->stop();
1592        mWriter.clear();
1593    }
1594
1595    if (mOutputFd >= 0) {
1596        ::close(mOutputFd);
1597        mOutputFd = -1;
1598    }
1599
1600    if (mCaptureAuxVideo) {
1601        if (mOutputFdAux >= 0) {
1602            ::close(mOutputFdAux);
1603            mOutputFdAux = -1;
1604        }
1605    }
1606
1607    if (mStarted) {
1608        mStarted = false;
1609
1610        uint32_t params = 0;
1611        if (mAudioSource != AUDIO_SOURCE_CNT) {
1612            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1613        }
1614        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1615            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1616        }
1617
1618        addBatteryData(params);
1619    }
1620
1621
1622    return err;
1623}
1624
1625status_t StagefrightRecorder::close() {
1626    LOGV("close");
1627    stop();
1628
1629    return OK;
1630}
1631
1632status_t StagefrightRecorder::reset() {
1633    LOGV("reset");
1634    stop();
1635
1636    // No audio or video source by default
1637    mAudioSource = AUDIO_SOURCE_CNT;
1638    mVideoSource = VIDEO_SOURCE_LIST_END;
1639
1640    // Default parameters
1641    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1642    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1643    mVideoEncoder  = VIDEO_ENCODER_H263;
1644    mVideoWidth    = 176;
1645    mVideoHeight   = 144;
1646    mAuxVideoWidth    = 176;
1647    mAuxVideoHeight   = 144;
1648    mFrameRate     = -1;
1649    mVideoBitRate  = 192000;
1650    mAuxVideoBitRate = 192000;
1651    mSampleRate    = 8000;
1652    mAudioChannels = 1;
1653    mAudioBitRate  = 12200;
1654    mInterleaveDurationUs = 0;
1655    mIFramesIntervalSec = 1;
1656    mAudioSourceNode = 0;
1657    mUse64BitFileOffset = false;
1658    mMovieTimeScale  = -1;
1659    mAudioTimeScale  = -1;
1660    mVideoTimeScale  = -1;
1661    mCameraId        = 0;
1662    mVideoEncoderProfile = -1;
1663    mVideoEncoderLevel   = -1;
1664    mMaxFileDurationUs = 0;
1665    mMaxFileSizeBytes = 0;
1666    mTrackEveryTimeDurationUs = 0;
1667    mCaptureTimeLapse = false;
1668    mTimeBetweenTimeLapseFrameCaptureUs = -1;
1669    mCaptureAuxVideo = false;
1670    mCameraSourceSplitter = NULL;
1671    mCameraSourceTimeLapse = NULL;
1672    mIsMetaDataStoredInVideoBuffers = false;
1673    mEncoderProfiles = MediaProfiles::getInstance();
1674    mRotationDegrees = 0;
1675    mLatitudex10000 = -3600000;
1676    mLongitudex10000 = -3600000;
1677
1678    mOutputFd = -1;
1679    mOutputFdAux = -1;
1680
1681    return OK;
1682}
1683
1684status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1685    LOGV("getMaxAmplitude");
1686
1687    if (max == NULL) {
1688        LOGE("Null pointer argument");
1689        return BAD_VALUE;
1690    }
1691
1692    if (mAudioSourceNode != 0) {
1693        *max = mAudioSourceNode->getMaxAmplitude();
1694    } else {
1695        *max = 0;
1696    }
1697
1698    return OK;
1699}
1700
1701status_t StagefrightRecorder::dump(
1702        int fd, const Vector<String16>& args) const {
1703    LOGV("dump");
1704    const size_t SIZE = 256;
1705    char buffer[SIZE];
1706    String8 result;
1707    if (mWriter != 0) {
1708        mWriter->dump(fd, args);
1709    } else {
1710        snprintf(buffer, SIZE, "   No file writer\n");
1711        result.append(buffer);
1712    }
1713    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1714    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1715    result.append(buffer);
1716    snprintf(buffer, SIZE, "   Output file Auxiliary (fd %d):\n", mOutputFdAux);
1717    result.append(buffer);
1718    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1719    result.append(buffer);
1720    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1721    result.append(buffer);
1722    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
1723    result.append(buffer);
1724    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1725    result.append(buffer);
1726    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1727    result.append(buffer);
1728    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1729    result.append(buffer);
1730    snprintf(buffer, SIZE, "   Audio\n");
1731    result.append(buffer);
1732    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1733    result.append(buffer);
1734    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1735    result.append(buffer);
1736    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1737    result.append(buffer);
1738    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1739    result.append(buffer);
1740    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1741    result.append(buffer);
1742    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1743    result.append(buffer);
1744    snprintf(buffer, SIZE, "   Video\n");
1745    result.append(buffer);
1746    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1747    result.append(buffer);
1748    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1749    result.append(buffer);
1750    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1751    result.append(buffer);
1752    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1753    result.append(buffer);
1754    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1755    result.append(buffer);
1756    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1757    result.append(buffer);
1758    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1759    result.append(buffer);
1760    snprintf(buffer, SIZE, "     Aux Frame size (pixels): %dx%d\n", mAuxVideoWidth, mAuxVideoHeight);
1761    result.append(buffer);
1762    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1763    result.append(buffer);
1764    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1765    result.append(buffer);
1766    snprintf(buffer, SIZE, "     Aux Bit rate (bps): %d\n", mAuxVideoBitRate);
1767    result.append(buffer);
1768    ::write(fd, result.string(), result.size());
1769    return OK;
1770}
1771}  // namespace android
1772