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