StagefrightRecorder.cpp revision 99c2a076b4a46762a22bbb4dfbd51d107e0532d9
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    reset();
47}
48
49StagefrightRecorder::~StagefrightRecorder() {
50    stop();
51
52    if (mOutputFd >= 0) {
53        ::close(mOutputFd);
54        mOutputFd = -1;
55    }
56}
57
58status_t StagefrightRecorder::init() {
59    return OK;
60}
61
62status_t StagefrightRecorder::setAudioSource(audio_source as) {
63    mAudioSource = as;
64
65    return OK;
66}
67
68status_t StagefrightRecorder::setVideoSource(video_source vs) {
69    mVideoSource = vs;
70
71    return OK;
72}
73
74status_t StagefrightRecorder::setOutputFormat(output_format of) {
75    mOutputFormat = of;
76
77    return OK;
78}
79
80status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
81    mAudioEncoder = ae;
82
83    return OK;
84}
85
86status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
87    mVideoEncoder = ve;
88
89    return OK;
90}
91
92status_t StagefrightRecorder::setVideoSize(int width, int height) {
93    if (width <= 0 || height <= 0) {
94        LOGE("Invalid video size: %dx%d", width, height);
95        return BAD_VALUE;
96    }
97
98    // Additional check on the dimension will be performed later
99    mVideoWidth = width;
100    mVideoHeight = height;
101
102    return OK;
103}
104
105status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
106    if (frames_per_second <= 0 || frames_per_second > 30) {
107        LOGE("Invalid video frame rate: %d", frames_per_second);
108        return BAD_VALUE;
109    }
110
111    // Additional check on the frame rate will be performed later
112    mFrameRate = frames_per_second;
113
114    return OK;
115}
116
117status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera) {
118    LOGV("setCamera");
119    if (camera == 0) {
120        LOGE("camera is NULL");
121        return UNKNOWN_ERROR;
122    }
123
124    int64_t token = IPCThreadState::self()->clearCallingIdentity();
125    mFlags &= ~FLAGS_HOT_CAMERA;
126    mCamera = Camera::create(camera);
127    if (mCamera == 0) {
128        LOGE("Unable to connect to camera");
129        IPCThreadState::self()->restoreCallingIdentity(token);
130        return UNKNOWN_ERROR;
131    }
132
133    LOGV("Connected to camera");
134    if (mCamera->previewEnabled()) {
135        LOGV("camera is hot");
136        mFlags |= FLAGS_HOT_CAMERA;
137    }
138    IPCThreadState::self()->restoreCallingIdentity(token);
139
140    return OK;
141}
142
143status_t StagefrightRecorder::setPreviewSurface(const sp<ISurface> &surface) {
144    mPreviewSurface = surface;
145
146    return OK;
147}
148
149status_t StagefrightRecorder::setOutputFile(const char *path) {
150    // We don't actually support this at all, as the media_server process
151    // no longer has permissions to create files.
152
153    return UNKNOWN_ERROR;
154}
155
156status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
157    // These don't make any sense, do they?
158    CHECK_EQ(offset, 0);
159    CHECK_EQ(length, 0);
160
161    if (mOutputFd >= 0) {
162        ::close(mOutputFd);
163    }
164    mOutputFd = dup(fd);
165
166    return OK;
167}
168
169// Attempt to parse an int64 literal optionally surrounded by whitespace,
170// returns true on success, false otherwise.
171static bool safe_strtoi64(const char *s, int64_t *val) {
172    char *end;
173    *val = strtoll(s, &end, 10);
174
175    if (end == s || errno == ERANGE) {
176        return false;
177    }
178
179    // Skip trailing whitespace
180    while (isspace(*end)) {
181        ++end;
182    }
183
184    // For a successful return, the string must contain nothing but a valid
185    // int64 literal optionally surrounded by whitespace.
186
187    return *end == '\0';
188}
189
190// Return true if the value is in [0, 0x007FFFFFFF]
191static bool safe_strtoi32(const char *s, int32_t *val) {
192    int64_t temp;
193    if (safe_strtoi64(s, &temp)) {
194        if (temp >= 0 && temp <= 0x007FFFFFFF) {
195            *val = static_cast<int32_t>(temp);
196            return true;
197        }
198    }
199    return false;
200}
201
202// Trim both leading and trailing whitespace from the given string.
203static void TrimString(String8 *s) {
204    size_t num_bytes = s->bytes();
205    const char *data = s->string();
206
207    size_t leading_space = 0;
208    while (leading_space < num_bytes && isspace(data[leading_space])) {
209        ++leading_space;
210    }
211
212    size_t i = num_bytes;
213    while (i > leading_space && isspace(data[i - 1])) {
214        --i;
215    }
216
217    s->setTo(String8(&data[leading_space], i - leading_space));
218}
219
220status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
221    LOGV("setParamAudioSamplingRate: %d", sampleRate);
222    if (sampleRate <= 0) {
223        LOGE("Invalid audio sampling rate: %d", sampleRate);
224        return BAD_VALUE;
225    }
226
227    // Additional check on the sample rate will be performed later.
228    mSampleRate = sampleRate;
229    return OK;
230}
231
232status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
233    LOGV("setParamAudioNumberOfChannels: %d", channels);
234    if (channels <= 0 || channels >= 3) {
235        LOGE("Invalid number of audio channels: %d", channels);
236    }
237
238    // Additional check on the number of channels will be performed later.
239    mAudioChannels = channels;
240    return OK;
241}
242
243status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
244    LOGV("setParamAudioEncodingBitRate: %d", bitRate);
245    if (bitRate <= 0) {
246        LOGE("Invalid audio encoding bit rate: %d", bitRate);
247        return BAD_VALUE;
248    }
249
250    // The target bit rate may not be exactly the same as the requested.
251    // It depends on many factors, such as rate control, and the bit rate
252    // range that a specific encoder supports. The mismatch between the
253    // the target and requested bit rate will NOT be treated as an error.
254    mAudioBitRate = bitRate;
255    return OK;
256}
257
258status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
259    LOGV("setParamVideoEncodingBitRate: %d", bitRate);
260    if (bitRate <= 0) {
261        LOGE("Invalid video encoding bit rate: %d", bitRate);
262        return BAD_VALUE;
263    }
264
265    // The target bit rate may not be exactly the same as the requested.
266    // It depends on many factors, such as rate control, and the bit rate
267    // range that a specific encoder supports. The mismatch between the
268    // the target and requested bit rate will NOT be treated as an error.
269    mVideoBitRate = bitRate;
270    return OK;
271}
272
273status_t StagefrightRecorder::setParamMaxDurationOrFileSize(int64_t limit,
274        bool limit_is_duration) {
275    LOGV("setParamMaxDurationOrFileSize: limit (%lld) for %s",
276            limit, limit_is_duration?"duration":"size");
277    if (limit_is_duration) {  // limit is in ms
278        if (limit <= 1000) {  // XXX: 1 second
279            LOGE("Max file duration is too short: %lld us", limit);
280        }
281        mMaxFileDurationUs = limit * 1000LL;
282    } else {
283        if (limit <= 1024) {  // XXX: 1 kB
284            LOGE("Max file size is too small: %lld bytes", limit);
285        }
286        mMaxFileSizeBytes = limit;
287    }
288    return OK;
289}
290
291status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
292    LOGV("setParamInterleaveDuration: %d", durationUs);
293    if (durationUs <= 500000) {           //  500 ms
294        // If interleave duration is too small, it is very inefficient to do
295        // interleaving since the metadata overhead will count for a significant
296        // portion of the saved contents
297        LOGE("Audio/video interleave duration is too small: %d us", durationUs);
298        return BAD_VALUE;
299    } else if (durationUs >= 10000000) {  // 10 seconds
300        // If interleaving duration is too large, it can cause the recording
301        // session to use too much memory since we have to save the output
302        // data before we write them out
303        LOGE("Audio/video interleave duration is too large: %d us", durationUs);
304        return BAD_VALUE;
305    }
306    mInterleaveDurationUs = durationUs;
307    return OK;
308}
309
310// If interval <  0, only the first frame is I frame, and rest are all P frames
311// If interval == 0, all frames are encoded as I frames. No P frames
312// If interval >  0, it is the time spacing between 2 neighboring I frames
313status_t StagefrightRecorder::setParamIFramesInterval(int32_t interval) {
314    LOGV("setParamIFramesInterval: %d seconds", interval);
315    mIFramesInterval = interval;
316    return OK;
317}
318
319status_t StagefrightRecorder::setParameter(
320        const String8 &key, const String8 &value) {
321    LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
322    if (key == "max-duration") {
323        int64_t max_duration_ms;
324        if (safe_strtoi64(value.string(), &max_duration_ms)) {
325            return setParamMaxDurationOrFileSize(
326                    max_duration_ms, true /* limit_is_duration */);
327        }
328    } else if (key == "max-filesize") {
329        int64_t max_filesize_bytes;
330        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
331            return setParamMaxDurationOrFileSize(
332                    max_filesize_bytes, false /* limit is filesize */);
333        }
334    } else if (key == "audio-param-sampling-rate") {
335        int32_t sampling_rate;
336        if (safe_strtoi32(value.string(), &sampling_rate)) {
337            return setParamAudioSamplingRate(sampling_rate);
338        }
339    } else if (key == "audio-param-number-of-channels") {
340        int32_t number_of_channels;
341        if (safe_strtoi32(value.string(), &number_of_channels)) {
342            return setParamAudioNumberOfChannels(number_of_channels);
343        }
344    } else if (key == "audio-param-encoding-bitrate") {
345        int32_t audio_bitrate;
346        if (safe_strtoi32(value.string(), &audio_bitrate)) {
347            return setParamAudioEncodingBitRate(audio_bitrate);
348        }
349    } else if (key == "video-param-encoding-bitrate") {
350        int32_t video_bitrate;
351        if (safe_strtoi32(value.string(), &video_bitrate)) {
352            return setParamVideoEncodingBitRate(video_bitrate);
353        }
354    } else if (key == "param-interleave-duration-us") {
355        int32_t durationUs;
356        if (safe_strtoi32(value.string(), &durationUs)) {
357            return setParamInterleaveDuration(durationUs);
358        }
359    } else if (key == "param-i-frames-interval") {
360        int32_t interval;
361        if (safe_strtoi32(value.string(), &interval)) {
362            return setParamIFramesInterval(interval);
363        }
364    } else {
365        LOGE("setParameter: failed to find key %s", key.string());
366    }
367    return BAD_VALUE;
368}
369
370status_t StagefrightRecorder::setParameters(const String8 &params) {
371    LOGV("setParameters: %s", params.string());
372    const char *cparams = params.string();
373    const char *key_start = cparams;
374    for (;;) {
375        const char *equal_pos = strchr(key_start, '=');
376        if (equal_pos == NULL) {
377            LOGE("Parameters %s miss a value", cparams);
378            return BAD_VALUE;
379        }
380        String8 key(key_start, equal_pos - key_start);
381        TrimString(&key);
382        if (key.length() == 0) {
383            LOGE("Parameters %s contains an empty key", cparams);
384            return BAD_VALUE;
385        }
386        const char *value_start = equal_pos + 1;
387        const char *semicolon_pos = strchr(value_start, ';');
388        String8 value;
389        if (semicolon_pos == NULL) {
390            value.setTo(value_start);
391        } else {
392            value.setTo(value_start, semicolon_pos - value_start);
393        }
394        if (setParameter(key, value) != OK) {
395            return BAD_VALUE;
396        }
397        if (semicolon_pos == NULL) {
398            break;  // Reaches the end
399        }
400        key_start = semicolon_pos + 1;
401    }
402    return OK;
403}
404
405status_t StagefrightRecorder::setListener(const sp<IMediaPlayerClient> &listener) {
406    mListener = listener;
407
408    return OK;
409}
410
411status_t StagefrightRecorder::prepare() {
412    return OK;
413}
414
415status_t StagefrightRecorder::start() {
416    if (mWriter != NULL) {
417        return UNKNOWN_ERROR;
418    }
419
420    switch (mOutputFormat) {
421        case OUTPUT_FORMAT_DEFAULT:
422        case OUTPUT_FORMAT_THREE_GPP:
423        case OUTPUT_FORMAT_MPEG_4:
424            return startMPEG4Recording();
425
426        case OUTPUT_FORMAT_AMR_NB:
427        case OUTPUT_FORMAT_AMR_WB:
428            return startAMRRecording();
429
430        case OUTPUT_FORMAT_AAC_ADIF:
431        case OUTPUT_FORMAT_AAC_ADTS:
432            return startAACRecording();
433
434        default:
435            return UNKNOWN_ERROR;
436    }
437}
438
439sp<MediaSource> StagefrightRecorder::createAudioSource() {
440    sp<AudioSource> audioSource =
441        new AudioSource(
442                mAudioSource,
443                mSampleRate,
444                mAudioChannels);
445
446    status_t err = audioSource->initCheck();
447
448    if (err != OK) {
449        LOGE("audio source is not initialized");
450        return NULL;
451    }
452
453    sp<MetaData> encMeta = new MetaData;
454    const char *mime;
455    switch (mAudioEncoder) {
456        case AUDIO_ENCODER_AMR_NB:
457        case AUDIO_ENCODER_DEFAULT:
458            mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
459            break;
460        case AUDIO_ENCODER_AMR_WB:
461            mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
462            break;
463        case AUDIO_ENCODER_AAC:
464            mime = MEDIA_MIMETYPE_AUDIO_AAC;
465            break;
466        default:
467            LOGE("Unknown audio encoder: %d", mAudioEncoder);
468            return NULL;
469    }
470    encMeta->setCString(kKeyMIMEType, mime);
471
472    int32_t maxInputSize;
473    CHECK(audioSource->getFormat()->findInt32(
474                kKeyMaxInputSize, &maxInputSize));
475
476    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
477    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
478    encMeta->setInt32(kKeySampleRate, mSampleRate);
479    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
480
481    OMXClient client;
482    CHECK_EQ(client.connect(), OK);
483
484    sp<MediaSource> audioEncoder =
485        OMXCodec::Create(client.interface(), encMeta,
486                         true /* createEncoder */, audioSource);
487
488    return audioEncoder;
489}
490
491status_t StagefrightRecorder::startAACRecording() {
492    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF ||
493          mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
494
495    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
496    CHECK(mAudioSource != AUDIO_SOURCE_LIST_END);
497    CHECK(mOutputFd >= 0);
498
499    CHECK(0 == "AACWriter is not implemented yet");
500
501    return OK;
502}
503
504status_t StagefrightRecorder::startAMRRecording() {
505    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
506          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
507
508    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
509        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
510            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
511            LOGE("Invalid encoder %d used for AMRNB recording",
512                    mAudioEncoder);
513            return UNKNOWN_ERROR;
514        }
515        if (mSampleRate != 8000) {
516            LOGE("Invalid sampling rate %d used for AMRNB recording",
517                    mSampleRate);
518            return UNKNOWN_ERROR;
519        }
520    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
521        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
522            LOGE("Invlaid encoder %d used for AMRWB recording",
523                    mAudioEncoder);
524            return UNKNOWN_ERROR;
525        }
526        if (mSampleRate != 16000) {
527            LOGE("Invalid sample rate %d used for AMRWB recording",
528                    mSampleRate);
529            return UNKNOWN_ERROR;
530        }
531    }
532    if (mAudioChannels != 1) {
533        LOGE("Invalid number of audio channels %d used for amr recording",
534                mAudioChannels);
535        return UNKNOWN_ERROR;
536    }
537
538    if (mAudioSource >= AUDIO_SOURCE_LIST_END) {
539        LOGE("Invalid audio source: %d", mAudioSource);
540        return UNKNOWN_ERROR;
541    }
542
543    sp<MediaSource> audioEncoder = createAudioSource();
544
545    if (audioEncoder == NULL) {
546        return UNKNOWN_ERROR;
547    }
548
549    CHECK(mOutputFd >= 0);
550    mWriter = new AMRWriter(dup(mOutputFd));
551    mWriter->addSource(audioEncoder);
552
553    if (mMaxFileDurationUs != 0) {
554        mWriter->setMaxFileDuration(mMaxFileDurationUs);
555    }
556    if (mMaxFileSizeBytes != 0) {
557        mWriter->setMaxFileSize(mMaxFileSizeBytes);
558    }
559    mWriter->setListener(mListener);
560    mWriter->start();
561
562    return OK;
563}
564
565void StagefrightRecorder::clipVideoFrameRate() {
566    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
567    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
568                        "enc.vid.fps.min", mVideoEncoder);
569    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
570                        "enc.vid.fps.max", mVideoEncoder);
571    if (mFrameRate < minFrameRate) {
572        LOGW("Intended video encoding frame rate (%d fps) is too small"
573             " and will be set to (%d fps)", mFrameRate, minFrameRate);
574        mFrameRate = minFrameRate;
575    } else if (mFrameRate > maxFrameRate) {
576        LOGW("Intended video encoding frame rate (%d fps) is too large"
577             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
578        mFrameRate = maxFrameRate;
579    }
580}
581
582void StagefrightRecorder::clipVideoBitRate() {
583    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
584    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
585                        "enc.vid.bps.min", mVideoEncoder);
586    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
587                        "enc.vid.bps.max", mVideoEncoder);
588    if (mVideoBitRate < minBitRate) {
589        LOGW("Intended video encoding bit rate (%d bps) is too small"
590             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
591        mVideoBitRate = minBitRate;
592    } else if (mVideoBitRate > maxBitRate) {
593        LOGW("Intended video encoding bit rate (%d bps) is too large"
594             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
595        mVideoBitRate = maxBitRate;
596    }
597}
598
599void StagefrightRecorder::clipVideoFrameWidth() {
600    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
601    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
602                        "enc.vid.width.min", mVideoEncoder);
603    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
604                        "enc.vid.width.max", mVideoEncoder);
605    if (mVideoWidth < minFrameWidth) {
606        LOGW("Intended video encoding frame width (%d) is too small"
607             " and will be set to (%d)", mVideoWidth, minFrameWidth);
608        mVideoWidth = minFrameWidth;
609    } else if (mVideoWidth > maxFrameWidth) {
610        LOGW("Intended video encoding frame width (%d) is too large"
611             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
612        mVideoWidth = maxFrameWidth;
613    }
614}
615
616void StagefrightRecorder::clipVideoFrameHeight() {
617    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
618    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
619                        "enc.vid.height.min", mVideoEncoder);
620    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
621                        "enc.vid.height.max", mVideoEncoder);
622    if (mVideoHeight < minFrameHeight) {
623        LOGW("Intended video encoding frame height (%d) is too small"
624             " and will be set to (%d)", mVideoHeight, minFrameHeight);
625        mVideoHeight = minFrameHeight;
626    } else if (mVideoHeight > maxFrameHeight) {
627        LOGW("Intended video encoding frame height (%d) is too large"
628             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
629        mVideoHeight = maxFrameHeight;
630    }
631}
632
633status_t StagefrightRecorder::startMPEG4Recording() {
634    mWriter = new MPEG4Writer(dup(mOutputFd));
635
636    // Add audio source first if it exists
637    if (mAudioSource != AUDIO_SOURCE_LIST_END) {
638        sp<MediaSource> audioEncoder;
639        switch(mAudioEncoder) {
640            case AUDIO_ENCODER_AMR_NB:
641            case AUDIO_ENCODER_AMR_WB:
642            case AUDIO_ENCODER_AAC:
643                audioEncoder = createAudioSource();
644                break;
645            default:
646                LOGE("Unsupported audio encoder: %d", mAudioEncoder);
647                return UNKNOWN_ERROR;
648        }
649
650        if (audioEncoder == NULL) {
651            return UNKNOWN_ERROR;
652        }
653
654        mWriter->addSource(audioEncoder);
655    }
656    if (mVideoSource == VIDEO_SOURCE_DEFAULT
657            || mVideoSource == VIDEO_SOURCE_CAMERA) {
658
659        clipVideoBitRate();
660        clipVideoFrameRate();
661        clipVideoFrameWidth();
662        clipVideoFrameHeight();
663
664        int64_t token = IPCThreadState::self()->clearCallingIdentity();
665        if (mCamera == 0) {
666            mCamera = Camera::connect(0);
667            mCamera->lock();
668        }
669
670        // Set the actual video recording frame size
671        CameraParameters params(mCamera->getParameters());
672        params.setPreviewSize(mVideoWidth, mVideoHeight);
673        params.setPreviewFrameRate(mFrameRate);
674        String8 s = params.flatten();
675        CHECK_EQ(OK, mCamera->setParameters(s));
676        CameraParameters newCameraParams(mCamera->getParameters());
677
678        // Check on video frame size
679        int frameWidth = 0, frameHeight = 0;
680        newCameraParams.getPreviewSize(&frameWidth, &frameHeight);
681        if (frameWidth  < 0 || frameWidth  != mVideoWidth ||
682            frameHeight < 0 || frameHeight != mVideoHeight) {
683            LOGE("Failed to set the video frame size to %dx%d",
684                    mVideoWidth, mVideoHeight);
685            IPCThreadState::self()->restoreCallingIdentity(token);
686            return UNKNOWN_ERROR;
687        }
688
689        // Check on video frame rate
690        int frameRate = newCameraParams.getPreviewFrameRate();
691        if (frameRate < 0 || (frameRate - mFrameRate) != 0) {
692            LOGE("Failed to set frame rate to %d fps. The actual "
693                 "frame rate is %d", mFrameRate, frameRate);
694        }
695
696        CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface));
697        IPCThreadState::self()->restoreCallingIdentity(token);
698
699        sp<CameraSource> cameraSource =
700            CameraSource::CreateFromCamera(mCamera);
701
702        CHECK(cameraSource != NULL);
703
704        sp<MetaData> enc_meta = new MetaData;
705        enc_meta->setInt32(kKeyBitRate, mVideoBitRate);
706        enc_meta->setInt32(kKeySampleRate, mFrameRate);  // XXX: kKeySampleRate?
707
708        switch (mVideoEncoder) {
709            case VIDEO_ENCODER_H263:
710                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
711                break;
712
713            case VIDEO_ENCODER_MPEG_4_SP:
714                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
715                break;
716
717            case VIDEO_ENCODER_H264:
718                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
719                break;
720
721            default:
722                CHECK(!"Should not be here, unsupported video encoding.");
723                break;
724        }
725
726        sp<MetaData> meta = cameraSource->getFormat();
727
728        int32_t width, height, stride, sliceHeight;
729        CHECK(meta->findInt32(kKeyWidth, &width));
730        CHECK(meta->findInt32(kKeyHeight, &height));
731        CHECK(meta->findInt32(kKeyStride, &stride));
732        CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
733
734        enc_meta->setInt32(kKeyWidth, width);
735        enc_meta->setInt32(kKeyHeight, height);
736        enc_meta->setInt32(kKeyIFramesInterval, mIFramesInterval);
737        enc_meta->setInt32(kKeyStride, stride);
738        enc_meta->setInt32(kKeySliceHeight, sliceHeight);
739
740        OMXClient client;
741        CHECK_EQ(client.connect(), OK);
742
743        sp<MediaSource> encoder =
744            OMXCodec::Create(
745                    client.interface(), enc_meta,
746                    true /* createEncoder */, cameraSource);
747
748        CHECK(mOutputFd >= 0);
749        mWriter->addSource(encoder);
750    }
751
752    {
753        // MPEGWriter specific handling
754        MPEG4Writer *writer = ((MPEG4Writer *) mWriter.get());  // mWriter is an MPEGWriter
755        writer->setInterleaveDuration(mInterleaveDurationUs);
756    }
757
758    if (mMaxFileDurationUs != 0) {
759        mWriter->setMaxFileDuration(mMaxFileDurationUs);
760    }
761    if (mMaxFileSizeBytes != 0) {
762        mWriter->setMaxFileSize(mMaxFileSizeBytes);
763    }
764    mWriter->setListener(mListener);
765    mWriter->start();
766    return OK;
767}
768
769status_t StagefrightRecorder::pause() {
770    if (mWriter == NULL) {
771        return UNKNOWN_ERROR;
772    }
773    mWriter->pause();
774    return OK;
775}
776
777status_t StagefrightRecorder::stop() {
778    if (mWriter == NULL) {
779        return UNKNOWN_ERROR;
780    }
781
782    mWriter->stop();
783    mWriter = NULL;
784
785    return OK;
786}
787
788status_t StagefrightRecorder::close() {
789    stop();
790
791    if (mCamera != 0) {
792        int64_t token = IPCThreadState::self()->clearCallingIdentity();
793        if ((mFlags & FLAGS_HOT_CAMERA) == 0) {
794            LOGV("Camera was cold when we started, stopping preview");
795            mCamera->stopPreview();
796        }
797        mCamera->unlock();
798        mCamera = NULL;
799        IPCThreadState::self()->restoreCallingIdentity(token);
800        mFlags = 0;
801    }
802    return OK;
803}
804
805status_t StagefrightRecorder::reset() {
806    stop();
807
808    // No audio or video source by default
809    mAudioSource = AUDIO_SOURCE_LIST_END;
810    mVideoSource = VIDEO_SOURCE_LIST_END;
811
812    // Default parameters
813    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
814    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
815    mVideoEncoder  = VIDEO_ENCODER_H263;
816    mVideoWidth    = 176;
817    mVideoHeight   = 144;
818    mFrameRate     = 20;
819    mVideoBitRate  = 192000;
820    mSampleRate    = 8000;
821    mAudioChannels = 1;
822    mAudioBitRate  = 12200;
823    mInterleaveDurationUs = 0;
824    mIFramesInterval = 1;
825    mEncoderProfiles = MediaProfiles::getInstance();
826
827    mOutputFd = -1;
828    mFlags = 0;
829
830    return OK;
831}
832
833status_t StagefrightRecorder::getMaxAmplitude(int *max) {
834    *max = 0;
835
836    return OK;
837}
838
839}  // namespace android
840