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