Replace a couple loops with algorithms
[openal-soft.git] / examples / alstreamcb.cpp
blobdae340482ef5593b40cd6a48e048fbd8516dd693
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. */
28 #include <algorithm>
29 #include <atomic>
30 #include <cassert>
31 #include <chrono>
32 #include <cstddef>
33 #include <cstdlib>
34 #include <cstdio>
35 #include <cstring>
36 #include <memory>
37 #include <stdexcept>
38 #include <string>
39 #include <string_view>
40 #include <thread>
41 #include <vector>
43 #include "sndfile.h"
45 #include "AL/al.h"
46 #include "AL/alc.h"
47 #include "AL/alext.h"
49 #include "alspan.h"
50 #include "alstring.h"
51 #include "common/alhelpers.h"
53 #include "win_main_utf8.h"
56 namespace {
58 using std::chrono::seconds;
59 using std::chrono::nanoseconds;
61 LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT;
63 struct StreamPlayer {
64 /* A lockless ring-buffer (supports single-provider, single-consumer
65 * operation).
67 std::vector<std::byte> mBufferData;
68 std::atomic<size_t> mReadPos{0};
69 std::atomic<size_t> mWritePos{0};
70 size_t mSamplesPerBlock{1};
71 size_t mBytesPerBlock{1};
73 enum class SampleType {
74 Int16, Float, IMA4, MSADPCM
76 SampleType mSampleFormat{SampleType::Int16};
78 /* The buffer to get the callback, and source to play with. */
79 ALuint mBuffer{0}, mSource{0};
80 size_t mStartOffset{0};
82 /* Handle for the audio file to decode. */
83 SNDFILE *mSndfile{nullptr};
84 SF_INFO mSfInfo{};
85 size_t mDecoderOffset{0};
87 /* The format of the callback samples. */
88 ALenum mFormat{};
90 StreamPlayer()
92 alGenBuffers(1, &mBuffer);
93 if(alGetError() != AL_NO_ERROR)
94 throw std::runtime_error{"alGenBuffers failed"};
95 alGenSources(1, &mSource);
96 if(alGetError() != AL_NO_ERROR)
98 alDeleteBuffers(1, &mBuffer);
99 throw std::runtime_error{"alGenSources failed"};
102 ~StreamPlayer()
104 alDeleteSources(1, &mSource);
105 alDeleteBuffers(1, &mBuffer);
106 if(mSndfile)
107 sf_close(mSndfile);
110 void close()
112 if(mSamplesPerBlock > 1)
113 alBufferi(mBuffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
115 if(mSndfile)
117 alSourceRewind(mSource);
118 alSourcei(mSource, AL_BUFFER, 0);
119 sf_close(mSndfile);
120 mSndfile = nullptr;
124 bool open(const std::string &filename)
126 close();
128 /* Open the file and figure out the OpenAL format. */
129 mSndfile = sf_open(filename.c_str(), SFM_READ, &mSfInfo);
130 if(!mSndfile)
132 fprintf(stderr, "Could not open audio in %s: %s\n", filename.c_str(),
133 sf_strerror(mSndfile));
134 return false;
137 switch((mSfInfo.format&SF_FORMAT_SUBMASK))
139 case SF_FORMAT_PCM_24:
140 case SF_FORMAT_PCM_32:
141 case SF_FORMAT_FLOAT:
142 case SF_FORMAT_DOUBLE:
143 case SF_FORMAT_VORBIS:
144 case SF_FORMAT_OPUS:
145 case SF_FORMAT_ALAC_20:
146 case SF_FORMAT_ALAC_24:
147 case SF_FORMAT_ALAC_32:
148 case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
149 case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
150 case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
151 if(alIsExtensionPresent("AL_EXT_FLOAT32"))
152 mSampleFormat = SampleType::Float;
153 break;
154 case SF_FORMAT_IMA_ADPCM:
155 if(mSfInfo.channels <= 2 && (mSfInfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
156 && alIsExtensionPresent("AL_EXT_IMA4")
157 && alIsExtensionPresent("AL_SOFT_block_alignment"))
158 mSampleFormat = SampleType::IMA4;
159 break;
160 case SF_FORMAT_MS_ADPCM:
161 if(mSfInfo.channels <= 2 && (mSfInfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
162 && alIsExtensionPresent("AL_SOFT_MSADPCM")
163 && alIsExtensionPresent("AL_SOFT_block_alignment"))
164 mSampleFormat = SampleType::MSADPCM;
165 break;
168 int splblocksize{}, byteblocksize{};
169 if(mSampleFormat == SampleType::IMA4 || mSampleFormat == SampleType::MSADPCM)
171 SF_CHUNK_INFO inf{ "fmt ", 4, 0, nullptr };
172 SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(mSndfile, &inf);
173 if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
174 mSampleFormat = SampleType::Int16;
175 else
177 auto fmtbuf = std::vector<ALubyte>(inf.datalen);
178 inf.data = fmtbuf.data();
179 if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
180 mSampleFormat = SampleType::Int16;
181 else
183 byteblocksize = fmtbuf[12] | (fmtbuf[13]<<8u);
184 if(mSampleFormat == SampleType::IMA4)
186 splblocksize = (byteblocksize/mSfInfo.channels - 4)/4*8 + 1;
187 if(splblocksize < 1
188 || ((splblocksize-1)/2 + 4)*mSfInfo.channels != byteblocksize)
189 mSampleFormat = SampleType::Int16;
191 else
193 splblocksize = (byteblocksize/mSfInfo.channels - 7)*2 + 2;
194 if(splblocksize < 2
195 || ((splblocksize-2)/2 + 7)*mSfInfo.channels != byteblocksize)
196 mSampleFormat = SampleType::Int16;
202 if(mSampleFormat == SampleType::Int16)
204 mSamplesPerBlock = 1;
205 mBytesPerBlock = static_cast<size_t>(mSfInfo.channels) * 2;
207 else if(mSampleFormat == SampleType::Float)
209 mSamplesPerBlock = 1;
210 mBytesPerBlock = static_cast<size_t>(mSfInfo.channels) * 4;
212 else
214 mSamplesPerBlock = static_cast<size_t>(splblocksize);
215 mBytesPerBlock = static_cast<size_t>(byteblocksize);
218 mFormat = AL_NONE;
219 if(mSfInfo.channels == 1)
221 if(mSampleFormat == SampleType::Int16)
222 mFormat = AL_FORMAT_MONO16;
223 else if(mSampleFormat == SampleType::Float)
224 mFormat = AL_FORMAT_MONO_FLOAT32;
225 else if(mSampleFormat == SampleType::IMA4)
226 mFormat = AL_FORMAT_MONO_IMA4;
227 else if(mSampleFormat == SampleType::MSADPCM)
228 mFormat = AL_FORMAT_MONO_MSADPCM_SOFT;
230 else if(mSfInfo.channels == 2)
232 if(mSampleFormat == SampleType::Int16)
233 mFormat = AL_FORMAT_STEREO16;
234 else if(mSampleFormat == SampleType::Float)
235 mFormat = AL_FORMAT_STEREO_FLOAT32;
236 else if(mSampleFormat == SampleType::IMA4)
237 mFormat = AL_FORMAT_STEREO_IMA4;
238 else if(mSampleFormat == SampleType::MSADPCM)
239 mFormat = AL_FORMAT_STEREO_MSADPCM_SOFT;
241 else if(mSfInfo.channels == 3)
243 if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
245 if(mSampleFormat == SampleType::Int16)
246 mFormat = AL_FORMAT_BFORMAT2D_16;
247 else if(mSampleFormat == SampleType::Float)
248 mFormat = AL_FORMAT_BFORMAT2D_FLOAT32;
251 else if(mSfInfo.channels == 4)
253 if(sf_command(mSndfile, SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
255 if(mSampleFormat == SampleType::Int16)
256 mFormat = AL_FORMAT_BFORMAT3D_16;
257 else if(mSampleFormat == SampleType::Float)
258 mFormat = AL_FORMAT_BFORMAT3D_FLOAT32;
261 if(!mFormat)
263 fprintf(stderr, "Unsupported channel count: %d\n", mSfInfo.channels);
264 sf_close(mSndfile);
265 mSndfile = nullptr;
267 return false;
270 /* Set a 1s ring buffer size. */
271 size_t numblocks{(static_cast<ALuint>(mSfInfo.samplerate) + mSamplesPerBlock-1)
272 / mSamplesPerBlock};
273 mBufferData.resize(static_cast<ALuint>(numblocks * mBytesPerBlock));
274 mReadPos.store(0, std::memory_order_relaxed);
275 mWritePos.store(0, std::memory_order_relaxed);
276 mDecoderOffset = 0;
278 return true;
281 /* The actual C-style callback just forwards to the non-static method. Not
282 * strictly needed and the compiler will optimize it to a normal function,
283 * but it allows the callback implementation to have a nice 'this' pointer
284 * with normal member access.
286 static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size) noexcept
287 { return static_cast<StreamPlayer*>(userptr)->bufferCallback(data, size); }
288 ALsizei bufferCallback(void *data, ALsizei size) noexcept
290 auto dst = al::span{static_cast<std::byte*>(data), static_cast<ALuint>(size)};
291 /* NOTE: The callback *MUST* be real-time safe! That means no blocking,
292 * no allocations or deallocations, no I/O, no page faults, or calls to
293 * functions that could do these things (this includes calling to
294 * libraries like SDL_sound, libsndfile, ffmpeg, etc). Nothing should
295 * unexpectedly stall this call since the audio has to get to the
296 * device on time.
298 ALsizei got{0};
300 size_t roffset{mReadPos.load(std::memory_order_acquire)};
301 while(!dst.empty())
303 /* If the write offset == read offset, there's nothing left in the
304 * ring-buffer. Break from the loop and give what has been written.
306 const size_t woffset{mWritePos.load(std::memory_order_relaxed)};
307 if(woffset == roffset) break;
309 /* If the write offset is behind the read offset, the readable
310 * portion wrapped around. Just read up to the end of the buffer in
311 * that case, otherwise read up to the write offset. Also limit the
312 * amount to copy given how much is remaining to write.
314 size_t todo{((woffset < roffset) ? mBufferData.size() : woffset) - roffset};
315 todo = std::min(todo, dst.size());
317 /* Copy from the ring buffer to the provided output buffer. Wrap
318 * the resulting read offset if it reached the end of the ring-
319 * buffer.
321 std::copy_n(mBufferData.cbegin()+ptrdiff_t(roffset), todo, dst.begin());
322 dst = dst.subspan(todo);
323 got += static_cast<ALsizei>(todo);
325 roffset += todo;
326 if(roffset == mBufferData.size())
327 roffset = 0;
329 /* Finally, store the updated read offset, and return how many bytes
330 * have been written.
332 mReadPos.store(roffset, std::memory_order_release);
334 return got;
337 bool prepare()
339 if(mSamplesPerBlock > 1)
340 alBufferi(mBuffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, static_cast<int>(mSamplesPerBlock));
341 alBufferCallbackSOFT(mBuffer, mFormat, mSfInfo.samplerate, bufferCallbackC, this);
342 alSourcei(mSource, AL_BUFFER, static_cast<ALint>(mBuffer));
343 if(ALenum err{alGetError()})
345 fprintf(stderr, "Failed to set callback: %s (0x%04x)\n", alGetString(err), err);
346 return false;
348 return true;
351 bool update()
353 ALenum state;
354 ALint pos;
355 alGetSourcei(mSource, AL_SAMPLE_OFFSET, &pos);
356 alGetSourcei(mSource, AL_SOURCE_STATE, &state);
358 size_t woffset{mWritePos.load(std::memory_order_acquire)};
359 if(state != AL_INITIAL)
361 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
362 const size_t readable{((woffset >= roffset) ? woffset : (mBufferData.size()+woffset)) -
363 roffset};
364 /* For a stopped (underrun) source, the current playback offset is
365 * the current decoder offset excluding the readable buffered data.
366 * For a playing/paused source, it's the source's offset including
367 * the playback offset the source was started with.
369 const size_t curtime{((state == AL_STOPPED)
370 ? (mDecoderOffset-readable) / mBytesPerBlock * mSamplesPerBlock
371 : (static_cast<ALuint>(pos) + mStartOffset/mBytesPerBlock*mSamplesPerBlock))
372 / static_cast<ALuint>(mSfInfo.samplerate)};
373 printf("\r%3zus (%3zu%% full)", curtime, readable * 100 / mBufferData.size());
375 else
376 fputs("Starting...", stdout);
377 fflush(stdout);
379 while(!sf_error(mSndfile))
381 size_t read_bytes;
382 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
383 if(roffset > woffset)
385 /* Note that the ring buffer's writable space is one byte less
386 * than the available area because the write offset ending up
387 * at the read offset would be interpreted as being empty
388 * instead of full.
390 const size_t writable{(roffset-woffset-1) / mBytesPerBlock};
391 if(!writable) break;
393 if(mSampleFormat == SampleType::Int16)
395 sf_count_t num_frames{sf_readf_short(mSndfile,
396 reinterpret_cast<short*>(&mBufferData[woffset]),
397 static_cast<sf_count_t>(writable*mSamplesPerBlock))};
398 if(num_frames < 1) break;
399 read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
401 else if(mSampleFormat == SampleType::Float)
403 sf_count_t num_frames{sf_readf_float(mSndfile,
404 reinterpret_cast<float*>(&mBufferData[woffset]),
405 static_cast<sf_count_t>(writable*mSamplesPerBlock))};
406 if(num_frames < 1) break;
407 read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
409 else
411 sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
412 static_cast<sf_count_t>(writable*mBytesPerBlock))};
413 if(numbytes < 1) break;
414 read_bytes = static_cast<size_t>(numbytes);
417 woffset += read_bytes;
419 else
421 /* If the read offset is at or behind the write offset, the
422 * writeable area (might) wrap around. Make sure the sample
423 * data can fit, and calculate how much can go in front before
424 * wrapping.
426 const size_t writable{(!roffset ? mBufferData.size()-woffset-1 :
427 (mBufferData.size()-woffset)) / mBytesPerBlock};
428 if(!writable) break;
430 if(mSampleFormat == SampleType::Int16)
432 sf_count_t num_frames{sf_readf_short(mSndfile,
433 reinterpret_cast<short*>(&mBufferData[woffset]),
434 static_cast<sf_count_t>(writable*mSamplesPerBlock))};
435 if(num_frames < 1) break;
436 read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
438 else if(mSampleFormat == SampleType::Float)
440 sf_count_t num_frames{sf_readf_float(mSndfile,
441 reinterpret_cast<float*>(&mBufferData[woffset]),
442 static_cast<sf_count_t>(writable*mSamplesPerBlock))};
443 if(num_frames < 1) break;
444 read_bytes = static_cast<size_t>(num_frames) * mBytesPerBlock;
446 else
448 sf_count_t numbytes{sf_read_raw(mSndfile, &mBufferData[woffset],
449 static_cast<sf_count_t>(writable*mBytesPerBlock))};
450 if(numbytes < 1) break;
451 read_bytes = static_cast<size_t>(numbytes);
454 woffset += read_bytes;
455 if(woffset == mBufferData.size())
456 woffset = 0;
458 mWritePos.store(woffset, std::memory_order_release);
459 mDecoderOffset += read_bytes;
462 if(state != AL_PLAYING && state != AL_PAUSED)
464 /* If the source is not playing or paused, it either underrun
465 * (AL_STOPPED) or is just getting started (AL_INITIAL). If the
466 * ring buffer is empty, it's done, otherwise play the source with
467 * what's available.
469 const size_t roffset{mReadPos.load(std::memory_order_relaxed)};
470 const size_t readable{((woffset >= roffset) ? woffset : (mBufferData.size()+woffset)) -
471 roffset};
472 if(readable == 0)
473 return false;
475 /* Store the playback offset that the source will start reading
476 * from, so it can be tracked during playback.
478 mStartOffset = mDecoderOffset - readable;
479 alSourcePlay(mSource);
480 if(alGetError() != AL_NO_ERROR)
481 return false;
483 return true;
487 int main(al::span<std::string_view> args)
489 /* A simple RAII container for OpenAL startup and shutdown. */
490 struct AudioManager {
491 AudioManager(al::span<std::string_view> &args_)
493 if(InitAL(args_) != 0)
494 throw std::runtime_error{"Failed to initialize OpenAL"};
496 ~AudioManager() { CloseAL(); }
499 /* Print out usage if no arguments were specified */
500 if(args.size() < 2)
502 fprintf(stderr, "Usage: %.*s [-device <name>] <filenames...>\n", al::sizei(args[0]),
503 args[0].data());
504 return 1;
507 args = args.subspan(1);
508 AudioManager almgr{args};
510 if(!alIsExtensionPresent("AL_SOFT_callback_buffer"))
512 fprintf(stderr, "AL_SOFT_callback_buffer extension not available\n");
513 return 1;
516 alBufferCallbackSOFT = reinterpret_cast<LPALBUFFERCALLBACKSOFT>(
517 alGetProcAddress("alBufferCallbackSOFT"));
519 ALCint refresh{25};
520 alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh);
522 auto player = std::make_unique<StreamPlayer>();
524 /* Play each file listed on the command line */
525 for(size_t i{0};i < args.size();++i)
527 if(!player->open(std::string{args[i]}))
528 continue;
530 /* Get the name portion, without the path, for display. */
531 auto namepart = args[i];
532 if(auto sep = namepart.rfind('/'); sep < namepart.size())
533 namepart = namepart.substr(sep+1);
534 else if(sep = namepart.rfind('\\'); sep < namepart.size())
535 namepart = namepart.substr(sep+1);
537 printf("Playing: %.*s (%s, %dhz)\n", al::sizei(namepart), namepart.data(),
538 FormatName(player->mFormat), player->mSfInfo.samplerate);
539 fflush(stdout);
541 if(!player->prepare())
543 player->close();
544 continue;
547 while(player->update())
548 std::this_thread::sleep_for(nanoseconds{seconds{1}} / refresh);
549 putc('\n', stdout);
551 /* All done with this file. Close it and go to the next */
552 player->close();
554 /* All done. */
555 printf("Done.\n");
557 return 0;
560 } // namespace
562 int main(int argc, char **argv)
564 assert(argc >= 0);
565 auto args = std::vector<std::string_view>(static_cast<unsigned int>(argc));
566 std::copy_n(argv, args.size(), args.begin());
567 return main(al::span{args});