Debian Codegraph @

src/pt2_mod2wav.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 <math.h>
7 #include <stdio.h>
8 #include <stdint.h>
9 #include <stdbool.h>
10 #include <string.h>
11 #include <sys/stat.h> // stat()
12 #ifndef _WIN32
13 #include <unistd.h> // chdir()
14 #endif
15 #include "pt2_audio.h"
16 #include "pt2_mouse.h"
17 #include "pt2_textout.h"
18 #include "pt2_visuals.h"
19 #include "pt2_mod2wav.h"
20 #include "pt2_downsample2x.h"
21 #include "pt2_config.h"
22 #include "pt2_askbox.h"
23 #include "pt2_replayer.h"
24
25 #define FADEOUT_CHUNK_SAMPLES 16384
26 #define TICKS_PER_RENDER_CHUNK 64
27
28 static int16_t *mod2WavBuffer, fadeOutBuffer[FADEOUT_CHUNK_SAMPLES * 2];
29 static char lastFilename[PATH_MAX + 1];
30
31 static void calcMod2WavTotalRows(void);
32
33 void mod2WavDrawFadeoutToggle(void)
34 {
35 fillRect(143, 50, FONT_CHAR_W, FONT_CHAR_H, video.palette[PAL_GENBKG]);
36 if (editor.mod2WavFadeOut)
37 charOut(143, 50, 'X', video.palette[PAL_GENTXT]);
38 }
39
40 void mod2WavDrawFadeoutSeconds(void)
41 {
42 fillRect(259, 61, FONT_CHAR_W*2, FONT_CHAR_H+1, video.palette[PAL_GENBKG]);
43 charOut(259, 62, '0' + ((editor.mod2WavFadeOutSeconds / 10) % 10), video.palette[PAL_GENTXT]);
44 charOut(267, 62, '0' + ( editor.mod2WavFadeOutSeconds % 10), video.palette[PAL_GENTXT]);
45 }
46
47 void mod2WavDrawLoopCount(void)
48 {
49 fillRect(259, 72, FONT_CHAR_W*2, FONT_CHAR_H+1, video.palette[PAL_GENBKG]);
50 charOut(259, 73, '0' + ((editor.mod2WavNumLoops / 10) % 10), video.palette[PAL_GENTXT]);
51 charOut(267, 73, '0' + ( editor.mod2WavNumLoops % 10), video.palette[PAL_GENTXT]);
52 }
53
54 void toggleMod2WavFadeout(void)
55 {
56 editor.mod2WavFadeOut ^= 1;
57 mod2WavDrawFadeoutToggle();
58 }
59
60 void mod2WavFadeoutUp(void)
61 {
62 if (editor.mod2WavFadeOutSeconds < 60)
63 {
64 editor.mod2WavFadeOutSeconds++;
65 mod2WavDrawFadeoutSeconds();
66 }
67 }
68
69 void mod2WavFadeoutDown(void)
70 {
71 if (editor.mod2WavFadeOutSeconds > 1)
72 {
73 editor.mod2WavFadeOutSeconds--;
74 mod2WavDrawFadeoutSeconds();
75 }
76 }
77
78 void mod2WavLoopCountUp(void)
79 {
80 if (editor.mod2WavNumLoops < 50)
81 {
82 editor.mod2WavNumLoops++;
83 mod2WavDrawLoopCount();
84 }
85 }
86
87 void mod2WavLoopCountDown(void)
88 {
89 if (editor.mod2WavNumLoops > 0)
90 {
91 editor.mod2WavNumLoops--;
92 mod2WavDrawLoopCount();
93 }
94 }
95
96 void drawMod2WavProgressDialog(void)
97 {
98 drawFramework3(120, 44, 200, 55);
99 textOut2(150, 53, "- RENDERING MODULE -");
100
101 const int32_t buttonW = (MOD2WAV_CANCEL_BTN_X2 - MOD2WAV_CANCEL_BTN_X1)+1;
102 const int32_t buttonH = (MOD2WAV_CANCEL_BTN_Y2 - MOD2WAV_CANCEL_BTN_Y1)+1;
103 drawButton1(MOD2WAV_CANCEL_BTN_X1, MOD2WAV_CANCEL_BTN_Y1, buttonW, buttonH, "CANCEL");
104 }
105
106 static void showMod2WavProgress(void)
107 {
108 char percText[16];
109
110 if (song->rowsInTotal == 0)
111 return;
112
113 // render progress bar
114
115 int32_t percent = (song->rowsCounter * 100) / song->rowsInTotal;
116 if (percent > 100)
117 percent = 100;
118
119 const int32_t x = 130;
120 const int32_t y = 66;
121 const int32_t w = 180;
122 const int32_t h = 11;
123
124 // foreground (progress)
125 const int32_t progressBarWidth = (percent * w) / 100;
126 if (progressBarWidth > 0)
127 fillRect(x, y, progressBarWidth, h, video.palette[PAL_GENBKG2]); // foreground (progress)
128
129 // background
130 int32_t bgWidth = w - progressBarWidth;
131 if (bgWidth > 0)
132 fillRect(x+progressBarWidth, y, bgWidth, h, video.palette[PAL_BORDER]);
133
134 // draw percentage text
135 sprintf(percText, "%d%%", percent);
136 const int32_t percTextW = (int32_t)strlen(percText) * (FONT_CHAR_W-1);
137 textOutTight(x + ((w - percTextW) / 2), y + ((h - FONT_CHAR_H) / 2), percText, video.palette[PAL_GENTXT]);
138 }
139
140 static void resetAudio(void)
141 {
142 audio.oversamplingFlag = (audio.outputRate < 96000);
143 const int32_t paulaMixFrequency = audio.oversamplingFlag ? audio.outputRate*2 : audio.outputRate;
144 paulaSetup(paulaMixFrequency, audio.amigaModel);
145 generateBpmTable(audio.outputRate, editor.timingMode == TEMPO_MODE_VBLANK);
146 clearDownsample2xStates();
147 modSetTempo(song->currBPM, true); // update BPM (samples per tick) with the tracker's audio frequency
148 }
149
150 static void handleMod2WavEnd(void)
151 {
152 pointerSetMode(POINTER_MODE_IDLE, DO_CARRY);
153
154 if (editor.abortMod2Wav)
155 {
156 displayErrorMsg("MOD2WAV ABORTED!");
157 }
158 else
159 {
160 displayMsg("MOD RENDERED!");
161 setMsgPointer();
162 }
163
164 removeAskBox();
165 resetAudio();
166
167 editor.mod2WavOngoing = false; // must be set before calling resetSong() !
168 resetSong();
169 }
170
171 void updateMod2WavDialog(void)
172 {
173 if (ui.updateMod2WavDialog)
174 {
175 ui.updateMod2WavDialog = false;
176
177 if (editor.mod2WavOngoing)
178 {
179 if (ui.mod2WavFinished)
180 {
181 ui.mod2WavFinished = false;
182 handleMod2WavEnd();
183 }
184 else
185 {
186 showMod2WavProgress();
187 }
188 }
189 }
190 }
191
192 static int32_t mod2WavThreadFunc(void *ptr)
193 {
194 wavHeader_t wavHeader;
195
196 FILE *f = (FILE *)ptr;
197 ASSERT(mod2WavBuffer != NULL && f != NULL);
198
199 // skip wav header place, render data first
200 fseek(f, sizeof (wavHeader_t), SEEK_SET);
201
202 uint32_t sampleCounter = 0;
203 uint64_t samplesToMixFrac = 0;
204 int8_t numLoops = editor.mod2WavNumLoops;
205
206 bool renderDone = false;
207 while (!renderDone)
208 {
209 uint32_t samplesInChunk = 0;
210
211 // render several ticks at once to prevent frequent disk I/O (speeds up the process)
212 int16_t *ptr16 = mod2WavBuffer;
213 for (uint32_t i = 0; i < TICKS_PER_RENDER_CHUNK; i++)
214 {
215 if (!editor.mod2WavOngoing || renderDone || editor.abortMod2Wav)
216 {
217 renderDone = true;
218 break;
219 }
220
221 /* Handle replayer tick (also sets audio.samplesPerTickInt and audio.samplesPerTickFrac).
222 ** Returns false on end of song.
223 */
224 if (!tickReplayer())
225 {
226 if (--numLoops < 0)
227 {
228 renderDone = true; // this tick is the last tick
229 }
230 else
231 {
232 // clear the "last visisted rows" table and let the song continue playing (loop)
233 memset(editor.rowVisitTable, 0, 128 * MOD_ROWS);
234 }
235 }
236
237 uint32_t samplesToMix = audio.samplesPerTickInt;
238
239 samplesToMixFrac += audio.samplesPerTickFrac;
240 if (samplesToMixFrac >= BPM_FRAC_SCALE)
241 {
242 samplesToMixFrac &= BPM_FRAC_MASK;
243 samplesToMix++;
244 }
245
246 outputAudio(ptr16, samplesToMix);
247 ptr16 += samplesToMix * 2; // *2 for stereo
248
249 samplesInChunk += samplesToMix;
250 sampleCounter += samplesToMix;
251
252 ui.updateMod2WavDialog = true;
253 }
254
255 // write buffer to disk
256 if (samplesInChunk > 0)
257 fwrite(mod2WavBuffer, sizeof (int16_t), samplesInChunk * 2, f);
258 }
259
260 ui.updateMod2WavDialog = true;
261
262 uint32_t endOfDataOffset = ftell(f);
263
264 free(mod2WavBuffer);
265
266 uint32_t totalRiffChunkLen = (uint32_t)ftell(f) - 8;
267
268 // go back and fill in WAV header
269 rewind(f);
270
271 wavHeader.chunkID = 0x46464952; // "RIFF"
272 wavHeader.chunkSize = totalRiffChunkLen;
273 wavHeader.format = 0x45564157; // "WAVE"
274 wavHeader.subchunk1ID = 0x20746D66; // "fmt "
275 wavHeader.subchunk1Size = 16;
276 wavHeader.audioFormat = 1;
277 wavHeader.numChannels = 2;
278 wavHeader.sampleRate = config.mod2WavOutputFreq;
279 wavHeader.bitsPerSample = 16;
280 wavHeader.byteRate = (wavHeader.sampleRate * wavHeader.numChannels * wavHeader.bitsPerSample) / 8;
281 wavHeader.blockAlign = (wavHeader.numChannels * wavHeader.bitsPerSample) / 8;
282 wavHeader.subchunk2ID = 0x61746164; // "data"
283 wavHeader.subchunk2Size = sampleCounter * sizeof (int16_t) * 2;
284
285 // write main header
286 fwrite(&wavHeader, sizeof (wavHeader_t), 1, f);
287 fclose(f);
288
289 // apply fadeout (if enabled)
290 if (editor.mod2WavFadeOut)
291 {
292 uint32_t numFadeOutSamples = config.mod2WavOutputFreq * editor.mod2WavFadeOutSeconds;
293 if (numFadeOutSamples > sampleCounter)
294 numFadeOutSamples = sampleCounter;
295
296 f = fopen(lastFilename, "r+b");
297
298 const double dFadeOutDelta = 1.0 / numFadeOutSamples;
299 double dFadeOutVal = 1.0;
300
301 fseek(f, endOfDataOffset - (numFadeOutSamples * sizeof (int16_t) * 2), SEEK_SET);
302
303 uint32_t samplesLeft = numFadeOutSamples;
304 while (samplesLeft > 0)
305 {
306 uint32_t samplesTodo = FADEOUT_CHUNK_SAMPLES;
307 if (samplesTodo > samplesLeft)
308 samplesTodo = samplesLeft;
309
310 fread(fadeOutBuffer, sizeof (int16_t), samplesTodo * 2, f);
311 fseek(f, 0 - (samplesTodo * sizeof (int16_t) * 2), SEEK_CUR);
312
313 // apply fadeout
314 for (uint32_t i = 0; i < samplesTodo; i++)
315 {
316 fadeOutBuffer[(i*2)+0] = (int16_t)(fadeOutBuffer[(i*2)+0] * dFadeOutVal); // L
317 fadeOutBuffer[(i*2)+1] = (int16_t)(fadeOutBuffer[(i*2)+1] * dFadeOutVal); // R
318 dFadeOutVal -= dFadeOutDelta;
319 }
320
321 fwrite(fadeOutBuffer, sizeof (int16_t), samplesTodo * 2, f);
322
323 samplesLeft -= samplesTodo;
324 }
325
326 fclose(f);
327 }
328
329 ui.mod2WavFinished = true;
330 ui.updateMod2WavDialog = true;
331
332 if (editor.abortMod2Wav)
333 editor.mod2WavOngoing = false;
334
335 return true;
336 }
337
338 static void assureModulesDir(void)
339 {
340 // if we're in samples mode in Disk Op., set dir to current modules dir
341 if (diskop.mode == DISKOP_MODE_SMP && editor.modulesPathU != NULL)
342 UNICHAR_CHDIR(editor.modulesPathU);
343 }
344
345 static void setBackDirIfNeeded(void)
346 {
347 // if we're in samples mode in Disk Op., set dir back to current samples dir
348 if (diskop.mode == DISKOP_MODE_SMP && editor.samplesPathU != NULL)
349 UNICHAR_CHDIR(editor.samplesPathU);
350 }
351
352 bool mod2WavRender(char *filename)
353 {
354 struct stat statBuffer;
355
356 lastFilename[0] = '\0'; // for rendering-thread
357
358 assureModulesDir();
359
360 if (stat(filename, &statBuffer) == 0)
361 {
362 if (!askBox(ASKBOX_YES_NO, "OVERWRITE FILE?"))
363 {
364 setBackDirIfNeeded();
365 return false;
366 }
367 }
368
369 FILE *fOut = fopen(filename, "wb");
370 if (fOut == NULL)
371 {
372 displayErrorMsg("FILE I/O ERROR");
373 setBackDirIfNeeded();
374 return false;
375 }
376
377 setBackDirIfNeeded();
378
379 strncpy(lastFilename, filename, PATH_MAX-1); // for rendering-thread
380
381 const int32_t paulaMixFrequency = config.mod2WavOutputFreq * 2; // *2 for oversampling (we always do oversampling in MOD2WAV)
382 int32_t maxSamplesPerTick = (int32_t)ceil(paulaMixFrequency / (MIN_BPM / 2.5)) + 1;
383
384 mod2WavBuffer = (int16_t *)malloc((TICKS_PER_RENDER_CHUNK * maxSamplesPerTick) * sizeof (int16_t) * 2);
385 if (mod2WavBuffer == NULL)
386 {
387 fclose(fOut);
388 statusOutOfMemory();
389 return false;
390 }
391
392 // wait for main audio callback to catch MOD2WAV flag
393 editor.mod2WavOngoing = true;
394 while (audio.callbackOngoing)
395 SDL_Delay(5);
396
397 // do some prep work
398 audio.oversamplingFlag = true;
399 generateBpmTable(config.mod2WavOutputFreq, editor.timingMode == TEMPO_MODE_VBLANK);
400 paulaSetup(paulaMixFrequency, audio.amigaModel);
401 storeTempVariables();
402 calcMod2WavTotalRows();
403 restartSong(); // this also updates BPM (samples per tick) with the MOD2WAV audio output rate
404 clearDownsample2xStates();
405
406 drawMod2WavProgressDialog();
407 editor.abortMod2Wav = false;
408
409 pointerSetMode(POINTER_MODE_MSG2, NO_CARRY);
410 setStatusMessage("RENDERING MOD...", NO_CARRY);
411
412 editor.mod2WavThread = SDL_CreateThread(mod2WavThreadFunc, "MOD2WAV thread", fOut);
413 if (editor.mod2WavThread == NULL)
414 {
415 fclose(fOut);
416 free(mod2WavBuffer);
417
418 doStopIt(true);
419
420 editor.mod2WavOngoing = false; // must be set before calling resetAudio()
421 resetAudio();
422
423 removeAskBox();
424 pointerSetMode(POINTER_MODE_IDLE, DO_CARRY);
425
426 displayErrorMsg("THREAD ERROR !");
427 return false;
428 }
429
430 SDL_DetachThread(editor.mod2WavThread);
431 return true;
432 }
433
434 #define CALC__END_OF_SONG \
435 if (--numLoops < 0) \
436 { \
437 calcingRows = false; \
438 break; \
439 } \
440 else \
441 { \
442 memset(editor.rowVisitTable, 0, 128 * MOD_ROWS); \
443 }
444
445 // ONLY used for a visual percentage counter, so accuracy is not very important
446 static void calcMod2WavTotalRows(void)
447 {
448 int8_t n_pattpos[PAULA_VOICES], n_loopcount[PAULA_VOICES];
449
450 // for pattern loop
451 memset(n_pattpos, 0, sizeof (n_pattpos));
452 memset(n_loopcount, 0, sizeof (n_loopcount));
453
454 song->rowsCounter = song->rowsInTotal = 0;
455
456 uint8_t modRow = 0;
457 int16_t modPos = 0;
458 uint16_t modPattern = song->header.patternTable[0];
459 uint8_t pBreakPosition = 0;
460 bool posJumpAssert = false;
461 bool pBreakFlag = false;
462
463 memset(editor.rowVisitTable, 0, 128 * MOD_ROWS);
464
465 int8_t numLoops = editor.mod2WavNumLoops; // make a copy
466
467 bool calcingRows = true;
468 while (calcingRows)
469 {
470 editor.rowVisitTable[(modPos * MOD_ROWS) + modRow] = true;
471
472 for (int32_t ch = 0; ch < PAULA_VOICES; ch++)
473 {
474 note_t *note = &song->patterns[modPattern][(modRow * PAULA_VOICES) + ch];
475 if (note->command == 0x0B) // Bxx - Position Jump
476 {
477 modPos = note->param - 1;
478 pBreakPosition = 0;
479 posJumpAssert = true;
480 }
481 else if (note->command == 0x0D) // Dxx - Pattern Break
482 {
483 pBreakPosition = (((note->param >> 4) * 10) + (note->param & 0x0F));
484 if (pBreakPosition > 63)
485 pBreakPosition = 0;
486
487 posJumpAssert = true;
488 }
489 else if (note->command == 0x0F && note->param == 0) // F00 - Set Speed 0 (stop)
490 {
491 CALC__END_OF_SONG
492 }
493 else if (note->command == 0x0E && (note->param >> 4) == 0x06) // E6x - Pattern Loop
494 {
495 uint8_t pos = note->param & 0x0F;
496 if (pos == 0)
497 {
498 n_pattpos[ch] = modRow;
499 }
500 else if (n_loopcount[ch] == 0)
501 {
502 n_loopcount[ch] = pos;
503
504 pBreakPosition = n_pattpos[ch];
505 pBreakFlag = true;
506
507 for (pos = pBreakPosition; pos <= modRow; pos++)
508 editor.rowVisitTable[(modPos * MOD_ROWS) + pos] = false;
509 }
510 else if (--n_loopcount[ch])
511 {
512 pBreakPosition = n_pattpos[ch];
513 pBreakFlag = true;
514
515 for (pos = pBreakPosition; pos <= modRow; pos++)
516 editor.rowVisitTable[(modPos * MOD_ROWS) + pos] = false;
517 }
518 }
519 }
520
521 modRow++;
522 song->rowsInTotal++;
523
524 if (pBreakFlag)
525 {
526 modRow = pBreakPosition;
527 pBreakPosition = 0;
528 pBreakFlag = false;
529 }
530
531 if (modRow >= MOD_ROWS || posJumpAssert)
532 {
533 modRow = pBreakPosition;
534 pBreakPosition = 0;
535 posJumpAssert = false;
536
537 modPos = (modPos + 1) & 127;
538 if (modPos >= song->header.songLength)
539 {
540 modPos = 0;
541 CALC__END_OF_SONG
542 }
543
544 modPattern = song->header.patternTable[modPos];
545 if (modPattern > MAX_PATTERNS-1)
546 modPattern = MAX_PATTERNS-1;
547 }
548
549 if (calcingRows && editor.rowVisitTable[(modPos * MOD_ROWS) + modRow])
550 {
551 // row has been visited before, we're now done!
552 CALC__END_OF_SONG
553 }
554 }
555 }