-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSound.cpp
More file actions
892 lines (670 loc) · 25.7 KB
/
Sound.cpp
File metadata and controls
892 lines (670 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
/*
* Sound.cpp
*
* Created on: Apr 12, 2020
* Author: ans
*/
#include "Sound.h"
// constructor initializing the libsoundio library
Sound::Sound()
: started(false),
connected(false),
initialized(false),
running(false),
secondsOffset(0.),
secondsPerFrame(0.),
soundIo(nullptr),
soundIoOutputDevice(nullptr),
soundIoOutStream(nullptr),
defaultOutputDeviceIndex(-1),
outputDeviceIndex(-1),
outputSampleRate(44100),
outputChannels(0),
outputMaxFrames(0),
outputLatency(0.025),
isUnderflow(false),
lastWritingError(0) {
// create soundio context
this->soundIo = soundio_create();
if(!(this->soundIo))
throw std::runtime_error("soundio_create failed");
// connect to the backend
int error = soundio_connect(this->soundIo);
if(error)
throw std::runtime_error(soundio_strerror(error));
// set state, callbacks and user pointer
this->connected = true;
this->soundIo->on_devices_change = Sound::callbackDevicesChanged;
this->soundIo->on_backend_disconnect = Sound::callbackBackendDisconnected;
this->soundIo->userdata = static_cast<void *>(this);
// flush events
soundio_flush_events(this->soundIo);
// get the default output device
this->defaultOutputDeviceIndex = soundio_default_output_device_index(this->soundIo);
if(this->defaultOutputDeviceIndex < 0)
throw std::runtime_error("soundio_default_output_device_index failed");
// use the default output device for now
this->setOutputDevice(this->defaultOutputDeviceIndex);
}
// destructor
Sound::~Sound() {
// stop the thread
this->stop();
// clear thread-related stuff (e.g. if the thread has been terminated by an exception)
this->threadClear();
// disconnect from the backend and destroy the soundio context
if(this->soundIo) {
if(this->connected) {
soundio_disconnect(this->soundIo);
this->connected = false;
}
soundio_destroy(this->soundIo);
this->soundIo = nullptr;
}
}
// write all available output devices into a vector and return it
std::vector<Sound::Device> Sound::listOutputDevices() const {
// check context and state
if(!(this->soundIo))
throw std::runtime_error("listDevices(): soundio not initialized");
const auto count = soundio_output_device_count(this->soundIo);
if(!count)
throw std::runtime_error("Could not find any output devices");
std::vector<Device> result;
result.reserve(count);
for(auto n = 0; n < count; ++n) {
auto * device = soundio_get_output_device(this->soundIo, n);
if(!device)
throw std::runtime_error(
"soundio_get_output_device failed for device #"
+ std::to_string(n)
);
result.emplace_back(
n,
device->id,
device->name
);
soundio_device_unref(device);
device = nullptr;
}
return result;
}
// get the index of the default output device or -1 if none is available
int Sound::getDefaultOutputDeviceIndex() const {
return this->defaultOutputDeviceIndex;
}
// get the ID of the currently selected device (e.g. for saving it into a settings file)
std::string Sound::getOutputDeviceId() const {
if(this->outputDeviceId.empty())
throw std::runtime_error("No device selected");
return this->outputDeviceId;
}
// get the name of the currently selected device
std::string Sound::getOutputDeviceName() const {
return this->outputDeviceName;
}
// get the name of the underlying backend used for communicating with the sound device(s)
std::string Sound::getBackend() const {
if(!(this->soundIo))
throw std::runtime_error("Sound::getBackend(): soundIo == nullptr");
switch(this->soundIo->current_backend) {
case SoundIoBackendNone:
return "<none>";
case SoundIoBackendJack:
return "Jack";
case SoundIoBackendPulseAudio:
return "PulseAudio";
case SoundIoBackendAlsa:
return "ALSA";
case SoundIoBackendCoreAudio:
return "Core Audio";
case SoundIoBackendWasapi:
return "Wasapi";
case SoundIoBackendDummy:
return "<dummy>";
}
return "<unknown>";
}
// set the current output device by its index (e.g. when received from Sound::listOutputDevices)
void Sound::setOutputDeviceByIndex(unsigned int index) {
this->setOutputDevice(index);
}
// set the current output device by its ID (e.g. when read from a settings file)
void Sound::setOutputDeviceById(const std::string& id) {
const auto index = this->outputDeviceIdToIndex(id);
if(index == -1)
throw std::runtime_error("Could not find device with \'" + id + "\'");
this->setOutputDevice(index);
}
// set the output function used for generating sound
void Sound::setOutputFunction(OutputFunction callBack) {
this->output = callBack;
}
// set the name of the output stream (default: empty, empty string is API default ("SoundIoOutStream")
void Sound::setOutputStreamName(const std::string& streamName) {
this->outputStreamName = streamName;
}
// set the sample rate (default: 44100, zero means device/library default)
void Sound::setOutputSampleRate(unsigned int sampleRate) {
this->outputSampleRate = sampleRate;
}
// set the number of channels (default: 0, zero means device/library default)
void Sound::setOutputChannels(unsigned int channels) {
this->outputChannels = channels;
}
// set the maximum amount of frames to output at once (default: 0, zero means unlimited)
// WARNING: Low numbers will lead to 'underflow' i.e. not enough data to write to the output sound device !
// Very low numbers will break the audio output completely !
void Sound::setOutputMaxFrames(unsigned int maxFrames) {
this->outputMaxFrames = maxFrames;
}
// set the desired software latency for the sound output (in seconds, default: 0.025 i.e. 25ms, zero means device default)
// WARNING: The device default might be a very high latency (e.g. 2s), therefore it is better to use the in-class default !
// Very low numbers will lead to 'underflow' i.e. not enough data to write to the output sound device !
void Sound::setOutputLatency(double latency) {
this->outputLatency = latency;
}
// start the sound system in an extra thread
void Sound::start(double startTimeInSeconds) {
if(this->running)
// sound system is already running
return throw std::runtime_error("The sound system has already been started");
this->started = true;
this->secondsOffset = startTimeInSeconds;
this->running = true;
this->soundThread = std::thread(&Sound::thread, this);
}
// stop the sound system, notify the soundio library and wait for the thread
void Sound::stop() {
if(this->started) {
this->started = false;
this->running = false;
soundio_wakeup(this->soundIo);
if(this->soundThread.joinable())
this->soundThread.join();
}
}
// check whether sound system has been succesfully started (thread-safe!)
bool Sound::isStarted() const {
return this->initialized;
}
// get the actual output sample rate chosen by the device
// NOTE: The sound system need to be completely started before you can use this function.
// You can use Sound::isStarted() to wait until it is ready.
int Sound::getOutputSampleRate() const {
if(!(this->soundIoOutStream))
throw std::runtime_error(
"Sound::getChannelType(): Sound system needs to be started before getting the type of a channel"
);
return this->soundIoOutStream->sample_rate;
}
// get the name of the currently selected layout
// NOTE: The sound system need to be completely started before you can use this function.
// You can use Sound::isStarted() to wait until it is ready.
std::string Sound::getOutputLayoutName() const {
if(!(this->soundIoOutStream))
throw std::runtime_error(
"Sound::getOutputLayoutName(): Sound system needs to be started before getting the layout of the output"
);
return this->soundIoOutStream->layout.name;
}
// get the number of output channels
// NOTE: The sound system need to be completely started before you can use this function.
// You can use Sound::isStarted() to wait until it is ready.
int Sound::getOutputChannels() const {
if(!(this->soundIoOutStream))
throw std::runtime_error(
"Sound::getOutputChannels(): Sound system needs to be started before getting the number of channels"
);
return this->soundIoOutStream->layout.channel_count;
}
// get the actual software latency (might return zero for low latencies depending on the device)
// NOTE: The sound system need to be completely started before you can use this function.
// You can use Sound::isStarted() to wait until it is ready.
double Sound::getOutputLatency() const {
if(!(this->soundIoOutStream))
throw std::runtime_error(
"Sound::getOutputLatency(): Sound system needs to be started before getting the latency of the output"
);
return this->soundIoOutStream->software_latency;
}
// get the type of the channel with the specified index
// NOTE: The sound system need to be completely started before you can use this function.
// You can use Sound::isStarted() to wait until it is ready.
Sound::Channel Sound::getOutputChannelType(unsigned int channel) const {
if(!(this->soundIoOutStream))
throw std::runtime_error(
"Sound::getOutputChannelType(): Sound system needs to be started before getting the type of a channel"
);
if(this->soundIoOutStream->layout.channel_count < 0)
return CHANNEL_NONE;
if(channel > static_cast<unsigned int>(this->soundIoOutStream->layout.channel_count))
return CHANNEL_NONE;
switch(this->soundIoOutStream->layout.channels[channel]) {
case SoundIoChannelIdInvalid:
return CHANNEL_NONE;
case SoundIoChannelIdFrontLeft:
return CHANNEL_FRONT_LEFT;
case SoundIoChannelIdFrontRight:
return CHANNEL_FRONT_RIGHT;
case SoundIoChannelIdFrontRightCenter:
return CHANNEL_FRONT_RIGHT_CENTER;
case SoundIoChannelIdFrontCenter:
return CHANNEL_FRONT_CENTER;
case SoundIoChannelIdBackLeft:
return CHANNEL_BACK_LEFT;
case SoundIoChannelIdBackRight:
return CHANNEL_BACK_RIGHT;
case SoundIoChannelIdFrontLeftCenter:
return CHANNEL_FRONT_LEFT;
case SoundIoChannelIdBackCenter:
return CHANNEL_BACK_CENTER;
case SoundIoChannelIdSideLeft:
return CHANNEL_SIDE_LEFT;
case SoundIoChannelIdSideRight:
return CHANNEL_SIDE_RIGHT;
case SoundIoChannelIdTopCenter:
return CHANNEL_TOP_CENTER;
case SoundIoChannelIdTopFrontLeft:
return CHANNEL_TOP_FRONT_LEFT;
case SoundIoChannelIdTopFrontCenter:
return CHANNEL_TOP_FRONT_CENTER;
case SoundIoChannelIdTopFrontRight:
return CHANNEL_TOP_FRONT_RIGHT;
case SoundIoChannelIdTopBackLeft:
return CHANNEL_TOP_BACK_LEFT;
case SoundIoChannelIdTopBackCenter:
return CHANNEL_TOP_BACK_CENTER;
case SoundIoChannelIdTopBackRight:
return CHANNEL_TOP_BACK_RIGHT;
case SoundIoChannelIdLfe:
return CHANNEL_SUBWOOFER;
default:
return CHANNEL_OTHER;
}
}
// get the name of the channel with the specified index
// NOTE: The sound system need to be completely started before you can use this function.
// You can use Sound::isStarted() to wait until it is ready.
std::string Sound::getOutputChannelName(unsigned int channel) const {
if(!(this->soundIoOutStream))
throw std::runtime_error(
"Sound::getChannelName(): Sound system needs to be started before getting the name of a channel"
);
if(this->soundIoOutStream->layout.channel_count < 0)
return "<none>";
if(channel > static_cast<unsigned int>(this->soundIoOutStream->layout.channel_count))
return "<none>";
switch(this->soundIoOutStream->layout.channels[channel]) {
case SoundIoChannelIdInvalid:
return "<none>";
case SoundIoChannelIdFrontLeft:
return "Front left";
case SoundIoChannelIdFrontRight:
return "Front right";
case SoundIoChannelIdFrontRightCenter:
return "Front right center";
case SoundIoChannelIdFrontCenter:
return "Front center";
case SoundIoChannelIdBackLeft:
return "Back left";
case SoundIoChannelIdBackRight:
return "Back right";
case SoundIoChannelIdFrontLeftCenter:
return "Front left";
case SoundIoChannelIdBackCenter:
return "Back center";
case SoundIoChannelIdSideLeft:
return "Side leftt";
case SoundIoChannelIdSideRight:
return "Side right";
case SoundIoChannelIdTopCenter:
return "Top center";
case SoundIoChannelIdTopFrontLeft:
return "Top front left";
case SoundIoChannelIdTopFrontCenter:
return "Top front center";
case SoundIoChannelIdTopFrontRight:
return "Top front right";
case SoundIoChannelIdTopBackLeft:
return "Top back left";
case SoundIoChannelIdTopBackCenter:
return "Top back center";
case SoundIoChannelIdTopBackRight:
return "Top back right";
case SoundIoChannelIdLfe:
return "Subwoofer";
default:
return "<other>";
}
}
// check whether a underflow error has occured while writing the output
// NOTE: Resets the state of the underflow error when called.
bool Sound::isOutputUnderflowOccured() {
bool changeIfValueIs = true;
return this->isUnderflow.compare_exchange_strong(
changeIfValueIs,
false,
std::memory_order_relaxed,
std::memory_order_release
);
}
// check whether errors occured while writing to the output buffer and request them from the sound system
bool Sound::isOutputWritingErrorsOccured(std::string& lastErrorOut) {
int lastError = this->lastWritingError.load(std::memory_order_acquire);
if(lastError) {
lastErrorOut = soundio_strerror(lastError);
this->lastWritingError.compare_exchange_strong(
lastError,
0,
std::memory_order_acquire,
std::memory_order_release
);
return true;
}
return false;
}
// get the current position in time of the sound thread (everything before has already been sent to the output device)
// NOTE: Should NOT be called from outside the sound thread (i.e. the callbacks of the sound system) !
double Sound::getTimePosition() const {
return this->secondsOffset;
}
// thread function for the actual sound output
void Sound::thread() {
// initialize thread-related resources
this->threadInit();
// handle sound events while the thread is running
while(this->running)
soundio_wait_events(this->soundIo);
// clear thread-related resources
this->threadClear();
}
// initialize thread-related resources
void Sound::threadInit() {
// get the output device
this->soundIoOutputDevice = soundio_get_output_device(this->soundIo, this->outputDeviceIndex);
if(!(this->soundIoOutputDevice))
throw std::runtime_error("Sound::threadInit(): soundio_get_output_device failed.");
// create the output stream
this->soundIoOutStream = soundio_outstream_create(this->soundIoOutputDevice);
if(!(this->soundIoOutStream))
throw std::runtime_error("Sound::threadInit(): soundio_outstream_create failed.");
// set output options
this->soundIoOutStream->format = SoundIoFormatFloat32NE;
if(!(this->outputStreamName.empty()))
this->soundIoOutStream->name = this->outputStreamName.c_str();
if(this->outputSampleRate)
this->soundIoOutStream->sample_rate = this->outputSampleRate;
if(this->outputChannels)
this->soundIoOutStream->layout = this->getLayout();
this->soundIoOutStream->write_callback = Sound::callbackWrite;
this->soundIoOutStream->underflow_callback = Sound::callbackUnderflow;
if(this->outputLatency > 0.)
this->soundIoOutStream->software_latency = this->outputLatency;
// choose output format
if(soundio_device_supports_format(this->soundIoOutputDevice, SoundIoFormatFloat64NE)) {
this->soundIoOutStream->format = SoundIoFormatFloat64NE;
this->write = writeSampleF64;
}
else if(soundio_device_supports_format(this->soundIoOutputDevice, SoundIoFormatFloat32NE)) {
this->soundIoOutStream->format = SoundIoFormatFloat32NE;
this->write = writeSampleF32;
}
else if(soundio_device_supports_format(this->soundIoOutputDevice, SoundIoFormatS32NE)) {
this->soundIoOutStream->format = SoundIoFormatS32NE;
this->write = writeSampleS32;
}
else if(soundio_device_supports_format(this->soundIoOutputDevice, SoundIoFormatS16NE)) {
this->soundIoOutStream->format = SoundIoFormatS16NE;
this->write = writeSampleS16;
}
else
throw std::runtime_error(
"Sound::threadInit(): Sound device does not support the available output formats."
);
// open the output stream
const auto errorOpen = soundio_outstream_open(this->soundIoOutStream);
if(errorOpen)
throw std::runtime_error(
"Sound::threadInit(): soundio_outstream_open failed, " + std::string(soundio_strerror(errorOpen))
);
if(this->soundIoOutStream->layout_error)
throw std::runtime_error(
"Sound::threadInit(): layout error, " + std::string(soundio_strerror(this->soundIoOutStream->layout_error))
);
// start the output stream
const auto errorStart = soundio_outstream_start(this->soundIoOutStream);
if(errorStart)
throw std::runtime_error(
"Sound::threadInit(): soundio_outstream_start failed, " + std::string(soundio_strerror(errorStart))
);
// calculate the number of seconds per sample
this->secondsPerFrame = 1. / this->soundIoOutStream->sample_rate;
// done
this->initialized = true;
}
// clear thread-related resources
void Sound::threadClear() {
this->initialized = false;
if(this->soundIoOutStream) {
soundio_outstream_destroy(this->soundIoOutStream);
this->soundIoOutStream = nullptr;
}
if(this->soundIoOutputDevice) {
soundio_device_unref(this->soundIoOutputDevice);
this->soundIoOutputDevice = nullptr;
}
}
// devices have been changed: check whether the output device remains valid
void Sound::onDevicesChanged() {
// get default device
this->defaultOutputDeviceIndex = soundio_default_output_device_index(this->soundIo);
if(this->defaultOutputDeviceIndex < 0)
throw std::runtime_error(
"Sound::onDevicesChanged(): Could not get new default output device"
);
if(!(this->outputDeviceId.empty())) {
// check whether the index of the current device has changed
const auto index = this->outputDeviceIdToIndex(this->outputDeviceId);
// check whether current device has been lost
if(index == -1)
// reset to default device
this->setOutputDevice(this->defaultOutputDeviceIndex);
else
// reset device if necessary
if(index != this->outputDeviceIndex)
this->setOutputDevice(index);
}
}
// backend has been disconnected: shutdown the sound system
void Sound::onBackendDisconnected(int error) {
this->running = false;
throw std::runtime_error(
"Sound system disconnected: " + std::string(soundio_strerror(error))
);
}
// write to the sound output device using the provided callback function
void Sound::onWrite(int frameCountMin, int frameCountMax) {
if(!(this->soundIoOutStream))
throw std::runtime_error("Sound::onWrite(): soundIoOutStream == nullptr");
const auto * pointerToLayout = &(this->soundIoOutStream->layout);
SoundIoChannelArea * pointerToAreas = nullptr;
if(frameCountMin < 0)
throw std::runtime_error("Sound::onWrite(): frameCountMin < 0");
if(frameCountMax < 0)
throw std::runtime_error("Sound::onWrite(): frameCountMax < 0");
if(pointerToLayout->channel_count <= 0)
throw std::runtime_error("Sound::onWrite(): no channels to write sound to");
const unsigned int channelCount = static_cast<unsigned int>(pointerToLayout->channel_count);
// write a decent number of frames
auto framesLeft = frameCountMax;
if(this->outputMaxFrames && framesLeft > this->outputMaxFrames && frameCountMin < framesLeft) {
if(this->outputMaxFrames > frameCountMin)
framesLeft = this->outputMaxFrames;
else
framesLeft = frameCountMin;
}
// loop through the frames
while(framesLeft) {
auto frameCount = framesLeft;
// start writing to the stream
const auto beginError = soundio_outstream_begin_write(this->soundIoOutStream, &pointerToAreas, &frameCount);
if(beginError) {
// save output error and cancel
this->lastWritingError.store(beginError, std::memory_order_release);
return;
}
if(!frameCount)
// no frames to write
return;
for(auto frame = 0; frame < frameCount; ++frame) {
// get sample from the callback function
for(unsigned int channel = 0; channel < channelCount; ++channel) {
const auto sample = this->output(channel, this->secondsOffset + frame * this->secondsPerFrame);
this->write(pointerToAreas[channel].ptr, sample > 1. ? 1. : sample);
pointerToAreas[channel].ptr += pointerToAreas[channel].step;
}
}
this->secondsOffset += this->secondsPerFrame * frameCount;
const auto endError = soundio_outstream_end_write(this->soundIoOutStream);
if(endError) {
// save output error and cancel
this->lastWritingError.store(endError, std::memory_order_release);
return;
}
framesLeft -= frameCount;
}
}
// buffer has underflow
void Sound::onUnderflow() {
this->isUnderflow.store(true, std::memory_order_release);
}
// delegate on devices changed event into the class
void Sound::callbackDevicesChanged(SoundIo * soundIo) {
if(!soundIo)
throw std::runtime_error("callbackDevicesChanged(): soundIo == nullptr");
if(!soundIo->userdata)
throw std::runtime_error("callbackDevicesChanged(): soundIo->userdata == nullptr");
static_cast<Sound *>(soundIo->userdata)->onDevicesChanged();
}
// delegate on backend disconnected event into class
void Sound::callbackBackendDisconnected(SoundIo * soundIo, int error) {
if(!soundIo)
throw std::runtime_error("callbackBackendDisconnected(): soundIo == nullptr");
if(!soundIo->userdata)
throw std::runtime_error("callbackBackendDisconnected(): soundIo->userdata == nullptr");
static_cast<Sound *>(soundIo->userdata)->onBackendDisconnected(error);
}
// delegate write request into class
void Sound::callbackWrite(SoundIoOutStream * soundIoOutStream, int frameCountMin, int frameCountMax) {
if(!soundIoOutStream)
throw std::runtime_error("callbackWrite(): soundIoOutStream == nullptr");
if(!(soundIoOutStream->device))
throw std::runtime_error("callbackWrite(): soundIoOutStream->device == nullptr");
if(!(soundIoOutStream->device->soundio))
throw std::runtime_error("callbackWrite(): soundIoOutStream->device->soundio == nullptr");
if(!(soundIoOutStream->device->soundio->userdata))
throw std::runtime_error("callbackWrite(): soundIoOutStream->device->soundio->userdata == nullptr");
static_cast<Sound *>(soundIoOutStream->device->soundio->userdata)->onWrite(frameCountMin, frameCountMax);
}
// delegate underflow event into class
void Sound::callbackUnderflow(SoundIoOutStream * soundIoOutStream) {
if(!soundIoOutStream)
throw std::runtime_error("callbackUnderflow(): soundIoOutStream == nullptr");
if(!(soundIoOutStream->device))
throw std::runtime_error("callbackUnderflow(): soundIoOutStream->device == nullptr");
if(!(soundIoOutStream->device->soundio))
throw std::runtime_error("callbackUnderflow(): soundIoOutStream->device->soundio == nullptr");
if(!(soundIoOutStream->device->soundio->userdata))
throw std::runtime_error("callbackUnderflow(): soundIoOutStream->device->soundio->userdata == nullptr");
static_cast<Sound *>(soundIoOutStream->device->soundio->userdata)->onUnderflow();
}
// helper function to find the index of the output device with the specified ID
int Sound::outputDeviceIdToIndex(const std::string& id) {
const auto count = soundio_output_device_count(this->soundIo);
if(!count)
throw std::runtime_error(
"Sound::outputDeviceIdToIndex(): Could not find any output devices."
);
int index = -1;
for(auto n = 0; n < count; ++n) {
auto * device = soundio_get_output_device(this->soundIo, n);
if(!device)
throw std::runtime_error(
"Sound::outputDeviceIdToIndex(): Could not get output device #" + std::to_string(n)
);
const std::string deviceId(device->id);
soundio_device_unref(device);
device = nullptr;
if(deviceId == id) {
index = n;
break;
}
}
return index;
}
// helper function to set the current output device and restart the thread if necessary
void Sound::setOutputDevice(int index) {
if(!(this->soundIo))
throw std::runtime_error("Sound::setOutputDevice(): this->soundio == nullptr");
bool restart = false;
if(this->running) {
this->stop();
restart = true;
}
if(index < 0)
this->outputDeviceIndex = this->defaultOutputDeviceIndex;
else if(index >= soundio_output_device_count(this->soundIo))
throw std::runtime_error("Sound::setOutputDevice(): Invalid output device #" + std::to_string(index));
else
this->outputDeviceIndex = index;
auto * tmpDevice = soundio_get_output_device(this->soundIo, this->outputDeviceIndex);
if(!tmpDevice)
throw std::runtime_error(
"soundio_get_output_device failed for default device #" + std::to_string(this->outputDeviceIndex)
);
this->outputDeviceId = tmpDevice->id;
this->outputDeviceName = tmpDevice->name;
soundio_device_unref(tmpDevice);
tmpDevice = nullptr;
if(restart)
this->start(this->secondsOffset);
}
// get the pointer to a layout fitting the specified options (i.e. channels) or to the default if none was found
const SoundIoChannelLayout& Sound::getLayout() const {
if(!(this->soundIoOutputDevice))
throw std::runtime_error("The sound system needs to be started before getting information about the output layout");
for(auto layout = 0; layout < this->soundIoOutputDevice->layout_count; ++layout)
if(
this->soundIoOutputDevice->layouts[layout].channel_count > 0
&& static_cast<unsigned int>(
this->soundIoOutputDevice->layouts[layout].channel_count
) == this->outputChannels
)
return this->soundIoOutputDevice->layouts[layout];
return this->soundIoOutputDevice->current_layout;
}
// write a 16-bit integer sample
void Sound::writeSampleS16(void * target, double sample) {
int16_t * buffer = static_cast<int16_t *>(target);
double range = static_cast<double>(std::numeric_limits<int16_t>::max())
- static_cast<double>(std::numeric_limits<int16_t>::min());
*buffer = static_cast<int16_t>(sample * range / 2.);
}
// write a 32-bit integer sample
void Sound::writeSampleS32(void * target, double sample) {
int32_t * buffer = static_cast<int32_t *>(target);
double range = static_cast<double>(std::numeric_limits<int32_t>::max())
- static_cast<double>(std::numeric_limits<int32_t>::min());
*buffer = static_cast<int32_t>(sample * range / 2.);
}
// write a 32-bit float sample
void Sound::writeSampleF32(void * target, double sample) {
float * buffer = static_cast<float *>(target);
*buffer = static_cast<float>(sample);
}
// write a 64-bit float sample
void Sound::writeSampleF64(void * target, double sample) {
double * buffer = static_cast<double *>(target);
*buffer = sample;
}