From 2dd4bdd715f586d4d30cf90cc6fc2bbfbce60fe0 Mon Sep 17 00:00:00 2001 From: Glenn Kasten Date: Wed, 29 Aug 2012 11:10:32 -0700 Subject: Move libnbaio out of AudioFlinger libnbaio is now a separate shared library from AudioFlinger, rather than a static library used only by AudioFlinger. AudioBufferProvider interface is now also independent of AudioFlinger, moved to include/media/ Change-Id: I9bb62ffbc38d42a38b0af76e66da5e9ab1e0e21b --- include/media/AudioBufferProvider.h | 55 ++++ include/media/ExtendedAudioBufferProvider.h | 31 ++ include/media/nbaio/AudioBufferProviderSource.h | 57 ++++ include/media/nbaio/AudioStreamInSource.h | 65 +++++ include/media/nbaio/AudioStreamOutSink.h | 68 +++++ include/media/nbaio/LibsndfileSink.h | 54 ++++ include/media/nbaio/LibsndfileSource.h | 58 ++++ include/media/nbaio/MonoPipe.h | 121 ++++++++ include/media/nbaio/MonoPipeReader.h | 64 +++++ include/media/nbaio/NBAIO.h | 315 +++++++++++++++++++++ include/media/nbaio/Pipe.h | 64 +++++ include/media/nbaio/PipeReader.h | 65 +++++ include/media/nbaio/SourceAudioBufferProvider.h | 52 ++++ include/media/nbaio/roundup.h | 31 ++ libvideoeditor/lvpp/VideoEditorSRC.h | 2 +- media/libnbaio/Android.mk | 32 +++ media/libnbaio/AudioBufferProviderSource.cpp | 145 ++++++++++ media/libnbaio/AudioStreamInSource.cpp | 83 ++++++ media/libnbaio/AudioStreamOutSink.cpp | 82 ++++++ media/libnbaio/LibsndfileSink.cpp | 50 ++++ media/libnbaio/LibsndfileSource.cpp | 80 ++++++ media/libnbaio/MonoPipe.cpp | 299 +++++++++++++++++++ media/libnbaio/MonoPipeReader.cpp | 89 ++++++ media/libnbaio/NBAIO.cpp | 190 +++++++++++++ media/libnbaio/Pipe.cpp | 70 +++++ media/libnbaio/PipeReader.cpp | 95 +++++++ media/libnbaio/SourceAudioBufferProvider.cpp | 104 +++++++ media/libnbaio/roundup.c | 32 +++ services/audioflinger/Android.mk | 28 +- services/audioflinger/AudioBufferProvider.h | 55 ---- .../audioflinger/AudioBufferProviderSource.cpp | 145 ---------- services/audioflinger/AudioBufferProviderSource.h | 57 ---- services/audioflinger/AudioFlinger.cpp | 12 +- services/audioflinger/AudioFlinger.h | 6 +- services/audioflinger/AudioMixer.h | 2 +- services/audioflinger/AudioResampler.h | 2 +- services/audioflinger/AudioStreamInSource.cpp | 83 ------ services/audioflinger/AudioStreamInSource.h | 65 ----- services/audioflinger/AudioStreamOutSink.cpp | 82 ------ services/audioflinger/AudioStreamOutSink.h | 68 ----- .../audioflinger/ExtendedAudioBufferProvider.h | 31 -- services/audioflinger/FastMixerState.h | 4 +- services/audioflinger/LibsndfileSink.cpp | 50 ---- services/audioflinger/LibsndfileSink.h | 54 ---- services/audioflinger/LibsndfileSource.cpp | 80 ------ services/audioflinger/LibsndfileSource.h | 58 ---- services/audioflinger/MonoPipe.cpp | 299 ------------------- services/audioflinger/MonoPipe.h | 121 -------- services/audioflinger/MonoPipeReader.cpp | 89 ------ services/audioflinger/MonoPipeReader.h | 64 ----- services/audioflinger/NBAIO.cpp | 190 ------------- services/audioflinger/NBAIO.h | 315 --------------------- services/audioflinger/Pipe.cpp | 70 ----- services/audioflinger/Pipe.h | 64 ----- services/audioflinger/PipeReader.cpp | 95 ------- services/audioflinger/PipeReader.h | 65 ----- .../audioflinger/SourceAudioBufferProvider.cpp | 104 ------- services/audioflinger/SourceAudioBufferProvider.h | 52 ---- services/audioflinger/roundup.c | 32 --- services/audioflinger/roundup.h | 31 -- 60 files changed, 2466 insertions(+), 2460 deletions(-) create mode 100644 include/media/AudioBufferProvider.h create mode 100644 include/media/ExtendedAudioBufferProvider.h create mode 100644 include/media/nbaio/AudioBufferProviderSource.h create mode 100644 include/media/nbaio/AudioStreamInSource.h create mode 100644 include/media/nbaio/AudioStreamOutSink.h create mode 100644 include/media/nbaio/LibsndfileSink.h create mode 100644 include/media/nbaio/LibsndfileSource.h create mode 100644 include/media/nbaio/MonoPipe.h create mode 100644 include/media/nbaio/MonoPipeReader.h create mode 100644 include/media/nbaio/NBAIO.h create mode 100644 include/media/nbaio/Pipe.h create mode 100644 include/media/nbaio/PipeReader.h create mode 100644 include/media/nbaio/SourceAudioBufferProvider.h create mode 100644 include/media/nbaio/roundup.h create mode 100644 media/libnbaio/Android.mk create mode 100644 media/libnbaio/AudioBufferProviderSource.cpp create mode 100644 media/libnbaio/AudioStreamInSource.cpp create mode 100644 media/libnbaio/AudioStreamOutSink.cpp create mode 100644 media/libnbaio/LibsndfileSink.cpp create mode 100644 media/libnbaio/LibsndfileSource.cpp create mode 100644 media/libnbaio/MonoPipe.cpp create mode 100644 media/libnbaio/MonoPipeReader.cpp create mode 100644 media/libnbaio/NBAIO.cpp create mode 100644 media/libnbaio/Pipe.cpp create mode 100644 media/libnbaio/PipeReader.cpp create mode 100644 media/libnbaio/SourceAudioBufferProvider.cpp create mode 100644 media/libnbaio/roundup.c delete mode 100644 services/audioflinger/AudioBufferProvider.h delete mode 100644 services/audioflinger/AudioBufferProviderSource.cpp delete mode 100644 services/audioflinger/AudioBufferProviderSource.h delete mode 100644 services/audioflinger/AudioStreamInSource.cpp delete mode 100644 services/audioflinger/AudioStreamInSource.h delete mode 100644 services/audioflinger/AudioStreamOutSink.cpp delete mode 100644 services/audioflinger/AudioStreamOutSink.h delete mode 100644 services/audioflinger/ExtendedAudioBufferProvider.h delete mode 100644 services/audioflinger/LibsndfileSink.cpp delete mode 100644 services/audioflinger/LibsndfileSink.h delete mode 100644 services/audioflinger/LibsndfileSource.cpp delete mode 100644 services/audioflinger/LibsndfileSource.h delete mode 100644 services/audioflinger/MonoPipe.cpp delete mode 100644 services/audioflinger/MonoPipe.h delete mode 100644 services/audioflinger/MonoPipeReader.cpp delete mode 100644 services/audioflinger/MonoPipeReader.h delete mode 100644 services/audioflinger/NBAIO.cpp delete mode 100644 services/audioflinger/NBAIO.h delete mode 100644 services/audioflinger/Pipe.cpp delete mode 100644 services/audioflinger/Pipe.h delete mode 100644 services/audioflinger/PipeReader.cpp delete mode 100644 services/audioflinger/PipeReader.h delete mode 100644 services/audioflinger/SourceAudioBufferProvider.cpp delete mode 100644 services/audioflinger/SourceAudioBufferProvider.h delete mode 100644 services/audioflinger/roundup.c delete mode 100644 services/audioflinger/roundup.h diff --git a/include/media/AudioBufferProvider.h b/include/media/AudioBufferProvider.h new file mode 100644 index 0000000..43e4de7 --- /dev/null +++ b/include/media/AudioBufferProvider.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007 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. + */ + +#ifndef ANDROID_AUDIO_BUFFER_PROVIDER_H +#define ANDROID_AUDIO_BUFFER_PROVIDER_H + +#include + +namespace android { +// ---------------------------------------------------------------------------- + +class AudioBufferProvider +{ +public: + + struct Buffer { + Buffer() : raw(NULL), frameCount(0) { } + union { + void* raw; + short* i16; + int8_t* i8; + }; + size_t frameCount; + }; + + virtual ~AudioBufferProvider() {} + + // value representing an invalid presentation timestamp + static const int64_t kInvalidPTS = 0x7FFFFFFFFFFFFFFFLL; // is too painful + + // pts is the local time when the next sample yielded by getNextBuffer + // will be rendered. + // Pass kInvalidPTS if the PTS is unknown or not applicable. + virtual status_t getNextBuffer(Buffer* buffer, int64_t pts = kInvalidPTS) = 0; + + virtual void releaseBuffer(Buffer* buffer) = 0; +}; + +// ---------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_AUDIO_BUFFER_PROVIDER_H diff --git a/include/media/ExtendedAudioBufferProvider.h b/include/media/ExtendedAudioBufferProvider.h new file mode 100644 index 0000000..00c4444 --- /dev/null +++ b/include/media/ExtendedAudioBufferProvider.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_EXTENDED_AUDIO_BUFFER_PROVIDER_H +#define ANDROID_EXTENDED_AUDIO_BUFFER_PROVIDER_H + +#include + +namespace android { + +class ExtendedAudioBufferProvider : public AudioBufferProvider { +public: + virtual size_t framesReady() const = 0; // see description at AudioFlinger.h +}; + +} // namespace android + +#endif // ANDROID_EXTENDED_AUDIO_BUFFER_PROVIDER_H diff --git a/include/media/nbaio/AudioBufferProviderSource.h b/include/media/nbaio/AudioBufferProviderSource.h new file mode 100644 index 0000000..2c4aaff --- /dev/null +++ b/include/media/nbaio/AudioBufferProviderSource.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2012 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. + */ + +// Implementation of NBAIO_Source that wraps an AudioBufferProvider + +#ifndef ANDROID_AUDIO_BUFFER_PROVIDER_SOURCE_H +#define ANDROID_AUDIO_BUFFER_PROVIDER_SOURCE_H + +#include "NBAIO.h" +#include + +namespace android { + +class AudioBufferProviderSource : public NBAIO_Source { + +public: + AudioBufferProviderSource(AudioBufferProvider *provider, NBAIO_Format format); + virtual ~AudioBufferProviderSource(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format(); + + // NBAIO_Source interface + + //virtual size_t framesRead() const; + //virtual size_t framesOverrun(); + //virtual size_t overruns(); + virtual ssize_t availableToRead(); + virtual ssize_t read(void *buffer, size_t count, int64_t readPTS); + virtual ssize_t readVia(readVia_t via, size_t total, void *user, + int64_t readPTS, size_t block); + +private: + AudioBufferProvider * const mProvider; + AudioBufferProvider::Buffer mBuffer; // current buffer + size_t mConsumed; // number of frames consumed so far from current buffer +}; + +} // namespace android + +#endif // ANDROID_AUDIO_BUFFER_PROVIDER_SOURCE_H diff --git a/include/media/nbaio/AudioStreamInSource.h b/include/media/nbaio/AudioStreamInSource.h new file mode 100644 index 0000000..07d8c89 --- /dev/null +++ b/include/media/nbaio/AudioStreamInSource.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_STREAM_IN_SOURCE_H +#define ANDROID_AUDIO_STREAM_IN_SOURCE_H + +#include +#include "NBAIO.h" + +namespace android { + +// not multi-thread safe +class AudioStreamInSource : public NBAIO_Source { + +public: + AudioStreamInSource(audio_stream_in *stream); + virtual ~AudioStreamInSource(); + + // NBAIO_Port interface + + virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Sink interface + + //virtual size_t framesRead() const; + virtual size_t framesOverrun(); + virtual size_t overruns() { (void) framesOverrun(); return mOverruns; } + + // This is an over-estimate, and could dupe the caller into making a blocking read() + // FIXME Use an audio HAL API to query the buffer filling status when it's available. + virtual ssize_t availableToRead() { return mStreamBufferSizeBytes >> mBitShift; } + + virtual ssize_t read(void *buffer, size_t count); + + // NBAIO_Sink end + +#if 0 // until necessary + audio_stream_in *stream() const { return mStream; } +#endif + +private: + audio_stream_in * const mStream; + size_t mStreamBufferSizeBytes; // as reported by get_buffer_size() + size_t mFramesOverrun; + size_t mOverruns; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_STREAM_IN_SOURCE_H diff --git a/include/media/nbaio/AudioStreamOutSink.h b/include/media/nbaio/AudioStreamOutSink.h new file mode 100644 index 0000000..5976b18 --- /dev/null +++ b/include/media/nbaio/AudioStreamOutSink.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_STREAM_OUT_SINK_H +#define ANDROID_AUDIO_STREAM_OUT_SINK_H + +#include +#include "NBAIO.h" + +namespace android { + +// not multi-thread safe +class AudioStreamOutSink : public NBAIO_Sink { + +public: + AudioStreamOutSink(audio_stream_out *stream); + virtual ~AudioStreamOutSink(); + + // NBAIO_Port interface + + virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format(); + + // NBAIO_Sink interface + + //virtual size_t framesWritten() const; + //virtual size_t framesUnderrun() const; + //virtual size_t underruns() const; + + // This is an over-estimate, and could dupe the caller into making a blocking write() + // FIXME Use an audio HAL API to query the buffer emptying status when it's available. + virtual ssize_t availableToWrite() const { return mStreamBufferSizeBytes >> mBitShift; } + + virtual ssize_t write(const void *buffer, size_t count); + + // AudioStreamOutSink wraps a HAL's output stream. Its + // getNextWriteTimestamp method is simply a passthru to the HAL's underlying + // implementation of GNWT (if any) + virtual status_t getNextWriteTimestamp(int64_t *timestamp); + + // NBAIO_Sink end + +#if 0 // until necessary + audio_stream_out *stream() const { return mStream; } +#endif + +private: + audio_stream_out * const mStream; + size_t mStreamBufferSizeBytes; // as reported by get_buffer_size() +}; + +} // namespace android + +#endif // ANDROID_AUDIO_STREAM_OUT_SINK_H diff --git a/include/media/nbaio/LibsndfileSink.h b/include/media/nbaio/LibsndfileSink.h new file mode 100644 index 0000000..f5d53d5 --- /dev/null +++ b/include/media/nbaio/LibsndfileSink.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_LIBSNDFILE_SINK_H +#define ANDROID_AUDIO_LIBSNDFILE_SINK_H + +#include "NBAIO.h" +#include "sndfile.h" + +// Implementation of NBAIO_Sink that wraps a libsndfile opened in SFM_WRITE mode + +namespace android { + +class LibsndfileSink : public NBAIO_Sink { + +public: + LibsndfileSink(SNDFILE *sndfile, const SF_INFO &sfinfo); + virtual ~LibsndfileSink(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Sink interface + + //virtual size_t framesWritten() const; + //virtual size_t framesUnderrun() const; + //virtual size_t underruns() const; + //virtual ssize_t availableToWrite() const; + virtual ssize_t write(const void *buffer, size_t count); + //virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block); + +private: + SNDFILE * mSndfile; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_LIBSNDFILE_SINK_H diff --git a/include/media/nbaio/LibsndfileSource.h b/include/media/nbaio/LibsndfileSource.h new file mode 100644 index 0000000..4fbdb4b --- /dev/null +++ b/include/media/nbaio/LibsndfileSource.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_LIBSNDFILE_SOURCE_H +#define ANDROID_AUDIO_LIBSNDFILE_SOURCE_H + +#include "NBAIO.h" +#include "sndfile.h" + +// Implementation of NBAIO_Source that wraps a libsndfile opened in SFM_READ mode + +namespace android { + +class LibsndfileSource : public NBAIO_Source { + +public: + // If 'loop' is true and it permits seeking, then we'll act as an infinite source + LibsndfileSource(SNDFILE *sndfile, const SF_INFO &sfinfo, bool loop = false); + virtual ~LibsndfileSource(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Source interface + + //virtual size_t framesRead() const; + //virtual size_t framesOverrun(); + //virtual size_t overruns(); + virtual ssize_t availableToRead(); + virtual ssize_t read(void *buffer, size_t count); + //virtual ssize_t readVia(readVia_t via, size_t total, void *user, size_t block); + +private: + SNDFILE * mSndfile; + sf_count_t mEstimatedFramesUntilEOF; + bool mLooping; + bool mReadAnyFramesThisLoopCycle; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_LIBSNDFILE_SOURCE_H diff --git a/include/media/nbaio/MonoPipe.h b/include/media/nbaio/MonoPipe.h new file mode 100644 index 0000000..c47bf6c --- /dev/null +++ b/include/media/nbaio/MonoPipe.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_MONO_PIPE_H +#define ANDROID_AUDIO_MONO_PIPE_H + +#include +#include +#include "NBAIO.h" + +namespace android { + +// MonoPipe is similar to Pipe except: +// - supports only a single reader, called MonoPipeReader +// - write() cannot overrun; instead it will return a short actual count if insufficient space +// - write() can optionally block if the pipe is full +// Like Pipe, it is not multi-thread safe for either writer or reader +// but writer and reader can be different threads. +class MonoPipe : public NBAIO_Sink { + + friend class MonoPipeReader; + +public: + // reqFrames will be rounded up to a power of 2, and all slots are available. Must be >= 2. + // Note: whatever shares this object with another thread needs to do so in an SMP-safe way (like + // creating it the object before creating the other thread, or storing the object with a + // release_store). Otherwise the other thread could see a partially-constructed object. + MonoPipe(size_t reqFrames, NBAIO_Format format, bool writeCanBlock = false); + virtual ~MonoPipe(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Sink interface + + //virtual size_t framesWritten() const; + //virtual size_t framesUnderrun() const; + //virtual size_t underruns() const; + + virtual ssize_t availableToWrite() const; + virtual ssize_t write(const void *buffer, size_t count); + //virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block); + + // MonoPipe's implementation of getNextWriteTimestamp works in conjunction + // with MonoPipeReader. Every time a MonoPipeReader reads from the pipe, it + // receives a "readPTS" indicating the point in time for which the reader + // would like to read data. This "last read PTS" is offset by the amt of + // data the reader is currently mixing and then cached cached along with the + // updated read pointer. This cached value is the local time for which the + // reader is going to request data next time it reads data (assuming we are + // in steady state and operating with no underflows). Writers to the + // MonoPipe who would like to know when their next write operation will hit + // the speakers can call getNextWriteTimestamp which will return the value + // of the last read PTS plus the duration of the amt of data waiting to be + // read in the MonoPipe. + virtual status_t getNextWriteTimestamp(int64_t *timestamp); + + // average number of frames present in the pipe under normal conditions. + // See throttling mechanism in MonoPipe::write() + size_t getAvgFrames() const { return mSetpoint; } + void setAvgFrames(size_t setpoint); + size_t maxFrames() const { return mMaxFrames; } + +private: + // A pair of methods and a helper variable which allows the reader and the + // writer to update and observe the values of mFront and mNextRdPTS in an + // atomic lock-less fashion. + // + // :: Important :: + // Two assumptions must be true in order for this lock-less approach to + // function properly on all systems. First, there may only be one updater + // thread in the system. Second, the updater thread must be running at a + // strictly higher priority than the observer threads. Currently, both of + // these assumptions are true. The only updater is always a single + // FastMixer thread (which runs with SCHED_FIFO/RT priority while the only + // observer is always an AudioFlinger::PlaybackThread running with + // traditional (non-RT) audio priority. + void updateFrontAndNRPTS(int32_t newFront, int64_t newNextRdPTS); + void observeFrontAndNRPTS(int32_t *outFront, int64_t *outNextRdPTS); + volatile int32_t mUpdateSeq; + + const size_t mReqFrames; // as requested in constructor, unrounded + const size_t mMaxFrames; // always a power of 2 + void * const mBuffer; + // mFront and mRear will never be separated by more than mMaxFrames. + // 32-bit overflow is possible if the pipe is active for a long time, but if that happens it's + // safe because we "&" with (mMaxFrames-1) at end of computations to calculate a buffer index. + volatile int32_t mFront; // written by the reader with updateFrontAndNRPTS, observed by + // the writer with observeFrontAndNRPTS + volatile int32_t mRear; // written by writer with android_atomic_release_store, + // read by reader with android_atomic_acquire_load + volatile int64_t mNextRdPTS; // written by the reader with updateFrontAndNRPTS, observed by + // the writer with observeFrontAndNRPTS + bool mWriteTsValid; // whether mWriteTs is valid + struct timespec mWriteTs; // time that the previous write() completed + size_t mSetpoint; // target value for pipe fill depth + const bool mWriteCanBlock; // whether write() should block if the pipe is full + + int64_t offsetTimestampByAudioFrames(int64_t ts, size_t audFrames); + LinearTransform mSamplesToLocalTime; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_MONO_PIPE_H diff --git a/include/media/nbaio/MonoPipeReader.h b/include/media/nbaio/MonoPipeReader.h new file mode 100644 index 0000000..0e1c992 --- /dev/null +++ b/include/media/nbaio/MonoPipeReader.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_MONO_PIPE_READER_H +#define ANDROID_AUDIO_MONO_PIPE_READER_H + +#include "MonoPipe.h" + +namespace android { + +// MonoPipeReader is safe for only a single reader thread +class MonoPipeReader : public NBAIO_Source { + +public: + + // Construct a MonoPipeReader and associate it with a MonoPipe; + // any data already in the pipe is visible to this PipeReader. + // There can be only a single MonoPipeReader per MonoPipe. + // FIXME make this constructor a factory method of MonoPipe. + MonoPipeReader(MonoPipe* pipe); + virtual ~MonoPipeReader(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Source interface + + //virtual size_t framesRead() const; + //virtual size_t framesOverrun(); + //virtual size_t overruns(); + + virtual ssize_t availableToRead(); + + virtual ssize_t read(void *buffer, size_t count, int64_t readPTS); + + // NBAIO_Source end + +#if 0 // until necessary + MonoPipe* pipe() const { return mPipe; } +#endif + +private: + MonoPipe * const mPipe; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_MONO_PIPE_READER_H diff --git a/include/media/nbaio/NBAIO.h b/include/media/nbaio/NBAIO.h new file mode 100644 index 0000000..81f42ed --- /dev/null +++ b/include/media/nbaio/NBAIO.h @@ -0,0 +1,315 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_NBAIO_H +#define ANDROID_AUDIO_NBAIO_H + +// Non-blocking audio I/O interface +// +// This header file has the abstract interfaces only. Concrete implementation classes are declared +// elsewhere. Implementations _should_ be non-blocking for all methods, especially read() and +// write(), but this is not enforced. In general, implementations do not need to be multi-thread +// safe, and any exceptions are noted in the particular implementation. + +#include +#include +#include +#include + +namespace android { + +// In addition to the usual status_t +enum { + NEGOTIATE = 0x80000010, // Must (re-)negotiate format. For negotiate() only, the offeree + // doesn't accept offers, and proposes counter-offers + OVERRUN = 0x80000011, // availableToRead(), read(), or readVia() detected lost input due + // to overrun; an event is counted and the caller should re-try + UNDERRUN = 0x80000012, // availableToWrite(), write(), or writeVia() detected a gap in + // output due to underrun (not being called often enough, or with + // enough data); an event is counted and the caller should re-try +}; + +// Negotiation of format is based on the data provider and data sink, or the data consumer and +// data source, exchanging prioritized arrays of offers and counter-offers until a single offer is +// mutually agreed upon. Each offer is an NBAIO_Format. For simplicity and performance, +// NBAIO_Format is an enum that ties together the most important combinations of the various +// attributes, rather than a struct with separate fields for format, sample rate, channel count, +// interleave, packing, alignment, etc. The reason is that NBAIO_Format tries to abstract out only +// the combinations that are actually needed within AudioFligner. If the list of combinations grows +// too large, then this decision should be re-visited. +enum NBAIO_Format { + Format_Invalid, + Format_SR44_1_C2_I16, // 44.1 kHz PCM stereo interleaved 16-bit signed + Format_SR48_C2_I16, // 48 kHz PCM stereo interleaved 16-bit signed + Format_SR44_1_C1_I16, // 44.1 kHz PCM mono interleaved 16-bit signed + Format_SR48_C1_I16, // 48 kHz PCM mono interleaved 16-bit signed +}; + +// Return the frame size of an NBAIO_Format in bytes +size_t Format_frameSize(NBAIO_Format format); + +// Return the frame size of an NBAIO_Format as a bit shift +size_t Format_frameBitShift(NBAIO_Format format); + +// Convert a sample rate in Hz and channel count to an NBAIO_Format +NBAIO_Format Format_from_SR_C(unsigned sampleRate, unsigned channelCount); + +// Return the sample rate in Hz of an NBAIO_Format +unsigned Format_sampleRate(NBAIO_Format format); + +// Return the channel count of an NBAIO_Format +unsigned Format_channelCount(NBAIO_Format format); + +// Callbacks used by NBAIO_Sink::writeVia() and NBAIO_Source::readVia() below. +typedef ssize_t (*writeVia_t)(void *user, void *buffer, size_t count); +typedef ssize_t (*readVia_t)(void *user, const void *buffer, + size_t count, int64_t readPTS); + +// Abstract class (interface) representing a data port. +class NBAIO_Port : public RefBase { + +public: + + // negotiate() must called first. The purpose of negotiate() is to check compatibility of + // formats, not to automatically adapt if they are incompatible. It's the responsibility of + // whoever sets up the graph connections to make sure formats are compatible, and this method + // just verifies that. The edges are "dumb" and don't attempt to adapt to bad connections. + // How it works: offerer proposes an array of formats, in descending order of preference from + // offers[0] to offers[numOffers - 1]. If offeree accepts one of these formats, it returns + // the index of that offer. Otherwise, offeree sets numCounterOffers to the number of + // counter-offers (up to a maximumum of the entry value of numCounterOffers), fills in the + // provided array counterOffers[] with its counter-offers, in descending order of preference + // from counterOffers[0] to counterOffers[numCounterOffers - 1], and returns NEGOTIATE. + // Note that since the offerer allocates space for counter-offers, but only the offeree knows + // how many counter-offers it has, there may be insufficient space for all counter-offers. + // In that case, the offeree sets numCounterOffers to the requested number of counter-offers + // (which is greater than the entry value of numCounterOffers), fills in as many of the most + // important counterOffers as will fit, and returns NEGOTIATE. As this implies a re-allocation, + // it should be used as a last resort. It is preferable for the offerer to simply allocate a + // larger space to begin with, and/or for the offeree to tolerate a smaller space than desired. + // Alternatively, the offerer can pass NULL for offers and counterOffers, and zero for + // numOffers. This indicates that it has not allocated space for any counter-offers yet. + // In this case, the offerree should set numCounterOffers appropriately and return NEGOTIATE. + // Then the offerer will allocate the correct amount of memory and retry. + // Format_Invalid is not allowed as either an offer or counter-offer. + // Returns: + // >= 0 Offer accepted. + // NEGOTIATE No offer accepted, and counter-offer(s) optionally made. See above for details. + virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + NBAIO_Format counterOffers[], size_t& numCounterOffers); + + // Return the current negotiated format, or Format_Invalid if negotiation has not been done, + // or if re-negotiation is required. + virtual NBAIO_Format format() const { return mNegotiated ? mFormat : Format_Invalid; } + +protected: + NBAIO_Port(NBAIO_Format format) : mNegotiated(false), mFormat(format), + mBitShift(Format_frameBitShift(format)) { } + virtual ~NBAIO_Port() { } + + // Implementations are free to ignore these if they don't need them + + bool mNegotiated; // mNegotiated implies (mFormat != Format_Invalid) + NBAIO_Format mFormat; // (mFormat != Format_Invalid) does not imply mNegotiated + size_t mBitShift; // assign in parallel with any assignment to mFormat +}; + +// Abstract class (interface) representing a non-blocking data sink, for use by a data provider. +class NBAIO_Sink : public NBAIO_Port { + +public: + + // For the next two APIs: + // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically. + + // Return the number of frames written successfully since construction. + virtual size_t framesWritten() const { return mFramesWritten; } + + // Number of frames lost due to underrun since construction. + virtual size_t framesUnderrun() const { return 0; } + + // Number of underruns since construction, where a set of contiguous lost frames is one event. + virtual size_t underruns() const { return 0; } + + // Estimate of number of frames that could be written successfully now without blocking. + // When a write() is actually attempted, the implementation is permitted to return a smaller or + // larger transfer count, however it will make a good faith effort to give an accurate estimate. + // Errors: + // NEGOTIATE (Re-)negotiation is needed. + // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. + // An underrun event is counted, and the caller should re-try this operation. + // WOULD_BLOCK Determining how many frames can be written without blocking would itself block. + virtual ssize_t availableToWrite() const { return SSIZE_MAX; } + + // Transfer data to sink from single input buffer. Implies a copy. + // Inputs: + // buffer Non-NULL buffer owned by provider. + // count Maximum number of frames to transfer. + // Return value: + // > 0 Number of frames successfully transferred prior to first error. + // = 0 Count was zero. + // < 0 status_t error occurred prior to the first frame transfer. + // Errors: + // NEGOTIATE (Re-)negotiation is needed. + // WOULD_BLOCK No frames can be transferred without blocking. + // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. + // An underrun event is counted, and the caller should re-try this operation. + virtual ssize_t write(const void *buffer, size_t count) = 0; + + // Transfer data to sink using a series of callbacks. More suitable for zero-fill, synthesis, + // and non-contiguous transfers (e.g. circular buffer or writev). + // Inputs: + // via Callback function that the sink will call as many times as needed to consume data. + // total Estimate of the number of frames the provider has available. This is an estimate, + // and it can provide a different number of frames during the series of callbacks. + // user Arbitrary void * reserved for data provider. + // block Number of frames per block, that is a suggested value for 'count' in each callback. + // Zero means no preference. This parameter is a hint only, and may be ignored. + // Return value: + // > 0 Total number of frames successfully transferred prior to first error. + // = 0 Count was zero. + // < 0 status_t error occurred prior to the first frame transfer. + // Errors: + // NEGOTIATE (Re-)negotiation is needed. + // WOULD_BLOCK No frames can be transferred without blocking. + // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. + // An underrun event is counted, and the caller should re-try this operation. + // + // The 'via' callback is called by the data sink as follows: + // Inputs: + // user Arbitrary void * reserved for data provider. + // buffer Non-NULL buffer owned by sink that callback should fill in with data, + // up to a maximum of 'count' frames. + // count Maximum number of frames to transfer during this callback. + // Return value: + // > 0 Number of frames successfully transferred during this callback prior to first error. + // = 0 Count was zero. + // < 0 status_t error occurred prior to the first frame transfer during this callback. + virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block = 0); + + // Get the time (on the LocalTime timeline) at which the first frame of audio of the next write + // operation to this sink will be eventually rendered by the HAL. + // Inputs: + // ts A pointer pointing to the int64_t which will hold the result. + // Return value: + // OK Everything went well, *ts holds the time at which the first audio frame of the next + // write operation will be rendered, or AudioBufferProvider::kInvalidPTS if this sink + // does not know the answer for some reason. Sinks which eventually lead to a HAL + // which implements get_next_write_timestamp may return Invalid temporarily if the DMA + // output of the audio driver has not started yet. Sinks which lead to a HAL which + // does not implement get_next_write_timestamp, or which don't lead to a HAL at all, + // will always return kInvalidPTS. + // Something unexpected happened internally. Check the logs and start debugging. + virtual status_t getNextWriteTimestamp(int64_t *ts) { return INVALID_OPERATION; } + +protected: + NBAIO_Sink(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesWritten(0) { } + virtual ~NBAIO_Sink() { } + + // Implementations are free to ignore these if they don't need them + size_t mFramesWritten; +}; + +// Abstract class (interface) representing a non-blocking data source, for use by a data consumer. +class NBAIO_Source : public NBAIO_Port { + +public: + + // For the next two APIs: + // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically. + + // Number of frames read successfully since construction. + virtual size_t framesRead() const { return mFramesRead; } + + // Number of frames lost due to overrun since construction. + // Not const because implementations may need to do I/O. + virtual size_t framesOverrun() /*const*/ { return 0; } + + // Number of overruns since construction, where a set of contiguous lost frames is one event. + // Not const because implementations may need to do I/O. + virtual size_t overruns() /*const*/ { return 0; } + + // Estimate of number of frames that could be read successfully now. + // When a read() is actually attempted, the implementation is permitted to return a smaller or + // larger transfer count, however it will make a good faith effort to give an accurate estimate. + // Errors: + // NEGOTIATE (Re-)negotiation is needed. + // OVERRUN One or more frames were lost due to overrun, try again to read more recent data. + // WOULD_BLOCK Determining how many frames can be read without blocking would itself block. + virtual ssize_t availableToRead() { return SSIZE_MAX; } + + // Transfer data from source into single destination buffer. Implies a copy. + // Inputs: + // buffer Non-NULL destination buffer owned by consumer. + // count Maximum number of frames to transfer. + // readPTS The presentation time (on the LocalTime timeline) for which data + // is being requested, or kInvalidPTS if not known. + // Return value: + // > 0 Number of frames successfully transferred prior to first error. + // = 0 Count was zero. + // < 0 status_t error occurred prior to the first frame transfer. + // Errors: + // NEGOTIATE (Re-)negotiation is needed. + // WOULD_BLOCK No frames can be transferred without blocking. + // OVERRUN read() has not been called frequently enough, or with enough frames to keep up. + // One or more frames were lost due to overrun, try again to read more recent data. + virtual ssize_t read(void *buffer, size_t count, int64_t readPTS) = 0; + + // Transfer data from source using a series of callbacks. More suitable for zero-fill, + // synthesis, and non-contiguous transfers (e.g. circular buffer or readv). + // Inputs: + // via Callback function that the source will call as many times as needed to provide data. + // total Estimate of the number of frames the consumer desires. This is an estimate, + // and it can consume a different number of frames during the series of callbacks. + // user Arbitrary void * reserved for data consumer. + // readPTS The presentation time (on the LocalTime timeline) for which data + // is being requested, or kInvalidPTS if not known. + // block Number of frames per block, that is a suggested value for 'count' in each callback. + // Zero means no preference. This parameter is a hint only, and may be ignored. + // Return value: + // > 0 Total number of frames successfully transferred prior to first error. + // = 0 Count was zero. + // < 0 status_t error occurred prior to the first frame transfer. + // Errors: + // NEGOTIATE (Re-)negotiation is needed. + // WOULD_BLOCK No frames can be transferred without blocking. + // OVERRUN read() has not been called frequently enough, or with enough frames to keep up. + // One or more frames were lost due to overrun, try again to read more recent data. + // + // The 'via' callback is called by the data source as follows: + // Inputs: + // user Arbitrary void * reserved for data consumer. + // dest Non-NULL buffer owned by source that callback should consume data from, + // up to a maximum of 'count' frames. + // count Maximum number of frames to transfer during this callback. + // Return value: + // > 0 Number of frames successfully transferred during this callback prior to first error. + // = 0 Count was zero. + // < 0 status_t error occurred prior to the first frame transfer during this callback. + virtual ssize_t readVia(readVia_t via, size_t total, void *user, + int64_t readPTS, size_t block = 0); + +protected: + NBAIO_Source(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesRead(0) { } + virtual ~NBAIO_Source() { } + + // Implementations are free to ignore these if they don't need them + size_t mFramesRead; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_NBAIO_H diff --git a/include/media/nbaio/Pipe.h b/include/media/nbaio/Pipe.h new file mode 100644 index 0000000..79a4eee --- /dev/null +++ b/include/media/nbaio/Pipe.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_PIPE_H +#define ANDROID_AUDIO_PIPE_H + +#include "NBAIO.h" + +namespace android { + +// Pipe is multi-thread safe for readers (see PipeReader), but safe for only a single writer thread. +// It cannot UNDERRUN on write, unless we allow designation of a master reader that provides the +// time-base. Readers can be added and removed dynamically, and it's OK to have no readers. +class Pipe : public NBAIO_Sink { + + friend class PipeReader; + +public: + // maxFrames will be rounded up to a power of 2, and all slots are available. Must be >= 2. + Pipe(size_t maxFrames, NBAIO_Format format); + virtual ~Pipe(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Sink interface + + //virtual size_t framesWritten() const; + //virtual size_t framesUnderrun() const; + //virtual size_t underruns() const; + + // The write side of a pipe permits overruns; flow control is the caller's responsibility. + // It doesn't return +infinity because that would guarantee an overrun. + virtual ssize_t availableToWrite() const { return mMaxFrames; } + + virtual ssize_t write(const void *buffer, size_t count); + //virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block); + +private: + const size_t mMaxFrames; // always a power of 2 + void * const mBuffer; + volatile int32_t mRear; // written by android_atomic_release_store + volatile int32_t mReaders; // number of PipeReader clients currently attached to this Pipe +}; + +} // namespace android + +#endif // ANDROID_AUDIO_PIPE_H diff --git a/include/media/nbaio/PipeReader.h b/include/media/nbaio/PipeReader.h new file mode 100644 index 0000000..350e6ab --- /dev/null +++ b/include/media/nbaio/PipeReader.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ANDROID_AUDIO_PIPE_READER_H +#define ANDROID_AUDIO_PIPE_READER_H + +#include "Pipe.h" + +namespace android { + +// PipeReader is safe for only a single thread +class PipeReader : public NBAIO_Source { + +public: + + // Construct a PipeReader and associate it with a Pipe + // FIXME make this constructor a factory method of Pipe. + PipeReader(Pipe& pipe); + virtual ~PipeReader(); + + // NBAIO_Port interface + + //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, + // NBAIO_Format counterOffers[], size_t& numCounterOffers); + //virtual NBAIO_Format format() const; + + // NBAIO_Source interface + + //virtual size_t framesRead() const; + virtual size_t framesOverrun() { return mFramesOverrun; } + virtual size_t overruns() { return mOverruns; } + + virtual ssize_t availableToRead(); + + virtual ssize_t read(void *buffer, size_t count, int64_t readPTS); + + // NBAIO_Source end + +#if 0 // until necessary + Pipe& pipe() const { return mPipe; } +#endif + +private: + Pipe& mPipe; + int32_t mFront; // follows behind mPipe.mRear + size_t mFramesOverrun; + size_t mOverruns; +}; + +} // namespace android + +#endif // ANDROID_AUDIO_PIPE_READER_H diff --git a/include/media/nbaio/SourceAudioBufferProvider.h b/include/media/nbaio/SourceAudioBufferProvider.h new file mode 100644 index 0000000..c08331b --- /dev/null +++ b/include/media/nbaio/SourceAudioBufferProvider.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2012 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. + */ + +// Implementation of AudioBufferProvider that wraps an NBAIO_Source + +#ifndef ANDROID_SOURCE_AUDIO_BUFFER_PROVIDER_H +#define ANDROID_SOURCE_AUDIO_BUFFER_PROVIDER_H + +#include "NBAIO.h" +#include + +namespace android { + +class SourceAudioBufferProvider : public ExtendedAudioBufferProvider { + +public: + SourceAudioBufferProvider(const sp& source); + virtual ~SourceAudioBufferProvider(); + + // AudioBufferProvider interface + virtual status_t getNextBuffer(Buffer *buffer, int64_t pts); + virtual void releaseBuffer(Buffer *buffer); + + // ExtendedAudioBufferProvider interface + virtual size_t framesReady() const; + +private: + const sp mSource; // the wrapped source + /*const*/ size_t mFrameBitShift; // log2(frame size in bytes) + void* mAllocated; // pointer to base of allocated memory + size_t mSize; // size of mAllocated in frames + size_t mOffset; // frame offset within mAllocated of valid data + size_t mRemaining; // frame count within mAllocated of valid data + size_t mGetCount; // buffer.frameCount of the most recent getNextBuffer +}; + +} // namespace android + +#endif // ANDROID_SOURCE_AUDIO_BUFFER_PROVIDER_H diff --git a/include/media/nbaio/roundup.h b/include/media/nbaio/roundup.h new file mode 100644 index 0000000..4c3cc25 --- /dev/null +++ b/include/media/nbaio/roundup.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2012 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. + */ + +#ifndef ROUNDUP_H +#define ROUNDUP_H + +#ifdef __cplusplus +extern "C" { +#endif + +// Round up to the next highest power of 2 +unsigned roundup(unsigned v); + +#ifdef __cplusplus +} +#endif + +#endif // ROUNDUP_H diff --git a/libvideoeditor/lvpp/VideoEditorSRC.h b/libvideoeditor/lvpp/VideoEditorSRC.h index 2b7e9b6..1707d4d 100755 --- a/libvideoeditor/lvpp/VideoEditorSRC.h +++ b/libvideoeditor/lvpp/VideoEditorSRC.h @@ -17,7 +17,7 @@ #include #include -#include "AudioBufferProvider.h" +#include #include "AudioResampler.h" namespace android { diff --git a/media/libnbaio/Android.mk b/media/libnbaio/Android.mk new file mode 100644 index 0000000..757272f --- /dev/null +++ b/media/libnbaio/Android.mk @@ -0,0 +1,32 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := \ + AudioBufferProviderSource.cpp \ + AudioStreamOutSink.cpp \ + AudioStreamInSource.cpp \ + NBAIO.cpp \ + MonoPipe.cpp \ + MonoPipeReader.cpp \ + Pipe.cpp \ + PipeReader.cpp \ + roundup.c \ + SourceAudioBufferProvider.cpp + +# libsndfile license is incompatible; uncomment to use for local debug only +#LOCAL_SRC_FILES += LibsndfileSink.cpp LibsndfileSource.cpp +#LOCAL_C_INCLUDES += path/to/libsndfile/src +#LOCAL_STATIC_LIBRARIES += libsndfile + +# uncomment for systrace +# LOCAL_CFLAGS += -DATRACE_TAG=ATRACE_TAG_AUDIO + +LOCAL_MODULE := libnbaio + +LOCAL_SHARED_LIBRARIES := \ + libcommon_time_client \ + libcutils \ + libutils + +include $(BUILD_SHARED_LIBRARY) diff --git a/media/libnbaio/AudioBufferProviderSource.cpp b/media/libnbaio/AudioBufferProviderSource.cpp new file mode 100644 index 0000000..74a6fdb --- /dev/null +++ b/media/libnbaio/AudioBufferProviderSource.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2012 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 "AudioBufferProviderSource" +//#define LOG_NDEBUG 0 + +#include +#include +#include + +namespace android { + +AudioBufferProviderSource::AudioBufferProviderSource(AudioBufferProvider *provider, + NBAIO_Format format) : + NBAIO_Source(format), mProvider(provider), mConsumed(0) +{ + ALOG_ASSERT(provider != NULL); + ALOG_ASSERT(format != Format_Invalid); +} + +AudioBufferProviderSource::~AudioBufferProviderSource() +{ + if (mBuffer.raw != NULL) { + mProvider->releaseBuffer(&mBuffer); + } +} + +ssize_t AudioBufferProviderSource::availableToRead() +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + return mBuffer.raw != NULL ? mBuffer.frameCount - mConsumed : 0; +} + +ssize_t AudioBufferProviderSource::read(void *buffer, + size_t count, + int64_t readPTS) +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + if (CC_UNLIKELY(mBuffer.raw == NULL)) { + mBuffer.frameCount = count; + status_t status = mProvider->getNextBuffer(&mBuffer, readPTS); + if (status != OK) { + return status == NOT_ENOUGH_DATA ? (ssize_t) WOULD_BLOCK : (ssize_t) status; + } + ALOG_ASSERT(mBuffer.raw != NULL); + // mConsumed is 0 either from constructor or after releaseBuffer() + } + size_t available = mBuffer.frameCount - mConsumed; + if (CC_UNLIKELY(count > available)) { + count = available; + } + // count could be zero, either because count was zero on entry or + // available is zero, but both are unlikely so don't check for that + memcpy(buffer, (char *) mBuffer.raw + (mConsumed << mBitShift), count << mBitShift); + if (CC_UNLIKELY((mConsumed += count) >= mBuffer.frameCount)) { + mProvider->releaseBuffer(&mBuffer); + mBuffer.raw = NULL; + mConsumed = 0; + } + mFramesRead += count; + // For better responsiveness with large values of count, + // return a short count rather than continuing with next buffer. + // This gives the caller a chance to interpolate other actions. + return count; +} + +ssize_t AudioBufferProviderSource::readVia(readVia_t via, size_t total, void *user, + int64_t readPTS, size_t block) +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + if (CC_UNLIKELY(block == 0)) { + block = ~0; + } + for (size_t accumulator = 0; ; ) { + ALOG_ASSERT(accumulator <= total); + size_t count = total - accumulator; + if (CC_UNLIKELY(count == 0)) { + return accumulator; + } + if (CC_LIKELY(count > block)) { + count = block; + } + // 1 <= count <= block + if (CC_UNLIKELY(mBuffer.raw == NULL)) { + mBuffer.frameCount = count; + status_t status = mProvider->getNextBuffer(&mBuffer, readPTS); + if (CC_LIKELY(status == OK)) { + ALOG_ASSERT(mBuffer.raw != NULL && mBuffer.frameCount <= count); + // mConsumed is 0 either from constructor or after releaseBuffer() + continue; + } + // FIXME simplify logic - does the initial count and block checks again for no reason; + // don't you just want to fall through to the size_t available line? + if (CC_LIKELY(status == NOT_ENOUGH_DATA)) { + status = WOULD_BLOCK; + } + return accumulator > 0 ? accumulator : (ssize_t) status; + } + size_t available = mBuffer.frameCount - mConsumed; + if (CC_UNLIKELY(count > available)) { + count = available; + } + if (CC_LIKELY(count > 0)) { + char* readTgt = (char *) mBuffer.raw + (mConsumed << mBitShift); + ssize_t ret = via(user, readTgt, count, readPTS); + if (CC_UNLIKELY(ret <= 0)) { + if (CC_LIKELY(accumulator > 0)) { + return accumulator; + } + return ret; + } + ALOG_ASSERT((size_t) ret <= count); + mFramesRead += ret; + accumulator += ret; + if (CC_LIKELY((mConsumed += ret) < mBuffer.frameCount)) { + continue; + } + } + mProvider->releaseBuffer(&mBuffer); + mBuffer.raw = NULL; + mConsumed = 0; + // don't get next buffer until we really need it + } +} + +} // namespace android diff --git a/media/libnbaio/AudioStreamInSource.cpp b/media/libnbaio/AudioStreamInSource.cpp new file mode 100644 index 0000000..05273f6 --- /dev/null +++ b/media/libnbaio/AudioStreamInSource.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2012 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 "AudioStreamInSource" +//#define LOG_NDEBUG 0 + +#include +#include +#include + +namespace android { + +AudioStreamInSource::AudioStreamInSource(audio_stream_in *stream) : + NBAIO_Source(), + mStream(stream), + mStreamBufferSizeBytes(0), + mFramesOverrun(0), + mOverruns(0) +{ + ALOG_ASSERT(stream != NULL); +} + +AudioStreamInSource::~AudioStreamInSource() +{ +} + +ssize_t AudioStreamInSource::negotiate(const NBAIO_Format offers[], size_t numOffers, + NBAIO_Format counterOffers[], size_t& numCounterOffers) +{ + if (mFormat == Format_Invalid) { + mStreamBufferSizeBytes = mStream->common.get_buffer_size(&mStream->common); + audio_format_t streamFormat = mStream->common.get_format(&mStream->common); + if (streamFormat == AUDIO_FORMAT_PCM_16_BIT) { + uint32_t sampleRate = mStream->common.get_sample_rate(&mStream->common); + audio_channel_mask_t channelMask = + (audio_channel_mask_t) mStream->common.get_channels(&mStream->common); + mFormat = Format_from_SR_C(sampleRate, popcount(channelMask)); + mBitShift = Format_frameBitShift(mFormat); + } + } + return NBAIO_Source::negotiate(offers, numOffers, counterOffers, numCounterOffers); +} + +size_t AudioStreamInSource::framesOverrun() +{ + uint32_t framesOverrun = mStream->get_input_frames_lost(mStream); + if (framesOverrun > 0) { + mFramesOverrun += framesOverrun; + // FIXME only increment for contiguous ranges + ++mOverruns; + } + return mFramesOverrun; +} + +ssize_t AudioStreamInSource::read(void *buffer, size_t count) +{ + if (CC_UNLIKELY(mFormat == Format_Invalid)) { + return NEGOTIATE; + } + ssize_t bytesRead = mStream->read(mStream, buffer, count << mBitShift); + if (bytesRead > 0) { + size_t framesRead = bytesRead >> mBitShift; + mFramesRead += framesRead; + return framesRead; + } else { + return bytesRead; + } +} + +} // namespace android diff --git a/media/libnbaio/AudioStreamOutSink.cpp b/media/libnbaio/AudioStreamOutSink.cpp new file mode 100644 index 0000000..6f525e5 --- /dev/null +++ b/media/libnbaio/AudioStreamOutSink.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2012 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 "AudioStreamOutSink" +//#define LOG_NDEBUG 0 + +#include +#include + +namespace android { + +AudioStreamOutSink::AudioStreamOutSink(audio_stream_out *stream) : + NBAIO_Sink(), + mStream(stream), + mStreamBufferSizeBytes(0) +{ + ALOG_ASSERT(stream != NULL); +} + +AudioStreamOutSink::~AudioStreamOutSink() +{ +} + +ssize_t AudioStreamOutSink::negotiate(const NBAIO_Format offers[], size_t numOffers, + NBAIO_Format counterOffers[], size_t& numCounterOffers) +{ + if (mFormat == Format_Invalid) { + mStreamBufferSizeBytes = mStream->common.get_buffer_size(&mStream->common); + audio_format_t streamFormat = mStream->common.get_format(&mStream->common); + if (streamFormat == AUDIO_FORMAT_PCM_16_BIT) { + uint32_t sampleRate = mStream->common.get_sample_rate(&mStream->common); + audio_channel_mask_t channelMask = + (audio_channel_mask_t) mStream->common.get_channels(&mStream->common); + mFormat = Format_from_SR_C(sampleRate, popcount(channelMask)); + mBitShift = Format_frameBitShift(mFormat); + } + } + return NBAIO_Sink::negotiate(offers, numOffers, counterOffers, numCounterOffers); +} + +ssize_t AudioStreamOutSink::write(const void *buffer, size_t count) +{ + if (!mNegotiated) { + return NEGOTIATE; + } + ALOG_ASSERT(mFormat != Format_Invalid); + ssize_t ret = mStream->write(mStream, buffer, count << mBitShift); + if (ret > 0) { + ret >>= mBitShift; + mFramesWritten += ret; + } else { + // FIXME verify HAL implementations are returning the correct error codes e.g. WOULD_BLOCK + } + return ret; +} + +status_t AudioStreamOutSink::getNextWriteTimestamp(int64_t *timestamp) { + ALOG_ASSERT(timestamp != NULL); + + if (NULL == mStream) + return INVALID_OPERATION; + + if (NULL == mStream->get_next_write_timestamp) + return INVALID_OPERATION; + + return mStream->get_next_write_timestamp(mStream, timestamp); +} + +} // namespace android diff --git a/media/libnbaio/LibsndfileSink.cpp b/media/libnbaio/LibsndfileSink.cpp new file mode 100644 index 0000000..77debc0 --- /dev/null +++ b/media/libnbaio/LibsndfileSink.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2012 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 "LibsndfileSink" +//#define LOG_NDEBUG 0 + +#include +#include +#include + +namespace android { + +LibsndfileSink::LibsndfileSink(SNDFILE *sndfile, const SF_INFO &sfinfo) : + NBAIO_Sink(Format_from_SR_C(sfinfo.samplerate, sfinfo.channels)), + mSndfile(sndfile) +{ +} + +LibsndfileSink::~LibsndfileSink() +{ + // do not close mSndfile; we don't own it +} + +ssize_t LibsndfileSink::write(const void *buffer, size_t count) +{ + if (!mNegotiated) { + return (ssize_t) NEGOTIATE; + } + if (mSndfile == NULL) { + return (ssize_t) NO_INIT; + } + sf_count_t actual = sf_writef_short(mSndfile, (short *) buffer, (sf_count_t) count); + mFramesWritten += actual; + return actual; +} + +} // namespace android diff --git a/media/libnbaio/LibsndfileSource.cpp b/media/libnbaio/LibsndfileSource.cpp new file mode 100644 index 0000000..98610e0 --- /dev/null +++ b/media/libnbaio/LibsndfileSource.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2012 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 "LibsndfileSource" +//#define LOG_NDEBUG 0 + +#include +#include +#include + +namespace android { + +LibsndfileSource::LibsndfileSource(SNDFILE *sndfile, const SF_INFO &sfinfo, bool loop) : + NBAIO_Source(Format_from_SR_C(sfinfo.samplerate, sfinfo.channels)), + mSndfile(sndfile), + mEstimatedFramesUntilEOF(sfinfo.frames), + mLooping(loop && sfinfo.seekable), + mReadAnyFramesThisLoopCycle(false) +{ +} + +LibsndfileSource::~LibsndfileSource() +{ + // do not close mSndfile; we don't own it +} + +ssize_t LibsndfileSource::availableToRead() +{ + // after we reach the presumed EOF, report infinity just in case there's actually more + return !mLooping && mEstimatedFramesUntilEOF > 0 ? mEstimatedFramesUntilEOF : SSIZE_MAX; +} + +ssize_t LibsndfileSource::read(void *buffer, size_t count) +{ + if (!mNegotiated) { + return (ssize_t) NEGOTIATE; + } + if (mSndfile == NULL) { + return (ssize_t) NO_INIT; + } + sf_count_t actual = sf_readf_short(mSndfile, (short *) buffer, (sf_count_t) count); + // Detect EOF by zero frames read, not by mFramesUntilEOF as it could be inaccurate + if (actual == 0) { + if (mLooping) { + if (mReadAnyFramesThisLoopCycle) { + (void) sf_seek(mSndfile, (sf_count_t) 0, SEEK_SET); + mReadAnyFramesThisLoopCycle = false; + } else { + // We didn't read any frames during the current loop cycle, so disable + // further looping to prevent the caller from busy waiting at read(). + // This is especially important when looping an empty file. + mLooping = false; + } + } + } else { + mFramesRead += actual; + if (actual >= mEstimatedFramesUntilEOF) { + mEstimatedFramesUntilEOF = 0; + } else { + mEstimatedFramesUntilEOF -= actual; + } + mReadAnyFramesThisLoopCycle = true; + } + return actual; +} + +} // namespace android diff --git a/media/libnbaio/MonoPipe.cpp b/media/libnbaio/MonoPipe.cpp new file mode 100644 index 0000000..c426efb --- /dev/null +++ b/media/libnbaio/MonoPipe.cpp @@ -0,0 +1,299 @@ +/* + * Copyright (C) 2012 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 "MonoPipe" +//#define LOG_NDEBUG 0 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace android { + +MonoPipe::MonoPipe(size_t reqFrames, NBAIO_Format format, bool writeCanBlock) : + NBAIO_Sink(format), + mUpdateSeq(0), + mReqFrames(reqFrames), + mMaxFrames(roundup(reqFrames)), + mBuffer(malloc(mMaxFrames * Format_frameSize(format))), + mFront(0), + mRear(0), + mWriteTsValid(false), + // mWriteTs + mSetpoint((reqFrames * 11) / 16), + mWriteCanBlock(writeCanBlock) +{ + CCHelper tmpHelper; + status_t res; + uint64_t N, D; + + mNextRdPTS = AudioBufferProvider::kInvalidPTS; + + mSamplesToLocalTime.a_zero = 0; + mSamplesToLocalTime.b_zero = 0; + mSamplesToLocalTime.a_to_b_numer = 0; + mSamplesToLocalTime.a_to_b_denom = 0; + + D = Format_sampleRate(format); + if (OK != (res = tmpHelper.getLocalFreq(&N))) { + ALOGE("Failed to fetch local time frequency when constructing a" + " MonoPipe (res = %d). getNextWriteTimestamp calls will be" + " non-functional", res); + return; + } + + LinearTransform::reduce(&N, &D); + static const uint64_t kSignedHiBitsMask = ~(0x7FFFFFFFull); + static const uint64_t kUnsignedHiBitsMask = ~(0xFFFFFFFFull); + if ((N & kSignedHiBitsMask) || (D & kUnsignedHiBitsMask)) { + ALOGE("Cannot reduce sample rate to local clock frequency ratio to fit" + " in a 32/32 bit rational. (max reduction is 0x%016llx/0x%016llx" + "). getNextWriteTimestamp calls will be non-functional", N, D); + return; + } + + mSamplesToLocalTime.a_to_b_numer = static_cast(N); + mSamplesToLocalTime.a_to_b_denom = static_cast(D); +} + +MonoPipe::~MonoPipe() +{ + free(mBuffer); +} + +ssize_t MonoPipe::availableToWrite() const +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + // uses mMaxFrames not mReqFrames, so allows "over-filling" the pipe beyond requested limit + ssize_t ret = mMaxFrames - (mRear - android_atomic_acquire_load(&mFront)); + ALOG_ASSERT((0 <= ret) && (ret <= mMaxFrames)); + return ret; +} + +ssize_t MonoPipe::write(const void *buffer, size_t count) +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + size_t totalFramesWritten = 0; + while (count > 0) { + // can't return a negative value, as we already checked for !mNegotiated + size_t avail = availableToWrite(); + size_t written = avail; + if (CC_LIKELY(written > count)) { + written = count; + } + size_t rear = mRear & (mMaxFrames - 1); + size_t part1 = mMaxFrames - rear; + if (part1 > written) { + part1 = written; + } + if (CC_LIKELY(part1 > 0)) { + memcpy((char *) mBuffer + (rear << mBitShift), buffer, part1 << mBitShift); + if (CC_UNLIKELY(rear + part1 == mMaxFrames)) { + size_t part2 = written - part1; + if (CC_LIKELY(part2 > 0)) { + memcpy(mBuffer, (char *) buffer + (part1 << mBitShift), part2 << mBitShift); + } + } + android_atomic_release_store(written + mRear, &mRear); + totalFramesWritten += written; + } + if (!mWriteCanBlock) { + break; + } + count -= written; + buffer = (char *) buffer + (written << mBitShift); + // Simulate blocking I/O by sleeping at different rates, depending on a throttle. + // The throttle tries to keep the mean pipe depth near the setpoint, with a slight jitter. + uint32_t ns; + if (written > 0) { + size_t filled = (mMaxFrames - avail) + written; + // FIXME cache these values to avoid re-computation + if (filled <= mSetpoint / 2) { + // pipe is (nearly) empty, fill quickly + ns = written * ( 500000000 / Format_sampleRate(mFormat)); + } else if (filled <= (mSetpoint * 3) / 4) { + // pipe is below setpoint, fill at slightly faster rate + ns = written * ( 750000000 / Format_sampleRate(mFormat)); + } else if (filled <= (mSetpoint * 5) / 4) { + // pipe is at setpoint, fill at nominal rate + ns = written * (1000000000 / Format_sampleRate(mFormat)); + } else if (filled <= (mSetpoint * 3) / 2) { + // pipe is above setpoint, fill at slightly slower rate + ns = written * (1150000000 / Format_sampleRate(mFormat)); + } else if (filled <= (mSetpoint * 7) / 4) { + // pipe is overflowing, fill slowly + ns = written * (1350000000 / Format_sampleRate(mFormat)); + } else { + // pipe is severely overflowing + ns = written * (1750000000 / Format_sampleRate(mFormat)); + } + } else { + ns = count * (1350000000 / Format_sampleRate(mFormat)); + } + if (ns > 999999999) { + ns = 999999999; + } + struct timespec nowTs; + bool nowTsValid = !clock_gettime(CLOCK_MONOTONIC, &nowTs); + // deduct the elapsed time since previous write() completed + if (nowTsValid && mWriteTsValid) { + time_t sec = nowTs.tv_sec - mWriteTs.tv_sec; + long nsec = nowTs.tv_nsec - mWriteTs.tv_nsec; + if (nsec < 0) { + --sec; + nsec += 1000000000; + } + if (sec == 0) { + if ((long) ns > nsec) { + ns -= nsec; + } else { + ns = 0; + } + } + } + if (ns > 0) { + const struct timespec req = {0, ns}; + nanosleep(&req, NULL); + } + // record the time that this write() completed + if (nowTsValid) { + mWriteTs = nowTs; + if ((mWriteTs.tv_nsec += ns) >= 1000000000) { + mWriteTs.tv_nsec -= 1000000000; + ++mWriteTs.tv_sec; + } + } + mWriteTsValid = nowTsValid; + } + mFramesWritten += totalFramesWritten; + return totalFramesWritten; +} + +void MonoPipe::setAvgFrames(size_t setpoint) +{ + mSetpoint = setpoint; +} + +status_t MonoPipe::getNextWriteTimestamp(int64_t *timestamp) +{ + int32_t front; + + ALOG_ASSERT(NULL != timestamp); + + if (0 == mSamplesToLocalTime.a_to_b_denom) + return UNKNOWN_ERROR; + + observeFrontAndNRPTS(&front, timestamp); + + if (AudioBufferProvider::kInvalidPTS != *timestamp) { + // If we have a valid read-pointer and next read timestamp pair, then + // use the current value of the write pointer to figure out how many + // frames are in the buffer, and offset the timestamp by that amt. Then + // next time we write to the MonoPipe, the data will hit the speakers at + // the next read timestamp plus the current amount of data in the + // MonoPipe. + size_t pendingFrames = (mRear - front) & (mMaxFrames - 1); + *timestamp = offsetTimestampByAudioFrames(*timestamp, pendingFrames); + } + + return OK; +} + +void MonoPipe::updateFrontAndNRPTS(int32_t newFront, int64_t newNextRdPTS) +{ + // Set the MSB of the update sequence number to indicate that there is a + // multi-variable update in progress. Use an atomic store with an "acquire" + // barrier to make sure that the next operations cannot be re-ordered and + // take place before the change to mUpdateSeq is commited.. + int32_t tmp = mUpdateSeq | 0x80000000; + android_atomic_acquire_store(tmp, &mUpdateSeq); + + // Update mFront and mNextRdPTS + mFront = newFront; + mNextRdPTS = newNextRdPTS; + + // We are finished with the update. Compute the next sequnce number (which + // should be the old sequence number, plus one, and with the MSB cleared) + // and then store it in mUpdateSeq using an atomic store with a "release" + // barrier so our update operations cannot be re-ordered past the update of + // the sequence number. + tmp = (tmp + 1) & 0x7FFFFFFF; + android_atomic_release_store(tmp, &mUpdateSeq); +} + +void MonoPipe::observeFrontAndNRPTS(int32_t *outFront, int64_t *outNextRdPTS) +{ + // Perform an atomic observation of mFront and mNextRdPTS. Basically, + // atomically observe the sequence number, then observer the variables, then + // atomically observe the sequence number again. If the two observations of + // the sequence number match, and the update-in-progress bit was not set, + // then we know we have a successful atomic observation. Otherwise, we loop + // around and try again. + // + // Note, it is very important that the observer be a lower priority thread + // than the updater. If the updater is lower than the observer, or they are + // the same priority and running with SCHED_FIFO (implying that quantum + // based premption is disabled) then we run the risk of deadlock. + int32_t seqOne, seqTwo; + + do { + seqOne = android_atomic_acquire_load(&mUpdateSeq); + *outFront = mFront; + *outNextRdPTS = mNextRdPTS; + seqTwo = android_atomic_release_load(&mUpdateSeq); + } while ((seqOne != seqTwo) || (seqOne & 0x80000000)); +} + +int64_t MonoPipe::offsetTimestampByAudioFrames(int64_t ts, size_t audFrames) +{ + if (0 == mSamplesToLocalTime.a_to_b_denom) + return AudioBufferProvider::kInvalidPTS; + + if (ts == AudioBufferProvider::kInvalidPTS) + return AudioBufferProvider::kInvalidPTS; + + int64_t frame_lt_duration; + if (!mSamplesToLocalTime.doForwardTransform(audFrames, + &frame_lt_duration)) { + // This should never fail, but if there is a bug which is causing it + // to fail, this message would probably end up flooding the logs + // because the conversion would probably fail forever. Log the + // error, but then zero out the ratio in the linear transform so + // that we don't try to do any conversions from now on. This + // MonoPipe's getNextWriteTimestamp is now broken for good. + ALOGE("Overflow when attempting to convert %d audio frames to" + " duration in local time. getNextWriteTimestamp will fail from" + " now on.", audFrames); + mSamplesToLocalTime.a_to_b_numer = 0; + mSamplesToLocalTime.a_to_b_denom = 0; + return AudioBufferProvider::kInvalidPTS; + } + + return ts + frame_lt_duration; +} + +} // namespace android diff --git a/media/libnbaio/MonoPipeReader.cpp b/media/libnbaio/MonoPipeReader.cpp new file mode 100644 index 0000000..394f6ac --- /dev/null +++ b/media/libnbaio/MonoPipeReader.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2012 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 "MonoPipeReader" +//#define LOG_NDEBUG 0 + +#include +#include +#include + +namespace android { + +MonoPipeReader::MonoPipeReader(MonoPipe* pipe) : + NBAIO_Source(pipe->mFormat), + mPipe(pipe) +{ +} + +MonoPipeReader::~MonoPipeReader() +{ +} + +ssize_t MonoPipeReader::availableToRead() +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + ssize_t ret = android_atomic_acquire_load(&mPipe->mRear) - mPipe->mFront; + ALOG_ASSERT((0 <= ret) && (ret <= mMaxFrames)); + return ret; +} + +ssize_t MonoPipeReader::read(void *buffer, size_t count, int64_t readPTS) +{ + // Compute the "next read PTS" and cache it. Callers of read pass a read + // PTS indicating the local time for which they are requesting data along + // with a count (which is the number of audio frames they are going to + // ultimately pass to the next stage of the pipeline). Offsetting readPTS + // by the duration of count will give us the readPTS which will be passed to + // us next time, assuming they system continues to operate in steady state + // with no discontinuities. We stash this value so it can be used by the + // MonoPipe writer to imlement getNextWriteTimestamp. + int64_t nextReadPTS; + nextReadPTS = mPipe->offsetTimestampByAudioFrames(readPTS, count); + + // count == 0 is unlikely and not worth checking for explicitly; will be handled automatically + ssize_t red = availableToRead(); + if (CC_UNLIKELY(red <= 0)) { + // Uh-oh, looks like we are underflowing. Update the next read PTS and + // get out. + mPipe->updateFrontAndNRPTS(mPipe->mFront, nextReadPTS); + return red; + } + if (CC_LIKELY((size_t) red > count)) { + red = count; + } + size_t front = mPipe->mFront & (mPipe->mMaxFrames - 1); + size_t part1 = mPipe->mMaxFrames - front; + if (part1 > (size_t) red) { + part1 = red; + } + if (CC_LIKELY(part1 > 0)) { + memcpy(buffer, (char *) mPipe->mBuffer + (front << mBitShift), part1 << mBitShift); + if (CC_UNLIKELY(front + part1 == mPipe->mMaxFrames)) { + size_t part2 = red - part1; + if (CC_LIKELY(part2 > 0)) { + memcpy((char *) buffer + (part1 << mBitShift), mPipe->mBuffer, part2 << mBitShift); + } + } + mPipe->updateFrontAndNRPTS(red + mPipe->mFront, nextReadPTS); + mFramesRead += red; + } + return red; +} + +} // namespace android diff --git a/media/libnbaio/NBAIO.cpp b/media/libnbaio/NBAIO.cpp new file mode 100644 index 0000000..00d2017 --- /dev/null +++ b/media/libnbaio/NBAIO.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2012 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 "NBAIO" +//#define LOG_NDEBUG 0 + +#include +#include + +namespace android { + +size_t Format_frameSize(NBAIO_Format format) +{ + switch (format) { + case Format_SR44_1_C2_I16: + case Format_SR48_C2_I16: + return 2 * sizeof(short); + case Format_SR44_1_C1_I16: + case Format_SR48_C1_I16: + return 1 * sizeof(short); + case Format_Invalid: + default: + return 0; + } +} + +size_t Format_frameBitShift(NBAIO_Format format) +{ + switch (format) { + case Format_SR44_1_C2_I16: + case Format_SR48_C2_I16: + return 2; // 1 << 2 == 2 * sizeof(short) + case Format_SR44_1_C1_I16: + case Format_SR48_C1_I16: + return 1; // 1 << 1 == 1 * sizeof(short) + case Format_Invalid: + default: + return 0; + } +} + +unsigned Format_sampleRate(NBAIO_Format format) +{ + switch (format) { + case Format_SR44_1_C1_I16: + case Format_SR44_1_C2_I16: + return 44100; + case Format_SR48_C1_I16: + case Format_SR48_C2_I16: + return 48000; + case Format_Invalid: + default: + return 0; + } +} + +unsigned Format_channelCount(NBAIO_Format format) +{ + switch (format) { + case Format_SR44_1_C1_I16: + case Format_SR48_C1_I16: + return 1; + case Format_SR44_1_C2_I16: + case Format_SR48_C2_I16: + return 2; + case Format_Invalid: + default: + return 0; + } +} + +NBAIO_Format Format_from_SR_C(unsigned sampleRate, unsigned channelCount) +{ + if (sampleRate == 44100 && channelCount == 2) return Format_SR44_1_C2_I16; + if (sampleRate == 48000 && channelCount == 2) return Format_SR48_C2_I16; + if (sampleRate == 44100 && channelCount == 1) return Format_SR44_1_C1_I16; + if (sampleRate == 48000 && channelCount == 1) return Format_SR48_C1_I16; + return Format_Invalid; +} + +// This is a default implementation; it is expected that subclasses will optimize this. +ssize_t NBAIO_Sink::writeVia(writeVia_t via, size_t total, void *user, size_t block) +{ + if (!mNegotiated) { + return (ssize_t) NEGOTIATE; + } + static const size_t maxBlock = 32; + size_t frameSize = Format_frameSize(mFormat); + ALOG_ASSERT(frameSize > 0 && frameSize <= 8); + // double guarantees alignment for stack similar to what malloc() gives for heap + if (block == 0 || block > maxBlock) { + block = maxBlock; + } + double buffer[((frameSize * block) + sizeof(double) - 1) / sizeof(double)]; + size_t accumulator = 0; + while (accumulator < total) { + size_t count = total - accumulator; + if (count > block) { + count = block; + } + ssize_t ret = via(user, buffer, count); + if (ret > 0) { + ALOG_ASSERT((size_t) ret <= count); + size_t maxRet = ret; + ret = write(buffer, maxRet); + if (ret > 0) { + ALOG_ASSERT((size_t) ret <= maxRet); + accumulator += ret; + continue; + } + } + return accumulator > 0 ? accumulator : ret; + } + return accumulator; +} + +// This is a default implementation; it is expected that subclasses will optimize this. +ssize_t NBAIO_Source::readVia(readVia_t via, size_t total, void *user, + int64_t readPTS, size_t block) +{ + if (!mNegotiated) { + return (ssize_t) NEGOTIATE; + } + static const size_t maxBlock = 32; + size_t frameSize = Format_frameSize(mFormat); + ALOG_ASSERT(frameSize > 0 && frameSize <= 8); + // double guarantees alignment for stack similar to what malloc() gives for heap + if (block == 0 || block > maxBlock) { + block = maxBlock; + } + double buffer[((frameSize * block) + sizeof(double) - 1) / sizeof(double)]; + size_t accumulator = 0; + while (accumulator < total) { + size_t count = total - accumulator; + if (count > block) { + count = block; + } + ssize_t ret = read(buffer, count, readPTS); + if (ret > 0) { + ALOG_ASSERT((size_t) ret <= count); + size_t maxRet = ret; + ret = via(user, buffer, maxRet, readPTS); + if (ret > 0) { + ALOG_ASSERT((size_t) ret <= maxRet); + accumulator += ret; + continue; + } + } + return accumulator > 0 ? accumulator : ret; + } + return accumulator; +} + +// Default implementation that only accepts my mFormat +ssize_t NBAIO_Port::negotiate(const NBAIO_Format offers[], size_t numOffers, + NBAIO_Format counterOffers[], size_t& numCounterOffers) +{ + ALOGV("negotiate offers=%p numOffers=%u countersOffers=%p numCounterOffers=%u", + offers, numOffers, counterOffers, numCounterOffers); + if (mFormat != Format_Invalid) { + for (size_t i = 0; i < numOffers; ++i) { + if (offers[i] == mFormat) { + mNegotiated = true; + return i; + } + } + if (numCounterOffers > 0) { + counterOffers[0] = mFormat; + } + numCounterOffers = 1; + } else { + numCounterOffers = 0; + } + return (ssize_t) NEGOTIATE; +} + +} // namespace android diff --git a/media/libnbaio/Pipe.cpp b/media/libnbaio/Pipe.cpp new file mode 100644 index 0000000..1c21f9c --- /dev/null +++ b/media/libnbaio/Pipe.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2012 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 "Pipe" +//#define LOG_NDEBUG 0 + +#include +#include +#include +#include +#include + +namespace android { + +Pipe::Pipe(size_t maxFrames, NBAIO_Format format) : + NBAIO_Sink(format), + mMaxFrames(roundup(maxFrames)), + mBuffer(malloc(mMaxFrames * Format_frameSize(format))), + mRear(0), + mReaders(0) +{ +} + +Pipe::~Pipe() +{ + ALOG_ASSERT(android_atomic_acquire_load(&mReaders) == 0); + free(mBuffer); +} + +ssize_t Pipe::write(const void *buffer, size_t count) +{ + // count == 0 is unlikely and not worth checking for + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + // write() is not multi-thread safe w.r.t. itself, so no mutex or atomic op needed to read mRear + size_t rear = mRear & (mMaxFrames - 1); + size_t written = mMaxFrames - rear; + if (CC_LIKELY(written > count)) { + written = count; + } + memcpy((char *) mBuffer + (rear << mBitShift), buffer, written << mBitShift); + if (CC_UNLIKELY(rear + written == mMaxFrames)) { + if (CC_UNLIKELY((count -= written) > rear)) { + count = rear; + } + if (CC_LIKELY(count > 0)) { + memcpy(mBuffer, (char *) buffer + (written << mBitShift), count << mBitShift); + written += count; + } + } + android_atomic_release_store(written + mRear, &mRear); + mFramesWritten += written; + return written; +} + +} // namespace android diff --git a/media/libnbaio/PipeReader.cpp b/media/libnbaio/PipeReader.cpp new file mode 100644 index 0000000..d786b84 --- /dev/null +++ b/media/libnbaio/PipeReader.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2012 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 "PipeReader" +//#define LOG_NDEBUG 0 + +#include +#include +#include + +namespace android { + +PipeReader::PipeReader(Pipe& pipe) : + NBAIO_Source(pipe.mFormat), + mPipe(pipe), + // any data already in the pipe is not visible to this PipeReader + mFront(android_atomic_acquire_load(&pipe.mRear)), + mFramesOverrun(0), + mOverruns(0) +{ + android_atomic_inc(&pipe.mReaders); +} + +PipeReader::~PipeReader() +{ + int32_t readers = android_atomic_dec(&mPipe.mReaders); + ALOG_ASSERT(readers > 0); +} + +ssize_t PipeReader::availableToRead() +{ + if (CC_UNLIKELY(!mNegotiated)) { + return NEGOTIATE; + } + int32_t rear = android_atomic_acquire_load(&mPipe.mRear); + // read() is not multi-thread safe w.r.t. itself, so no mutex or atomic op needed to read mFront + size_t avail = rear - mFront; + if (CC_UNLIKELY(avail > mPipe.mMaxFrames)) { + // Discard 1/16 of the most recent data in pipe to avoid another overrun immediately + int32_t oldFront = mFront; + mFront = rear - mPipe.mMaxFrames + (mPipe.mMaxFrames >> 4); + mFramesOverrun += (size_t) (mFront - oldFront); + ++mOverruns; + return OVERRUN; + } + return avail; +} + +ssize_t PipeReader::read(void *buffer, size_t count, int64_t readPTS) +{ + ssize_t avail = availableToRead(); + if (CC_UNLIKELY(avail <= 0)) { + return avail; + } + // An overrun can occur from here on and be silently ignored, + // but it will be caught at next read() + if (CC_LIKELY(count > (size_t) avail)) { + count = avail; + } + size_t front = mFront & (mPipe.mMaxFrames - 1); + size_t red = mPipe.mMaxFrames - front; + if (CC_LIKELY(red > count)) { + red = count; + } + // In particular, an overrun during the memcpy will result in reading corrupt data + memcpy(buffer, (char *) mPipe.mBuffer + (front << mBitShift), red << mBitShift); + // We could re-read the rear pointer here to detect the corruption, but why bother? + if (CC_UNLIKELY(front + red == mPipe.mMaxFrames)) { + if (CC_UNLIKELY((count -= red) > front)) { + count = front; + } + if (CC_LIKELY(count > 0)) { + memcpy((char *) buffer + (red << mBitShift), mPipe.mBuffer, count << mBitShift); + red += count; + } + } + mFront += red; + mFramesRead += red; + return red; +} + +} // namespace android diff --git a/media/libnbaio/SourceAudioBufferProvider.cpp b/media/libnbaio/SourceAudioBufferProvider.cpp new file mode 100644 index 0000000..d11a86c --- /dev/null +++ b/media/libnbaio/SourceAudioBufferProvider.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2012 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 "SourceAudioBufferProvider" +//#define LOG_NDEBUG 0 + +#include +#include + +namespace android { + +SourceAudioBufferProvider::SourceAudioBufferProvider(const sp& source) : + mSource(source), + // mFrameBitShiftFormat below + mAllocated(NULL), mSize(0), mOffset(0), mRemaining(0), mGetCount(0) +{ + ALOG_ASSERT(source != 0); + + // negotiate with source + NBAIO_Format counterOffers[1]; + size_t numCounterOffers = 1; + ssize_t index = source->negotiate(NULL, 0, counterOffers, numCounterOffers); + ALOG_ASSERT(index == (ssize_t) NEGOTIATE && numCounterOffers > 0); + numCounterOffers = 0; + index = source->negotiate(counterOffers, 1, NULL, numCounterOffers); + ALOG_ASSERT(index == 0); + mFrameBitShift = Format_frameBitShift(source->format()); +} + +SourceAudioBufferProvider::~SourceAudioBufferProvider() +{ + free(mAllocated); +} + +status_t SourceAudioBufferProvider::getNextBuffer(Buffer *buffer, int64_t pts) +{ + ALOG_ASSERT(buffer != NULL && buffer->frameCount > 0 && mGetCount == 0); + // any leftover data available? + if (mRemaining > 0) { + ALOG_ASSERT(mOffset + mRemaining <= mSize); + if (mRemaining < buffer->frameCount) { + buffer->frameCount = mRemaining; + } + buffer->raw = (char *) mAllocated + (mOffset << mFrameBitShift); + mGetCount = buffer->frameCount; + return OK; + } + // do we need to reallocate? + if (buffer->frameCount > mSize) { + free(mAllocated); + mAllocated = malloc(buffer->frameCount << mFrameBitShift); + mSize = buffer->frameCount; + } + // read from source + ssize_t actual = mSource->read(mAllocated, buffer->frameCount, pts); + if (actual > 0) { + ALOG_ASSERT((size_t) actual <= buffer->frameCount); + mOffset = 0; + mRemaining = actual; + buffer->raw = mAllocated; + buffer->frameCount = actual; + mGetCount = actual; + return OK; + } + buffer->raw = NULL; + buffer->frameCount = 0; + mGetCount = 0; + return NOT_ENOUGH_DATA; +} + +void SourceAudioBufferProvider::releaseBuffer(Buffer *buffer) +{ + ALOG_ASSERT((buffer != NULL) && + (buffer->raw == (char *) mAllocated + (mOffset << mFrameBitShift)) && + (buffer->frameCount <= mGetCount) && + (mGetCount <= mRemaining) && + (mOffset + mRemaining <= mSize)); + mOffset += buffer->frameCount; + mRemaining -= buffer->frameCount; + buffer->raw = NULL; + buffer->frameCount = 0; + mGetCount = 0; +} + +size_t SourceAudioBufferProvider::framesReady() const +{ + ssize_t avail = mSource->availableToRead(); + return avail < 0 ? 0 : (size_t) avail; +} + +} // namespace android diff --git a/media/libnbaio/roundup.c b/media/libnbaio/roundup.c new file mode 100644 index 0000000..1d552d1 --- /dev/null +++ b/media/libnbaio/roundup.c @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2012 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. + */ + +#include + +unsigned roundup(unsigned v) +{ + // __builtin_clz is undefined for zero input + if (v == 0) { + v = 1; + } + int lz = __builtin_clz((int) v); + unsigned rounded = ((unsigned) 0x80000000) >> lz; + // 0x800000001 and higher are actually rounded _down_ to prevent overflow + if (v > rounded && lz > 0) { + rounded <<= 1; + } + return rounded; +} diff --git a/services/audioflinger/Android.mk b/services/audioflinger/Android.mk index c2d2790..66759d1 100644 --- a/services/audioflinger/Android.mk +++ b/services/audioflinger/Android.mk @@ -13,32 +13,6 @@ include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) -LOCAL_SRC_FILES := \ - AudioBufferProviderSource.cpp \ - AudioStreamOutSink.cpp \ - AudioStreamInSource.cpp \ - NBAIO.cpp \ - MonoPipe.cpp \ - MonoPipeReader.cpp \ - Pipe.cpp \ - PipeReader.cpp \ - roundup.c \ - SourceAudioBufferProvider.cpp - -# libsndfile license is incompatible; uncomment to use for local debug only -#LOCAL_SRC_FILES += LibsndfileSink.cpp LibsndfileSource.cpp -#LOCAL_C_INCLUDES += path/to/libsndfile/src -#LOCAL_STATIC_LIBRARIES += libsndfile - -# uncomment for systrace -# LOCAL_CFLAGS += -DATRACE_TAG=ATRACE_TAG_AUDIO - -LOCAL_MODULE := libnbaio - -include $(BUILD_STATIC_LIBRARY) - -include $(CLEAR_VARS) - LOCAL_SRC_FILES:= \ AudioFlinger.cpp \ AudioMixer.cpp.arm \ @@ -66,6 +40,7 @@ LOCAL_SHARED_LIBRARIES := \ libbinder \ libmedia \ libmedia_native \ + libnbaio \ libhardware \ libhardware_legacy \ libeffects \ @@ -74,7 +49,6 @@ LOCAL_SHARED_LIBRARIES := \ LOCAL_STATIC_LIBRARIES := \ libscheduling_policy \ - libnbaio \ libcpustats \ libmedia_helper diff --git a/services/audioflinger/AudioBufferProvider.h b/services/audioflinger/AudioBufferProvider.h deleted file mode 100644 index 43e4de7..0000000 --- a/services/audioflinger/AudioBufferProvider.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2007 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. - */ - -#ifndef ANDROID_AUDIO_BUFFER_PROVIDER_H -#define ANDROID_AUDIO_BUFFER_PROVIDER_H - -#include - -namespace android { -// ---------------------------------------------------------------------------- - -class AudioBufferProvider -{ -public: - - struct Buffer { - Buffer() : raw(NULL), frameCount(0) { } - union { - void* raw; - short* i16; - int8_t* i8; - }; - size_t frameCount; - }; - - virtual ~AudioBufferProvider() {} - - // value representing an invalid presentation timestamp - static const int64_t kInvalidPTS = 0x7FFFFFFFFFFFFFFFLL; // is too painful - - // pts is the local time when the next sample yielded by getNextBuffer - // will be rendered. - // Pass kInvalidPTS if the PTS is unknown or not applicable. - virtual status_t getNextBuffer(Buffer* buffer, int64_t pts = kInvalidPTS) = 0; - - virtual void releaseBuffer(Buffer* buffer) = 0; -}; - -// ---------------------------------------------------------------------------- -}; // namespace android - -#endif // ANDROID_AUDIO_BUFFER_PROVIDER_H diff --git a/services/audioflinger/AudioBufferProviderSource.cpp b/services/audioflinger/AudioBufferProviderSource.cpp deleted file mode 100644 index 613e924..0000000 --- a/services/audioflinger/AudioBufferProviderSource.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2012 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 "AudioBufferProviderSource" -//#define LOG_NDEBUG 0 - -#include -#include -#include "AudioBufferProviderSource.h" - -namespace android { - -AudioBufferProviderSource::AudioBufferProviderSource(AudioBufferProvider *provider, - NBAIO_Format format) : - NBAIO_Source(format), mProvider(provider), mConsumed(0) -{ - ALOG_ASSERT(provider != NULL); - ALOG_ASSERT(format != Format_Invalid); -} - -AudioBufferProviderSource::~AudioBufferProviderSource() -{ - if (mBuffer.raw != NULL) { - mProvider->releaseBuffer(&mBuffer); - } -} - -ssize_t AudioBufferProviderSource::availableToRead() -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - return mBuffer.raw != NULL ? mBuffer.frameCount - mConsumed : 0; -} - -ssize_t AudioBufferProviderSource::read(void *buffer, - size_t count, - int64_t readPTS) -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - if (CC_UNLIKELY(mBuffer.raw == NULL)) { - mBuffer.frameCount = count; - status_t status = mProvider->getNextBuffer(&mBuffer, readPTS); - if (status != OK) { - return status == NOT_ENOUGH_DATA ? (ssize_t) WOULD_BLOCK : (ssize_t) status; - } - ALOG_ASSERT(mBuffer.raw != NULL); - // mConsumed is 0 either from constructor or after releaseBuffer() - } - size_t available = mBuffer.frameCount - mConsumed; - if (CC_UNLIKELY(count > available)) { - count = available; - } - // count could be zero, either because count was zero on entry or - // available is zero, but both are unlikely so don't check for that - memcpy(buffer, (char *) mBuffer.raw + (mConsumed << mBitShift), count << mBitShift); - if (CC_UNLIKELY((mConsumed += count) >= mBuffer.frameCount)) { - mProvider->releaseBuffer(&mBuffer); - mBuffer.raw = NULL; - mConsumed = 0; - } - mFramesRead += count; - // For better responsiveness with large values of count, - // return a short count rather than continuing with next buffer. - // This gives the caller a chance to interpolate other actions. - return count; -} - -ssize_t AudioBufferProviderSource::readVia(readVia_t via, size_t total, void *user, - int64_t readPTS, size_t block) -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - if (CC_UNLIKELY(block == 0)) { - block = ~0; - } - for (size_t accumulator = 0; ; ) { - ALOG_ASSERT(accumulator <= total); - size_t count = total - accumulator; - if (CC_UNLIKELY(count == 0)) { - return accumulator; - } - if (CC_LIKELY(count > block)) { - count = block; - } - // 1 <= count <= block - if (CC_UNLIKELY(mBuffer.raw == NULL)) { - mBuffer.frameCount = count; - status_t status = mProvider->getNextBuffer(&mBuffer, readPTS); - if (CC_LIKELY(status == OK)) { - ALOG_ASSERT(mBuffer.raw != NULL && mBuffer.frameCount <= count); - // mConsumed is 0 either from constructor or after releaseBuffer() - continue; - } - // FIXME simplify logic - does the initial count and block checks again for no reason; - // don't you just want to fall through to the size_t available line? - if (CC_LIKELY(status == NOT_ENOUGH_DATA)) { - status = WOULD_BLOCK; - } - return accumulator > 0 ? accumulator : (ssize_t) status; - } - size_t available = mBuffer.frameCount - mConsumed; - if (CC_UNLIKELY(count > available)) { - count = available; - } - if (CC_LIKELY(count > 0)) { - char* readTgt = (char *) mBuffer.raw + (mConsumed << mBitShift); - ssize_t ret = via(user, readTgt, count, readPTS); - if (CC_UNLIKELY(ret <= 0)) { - if (CC_LIKELY(accumulator > 0)) { - return accumulator; - } - return ret; - } - ALOG_ASSERT((size_t) ret <= count); - mFramesRead += ret; - accumulator += ret; - if (CC_LIKELY((mConsumed += ret) < mBuffer.frameCount)) { - continue; - } - } - mProvider->releaseBuffer(&mBuffer); - mBuffer.raw = NULL; - mConsumed = 0; - // don't get next buffer until we really need it - } -} - -} // namespace android diff --git a/services/audioflinger/AudioBufferProviderSource.h b/services/audioflinger/AudioBufferProviderSource.h deleted file mode 100644 index 1435a84..0000000 --- a/services/audioflinger/AudioBufferProviderSource.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -// Implementation of NBAIO_Source that wraps an AudioBufferProvider - -#ifndef ANDROID_AUDIO_BUFFER_PROVIDER_SOURCE_H -#define ANDROID_AUDIO_BUFFER_PROVIDER_SOURCE_H - -#include "NBAIO.h" -#include "AudioBufferProvider.h" - -namespace android { - -class AudioBufferProviderSource : public NBAIO_Source { - -public: - AudioBufferProviderSource(AudioBufferProvider *provider, NBAIO_Format format); - virtual ~AudioBufferProviderSource(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format(); - - // NBAIO_Source interface - - //virtual size_t framesRead() const; - //virtual size_t framesOverrun(); - //virtual size_t overruns(); - virtual ssize_t availableToRead(); - virtual ssize_t read(void *buffer, size_t count, int64_t readPTS); - virtual ssize_t readVia(readVia_t via, size_t total, void *user, - int64_t readPTS, size_t block); - -private: - AudioBufferProvider * const mProvider; - AudioBufferProvider::Buffer mBuffer; // current buffer - size_t mConsumed; // number of frames consumed so far from current buffer -}; - -} // namespace android - -#endif // ANDROID_AUDIO_BUFFER_PROVIDER_SOURCE_H diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 7126006..8acd244 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -76,12 +76,12 @@ #include "FastMixer.h" // NBAIO implementations -#include "AudioStreamOutSink.h" -#include "MonoPipe.h" -#include "MonoPipeReader.h" -#include "Pipe.h" -#include "PipeReader.h" -#include "SourceAudioBufferProvider.h" +#include +#include +#include +#include +#include +#include #include "SchedulingPolicyService.h" diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index 682d61d..b4aefc1 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -45,10 +45,10 @@ #include #include -#include "AudioBufferProvider.h" -#include "ExtendedAudioBufferProvider.h" +#include +#include #include "FastMixer.h" -#include "NBAIO.h" +#include #include "AudioWatchdog.h" #include diff --git a/services/audioflinger/AudioMixer.h b/services/audioflinger/AudioMixer.h index 46deae7..6e34cd1 100644 --- a/services/audioflinger/AudioMixer.h +++ b/services/audioflinger/AudioMixer.h @@ -23,7 +23,7 @@ #include -#include "AudioBufferProvider.h" +#include #include "AudioResampler.h" #include diff --git a/services/audioflinger/AudioResampler.h b/services/audioflinger/AudioResampler.h index 1610e00..dc696d8 100644 --- a/services/audioflinger/AudioResampler.h +++ b/services/audioflinger/AudioResampler.h @@ -20,7 +20,7 @@ #include #include -#include "AudioBufferProvider.h" +#include namespace android { // ---------------------------------------------------------------------------- diff --git a/services/audioflinger/AudioStreamInSource.cpp b/services/audioflinger/AudioStreamInSource.cpp deleted file mode 100644 index 8b4bebf..0000000 --- a/services/audioflinger/AudioStreamInSource.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2012 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 "AudioStreamInSource" -//#define LOG_NDEBUG 0 - -#include -#include -#include "AudioStreamInSource.h" - -namespace android { - -AudioStreamInSource::AudioStreamInSource(audio_stream_in *stream) : - NBAIO_Source(), - mStream(stream), - mStreamBufferSizeBytes(0), - mFramesOverrun(0), - mOverruns(0) -{ - ALOG_ASSERT(stream != NULL); -} - -AudioStreamInSource::~AudioStreamInSource() -{ -} - -ssize_t AudioStreamInSource::negotiate(const NBAIO_Format offers[], size_t numOffers, - NBAIO_Format counterOffers[], size_t& numCounterOffers) -{ - if (mFormat == Format_Invalid) { - mStreamBufferSizeBytes = mStream->common.get_buffer_size(&mStream->common); - audio_format_t streamFormat = mStream->common.get_format(&mStream->common); - if (streamFormat == AUDIO_FORMAT_PCM_16_BIT) { - uint32_t sampleRate = mStream->common.get_sample_rate(&mStream->common); - audio_channel_mask_t channelMask = - (audio_channel_mask_t) mStream->common.get_channels(&mStream->common); - mFormat = Format_from_SR_C(sampleRate, popcount(channelMask)); - mBitShift = Format_frameBitShift(mFormat); - } - } - return NBAIO_Source::negotiate(offers, numOffers, counterOffers, numCounterOffers); -} - -size_t AudioStreamInSource::framesOverrun() -{ - uint32_t framesOverrun = mStream->get_input_frames_lost(mStream); - if (framesOverrun > 0) { - mFramesOverrun += framesOverrun; - // FIXME only increment for contiguous ranges - ++mOverruns; - } - return mFramesOverrun; -} - -ssize_t AudioStreamInSource::read(void *buffer, size_t count) -{ - if (CC_UNLIKELY(mFormat == Format_Invalid)) { - return NEGOTIATE; - } - ssize_t bytesRead = mStream->read(mStream, buffer, count << mBitShift); - if (bytesRead > 0) { - size_t framesRead = bytesRead >> mBitShift; - mFramesRead += framesRead; - return framesRead; - } else { - return bytesRead; - } -} - -} // namespace android diff --git a/services/audioflinger/AudioStreamInSource.h b/services/audioflinger/AudioStreamInSource.h deleted file mode 100644 index 07d8c89..0000000 --- a/services/audioflinger/AudioStreamInSource.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_STREAM_IN_SOURCE_H -#define ANDROID_AUDIO_STREAM_IN_SOURCE_H - -#include -#include "NBAIO.h" - -namespace android { - -// not multi-thread safe -class AudioStreamInSource : public NBAIO_Source { - -public: - AudioStreamInSource(audio_stream_in *stream); - virtual ~AudioStreamInSource(); - - // NBAIO_Port interface - - virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Sink interface - - //virtual size_t framesRead() const; - virtual size_t framesOverrun(); - virtual size_t overruns() { (void) framesOverrun(); return mOverruns; } - - // This is an over-estimate, and could dupe the caller into making a blocking read() - // FIXME Use an audio HAL API to query the buffer filling status when it's available. - virtual ssize_t availableToRead() { return mStreamBufferSizeBytes >> mBitShift; } - - virtual ssize_t read(void *buffer, size_t count); - - // NBAIO_Sink end - -#if 0 // until necessary - audio_stream_in *stream() const { return mStream; } -#endif - -private: - audio_stream_in * const mStream; - size_t mStreamBufferSizeBytes; // as reported by get_buffer_size() - size_t mFramesOverrun; - size_t mOverruns; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_STREAM_IN_SOURCE_H diff --git a/services/audioflinger/AudioStreamOutSink.cpp b/services/audioflinger/AudioStreamOutSink.cpp deleted file mode 100644 index bc2d15b..0000000 --- a/services/audioflinger/AudioStreamOutSink.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2012 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 "AudioStreamOutSink" -//#define LOG_NDEBUG 0 - -#include -#include "AudioStreamOutSink.h" - -namespace android { - -AudioStreamOutSink::AudioStreamOutSink(audio_stream_out *stream) : - NBAIO_Sink(), - mStream(stream), - mStreamBufferSizeBytes(0) -{ - ALOG_ASSERT(stream != NULL); -} - -AudioStreamOutSink::~AudioStreamOutSink() -{ -} - -ssize_t AudioStreamOutSink::negotiate(const NBAIO_Format offers[], size_t numOffers, - NBAIO_Format counterOffers[], size_t& numCounterOffers) -{ - if (mFormat == Format_Invalid) { - mStreamBufferSizeBytes = mStream->common.get_buffer_size(&mStream->common); - audio_format_t streamFormat = mStream->common.get_format(&mStream->common); - if (streamFormat == AUDIO_FORMAT_PCM_16_BIT) { - uint32_t sampleRate = mStream->common.get_sample_rate(&mStream->common); - audio_channel_mask_t channelMask = - (audio_channel_mask_t) mStream->common.get_channels(&mStream->common); - mFormat = Format_from_SR_C(sampleRate, popcount(channelMask)); - mBitShift = Format_frameBitShift(mFormat); - } - } - return NBAIO_Sink::negotiate(offers, numOffers, counterOffers, numCounterOffers); -} - -ssize_t AudioStreamOutSink::write(const void *buffer, size_t count) -{ - if (!mNegotiated) { - return NEGOTIATE; - } - ALOG_ASSERT(mFormat != Format_Invalid); - ssize_t ret = mStream->write(mStream, buffer, count << mBitShift); - if (ret > 0) { - ret >>= mBitShift; - mFramesWritten += ret; - } else { - // FIXME verify HAL implementations are returning the correct error codes e.g. WOULD_BLOCK - } - return ret; -} - -status_t AudioStreamOutSink::getNextWriteTimestamp(int64_t *timestamp) { - ALOG_ASSERT(timestamp != NULL); - - if (NULL == mStream) - return INVALID_OPERATION; - - if (NULL == mStream->get_next_write_timestamp) - return INVALID_OPERATION; - - return mStream->get_next_write_timestamp(mStream, timestamp); -} - -} // namespace android diff --git a/services/audioflinger/AudioStreamOutSink.h b/services/audioflinger/AudioStreamOutSink.h deleted file mode 100644 index 5976b18..0000000 --- a/services/audioflinger/AudioStreamOutSink.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_STREAM_OUT_SINK_H -#define ANDROID_AUDIO_STREAM_OUT_SINK_H - -#include -#include "NBAIO.h" - -namespace android { - -// not multi-thread safe -class AudioStreamOutSink : public NBAIO_Sink { - -public: - AudioStreamOutSink(audio_stream_out *stream); - virtual ~AudioStreamOutSink(); - - // NBAIO_Port interface - - virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format(); - - // NBAIO_Sink interface - - //virtual size_t framesWritten() const; - //virtual size_t framesUnderrun() const; - //virtual size_t underruns() const; - - // This is an over-estimate, and could dupe the caller into making a blocking write() - // FIXME Use an audio HAL API to query the buffer emptying status when it's available. - virtual ssize_t availableToWrite() const { return mStreamBufferSizeBytes >> mBitShift; } - - virtual ssize_t write(const void *buffer, size_t count); - - // AudioStreamOutSink wraps a HAL's output stream. Its - // getNextWriteTimestamp method is simply a passthru to the HAL's underlying - // implementation of GNWT (if any) - virtual status_t getNextWriteTimestamp(int64_t *timestamp); - - // NBAIO_Sink end - -#if 0 // until necessary - audio_stream_out *stream() const { return mStream; } -#endif - -private: - audio_stream_out * const mStream; - size_t mStreamBufferSizeBytes; // as reported by get_buffer_size() -}; - -} // namespace android - -#endif // ANDROID_AUDIO_STREAM_OUT_SINK_H diff --git a/services/audioflinger/ExtendedAudioBufferProvider.h b/services/audioflinger/ExtendedAudioBufferProvider.h deleted file mode 100644 index 88279b4..0000000 --- a/services/audioflinger/ExtendedAudioBufferProvider.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_EXTENDED_AUDIO_BUFFER_PROVIDER_H -#define ANDROID_EXTENDED_AUDIO_BUFFER_PROVIDER_H - -#include "AudioBufferProvider.h" - -namespace android { - -class ExtendedAudioBufferProvider : public AudioBufferProvider { -public: - virtual size_t framesReady() const = 0; // see description at AudioFlinger.h -}; - -} // namespace android - -#endif // ANDROID_EXTENDED_AUDIO_BUFFER_PROVIDER_H diff --git a/services/audioflinger/FastMixerState.h b/services/audioflinger/FastMixerState.h index bc69c9c..6e53f21 100644 --- a/services/audioflinger/FastMixerState.h +++ b/services/audioflinger/FastMixerState.h @@ -18,8 +18,8 @@ #define ANDROID_AUDIO_FAST_MIXER_STATE_H #include -#include "ExtendedAudioBufferProvider.h" -#include "NBAIO.h" +#include +#include namespace android { diff --git a/services/audioflinger/LibsndfileSink.cpp b/services/audioflinger/LibsndfileSink.cpp deleted file mode 100644 index efc1c8f..0000000 --- a/services/audioflinger/LibsndfileSink.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012 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 "LibsndfileSink" -//#define LOG_NDEBUG 0 - -#include -#include -#include "LibsndfileSink.h" - -namespace android { - -LibsndfileSink::LibsndfileSink(SNDFILE *sndfile, const SF_INFO &sfinfo) : - NBAIO_Sink(Format_from_SR_C(sfinfo.samplerate, sfinfo.channels)), - mSndfile(sndfile) -{ -} - -LibsndfileSink::~LibsndfileSink() -{ - // do not close mSndfile; we don't own it -} - -ssize_t LibsndfileSink::write(const void *buffer, size_t count) -{ - if (!mNegotiated) { - return (ssize_t) NEGOTIATE; - } - if (mSndfile == NULL) { - return (ssize_t) NO_INIT; - } - sf_count_t actual = sf_writef_short(mSndfile, (short *) buffer, (sf_count_t) count); - mFramesWritten += actual; - return actual; -} - -} // namespace android diff --git a/services/audioflinger/LibsndfileSink.h b/services/audioflinger/LibsndfileSink.h deleted file mode 100644 index f5d53d5..0000000 --- a/services/audioflinger/LibsndfileSink.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_LIBSNDFILE_SINK_H -#define ANDROID_AUDIO_LIBSNDFILE_SINK_H - -#include "NBAIO.h" -#include "sndfile.h" - -// Implementation of NBAIO_Sink that wraps a libsndfile opened in SFM_WRITE mode - -namespace android { - -class LibsndfileSink : public NBAIO_Sink { - -public: - LibsndfileSink(SNDFILE *sndfile, const SF_INFO &sfinfo); - virtual ~LibsndfileSink(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Sink interface - - //virtual size_t framesWritten() const; - //virtual size_t framesUnderrun() const; - //virtual size_t underruns() const; - //virtual ssize_t availableToWrite() const; - virtual ssize_t write(const void *buffer, size_t count); - //virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block); - -private: - SNDFILE * mSndfile; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_LIBSNDFILE_SINK_H diff --git a/services/audioflinger/LibsndfileSource.cpp b/services/audioflinger/LibsndfileSource.cpp deleted file mode 100644 index 28317d6..0000000 --- a/services/audioflinger/LibsndfileSource.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2012 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 "LibsndfileSource" -//#define LOG_NDEBUG 0 - -#include -#include -#include "LibsndfileSource.h" - -namespace android { - -LibsndfileSource::LibsndfileSource(SNDFILE *sndfile, const SF_INFO &sfinfo, bool loop) : - NBAIO_Source(Format_from_SR_C(sfinfo.samplerate, sfinfo.channels)), - mSndfile(sndfile), - mEstimatedFramesUntilEOF(sfinfo.frames), - mLooping(loop && sfinfo.seekable), - mReadAnyFramesThisLoopCycle(false) -{ -} - -LibsndfileSource::~LibsndfileSource() -{ - // do not close mSndfile; we don't own it -} - -ssize_t LibsndfileSource::availableToRead() -{ - // after we reach the presumed EOF, report infinity just in case there's actually more - return !mLooping && mEstimatedFramesUntilEOF > 0 ? mEstimatedFramesUntilEOF : SSIZE_MAX; -} - -ssize_t LibsndfileSource::read(void *buffer, size_t count) -{ - if (!mNegotiated) { - return (ssize_t) NEGOTIATE; - } - if (mSndfile == NULL) { - return (ssize_t) NO_INIT; - } - sf_count_t actual = sf_readf_short(mSndfile, (short *) buffer, (sf_count_t) count); - // Detect EOF by zero frames read, not by mFramesUntilEOF as it could be inaccurate - if (actual == 0) { - if (mLooping) { - if (mReadAnyFramesThisLoopCycle) { - (void) sf_seek(mSndfile, (sf_count_t) 0, SEEK_SET); - mReadAnyFramesThisLoopCycle = false; - } else { - // We didn't read any frames during the current loop cycle, so disable - // further looping to prevent the caller from busy waiting at read(). - // This is especially important when looping an empty file. - mLooping = false; - } - } - } else { - mFramesRead += actual; - if (actual >= mEstimatedFramesUntilEOF) { - mEstimatedFramesUntilEOF = 0; - } else { - mEstimatedFramesUntilEOF -= actual; - } - mReadAnyFramesThisLoopCycle = true; - } - return actual; -} - -} // namespace android diff --git a/services/audioflinger/LibsndfileSource.h b/services/audioflinger/LibsndfileSource.h deleted file mode 100644 index 4fbdb4b..0000000 --- a/services/audioflinger/LibsndfileSource.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_LIBSNDFILE_SOURCE_H -#define ANDROID_AUDIO_LIBSNDFILE_SOURCE_H - -#include "NBAIO.h" -#include "sndfile.h" - -// Implementation of NBAIO_Source that wraps a libsndfile opened in SFM_READ mode - -namespace android { - -class LibsndfileSource : public NBAIO_Source { - -public: - // If 'loop' is true and it permits seeking, then we'll act as an infinite source - LibsndfileSource(SNDFILE *sndfile, const SF_INFO &sfinfo, bool loop = false); - virtual ~LibsndfileSource(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Source interface - - //virtual size_t framesRead() const; - //virtual size_t framesOverrun(); - //virtual size_t overruns(); - virtual ssize_t availableToRead(); - virtual ssize_t read(void *buffer, size_t count); - //virtual ssize_t readVia(readVia_t via, size_t total, void *user, size_t block); - -private: - SNDFILE * mSndfile; - sf_count_t mEstimatedFramesUntilEOF; - bool mLooping; - bool mReadAnyFramesThisLoopCycle; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_LIBSNDFILE_SOURCE_H diff --git a/services/audioflinger/MonoPipe.cpp b/services/audioflinger/MonoPipe.cpp deleted file mode 100644 index bd876b4..0000000 --- a/services/audioflinger/MonoPipe.cpp +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (C) 2012 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 "MonoPipe" -//#define LOG_NDEBUG 0 - -#include -#include -#include -#include -#include -#include -#include "AudioBufferProvider.h" -#include "MonoPipe.h" -#include "roundup.h" - - -namespace android { - -MonoPipe::MonoPipe(size_t reqFrames, NBAIO_Format format, bool writeCanBlock) : - NBAIO_Sink(format), - mUpdateSeq(0), - mReqFrames(reqFrames), - mMaxFrames(roundup(reqFrames)), - mBuffer(malloc(mMaxFrames * Format_frameSize(format))), - mFront(0), - mRear(0), - mWriteTsValid(false), - // mWriteTs - mSetpoint((reqFrames * 11) / 16), - mWriteCanBlock(writeCanBlock) -{ - CCHelper tmpHelper; - status_t res; - uint64_t N, D; - - mNextRdPTS = AudioBufferProvider::kInvalidPTS; - - mSamplesToLocalTime.a_zero = 0; - mSamplesToLocalTime.b_zero = 0; - mSamplesToLocalTime.a_to_b_numer = 0; - mSamplesToLocalTime.a_to_b_denom = 0; - - D = Format_sampleRate(format); - if (OK != (res = tmpHelper.getLocalFreq(&N))) { - ALOGE("Failed to fetch local time frequency when constructing a" - " MonoPipe (res = %d). getNextWriteTimestamp calls will be" - " non-functional", res); - return; - } - - LinearTransform::reduce(&N, &D); - static const uint64_t kSignedHiBitsMask = ~(0x7FFFFFFFull); - static const uint64_t kUnsignedHiBitsMask = ~(0xFFFFFFFFull); - if ((N & kSignedHiBitsMask) || (D & kUnsignedHiBitsMask)) { - ALOGE("Cannot reduce sample rate to local clock frequency ratio to fit" - " in a 32/32 bit rational. (max reduction is 0x%016llx/0x%016llx" - "). getNextWriteTimestamp calls will be non-functional", N, D); - return; - } - - mSamplesToLocalTime.a_to_b_numer = static_cast(N); - mSamplesToLocalTime.a_to_b_denom = static_cast(D); -} - -MonoPipe::~MonoPipe() -{ - free(mBuffer); -} - -ssize_t MonoPipe::availableToWrite() const -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - // uses mMaxFrames not mReqFrames, so allows "over-filling" the pipe beyond requested limit - ssize_t ret = mMaxFrames - (mRear - android_atomic_acquire_load(&mFront)); - ALOG_ASSERT((0 <= ret) && (ret <= mMaxFrames)); - return ret; -} - -ssize_t MonoPipe::write(const void *buffer, size_t count) -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - size_t totalFramesWritten = 0; - while (count > 0) { - // can't return a negative value, as we already checked for !mNegotiated - size_t avail = availableToWrite(); - size_t written = avail; - if (CC_LIKELY(written > count)) { - written = count; - } - size_t rear = mRear & (mMaxFrames - 1); - size_t part1 = mMaxFrames - rear; - if (part1 > written) { - part1 = written; - } - if (CC_LIKELY(part1 > 0)) { - memcpy((char *) mBuffer + (rear << mBitShift), buffer, part1 << mBitShift); - if (CC_UNLIKELY(rear + part1 == mMaxFrames)) { - size_t part2 = written - part1; - if (CC_LIKELY(part2 > 0)) { - memcpy(mBuffer, (char *) buffer + (part1 << mBitShift), part2 << mBitShift); - } - } - android_atomic_release_store(written + mRear, &mRear); - totalFramesWritten += written; - } - if (!mWriteCanBlock) { - break; - } - count -= written; - buffer = (char *) buffer + (written << mBitShift); - // Simulate blocking I/O by sleeping at different rates, depending on a throttle. - // The throttle tries to keep the mean pipe depth near the setpoint, with a slight jitter. - uint32_t ns; - if (written > 0) { - size_t filled = (mMaxFrames - avail) + written; - // FIXME cache these values to avoid re-computation - if (filled <= mSetpoint / 2) { - // pipe is (nearly) empty, fill quickly - ns = written * ( 500000000 / Format_sampleRate(mFormat)); - } else if (filled <= (mSetpoint * 3) / 4) { - // pipe is below setpoint, fill at slightly faster rate - ns = written * ( 750000000 / Format_sampleRate(mFormat)); - } else if (filled <= (mSetpoint * 5) / 4) { - // pipe is at setpoint, fill at nominal rate - ns = written * (1000000000 / Format_sampleRate(mFormat)); - } else if (filled <= (mSetpoint * 3) / 2) { - // pipe is above setpoint, fill at slightly slower rate - ns = written * (1150000000 / Format_sampleRate(mFormat)); - } else if (filled <= (mSetpoint * 7) / 4) { - // pipe is overflowing, fill slowly - ns = written * (1350000000 / Format_sampleRate(mFormat)); - } else { - // pipe is severely overflowing - ns = written * (1750000000 / Format_sampleRate(mFormat)); - } - } else { - ns = count * (1350000000 / Format_sampleRate(mFormat)); - } - if (ns > 999999999) { - ns = 999999999; - } - struct timespec nowTs; - bool nowTsValid = !clock_gettime(CLOCK_MONOTONIC, &nowTs); - // deduct the elapsed time since previous write() completed - if (nowTsValid && mWriteTsValid) { - time_t sec = nowTs.tv_sec - mWriteTs.tv_sec; - long nsec = nowTs.tv_nsec - mWriteTs.tv_nsec; - if (nsec < 0) { - --sec; - nsec += 1000000000; - } - if (sec == 0) { - if ((long) ns > nsec) { - ns -= nsec; - } else { - ns = 0; - } - } - } - if (ns > 0) { - const struct timespec req = {0, ns}; - nanosleep(&req, NULL); - } - // record the time that this write() completed - if (nowTsValid) { - mWriteTs = nowTs; - if ((mWriteTs.tv_nsec += ns) >= 1000000000) { - mWriteTs.tv_nsec -= 1000000000; - ++mWriteTs.tv_sec; - } - } - mWriteTsValid = nowTsValid; - } - mFramesWritten += totalFramesWritten; - return totalFramesWritten; -} - -void MonoPipe::setAvgFrames(size_t setpoint) -{ - mSetpoint = setpoint; -} - -status_t MonoPipe::getNextWriteTimestamp(int64_t *timestamp) -{ - int32_t front; - - ALOG_ASSERT(NULL != timestamp); - - if (0 == mSamplesToLocalTime.a_to_b_denom) - return UNKNOWN_ERROR; - - observeFrontAndNRPTS(&front, timestamp); - - if (AudioBufferProvider::kInvalidPTS != *timestamp) { - // If we have a valid read-pointer and next read timestamp pair, then - // use the current value of the write pointer to figure out how many - // frames are in the buffer, and offset the timestamp by that amt. Then - // next time we write to the MonoPipe, the data will hit the speakers at - // the next read timestamp plus the current amount of data in the - // MonoPipe. - size_t pendingFrames = (mRear - front) & (mMaxFrames - 1); - *timestamp = offsetTimestampByAudioFrames(*timestamp, pendingFrames); - } - - return OK; -} - -void MonoPipe::updateFrontAndNRPTS(int32_t newFront, int64_t newNextRdPTS) -{ - // Set the MSB of the update sequence number to indicate that there is a - // multi-variable update in progress. Use an atomic store with an "acquire" - // barrier to make sure that the next operations cannot be re-ordered and - // take place before the change to mUpdateSeq is commited.. - int32_t tmp = mUpdateSeq | 0x80000000; - android_atomic_acquire_store(tmp, &mUpdateSeq); - - // Update mFront and mNextRdPTS - mFront = newFront; - mNextRdPTS = newNextRdPTS; - - // We are finished with the update. Compute the next sequnce number (which - // should be the old sequence number, plus one, and with the MSB cleared) - // and then store it in mUpdateSeq using an atomic store with a "release" - // barrier so our update operations cannot be re-ordered past the update of - // the sequence number. - tmp = (tmp + 1) & 0x7FFFFFFF; - android_atomic_release_store(tmp, &mUpdateSeq); -} - -void MonoPipe::observeFrontAndNRPTS(int32_t *outFront, int64_t *outNextRdPTS) -{ - // Perform an atomic observation of mFront and mNextRdPTS. Basically, - // atomically observe the sequence number, then observer the variables, then - // atomically observe the sequence number again. If the two observations of - // the sequence number match, and the update-in-progress bit was not set, - // then we know we have a successful atomic observation. Otherwise, we loop - // around and try again. - // - // Note, it is very important that the observer be a lower priority thread - // than the updater. If the updater is lower than the observer, or they are - // the same priority and running with SCHED_FIFO (implying that quantum - // based premption is disabled) then we run the risk of deadlock. - int32_t seqOne, seqTwo; - - do { - seqOne = android_atomic_acquire_load(&mUpdateSeq); - *outFront = mFront; - *outNextRdPTS = mNextRdPTS; - seqTwo = android_atomic_release_load(&mUpdateSeq); - } while ((seqOne != seqTwo) || (seqOne & 0x80000000)); -} - -int64_t MonoPipe::offsetTimestampByAudioFrames(int64_t ts, size_t audFrames) -{ - if (0 == mSamplesToLocalTime.a_to_b_denom) - return AudioBufferProvider::kInvalidPTS; - - if (ts == AudioBufferProvider::kInvalidPTS) - return AudioBufferProvider::kInvalidPTS; - - int64_t frame_lt_duration; - if (!mSamplesToLocalTime.doForwardTransform(audFrames, - &frame_lt_duration)) { - // This should never fail, but if there is a bug which is causing it - // to fail, this message would probably end up flooding the logs - // because the conversion would probably fail forever. Log the - // error, but then zero out the ratio in the linear transform so - // that we don't try to do any conversions from now on. This - // MonoPipe's getNextWriteTimestamp is now broken for good. - ALOGE("Overflow when attempting to convert %d audio frames to" - " duration in local time. getNextWriteTimestamp will fail from" - " now on.", audFrames); - mSamplesToLocalTime.a_to_b_numer = 0; - mSamplesToLocalTime.a_to_b_denom = 0; - return AudioBufferProvider::kInvalidPTS; - } - - return ts + frame_lt_duration; -} - -} // namespace android diff --git a/services/audioflinger/MonoPipe.h b/services/audioflinger/MonoPipe.h deleted file mode 100644 index c47bf6c..0000000 --- a/services/audioflinger/MonoPipe.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_MONO_PIPE_H -#define ANDROID_AUDIO_MONO_PIPE_H - -#include -#include -#include "NBAIO.h" - -namespace android { - -// MonoPipe is similar to Pipe except: -// - supports only a single reader, called MonoPipeReader -// - write() cannot overrun; instead it will return a short actual count if insufficient space -// - write() can optionally block if the pipe is full -// Like Pipe, it is not multi-thread safe for either writer or reader -// but writer and reader can be different threads. -class MonoPipe : public NBAIO_Sink { - - friend class MonoPipeReader; - -public: - // reqFrames will be rounded up to a power of 2, and all slots are available. Must be >= 2. - // Note: whatever shares this object with another thread needs to do so in an SMP-safe way (like - // creating it the object before creating the other thread, or storing the object with a - // release_store). Otherwise the other thread could see a partially-constructed object. - MonoPipe(size_t reqFrames, NBAIO_Format format, bool writeCanBlock = false); - virtual ~MonoPipe(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Sink interface - - //virtual size_t framesWritten() const; - //virtual size_t framesUnderrun() const; - //virtual size_t underruns() const; - - virtual ssize_t availableToWrite() const; - virtual ssize_t write(const void *buffer, size_t count); - //virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block); - - // MonoPipe's implementation of getNextWriteTimestamp works in conjunction - // with MonoPipeReader. Every time a MonoPipeReader reads from the pipe, it - // receives a "readPTS" indicating the point in time for which the reader - // would like to read data. This "last read PTS" is offset by the amt of - // data the reader is currently mixing and then cached cached along with the - // updated read pointer. This cached value is the local time for which the - // reader is going to request data next time it reads data (assuming we are - // in steady state and operating with no underflows). Writers to the - // MonoPipe who would like to know when their next write operation will hit - // the speakers can call getNextWriteTimestamp which will return the value - // of the last read PTS plus the duration of the amt of data waiting to be - // read in the MonoPipe. - virtual status_t getNextWriteTimestamp(int64_t *timestamp); - - // average number of frames present in the pipe under normal conditions. - // See throttling mechanism in MonoPipe::write() - size_t getAvgFrames() const { return mSetpoint; } - void setAvgFrames(size_t setpoint); - size_t maxFrames() const { return mMaxFrames; } - -private: - // A pair of methods and a helper variable which allows the reader and the - // writer to update and observe the values of mFront and mNextRdPTS in an - // atomic lock-less fashion. - // - // :: Important :: - // Two assumptions must be true in order for this lock-less approach to - // function properly on all systems. First, there may only be one updater - // thread in the system. Second, the updater thread must be running at a - // strictly higher priority than the observer threads. Currently, both of - // these assumptions are true. The only updater is always a single - // FastMixer thread (which runs with SCHED_FIFO/RT priority while the only - // observer is always an AudioFlinger::PlaybackThread running with - // traditional (non-RT) audio priority. - void updateFrontAndNRPTS(int32_t newFront, int64_t newNextRdPTS); - void observeFrontAndNRPTS(int32_t *outFront, int64_t *outNextRdPTS); - volatile int32_t mUpdateSeq; - - const size_t mReqFrames; // as requested in constructor, unrounded - const size_t mMaxFrames; // always a power of 2 - void * const mBuffer; - // mFront and mRear will never be separated by more than mMaxFrames. - // 32-bit overflow is possible if the pipe is active for a long time, but if that happens it's - // safe because we "&" with (mMaxFrames-1) at end of computations to calculate a buffer index. - volatile int32_t mFront; // written by the reader with updateFrontAndNRPTS, observed by - // the writer with observeFrontAndNRPTS - volatile int32_t mRear; // written by writer with android_atomic_release_store, - // read by reader with android_atomic_acquire_load - volatile int64_t mNextRdPTS; // written by the reader with updateFrontAndNRPTS, observed by - // the writer with observeFrontAndNRPTS - bool mWriteTsValid; // whether mWriteTs is valid - struct timespec mWriteTs; // time that the previous write() completed - size_t mSetpoint; // target value for pipe fill depth - const bool mWriteCanBlock; // whether write() should block if the pipe is full - - int64_t offsetTimestampByAudioFrames(int64_t ts, size_t audFrames); - LinearTransform mSamplesToLocalTime; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_MONO_PIPE_H diff --git a/services/audioflinger/MonoPipeReader.cpp b/services/audioflinger/MonoPipeReader.cpp deleted file mode 100644 index 39a07de..0000000 --- a/services/audioflinger/MonoPipeReader.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2012 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 "MonoPipeReader" -//#define LOG_NDEBUG 0 - -#include -#include -#include "MonoPipeReader.h" - -namespace android { - -MonoPipeReader::MonoPipeReader(MonoPipe* pipe) : - NBAIO_Source(pipe->mFormat), - mPipe(pipe) -{ -} - -MonoPipeReader::~MonoPipeReader() -{ -} - -ssize_t MonoPipeReader::availableToRead() -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - ssize_t ret = android_atomic_acquire_load(&mPipe->mRear) - mPipe->mFront; - ALOG_ASSERT((0 <= ret) && (ret <= mMaxFrames)); - return ret; -} - -ssize_t MonoPipeReader::read(void *buffer, size_t count, int64_t readPTS) -{ - // Compute the "next read PTS" and cache it. Callers of read pass a read - // PTS indicating the local time for which they are requesting data along - // with a count (which is the number of audio frames they are going to - // ultimately pass to the next stage of the pipeline). Offsetting readPTS - // by the duration of count will give us the readPTS which will be passed to - // us next time, assuming they system continues to operate in steady state - // with no discontinuities. We stash this value so it can be used by the - // MonoPipe writer to imlement getNextWriteTimestamp. - int64_t nextReadPTS; - nextReadPTS = mPipe->offsetTimestampByAudioFrames(readPTS, count); - - // count == 0 is unlikely and not worth checking for explicitly; will be handled automatically - ssize_t red = availableToRead(); - if (CC_UNLIKELY(red <= 0)) { - // Uh-oh, looks like we are underflowing. Update the next read PTS and - // get out. - mPipe->updateFrontAndNRPTS(mPipe->mFront, nextReadPTS); - return red; - } - if (CC_LIKELY((size_t) red > count)) { - red = count; - } - size_t front = mPipe->mFront & (mPipe->mMaxFrames - 1); - size_t part1 = mPipe->mMaxFrames - front; - if (part1 > (size_t) red) { - part1 = red; - } - if (CC_LIKELY(part1 > 0)) { - memcpy(buffer, (char *) mPipe->mBuffer + (front << mBitShift), part1 << mBitShift); - if (CC_UNLIKELY(front + part1 == mPipe->mMaxFrames)) { - size_t part2 = red - part1; - if (CC_LIKELY(part2 > 0)) { - memcpy((char *) buffer + (part1 << mBitShift), mPipe->mBuffer, part2 << mBitShift); - } - } - mPipe->updateFrontAndNRPTS(red + mPipe->mFront, nextReadPTS); - mFramesRead += red; - } - return red; -} - -} // namespace android diff --git a/services/audioflinger/MonoPipeReader.h b/services/audioflinger/MonoPipeReader.h deleted file mode 100644 index 0e1c992..0000000 --- a/services/audioflinger/MonoPipeReader.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_MONO_PIPE_READER_H -#define ANDROID_AUDIO_MONO_PIPE_READER_H - -#include "MonoPipe.h" - -namespace android { - -// MonoPipeReader is safe for only a single reader thread -class MonoPipeReader : public NBAIO_Source { - -public: - - // Construct a MonoPipeReader and associate it with a MonoPipe; - // any data already in the pipe is visible to this PipeReader. - // There can be only a single MonoPipeReader per MonoPipe. - // FIXME make this constructor a factory method of MonoPipe. - MonoPipeReader(MonoPipe* pipe); - virtual ~MonoPipeReader(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Source interface - - //virtual size_t framesRead() const; - //virtual size_t framesOverrun(); - //virtual size_t overruns(); - - virtual ssize_t availableToRead(); - - virtual ssize_t read(void *buffer, size_t count, int64_t readPTS); - - // NBAIO_Source end - -#if 0 // until necessary - MonoPipe* pipe() const { return mPipe; } -#endif - -private: - MonoPipe * const mPipe; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_MONO_PIPE_READER_H diff --git a/services/audioflinger/NBAIO.cpp b/services/audioflinger/NBAIO.cpp deleted file mode 100644 index 2c07ebf..0000000 --- a/services/audioflinger/NBAIO.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2012 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 "NBAIO" -//#define LOG_NDEBUG 0 - -#include -#include "NBAIO.h" - -namespace android { - -size_t Format_frameSize(NBAIO_Format format) -{ - switch (format) { - case Format_SR44_1_C2_I16: - case Format_SR48_C2_I16: - return 2 * sizeof(short); - case Format_SR44_1_C1_I16: - case Format_SR48_C1_I16: - return 1 * sizeof(short); - case Format_Invalid: - default: - return 0; - } -} - -size_t Format_frameBitShift(NBAIO_Format format) -{ - switch (format) { - case Format_SR44_1_C2_I16: - case Format_SR48_C2_I16: - return 2; // 1 << 2 == 2 * sizeof(short) - case Format_SR44_1_C1_I16: - case Format_SR48_C1_I16: - return 1; // 1 << 1 == 1 * sizeof(short) - case Format_Invalid: - default: - return 0; - } -} - -unsigned Format_sampleRate(NBAIO_Format format) -{ - switch (format) { - case Format_SR44_1_C1_I16: - case Format_SR44_1_C2_I16: - return 44100; - case Format_SR48_C1_I16: - case Format_SR48_C2_I16: - return 48000; - case Format_Invalid: - default: - return 0; - } -} - -unsigned Format_channelCount(NBAIO_Format format) -{ - switch (format) { - case Format_SR44_1_C1_I16: - case Format_SR48_C1_I16: - return 1; - case Format_SR44_1_C2_I16: - case Format_SR48_C2_I16: - return 2; - case Format_Invalid: - default: - return 0; - } -} - -NBAIO_Format Format_from_SR_C(unsigned sampleRate, unsigned channelCount) -{ - if (sampleRate == 44100 && channelCount == 2) return Format_SR44_1_C2_I16; - if (sampleRate == 48000 && channelCount == 2) return Format_SR48_C2_I16; - if (sampleRate == 44100 && channelCount == 1) return Format_SR44_1_C1_I16; - if (sampleRate == 48000 && channelCount == 1) return Format_SR48_C1_I16; - return Format_Invalid; -} - -// This is a default implementation; it is expected that subclasses will optimize this. -ssize_t NBAIO_Sink::writeVia(writeVia_t via, size_t total, void *user, size_t block) -{ - if (!mNegotiated) { - return (ssize_t) NEGOTIATE; - } - static const size_t maxBlock = 32; - size_t frameSize = Format_frameSize(mFormat); - ALOG_ASSERT(frameSize > 0 && frameSize <= 8); - // double guarantees alignment for stack similar to what malloc() gives for heap - if (block == 0 || block > maxBlock) { - block = maxBlock; - } - double buffer[((frameSize * block) + sizeof(double) - 1) / sizeof(double)]; - size_t accumulator = 0; - while (accumulator < total) { - size_t count = total - accumulator; - if (count > block) { - count = block; - } - ssize_t ret = via(user, buffer, count); - if (ret > 0) { - ALOG_ASSERT((size_t) ret <= count); - size_t maxRet = ret; - ret = write(buffer, maxRet); - if (ret > 0) { - ALOG_ASSERT((size_t) ret <= maxRet); - accumulator += ret; - continue; - } - } - return accumulator > 0 ? accumulator : ret; - } - return accumulator; -} - -// This is a default implementation; it is expected that subclasses will optimize this. -ssize_t NBAIO_Source::readVia(readVia_t via, size_t total, void *user, - int64_t readPTS, size_t block) -{ - if (!mNegotiated) { - return (ssize_t) NEGOTIATE; - } - static const size_t maxBlock = 32; - size_t frameSize = Format_frameSize(mFormat); - ALOG_ASSERT(frameSize > 0 && frameSize <= 8); - // double guarantees alignment for stack similar to what malloc() gives for heap - if (block == 0 || block > maxBlock) { - block = maxBlock; - } - double buffer[((frameSize * block) + sizeof(double) - 1) / sizeof(double)]; - size_t accumulator = 0; - while (accumulator < total) { - size_t count = total - accumulator; - if (count > block) { - count = block; - } - ssize_t ret = read(buffer, count, readPTS); - if (ret > 0) { - ALOG_ASSERT((size_t) ret <= count); - size_t maxRet = ret; - ret = via(user, buffer, maxRet, readPTS); - if (ret > 0) { - ALOG_ASSERT((size_t) ret <= maxRet); - accumulator += ret; - continue; - } - } - return accumulator > 0 ? accumulator : ret; - } - return accumulator; -} - -// Default implementation that only accepts my mFormat -ssize_t NBAIO_Port::negotiate(const NBAIO_Format offers[], size_t numOffers, - NBAIO_Format counterOffers[], size_t& numCounterOffers) -{ - ALOGV("negotiate offers=%p numOffers=%u countersOffers=%p numCounterOffers=%u", - offers, numOffers, counterOffers, numCounterOffers); - if (mFormat != Format_Invalid) { - for (size_t i = 0; i < numOffers; ++i) { - if (offers[i] == mFormat) { - mNegotiated = true; - return i; - } - } - if (numCounterOffers > 0) { - counterOffers[0] = mFormat; - } - numCounterOffers = 1; - } else { - numCounterOffers = 0; - } - return (ssize_t) NEGOTIATE; -} - -} // namespace android diff --git a/services/audioflinger/NBAIO.h b/services/audioflinger/NBAIO.h deleted file mode 100644 index 81f42ed..0000000 --- a/services/audioflinger/NBAIO.h +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_NBAIO_H -#define ANDROID_AUDIO_NBAIO_H - -// Non-blocking audio I/O interface -// -// This header file has the abstract interfaces only. Concrete implementation classes are declared -// elsewhere. Implementations _should_ be non-blocking for all methods, especially read() and -// write(), but this is not enforced. In general, implementations do not need to be multi-thread -// safe, and any exceptions are noted in the particular implementation. - -#include -#include -#include -#include - -namespace android { - -// In addition to the usual status_t -enum { - NEGOTIATE = 0x80000010, // Must (re-)negotiate format. For negotiate() only, the offeree - // doesn't accept offers, and proposes counter-offers - OVERRUN = 0x80000011, // availableToRead(), read(), or readVia() detected lost input due - // to overrun; an event is counted and the caller should re-try - UNDERRUN = 0x80000012, // availableToWrite(), write(), or writeVia() detected a gap in - // output due to underrun (not being called often enough, or with - // enough data); an event is counted and the caller should re-try -}; - -// Negotiation of format is based on the data provider and data sink, or the data consumer and -// data source, exchanging prioritized arrays of offers and counter-offers until a single offer is -// mutually agreed upon. Each offer is an NBAIO_Format. For simplicity and performance, -// NBAIO_Format is an enum that ties together the most important combinations of the various -// attributes, rather than a struct with separate fields for format, sample rate, channel count, -// interleave, packing, alignment, etc. The reason is that NBAIO_Format tries to abstract out only -// the combinations that are actually needed within AudioFligner. If the list of combinations grows -// too large, then this decision should be re-visited. -enum NBAIO_Format { - Format_Invalid, - Format_SR44_1_C2_I16, // 44.1 kHz PCM stereo interleaved 16-bit signed - Format_SR48_C2_I16, // 48 kHz PCM stereo interleaved 16-bit signed - Format_SR44_1_C1_I16, // 44.1 kHz PCM mono interleaved 16-bit signed - Format_SR48_C1_I16, // 48 kHz PCM mono interleaved 16-bit signed -}; - -// Return the frame size of an NBAIO_Format in bytes -size_t Format_frameSize(NBAIO_Format format); - -// Return the frame size of an NBAIO_Format as a bit shift -size_t Format_frameBitShift(NBAIO_Format format); - -// Convert a sample rate in Hz and channel count to an NBAIO_Format -NBAIO_Format Format_from_SR_C(unsigned sampleRate, unsigned channelCount); - -// Return the sample rate in Hz of an NBAIO_Format -unsigned Format_sampleRate(NBAIO_Format format); - -// Return the channel count of an NBAIO_Format -unsigned Format_channelCount(NBAIO_Format format); - -// Callbacks used by NBAIO_Sink::writeVia() and NBAIO_Source::readVia() below. -typedef ssize_t (*writeVia_t)(void *user, void *buffer, size_t count); -typedef ssize_t (*readVia_t)(void *user, const void *buffer, - size_t count, int64_t readPTS); - -// Abstract class (interface) representing a data port. -class NBAIO_Port : public RefBase { - -public: - - // negotiate() must called first. The purpose of negotiate() is to check compatibility of - // formats, not to automatically adapt if they are incompatible. It's the responsibility of - // whoever sets up the graph connections to make sure formats are compatible, and this method - // just verifies that. The edges are "dumb" and don't attempt to adapt to bad connections. - // How it works: offerer proposes an array of formats, in descending order of preference from - // offers[0] to offers[numOffers - 1]. If offeree accepts one of these formats, it returns - // the index of that offer. Otherwise, offeree sets numCounterOffers to the number of - // counter-offers (up to a maximumum of the entry value of numCounterOffers), fills in the - // provided array counterOffers[] with its counter-offers, in descending order of preference - // from counterOffers[0] to counterOffers[numCounterOffers - 1], and returns NEGOTIATE. - // Note that since the offerer allocates space for counter-offers, but only the offeree knows - // how many counter-offers it has, there may be insufficient space for all counter-offers. - // In that case, the offeree sets numCounterOffers to the requested number of counter-offers - // (which is greater than the entry value of numCounterOffers), fills in as many of the most - // important counterOffers as will fit, and returns NEGOTIATE. As this implies a re-allocation, - // it should be used as a last resort. It is preferable for the offerer to simply allocate a - // larger space to begin with, and/or for the offeree to tolerate a smaller space than desired. - // Alternatively, the offerer can pass NULL for offers and counterOffers, and zero for - // numOffers. This indicates that it has not allocated space for any counter-offers yet. - // In this case, the offerree should set numCounterOffers appropriately and return NEGOTIATE. - // Then the offerer will allocate the correct amount of memory and retry. - // Format_Invalid is not allowed as either an offer or counter-offer. - // Returns: - // >= 0 Offer accepted. - // NEGOTIATE No offer accepted, and counter-offer(s) optionally made. See above for details. - virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - NBAIO_Format counterOffers[], size_t& numCounterOffers); - - // Return the current negotiated format, or Format_Invalid if negotiation has not been done, - // or if re-negotiation is required. - virtual NBAIO_Format format() const { return mNegotiated ? mFormat : Format_Invalid; } - -protected: - NBAIO_Port(NBAIO_Format format) : mNegotiated(false), mFormat(format), - mBitShift(Format_frameBitShift(format)) { } - virtual ~NBAIO_Port() { } - - // Implementations are free to ignore these if they don't need them - - bool mNegotiated; // mNegotiated implies (mFormat != Format_Invalid) - NBAIO_Format mFormat; // (mFormat != Format_Invalid) does not imply mNegotiated - size_t mBitShift; // assign in parallel with any assignment to mFormat -}; - -// Abstract class (interface) representing a non-blocking data sink, for use by a data provider. -class NBAIO_Sink : public NBAIO_Port { - -public: - - // For the next two APIs: - // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically. - - // Return the number of frames written successfully since construction. - virtual size_t framesWritten() const { return mFramesWritten; } - - // Number of frames lost due to underrun since construction. - virtual size_t framesUnderrun() const { return 0; } - - // Number of underruns since construction, where a set of contiguous lost frames is one event. - virtual size_t underruns() const { return 0; } - - // Estimate of number of frames that could be written successfully now without blocking. - // When a write() is actually attempted, the implementation is permitted to return a smaller or - // larger transfer count, however it will make a good faith effort to give an accurate estimate. - // Errors: - // NEGOTIATE (Re-)negotiation is needed. - // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. - // An underrun event is counted, and the caller should re-try this operation. - // WOULD_BLOCK Determining how many frames can be written without blocking would itself block. - virtual ssize_t availableToWrite() const { return SSIZE_MAX; } - - // Transfer data to sink from single input buffer. Implies a copy. - // Inputs: - // buffer Non-NULL buffer owned by provider. - // count Maximum number of frames to transfer. - // Return value: - // > 0 Number of frames successfully transferred prior to first error. - // = 0 Count was zero. - // < 0 status_t error occurred prior to the first frame transfer. - // Errors: - // NEGOTIATE (Re-)negotiation is needed. - // WOULD_BLOCK No frames can be transferred without blocking. - // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. - // An underrun event is counted, and the caller should re-try this operation. - virtual ssize_t write(const void *buffer, size_t count) = 0; - - // Transfer data to sink using a series of callbacks. More suitable for zero-fill, synthesis, - // and non-contiguous transfers (e.g. circular buffer or writev). - // Inputs: - // via Callback function that the sink will call as many times as needed to consume data. - // total Estimate of the number of frames the provider has available. This is an estimate, - // and it can provide a different number of frames during the series of callbacks. - // user Arbitrary void * reserved for data provider. - // block Number of frames per block, that is a suggested value for 'count' in each callback. - // Zero means no preference. This parameter is a hint only, and may be ignored. - // Return value: - // > 0 Total number of frames successfully transferred prior to first error. - // = 0 Count was zero. - // < 0 status_t error occurred prior to the first frame transfer. - // Errors: - // NEGOTIATE (Re-)negotiation is needed. - // WOULD_BLOCK No frames can be transferred without blocking. - // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. - // An underrun event is counted, and the caller should re-try this operation. - // - // The 'via' callback is called by the data sink as follows: - // Inputs: - // user Arbitrary void * reserved for data provider. - // buffer Non-NULL buffer owned by sink that callback should fill in with data, - // up to a maximum of 'count' frames. - // count Maximum number of frames to transfer during this callback. - // Return value: - // > 0 Number of frames successfully transferred during this callback prior to first error. - // = 0 Count was zero. - // < 0 status_t error occurred prior to the first frame transfer during this callback. - virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block = 0); - - // Get the time (on the LocalTime timeline) at which the first frame of audio of the next write - // operation to this sink will be eventually rendered by the HAL. - // Inputs: - // ts A pointer pointing to the int64_t which will hold the result. - // Return value: - // OK Everything went well, *ts holds the time at which the first audio frame of the next - // write operation will be rendered, or AudioBufferProvider::kInvalidPTS if this sink - // does not know the answer for some reason. Sinks which eventually lead to a HAL - // which implements get_next_write_timestamp may return Invalid temporarily if the DMA - // output of the audio driver has not started yet. Sinks which lead to a HAL which - // does not implement get_next_write_timestamp, or which don't lead to a HAL at all, - // will always return kInvalidPTS. - // Something unexpected happened internally. Check the logs and start debugging. - virtual status_t getNextWriteTimestamp(int64_t *ts) { return INVALID_OPERATION; } - -protected: - NBAIO_Sink(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesWritten(0) { } - virtual ~NBAIO_Sink() { } - - // Implementations are free to ignore these if they don't need them - size_t mFramesWritten; -}; - -// Abstract class (interface) representing a non-blocking data source, for use by a data consumer. -class NBAIO_Source : public NBAIO_Port { - -public: - - // For the next two APIs: - // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically. - - // Number of frames read successfully since construction. - virtual size_t framesRead() const { return mFramesRead; } - - // Number of frames lost due to overrun since construction. - // Not const because implementations may need to do I/O. - virtual size_t framesOverrun() /*const*/ { return 0; } - - // Number of overruns since construction, where a set of contiguous lost frames is one event. - // Not const because implementations may need to do I/O. - virtual size_t overruns() /*const*/ { return 0; } - - // Estimate of number of frames that could be read successfully now. - // When a read() is actually attempted, the implementation is permitted to return a smaller or - // larger transfer count, however it will make a good faith effort to give an accurate estimate. - // Errors: - // NEGOTIATE (Re-)negotiation is needed. - // OVERRUN One or more frames were lost due to overrun, try again to read more recent data. - // WOULD_BLOCK Determining how many frames can be read without blocking would itself block. - virtual ssize_t availableToRead() { return SSIZE_MAX; } - - // Transfer data from source into single destination buffer. Implies a copy. - // Inputs: - // buffer Non-NULL destination buffer owned by consumer. - // count Maximum number of frames to transfer. - // readPTS The presentation time (on the LocalTime timeline) for which data - // is being requested, or kInvalidPTS if not known. - // Return value: - // > 0 Number of frames successfully transferred prior to first error. - // = 0 Count was zero. - // < 0 status_t error occurred prior to the first frame transfer. - // Errors: - // NEGOTIATE (Re-)negotiation is needed. - // WOULD_BLOCK No frames can be transferred without blocking. - // OVERRUN read() has not been called frequently enough, or with enough frames to keep up. - // One or more frames were lost due to overrun, try again to read more recent data. - virtual ssize_t read(void *buffer, size_t count, int64_t readPTS) = 0; - - // Transfer data from source using a series of callbacks. More suitable for zero-fill, - // synthesis, and non-contiguous transfers (e.g. circular buffer or readv). - // Inputs: - // via Callback function that the source will call as many times as needed to provide data. - // total Estimate of the number of frames the consumer desires. This is an estimate, - // and it can consume a different number of frames during the series of callbacks. - // user Arbitrary void * reserved for data consumer. - // readPTS The presentation time (on the LocalTime timeline) for which data - // is being requested, or kInvalidPTS if not known. - // block Number of frames per block, that is a suggested value for 'count' in each callback. - // Zero means no preference. This parameter is a hint only, and may be ignored. - // Return value: - // > 0 Total number of frames successfully transferred prior to first error. - // = 0 Count was zero. - // < 0 status_t error occurred prior to the first frame transfer. - // Errors: - // NEGOTIATE (Re-)negotiation is needed. - // WOULD_BLOCK No frames can be transferred without blocking. - // OVERRUN read() has not been called frequently enough, or with enough frames to keep up. - // One or more frames were lost due to overrun, try again to read more recent data. - // - // The 'via' callback is called by the data source as follows: - // Inputs: - // user Arbitrary void * reserved for data consumer. - // dest Non-NULL buffer owned by source that callback should consume data from, - // up to a maximum of 'count' frames. - // count Maximum number of frames to transfer during this callback. - // Return value: - // > 0 Number of frames successfully transferred during this callback prior to first error. - // = 0 Count was zero. - // < 0 status_t error occurred prior to the first frame transfer during this callback. - virtual ssize_t readVia(readVia_t via, size_t total, void *user, - int64_t readPTS, size_t block = 0); - -protected: - NBAIO_Source(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesRead(0) { } - virtual ~NBAIO_Source() { } - - // Implementations are free to ignore these if they don't need them - size_t mFramesRead; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_NBAIO_H diff --git a/services/audioflinger/Pipe.cpp b/services/audioflinger/Pipe.cpp deleted file mode 100644 index e5b3561..0000000 --- a/services/audioflinger/Pipe.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2012 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 "Pipe" -//#define LOG_NDEBUG 0 - -#include -#include -#include -#include "Pipe.h" -#include "roundup.h" - -namespace android { - -Pipe::Pipe(size_t maxFrames, NBAIO_Format format) : - NBAIO_Sink(format), - mMaxFrames(roundup(maxFrames)), - mBuffer(malloc(mMaxFrames * Format_frameSize(format))), - mRear(0), - mReaders(0) -{ -} - -Pipe::~Pipe() -{ - ALOG_ASSERT(android_atomic_acquire_load(&mReaders) == 0); - free(mBuffer); -} - -ssize_t Pipe::write(const void *buffer, size_t count) -{ - // count == 0 is unlikely and not worth checking for - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - // write() is not multi-thread safe w.r.t. itself, so no mutex or atomic op needed to read mRear - size_t rear = mRear & (mMaxFrames - 1); - size_t written = mMaxFrames - rear; - if (CC_LIKELY(written > count)) { - written = count; - } - memcpy((char *) mBuffer + (rear << mBitShift), buffer, written << mBitShift); - if (CC_UNLIKELY(rear + written == mMaxFrames)) { - if (CC_UNLIKELY((count -= written) > rear)) { - count = rear; - } - if (CC_LIKELY(count > 0)) { - memcpy(mBuffer, (char *) buffer + (written << mBitShift), count << mBitShift); - written += count; - } - } - android_atomic_release_store(written + mRear, &mRear); - mFramesWritten += written; - return written; -} - -} // namespace android diff --git a/services/audioflinger/Pipe.h b/services/audioflinger/Pipe.h deleted file mode 100644 index 79a4eee..0000000 --- a/services/audioflinger/Pipe.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_PIPE_H -#define ANDROID_AUDIO_PIPE_H - -#include "NBAIO.h" - -namespace android { - -// Pipe is multi-thread safe for readers (see PipeReader), but safe for only a single writer thread. -// It cannot UNDERRUN on write, unless we allow designation of a master reader that provides the -// time-base. Readers can be added and removed dynamically, and it's OK to have no readers. -class Pipe : public NBAIO_Sink { - - friend class PipeReader; - -public: - // maxFrames will be rounded up to a power of 2, and all slots are available. Must be >= 2. - Pipe(size_t maxFrames, NBAIO_Format format); - virtual ~Pipe(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Sink interface - - //virtual size_t framesWritten() const; - //virtual size_t framesUnderrun() const; - //virtual size_t underruns() const; - - // The write side of a pipe permits overruns; flow control is the caller's responsibility. - // It doesn't return +infinity because that would guarantee an overrun. - virtual ssize_t availableToWrite() const { return mMaxFrames; } - - virtual ssize_t write(const void *buffer, size_t count); - //virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block); - -private: - const size_t mMaxFrames; // always a power of 2 - void * const mBuffer; - volatile int32_t mRear; // written by android_atomic_release_store - volatile int32_t mReaders; // number of PipeReader clients currently attached to this Pipe -}; - -} // namespace android - -#endif // ANDROID_AUDIO_PIPE_H diff --git a/services/audioflinger/PipeReader.cpp b/services/audioflinger/PipeReader.cpp deleted file mode 100644 index 529d478..0000000 --- a/services/audioflinger/PipeReader.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2012 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 "PipeReader" -//#define LOG_NDEBUG 0 - -#include -#include -#include "PipeReader.h" - -namespace android { - -PipeReader::PipeReader(Pipe& pipe) : - NBAIO_Source(pipe.mFormat), - mPipe(pipe), - // any data already in the pipe is not visible to this PipeReader - mFront(android_atomic_acquire_load(&pipe.mRear)), - mFramesOverrun(0), - mOverruns(0) -{ - android_atomic_inc(&pipe.mReaders); -} - -PipeReader::~PipeReader() -{ - int32_t readers = android_atomic_dec(&mPipe.mReaders); - ALOG_ASSERT(readers > 0); -} - -ssize_t PipeReader::availableToRead() -{ - if (CC_UNLIKELY(!mNegotiated)) { - return NEGOTIATE; - } - int32_t rear = android_atomic_acquire_load(&mPipe.mRear); - // read() is not multi-thread safe w.r.t. itself, so no mutex or atomic op needed to read mFront - size_t avail = rear - mFront; - if (CC_UNLIKELY(avail > mPipe.mMaxFrames)) { - // Discard 1/16 of the most recent data in pipe to avoid another overrun immediately - int32_t oldFront = mFront; - mFront = rear - mPipe.mMaxFrames + (mPipe.mMaxFrames >> 4); - mFramesOverrun += (size_t) (mFront - oldFront); - ++mOverruns; - return OVERRUN; - } - return avail; -} - -ssize_t PipeReader::read(void *buffer, size_t count, int64_t readPTS) -{ - ssize_t avail = availableToRead(); - if (CC_UNLIKELY(avail <= 0)) { - return avail; - } - // An overrun can occur from here on and be silently ignored, - // but it will be caught at next read() - if (CC_LIKELY(count > (size_t) avail)) { - count = avail; - } - size_t front = mFront & (mPipe.mMaxFrames - 1); - size_t red = mPipe.mMaxFrames - front; - if (CC_LIKELY(red > count)) { - red = count; - } - // In particular, an overrun during the memcpy will result in reading corrupt data - memcpy(buffer, (char *) mPipe.mBuffer + (front << mBitShift), red << mBitShift); - // We could re-read the rear pointer here to detect the corruption, but why bother? - if (CC_UNLIKELY(front + red == mPipe.mMaxFrames)) { - if (CC_UNLIKELY((count -= red) > front)) { - count = front; - } - if (CC_LIKELY(count > 0)) { - memcpy((char *) buffer + (red << mBitShift), mPipe.mBuffer, count << mBitShift); - red += count; - } - } - mFront += red; - mFramesRead += red; - return red; -} - -} // namespace android diff --git a/services/audioflinger/PipeReader.h b/services/audioflinger/PipeReader.h deleted file mode 100644 index 350e6ab..0000000 --- a/services/audioflinger/PipeReader.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ANDROID_AUDIO_PIPE_READER_H -#define ANDROID_AUDIO_PIPE_READER_H - -#include "Pipe.h" - -namespace android { - -// PipeReader is safe for only a single thread -class PipeReader : public NBAIO_Source { - -public: - - // Construct a PipeReader and associate it with a Pipe - // FIXME make this constructor a factory method of Pipe. - PipeReader(Pipe& pipe); - virtual ~PipeReader(); - - // NBAIO_Port interface - - //virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, - // NBAIO_Format counterOffers[], size_t& numCounterOffers); - //virtual NBAIO_Format format() const; - - // NBAIO_Source interface - - //virtual size_t framesRead() const; - virtual size_t framesOverrun() { return mFramesOverrun; } - virtual size_t overruns() { return mOverruns; } - - virtual ssize_t availableToRead(); - - virtual ssize_t read(void *buffer, size_t count, int64_t readPTS); - - // NBAIO_Source end - -#if 0 // until necessary - Pipe& pipe() const { return mPipe; } -#endif - -private: - Pipe& mPipe; - int32_t mFront; // follows behind mPipe.mRear - size_t mFramesOverrun; - size_t mOverruns; -}; - -} // namespace android - -#endif // ANDROID_AUDIO_PIPE_READER_H diff --git a/services/audioflinger/SourceAudioBufferProvider.cpp b/services/audioflinger/SourceAudioBufferProvider.cpp deleted file mode 100644 index 3343b53..0000000 --- a/services/audioflinger/SourceAudioBufferProvider.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2012 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 "SourceAudioBufferProvider" -//#define LOG_NDEBUG 0 - -#include -#include "SourceAudioBufferProvider.h" - -namespace android { - -SourceAudioBufferProvider::SourceAudioBufferProvider(const sp& source) : - mSource(source), - // mFrameBitShiftFormat below - mAllocated(NULL), mSize(0), mOffset(0), mRemaining(0), mGetCount(0) -{ - ALOG_ASSERT(source != 0); - - // negotiate with source - NBAIO_Format counterOffers[1]; - size_t numCounterOffers = 1; - ssize_t index = source->negotiate(NULL, 0, counterOffers, numCounterOffers); - ALOG_ASSERT(index == (ssize_t) NEGOTIATE && numCounterOffers > 0); - numCounterOffers = 0; - index = source->negotiate(counterOffers, 1, NULL, numCounterOffers); - ALOG_ASSERT(index == 0); - mFrameBitShift = Format_frameBitShift(source->format()); -} - -SourceAudioBufferProvider::~SourceAudioBufferProvider() -{ - free(mAllocated); -} - -status_t SourceAudioBufferProvider::getNextBuffer(Buffer *buffer, int64_t pts) -{ - ALOG_ASSERT(buffer != NULL && buffer->frameCount > 0 && mGetCount == 0); - // any leftover data available? - if (mRemaining > 0) { - ALOG_ASSERT(mOffset + mRemaining <= mSize); - if (mRemaining < buffer->frameCount) { - buffer->frameCount = mRemaining; - } - buffer->raw = (char *) mAllocated + (mOffset << mFrameBitShift); - mGetCount = buffer->frameCount; - return OK; - } - // do we need to reallocate? - if (buffer->frameCount > mSize) { - free(mAllocated); - mAllocated = malloc(buffer->frameCount << mFrameBitShift); - mSize = buffer->frameCount; - } - // read from source - ssize_t actual = mSource->read(mAllocated, buffer->frameCount, pts); - if (actual > 0) { - ALOG_ASSERT((size_t) actual <= buffer->frameCount); - mOffset = 0; - mRemaining = actual; - buffer->raw = mAllocated; - buffer->frameCount = actual; - mGetCount = actual; - return OK; - } - buffer->raw = NULL; - buffer->frameCount = 0; - mGetCount = 0; - return NOT_ENOUGH_DATA; -} - -void SourceAudioBufferProvider::releaseBuffer(Buffer *buffer) -{ - ALOG_ASSERT((buffer != NULL) && - (buffer->raw == (char *) mAllocated + (mOffset << mFrameBitShift)) && - (buffer->frameCount <= mGetCount) && - (mGetCount <= mRemaining) && - (mOffset + mRemaining <= mSize)); - mOffset += buffer->frameCount; - mRemaining -= buffer->frameCount; - buffer->raw = NULL; - buffer->frameCount = 0; - mGetCount = 0; -} - -size_t SourceAudioBufferProvider::framesReady() const -{ - ssize_t avail = mSource->availableToRead(); - return avail < 0 ? 0 : (size_t) avail; -} - -} // namespace android diff --git a/services/audioflinger/SourceAudioBufferProvider.h b/services/audioflinger/SourceAudioBufferProvider.h deleted file mode 100644 index 85ccbb2..0000000 --- a/services/audioflinger/SourceAudioBufferProvider.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -// Implementation of AudioBufferProvider that wraps an NBAIO_Source - -#ifndef ANDROID_SOURCE_AUDIO_BUFFER_PROVIDER_H -#define ANDROID_SOURCE_AUDIO_BUFFER_PROVIDER_H - -#include "NBAIO.h" -#include "ExtendedAudioBufferProvider.h" - -namespace android { - -class SourceAudioBufferProvider : public ExtendedAudioBufferProvider { - -public: - SourceAudioBufferProvider(const sp& source); - virtual ~SourceAudioBufferProvider(); - - // AudioBufferProvider interface - virtual status_t getNextBuffer(Buffer *buffer, int64_t pts); - virtual void releaseBuffer(Buffer *buffer); - - // ExtendedAudioBufferProvider interface - virtual size_t framesReady() const; - -private: - const sp mSource; // the wrapped source - /*const*/ size_t mFrameBitShift; // log2(frame size in bytes) - void* mAllocated; // pointer to base of allocated memory - size_t mSize; // size of mAllocated in frames - size_t mOffset; // frame offset within mAllocated of valid data - size_t mRemaining; // frame count within mAllocated of valid data - size_t mGetCount; // buffer.frameCount of the most recent getNextBuffer -}; - -} // namespace android - -#endif // ANDROID_SOURCE_AUDIO_BUFFER_PROVIDER_H diff --git a/services/audioflinger/roundup.c b/services/audioflinger/roundup.c deleted file mode 100644 index 4f9af6a..0000000 --- a/services/audioflinger/roundup.c +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#include "roundup.h" - -unsigned roundup(unsigned v) -{ - // __builtin_clz is undefined for zero input - if (v == 0) { - v = 1; - } - int lz = __builtin_clz((int) v); - unsigned rounded = ((unsigned) 0x80000000) >> lz; - // 0x800000001 and higher are actually rounded _down_ to prevent overflow - if (v > rounded && lz > 0) { - rounded <<= 1; - } - return rounded; -} diff --git a/services/audioflinger/roundup.h b/services/audioflinger/roundup.h deleted file mode 100644 index 4c3cc25..0000000 --- a/services/audioflinger/roundup.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ROUNDUP_H -#define ROUNDUP_H - -#ifdef __cplusplus -extern "C" { -#endif - -// Round up to the next highest power of 2 -unsigned roundup(unsigned v); - -#ifdef __cplusplus -} -#endif - -#endif // ROUNDUP_H -- cgit v1.1