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
25 /* This file contains a streaming audio player using a callback buffer. */
45 #include "common/alhelpers.h"
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
);
62 using std::chrono::seconds
;
63 using std::chrono::nanoseconds
;
65 LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT
;
68 /* A lockless ring-buffer (supports single-provider, single-consumer
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};
76 /* The buffer to get the callback, and source to play with. */
77 ALuint mBuffer
{0}, mSource
{0};
78 size_t mStartOffset
{0};
80 /* Handle for the audio file to decode. */
81 SNDFILE
*mSndfile
{nullptr};
83 size_t mDecoderOffset
{0};
85 /* The format of the callback samples. */
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()})
96 alDeleteBuffers(1, &mBuffer
);
97 throw std::runtime_error
{"alGenSources failed"};
102 alDeleteSources(1, &mSource
);
103 alDeleteBuffers(1, &mBuffer
);
112 alSourceRewind(mSource
);
113 alSourcei(mSource
, AL_BUFFER
, 0);
119 bool open(const char *filename
)
123 /* Open the file and figure out the OpenAL format. */
124 mSndfile
= sf_open(filename
, SFM_READ
, &mSfInfo
);
127 fprintf(stderr
, "Could not open audio in %s: %s\n", filename
, sf_strerror(mSndfile
));
132 if(mSfInfo
.channels
== 1)
133 mFormat
= AL_FORMAT_MONO_FLOAT32
;
134 else if(mSfInfo
.channels
== 2)
135 mFormat
= AL_FORMAT_STEREO_FLOAT32
;
136 else if(mSfInfo
.channels
== 3)
138 if(sf_command(mSndfile
, SFC_WAVEX_GET_AMBISONIC
, NULL
, 0) == SF_AMBISONIC_B_FORMAT
)
139 mFormat
= AL_FORMAT_BFORMAT2D_FLOAT32
;
141 else if(mSfInfo
.channels
== 4)
143 if(sf_command(mSndfile
, SFC_WAVEX_GET_AMBISONIC
, NULL
, 0) == SF_AMBISONIC_B_FORMAT
)
144 mFormat
= AL_FORMAT_BFORMAT3D_FLOAT32
;
148 fprintf(stderr
, "Unsupported channel count: %d\n", mSfInfo
.channels
);
155 /* Set a 1s ring buffer size. */
156 mBufferDataSize
= static_cast<ALuint
>(mSfInfo
.samplerate
*mSfInfo
.channels
) * sizeof(float);
157 mBufferData
.reset(new ALbyte
[mBufferDataSize
]);
158 mReadPos
.store(0, std::memory_order_relaxed
);
159 mWritePos
.store(0, std::memory_order_relaxed
);
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.
170 static ALsizei AL_APIENTRY
bufferCallbackC(void *userptr
, void *data
, ALsizei size
)
171 { return static_cast<StreamPlayer
*>(userptr
)->bufferCallback(data
, size
); }
172 ALsizei
bufferCallback(void *data
, ALsizei size
)
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
183 size_t roffset
{mReadPos
.load(std::memory_order_acquire
)};
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.
189 const size_t woffset
{mWritePos
.load(std::memory_order_relaxed
)};
190 if(woffset
== roffset
) break;
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.
197 size_t todo
{((woffset
< roffset
) ? mBufferDataSize
: woffset
) - roffset
};
198 todo
= std::min
<size_t>(todo
, static_cast<ALuint
>(size
-got
));
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-
204 memcpy(data
, &mBufferData
[roffset
], todo
);
205 data
= static_cast<ALbyte
*>(data
) + todo
;
206 got
+= static_cast<ALsizei
>(todo
);
209 if(roffset
== mBufferDataSize
)
212 /* Finally, store the updated read offset, and return how many bytes
215 mReadPos
.store(roffset
, std::memory_order_release
);
222 alBufferCallbackSOFT(mBuffer
, mFormat
, mSfInfo
.samplerate
, bufferCallbackC
, this, 0);
223 alSourcei(mSource
, AL_BUFFER
, static_cast<ALint
>(mBuffer
));
224 if(ALenum err
{alGetError()})
226 fprintf(stderr
, "Failed to set callback: %s (0x%04x)\n", alGetString(err
), err
);
236 alGetSourcei(mSource
, AL_SAMPLE_OFFSET
, &pos
);
237 alGetSourcei(mSource
, AL_SOURCE_STATE
, &state
);
239 const size_t frame_size
{static_cast<ALuint
>(mSfInfo
.channels
) * sizeof(float)};
240 size_t woffset
{mWritePos
.load(std::memory_order_acquire
)};
241 if(state
!= AL_INITIAL
)
243 const size_t roffset
{mReadPos
.load(std::memory_order_relaxed
)};
244 const size_t readable
{((woffset
>= roffset
) ? woffset
: (mBufferDataSize
+woffset
)) -
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.
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
);
257 fputs("Starting...", stdout
);
260 while(!sf_error(mSndfile
))
263 const size_t roffset
{mReadPos
.load(std::memory_order_relaxed
)};
264 if(roffset
> woffset
)
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
271 const size_t writable
{roffset
-woffset
-1};
272 if(writable
< frame_size
) break;
274 sf_count_t num_frames
{sf_readf_float(mSndfile
,
275 reinterpret_cast<float*>(&mBufferData
[woffset
]),
276 static_cast<sf_count_t
>(writable
/frame_size
))};
277 if(num_frames
< 1) break;
279 read_bytes
= static_cast<size_t>(num_frames
) * frame_size
;
280 woffset
+= read_bytes
;
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
289 const size_t writable
{!roffset
? mBufferDataSize
-woffset
-1 :
290 (mBufferDataSize
-woffset
)};
291 if(writable
< frame_size
) break;
293 sf_count_t num_frames
{sf_readf_float(mSndfile
,
294 reinterpret_cast<float*>(&mBufferData
[woffset
]),
295 static_cast<sf_count_t
>(writable
/frame_size
))};
296 if(num_frames
< 1) break;
298 read_bytes
= static_cast<size_t>(num_frames
) * frame_size
;
299 woffset
+= read_bytes
;
300 if(woffset
== mBufferDataSize
)
303 mWritePos
.store(woffset
, std::memory_order_release
);
304 mDecoderOffset
+= read_bytes
;
307 if(state
!= AL_PLAYING
&& state
!= AL_PAUSED
)
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
314 const size_t roffset
{mReadPos
.load(std::memory_order_relaxed
)};
315 const size_t readable
{((woffset
>= roffset
) ? woffset
: (mBufferDataSize
+woffset
)) -
320 /* Store the playback offset that the source will start reading
321 * from, so it can be tracked during playback.
323 mStartOffset
= mDecoderOffset
- readable
;
324 alSourcePlay(mSource
);
325 if(alGetError() != AL_NO_ERROR
)
334 int main(int argc
, char **argv
)
336 /* A simple RAII container for OpenAL startup and shutdown. */
337 struct AudioManager
{
338 AudioManager(char ***argv_
, int *argc_
)
340 if(InitAL(argv_
, argc_
) != 0)
341 throw std::runtime_error
{"Failed to initialize OpenAL"};
343 ~AudioManager() { CloseAL(); }
346 /* Print out usage if no arguments were specified */
349 fprintf(stderr
, "Usage: %s [-device <name>] <filenames...>\n", argv
[0]);
354 AudioManager almgr
{&argv
, &argc
};
356 if(!alIsExtensionPresent("AL_SOFTX_callback_buffer"))
358 fprintf(stderr
, "AL_SOFT_callback_buffer extension not available\n");
362 alBufferCallbackSOFT
= reinterpret_cast<LPALBUFFERCALLBACKSOFT
>(
363 alGetProcAddress("alBufferCallbackSOFT"));
366 alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH
, 1, &refresh
);
368 std::unique_ptr
<StreamPlayer
> player
{new StreamPlayer
{}};
370 /* Play each file listed on the command line */
371 for(int i
{0};i
< argc
;++i
)
373 if(!player
->open(argv
[i
]))
376 /* Get the name portion, without the path, for display. */
377 const char *namepart
{strrchr(argv
[i
], '/')};
378 if(namepart
|| (namepart
=strrchr(argv
[i
], '\\')))
383 printf("Playing: %s (%s, %dhz)\n", namepart
, FormatName(player
->mFormat
),
384 player
->mSfInfo
.samplerate
);
387 if(!player
->prepare())
393 while(player
->update())
394 std::this_thread::sleep_for(nanoseconds
{seconds
{1}} / refresh
);
397 /* All done with this file. Close it and go to the next */