Debian Codegraph @

src/engine/wavOps.cpp

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "engine.h"
21 #include "../ta-log.h"
22 #ifdef HAVE_SNDFILE
23 #include "sfWrapper.h"
24 #endif
25
26 #define EXPORT_BUFSIZE 2048
27
28 void _runExportThread(DivEngine* caller) {
29 caller->runExportThread();
30 }
31
32 bool DivEngine::isExporting() {
33 return exporting;
34 }
35
36 void DivEngine::getLoopsLeft(int &loops) {
37 if (totalLoops<0 || exportLoopCount==0) {
38 loops=0;
39 return;
40 }
41 loops=exportLoopCount-1-totalLoops;
42 }
43
44 void DivEngine::getTotalLoops(int &loops) {
45 loops=exportLoopCount-1;
46 }
47
48 void DivEngine::getCurSongPos(int &row, int &order) {
49 row=curRow;
50 order=curOrder;
51 }
52
53 void DivEngine::getTotalAudioFiles(int &files) {
54 files=0;
55
56 switch (exportMode) {
57 case DIV_EXPORT_MODE_ONE: {
58 files=1;
59 break;
60 }
61 case DIV_EXPORT_MODE_MANY_SYS: {
62 files=1; // there actually are several files but they are processed in the same loop, so to correctly draw progress we think of them as one file
63 break;
64 }
65 case DIV_EXPORT_MODE_MANY_CHAN: {
66 for (int i=0; i<chans; i++) {
67 if (!exportChannelMask[i]) continue;
68
69 files++;
70
71 if (getChannelType(i)==5) {
72 i++;
73 while (true) {
74 if (i>=chans) break;
75 if (getChannelType(i)!=5) break;
76 i++;
77 }
78 i--;
79 }
80 }
81 break;
82 }
83 default:
84 break;
85 }
86 }
87
88 void DivEngine::getCurFileIndex(int &file) {
89 file=0;
90
91 switch (exportMode) {
92 case DIV_EXPORT_MODE_ONE: {
93 file=0;
94 break;
95 }
96 case DIV_EXPORT_MODE_MANY_SYS: {
97 file=0; // there actually are several files but they are processed in the same loop, so to correctly draw progress we think of them as one file
98 break;
99 }
100 case DIV_EXPORT_MODE_MANY_CHAN: {
101 file=curExportChan;
102 break;
103 }
104 default:
105 break;
106 }
107 }
108
109 bool DivEngine::getIsFadingOut() {
110 return isFadingOut;
111 }
112
113 #ifdef HAVE_SNDFILE
114 void DivEngine::runExportThread() {
115 size_t fadeOutSamples=got.rate*exportFadeOut;
116 size_t curFadeOutSample=0;
117 isFadingOut=false;
118
119 switch (exportMode) {
120 case DIV_EXPORT_MODE_ONE: {
121 SNDFILE* sf;
122 SF_INFO si;
123 SFWrapper sfWrap;
124 si.samplerate=got.rate;
125 si.channels=exportOutputs;
126 if (exportFormat==DIV_EXPORT_FORMAT_S16) {
127 si.format=SF_FORMAT_WAV|SF_FORMAT_PCM_16;
128 } else {
129 si.format=SF_FORMAT_WAV|SF_FORMAT_FLOAT;
130 }
131
132 sf=sfWrap.doOpen(exportPath.c_str(),SFM_WRITE,&si);
133 if (sf==NULL) {
134 logE("could not open file for writing! (%s)",sf_strerror(NULL));
135 exporting=false;
136 return;
137 }
138
139 float* outBuf[DIV_MAX_OUTPUTS];
140 float* outBufFinal;
141 for (int i=0; i<exportOutputs; i++) {
142 outBuf[i]=new float[EXPORT_BUFSIZE];
143 }
144 outBufFinal=new float[EXPORT_BUFSIZE*exportOutputs];
145
146 // take control of audio output
147 deinitAudioBackend();
148 freelance=false;
149 playSub(false);
150 freelance=false;
151
152 logI("rendering to file...");
153
154 while (playing) {
155 size_t total=0;
156 nextBuf(NULL,outBuf,0,exportOutputs,EXPORT_BUFSIZE);
157 if (totalProcessed>EXPORT_BUFSIZE) {
158 logE("error: total processed is bigger than export bufsize! %d>%d",totalProcessed,EXPORT_BUFSIZE);
159 totalProcessed=EXPORT_BUFSIZE;
160 }
161 int fi=0;
162 for (int i=0; i<(int)totalProcessed; i++) {
163 total++;
164 if (isFadingOut) {
165 double mul=(1.0-((double)curFadeOutSample/(double)fadeOutSamples));
166 for (int j=0; j<exportOutputs; j++) {
167 outBufFinal[fi++]=MAX(-1.0f,MIN(1.0f,outBuf[j][i]))*mul;
168 }
169 if (++curFadeOutSample>=fadeOutSamples) {
170 playing=false;
171 break;
172 }
173 } else {
174 for (int j=0; j<exportOutputs; j++) {
175 outBufFinal[fi++]=MAX(-1.0f,MIN(1.0f,outBuf[j][i]));
176 }
177 if (lastLoopPos>-1 && i>=lastLoopPos && totalLoops>=exportLoopCount) {
178 logD("start fading out...");
179 isFadingOut=true;
180 if (fadeOutSamples==0) break;
181 }
182 }
183 }
184
185 if (sf_writef_float(sf,outBufFinal,total)!=(int)total) {
186 logE("error: failed to write entire buffer!");
187 break;
188 }
189 }
190
191 delete[] outBufFinal;
192 for (int i=0; i<exportOutputs; i++) {
193 delete[] outBuf[i];
194 }
195
196 if (sfWrap.doClose()!=0) {
197 logE("could not close audio file!");
198 }
199
200 if (initAudioBackend()) {
201 for (int i=0; i<song.systemLen; i++) {
202 disCont[i].setRates(got.rate);
203 disCont[i].setQuality(lowQuality,dcHiPass);
204 }
205 if (!output->setRun(true)) {
206 logE("error while activating audio!");
207 }
208 }
209 logI("done!");
210 exporting=false;
211 break;
212 }
213 case DIV_EXPORT_MODE_MANY_SYS: {
214 SNDFILE* sf[DIV_MAX_CHIPS];
215 SF_INFO si[DIV_MAX_CHIPS];
216 String fname[DIV_MAX_CHIPS];
217 SFWrapper sfWrap[DIV_MAX_CHIPS];
218 for (int i=0; i<song.systemLen; i++) {
219 sf[i]=NULL;
220 si[i].samplerate=got.rate;
221 si[i].channels=disCont[i].dispatch->getOutputCount();
222 si[i].format=SF_FORMAT_WAV|SF_FORMAT_PCM_16;
223 }
224
225 for (int i=0; i<song.systemLen; i++) {
226 fname[i]=fmt::sprintf("%s_s%02d.wav",exportPath,i+1);
227 logI("- %s",fname[i].c_str());
228 sf[i]=sfWrap[i].doOpen(fname[i].c_str(),SFM_WRITE,&si[i]);
229 if (sf[i]==NULL) {
230 logE("could not open file for writing! (%s)",sf_strerror(NULL));
231 for (int j=0; j<i; j++) {
232 sfWrap[i].doClose();
233 }
234 return;
235 }
236 }
237
238 float* outBuf[DIV_MAX_OUTPUTS];
239 memset(outBuf,0,sizeof(void*)*DIV_MAX_OUTPUTS);
240 outBuf[0]=new float[EXPORT_BUFSIZE];
241 outBuf[1]=new float[EXPORT_BUFSIZE];
242 short* sysBuf[DIV_MAX_CHIPS];
243 for (int i=0; i<song.systemLen; i++) {
244 sysBuf[i]=new short[EXPORT_BUFSIZE*disCont[i].dispatch->getOutputCount()];
245 }
246
247 // take control of audio output
248 deinitAudioBackend();
249 freelance=false;
250 playSub(false);
251 freelance=false;
252
253 logI("rendering to files...");
254
255 while (playing) {
256 size_t total=0;
257 nextBuf(NULL,outBuf,0,2,EXPORT_BUFSIZE);
258 if (totalProcessed>EXPORT_BUFSIZE) {
259 logE("error: total processed is bigger than export bufsize! %d>%d",totalProcessed,EXPORT_BUFSIZE);
260 totalProcessed=EXPORT_BUFSIZE;
261 }
262 for (int j=0; j<(int)totalProcessed; j++) {
263 total++;
264 if (isFadingOut) {
265 double mul=(1.0-((double)curFadeOutSample/(double)fadeOutSamples));
266 for (int i=0; i<song.systemLen; i++) {
267 for (int k=0; k<si[i].channels; k++) {
268 if (disCont[i].bbOut[k]==NULL) {
269 sysBuf[i][k+(j*si[i].channels)]=0;
270 } else {
271 sysBuf[i][k+(j*si[i].channels)]=(double)disCont[i].bbOut[k][j]*mul;
272 }
273 }
274 }
275 if (++curFadeOutSample>=fadeOutSamples) {
276 playing=false;
277 break;
278 }
279 } else {
280 for (int i=0; i<song.systemLen; i++) {
281 for (int k=0; k<si[i].channels; k++) {
282 if (disCont[i].bbOut[k]==NULL) {
283 sysBuf[i][k+(j*si[i].channels)]=0;
284 } else {
285 sysBuf[i][k+(j*si[i].channels)]=disCont[i].bbOut[k][j];
286 }
287 }
288 }
289 if (lastLoopPos>-1 && j>=lastLoopPos && totalLoops>=exportLoopCount) {
290 logD("start fading out...");
291 isFadingOut=true;
292 if (fadeOutSamples==0) break;
293 }
294 }
295 }
296 for (int i=0; i<song.systemLen; i++) {
297 if (sf_writef_short(sf[i],sysBuf[i],total)!=(int)total) {
298 logE("error: failed to write entire buffer! (%d)",i);
299 break;
300 }
301 }
302 }
303
304 delete[] outBuf[0];
305 delete[] outBuf[1];
306
307 for (int i=0; i<song.systemLen; i++) {
308 delete[] sysBuf[i];
309 if (sfWrap[i].doClose()!=0) {
310 logE("could not close audio file!");
311 }
312 }
313
314 if (initAudioBackend()) {
315 for (int i=0; i<song.systemLen; i++) {
316 disCont[i].setRates(got.rate);
317 disCont[i].setQuality(lowQuality,dcHiPass);
318 }
319 if (!output->setRun(true)) {
320 logE("error while activating audio!");
321 }
322 }
323 logI("done!");
324 exporting=false;
325 break;
326 }
327 case DIV_EXPORT_MODE_MANY_CHAN: {
328 // take control of audio output
329 deinitAudioBackend();
330
331 curExportChan=0;
332
333 float* outBuf[DIV_MAX_OUTPUTS];
334 float* outBufFinal;
335 for (int i=0; i<exportOutputs; i++) {
336 outBuf[i]=new float[EXPORT_BUFSIZE];
337 }
338 outBufFinal=new float[EXPORT_BUFSIZE*exportOutputs];
339
340 logI("rendering to files...");
341
342 for (int i=0; i<chans; i++) {
343 if (!exportChannelMask[i]) continue;
344
345 SNDFILE* sf;
346 SF_INFO si;
347 SFWrapper sfWrap;
348 String fname=fmt::sprintf("%s_c%02d.wav",exportPath,i+1);
349 logI("- %s",fname.c_str());
350 si.samplerate=got.rate;
351 si.channels=exportOutputs;
352 if (exportFormat==DIV_EXPORT_FORMAT_S16) {
353 si.format=SF_FORMAT_WAV|SF_FORMAT_PCM_16;
354 } else {
355 si.format=SF_FORMAT_WAV|SF_FORMAT_FLOAT;
356 }
357
358 sf=sfWrap.doOpen(fname.c_str(),SFM_WRITE,&si);
359 if (sf==NULL) {
360 logE("could not open file for writing! (%s)",sf_strerror(NULL));
361 break;
362 }
363
364 for (int j=0; j<chans; j++) {
365 bool mute=(j!=i);
366 isMuted[j]=mute;
367 }
368 if (getChannelType(i)==5) {
369 for (int j=i; j<chans; j++) {
370 if (getChannelType(j)!=5) break;
371 isMuted[j]=false;
372 }
373 }
374 for (int j=0; j<chans; j++) {
375 if (disCont[dispatchOfChan[j]].dispatch!=NULL) {
376 disCont[dispatchOfChan[j]].dispatch->muteChannel(dispatchChanOfChan[j],isMuted[j]);
377 }
378 }
379
380 curOrder=0;
381 prevOrder=0;
382 curFadeOutSample=0;
383 lastLoopPos=-1;
384 totalLoops=0;
385 isFadingOut=false;
386 remainingLoops=-1;
387 freelance=false;
388 playSub(false);
389 freelance=false;
390
391 while (playing) {
392 size_t total=0;
393 nextBuf(NULL,outBuf,0,exportOutputs,EXPORT_BUFSIZE);
394 if (totalProcessed>EXPORT_BUFSIZE) {
395 logE("error: total processed is bigger than export bufsize! %d>%d",totalProcessed,EXPORT_BUFSIZE);
396 totalProcessed=EXPORT_BUFSIZE;
397 }
398 int fi=0;
399 for (int j=0; j<(int)totalProcessed; j++) {
400 total++;
401 if (isFadingOut) {
402 double mul=(1.0-((double)curFadeOutSample/(double)fadeOutSamples));
403 for (int k=0; k<exportOutputs; k++) {
404 outBufFinal[fi++]=MAX(-1.0f,MIN(1.0f,outBuf[k][j]))*mul;
405 }
406 if (++curFadeOutSample>=fadeOutSamples) {
407 playing=false;
408 break;
409 }
410 } else {
411 for (int k=0; k<exportOutputs; k++) {
412 outBufFinal[fi++]=MAX(-1.0f,MIN(1.0f,outBuf[k][j]));
413 }
414 if (lastLoopPos>-1 && j>=lastLoopPos && totalLoops>=exportLoopCount) {
415 logD("start fading out...");
416 isFadingOut=true;
417 if (fadeOutSamples==0) break;
418 }
419 }
420 }
421 if (sf_writef_float(sf,outBufFinal,total)!=(int)total) {
422 logE("error: failed to write entire buffer!");
423 break;
424 }
425 }
426
427 curExportChan++;
428
429 if (sfWrap.doClose()!=0) {
430 logE("could not close audio file!");
431 }
432
433 if (getChannelType(i)==5) {
434 i++;
435 while (true) {
436 if (i>=chans) break;
437 if (getChannelType(i)!=5) break;
438 i++;
439 }
440 i--;
441 }
442
443 if (stopExport) break;
444 }
445
446 delete[] outBufFinal;
447 for (int i=0; i<exportOutputs; i++) {
448 delete[] outBuf[i];
449 }
450
451 for (int i=0; i<chans; i++) {
452 isMuted[i]=false;
453 if (disCont[dispatchOfChan[i]].dispatch!=NULL) {
454 disCont[dispatchOfChan[i]].dispatch->muteChannel(dispatchChanOfChan[i],false);
455 }
456 }
457
458 if (initAudioBackend()) {
459 for (int i=0; i<song.systemLen; i++) {
460 disCont[i].setRates(got.rate);
461 disCont[i].setQuality(lowQuality,dcHiPass);
462 }
463 if (!output->setRun(true)) {
464 logE("error while activating audio!");
465 }
466 }
467 logI("done!");
468 exporting=false;
469 curExportChan=0;
470 break;
471 }
472 }
473
474 stopExport=false;
475 }
476 #else
477 void DivEngine::runExportThread() {
478 }
479 #endif
480
481 bool DivEngine::shallSwitchCores() {
482 return true;
483 }
484
485 bool DivEngine::saveAudio(const char* path, DivAudioExportOptions options) {
486 #ifndef HAVE_SNDFILE
487 logE("Furnace was not compiled with libsndfile. cannot export!");
488 return false;
489 #else
490 exportPath=path;
491 exportMode=options.mode;
492 exportFormat=options.format;
493 exportFadeOut=options.fadeOut;
494 memcpy(exportChannelMask,options.channelMask,DIV_MAX_CHANS*sizeof(bool));
495 if (exportMode!=DIV_EXPORT_MODE_ONE) {
496 // remove extension
497 String lowerCase=exportPath;
498 for (char& i: lowerCase) {
499 if (i>='A' && i<='Z') i+='a'-'A';
500 }
501 size_t extPos=lowerCase.rfind(".wav");
502 if (extPos!=String::npos) {
503 exportPath=exportPath.substr(0,extPos);
504 }
505 }
506 exporting=true;
507 stopExport=false;
508 stop();
509 repeatPattern=false;
510 setOrder(0);
511 remainingLoops=-1;
512 got.rate=options.sampleRate;
513
514 if (shallSwitchCores()) {
515 bool isMutedBefore[DIV_MAX_CHANS];
516 memcpy(isMutedBefore,isMuted,DIV_MAX_CHANS*sizeof(bool));
517 quitDispatch();
518 initDispatch(true);
519 renderSamplesP();
520 for (int i=0; i<chans; i++) {
521 if (isMutedBefore[i]) {
522 muteChannel(i,true);
523 }
524 }
525 }
526
527 exportOutputs=options.chans;
528 if (exportOutputs<1) exportOutputs=1;
529 if (exportOutputs>DIV_MAX_OUTPUTS) exportOutputs=DIV_MAX_OUTPUTS;
530
531 exportLoopCount=options.loops+1;
532 exportThread=new std::thread(_runExportThread,this);
533 return true;
534 #endif
535 }
536
537 void DivEngine::waitAudioFile() {
538 if (exportThread!=NULL) {
539 exportThread->join();
540 }
541 }
542
543 bool DivEngine::haltAudioFile() {
544 stopExport=true;
545 stop();
546 waitAudioFile();
547 finishAudioFile();
548 return true;
549 }
550
551 void DivEngine::finishAudioFile() {
552 if (shallSwitchCores()) {
553 bool isMutedBefore[DIV_MAX_CHANS];
554 memcpy(isMutedBefore,isMuted,DIV_MAX_CHANS*sizeof(bool));
555 quitDispatch();
556 initDispatch(false);
557 renderSamplesP();
558 for (int i=0; i<chans; i++) {
559 if (isMutedBefore[i]) {
560 muteChannel(i,true);
561 }
562 }
563 }
564 }
565