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