Reorganize some convolution fields
[openal-soft.git] / examples / alstreamcb.cpp
blob8fb1f102e34a0455f4062b5fc1d9528ca3d4cabb
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"
44 #include "common/alhelpers.h"
47 #ifndef AL_SOFT_callback_buffer
48 #define AL_SOFT_callback_buffer
49 typedef unsigned int ALbitfieldSOFT;
50 #define AL_BUFFER_CALLBACK_FUNCTION_SOFT 0x19A0
51 #define AL_BUFFER_CALLBACK_USER_PARAM_SOFT 0x19A1
52 typedef ALsizei (AL_APIENTRY*LPALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numsamples);
53 typedef void (AL_APIENTRY*LPALBUFFERCALLBACKSOFT)(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags);
54 typedef void (AL_APIENTRY*LPALGETBUFFERPTRSOFT)(ALuint buffer, ALenum param, ALvoid **value);
55 typedef void (AL_APIENTRY*LPALGETBUFFER3PTRSOFT)(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3);
56 typedef void (AL_APIENTRY*LPALGETBUFFERPTRVSOFT)(ALuint buffer, ALenum param, ALvoid **values);
57 #endif
59 namespace {
61 using std::chrono::seconds;
62 using std::chrono::nanoseconds;
64 LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
66 struct StreamPlayer {
67 /* A lockless ring-buffer (supports single-provider, single-consumer
68 * operation).
70 std::unique_ptr<ALbyte[]> mBufferData;
71 size_t mBufferDataSize{0};
72 std::atomic<size_t> mReadPos{0};
73 std::atomic<size_t> mWritePos{0};
75 /* The buffer to get the callback, and source to play with. */
76 ALuint mBuffer{0}, mSource{0};
77 size_t mStartOffset{0};
79 /* Handle for the audio file to decode. */
80 SNDFILE *mSndfile{nullptr};
81 SF_INFO mSfInfo{};
82 size_t mDecoderOffset{0};
84 /* The format of the callback samples. */
85 ALenum mFormat;
87 StreamPlayer()
89 alGenBuffers(1, &mBuffer);
90 if(ALenum err{alGetError()})
91 throw std::runtime_error{"alGenBuffers failed"};
92 alGenSources(1, &mSource);
93 if(ALenum err{alGetError()})
95 alDeleteBuffers(1, &mBuffer);
96 throw std::runtime_error{"alGenSources failed"};
99 ~StreamPlayer()
101 alDeleteSources(1, &mSource);
102 alDeleteBuffers(1, &mBuffer);
103 if(mSndfile)
104 sf_close(mSndfile);
107 void close()
109 if(mSndfile)
111 alSourceRewind(mSource);
112 alSourcei(mSource, AL_BUFFER, 0);
113 sf_close(mSndfile);
114 mSndfile = nullptr;
118 bool open(const char *filename)
120 close();
122 /* Open the file and figure out the OpenAL format. */
123 mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
124 if(!mSndfile)
126 fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
127 return false;
130 mFormat = AL_NONE;
131 if(mSfInfo.channels == 1)
132 mFormat = AL_FORMAT_MONO16;
133 else if(mSfInfo.channels == 2)
134 mFormat = AL_FORMAT_STEREO16;
135 else
137 fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
138 sf_close(mSndfile);
139 mSndfile = nullptr;
141 return false;
144 /* Set a 1s ring buffer size. */
145 mBufferDataSize = static_cast<ALuint>(mSfInfo.samplerate*mSfInfo.channels) * sizeof(short);
146 mBufferData.reset(new ALbyte[mBufferDataSize]);
147 mReadPos.store(0, std::memory_order_relaxed);
148 mWritePos.store(0, std::memory_order_relaxed);
149 mDecoderOffset = 0;
151 return true;
154 /* The actual C-style callback just forwards to the non-static method. Not
155 * strictly needed and the compiler will optimize it to a normal function,
156 * but it allows the callback implementation to have a nice 'this' pointer
157 * with normal member access.
159 static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
160 { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
161 ALsizei bufferCallback(void *data, ALsizei size)
163 /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
164 * no allocations or deallocations, no I/O, no page faults, or calls to
165 * functions that could do these things (this includes calling to
166 * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
167 * unexpectedly stall this call since the audio has to get to the
168 * device on time.
170 ALsizei got{0};
172 size_t roffset{mReadPos.load(std::memory_order_acquire)};
173 while(got < size)
175 /* If the write offset == read offset, there's nothing left in the
176 * ring-buffer. Break from the loop and give what has been written.
178 const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
179 if(woffset == roffset) break;
181 /* If the write offset is behind the read offset, the readable
182 * portion wrapped around. Just read up to the end of the buffer in
183 * that case, otherwise read up to the write offset. Also limit the
184 * amount to copy given how much is remaining to write.
186 size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
187 todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
189 /* Copy from the ring buffer to the provided output buffer. Wrap
190 * the resulting read offset if it reached the end of the ring-
191 * buffer.
193 memcpy(data, &mBufferData[roffset], todo);
194 data = static_cast<ALbyte*>(data) + todo;
195 got += static_cast<ALsizei>(todo);
197 roffset += todo;
198 if(roffset == mBufferDataSize)
199 roffset = 0;
201 /* Finally, store the updated read offset, and return how many bytes
202 * have been written.
204 mReadPos.store(roffset, std::memory_order_release);
206 return got;
209 bool prepare()
211 alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this, 0);
212 alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
213 if(ALenum err{alGetError()})
215 fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
216 return false;
218 return true;
221 bool update()
223 ALenum state;
224 ALint pos;
225 alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
226 alGetSourcei(mSource, AL_SOURCE_STATE, &state);
228 const size_t frame_size{static_cast<ALuint>(mSfInfo.channels) * sizeof(short)};
229 size_t woffset{mWritePos.load(std::memory_order_acquire)};
230 if(state != AL_INITIAL)
232 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
233 const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
234 roffset};
235 /* For a stopped (underrun) source, the current playback offset is
236 * the current decoder offset excluding the readable buffered data.
237 * For a playing/paused source, it's the source's offset including
238 * the playback offset the source was started with.
240 const size_t curtime{((state==AL_STOPPED) ? (mDecoderOffset-readable) / frame_size
241 : (static_cast<ALuint>(pos) + mStartOffset/frame_size))
242 / static_cast<ALuint>(mSfInfo.samplerate)};
243 printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
245 else
246 fputs("Starting...", stdout);
247 fflush(stdout);
249 while(!sf_error(mSndfile))
251 size_t read_bytes;
252 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
253 if(roffset > woffset)
255 /* Note that the ring buffer's writable space is one byte less
256 * than the available area because the write offset ending up
257 * at the read offset would be interpreted as being empty
258 * instead of full.
260 const size_t writable{roffset-woffset-1};
261 if(writable < frame_size) break;
263 sf_count_t num_frames{sf_readf_short(mSndfile,
264 reinterpret_cast<short*>(&mBufferData[woffset]),
265 static_cast<sf_count_t>(writable/frame_size))};
266 if(num_frames < 1) break;
268 read_bytes = static_cast<size_t>(num_frames) * frame_size;
269 woffset += read_bytes;
271 else
273 /* If the read offset is at or behind the write offset, the
274 * writeable area (might) wrap around. Make sure the sample
275 * data can fit, and calculate how much can go in front before
276 * wrapping.
278 const size_t writable{!roffset ? mBufferDataSize-woffset-1 :
279 (mBufferDataSize-woffset)};
280 if(writable < frame_size) break;
282 sf_count_t num_frames{sf_readf_short(mSndfile,
283 reinterpret_cast<short*>(&mBufferData[woffset]),
284 static_cast<sf_count_t>(writable/frame_size))};
285 if(num_frames < 1) break;
287 read_bytes = static_cast<size_t>(num_frames) * frame_size;
288 woffset += read_bytes;
289 if(woffset == mBufferDataSize)
290 woffset = 0;
292 mWritePos.store(woffset, std::memory_order_release);
293 mDecoderOffset += read_bytes;
296 if(state != AL_PLAYING && state != AL_PAUSED)
298 /* If the source is not playing or paused, it either underrun
299 * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
300 * ring buffer is empty, it's done, otherwise play the source with
301 * what's available.
303 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
304 const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
305 roffset};
306 if(readable == 0)
307 return false;
309 /* Store the playback offset that the source will start reading
310 * from, so it can be tracked during playback.
312 mStartOffset = mDecoderOffset - readable;
313 alSourcePlay(mSource);
314 if(alGetError() != AL_NO_ERROR)
315 return false;
317 return true;
321 } // namespace
323 int main(int argc, char **argv)
325 /* A simple RAII container for OpenAL startup and shutdown. */
326 struct AudioManager {
327 AudioManager(char ***argv_, int *argc_)
329 if(InitAL(argv_, argc_) != 0)
330 throw std::runtime_error{"Failed to initialize OpenAL"};
332 ~AudioManager() { CloseAL(); }
335 /* Print out usage if no arguments were specified */
336 if(argc < 2)
338 fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
339 return 1;
342 argv++; argc--;
343 AudioManager almgr{&argv, &argc};
345 if(!alIsExtensionPresent("AL_SOFTX_callback_buffer"))
347 fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
348 return 1;
351 alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
352 alGetProcAddress("alBufferCallbackSOFT"));
354 ALCint refresh{25};
355 alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
357 std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
359 /* Play each file listed on the command line */
360 for(int i{0};i < argc;++i)
362 if(!player->open(argv[i]))
363 continue;
365 /* Get the name portion, without the path, for display. */
366 const char *namepart{strrchr(argv[i], '/')};
367 if(namepart || (namepart=strrchr(argv[i], '\\')))
368 ++namepart;
369 else
370 namepart = argv[i];
372 printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
373 player->mSfInfo.samplerate);
374 fflush(stdout);
376 if(!player->prepare())
378 player->close();
379 continue;
382 while(player->update())
383 std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
384 putc('\n', stdout);
386 /* All done with this file. Close it and go to the next */
387 player->close();
389 /* All done. */
390 printf("Done.\n");
392 return 0;