AudioSource.cpp revision eaae38445a340c4857c1c5569475879a728e63b7
1/*
2 * Copyright (C) 2010 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 "AudioSource"
19#include <utils/Log.h>
20
21#include <media/stagefright/AudioSource.h>
22
23#include <media/AudioRecord.h>
24#include <media/stagefright/MediaBufferGroup.h>
25#include <media/stagefright/MediaDebug.h>
26#include <media/stagefright/MediaDefs.h>
27#include <media/stagefright/MetaData.h>
28#include <cutils/properties.h>
29#include <stdlib.h>
30
31namespace android {
32
33AudioSource::AudioSource(
34        int inputSource, uint32_t sampleRate, uint32_t channels)
35    : mStarted(false),
36      mCollectStats(false),
37      mPrevSampleTimeUs(0),
38      mTotalLostFrames(0),
39      mPrevLostBytes(0),
40      mGroup(NULL) {
41
42    LOGV("sampleRate: %d, channels: %d", sampleRate, channels);
43    CHECK(channels == 1 || channels == 2);
44    uint32_t flags = AudioRecord::RECORD_AGC_ENABLE |
45                     AudioRecord::RECORD_NS_ENABLE  |
46                     AudioRecord::RECORD_IIR_ENABLE;
47
48    mRecord = new AudioRecord(
49                inputSource, sampleRate, AudioSystem::PCM_16_BIT,
50                channels > 1? AudioSystem::CHANNEL_IN_STEREO: AudioSystem::CHANNEL_IN_MONO,
51                4 * kMaxBufferSize / sizeof(int16_t), /* Enable ping-pong buffers */
52                flags);
53
54    mInitCheck = mRecord->initCheck();
55}
56
57AudioSource::~AudioSource() {
58    if (mStarted) {
59        stop();
60    }
61
62    delete mRecord;
63    mRecord = NULL;
64}
65
66status_t AudioSource::initCheck() const {
67    return mInitCheck;
68}
69
70status_t AudioSource::start(MetaData *params) {
71    if (mStarted) {
72        return UNKNOWN_ERROR;
73    }
74
75    if (mInitCheck != OK) {
76        return NO_INIT;
77    }
78
79    char value[PROPERTY_VALUE_MAX];
80    if (property_get("media.stagefright.record-stats", value, NULL)
81        && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
82        mCollectStats = true;
83    }
84
85    mTrackMaxAmplitude = false;
86    mMaxAmplitude = 0;
87    mInitialReadTimeUs = 0;
88    mStartTimeUs = 0;
89    int64_t startTimeUs;
90    if (params && params->findInt64(kKeyTime, &startTimeUs)) {
91        mStartTimeUs = startTimeUs;
92    }
93    status_t err = mRecord->start();
94    if (err == OK) {
95        mGroup = new MediaBufferGroup;
96        mGroup->add_buffer(new MediaBuffer(kMaxBufferSize));
97
98        mStarted = true;
99    } else {
100        delete mRecord;
101        mRecord = NULL;
102    }
103
104
105    return err;
106}
107
108status_t AudioSource::stop() {
109    if (!mStarted) {
110        return UNKNOWN_ERROR;
111    }
112
113    if (mInitCheck != OK) {
114        return NO_INIT;
115    }
116
117    mRecord->stop();
118
119    delete mGroup;
120    mGroup = NULL;
121
122    mStarted = false;
123
124    if (mCollectStats) {
125        LOGI("Total lost audio frames: %lld",
126            mTotalLostFrames + (mPrevLostBytes >> 1));
127    }
128
129    return OK;
130}
131
132sp<MetaData> AudioSource::getFormat() {
133    if (mInitCheck != OK) {
134        return 0;
135    }
136
137    sp<MetaData> meta = new MetaData;
138    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
139    meta->setInt32(kKeySampleRate, mRecord->getSampleRate());
140    meta->setInt32(kKeyChannelCount, mRecord->channelCount());
141    meta->setInt32(kKeyMaxInputSize, kMaxBufferSize);
142
143    return meta;
144}
145
146void AudioSource::rampVolume(
147        int32_t startFrame, int32_t rampDurationFrames,
148        uint8_t *data,   size_t bytes) {
149
150    const int32_t kShift = 14;
151    int32_t fixedMultiplier = (startFrame << kShift) / rampDurationFrames;
152    const int32_t nChannels = mRecord->channelCount();
153    int32_t stopFrame = startFrame + bytes / sizeof(int16_t);
154    int16_t *frame = (int16_t *) data;
155    if (stopFrame > rampDurationFrames) {
156        stopFrame = rampDurationFrames;
157    }
158
159    while (startFrame < stopFrame) {
160        if (nChannels == 1) {  // mono
161            frame[0] = (frame[0] * fixedMultiplier) >> kShift;
162            ++frame;
163            ++startFrame;
164        } else {               // stereo
165            frame[0] = (frame[0] * fixedMultiplier) >> kShift;
166            frame[1] = (frame[1] * fixedMultiplier) >> kShift;
167            frame += 2;
168            startFrame += 2;
169        }
170
171        // Update the multiplier every 4 frames
172        if ((startFrame & 3) == 0) {
173            fixedMultiplier = (startFrame << kShift) / rampDurationFrames;
174        }
175    }
176}
177
178status_t AudioSource::read(
179        MediaBuffer **out, const ReadOptions *options) {
180
181    if (mInitCheck != OK) {
182        return NO_INIT;
183    }
184
185    int64_t readTimeUs = systemTime() / 1000;
186    *out = NULL;
187
188    MediaBuffer *buffer;
189    CHECK_EQ(mGroup->acquire_buffer(&buffer), OK);
190
191    int err = 0;
192    if (mStarted) {
193
194        uint32_t numFramesRecorded;
195        mRecord->getPosition(&numFramesRecorded);
196
197
198        if (numFramesRecorded == 0 && mPrevSampleTimeUs == 0) {
199            mInitialReadTimeUs = readTimeUs;
200            // Initial delay
201            if (mStartTimeUs > 0) {
202                mStartTimeUs = readTimeUs - mStartTimeUs;
203            } else {
204                // Assume latency is constant.
205                mStartTimeUs += mRecord->latency() * 1000;
206            }
207            mPrevSampleTimeUs = mStartTimeUs;
208        }
209
210        uint32_t sampleRate = mRecord->getSampleRate();
211
212        // Insert null frames when lost frames are detected.
213        int64_t timestampUs = mPrevSampleTimeUs;
214        uint32_t numLostBytes = mRecord->getInputFramesLost() << 1;
215        numLostBytes += mPrevLostBytes;
216#if 0
217        // Simulate lost frames
218        numLostBytes = ((rand() * 1.0 / RAND_MAX)) * 2 * kMaxBufferSize;
219        numLostBytes &= 0xFFFFFFFE; // Alignment requirement
220
221        // Reduce the chance to lose
222        if (rand() * 1.0 / RAND_MAX >= 0.05) {
223            numLostBytes = 0;
224        }
225#endif
226        if (numLostBytes > 0) {
227            if (numLostBytes > kMaxBufferSize) {
228                mPrevLostBytes = numLostBytes - kMaxBufferSize;
229                numLostBytes = kMaxBufferSize;
230            } else {
231                mPrevLostBytes = 0;
232            }
233
234            CHECK_EQ(numLostBytes & 1, 0);
235            timestampUs += ((1000000LL * (numLostBytes >> 1)) +
236                    (sampleRate >> 1)) / sampleRate;
237
238            CHECK(timestampUs > mPrevSampleTimeUs);
239            if (mCollectStats) {
240                mTotalLostFrames += (numLostBytes >> 1);
241            }
242            memset(buffer->data(), 0, numLostBytes);
243            buffer->set_range(0, numLostBytes);
244            if (numFramesRecorded == 0) {
245                buffer->meta_data()->setInt64(kKeyAnchorTime, mStartTimeUs);
246            }
247            buffer->meta_data()->setInt64(kKeyTime, mStartTimeUs + mPrevSampleTimeUs);
248            buffer->meta_data()->setInt64(kKeyDriftTime, readTimeUs - mInitialReadTimeUs);
249            mPrevSampleTimeUs = timestampUs;
250            *out = buffer;
251            return OK;
252        }
253
254        ssize_t n = mRecord->read(buffer->data(), buffer->size());
255        if (n < 0) {
256            buffer->release();
257            return (status_t)n;
258        }
259
260        int64_t recordDurationUs = (1000000LL * n >> 1) / sampleRate;
261        timestampUs += recordDurationUs;
262
263        if (mPrevSampleTimeUs - mStartTimeUs < kAutoRampStartUs) {
264            // Mute the initial video recording signal
265            memset((uint8_t *) buffer->data(), 0, n);
266        } else if (mPrevSampleTimeUs - mStartTimeUs < kAutoRampStartUs + kAutoRampDurationUs) {
267            int32_t autoRampDurationFrames =
268                    (kAutoRampDurationUs * sampleRate + 500000LL) / 1000000LL;
269
270            int32_t autoRampStartFrames =
271                    (kAutoRampStartUs * sampleRate + 500000LL) / 1000000LL;
272
273            int32_t nFrames = numFramesRecorded - autoRampStartFrames;
274            rampVolume(nFrames, autoRampDurationFrames, (uint8_t *) buffer->data(), n);
275        }
276        if (mTrackMaxAmplitude) {
277            trackMaxAmplitude((int16_t *) buffer->data(), n >> 1);
278        }
279
280        if (numFramesRecorded == 0) {
281            buffer->meta_data()->setInt64(kKeyAnchorTime, mStartTimeUs);
282        }
283
284        buffer->meta_data()->setInt64(kKeyTime, mStartTimeUs + mPrevSampleTimeUs);
285        buffer->meta_data()->setInt64(kKeyDriftTime, readTimeUs - mInitialReadTimeUs);
286        CHECK(timestampUs > mPrevSampleTimeUs);
287        mPrevSampleTimeUs = timestampUs;
288        LOGV("initial delay: %lld, sample rate: %d, timestamp: %lld",
289                mStartTimeUs, sampleRate, timestampUs);
290
291        buffer->set_range(0, n);
292
293        *out = buffer;
294        return OK;
295    }
296
297    return OK;
298}
299
300void AudioSource::trackMaxAmplitude(int16_t *data, int nSamples) {
301    for (int i = nSamples; i > 0; --i) {
302        int16_t value = *data++;
303        if (value < 0) {
304            value = -value;
305        }
306        if (mMaxAmplitude < value) {
307            mMaxAmplitude = value;
308        }
309    }
310}
311
312int16_t AudioSource::getMaxAmplitude() {
313    // First call activates the tracking.
314    if (!mTrackMaxAmplitude) {
315        mTrackMaxAmplitude = true;
316    }
317    int16_t value = mMaxAmplitude;
318    mMaxAmplitude = 0;
319    LOGV("max amplitude since last call: %d", value);
320    return value;
321}
322
323}  // namespace android
324