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