1 /*
2  * OpenAL Callback-based Stream Example
3  *
4  * Copyright (c) 2020 by Chris Robinson <chris.kcat@gmail.com>
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 /* This file contains a streaming audio player using a callback buffer. */
26 
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 
31 #include <atomic>
32 #include <chrono>
33 #include <memory>
34 #include <stdexcept>
35 #include <string>
36 #include <thread>
37 #include <vector>
38 
39 #include "sndfile.h"
40 
41 #include "AL/al.h"
42 #include "AL/alc.h"
43 #include "AL/alext.h"
44 
45 #include "common/alhelpers.h"
46 
47 
48 #ifndef AL_SOFT_callback_buffer
49 #define AL_SOFT_callback_buffer
50 typedef unsigned int ALbitfieldSOFT;
51 #define AL_BUFFER_CALLBACK_FUNCTION_SOFT         0x19A0
52 #define AL_BUFFER_CALLBACK_USER_PARAM_SOFT       0x19A1
53 typedef ALsizei (AL_APIENTRY*LPALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numsamples);
54 typedef void (AL_APIENTRY*LPALBUFFERCALLBACKSOFT)(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags);
55 typedef void (AL_APIENTRY*LPALGETBUFFERPTRSOFT)(ALuint buffer, ALenum param, ALvoid **value);
56 typedef void (AL_APIENTRY*LPALGETBUFFER3PTRSOFT)(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3);
57 typedef void (AL_APIENTRY*LPALGETBUFFERPTRVSOFT)(ALuint buffer, ALenum param, ALvoid **values);
58 #endif
59 
60 namespace {
61 
62 using std::chrono::seconds;
63 using std::chrono::nanoseconds;
64 
65 LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
66 
67 struct StreamPlayer {
68     /* A lockless ring-buffer (supports single-provider, single-consumer
69      * operation).
70      */
71     std::unique_ptr<ALbyte[]> mBufferData;
72     size_t mBufferDataSize{0};
73     std::atomic<size_t> mReadPos{0};
74     std::atomic<size_t> mWritePos{0};
75 
76     /* The buffer to get the callback, and source to play with. */
77     ALuint mBuffer{0}, mSource{0};
78     size_t mStartOffset{0};
79 
80     /* Handle for the audio file to decode. */
81     SNDFILE *mSndfile{nullptr};
82     SF_INFO mSfInfo{};
83     size_t mDecoderOffset{0};
84 
85     /* The format of the callback samples. */
86     ALenum mFormat;
87 
StreamPlayer__anona21ac2e40111::StreamPlayer88     StreamPlayer()
89     {
90         alGenBuffers(1, &mBuffer);
91         if(ALenum err{alGetError()})
92             throw std::runtime_error{"alGenBuffers failed"};
93         alGenSources(1, &mSource);
94         if(ALenum err{alGetError()})
95         {
96             alDeleteBuffers(1, &mBuffer);
97             throw std::runtime_error{"alGenSources failed"};
98         }
99     }
~StreamPlayer__anona21ac2e40111::StreamPlayer100     ~StreamPlayer()
101     {
102         alDeleteSources(1, &mSource);
103         alDeleteBuffers(1, &mBuffer);
104         if(mSndfile)
105             sf_close(mSndfile);
106     }
107 
close__anona21ac2e40111::StreamPlayer108     void close()
109     {
110         if(mSndfile)
111         {
112             alSourceRewind(mSource);
113             alSourcei(mSource, AL_BUFFER, 0);
114             sf_close(mSndfile);
115             mSndfile = nullptr;
116         }
117     }
118 
open__anona21ac2e40111::StreamPlayer119     bool open(const char *filename)
120     {
121         close();
122 
123         /* Open the file and figure out the OpenAL format. */
124         mSndfile = sf_open(filename, SFM_READ, &mSfInfo);
125         if(!mSndfile)
126         {
127             fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(mSndfile));
128             return false;
129         }
130 
131         mFormat = AL_NONE;
132         if(mSfInfo.channels == 1)
133             mFormat = AL_FORMAT_MONO16;
134         else if(mSfInfo.channels == 2)
135             mFormat = AL_FORMAT_STEREO16;
136         else if(mSfInfo.channels == 3)
137         {
138             if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
139                 mFormat = AL_FORMAT_BFORMAT2D_16;
140         }
141         else if(mSfInfo.channels == 4)
142         {
143             if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
144                 mFormat = AL_FORMAT_BFORMAT3D_16;
145         }
146         if(!mFormat)
147         {
148             fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
149             sf_close(mSndfile);
150             mSndfile = nullptr;
151 
152             return false;
153         }
154 
155         /* Set a 1s ring buffer size. */
156         mBufferDataSize = static_cast<ALuint>(mSfInfo.samplerate*mSfInfo.channels) * sizeof(short);
157         mBufferData.reset(new ALbyte[mBufferDataSize]);
158         mReadPos.store(0, std::memory_order_relaxed);
159         mWritePos.store(0, std::memory_order_relaxed);
160         mDecoderOffset = 0;
161 
162         return true;
163     }
164 
165     /* The actual C-style callback just forwards to the non-static method. Not
166      * strictly needed and the compiler will optimize it to a normal function,
167      * but it allows the callback implementation to have a nice 'this' pointer
168      * with normal member access.
169      */
bufferCallbackC__anona21ac2e40111::StreamPlayer170     static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size)
171     { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
bufferCallback__anona21ac2e40111::StreamPlayer172     ALsizei bufferCallback(void *data, ALsizei size)
173     {
174         /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
175          * no allocations or deallocations, no I/O, no page faults, or calls to
176          * functions that could do these things (this includes calling to
177          * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
178          * unexpectedly stall this call since the audio has to get to the
179          * device on time.
180          */
181         ALsizei got{0};
182 
183         size_t roffset{mReadPos.load(std::memory_order_acquire)};
184         while(got < size)
185         {
186             /* If the write offset == read offset, there's nothing left in the
187              * ring-buffer. Break from the loop and give what has been written.
188              */
189             const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
190             if(woffset == roffset) break;
191 
192             /* If the write offset is behind the read offset, the readable
193              * portion wrapped around. Just read up to the end of the buffer in
194              * that case, otherwise read up to the write offset. Also limit the
195              * amount to copy given how much is remaining to write.
196              */
197             size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset};
198             todo = std::min<size_t>(todo, static_cast<ALuint>(size-got));
199 
200             /* Copy from the ring buffer to the provided output buffer. Wrap
201              * the resulting read offset if it reached the end of the ring-
202              * buffer.
203              */
204             memcpy(data, &mBufferData[roffset], todo);
205             data = static_cast<ALbyte*>(data) + todo;
206             got += static_cast<ALsizei>(todo);
207 
208             roffset += todo;
209             if(roffset == mBufferDataSize)
210                 roffset = 0;
211         }
212         /* Finally, store the updated read offset, and return how many bytes
213          * have been written.
214          */
215         mReadPos.store(roffset, std::memory_order_release);
216 
217         return got;
218     }
219 
prepare__anona21ac2e40111::StreamPlayer220     bool prepare()
221     {
222         alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this, 0);
223         alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
224         if(ALenum err{alGetError()})
225         {
226             fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
227             return false;
228         }
229         return true;
230     }
231 
update__anona21ac2e40111::StreamPlayer232     bool update()
233     {
234         ALenum state;
235         ALint pos;
236         alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
237         alGetSourcei(mSource, AL_SOURCE_STATE, &state);
238 
239         const size_t frame_size{static_cast<ALuint>(mSfInfo.channels) * sizeof(short)};
240         size_t woffset{mWritePos.load(std::memory_order_acquire)};
241         if(state != AL_INITIAL)
242         {
243             const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
244             const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
245                 roffset};
246             /* For a stopped (underrun) source, the current playback offset is
247              * the current decoder offset excluding the readable buffered data.
248              * For a playing/paused source, it's the source's offset including
249              * the playback offset the source was started with.
250              */
251             const size_t curtime{((state==AL_STOPPED) ? (mDecoderOffset-readable) / frame_size
252                 : (static_cast<ALuint>(pos) + mStartOffset/frame_size))
253                 / static_cast<ALuint>(mSfInfo.samplerate)};
254             printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferDataSize);
255         }
256         else
257             fputs("Starting...", stdout);
258         fflush(stdout);
259 
260         while(!sf_error(mSndfile))
261         {
262             size_t read_bytes;
263             const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
264             if(roffset > woffset)
265             {
266                 /* Note that the ring buffer's writable space is one byte less
267                  * than the available area because the write offset ending up
268                  * at the read offset would be interpreted as being empty
269                  * instead of full.
270                  */
271                 const size_t writable{roffset-woffset-1};
272                 if(writable < frame_size) break;
273 
274                 sf_count_t num_frames{sf_readf_short(mSndfile,
275                     reinterpret_cast<short*>(&mBufferData[woffset]),
276                     static_cast<sf_count_t>(writable/frame_size))};
277                 if(num_frames < 1) break;
278 
279                 read_bytes = static_cast<size_t>(num_frames) * frame_size;
280                 woffset += read_bytes;
281             }
282             else
283             {
284                 /* If the read offset is at or behind the write offset, the
285                  * writeable area (might) wrap around. Make sure the sample
286                  * data can fit, and calculate how much can go in front before
287                  * wrapping.
288                  */
289                 const size_t writable{!roffset ? mBufferDataSize-woffset-1 :
290                     (mBufferDataSize-woffset)};
291                 if(writable < frame_size) break;
292 
293                 sf_count_t num_frames{sf_readf_short(mSndfile,
294                     reinterpret_cast<short*>(&mBufferData[woffset]),
295                     static_cast<sf_count_t>(writable/frame_size))};
296                 if(num_frames < 1) break;
297 
298                 read_bytes = static_cast<size_t>(num_frames) * frame_size;
299                 woffset += read_bytes;
300                 if(woffset == mBufferDataSize)
301                     woffset = 0;
302             }
303             mWritePos.store(woffset, std::memory_order_release);
304             mDecoderOffset += read_bytes;
305         }
306 
307         if(state != AL_PLAYING && state != AL_PAUSED)
308         {
309             /* If the source is not playing or paused, it either underrun
310              * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
311              * ring buffer is empty, it's done, otherwise play the source with
312              * what's available.
313              */
314             const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
315             const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) -
316                 roffset};
317             if(readable == 0)
318                 return false;
319 
320             /* Store the playback offset that the source will start reading
321              * from, so it can be tracked during playback.
322              */
323             mStartOffset = mDecoderOffset - readable;
324             alSourcePlay(mSource);
325             if(alGetError() != AL_NO_ERROR)
326                 return false;
327         }
328         return true;
329     }
330 };
331 
332 } // namespace
333 
main(int argc,char ** argv)334 int main(int argc, char **argv)
335 {
336     /* A simple RAII container for OpenAL startup and shutdown. */
337     struct AudioManager {
338         AudioManager(char ***argv_, int *argc_)
339         {
340             if(InitAL(argv_, argc_) != 0)
341                 throw std::runtime_error{"Failed to initialize OpenAL"};
342         }
343         ~AudioManager() { CloseAL(); }
344     };
345 
346     /* Print out usage if no arguments were specified */
347     if(argc < 2)
348     {
349         fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
350         return 1;
351     }
352 
353     argv++; argc--;
354     AudioManager almgr{&argv, &argc};
355 
356     if(!alIsExtensionPresent("AL_SOFTX_callback_buffer"))
357     {
358         fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
359         return 1;
360     }
361 
362     alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
363         alGetProcAddress("alBufferCallbackSOFT"));
364 
365     ALCint refresh{25};
366     alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
367 
368     std::unique_ptr<StreamPlayer> player{new StreamPlayer{}};
369 
370     /* Play each file listed on the command line */
371     for(int i{0};i < argc;++i)
372     {
373         if(!player->open(argv[i]))
374             continue;
375 
376         /* Get the name portion, without the path, for display. */
377         const char *namepart{strrchr(argv[i], '/')};
378         if(namepart || (namepart=strrchr(argv[i], '\\')))
379             ++namepart;
380         else
381             namepart = argv[i];
382 
383         printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->mFormat),
384             player->mSfInfo.samplerate);
385         fflush(stdout);
386 
387         if(!player->prepare())
388         {
389             player->close();
390             continue;
391         }
392 
393         while(player->update())
394             std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
395         putc('\n', stdout);
396 
397         /* All done with this file. Close it and go to the next */
398         player->close();
399     }
400     /* All done. */
401     printf("Done.\n");
402 
403     return 0;
404 }
405