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