File: openal_track.cpp

package info (click to toggle)
warzone2100 4.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 660,320 kB
  • sloc: cpp: 676,209; ansic: 391,201; javascript: 78,238; python: 16,632; php: 4,294; sh: 4,094; makefile: 2,629; lisp: 1,492; cs: 489; xml: 404; perl: 224; ruby: 156; java: 89
file content (1520 lines) | stat: -rw-r--r-- 43,288 bytes parent folder | download | duplicates (2)
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
/*
	This file is part of Warzone 2100.
	Copyright (C) 1999-2004  Eidos Interactive
	Copyright (C) 2005-2020  Warzone 2100 Project

	Warzone 2100 is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	Warzone 2100 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Warzone 2100; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/** \file
 *  Sound library-specific functions
 */

// this has to be first
#include "lib/framework/frame.h"
#include "lib/framework/math_ext.h"
#include "lib/framework/frameresource.h"
#include "lib/framework/object_list_iteration.h"
#include "lib/exceptionhandler/dumpinfo.h"

#include <AL/al.h>
#include <AL/alc.h>
#if defined(HAVE_OPENAL_ALEXT_H)
# include <AL/alext.h>
#endif

#include <physfs.h>
#include "lib/framework/physfs_ext.h"
#include <string.h>
#include <math.h>
#include <limits>
#include <list>

#include "tracklib.h"
#include "audio.h"
#include "cdaudio.h"
#include "oggvorbis.h"
#include "openal_error.h"
#include "mixer.h"
#include "openal_info.h"
#include "oggopus.h"
#include "oggvorbis.h"
static ALuint current_queue_sample = -1;

static bool openal_initialized = false;
static const size_t bufferSize = 16 * 1024;
static const unsigned int buffer_count = 32;

/** Source of music */
struct AUDIO_STREAM
{
	ALuint                  source = -1;        // OpenAL name of the sound source
	WZDecoder       		*decoder = nullptr;
	PHYSFS_file				*fileHandle = nullptr;
	float                   volume = 0.f;
	bool					queuedStop = false;	// when sound_StopStream has been called on the stream

	// Callbacks
	std::function<void (const AUDIO_STREAM *, const void *)> onFinished;
	const void              *user_data = nullptr;
};

static std::list<AUDIO_SAMPLE *> active_samples;

/* actives openAL-Sources */
static std::list<AUDIO_STREAM *> active_streams;

static ALfloat		sfx_volume = 1.0;
static ALfloat		sfx3d_volume = 1.0;

static ALCdevice *device = nullptr;
static ALCcontext *context = nullptr;

#if defined(ALC_SOFT_HRTF)
# if defined(__EMSCRIPTEN__)
typedef const ALCchar* (*LPALCGETSTRINGISOFT)(ALCdevice *device, ALCenum paramName, ALCsizei index);
typedef ALCboolean (*LPALCRESETDEVICESOFT)(ALCdevice *device, const ALCint *attribs);
# endif
static LPALCGETSTRINGISOFT alcGetStringiSOFT = nullptr;
static LPALCRESETDEVICESOFT alcResetDeviceSOFT = nullptr;
#endif

