1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#include "sound.h"
4
5#include <base/bytes.h>
6#include <base/dbg.h>
7#include <base/log.h>
8#include <base/math.h>
9#include <base/mem.h>
10#include <base/str.h>
11#include <base/time.h>
12
13#include <engine/graphics.h>
14#include <engine/shared/config.h>
15#include <engine/storage.h>
16
17#include <SDL.h>
18
19#if defined(CONF_VIDEORECORDER)
20#include <engine/shared/video.h>
21#endif
22extern "C" {
23#include <opusfile.h>
24#include <wavpack.h>
25}
26
27#include <cinttypes>
28#include <cmath>
29#include <cstdio> // SEEK_*
30#include <limits>
31
32static constexpr int SAMPLE_INDEX_USED = -2;
33static constexpr int SAMPLE_INDEX_FULL = -1;
34
35unsigned CSound::AdvanceVoice(CVoice &Voice, unsigned Frames)
36{
37 // make sure that we don't go outside the sound data
38 const unsigned Advanced = std::min(a: Frames, b: (unsigned)(Voice.m_pSample->m_NumFrames - Voice.m_Tick));
39 Voice.m_Tick += Advanced;
40
41 // free voice if not used any more
42 if(Voice.m_Tick == Voice.m_pSample->m_NumFrames)
43 {
44 if(Voice.m_Flags & ISound::FLAG_LOOP)
45 {
46 Voice.m_Tick = Voice.m_pSample->m_LoopStart;
47 }
48 else
49 {
50 Voice.m_pSample = nullptr;
51 Voice.m_Age++;
52 }
53 }
54
55 return Advanced;
56}
57
58void CSound::Mix(short *pFinalOut, unsigned Frames)
59{
60 Frames = std::min(a: Frames, b: m_MaxFrames);
61 mem_zero(block: m_pMixBuffer, size: Frames * 2 * sizeof(int));
62
63 // acquire lock while we are mixing
64 m_SoundLock.lock();
65
66 const int MasterVol = m_SoundVolume.load(m: std::memory_order_relaxed);
67
68 for(auto &Voice : m_aVoices)
69 {
70 if(!Voice.m_pSample)
71 continue;
72
73 // mix voice
74 int *pOut = m_pMixBuffer;
75
76 const CSample *pSample = Voice.m_pSample;
77 const int Step = pSample->m_Channels; // setup input sources
78 short *pInL = &pSample->m_pData[Voice.m_Tick * Step];
79 short *pInR = &pSample->m_pData[Voice.m_Tick * Step + 1];
80
81 const unsigned End = AdvanceVoice(Voice, Frames);
82
83 int VolumeR = round_truncate(f: Voice.m_pChannel->m_Vol * (Voice.m_Vol / 255.0f));
84 int VolumeL = VolumeR;
85
86 // check if we have a mono sound
87 if(pSample->m_Channels == 1)
88 pInR = pInL;
89
90 // volume calculation
91 if(Voice.m_Flags & ISound::FLAG_POS && Voice.m_pChannel->m_Pan)
92 {
93 // TODO: we should respect the channel panning value
94 const vec2 Delta = Voice.m_Position - vec2(m_ListenerPositionX.load(m: std::memory_order_relaxed), m_ListenerPositionY.load(m: std::memory_order_relaxed));
95 vec2 Falloff = vec2(0.0f, 0.0f);
96
97 float RangeX = 0.0f; // for panning
98 bool InVoiceField = false;
99
100 switch(Voice.m_Shape)
101 {
102 case ISound::SHAPE_CIRCLE:
103 {
104 const float Radius = Voice.m_Circle.m_Radius;
105 RangeX = Radius;
106
107 const float Dist = length(a: Delta);
108 if(Dist < Radius)
109 {
110 InVoiceField = true;
111
112 // falloff
113 const float FalloffDistance = Radius * Voice.m_Falloff;
114 Falloff.x = Falloff.y = Dist > FalloffDistance ? (Radius - Dist) / (Radius - FalloffDistance) : 1.0f;
115 }
116 break;
117 }
118
119 case ISound::SHAPE_RECTANGLE:
120 {
121 const vec2 AbsoluteDelta = vec2(absolute(a: Delta.x), absolute(a: Delta.y));
122 const float w = Voice.m_Rectangle.m_Width / 2.0f;
123 const float h = Voice.m_Rectangle.m_Height / 2.0f;
124 RangeX = w;
125
126 if(AbsoluteDelta.x < w && AbsoluteDelta.y < h)
127 {
128 InVoiceField = true;
129
130 // falloff
131 const vec2 FalloffDistance = vec2(w, h) * Voice.m_Falloff;
132 Falloff.x = AbsoluteDelta.x > FalloffDistance.x ? (w - AbsoluteDelta.x) / (w - FalloffDistance.x) : 1.0f;
133 Falloff.y = AbsoluteDelta.y > FalloffDistance.y ? (h - AbsoluteDelta.y) / (h - FalloffDistance.y) : 1.0f;
134 }
135 break;
136 }
137 };
138
139 if(InVoiceField)
140 {
141 // panning
142 if(!(Voice.m_Flags & ISound::FLAG_NO_PANNING))
143 {
144 if(Delta.x > 0)
145 VolumeL = ((RangeX - absolute(a: Delta.x)) * VolumeL) / RangeX;
146 else
147 VolumeR = ((RangeX - absolute(a: Delta.x)) * VolumeR) / RangeX;
148 }
149
150 {
151 VolumeL *= Falloff.x * Falloff.y;
152 VolumeR *= Falloff.x * Falloff.y;
153 }
154 }
155 else
156 {
157 VolumeL = 0;
158 VolumeR = 0;
159 }
160 }
161
162 // process all frames
163 for(unsigned s = 0; s < End; s++)
164 {
165 *pOut++ += (*pInL) * VolumeL;
166 *pOut++ += (*pInR) * VolumeR;
167 pInL += Step;
168 pInR += Step;
169 }
170 }
171
172 m_SoundLock.unlock();
173
174 // clamp accumulated values
175 for(unsigned i = 0; i < Frames * 2; i++)
176 pFinalOut[i] = std::clamp<int>(val: ((m_pMixBuffer[i] * MasterVol) / 101) >> 8, lo: std::numeric_limits<short>::min(), hi: std::numeric_limits<short>::max());
177
178#if defined(CONF_ARCH_ENDIAN_BIG)
179 swap_endian(pFinalOut, sizeof(short), Frames * 2);
180#endif
181}
182
183static void SdlCallback(void *pUser, Uint8 *pStream, int Len)
184{
185 CSound *pSound = static_cast<CSound *>(pUser);
186
187#if defined(CONF_VIDEORECORDER)
188 if(!(IVideo::Current() && g_Config.m_ClVideoSndEnable))
189 {
190 pSound->Mix(pFinalOut: (short *)pStream, Frames: Len / sizeof(short) / 2);
191 }
192 else
193 {
194 mem_zero(block: pStream, size: Len);
195 }
196#else
197 pSound->Mix((short *)pStream, Len / sizeof(short) / 2);
198#endif
199}
200
201int CSound::Init()
202{
203 m_SoundEnabled = false;
204 m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();
205 m_pStorage = Kernel()->RequestInterface<IStorage>();
206
207 // Initialize sample indices. We always need them to load sounds in
208 // the editor even if sound is disabled or failed to be enabled.
209 const CLockScope LockScope(m_SoundLock);
210 m_FirstFreeSampleIndex = 0;
211 for(size_t i = 0; i < std::size(m_aSamples) - 1; ++i)
212 {
213 m_aSamples[i].m_Index = i;
214 m_aSamples[i].m_NextFreeSampleIndex = i + 1;
215 m_aSamples[i].m_pData = nullptr;
216 }
217 m_aSamples[std::size(m_aSamples) - 1].m_Index = std::size(m_aSamples) - 1;
218 m_aSamples[std::size(m_aSamples) - 1].m_NextFreeSampleIndex = SAMPLE_INDEX_FULL;
219
220 if(!g_Config.m_SndEnable)
221 return 0;
222
223 if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
224 {
225 log_error("sound", "Unable to init SDL audio: %s", SDL_GetError());
226 return -1;
227 }
228
229 m_AudioSpec.freq = g_Config.m_SndRate;
230 m_AudioSpec.format = AUDIO_S16;
231 m_AudioSpec.channels = 2;
232 m_AudioSpec.samples = g_Config.m_SndBufferSize;
233 m_AudioSpec.callback = SdlCallback;
234 m_AudioSpec.userdata = this;
235
236 m_MixingRate = m_AudioSpec.freq;
237 m_MaxFrames = m_AudioSpec.samples * 2;
238#if defined(CONF_VIDEORECORDER)
239 m_MaxFrames = std::max(a: m_MaxFrames, b: 1024u * 2u); // make the buffer bigger just in case
240#endif
241 m_pMixBuffer = (int *)calloc(nmemb: m_MaxFrames * 2, size: sizeof(int));
242
243 m_SoundEnabled = true;
244 UpdateVolume();
245
246 SDL_AddEventWatch(filter: HandleAudioDeviceEvent, userdata: this);
247 if(OpenDevice(AllowFrequencyChange: true))
248 {
249 log_info("sound", "Sound init successful using audio driver '%s'", SDL_GetCurrentAudioDriver());
250 }
251 else
252 {
253 log_error("sound", "Unable to open audio device (%s), waiting for one to become available", SDL_GetError());
254 }
255 return 0;
256}
257
258int SDLCALL CSound::HandleAudioDeviceEvent(void *pUser, SDL_Event *pEvent)
259{
260 if((pEvent->type == SDL_AUDIODEVICEADDED || pEvent->type == SDL_AUDIODEVICEREMOVED) && !pEvent->adevice.iscapture)
261 {
262 static_cast<CSound *>(pUser)->m_DeviceChanged.store(i: true, m: std::memory_order_relaxed);
263 }
264 return 0;
265}
266
267bool CSound::OpenDevice(bool AllowFrequencyChange)
268{
269 dbg_assert(m_Device == 0, "Audio device already open");
270
271 SDL_AudioSpec FormatOut;
272 m_Device = SDL_OpenAudioDevice(device: nullptr, iscapture: 0, desired: &m_AudioSpec, obtained: &FormatOut, allowed_changes: AllowFrequencyChange ? SDL_AUDIO_ALLOW_FREQUENCY_CHANGE : 0);
273 if(m_Device == 0)
274 return false;
275
276 if(AllowFrequencyChange)
277 {
278 // Samples are converted to this rate when they are loaded, so later devices are asked for it
279 m_MixingRate = FormatOut.freq;
280 m_AudioSpec.freq = m_MixingRate;
281 }
282 SDL_PauseAudioDevice(dev: m_Device, pause_on: m_DevicePaused ? 1 : 0);
283 return true;
284}
285
286void CSound::CloseDevice()
287{
288 if(m_Device == 0)
289 return;
290
291 SDL_CloseAudioDevice(dev: m_Device);
292 m_Device = 0;
293}
294
295void CSound::UpdateDevice()
296{
297 if(!m_SoundEnabled)
298 return;
299
300 if(m_Device != 0)
301 {
302 if(SDL_GetAudioDeviceStatus(dev: m_Device) != SDL_AUDIO_STOPPED)
303 return;
304 log_info("sound", "Audio device was disconnected");
305 CloseDevice();
306 }
307
308 // Opening the device when the system has none blocks for up to eight seconds
309 // in SDL's WASAPI backend, which would stall the main loop
310 if(SDL_GetNumAudioDevices(iscapture: 0) <= 0)
311 return;
312
313 if(!m_DeviceChanged.exchange(i: false, m: std::memory_order_relaxed))
314 return;
315
316 if(OpenDevice(AllowFrequencyChange: false))
317 {
318 log_info("sound", "Audio device connected, using audio driver '%s'", SDL_GetCurrentAudioDriver());
319 }
320}
321
322bool CSound::HasAudioOutput() const
323{
324#if defined(CONF_VIDEORECORDER)
325 if(IVideo::Current() && g_Config.m_ClVideoSndEnable)
326 return true;
327#endif
328 return m_Device != 0;
329}
330
331int CSound::Update()
332{
333 UpdateVolume();
334 UpdateDevice();
335 AdvancePlayback();
336 return 0;
337}
338
339void CSound::AdvancePlayback()
340{
341 if(!m_SoundEnabled || HasAudioOutput())
342 {
343 m_PlaybackTime = 0;
344 return;
345 }
346
347 // Advance the voices in real time while there is no device, so that sounds
348 // end and loop like they would during playback
349 const int64_t Now = time_get();
350 if(m_PlaybackTime == 0)
351 {
352 m_PlaybackTime = Now;
353 return;
354 }
355
356 // Drop the backlog after the client was blocked for a long time
357 m_PlaybackTime = std::max(a: m_PlaybackTime, b: Now - time_freq());
358
359 int64_t Frames = ((Now - m_PlaybackTime) * m_MixingRate) / time_freq();
360 if(Frames <= 0)
361 return;
362 // Only count the whole frames, keeping the remainder for the next update
363 m_PlaybackTime += (Frames * time_freq()) / m_MixingRate;
364
365 const CLockScope LockScope(m_SoundLock);
366 while(Frames > 0)
367 {
368 // Advance in the same chunks as the mixer, so voices loop at the same points
369 const unsigned ChunkFrames = std::min<unsigned>(a: Frames, b: m_MaxFrames);
370 for(auto &Voice : m_aVoices)
371 {
372 if(Voice.m_pSample)
373 AdvanceVoice(Voice, Frames: ChunkFrames);
374 }
375 Frames -= ChunkFrames;
376 }
377}
378
379void CSound::UpdateVolume()
380{
381 int WantedVolume = g_Config.m_SndVolume;
382 if(!m_pGraphics->WindowActive() && g_Config.m_SndNonactiveMute)
383 WantedVolume = 0;
384 m_SoundVolume.store(i: WantedVolume, m: std::memory_order_relaxed);
385}
386
387void CSound::Shutdown()
388{
389 StopAll();
390
391 // Stop sound callback before freeing sample data
392 SDL_DelEventWatch(filter: HandleAudioDeviceEvent, userdata: this);
393 CloseDevice();
394 SDL_QuitSubSystem(SDL_INIT_AUDIO);
395
396 const CLockScope LockScope(m_SoundLock);
397 for(auto &Sample : m_aSamples)
398 {
399 free(ptr: Sample.m_pData);
400 Sample.m_pData = nullptr;
401 }
402
403 free(ptr: m_pMixBuffer);
404 m_pMixBuffer = nullptr;
405 m_SoundEnabled = false;
406}
407
408CSample *CSound::AllocSample()
409{
410 const CLockScope LockScope(m_SoundLock);
411 if(m_FirstFreeSampleIndex == SAMPLE_INDEX_FULL)
412 return nullptr;
413
414 CSample *pSample = &m_aSamples[m_FirstFreeSampleIndex];
415 dbg_assert(
416 pSample->m_pData == nullptr && pSample->m_NextFreeSampleIndex != SAMPLE_INDEX_USED,
417 "Sample was not unloaded (index=%d, next=%d, duration=%f, data=%p)",
418 pSample->m_Index, pSample->m_NextFreeSampleIndex, pSample->TotalTime(), pSample->m_pData);
419 m_FirstFreeSampleIndex = pSample->m_NextFreeSampleIndex;
420 pSample->m_NextFreeSampleIndex = SAMPLE_INDEX_USED;
421 return pSample;
422}
423
424void CSound::RateConvert(CSample &Sample) const
425{
426 dbg_assert(Sample.IsLoaded(), "Sample not loaded: %d", Sample.m_Index);
427 // make sure that we need to convert this sound
428 if(Sample.m_Rate == m_MixingRate)
429 return;
430
431 // allocate new data
432 const int NumFrames = (int)((Sample.m_NumFrames / (float)Sample.m_Rate) * m_MixingRate);
433 short *pNewData = (short *)calloc(nmemb: (size_t)NumFrames * Sample.m_Channels, size: sizeof(short));
434
435 for(int i = 0; i < NumFrames; i++)
436 {
437 // resample TODO: this should be done better, like linear at least
438 float a = i / (float)NumFrames;
439 int f = (int)(a * Sample.m_NumFrames);
440 if(f >= Sample.m_NumFrames)
441 f = Sample.m_NumFrames - 1;
442
443 // set new data
444 if(Sample.m_Channels == 1)
445 pNewData[i] = Sample.m_pData[f];
446 else if(Sample.m_Channels == 2)
447 {
448 pNewData[i * 2] = Sample.m_pData[f * 2];
449 pNewData[i * 2 + 1] = Sample.m_pData[f * 2 + 1];
450 }
451 }
452
453 // adjust looping position, note that this is not precise
454 const double Factor = (double)m_MixingRate / (double)Sample.m_Rate;
455 Sample.m_LoopStart = std::round(x: Sample.m_LoopStart * Factor);
456
457 // free old data and apply new
458 free(ptr: Sample.m_pData);
459 Sample.m_pData = pNewData;
460 Sample.m_NumFrames = NumFrames;
461 Sample.m_Rate = m_MixingRate;
462}
463
464bool CSound::DecodeOpus(CSample &Sample, const void *pData, unsigned DataSize, const char *pContextName) const
465{
466 int OpusError = 0;
467 OggOpusFile *pOpusFile = op_open_memory(data: (const unsigned char *)pData, size: DataSize, error: &OpusError);
468 if(pOpusFile)
469 {
470 const int NumChannels = op_channel_count(of: pOpusFile, li: -1);
471 if(NumChannels > 2)
472 {
473 op_free(of: pOpusFile);
474 log_error("sound/opus", "File is not mono or stereo. Filename='%s'", pContextName);
475 return false;
476 }
477
478 const int NumSamples = op_pcm_total(of: pOpusFile, li: -1); // per channel!
479 if(NumSamples < 0)
480 {
481 op_free(of: pOpusFile);
482 log_error("sound/opus", "Failed to get number of samples, error %d. Filename='%s'", NumSamples, pContextName);
483 return false;
484 }
485
486 short *pSampleData = (short *)calloc(nmemb: (size_t)NumSamples * NumChannels, size: sizeof(short));
487
488 int Pos = 0;
489 while(Pos < NumSamples)
490 {
491 const int Read = op_read(of: pOpusFile, pcm: pSampleData + Pos * NumChannels, buf_size: (NumSamples - Pos) * NumChannels, li: nullptr);
492 if(Read < 0)
493 {
494 free(ptr: pSampleData);
495 op_free(of: pOpusFile);
496 log_error("sound/opus", "op_read error %d at %d. Filename='%s'", Read, Pos, pContextName);
497 return false;
498 }
499 else if(Read == 0) // EOF
500 break;
501 Pos += Read;
502 }
503
504 Sample.m_pData = pSampleData;
505 Sample.m_NumFrames = Pos;
506 Sample.m_Rate = 48000;
507 Sample.m_Channels = NumChannels;
508 Sample.m_LoopStart = 0;
509 Sample.m_PausedAt = 0;
510
511 const OpusTags *pTags = op_tags(of: pOpusFile, li: -1);
512 if(pTags)
513 {
514 for(int i = 0; i < pTags->comments; ++i)
515 {
516 const char *pComment = pTags->user_comments[i];
517 if(!pComment)
518 continue;
519 if(!str_startswith(str: pComment, prefix: "LOOP_START="))
520 continue;
521 int LoopStart = -1;
522 if(!str_toint(str: pComment + str_length(str: "LOOP_START="), out: &LoopStart))
523 {
524 log_error("sound/opus", "Invalid LOOP_START tag. Value='%s' Filename='%s'", pComment + str_length("LOOP_START="), pContextName);
525 break;
526 }
527 if(LoopStart < 0 || LoopStart >= Sample.m_NumFrames)
528 {
529 log_error("sound/opus", "Tag LOOP_START out of range. Value=%d Min=0 Max=%d Filename='%s'", LoopStart, Sample.m_NumFrames - 1, pContextName);
530 break;
531 }
532 Sample.m_LoopStart = LoopStart;
533 break;
534 }
535 }
536
537 op_free(of: pOpusFile);
538 }
539 else
540 {
541 log_error("sound/opus", "Failed to decode sample, error %d. Filename='%s'", OpusError, pContextName);
542 return false;
543 }
544
545 return true;
546}
547
548// Buffer being decoded, passed to the wavpack callbacks as their pId parameter
549class CWavpackReader
550{
551 const char *m_pBuffer;
552 int m_Size;
553 int m_Position = 0;
554
555public:
556 CWavpackReader(const void *pBuffer, int Size) :
557 m_pBuffer(static_cast<const char *>(pBuffer)), m_Size(Size)
558 {
559 }
560
561 static int ReadData(void *pId, void *pBuffer, int Size)
562 {
563 CWavpackReader *pReader = static_cast<CWavpackReader *>(pId);
564 int ChunkSize = std::min(a: Size, b: pReader->m_Size - pReader->m_Position);
565 mem_copy(dest: pBuffer, source: pReader->m_pBuffer + pReader->m_Position, size: ChunkSize);
566 pReader->m_Position += ChunkSize;
567 return ChunkSize;
568 }
569
570 static int CanSeek(void *pId)
571 {
572 return 1;
573 }
574
575 static int SetPosAbs(void *pId, uint32_t Position)
576 {
577 CWavpackReader *pReader = static_cast<CWavpackReader *>(pId);
578 if(Position > (uint32_t)pReader->m_Size)
579 return -1;
580 pReader->m_Position = Position;
581 return 0;
582 }
583
584 static int SetPosRel(void *pId, int32_t Delta, int Mode)
585 {
586 CWavpackReader *pReader = static_cast<CWavpackReader *>(pId);
587 const int64_t Base = Mode == SEEK_SET ? 0 : (Mode == SEEK_CUR ? pReader->m_Position : pReader->m_Size);
588 const int64_t Position = Base + Delta;
589 if(Position < 0 || Position > pReader->m_Size)
590 return -1;
591 pReader->m_Position = Position;
592 return 0;
593 }
594
595 static unsigned int GetPos(void *pId)
596 {
597 return static_cast<CWavpackReader *>(pId)->m_Position;
598 }
599
600 static unsigned int GetLength(void *pId)
601 {
602 return static_cast<CWavpackReader *>(pId)->m_Size;
603 }
604
605 static int PushBackByte(void *pId, int Char)
606 {
607 static_cast<CWavpackReader *>(pId)->m_Position -= 1;
608 return 0;
609 }
610};
611
612bool CSound::DecodeWV(CSample &Sample, const void *pData, unsigned DataSize, const char *pContextName) const
613{
614 // no need to load sound when we are running with no sound
615 if(!m_SoundEnabled)
616 return false;
617
618 char aError[100];
619
620 CWavpackReader Reader(pData, DataSize);
621 WavpackStreamReader Callback = {};
622 Callback.can_seek = CWavpackReader::CanSeek;
623 Callback.get_length = CWavpackReader::GetLength;
624 Callback.get_pos = CWavpackReader::GetPos;
625 Callback.push_back_byte = CWavpackReader::PushBackByte;
626 Callback.read_bytes = CWavpackReader::ReadData;
627 Callback.set_pos_abs = CWavpackReader::SetPosAbs;
628 Callback.set_pos_rel = CWavpackReader::SetPosRel;
629 WavpackContext *pContext = WavpackOpenFileInputEx(reader: &Callback, wv_id: &Reader, wvc_id: nullptr, error: aError, flags: 0, norm_offset: 0);
630 if(pContext)
631 {
632 const int BitsPerSample = WavpackGetBitsPerSample(wpc: pContext);
633 const unsigned int SampleRate = WavpackGetSampleRate(wpc: pContext);
634 const int NumChannels = WavpackGetNumChannels(wpc: pContext);
635
636 if(NumChannels > 2)
637 {
638 log_error("sound/wv", "File is not mono or stereo. Filename='%s'", pContextName);
639 WavpackCloseFile(wpc: pContext);
640 return false;
641 }
642
643 if(BitsPerSample != 16)
644 {
645 log_error("sound/wv", "Bits per sample is %d, not 16. Filename='%s'", BitsPerSample, pContextName);
646 WavpackCloseFile(wpc: pContext);
647 return false;
648 }
649
650 // wavpack reports -1 when the length of the stream is unknown
651 const int64_t NumSamples = WavpackGetNumSamples64(wpc: pContext);
652 if(NumSamples <= 0 || NumSamples > std::numeric_limits<int>::max())
653 {
654 log_error("sound/wv", "Number of samples is %" PRId64 ", not supported. Filename='%s'", NumSamples, pContextName);
655 WavpackCloseFile(wpc: pContext);
656 return false;
657 }
658
659 int *pBuffer = (int *)calloc(nmemb: (size_t)NumSamples * NumChannels, size: sizeof(int));
660 if(!WavpackUnpackSamples(wpc: pContext, buffer: pBuffer, samples: NumSamples))
661 {
662 free(ptr: pBuffer);
663 log_error("sound/wv", "WavpackUnpackSamples failed. NumSamples=%" PRId64 " NumChannels=%d Filename='%s'", NumSamples, NumChannels, pContextName);
664 WavpackCloseFile(wpc: pContext);
665 return false;
666 }
667
668 Sample.m_pData = (short *)calloc(nmemb: (size_t)NumSamples * NumChannels, size: sizeof(short));
669
670 int *pSrc = pBuffer;
671 short *pDst = Sample.m_pData;
672 for(int64_t i = 0; i < NumSamples * NumChannels; i++)
673 *pDst++ = (short)*pSrc++;
674
675 free(ptr: pBuffer);
676 WavpackCloseFile(wpc: pContext);
677
678 Sample.m_NumFrames = NumSamples;
679 Sample.m_Rate = SampleRate;
680 Sample.m_Channels = NumChannels;
681 Sample.m_LoopStart = 0;
682 Sample.m_PausedAt = 0;
683 }
684 else
685 {
686 log_error("sound/wv", "Failed to decode sample (%s). Filename='%s'", aError, pContextName);
687 return false;
688 }
689
690 return true;
691}
692
693int CSound::LoadOpus(const char *pFilename, int StorageType)
694{
695 // no need to load sound when we are running with no sound
696 if(!m_SoundEnabled)
697 return -1;
698
699 CSample *pSample = AllocSample();
700 if(!pSample)
701 {
702 log_error("sound/opus", "Failed to allocate sample ID. Filename='%s'", pFilename);
703 return -1;
704 }
705
706 void *pData;
707 unsigned DataSize;
708 if(!m_pStorage->ReadFile(pFilename, Type: StorageType, ppResult: &pData, pResultLen: &DataSize))
709 {
710 UnloadSample(SampleId: pSample->m_Index);
711 log_error("sound/opus", "Failed to open file. Filename='%s'", pFilename);
712 return -1;
713 }
714
715 const bool DecodeSuccess = DecodeOpus(Sample&: *pSample, pData, DataSize, pContextName: pFilename);
716 free(ptr: pData);
717 if(!DecodeSuccess)
718 {
719 UnloadSample(SampleId: pSample->m_Index);
720 return -1;
721 }
722
723 if(g_Config.m_Debug)
724 log_trace("sound/opus", "Loaded '%s' (index %d)", pFilename, pSample->m_Index);
725
726 RateConvert(Sample&: *pSample);
727 return pSample->m_Index;
728}
729
730int CSound::LoadWV(const char *pFilename, int StorageType)
731{
732 // no need to load sound when we are running with no sound
733 if(!m_SoundEnabled)
734 return -1;
735
736 CSample *pSample = AllocSample();
737 if(!pSample)
738 {
739 log_error("sound/wv", "Failed to allocate sample ID. Filename='%s'", pFilename);
740 return -1;
741 }
742
743 void *pData;
744 unsigned DataSize;
745 if(!m_pStorage->ReadFile(pFilename, Type: StorageType, ppResult: &pData, pResultLen: &DataSize))
746 {
747 UnloadSample(SampleId: pSample->m_Index);
748 log_error("sound/wv", "Failed to open file. Filename='%s'", pFilename);
749 return -1;
750 }
751
752 const bool DecodeSuccess = DecodeWV(Sample&: *pSample, pData, DataSize, pContextName: pFilename);
753 free(ptr: pData);
754 if(!DecodeSuccess)
755 {
756 UnloadSample(SampleId: pSample->m_Index);
757 return -1;
758 }
759
760 if(g_Config.m_Debug)
761 log_trace("sound/wv", "Loaded '%s' (index %d)", pFilename, pSample->m_Index);
762
763 RateConvert(Sample&: *pSample);
764 return pSample->m_Index;
765}
766
767int CSound::LoadOpusFromMem(const void *pData, unsigned DataSize, bool ForceLoad, const char *pContextName)
768{
769 // no need to load sound when we are running with no sound
770 if(!m_SoundEnabled && !ForceLoad)
771 return -1;
772
773 CSample *pSample = AllocSample();
774 if(!pSample)
775 return -1;
776
777 if(!DecodeOpus(Sample&: *pSample, pData, DataSize, pContextName))
778 {
779 UnloadSample(SampleId: pSample->m_Index);
780 return -1;
781 }
782
783 RateConvert(Sample&: *pSample);
784 return pSample->m_Index;
785}
786
787int CSound::LoadWVFromMem(const void *pData, unsigned DataSize, bool ForceLoad, const char *pContextName)
788{
789 // no need to load sound when we are running with no sound
790 if(!m_SoundEnabled && !ForceLoad)
791 return -1;
792
793 CSample *pSample = AllocSample();
794 if(!pSample)
795 return -1;
796
797 if(!DecodeWV(Sample&: *pSample, pData, DataSize, pContextName))
798 {
799 UnloadSample(SampleId: pSample->m_Index);
800 return -1;
801 }
802
803 RateConvert(Sample&: *pSample);
804 return pSample->m_Index;
805}
806
807void CSound::UnloadSample(int SampleId)
808{
809 if(SampleId == -1)
810 return;
811
812 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
813 const CLockScope LockScope(m_SoundLock);
814 CSample &Sample = m_aSamples[SampleId];
815
816 if(Sample.IsLoaded())
817 {
818 // Stop voices using this sample
819 for(auto &Voice : m_aVoices)
820 {
821 if(Voice.m_pSample == &Sample)
822 {
823 Voice.m_pSample = nullptr;
824 }
825 }
826
827 // Free data
828 free(ptr: Sample.m_pData);
829 Sample.m_pData = nullptr;
830 }
831
832 // Free slot
833 if(Sample.m_NextFreeSampleIndex == SAMPLE_INDEX_USED)
834 {
835 Sample.m_NextFreeSampleIndex = m_FirstFreeSampleIndex;
836 m_FirstFreeSampleIndex = Sample.m_Index;
837 }
838}
839
840float CSound::GetSampleTotalTime(int SampleId)
841{
842 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
843
844 const CLockScope LockScope(m_SoundLock);
845 dbg_assert(m_aSamples[SampleId].IsLoaded(), "Sample not loaded: %d", SampleId);
846 return m_aSamples[SampleId].TotalTime();
847}
848
849float CSound::GetSampleCurrentTime(int SampleId)
850{
851 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
852
853 const CLockScope LockScope(m_SoundLock);
854 dbg_assert(m_aSamples[SampleId].IsLoaded(), "Sample not loaded: %d", SampleId);
855 CSample *pSample = &m_aSamples[SampleId];
856 for(auto &Voice : m_aVoices)
857 {
858 if(Voice.m_pSample == pSample)
859 {
860 return Voice.m_Tick / (float)pSample->m_Rate;
861 }
862 }
863
864 return pSample->m_PausedAt / (float)pSample->m_Rate;
865}
866
867void CSound::SetSampleCurrentTime(int SampleId, float Time)
868{
869 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
870
871 const CLockScope LockScope(m_SoundLock);
872 dbg_assert(m_aSamples[SampleId].IsLoaded(), "Sample not loaded: %d", SampleId);
873 CSample *pSample = &m_aSamples[SampleId];
874 for(auto &Voice : m_aVoices)
875 {
876 if(Voice.m_pSample == pSample)
877 {
878 Voice.m_Tick = pSample->m_NumFrames * Time;
879 return;
880 }
881 }
882
883 pSample->m_PausedAt = pSample->m_NumFrames * Time;
884}
885
886void CSound::SetChannel(int ChannelId, float Vol, float Pan)
887{
888 dbg_assert(ChannelId >= 0 && ChannelId < NUM_CHANNELS, "ChannelId invalid: %d", ChannelId);
889
890 const CLockScope LockScope(m_SoundLock);
891 m_aChannels[ChannelId].m_Vol = (int)(Vol * 255.0f);
892 m_aChannels[ChannelId].m_Pan = (int)(Pan * 255.0f); // TODO: this is only on and off right now
893}
894
895void CSound::SetListenerPosition(vec2 Position)
896{
897 m_ListenerPositionX.store(t: Position.x, m: std::memory_order_relaxed);
898 m_ListenerPositionY.store(t: Position.y, m: std::memory_order_relaxed);
899}
900
901void CSound::SetVoiceVolume(CVoiceHandle Voice, float Volume)
902{
903 if(!Voice.IsValid())
904 return;
905
906 int VoiceId = Voice.Id();
907
908 const CLockScope LockScope(m_SoundLock);
909 if(m_aVoices[VoiceId].m_Age != Voice.Age())
910 return;
911
912 Volume = std::clamp(val: Volume, lo: 0.0f, hi: 1.0f);
913 m_aVoices[VoiceId].m_Vol = (int)(Volume * 255.0f);
914}
915
916void CSound::SetVoiceFalloff(CVoiceHandle Voice, float Falloff)
917{
918 if(!Voice.IsValid())
919 return;
920
921 int VoiceId = Voice.Id();
922
923 const CLockScope LockScope(m_SoundLock);
924 if(m_aVoices[VoiceId].m_Age != Voice.Age())
925 return;
926
927 Falloff = std::clamp(val: Falloff, lo: 0.0f, hi: 1.0f);
928 m_aVoices[VoiceId].m_Falloff = Falloff;
929}
930
931void CSound::SetVoicePosition(CVoiceHandle Voice, vec2 Position)
932{
933 if(!Voice.IsValid())
934 return;
935
936 int VoiceId = Voice.Id();
937
938 const CLockScope LockScope(m_SoundLock);
939 if(m_aVoices[VoiceId].m_Age != Voice.Age())
940 return;
941
942 m_aVoices[VoiceId].m_Position = Position;
943}
944
945void CSound::SetVoiceTimeOffset(CVoiceHandle Voice, float TimeOffset)
946{
947 if(!Voice.IsValid())
948 return;
949
950 int VoiceId = Voice.Id();
951
952 const CLockScope LockScope(m_SoundLock);
953 if(m_aVoices[VoiceId].m_Age != Voice.Age())
954 return;
955
956 if(!m_aVoices[VoiceId].m_pSample)
957 return;
958
959 int Tick = 0;
960 bool IsLooping = m_aVoices[VoiceId].m_Flags & ISound::FLAG_LOOP;
961 uint64_t TickOffset = m_aVoices[VoiceId].m_pSample->m_Rate * TimeOffset;
962 if(m_aVoices[VoiceId].m_pSample->m_NumFrames > 0 && IsLooping)
963 {
964 const int LoopStart = m_aVoices[VoiceId].m_pSample->m_LoopStart;
965 const int NumFrames = m_aVoices[VoiceId].m_pSample->m_NumFrames;
966 if(TickOffset < static_cast<uint64_t>(NumFrames))
967 {
968 // Still in first playthrough
969 Tick = TickOffset;
970 }
971 else
972 {
973 // Past first playthrough, wrap within loop section only
974 const int LoopLength = NumFrames - LoopStart;
975 if(LoopLength > 0)
976 Tick = LoopStart + ((TickOffset - NumFrames) % LoopLength);
977 else
978 Tick = LoopStart;
979 }
980 }
981 else
982 {
983 Tick = std::clamp<uint64_t>(val: TickOffset, lo: 0, hi: m_aVoices[VoiceId].m_pSample->m_NumFrames);
984 }
985
986 // at least 200msec off, else depend on buffer size
987 float Threshold = std::max(a: 0.2f * m_aVoices[VoiceId].m_pSample->m_Rate, b: (float)m_MaxFrames);
988 if(absolute(a: m_aVoices[VoiceId].m_Tick - Tick) > Threshold)
989 {
990 // take care of looping (modulo!)
991 if(!(IsLooping && (std::min(a: m_aVoices[VoiceId].m_Tick, b: Tick) + m_aVoices[VoiceId].m_pSample->m_NumFrames - std::max(a: m_aVoices[VoiceId].m_Tick, b: Tick)) <= Threshold))
992 {
993 m_aVoices[VoiceId].m_Tick = Tick;
994 }
995 }
996}
997
998void CSound::SetVoiceCircle(CVoiceHandle Voice, float Radius)
999{
1000 if(!Voice.IsValid())
1001 return;
1002
1003 int VoiceId = Voice.Id();
1004
1005 const CLockScope LockScope(m_SoundLock);
1006 if(m_aVoices[VoiceId].m_Age != Voice.Age())
1007 return;
1008
1009 m_aVoices[VoiceId].m_Shape = ISound::SHAPE_CIRCLE;
1010 m_aVoices[VoiceId].m_Circle.m_Radius = std::max(a: 0.0f, b: Radius);
1011}
1012
1013void CSound::SetVoiceRectangle(CVoiceHandle Voice, float Width, float Height)
1014{
1015 if(!Voice.IsValid())
1016 return;
1017
1018 int VoiceId = Voice.Id();
1019
1020 const CLockScope LockScope(m_SoundLock);
1021 if(m_aVoices[VoiceId].m_Age != Voice.Age())
1022 return;
1023
1024 m_aVoices[VoiceId].m_Shape = ISound::SHAPE_RECTANGLE;
1025 m_aVoices[VoiceId].m_Rectangle.m_Width = std::max(a: 0.0f, b: Width);
1026 m_aVoices[VoiceId].m_Rectangle.m_Height = std::max(a: 0.0f, b: Height);
1027}
1028
1029ISound::CVoiceHandle CSound::Play(int ChannelId, int SampleId, int Flags, float Volume, vec2 Position)
1030{
1031 dbg_assert(ChannelId >= 0 && ChannelId < NUM_CHANNELS, "ChannelId invalid: %d", ChannelId);
1032 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
1033
1034 const CLockScope LockScope(m_SoundLock);
1035
1036 // search for voice
1037 int VoiceId = -1;
1038 for(int i = 0; i < NUM_VOICES; i++)
1039 {
1040 int NextId = (m_NextVoice + i) % NUM_VOICES;
1041 if(!m_aVoices[NextId].m_pSample)
1042 {
1043 VoiceId = NextId;
1044 m_NextVoice = NextId + 1;
1045 break;
1046 }
1047 }
1048 if(VoiceId == -1)
1049 {
1050 return CreateVoiceHandle(Index: -1, Age: -1);
1051 }
1052
1053 // voice found, use it
1054 m_aVoices[VoiceId].m_pSample = &m_aSamples[SampleId];
1055 m_aVoices[VoiceId].m_pChannel = &m_aChannels[ChannelId];
1056 if(Flags & FLAG_LOOP)
1057 {
1058 m_aVoices[VoiceId].m_Tick = m_aSamples[SampleId].m_PausedAt;
1059 }
1060 else if(Flags & FLAG_PREVIEW)
1061 {
1062 m_aVoices[VoiceId].m_Tick = m_aSamples[SampleId].m_PausedAt;
1063 m_aSamples[SampleId].m_PausedAt = 0;
1064 }
1065 else
1066 {
1067 m_aVoices[VoiceId].m_Tick = 0;
1068 }
1069 m_aVoices[VoiceId].m_Vol = (int)(std::clamp(val: Volume, lo: 0.0f, hi: 1.0f) * 255.0f);
1070 m_aVoices[VoiceId].m_Flags = Flags;
1071 m_aVoices[VoiceId].m_Position = Position;
1072 m_aVoices[VoiceId].m_Falloff = 0.0f;
1073 m_aVoices[VoiceId].m_Shape = ISound::SHAPE_CIRCLE;
1074 m_aVoices[VoiceId].m_Circle.m_Radius = 1500;
1075 return CreateVoiceHandle(Index: VoiceId, Age: m_aVoices[VoiceId].m_Age);
1076}
1077
1078ISound::CVoiceHandle CSound::PlayAt(int ChannelId, int SampleId, int Flags, float Volume, vec2 Position)
1079{
1080 return Play(ChannelId, SampleId, Flags: Flags | ISound::FLAG_POS, Volume, Position);
1081}
1082
1083ISound::CVoiceHandle CSound::Play(int ChannelId, int SampleId, int Flags, float Volume)
1084{
1085 return Play(ChannelId, SampleId, Flags, Volume, Position: vec2(0.0f, 0.0f));
1086}
1087
1088void CSound::Pause(int SampleId)
1089{
1090 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
1091
1092 // TODO: a nice fade out
1093 const CLockScope LockScope(m_SoundLock);
1094 CSample *pSample = &m_aSamples[SampleId];
1095 dbg_assert(m_aSamples[SampleId].IsLoaded(), "Sample not loaded: %d", SampleId);
1096 for(auto &Voice : m_aVoices)
1097 {
1098 if(Voice.m_pSample == pSample)
1099 {
1100 Voice.m_pSample->m_PausedAt = Voice.m_Tick;
1101 Voice.m_pSample = nullptr;
1102 }
1103 }
1104}
1105
1106void CSound::Stop(int SampleId)
1107{
1108 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
1109
1110 // TODO: a nice fade out
1111 const CLockScope LockScope(m_SoundLock);
1112 CSample *pSample = &m_aSamples[SampleId];
1113 dbg_assert(m_aSamples[SampleId].IsLoaded(), "Sample not loaded: %d", SampleId);
1114 for(auto &Voice : m_aVoices)
1115 {
1116 if(Voice.m_pSample == pSample)
1117 {
1118 if(Voice.m_Flags & FLAG_LOOP)
1119 Voice.m_pSample->m_PausedAt = Voice.m_Tick;
1120 else
1121 Voice.m_pSample->m_PausedAt = 0;
1122 Voice.m_pSample = nullptr;
1123 }
1124 }
1125}
1126
1127void CSound::StopAll()
1128{
1129 // TODO: a nice fade out
1130 const CLockScope LockScope(m_SoundLock);
1131 for(auto &Voice : m_aVoices)
1132 {
1133 if(Voice.m_pSample)
1134 {
1135 if(Voice.m_Flags & FLAG_LOOP)
1136 Voice.m_pSample->m_PausedAt = Voice.m_Tick;
1137 else
1138 Voice.m_pSample->m_PausedAt = 0;
1139 }
1140 Voice.m_pSample = nullptr;
1141 }
1142}
1143
1144void CSound::StopVoice(CVoiceHandle Voice)
1145{
1146 if(!Voice.IsValid())
1147 return;
1148
1149 int VoiceId = Voice.Id();
1150
1151 const CLockScope LockScope(m_SoundLock);
1152 if(m_aVoices[VoiceId].m_Age != Voice.Age())
1153 return;
1154
1155 m_aVoices[VoiceId].m_pSample = nullptr;
1156 m_aVoices[VoiceId].m_Age++;
1157}
1158
1159bool CSound::IsPlaying(int SampleId)
1160{
1161 dbg_assert(SampleId >= 0 && SampleId < NUM_SAMPLES, "SampleId invalid: %d", SampleId);
1162 const CLockScope LockScope(m_SoundLock);
1163 const CSample *pSample = &m_aSamples[SampleId];
1164 dbg_assert(m_aSamples[SampleId].IsLoaded(), "Sample not loaded: %d", SampleId);
1165 return std::any_of(first: std::begin(arr&: m_aVoices), last: std::end(arr&: m_aVoices), pred: [pSample](const auto &Voice) { return Voice.m_pSample == pSample; });
1166}
1167
1168void CSound::PauseAudioDevice()
1169{
1170 m_DevicePaused = true;
1171 if(m_Device != 0)
1172 {
1173 SDL_PauseAudioDevice(dev: m_Device, pause_on: 1);
1174 }
1175}
1176
1177void CSound::UnpauseAudioDevice()
1178{
1179 m_DevicePaused = false;
1180 if(m_Device != 0)
1181 {
1182 SDL_PauseAudioDevice(dev: m_Device, pause_on: 0);
1183 }
1184}
1185
1186IEngineSound *CreateEngineSound() { return new CSound; }
1187