Debian Codegraph @

src/pt2_audio.c

raw symbols SCIP
1 // for finding memory leaks in debug mode with Visual Studio
2 #if defined _DEBUG && defined _MSC_VER
3 #include <crtdbg.h>
4 #endif
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdint.h>
9 #include <stdbool.h>
10 #include <string.h>
11 #include <math.h>
12 #include <SDL2/SDL.h>
13 #ifdef _WIN32
14 #include <io.h>
15 #else
16 #include <unistd.h>
17 #endif
18 #include <fcntl.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <limits.h>
22 #include "pt2_audio.h"
23 #include "pt2_helpers.h"
24 #include "pt2_config.h"
25 #include "pt2_textout.h"
26 #include "pt2_scopes.h"
27 #include "pt2_visuals_sync.h"
28 #include "pt2_downsample2x.h"
29 #include "pt2_replayer.h"
30 #include "pt2_paula.h"
31
32 // cumulative mid/side normalization factor (1/sqrt(2))*(1/sqrt(2))
33 #define STEREO_NORM_FACTOR 0.5f
34
35 #define INITIAL_DITHER_SEED 0x12345000
36
37 static uint8_t panningMode;
38 static int32_t stereoSeparation = 100;
39 static uint32_t randSeed = INITIAL_DITHER_SEED;
40 static float *fMixBufferL, *fMixBufferR, fSideFactor, fPrngStateL, fPrngStateR;
41 static SDL_AudioDeviceID dev;
42
43 audio_t audio; // globalized
44
45 void setAmigaFilterModel(uint8_t model)
46 {
47 if (audio.amigaModel == model)
48 return; // same state as before!
49
50 const bool audioWasntLocked = !audio.locked;
51 if (audioWasntLocked)
52 lockAudio();
53
54 audio.amigaModel = model;
55
56 const int32_t paulaMixFrequency = audio.oversamplingFlag ? audio.outputRate*2 : audio.outputRate;
57 paulaSetup(paulaMixFrequency, audio.amigaModel);
58
59 if (audioWasntLocked)
60 unlockAudio();
61 }
62
63 void toggleAmigaFilterModel(void)
64 {
65 const bool audioWasntLocked = !audio.locked;
66 if (audioWasntLocked)
67 lockAudio();
68
69 audio.amigaModel ^= 1;
70
71 const int32_t paulaMixFrequency = audio.oversamplingFlag ? audio.outputRate*2 : audio.outputRate;
72 paulaSetup(paulaMixFrequency, audio.amigaModel);
73
74 if (audioWasntLocked)
75 unlockAudio();
76
77 if (audio.amigaModel == MODEL_A500)
78 displayMsg("AUDIO: AMIGA 500");
79 else
80 displayMsg("AUDIO: AMIGA 1200");
81 }
82
83 void setLEDFilter(bool state)
84 {
85 if (audio.ledFilterEnabled == state)
86 return; // same state as before!
87
88 const bool audioWasntLocked = !audio.locked;
89 if (audioWasntLocked)
90 lockAudio();
91
92 audio.ledFilterEnabled = state;
93 paulaWriteByte(0xBFE001, (uint8_t)audio.ledFilterEnabled << 1);
94
95 if (audioWasntLocked)
96 unlockAudio();
97 }
98
99 void toggleLEDFilter(void)
100 {
101 const bool audioWasntLocked = !audio.locked;
102 if (audioWasntLocked)
103 lockAudio();
104
105 audio.ledFilterEnabled ^= 1;
106 paulaWriteByte(0xBFE001, (uint8_t)audio.ledFilterEnabled << 1);
107
108 if (audioWasntLocked)
109 unlockAudio();
110 }
111
112 void lockAudio(void)
113 {
114 if (dev != 0)
115 SDL_LockAudioDevice(dev);
116
117 audio.locked = true;
118
119 audio.resetSyncTickTimeFlag = true;
120 resetChSyncQueue();
121 }
122
123 void unlockAudio(void)
124 {
125 if (dev != 0)
126 SDL_UnlockAudioDevice(dev);
127
128 audio.resetSyncTickTimeFlag = true;
129 resetChSyncQueue();
130
131 audio.locked = false;
132 }
133
134 void resetAudioDither(void)
135 {
136 randSeed = INITIAL_DITHER_SEED;
137 fPrngStateL = fPrngStateR = 0.0f;
138 }
139
140 static inline int32_t random32(void)
141 {
142 // LCG 32-bit random
143 randSeed *= 134775813;
144 randSeed++;
145
146 return (int32_t)randSeed;
147 }
148
149 /* So yeah, the audio may be a little quiet in some cases, but
150 ** the output can already clip quite a bit in extreme cases due
151 ** to the ~5Hz high-pass filter, so think twice before changing
152 ** this...
153 */
154 #define AUDIO_GAIN 2.0
155
156 #define NORMALIZE_VALUE (float)(AUDIO_GAIN * ((INT16_MAX+1.0) / PAULA_VOICES))
157
158 static inline void processMixedSamplesAmigaPanning(int32_t i, int16_t *out)
159 {
160 int32_t out32;
161 float fOut, fPrng;
162
163 float fL = fMixBufferL[i];
164 float fR = fMixBufferR[i];
165
166 fL *= NORMALIZE_VALUE;
167 fR *= NORMALIZE_VALUE;
168
169 // left channel - 1-bit triangular dithering
170 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
171 fOut = (fL + fPrng) - fPrngStateL;
172 fPrngStateL = fPrng;
173 out32 = (int32_t)fOut;
174 out[0] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
175
176 // right channel - 1-bit triangular dithering
177 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
178 fOut = (fR + fPrng) - fPrngStateR;
179 fPrngStateR = fPrng;
180 out32 = (int32_t)fOut;
181 out[1] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
182 }
183
184 static inline void processMixedSamples(int32_t i, int16_t *out)
185 {
186 int32_t out32;
187 float fOut, fPrng;
188
189 float fL = fMixBufferL[i];
190 float fR = fMixBufferR[i];
191
192 // apply stereo separation
193 const float fOldL = fL;
194 const float fOldR = fR;
195 float fMid = (fOldL + fOldR) * STEREO_NORM_FACTOR;
196 float fSide = (fOldL - fOldR) * fSideFactor;
197 fL = fMid + fSide;
198 fR = fMid - fSide;
199
200 fL *= NORMALIZE_VALUE;
201 fR *= NORMALIZE_VALUE;
202
203 // left channel - 1-bit triangular dithering
204 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
205 fOut = (fL + fPrng) - fPrngStateL;
206 fPrngStateL = fPrng;
207 out32 = (int32_t)fOut;
208 out[0] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
209
210 // right channel - 1-bit triangular dithering
211 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
212 fOut = (fR + fPrng) - fPrngStateR;
213 fPrngStateR = fPrng;
214 out32 = (int32_t)fOut;
215 out[1] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
216 }
217
218 static inline void processMixedSamplesAmigaPanning_2x(int32_t i, int16_t *out) // 2x oversampling
219 {
220 int32_t out32;
221 float fL, fR, fOut, fPrng;
222
223 // 2x downsampling
224 const uint32_t offset1 = (i << 1) + 0;
225 const uint32_t offset2 = (i << 1) + 1;
226 fL = downsample2x_L(fMixBufferL[offset1], fMixBufferL[offset2]);
227 fR = downsample2x_R(fMixBufferR[offset1], fMixBufferR[offset2]);
228
229 fL *= NORMALIZE_VALUE;
230 fR *= NORMALIZE_VALUE;
231
232 // left channel - 1-bit triangular dithering
233 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
234 fOut = (fL + fPrng) - fPrngStateL;
235 fPrngStateL = fPrng;
236 out32 = (int32_t)fOut;
237 out[0] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
238
239 // right channel - 1-bit triangular dithering
240 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
241 fOut = (fR + fPrng) - fPrngStateR;
242 fPrngStateR = fPrng;
243 out32 = (int32_t)fOut;
244 out[1] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
245 }
246
247 static inline void processMixedSamples_2x(int32_t i, int16_t *out) // 2x oversampling
248 {
249 int32_t out32;
250 float fL, fR, fOut, fPrng;
251
252 // 2x downsampling
253 const uint32_t offset1 = (i << 1) + 0;
254 const uint32_t offset2 = (i << 1) + 1;
255 fL = downsample2x_L(fMixBufferL[offset1], fMixBufferL[offset2]);
256 fR = downsample2x_R(fMixBufferR[offset1], fMixBufferR[offset2]);
257
258 // apply stereo separation
259 const float fOldL = fL;
260 const float fOldR = fR;
261 float fMid = (fOldL + fOldR) * STEREO_NORM_FACTOR;
262 float fSide = (fOldL - fOldR) * fSideFactor;
263 fL = fMid + fSide;
264 fR = fMid - fSide;
265
266 fL *= NORMALIZE_VALUE;
267 fR *= NORMALIZE_VALUE;
268
269 // left channel - 1-bit triangular dithering
270 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
271 fOut = (fL + fPrng) - fPrngStateL;
272 fPrngStateL = fPrng;
273 out32 = (int32_t)fOut;
274 out[0] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
275
276 // right channel - 1-bit triangular dithering
277 fPrng = (float)random32() * (1.0f / ((float)UINT32_MAX+1.0f)); // -0.5f .. 0.5f
278 fOut = (fR + fPrng) - fPrngStateR;
279 fPrngStateR = fPrng;
280 out32 = (int32_t)fOut;
281 out[1] = (int16_t)(CLAMP(out32, INT16_MIN, INT16_MAX));
282 }
283
284 void outputAudio(int16_t *target, int32_t numSamples)
285 {
286 if (audio.oversamplingFlag) // 2x oversampling
287 {
288 paulaGenerateSamples(fMixBufferL, fMixBufferR, numSamples*2);
289
290 // downsample and normalize
291 int16_t out[2];
292 int16_t *outStream = target;
293 if (stereoSeparation == 100)
294 {
295 for (int32_t i = 0; i < numSamples; i++)
296 {
297 processMixedSamplesAmigaPanning_2x(i, out);
298 *outStream++ = out[0];
299 *outStream++ = out[1];
300 }
301 }
302 else
303 {
304 for (int32_t i = 0; i < numSamples; i++)
305 {
306 processMixedSamples_2x(i, out);
307 *outStream++ = out[0];
308 *outStream++ = out[1];
309 }
310 }
311 }
312 else
313 {
314 paulaGenerateSamples(fMixBufferL, fMixBufferR, numSamples);
315
316 // normalize
317 int16_t out[2];
318 int16_t *outStream = target;
319 if (stereoSeparation == 100)
320 {
321 for (int32_t i = 0; i < numSamples; i++)
322 {
323 processMixedSamplesAmigaPanning(i, out);
324 *outStream++ = out[0];
325 *outStream++ = out[1];
326 }
327 }
328 else
329 {
330 for (int32_t i = 0; i < numSamples; i++)
331 {
332 processMixedSamples(i, out);
333 *outStream++ = out[0];
334 *outStream++ = out[1];
335 }
336 }
337 }
338 }
339
340 static void audioCallback(void *userdata, Uint8 *stream, int len)
341 {
342 if (editor.mod2WavOngoing || editor.pat2SmpOngoing) // send silence to sound output device
343 {
344 memset(stream, 0, len);
345 return;
346 }
347
348 audio.callbackOngoing = true;
349
350 int16_t *streamOut = (int16_t *)stream;
351
352 uint32_t samplesLeft = (uint32_t)len / 4;
353 while (samplesLeft > 0)
354 {
355 if (audio.tickSampleCounter <= 0) // new replayer tick
356 {
357 if (editor.songPlaying)
358 {
359 tickReplayer(); // (sets audio.samplesPerTickInt and audio.samplesPerTickFrac)
360
361 if (audio.samplesPerTickInt != 0)
362 fillVisualsSyncBuffer();
363 }
364
365 audio.tickSampleCounter = audio.samplesPerTickInt;
366
367 audio.tickSampleCounterFrac += audio.samplesPerTickFrac;
368 if (audio.tickSampleCounterFrac >= BPM_FRAC_SCALE)
369 {
370 audio.tickSampleCounterFrac &= BPM_FRAC_MASK;
371 audio.tickSampleCounter++;
372 }
373 }
374
375 int32_t samplesToMix = samplesLeft;
376 if (audio.tickSampleCounter > 0 && samplesToMix > audio.tickSampleCounter)
377 samplesToMix = audio.tickSampleCounter;
378
379 outputAudio(streamOut, samplesToMix);
380 streamOut += samplesToMix * 2; // *2 for stereo
381
382 audio.tickSampleCounter -= samplesToMix;
383 samplesLeft -= samplesToMix;
384 }
385
386 audio.callbackOngoing = false;
387
388 (void)userdata;
389 }
390
391 void audioSetStereoSeparation(uint8_t percentage) // 0..100 (percentage)
392 {
393 ASSERT(percentage <= 100);
394
395 stereoSeparation = percentage;
396 fSideFactor = (percentage / 100.0f) * STEREO_NORM_FACTOR;
397 }
398
399 void generateBpmTable(double dAudioFreq, bool vblankTimingFlag)
400 {
401 const bool audioWasntLocked = !audio.locked;
402 if (audioWasntLocked)
403 lockAudio();
404
405 for (int32_t bpm = MIN_BPM; bpm <= MAX_BPM; bpm++)
406 {
407 const double dHz = vblankTimingFlag ? AMIGA_PAL_VBLANK_HZ : ciaBpm2Hz(bpm);
408
409 const double dSamplesPerTick = dAudioFreq / dHz;
410 double dSamplesPerTickInt, dSamplesPerTickFrac = modf(dSamplesPerTick, &dSamplesPerTickInt);
411
412 const int32_t i = bpm - MIN_BPM;
413 audio.samplesPerTickIntTab[i] = (uint32_t)dSamplesPerTickInt;
414 audio.samplesPerTickFracTab[i] = (uint64_t)(dSamplesPerTickFrac * BPM_FRAC_SCALE);
415 }
416
417 audio.tickSampleCounter = 0;
418 audio.tickSampleCounterFrac = 0;
419
420 if (audioWasntLocked)
421 unlockAudio();
422 }
423
424 static void generateTickLengthTable(bool vblankTimingFlag) // for performance counter (syncing visuals to audio)
425 {
426 for (int32_t bpm = MIN_BPM; bpm <= MAX_BPM; bpm++)
427 {
428 double dHz = vblankTimingFlag ? AMIGA_PAL_VBLANK_HZ : ciaBpm2Hz(bpm);
429
430 const double dTickTime = (double)hpcFreq.freq64 / dHz;
431 double dTickTimeInt, dTickTimeFrac = modf(dTickTime, &dTickTimeInt);
432
433 const int32_t i = bpm - MIN_BPM;
434 audio.tickTimeIntTab[i] = (uint32_t)dTickTimeInt;
435 audio.tickTimeFracTab[i] = (uint64_t)(dTickTimeFrac * TICK_TIME_FRAC_SCALE);
436 }
437 }
438
439 void updateReplayerTimingMode(void)
440 {
441 const bool audioWasntLocked = !audio.locked;
442 if (audioWasntLocked)
443 lockAudio();
444
445 const bool vblankTimingMode = (editor.timingMode == TEMPO_MODE_VBLANK);
446 generateBpmTable(audio.outputRate, vblankTimingMode);
447 generateTickLengthTable(vblankTimingMode);
448
449 if (audioWasntLocked)
450 unlockAudio();
451 }
452
453 bool setupAudio(void)
454 {
455 SDL_AudioSpec want, have;
456
457 audio.callbackOngoing = false;
458
459 want.freq = config.soundFrequency;
460 want.samples = (uint16_t)config.soundBufferSize;
461 want.format = AUDIO_S16;
462 want.channels = 2;
463 want.callback = audioCallback;
464 want.userdata = NULL;
465
466 dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
467 if (dev == 0)
468 {
469 showErrorMsgBox("Couldn't open audio device:\n\"%s\"\n\nDo you have an audio device enabled and plugged in?", SDL_GetError());
470 return false;
471 }
472
473 // lower than this is not safe for the BLEP synthesis in the mixer
474 const int32_t minFreq = (int32_t)(PAULA_PAL_CLK / 113.0 / 2.0)+1; // /2 because we do 2x oversampling
475 if (have.freq < minFreq)
476 {
477 showErrorMsgBox("Unable to open audio: An audio rate below %dHz can't be used!", minFreq);
478 return false;
479 }
480
481 audio.outputRate = have.freq;
482 audio.audioBufferSize = have.samples;
483 audio.oversamplingFlag = (audio.outputRate < 96000); // we do 2x oversampling if the audio output rate is below 96kHz
484 audio.amigaModel = config.amigaModel;
485
486 uint32_t maxFrequency = audio.outputRate;
487 if (maxFrequency < config.mod2WavOutputFreq)
488 maxFrequency = config.mod2WavOutputFreq;
489
490 maxFrequency *= 2; // oversampling
491
492 const int32_t paulaMixFrequency = audio.oversamplingFlag ? audio.outputRate*2 : audio.outputRate;
493 int32_t maxSamplesPerTick = (int32_t)ceil(maxFrequency / (MIN_BPM / 2.5)) + 1;
494
495 fMixBufferL = (float *)malloc(maxSamplesPerTick * sizeof (float));
496 fMixBufferR = (float *)malloc(maxSamplesPerTick * sizeof (float));
497
498 if (fMixBufferL == NULL || fMixBufferR == NULL)
499 {
500 // these two are free'd later
501 showErrorMsgBox("Out of memory!");
502 return false;
503 }
504
505 paulaSetup(paulaMixFrequency, audio.amigaModel);
506 audioSetStereoSeparation(config.stereoSeparation);
507 updateReplayerTimingMode(); // also generates the BPM table (audio.samplesPerTickIntTab & audio.samplesPerTickFracTab)
508 setLEDFilter(false);
509 calcAudioLatencyVars(audio.audioBufferSize, audio.outputRate);
510
511 clearDownsample2xStates();
512 audio.resetSyncTickTimeFlag = true;
513
514 audio.samplesPerTickInt = audio.samplesPerTickIntTab[125-MIN_BPM]; // BPM 125
515 audio.samplesPerTickFrac = audio.samplesPerTickFracTab[125-MIN_BPM]; // BPM 125
516
517 audio.tickSampleCounter = 0; // zero tick sample counter so that it will instantly initiate a tick
518 audio.tickSampleCounterFrac = 0;
519
520 SDL_PauseAudioDevice(dev, false);
521 return true;
522 }
523
524 void audioClose(void)
525 {
526 if (dev > 0)
527 {
528 SDL_PauseAudioDevice(dev, true);
529 SDL_CloseAudioDevice(dev);
530 dev = 0;
531 }
532
533 audio.callbackOngoing = false;
534
535 if (fMixBufferL != NULL)
536 {
537 free(fMixBufferL);
538 fMixBufferL = NULL;
539 }
540
541 if (fMixBufferR != NULL)
542 {
543 free(fMixBufferR);
544 fMixBufferR = NULL;
545 }
546 }
547
548 void toggleAmigaPanMode(void)
549 {
550 panningMode = (panningMode + 1) % 3;
551
552 const bool audioWasntLocked = !audio.locked;
553 if (audioWasntLocked)
554 lockAudio();
555
556 if (panningMode == 0)
557 audioSetStereoSeparation(config.stereoSeparation);
558 else if (panningMode == 1)
559 audioSetStereoSeparation(0);
560 else
561 audioSetStereoSeparation(100);
562
563 if (audioWasntLocked)
564 unlockAudio();
565
566 if (panningMode == 0)
567 displayMsg("CUSTOM PANNING");
568 else if (panningMode == 1)
569 displayMsg("CENTERED PANNING");
570 else
571 displayMsg("AMIGA PANNING");
572 }
573
574 uint16_t get16BitPeak(int16_t *sampleData, uint32_t sampleLength)
575 {
576 uint16_t samplePeak = 0;
577 for (uint32_t i = 0; i < sampleLength; i++)
578 {
579 uint16_t sample = ABS(sampleData[i]);
580 if (samplePeak < sample)
581 samplePeak = sample;
582 }
583
584 return samplePeak;
585 }
586
587 uint32_t get32BitPeak(int32_t *sampleData, uint32_t sampleLength)
588 {
589 uint32_t samplePeak = 0;
590 for (uint32_t i = 0; i < sampleLength; i++)
591 {
592 uint32_t sample = ABS(sampleData[i]);
593 if (samplePeak < sample)
594 samplePeak = sample;
595 }
596
597 return samplePeak;
598 }
599
600 float getFloatPeak(float *fSampleData, uint32_t sampleLength)
601 {
602 float fSamplePeak = 0.0f;
603 for (uint32_t i = 0; i < sampleLength; i++)
604 {
605 const float fSample = fabsf(fSampleData[i]);
606 if (fSamplePeak < fSample)
607 fSamplePeak = fSample;
608 }
609
610 return fSamplePeak;
611 }
612
613 double getDoublePeak(double *dSampleData, uint32_t sampleLength)
614 {
615 double dSamplePeak = 0.0;
616 for (uint32_t i = 0; i < sampleLength; i++)
617 {
618 const double dSample = fabs(dSampleData[i]);
619 if (dSamplePeak < dSample)
620 dSamplePeak = dSample;
621 }
622
623 return dSamplePeak;
624 }
625
626 void normalize16BitTo8Bit(int16_t *sampleData, uint32_t sampleLength)
627 {
628 const uint16_t samplePeak = get16BitPeak(sampleData, sampleLength);
629 if (samplePeak == 0 || samplePeak >= INT16_MAX)
630 return;
631
632 const double dGain = (double)INT16_MAX / samplePeak;
633 for (uint32_t i = 0; i < sampleLength; i++)
634 {
635 const int32_t sample = (const int32_t)(sampleData[i] * dGain);
636 sampleData[i] = (int16_t)sample;
637 }
638 }
639
640 void normalize32BitTo8Bit(int32_t *sampleData, uint32_t sampleLength)
641 {
642 const uint32_t samplePeak = get32BitPeak(sampleData, sampleLength);
643 if (samplePeak == 0 || samplePeak >= INT32_MAX)
644 return;
645
646 const double dGain = (double)INT32_MAX / samplePeak;
647 for (uint32_t i = 0; i < sampleLength; i++)
648 {
649 const int32_t sample = (const int32_t)(sampleData[i] * dGain);
650 sampleData[i] = (int32_t)sample;
651 }
652 }
653
654 void normalizeFloatTo8Bit(float *fSampleData, uint32_t sampleLength)
655 {
656 const float fSamplePeak = getFloatPeak(fSampleData, sampleLength);
657 if (fSamplePeak <= 0.0f)
658 return;
659
660 const float fGain = INT8_MAX / fSamplePeak;
661 for (uint32_t i = 0; i < sampleLength; i++)
662 fSampleData[i] *= fGain;
663 }
664
665 void normalizeDoubleTo8Bit(double *dSampleData, uint32_t sampleLength)
666 {
667 const double dSamplePeak = getDoublePeak(dSampleData, sampleLength);
668 if (dSamplePeak <= 0.0)
669 return;
670
671 const double dGain = INT8_MAX / dSamplePeak;
672 for (uint32_t i = 0; i < sampleLength; i++)
673 dSampleData[i] *= dGain;
674 }