ALCint HRTFModeToALCint(HRTFMode mode)
{
#if defined(ALC_SOFT_HRTF)
	switch (mode)
	{
	case HRTFMode::Unsupported:
		// should never be called with unsupported, log it and fall through to disabled
		debug(LOG_ERROR, "HRTFModeToALCint called with HRTFMode::Unsupported");
		// fallthrough
	case HRTFMode::Disabled:
		return ALC_FALSE;
	case HRTFMode::Enabled:
		return ALC_TRUE;
	case HRTFMode::Auto:
		return ALC_DONT_CARE_SOFT;
	}
#endif
	return ALC_FALSE;
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
bool sound_InitLibrary(HRTFMode hrtf)
{
	int err;
	const ALfloat listenerVel[3] = { 0.0, 0.0, 0.0 };
	const ALfloat listenerOri[6] = { 0.0, 0.0, 1.0, 0.0, 1.0, 0.0 };
	char buf[512];
	const ALCchar *deviceName;

#if 0
	// This code is disabled because enumerating devices apparently crashes PulseAudio on Fedora12

	/* Get the available devices and print them.
	 * Devices are separated by NUL chars ('\0') and the list of devices is
	 * terminated by two NUL chars.
	 */
	deviceName = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
	while (deviceName != NULL && *deviceName != '\0')
	{
		debug(LOG_SOUND, "available OpenAL device(s) are: %s", deviceName);
		deviceName += strlen(deviceName) + 1;
	}
#endif

	if (enabled_debug[LOG_SOUND])
	{
		OpenALInfo::Output_PlaybackDevices([](const std::string &output) {
			addDumpInfo(output.c_str());
			if (enabled_debug[LOG_SOUND])
			{
				_debug_multiline(0, LOG_SOUND, "sound", output);
			}
		});
	}

	// Open default device
	device = alcOpenDevice(nullptr);

	if (!device)
	{
		debug(LOG_ERROR, "Couldn't open audio device.");
		return false;
	}

	if (enabled_debug[LOG_SOUND])
	{
		OpenALInfo::Output_ALCInfo(device, [](const std::string &output) {
			// addDumpInfo(output.c_str());
			//if (enabled_debug[LOG_SOUND])
			//{
				_debug_multiline(0, LOG_SOUND, "sound", output);
			//}
		});
	}

#if defined(ALC_SOFT_HRTF)
	// Load some extensions from OpenAL-Soft (if available)
	alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress(device, "alcGetStringiSOFT");
	alcResetDeviceSOFT = (LPALCRESETDEVICESOFT)alcGetProcAddress(device, "alcResetDeviceSOFT");
#endif


	// Print current device name and add it to dump info
	deviceName = alcGetString(device, ALC_DEVICE_SPECIFIER);
	debug(LOG_SOUND, "Current audio device: %s", deviceName);
	ssprintf(buf, "OpenAL Device Name: %s", deviceName);
	addDumpInfo(buf);

	context = alcCreateContext(device, nullptr);		//NULL was contextAttributes
	if (!context)
	{
		debug(LOG_ERROR, "Couldn't open audio context.");

		debug(LOG_SOUND, "close device");
		if (alcCloseDevice(device) == ALC_FALSE)
		{
			debug(LOG_SOUND, "OpenAl could not close the audio device.");
		}
		device = nullptr;
		return false;
	}

	alcMakeContextCurrent(context);

	err = sound_GetContextError(device);
	if (err != ALC_NO_ERROR)
	{
		debug(LOG_ERROR, "Couldn't initialize audio context: %s", alcGetString(device, err));

		alcGetError(device);	// clear error codes

		alcMakeContextCurrent(nullptr);
		sound_GetContextError(device);
		alcDestroyContext(context); // this gives a long delay on some impl.
		context = nullptr;
		sound_GetContextError(device);

		debug(LOG_SOUND, "close device");
		if (alcCloseDevice(device) == ALC_FALSE)
		{
			debug(LOG_SOUND, "OpenAl could not close the audio device.");
		}
		device = nullptr;
		return false;
	}

	// Dump Open AL device info (depends on context)
	// to the crash handler for the dump file and debug log
	ssprintf(buf, "OpenAL Vendor: %s", alGetString(AL_VENDOR));
	addDumpInfo(buf);
	debug(LOG_SOUND, "%s", buf);

	ssprintf(buf, "OpenAL Version: %s", alGetString(AL_VERSION));
	addDumpInfo(buf);
	debug(LOG_SOUND, "%s", buf);

	ssprintf(buf, "OpenAL Renderer: %s", alGetString(AL_RENDERER));
	addDumpInfo(buf);
	debug(LOG_SOUND, "%s", buf);

	ssprintf(buf, "OpenAL Extensions: %s", alGetString(AL_EXTENSIONS));
	addDumpInfo(buf);
	debug(LOG_SOUND, "%s", buf);

	openal_initialized = true;

#if defined(ALC_SOFT_HRTF)
	if(alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
	{
		// Set desired HRTF mode
		sound_SetHRTFMode(hrtf);

		// Get current HRTF status
		ALCint hrtfStatus;
		alcGetIntegerv(device, ALC_HRTF_STATUS_SOFT, 1, &hrtfStatus);

		const char *hrtfStatusString = nullptr;
		switch (hrtfStatus)
		{
		case ALC_HRTF_DISABLED_SOFT:
			hrtfStatusString = "ALC_HRTF_DISABLED_SOFT: HRTF is disabled";
			break;
		case ALC_HRTF_ENABLED_SOFT:
			hrtfStatusString = "ALC_HRTF_ENABLED_SOFT: HRTF is enabled";
			break;
		case ALC_HRTF_DENIED_SOFT:
			// This may be caused by invalid resource permissions, or other user configuration that disallows HRTF.
			hrtfStatusString = "ALC_HRTF_DENIED_SOFT: HRTF is disabled because it's not allowed on the device.";
			break;
		case ALC_HRTF_REQUIRED_SOFT:
			// This may be caused by a device that can only use HRTF, or other user configuration that forces HRTF to be used.
			hrtfStatusString = "ALC_HRTF_REQUIRED_SOFT: HRTF is enabled because it must be used on the device.";
			break;
		case ALC_HRTF_HEADPHONES_DETECTED_SOFT:
			hrtfStatusString = "ALC_HRTF_HEADPHONES_DETECTED_SOFT: HRTF is enabled automatically because the device reported itself as headphones.";
			break;
		case ALC_HRTF_UNSUPPORTED_FORMAT_SOFT:
			// HRTF is disabled because the device does not support it with the current format.
			// Typically this is caused by non-stereo output or an incompatible output frequency.
			hrtfStatusString = "ALC_HRTF_UNSUPPORTED_FORMAT_SOFT: HRTF is disabled because the device does not support it with the current format.";
			break;
		default:
			hrtfStatusString = nullptr;
			break;
		}

		if (hrtfStatusString)
		{
			debug(LOG_SOUND, "%s", hrtfStatusString);
		}
		else
		{
			debug(LOG_SOUND, "OpenAL-Soft returned an unknown ALC_HRTF_STATUS_SOFT result: %d", hrtfStatus);
		}
	}
	else
	{
		debug(LOG_SOUND, "alcIsExtensionPresent(..., \"ALC_SOFT_HRTF\") returned false");
	}
#else
	debug(LOG_SOUND, "ALC_SOFT_HRTF not defined");
#endif

	// Clear Error Codes
	alGetError();
	alcGetError(device);

	alListener3f(AL_POSITION, 0.f, 0.f, 0.f);
	alListenerfv(AL_VELOCITY, listenerVel);
	alListenerfv(AL_ORIENTATION, listenerOri);
	alDistanceModel(AL_NONE);
	sound_GetError();

	return true;
}

HRTFMode sound_GetHRTFMode()
{
#if defined(ALC_SOFT_HRTF)
	if(alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
	{
		ALCint hrtfStatus;
		alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtfStatus);
		switch (hrtfStatus)
		{
		case ALC_TRUE:
			return HRTFMode::Enabled;
		case ALC_FALSE:
			return HRTFMode::Disabled;
		default:
			debug(LOG_SOUND, "OpenAL-Soft returned an unexpected ALC_HRTF_SOFT result: %d", hrtfStatus);
		}
	}
#endif
	return HRTFMode::Unsupported;
}

bool sound_SetHRTFMode(HRTFMode mode)
{
#if defined(ALC_SOFT_HRTF)
	if(alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
	{
		ALCint hrtfSetting = HRTFModeToALCint(mode);

		ALCint attrs[] = {
			ALC_HRTF_SOFT, hrtfSetting, /* configure HRTF */
			0 /* end of list */
		};
		if (alcResetDeviceSOFT)
		{
			ASSERT(device, "device is null");
			if (!alcResetDeviceSOFT(device, attrs))
			{
				debug(LOG_ERROR, "Failed to reset device: %s\n", alcGetString(device, alcGetError(device)));
				return false;
			}
			return true;
		}
		else
		{
			debug(LOG_ERROR, "ALC_SOFT_HRTF extension is available, but alcResetDeviceSOFT is null");
		}
	}
#endif
	return false;
}

static void sound_UpdateStreams(void);

void sound_ShutdownLibrary(void)
{
	if (!openal_initialized)
	{
		return;
	}
	debug(LOG_SOUND, "starting shutdown");

	// Stop all streams, sound_UpdateStreams() will deallocate all stopped streams
	for (AUDIO_STREAM* stream : active_streams)
	{
		sound_StopStream(stream);
	}
	sound_UpdateStreams();

	alcGetError(device);	// clear error codes

	/* On Linux since this caused some versions of OpenAL to hang on exit. - Per */
	debug(LOG_SOUND, "make default context NULL");
	alcMakeContextCurrent(nullptr);
	sound_GetContextError(device);

	debug(LOG_SOUND, "destroy previous context");
	alcDestroyContext(context); // this gives a long delay on some impl.
	context = nullptr;
	sound_GetContextError(device);

	debug(LOG_SOUND, "close device");
	if (alcCloseDevice(device) == ALC_FALSE)
	{
		debug(LOG_SOUND, "OpenAl could not close the audio device.");
	}
	device = nullptr;

	active_samples.clear();
}

/** Deletes the given sample and performs additional OpenAL cleanup procedures.
 *  \param sample iterator to the current sample in the list which you want to delete, invalidated upon return
 */
static void sound_DestroyIteratedSample(typename std::list<AUDIO_SAMPLE*>::iterator it)
{
	AUDIO_SAMPLE* sample = *it;
	// If an OpenAL source is associated with this sample, release it
	if (sample->iSample != (ALuint)AL_INVALID)
	{
		alDeleteSources(1, &sample->iSample);
		sound_GetError();
	}

	// Do the cleanup of this sample
	sound_FinishedCallback(sample);

	// Remove the sample from the list
	active_samples.erase(it);
}

/** Counts the number of samples in active_samples
 *  \return the number of actively playing sound samples
 */
unsigned int sound_GetActiveSamplesCount()
{
	return static_cast<unsigned int>(active_samples.size());
}

/* gets called in audio.cpp: audio_update(), which gets called in renderLoop() */
void sound_Update()
{

	if (!openal_initialized)
	{
		return;
	}

	// Update all streaming audio
	sound_UpdateStreams();

	mutating_list_iterate(active_samples, [](typename std::list<AUDIO_SAMPLE*>::iterator sampleIt)
	{
		ALenum state, err;
		ALfloat gain;

		AUDIO_SAMPLE* sample = *sampleIt;

		// query what the gain is for this sample
		alGetSourcef(sample->iSample, AL_GAIN, &gain);
		err = sound_GetError();

		// if gain is 0, then we can't hear it, so we kill it.
		if (gain == 0.0f)
		{
			sound_DestroyIteratedSample(sampleIt);
			return IterationResult::CONTINUE_ITERATION;
		}

		//ASSERT(alIsSource(node->curr->iSample), "Not a valid source!");
		alGetSourcei(sample->iSample, AL_SOURCE_STATE, &state);

		// Check whether an error occurred while retrieving the state.
		// If one did, the state returned is useless. So instead of
		// using it continue with the next sample.
		err = sound_GetError();
		if (err != AL_NO_ERROR)
		{
			// Make sure to invoke the "finished" callback
			sound_FinishedCallback(sample);

			// Destroy this object and move to the next object
			sound_DestroyIteratedSample(sampleIt);
			return IterationResult::CONTINUE_ITERATION;
		}

		switch (state)
		{
		case AL_PLAYING:
		case AL_PAUSED:
			// If we haven't finished playing yet, just
			// continue with the next item in the list.

			// sound_SetObjectPosition(i->curr->iSample, i->curr->x, i->curr->y, i->curr->z);

			// Move to the next object
			return IterationResult::CONTINUE_ITERATION;

			// NOTE: if it isn't playing | paused, then it is most likely either done
			// or a error.  In either case, we want to kill the sample in question.

		default:
			sound_DestroyIteratedSample(sampleIt);
			break;
		}
		return IterationResult::CONTINUE_ITERATION;
	});

	// Reset the current error state
	alcGetError(device);

	alcProcessContext(context);

	ALCenum err = sound_GetContextError(device);
	if (err != ALC_NO_ERROR)
	{
		debug(LOG_ERROR, "Error while processing audio context: %s", alGetString(err));
	}
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
bool sound_QueueSamplePlaying()
{
	ALenum	state;

	if (!openal_initialized)
	{
		return false;
	}
	if (current_queue_sample == (ALuint)AL_INVALID)
	{
		return false;
	}

	alGetSourcei(current_queue_sample, AL_SOURCE_STATE, &state);

	// Check whether an error occurred while retrieving the state.
	// If one did, the state returned is useless. So instead of
	// using it return false.
	if (sound_GetError() != AL_NO_ERROR)
	{
		return false;
	}

	if (state == AL_PLAYING)
	{
		return true;
	}

	if (current_queue_sample != (ALuint)AL_INVALID)
	{
		bool sampleFound = false;
		mutating_list_iterate(active_samples, [&sampleFound](typename std::list<AUDIO_SAMPLE*>::iterator sampleIt)
		{
			if ((*sampleIt)->iSample == current_queue_sample)
			{
				sound_DestroyIteratedSample(sampleIt);
				current_queue_sample = AL_INVALID;
				sampleFound = true;
				return IterationResult::BREAK_ITERATION;
			}
			return IterationResult::CONTINUE_ITERATION;
		});
		if (sampleFound)
		{
			return false;
		}

		debug(LOG_ERROR, "Sample %u not deleted because it wasn't in the active queue!", current_queue_sample);
		current_queue_sample = AL_INVALID;
	}
	return false;
}

/** Decodes *entirely* an opened OggVorbis file into an OpenAL buffer.
 *  This is used to play sound effects, not "music". Assumes .ogg file.
 *
 *  \param psTrack pointer to object which will contain the final buffer
 *  \param PHYSFS_fileHandle file handle given by PhysicsFS to the opened file
 *  \return true on success
 */
static inline bool sound_DecodeOggVorbisTrack(TRACK *psTrack, const char* fileName)
{
	if (!openal_initialized)
	{
		return false;
	}

	WZVorbisDecoder* decoder = WZVorbisDecoder::fromFilename(fileName);
	if (!decoder)
	{
		debug(LOG_ERROR, "couldn't allocate decoder for %s", fileName);
		return false;
	}
	const unsigned estimate = decoder->totalSamples() * decoder->channels() * 2;
	uint8_t* buffer = (uint8_t*) malloc(estimate);
	if (buffer == nullptr)
	{
		debug(LOG_ERROR, "couldn't allocate temp buffer to load track %s", fileName);
		delete decoder;
		return false;
	}
	memset(buffer, 0, estimate);
	auto res = decoder->decode(buffer, estimate);
	if (!res.has_value())
	{
		debug(LOG_ERROR, "failed decoding %s", fileName);
		free(buffer);
		delete decoder;
		return false;
	}

	// Determine PCM data format
	ALenum format = (decoder->channels() == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
	ALuint alBuffer;
	// Create an OpenAL buffer and fill it with the decoded data
	alGenBuffers(1, &alBuffer);
	sound_GetError();
	ASSERT(estimate <= static_cast<size_t>(std::numeric_limits<ALsizei>::max()), "soundBuffer->size (%u) exceeds ALsizei::max", estimate);
	ASSERT(decoder->frequency() <= static_cast<size_t>(std::numeric_limits<ALsizei>::max()), "decoder->frequency() (%zu) exceeds ALsizei::max ??", decoder->frequency());
	alBufferData(alBuffer, format, buffer, static_cast<ALsizei>(estimate), static_cast<ALsizei>(decoder->frequency()));
	sound_GetError();

	// save buffer name in track
	psTrack->iBufferName = alBuffer;
	free(buffer);
	delete decoder;
	return true;
}

/** This is used to play sound effets (not "music"). Assumes .ogg file.
 * \param [in] fileName: <soundeffect>.ogg
 * \returns Track pointer, or nullptr on failure
*/
TRACK *sound_LoadTrackFromFile(const char *fileName)
{
	TRACK *pTrack;
	size_t filename_size;
	char *track_name;

	if (GetLastResourceFilename() == nullptr)
	{
		// This is a non fatal error.  We just can't find filename for some reason.
		debug(LOG_WARNING, "sound_LoadTrackFromFile: missing resource filename?");
		filename_size = 0;
	}
	else
	{
		filename_size = strlen(GetLastResourceFilename()) + 1;
	}

	// allocate track, plus the memory required to contain the filename
	// one malloc call ensures only one free call is required
	pTrack = (TRACK *)malloc(sizeof(TRACK) + filename_size);
	if (pTrack == nullptr)
	{
		debug(LOG_FATAL, "sound_ConstructTrack: couldn't allocate memory\n");
		abort();
		return nullptr;
	}

	// Initialize everything (except for the filename) to zero
	memset(pTrack, 0, sizeof(TRACK));

	// Set filename pointer; if the filename (as returned by
	// GetLastResourceFilename()) is a NULL pointer, then this will be a
	// NULL pointer as well.
	track_name = filename_size ? (char *)(pTrack + 1) : nullptr;

	// Copy the filename into the struct, if we don't have a NULL pointer
	if (filename_size != 0)
	{
		strcpy(track_name, GetLastResourceFilename());
	}
	pTrack->fileName = track_name;

	// Now use sound_ReadTrackFromBuffer to decode the file's contents
	if (!sound_DecodeOggVorbisTrack(pTrack, fileName))
	{
		free(pTrack);
		return nullptr;
	}

	return pTrack;
}

void sound_FreeTrack(TRACK *psTrack)
{
	alDeleteBuffers(1, &psTrack->iBufferName);
	sound_GetError();
}

static void sound_AddActiveSample(AUDIO_SAMPLE *psSample)
{
	// Prepend the given sample to our list of active samples
	active_samples.emplace_front(psSample);
}

/** Routine gets rid of the psObj's sound sample and reference in active_samples.
 */
void sound_RemoveActiveSample(AUDIO_SAMPLE *psSample)
{
	mutating_list_iterate(active_samples, [psSample](typename std::list<AUDIO_SAMPLE*>::iterator sampleIt)
	{
		AUDIO_SAMPLE* currSample = *sampleIt;
		if (currSample->psObj != psSample->psObj)
		{
			// Move to the next sample object
			return IterationResult::CONTINUE_ITERATION;
		}
		debug(LOG_MEMORY, "Removing object 0x%p from active_samples list\n", static_cast<void*>(psSample->psObj));

		// Buginator: should we wait for it to finish, or just stop it?
		sound_StopSample(currSample);

		sound_FinishedCallback(currSample);	//tell the callback it is finished.

		sound_DestroyIteratedSample(sampleIt);

		return IterationResult::CONTINUE_ITERATION;
	});
}

static bool sound_SetupChannel(AUDIO_SAMPLE *psSample)
{
	sound_AddActiveSample(psSample);

	return sound_TrackLooped(psSample->iTrack);
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
bool sound_Play2DSample(TRACK *psTrack, AUDIO_SAMPLE *psSample, bool bQueued)
{
	ALfloat zero[3] = { 0.0, 0.0, 0.0 };
	ALfloat volume;
	ALint error;

	if (sfx_volume == 0.0)
	{
		return false;
	}
	volume = ((float)psTrack->iVol / 100.0f);		// each object can have OWN volume!
	psSample->fVol = volume;						// save computed volume
	volume *= sfx_volume;							// and now take into account the Users sound Prefs.

	// We can't hear it, so don't bother creating it.
	if (volume == 0.0f)
	{
		return false;
	}

	// Clear error codes
	alGetError();

	alGenSources(1, &(psSample->iSample));

	error = sound_GetError();
	if (error != AL_NO_ERROR)
	{
		/* FIXME: We run out of OpenAL sources very quickly, so we
		 * should handle the case where we've ran out of them.
		 * Currently we don't do this, causing some unpleasant side
		 * effects, e.g. crashing...
		 */
	}

	alSourcef(psSample->iSample, AL_PITCH, 1.0f);
	alSourcef(psSample->iSample, AL_GAIN, volume);
	alSourcefv(psSample->iSample, AL_POSITION, zero);
	alSourcefv(psSample->iSample, AL_VELOCITY, zero);
	alSourcei(psSample->iSample, AL_BUFFER, psTrack->iBufferName);
	alSourcei(psSample->iSample, AL_SOURCE_RELATIVE, AL_TRUE);
	alSourcei(psSample->iSample, AL_LOOPING, (sound_SetupChannel(psSample)) ? AL_TRUE : AL_FALSE);

	// NOTE: this is only useful for debugging.
#ifdef DEBUG
	psSample->is3d = false;
	psSample->isLooping = sound_TrackLooped(psSample->iTrack) ? AL_TRUE : AL_FALSE;
	memcpy(psSample->filename, psTrack->fileName, strlen(psTrack->fileName));
	psSample->filename[strlen(psTrack->fileName)] = '\0';
#endif
	// Clear error codes
	alGetError();

	alSourcePlay(psSample->iSample);
	sound_GetError();

	if (bQueued)
	{
		current_queue_sample = psSample->iSample;
	}
	else if (current_queue_sample == psSample->iSample)
	{
		current_queue_sample = -1;
	}

	return true;
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
bool sound_Play3DSample(TRACK *psTrack, AUDIO_SAMPLE *psSample)
{
	ALfloat zero[3] = { 0.0, 0.0, 0.0 };
	ALfloat volume;
	ALint error;

	if (sfx3d_volume == 0.0)
	{
		return false;
	}

	volume = ((float)psTrack->iVol / 100.f);		// max range is 0-100
	psSample->fVol = volume;						// store results for later

	// If we can't hear it, then don't bother playing it.
	if (volume == 0.0f)
	{
		return false;
	}
	// Clear error codes
	alGetError();

	alGenSources(1, &(psSample->iSample));

	error = sound_GetError();
	if (error != AL_NO_ERROR)
	{
		/* FIXME: We run out of OpenAL sources very quickly, so we
		 * should handle the case where we've ran out of them.
		 * Currently we don't do this, causing some unpleasant side
		 * effects, e.g. crashing...
		 */
	}

#if defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)
	// HACK: this is a workaround for a bug in the 64bit implementation of OpenAL on GNU/Linux
	// The AL_PITCH value really should be 1.0.
	alSourcef(psSample->iSample, AL_PITCH, 1.001f);
#else
	alSourcef(psSample->iSample, AL_PITCH, 1.0f);
#endif

	sound_SetObjectPosition(psSample);
	alSourcefv(psSample->iSample, AL_VELOCITY, zero);
	alSourcei(psSample->iSample, AL_BUFFER, psTrack->iBufferName);
	alSourcei(psSample->iSample, AL_LOOPING, (sound_SetupChannel(psSample)) ? AL_TRUE : AL_FALSE);

	// NOTE: this is only useful for debugging.
#ifdef DEBUG
	psSample->is3d = true;
	psSample->isLooping = sound_TrackLooped(psSample->iTrack) ? AL_TRUE : AL_FALSE;
	memcpy(psSample->filename, psTrack->fileName, strlen(psTrack->fileName));
	psSample->filename[strlen(psTrack->fileName)] = '\0';
#endif

	// Clear error codes
	alGetError();

	alSourcePlay(psSample->iSample);
	sound_GetError();

	return true;
}

/** Fills N buffers, each of buffSize
 *  Only frees whatever was allocated by itself.
 * \returns nb of buffers copied (but not enqueued yet) to openAL
*/
static int sound_fillNBuffers(ALuint* alBuffersIds, WZDecoder* decoder, size_t n, size_t buffSize)
{
	ASSERT_OR_RETURN(-1, n <= static_cast<size_t>(std::numeric_limits<int>::max()), "number of buffers (%zu) exceeds int::max", n);
	static uint8_t *pcm = (uint8_t*) malloc(buffSize);
	if (!pcm)
	{
		debug(LOG_ERROR, "can't allocate buff of size %zu", buffSize);
		return -1;
	}
	// Determine PCM data format
	ALenum format = (decoder->channels() == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
	int i = 0;
	const int i_max = static_cast<int>(n);
	for (; i < i_max; ++i)
	{
		memset(pcm, 0, buffSize);
		// Decode some audio data
		auto res = decoder->decode(pcm, buffSize);

		if (!res.has_value())
		{
			//free(pcm);
			sound_GetError();
			return -1;
		}

		// If we actually decoded some data
		if (res.value() > 0)
		{
			ASSERT(res.value() <= static_cast<size_t>(std::numeric_limits<ALint>::max()), "read size (%zu) exceeds ALint::max", res.value());
			alBufferData(alBuffersIds[i], format, pcm, static_cast<ALint>(res.value()), static_cast<ALsizei>(decoder->frequency()));
			sound_GetError();
		}
		else // if (res.value() == 0)
		{
			// If no data has been decoded we're probably at the end of our
			// stream. So cleanup the excess stuff here.
			// First remove the data buffer itself
			//free(pcm);
			sound_GetError();
			break;
		}
	}
	// all good: return how many buffers were actually (at least partially) filled
	return i;
}


/** Plays the audio data from the given file
 *  \param volume the volume to play the audio at (in a range of 0.0 to 1.0)
 *  \param onFinished callback to invoke when we're finished playing
 *  \param user_data user-data pointer to pass to the \c onFinished callback
 *  \return a pointer to the currently playing stream when playing started
 *          successfully, NULL otherwise.
 *  \note The returned pointer will become invalid/dangling immediately after
 *        the \c onFinished callback is invoked.
 *  \note You must _never_ manually free() the memory used by the returned
 *        pointer.
 */
AUDIO_STREAM *sound_PlayStream(const char* fileName, bool bufferEntireStream,
	float volume,
	const std::function<void (const AUDIO_STREAM *, const void *)>& onFinished,
	const void *user_data)
{
	if (!openal_initialized)
	{
		debug(LOG_WARNING, "OpenAL isn't initialized, not creating an audio stream");
		return nullptr;
	}
		// Clean errors
	alGetError();
	WZDecoder *decoder = nullptr;
	const size_t len = strlen(fileName);
	if (len > 4 && (strncasecmp(fileName + len - 4, ".ogg", 4) == 0))
	{
		decoder = WZVorbisDecoder::fromFilename(fileName);
	}
	else if (len > 5 && (strncasecmp(fileName + len - 5, ".opus", 5) == 0))
	{
		decoder = WZOpusDecoder::fromFilename(fileName, bufferEntireStream);
	}
	if (!decoder)
	{
		debug(LOG_ERROR, "couldn't allocate decoder for %s", fileName);
		return nullptr;
	}

	AUDIO_STREAM *stream = new AUDIO_STREAM();
	if (stream == nullptr)
	{
		debug(LOG_FATAL, "sound_PlayStream: Out of memory");
		abort();
		return nullptr;
	}
	stream->decoder = decoder;
	// Retrieve an OpenAL sound source
	alGenSources(1, &(stream->source));
	if (sound_GetError() != AL_NO_ERROR)
	{
		// Failed to create OpenAL sound source, so bail out...
		debug(LOG_SOUND, "alGenSources failed, most likely out of sound sources");
		delete stream;
		delete decoder;
		return nullptr;
	}

	stream->volume = volume;
	alSourcef(stream->source, AL_GAIN, stream->volume);

#if defined(WZ_OS_UNIX) && !defined(WZ_OS_MAC)
	// HACK: this is a workaround for a bug in the 64bit implementation of OpenAL on GNU/Linux
	// The AL_PITCH value really should be 1.0.
	alSourcef(stream->source, AL_PITCH, 1.001f);
#else
	alSourcef(stream->source, AL_PITCH, 1.0f);
#endif
	if (sound_GetError() != AL_NO_ERROR)
	{
		delete decoder;
		delete stream;
		return nullptr;
	}
	int res =0;
	// Create some OpenAL buffers to store the decoded data in
	static ALuint       *alBuffersIds = (ALuint *) malloc(buffer_count * sizeof(ALuint));
	memset(alBuffersIds, 0, buffer_count * sizeof(ALuint));
	alGenBuffers(buffer_count, alBuffersIds);
	if (sound_GetError() != AL_NO_ERROR) { goto _error; }
	// Copy the audio data into one of OpenAL's own buffers
	ASSERT(bufferSize <= static_cast<size_t>(std::numeric_limits<ALsizei>::max()), "soundBuffer->size (%zu) exceeds ALsizei::max", bufferSize);

	res = sound_fillNBuffers(alBuffersIds, decoder, buffer_count, bufferSize);
	// Bail out if we didn't fill any buffers
	if (res <= 0)
	{
		debug(LOG_ERROR, "Failed to fill buffers with decoded audio data!");
		goto _error_with_albuffers;
	}
	// Attach the OpenAL buffers to our OpenAL source
	alGetError();
	if (res < buffer_count)
	{
		// free unused buffers
		debug(LOG_SOUND, "freeing unused %i buffers", buffer_count - res);
		alDeleteBuffers(buffer_count - res, alBuffersIds + res);
		if (sound_GetError() != AL_NO_ERROR) {	goto _error_with_albuffers; }
	}

	alSourceQueueBuffers(stream->source, res, alBuffersIds);
	if (sound_GetError() != AL_NO_ERROR) {	goto _error_with_albuffers; }

	// Start playing the source
	alGetError();
	alSourcePlay(stream->source);
	if (sound_GetError() != AL_NO_ERROR) {	goto _error_with_albuffers; }

	// Set callback info
	stream->onFinished = onFinished;
	stream->user_data = user_data;

	// Prepend this stream to the linked list
	active_streams.emplace_front(stream);

	return stream;

	_error_with_albuffers:
		alDeleteBuffers(buffer_count, alBuffersIds);

	_error:
		alDeleteSources(1, &stream->source);
		delete stream;
		delete decoder;
		return nullptr;
}

/** Checks if the stream is playing.
 *  \param stream the stream to check
 *  \post true if playing, false otherwise.
 *
 */
bool sound_isStreamPlaying(AUDIO_STREAM *stream)
{
	ALint state;
	alGetError();
	if (stream)
	{
		alGetSourcei(stream->source, AL_SOURCE_STATE, &state);
		sound_GetError();
		if (state == AL_PLAYING)
		{
			return true;
		}
	}
	return false;
}

/** Stops the current stream from playing.
 *  \param stream the stream to stop
 *  \post The stopped stream will be destroyed on the next invocation of
 *        sound_UpdateStreams(). So calling this function will result in the
 *        \c onFinished callback being called and the \c stream pointer becoming
 *        invalid.
 */
void sound_StopStream(AUDIO_STREAM *stream)
{
	assert(stream != nullptr);

	alGetError();	// clear error codes
	stream->queuedStop = true;
	// Tell OpenAL to stop playing on the given source
	alSourceStop(stream->source);
	sound_GetError();
}

/** Pauses playing of this stream until playing is resumed with
 *  sound_ResumeStream() or completely stopped with sound_StopStream().
 *  \param stream the stream to pause playing for
 */
void sound_PauseStream(AUDIO_STREAM *stream)
{
	ALint state;

	// To be sure we won't go mutilating this OpenAL source, check whether
	// it's playing first.
	alGetError();
	alGetSourcei(stream->source, AL_SOURCE_STATE, &state);
	sound_GetError();

	if (state != AL_PLAYING)
	{
		return;
	}

	// Pause playing of this OpenAL source
	alSourcePause(stream->source);
	sound_GetError();
}

/** Resumes playing of a stream that's paused by means of sound_PauseStream().
 *  \param stream the stream to resume playing for
 */
void sound_ResumeStream(AUDIO_STREAM *stream)
{
	ALint state;

	// To be sure we won't go mutilating this OpenAL source, check whether
	// it's paused first.
	alGetError();
	alGetSourcei(stream->source, AL_SOURCE_STATE, &state);
	sound_GetError();

	if (state != AL_PAUSED)
	{
		return;
	}

	// Resume playing of this OpenAL source
	alSourcePlay(stream->source);
	sound_GetError();
}

/** Retrieve the playing volume of the given stream.
 *
 *  @param stream the stream to retrieve the volume for.
 *
 *  @return a floating point value between 0.f and 1.f, representing this
 *          stream's volume.
 */
float sound_GetStreamVolume(const AUDIO_STREAM *stream)
{
	ALfloat volume;
	alGetError();
	alGetSourcef(stream->source, AL_GAIN, &volume);
	sound_GetError();

	return volume;
}

/** Set the playing volume of the given stream.
 *
 *  @param stream the stream to change the volume for.
 *  @param volume a floating point value between 0.f and 1.f, to use as this
 *                @c stream's volume.
 */
void sound_SetStreamVolume(AUDIO_STREAM *stream, float volume)
{
	alGetError();
	stream->volume = volume;
	alSourcef(stream->source, AL_GAIN, stream->volume);
	sound_GetError();
}

double sound_GetStreamTotalTime(AUDIO_STREAM *stream)
{
	return stream->decoder->totalTime();
}

/** Update the given stream (="alSource" in openAL parlance) by making sure its buffers remain full
 *  \param stream the stream to update
 *  \return true when the stream is still playing, false when it has stopped
 */
static bool sound_UpdateStream(AUDIO_STREAM *stream)
{
	ALint state, buffers_processed_count;
	alGetError();
	alGetSourcei(stream->source, AL_SOURCE_STATE, &state);
	sound_GetError();

	if (state != AL_PLAYING && state != AL_PAUSED && (state != AL_STOPPED || stream->queuedStop))
	{
		return false;
	}

	// Retrieve the amount of buffers which were processed and need refilling
	alGetSourcei(stream->source, AL_BUFFERS_PROCESSED, &buffers_processed_count);
	if (sound_GetError() != AL_NO_ERROR) { return false; }
	if (buffers_processed_count == 0) { return true; }

	// Determine PCM data format
	ALuint *alBuffersIds = (ALuint *) malloc(buffers_processed_count * sizeof(ALuint));
	alSourceUnqueueBuffers(stream->source, buffers_processed_count, alBuffersIds);
	if (sound_GetError() != AL_NO_ERROR) { return false; }

	auto freeUnusedALBuffers = [alBuffersIds, buffers_processed_count](ALint startingIdx) {
		if (startingIdx < buffers_processed_count)
		{
			alDeleteBuffers(buffers_processed_count - startingIdx, &alBuffersIds[startingIdx]);
		}
	};

	const auto res = sound_fillNBuffers(alBuffersIds, stream->decoder, buffers_processed_count, bufferSize);
	if (res == 0)
	{
		// nothing more to read and queue - will be deleted with sound_DestroyStream (later, when done playing)
		sound_GetError();
		freeUnusedALBuffers(0);
		free(alBuffersIds);
		if (state != AL_STOPPED)
		{
			return true; // must return true here - don't shortcut playing the remaining buffers!
		}
		else
		{
			// no more buffers to read, and the existing audio has stopped
			return false;
		}
	}
	if (res < 0)
	{
		debug(LOG_ERROR, "bailing out");
		freeUnusedALBuffers(0);
		free(alBuffersIds);
		return false;
	}
	// Reattach the filled buffers to the source
	alSourceQueueBuffers(stream->source, res, alBuffersIds);
	// Delete any unused unqueued buffers
	freeUnusedALBuffers(res);
	sound_GetError();
	free(alBuffersIds);

	if (state == AL_STOPPED && !stream->queuedStop)
	{
		// Resume playing of this OpenAL source
		debug(LOG_SOUND, "Auto-resuming play of stream");
		alSourcePlay(stream->source);
		if (sound_GetError() != AL_NO_ERROR) { return false; }
	}

	return true;
}

/** Destroy the given stream (="alSource" in openAL parlance) and release its associated resources. This function
 *  also handles calling of the \c onFinished callback function and closing of
 *  the PhysicsFS file handle.
 *  \param stream the stream to destroy
 *  \note  we are not exiting on errors, we don't want to leak memory...
 */
static void sound_DestroyStream(AUDIO_STREAM *stream)
{
	ALint buffers_processed_count = 0;
	ALuint *buffers = nullptr;

	// Stop the OpenAL source from playing
	alGetError();
	alSourceStop(stream->source);

	sound_GetError();

	// Retrieve the amount of buffers which were processed
	alGetSourcei(stream->source, AL_BUFFERS_PROCESSED, &buffers_processed_count);
	if(sound_GetError() != AL_NO_ERROR)
	{
		buffers_processed_count = 0;
		// proceed as if nothing happened
	}

	// Detach all buffers and retrieve their ID numbers
	if (buffers_processed_count > 0)
	{
		const size_t buffer_count_sizet = static_cast<size_t>(buffers_processed_count);
		buffers = (ALuint *)malloc(buffer_count_sizet * sizeof(ALuint));
		memset(buffers, 0, buffer_count_sizet * sizeof(ALuint));
		alSourceUnqueueBuffers(stream->source, buffers_processed_count, buffers);
		sound_GetError();

		// Destroy all of these buffers
		alDeleteBuffers(buffers_processed_count, buffers);
		sound_GetError();
		free(buffers);
	}
	else
	{
		debug(LOG_SOUND, "alGetSourcei(AL_BUFFERS_PROCESSED) returned count: %d", buffers_processed_count);
	}

	// Destroy the OpenAL source
	alDeleteSources(1, &stream->source);
	sound_GetError();

	// Destroy the sound decoder
	delete stream->decoder;

	// Now call the finished callback
	if (stream->onFinished)
	{
		ASSERT(stream->user_data == nullptr, "user_data was not null!");
		stream->onFinished(stream, stream->user_data);
	}

	// Free the memory used by this stream
	delete stream;
}

/** Update all currently running streams(="alSource"s) and destroy them when they're finished.
 */
static void sound_UpdateStreams()
{
	mutating_list_iterate(active_streams, [](typename std::list<AUDIO_STREAM*>::iterator streamIt)
	{
		// Attempt to update the current stream, if we find that impossible,
		// destroy it instead.
		if (!sound_UpdateStream(*streamIt))
		{
			AUDIO_STREAM* stream = *streamIt;
			// First remove our current stream from the linked list
			active_streams.erase(streamIt);
			// Now actually destroy the current stream
			sound_DestroyStream(stream);
		}
		return IterationResult::CONTINUE_ITERATION;
	});
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
void sound_StopSample(AUDIO_SAMPLE *psSample)
{
	if (psSample->iSample == (ALuint)SAMPLE_NOT_ALLOCATED)
	{
		debug(LOG_SOUND, "sound_StopSample: sample number (%u) out of range, we probably have run out of available OpenAL sources", psSample->iSample);
		return;
	}
	alGetError();	// clear error codes
	// Tell OpenAL to stop playing the given sample
	alSourceStop(psSample->iSample);
	sound_GetError();
}

void sound_SetPlayerPos(Vector3f pos)
{
	alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
	sound_GetError();
}

/**
 * Sets the player's orientation to use for sound
 * \param angle the angle in radians
 @NOTE the up vector is swapped because of qsound idiosyncrasies
 @FIXME we don't use qsound, but it still is in qsound 'format'...
*/
void sound_SetPlayerOrientation(float angle)
{
	const ALfloat ori[6] =
	{
		-sinf(angle), cosf(angle), 0.0f,	// forward (at) vector
		0.0f, 0.0f, 1.0f,					// up vector
	};
	alGetError();
	alListenerfv(AL_ORIENTATION, ori);
	sound_GetError();
}

/**
 * Sets the player's orientation to use for sound
 * \param forward forward pointing vector
 * \param up      upward pointing vector
 */
void sound_SetPlayerOrientationVector(Vector3f forward, Vector3f up)
{
	const ALfloat ori[6] =
	{
		forward.x, forward.y, forward.z,
		up.x,      up.y,      up.z,
	};
	alGetError();
	alListenerfv(AL_ORIENTATION, ori);
	sound_GetError();
}

//*
// =======================================================================================================================
// Compute the sample's volume relative to AL_POSITION.
// =======================================================================================================================
//
void sound_SetObjectPosition(AUDIO_SAMPLE *psSample)
{
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// coordinates
	float	listenerX, listenerY, listenerZ, dX, dY, dZ;

	// calculation results
	float	distance, gain;
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	// only set it when we have a valid sample
	if (!psSample)
	{
		return;
	}
	alGetError();
	// compute distance
	alGetListener3f(AL_POSITION, &listenerX, &listenerY, &listenerZ);
	sound_GetError();
	dX = psSample->x  - listenerX; // distances on all axis
	dY = psSample->y - listenerY;
	dZ = psSample->z - listenerZ;
	distance = sqrtf(dX * dX + dY * dY + dZ * dZ); // Pythagorean theorem

	// compute gain
	gain = (1.0f - (distance * ATTENUATION_FACTOR)) * psSample->fVol * sfx3d_volume;
	// max volume
	if (gain > 1.0f)
	{
		gain = 1.0f;
	}
	if (gain < 0.0f)
	{
		// this sample can't be heard right now
		gain = 0.0f;
	}
	alSourcef(psSample->iSample, AL_GAIN, gain);

	// the alSource3i variant would be better, if it wouldn't provide linker errors however
	alSource3f(psSample->iSample, AL_POSITION, (float)psSample->x, (float)psSample->y, (float)psSample->z);
	sound_GetError();

	return;
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
void sound_PauseSample(AUDIO_SAMPLE *psSample)
{
	alGetError();
	alSourcePause(psSample->iSample);
	sound_GetError();
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
void sound_ResumeSample(AUDIO_SAMPLE *psSample)
{
	alGetError();
	alSourcePlay(psSample->iSample);
	sound_GetError();
}

//*
// =======================================================================================================================
// =======================================================================================================================
//
bool sound_SampleIsFinished(AUDIO_SAMPLE *psSample)
{
	ALenum	state;
	alGetError();
	alGetSourcei(psSample->iSample, AL_SOURCE_STATE, &state);
	sound_GetError(); // check for an error and clear the error state for later on in this function
	if (state == AL_PLAYING || state == AL_PAUSED)
	{
		return false;
	}

	if (psSample->iSample != (ALuint)AL_INVALID)
	{
		alDeleteSources(1, &(psSample->iSample));
		sound_GetError();
		psSample->iSample = AL_INVALID;
	}

	return true;
}

//*
// =======================================================================================================================
// =======================================================================================================================
//

float sound_GetUIVolume()
{
	return sfx_volume;
}

void sound_SetUIVolume(float volume)
{
	sfx_volume = volume;

	// Keep volume in the range of 0.0 - 1.0
	if (sfx_volume < 0.0)
	{
		sfx_volume = 0.0;
	}
	else if (sfx_volume > 1.0)
	{
		sfx_volume = 1.0;
	}
}

float sound_GetEffectsVolume()
{
	return sfx3d_volume;
}

void sound_SetEffectsVolume(float volume)
{
	sfx3d_volume = volume;

	// Keep volume in the range of 0.0 - 1.0
	if (sfx3d_volume < 0.0)
	{
		sfx3d_volume = 0.0;
	}
	else if (sfx3d_volume > 1.0)
	{
		sfx3d_volume = 1.0;
	}
}