StagefrightRecorder.cpp revision d3d4e5069e1af0437c4f5a7b4ba344bda5b937af
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    mAudioSourceNode = audioSource;
488
489    return audioEncoder;
490}
491
492status_t StagefrightRecorder::startAACRecording() {
493    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF ||
494          mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
495
496    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
497    CHECK(mAudioSource != AUDIO_SOURCE_LIST_END);
498    CHECK(mOutputFd >= 0);
499
500    CHECK(0 == "AACWriter is not implemented yet");
501
502    return OK;
503}
504
505status_t StagefrightRecorder::startAMRRecording() {
506    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
507          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
508
509    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
510        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
511            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
512            LOGE("Invalid encoder %d used for AMRNB recording",
513                    mAudioEncoder);
514            return UNKNOWN_ERROR;
515        }
516        if (mSampleRate != 8000) {
517            LOGE("Invalid sampling rate %d used for AMRNB recording",
518                    mSampleRate);
519            return UNKNOWN_ERROR;
520        }
521    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
522        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
523            LOGE("Invlaid encoder %d used for AMRWB recording",
524                    mAudioEncoder);
525            return UNKNOWN_ERROR;
526        }
527        if (mSampleRate != 16000) {
528            LOGE("Invalid sample rate %d used for AMRWB recording",
529                    mSampleRate);
530            return UNKNOWN_ERROR;
531        }
532    }
533    if (mAudioChannels != 1) {
534        LOGE("Invalid number of audio channels %d used for amr recording",
535                mAudioChannels);
536        return UNKNOWN_ERROR;
537    }
538
539    if (mAudioSource >= AUDIO_SOURCE_LIST_END) {
540        LOGE("Invalid audio source: %d", mAudioSource);
541        return UNKNOWN_ERROR;
542    }
543
544    sp<MediaSource> audioEncoder = createAudioSource();
545
546    if (audioEncoder == NULL) {
547        return UNKNOWN_ERROR;
548    }
549
550    CHECK(mOutputFd >= 0);
551    mWriter = new AMRWriter(dup(mOutputFd));
552    mWriter->addSource(audioEncoder);
553
554    if (mMaxFileDurationUs != 0) {
555        mWriter->setMaxFileDuration(mMaxFileDurationUs);
556    }
557    if (mMaxFileSizeBytes != 0) {
558        mWriter->setMaxFileSize(mMaxFileSizeBytes);
559    }
560    mWriter->setListener(mListener);
561    mWriter->start();
562
563    return OK;
564}
565
566void StagefrightRecorder::clipVideoFrameRate() {
567    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
568    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
569                        "enc.vid.fps.min", mVideoEncoder);
570    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
571                        "enc.vid.fps.max", mVideoEncoder);
572    if (mFrameRate < minFrameRate) {
573        LOGW("Intended video encoding frame rate (%d fps) is too small"
574             " and will be set to (%d fps)", mFrameRate, minFrameRate);
575        mFrameRate = minFrameRate;
576    } else if (mFrameRate > maxFrameRate) {
577        LOGW("Intended video encoding frame rate (%d fps) is too large"
578             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
579        mFrameRate = maxFrameRate;
580    }
581}
582
583void StagefrightRecorder::clipVideoBitRate() {
584    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
585    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
586                        "enc.vid.bps.min", mVideoEncoder);
587    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
588                        "enc.vid.bps.max", mVideoEncoder);
589    if (mVideoBitRate < minBitRate) {
590        LOGW("Intended video encoding bit rate (%d bps) is too small"
591             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
592        mVideoBitRate = minBitRate;
593    } else if (mVideoBitRate > maxBitRate) {
594        LOGW("Intended video encoding bit rate (%d bps) is too large"
595             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
596        mVideoBitRate = maxBitRate;
597    }
598}
599
600void StagefrightRecorder::clipVideoFrameWidth() {
601    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
602    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
603                        "enc.vid.width.min", mVideoEncoder);
604    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
605                        "enc.vid.width.max", mVideoEncoder);
606    if (mVideoWidth < minFrameWidth) {
607        LOGW("Intended video encoding frame width (%d) is too small"
608             " and will be set to (%d)", mVideoWidth, minFrameWidth);
609        mVideoWidth = minFrameWidth;
610    } else if (mVideoWidth > maxFrameWidth) {
611        LOGW("Intended video encoding frame width (%d) is too large"
612             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
613        mVideoWidth = maxFrameWidth;
614    }
615}
616
617void StagefrightRecorder::clipVideoFrameHeight() {
618    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
619    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
620                        "enc.vid.height.min", mVideoEncoder);
621    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
622                        "enc.vid.height.max", mVideoEncoder);
623    if (mVideoHeight < minFrameHeight) {
624        LOGW("Intended video encoding frame height (%d) is too small"
625             " and will be set to (%d)", mVideoHeight, minFrameHeight);
626        mVideoHeight = minFrameHeight;
627    } else if (mVideoHeight > maxFrameHeight) {
628        LOGW("Intended video encoding frame height (%d) is too large"
629             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
630        mVideoHeight = maxFrameHeight;
631    }
632}
633
634status_t StagefrightRecorder::startMPEG4Recording() {
635    mWriter = new MPEG4Writer(dup(mOutputFd));
636
637    // Add audio source first if it exists
638    if (mAudioSource != AUDIO_SOURCE_LIST_END) {
639        sp<MediaSource> audioEncoder;
640        switch(mAudioEncoder) {
641            case AUDIO_ENCODER_AMR_NB:
642            case AUDIO_ENCODER_AMR_WB:
643            case AUDIO_ENCODER_AAC:
644                audioEncoder = createAudioSource();
645                break;
646            default:
647                LOGE("Unsupported audio encoder: %d", mAudioEncoder);
648                return UNKNOWN_ERROR;
649        }
650
651        if (audioEncoder == NULL) {
652            return UNKNOWN_ERROR;
653        }
654
655        mWriter->addSource(audioEncoder);
656    }
657    if (mVideoSource == VIDEO_SOURCE_DEFAULT
658            || mVideoSource == VIDEO_SOURCE_CAMERA) {
659
660        clipVideoBitRate();
661        clipVideoFrameRate();
662        clipVideoFrameWidth();
663        clipVideoFrameHeight();
664
665        int64_t token = IPCThreadState::self()->clearCallingIdentity();
666        if (mCamera == 0) {
667            mCamera = Camera::connect(0);
668            mCamera->lock();
669        }
670
671        // Set the actual video recording frame size
672        CameraParameters params(mCamera->getParameters());
673        params.setPreviewSize(mVideoWidth, mVideoHeight);
674        params.setPreviewFrameRate(mFrameRate);
675        String8 s = params.flatten();
676        CHECK_EQ(OK, mCamera->setParameters(s));
677        CameraParameters newCameraParams(mCamera->getParameters());
678
679        // Check on video frame size
680        int frameWidth = 0, frameHeight = 0;
681        newCameraParams.getPreviewSize(&frameWidth, &frameHeight);
682        if (frameWidth  < 0 || frameWidth  != mVideoWidth ||
683            frameHeight < 0 || frameHeight != mVideoHeight) {
684            LOGE("Failed to set the video frame size to %dx%d",
685                    mVideoWidth, mVideoHeight);
686            IPCThreadState::self()->restoreCallingIdentity(token);
687            return UNKNOWN_ERROR;
688        }
689
690        // Check on video frame rate
691        int frameRate = newCameraParams.getPreviewFrameRate();
692        if (frameRate < 0 || (frameRate - mFrameRate) != 0) {
693            LOGE("Failed to set frame rate to %d fps. The actual "
694                 "frame rate is %d", mFrameRate, frameRate);
695        }
696
697        CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface));
698        IPCThreadState::self()->restoreCallingIdentity(token);
699
700        sp<CameraSource> cameraSource =
701            CameraSource::CreateFromCamera(mCamera);
702
703        CHECK(cameraSource != NULL);
704
705        sp<MetaData> enc_meta = new MetaData;
706        enc_meta->setInt32(kKeyBitRate, mVideoBitRate);
707        enc_meta->setInt32(kKeySampleRate, mFrameRate);  // XXX: kKeySampleRate?
708
709        switch (mVideoEncoder) {
710            case VIDEO_ENCODER_H263:
711                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
712                break;
713
714            case VIDEO_ENCODER_MPEG_4_SP:
715                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
716                break;
717
718            case VIDEO_ENCODER_H264:
719                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
720                break;
721
722            default:
723                CHECK(!"Should not be here, unsupported video encoding.");
724                break;
725        }
726
727        sp<MetaData> meta = cameraSource->getFormat();
728
729        int32_t width, height, stride, sliceHeight;
730        CHECK(meta->findInt32(kKeyWidth, &width));
731        CHECK(meta->findInt32(kKeyHeight, &height));
732        CHECK(meta->findInt32(kKeyStride, &stride));
733        CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
734
735        enc_meta->setInt32(kKeyWidth, width);
736        enc_meta->setInt32(kKeyHeight, height);
737        enc_meta->setInt32(kKeyIFramesInterval, mIFramesInterval);
738        enc_meta->setInt32(kKeyStride, stride);
739        enc_meta->setInt32(kKeySliceHeight, sliceHeight);
740
741        OMXClient client;
742        CHECK_EQ(client.connect(), OK);
743
744        sp<MediaSource> encoder =
745            OMXCodec::Create(
746                    client.interface(), enc_meta,
747                    true /* createEncoder */, cameraSource);
748
749        CHECK(mOutputFd >= 0);
750        mWriter->addSource(encoder);
751    }
752
753    {
754        // MPEGWriter specific handling
755        MPEG4Writer *writer = ((MPEG4Writer *) mWriter.get());  // mWriter is an MPEGWriter
756        writer->setInterleaveDuration(mInterleaveDurationUs);
757    }
758
759    if (mMaxFileDurationUs != 0) {
760        mWriter->setMaxFileDuration(mMaxFileDurationUs);
761    }
762    if (mMaxFileSizeBytes != 0) {
763        mWriter->setMaxFileSize(mMaxFileSizeBytes);
764    }
765    mWriter->setListener(mListener);
766    mWriter->start();
767    return OK;
768}
769
770status_t StagefrightRecorder::pause() {
771    if (mWriter == NULL) {
772        return UNKNOWN_ERROR;
773    }
774    mWriter->pause();
775    return OK;
776}
777
778status_t StagefrightRecorder::stop() {
779    if (mWriter == NULL) {
780        return UNKNOWN_ERROR;
781    }
782
783    mWriter->stop();
784    mWriter = NULL;
785
786    return OK;
787}
788
789status_t StagefrightRecorder::close() {
790    stop();
791
792    if (mCamera != 0) {
793        int64_t token = IPCThreadState::self()->clearCallingIdentity();
794        if ((mFlags & FLAGS_HOT_CAMERA) == 0) {
795            LOGV("Camera was cold when we started, stopping preview");
796            mCamera->stopPreview();
797        }
798        mCamera->unlock();
799        mCamera = NULL;
800        IPCThreadState::self()->restoreCallingIdentity(token);
801        mFlags = 0;
802    }
803    return OK;
804}
805
806status_t StagefrightRecorder::reset() {
807    stop();
808
809    // No audio or video source by default
810    mAudioSource = AUDIO_SOURCE_LIST_END;
811    mVideoSource = VIDEO_SOURCE_LIST_END;
812
813    // Default parameters
814    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
815    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
816    mVideoEncoder  = VIDEO_ENCODER_H263;
817    mVideoWidth    = 176;
818    mVideoHeight   = 144;
819    mFrameRate     = 20;
820    mVideoBitRate  = 192000;
821    mSampleRate    = 8000;
822    mAudioChannels = 1;
823    mAudioBitRate  = 12200;
824    mInterleaveDurationUs = 0;
825    mIFramesInterval = 1;
826    mAudioSourceNode = 0;
827    mEncoderProfiles = MediaProfiles::getInstance();
828
829    mOutputFd = -1;
830    mFlags = 0;
831
832    return OK;
833}
834
835status_t StagefrightRecorder::getMaxAmplitude(int *max) {
836    if (mAudioSourceNode != 0) {
837        *max = mAudioSourceNode->getMaxAmplitude();
838    } else {
839        *max = 0;
840    }
841
842    return OK;
843}
844
845}  // namespace android
846