/
system.cpp
2912 lines (2475 loc) · 81.9 KB
/
system.cpp
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
/** @file system.cpp Audio subsystem module.
*
* @authors Copyright © 2003-2013 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2015 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2006-2007 Jamie Jones <jamie_jones_au@yahoo.com.au> *
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program 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. This program 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 this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#define DENG_NO_API_MACROS_SOUND
#include "audio/system.h"
#include "dd_share.h" // SF_* flags
#include "dd_main.h" // ::isDedicated
#include "def_main.h" // ::defs
#ifdef __CLIENT__
# include "sys_system.h" // Sys_Sleep()
#endif
#ifdef __CLIENT__
# include "client/clientsubsector.h"
#endif
#ifdef __SERVER__
# include "server/sv_sound.h"
#endif
#ifdef __CLIENT__
# include "audio/m_mus2midi.h"
# include "audio/sfxchannel.h"
#endif
#include "audio/s_cache.h"
#include "api_map.h"
#ifdef __CLIENT__
# include "world/audioenvironment.h"
#endif
#include "world/p_players.h"
#include "world/thinkers.h"
#include "Sector"
#include "Subsector"
#include <doomsday/console/cmd.h>
#include <doomsday/console/var.h>
#ifdef __CLIENT__
# include <doomsday/defs/music.h>
# include <doomsday/filesys/fs_main.h>
# include <doomsday/filesys/fs_util.h>
#endif
#include <de/App>
#include <de/CommandLine>
#include <de/FileSystem>
#include <de/NativeFile>
#include <de/timer.h>
#include <de/c_wrapper.h>
#ifdef __CLIENT__
# include <de/concurrency.h>
# include <de/memory.h>
#endif
#include <QMultiHash>
#include <QtAlgorithms>
using namespace de;
dint soundMinDist = 256; // No distance attenuation this close.
dint soundMaxDist = 2025;
// Setting these variables is enough to adjust the volumes.
// S_StartFrame() will call the actual routines to change the volume
// when there are changes.
dint sfxVolume = 255 * 2/3;
dint musVolume = 255 * 2/3;
dint sfxBits = 8;
dint sfxRate = 11025;
#ifdef __CLIENT__
# ifdef MACOSX
/// Built-in QuickTime audio interface implemented by MusicPlayer.m
DENG_EXTERN_C audiointerface_music_t audiodQuickTimeMusic;
# endif
#endif
namespace audio {
static audio::System *theAudioSystem;
static duint const SOUND_LOGICAL_PURGEINTERVAL = 2000; ///< 2 seconds
#ifdef __CLIENT__
static dint const SOUND_CHANNEL_COUNT_DEFAULT = 16;
static dint const SOUND_CHANNEL_COUNT_MAX = 256;
static dint const SOUND_CHANNEL_2DCOUNT = 4;
static char const *MUSIC_BUFFEREDFILE = "/tmp/dd-buffered-song";
static thread_t refreshHandle;
static volatile bool allowRefresh, refreshing;
static bool sfxNoRndPitch; ///< @todo should be a cvar.
// Console variables:
static dint sfx16Bit;
static dint sfxSampleRate = 11025;
static dint sfx3D;
#endif // __CLIENT__
static byte sfxOneSoundPerEmitter; //< @c false= Traditional Doomsday behavior: allow sounds to overlap.
#ifdef __CLIENT__
static dfloat sfxReverbStrength = 0.5f;
static char *musMidiFontPath = (char *) "";
// When multiple sources are available this setting determines which to use (mus < ext < cd).
static audio::System::MusicSource musSourcePreference = audio::System::MUSP_EXT;
/**
* This is a high-priority thread that periodically checks if the channels need
* to be updated with more data. The thread terminates when it notices that the
* channels have been destroyed. The Sfx audio driver maintains a 250ms buffer
* for each channel, which means the refresh must be done often enough to keep
* them filled.
*
* @todo Use a real mutex, will you?
*/
static dint C_DECL sfxChannelRefreshThread(void *)
{
// We'll continue looping until the Sfx module is shut down.
while(App_AudioSystem().sfxIsAvailable() && App_AudioSystem().hasSfxChannels())
{
// The bit is swapped on each refresh (debug info).
::refMonitor ^= 1;
if(allowRefresh)
{
// Do the refresh.
refreshing = true;
App_AudioSystem().sfxChannels().refreshAll();
refreshing = false;
// Let's take a nap.
Sys_Sleep(200);
}
else
{
// Refreshing is not allowed, so take a shorter nap while
// waiting for allowRefresh.
Sys_Sleep(150);
}
}
// Time to end this thread.
return 0;
}
static audiodriverid_t identifierToDriverId(String name)
{
static String const driverIdentifier[AUDIODRIVER_COUNT] = {
"dummy",
"sdlmixer",
"openal",
"fmod",
"fluidsynth",
"dsound",
"winmm"
};
name = name.toLower();
for(dint i = 0; i < AUDIODRIVER_COUNT; ++i)
{
if(name == driverIdentifier[i]) return audiodriverid_t( i );
}
LOG_AUDIO_ERROR("'%s' is not a valid audio driver name") << name;
return AUDIOD_INVALID;
}
/**
* Returns @c true if the given @a file appears to contain MUS format music.
*/
static bool recognizeMus(de::File1 &file)
{
char buf[4];
file.read((uint8_t *)buf, 0, 4);
// ASCII "MUS" and CTRL-Z (hex 4d 55 53 1a)
return !qstrncmp(buf, "MUS\x01a", 4);
}
#endif
DENG2_PIMPL(System)
, DENG2_OBSERVES(DoomsdayApp, GameUnload)
#ifdef __CLIENT__
, DENG2_OBSERVES(SfxSampleCache, SampleRemove)
#endif
{
#ifdef __CLIENT__
AudioDriver drivers[AUDIODRIVER_COUNT];
AudioDriver &driverById(audiodriverid_t id)
{
DENG2_ASSERT(VALID_AUDIODRIVER_IDENTIFIER(id));
return drivers[id];
}
/**
* Chooses the default audio driver based on configuration options.
*/
audiodriverid_t chooseAudioDriver()
{
CommandLine &cmdLine = App::commandLine();
// No audio output?
if(::isDedicated)
return AUDIOD_DUMMY;
if(cmdLine.has("-dummy"))
return AUDIOD_DUMMY;
if(cmdLine.has("-fmod"))
return AUDIOD_FMOD;
if(cmdLine.has("-oal") || cmdLine.has("-openal"))
return AUDIOD_OPENAL;
#ifdef WIN32
if(cmdLine.has("-dsound"))
return AUDIOD_DSOUND;
if(cmdLine.has("-winmm"))
return AUDIOD_WINMM;
#endif
#ifndef DENG_DISABLE_SDLMIXER
if(cmdLine.has("-sdlmixer"))
return AUDIOD_SDL_MIXER;
#endif
// The default audio driver.
return AUDIOD_FMOD;
}
/**
* Initializes the audio driver interfaces.
*
* @return @c true iff successful.
*/
bool initDriver(audiodriverid_t driverId)
{
LOG_AS("audio::System");
try
{
AudioDriver &driver = driverById(driverId);
switch(driverId)
{
case AUDIOD_DUMMY: driver.load("dummy"); break;
#ifndef DENG_DISABLE_SDLMIXER
case AUDIOD_SDL_MIXER: driver.load("sdlmixer"); break;
#endif
case AUDIOD_OPENAL: driver.load("openal"); break;
case AUDIOD_FMOD: driver.load("fmod"); break;
case AUDIOD_FLUIDSYNTH: driver.load("fluidsynth"); break;
#ifdef WIN32
case AUDIOD_DSOUND: driver.load("directsound"); break;
case AUDIOD_WINMM: driver.load("winmm"); break;
#endif
default: return false;
}
// All loaded drivers are automatically initialized so they are ready for use.
driver.initialize();
return driver.isInitialized();
}
catch(AudioDriver::LoadError const &er)
{
LOG_AUDIO_WARNING("Failed initializing driver \"%s\":\n")
<< AudioDriver_GetName(driverId)
<< er.asText();
}
return false;
}
audiodriverid_t initDriverIfNeeded(String const &identifier)
{
audiodriverid_t id = identifierToDriverId(identifier);
AudioDriver &driver = driverById(id);
if(!driver.isInitialized())
{
initDriver(id);
}
return id;
}
bool loadDrivers()
{
activeInterfaces.clear();
if(App::commandLine().has("-nosound"))
return false;
audiodriverid_t defaultDriverId = chooseAudioDriver();
bool ok = initDriver(defaultDriverId);
// Fallback option for the default driver.
#ifndef DENG_DISABLE_SDLMIXER
if(!ok)
{
defaultDriverId = AUDIOD_SDL_MIXER;
ok = initDriver(defaultDriverId);
}
#endif
if(ok)
{
// Choose the interfaces to use.
selectInterfaces(defaultDriverId);
}
return ok;
}
void unloadDrivers()
{
// Deinitialize all loaded drivers. (Note: reverse order)
for(dint i = AUDIODRIVER_COUNT; i--> 0; )
{
drivers[i].deinitialize();
}
// Unload the plugins after everything has been shut down.
for(AudioDriver &driver : drivers)
{
driver.unload();
}
// No more interfaces available.
activeInterfaces.clear();
}
/**
* The active/loaded interfaces.
*
* @todo The audio interface could also declare which audio formats it is capable
* of playing (e.g., MIDI only, CD tracks only).
*/
struct AudioInterface
{
audiointerfacetype_t type;
union {
void *any;
audiointerface_sfx_t *sfx;
audiointerface_music_t *music;
audiointerface_cd_t *cd;
} i;
};
QList<AudioInterface> activeInterfaces;
/**
* Choose the SFX, Music, and CD audio interfaces to use.
*
* @param defaultDriverId Default audio driver to use unless overridden.
*/
void selectInterfaces(audiodriverid_t defaultDriverId)
{
AudioDriver &defaultDriver = driverById(defaultDriverId);
// The default driver goes on the bottom of the stack.
if(defaultDriver.hasSfx())
{
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_ISFX;
ifs.i.any = &defaultDriver.iSfx();
activeInterfaces << ifs; // a copy is made
}
if(defaultDriver.hasMusic())
{
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_IMUSIC;
ifs.i.any = &defaultDriver.iMusic();
activeInterfaces << ifs; // a copy is made
}
#ifdef MACOSX
else if(defaultDriverId != AUDIOD_DUMMY)
{
// On the Mac, use the built-in QuickTime interface as the fallback for music.
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_IMUSIC;
ifs.i.any = &::audiodQuickTimeMusic;
activeInterfaces << ifs; // a copy is made
}
#endif
#ifndef WIN32
// At the moment, dsFMOD supports streaming samples so we can
// automatically load dsFluidSynth for MIDI music.
if(defaultDriverId == AUDIOD_FMOD)
{
initDriverIfNeeded("fluidsynth");
AudioDriver &fluidSynth = driverById(AUDIOD_FLUIDSYNTH);
if(fluidSynth.isInitialized())
{
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_IMUSIC;
ifs.i.any = &fluidSynth.iMusic();
activeInterfaces << ifs; // a copy is made
}
}
#endif
if(defaultDriver.hasCd())
{
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_ICD;
ifs.i.any = &defaultDriver.iCd();
activeInterfaces << ifs; // a copy is made
}
CommandLine &cmdLine = App::commandLine();
for(dint p = 1; p < cmdLine.count() - 1; ++p)
{
if(!cmdLine.isOption(p)) continue;
// Check for SFX override.
if(cmdLine.matches("-isfx", cmdLine.at(p)))
{
AudioDriver &driver = driverById(initDriverIfNeeded(cmdLine.at(++p)));
if(!driver.hasSfx())
throw Error("selectInterfaces", "Audio driver '" + driver.name() + "' does not provide an SFX interface");
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_ISFX;
ifs.i.any = &driver.iSfx();
activeInterfaces << ifs; // a copy is made
continue;
}
// Check for Music override.
if(cmdLine.matches("-imusic", cmdLine.at(p)))
{
AudioDriver &driver = driverById(initDriverIfNeeded(cmdLine.at(++p)));
if(!driver.hasMusic())
throw Error("selectInterfaces", "Audio driver '" + driver.name() + "' does not provide a Music interface");
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_IMUSIC;
ifs.i.any = &driver.iMusic();
activeInterfaces << ifs; // a copy is made
continue;
}
// Check for CD override.
if(cmdLine.matches("-icd", cmdLine.at(p)))
{
AudioDriver &driver = driverById(initDriverIfNeeded(cmdLine.at(++p)));
if(!driver.hasCd())
throw Error("selectInterfaces", "Audio driver '" + driver.name() + "' does not provide a CD interface");
AudioInterface ifs; zap(ifs);
ifs.type = AUDIO_ICD;
ifs.i.any = &driver.iCd();
activeInterfaces << ifs; // a copy is made
continue;
}
}
// Let the music driver(s) know of the primary sfx interface, in case they
// want to play audio through it.
setMusicProperty(AUDIOP_SFX_INTERFACE, self.sfx());
}
/**
* Iterate through the active interfaces of a given type, in descending priority
* order: the most important interface is visited first.
*
* @param type Type of interface to process.
* @param func Callback to make for each interface.
*/
LoopResult forAllInterfaces(audiointerfacetype_t type, std::function<LoopResult (void *)> func) const
{
if(type != AUDIO_INONE)
{
for(dint i = activeInterfaces.count(); i--> 0; )
{
AudioInterface const &ifs = activeInterfaces[i];
if(ifs.type == type ||
(type == AUDIO_IMUSIC_OR_ICD && (ifs.type == AUDIO_IMUSIC ||
ifs.type == AUDIO_ICD)))
{
if(auto result = func(ifs.i.any))
return result;
}
}
}
return LoopContinue;
}
/**
* Find the Base interface of the audio driver to which @a anyAudioInterface
* belongs.
*
* @param anyAudioInterface Pointer to a SFX, Music, or CD interface.
*
* @return Audio interface, or @c nullptr if the none of the loaded drivers match.
*/
audiodriver_t &getBaseInterface(void *anyAudioInterface) const
{
if(anyAudioInterface)
{
for(AudioDriver const &driver : drivers)
{
if((void *)&driver.iSfx() == anyAudioInterface ||
(void *)&driver.iMusic() == anyAudioInterface ||
(void *)&driver.iCd() == anyAudioInterface)
{
return driver.iBase();
}
}
}
throw Error("audio::System::getBaseInterface", "Unknown audio interface");
}
audiointerfacetype_t interfaceType(void *anyAudioInterface) const
{
if(anyAudioInterface)
{
for(AudioDriver const &driver : drivers)
{
if((void *)&driver.iSfx() == anyAudioInterface) return AUDIO_ISFX;
if((void *)&driver.iMusic() == anyAudioInterface) return AUDIO_IMUSIC;
if((void *)&driver.iCd() == anyAudioInterface) return AUDIO_ICD;
}
}
return AUDIO_INONE;
}
String interfaceName(void *anyAudioInterface) const
{
if(anyAudioInterface)
{
for(AudioDriver const &driver : drivers)
{
String const name = driver.interfaceName(anyAudioInterface);
if(!name.isEmpty()) return name;
}
}
return "(invalid)";
}
#endif // __CLIENT__
/**
* LogicSounds are used to track currently playing sounds on a logical
* level (irrespective of whether playback is available, or if the sounds
* are actually audible to anyone).
*
* @todo The premise behind this functionality is fundamentally flawed in
* that it assumes that the same samples are used by both the Client and
* the Server, and that the later schedules remote playback of the former
* (determined by examining sample lengths on Server side).
*
* Furthermore, the Server should not be dictating 'oneSoundPerEmitter'
* policy so that Clients can be configured independently.
*/
struct LogicSound
{
//dint soundId = 0;
mobj_t *emitter = nullptr;
duint endTime = 0;
bool isRepeating = false;
bool inline isPlaying(duint nowTime) const {
return (isRepeating || endTime > nowTime);
}
};
typedef QMultiHash<dint /*key: soundId*/, LogicSound *> LogicSoundHash;
typedef QMutableHashIterator<dint /*key: soundId*/, LogicSound *> MutableLogicSoundHashIterator;
#if __CLIENT__
bool musAvail = false; ///< @c true if at least one driver is initialized for music playback.
bool musNeedBufFileSwitch = false; ///< @c true= choose a new file name for the buffered playback file when asked. */
String musCurrentSong;
bool musPaused = false;
bool sfxAvail = false; ///< @c true if a sound driver is initialized for sound effect playback.
mobj_t *sfxListener = nullptr;
world::Subsector *sfxListenerSubsector = nullptr;
std::unique_ptr<SfxChannels> sfxChannels;
#endif
SfxSampleCache sfxSampleCache; ///< @todo should be __CLIENT__ only.
LogicSoundHash sfxLogicHash;
duint sfxLogicLastPurge = 0;
bool sfxLogicOneSoundPerEmitter = false; ///< set at the start of the frame
Impl(Public *i) : Base(i)
{
theAudioSystem = thisPublic;
#ifdef __CLIENT__
DoomsdayApp::app().audienceForGameUnload() += this;
sfxSampleCache.audienceForSampleRemove() += this;
#endif
}
~Impl()
{
sfxClearLogical();
//#ifdef __CLIENT__
// sfxSampleCache.audienceForSampleRemove() -= this;
// DoomsdayApp::app().audienceForGameUnload() -= this;
//#endif
theAudioSystem = nullptr;
}
#ifdef __CLIENT__
String composeMusicBufferFilename(String const &ext = "")
{
// Switch the name of the buffered song file?
static dint currentBufFile = 0;
if(musNeedBufFileSwitch)
{
currentBufFile ^= 1;
musNeedBufFileSwitch = false;
}
// Compose the name.
return MUSIC_BUFFEREDFILE + String::number(currentBufFile) + ext;
}
void setMusicProperty(dint prop, void const *ptr)
{
forAllInterfaces(AUDIO_IMUSIC, [this, &prop, &ptr] (void *ifs)
{
audiodriver_t &iBase = getBaseInterface(ifs);
if(iBase.Set) iBase.Set(prop, ptr);
return LoopContinue;
});
if(prop == AUDIOP_SOUNDFONT_FILENAME)
{
auto *fn = (char const *) ptr;
if(!fn || !fn[0]) return; // No path.
if(F_FileExists(fn))
{
LOG_AUDIO_MSG("Current soundfont set to: \"%s\"") << fn;
}
else
{
LOG_AUDIO_WARNING("Soundfont \"%s\" not found") << fn;
}
}
}
dint playMusicFile(String const &virtualOrNativePath, bool looped = false)
{
DENG2_ASSERT(musAvail);
if(virtualOrNativePath.isEmpty())
return 0;
// Relative paths are relative to the native working directory.
String const path = (NativePath::workPath() / NativePath(virtualOrNativePath).expand()).withSeparators('/');
LOG_AUDIO_VERBOSE("Attempting to play music file \"%s\"")
<< NativePath(virtualOrNativePath).pretty();
try
{
std::unique_ptr<FileHandle> hndl(&App_FileSystem().openFile(path, "rb"));
auto didPlay = forAllInterfaces(AUDIO_IMUSIC, [this, &path, &hndl, &looped] (void *ifs)
{
auto *iMusic = (audiointerface_music_t *) ifs;
// Does this interface offer buffered playback?
if(iMusic->PlayFile)
{
// Write the data to disk and play from there.
File &file = App::rootFolder().replaceFile(composeMusicBufferFilename(path.fileNameExtension()));
Block buf(hndl->length());
hndl->read(buf.data(), buf.size());
file << buf;
file.flush();
return iMusic->PlayFile(file.as<NativeFile>().nativePath().toUtf8(), looped);
}
else if(iMusic->Play && iMusic->SongBuffer)
{
// Buffer the data using the driver's own facility.
dsize const len = hndl->length();
hndl->read((duint8 *) iMusic->SongBuffer(len), len);
return iMusic->Play(looped);
}
// Does this interface offer playback from a native file?
else
return 0; // Continue.
});
App_FileSystem().releaseFile(hndl->file());
return didPlay;
}
catch(FS1::NotFoundError const &)
{} // Ignore this error.
return 0; // Continue.
}
/**
* @return @c 1= if music was started. 0, if attempted to start but failed.
* @c -1= if it was MUS data and @a canPlayMUS says we can't play it.
*/
dint playMusicLump(lumpnum_t lumpNum, bool looped = false, bool canPlayMUS = true)
{
DENG2_ASSERT(musAvail);
if(!App_FileSystem().nameIndex().hasLump(lumpNum))
return 0;
File1 &lump = App_FileSystem().lump(lumpNum);
if(recognizeMus(lump))
{
// Lump is in DOOM's MUS format. We must first convert it to MIDI.
if(!canPlayMUS) return -1;
File &midi = App::rootFolder().replaceFile(composeMusicBufferFilename(".mid"));
// Read the lump, convert to MIDI and output to a temp file in the working directory.
// Use a filename with the .mid extension so that any player which relies on the it
// for format recognition works as expected.
//duint8 *buf = (duint8 *) M_Malloc(lump.size());
Block buf(lump.size());
lump.read(buf.data(), 0, lump.size());
midi << M_Mus2Midi(buf);
midi.flush();
//M_Free(buf); buf = nullptr;
return forAllInterfaces(AUDIO_IMUSIC, [&midi, &looped] (void *ifs)
{
auto *iMusic = (audiointerface_music_t *) ifs;
if(iMusic->PlayFile)
{
return iMusic->PlayFile(midi.as<NativeFile>().nativePath().toUtf8(), looped);
}
return 0; // Continue.
});
}
return forAllInterfaces(AUDIO_IMUSIC, [this, &lump, &looped] (void *ifs)
{
auto *iMusic = (audiointerface_music_t *) ifs;
// Does this interface offer buffered playback?
if(iMusic->Play && iMusic->SongBuffer)
{
// Buffer the data using the driver's own facility.
std::unique_ptr<FileHandle> hndl(&App_FileSystem().openLump(lump));
dsize const length = hndl->length();
hndl->read((duint8 *) iMusic->SongBuffer(length), length);
App_FileSystem().releaseFile(hndl->file());
return iMusic->Play(looped);
}
// Does this interface offer playback from a native file?
else if(iMusic->PlayFile)
{
String bufName = composeMusicBufferFilename();
if(!F_DumpFile(lump, bufName.toUtf8()))
{
// Failed to write the lump...
return 0;
}
return iMusic->PlayFile(App::rootFolder().locate<File const>(bufName)
.as<NativeFile>().nativePath().toUtf8(), looped);
}
return 0; // Continue.
});
}
dint playMusicCDTrack(dint track, bool looped)
{
// Assume track 0 is not valid.
if(track == 0) return 0;
return forAllInterfaces(AUDIO_ICD, [&track, &looped] (void *ifs)
{
auto *iCD = (audiointerface_cd_t *) ifs;
if(iCD->Play)
{
return iCD->Play(track, looped);
}
return 0; // Continue.
});
}
/**
* Perform initialization for music playback.
*/
void initMusic()
{
// Already been here?
if(musAvail) return;
LOG_AUDIO_VERBOSE("Initializing Music subsystem...");
musAvail = false;
musCurrentSong = "";
musPaused = false;
CommandLine &cmdLine = App::commandLine();
if(::isDedicated || cmdLine.has("-nomusic"))
{
LOG_AUDIO_NOTE("Music disabled");
return;
}
// Initialize interfaces for music playback.
dint initialized = 0;
forAllInterfaces(AUDIO_IMUSIC_OR_ICD, [this, &initialized] (void *ifs)
{
auto *iMusic = (audiointerface_music_generic_t *) ifs;
if(iMusic->Init())
{
initialized += 1;
}
else
{
LOG_AUDIO_WARNING("Failed to initialize \"%s\" for music playback")
<< interfaceName(iMusic);
}
return LoopContinue;
});
// Remember whether an interface for music playback initialized successfully.
musAvail = initialized >= 1;
if(musAvail)
{
// Tell audio drivers about our soundfont config.
self.updateMusicMidiFont();
}
}
/**
* Perform deinitialize for music playback.
*/
void deinitMusic()
{
// Already been here?
if(!musAvail) return;
musAvail = false;
// Shutdown interfaces.
forAllInterfaces(AUDIO_IMUSIC_OR_ICD, [] (void *ifs)
{
auto *iMusic = (audiointerface_music_generic_t *) ifs;
if(iMusic->Shutdown) iMusic->Shutdown();
return LoopContinue;
});
}
void updateMusicVolumeIfChanged()
{
if(!musAvail) return;
static dint oldMusVolume = -1;
if(::musVolume != oldMusVolume)
{
oldMusVolume = ::musVolume;
// Set volume of all available interfaces.
dfloat newVolume = ::musVolume / 255.0f;
forAllInterfaces(AUDIO_IMUSIC_OR_ICD, [&newVolume] (void *ifs)
{
auto *iMusic = (audiointerface_music_generic_t *) ifs;
iMusic->Set(MUSIP_VOLUME, newVolume);
return LoopContinue;
});
}
}
/**
* Perform initialization for sound effect playback.
*/
void initSfx()
{
// Already initialized?
if(sfxAvail) return;
// Check if sound has been disabled with a command line option.
if(App::commandLine().has("-nosfx"))
{
LOG_AUDIO_NOTE("Sound effects disabled");
return;
}
LOG_AUDIO_VERBOSE("Initializing sound effect playback...");
// No available interface?
if(!self.sfx()) return;
// This is based on the scientific calculations that if the DOOM marine
// is 56 units tall, 60 is about two meters.
//// @todo Derive from the viewheight.
self.sfx()->Listener(SFXLP_UNITS_PER_METER, 30);
self.sfx()->Listener(SFXLP_DOPPLER, 1.5f);
// The audio driver is working, let's create the channels.
initSfxChannels();
// (Re)Init the sample cache.
sfxSampleCache.clear();
// Initialize reverb effects to off.
sfxListenerNoReverb();
// Finally, start the sound channel refresh thread. It will stop on its
// own when it notices that the rest of the sound system is going down.
refreshing = false;
allowRefresh = true;
dint disableRefresh = false;
// Nothing to refresh?
if(!self.sfx()) goto noRefresh;
if(self.sfx()->Getv)
{
self.sfx()->Getv(SFXIP_DISABLE_CHANNEL_REFRESH, &disableRefresh);
}
if(!disableRefresh)
{
// Start the refresh thread. It will run until the Sfx module is shut down.
refreshHandle = Sys_StartThread(sfxChannelRefreshThread, nullptr);
if(!refreshHandle)
{
throw Error("audio::System::initSfx", "Failed to start refresh thread");
}
}
else
{
noRefresh:
LOGDEV_AUDIO_NOTE("Audio driver does not require a refresh thread");
}
// The Sfx module is now available.
sfxAvail = true;
}
/**
* Perform deinitialization for sound effect playback.
*/
void deinitSfx()
{
// Not initialized?
if(!sfxAvail) return;
// These will stop further refreshing.
sfxAvail = false;
allowRefresh = false;
if(refreshHandle)
{
// Wait for the sfx refresh thread to stop.
Sys_WaitThread(refreshHandle, 2000, nullptr);
refreshHandle = nullptr;
}
// Clear the sample cache.
sfxSampleCache.clear();
// Destroy channels.
shutdownSfxChannels();
}
/**
* The specified sample will soon no longer exist. All channel buffers
* loaded with the sample will be reset.
*/
void unloadSoundID(dint id)
{
if(!sfxAvail) return;
self.allowSfxRefresh(false);
sfxChannels->forAll([this, &id] (SfxChannel &ch)
{
if(ch.hasBuffer())
{
sfxbuffer_t &sbuf = ch.buffer();
if(sbuf.sample && sbuf.sample->id == id)