AudioSource.cpp revision d3d4e5069e1af0437c4f5a7b4ba344bda5b937af
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 <sys/time.h>
30#include <time.h>
31
32namespace android {
33
34AudioSource::AudioSource(
35        int inputSource, uint32_t sampleRate, uint32_t channels)
36    : mStarted(false),
37      mCollectStats(false),
38      mTotalReadTimeUs(0),
39      mTotalReadBytes(0),
40      mTotalReads(0),
41      mGroup(NULL) {
42
43    LOGV("sampleRate: %d, channels: %d", sampleRate, channels);
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    char value[PROPERTY_VALUE_MAX];
76    if (property_get("media.stagefright.record-stats", value, NULL)
77        && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
78        mCollectStats = true;
79    }
80
81    mTrackMaxAmplitude = false;
82    mMaxAmplitude = 0;
83    mStartTimeUs = 0;
84    int64_t startTimeUs;
85    if (params && params->findInt64(kKeyTime, &startTimeUs)) {
86        mStartTimeUs = startTimeUs;
87    }
88    status_t err = mRecord->start();
89
90    if (err == OK) {
91        mGroup = new MediaBufferGroup;
92        mGroup->add_buffer(new MediaBuffer(kMaxBufferSize));
93
94        mStarted = true;
95    }
96
97    return err;
98}
99
100status_t AudioSource::stop() {
101    if (!mStarted) {
102        return UNKNOWN_ERROR;
103    }
104
105    mRecord->stop();
106
107    delete mGroup;
108    mGroup = NULL;
109
110    mStarted = false;
111
112    if (mCollectStats) {
113        LOGI("%lld reads: %.2f bps in %lld us",
114                mTotalReads,
115                (mTotalReadBytes * 8000000.0) / mTotalReadTimeUs,
116                mTotalReadTimeUs);
117    }
118
119    return OK;
120}
121
122sp<MetaData> AudioSource::getFormat() {
123    sp<MetaData> meta = new MetaData;
124    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
125    meta->setInt32(kKeySampleRate, mRecord->getSampleRate());
126    meta->setInt32(kKeyChannelCount, mRecord->channelCount());
127    meta->setInt32(kKeyMaxInputSize, kMaxBufferSize);
128
129    return meta;
130}
131
132status_t AudioSource::read(
133        MediaBuffer **out, const ReadOptions *options) {
134    *out = NULL;
135    ++mTotalReads;
136
137    MediaBuffer *buffer;
138    CHECK_EQ(mGroup->acquire_buffer(&buffer), OK);
139
140    uint32_t numFramesRecorded;
141    mRecord->getPosition(&numFramesRecorded);
142    int64_t latency = mRecord->latency() * 1000;
143
144    int64_t readTime = systemTime() / 1000;
145    if (numFramesRecorded == 0) {
146        // Initial delay
147        if (mStartTimeUs > 0) {
148            mStartTimeUs = readTime - mStartTimeUs;
149        } else {
150            mStartTimeUs += latency;
151        }
152    }
153
154    ssize_t n = 0;
155    if (mCollectStats) {
156        n = mRecord->read(buffer->data(), buffer->size());
157        int64_t endTime = systemTime() / 1000;
158        mTotalReadTimeUs += (endTime - readTime);
159        if (n >= 0) {
160            mTotalReadBytes += n;
161        }
162    } else {
163        n = mRecord->read(buffer->data(), buffer->size());
164    }
165
166    if (n < 0) {
167        buffer->release();
168        buffer = NULL;
169
170        return (status_t)n;
171    }
172
173    if (mTrackMaxAmplitude) {
174        trackMaxAmplitude((int16_t *) buffer->data(), n >> 1);
175    }
176
177    uint32_t sampleRate = mRecord->getSampleRate();
178    int64_t timestampUs = (1000000LL * numFramesRecorded) / sampleRate + mStartTimeUs;
179    buffer->meta_data()->setInt64(kKeyTime, timestampUs);
180    LOGV("initial delay: %lld, sample rate: %d, timestamp: %lld",
181            mStartTimeUs, sampleRate, timestampUs);
182
183    buffer->set_range(0, n);
184
185    *out = buffer;
186
187    return OK;
188}
189
190void AudioSource::trackMaxAmplitude(int16_t *data, int nSamples) {
191    for (int i = nSamples; i > 0; --i) {
192        int16_t value = *data++;
193        if (value < 0) {
194            value = -value;
195        }
196        if (mMaxAmplitude < value) {
197            mMaxAmplitude = value;
198        }
199    }
200}
201
202int16_t AudioSource::getMaxAmplitude() {
203    // First call activates the tracking.
204    if (!mTrackMaxAmplitude) {
205        mTrackMaxAmplitude = true;
206    }
207    int16_t value = mMaxAmplitude;
208    mMaxAmplitude = 0;
209    LOGV("max amplitude since last call: %d", value);
210    return value;
211}
212
213}  // namespace android
214