StagefrightRecorder.cpp revision aeb8fd460ed87d032b3fb8bb61e21eb542ce0f5b
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<ISurfaceTexture> 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_AAC_ELD:
824            mime = MEDIA_MIMETYPE_AUDIO_AAC;
825            encMeta->setInt32(kKeyAACProfile, OMX_AUDIO_AACObjectELD);
826            break;
827        default:
828            ALOGE("Unknown audio encoder: %d", mAudioEncoder);
829            return NULL;
830    }
831    encMeta->setCString(kKeyMIMEType, mime);
832
833    int32_t maxInputSize;
834    CHECK(audioSource->getFormat()->findInt32(
835                kKeyMaxInputSize, &maxInputSize));
836
837    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
838    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
839    encMeta->setInt32(kKeySampleRate, mSampleRate);
840    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
841    if (mAudioTimeScale > 0) {
842        encMeta->setInt32(kKeyTimeScale, mAudioTimeScale);
843    }
844
845    OMXClient client;
846    CHECK_EQ(client.connect(), (status_t)OK);
847
848    sp<MediaSource> audioEncoder =
849        OMXCodec::Create(client.interface(), encMeta,
850                         true /* createEncoder */, audioSource);
851    mAudioSourceNode = audioSource;
852
853    return audioEncoder;
854}
855
856status_t StagefrightRecorder::startAACRecording() {
857    // FIXME:
858    // Add support for OUTPUT_FORMAT_AAC_ADIF
859    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS);
860
861    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC ||
862          mAudioEncoder == AUDIO_ENCODER_AAC_ELD);
863    CHECK(mAudioSource != AUDIO_SOURCE_CNT);
864
865    mWriter = new AACWriter(mOutputFd);
866    status_t status = startRawAudioRecording();
867    if (status != OK) {
868        mWriter.clear();
869        mWriter = NULL;
870    }
871
872    return status;
873}
874
875status_t StagefrightRecorder::startAMRRecording() {
876    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
877          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
878
879    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
880        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
881            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
882            ALOGE("Invalid encoder %d used for AMRNB recording",
883                    mAudioEncoder);
884            return BAD_VALUE;
885        }
886    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
887        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
888            ALOGE("Invlaid encoder %d used for AMRWB recording",
889                    mAudioEncoder);
890            return BAD_VALUE;
891        }
892    }
893
894    mWriter = new AMRWriter(mOutputFd);
895    status_t status = startRawAudioRecording();
896    if (status != OK) {
897        mWriter.clear();
898        mWriter = NULL;
899    }
900    return status;
901}
902
903status_t StagefrightRecorder::startRawAudioRecording() {
904    if (mAudioSource >= AUDIO_SOURCE_CNT) {
905        ALOGE("Invalid audio source: %d", mAudioSource);
906        return BAD_VALUE;
907    }
908
909    status_t status = BAD_VALUE;
910    if (OK != (status = checkAudioEncoderCapabilities())) {
911        return status;
912    }
913
914    sp<MediaSource> audioEncoder = createAudioSource();
915    if (audioEncoder == NULL) {
916        return UNKNOWN_ERROR;
917    }
918
919    CHECK(mWriter != 0);
920    mWriter->addSource(audioEncoder);
921
922    if (mMaxFileDurationUs != 0) {
923        mWriter->setMaxFileDuration(mMaxFileDurationUs);
924    }
925    if (mMaxFileSizeBytes != 0) {
926        mWriter->setMaxFileSize(mMaxFileSizeBytes);
927    }
928    mWriter->setListener(mListener);
929    mWriter->start();
930
931    return OK;
932}
933
934status_t StagefrightRecorder::startRTPRecording() {
935    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
936
937    if ((mAudioSource != AUDIO_SOURCE_CNT
938                && mVideoSource != VIDEO_SOURCE_LIST_END)
939            || (mAudioSource == AUDIO_SOURCE_CNT
940                && mVideoSource == VIDEO_SOURCE_LIST_END)) {
941        // Must have exactly one source.
942        return BAD_VALUE;
943    }
944
945    if (mOutputFd < 0) {
946        return BAD_VALUE;
947    }
948
949    sp<MediaSource> source;
950
951    if (mAudioSource != AUDIO_SOURCE_CNT) {
952        source = createAudioSource();
953    } else {
954
955        sp<MediaSource> mediaSource;
956        status_t err = setupMediaSource(&mediaSource);
957        if (err != OK) {
958            return err;
959        }
960
961        err = setupVideoEncoder(mediaSource, mVideoBitRate, &source);
962        if (err != OK) {
963            return err;
964        }
965    }
966
967    mWriter = new ARTPWriter(mOutputFd);
968    mWriter->addSource(source);
969    mWriter->setListener(mListener);
970
971    return mWriter->start();
972}
973
974status_t StagefrightRecorder::startMPEG2TSRecording() {
975    CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
976
977    sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
978
979    if (mAudioSource != AUDIO_SOURCE_CNT) {
980        if (mAudioEncoder != AUDIO_ENCODER_AAC) {
981            return ERROR_UNSUPPORTED;
982        }
983
984        status_t err = setupAudioEncoder(writer);
985
986        if (err != OK) {
987            return err;
988        }
989    }
990
991    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
992        if (mVideoEncoder != VIDEO_ENCODER_H264) {
993            return ERROR_UNSUPPORTED;
994        }
995
996        sp<MediaSource> mediaSource;
997        status_t err = setupMediaSource(&mediaSource);
998        if (err != OK) {
999            return err;
1000        }
1001
1002        sp<MediaSource> encoder;
1003        err = setupVideoEncoder(mediaSource, mVideoBitRate, &encoder);
1004
1005        if (err != OK) {
1006            return err;
1007        }
1008
1009        writer->addSource(encoder);
1010    }
1011
1012    if (mMaxFileDurationUs != 0) {
1013        writer->setMaxFileDuration(mMaxFileDurationUs);
1014    }
1015
1016    if (mMaxFileSizeBytes != 0) {
1017        writer->setMaxFileSize(mMaxFileSizeBytes);
1018    }
1019
1020    mWriter = writer;
1021
1022    return mWriter->start();
1023}
1024
1025void StagefrightRecorder::clipVideoFrameRate() {
1026    ALOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1027    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1028                        "enc.vid.fps.min", mVideoEncoder);
1029    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1030                        "enc.vid.fps.max", mVideoEncoder);
1031    if (mFrameRate < minFrameRate && mFrameRate != -1) {
1032        ALOGW("Intended video encoding frame rate (%d fps) is too small"
1033             " and will be set to (%d fps)", mFrameRate, minFrameRate);
1034        mFrameRate = minFrameRate;
1035    } else if (mFrameRate > maxFrameRate) {
1036        ALOGW("Intended video encoding frame rate (%d fps) is too large"
1037             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1038        mFrameRate = maxFrameRate;
1039    }
1040}
1041
1042void StagefrightRecorder::clipVideoBitRate() {
1043    ALOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1044    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1045                        "enc.vid.bps.min", mVideoEncoder);
1046    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1047                        "enc.vid.bps.max", mVideoEncoder);
1048    if (mVideoBitRate < minBitRate) {
1049        ALOGW("Intended video encoding bit rate (%d bps) is too small"
1050             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1051        mVideoBitRate = minBitRate;
1052    } else if (mVideoBitRate > maxBitRate) {
1053        ALOGW("Intended video encoding bit rate (%d bps) is too large"
1054             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1055        mVideoBitRate = maxBitRate;
1056    }
1057}
1058
1059void StagefrightRecorder::clipVideoFrameWidth() {
1060    ALOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1061    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1062                        "enc.vid.width.min", mVideoEncoder);
1063    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1064                        "enc.vid.width.max", mVideoEncoder);
1065    if (mVideoWidth < minFrameWidth) {
1066        ALOGW("Intended video encoding frame width (%d) is too small"
1067             " and will be set to (%d)", mVideoWidth, minFrameWidth);
1068        mVideoWidth = minFrameWidth;
1069    } else if (mVideoWidth > maxFrameWidth) {
1070        ALOGW("Intended video encoding frame width (%d) is too large"
1071             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1072        mVideoWidth = maxFrameWidth;
1073    }
1074}
1075
1076status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1077    if (!mCaptureTimeLapse) {
1078        // Dont clip for time lapse capture as encoder will have enough
1079        // time to encode because of slow capture rate of time lapse.
1080        clipVideoBitRate();
1081        clipVideoFrameRate();
1082        clipVideoFrameWidth();
1083        clipVideoFrameHeight();
1084        setDefaultProfileIfNecessary();
1085    }
1086    return OK;
1087}
1088
1089// Set to use AVC baseline profile if the encoding parameters matches
1090// CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service.
1091void StagefrightRecorder::setDefaultProfileIfNecessary() {
1092    ALOGV("setDefaultProfileIfNecessary");
1093
1094    camcorder_quality quality = CAMCORDER_QUALITY_LOW;
1095
1096    int64_t durationUs   = mEncoderProfiles->getCamcorderProfileParamByName(
1097                                "duration", mCameraId, quality) * 1000000LL;
1098
1099    int fileFormat       = mEncoderProfiles->getCamcorderProfileParamByName(
1100                                "file.format", mCameraId, quality);
1101
1102    int videoCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1103                                "vid.codec", mCameraId, quality);
1104
1105    int videoBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1106                                "vid.bps", mCameraId, quality);
1107
1108    int videoFrameRate   = mEncoderProfiles->getCamcorderProfileParamByName(
1109                                "vid.fps", mCameraId, quality);
1110
1111    int videoFrameWidth  = mEncoderProfiles->getCamcorderProfileParamByName(
1112                                "vid.width", mCameraId, quality);
1113
1114    int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName(
1115                                "vid.height", mCameraId, quality);
1116
1117    int audioCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1118                                "aud.codec", mCameraId, quality);
1119
1120    int audioBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1121                                "aud.bps", mCameraId, quality);
1122
1123    int audioSampleRate  = mEncoderProfiles->getCamcorderProfileParamByName(
1124                                "aud.hz", mCameraId, quality);
1125
1126    int audioChannels    = mEncoderProfiles->getCamcorderProfileParamByName(
1127                                "aud.ch", mCameraId, quality);
1128
1129    if (durationUs == mMaxFileDurationUs &&
1130        fileFormat == mOutputFormat &&
1131        videoCodec == mVideoEncoder &&
1132        videoBitRate == mVideoBitRate &&
1133        videoFrameRate == mFrameRate &&
1134        videoFrameWidth == mVideoWidth &&
1135        videoFrameHeight == mVideoHeight &&
1136        audioCodec == mAudioEncoder &&
1137        audioBitRate == mAudioBitRate &&
1138        audioSampleRate == mSampleRate &&
1139        audioChannels == mAudioChannels) {
1140        if (videoCodec == VIDEO_ENCODER_H264) {
1141            ALOGI("Force to use AVC baseline profile");
1142            setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline);
1143        }
1144    }
1145}
1146
1147status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1148    clipAudioBitRate();
1149    clipAudioSampleRate();
1150    clipNumberOfAudioChannels();
1151    return OK;
1152}
1153
1154void StagefrightRecorder::clipAudioBitRate() {
1155    ALOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1156
1157    int minAudioBitRate =
1158            mEncoderProfiles->getAudioEncoderParamByName(
1159                "enc.aud.bps.min", mAudioEncoder);
1160    if (mAudioBitRate < minAudioBitRate) {
1161        ALOGW("Intended audio encoding bit rate (%d) is too small"
1162            " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1163        mAudioBitRate = minAudioBitRate;
1164    }
1165
1166    int maxAudioBitRate =
1167            mEncoderProfiles->getAudioEncoderParamByName(
1168                "enc.aud.bps.max", mAudioEncoder);
1169    if (mAudioBitRate > maxAudioBitRate) {
1170        ALOGW("Intended audio encoding bit rate (%d) is too large"
1171            " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1172        mAudioBitRate = maxAudioBitRate;
1173    }
1174}
1175
1176void StagefrightRecorder::clipAudioSampleRate() {
1177    ALOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1178
1179    int minSampleRate =
1180            mEncoderProfiles->getAudioEncoderParamByName(
1181                "enc.aud.hz.min", mAudioEncoder);
1182    if (mSampleRate < minSampleRate) {
1183        ALOGW("Intended audio sample rate (%d) is too small"
1184            " and will be set to (%d)", mSampleRate, minSampleRate);
1185        mSampleRate = minSampleRate;
1186    }
1187
1188    int maxSampleRate =
1189            mEncoderProfiles->getAudioEncoderParamByName(
1190                "enc.aud.hz.max", mAudioEncoder);
1191    if (mSampleRate > maxSampleRate) {
1192        ALOGW("Intended audio sample rate (%d) is too large"
1193            " and will be set to (%d)", mSampleRate, maxSampleRate);
1194        mSampleRate = maxSampleRate;
1195    }
1196}
1197
1198void StagefrightRecorder::clipNumberOfAudioChannels() {
1199    ALOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1200
1201    int minChannels =
1202            mEncoderProfiles->getAudioEncoderParamByName(
1203                "enc.aud.ch.min", mAudioEncoder);
1204    if (mAudioChannels < minChannels) {
1205        ALOGW("Intended number of audio channels (%d) is too small"
1206            " and will be set to (%d)", mAudioChannels, minChannels);
1207        mAudioChannels = minChannels;
1208    }
1209
1210    int maxChannels =
1211            mEncoderProfiles->getAudioEncoderParamByName(
1212                "enc.aud.ch.max", mAudioEncoder);
1213    if (mAudioChannels > maxChannels) {
1214        ALOGW("Intended number of audio channels (%d) is too large"
1215            " and will be set to (%d)", mAudioChannels, maxChannels);
1216        mAudioChannels = maxChannels;
1217    }
1218}
1219
1220void StagefrightRecorder::clipVideoFrameHeight() {
1221    ALOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1222    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1223                        "enc.vid.height.min", mVideoEncoder);
1224    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1225                        "enc.vid.height.max", mVideoEncoder);
1226    if (mVideoHeight < minFrameHeight) {
1227        ALOGW("Intended video encoding frame height (%d) is too small"
1228             " and will be set to (%d)", mVideoHeight, minFrameHeight);
1229        mVideoHeight = minFrameHeight;
1230    } else if (mVideoHeight > maxFrameHeight) {
1231        ALOGW("Intended video encoding frame height (%d) is too large"
1232             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1233        mVideoHeight = maxFrameHeight;
1234    }
1235}
1236
1237// Set up the appropriate MediaSource depending on the chosen option
1238status_t StagefrightRecorder::setupMediaSource(
1239                      sp<MediaSource> *mediaSource) {
1240    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1241            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1242        sp<CameraSource> cameraSource;
1243        status_t err = setupCameraSource(&cameraSource);
1244        if (err != OK) {
1245            return err;
1246        }
1247        *mediaSource = cameraSource;
1248    } else if (mVideoSource == VIDEO_SOURCE_GRALLOC_BUFFER) {
1249        // If using GRAlloc buffers, setup surfacemediasource.
1250        // Later a handle to that will be passed
1251        // to the client side when queried
1252        status_t err = setupSurfaceMediaSource();
1253        if (err != OK) {
1254            return err;
1255        }
1256        *mediaSource = mSurfaceMediaSource;
1257    } else {
1258        return INVALID_OPERATION;
1259    }
1260    return OK;
1261}
1262
1263// setupSurfaceMediaSource creates a source with the given
1264// width and height and framerate.
1265// TODO: This could go in a static function inside SurfaceMediaSource
1266// similar to that in CameraSource
1267status_t StagefrightRecorder::setupSurfaceMediaSource() {
1268    status_t err = OK;
1269    mSurfaceMediaSource = new SurfaceMediaSource(mVideoWidth, mVideoHeight);
1270    if (mSurfaceMediaSource == NULL) {
1271        return NO_INIT;
1272    }
1273
1274    if (mFrameRate == -1) {
1275        int32_t frameRate = 0;
1276        CHECK (mSurfaceMediaSource->getFormat()->findInt32(
1277                                        kKeyFrameRate, &frameRate));
1278        ALOGI("Frame rate is not explicitly set. Use the current frame "
1279             "rate (%d fps)", frameRate);
1280        mFrameRate = frameRate;
1281    } else {
1282        err = mSurfaceMediaSource->setFrameRate(mFrameRate);
1283    }
1284    CHECK(mFrameRate != -1);
1285
1286    mIsMetaDataStoredInVideoBuffers =
1287        mSurfaceMediaSource->isMetaDataStoredInVideoBuffers();
1288    return err;
1289}
1290
1291status_t StagefrightRecorder::setupCameraSource(
1292        sp<CameraSource> *cameraSource) {
1293    status_t err = OK;
1294    if ((err = checkVideoEncoderCapabilities()) != OK) {
1295        return err;
1296    }
1297    Size videoSize;
1298    videoSize.width = mVideoWidth;
1299    videoSize.height = mVideoHeight;
1300    if (mCaptureTimeLapse) {
1301        if (mTimeBetweenTimeLapseFrameCaptureUs < 0) {
1302            ALOGE("Invalid mTimeBetweenTimeLapseFrameCaptureUs value: %lld",
1303                mTimeBetweenTimeLapseFrameCaptureUs);
1304            return BAD_VALUE;
1305        }
1306
1307        mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1308                mCamera, mCameraProxy, mCameraId,
1309                videoSize, mFrameRate, mPreviewSurface,
1310                mTimeBetweenTimeLapseFrameCaptureUs);
1311        *cameraSource = mCameraSourceTimeLapse;
1312    } else {
1313        *cameraSource = CameraSource::CreateFromCamera(
1314                mCamera, mCameraProxy, mCameraId, videoSize, mFrameRate,
1315                mPreviewSurface, true /*storeMetaDataInVideoBuffers*/);
1316    }
1317    mCamera.clear();
1318    mCameraProxy.clear();
1319    if (*cameraSource == NULL) {
1320        return UNKNOWN_ERROR;
1321    }
1322
1323    if ((*cameraSource)->initCheck() != OK) {
1324        (*cameraSource).clear();
1325        *cameraSource = NULL;
1326        return NO_INIT;
1327    }
1328
1329    // When frame rate is not set, the actual frame rate will be set to
1330    // the current frame rate being used.
1331    if (mFrameRate == -1) {
1332        int32_t frameRate = 0;
1333        CHECK ((*cameraSource)->getFormat()->findInt32(
1334                    kKeyFrameRate, &frameRate));
1335        ALOGI("Frame rate is not explicitly set. Use the current frame "
1336             "rate (%d fps)", frameRate);
1337        mFrameRate = frameRate;
1338    }
1339
1340    CHECK(mFrameRate != -1);
1341
1342    mIsMetaDataStoredInVideoBuffers =
1343        (*cameraSource)->isMetaDataStoredInVideoBuffers();
1344
1345    return OK;
1346}
1347
1348status_t StagefrightRecorder::setupVideoEncoder(
1349        sp<MediaSource> cameraSource,
1350        int32_t videoBitRate,
1351        sp<MediaSource> *source) {
1352    source->clear();
1353
1354    sp<MetaData> enc_meta = new MetaData;
1355    enc_meta->setInt32(kKeyBitRate, videoBitRate);
1356    enc_meta->setInt32(kKeyFrameRate, mFrameRate);
1357
1358    switch (mVideoEncoder) {
1359        case VIDEO_ENCODER_H263:
1360            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
1361            break;
1362
1363        case VIDEO_ENCODER_MPEG_4_SP:
1364            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
1365            break;
1366
1367        case VIDEO_ENCODER_H264:
1368            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
1369            break;
1370
1371        default:
1372            CHECK(!"Should not be here, unsupported video encoding.");
1373            break;
1374    }
1375
1376    sp<MetaData> meta = cameraSource->getFormat();
1377
1378    int32_t width, height, stride, sliceHeight, colorFormat;
1379    CHECK(meta->findInt32(kKeyWidth, &width));
1380    CHECK(meta->findInt32(kKeyHeight, &height));
1381    CHECK(meta->findInt32(kKeyStride, &stride));
1382    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1383    CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1384
1385    enc_meta->setInt32(kKeyWidth, width);
1386    enc_meta->setInt32(kKeyHeight, height);
1387    enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
1388    enc_meta->setInt32(kKeyStride, stride);
1389    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
1390    enc_meta->setInt32(kKeyColorFormat, colorFormat);
1391    if (mVideoTimeScale > 0) {
1392        enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
1393    }
1394    if (mVideoEncoderProfile != -1) {
1395        enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
1396    }
1397    if (mVideoEncoderLevel != -1) {
1398        enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
1399    }
1400
1401    OMXClient client;
1402    CHECK_EQ(client.connect(), (status_t)OK);
1403
1404    uint32_t encoder_flags = 0;
1405    if (mIsMetaDataStoredInVideoBuffers) {
1406        encoder_flags |= OMXCodec::kHardwareCodecsOnly;
1407        encoder_flags |= OMXCodec::kStoreMetaDataInVideoBuffers;
1408    }
1409
1410    // Do not wait for all the input buffers to become available.
1411    // This give timelapse video recording faster response in
1412    // receiving output from video encoder component.
1413    if (mCaptureTimeLapse) {
1414        encoder_flags |= OMXCodec::kOnlySubmitOneInputBufferAtOneTime;
1415    }
1416
1417    sp<MediaSource> encoder = OMXCodec::Create(
1418            client.interface(), enc_meta,
1419            true /* createEncoder */, cameraSource,
1420            NULL, encoder_flags);
1421    if (encoder == NULL) {
1422        ALOGW("Failed to create the encoder");
1423        // When the encoder fails to be created, we need
1424        // release the camera source due to the camera's lock
1425        // and unlock mechanism.
1426        cameraSource->stop();
1427        return UNKNOWN_ERROR;
1428    }
1429
1430    *source = encoder;
1431
1432    return OK;
1433}
1434
1435status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1436    status_t status = BAD_VALUE;
1437    if (OK != (status = checkAudioEncoderCapabilities())) {
1438        return status;
1439    }
1440
1441    switch(mAudioEncoder) {
1442        case AUDIO_ENCODER_AMR_NB:
1443        case AUDIO_ENCODER_AMR_WB:
1444        case AUDIO_ENCODER_AAC:
1445        case AUDIO_ENCODER_AAC_ELD:
1446            break;
1447
1448        default:
1449            ALOGE("Unsupported audio encoder: %d", mAudioEncoder);
1450            return UNKNOWN_ERROR;
1451    }
1452
1453    sp<MediaSource> audioEncoder = createAudioSource();
1454    if (audioEncoder == NULL) {
1455        return UNKNOWN_ERROR;
1456    }
1457
1458    writer->addSource(audioEncoder);
1459    return OK;
1460}
1461
1462status_t StagefrightRecorder::setupMPEG4Recording(
1463        int outputFd,
1464        int32_t videoWidth, int32_t videoHeight,
1465        int32_t videoBitRate,
1466        int32_t *totalBitRate,
1467        sp<MediaWriter> *mediaWriter) {
1468    mediaWriter->clear();
1469    *totalBitRate = 0;
1470    status_t err = OK;
1471    sp<MediaWriter> writer = new MPEG4Writer(outputFd);
1472
1473    if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1474
1475        sp<MediaSource> mediaSource;
1476        err = setupMediaSource(&mediaSource);
1477        if (err != OK) {
1478            return err;
1479        }
1480
1481        sp<MediaSource> encoder;
1482        err = setupVideoEncoder(mediaSource, videoBitRate, &encoder);
1483        if (err != OK) {
1484            return err;
1485        }
1486
1487        writer->addSource(encoder);
1488        *totalBitRate += videoBitRate;
1489    }
1490
1491    // Audio source is added at the end if it exists.
1492    // This help make sure that the "recoding" sound is suppressed for
1493    // camcorder applications in the recorded files.
1494    if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_CNT)) {
1495        err = setupAudioEncoder(writer);
1496        if (err != OK) return err;
1497        *totalBitRate += mAudioBitRate;
1498    }
1499
1500    if (mInterleaveDurationUs > 0) {
1501        reinterpret_cast<MPEG4Writer *>(writer.get())->
1502            setInterleaveDuration(mInterleaveDurationUs);
1503    }
1504    if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1505        reinterpret_cast<MPEG4Writer *>(writer.get())->
1506            setGeoData(mLatitudex10000, mLongitudex10000);
1507    }
1508    if (mMaxFileDurationUs != 0) {
1509        writer->setMaxFileDuration(mMaxFileDurationUs);
1510    }
1511    if (mMaxFileSizeBytes != 0) {
1512        writer->setMaxFileSize(mMaxFileSizeBytes);
1513    }
1514
1515    mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1516    if (mStartTimeOffsetMs > 0) {
1517        reinterpret_cast<MPEG4Writer *>(writer.get())->
1518            setStartTimeOffsetMs(mStartTimeOffsetMs);
1519    }
1520
1521    writer->setListener(mListener);
1522    *mediaWriter = writer;
1523    return OK;
1524}
1525
1526void StagefrightRecorder::setupMPEG4MetaData(int64_t startTimeUs, int32_t totalBitRate,
1527        sp<MetaData> *meta) {
1528    (*meta)->setInt64(kKeyTime, startTimeUs);
1529    (*meta)->setInt32(kKeyFileType, mOutputFormat);
1530    (*meta)->setInt32(kKeyBitRate, totalBitRate);
1531    (*meta)->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1532    if (mMovieTimeScale > 0) {
1533        (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
1534    }
1535    if (mTrackEveryTimeDurationUs > 0) {
1536        (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1537    }
1538    if (mRotationDegrees != 0) {
1539        (*meta)->setInt32(kKeyRotation, mRotationDegrees);
1540    }
1541}
1542
1543status_t StagefrightRecorder::startMPEG4Recording() {
1544    int32_t totalBitRate;
1545    status_t err = setupMPEG4Recording(
1546            mOutputFd, mVideoWidth, mVideoHeight,
1547            mVideoBitRate, &totalBitRate, &mWriter);
1548    if (err != OK) {
1549        return err;
1550    }
1551
1552    int64_t startTimeUs = systemTime() / 1000;
1553    sp<MetaData> meta = new MetaData;
1554    setupMPEG4MetaData(startTimeUs, totalBitRate, &meta);
1555
1556    err = mWriter->start(meta.get());
1557    if (err != OK) {
1558        return err;
1559    }
1560
1561    return OK;
1562}
1563
1564status_t StagefrightRecorder::pause() {
1565    ALOGV("pause");
1566    if (mWriter == NULL) {
1567        return UNKNOWN_ERROR;
1568    }
1569    mWriter->pause();
1570
1571    if (mStarted) {
1572        mStarted = false;
1573
1574        uint32_t params = 0;
1575        if (mAudioSource != AUDIO_SOURCE_CNT) {
1576            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1577        }
1578        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1579            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1580        }
1581
1582        addBatteryData(params);
1583    }
1584
1585
1586    return OK;
1587}
1588
1589status_t StagefrightRecorder::stop() {
1590    ALOGV("stop");
1591    status_t err = OK;
1592
1593    if (mCaptureTimeLapse && mCameraSourceTimeLapse != NULL) {
1594        mCameraSourceTimeLapse->startQuickReadReturns();
1595        mCameraSourceTimeLapse = NULL;
1596    }
1597
1598    if (mWriter != NULL) {
1599        err = mWriter->stop();
1600        mWriter.clear();
1601    }
1602
1603    if (mOutputFd >= 0) {
1604        ::close(mOutputFd);
1605        mOutputFd = -1;
1606    }
1607
1608    if (mStarted) {
1609        mStarted = false;
1610
1611        uint32_t params = 0;
1612        if (mAudioSource != AUDIO_SOURCE_CNT) {
1613            params |= IMediaPlayerService::kBatteryDataTrackAudio;
1614        }
1615        if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1616            params |= IMediaPlayerService::kBatteryDataTrackVideo;
1617        }
1618
1619        addBatteryData(params);
1620    }
1621
1622
1623    return err;
1624}
1625
1626status_t StagefrightRecorder::close() {
1627    ALOGV("close");
1628    stop();
1629
1630    return OK;
1631}
1632
1633status_t StagefrightRecorder::reset() {
1634    ALOGV("reset");
1635    stop();
1636
1637    // No audio or video source by default
1638    mAudioSource = AUDIO_SOURCE_CNT;
1639    mVideoSource = VIDEO_SOURCE_LIST_END;
1640
1641    // Default parameters
1642    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1643    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1644    mVideoEncoder  = VIDEO_ENCODER_H263;
1645    mVideoWidth    = 176;
1646    mVideoHeight   = 144;
1647    mFrameRate     = -1;
1648    mVideoBitRate  = 192000;
1649    mSampleRate    = 8000;
1650    mAudioChannels = 1;
1651    mAudioBitRate  = 12200;
1652    mInterleaveDurationUs = 0;
1653    mIFramesIntervalSec = 1;
1654    mAudioSourceNode = 0;
1655    mUse64BitFileOffset = false;
1656    mMovieTimeScale  = -1;
1657    mAudioTimeScale  = -1;
1658    mVideoTimeScale  = -1;
1659    mCameraId        = 0;
1660    mStartTimeOffsetMs = -1;
1661    mVideoEncoderProfile = -1;
1662    mVideoEncoderLevel   = -1;
1663    mMaxFileDurationUs = 0;
1664    mMaxFileSizeBytes = 0;
1665    mTrackEveryTimeDurationUs = 0;
1666    mCaptureTimeLapse = false;
1667    mTimeBetweenTimeLapseFrameCaptureUs = -1;
1668    mCameraSourceTimeLapse = NULL;
1669    mIsMetaDataStoredInVideoBuffers = false;
1670    mEncoderProfiles = MediaProfiles::getInstance();
1671    mRotationDegrees = 0;
1672    mLatitudex10000 = -3600000;
1673    mLongitudex10000 = -3600000;
1674
1675    mOutputFd = -1;
1676
1677    return OK;
1678}
1679
1680status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1681    ALOGV("getMaxAmplitude");
1682
1683    if (max == NULL) {
1684        ALOGE("Null pointer argument");
1685        return BAD_VALUE;
1686    }
1687
1688    if (mAudioSourceNode != 0) {
1689        *max = mAudioSourceNode->getMaxAmplitude();
1690    } else {
1691        *max = 0;
1692    }
1693
1694    return OK;
1695}
1696
1697status_t StagefrightRecorder::dump(
1698        int fd, const Vector<String16>& args) const {
1699    ALOGV("dump");
1700    const size_t SIZE = 256;
1701    char buffer[SIZE];
1702    String8 result;
1703    if (mWriter != 0) {
1704        mWriter->dump(fd, args);
1705    } else {
1706        snprintf(buffer, SIZE, "   No file writer\n");
1707        result.append(buffer);
1708    }
1709    snprintf(buffer, SIZE, "   Recorder: %p\n", this);
1710    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1711    result.append(buffer);
1712    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1713    result.append(buffer);
1714    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1715    result.append(buffer);
1716    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
1717    result.append(buffer);
1718    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1719    result.append(buffer);
1720    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1721    result.append(buffer);
1722    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1723    result.append(buffer);
1724    snprintf(buffer, SIZE, "   Audio\n");
1725    result.append(buffer);
1726    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1727    result.append(buffer);
1728    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1729    result.append(buffer);
1730    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1731    result.append(buffer);
1732    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1733    result.append(buffer);
1734    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1735    result.append(buffer);
1736    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1737    result.append(buffer);
1738    snprintf(buffer, SIZE, "   Video\n");
1739    result.append(buffer);
1740    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1741    result.append(buffer);
1742    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1743    result.append(buffer);
1744    snprintf(buffer, SIZE, "     Start time offset (ms): %d\n", mStartTimeOffsetMs);
1745    result.append(buffer);
1746    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1747    result.append(buffer);
1748    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1749    result.append(buffer);
1750    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1751    result.append(buffer);
1752    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1753    result.append(buffer);
1754    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1755    result.append(buffer);
1756    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1757    result.append(buffer);
1758    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1759    result.append(buffer);
1760    ::write(fd, result.string(), result.size());
1761    return OK;
1762}
1763}  // namespace android
1764