AudioStreamInSource.cpp revision 6e0d67d7b496ce17c0970a4ffd3a6f808860949c
1/*
2 * Copyright (C) 2012 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_TAG "AudioStreamInSource"
18//#define LOG_NDEBUG 0
19
20#include <cutils/compiler.h>
21#include <utils/Log.h>
22#include <media/nbaio/AudioStreamInSource.h>
23
24namespace android {
25
26AudioStreamInSource::AudioStreamInSource(audio_stream_in *stream) :
27        NBAIO_Source(),
28        mStream(stream),
29        mStreamBufferSizeBytes(0),
30        mFramesOverrun(0),
31        mOverruns(0)
32{
33    ALOG_ASSERT(stream != NULL);
34}
35
36AudioStreamInSource::~AudioStreamInSource()
37{
38}
39
40ssize_t AudioStreamInSource::negotiate(const NBAIO_Format offers[], size_t numOffers,
41                                      NBAIO_Format counterOffers[], size_t& numCounterOffers)
42{
43    if (!Format_isValid(mFormat)) {
44        mStreamBufferSizeBytes = mStream->common.get_buffer_size(&mStream->common);
45        audio_format_t streamFormat = mStream->common.get_format(&mStream->common);
46        if (streamFormat == AUDIO_FORMAT_PCM_16_BIT) {
47            uint32_t sampleRate = mStream->common.get_sample_rate(&mStream->common);
48            audio_channel_mask_t channelMask =
49                    (audio_channel_mask_t) mStream->common.get_channels(&mStream->common);
50            mFormat = Format_from_SR_C(sampleRate, popcount(channelMask));
51            mBitShift = Format_frameBitShift(mFormat);
52        }
53    }
54    return NBAIO_Source::negotiate(offers, numOffers, counterOffers, numCounterOffers);
55}
56
57size_t AudioStreamInSource::framesOverrun()
58{
59    uint32_t framesOverrun = mStream->get_input_frames_lost(mStream);
60    if (framesOverrun > 0) {
61        mFramesOverrun += framesOverrun;
62        // FIXME only increment for contiguous ranges
63        ++mOverruns;
64    }
65    return mFramesOverrun;
66}
67
68ssize_t AudioStreamInSource::read(void *buffer, size_t count)
69{
70    if (CC_UNLIKELY(!Format_isValid(mFormat))) {
71        return NEGOTIATE;
72    }
73    ssize_t bytesRead = mStream->read(mStream, buffer, count << mBitShift);
74    if (bytesRead > 0) {
75        size_t framesRead = bytesRead >> mBitShift;
76        mFramesRead += framesRead;
77        return framesRead;
78    } else {
79        return bytesRead;
80    }
81}
82
83}   // namespace android
84