Reset the ringbuffer when stopping OpenSL playback
[openal-soft.git] / examples / alstreamcb.cpp
blobe0dff4aadf1e86d729722884605d07ec19699a80
1 /*
2 * OpenAL Callback-based Stream Example
4 * Copyright (c) 2020 by Chris Robinson <chris.kcat@gmail.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 /* This file contains a streaming audio player using a callback buffer. */
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
31 #include <atomic>
32 #include <chrono>
33 #include <memory>
34 #include <stdexcept>
35 #include <string>
36 #include <thread>
37 #include <vector>
39 #include "sndfile.h"
41 #include "AL/al.h"
42 #include "AL/alc.h"
43 #include "AL/alext.h"
45 #include "common/alhelpers.h"
48 namespace {
50 using std::chrono::seconds;
51 using std::chrono::nanoseconds;
53 LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
55 struct StreamPlayer {
56 /* A lockless ring-buffer (supports single-provider, single-consumer
57 * operation).
59 std::unique_ptr<ALbyte[]> mBufferData;
60 size_t mBufferDataSize{0};
61 std::atomic<size_t> mReadPos{0};
62 std::atomic<size_t> mWritePos{0};
64 /* The buffer to get the callback, and source to play with. */
65 ALuint mBuffer{0}, mSource{0};
66 size_t mStartOffset{0};
68 /* Handle for the audio file to decode. */
69 SNDFILE *mSndfile{nullptr};
70 SF_INFO mSfInfo{};
71 size_t mDecoderOffset{0};
73 /* The format of the callback samples. */
74 ALenum mFormat;
76 StreamPlayer()
78 alGenBuffers(1, &mBuffer);
79 if(ALenum err{alGetError()})
80 throw std::runtime_error{"alGenBuffers failed"};
81 alGenSources(1, &mSource);
82 if(ALenum err{alGetError()})
84 alDeleteBuffers(1, &mBuffer);
85 throw std::runtime_error{"alGenSources failed"};
88 ~StreamPlayer()
90 alDeleteSources(1, &mSource);
91 alDeleteBuffers(1, &mBuffer);
92 if(mSndfile)
93 sf_close(mSndfile);
96 void close()
98 if(mSndfile)
100 alSourceRewind(mSource);
101 alSourcei(mSource, AL_BUFFER, 0);
102 sf_close(mSndfile);
103 mSndfile = nullptr;
107 bool open(const char *filename)
109 close();
111 /* Open the file and figure out the OpenAL format. */
112 mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
113 if(!mSndfile)
115 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
116 return false;
119 mFormat = AL_NONE;
120 if(mSfInfo.channels == 1)
121 mFormat = AL_FORMAT_MONO_FLOAT32;
122 else if(mSfInfo.channels == 2)
123 mFormat = AL_FORMAT_STEREO_FLOAT32;
124 else if(mSfInfo.channels == 3)
126 if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
127 mFormat = AL_FORMAT_BFORMAT2D_FLOAT32;
129 else if(mSfInfo.channels == 4)
131 if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
132 mFormat = AL_FORMAT_BFORMAT3D_FLOAT32;
134 if(!mFormat)
136 fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
137 sf_close(mSndfile);
138 mSndfile = nullptr;
140 return false;
143 /* Set a 1s ring buffer size. */
144 mBufferDataSize = static_cast<ALuint>(mSfInfo.samplerate*mSfInfo.channels) * sizeof(float);
145 mBufferData.reset(new ALbyte[mBufferDataSize]);
146 mReadPos.store(0, std::memory_order_relaxed);
147 mWritePos.store(0, std::memory_order_relaxed);
148 mDecoderOffset = 0;
150 return true;
153 /* The actual C-style callback just forwards to the non-static method. Not
154 * strictly needed and the compiler will optimize it to a normal function,
155 * but it allows the callback implementation to have a nice 'this' pointer
156 * with normal member access.
158 static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
159 { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
160 ALsizei bufferCallback(void *data, ALsizei size)
162 /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
163 * no allocations or deallocations, no I/O, no page faults, or calls to
164 * functions that could do these things (this includes calling to
165 * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
166 * unexpectedly stall this call since the audio has to get to the
167 * device on time.
169 ALsizei got{0};
171 size_t roffset{mReadPos.load(std::memory_order_acquire)};
172 while(got < size)
174 /* If the write offset == read offset, there's nothing left in the
175 * ring-buffer. Break from the loop and give what has been written.
177 const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
178 if(woffset == roffset) break;
180 /* If the write offset is behind the read offset, the readable
181 * portion wrapped around. Just read up to the end of the buffer in
182 * that case, otherwise read up to the write offset. Also limit the
183 * amount to copy given how much is remaining to write.
185 size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
186 todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
188 /* Copy from the ring buffer to the provided output buffer. Wrap
189 * the resulting read offset if it reached the end of the ring-
190 * buffer.
192 memcpy(data, &mBufferData[roffset], todo);
193 data = static_cast<ALbyte*>(data) + todo;
194 got += static_cast<ALsizei>(todo);
196 roffset += todo;
197 if(roffset == mBufferDataSize)
198 roffset = 0;
200 /* Finally, store the updated read offset, and return how many bytes
201 * have been written.
203 mReadPos.store(roffset, std::memory_order_release);
205 return got;
208 bool prepare()
210 alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this);
211 alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
212 if(ALenum err{alGetError()})
214 fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
215 return false;
217 return true;
220 bool update()
222 ALenum state;
223 ALint pos;
224 alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
225 alGetSourcei(mSource, AL_SOURCE_STATE, &state);
227 const size_t frame_size{static_cast<ALuint>(mSfInfo.channels) * sizeof(float)};
228 size_t woffset{mWritePos.load(std::memory_order_acquire)};
229 if(state != AL_INITIAL)
231 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
232 const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
233 roffset};
234 /* For a stopped (underrun) source, the current playback offset is
235 * the current decoder offset excluding the readable buffered data.
236 * For a playing/paused source, it's the source's offset including
237 * the playback offset the source was started with.
239 const size_t curtime{((state==AL_STOPPED) ? (mDecoderOffset-readable) / frame_size
240 : (static_cast<ALuint>(pos) + mStartOffset/frame_size))
241 / static_cast<ALuint>(mSfInfo.samplerate)};
242 printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
244 else
245 fputs("Starting...", stdout);
246 fflush(stdout);
248 while(!sf_error(mSndfile))
250 size_t read_bytes;
251 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
252 if(roffset > woffset)
254 /* Note that the ring buffer's writable space is one byte less
255 * than the available area because the write offset ending up
256 * at the read offset would be interpreted as being empty
257 * instead of full.
259 const size_t writable{roffset-woffset-1};
260 if(writable < frame_size) break;
262 sf_count_t num_frames{sf_readf_float(mSndfile,
263 reinterpret_cast<float*>(&mBufferData[woffset]),
264 static_cast<sf_count_t>(writable/frame_size))};
265 if(num_frames < 1) break;
267 read_bytes = static_cast<size_t>(num_frames) * frame_size;
268 woffset += read_bytes;
270 else
272 /* If the read offset is at or behind the write offset, the
273 * writeable area (might) wrap around. Make sure the sample
274 * data can fit, and calculate how much can go in front before
275 * wrapping.
277 const size_t writable{!roffset ? mBufferDataSize-woffset-1 :
278 (mBufferDataSize-woffset)};
279 if(writable < frame_size) break;
281 sf_count_t num_frames{sf_readf_float(mSndfile,
282 reinterpret_cast<float*>(&mBufferData[woffset]),
283 static_cast<sf_count_t>(writable/frame_size))};
284 if(num_frames < 1) break;
286 read_bytes = static_cast<size_t>(num_frames) * frame_size;
287 woffset += read_bytes;
288 if(woffset == mBufferDataSize)
289 woffset = 0;
291 mWritePos.store(woffset, std::memory_order_release);
292 mDecoderOffset += read_bytes;
295 if(state != AL_PLAYING && state != AL_PAUSED)
297 /* If the source is not playing or paused, it either underrun
298 * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
299 * ring buffer is empty, it's done, otherwise play the source with
300 * what's available.
302 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
303 const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
304 roffset};
305 if(readable == 0)
306 return false;
308 /* Store the playback offset that the source will start reading
309 * from, so it can be tracked during playback.
311 mStartOffset = mDecoderOffset - readable;
312 alSourcePlay(mSource);
313 if(alGetError() != AL_NO_ERROR)
314 return false;
316 return true;
320 } // namespace
322 int main(int argc, char **argv)
324 /* A simple RAII container for OpenAL startup and shutdown. */
325 struct AudioManager {
326 AudioManager(char ***argv_, int *argc_)
328 if(InitAL(argv_, argc_) != 0)
329 throw std::runtime_error{"Failed to initialize OpenAL"};
331 ~AudioManager() { CloseAL(); }
334 /* Print out usage if no arguments were specified */
335 if(argc < 2)
337 fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
338 return 1;
341 argv++; argc--;
342 AudioManager almgr{&argv, &argc};
344 if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
346 fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
347 return 1;
350 alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
351 alGetProcAddress("alBufferCallbackSOFT"));
353 ALCint refresh{25};
354 alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
356 std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
358 /* Play each file listed on the command line */
359 for(int i{0};i < argc;++i)
361 if(!player->open(argv[i]))
362 continue;
364 /* Get the name portion, without the path, for display. */
365 const char *namepart{strrchr(argv[i], '/')};
366 if(namepart || (namepart=strrchr(argv[i], '\\')))
367 ++namepart;
368 else
369 namepart = argv[i];
371 printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
372 player->mSfInfo.samplerate);
373 fflush(stdout);
375 if(!player->prepare())
377 player->close();
378 continue;
381 while(player->update())
382 std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
383 putc('\n', stdout);
385 /* All done with this file. Close it and go to the next */
386 player->close();
388 /* All done. */
389 printf("Done.\n");
391 return 0;