1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <memory>
18
19 #include "oboe/Oboe.h"
20
21 #include "opensles/AudioStreamBuffered.h"
22 #include "common/AudioClock.h"
23
24 namespace oboe {
25
26 constexpr int kDefaultBurstsPerBuffer = 16; // arbitrary, allows dynamic latency tuning
27 constexpr int kMinBurstsPerBuffer = 4; // arbitrary, allows dynamic latency tuning
28 constexpr int kMinFramesPerBuffer = 48 * 32; // arbitrary
29
30 /*
31 * AudioStream with a FifoBuffer
32 */
AudioStreamBuffered(const AudioStreamBuilder & builder)33 AudioStreamBuffered::AudioStreamBuffered(const AudioStreamBuilder &builder)
34 : AudioStream(builder) {
35 }
36
allocateFifo()37 void AudioStreamBuffered::allocateFifo() {
38 // If the caller does not provide a callback use our own internal
39 // callback that reads data from the FIFO.
40 if (usingFIFO()) {
41 // FIFO is configured with the same format and channels as the stream.
42 int32_t capacityFrames = getBufferCapacityInFrames();
43 if (capacityFrames == oboe::kUnspecified) {
44 capacityFrames = getFramesPerBurst() * kDefaultBurstsPerBuffer;
45 } else {
46 int32_t minFramesPerBufferByBursts = getFramesPerBurst() * kMinBurstsPerBuffer;
47 if (capacityFrames <= minFramesPerBufferByBursts) {
48 capacityFrames = minFramesPerBufferByBursts;
49 } else {
50 capacityFrames = std::max(kMinFramesPerBuffer, capacityFrames);
51 // round up to nearest burst
52 int32_t numBursts = (capacityFrames + getFramesPerBurst() - 1)
53 / getFramesPerBurst();
54 capacityFrames = numBursts * getFramesPerBurst();
55 }
56 }
57 // TODO consider using std::make_unique if we require c++14
58 mFifoBuffer.reset(new FifoBuffer(getBytesPerFrame(), capacityFrames));
59 mBufferCapacityInFrames = capacityFrames;
60 }
61 }
62
updateFramesWritten()63 void AudioStreamBuffered::updateFramesWritten() {
64 if (mFifoBuffer) {
65 mFramesWritten = static_cast<int64_t>(mFifoBuffer->getWriteCounter());
66 } // or else it will get updated by processBufferCallback()
67 }
68
updateFramesRead()69 void AudioStreamBuffered::updateFramesRead() {
70 if (mFifoBuffer) {
71 mFramesRead = static_cast<int64_t>(mFifoBuffer->getReadCounter());
72 } // or else it will get updated by processBufferCallback()
73 }
74
75 // This is called by the OpenSL ES callback to read or write the back end of the FIFO.
onDefaultCallback(void * audioData,int numFrames)76 DataCallbackResult AudioStreamBuffered::onDefaultCallback(void *audioData, int numFrames) {
77 int32_t framesTransferred = 0;
78
79 if (getDirection() == oboe::Direction::Output) {
80 // Read from the FIFO and write to audioData, clear part of buffer if not enough data.
81 framesTransferred = mFifoBuffer->readNow(audioData, numFrames);
82 } else {
83 // Read from audioData and write to the FIFO
84 framesTransferred = mFifoBuffer->write(audioData, numFrames); // There is no writeNow()
85 }
86
87 if (framesTransferred < numFrames) {
88 LOGD("AudioStreamBuffered::%s(): xrun! framesTransferred = %d, numFrames = %d",
89 __func__, framesTransferred, numFrames);
90 // TODO If we do not allow FIFO to wrap then our timestamps will drift when there is an XRun!
91 incrementXRunCount();
92 }
93 markCallbackTime(static_cast<int32_t>(numFrames)); // so foreground knows how long to wait.
94 return DataCallbackResult::Continue;
95 }
96
markCallbackTime(int32_t numFrames)97 void AudioStreamBuffered::markCallbackTime(int32_t numFrames) {
98 mLastBackgroundSize = numFrames;
99 mBackgroundRanAtNanoseconds = AudioClock::getNanoseconds();
100 }
101
predictNextCallbackTime()102 int64_t AudioStreamBuffered::predictNextCallbackTime() {
103 if (mBackgroundRanAtNanoseconds == 0) {
104 return 0;
105 }
106 int64_t nanosPerBuffer = (kNanosPerSecond * mLastBackgroundSize) / getSampleRate();
107 const int64_t margin = 200 * kNanosPerMicrosecond; // arbitrary delay so we wake up just after
108 return mBackgroundRanAtNanoseconds + nanosPerBuffer + margin;
109 }
110
111 // Common code for read/write.
112 // @return Result::OK with frames read/written, or Result::Error*
transfer(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)113 ResultWithValue<int32_t> AudioStreamBuffered::transfer(void *buffer,
114 int32_t numFrames,
115 int64_t timeoutNanoseconds) {
116 // Validate arguments.
117 if (buffer == nullptr) {
118 LOGE("AudioStreamBuffered::%s(): buffer is NULL", __func__);
119 return ResultWithValue<int32_t>(Result::ErrorNull);
120 }
121 if (numFrames < 0) {
122 LOGE("AudioStreamBuffered::%s(): numFrames is negative", __func__);
123 return ResultWithValue<int32_t>(Result::ErrorOutOfRange);
124 } else if (numFrames == 0) {
125 return ResultWithValue<int32_t>(numFrames);
126 }
127 if (timeoutNanoseconds < 0) {
128 LOGE("AudioStreamBuffered::%s(): timeoutNanoseconds is negative", __func__);
129 return ResultWithValue<int32_t>(Result::ErrorOutOfRange);
130 }
131
132 int32_t result = 0;
133 uint8_t *data = reinterpret_cast<uint8_t *>(buffer);
134 int32_t framesLeft = numFrames;
135 int64_t timeToQuit = 0;
136 bool repeat = true;
137
138 // Calculate when to timeout.
139 if (timeoutNanoseconds > 0) {
140 timeToQuit = AudioClock::getNanoseconds() + timeoutNanoseconds;
141 }
142
143 // Loop until we get the data, or we have an error, or we timeout.
144 do {
145 // read or write
146 if (getDirection() == Direction::Input) {
147 result = mFifoBuffer->read(data, framesLeft);
148 } else {
149 // between zero and capacity
150 uint32_t fullFrames = mFifoBuffer->getFullFramesAvailable();
151 // Do not write above threshold size.
152 int32_t emptyFrames = getBufferSizeInFrames() - static_cast<int32_t>(fullFrames);
153 int32_t framesToWrite = std::max(0, std::min(framesLeft, emptyFrames));
154 result = mFifoBuffer->write(data, framesToWrite);
155 }
156 if (result > 0) {
157 data += mFifoBuffer->convertFramesToBytes(result);
158 framesLeft -= result;
159 }
160
161 // If we need more data then sleep and try again.
162 if (framesLeft > 0 && result >= 0 && timeoutNanoseconds > 0) {
163 int64_t timeNow = AudioClock::getNanoseconds();
164 if (timeNow >= timeToQuit) {
165 LOGE("AudioStreamBuffered::%s(): TIMEOUT", __func__);
166 repeat = false; // TIMEOUT
167 } else {
168 // Figure out how long to sleep.
169 int64_t sleepForNanos;
170 int64_t wakeTimeNanos = predictNextCallbackTime();
171 if (wakeTimeNanos <= 0) {
172 // No estimate available. Sleep for one burst.
173 sleepForNanos = (getFramesPerBurst() * kNanosPerSecond) / getSampleRate();
174 } else {
175 // Don't sleep past timeout.
176 if (wakeTimeNanos > timeToQuit) {
177 wakeTimeNanos = timeToQuit;
178 }
179 sleepForNanos = wakeTimeNanos - timeNow;
180 // Avoid rapid loop with no sleep.
181 const int64_t minSleepTime = kNanosPerMillisecond; // arbitrary
182 if (sleepForNanos < minSleepTime) {
183 sleepForNanos = minSleepTime;
184 }
185 }
186
187 AudioClock::sleepForNanos(sleepForNanos);
188 }
189
190 } else {
191 repeat = false;
192 }
193 } while(repeat);
194
195 if (result < 0) {
196 return ResultWithValue<int32_t>(static_cast<Result>(result));
197 } else {
198 int32_t framesWritten = numFrames - framesLeft;
199 return ResultWithValue<int32_t>(framesWritten);
200 }
201 }
202
203 // Write to the FIFO so the callback can read from it.
write(const void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)204 ResultWithValue<int32_t> AudioStreamBuffered::write(const void *buffer,
205 int32_t numFrames,
206 int64_t timeoutNanoseconds) {
207 if (getState() == StreamState::Closed){
208 return ResultWithValue<int32_t>(Result::ErrorClosed);
209 }
210
211 if (getDirection() == Direction::Input) {
212 return ResultWithValue<int32_t>(Result::ErrorUnavailable); // TODO review, better error code?
213 }
214 updateServiceFrameCounter();
215 return transfer(const_cast<void *>(buffer), numFrames, timeoutNanoseconds);
216 }
217
218 // Read data from the FIFO that was written by the callback.
read(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)219 ResultWithValue<int32_t> AudioStreamBuffered::read(void *buffer,
220 int32_t numFrames,
221 int64_t timeoutNanoseconds) {
222 if (getState() == StreamState::Closed){
223 return ResultWithValue<int32_t>(Result::ErrorClosed);
224 }
225
226 if (getDirection() == Direction::Output) {
227 return ResultWithValue<int32_t>(Result::ErrorUnavailable); // TODO review, better error code?
228 }
229 updateServiceFrameCounter();
230 return transfer(buffer, numFrames, timeoutNanoseconds);
231 }
232
233 // Only supported when we are not using a callback.
setBufferSizeInFrames(int32_t requestedFrames)234 ResultWithValue<int32_t> AudioStreamBuffered::setBufferSizeInFrames(int32_t requestedFrames)
235 {
236 if (getState() == StreamState::Closed){
237 return ResultWithValue<int32_t>(Result::ErrorClosed);
238 }
239
240 if (!mFifoBuffer) {
241 return ResultWithValue<int32_t>(Result::ErrorUnimplemented);
242 }
243
244 if (requestedFrames > mFifoBuffer->getBufferCapacityInFrames()) {
245 requestedFrames = mFifoBuffer->getBufferCapacityInFrames();
246 } else if (requestedFrames < getFramesPerBurst()) {
247 requestedFrames = getFramesPerBurst();
248 }
249 mBufferSizeInFrames = requestedFrames;
250 return ResultWithValue<int32_t>(requestedFrames);
251 }
252
getBufferCapacityInFrames() const253 int32_t AudioStreamBuffered::getBufferCapacityInFrames() const {
254 if (mFifoBuffer) {
255 return mFifoBuffer->getBufferCapacityInFrames();
256 } else {
257 return AudioStream::getBufferCapacityInFrames();
258 }
259 }
260
isXRunCountSupported() const261 bool AudioStreamBuffered::isXRunCountSupported() const {
262 // XRun count is only supported if we're using blocking I/O (not callbacks)
263 return (getCallback() == nullptr);
264 }
265
266 } // namespace oboe