summaryrefslogtreecommitdiffstats
path: root/media/libmedia/AudioRecord.cpp
blob: f3e412389c93bd772e63907f63cf45ba008bd7dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
**
** Copyright 2008, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License"); 
** you may not use this file except in compliance with the License. 
** You may obtain a copy of the License at 
**
**     http://www.apache.org/licenses/LICENSE-2.0 
**
** Unless required by applicable law or agreed to in writing, software 
** distributed under the License is distributed on an "AS IS" BASIS, 
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
** See the License for the specific language governing permissions and 
** limitations under the License.
*/

#define LOG_TAG "AudioRecord"

#include <stdint.h>
#include <sys/types.h>

#include <sched.h>
#include <sys/resource.h>

#include <private/media/AudioTrackShared.h>

#include <media/AudioSystem.h>
#include <media/AudioRecord.h>

#include <utils/IServiceManager.h>
#include <utils/Log.h>
#include <utils/MemoryDealer.h>
#include <utils/Parcel.h>
#include <utils/IPCThreadState.h>
#include <utils/Timers.h>
#include <cutils/atomic.h>

#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))

namespace android {

// ---------------------------------------------------------------------------

AudioRecord::AudioRecord()
    : mStatus(NO_INIT)
{
}

AudioRecord::AudioRecord(
        int streamType,
        uint32_t sampleRate,
        int format,
        int channelCount,
        int bufferCount,
        uint32_t flags,
        callback_t cbf, void* user)
    : mStatus(NO_INIT)
{
    mStatus = set(streamType, sampleRate, format, channelCount,
            bufferCount, flags, cbf, user);
}

AudioRecord::~AudioRecord()
{
    if (mStatus == NO_ERROR) {
        if (mPosition) {
            releaseBuffer(&mAudioBuffer);
        }
        // obtainBuffer() will give up with an error
        mAudioRecord->stop();
        if (mClientRecordThread != 0) {
            mClientRecordThread->requestExitAndWait();
            mClientRecordThread.clear();
        }
        mAudioRecord.clear();
        IPCThreadState::self()->flushCommands();
    }
}

status_t AudioRecord::set(
        int streamType,
        uint32_t sampleRate,
        int format,
        int channelCount,
        int bufferCount,
        uint32_t flags,
        callback_t cbf, void* user)
{

    if (mAudioFlinger != 0) {
        return INVALID_OPERATION;
    }

    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
    if (audioFlinger == 0) {
        return NO_INIT;
    }

    if (streamType == DEFAULT_INPUT) {
        streamType = MIC_INPUT;
    }

    if (sampleRate == 0) {
        sampleRate = DEFAULT_SAMPLE_RATE;
    }
    // these below should probably come from the audioFlinger too...
    if (format == 0) {
        format = AudioSystem::PCM_16_BIT;
    }
    if (channelCount == 0) {
        channelCount = 1;
    }
    if (bufferCount == 0) {
        bufferCount = 2;
    } else if (bufferCount < 2) {
        return BAD_VALUE;
    }

    // validate parameters
    if (format != AudioSystem::PCM_16_BIT) {
        return BAD_VALUE;
    }
    if (channelCount != 1 && channelCount != 2) {
        return BAD_VALUE;
    }
    if (bufferCount < 2) {
        return BAD_VALUE;
    }

    // open record channel
    sp<IAudioRecord> record = audioFlinger->openRecord(getpid(), streamType,
            sampleRate, format, channelCount, bufferCount, flags);
    if (record == 0) {
        return NO_INIT;
    }
    sp<IMemory> cblk = record->getCblk();
    if (cblk == 0) {
        return NO_INIT;
    }
    if (cbf != 0) {
        mClientRecordThread = new ClientRecordThread(*this);
        if (mClientRecordThread == 0) {
            return NO_INIT;
        }
    }

    mStatus = NO_ERROR;

    mAudioFlinger = audioFlinger;
    mAudioRecord = record;
    mCblkMemory = cblk;
    mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
    mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
    mSampleRate = sampleRate;
    mFrameCount = audioFlinger->frameCount();
    mFormat = format;
    mBufferCount = bufferCount;
    mChannelCount = channelCount;
    mActive = 0;
    mCbf = cbf;
    mUserData = user;
    mLatency = seconds(mFrameCount) / mSampleRate;
    mPosition = 0;
    return NO_ERROR;
}

status_t AudioRecord::initCheck() const
{
    return mStatus;
}

// -------------------------------------------------------------------------

nsecs_t AudioRecord::latency() const
{
    return mLatency;
}

uint32_t AudioRecord::sampleRate() const
{
    return mSampleRate;
}

int AudioRecord::format() const
{
    return mFormat;
}

int AudioRecord::channelCount() const
{
    return mChannelCount;
}

int AudioRecord::bufferCount() const
{
    return mBufferCount;
}

// -------------------------------------------------------------------------

status_t AudioRecord::start()
{
    status_t ret = NO_ERROR;
    
    // If using record thread, protect start sequence to make sure that
    // no stop command is processed before the thread is started
    if (mClientRecordThread != 0) {
        mRecordThreadLock.lock();        
    }

    if (android_atomic_or(1, &mActive) == 0) {
        setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT);
        ret = mAudioRecord->start();
        if (ret == NO_ERROR) {
            if (mClientRecordThread != 0) {
                mClientRecordThread->run("ClientRecordThread", THREAD_PRIORITY_AUDIO_CLIENT);
            }
        }
    }
    
