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