StagefrightRecorder.cpp revision 934da11c4cc598d3dd3b53726c362bcdcc0fd37f
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "StagefrightRecorder"
19#include <utils/Log.h>
20
21#include "StagefrightRecorder.h"
22
23#include <binder/IPCThreadState.h>
24#include <media/stagefright/AudioSource.h>
25#include <media/stagefright/AMRWriter.h>
26#include <media/stagefright/CameraSource.h>
27#include <media/stagefright/MPEG4Writer.h>
28#include <media/stagefright/MediaDebug.h>
29#include <media/stagefright/MediaDefs.h>
30#include <media/stagefright/MetaData.h>
31#include <media/stagefright/OMXClient.h>
32#include <media/stagefright/OMXCodec.h>
33#include <media/MediaProfiles.h>
34#include <camera/ICamera.h>
35#include <camera/Camera.h>
36#include <camera/CameraParameters.h>
37#include <surfaceflinger/ISurface.h>
38#include <utils/Errors.h>
39#include <sys/types.h>
40#include <unistd.h>
41#include <ctype.h>
42
43namespace android {
44
45StagefrightRecorder::StagefrightRecorder()
46    : mWriter(NULL),
47      mOutputFd(-1) {
48
49    LOGV("Constructor");
50    reset();
51}
52
53StagefrightRecorder::~StagefrightRecorder() {
54    LOGV("Destructor");
55    stop();
56
57    if (mOutputFd >= 0) {
58        ::close(mOutputFd);
59        mOutputFd = -1;
60    }
61}
62
63status_t StagefrightRecorder::init() {
64    LOGV("init");
65    return OK;
66}
67
68status_t StagefrightRecorder::setAudioSource(audio_source as) {
69    LOGV("setAudioSource: %d", as);
70    if (as < AUDIO_SOURCE_DEFAULT ||
71        as >= AUDIO_SOURCE_LIST_END) {
72        LOGE("Invalid audio source: %d", as);
73        return BAD_VALUE;
74    }
75
76    if (as == AUDIO_SOURCE_DEFAULT) {
77        mAudioSource = AUDIO_SOURCE_MIC;
78    } else {
79        mAudioSource = as;
80    }
81
82    return OK;
83}
84
85status_t StagefrightRecorder::setVideoSource(video_source vs) {
86    LOGV("setVideoSource: %d", vs);
87    if (vs < VIDEO_SOURCE_DEFAULT ||
88        vs >= VIDEO_SOURCE_LIST_END) {
89        LOGE("Invalid video source: %d", vs);
90        return BAD_VALUE;
91    }
92
93    if (vs == VIDEO_SOURCE_DEFAULT) {
94        mVideoSource = VIDEO_SOURCE_CAMERA;
95    } else {
96        mVideoSource = vs;
97    }
98
99    return OK;
100}
101
102status_t StagefrightRecorder::setOutputFormat(output_format of) {
103    LOGV("setOutputFormat: %d", of);
104    if (of < OUTPUT_FORMAT_DEFAULT ||
105        of >= OUTPUT_FORMAT_LIST_END) {
106        LOGE("Invalid output format: %d", of);
107        return BAD_VALUE;
108    }
109
110    if (of == OUTPUT_FORMAT_DEFAULT) {
111        mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
112    } else {
113        mOutputFormat = of;
114    }
115
116    return OK;
117}
118
119status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
120    LOGV("setAudioEncoder: %d", ae);
121    if (ae < AUDIO_ENCODER_DEFAULT ||
122        ae >= AUDIO_ENCODER_LIST_END) {
123        LOGE("Invalid audio encoder: %d", ae);
124        return BAD_VALUE;
125    }
126
127    if (ae == AUDIO_ENCODER_DEFAULT) {
128        mAudioEncoder = AUDIO_ENCODER_AMR_NB;
129    } else {
130        mAudioEncoder = ae;
131    }
132
133    return OK;
134}
135
136status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
137    LOGV("setVideoEncoder: %d", ve);
138    if (ve < VIDEO_ENCODER_DEFAULT ||
139        ve >= VIDEO_ENCODER_LIST_END) {
140        LOGE("Invalid video encoder: %d", ve);
141        return BAD_VALUE;
142    }
143
144    if (ve == VIDEO_ENCODER_DEFAULT) {
145        mVideoEncoder = VIDEO_ENCODER_H263;
146    } else {
147        mVideoEncoder = ve;
148    }
149
150    return OK;
151}
152
153status_t StagefrightRecorder::setVideoSize(int width, int height) {
154    LOGV("setVideoSize: %dx%d", width, height);
155    if (width <= 0 || height <= 0) {
156        LOGE("Invalid video size: %dx%d", width, height);
157        return BAD_VALUE;
158    }
159
160    // Additional check on the dimension will be performed later
161    mVideoWidth = width;
162    mVideoHeight = height;
163
164    return OK;
165}
166
167status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
168    LOGV("setVideoFrameRate: %d", frames_per_second);
169    if (frames_per_second <= 0 || frames_per_second > 30) {
170        LOGE("Invalid video frame rate: %d", frames_per_second);
171        return BAD_VALUE;
172    }
173
174    // Additional check on the frame rate will be performed later
175    mFrameRate = frames_per_second;
176
177    return OK;
178}
179
180status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera) {
181    LOGV("setCamera");
182    if (camera == 0) {
183        LOGE("camera is NULL");
184        return BAD_VALUE;
185    }
186
187    int64_t token = IPCThreadState::self()->clearCallingIdentity();
188    mFlags &= ~FLAGS_HOT_CAMERA;
189    mCamera = Camera::create(camera);
190    if (mCamera == 0) {
191        LOGE("Unable to connect to camera");
192        IPCThreadState::self()->restoreCallingIdentity(token);
193        return -EBUSY;
194    }
195
196    LOGV("Connected to camera");
197    if (mCamera->previewEnabled()) {
198        LOGV("camera is hot");
199        mFlags |= FLAGS_HOT_CAMERA;
200    }
201    IPCThreadState::self()->restoreCallingIdentity(token);
202
203    return OK;
204}
205
206status_t StagefrightRecorder::setPreviewSurface(const sp<ISurface> &surface) {
207    LOGV("setPreviewSurface: %p", surface.get());
208    mPreviewSurface = surface;
209
210    return OK;
211}
212
213status_t StagefrightRecorder::setOutputFile(const char *path) {
214    LOGE("setOutputFile(const char*) must not be called");
215    // We don't actually support this at all, as the media_server process
216    // no longer has permissions to create files.
217
218    return -EPERM;
219}
220
221status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
222    LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length);
223    // These don't make any sense, do they?
224    CHECK_EQ(offset, 0);
225    CHECK_EQ(length, 0);
226
227    if (fd < 0) {
228        LOGE("Invalid file descriptor: %d", fd);
229        return -EBADF;
230    }
231
232    if (mOutputFd >= 0) {
233        ::close(mOutputFd);
234    }
235    mOutputFd = dup(fd);
236
237    return OK;
238}
239
240// Attempt to parse an int64 literal optionally surrounded by whitespace,
241// returns true on success, false otherwise.
242static bool safe_strtoi64(const char *s, int64_t *val) {
243    char *end;
244    *val = strtoll(s, &end, 10);
245
246    if (end == s || errno == ERANGE) {
247        return false;
248    }
249
250    // Skip trailing whitespace
251    while (isspace(*end)) {
252        ++end;
253    }
254
255    // For a successful return, the string must contain nothing but a valid
256    // int64 literal optionally surrounded by whitespace.
257
258    return *end == '\0';
259}
260
261// Return true if the value is in [0, 0x007FFFFFFF]
262static bool safe_strtoi32(const char *s, int32_t *val) {
263    int64_t temp;
264    if (safe_strtoi64(s, &temp)) {
265        if (temp >= 0 && temp <= 0x007FFFFFFF) {
266            *val = static_cast<int32_t>(temp);
267            return true;
268        }
269    }
270    return false;
271}
272
273// Trim both leading and trailing whitespace from the given string.
274static void TrimString(String8 *s) {
275    size_t num_bytes = s->bytes();
276    const char *data = s->string();
277
278    size_t leading_space = 0;
279    while (leading_space < num_bytes && isspace(data[leading_space])) {
280        ++leading_space;
281    }
282
283    size_t i = num_bytes;
284    while (i > leading_space && isspace(data[i - 1])) {
285        --i;
286    }
287
288    s->setTo(String8(&data[leading_space], i - leading_space));
289}
290
291status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
292    LOGV("setParamAudioSamplingRate: %d", sampleRate);
293    if (sampleRate <= 0) {
294        LOGE("Invalid audio sampling rate: %d", sampleRate);
295        return BAD_VALUE;
296    }
297
298    // Additional check on the sample rate will be performed later.
299    mSampleRate = sampleRate;
300    return OK;
301}
302
303status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
304    LOGV("setParamAudioNumberOfChannels: %d", channels);
305    if (channels <= 0 || channels >= 3) {
306        LOGE("Invalid number of audio channels: %d", channels);
307        return BAD_VALUE;
308    }
309
310    // Additional check on the number of channels will be performed later.
311    mAudioChannels = channels;
312    return OK;
313}
314
315status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
316    LOGV("setParamAudioEncodingBitRate: %d", bitRate);
317    if (bitRate <= 0) {
318        LOGE("Invalid audio encoding bit rate: %d", bitRate);
319        return BAD_VALUE;
320    }
321
322    // The target bit rate may not be exactly the same as the requested.
323    // It depends on many factors, such as rate control, and the bit rate
324    // range that a specific encoder supports. The mismatch between the
325    // the target and requested bit rate will NOT be treated as an error.
326    mAudioBitRate = bitRate;
327    return OK;
328}
329
330status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
331    LOGV("setParamVideoEncodingBitRate: %d", bitRate);
332    if (bitRate <= 0) {
333        LOGE("Invalid video encoding bit rate: %d", bitRate);
334        return BAD_VALUE;
335    }
336
337    // The target bit rate may not be exactly the same as the requested.
338    // It depends on many factors, such as rate control, and the bit rate
339    // range that a specific encoder supports. The mismatch between the
340    // the target and requested bit rate will NOT be treated as an error.
341    mVideoBitRate = bitRate;
342    return OK;
343}
344
345status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
346    LOGV("setParamMaxFileDurationUs: %lld us", timeUs);
347    if (timeUs <= 1000000LL) {  // XXX: 1 second
348        LOGE("Max file duration is too short: %lld us", timeUs);
349        return BAD_VALUE;
350    }
351    mMaxFileDurationUs = timeUs;
352    return OK;
353}
354
355status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
356    LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
357    if (bytes <= 1024) {  // XXX: 1 kB
358        LOGE("Max file size is too small: %lld bytes", bytes);
359        return BAD_VALUE;
360    }
361    mMaxFileSizeBytes = bytes;
362    return OK;
363}
364
365status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
366    LOGV("setParamInterleaveDuration: %d", durationUs);
367    if (durationUs <= 500000) {           //  500 ms
368        // If interleave duration is too small, it is very inefficient to do
369        // interleaving since the metadata overhead will count for a significant
370        // portion of the saved contents
371        LOGE("Audio/video interleave duration is too small: %d us", durationUs);
372        return BAD_VALUE;
373    } else if (durationUs >= 10000000) {  // 10 seconds
374        // If interleaving duration is too large, it can cause the recording
375        // session to use too much memory since we have to save the output
376        // data before we write them out
377        LOGE("Audio/video interleave duration is too large: %d us", durationUs);
378        return BAD_VALUE;
379    }
380    mInterleaveDurationUs = durationUs;
381    return OK;
382}
383
384// If interval <  0, only the first frame is I frame, and rest are all P frames
385// If interval == 0, all frames are encoded as I frames. No P frames
386// If interval >  0, it is the time spacing (seconds) between 2 neighboring I frames
387status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t interval) {
388    LOGV("setParamVideoIFramesInterval: %d seconds", interval);
389    mIFramesInterval = interval;
390    return OK;
391}
392
393status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
394    LOGV("setParam64BitFileOffset: %s",
395        use64Bit? "use 64 bit file offset": "use 32 bit file offset");
396    mUse64BitFileOffset = use64Bit;
397    return OK;
398}
399
400status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
401    LOGV("setParamVideoCameraId: %d", cameraId);
402    if (cameraId < 0) {
403        return BAD_VALUE;
404    }
405    mCameraId = cameraId;
406    return OK;
407}
408
409status_t StagefrightRecorder::setParamTrackFrameStatus(int32_t nFrames) {
410    LOGV("setParamTrackFrameStatus: %d", nFrames);
411    if (nFrames <= 0) {
412        LOGE("Invalid number of frames to track: %d", nFrames);
413        return BAD_VALUE;
414    }
415    mTrackEveryNumberOfFrames = nFrames;
416    return OK;
417}
418
419status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
420    LOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
421    if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
422        LOGE("Tracking time duration too short: %lld us", timeDurationUs);
423        return BAD_VALUE;
424    }
425    mTrackEveryTimeDurationUs = timeDurationUs;
426    return OK;
427}
428
429status_t StagefrightRecorder::setParameter(
430        const String8 &key, const String8 &value) {
431    LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
432    if (key == "max-duration") {
433        int64_t max_duration_ms;
434        if (safe_strtoi64(value.string(), &max_duration_ms)) {
435            return setParamMaxFileDurationUs(1000LL * max_duration_ms);
436        }
437    } else if (key == "max-filesize") {
438        int64_t max_filesize_bytes;
439        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
440            return setParamMaxFileSizeBytes(max_filesize_bytes);
441        }
442    } else if (key == "interleave-duration-us") {
443        int32_t durationUs;
444        if (safe_strtoi32(value.string(), &durationUs)) {
445            return setParamInterleaveDuration(durationUs);
446        }
447    } else if (key == "param-use-64bit-offset") {
448        int32_t use64BitOffset;
449        if (safe_strtoi32(value.string(), &use64BitOffset)) {
450            return setParam64BitFileOffset(use64BitOffset != 0);
451        }
452    } else if (key == "param-track-frame-status") {
453        int32_t nFrames;
454        if (safe_strtoi32(value.string(), &nFrames)) {
455            return setParamTrackFrameStatus(nFrames);
456        }
457    } else if (key == "param-track-time-status") {
458        int64_t timeDurationUs;
459        if (safe_strtoi64(value.string(), &timeDurationUs)) {
460            return setParamTrackTimeStatus(timeDurationUs);
461        }
462    } else if (key == "audio-param-sampling-rate") {
463        int32_t sampling_rate;
464        if (safe_strtoi32(value.string(), &sampling_rate)) {
465            return setParamAudioSamplingRate(sampling_rate);
466        }
467    } else if (key == "audio-param-number-of-channels") {
468        int32_t number_of_channels;
469        if (safe_strtoi32(value.string(), &number_of_channels)) {
470            return setParamAudioNumberOfChannels(number_of_channels);
471        }
472    } else if (key == "audio-param-encoding-bitrate") {
473        int32_t audio_bitrate;
474        if (safe_strtoi32(value.string(), &audio_bitrate)) {
475            return setParamAudioEncodingBitRate(audio_bitrate);
476        }
477    } else if (key == "video-param-encoding-bitrate") {
478        int32_t video_bitrate;
479        if (safe_strtoi32(value.string(), &video_bitrate)) {
480            return setParamVideoEncodingBitRate(video_bitrate);
481        }
482    } else if (key == "video-param-i-frames-interval") {
483        int32_t interval;
484        if (safe_strtoi32(value.string(), &interval)) {
485            return setParamVideoIFramesInterval(interval);
486        }
487    } else if (key == "video-param-camera-id") {
488        int32_t cameraId;
489        if (safe_strtoi32(value.string(), &cameraId)) {
490            return setParamVideoCameraId(cameraId);
491        }
492    } else {
493        LOGE("setParameter: failed to find key %s", key.string());
494    }
495    return BAD_VALUE;
496}
497
498status_t StagefrightRecorder::setParameters(const String8 &params) {
499    LOGV("setParameters: %s", params.string());
500    const char *cparams = params.string();
501    const char *key_start = cparams;
502    for (;;) {
503        const char *equal_pos = strchr(key_start, '=');
504        if (equal_pos == NULL) {
505            LOGE("Parameters %s miss a value", cparams);
506            return BAD_VALUE;
507        }
508        String8 key(key_start, equal_pos - key_start);
509        TrimString(&key);
510        if (key.length() == 0) {
511            LOGE("Parameters %s contains an empty key", cparams);
512            return BAD_VALUE;
513        }
514        const char *value_start = equal_pos + 1;
515        const char *semicolon_pos = strchr(value_start, ';');
516        String8 value;
517        if (semicolon_pos == NULL) {
518            value.setTo(value_start);
519        } else {
520            value.setTo(value_start, semicolon_pos - value_start);
521        }
522        if (setParameter(key, value) != OK) {
523            return BAD_VALUE;
524        }
525        if (semicolon_pos == NULL) {
526            break;  // Reaches the end
527        }
528        key_start = semicolon_pos + 1;
529    }
530    return OK;
531}
532
533status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
534    mListener = listener;
535
536    return OK;
537}
538
539status_t StagefrightRecorder::prepare() {
540    return OK;
541}
542
543status_t StagefrightRecorder::start() {
544    CHECK(mOutputFd >= 0);
545
546    if (mWriter != NULL) {
547        LOGE("File writer is not avaialble");
548        return UNKNOWN_ERROR;
549    }
550
551    switch (mOutputFormat) {
552        case OUTPUT_FORMAT_DEFAULT:
553        case OUTPUT_FORMAT_THREE_GPP:
554        case OUTPUT_FORMAT_MPEG_4:
555            return startMPEG4Recording();
556
557        case OUTPUT_FORMAT_AMR_NB:
558        case OUTPUT_FORMAT_AMR_WB:
559            return startAMRRecording();
560
561        case OUTPUT_FORMAT_AAC_ADIF:
562        case OUTPUT_FORMAT_AAC_ADTS:
563            return startAACRecording();
564
565        default:
566            LOGE("Unsupported output file format: %d", mOutputFormat);
567            return UNKNOWN_ERROR;
568    }
569}
570
571sp<MediaSource> StagefrightRecorder::createAudioSource() {
572    sp<AudioSource> audioSource =
573        new AudioSource(
574                mAudioSource,
575                mSampleRate,
576                mAudioChannels);
577
578    status_t err = audioSource->initCheck();
579
580    if (err != OK) {
581        LOGE("audio source is not initialized");
582        return NULL;
583    }
584
585    sp<MetaData> encMeta = new MetaData;
586    const char *mime;
587    switch (mAudioEncoder) {
588        case AUDIO_ENCODER_AMR_NB:
589        case AUDIO_ENCODER_DEFAULT:
590            mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
591            break;
592        case AUDIO_ENCODER_AMR_WB:
593            mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
594            break;
595        case AUDIO_ENCODER_AAC:
596            mime = MEDIA_MIMETYPE_AUDIO_AAC;
597            break;
598        default:
599            LOGE("Unknown audio encoder: %d", mAudioEncoder);
600            return NULL;
601    }
602    encMeta->setCString(kKeyMIMEType, mime);
603
604    int32_t maxInputSize;
605    CHECK(audioSource->getFormat()->findInt32(
606                kKeyMaxInputSize, &maxInputSize));
607
608    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
609    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
610    encMeta->setInt32(kKeySampleRate, mSampleRate);
611    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
612
613    OMXClient client;
614    CHECK_EQ(client.connect(), OK);
615
616    sp<MediaSource> audioEncoder =
617        OMXCodec::Create(client.interface(), encMeta,
618                         true /* createEncoder */, audioSource);
619    mAudioSourceNode = audioSource;
620
621    return audioEncoder;
622}
623
624status_t StagefrightRecorder::startAACRecording() {
625    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF ||
626          mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
627
628    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
629    CHECK(mAudioSource != AUDIO_SOURCE_LIST_END);
630
631    CHECK(0 == "AACWriter is not implemented yet");
632
633    return OK;
634}
635
636status_t StagefrightRecorder::startAMRRecording() {
637    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
638          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
639
640    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
641        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
642            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
643            LOGE("Invalid encoder %d used for AMRNB recording",
644                    mAudioEncoder);
645            return BAD_VALUE;
646        }
647        if (mSampleRate != 8000) {
648            LOGE("Invalid sampling rate %d used for AMRNB recording",
649                    mSampleRate);
650            return BAD_VALUE;
651        }
652    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
653        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
654            LOGE("Invlaid encoder %d used for AMRWB recording",
655                    mAudioEncoder);
656            return BAD_VALUE;
657        }
658        if (mSampleRate != 16000) {
659            LOGE("Invalid sample rate %d used for AMRWB recording",
660                    mSampleRate);
661            return BAD_VALUE;
662        }
663    }
664    if (mAudioChannels != 1) {
665        LOGE("Invalid number of audio channels %d used for amr recording",
666                mAudioChannels);
667        return BAD_VALUE;
668    }
669
670    if (mAudioSource >= AUDIO_SOURCE_LIST_END) {
671        LOGE("Invalid audio source: %d", mAudioSource);
672        return BAD_VALUE;
673    }
674
675    sp<MediaSource> audioEncoder = createAudioSource();
676
677    if (audioEncoder == NULL) {
678        return UNKNOWN_ERROR;
679    }
680
681    mWriter = new AMRWriter(dup(mOutputFd));
682    mWriter->addSource(audioEncoder);
683
684    if (mMaxFileDurationUs != 0) {
685        mWriter->setMaxFileDuration(mMaxFileDurationUs);
686    }
687    if (mMaxFileSizeBytes != 0) {
688        mWriter->setMaxFileSize(mMaxFileSizeBytes);
689    }
690    mWriter->setListener(mListener);
691    mWriter->start();
692
693    return OK;
694}
695
696void StagefrightRecorder::clipVideoFrameRate() {
697    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
698    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
699                        "enc.vid.fps.min", mVideoEncoder);
700    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
701                        "enc.vid.fps.max", mVideoEncoder);
702    if (mFrameRate < minFrameRate) {
703        LOGW("Intended video encoding frame rate (%d fps) is too small"
704             " and will be set to (%d fps)", mFrameRate, minFrameRate);
705        mFrameRate = minFrameRate;
706    } else if (mFrameRate > maxFrameRate) {
707        LOGW("Intended video encoding frame rate (%d fps) is too large"
708             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
709        mFrameRate = maxFrameRate;
710    }
711}
712
713void StagefrightRecorder::clipVideoBitRate() {
714    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
715    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
716                        "enc.vid.bps.min", mVideoEncoder);
717    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
718                        "enc.vid.bps.max", mVideoEncoder);
719    if (mVideoBitRate < minBitRate) {
720        LOGW("Intended video encoding bit rate (%d bps) is too small"
721             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
722        mVideoBitRate = minBitRate;
723    } else if (mVideoBitRate > maxBitRate) {
724        LOGW("Intended video encoding bit rate (%d bps) is too large"
725             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
726        mVideoBitRate = maxBitRate;
727    }
728}
729
730void StagefrightRecorder::clipVideoFrameWidth() {
731    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
732    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
733                        "enc.vid.width.min", mVideoEncoder);
734    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
735                        "enc.vid.width.max", mVideoEncoder);
736    if (mVideoWidth < minFrameWidth) {
737        LOGW("Intended video encoding frame width (%d) is too small"
738             " and will be set to (%d)", mVideoWidth, minFrameWidth);
739        mVideoWidth = minFrameWidth;
740    } else if (mVideoWidth > maxFrameWidth) {
741        LOGW("Intended video encoding frame width (%d) is too large"
742             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
743        mVideoWidth = maxFrameWidth;
744    }
745}
746
747status_t StagefrightRecorder::setupCameraSource() {
748    clipVideoBitRate();
749    clipVideoFrameRate();
750    clipVideoFrameWidth();
751    clipVideoFrameHeight();
752
753    int64_t token = IPCThreadState::self()->clearCallingIdentity();
754    if (mCamera == 0) {
755        mCamera = Camera::connect(mCameraId);
756        if (mCamera == 0) {
757            LOGE("Camera connection could not be established.");
758            return -EBUSY;
759        }
760        mFlags &= ~FLAGS_HOT_CAMERA;
761        mCamera->lock();
762    }
763
764    // Set the actual video recording frame size
765    CameraParameters params(mCamera->getParameters());
766    params.setPreviewSize(mVideoWidth, mVideoHeight);
767    params.setPreviewFrameRate(mFrameRate);
768    String8 s = params.flatten();
769    CHECK_EQ(OK, mCamera->setParameters(s));
770    CameraParameters newCameraParams(mCamera->getParameters());
771
772    // Check on video frame size
773    int frameWidth = 0, frameHeight = 0;
774    newCameraParams.getPreviewSize(&frameWidth, &frameHeight);
775    if (frameWidth  < 0 || frameWidth  != mVideoWidth ||
776        frameHeight < 0 || frameHeight != mVideoHeight) {
777        LOGE("Failed to set the video frame size to %dx%d",
778                mVideoWidth, mVideoHeight);
779        IPCThreadState::self()->restoreCallingIdentity(token);
780        return UNKNOWN_ERROR;
781    }
782
783    // Check on video frame rate
784    int frameRate = newCameraParams.getPreviewFrameRate();
785    if (frameRate < 0 || (frameRate - mFrameRate) != 0) {
786        LOGE("Failed to set frame rate to %d fps. The actual "
787             "frame rate is %d", mFrameRate, frameRate);
788    }
789
790    CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface));
791    IPCThreadState::self()->restoreCallingIdentity(token);
792    return OK;
793}
794
795void StagefrightRecorder::clipVideoFrameHeight() {
796    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
797    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
798                        "enc.vid.height.min", mVideoEncoder);
799    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
800                        "enc.vid.height.max", mVideoEncoder);
801    if (mVideoHeight < minFrameHeight) {
802        LOGW("Intended video encoding frame height (%d) is too small"
803             " and will be set to (%d)", mVideoHeight, minFrameHeight);
804        mVideoHeight = minFrameHeight;
805    } else if (mVideoHeight > maxFrameHeight) {
806        LOGW("Intended video encoding frame height (%d) is too large"
807             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
808        mVideoHeight = maxFrameHeight;
809    }
810}
811
812status_t StagefrightRecorder::setupVideoEncoder(const sp<MediaWriter>& writer) {
813    status_t err = setupCameraSource();
814    if (err != OK) return err;
815
816    sp<CameraSource> cameraSource = CameraSource::CreateFromCamera(mCamera);
817    CHECK(cameraSource != NULL);
818
819    sp<MetaData> enc_meta = new MetaData;
820    enc_meta->setInt32(kKeyBitRate, mVideoBitRate);
821    enc_meta->setInt32(kKeySampleRate, mFrameRate);
822
823    switch (mVideoEncoder) {
824        case VIDEO_ENCODER_H263:
825            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
826            break;
827
828        case VIDEO_ENCODER_MPEG_4_SP:
829            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
830            break;
831
832        case VIDEO_ENCODER_H264:
833            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
834            break;
835
836        default:
837            CHECK(!"Should not be here, unsupported video encoding.");
838            break;
839    }
840
841    sp<MetaData> meta = cameraSource->getFormat();
842
843    int32_t width, height, stride, sliceHeight;
844    CHECK(meta->findInt32(kKeyWidth, &width));
845    CHECK(meta->findInt32(kKeyHeight, &height));
846    CHECK(meta->findInt32(kKeyStride, &stride));
847    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
848
849    enc_meta->setInt32(kKeyWidth, width);
850    enc_meta->setInt32(kKeyHeight, height);
851    enc_meta->setInt32(kKeyIFramesInterval, mIFramesInterval);
852    enc_meta->setInt32(kKeyStride, stride);
853    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
854
855    OMXClient client;
856    CHECK_EQ(client.connect(), OK);
857
858    sp<MediaSource> encoder = OMXCodec::Create(
859            client.interface(), enc_meta,
860            true /* createEncoder */, cameraSource);
861    if (encoder == NULL) {
862        return UNKNOWN_ERROR;
863    }
864
865    writer->addSource(encoder);
866    return OK;
867}
868
869status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
870    sp<MediaSource> audioEncoder;
871    switch(mAudioEncoder) {
872        case AUDIO_ENCODER_AMR_NB:
873        case AUDIO_ENCODER_AMR_WB:
874        case AUDIO_ENCODER_AAC:
875            audioEncoder = createAudioSource();
876            break;
877        default:
878            LOGE("Unsupported audio encoder: %d", mAudioEncoder);
879            return UNKNOWN_ERROR;
880    }
881
882    if (audioEncoder == NULL) {
883        return UNKNOWN_ERROR;
884    }
885    writer->addSource(audioEncoder);
886    return OK;
887}
888
889status_t StagefrightRecorder::startMPEG4Recording() {
890    int32_t totalBitRate = 0;
891    status_t err = OK;
892    sp<MediaWriter> writer = new MPEG4Writer(dup(mOutputFd));
893
894    // Add audio source first if it exists
895    if (mAudioSource != AUDIO_SOURCE_LIST_END) {
896        err = setupAudioEncoder(writer);
897        if (err != OK) return err;
898        totalBitRate += mAudioBitRate;
899    }
900    if (mVideoSource == VIDEO_SOURCE_DEFAULT
901            || mVideoSource == VIDEO_SOURCE_CAMERA) {
902        err = setupVideoEncoder(writer);
903        if (err != OK) return err;
904        totalBitRate += mVideoBitRate;
905    }
906
907    reinterpret_cast<MPEG4Writer *>(writer.get())->
908        setInterleaveDuration(mInterleaveDurationUs);
909
910    if (mMaxFileDurationUs != 0) {
911        writer->setMaxFileDuration(mMaxFileDurationUs);
912    }
913    if (mMaxFileSizeBytes != 0) {
914        writer->setMaxFileSize(mMaxFileSizeBytes);
915    }
916    sp<MetaData> meta = new MetaData;
917    meta->setInt64(kKeyTime, systemTime() / 1000);
918    meta->setInt32(kKeyFileType, mOutputFormat);
919    meta->setInt32(kKeyBitRate, totalBitRate);
920    meta->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
921    if (mTrackEveryNumberOfFrames > 0) {
922        meta->setInt32(kKeyTrackFrameStatus, mTrackEveryNumberOfFrames);
923    }
924    if (mTrackEveryTimeDurationUs > 0) {
925        meta->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
926    }
927    writer->setListener(mListener);
928    mWriter = writer;
929    return mWriter->start(meta.get());
930}
931
932status_t StagefrightRecorder::pause() {
933    LOGV("pause");
934    if (mWriter == NULL) {
935        return UNKNOWN_ERROR;
936    }
937    mWriter->pause();
938    return OK;
939}
940
941status_t StagefrightRecorder::stop() {
942    LOGV("stop");
943    if (mWriter != NULL) {
944        mWriter->stop();
945        mWriter.clear();
946    }
947
948    if (mCamera != 0) {
949        LOGV("Disconnect camera");
950        int64_t token = IPCThreadState::self()->clearCallingIdentity();
951        if ((mFlags & FLAGS_HOT_CAMERA) == 0) {
952            LOGV("Camera was cold when we started, stopping preview");
953            mCamera->stopPreview();
954        }
955        mCamera->unlock();
956        mCamera.clear();
957        IPCThreadState::self()->restoreCallingIdentity(token);
958        mFlags = 0;
959    }
960
961    return OK;
962}
963
964status_t StagefrightRecorder::close() {
965    LOGV("close");
966    stop();
967
968    return OK;
969}
970
971status_t StagefrightRecorder::reset() {
972    LOGV("reset");
973    stop();
974
975    // No audio or video source by default
976    mAudioSource = AUDIO_SOURCE_LIST_END;
977    mVideoSource = VIDEO_SOURCE_LIST_END;
978
979    // Default parameters
980    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
981    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
982    mVideoEncoder  = VIDEO_ENCODER_H263;
983    mVideoWidth    = 176;
984    mVideoHeight   = 144;
985    mFrameRate     = 20;
986    mVideoBitRate  = 192000;
987    mSampleRate    = 8000;
988    mAudioChannels = 1;
989    mAudioBitRate  = 12200;
990    mInterleaveDurationUs = 0;
991    mIFramesInterval = 1;
992    mAudioSourceNode = 0;
993    mUse64BitFileOffset = false;
994    mCameraId        = 0;
995    mTrackEveryNumberOfFrames = 0;
996    mTrackEveryTimeDurationUs = 0;
997    mEncoderProfiles = MediaProfiles::getInstance();
998
999    mOutputFd = -1;
1000    mFlags = 0;
1001
1002    return OK;
1003}
1004
1005status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1006    LOGV("getMaxAmplitude");
1007
1008    if (max == NULL) {
1009        LOGE("Null pointer argument");
1010        return BAD_VALUE;
1011    }
1012
1013    if (mAudioSourceNode != 0) {
1014        *max = mAudioSourceNode->getMaxAmplitude();
1015    } else {
1016        *max = 0;
1017    }
1018
1019    return OK;
1020}
1021
1022}  // namespace android
1023