Debian Codegraph @

src/engine/engine.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 #define _USE_MATH_DEFINES
21 #include "dispatch.h"
22 #include "song.h"
23 #include "engine.h"
24 #include "instrument.h"
25 #include "safeReader.h"
26 #include "workPool.h"
27 #include "../ta-log.h"
28 #include "../fileutils.h"
29 #ifdef HAVE_SDL2
30 #include "../audio/sdlAudio.h"
31 #endif
32 #include <stdexcept>
33 #ifdef HAVE_JACK
34 #include "../audio/jack.h"
35 #endif
36 #ifdef HAVE_PA
37 #include "../audio/pa.h"
38 #endif
39 #include "../audio/pipe.h"
40 #include <math.h>
41 #include <float.h>
42 #include <fmt/printf.h>
43 #include <chrono>
44
45 void process(void* u, float** in, float** out, int inChans, int outChans, unsigned int size) {
46 ((DivEngine*)u)->nextBuf(in,out,inChans,outChans,size);
47 }
48
49 const char* DivEngine::getEffectDesc(unsigned char effect, int chan, bool notNull) {
50 switch (effect) {
51 case 0x00:
52 return _("00xy: Arpeggio");
53 case 0x01:
54 return _("01xx: Pitch slide up");
55 case 0x02:
56 return _("02xx: Pitch slide down");
57 case 0x03:
58 return _("03xx: Portamento");
59 case 0x04:
60 return _("04xy: Vibrato (x: speed; y: depth)");
61 case 0x05:
62 return _("05xy: Volume slide + vibrato (compatibility only!)");
63 case 0x06:
64 return _("06xy: Volume slide + portamento (compatibility only!)");
65 case 0x07:
66 return _("07xy: Tremolo (x: speed; y: depth)");
67 case 0x08:
68 return _("08xy: Set panning (x: left; y: right)");
69 case 0x09:
70 return _("09xx: Set groove pattern (speed 1 if no grooves exist)");
71 case 0x0a:
72 return _("0Axy: Volume slide (0y: down; x0: up)");
73 case 0x0b:
74 return _("0Bxx: Jump to pattern");
75 case 0x0c:
76 return _("0Cxx: Retrigger");
77 case 0x0d:
78 return _("0Dxx: Jump to next pattern");
79 case 0x0f:
80 return _("0Fxx: Set speed (speed 2 if no grooves exist)");
81 case 0x80:
82 return _("80xx: Set panning (00: left; 80: center; FF: right)");
83 case 0x81:
84 return _("81xx: Set panning (left channel)");
85 case 0x82:
86 return _("82xx: Set panning (right channel)");
87 case 0x83:
88 return _("83xy: Panning slide (x0: left; 0y: right)");
89 case 0x84:
90 return _("84xy: Panbrello (x: speed; y: depth)");
91 case 0x88:
92 return _("88xy: Set panning (rear channels; x: left; y: right)");
93 break;
94 case 0x89:
95 return _("89xx: Set panning (rear left channel)");
96 break;
97 case 0x8a:
98 return _("8Axx: Set panning (rear right channel)");
99 break;
100 case 0xc0: case 0xc1: case 0xc2: case 0xc3:
101 return _("Cxxx: Set tick rate (hz)");
102 case 0xd3:
103 return _("D3xx: Volume portamento");
104 case 0xd4:
105 return _("D4xx: Volume portamento (fast)");
106 case 0xdc:
107 return _("DCxx: Delayed mute");
108 case 0xe0:
109 return _("E0xx: Set arp speed");
110 case 0xe1:
111 return _("E1xy: Note slide up (x: speed; y: semitones)");
112 case 0xe2:
113 return _("E2xy: Note slide down (x: speed; y: semitones)");
114 case 0xe3:
115 return _("E3xx: Set vibrato shape");
116 case 0xe4:
117 return _("E4xx: Set vibrato range");
118 case 0xe5:
119 return _("E5xx: Set pitch (80: center)");
120 case 0xe6:
121 return _("E6xy: Quick legato (x: time (0-7 up; 8-F down); y: semitones)");
122 case 0xe7:
123 return _("E7xx: Macro release");
124 case 0xe8:
125 return _("E8xy: Quick legato up (x: time; y: semitones)");
126 case 0xe9:
127 return _("E9xy: Quick legato down (x: time; y: semitones)");
128 case 0xea:
129 return _("EAxx: Legato");
130 case 0xeb:
131 return _("EBxx: Set LEGACY sample mode bank");
132 case 0xec:
133 return _("ECxx: Note cut");
134 case 0xed:
135 return _("EDxx: Note delay");
136 case 0xee:
137 return _("EExx: Send external command");
138 case 0xf0:
139 return _("F0xx: Set tick rate (bpm)");
140 case 0xf1:
141 return _("F1xx: Single tick pitch up");
142 case 0xf2:
143 return _("F2xx: Single tick pitch down");
144 case 0xf3:
145 return _("F3xx: Fine volume slide up");
146 case 0xf4:
147 return _("F4xx: Fine volume slide down");
148 case 0xf5:
149 return _("F5xx: Disable macro (see manual)");
150 case 0xf6:
151 return _("F6xx: Enable macro (see manual)");
152 case 0xf7:
153 return _("F7xx: Restart macro (see manual)");
154 case 0xf8:
155 return _("F8xx: Single tick volume up");
156 case 0xf9:
157 return _("F9xx: Single tick volume down");
158 case 0xfa:
159 return _("FAxx: Fast volume slide (0y: down; x0: up)");
160 case 0xfc:
161 return _("FCxx: Note release");
162 case 0xfd:
163 return _("FDxx: Set virtual tempo numerator");
164 case 0xfe:
165 return _("FExx: Set virtual tempo denominator");
166 case 0xff:
167 return _("FFxx: Stop song");
168 default:
169 if ((effect&0xf0)==0x90) {
170 if (song.oldSampleOffset) {
171 return _("9xxx: Set sample offset*256");
172 }
173 switch (effect) {
174 case 0x90:
175 return _("90xx: Set sample offset (first byte)");
176 case 0x91:
177 return _("91xx: Set sample offset (second byte, ×256)");
178 case 0x92:
179 return _("92xx: Set sample offset (third byte, ×65536)");
180 }
181 } else if (chan>=0 && chan<chans) {
182 DivSysDef* sysDef=sysDefs[sysOfChan[chan]];
183 auto iter=sysDef->effectHandlers.find(effect);
184 if (iter!=sysDef->effectHandlers.end()) {
185 return iter->second.description;
186 }
187 iter=sysDef->postEffectHandlers.find(effect);
188 if (iter!=sysDef->postEffectHandlers.end()) {
189 return iter->second.description;
190 }
191 iter=sysDef->preEffectHandlers.find(effect);
192 if (iter!=sysDef->preEffectHandlers.end()) {
193 return iter->second.description;
194 }
195 }
196 break;
197 }
198 return notNull?_("Invalid effect"):NULL;
199 }
200
201 void DivEngine::walkSong(int& loopOrder, int& loopRow, int& loopEnd) {
202 if (curSubSong!=NULL) {
203 curSubSong->walk(loopOrder,loopRow,loopEnd,chans,song.jumpTreatment,song.ignoreJumpAtEnd);
204 }
205 }
206
207 void DivEngine::findSongLength(int loopOrder, int loopRow, double fadeoutLen, int& rowsForFadeout, bool& hasFFxx, std::vector<int>& orders, int& length) {
208 if (curSubSong!=NULL) {
209 curSubSong->findLength(loopOrder,loopRow,fadeoutLen,rowsForFadeout,hasFFxx,orders,song.grooves,length,chans,song.jumpTreatment,song.ignoreJumpAtEnd);
210 }
211 }
212
213 #define EXPORT_BUFSIZE 2048
214
215 double DivEngine::benchmarkPlayback() {
216 float* outBuf[2];
217 outBuf[0]=new float[EXPORT_BUFSIZE];
218 outBuf[1]=new float[EXPORT_BUFSIZE];
219
220 curOrder=0;
221 prevOrder=0;
222 remainingLoops=1;
223 playSub(false);
224
225 std::chrono::high_resolution_clock::time_point timeStart=std::chrono::high_resolution_clock::now();
226
227 // benchmark
228 while (playing) {
229 nextBuf(NULL,outBuf,0,2,EXPORT_BUFSIZE);
230 }
231
232 std::chrono::high_resolution_clock::time_point timeEnd=std::chrono::high_resolution_clock::now();
233
234 delete[] outBuf[0];
235 delete[] outBuf[1];
236
237 double t=(double)(std::chrono::duration_cast<std::chrono::microseconds>(timeEnd-timeStart).count())/1000000.0;
238 printf("[RESULT] %fs\n",t);
239 return t;
240 }
241
242 double DivEngine::benchmarkSeek() {
243 double t[20];
244 curOrder=curSubSong->ordersLen-1;
245 prevOrder=curSubSong->ordersLen-1;
246
247 // benchmark
248 for (int i=0; i<20; i++) {
249 std::chrono::high_resolution_clock::time_point timeStart=std::chrono::high_resolution_clock::now();
250 playSub(false);
251 std::chrono::high_resolution_clock::time_point timeEnd=std::chrono::high_resolution_clock::now();
252 t[i]=(double)(std::chrono::duration_cast<std::chrono::microseconds>(timeEnd-timeStart).count())/1000000.0;
253 printf("[#%d] %fs\n",i+1,t[i]);
254 }
255
256 double tMin=DBL_MAX;
257 double tMax=0.0;
258 double tAvg=0.0;
259 for (int i=0; i<20; i++) {
260 if (t[i]<tMin) tMin=t[i];
261 if (t[i]>tMax) tMax=t[i];
262 tAvg+=t[i];
263 }
264 tAvg/=20.0;
265
266 printf("[RESULT] min %fs max %fs average %fs\n",tMin,tMax,tAvg);
267 return tAvg;
268 }
269
270 void DivEngine::notifyInsChange(int ins) {
271 BUSY_BEGIN;
272 for (int i=0; i<song.systemLen; i++) {
273 disCont[i].dispatch->notifyInsChange(ins);
274 }
275 BUSY_END;
276 }
277
278 void DivEngine::notifyWaveChange(int wave) {
279 BUSY_BEGIN;
280 for (int i=0; i<song.systemLen; i++) {
281 disCont[i].dispatch->notifyWaveChange(wave);
282 }
283 BUSY_END;
284 }
285
286 int DivEngine::loadSampleROM(String path, ssize_t expectedSize, unsigned char*& ret) {
287 ret=NULL;
288 if (path.empty()) {
289 return 0;
290 }
291 logI("loading ROM %s...",path);
292 FILE* f=ps_fopen(path.c_str(),"rb");
293 if (f==NULL) {
294 logE("error: %s",strerror(errno));
295 lastError=strerror(errno);
296 return -1;
297 }
298 if (fseek(f,0,SEEK_END)<0) {
299 logE("size error: %s",strerror(errno));
300 lastError=fmt::sprintf(_("on seek: %s"),strerror(errno));
301 fclose(f);
302 return -1;
303 }
304 ssize_t len=ftell(f);
305 if (len==(SIZE_MAX>>1)) {
306 logE("could not get file length: %s",strerror(errno));
307 lastError=fmt::sprintf(_("on pre tell: %s"),strerror(errno));
308 fclose(f);
309 return -1;
310 }
311 if (len<1) {
312 if (len==0) {
313 logE("that file is empty!");
314 lastError=_("file is empty");
315 } else {
316 logE("tell error: %s",strerror(errno));
317 lastError=fmt::sprintf(_("on tell: %s"),strerror(errno));
318 }
319 fclose(f);
320 return -1;
321 }
322 if (len!=expectedSize) {
323 logE("ROM size mismatch, expected: %d bytes, was: %d bytes", expectedSize, len);
324 lastError=fmt::sprintf(_("ROM size mismatch, expected: %d bytes, was: %d"), expectedSize, len);
325 return -1;
326 }
327 if (fseek(f,0,SEEK_SET)<0) {
328 logE("size error: %s",strerror(errno));
329 lastError=fmt::sprintf(_("on get size: %s"),strerror(errno));
330 fclose(f);
331 return -1;
332 }
333 unsigned char* file=new unsigned char[len];
334 if (fread(file,1,(size_t)len,f)!=(size_t)len) {
335 logE("read error: %s",strerror(errno));
336 lastError=fmt::sprintf(_("on read: %s"),strerror(errno));
337 fclose(f);
338 delete[] file;
339 return -1;
340 }
341 fclose(f);
342 ret=file;
343 return 0;
344 }
345
346 unsigned int DivEngine::getSampleFormatMask() {
347 unsigned int formatMask=1U<<16; // 16-bit is always on
348 for (int i=0; i<song.systemLen; i++) {
349 const DivSysDef* s=getSystemDef(song.system[i]);
350 if (s==NULL) continue;
351 formatMask|=s->sampleFormatMask;
352 }
353 return formatMask;
354 }
355
356 int DivEngine::loadSampleROMs() {
357 if (yrw801ROM!=NULL) {
358 delete[] yrw801ROM;
359 yrw801ROM=NULL;
360 }
361 if (tg100ROM!=NULL) {
362 delete[] tg100ROM;
363 tg100ROM=NULL;
364 }
365 if (mu5ROM!=NULL) {
366 delete[] mu5ROM;
367 mu5ROM=NULL;
368 }
369 int error=0;
370 error+=loadSampleROM(getConfString("yrw801Path",""), 0x200000, yrw801ROM);
371 error+=loadSampleROM(getConfString("tg100Path",""), 0x200000, tg100ROM);
372 error+=loadSampleROM(getConfString("mu5Path",""), 0x200000, mu5ROM);
373 return error;
374 }
375
376 void DivEngine::renderSamplesP(int whichSample) {
377 BUSY_BEGIN;
378 renderSamples(whichSample);
379 BUSY_END;
380 }
381
382 void DivEngine::renderSamples(int whichSample) {
383 sPreview.sample=-1;
384 sPreview.pos=0;
385 sPreview.dir=false;
386
387 logD("rendering samples...");
388
389 // step 0: make sample format mask
390 unsigned int formatMask=1U<<16; // 16-bit is always on
391 for (int i=0; i<song.systemLen; i++) {
392 const DivSysDef* s=getSystemDef(song.system[i]);
393 if (s==NULL) continue;
394 formatMask|=s->sampleFormatMask;
395 }
396
397 // step 1: render samples
398 if (whichSample==-1) {
399 for (int i=0; i<song.sampleLen; i++) {
400 song.sample[i]->render(formatMask);
401 }
402 } else if (whichSample>=0 && whichSample<song.sampleLen) {
403 song.sample[whichSample]->render(formatMask);
404 }
405
406 // step 2: render samples to dispatch
407 for (int i=0; i<song.systemLen; i++) {
408 if (disCont[i].dispatch!=NULL) {
409 disCont[i].dispatch->renderSamples(i);
410 }
411 }
412 }
413
414 String DivEngine::decodeSysDesc(String desc) {
415 DivConfig newDesc;
416 bool hasVal=false;
417 bool negative=false;
418 int val=0;
419 int curStage=0;
420 int sysID=0;
421 float sysVol=0;
422 float sysPan=0;
423 int sysFlags=0;
424 int curSys=0;
425 desc+=' '; // ha
426 for (char i: desc) {
427 switch (i) {
428 case ' ':
429 if (hasVal) {
430 if (negative) val=-val;
431 switch (curStage) {
432 case 0:
433 sysID=val;
434 curStage++;
435 break;
436 case 1:
437 sysVol=(float)val/64.0f;
438 curStage++;
439 break;
440 case 2:
441 sysPan=(float)val/127.0f;
442 curStage++;
443 break;
444 case 3:
445 sysFlags=val;
446
447 if (sysID!=0) {
448 if (sysVol<-1.0f) sysVol=-1.0f;
449 if (sysVol>1.0f) sysVol=1.0f;
450 if (sysPan<-1.0f) sysPan=-1.0f;
451 if (sysPan>1.0f) sysPan=1.0f;
452 newDesc.set(fmt::sprintf("id%d",curSys),sysID);
453 newDesc.set(fmt::sprintf("vol%d",curSys),sysVol);
454 newDesc.set(fmt::sprintf("pan%d",curSys),sysPan);
455 newDesc.set(fmt::sprintf("fr%d",curSys),0.0f);
456 DivConfig newFlagsC;
457 newFlagsC.clear();
458 convertOldFlags((unsigned int)sysFlags,newFlagsC,systemFromFileFur(sysID));
459 newDesc.set(fmt::sprintf("flags%d",curSys),newFlagsC.toBase64());
460 curSys++;
461 }
462
463 curStage=0;
464 break;
465 }
466 hasVal=false;
467 negative=false;
468 val=0;
469 }
470 break;
471 case '0': case '1': case '2': case '3': case '4':
472 case '5': case '6': case '7': case '8': case '9':
473 val=(val*10)+(i-'0');
474 hasVal=true;
475 break;
476 case '-':
477 if (!hasVal) negative=true;
478 break;
479 }
480 }
481
482 return newDesc.toBase64();
483 }
484
485 void DivEngine::initSongWithDesc(const char* description, bool inBase64, bool oldVol) {
486 int chanCount=0;
487 DivConfig c;
488 if (inBase64) {
489 c.loadFromBase64(description);
490 } else {
491 c.loadFromMemory(description);
492 }
493 int index=0;
494 for (; index<DIV_MAX_CHIPS; index++) {
495 song.system[index]=systemFromFileFur(c.getInt(fmt::sprintf("id%d",index),0));
496 if (song.system[index]==DIV_SYSTEM_NULL) {
497 break;
498 }
499 chanCount+=getChannelCount(song.system[index]);
500 if (chanCount>=DIV_MAX_CHANS) {
501 song.system[index]=DIV_SYSTEM_NULL;
502 break;
503 }
504 song.systemVol[index]=c.getFloat(fmt::sprintf("vol%d",index),1.0f);
505 song.systemPan[index]=c.getFloat(fmt::sprintf("pan%d",index),0.0f);
506 song.systemPanFR[index]=c.getFloat(fmt::sprintf("fr%d",index),0.0f);
507 song.systemFlags[index].clear();
508
509 if (oldVol) {
510 song.systemVol[index]/=64.0f;
511 song.systemPan[index]/=127.0f;
512 }
513
514 String flags=c.getString(fmt::sprintf("flags%d",index),"");
515 song.systemFlags[index].loadFromBase64(flags.c_str());
516 }
517 song.systemLen=index;
518
519 // extra attributes
520 song.subsong[0]->hz=c.getDouble("tickRate",60.0);
521 if (song.subsong[0]->hz<1.0) song.subsong[0]->hz=1.0;
522 if (song.subsong[0]->hz>999.0) song.subsong[0]->hz=999.0;
523
524 curChanMask=c.getIntList("chanMask",{});
525 for (unsigned char i:curChanMask) {
526 int j=i-1;
527 if (j<0) j=0;
528 if (j>DIV_MAX_CHANS) j=DIV_MAX_CHANS-1;
529 curSubSong->chanShow[j]=false;
530 curSubSong->chanShowChanOsc[j]=false;
531 }
532
533 song.author=getConfString("defaultAuthorName","");
534 }
535
536 void DivEngine::createNew(const char* description, String sysName, bool inBase64) {
537 quitDispatch();
538 BUSY_BEGIN;
539 saveLock.lock();
540 song.unload();
541 song=DivSong();
542 changeSong(0);
543 if (description!=NULL) {
544 initSongWithDesc(description,inBase64);
545 }
546 if (sysName=="") {
547 song.systemName=getSongSystemLegacyName(song,!getConfInt("noMultiSystem",0));
548 } else {
549 song.systemName=sysName;
550 }
551 recalcChans();
552 saveLock.unlock();
553 BUSY_END;
554 initDispatch();
555 BUSY_BEGIN;
556 renderSamples();
557 reset();
558 BUSY_END;
559 }
560
561 void DivEngine::createNewFromDefaults() {
562 quitDispatch();
563 BUSY_BEGIN;
564 saveLock.lock();
565 song.unload();
566 song=DivSong();
567 changeSong(0);
568
569 String preset=getConfString("initialSys2","");
570 bool oldVol=getConfInt("configVersion",DIV_ENGINE_VERSION)<135;
571 if (preset.empty()) {
572 // try loading old preset
573 logD("trying to load old preset");
574 preset=decodeSysDesc(getConfString("initialSys",""));
575 oldVol=false;
576 }
577 logD("preset size %ld",preset.size());
578 if (preset.size()>0 && (preset.size()&3)==0) {
579 initSongWithDesc(preset.c_str(),true,oldVol);
580 }
581 String sysName=getConfString("initialSysName","");
582 if (sysName=="") {
583 song.systemName=getSongSystemLegacyName(song,!getConfInt("noMultiSystem",0));
584 } else {
585 song.systemName=sysName;
586 }
587
588 recalcChans();
589 saveLock.unlock();
590 BUSY_END;
591 initDispatch();
592 BUSY_BEGIN;
593 renderSamples();
594 reset();
595 BUSY_END;
596 }
597
598 void DivEngine::swapChannels(int src, int dest) {
599 logV("swapping channel %d with %d",src,dest);
600 if (src==dest) {
601 logV("not swapping channels because it's the same channel!",src,dest);
602 return;
603 }
604
605 for (int i=0; i<DIV_MAX_PATTERNS; i++) {
606 curOrders->ord[dest][i]^=curOrders->ord[src][i];
607 curOrders->ord[src][i]^=curOrders->ord[dest][i];
608 curOrders->ord[dest][i]^=curOrders->ord[src][i];
609
610 DivPattern* prev=curPat[src].data[i];
611 curPat[src].data[i]=curPat[dest].data[i];
612 curPat[dest].data[i]=prev;
613 }
614
615 curPat[src].effectCols^=curPat[dest].effectCols;
616 curPat[dest].effectCols^=curPat[src].effectCols;
617 curPat[src].effectCols^=curPat[dest].effectCols;
618
619 String prevChanName=curSubSong->chanName[src];
620 String prevChanShortName=curSubSong->chanShortName[src];
621 bool prevChanShow=curSubSong->chanShow[src];
622 bool prevChanShowChanOsc=curSubSong->chanShowChanOsc[src];
623 unsigned char prevChanCollapse=curSubSong->chanCollapse[src];
624
625 curSubSong->chanName[src]=curSubSong->chanName[dest];
626 curSubSong->chanShortName[src]=curSubSong->chanShortName[dest];
627 curSubSong->chanShow[src]=curSubSong->chanShow[dest];
628 curSubSong->chanShowChanOsc[src]=curSubSong->chanShowChanOsc[dest];
629 curSubSong->chanCollapse[src]=curSubSong->chanCollapse[dest];
630 curSubSong->chanName[dest]=prevChanName;
631 curSubSong->chanShortName[dest]=prevChanShortName;
632 curSubSong->chanShow[dest]=prevChanShow;
633 curSubSong->chanShowChanOsc[dest]=prevChanShowChanOsc;
634 curSubSong->chanCollapse[dest]=prevChanCollapse;
635 }
636
637 void DivEngine::stompChannel(int ch) {
638 logV("stomping channel %d",ch);
639 for (int i=0; i<DIV_MAX_PATTERNS; i++) {
640 curOrders->ord[ch][i]=0;
641 }
642 curPat[ch].wipePatterns();
643 curPat[ch].effectCols=1;
644 curSubSong->chanName[ch]="";
645 curSubSong->chanShortName[ch]="";
646 curSubSong->chanShow[ch]=true;
647 curSubSong->chanShowChanOsc[ch]=true;
648 curSubSong->chanCollapse[ch]=false;
649 }
650
651 void DivEngine::changeSong(size_t songIndex) {
652 if (songIndex>=song.subsong.size()) return;
653 curSubSong=song.subsong[songIndex];
654 curPat=song.subsong[songIndex]->pat;
655 curOrders=&song.subsong[songIndex]->orders;
656 curSubSongIndex=songIndex;
657 curOrder=0;
658 curRow=0;
659 prevOrder=0;
660 prevRow=0;
661 }
662
663 void DivEngine::moveAsset(std::vector<DivAssetDir>& dir, int before, int after) {
664 if (before<0 || after<0) return;
665 for (DivAssetDir& i: dir) {
666 for (size_t j=0; j<i.entries.size(); j++) {
667 // erase matching entry
668 if (i.entries[j]==before) {
669 i.entries[j]=after;
670 } else if (i.entries[j]==after) {
671 i.entries[j]=before;
672 }
673 }
674 }
675 }
676
677 void DivEngine::removeAsset(std::vector<DivAssetDir>& dir, int entry) {
678 if (entry<0) return;
679 for (DivAssetDir& i: dir) {
680 for (size_t j=0; j<i.entries.size(); j++) {
681 // erase matching entry
682 if (i.entries[j]==entry) {
683 i.entries.erase(i.entries.begin()+j);
684 j--;
685 } else if (i.entries[j]>entry) {
686 i.entries[j]--;
687 }
688 }
689 }
690 }
691
692 void DivEngine::checkAssetDir(std::vector<DivAssetDir>& dir, size_t entries) {
693 bool* inAssetDir=new bool[entries];
694 memset(inAssetDir,0,entries*sizeof(bool));
695
696 for (DivAssetDir& i: dir) {
697 for (size_t j=0; j<i.entries.size(); j++) {
698 // erase invalid entry
699 if (i.entries[j]<0 || i.entries[j]>=(int)entries) {
700 i.entries.erase(i.entries.begin()+j);
701 j--;
702 continue;
703 }
704
705 // erase duplicate entry
706 if (inAssetDir[i.entries[j]]) {
707 i.entries.erase(i.entries.begin()+j);
708 j--;
709 continue;
710 }
711
712 // mark entry as present
713 inAssetDir[i.entries[j]]=true;
714 }
715 }
716
717 // get unsorted directory
718 DivAssetDir* unsortedDir=NULL;
719 for (DivAssetDir& i: dir) {
720 if (i.name.empty()) {
721 unsortedDir=&i;
722 break;
723 }
724 }
725
726 // add missing items to unsorted directory
727 for (size_t i=0; i<entries; i++) {
728 if (!inAssetDir[i]) {
729 // create unsorted directory if it doesn't exist
730 if (unsortedDir==NULL) {
731 dir.push_back(DivAssetDir(""));
732 unsortedDir=&(*dir.rbegin());
733 }
734 unsortedDir->entries.push_back(i);
735 }
736 }
737
738 delete[] inAssetDir;
739 }
740
741 void DivEngine::swapChannelsP(int src, int dest) {
742 if (src<0 || src>=chans) return;
743 if (dest<0 || dest>=chans) return;
744 BUSY_BEGIN;
745 saveLock.lock();
746 swapChannels(src,dest);
747 saveLock.unlock();
748 BUSY_END;
749 }
750
751 void DivEngine::changeSongP(size_t index) {
752 if (index>=song.subsong.size()) return;
753 if (index==curSubSongIndex) return;
754 stop();
755 BUSY_BEGIN;
756 saveLock.lock();
757 changeSong(index);
758 saveLock.unlock();
759 BUSY_END;
760 }
761
762 int DivEngine::addSubSong() {
763 if (song.subsong.size()>=127) return -1;
764 BUSY_BEGIN;
765 saveLock.lock();
766 song.subsong.push_back(new DivSubSong);
767 for (unsigned char i:curChanMask) {
768 int j=i-1;
769 if (j<0) j=0;
770 if (j>DIV_MAX_CHANS) j=DIV_MAX_CHANS-1;
771 song.subsong.back()->chanShow[j]=false;
772 song.subsong.back()->chanShowChanOsc[j]=false;
773 }
774 saveLock.unlock();
775 BUSY_END;
776 return song.subsong.size()-1;
777 }
778
779 int DivEngine::duplicateSubSong(int index) {
780 if (song.subsong.size()>=127) return -1;
781 BUSY_BEGIN;
782 saveLock.lock();
783 DivSubSong* theCopy=new DivSubSong;
784 DivSubSong* theOrig=song.subsong[index];
785
786 theCopy->name=theOrig->name;
787 theCopy->notes=theOrig->notes;
788 theCopy->hilightA=theOrig->hilightA;
789 theCopy->hilightB=theOrig->hilightB;
790 theCopy->timeBase=theOrig->timeBase;
791 theCopy->arpLen=theOrig->arpLen;
792 theCopy->speeds=theOrig->speeds;
793 theCopy->virtualTempoN=theOrig->virtualTempoN;
794 theCopy->virtualTempoD=theOrig->virtualTempoD;
795 theCopy->hz=theOrig->hz;
796 theCopy->patLen=theOrig->patLen;
797 theCopy->ordersLen=theOrig->ordersLen;
798 theCopy->orders=theOrig->orders;
799
800 memcpy(theCopy->chanShow,theOrig->chanShow,DIV_MAX_CHANS*sizeof(bool));
801 memcpy(theCopy->chanShowChanOsc,theOrig->chanShowChanOsc,DIV_MAX_CHANS*sizeof(bool));
802 memcpy(theCopy->chanCollapse,theOrig->chanCollapse,DIV_MAX_CHANS);
803
804 for (int i=0; i<DIV_MAX_CHANS; i++) {
805 theCopy->chanName[i]=theOrig->chanName[i];
806 theCopy->chanShortName[i]=theOrig->chanShortName[i];
807
808 theCopy->pat[i].effectCols=theOrig->pat[i].effectCols;
809
810 for (int j=0; j<DIV_MAX_PATTERNS; j++) {
811 if (theOrig->pat[i].data[j]==NULL) continue;
812 DivPattern* origPat=theOrig->pat[i].getPattern(j,false);
813 DivPattern* copyPat=theCopy->pat[i].getPattern(j,true);
814 origPat->copyOn(copyPat);
815 }
816 }
817
818 song.subsong.push_back(theCopy);
819
820 saveLock.unlock();
821 BUSY_END;
822 return song.subsong.size()-1;
823 }
824
825 bool DivEngine::removeSubSong(int index) {
826 if (song.subsong.size()<=1) return false;
827 stop();
828 BUSY_BEGIN;
829 saveLock.lock();
830 song.subsong[index]->clearData();
831 delete song.subsong[index];
832 song.subsong.erase(song.subsong.begin()+index);
833 changeSong(0);
834 saveLock.unlock();
835 BUSY_END;
836 return true;
837 }
838
839 void DivEngine::moveSubSongUp(size_t index) {
840 if (index<1 || index>=song.subsong.size()) return;
841 BUSY_BEGIN;
842 saveLock.lock();
843
844 if (index==curSubSongIndex) {
845 curSubSongIndex--;
846 } else if (index-1==curSubSongIndex) {
847 curSubSongIndex++;
848 }
849
850 DivSubSong* prev=song.subsong[index-1];
851 song.subsong[index-1]=song.subsong[index];
852 song.subsong[index]=prev;
853
854 saveLock.unlock();
855 BUSY_END;
856 }
857
858 void DivEngine::moveSubSongDown(size_t index) {
859 if (index>=song.subsong.size()-1) return;
860 BUSY_BEGIN;
861 saveLock.lock();
862
863 if (index==curSubSongIndex) {
864 curSubSongIndex++;
865 } else if (index+1==curSubSongIndex) {
866 curSubSongIndex--;
867 }
868
869 DivSubSong* prev=song.subsong[index+1];
870 song.subsong[index+1]=song.subsong[index];
871 song.subsong[index]=prev;
872
873 saveLock.unlock();
874 BUSY_END;
875 }
876
877 void DivEngine::clearSubSongs() {
878 BUSY_BEGIN;
879 saveLock.lock();
880 song.clearSongData();
881 changeSong(0);
882 curOrder=0;
883 prevOrder=0;
884 saveLock.unlock();
885 BUSY_END;
886 }
887
888 void DivEngine::delUnusedIns() {
889 BUSY_BEGIN;
890 saveLock.lock();
891
892 bool isUsed[256];
893 memset(isUsed,0,256*sizeof(bool));
894
895 // scan
896 for (int i=0; i<chans; i++) {
897 for (size_t j=0; j<song.subsong.size(); j++) {
898 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
899 if (song.subsong[j]->pat[i].data[k]==NULL) continue;
900 for (int l=0; l<song.subsong[j]->patLen; l++) {
901 if (song.subsong[j]->pat[i].data[k]->data[l][2]>=0 && song.subsong[j]->pat[i].data[k]->data[l][2]<256) {
902 isUsed[song.subsong[j]->pat[i].data[k]->data[l][2]]=true;
903 }
904 }
905 }
906 }
907 }
908
909 // delete
910 for (int i=0; i<song.insLen; i++) {
911 if (!isUsed[i]) {
912 delInstrumentUnsafe(i);
913 // rotate
914 for (int j=i; j<255; j++) {
915 isUsed[j]=isUsed[j+1];
916 }
917 isUsed[255]=true;
918 i--;
919 }
920 }
921
922 saveLock.unlock();
923 BUSY_END;
924 }
925
926 void DivEngine::delUnusedWaves() {
927 BUSY_BEGIN;
928 saveLock.lock();
929
930 saveLock.unlock();
931 BUSY_END;
932 }
933
934 void DivEngine::delUnusedSamples() {
935 if (song.sample.empty()) return;
936
937 BUSY_BEGIN;
938 saveLock.lock();
939
940 bool* isUsed=new bool[song.sample.size()];
941 memset(isUsed,0,song.sample.size()*sizeof(bool));
942 int isUsedMax=((int)song.sample.size())-1;
943
944 // scan in instruments
945 for (DivInstrument* i: song.ins) {
946 if ((i->type==DIV_INS_PCE && i->amiga.useSample) ||
947 i->type==DIV_INS_MSM6258 ||
948 i->type==DIV_INS_MSM6295 ||
949 i->type==DIV_INS_ADPCMA ||
950 i->type==DIV_INS_ADPCMB ||
951 i->type==DIV_INS_SEGAPCM ||
952 i->type==DIV_INS_QSOUND ||
953 i->type==DIV_INS_YMZ280B ||
954 i->type==DIV_INS_RF5C68 ||
955 i->type==DIV_INS_AMIGA ||
956 i->type==DIV_INS_MULTIPCM ||
957 (i->type==DIV_INS_MIKEY && i->amiga.useSample) ||
958 (i->type==DIV_INS_X1_010 && i->amiga.useSample) ||
959 (i->type==DIV_INS_SWAN && i->amiga.useSample) ||
960 (i->type==DIV_INS_AY && i->amiga.useSample) ||
961 (i->type==DIV_INS_AY8930 && i->amiga.useSample) ||
962 (i->type==DIV_INS_VRC6 && i->amiga.useSample) ||
963 (i->type==DIV_INS_SU && i->amiga.useSample) ||
964 i->type==DIV_INS_SNES ||
965 i->type==DIV_INS_ES5506 ||
966 i->type==DIV_INS_K007232 ||
967 i->type==DIV_INS_GA20 ||
968 i->type==DIV_INS_K053260 ||
969 i->type==DIV_INS_C140 ||
970 i->type==DIV_INS_C219 ||
971 i->type==DIV_INS_NDS ||
972 i->type==DIV_INS_GBA_DMA ||
973 i->type==DIV_INS_GBA_MINMOD) {
974 if (i->amiga.initSample>=0 && i->amiga.initSample<song.sampleLen) {
975 isUsed[i->amiga.initSample]=true;
976 }
977 if (i->amiga.useNoteMap) {
978 for (int j=0; j<120; j++) {
979 if (i->amiga.noteMap[j].map>=0 && i->amiga.noteMap[j].map<song.sampleLen) {
980 isUsed[i->amiga.noteMap[j].map]=true;
981 }
982 }
983 }
984 }
985 }
986
987 // scan in pattern (legacy sample mode)
988 // disabled because it is unreliable
989 /*
990 for (DivSubSong* i: song.subsong) {
991 for (int j=0; j<getTotalChannelCount(); j++) {
992 bool is17On=false;
993 int bank=0;
994 for (int k=0; k<i->ordersLen; k++) {
995 DivPattern* p=i->pat[j].getPattern(i->orders.ord[j][k],false);
996 for (int l=0; l<i->patLen; l++) {
997 for (int m=0; m<i->pat[j].effectCols; m++) {
998 if (p->data[l][4+(m<<1)]==0x17) {
999 is17On=(p->data[l][5+(m<<1)]>0);
1000 }
1001 if (p->data[l][4+(m<<1)]==0xeb) {
1002 bank=p->data[l][5+(m<<1)];
1003 if (bank==-1) bank=0;
1004 }
1005 }
1006 if (is17On) {
1007 if (p->data[l][1]!=0 || p->data[l][0]!=0) {
1008 if (p->data[l][0]<=12) {
1009 int note=(12*bank)+(p->data[l][0]%12);
1010 if (note<256) isUsed[note]=true;
1011 }
1012 }
1013 }
1014 }
1015 }
1016 }
1017 }*/
1018
1019 // delete
1020 for (int i=0; i<song.sampleLen; i++) {
1021 if (!isUsed[i]) {
1022 delSampleUnsafe(i,false);
1023 // rotate
1024 for (int j=i; j<isUsedMax; j++) {
1025 isUsed[j]=isUsed[j+1];
1026 }
1027 isUsed[isUsedMax]=true;
1028 i--;
1029 }
1030 }
1031
1032 // render
1033 renderSamples();
1034
1035 delete[] isUsed;
1036
1037 saveLock.unlock();
1038 BUSY_END;
1039 }
1040
1041 bool DivEngine::changeSystem(int index, DivSystem which, bool preserveOrder) {
1042 if (index<0 || index>=song.systemLen) {
1043 lastError=_("invalid index");
1044 return false;
1045 }
1046 if (chans-getChannelCount(song.system[index])+getChannelCount(which)>DIV_MAX_CHANS) {
1047 lastError=fmt::sprintf(_("max number of total channels is %d"),DIV_MAX_CHANS);
1048 return false;
1049 }
1050
1051 int chanCount=chans;
1052 quitDispatch();
1053 BUSY_BEGIN;
1054 saveLock.lock();
1055
1056 if (!preserveOrder) {
1057 int firstChan=0;
1058 int chanMovement=getChannelCount(which)-getChannelCount(song.system[index]);
1059 while (dispatchOfChan[firstChan]!=index) firstChan++;
1060 int lastChan=firstChan+getChannelCount(song.system[index]);
1061 if (chanMovement!=0) {
1062 if (chanMovement>0) {
1063 // add channels
1064 for (int i=chanCount+chanMovement-1; i>=lastChan+chanMovement; i--) {
1065 swapChannels(i,i-chanMovement);
1066 }
1067 for (int i=lastChan; i<lastChan+chanMovement; i++) {
1068 stompChannel(i);
1069 }
1070 } else {
1071 // remove channels
1072 for (int i=lastChan+chanMovement; i<lastChan; i++) {
1073 stompChannel(i);
1074 }
1075 for (int i=lastChan+chanMovement; i<chanCount+chanMovement; i++) {
1076 swapChannels(i,i-chanMovement);
1077 }
1078 }
1079 }
1080 }
1081
1082 song.system[index]=which;
1083 song.systemFlags[index].clear();
1084 recalcChans();
1085 saveLock.unlock();
1086 BUSY_END;
1087 initDispatch();
1088 BUSY_BEGIN;
1089 renderSamples();
1090 reset();
1091 BUSY_END;
1092
1093 return true;
1094 }
1095
1096 bool DivEngine::addSystem(DivSystem which) {
1097 if (song.systemLen>=DIV_MAX_CHIPS) {
1098 lastError=fmt::sprintf(_("max number of systems is %d"),DIV_MAX_CHIPS);
1099 return false;
1100 }
1101 if (chans+getChannelCount(which)>DIV_MAX_CHANS) {
1102 lastError=fmt::sprintf(_("max number of total channels is %d"),DIV_MAX_CHANS);
1103 return false;
1104 }
1105 quitDispatch();
1106 BUSY_BEGIN;
1107 saveLock.lock();
1108 song.system[song.systemLen]=which;
1109 song.systemVol[song.systemLen]=1.0;
1110 song.systemPan[song.systemLen]=0;
1111 song.systemPanFR[song.systemLen]=0;
1112 song.systemFlags[song.systemLen++].clear();
1113 recalcChans();
1114 saveLock.unlock();
1115 BUSY_END;
1116 initDispatch();
1117 BUSY_BEGIN;
1118 saveLock.lock();
1119 if (song.patchbayAuto) {
1120 autoPatchbay();
1121 } else {
1122 int i=song.systemLen-1;
1123 if (disCont[i].dispatch!=NULL) {
1124 unsigned int outs=disCont[i].dispatch->getOutputCount();
1125 if (outs>16) outs=16;
1126 if (outs<2) {
1127 song.patchbay.reserve(DIV_MAX_OUTPUTS);
1128 for (unsigned int j=0; j<DIV_MAX_OUTPUTS; j++) {
1129 song.patchbay.push_back((i<<20)|j);
1130 }
1131 } else {
1132 if (outs>0) song.patchbay.reserve(outs);
1133 for (unsigned int j=0; j<outs; j++) {
1134 song.patchbay.push_back((i<<20)|(j<<16)|j);
1135 }
1136 }
1137 }
1138 }
1139 saveLock.unlock();
1140 renderSamples();
1141 reset();
1142 BUSY_END;
1143 return true;
1144 }
1145
1146 bool DivEngine::duplicateSystem(int index, bool pat, bool end) {
1147 if (index<0 || index>=song.systemLen) {
1148 lastError=_("invalid index");
1149 return false;
1150 }
1151 if (song.systemLen>=DIV_MAX_CHIPS) {
1152 lastError=fmt::sprintf(_("max number of systems is %d"),DIV_MAX_CHIPS);
1153 return false;
1154 }
1155 if (chans+getChannelCount(song.system[index])>DIV_MAX_CHANS) {
1156 lastError=fmt::sprintf(_("max number of total channels is %d"),DIV_MAX_CHANS);
1157 return false;
1158 }
1159 quitDispatch();
1160 BUSY_BEGIN;
1161 saveLock.lock();
1162 song.system[song.systemLen]=song.system[index];
1163 song.systemVol[song.systemLen]=song.systemVol[index];
1164 song.systemPan[song.systemLen]=song.systemPan[index];
1165 song.systemPanFR[song.systemLen]=song.systemPanFR[index];
1166 song.systemFlags[song.systemLen++]=song.systemFlags[index];
1167 recalcChans();
1168 saveLock.unlock();
1169 BUSY_END;
1170 initDispatch();
1171 BUSY_BEGIN;
1172 saveLock.lock();
1173 if (song.patchbayAuto) {
1174 autoPatchbay();
1175 } else {
1176 int i=song.systemLen-1;
1177 if (disCont[i].dispatch!=NULL) {
1178 unsigned int outs=disCont[i].dispatch->getOutputCount();
1179 if (outs>16) outs=16;
1180 if (outs<2) {
1181 song.patchbay.reserve(DIV_MAX_OUTPUTS);
1182 for (unsigned int j=0; j<DIV_MAX_OUTPUTS; j++) {
1183 song.patchbay.push_back((i<<20)|j);
1184 }
1185 } else {
1186 if (outs>0) song.patchbay.reserve(outs);
1187 for (unsigned int j=0; j<outs; j++) {
1188 song.patchbay.push_back((i<<20)|(j<<16)|j);
1189 }
1190 }
1191 }
1192 }
1193
1194 // duplicate patterns
1195 if (pat) {
1196 int srcChan=0;
1197 int destChan=0;
1198 for (int i=0; i<index; i++) {
1199 srcChan+=getChannelCount(song.system[i]);
1200 }
1201 for (int i=0; i<song.systemLen-1; i++) {
1202 destChan+=getChannelCount(song.system[i]);
1203 }
1204 for (DivSubSong* i: song.subsong) {
1205 for (int j=0; j<getChannelCount(song.system[index]); j++) {
1206 i->pat[destChan+j].effectCols=i->pat[srcChan+j].effectCols;
1207 i->chanShow[destChan+j]=i->chanShow[srcChan+j];
1208 i->chanShowChanOsc[destChan+j]=i->chanShowChanOsc[srcChan+j];
1209 i->chanCollapse[destChan+j]=i->chanCollapse[srcChan+j];
1210 i->chanName[destChan+j]=i->chanName[srcChan+j];
1211 i->chanShortName[destChan+j]=i->chanShortName[srcChan+j];
1212 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
1213 if (i->pat[srcChan+j].data[k]!=NULL) {
1214 i->pat[srcChan+j].data[k]->copyOn(i->pat[destChan+j].getPattern(k,true));
1215 }
1216 }
1217
1218 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
1219 i->orders.ord[destChan+j][k]=i->orders.ord[srcChan+j][k];
1220 }
1221 }
1222 }
1223 }
1224 saveLock.unlock();
1225 renderSamples();
1226 reset();
1227 BUSY_END;
1228
1229 if (!end) {
1230 quitDispatch();
1231 BUSY_BEGIN;
1232 saveLock.lock();
1233
1234 for (int i=song.systemLen-1; i>index; i--) {
1235 swapSystemUnsafe(i,i-1,false);
1236 }
1237
1238 recalcChans();
1239 saveLock.unlock();
1240 BUSY_END;
1241 initDispatch();
1242 BUSY_BEGIN;
1243 renderSamples();
1244 reset();
1245 BUSY_END;
1246 }
1247 return true;
1248 }
1249
1250 // TODO: maybe issue with subsongs?
1251 bool DivEngine::removeSystem(int index, bool preserveOrder) {
1252 if (song.systemLen<=1) {
1253 lastError=_("cannot remove the last one");
1254 return false;
1255 }
1256 if (index<0 || index>=song.systemLen) {
1257 lastError=_("invalid index");
1258 return false;
1259 }
1260 int chanCount=chans;
1261 quitDispatch();
1262 BUSY_BEGIN;
1263 saveLock.lock();
1264
1265 if (!preserveOrder) {
1266 int firstChan=0;
1267 while (dispatchOfChan[firstChan]!=index) firstChan++;
1268 for (int i=0; i<getChannelCount(song.system[index]); i++) {
1269 stompChannel(i+firstChan);
1270 }
1271 for (int i=firstChan+getChannelCount(song.system[index]); i<chanCount; i++) {
1272 swapChannels(i,i-getChannelCount(song.system[index]));
1273 }
1274 }
1275
1276 // patchbay
1277 for (size_t i=0; i<song.patchbay.size(); i++) {
1278 if (((song.patchbay[i]>>20)&0xfff)==(unsigned int)index) {
1279 song.patchbay.erase(song.patchbay.begin()+i);
1280 i--;
1281 }
1282 }
1283
1284 song.system[index]=DIV_SYSTEM_NULL;
1285 song.systemLen--;
1286 for (int i=index; i<song.systemLen; i++) {
1287 song.system[i]=song.system[i+1];
1288 song.systemVol[i]=song.systemVol[i+1];
1289 song.systemPan[i]=song.systemPan[i+1];
1290 song.systemPanFR[i]=song.systemPanFR[i+1];
1291 song.systemFlags[i]=song.systemFlags[i+1];
1292 }
1293 recalcChans();
1294 saveLock.unlock();
1295 BUSY_END;
1296 initDispatch();
1297 BUSY_BEGIN;
1298 renderSamples();
1299 reset();
1300 BUSY_END;
1301 return true;
1302 }
1303
1304 void DivEngine::swapSystemUnsafe(int src, int dest, bool preserveOrder) {
1305 if (!preserveOrder) {
1306 // move channels
1307 unsigned char unswappedChannels[DIV_MAX_CHANS];
1308 unsigned char swappedChannels[DIV_MAX_CHANS];
1309 std::vector<std::vector<int>> swapList;
1310 std::vector<int> chanList;
1311
1312 int tchans=0;
1313
1314 for (int i=0; i<song.systemLen; i++) {
1315 tchans+=getChannelCount(song.system[i]);
1316 }
1317
1318 memset(unswappedChannels,0,DIV_MAX_CHANS);
1319 memset(swappedChannels,0,DIV_MAX_CHANS);
1320
1321 for (int i=0; i<tchans; i++) {
1322 unswappedChannels[i]=i;
1323 }
1324
1325 // prepare swap list
1326 int index=0;
1327 if (song.systemLen>0) swapList.reserve(song.systemLen);
1328 for (int i=0; i<song.systemLen; i++) {
1329 chanList.clear();
1330 const int channelCount=getChannelCount(song.system[i]);
1331 if (channelCount>0) chanList.reserve(channelCount);
1332 for (int j=0; j<channelCount; j++) {
1333 chanList.push_back(index);
1334 index++;
1335 }
1336 swapList.push_back(chanList);
1337 }
1338 swapList[src].swap(swapList[dest]);
1339
1340 // unfold it
1341 index=0;
1342 for (std::vector<int>& i: swapList) {
1343 for (int& j: i) {
1344 swappedChannels[index++]=j;
1345 }
1346 }
1347
1348 // swap channels
1349 logV("swap list:");
1350 for (int i=0; i<tchans; i++) {
1351 logV("- %d -> %d",unswappedChannels[i],swappedChannels[i]);
1352 }
1353
1354 for (size_t i=0; i<song.subsong.size(); i++) {
1355 DivOrders prevOrders=song.subsong[i]->orders;
1356 DivPattern* prevPat[DIV_MAX_CHANS][DIV_MAX_PATTERNS];
1357 unsigned char prevEffectCols[DIV_MAX_CHANS];
1358 String prevChanName[DIV_MAX_CHANS];
1359 String prevChanShortName[DIV_MAX_CHANS];
1360 bool prevChanShow[DIV_MAX_CHANS];
1361 bool prevChanShowChanOsc[DIV_MAX_CHANS];
1362 unsigned char prevChanCollapse[DIV_MAX_CHANS];
1363
1364 for (int j=0; j<tchans; j++) {
1365 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
1366 prevPat[j][k]=song.subsong[i]->pat[j].data[k];
1367 }
1368 prevEffectCols[j]=song.subsong[i]->pat[j].effectCols;
1369
1370 prevChanName[j]=song.subsong[i]->chanName[j];
1371 prevChanShortName[j]=song.subsong[i]->chanShortName[j];
1372 prevChanShow[j]=song.subsong[i]->chanShow[j];
1373 prevChanShowChanOsc[j]=song.subsong[i]->chanShowChanOsc[j];
1374 prevChanCollapse[j]=song.subsong[i]->chanCollapse[j];
1375 }
1376
1377 for (int j=0; j<tchans; j++) {
1378 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
1379 song.subsong[i]->orders.ord[j][k]=prevOrders.ord[swappedChannels[j]][k];
1380 song.subsong[i]->pat[j].data[k]=prevPat[swappedChannels[j]][k];
1381 }
1382
1383 song.subsong[i]->pat[j].effectCols=prevEffectCols[swappedChannels[j]];
1384 song.subsong[i]->chanName[j]=prevChanName[swappedChannels[j]];
1385 song.subsong[i]->chanShortName[j]=prevChanShortName[swappedChannels[j]];
1386 song.subsong[i]->chanShow[j]=prevChanShow[swappedChannels[j]];
1387 song.subsong[i]->chanShowChanOsc[j]=prevChanShowChanOsc[swappedChannels[j]];
1388 song.subsong[i]->chanCollapse[j]=prevChanCollapse[swappedChannels[j]];
1389 }
1390 }
1391 }
1392
1393 DivSystem srcSystem=song.system[src];
1394 float srcVol=song.systemVol[src];
1395 float srcPan=song.systemPan[src];
1396 float srcPanFR=song.systemPanFR[src];
1397
1398 song.system[src]=song.system[dest];
1399 song.system[dest]=srcSystem;
1400
1401 song.systemVol[src]=song.systemVol[dest];
1402 song.systemVol[dest]=srcVol;
1403
1404 song.systemPan[src]=song.systemPan[dest];
1405 song.systemPan[dest]=srcPan;
1406
1407 song.systemPanFR[src]=song.systemPanFR[dest];
1408 song.systemPanFR[dest]=srcPanFR;
1409
1410 // I am kinda scared to use std::swap
1411 DivConfig oldFlags=song.systemFlags[src];
1412 song.systemFlags[src]=song.systemFlags[dest];
1413 song.systemFlags[dest]=oldFlags;
1414
1415 // patchbay
1416 for (unsigned int& i: song.patchbay) {
1417 if (((i>>20)&0xfff)==(unsigned int)src) {
1418 i=(i&(~0xfff00000))|((unsigned int)dest<<20);
1419 } else if (((i>>20)&0xfff)==(unsigned int)dest) {
1420 i=(i&(~0xfff00000))|((unsigned int)src<<20);
1421 }
1422 }
1423 }
1424
1425 bool DivEngine::swapSystem(int src, int dest, bool preserveOrder) {
1426 if (src==dest) {
1427 lastError=_("source and destination are equal");
1428 return false;
1429 }
1430 if (src<0 || src>=song.systemLen) {
1431 lastError=_("invalid source index");
1432 return false;
1433 }
1434 if (dest<0 || dest>=song.systemLen) {
1435 lastError=_("invalid destination index");
1436 return false;
1437 }
1438 //int chanCount=chans;
1439 quitDispatch();
1440 BUSY_BEGIN;
1441 saveLock.lock();
1442
1443 swapSystemUnsafe(src,dest,preserveOrder);
1444
1445 recalcChans();
1446 saveLock.unlock();
1447 BUSY_END;
1448 initDispatch();
1449 BUSY_BEGIN;
1450 renderSamples();
1451 reset();
1452 BUSY_END;
1453 return true;
1454 }
1455
1456 void DivEngine::poke(int sys, unsigned int addr, unsigned short val) {
1457 if (sys<0 || sys>=song.systemLen) return;
1458 BUSY_BEGIN;
1459 disCont[sys].dispatch->poke(addr,val);
1460 BUSY_END;
1461 }
1462
1463 void DivEngine::poke(int sys, std::vector<DivRegWrite>& wlist) {
1464 if (sys<0 || sys>=song.systemLen) return;
1465 BUSY_BEGIN;
1466 disCont[sys].dispatch->poke(wlist);
1467 BUSY_END;
1468 }
1469
1470 String DivEngine::getLastError() {
1471 return lastError;
1472 }
1473
1474 String DivEngine::getWarnings() {
1475 return warnings;
1476 }
1477
1478 String DivEngine::getPlaybackDebugInfo() {
1479 return fmt::sprintf(
1480 "curOrder: %d\n"
1481 "prevOrder: %d\n"
1482 "curRow: %d\n"
1483 "prevRow: %d\n"
1484 "ticks: %d\n"
1485 "subticks: %d\n"
1486 "totalLoops: %d\n"
1487 "lastLoopPos: %d\n"
1488 "nextSpeed: %d\n"
1489 "divider: %f\n"
1490 "cycles: %d\n"
1491 "clockDrift: %f\n"
1492 "midiClockCycles: %d\n"
1493 "midiClockDrift: %f\n"
1494 "midiTimeCycles: %d\n"
1495 "midiTimeDrift: %f\n"
1496 "changeOrd: %d\n"
1497 "changePos: %d\n"
1498 "totalSeconds: %d\n"
1499 "totalTicks: %d\n"
1500 "totalTicksR: %d\n"
1501 "curMidiClock: %d\n"
1502 "curMidiTime: %d\n"
1503 "totalCmds: %d\n"
1504 "lastCmds: %d\n"
1505 "cmdsPerSecond: %d\n"
1506 "globalPitch: %d\n"
1507 "extValue: %d\n"
1508 "tempoAccum: %d\n"
1509 "totalProcessed: %d\n"
1510 "bufferPos: %d\n",
1511 curOrder,prevOrder,curRow,prevRow,ticks,subticks,totalLoops,lastLoopPos,nextSpeed,divider,cycles,clockDrift,
1512 midiClockCycles,midiClockDrift,midiTimeCycles,midiTimeDrift,changeOrd,changePos,totalSeconds,totalTicks,
1513 totalTicksR,curMidiClock,curMidiTime,totalCmds,lastCmds,cmdsPerSecond,globalPitch,
1514 (int)extValue,(int)tempoAccum,(int)totalProcessed,(int)bufferPos
1515 );
1516 }
1517
1518 DivInstrument* DivEngine::getIns(int index, DivInstrumentType fallbackType) {
1519 if (index==-2 && tempIns!=NULL) {
1520 return tempIns;
1521 }
1522 if (index<0 || index>=song.insLen) {
1523 switch (fallbackType) {
1524 case DIV_INS_OPLL:
1525 return &song.nullInsOPLL;
1526 break;
1527 case DIV_INS_OPL:
1528 return &song.nullInsOPL;
1529 break;
1530 case DIV_INS_OPL_DRUMS:
1531 return &song.nullInsOPLDrums;
1532 break;
1533 case DIV_INS_ESFM:
1534 return &song.nullInsESFM;
1535 break;
1536 default:
1537 break;
1538 }
1539 return &song.nullIns;
1540 }
1541 return song.ins[index];
1542 }
1543
1544 DivWavetable* DivEngine::getWave(int index) {
1545 if (index<0 || index>=song.waveLen) {
1546 if (song.waveLen>0) {
1547 return song.wave[0];
1548 } else {
1549 return &song.nullWave;
1550 }
1551 }
1552 return song.wave[index];
1553 }
1554
1555 DivSample* DivEngine::getSample(int index) {
1556 if (index<0 || index>=song.sampleLen) return &song.nullSample;
1557 return song.sample[index];
1558 }
1559
1560 DivDispatch* DivEngine::getDispatch(int index) {
1561 if (index<0 || index>=song.systemLen) return NULL;
1562 return disCont[index].dispatch;
1563 }
1564
1565 void DivEngine::setLoops(int loops) {
1566 remainingLoops=loops;
1567 }
1568
1569 DivChannelState* DivEngine::getChanState(int ch) {
1570 if (ch<0 || ch>=chans) return NULL;
1571 return &chan[ch];
1572 }
1573
1574 unsigned short DivEngine::getChanPan(int ch) {
1575 if (ch<0 || ch>=chans) return 0;
1576 return disCont[dispatchOfChan[ch]].dispatch->getPan(dispatchChanOfChan[ch]);
1577 }
1578
1579 void* DivEngine::getDispatchChanState(int ch) {
1580 if (ch<0 || ch>=chans) return NULL;
1581 return disCont[dispatchOfChan[ch]].dispatch->getChanState(dispatchChanOfChan[ch]);
1582 }
1583
1584 void DivEngine::getChanPaired(int ch, std::vector<DivChannelPair>& ret) {
1585 if (ch<0 || ch>=chans) return;
1586 disCont[dispatchOfChan[ch]].dispatch->getPaired(dispatchChanOfChan[ch],ret);
1587 }
1588
1589 DivChannelModeHints DivEngine::getChanModeHints(int ch) {
1590 if (ch<0 || ch>=chans) return DivChannelModeHints();
1591 return disCont[dispatchOfChan[ch]].dispatch->getModeHints(dispatchChanOfChan[ch]);
1592 }
1593
1594 unsigned char* DivEngine::getRegisterPool(int sys, int& size, int& depth) {
1595 if (sys<0 || sys>=song.systemLen) return NULL;
1596 if (disCont[sys].dispatch==NULL) return NULL;
1597 size=disCont[sys].dispatch->getRegisterPoolSize();
1598 depth=disCont[sys].dispatch->getRegisterPoolDepth();
1599 return disCont[sys].dispatch->getRegisterPool();
1600 }
1601
1602 DivMacroInt* DivEngine::getMacroInt(int chan) {
1603 if (chan<0 || chan>=chans) return NULL;
1604 return disCont[dispatchOfChan[chan]].dispatch->getChanMacroInt(dispatchChanOfChan[chan]);
1605 }
1606
1607 DivSamplePos DivEngine::getSamplePos(int chan) {
1608 if (chan<0 || chan>=chans) return DivSamplePos();
1609 return disCont[dispatchOfChan[chan]].dispatch->getSamplePos(dispatchChanOfChan[chan]);
1610 }
1611
1612 DivDispatchOscBuffer* DivEngine::getOscBuffer(int chan) {
1613 if (chan<0 || chan>=chans) return NULL;
1614 return disCont[dispatchOfChan[chan]].dispatch->getOscBuffer(dispatchChanOfChan[chan]);
1615 }
1616
1617 void DivEngine::enableCommandStream(bool enable) {
1618 cmdStreamEnabled=enable;
1619 }
1620
1621 void DivEngine::getCommandStream(std::vector<DivCommand>& where) {
1622 BUSY_BEGIN;
1623 where.clear();
1624 where.reserve(cmdStream.size());
1625 for (DivCommand& i: cmdStream) {
1626 where.push_back(i);
1627 }
1628 cmdStream.clear();
1629 BUSY_END;
1630 }
1631
1632 void DivEngine::playSub(bool preserveDrift, int goalRow) {
1633 logV("playSub() called");
1634 std::chrono::high_resolution_clock::time_point timeStart=std::chrono::high_resolution_clock::now();
1635 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->setSkipRegisterWrites(false);
1636 reset();
1637 if (preserveDrift && curOrder==0) {
1638 logV("preserveDrift && curOrder is true");
1639 return;
1640 }
1641 bool oldRepeatPattern=repeatPattern;
1642 repeatPattern=false;
1643 int goal=curOrder;
1644 curOrder=0;
1645 curRow=0;
1646 prevOrder=0;
1647 prevRow=0;
1648 stepPlay=0;
1649 if (curSubSong!=NULL) curSubSong->arpLen=1;
1650 int prevDrift, prevMidiClockDrift, prevMidiTimeDrift;
1651 prevDrift=clockDrift;
1652 prevMidiClockDrift=midiClockDrift;
1653 prevMidiTimeDrift=midiTimeDrift;
1654 clockDrift=0;
1655 cycles=0;
1656 midiClockCycles=0;
1657 midiClockDrift=0;
1658 midiTimeCycles=0;
1659 midiTimeDrift=0;
1660 if (!preserveDrift) {
1661 ticks=1;
1662 tempoAccum=0;
1663 totalTicks=0;
1664 totalTicksOff=0;
1665 totalSeconds=0;
1666 totalTicksR=0;
1667 curMidiClock=0;
1668 curMidiTime=0;
1669 curMidiTimeCode=0;
1670 curMidiTimePiece=0;
1671 totalLoops=0;
1672 lastLoopPos=-1;
1673 }
1674 endOfSong=false;
1675 // whaaaaa?
1676 curSpeed=0;
1677 playing=true;
1678 skipping=true;
1679 memset(walked,0,8192);
1680 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->setSkipRegisterWrites(true);
1681 logV("goal: %d goalRow: %d",goal,goalRow);
1682 while (playing && curOrder<goal) {
1683 if (nextTick(preserveDrift)) {
1684 skipping=false;
1685 cmdStream.clear();
1686 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->setSkipRegisterWrites(false);
1687 if (goal>0 || goalRow>0) {
1688 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->forceIns();
1689 }
1690 return;
1691 }
1692 if (!preserveDrift) {
1693 runMidiClock(cycles);
1694 runMidiTime(cycles);
1695 }
1696 }
1697 int oldOrder=curOrder;
1698 while (playing && (curRow<goalRow || ticks>1)) {
1699 if (nextTick(preserveDrift)) {
1700 skipping=false;
1701 cmdStream.clear();
1702 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->setSkipRegisterWrites(false);
1703 if (goal>0 || goalRow>0) {
1704 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->forceIns();
1705 }
1706 return;
1707 }
1708 if (!preserveDrift) {
1709 runMidiClock(cycles);
1710 runMidiTime(cycles);
1711 }
1712 if (oldOrder!=curOrder) break;
1713 if (ticks-((tempoAccum+virtualTempoN)/MAX(1,virtualTempoD))<1 && curRow>=goalRow) break;
1714 }
1715 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->setSkipRegisterWrites(false);
1716 if (goal>0 || goalRow>0) {
1717 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->forceIns();
1718 }
1719 for (int i=0; i<chans; i++) {
1720 chan[i].cut=-1;
1721 chan[i].cutType=0;
1722 }
1723 repeatPattern=oldRepeatPattern;
1724 if (preserveDrift) {
1725 clockDrift=prevDrift;
1726 midiClockDrift=prevMidiClockDrift;
1727 midiTimeDrift=prevMidiTimeDrift;
1728 } else {
1729 clockDrift=0;
1730 cycles=0;
1731 midiClockCycles=0;
1732 midiClockDrift=0;
1733 midiTimeCycles=0;
1734 midiTimeDrift=0;
1735 if (curMidiTime>0) {
1736 curMidiTime--;
1737 }
1738 if (curMidiClock>0) {
1739 curMidiClock--;
1740 }
1741 curMidiTimePiece=0;
1742 }
1743 if (!preserveDrift) {
1744 ticks=1;
1745 subticks=1;
1746 prevOrder=curOrder;
1747 prevRow=curRow;
1748 prevSpeed=nextSpeed;
1749 tempoAccum=0;
1750 }
1751 skipping=false;
1752 cmdStream.clear();
1753 std::chrono::high_resolution_clock::time_point timeEnd=std::chrono::high_resolution_clock::now();
1754 logV("playSub() took %dµs",std::chrono::duration_cast<std::chrono::microseconds>(timeEnd-timeStart).count());
1755 }
1756
1757 /*
1758 int DivEngine::calcBaseFreq(double clock, double divider, int note, bool period) {
1759 double base=(period?(song.tuning*0.0625):song.tuning)*pow(2.0,(float)(note+3)/12.0);
1760 return period?
1761 round((clock/base)/divider):
1762 base*(divider/clock);
1763 }*/
1764
1765 double DivEngine::calcBaseFreq(double clock, double divider, int note, bool period) {
1766 if (song.linearPitch==2) { // full linear
1767 return (note<<7);
1768 }
1769 double base=(period?(song.tuning*0.0625):song.tuning)*pow(2.0,(float)(note+3)/12.0);
1770 return period?
1771 (clock/base)/divider:
1772 base*(divider/clock);
1773 }
1774
1775 #define CONVERT_FNUM_BLOCK(bf,bits,note) \
1776 double tuning=song.tuning; \
1777 if (tuning<400.0) tuning=400.0; \
1778 if (tuning>500.0) tuning=500.0; \
1779 int boundaryBottom=tuning*pow(2.0,0.25)*(divider/clock); \
1780 int boundaryTop=2.0*tuning*pow(2.0,0.25)*(divider/clock); \
1781 while (boundaryTop>((1<<bits)-1)) { \
1782 boundaryTop>>=1; \
1783 boundaryBottom>>=1; \
1784 } \
1785 int block=(note)/12; \
1786 if (block<0) block=0; \
1787 if (block>7) block=7; \
1788 bf>>=block; \
1789 if (bf<0) bf=0; \
1790 /* octave boundaries */ \
1791 while (bf>0 && bf<boundaryBottom && block>0) { \
1792 bf<<=1; \
1793 block--; \
1794 } \
1795 if (bf>boundaryTop) { \
1796 while (block<7 && bf>boundaryTop) { \
1797 bf>>=1; \
1798 block++; \
1799 } \
1800 if (bf>((1<<bits)-1)) { \
1801 bf=(1<<bits)-1; \
1802 } \
1803 } \
1804 /* logV("f-num: %d block: %d",bf,block); */ \
1805 return bf|(block<<bits);
1806
1807 #define CONVERT_FNUM_FIXEDBLOCK(bf,bits,block) \
1808 bf>>=(block); \
1809 if (bf<0) bf=0; \
1810 if (bf>((1<<(bits))-1)) { \
1811 bf=(1<<(bits))-1; \
1812 } \
1813 return bf|((block)<<(bits));
1814
1815 int DivEngine::calcBaseFreqFNumBlock(double clock, double divider, int note, int bits, int fixedBlock) {
1816 if (song.linearPitch==2) { // full linear
1817 return (note<<7);
1818 }
1819 int bf=calcBaseFreq(clock,divider,note,false);
1820 if (fixedBlock>0) {
1821 CONVERT_FNUM_FIXEDBLOCK(bf,bits,fixedBlock-1);
1822 } else {
1823 CONVERT_FNUM_BLOCK(bf,bits,note);
1824 }
1825 }
1826
1827 int DivEngine::calcFreq(int base, int pitch, int arp, bool arpFixed, bool period, int octave, int pitch2, double clock, double divider, int blockBits, int fixedBlock) {
1828 if (song.linearPitch==2) {
1829 // do frequency calculation here
1830 int nbase=base+pitch+pitch2;
1831 if (!song.oldArpStrategy) {
1832 if (arpFixed) {
1833 nbase=(arp<<7)+pitch+pitch2;
1834 } else {
1835 nbase+=arp<<7;
1836 }
1837 }
1838 double fbase=(period?(song.tuning*0.0625):song.tuning)*pow(2.0,(float)(nbase+384)/(128.0*12.0));
1839 int bf=period?
1840 round((clock/fbase)/divider):
1841 round(fbase*(divider/clock));
1842 if (blockBits>0) {
1843 if (fixedBlock>0) {
1844 CONVERT_FNUM_FIXEDBLOCK(bf,blockBits,fixedBlock-1);
1845 } else {
1846 CONVERT_FNUM_BLOCK(bf,blockBits,nbase>>7);
1847 }
1848 } else {
1849 return bf;
1850 }
1851 }
1852 if (song.linearPitch==1) {
1853 // global pitch multiplier
1854 int whatTheFuck=(1024+(globalPitch<<6)-(globalPitch<0?globalPitch-6:0));
1855 if (whatTheFuck<1) whatTheFuck=1; // avoids division by zero but please kill me
1856 if (song.pitchMacroIsLinear) {
1857 pitch+=pitch2;
1858 }
1859 pitch+=2048;
1860 if (pitch<0) pitch=0;
1861 if (pitch>4095) pitch=4095;
1862 int ret=period?
1863 ((base*(reversePitchTable[pitch]))/whatTheFuck):
1864 (((base*(pitchTable[pitch]))>>10)*whatTheFuck)/1024;
1865 if (!song.pitchMacroIsLinear) {
1866 ret+=period?(-pitch2):pitch2;
1867 }
1868 return ret;
1869 }
1870 return period?
1871 base-pitch-pitch2:
1872 base+((pitch*octave)>>1)+pitch2;
1873 }
1874
1875 int DivEngine::calcArp(int note, int arp, int offset) {
1876 if (arp<0) {
1877 if (!(arp&0x40000000)) return (arp|0x40000000)+offset;
1878 } else {
1879 if (arp&0x40000000) return (arp&(~0x40000000))+offset;
1880 }
1881 return note+arp;
1882 }
1883
1884 int DivEngine::convertPanSplitToLinear(unsigned int val, unsigned char bits, int range) {
1885 int panL=val>>bits;
1886 int panR=val&((1<<bits)-1);
1887 int diff=panR-panL;
1888 float pan=0.5f;
1889 if (diff!=0) {
1890 pan=(1.0f+((float)diff/(float)MAX(panL,panR)))*0.5f;
1891 }
1892 return pan*range;
1893 }
1894
1895 int DivEngine::convertPanSplitToLinearLR(unsigned char left, unsigned char right, int range) {
1896 return convertPanSplitToLinear((left<<8)|right,8,range);
1897 }
1898
1899 unsigned int DivEngine::convertPanLinearToSplit(int val, unsigned char bits, int range) {
1900 if (val<0) val=0;
1901 if (val>range) val=range;
1902 int maxV=(1<<bits)-1;
1903 int panL=(((range-val)*maxV*2))/range;
1904 int panR=((val)*maxV*2)/range;
1905 if (panL>maxV) panL=maxV;
1906 if (panR>maxV) panR=maxV;
1907 return (panL<<bits)|panR;
1908 }
1909
1910 bool DivEngine::play() {
1911 BUSY_BEGIN_SOFT;
1912 curOrder=prevOrder;
1913 sPreview.sample=-1;
1914 sPreview.wave=-1;
1915 sPreview.pos=0;
1916 sPreview.dir=false;
1917 shallStop=false;
1918 if (stepPlay==0) {
1919 freelance=false;
1920 playSub(false);
1921 } else {
1922 stepPlay=0;
1923 }
1924 for (int i=0; i<DIV_MAX_CHANS; i++) {
1925 keyHit[i]=false;
1926 }
1927 curMidiTimePiece=0;
1928 if (output) if (!skipping && output->midiOut!=NULL) {
1929 if (midiOutClock) {
1930 output->midiOut->send(TAMidiMessage(TA_MIDI_POSITION,(curMidiClock>>7)&0x7f,curMidiClock&0x7f));
1931 }
1932 if (midiOutTime) {
1933 TAMidiMessage msg;
1934 msg.type=TA_MIDI_SYSEX;
1935 msg.sysExData.reset(new unsigned char[10],std::default_delete<unsigned char[]>());
1936 msg.sysExLen=10;
1937 unsigned char* msgData=msg.sysExData.get();
1938 int actualTime=curMidiTime;
1939 int timeRate=midiOutTimeRate;
1940 int drop=0;
1941 if (timeRate<1 || timeRate>4) {
1942 if (curSubSong->hz>=47.98 && curSubSong->hz<=48.02) {
1943 timeRate=1;
1944 } else if (curSubSong->hz>=49.98 && curSubSong->hz<=50.02) {
1945 timeRate=2;
1946 } else if (curSubSong->hz>=59.9 && curSubSong->hz<=60.11) {
1947 timeRate=4;
1948 } else {
1949 timeRate=4;
1950 }
1951 }
1952
1953 switch (timeRate) {
1954 case 1: // 24
1955 msgData[5]=(actualTime/(60*60*24))%24;
1956 msgData[6]=(actualTime/(60*24))%60;
1957 msgData[7]=(actualTime/24)%60;
1958 msgData[8]=actualTime%24;
1959 break;
1960 case 2: // 25
1961 msgData[5]=(actualTime/(60*60*25))%24;
1962 msgData[6]=(actualTime/(60*25))%60;
1963 msgData[7]=(actualTime/25)%60;
1964 msgData[8]=actualTime%25;
1965 break;
1966 case 3: // 29.97 (NTSC drop)
1967 // drop
1968 drop=((actualTime/(30*60))-(actualTime/(30*600)))*2;
1969 actualTime+=drop;
1970
1971 msgData[5]=(actualTime/(60*60*30))%24;
1972 msgData[6]=(actualTime/(60*30))%60;
1973 msgData[7]=(actualTime/30)%60;
1974 msgData[8]=actualTime%30;
1975 break;
1976 case 4: // 30 (NTSC non-drop)
1977 default:
1978 msgData[5]=(actualTime/(60*60*30))%24;
1979 msgData[6]=(actualTime/(60*30))%60;
1980 msgData[7]=(actualTime/30)%60;
1981 msgData[8]=actualTime%30;
1982 break;
1983 }
1984
1985 msgData[5]|=(timeRate-1)<<5;
1986
1987 msgData[0]=0xf0;
1988 msgData[1]=0x7f;
1989 msgData[2]=0x7f;
1990 msgData[3]=0x01;
1991 msgData[4]=0x01;
1992 msgData[9]=0xf7;
1993 output->midiOut->send(msg);
1994 }
1995 output->midiOut->send(TAMidiMessage(TA_MIDI_MACHINE_PLAY,0,0));
1996 }
1997 bool didItPlay=playing;
1998 BUSY_END;
1999 return didItPlay;
2000 }
2001
2002 bool DivEngine::playToRow(int row) {
2003 BUSY_BEGIN_SOFT;
2004 sPreview.sample=-1;
2005 sPreview.wave=-1;
2006 sPreview.pos=0;
2007 sPreview.dir=false;
2008 freelance=false;
2009 playSub(false,row);
2010 for (int i=0; i<DIV_MAX_CHANS; i++) {
2011 keyHit[i]=false;
2012 }
2013 bool didItPlay=playing;
2014 BUSY_END;
2015 return didItPlay;
2016 }
2017
2018 void DivEngine::stepOne(int row) {
2019 if (!isPlaying()) {
2020 BUSY_BEGIN_SOFT;
2021 freelance=false;
2022 playSub(false,row);
2023 for (int i=0; i<DIV_MAX_CHANS; i++) {
2024 keyHit[i]=false;
2025 }
2026 } else {
2027 BUSY_BEGIN;
2028 }
2029 stepPlay=2;
2030 ticks=1;
2031 prevOrder=curOrder;
2032 prevRow=curRow;
2033 BUSY_END;
2034 }
2035
2036 void DivEngine::stop() {
2037 BUSY_BEGIN;
2038 freelance=false;
2039 if (!playing) {
2040 //Send midi panic
2041 if (output) if (output->midiOut!=NULL) {
2042 output->midiOut->send(TAMidiMessage(TA_MIDI_CONTROL,0x7B,0));
2043 logV("Midi panic sent");
2044 }
2045 }
2046 playing=false;
2047 extValuePresent=false;
2048 endOfSong=false; // what?
2049 stepPlay=0;
2050 curOrder=prevOrder;
2051 curRow=prevRow;
2052 remainingLoops=-1;
2053 sPreview.sample=-1;
2054 sPreview.wave=-1;
2055 sPreview.pos=0;
2056 sPreview.dir=false;
2057 for (int i=0; i<song.systemLen; i++) {
2058 disCont[i].dispatch->notifyPlaybackStop();
2059 }
2060 if (output) if (output->midiOut!=NULL) {
2061 output->midiOut->send(TAMidiMessage(TA_MIDI_MACHINE_STOP,0,0));
2062 for (int i=0; i<chans; i++) {
2063 if (chan[i].curMidiNote>=0) {
2064 output->midiOut->send(TAMidiMessage(0x80|(i&15),chan[i].curMidiNote,0));
2065 }
2066 }
2067 }
2068
2069 // reset all chan oscs
2070 for (int i=0; i<chans; i++) {
2071 DivDispatchOscBuffer* buf=disCont[dispatchOfChan[i]].dispatch->getOscBuffer(dispatchChanOfChan[i]);
2072 if (buf!=NULL) {
2073 buf->reset();
2074 }
2075 }
2076 BUSY_END;
2077 }
2078
2079 void DivEngine::halt() {
2080 BUSY_BEGIN;
2081 halted=true;
2082 BUSY_END;
2083 }
2084
2085 void DivEngine::resume() {
2086 BUSY_BEGIN;
2087 halted=false;
2088 haltOn=DIV_HALT_NONE;
2089 BUSY_END;
2090 }
2091
2092 void DivEngine::haltWhen(DivHaltPositions when) {
2093 BUSY_BEGIN;
2094 halted=false;
2095 haltOn=when;
2096 BUSY_END;
2097 }
2098
2099 bool DivEngine::isHalted() {
2100 return halted;
2101 }
2102
2103 const char** DivEngine::getRegisterSheet(int sys) {
2104 if (sys<0 || sys>=song.systemLen) return NULL;
2105 return disCont[sys].dispatch->getRegisterSheet();
2106 }
2107
2108 void DivEngine::recalcChans() {
2109 bool isInsTypePossible[DIV_INS_MAX];
2110 chans=0;
2111 int chanIndex=0;
2112 memset(isInsTypePossible,0,DIV_INS_MAX*sizeof(bool));
2113 for (int i=0; i<song.systemLen; i++) {
2114 int chanCount=getChannelCount(song.system[i]);
2115 int firstChan=chans;
2116 chans+=chanCount;
2117 for (int j=0; j<chanCount; j++) {
2118 sysOfChan[chanIndex]=song.system[i];
2119 dispatchOfChan[chanIndex]=i;
2120 dispatchChanOfChan[chanIndex]=j;
2121 dispatchFirstChan[chanIndex]=firstChan;
2122 chanIndex++;
2123
2124 if (sysDefs[song.system[i]]!=NULL) {
2125 if (sysDefs[song.system[i]]->chanInsType[j][0]!=DIV_INS_NULL) {
2126 isInsTypePossible[sysDefs[song.system[i]]->chanInsType[j][0]]=true;
2127 }
2128
2129 if (sysDefs[song.system[i]]->chanInsType[j][1]!=DIV_INS_NULL) {
2130 isInsTypePossible[sysDefs[song.system[i]]->chanInsType[j][1]]=true;
2131 }
2132 }
2133 }
2134 }
2135
2136 possibleInsTypes.clear();
2137 for (int i=0; i<DIV_INS_MAX; i++) {
2138 if (isInsTypePossible[i]) possibleInsTypes.push_back((DivInstrumentType)i);
2139 }
2140
2141 checkAssetDir(song.insDir,song.ins.size());
2142 checkAssetDir(song.waveDir,song.wave.size());
2143 checkAssetDir(song.sampleDir,song.sample.size());
2144
2145 hasLoadedSomething=true;
2146 }
2147
2148 void DivEngine::reset() {
2149 if (output) if (output->midiOut!=NULL) {
2150 output->midiOut->send(TAMidiMessage(TA_MIDI_MACHINE_STOP,0,0));
2151 for (int i=0; i<chans; i++) {
2152 if (chan[i].curMidiNote>=0) {
2153 output->midiOut->send(TAMidiMessage(0x80|(i&15),chan[i].curMidiNote,0));
2154 }
2155 }
2156 }
2157 for (int i=0; i<DIV_MAX_CHANS; i++) {
2158 chan[i]=DivChannelState();
2159 if (i<chans) chan[i].volMax=(disCont[dispatchOfChan[i]].dispatch->dispatch(DivCommand(DIV_CMD_GET_VOLMAX,dispatchChanOfChan[i]))<<8)|0xff;
2160 chan[i].volume=chan[i].volMax;
2161 if (song.linearPitch==0) chan[i].vibratoFine=4;
2162 }
2163 extValue=0;
2164 extValuePresent=0;
2165 speeds=curSubSong->speeds;
2166 virtualTempoN=curSubSong->virtualTempoN;
2167 virtualTempoD=curSubSong->virtualTempoD;
2168 firstTick=false;
2169 shallStop=false;
2170 shallStopSched=false;
2171 pendingMetroTick=0;
2172 elapsedBars=0;
2173 elapsedBeats=0;
2174 nextSpeed=speeds.val[0];
2175 divider=curSubSong->hz;
2176 globalPitch=0;
2177 for (int i=0; i<song.systemLen; i++) {
2178 disCont[i].dispatch->reset();
2179 disCont[i].clear();
2180 }
2181 }
2182
2183 void DivEngine::syncReset() {
2184 BUSY_BEGIN;
2185 reset();
2186 BUSY_END;
2187 }
2188
2189 const int sampleRates[6]={
2190 4000, 8000, 11025, 16000, 22050, 32000
2191 };
2192
2193 int DivEngine::fileToDivRate(int frate) {
2194 if (frate<0) frate=0;
2195 if (frate>5) frate=5;
2196 return sampleRates[frate];
2197 }
2198
2199 int DivEngine::divToFileRate(int drate) {
2200 if (drate>26000) {
2201 return 5;
2202 } else if (drate>18000) {
2203 return 4;
2204 } else if (drate>14000) {
2205 return 3;
2206 } else if (drate>9500) {
2207 return 2;
2208 } else if (drate>6000) {
2209 return 1;
2210 } else {
2211 return 0;
2212 }
2213 return 4;
2214 }
2215
2216 void DivEngine::testFunction() {
2217 logI("it works!");
2218 }
2219
2220 int DivEngine::getEffectiveSampleRate(int rate) {
2221 if (rate<1) return 0;
2222 switch (song.system[0]) {
2223 case DIV_SYSTEM_YMU759:
2224 return 8000;
2225 case DIV_SYSTEM_YM2612: case DIV_SYSTEM_YM2612_EXT:
2226 return 1278409/(1280000/rate);
2227 case DIV_SYSTEM_PCE:
2228 return 1789773/(1789773/rate);
2229 case DIV_SYSTEM_SEGAPCM: case DIV_SYSTEM_SEGAPCM_COMPAT:
2230 return (31250*MIN(255,(rate*255/31250)))/255;
2231 case DIV_SYSTEM_QSOUND:
2232 return (24038*MIN(65535,(rate*4096/24038)))/4096;
2233 case DIV_SYSTEM_YM2610: case DIV_SYSTEM_YM2610_EXT: case DIV_SYSTEM_YM2610_FULL: case DIV_SYSTEM_YM2610_FULL_EXT: case DIV_SYSTEM_YM2610B: case DIV_SYSTEM_YM2610B_EXT:
2234 return 18518;
2235 case DIV_SYSTEM_VERA:
2236 return (48828*MIN(128,(rate*128/48828)))/128;
2237 case DIV_SYSTEM_X1_010:
2238 return (31250*MIN(255,(rate*16/31250)))/16; // TODO: support variable clock case
2239 case DIV_SYSTEM_ES5506:
2240 return (31250*MIN(131071,(rate*2048/31250)))/2048; // TODO: support variable clock, channel limit case
2241 default:
2242 break;
2243 }
2244 return rate;
2245 }
2246
2247 void DivEngine::previewSample(int sample, int note, int pStart, int pEnd) {
2248 BUSY_BEGIN;
2249 previewSampleNoLock(sample,note,pStart,pEnd);
2250 BUSY_END;
2251 }
2252
2253 void DivEngine::stopSamplePreview() {
2254 BUSY_BEGIN;
2255 stopSamplePreviewNoLock();
2256 BUSY_END;
2257 }
2258
2259 void DivEngine::previewWave(int wave, int note) {
2260 BUSY_BEGIN;
2261 previewWaveNoLock(wave,note);
2262 BUSY_END;
2263 }
2264
2265 void DivEngine::stopWavePreview() {
2266 BUSY_BEGIN;
2267 stopWavePreviewNoLock();
2268 BUSY_END;
2269 }
2270
2271 void DivEngine::previewSampleNoLock(int sample, int note, int pStart, int pEnd) {
2272 sPreview.pBegin=pStart;
2273 sPreview.pEnd=pEnd;
2274 sPreview.dir=false;
2275 if (sample<0 || sample>=(int)song.sample.size()) {
2276 sPreview.sample=-1;
2277 sPreview.pos=0;
2278 sPreview.dir=false;
2279 return;
2280 }
2281 blip_clear(samp_bb);
2282 double rate=song.sample[sample]->centerRate;
2283 if (note>=0) {
2284 rate=(pow(2.0,(double)(note)/12.0)*((double)song.sample[sample]->centerRate)*0.0625);
2285 if (rate<=0) rate=song.sample[sample]->centerRate;
2286 }
2287 if (rate<100) rate=100;
2288 double rateOrig=rate;
2289 sPreview.rateMul=1;
2290 while (sPreview.rateMul<0x40000000 && rate<got.rate) {
2291 sPreview.rateMul<<=1;
2292 rate*=2.0;
2293 }
2294 blip_set_rates(samp_bb,rate,got.rate);
2295 samp_prevSample=0;
2296 sPreview.rate=rateOrig;
2297 sPreview.pos=(sPreview.pBegin>=0)?sPreview.pBegin:0;
2298 sPreview.posSub=0;
2299 sPreview.sample=sample;
2300 sPreview.wave=-1;
2301 sPreview.dir=false;
2302 }
2303
2304 void DivEngine::stopSamplePreviewNoLock() {
2305 sPreview.sample=-1;
2306 sPreview.pos=0;
2307 sPreview.dir=false;
2308 }
2309
2310 void DivEngine::previewWaveNoLock(int wave, int note) {
2311 if (wave<0 || wave>=(int)song.wave.size()) {
2312 sPreview.wave=-1;
2313 sPreview.pos=0;
2314 sPreview.dir=false;
2315 return;
2316 }
2317 if (song.wave[wave]->len<=0) {
2318 return;
2319 }
2320 blip_clear(samp_bb);
2321 double rate=song.wave[wave]->len*((song.tuning*0.0625)*pow(2.0,(double)(note+3)/12.0));
2322 if (rate<100) rate=100;
2323 double rateOrig=rate;
2324 sPreview.rateMul=1;
2325 while (sPreview.rateMul<0x40000000 && rate<got.rate) {
2326 sPreview.rateMul<<=1;
2327 rate*=2.0;
2328 }
2329 blip_set_rates(samp_bb,rate,got.rate);
2330 samp_prevSample=0;
2331 sPreview.rate=rateOrig;
2332 sPreview.pos=0;
2333 sPreview.posSub=0;
2334 sPreview.sample=-1;
2335 sPreview.wave=wave;
2336 sPreview.dir=false;
2337 }
2338
2339 void DivEngine::stopWavePreviewNoLock() {
2340 sPreview.wave=-1;
2341 sPreview.pos=0;
2342 sPreview.dir=false;
2343 }
2344
2345 bool DivEngine::isPreviewingSample() {
2346 return (sPreview.sample>=0 && sPreview.sample<(int)song.sample.size() && sPreview.pos!=sPreview.pEnd);
2347 }
2348
2349 int DivEngine::getSamplePreviewSample() {
2350 return sPreview.sample;
2351 }
2352
2353 int DivEngine::getSamplePreviewPos() {
2354 return sPreview.pos;
2355 }
2356
2357 double DivEngine::getSamplePreviewRate() {
2358 return sPreview.rate;
2359 }
2360
2361 double DivEngine::getCenterRate() {
2362 return song.oldCenterRate?8363.0:8372.0;
2363 }
2364
2365 String DivEngine::getConfigPath() {
2366 return configPath;
2367 }
2368
2369 int DivEngine::getMaxVolumeChan(int ch) {
2370 return chan[ch].volMax>>8;
2371 }
2372
2373 int DivEngine::mapVelocity(int ch, float vel) {
2374 if (ch<0) return 0;
2375 if (ch>=chans) return 0;
2376 if (disCont[dispatchOfChan[ch]].dispatch==NULL) return 0;
2377 return disCont[dispatchOfChan[ch]].dispatch->mapVelocity(dispatchChanOfChan[ch],vel);
2378 }
2379
2380 float DivEngine::getGain(int ch, int vol) {
2381 if (ch<0) return 0;
2382 if (ch>=chans) return 0;
2383 if (disCont[dispatchOfChan[ch]].dispatch==NULL) return 0;
2384 return disCont[dispatchOfChan[ch]].dispatch->getGain(dispatchChanOfChan[ch],vol);
2385 }
2386
2387 unsigned char DivEngine::getOrder() {
2388 return prevOrder;
2389 }
2390
2391 int DivEngine::getRow() {
2392 return prevRow;
2393 }
2394
2395 void DivEngine::getPlayPos(int& order, int& row) {
2396 playPosLock.lock();
2397 order=prevOrder;
2398 row=prevRow;
2399 playPosLock.unlock();
2400 }
2401
2402 void DivEngine::getPlayPosTick(int& order, int& row, int& tick, int& speed) {
2403 playPosLock.lock();
2404 order=prevOrder;
2405 row=prevRow;
2406 tick=ticks;
2407 speed=prevSpeed;
2408 playPosLock.unlock();
2409 }
2410
2411 int DivEngine::getElapsedBars() {
2412 return elapsedBars;
2413 }
2414
2415 int DivEngine::getElapsedBeats() {
2416 return elapsedBeats;
2417 }
2418
2419 size_t DivEngine::getCurrentSubSong() {
2420 return curSubSongIndex;
2421 }
2422
2423 const DivGroovePattern& DivEngine::getSpeeds() {
2424 return speeds;
2425 }
2426
2427 float DivEngine::getHz() {
2428 return curSubSong->hz;
2429 }
2430
2431 float DivEngine::getCurHz() {
2432 return divider;
2433 }
2434
2435 short DivEngine::getVirtualTempoN() {
2436 return virtualTempoN;
2437 }
2438
2439 short DivEngine::getVirtualTempoD() {
2440 return virtualTempoD;
2441 }
2442
2443 void DivEngine::virtualTempoChanged() {
2444 BUSY_BEGIN;
2445 virtualTempoN=curSubSong->virtualTempoN;
2446 virtualTempoD=curSubSong->virtualTempoD;
2447 BUSY_END;
2448 }
2449
2450 int DivEngine::getTotalSeconds() {
2451 return totalSeconds;
2452 }
2453
2454 int DivEngine::getTotalTicks() {
2455 return totalTicks;
2456 }
2457
2458 bool DivEngine::getRepeatPattern() {
2459 return repeatPattern;
2460 }
2461
2462 void DivEngine::setRepeatPattern(bool value) {
2463 BUSY_BEGIN;
2464 repeatPattern=value;
2465 BUSY_END;
2466 }
2467
2468 bool DivEngine::hasExtValue() {
2469 return extValuePresent;
2470 }
2471
2472 unsigned char DivEngine::getExtValue() {
2473 return extValue;
2474 }
2475
2476 bool DivEngine::isPlaying() {
2477 return (playing && !freelance);
2478 }
2479
2480 bool DivEngine::isRunning() {
2481 return playing;
2482 }
2483
2484 bool DivEngine::isStepping() {
2485 return !(stepPlay==0);
2486 }
2487
2488 bool DivEngine::isChannelMuted(int chan) {
2489 return isMuted[chan];
2490 }
2491
2492 void DivEngine::toggleMute(int chan) {
2493 muteChannel(chan,!isMuted[chan]);
2494 }
2495
2496 void DivEngine::toggleSolo(int chan) {
2497 bool solo=false;
2498 for (int i=0; i<chans; i++) {
2499 if (i==chan) {
2500 solo=true;
2501 continue;
2502 } else {
2503 if (!isMuted[i]) {
2504 solo=false;
2505 break;
2506 }
2507 }
2508 }
2509 BUSY_BEGIN;
2510 if (!solo) {
2511 for (int i=0; i<chans; i++) {
2512 isMuted[i]=(i!=chan);
2513 if (disCont[dispatchOfChan[i]].dispatch!=NULL) {
2514 disCont[dispatchOfChan[i]].dispatch->muteChannel(dispatchChanOfChan[i],isMuted[i]);
2515 }
2516 }
2517 } else {
2518 for (int i=0; i<chans; i++) {
2519 isMuted[i]=false;
2520 if (disCont[dispatchOfChan[i]].dispatch!=NULL) {
2521 disCont[dispatchOfChan[i]].dispatch->muteChannel(dispatchChanOfChan[i],isMuted[i]);
2522 }
2523 }
2524 }
2525 BUSY_END;
2526 }
2527
2528 void DivEngine::muteChannel(int chan, bool mute) {
2529 BUSY_BEGIN;
2530 isMuted[chan]=mute;
2531 if (disCont[dispatchOfChan[chan]].dispatch!=NULL) {
2532 disCont[dispatchOfChan[chan]].dispatch->muteChannel(dispatchChanOfChan[chan],isMuted[chan]);
2533 }
2534 BUSY_END;
2535 }
2536
2537 void DivEngine::unmuteAll() {
2538 BUSY_BEGIN;
2539 for (int i=0; i<chans; i++) {
2540 isMuted[i]=false;
2541 if (disCont[dispatchOfChan[i]].dispatch!=NULL) {
2542 disCont[dispatchOfChan[i]].dispatch->muteChannel(dispatchChanOfChan[i],isMuted[i]);
2543 }
2544 }
2545 BUSY_END;
2546 }
2547
2548 void DivEngine::dumpSongInfo() {
2549 printf(
2550 "SONG INFORMATION\n"
2551 "- name: %s\n"
2552 "- author: %s\n"
2553 "- album: %s\n"
2554 "- system: %s\n"
2555 "- %d ins, %d waves, %d samples\n"
2556 "<<<\n%s\n>>>\n\n",
2557 song.name.c_str(),
2558 song.author.c_str(),
2559 song.category.c_str(),
2560 song.systemName.c_str(),
2561 song.insLen,
2562 song.waveLen,
2563 song.sampleLen,
2564 song.notes.c_str()
2565 );
2566
2567 printf("SUB-SONGS\n");
2568 int index=0;
2569 for (DivSubSong* i: song.subsong) {
2570 printf(
2571 "=== %d: %s\n"
2572 "<<<\n%s\n>>>\n",
2573 index,
2574 i->name.c_str(),
2575 i->notes.c_str()
2576 );
2577 index++;
2578 }
2579
2580 if (!song.ins.empty()) {
2581 printf("\nINSTRUMENTS\n");
2582 index=0;
2583 for (DivInstrument* i: song.ins) {
2584 printf(
2585 "- %d: %s\n",
2586 index,
2587 i->name.c_str()
2588 );
2589 index++;
2590 }
2591 }
2592
2593 if (!song.sample.empty()) {
2594 printf("\nSAMPLES\n");
2595 index=0;
2596 for (DivSample* i: song.sample) {
2597 printf(
2598 "- %d: %s\n",
2599 index,
2600 i->name.c_str()
2601 );
2602 index++;
2603 }
2604 }
2605 }
2606
2607 int DivEngine::addInstrument(int refChan, DivInstrumentType fallbackType) {
2608 if (song.ins.size()>=256) return -1;
2609 BUSY_BEGIN;
2610 DivInstrument* ins=new DivInstrument;
2611 int insCount=(int)song.ins.size();
2612 DivInstrumentType prefType;
2613 if (refChan>chans) {
2614 refChan=chans-1;
2615 }
2616 if (refChan<0) {
2617 prefType=fallbackType;
2618 } else {
2619 prefType=getPreferInsType(refChan);
2620 }
2621 switch (prefType) {
2622 case DIV_INS_OPLL:
2623 *ins=song.nullInsOPLL;
2624 break;
2625 case DIV_INS_OPL:
2626 *ins=song.nullInsOPL;
2627 break;
2628 case DIV_INS_OPL_DRUMS:
2629 *ins=song.nullInsOPLDrums;
2630 break;
2631 case DIV_INS_ESFM:
2632 *ins=song.nullInsESFM;
2633 break;
2634 default:
2635 break;
2636 }
2637 if (refChan>=0) {
2638 if (sysOfChan[refChan]==DIV_SYSTEM_QSOUND) {
2639 *ins=song.nullInsQSound;
2640 }
2641 }
2642 ins->name=fmt::sprintf(_("Instrument %d"),insCount);
2643 if (prefType!=DIV_INS_NULL) {
2644 ins->type=prefType;
2645 }
2646 saveLock.lock();
2647 song.ins.push_back(ins);
2648 song.insLen=insCount+1;
2649 checkAssetDir(song.insDir,song.ins.size());
2650 saveLock.unlock();
2651 BUSY_END;
2652 return insCount;
2653 }
2654
2655 int DivEngine::addInstrumentPtr(DivInstrument* which) {
2656 if (song.ins.size()>=256) {
2657 delete which;
2658 return -1;
2659 }
2660 BUSY_BEGIN;
2661 saveLock.lock();
2662 song.ins.push_back(which);
2663 song.insLen=song.ins.size();
2664 checkAssetDir(song.insDir,song.ins.size());
2665 checkAssetDir(song.waveDir,song.wave.size());
2666 checkAssetDir(song.sampleDir,song.sample.size());
2667 saveLock.unlock();
2668 BUSY_END;
2669 return song.insLen;
2670 }
2671
2672 void DivEngine::loadTempIns(DivInstrument* which) {
2673 BUSY_BEGIN;
2674 if (tempIns==NULL) {
2675 tempIns=new DivInstrument;
2676 }
2677 *tempIns=*which;
2678 BUSY_END;
2679 }
2680
2681 void DivEngine::delInstrumentUnsafe(int index) {
2682 if (index>=0 && index<(int)song.ins.size()) {
2683 for (int i=0; i<song.systemLen; i++) {
2684 disCont[i].dispatch->notifyInsDeletion(song.ins[index]);
2685 }
2686 delete song.ins[index];
2687 song.ins.erase(song.ins.begin()+index);
2688 song.insLen=song.ins.size();
2689 for (int i=0; i<chans; i++) {
2690 for (size_t j=0; j<song.subsong.size(); j++) {
2691 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
2692 if (song.subsong[j]->pat[i].data[k]==NULL) continue;
2693 for (int l=0; l<song.subsong[j]->patLen; l++) {
2694 if (song.subsong[j]->pat[i].data[k]->data[l][2]>index) {
2695 song.subsong[j]->pat[i].data[k]->data[l][2]--;
2696 }
2697 }
2698 }
2699 }
2700 }
2701 removeAsset(song.insDir,index);
2702 checkAssetDir(song.insDir,song.ins.size());
2703 }
2704 }
2705
2706 void DivEngine::delInstrument(int index) {
2707 BUSY_BEGIN;
2708 saveLock.lock();
2709 delInstrumentUnsafe(index);
2710 saveLock.unlock();
2711 BUSY_END;
2712 }
2713
2714 int DivEngine::addWave() {
2715 if (song.wave.size()>=32768) {
2716 lastError=_("too many wavetables!");
2717 return -1;
2718 }
2719 BUSY_BEGIN;
2720 saveLock.lock();
2721 DivWavetable* wave=new DivWavetable;
2722 int waveCount=(int)song.wave.size();
2723 song.wave.push_back(wave);
2724 song.waveLen=waveCount+1;
2725 checkAssetDir(song.waveDir,song.wave.size());
2726 saveLock.unlock();
2727 BUSY_END;
2728 return waveCount;
2729 }
2730
2731 int DivEngine::addWavePtr(DivWavetable* which) {
2732 if (song.wave.size()>=32768) {
2733 lastError=_("too many wavetables!");
2734 delete which;
2735 return -1;
2736 }
2737 BUSY_BEGIN;
2738 saveLock.lock();
2739 int waveCount=(int)song.wave.size();
2740 song.wave.push_back(which);
2741 song.waveLen=waveCount+1;
2742 checkAssetDir(song.waveDir,song.wave.size());
2743 saveLock.unlock();
2744 BUSY_END;
2745 return song.waveLen;
2746 }
2747
2748 DivWavetable* DivEngine::waveFromFile(const char* path, bool addRaw) {
2749 FILE* f=ps_fopen(path,"rb");
2750 if (f==NULL) {
2751 lastError=fmt::sprintf("%s",strerror(errno));
2752 return NULL;
2753 }
2754 unsigned char* buf;
2755 ssize_t len;
2756 if (fseek(f,0,SEEK_END)!=0) {
2757 fclose(f);
2758 lastError=fmt::sprintf(_("could not seek to end: %s"),strerror(errno));
2759 return NULL;
2760 }
2761 len=ftell(f);
2762 if (len<0) {
2763 fclose(f);
2764 lastError=fmt::sprintf(_("could not determine file size: %s"),strerror(errno));
2765 return NULL;
2766 }
2767 if (len==(SIZE_MAX>>1)) {
2768 fclose(f);
2769 lastError=_("file size is invalid!");
2770 return NULL;
2771 }
2772 if (len==0) {
2773 fclose(f);
2774 lastError=_("file is empty");
2775 return NULL;
2776 }
2777 if (fseek(f,0,SEEK_SET)!=0) {
2778 fclose(f);
2779 lastError=fmt::sprintf(_("could not seek to beginning: %s"),strerror(errno));
2780 return NULL;
2781 }
2782 buf=new unsigned char[len];
2783 if (fread(buf,1,len,f)!=(size_t)len) {
2784 logW("did not read entire wavetable file buffer!");
2785 delete[] buf;
2786 lastError=fmt::sprintf(_("could not read entire file: %s"),strerror(errno));
2787 return NULL;
2788 }
2789 fclose(f);
2790
2791 SafeReader reader=SafeReader(buf,len);
2792
2793 unsigned char magic[16];
2794 bool isFurnaceTable=false;
2795 try {
2796 reader.read(magic,16);
2797 if (memcmp("-Furnace waveta-",magic,16)==0) {
2798 isFurnaceTable=true;
2799 }
2800 } catch (EndOfFileException& e) {
2801 reader.seek(0,SEEK_SET);
2802 }
2803
2804 DivWavetable* wave=new DivWavetable;
2805 try {
2806 if (isFurnaceTable) {
2807 reader.seek(16,SEEK_SET);
2808 short version=reader.readS();
2809 reader.readS(); // reserved
2810 reader.seek(20,SEEK_SET);
2811 if (wave->readWaveData(reader,version)!=DIV_DATA_SUCCESS) {
2812 lastError=_("invalid wavetable header/data!");
2813 delete wave;
2814 delete[] buf;
2815 return NULL;
2816 }
2817 } else {
2818 try {
2819 // read as .dmw
2820 reader.seek(0,SEEK_SET);
2821 int len=reader.readI();
2822 logD("wave length %d",len);
2823 if (len<=0 || len>256) {
2824 throw EndOfFileException(&reader,reader.size());
2825 }
2826 wave->len=len;
2827 wave->max=(unsigned char)reader.readC();
2828 if (wave->max==255) { // new wavetable format
2829 unsigned char waveVersion=reader.readC();
2830 logI("reading modern .dmw...");
2831 logD("wave version %d",waveVersion);
2832 wave->max=(unsigned char)reader.readC();
2833 for (int i=0; i<len; i++) {
2834 wave->data[i]=reader.readI();
2835 }
2836 } else if (reader.size()==(size_t)(len+5)) {
2837 // read as .dmw
2838 logI("reading .dmw...");
2839 if (len>256) len=256;
2840 for (int i=0; i<len; i++) {
2841 wave->data[i]=(unsigned char)reader.readC();
2842 }
2843 } else {
2844 // read as binary
2845 if (addRaw) {
2846 logI("reading binary...");
2847 len=reader.size();
2848 if (len>256) len=256;
2849 reader.seek(0,SEEK_SET);
2850 for (int i=0; i<len; i++) {
2851 wave->data[i]=(unsigned char)reader.readC();
2852 if (wave->max<wave->data[i]) wave->max=wave->data[i];
2853 }
2854 wave->len=len;
2855 } else {
2856 delete wave;
2857 delete[] buf;
2858 return NULL;
2859 }
2860 }
2861 } catch (EndOfFileException& e) {
2862 // read as binary
2863 if (addRaw) {
2864 len=reader.size();
2865 logI("reading binary for being too small...");
2866 if (len>256) len=256;
2867 reader.seek(0,SEEK_SET);
2868 for (int i=0; i<len; i++) {
2869 wave->data[i]=(unsigned char)reader.readC();
2870 if (wave->max<wave->data[i]) wave->max=wave->data[i];
2871 }
2872 wave->len=len;
2873 } else {
2874 delete wave;
2875 delete[] buf;
2876 return NULL;
2877 }
2878 }
2879 }
2880 } catch (EndOfFileException& e) {
2881 delete wave;
2882 delete[] buf;
2883 lastError=_("premature end of file");
2884 return NULL;
2885 }
2886
2887 return wave;
2888 }
2889
2890 void DivEngine::delWaveUnsafe(int index) {
2891 if (index>=0 && index<(int)song.wave.size()) {
2892 delete song.wave[index];
2893 song.wave.erase(song.wave.begin()+index);
2894 song.waveLen=song.wave.size();
2895 removeAsset(song.waveDir,index);
2896 checkAssetDir(song.waveDir,song.wave.size());
2897 }
2898 }
2899
2900 void DivEngine::delWave(int index) {
2901 BUSY_BEGIN;
2902 saveLock.lock();
2903 delWaveUnsafe(index);
2904 saveLock.unlock();
2905 BUSY_END;
2906 }
2907
2908 int DivEngine::addSample() {
2909 if (song.sample.size()>=32768) {
2910 lastError=_("too many samples!");
2911 return -1;
2912 }
2913 BUSY_BEGIN;
2914 saveLock.lock();
2915 DivSample* sample=new DivSample;
2916 int sampleCount=(int)song.sample.size();
2917 sample->name=fmt::sprintf(_("Sample %d"),sampleCount);
2918 sample->centerRate=getCenterRate();
2919 song.sample.push_back(sample);
2920 song.sampleLen=sampleCount+1;
2921 sPreview.sample=-1;
2922 sPreview.pos=0;
2923 sPreview.dir=false;
2924 checkAssetDir(song.sampleDir,song.sample.size());
2925 saveLock.unlock();
2926 renderSamples();
2927 BUSY_END;
2928 return sampleCount;
2929 }
2930
2931 int DivEngine::addSamplePtr(DivSample* which) {
2932 if (song.sample.size()>=32768) {
2933 lastError=_("too many samples!");
2934 delete which;
2935 return -1;
2936 }
2937 int sampleCount=(int)song.sample.size();
2938 BUSY_BEGIN;
2939 saveLock.lock();
2940 song.sample.push_back(which);
2941 song.sampleLen=sampleCount+1;
2942 checkAssetDir(song.sampleDir,song.sample.size());
2943 saveLock.unlock();
2944 renderSamples();
2945 BUSY_END;
2946 return sampleCount;
2947 }
2948
2949 void DivEngine::delSampleUnsafe(int index, bool render) {
2950 sPreview.sample=-1;
2951 sPreview.pos=0;
2952 sPreview.dir=false;
2953 if (index>=0 && index<(int)song.sample.size()) {
2954 delete song.sample[index];
2955 song.sample.erase(song.sample.begin()+index);
2956 song.sampleLen=song.sample.size();
2957 removeAsset(song.sampleDir,index);
2958 checkAssetDir(song.sampleDir,song.sample.size());
2959
2960 // compensate
2961 for (DivInstrument* i: song.ins) {
2962 if (i->amiga.initSample==index) {
2963 i->amiga.initSample=-1;
2964 } else if (i->amiga.initSample>index) {
2965 i->amiga.initSample--;
2966 }
2967 for (int j=0; j<120; j++) {
2968 if (i->amiga.noteMap[j].map==index) {
2969 i->amiga.noteMap[j].map=-1;
2970 } else if (i->amiga.noteMap[j].map>index) {
2971 i->amiga.noteMap[j].map--;
2972 }
2973 }
2974 }
2975
2976 if (render) renderSamples();
2977 }
2978 }
2979
2980 void DivEngine::delSample(int index) {
2981 BUSY_BEGIN;
2982 saveLock.lock();
2983 delSampleUnsafe(index);
2984 saveLock.unlock();
2985 BUSY_END;
2986 }
2987
2988 void DivEngine::addOrder(int pos, bool duplicate, bool where) {
2989 unsigned char order[DIV_MAX_CHANS];
2990 if (curSubSong->ordersLen>=(DIV_MAX_PATTERNS-1)) return;
2991 memset(order,0,DIV_MAX_CHANS);
2992 BUSY_BEGIN_SOFT;
2993 if (duplicate) {
2994 for (int i=0; i<DIV_MAX_CHANS; i++) {
2995 order[i]=curOrders->ord[i][pos];
2996 }
2997 } else {
2998 bool used[DIV_MAX_PATTERNS];
2999 for (int i=0; i<chans; i++) {
3000 memset(used,0,sizeof(bool)*DIV_MAX_PATTERNS);
3001 for (int j=0; j<curSubSong->ordersLen; j++) {
3002 used[curOrders->ord[i][j]]=true;
3003 }
3004 order[i]=(DIV_MAX_PATTERNS-1);
3005 for (int j=0; j<DIV_MAX_PATTERNS; j++) {
3006 if (!used[j]) {
3007 order[i]=j;
3008 break;
3009 }
3010 }
3011 }
3012 }
3013 if (where) { // at the end
3014 saveLock.lock();
3015 for (int i=0; i<DIV_MAX_CHANS; i++) {
3016 curOrders->ord[i][curSubSong->ordersLen]=order[i];
3017 }
3018 curSubSong->ordersLen++;
3019 saveLock.unlock();
3020 } else { // after current order
3021 saveLock.lock();
3022 for (int i=0; i<DIV_MAX_CHANS; i++) {
3023 for (int j=curSubSong->ordersLen; j>pos; j--) {
3024 curOrders->ord[i][j]=curOrders->ord[i][j-1];
3025 }
3026 curOrders->ord[i][pos+1]=order[i];
3027 }
3028 curSubSong->ordersLen++;
3029 saveLock.unlock();
3030 curOrder=pos+1;
3031 prevOrder=curOrder;
3032 if (playing && !freelance) {
3033 playSub(false);
3034 }
3035 }
3036 BUSY_END;
3037 }
3038
3039 void DivEngine::deepCloneOrder(int pos, bool where) {
3040 unsigned char order[DIV_MAX_CHANS];
3041 if (curSubSong->ordersLen>=(DIV_MAX_PATTERNS-1)) return;
3042 warnings="";
3043 BUSY_BEGIN_SOFT;
3044 for (int i=0; i<chans; i++) {
3045 bool didNotFind=true;
3046 logD("channel %d",i);
3047 order[i]=curOrders->ord[i][pos];
3048 // find free slot
3049 for (int j=0; j<DIV_MAX_PATTERNS; j++) {
3050 logD("finding free slot in %d...",j);
3051 if (curPat[i].data[j]==NULL) {
3052 int origOrd=order[i];
3053 order[i]=j;
3054 DivPattern* oldPat=curPat[i].getPattern(origOrd,false);
3055 DivPattern* pat=curPat[i].getPattern(j,true);
3056 memcpy(pat->data,oldPat->data,DIV_MAX_ROWS*DIV_MAX_COLS*sizeof(short));
3057 logD("found at %d",j);
3058 didNotFind=false;
3059 break;
3060 }
3061 }
3062 if (didNotFind) {
3063 addWarning(fmt::sprintf(_("no free patterns in channel %d!"),i));
3064 }
3065 }
3066 if (where) { // at the end
3067 saveLock.lock();
3068 for (int i=0; i<chans; i++) {
3069 curOrders->ord[i][curSubSong->ordersLen]=order[i];
3070 }
3071 curSubSong->ordersLen++;
3072 saveLock.unlock();
3073 } else { // after current order
3074 saveLock.lock();
3075 for (int i=0; i<chans; i++) {
3076 for (int j=curSubSong->ordersLen; j>pos; j--) {
3077 curOrders->ord[i][j]=curOrders->ord[i][j-1];
3078 }
3079 curOrders->ord[i][pos+1]=order[i];
3080 }
3081 curSubSong->ordersLen++;
3082 saveLock.unlock();
3083 if (pos<=curOrder) curOrder++;
3084 if (playing && !freelance) {
3085 playSub(false);
3086 }
3087 }
3088 BUSY_END;
3089 }
3090
3091 void DivEngine::deleteOrder(int pos) {
3092 if (curSubSong->ordersLen<=1) return;
3093 BUSY_BEGIN_SOFT;
3094 saveLock.lock();
3095 for (int i=0; i<DIV_MAX_CHANS; i++) {
3096 for (int j=pos; j<curSubSong->ordersLen; j++) {
3097 curOrders->ord[i][j]=curOrders->ord[i][j+1];
3098 }
3099 }
3100 curSubSong->ordersLen--;
3101 saveLock.unlock();
3102 if (curOrder>pos) curOrder--;
3103 if (curOrder>=curSubSong->ordersLen) curOrder=curSubSong->ordersLen-1;
3104 if (playing && !freelance) {
3105 playSub(false);
3106 }
3107 BUSY_END;
3108 }
3109
3110 void DivEngine::moveOrderUp(int& pos) {
3111 BUSY_BEGIN_SOFT;
3112 if (pos<1) {
3113 BUSY_END;
3114 return;
3115 }
3116 saveLock.lock();
3117 for (int i=0; i<DIV_MAX_CHANS; i++) {
3118 curOrders->ord[i][pos]^=curOrders->ord[i][pos-1];
3119 curOrders->ord[i][pos-1]^=curOrders->ord[i][pos];
3120 curOrders->ord[i][pos]^=curOrders->ord[i][pos-1];
3121 }
3122 saveLock.unlock();
3123 if (curOrder==pos) {
3124 curOrder--;
3125 }
3126 pos--;
3127 if (playing && !freelance) {
3128 playSub(false);
3129 }
3130 BUSY_END;
3131 }
3132
3133 void DivEngine::moveOrderDown(int& pos) {
3134 BUSY_BEGIN_SOFT;
3135 if (pos>=curSubSong->ordersLen-1) {
3136 BUSY_END;
3137 return;
3138 }
3139 saveLock.lock();
3140 for (int i=0; i<DIV_MAX_CHANS; i++) {
3141 curOrders->ord[i][pos]^=curOrders->ord[i][pos+1];
3142 curOrders->ord[i][pos+1]^=curOrders->ord[i][pos];
3143 curOrders->ord[i][pos]^=curOrders->ord[i][pos+1];
3144 }
3145 saveLock.unlock();
3146 if (curOrder==pos) {
3147 curOrder++;
3148 }
3149 pos++;
3150 if (playing && !freelance) {
3151 playSub(false);
3152 }
3153 BUSY_END;
3154 }
3155
3156 void DivEngine::exchangeIns(int one, int two) {
3157 for (int i=0; i<chans; i++) {
3158 for (size_t j=0; j<song.subsong.size(); j++) {
3159 for (int k=0; k<DIV_MAX_PATTERNS; k++) {
3160 if (song.subsong[j]->pat[i].data[k]==NULL) continue;
3161 for (int l=0; l<song.subsong[j]->patLen; l++) {
3162 if (song.subsong[j]->pat[i].data[k]->data[l][2]==one) {
3163 song.subsong[j]->pat[i].data[k]->data[l][2]=two;
3164 } else if (song.subsong[j]->pat[i].data[k]->data[l][2]==two) {
3165 song.subsong[j]->pat[i].data[k]->data[l][2]=one;
3166 }
3167 }
3168 }
3169 }
3170 }
3171 }
3172
3173 void DivEngine::exchangeWave(int one, int two) {
3174 // TODO
3175 }
3176
3177 void DivEngine::exchangeSample(int one, int two) {
3178 for (DivInstrument* i: song.ins) {
3179 if (i->amiga.initSample==one) {
3180 i->amiga.initSample=two;
3181 } else if (i->amiga.initSample==two) {
3182 i->amiga.initSample=one;
3183 }
3184 for (int j=0; j<120; j++) {
3185 if (i->amiga.noteMap[j].map==one) {
3186 i->amiga.noteMap[j].map=two;
3187 } else if (i->amiga.noteMap[j].map==two) {
3188 i->amiga.noteMap[j].map=one;
3189 }
3190 }
3191 }
3192 }
3193
3194 bool DivEngine::moveInsUp(int which) {
3195 if (which<1 || which>=(int)song.ins.size()) return false;
3196 BUSY_BEGIN;
3197 DivInstrument* prev=song.ins[which];
3198 saveLock.lock();
3199 song.ins[which]=song.ins[which-1];
3200 song.ins[which-1]=prev;
3201 moveAsset(song.insDir,which,which-1);
3202 exchangeIns(which,which-1);
3203 saveLock.unlock();
3204 BUSY_END;
3205 return true;
3206 }
3207
3208 bool DivEngine::moveWaveUp(int which) {
3209 if (which<1 || which>=(int)song.wave.size()) return false;
3210 BUSY_BEGIN;
3211 DivWavetable* prev=song.wave[which];
3212 saveLock.lock();
3213 song.wave[which]=song.wave[which-1];
3214 song.wave[which-1]=prev;
3215 moveAsset(song.waveDir,which,which-1);
3216 exchangeWave(which,which-1);
3217 saveLock.unlock();
3218 BUSY_END;
3219 return true;
3220 }
3221
3222 bool DivEngine::moveSampleUp(int which) {
3223 if (which<1 || which>=(int)song.sample.size()) return false;
3224 BUSY_BEGIN;
3225 sPreview.sample=-1;
3226 sPreview.pos=0;
3227 sPreview.dir=false;
3228 DivSample* prev=song.sample[which];
3229 saveLock.lock();
3230 song.sample[which]=song.sample[which-1];
3231 song.sample[which-1]=prev;
3232 moveAsset(song.sampleDir,which,which-1);
3233 exchangeSample(which,which-1);
3234 saveLock.unlock();
3235 renderSamples();
3236 BUSY_END;
3237 return true;
3238 }
3239
3240 bool DivEngine::moveInsDown(int which) {
3241 if (which<0 || which>=((int)song.ins.size())-1) return false;
3242 BUSY_BEGIN;
3243 DivInstrument* prev=song.ins[which];
3244 saveLock.lock();
3245 song.ins[which]=song.ins[which+1];
3246 song.ins[which+1]=prev;
3247 exchangeIns(which,which+1);
3248 moveAsset(song.insDir,which,which+1);
3249 saveLock.unlock();
3250 BUSY_END;
3251 return true;
3252 }
3253
3254 bool DivEngine::moveWaveDown(int which) {
3255 if (which<0 || which>=((int)song.wave.size())-1) return false;
3256 BUSY_BEGIN;
3257 DivWavetable* prev=song.wave[which];
3258 saveLock.lock();
3259 song.wave[which]=song.wave[which+1];
3260 song.wave[which+1]=prev;
3261 exchangeWave(which,which+1);
3262 moveAsset(song.waveDir,which,which+1);
3263 saveLock.unlock();
3264 BUSY_END;
3265 return true;
3266 }
3267
3268 bool DivEngine::moveSampleDown(int which) {
3269 if (which<0 || which>=((int)song.sample.size())-1) return false;
3270 BUSY_BEGIN;
3271 sPreview.sample=-1;
3272 sPreview.pos=0;
3273 sPreview.dir=false;
3274 DivSample* prev=song.sample[which];
3275 saveLock.lock();
3276 song.sample[which]=song.sample[which+1];
3277 song.sample[which+1]=prev;
3278 exchangeSample(which,which+1);
3279 moveAsset(song.sampleDir,which,which+1);
3280 saveLock.unlock();
3281 renderSamples();
3282 BUSY_END;
3283 return true;
3284 }
3285
3286 bool DivEngine::swapInstruments(int a, int b) {
3287 if (a<0 || a>=(int)song.ins.size() || b<0 || b>=(int)song.ins.size()) return false;
3288 BUSY_BEGIN;
3289 DivInstrument* temp=song.ins[a];
3290 saveLock.lock();
3291 song.ins[a]=song.ins[b];
3292 song.ins[b]=temp;
3293 moveAsset(song.insDir,a,b);
3294 exchangeIns(a,b);
3295 saveLock.unlock();
3296 BUSY_END;
3297 return true;
3298 }
3299
3300 bool DivEngine::swapWaves(int a, int b) {
3301 if (a<0 || a>=(int)song.wave.size() || b<0 || b>=(int)song.wave.size()) return false;
3302 BUSY_BEGIN;
3303 DivWavetable* temp=song.wave[a];
3304 saveLock.lock();
3305 song.wave[a]=song.wave[b];
3306 song.wave[b]=temp;
3307 exchangeWave(a,b);
3308 moveAsset(song.waveDir,a,b);
3309 saveLock.unlock();
3310 BUSY_END;
3311 return true;
3312 }
3313
3314 bool DivEngine::swapSamples(int a, int b) {
3315 if (a<0 || a>=(int)song.sample.size() || b<0 || b>=(int)song.sample.size()) return false;
3316 BUSY_BEGIN;
3317 sPreview.sample=-1;
3318 sPreview.pos=0;
3319 sPreview.dir=false;
3320 DivSample* temp=song.sample[a];
3321 saveLock.lock();
3322 song.sample[a]=song.sample[b];
3323 song.sample[b]=temp;
3324 exchangeSample(a,b);
3325 moveAsset(song.sampleDir,a,b);
3326 saveLock.unlock();
3327 renderSamples();
3328 BUSY_END;
3329 return true;
3330 }
3331
3332
3333 void DivEngine::autoPatchbay() {
3334 song.patchbay.clear();
3335 for (unsigned int i=0; i<song.systemLen; i++) {
3336 if (disCont[i].dispatch==NULL) continue;
3337
3338 unsigned int outs=disCont[i].dispatch->getOutputCount();
3339 if (outs>16) outs=16;
3340 if (outs<2) {
3341 song.patchbay.reserve(DIV_MAX_OUTPUTS);
3342 for (unsigned int j=0; j<DIV_MAX_OUTPUTS; j++) {
3343 song.patchbay.push_back((i<<20)|j);
3344 }
3345 } else {
3346 song.patchbay.reserve(outs);
3347 for (unsigned int j=0; j<outs; j++) {
3348 song.patchbay.push_back((i<<20)|(j<<16)|j);
3349 }
3350 }
3351 }
3352
3353 // wave/sample preview
3354 song.patchbay.reserve(DIV_MAX_OUTPUTS);
3355 for (unsigned int j=0; j<DIV_MAX_OUTPUTS; j++) {
3356 song.patchbay.push_back(0xffd00000|j);
3357 }
3358
3359 // metronome
3360 song.patchbay.reserve(DIV_MAX_OUTPUTS);
3361 for (unsigned int j=0; j<DIV_MAX_OUTPUTS; j++) {
3362 song.patchbay.push_back(0xffe00000|j);
3363 }
3364 }
3365
3366 void DivEngine::autoPatchbayP() {
3367 BUSY_BEGIN;
3368 saveLock.lock();
3369 autoPatchbay();
3370 saveLock.unlock();
3371 BUSY_END;
3372 }
3373
3374 void DivEngine::recalcPatchbay() {
3375
3376 }
3377
3378 bool DivEngine::patchConnect(unsigned int src, unsigned int dest) {
3379 unsigned int armed=(src<<16)|(dest&0xffff);
3380 for (unsigned int i: song.patchbay) {
3381 if (i==armed) return false;
3382 }
3383 BUSY_BEGIN;
3384 saveLock.lock();
3385 song.patchbay.push_back(armed);
3386 song.patchbayAuto=false;
3387 saveLock.unlock();
3388 BUSY_END;
3389 return true;
3390 }
3391
3392 bool DivEngine::patchDisconnect(unsigned int src, unsigned int dest) {
3393 unsigned int armed=(src<<16)|(dest&0xffff);
3394 for (auto i=song.patchbay.begin(); i!=song.patchbay.end(); i++) {
3395 if (*i==armed) {
3396 BUSY_BEGIN;
3397 saveLock.lock();
3398 song.patchbay.erase(i);
3399 song.patchbayAuto=false;
3400 saveLock.unlock();
3401 BUSY_END;
3402 return true;
3403 }
3404 }
3405 return false;
3406 }
3407
3408 void DivEngine::patchDisconnectAll(unsigned int portSet) {
3409 BUSY_BEGIN;
3410 saveLock.lock();
3411
3412 if (portSet&0x1000) {
3413 portSet&=0xfff;
3414
3415 for (size_t i=0; i<song.patchbay.size(); i++) {
3416 if ((song.patchbay[i]&0xfff0)==(portSet<<4)) {
3417 song.patchbay.erase(song.patchbay.begin()+i);
3418 i--;
3419 }
3420 }
3421 } else {
3422 portSet&=0xfff;
3423
3424 for (size_t i=0; i<song.patchbay.size(); i++) {
3425 if ((song.patchbay[i]&0xfff00000)==(portSet<<20)) {
3426 song.patchbay.erase(song.patchbay.begin()+i);
3427 i--;
3428 }
3429 }
3430 }
3431
3432 saveLock.unlock();
3433 BUSY_END;
3434 }
3435
3436 void DivEngine::noteOn(int chan, int ins, int note, int vol) {
3437 if (chan<0 || chan>=chans) return;
3438 BUSY_BEGIN;
3439 pendingNotes.push_back(DivNoteEvent(chan,ins,note,vol,true));
3440 if (!playing) {
3441 reset();
3442 freelance=true;
3443 playing=true;
3444 }
3445 BUSY_END;
3446 }
3447
3448 void DivEngine::noteOff(int chan) {
3449 if (chan<0 || chan>=chans) return;
3450 BUSY_BEGIN;
3451 pendingNotes.push_back(DivNoteEvent(chan,-1,-1,-1,false));
3452 if (!playing) {
3453 reset();
3454 freelance=true;
3455 playing=true;
3456 }
3457 BUSY_END;
3458 }
3459
3460 bool DivEngine::autoNoteOn(int ch, int ins, int note, int vol) {
3461 bool isViable[DIV_MAX_CHANS];
3462 bool canPlayAnyway=false;
3463 bool notInViableChannel=false;
3464 if (midiBaseChan<0) midiBaseChan=0;
3465 if (midiBaseChan>=chans) midiBaseChan=chans-1;
3466 int finalChan=midiBaseChan;
3467 int finalChanType=getChannelType(finalChan);
3468
3469 if (!playing) {
3470 reset();
3471 freelance=true;
3472 playing=true;
3473 }
3474
3475 // 1. check which channels are viable for this instrument
3476 DivInstrument* insInst=getIns(ins);
3477 if (getPreferInsType(finalChan)!=insInst->type && getPreferInsSecondType(finalChan)!=insInst->type && getPreferInsType(finalChan)!=DIV_INS_NULL) notInViableChannel=true;
3478 for (int i=0; i<chans; i++) {
3479 if (ins==-1 || ins>=song.insLen || getPreferInsType(i)==insInst->type || (getPreferInsType(i)==DIV_INS_NULL && finalChanType==DIV_CH_NOISE) || getPreferInsSecondType(i)==insInst->type) {
3480 if (insInst->type==DIV_INS_OPL) {
3481 if (insInst->fm.ops==2 || getChannelType(i)==DIV_CH_OP) {
3482 isViable[i]=true;
3483 canPlayAnyway=true;
3484 } else {
3485 isViable[i]=false;
3486 }
3487 } else {
3488 isViable[i]=true;
3489 canPlayAnyway=true;
3490 }
3491 } else {
3492 isViable[i]=false;
3493 }
3494 }
3495
3496 if (!canPlayAnyway) return false;
3497
3498 // 2. find a free channel
3499 do {
3500 if ((!midiPoly) || (isViable[finalChan] && chan[finalChan].midiNote==-1 && (insInst->type==DIV_INS_OPL || getChannelType(finalChan)==finalChanType || notInViableChannel))) {
3501 chan[finalChan].midiNote=note;
3502 chan[finalChan].midiAge=midiAgeCounter++;
3503 pendingNotes.push_back(DivNoteEvent(finalChan,ins,note,vol,true));
3504 return true;
3505 }
3506 if (++finalChan>=chans) {
3507 finalChan=0;
3508 }
3509 } while (finalChan!=midiBaseChan);
3510
3511 // 3. find the oldest channel
3512 int candidate=finalChan;
3513 do {
3514 if (isViable[finalChan] && (insInst->type==DIV_INS_OPL || getChannelType(finalChan)==finalChanType || notInViableChannel) && chan[finalChan].midiAge<chan[candidate].midiAge) {
3515 candidate=finalChan;
3516 }
3517 if (++finalChan>=chans) {
3518 finalChan=0;
3519 }
3520 } while (finalChan!=midiBaseChan);
3521
3522 chan[candidate].midiNote=note;
3523 chan[candidate].midiAge=midiAgeCounter++;
3524 pendingNotes.push_back(DivNoteEvent(candidate,ins,note,vol,true));
3525 return true;
3526 }
3527
3528 void DivEngine::autoNoteOff(int ch, int note, int vol) {
3529 if (!playing) {
3530 return;
3531 }
3532 //if (ch<0 || ch>=chans) return;
3533 for (int i=0; i<chans; i++) {
3534 if (chan[i].midiNote==note) {
3535 pendingNotes.push_back(DivNoteEvent(i,-1,-1,-1,false));
3536 chan[i].midiNote=-1;
3537 }
3538 }
3539 }
3540
3541 void DivEngine::autoNoteOffAll() {
3542 if (!playing) {
3543 return;
3544 }
3545 for (int i=0; i<chans; i++) {
3546 if (chan[i].midiNote!=-1) {
3547 pendingNotes.push_back(DivNoteEvent(i,-1,-1,-1,false));
3548 chan[i].midiNote=-1;
3549 }
3550 }
3551 }
3552
3553 void DivEngine::setAutoNotePoly(bool poly) {
3554 midiPoly=poly;
3555 }
3556
3557 void DivEngine::setOrder(unsigned char order) {
3558 BUSY_BEGIN_SOFT;
3559 curOrder=order;
3560 if (order>=curSubSong->ordersLen) curOrder=0;
3561 prevOrder=curOrder;
3562 if (playing && !freelance) {
3563 playSub(false);
3564 }
3565 BUSY_END;
3566 }
3567
3568 void DivEngine::updateSysFlags(int system, bool restart, bool render) {
3569 BUSY_BEGIN_SOFT;
3570 disCont[system].dispatch->setFlags(song.systemFlags[system]);
3571 disCont[system].setRates(got.rate);
3572 if (render) renderSamples();
3573
3574 // patchbay
3575 if (song.patchbayAuto) {
3576 saveLock.lock();
3577 autoPatchbay();
3578 saveLock.unlock();
3579 }
3580
3581 if (restart) {
3582 if (isPlaying()) {
3583 playSub(false);
3584 } else if (freelance) {
3585 reset();
3586 }
3587 }
3588 BUSY_END;
3589 }
3590
3591 void DivEngine::setSongRate(float hz) {
3592 BUSY_BEGIN;
3593 saveLock.lock();
3594 curSubSong->hz=hz;
3595 divider=curSubSong->hz;
3596 saveLock.unlock();
3597 BUSY_END;
3598 }
3599
3600 void DivEngine::setAudio(DivAudioEngines which) {
3601 audioEngine=which;
3602 }
3603
3604 void DivEngine::setView(DivStatusView which) {
3605 view=which;
3606 }
3607
3608 bool DivEngine::getMetronome() {
3609 return metronome;
3610 }
3611
3612 void DivEngine::setMetronome(bool enable) {
3613 metronome=enable;
3614 metroAmp=0;
3615 }
3616
3617 void DivEngine::setMetronomeVol(float vol) {
3618 metroVol=vol;
3619 }
3620
3621 void DivEngine::setSamplePreviewVol(float vol) {
3622 previewVol=vol;
3623 }
3624
3625 void DivEngine::setConsoleMode(bool enable, bool statusOut) {
3626 consoleMode=enable;
3627 disableStatusOut=!statusOut;
3628 }
3629
3630 bool DivEngine::switchMaster(bool full) {
3631 logI("switching output...");
3632 deinitAudioBackend(true);
3633 if (full) {
3634 quitDispatch();
3635 initDispatch();
3636 }
3637 if (renderPool!=NULL) {
3638 delete renderPool;
3639 renderPool=NULL;
3640 }
3641 if (initAudioBackend()) {
3642 for (int i=0; i<song.systemLen; i++) {
3643 disCont[i].setRates(got.rate);
3644 disCont[i].setQuality(lowQuality,dcHiPass);
3645 }
3646 if (!output->setRun(true)) {
3647 logE("error while activating audio!");
3648 return false;
3649 }
3650 } else {
3651 return false;
3652 }
3653 renderSamples();
3654 return true;
3655 }
3656
3657 void DivEngine::setMidiBaseChan(int chan) {
3658 if (chan<0 || chan>=chans) chan=0;
3659 midiBaseChan=chan;
3660 }
3661
3662 void DivEngine::setMidiDirect(bool value) {
3663 midiIsDirect=value;
3664 }
3665
3666 void DivEngine::setMidiDirectProgram(bool value) {
3667 midiIsDirectProgram=value;
3668 }
3669
3670 void DivEngine::setMidiVolExp(float value) {
3671 midiVolExp=value;
3672 }
3673
3674 void DivEngine::setMidiCallback(std::function<int(const TAMidiMessage&)> what) {
3675 midiCallback=what;
3676 }
3677
3678 void DivEngine::setMidiDebug(bool enable) {
3679 midiDebug=enable;
3680 }
3681
3682 bool DivEngine::sendMidiMessage(TAMidiMessage& msg) {
3683 if (output==NULL) {
3684 logW("output is NULL!");
3685 return false;
3686 }
3687 if (output->midiOut==NULL) {
3688 logW("MIDI output is NULL!");
3689 return false;
3690 }
3691 BUSY_BEGIN;
3692 logD("sending MIDI message...");
3693 bool ret=(output->midiOut->send(msg));
3694 BUSY_END;
3695 return ret;
3696 }
3697
3698 void DivEngine::synchronized(const std::function<void()>& what) {
3699 BUSY_BEGIN;
3700 what();
3701 BUSY_END;
3702 }
3703
3704 void DivEngine::synchronizedSoft(const std::function<void()>& what) {
3705 BUSY_BEGIN_SOFT;
3706 what();
3707 BUSY_END;
3708 }
3709
3710 void DivEngine::lockSave(const std::function<void()>& what) {
3711 saveLock.lock();
3712 what();
3713 saveLock.unlock();
3714 }
3715
3716 void DivEngine::lockEngine(const std::function<void()>& what) {
3717 BUSY_BEGIN;
3718 saveLock.lock();
3719 what();
3720 saveLock.unlock();
3721 BUSY_END;
3722 }
3723
3724 TAAudioDesc& DivEngine::getAudioDescWant() {
3725 return want;
3726 }
3727
3728 TAAudioDesc& DivEngine::getAudioDescGot() {
3729 return got;
3730 }
3731
3732 std::vector<String>& DivEngine::getAudioDevices() {
3733 return audioDevs;
3734 }
3735
3736 std::vector<String>& DivEngine::getMidiIns() {
3737 return midiIns;
3738 }
3739
3740 std::vector<String>& DivEngine::getMidiOuts() {
3741 return midiOuts;
3742 }
3743
3744 void DivEngine::rescanAudioDevices() {
3745 audioDevs.clear();
3746 if (output!=NULL) {
3747 audioDevs=output->listAudioDevices();
3748 }
3749 }
3750
3751 void DivEngine::rescanMidiDevices() {
3752 if (output!=NULL) {
3753 logV("re-scanning midi...");
3754 if (output->midiIn!=NULL) {
3755 midiIns=output->midiIn->listDevices();
3756 }
3757 if (output->midiOut!=NULL) {
3758 midiOuts=output->midiOut->listDevices();
3759 }
3760 }
3761 }
3762
3763 void DivEngine::initDispatch(bool isRender) {
3764 BUSY_BEGIN;
3765 logV("initializing dispatch...");
3766 if (isRender) logI("render cores set");
3767
3768 lowQuality=getConfInt("audioQuality",0);
3769 dcHiPass=getConfInt("audioHiPass",1);
3770
3771 if (lowQuality) {
3772 blip_add_delta=blip_add_delta_fast;
3773 } else {
3774 blip_add_delta=blip_add_delta_slow;
3775 }
3776
3777 for (int i=0; i<song.systemLen; i++) {
3778 disCont[i].init(song.system[i],this,getChannelCount(song.system[i]),got.rate,song.systemFlags[i],isRender);
3779 disCont[i].setRates(got.rate);
3780 disCont[i].setQuality(lowQuality,dcHiPass);
3781 }
3782 if (song.patchbayAuto) {
3783 saveLock.lock();
3784 autoPatchbay();
3785 saveLock.unlock();
3786 }
3787 recalcChans();
3788 BUSY_END;
3789 }
3790
3791 void DivEngine::quitDispatch() {
3792 BUSY_BEGIN;
3793 logV("terminating dispatch...");
3794 for (int i=0; i<song.systemLen; i++) {
3795 disCont[i].quit();
3796 }
3797 cycles=0;
3798 clockDrift=0;
3799 midiClockCycles=0;
3800 midiClockDrift=0;
3801 midiTimeCycles=0;
3802 midiTimeDrift=0;
3803 chans=0;
3804 playing=false;
3805 curSpeed=0;
3806 endOfSong=false;
3807 stepPlay=0;
3808 ticks=0;
3809 tempoAccum=0;
3810 curRow=0;
3811 curOrder=0;
3812 prevRow=0;
3813 prevOrder=0;
3814 nextSpeed=3;
3815 changeOrd=-1;
3816 changePos=0;
3817 totalTicks=0;
3818 totalTicksOff=0;
3819 totalSeconds=0;
3820 totalTicksR=0;
3821 curMidiClock=0;
3822 curMidiTime=0;
3823 curMidiTimeCode=0;
3824 curMidiTimePiece=0;
3825 totalCmds=0;
3826 lastCmds=0;
3827 cmdsPerSecond=0;
3828 for (int i=0; i<DIV_MAX_CHANS; i++) {
3829 isMuted[i]=0;
3830 }
3831 if (renderPool!=NULL) {
3832 delete renderPool;
3833 renderPool=NULL;
3834 }
3835 BUSY_END;
3836 }
3837
3838 bool DivEngine::initAudioBackend() {
3839 // load values
3840 logI("initializing audio.");
3841 if (audioEngine==DIV_AUDIO_NULL) {
3842 if (getConfString("audioEngine","SDL")=="JACK") {
3843 audioEngine=DIV_AUDIO_JACK;
3844 } else if (getConfString("audioEngine","SDL")=="PortAudio") {
3845 audioEngine=DIV_AUDIO_PORTAUDIO;
3846 } else {
3847 audioEngine=DIV_AUDIO_SDL;
3848 }
3849 }
3850
3851 #ifdef HAVE_SDL2
3852 if (audioEngine==DIV_AUDIO_SDL) {
3853 String audioDriver=getConfString("sdlAudioDriver","");
3854 if (!audioDriver.empty()) {
3855 SDL_SetHint(SDL_HINT_AUDIODRIVER,audioDriver.c_str());
3856 }
3857 }
3858 #endif
3859
3860 forceMono=getConfInt("forceMono",0);
3861 clampSamples=getConfInt("clampSamples",0);
3862 lowLatency=getConfInt("lowLatency",0);
3863 metroVol=(float)(getConfInt("metroVol",100))/100.0f;
3864 previewVol=(float)(getConfInt("sampleVol",50))/100.0f;
3865 midiOutClock=getConfInt("midiOutClock",0);
3866 midiOutTime=getConfInt("midiOutTime",0);
3867 midiOutTimeRate=getConfInt("midiOutTimeRate",0);
3868 midiOutProgramChange=getConfInt("midiOutProgramChange",0);
3869 midiOutMode=getConfInt("midiOutMode",DIV_MIDI_MODE_NOTE);
3870 if (metroVol<0.0f) metroVol=0.0f;
3871 if (metroVol>2.0f) metroVol=2.0f;
3872 if (previewVol<0.0f) previewVol=0.0f;
3873 if (previewVol>1.0f) previewVol=1.0f;
3874 renderPoolThreads=getConfInt("renderPoolThreads",0);
3875
3876 if (lowLatency) logI("using low latency mode.");
3877
3878 switch (audioEngine) {
3879 case DIV_AUDIO_JACK:
3880 #ifndef HAVE_JACK
3881 logE("Furnace was not compiled with JACK support!");
3882 setConf("audioEngine","SDL");
3883 saveConf();
3884 #ifdef HAVE_SDL2
3885 output=new TAAudioSDL;
3886 #else
3887 logE("Furnace was not compiled with SDL support either!");
3888 output=new TAAudio;
3889 #endif
3890 #else
3891 output=new TAAudioJACK;
3892 #endif
3893 break;
3894 case DIV_AUDIO_PORTAUDIO:
3895 #ifndef HAVE_PA
3896 logE("Furnace was not compiled with PortAudio!");
3897 setConf("audioEngine","SDL");
3898 saveConf();
3899 #ifdef HAVE_SDL2
3900 output=new TAAudioSDL;
3901 #else
3902 logE("Furnace was not compiled with SDL support either!");
3903 output=new TAAudio;
3904 #endif
3905 #else
3906 output=new TAAudioPA;
3907 #endif
3908 break;
3909 case DIV_AUDIO_SDL:
3910 #ifdef HAVE_SDL2
3911 output=new TAAudioSDL;
3912 #else
3913 logE("Furnace was not compiled with SDL support!");
3914 output=new TAAudio;
3915 #endif
3916 break;
3917 case DIV_AUDIO_PIPE:
3918 output=new TAAudioPipe;
3919 break;
3920 case DIV_AUDIO_DUMMY:
3921 output=new TAAudio;
3922 break;
3923 default:
3924 logE("invalid audio engine!");
3925 return false;
3926 }
3927
3928 logV("listing audio devices");
3929 audioDevs=output->listAudioDevices();
3930
3931 want.deviceName=getConfString("audioDevice","");
3932 want.bufsize=getConfInt("audioBufSize",1024);
3933 want.rate=getConfInt("audioRate",44100);
3934 want.fragments=2;
3935 want.inChans=0;
3936 want.outChans=getConfInt("audioChans",2);
3937 want.outFormat=TA_AUDIO_FORMAT_F32;
3938 want.wasapiEx=getConfInt("wasapiEx",0);
3939 want.name="Furnace";
3940
3941 if (want.outChans<1) want.outChans=1;
3942 if (want.outChans>16) want.outChans=16;
3943
3944 logV("setting callback");
3945 output->setCallback(process,this);
3946
3947 logV("calling init");
3948 if (!output->init(want,got)) {
3949 logE("error while initializing audio!");
3950 delete output;
3951 output=NULL;
3952 audioEngine=DIV_AUDIO_NULL;
3953 return false;
3954 }
3955
3956 logV("allocating oscBuf...");
3957 for (int i=0; i<got.outChans; i++) {
3958 if (oscBuf[i]==NULL) {
3959 oscBuf[i]=new float[32768];
3960 }
3961 memset(oscBuf[i],0,32768*sizeof(float));
3962 }
3963
3964 logI("initializing MIDI.");
3965 if (output->initMidi(false)) {
3966 midiIns=output->midiIn->listDevices();
3967 midiOuts=output->midiOut->listDevices();
3968 } else {
3969 logW("error while initializing MIDI!");
3970 }
3971 if (output->midiIn) {
3972 String inName=getConfString("midiInDevice","");
3973 if (!inName.empty()) {
3974 // try opening device
3975 logI("opening MIDI input.");
3976 if (!output->midiIn->openDevice(inName)) {
3977 logW("could not open MIDI input device!");
3978 }
3979 } else {
3980 logV("no MIDI input device selected.");
3981 }
3982 }
3983 if (output->midiOut) {
3984 String outName=getConfString("midiOutDevice","");
3985 if (!outName.empty()) {
3986 // try opening device
3987 logI("opening MIDI output.");
3988 if (!output->midiOut->openDevice(outName)) {
3989 logW("could not open MIDI output device!");
3990 }
3991 } else {
3992 logV("no MIDI output device selected.");
3993 }
3994 }
3995
3996 logV("initAudioBackend done");
3997 return true;
3998 }
3999
4000 bool DivEngine::deinitAudioBackend(bool dueToSwitchMaster) {
4001 if (output!=NULL) {
4002 logI("closing audio output.");
4003 output->quit();
4004 if (output->midiIn) {
4005 if (output->midiIn->isDeviceOpen()) {
4006 logI("closing MIDI input.");
4007 output->midiIn->closeDevice();
4008 }
4009 }
4010 if (output->midiOut) {
4011 if (output->midiOut->isDeviceOpen()) {
4012 logI("closing MIDI output.");
4013 output->midiOut->closeDevice();
4014 }
4015 }
4016 output->quitMidi();
4017 delete output;
4018 output=NULL;
4019 if (dueToSwitchMaster) {
4020 audioEngine=DIV_AUDIO_NULL;
4021 }
4022 }
4023 return true;
4024 }
4025
4026 bool DivEngine::prePreInit() {
4027 // init config
4028 initConfDir();
4029 logD("config path: %s",configPath.c_str());
4030
4031 configLoaded=true;
4032 return loadConf();
4033 }
4034
4035 bool DivEngine::preInit(bool noSafeMode) {
4036 bool wantSafe=false;
4037 if (!configLoaded) prePreInit();
4038
4039 logI("Furnace version " DIV_VERSION ".");
4040
4041 // register systems
4042 if (!systemsRegistered) registerSystems();
4043
4044 // register ROM exports
4045 if (!romExportsRegistered) registerROMExports();
4046
4047 // TODO: re-enable with a better approach
4048 // see issue #1581
4049 /*
4050 if (!noSafeMode) {
4051 String safeModePath=configPath+DIR_SEPARATOR_STR+"safemode";
4052 if (touchFile(safeModePath.c_str())==-EEXIST) {
4053 wantSafe=true;
4054 }
4055 }
4056 */
4057
4058 String logPath=configPath+DIR_SEPARATOR_STR+"furnace.log";
4059 startLogFile(logPath.c_str());
4060
4061 if (!conf.has("opn1Core")) {
4062 if (conf.has("opnCore")) {
4063 conf.set("opn1Core",conf.getString("opnCore",""));
4064 }
4065 }
4066 if (!conf.has("opnaCore")) {
4067 if (conf.has("opnCore")) {
4068 conf.set("opnaCore",conf.getString("opnCore",""));
4069 }
4070 }
4071 if (!conf.has("opnbCore")) {
4072 if (conf.has("opnCore")) {
4073 conf.set("opnbCore",conf.getString("opnCore",""));
4074 }
4075 }
4076
4077 #ifdef HAVE_SDL2
4078 String audioDriver=getConfString("sdlAudioDriver","");
4079 if (!audioDriver.empty()) {
4080 SDL_SetHint(SDL_HINT_AUDIODRIVER,audioDriver.c_str());
4081 }
4082 #endif
4083
4084 if (wantSafe) {
4085 logW("requesting safe mode.");
4086 }
4087
4088 return wantSafe;
4089 }
4090
4091 void DivEngine::everythingOK() {
4092 // TODO: re-enable with a better approach
4093 // see issue #1581
4094 /*
4095 String safeModePath=configPath+DIR_SEPARATOR_STR+"safemode";
4096 deleteFile(safeModePath.c_str());
4097 */
4098 }
4099
4100 bool DivEngine::init() {
4101 loadSampleROMs();
4102
4103 // set default system preset
4104 if (!hasLoadedSomething) {
4105 logD("setting default preset");
4106 String preset=getConfString("initialSys2","");
4107 bool oldVol=getConfInt("configVersion",DIV_ENGINE_VERSION)<135;
4108 if (preset.empty()) {
4109 // try loading old preset
4110 logD("trying to load old preset");
4111 preset=decodeSysDesc(getConfString("initialSys",""));
4112 oldVol=false;
4113 }
4114 logD("preset size %ld",preset.size());
4115 if (preset.size()>0 && (preset.size()&3)==0) {
4116 initSongWithDesc(preset.c_str(),true,oldVol);
4117 }
4118 String sysName=getConfString("initialSysName","");
4119 if (sysName=="") {
4120 song.systemName=getSongSystemLegacyName(song,!getConfInt("noMultiSystem",0));
4121 } else {
4122 song.systemName=sysName;
4123 }
4124 hasLoadedSomething=true;
4125 }
4126
4127 // init the rest of engine
4128 bool haveAudio=false;
4129 if (!initAudioBackend()) {
4130 logE("no audio output available!");
4131 } else {
4132 haveAudio=true;
4133 }
4134
4135 logV("creating blip_buf");
4136
4137 samp_bb=blip_new(32768);
4138 if (samp_bb==NULL) {
4139 logE("not enough memory!");
4140 return false;
4141 }
4142 blip_set_dc(samp_bb,0);
4143
4144 samp_bbOut=new short[32768];
4145
4146 samp_bbIn=new short[32768];
4147 samp_bbInLen=32768;
4148
4149 metroBuf=new float[8192];
4150 metroBufLen=8192;
4151
4152 logV("setting blip rate of samp_bb (%f)",got.rate);
4153
4154 blip_set_rates(samp_bb,44100,got.rate);
4155
4156 for (int i=0; i<64; i++) {
4157 vibTable[i]=127*sin(((double)i/64.0)*(2*M_PI));
4158 }
4159 for (int i=0; i<128; i++) {
4160 tremTable[i]=255*0.5*(1.0-cos(((double)i/128.0)*(2*M_PI)));
4161 }
4162 for (int i=0; i<4096; i++) {
4163 reversePitchTable[i]=round(1024.0*pow(2.0,(2048.0-(double)i)/(12.0*128.0)));
4164 pitchTable[i]=round(1024.0*pow(2.0,((double)i-2048.0)/(12.0*128.0)));
4165 }
4166
4167 for (int i=0; i<DIV_MAX_CHANS; i++) {
4168 isMuted[i]=0;
4169 keyHit[i]=false;
4170 }
4171
4172 initDispatch();
4173 renderSamples();
4174 reset();
4175 active=true;
4176
4177 if (!haveAudio) {
4178 return false;
4179 } else {
4180 if (output==NULL) {
4181 logE("output is NULL!");
4182 return false;
4183 }
4184 if (!output->setRun(true)) {
4185 logE("error while activating!");
4186 return false;
4187 }
4188 }
4189 return true;
4190 }
4191
4192 bool DivEngine::quit(bool saveConfig) {
4193 deinitAudioBackend();
4194 quitDispatch();
4195 if (saveConfig) {
4196 logI("saving config.");
4197 saveConf();
4198 }
4199 active=false;
4200 for (int i=0; i<DIV_MAX_OUTPUTS; i++) {
4201 if (oscBuf[i]!=NULL) delete[] oscBuf[i];
4202 }
4203 if (metroBuf!=NULL) {
4204 delete[] metroBuf;
4205 metroBuf=NULL;
4206 metroBufLen=0;
4207 }
4208 if (yrw801ROM!=NULL) delete[] yrw801ROM;
4209 if (tg100ROM!=NULL) delete[] tg100ROM;
4210 if (mu5ROM!=NULL) delete[] mu5ROM;
4211 song.unload();
4212 return true;
4213 }