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