    if (mClientRecordThread != 0) {
        mRecordThreadLock.unlock();        
    }
    
    return ret;
}

status_t AudioRecord::stop()
{
    // If using record thread, protect stop sequence to make sure that
    // no start command is processed before requestExit() is called
    if (mClientRecordThread != 0) {
        mRecordThreadLock.lock();        
    }

    if (android_atomic_and(~1, &mActive) == 1) {
        if (mPosition) {
            mPosition = 0;
            releaseBuffer(&mAudioBuffer);
        }
        mAudioRecord->stop();
        setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
        if (mClientRecordThread != 0) {
            mClientRecordThread->requestExit();
        }
    }
    
    if (mClientRecordThread != 0) {
        mRecordThreadLock.unlock();        
    }
    
    return NO_ERROR;
}

bool AudioRecord::stopped() const
{
    return !mActive;
}

// -------------------------------------------------------------------------

status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, bool blocking)
{
    int active = mActive;
    int timeout = 0;
    status_t result;
    audio_track_cblk_t* cblk = mCblk;

    const uint32_t u = cblk->user;
    uint32_t s = cblk->server;

    if (u == s) {
        Mutex::Autolock _l(cblk->lock);
        goto start_loop_here;
        while (u == s) {
            active = mActive;
            if (UNLIKELY(!active))
                return NO_MORE_BUFFERS;
            if (UNLIKELY(!blocking))
                return WOULD_BLOCK;
            timeout = 0;
            result = cblk->cv.waitRelative(cblk->lock, seconds(1));
            if (__builtin_expect(result!=NO_ERROR, false)) {
                LOGW(   "obtainBuffer timed out (is the CPU pegged?) "
                        "user=%08x, server=%08x", u, s);
                timeout = 1;
            }
            // read the server count again
        start_loop_here:
            s = cblk->server;
        }
    }

    LOGW_IF(timeout,
        "*** SERIOUS WARNING *** obtainBuffer() timed out "
        "but didn't need to be locked. We recovered, but "
        "this shouldn't happen (user=%08x, server=%08x)", u, s);

    audioBuffer->flags       = 0;
    audioBuffer->channelCount= mChannelCount;
    audioBuffer->format      = mFormat;
    audioBuffer->frameCount  = mFrameCount;
    audioBuffer->size        = cblk->size;
    audioBuffer->raw         = (int8_t*)
            cblk->buffer(cblk->user & audio_track_cblk_t::BUFFER_MASK);
    return active ? status_t(NO_ERROR) : status_t(STOPPED);
}

void AudioRecord::releaseBuffer(Buffer* audioBuffer)
{
    // next buffer...
    if (UNLIKELY(mPosition)) {
        // clean the remaining part of the buffer
        size_t capacity = mAudioBuffer.size - mPosition;
        memset(mAudioBuffer.i8 + mPosition, 0, capacity);
    }
    audio_track_cblk_t* cblk = mCblk;
    cblk->stepUser(mBufferCount);
}

// -------------------------------------------------------------------------

ssize_t AudioRecord::read(void* buffer, size_t userSize)
{
    ssize_t read = 0;
    do {
        if (mPosition == 0) {
            status_t err = obtainBuffer(&mAudioBuffer, true);
            if (err < 0) {
                // out of buffers, return #bytes written
                if (err == status_t(NO_MORE_BUFFERS))
                    break;
                return ssize_t(err);
            }
        }

        size_t capacity = mAudioBuffer.size - mPosition;
        size_t toRead = userSize < capacity ? userSize : capacity;

        memcpy(buffer, mAudioBuffer.i8 + mPosition, toRead);

        buffer = static_cast<int8_t*>(buffer) + toRead;
        mPosition += toRead;
        userSize -= toRead;
        capacity -= toRead;
        read += toRead;

        if (capacity == 0) {
            mPosition = 0;
            releaseBuffer(&mAudioBuffer);
        }
    } while (userSize);

    return read;
}

// -------------------------------------------------------------------------

bool AudioRecord::processAudioBuffer(const sp<ClientRecordThread>& thread)
{
    Buffer audioBuffer;
    bool more;

    do {
        status_t err = obtainBuffer(&audioBuffer, true); 
        if (err < NO_ERROR) {
            LOGE("Error obtaining an audio buffer, giving up.");
            return false;
        }
        more = mCbf(mUserData, audioBuffer);
        releaseBuffer(&audioBuffer);
    } while (more && !thread->exitPending());

    // stop the track automatically
    this->stop();

    return true;
}

// =========================================================================

AudioRecord::ClientRecordThread::ClientRecordThread(AudioRecord& receiver)
    : Thread(false), mReceiver(receiver)
{
}

bool AudioRecord::ClientRecordThread::threadLoop()
{
    return mReceiver.processAudioBuffer(this);
}

// -------------------------------------------------------------------------

}; // namespace android