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