Debian Codegraph @

src/engine/playback.cpp

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "macroInt.h"
21 #include <chrono>
22 #define _USE_MATH_DEFINES
23 #include "dispatch.h"
24 #include "engine.h"
25 #include "workPool.h"
26 #include "../ta-log.h"
27 #include <math.h>
28
29 void DivEngine::nextOrder() {
30 curRow=0;
31 if (repeatPattern) return;
32 if (++curOrder>=curSubSong->ordersLen) {
33 logV("end of orders reached");
34 endOfSong=true;
35 memset(walked,0,8192);
36 curOrder=0;
37 }
38 }
39
40 static const char* notes[12]={
41 "C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"
42 };
43
44 // update this when adding new commands.
45 const char* cmdName[]={
46 "NOTE_ON",
47 "NOTE_OFF",
48 "NOTE_OFF_ENV",
49 "ENV_RELEASE",
50 "INSTRUMENT",
51 "VOLUME",
52 "GET_VOLUME",
53 "GET_VOLMAX",
54 "NOTE_PORTA",
55 "PITCH",
56 "PANNING",
57 "LEGATO",
58 "PRE_PORTA",
59 "PRE_NOTE",
60
61 "HINT_VIBRATO",
62 "HINT_VIBRATO_RANGE",
63 "HINT_VIBRATO_SHAPE",
64 "HINT_PITCH",
65 "HINT_ARPEGGIO",
66 "HINT_VOLUME",
67 "HINT_VOL_SLIDE",
68 "HINT_PORTA",
69 "HINT_LEGATO",
70 "HINT_VOL_SLIDE_TARGET",
71 "HINT_TREMOLO",
72 "HINT_PANBRELLO",
73 "HINT_PAN_SLIDE",
74 "HINT_PANNING",
75
76 "SAMPLE_MODE",
77 "SAMPLE_FREQ",
78 "SAMPLE_BANK",
79 "SAMPLE_POS",
80 "SAMPLE_DIR",
81
82 "FM_HARD_RESET",
83 "FM_LFO",
84 "FM_LFO_WAVE",
85 "FM_TL",
86 "FM_AM",
87 "FM_AR",
88 "FM_DR",
89 "FM_SL",
90 "FM_D2R",
91 "FM_RR",
92 "FM_DT",
93 "FM_DT2",
94 "FM_RS",
95 "FM_KSR",
96 "FM_VIB",
97 "FM_SUS",
98 "FM_WS",
99 "FM_SSG",
100 "FM_REV",
101 "FM_EG_SHIFT",
102 "FM_FB",
103 "FM_MULT",
104 "FM_FINE",
105 "FM_FIXFREQ",
106 "FM_EXTCH",
107 "FM_AM_DEPTH",
108 "FM_PM_DEPTH",
109
110 "FM_LFO2",
111 "FM_LFO2_WAVE",
112
113 "STD_NOISE_FREQ",
114 "STD_NOISE_MODE",
115
116 "WAVE",
117
118 "GB_SWEEP_TIME",
119 "GB_SWEEP_DIR",
120
121 "PCE_LFO_MODE",
122 "PCE_LFO_SPEED",
123
124 "NES_SWEEP",
125 "NES_DMC",
126
127 "C64_CUTOFF",
128 "C64_RESONANCE",
129 "C64_FILTER_MODE",
130 "C64_RESET_TIME",
131 "C64_RESET_MASK",
132 "C64_FILTER_RESET",
133 "C64_DUTY_RESET",
134 "C64_EXTENDED",
135 "C64_FINE_DUTY",
136 "C64_FINE_CUTOFF",
137
138 "AY_ENVELOPE_SET",
139 "AY_ENVELOPE_LOW",
140 "AY_ENVELOPE_HIGH",
141 "AY_ENVELOPE_SLIDE",
142 "AY_NOISE_MASK_AND",
143 "AY_NOISE_MASK_OR",
144 "AY_AUTO_ENVELOPE",
145 "AY_IO_WRITE",
146 "AY_AUTO_PWM",
147
148 "FDS_MOD_DEPTH",
149 "FDS_MOD_HIGH",
150 "FDS_MOD_LOW",
151 "FDS_MOD_POS",
152 "FDS_MOD_WAVE",
153
154 "SAA_ENVELOPE",
155
156 "AMIGA_FILTER",
157 "AMIGA_AM",
158 "AMIGA_PM",
159
160 "LYNX_LFSR_LOAD",
161
162 "QSOUND_ECHO_FEEDBACK",
163 "QSOUND_ECHO_DELAY",
164 "QSOUND_ECHO_LEVEL",
165 "QSOUND_SURROUND",
166
167 "X1_010_ENVELOPE_SHAPE",
168 "X1_010_ENVELOPE_ENABLE",
169 "X1_010_ENVELOPE_MODE",
170 "X1_010_ENVELOPE_PERIOD",
171 "X1_010_ENVELOPE_SLIDE",
172 "X1_010_AUTO_ENVELOPE",
173 "X1_010_SAMPLE_BANK_SLOT",
174
175 "WS_SWEEP_TIME",
176 "WS_SWEEP_AMOUNT",
177
178 "N163_WAVE_POSITION",
179 "N163_WAVE_LENGTH",
180 "N163_WAVE_MODE",
181 "N163_WAVE_LOAD",
182 "N163_WAVE_LOADPOS",
183 "N163_WAVE_LOADLEN",
184 "N163_WAVE_LOADMODE",
185 "N163_CHANNEL_LIMIT",
186 "N163_GLOBAL_WAVE_LOAD",
187 "N163_GLOBAL_WAVE_LOADPOS",
188 "N163_GLOBAL_WAVE_LOADLEN",
189 "N163_GLOBAL_WAVE_LOADMODE",
190
191 "SU_SWEEP_PERIOD_LOW",
192 "SU_SWEEP_PERIOD_HIGH",
193 "SU_SWEEP_BOUND",
194 "SU_SWEEP_ENABLE",
195 "SU_SYNC_PERIOD_LOW",
196 "SU_SYNC_PERIOD_HIGH",
197
198 "ADPCMA_GLOBAL_VOLUME",
199
200 "SNES_ECHO",
201 "SNES_PITCH_MOD",
202 "SNES_INVERT",
203 "SNES_GAIN_MODE",
204 "SNES_GAIN",
205 "SNES_ECHO_ENABLE",
206 "SNES_ECHO_DELAY",
207 "SNES_ECHO_VOL_LEFT",
208 "SNES_ECHO_VOL_RIGHT",
209 "SNES_ECHO_FEEDBACK",
210 "SNES_ECHO_FIR",
211
212 "NES_ENV_MODE",
213 "NES_LENGTH",
214 "NES_COUNT_MODE",
215
216 "MACRO_OFF",
217 "MACRO_ON",
218
219 "SURROUND_PANNING",
220
221 "FM_AM2_DEPTH",
222 "FM_PM2_DEPTH",
223
224 "ES5506_FILTER_MODE",
225 "ES5506_FILTER_K1",
226 "ES5506_FILTER_K2",
227 "ES5506_FILTER_K1_SLIDE",
228 "ES5506_FILTER_K2_SLIDE",
229 "ES5506_ENVELOPE_COUNT",
230 "ES5506_ENVELOPE_LVRAMP",
231 "ES5506_ENVELOPE_RVRAMP",
232 "ES5506_ENVELOPE_K1RAMP",
233 "ES5506_ENVELOPE_K2RAMP",
234 "ES5506_PAUSE",
235
236 "HINT_ARP_TIME",
237
238 "SNES_GLOBAL_VOL_LEFT",
239 "SNES_GLOBAL_VOL_RIGHT",
240
241 "NES_LINEAR_LENGTH",
242
243 "EXTERNAL",
244
245 "C64_AD",
246 "C64_SR",
247
248 "ESFM_OP_PANNING",
249 "ESFM_OUTLVL",
250 "ESFM_MODIN",
251 "ESFM_ENV_DELAY",
252
253 "MACRO_RESTART",
254
255 "POWERNOISE_COUNTER_LOAD",
256 "POWERNOISE_IO_WRITE",
257
258 "DAVE_HIGH_PASS",
259 "DAVE_RING_MOD",
260 "DAVE_SWAP_COUNTERS",
261 "DAVE_LOW_PASS",
262 "DAVE_CLOCK_DIV",
263
264 "MINMOD_ECHO",
265
266 "BIFURCATOR_STATE_LOAD",
267 "BIFURCATOR_PARAMETER",
268
269 "FDS_MOD_AUTO",
270
271 "FM_OPMASK",
272
273 "MULTIPCM_MIX_FM",
274 "MULTIPCM_MIX_PCM",
275 "MULTIPCM_LFO",
276 "MULTIPCM_VIB",
277 "MULTIPCM_AM",
278 "MULTIPCM_AR",
279 "MULTIPCM_D1R",
280 "MULTIPCM_DL",
281 "MULTIPCM_D2R",
282 "MULTIPCM_RR",
283 "MULTIPCM_RC",
284 "MULTIPCM_DAMP",
285 "MULTIPCM_PSEUDO_REVERB",
286 "MULTIPCM_LFO_RESET",
287 "MULTIPCM_LEVEL_DIRECT",
288
289 "SID3_SPECIAL_WAVE",
290 "SID3_RING_MOD_SRC",
291 "SID3_HARD_SYNC_SRC",
292 "SID3_PHASE_MOD_SRC",
293 "SID3_WAVE_MIX",
294 "SID3_LFSR_FEEDBACK_BITS",
295 "SID3_1_BIT_NOISE",
296 "SID3_FILTER_DISTORTION",
297 "SID3_FILTER_OUTPUT_VOLUME",
298 "SID3_CHANNEL_INVERSION",
299 "SID3_FILTER_CONNECTION",
300 "SID3_FILTER_MATRIX",
301 "SID3_FILTER_ENABLE",
302
303 "C64_PW_SLIDE",
304 "C64_CUTOFF_SLIDE",
305
306 "SID3_PHASE_RESET",
307 "SID3_NOISE_PHASE_RESET",
308 "SID3_ENVELOPE_RESET",
309 "SID3_CUTOFF_SCALING",
310 "SID3_RESONANCE_SCALING",
311
312 "WS_GLOBAL_SPEAKER_VOLUME",
313
314 "FM_ALG",
315 "FM_FMS",
316 "FM_AMS",
317 "FM_FMS2",
318 "FM_AMS2"
319 };
320
321 static_assert((sizeof(cmdName)/sizeof(void*))==DIV_CMD_MAX,"update cmdName!");
322
323 const char* formatNote(unsigned char note, unsigned char octave) {
324 static char ret[4];
325 if (note==100) {
326 return "OFF";
327 } else if (note==101) {
328 return "===";
329 } else if (note==102) {
330 return "REL";
331 } else if (octave==0 && note==0) {
332 return "---";
333 }
334 snprintf(ret,4,"%s%d",notes[note%12],octave+note/12);
335 return ret;
336 }
337
338 int DivEngine::dispatchCmd(DivCommand c) {
339 if (view==DIV_STATUS_COMMANDS) {
340 if (!skipping) {
341 switch (c.cmd) {
342 // strip away hinted/useless commands
343 case DIV_CMD_GET_VOLUME:
344 break;
345 case DIV_CMD_VOLUME:
346 break;
347 case DIV_CMD_NOTE_PORTA:
348 break;
349 case DIV_CMD_LEGATO:
350 break;
351 case DIV_CMD_PITCH:
352 break;
353 case DIV_CMD_PRE_NOTE:
354 break;
355 default:
356 printf("%8d | %d: %s(%d, %d)\n",totalTicksR,c.chan,cmdName[c.cmd],c.value,c.value2);
357 }
358 }
359 }
360 totalCmds++;
361 if (cmdStreamEnabled && cmdStream.size()<2000) {
362 cmdStream.push_back(c);
363 }
364
365 if (output) if (!skipping && output->midiOut!=NULL && !isChannelMuted(c.chan)) {
366 if (output->midiOut->isDeviceOpen()) {
367 if (midiOutMode==DIV_MIDI_MODE_NOTE) {
368 int scaledVol=(chan[c.chan].volume*127)/MAX(1,chan[c.chan].volMax);
369 if (scaledVol<0) scaledVol=0;
370 if (scaledVol>127) scaledVol=127;
371 switch (c.cmd) {
372 case DIV_CMD_NOTE_ON:
373 case DIV_CMD_LEGATO:
374 if (chan[c.chan].curMidiNote>=0) {
375 output->midiOut->send(TAMidiMessage(0x80|(c.chan&15),chan[c.chan].curMidiNote,scaledVol));
376 }
377 if (c.value!=DIV_NOTE_NULL) {
378 chan[c.chan].curMidiNote=c.value+12;
379 if (chan[c.chan].curMidiNote<0) chan[c.chan].curMidiNote=0;
380 if (chan[c.chan].curMidiNote>127) chan[c.chan].curMidiNote=127;
381 }
382 if (chan[c.chan].curMidiNote>=0) {
383 output->midiOut->send(TAMidiMessage(0x90|(c.chan&15),chan[c.chan].curMidiNote,scaledVol));
384 }
385 break;
386 case DIV_CMD_NOTE_OFF:
387 case DIV_CMD_NOTE_OFF_ENV:
388 if (chan[c.chan].curMidiNote>=0) {
389 output->midiOut->send(TAMidiMessage(0x80|(c.chan&15),chan[c.chan].curMidiNote,scaledVol));
390 }
391 chan[c.chan].curMidiNote=-1;
392 break;
393 case DIV_CMD_INSTRUMENT:
394 if (chan[c.chan].lastIns!=c.value && midiOutProgramChange) {
395 output->midiOut->send(TAMidiMessage(0xc0|(c.chan&15),c.value&0x7f,0));
396 }
397 break;
398 case DIV_CMD_VOLUME:
399 if (chan[c.chan].curMidiNote>=0 && chan[c.chan].midiAftertouch) {
400 chan[c.chan].midiAftertouch=false;
401 output->midiOut->send(TAMidiMessage(0xa0|(c.chan&15),chan[c.chan].curMidiNote,scaledVol));
402 }
403 break;
404 case DIV_CMD_PITCH: {
405 int pitchBend=8192+(c.value<<5);
406 if (pitchBend<0) pitchBend=0;
407 if (pitchBend>16383) pitchBend=16383;
408 if (pitchBend!=chan[c.chan].midiPitch) {
409 chan[c.chan].midiPitch=pitchBend;
410 output->midiOut->send(TAMidiMessage(0xe0|(c.chan&15),pitchBend&0x7f,pitchBend>>7));
411 }
412 break;
413 }
414 case DIV_CMD_PANNING: {
415 int pan=convertPanSplitToLinearLR(c.value,c.value2,127);
416 if (pan<0) pan=0;
417 if (pan>127) pan=127;
418 output->midiOut->send(TAMidiMessage(0xb0|(c.chan&15),0x0a,pan));
419 break;
420 }
421 case DIV_CMD_HINT_PORTA: {
422 if (c.value2>0) {
423 if (c.value<=0 || c.value>=255) break;
424 //output->midiOut->send(TAMidiMessage(0x80|(c.chan&15),chan[c.chan].curMidiNote,scaledVol));
425 int target=c.value+12;
426 if (target<0) target=0;
427 if (target>127) target=127;
428
429 if (chan[c.chan].curMidiNote>=0) {
430 output->midiOut->send(TAMidiMessage(0xb0|(c.chan&15),0x54,chan[c.chan].curMidiNote));
431 }
432 output->midiOut->send(TAMidiMessage(0xb0|(c.chan&15),0x05,1/*MIN(0x7f,c.value2/4)*/));
433 output->midiOut->send(TAMidiMessage(0xb0|(c.chan&15),0x41,0x7f));
434
435 output->midiOut->send(TAMidiMessage(0x90|(c.chan&15),target,scaledVol));
436 } else {
437 output->midiOut->send(TAMidiMessage(0xb0|(c.chan&15),0x41,0));
438 }
439 break;
440 }
441 default:
442 break;
443 }
444 }
445 }
446 }
447
448 c.chan=dispatchChanOfChan[c.dis];
449
450 return disCont[dispatchOfChan[c.dis]].dispatch->dispatch(c);
451 }
452
453 bool DivEngine::perSystemEffect(int ch, unsigned char effect, unsigned char effectVal) {
454 DivSysDef* sysDef=sysDefs[sysOfChan[ch]];
455 if (sysDef==NULL) return false;
456 auto iter=sysDef->effectHandlers.find(effect);
457 if (iter==sysDef->effectHandlers.end()) return false;
458 EffectHandler handler=iter->second;
459 int val=0;
460 int val2=0;
461 try {
462 val=handler.val?handler.val(effect,effectVal):effectVal;
463 val2=handler.val2?handler.val2(effect,effectVal):0;
464 } catch (DivDoNotHandleEffect& e) {
465 return false;
466 }
467 // wouldn't this cause problems if it were to return 0?
468 return dispatchCmd(DivCommand(handler.dispatchCmd,ch,val,val2));
469 }
470
471 bool DivEngine::perSystemPostEffect(int ch, unsigned char effect, unsigned char effectVal) {
472 DivSysDef* sysDef=sysDefs[sysOfChan[ch]];
473 if (sysDef==NULL) return false;
474 auto iter=sysDef->postEffectHandlers.find(effect);
475 if (iter==sysDef->postEffectHandlers.end()) return false;
476 EffectHandler handler=iter->second;
477 int val=0;
478 int val2=0;
479 try {
480 val=handler.val?handler.val(effect,effectVal):effectVal;
481 val2=handler.val2?handler.val2(effect,effectVal):0;
482 } catch (DivDoNotHandleEffect& e) {
483 return true;
484 }
485 // wouldn't this cause problems if it were to return 0?
486 return dispatchCmd(DivCommand(handler.dispatchCmd,ch,val,val2));
487 }
488
489 bool DivEngine::perSystemPreEffect(int ch, unsigned char effect, unsigned char effectVal) {
490 DivSysDef* sysDef=sysDefs[sysOfChan[ch]];
491 if (sysDef==NULL) return false;
492 auto iter=sysDef->preEffectHandlers.find(effect);
493 if (iter==sysDef->preEffectHandlers.end()) return false;
494 EffectHandler handler=iter->second;
495 int val=0;
496 int val2=0;
497 try {
498 val=handler.val?handler.val(effect,effectVal):effectVal;
499 val2=handler.val2?handler.val2(effect,effectVal):0;
500 } catch (DivDoNotHandleEffect& e) {
501 return false;
502 }
503 // wouldn't this cause problems if it were to return 0?
504 return dispatchCmd(DivCommand(handler.dispatchCmd,ch,val,val2));
505 }
506
507 void DivEngine::processRowPre(int i) {
508 int whatOrder=curOrder;
509 int whatRow=curRow;
510 DivPattern* pat=curPat[i].getPattern(curOrders->ord[i][whatOrder],false);
511 for (int j=0; j<curPat[i].effectCols; j++) {
512 short effect=pat->data[whatRow][4+(j<<1)];
513 short effectVal=pat->data[whatRow][5+(j<<1)];
514
515 if (effectVal==-1) effectVal=0;
516 effectVal&=255;
517 perSystemPreEffect(i,effect,effectVal);
518 }
519 }
520
521 void DivEngine::processRow(int i, bool afterDelay) {
522 int whatOrder=afterDelay?chan[i].delayOrder:curOrder;
523 int whatRow=afterDelay?chan[i].delayRow:curRow;
524 DivPattern* pat=curPat[i].getPattern(curOrders->ord[i][whatOrder],false);
525 // pre effects
526 if (!afterDelay) {
527 bool returnAfterPre=false;
528 for (int j=0; j<curPat[i].effectCols; j++) {
529 short effect=pat->data[whatRow][4+(j<<1)];
530 short effectVal=pat->data[whatRow][5+(j<<1)];
531
532 if (effectVal==-1) effectVal=0;
533 effectVal&=255;
534
535 switch (effect) {
536 case 0x09: // select groove pattern/speed 1
537 if (song.grooves.empty()) {
538 if (effectVal>0) speeds.val[0]=effectVal;
539 } else {
540 if (effectVal<(short)song.grooves.size()) {
541 speeds=song.grooves[effectVal];
542 curSpeed=0;
543 }
544 }
545 break;
546 case 0x0f: // speed 1/speed 2
547 if (speeds.len==2 && song.grooves.empty()) {
548 if (effectVal>0) speeds.val[1]=effectVal;
549 } else {
550 if (effectVal>0) speeds.val[0]=effectVal;
551 }
552 break;
553 case 0xfd: // virtual tempo num
554 if (effectVal>0) virtualTempoN=effectVal;
555 break;
556 case 0xfe: // virtual tempo den
557 if (effectVal>0) virtualTempoD=effectVal;
558 break;
559 case 0x0b: // change order
560 if (changeOrd==-1 || song.jumpTreatment==0) {
561 changeOrd=effectVal;
562 if (song.jumpTreatment==1 || song.jumpTreatment==2) {
563 changePos=0;
564 }
565 }
566 break;
567 case 0x0d: // next order
568 if (song.jumpTreatment==2) {
569 if ((curOrder<(curSubSong->ordersLen-1) || !song.ignoreJumpAtEnd)) {
570 changeOrd=-2;
571 changePos=effectVal;
572 }
573 } else if (song.jumpTreatment==1) {
574 if (changeOrd<0 && (curOrder<(curSubSong->ordersLen-1) || !song.ignoreJumpAtEnd)) {
575 changeOrd=-2;
576 changePos=effectVal;
577 }
578 } else {
579 if (curOrder<(curSubSong->ordersLen-1) || !song.ignoreJumpAtEnd) {
580 if (changeOrd<0) {
581 changeOrd=-2;
582 }
583 changePos=effectVal;
584 }
585 }
586 break;
587 case 0xed: // delay
588 if (effectVal!=0) {
589 bool comparison=(song.delayBehavior==1)?(effectVal<=nextSpeed):(effectVal<(nextSpeed*(curSubSong->timeBase+1)));
590 if (song.delayBehavior==2) comparison=true;
591 if (comparison) {
592 chan[i].rowDelay=effectVal;
593 chan[i].delayOrder=whatOrder;
594 chan[i].delayRow=whatRow;
595 if (effectVal==nextSpeed) {
596 //if (sysOfChan[i]!=DIV_SYSTEM_YM2610 && sysOfChan[i]!=DIV_SYSTEM_YM2610_EXT) chan[i].delayLocked=true;
597 } else {
598 chan[i].delayLocked=false;
599 }
600 returnAfterPre=true;
601 } else {
602 logV("higher than nextSpeed! %d>%d",effectVal,nextSpeed);
603 chan[i].delayLocked=false;
604 }
605 }
606 break;
607 }
608 }
609 if (returnAfterPre) return;
610 } else {
611 //logV("honoring delay at position %d",whatRow);
612 }
613
614 if (chan[i].delayLocked) return;
615
616 // instrument
617 bool insChanged=false;
618 if (pat->data[whatRow][2]!=-1) {
619 if (chan[i].lastIns!=pat->data[whatRow][2]) {
620 dispatchCmd(DivCommand(DIV_CMD_INSTRUMENT,i,pat->data[whatRow][2]));
621 chan[i].lastIns=pat->data[whatRow][2];
622 insChanged=true;
623 if (song.legacyVolumeSlides && chan[i].volume==chan[i].volMax+1) {
624 logV("forcing volume");
625 chan[i].volume=chan[i].volMax;
626 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
627 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
628 }
629 }
630 }
631 // note
632 if (pat->data[whatRow][0]==100) { // note off
633 //chan[i].note=-1;
634 chan[i].keyOn=false;
635 chan[i].keyOff=true;
636 if (chan[i].inPorta && song.noteOffResetsSlides) {
637 if (chan[i].stopOnOff) {
638 chan[i].portaNote=-1;
639 chan[i].portaSpeed=-1;
640 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
641 chan[i].stopOnOff=false;
642 }
643 if (disCont[dispatchOfChan[i]].dispatch->keyOffAffectsPorta(dispatchChanOfChan[i])) {
644 chan[i].portaNote=-1;
645 chan[i].portaSpeed=-1;
646 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
647 /*if (i==2 && sysOfChan[i]==DIV_SYSTEM_SMS) {
648 chan[i+1].portaNote=-1;
649 chan[i+1].portaSpeed=-1;
650 }*/
651 }
652 chan[i].scheduledSlideReset=true;
653 }
654 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF,i));
655 } else if (pat->data[whatRow][0]==101) { // note off + env release
656 //chan[i].note=-1;
657 chan[i].keyOn=false;
658 chan[i].keyOff=true;
659 if (chan[i].inPorta && song.noteOffResetsSlides) {
660 if (chan[i].stopOnOff) {
661 chan[i].portaNote=-1;
662 chan[i].portaSpeed=-1;
663 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
664 chan[i].stopOnOff=false;
665 }
666 if (disCont[dispatchOfChan[i]].dispatch->keyOffAffectsPorta(dispatchChanOfChan[i])) {
667 chan[i].portaNote=-1;
668 chan[i].portaSpeed=-1;
669 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
670 /*if (i==2 && sysOfChan[i]==DIV_SYSTEM_SMS) {
671 chan[i+1].portaNote=-1;
672 chan[i+1].portaSpeed=-1;
673 }*/
674 }
675 chan[i].scheduledSlideReset=true;
676 }
677 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF_ENV,i));
678 chan[i].releasing=true;
679 } else if (pat->data[whatRow][0]==102) { // env release
680 dispatchCmd(DivCommand(DIV_CMD_ENV_RELEASE,i));
681 chan[i].releasing=true;
682 } else if (!(pat->data[whatRow][0]==0 && pat->data[whatRow][1]==0)) {
683 chan[i].oldNote=chan[i].note;
684 chan[i].note=pat->data[whatRow][0]+((signed char)pat->data[whatRow][1])*12;
685 if (!chan[i].keyOn) {
686 if (disCont[dispatchOfChan[i]].dispatch->keyOffAffectsArp(dispatchChanOfChan[i])) {
687 chan[i].arp=0;
688 dispatchCmd(DivCommand(DIV_CMD_HINT_ARPEGGIO,i,chan[i].arp));
689 }
690 }
691 chan[i].doNote=true;
692 if (chan[i].arp!=0 && song.compatibleArpeggio) {
693 chan[i].arpYield=true;
694 }
695 }
696
697 // volume
698 int volPortaTarget=-1;
699 bool noApplyVolume=false;
700 for (int j=0; j<curPat[i].effectCols; j++) {
701 short effect=pat->data[whatRow][4+(j<<1)];
702 if (effect==0xd3 || effect==0xd4) { // vol porta
703 volPortaTarget=pat->data[whatRow][3]<<8; // can be -256
704
705 short effectVal=pat->data[whatRow][5+(j<<1)];
706 if (effectVal==-1) effectVal=0;
707 effectVal&=255;
708
709 noApplyVolume=effectVal>0; // "D3.." or "D300" shouldn't stop volume from applying
710 break; // technically you could have both D3 and D4... let's not care
711 }
712 }
713
714 if (pat->data[whatRow][3]!=-1 && !noApplyVolume) {
715 if (!song.oldAlwaysSetVolume || disCont[dispatchOfChan[i]].dispatch->getLegacyAlwaysSetVolume() || (MIN(chan[i].volMax,chan[i].volume)>>8)!=pat->data[whatRow][3]) {
716 if (pat->data[whatRow][0]==0 && pat->data[whatRow][1]==0) {
717 chan[i].midiAftertouch=true;
718 }
719 chan[i].volume=pat->data[whatRow][3]<<8;
720 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
721 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
722 }
723 }
724
725 chan[i].retrigSpeed=0;
726
727 short lastSlide=-1;
728 bool calledPorta=false;
729 bool panChanged=false;
730 bool surroundPanChanged=false;
731 bool sampleOffSet=false;
732
733 // effects
734 for (int j=0; j<curPat[i].effectCols; j++) {
735 short effect=pat->data[whatRow][4+(j<<1)];
736 short effectVal=pat->data[whatRow][5+(j<<1)];
737
738 if (effectVal==-1) effectVal=0;
739 effectVal&=255;
740
741 // per-system effect
742 if (!perSystemEffect(i,effect,effectVal)) switch (effect) {
743 case 0x08: // panning (split 4-bit)
744 chan[i].panL=(effectVal>>4)|(effectVal&0xf0);
745 chan[i].panR=(effectVal&15)|((effectVal&15)<<4);
746 panChanged=true;
747 break;
748 case 0x80: { // panning (linear)
749 unsigned short pan=convertPanLinearToSplit(effectVal,8,255);
750 chan[i].panL=pan>>8;
751 chan[i].panR=pan&0xff;
752 panChanged=true;
753 break;
754 }
755 case 0x81: // panning left (split 8-bit)
756 chan[i].panL=effectVal;
757 panChanged=true;
758 break;
759 case 0x82: // panning right (split 8-bit)
760 chan[i].panR=effectVal;
761 panChanged=true;
762 break;
763 case 0x83: // pan slide
764 if (effectVal!=0) {
765 if ((effectVal&15)!=0) {
766 chan[i].panSpeed=(effectVal&15);
767 } else {
768 chan[i].panSpeed=-(effectVal>>4);
769 }
770 // panbrello and slides are incompatible
771 chan[i].panDepth=0;
772 chan[i].panRate=0;
773 chan[i].panPos=0;
774 } else {
775 chan[i].panSpeed=0;
776 }
777 dispatchCmd(DivCommand(DIV_CMD_HINT_PAN_SLIDE,i,chan[i].panSpeed&0xff));
778 break;
779 case 0x84: // panbrello
780 if (chan[i].panDepth==0) {
781 chan[i].panPos=0;
782 }
783 chan[i].panDepth=effectVal&15;
784 chan[i].panRate=effectVal>>4;
785 if (chan[i].panDepth!=0) {
786 chan[i].panSpeed=0;
787 }
788 dispatchCmd(DivCommand(DIV_CMD_HINT_PANBRELLO,i,effectVal));
789 break;
790 case 0x88: // panning rear (split 4-bit)
791 chan[i].panRL=(effectVal>>4)|(effectVal&0xf0);
792 chan[i].panRR=(effectVal&15)|((effectVal&15)<<4);
793 surroundPanChanged=true;
794 break;
795 case 0x89: // panning left (split 8-bit)
796 chan[i].panRL=effectVal;
797 surroundPanChanged=true;
798 break;
799 case 0x8a: // panning right (split 8-bit)
800 chan[i].panRR=effectVal;
801 surroundPanChanged=true;
802 break;
803 case 0x01: // ramp up
804 if (song.ignoreDuplicateSlides && (lastSlide==0x01 || lastSlide==0x1337)) break;
805 lastSlide=0x01;
806 if (effectVal==0) {
807 chan[i].portaNote=-1;
808 chan[i].portaSpeed=-1;
809 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
810 chan[i].inPorta=false;
811 if (!song.arpNonPorta) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
812 } else {
813 chan[i].portaNote=song.limitSlides?0x60:255;
814 chan[i].portaSpeed=effectVal;
815 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
816 chan[i].portaStop=true;
817 chan[i].nowYouCanStop=false;
818 chan[i].stopOnOff=false;
819 chan[i].scheduledSlideReset=false;
820 chan[i].wasShorthandPorta=false;
821 chan[i].inPorta=false;
822 if (!song.arpNonPorta) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,0));
823 }
824 break;
825 case 0x02: // ramp down
826 if (song.ignoreDuplicateSlides && (lastSlide==0x02 || lastSlide==0x1337)) break;
827 lastSlide=0x02;
828 if (effectVal==0) {
829 chan[i].portaNote=-1;
830 chan[i].portaSpeed=-1;
831 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
832 chan[i].inPorta=false;
833 if (!song.arpNonPorta) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
834 } else {
835 chan[i].portaNote=song.limitSlides?disCont[dispatchOfChan[i]].dispatch->getPortaFloor(dispatchChanOfChan[i]):-60;
836 chan[i].portaSpeed=effectVal;
837 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
838 chan[i].portaStop=true;
839 chan[i].nowYouCanStop=false;
840 chan[i].stopOnOff=false;
841 chan[i].scheduledSlideReset=false;
842 chan[i].wasShorthandPorta=false;
843 chan[i].inPorta=false;
844 if (!song.arpNonPorta) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,0));
845 }
846 break;
847 case 0x03: // portamento
848 if (effectVal==0) {
849 chan[i].portaNote=-1;
850 chan[i].portaSpeed=-1;
851 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
852 chan[i].inPorta=false;
853 dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
854 } else {
855 chan[i].lastPorta=effectVal;
856 calledPorta=true;
857 if (chan[i].note==chan[i].oldNote && !chan[i].inPorta && song.buggyPortaAfterSlide) {
858 chan[i].portaNote=chan[i].note;
859 chan[i].portaSpeed=-1;
860 } else {
861 chan[i].portaNote=chan[i].note;
862 chan[i].portaSpeed=effectVal;
863 chan[i].inPorta=true;
864 chan[i].wasShorthandPorta=false;
865 }
866 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
867 chan[i].portaStop=true;
868 if (chan[i].keyOn) chan[i].doNote=false;
869 chan[i].stopOnOff=song.stopPortaOnNoteOff; // what?!
870 chan[i].scheduledSlideReset=false;
871 dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,1));
872 lastSlide=0x1337; // i hate this so much
873 }
874 break;
875 case 0x04: // vibrato
876 if (effectVal) chan[i].lastVibrato=effectVal;
877 chan[i].vibratoDepth=effectVal&15;
878 chan[i].vibratoRate=effectVal>>4;
879 dispatchCmd(DivCommand(DIV_CMD_HINT_VIBRATO,i,(chan[i].vibratoDepth&15)|(chan[i].vibratoRate<<4)));
880 dispatchCmd(DivCommand(DIV_CMD_PITCH,i,chan[i].pitch+(((chan[i].vibratoDepth*vibTable[chan[i].vibratoPos]*chan[i].vibratoFine)>>4)/15)));
881 break;
882 case 0x05: // vol slide + vibrato
883 if (effectVal==0) {
884 chan[i].vibratoDepth=0;
885 chan[i].vibratoRate=0;
886 } else {
887 chan[i].vibratoDepth=chan[i].lastVibrato&15;
888 chan[i].vibratoRate=chan[i].lastVibrato>>4;
889 }
890 dispatchCmd(DivCommand(DIV_CMD_HINT_VIBRATO,i,(chan[i].vibratoDepth&15)|(chan[i].vibratoRate<<4)));
891 dispatchCmd(DivCommand(DIV_CMD_PITCH,i,chan[i].pitch+(((chan[i].vibratoDepth*vibTable[chan[i].vibratoPos]*chan[i].vibratoFine)>>4)/15)));
892 // TODO: non-0x-or-x0 value should be treated as 00
893 if (effectVal!=0) {
894 if ((effectVal&15)!=0) {
895 chan[i].volSpeed=-(effectVal&15)*64;
896 } else {
897 chan[i].volSpeed=(effectVal>>4)*64;
898 }
899 // tremolo and vol slides are incompatible
900 chan[i].tremoloDepth=0;
901 chan[i].tremoloRate=0;
902 } else {
903 chan[i].volSpeed=0;
904 }
905 chan[i].volSpeedTarget=-1;
906 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,chan[i].volSpeed));
907 break;
908 case 0x06: // vol slide + porta
909 if (effectVal==0 || chan[i].lastPorta==0) {
910 chan[i].portaNote=-1;
911 chan[i].portaSpeed=-1;
912 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
913 chan[i].inPorta=false;
914 dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
915 } else {
916 calledPorta=true;
917 if (chan[i].note==chan[i].oldNote && !chan[i].inPorta && song.buggyPortaAfterSlide) {
918 chan[i].portaNote=chan[i].note;
919 chan[i].portaSpeed=-1;
920 } else {
921 chan[i].portaNote=chan[i].note;
922 chan[i].portaSpeed=chan[i].lastPorta;
923 chan[i].inPorta=true;
924 chan[i].wasShorthandPorta=false;
925 }
926 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
927 chan[i].portaStop=true;
928 if (chan[i].keyOn) chan[i].doNote=false;
929 chan[i].stopOnOff=song.stopPortaOnNoteOff; // what?!
930 chan[i].scheduledSlideReset=false;
931 dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,1));
932 lastSlide=0x1337; // i hate this so much
933 }
934 // TODO: non-0x-or-x0 value should be treated as 00
935 if (effectVal!=0) {
936 if ((effectVal&15)!=0) {
937 chan[i].volSpeed=-(effectVal&15)*64;
938 } else {
939 chan[i].volSpeed=(effectVal>>4)*64;
940 }
941 // tremolo and vol slides are incompatible
942 chan[i].tremoloDepth=0;
943 chan[i].tremoloRate=0;
944 } else {
945 chan[i].volSpeed=0;
946 }
947 chan[i].volSpeedTarget=-1;
948 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,chan[i].volSpeed));
949 break;
950 case 0x07: // tremolo
951 if (chan[i].tremoloDepth==0) {
952 chan[i].tremoloPos=0;
953 }
954 chan[i].tremoloDepth=effectVal&15;
955 chan[i].tremoloRate=effectVal>>4;
956 dispatchCmd(DivCommand(DIV_CMD_HINT_TREMOLO,i,effectVal));
957 if (chan[i].tremoloDepth!=0) {
958 chan[i].volSpeed=0;
959 chan[i].volSpeedTarget=-1;
960 } else {
961 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
962 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
963 }
964 break;
965 case 0x0a: // volume ramp
966 // TODO: non-0x-or-x0 value should be treated as 00
967 if (effectVal!=0) {
968 if ((effectVal&15)!=0) {
969 chan[i].volSpeed=-(effectVal&15)*64;
970 } else {
971 chan[i].volSpeed=(effectVal>>4)*64;
972 }
973 // tremolo and vol slides are incompatible
974 chan[i].tremoloDepth=0;
975 chan[i].tremoloRate=0;
976 } else {
977 chan[i].volSpeed=0;
978 }
979 chan[i].volSpeedTarget=-1;
980 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,chan[i].volSpeed));
981 break;
982 case 0x00: // arpeggio
983 chan[i].arp=effectVal;
984 if (chan[i].arp==0 && song.arp0Reset) {
985 chan[i].resetArp=true;
986 }
987 dispatchCmd(DivCommand(DIV_CMD_HINT_ARPEGGIO,i,chan[i].arp));
988 break;
989 case 0x0c: // retrigger
990 if (effectVal!=0) {
991 chan[i].retrigSpeed=effectVal;
992 chan[i].retrigTick=0;
993 }
994 break;
995 case 0x90: case 0x91: case 0x92: case 0x93:
996 case 0x94: case 0x95: case 0x96: case 0x97:
997 case 0x98: case 0x99: case 0x9a: case 0x9b:
998 case 0x9c: case 0x9d: case 0x9e: case 0x9f: // set samp. pos
999 if (song.oldSampleOffset) {
1000 dispatchCmd(DivCommand(DIV_CMD_SAMPLE_POS,i,(((effect&0x0f)<<8)|effectVal)*256));
1001 } else {
1002 if (effect<0x93) {
1003 chan[i].sampleOff&=~(0xff<<((effect-0x90)<<3));
1004 chan[i].sampleOff|=effectVal<<((effect-0x90)<<3);
1005 sampleOffSet=true;
1006 }
1007 }
1008 break;
1009 case 0xc0: case 0xc1: case 0xc2: case 0xc3: // set Hz
1010 divider=(double)(((effect&0x3)<<8)|effectVal);
1011 if (divider<1) divider=1;
1012 cycles=got.rate/divider;
1013 clockDrift=0;
1014 subticks=0;
1015 break;
1016 case 0xdc: // delayed mute
1017 if (effectVal>0 && (song.delayBehavior==2 || effectVal<nextSpeed)) {
1018 chan[i].volCut=effectVal+1;
1019 chan[i].cutType=0;
1020 }
1021 break;
1022 case 0xd3: // volume portamento (vol porta)
1023 // tremolo and vol slides are incompatible
1024 chan[i].tremoloDepth=0;
1025 chan[i].tremoloRate=0;
1026 chan[i].volSpeed=volPortaTarget<0 ? 0 : volPortaTarget>chan[i].volume ? effectVal : -effectVal;
1027 chan[i].volSpeedTarget=chan[i].volSpeed==0 ? -1 : volPortaTarget;
1028 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE_TARGET,i,chan[i].volSpeed,chan[i].volSpeedTarget));
1029 break;
1030 case 0xd4: // volume portamento fast (vol porta fast)
1031 // tremolo and vol slides are incompatible
1032 chan[i].tremoloDepth=0;
1033 chan[i].tremoloRate=0;
1034 chan[i].volSpeed=volPortaTarget<0 ? 0 : volPortaTarget>chan[i].volume ? 256*effectVal : -256*effectVal;
1035 chan[i].volSpeedTarget=chan[i].volSpeed==0 ? -1 : volPortaTarget;
1036 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE_TARGET,i,chan[i].volSpeed,chan[i].volSpeedTarget));
1037 break;
1038 case 0xe0: // arp speed
1039 if (effectVal>0) {
1040 curSubSong->arpLen=effectVal;
1041 dispatchCmd(DivCommand(DIV_CMD_HINT_ARP_TIME,i,curSubSong->arpLen));
1042 }
1043 break;
1044 case 0xe1: // portamento up
1045 chan[i].portaNote=chan[i].note+(effectVal&15);
1046 chan[i].portaSpeed=(effectVal>>4)*4;
1047 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1048 chan[i].portaStop=true;
1049 chan[i].nowYouCanStop=false;
1050 chan[i].stopOnOff=song.stopPortaOnNoteOff; // what?!
1051 chan[i].scheduledSlideReset=false;
1052 if ((effectVal&15)!=0) {
1053 chan[i].inPorta=true;
1054 chan[i].shorthandPorta=true;
1055 chan[i].wasShorthandPorta=true;
1056 if (!song.brokenShortcutSlides) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,0));
1057 if (song.e1e2AlsoTakePriority) lastSlide=0x1337; // ...
1058 } else {
1059 chan[i].inPorta=false;
1060 if (!song.brokenShortcutSlides) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
1061 }
1062 break;
1063 case 0xe2: // portamento down
1064 chan[i].portaNote=chan[i].note-(effectVal&15);
1065 chan[i].portaSpeed=(effectVal>>4)*4;
1066 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1067 chan[i].portaStop=true;
1068 chan[i].nowYouCanStop=false;
1069 chan[i].stopOnOff=song.stopPortaOnNoteOff; // what?!
1070 chan[i].scheduledSlideReset=false;
1071 if ((effectVal&15)!=0) {
1072 chan[i].inPorta=true;
1073 chan[i].shorthandPorta=true;
1074 chan[i].wasShorthandPorta=true;
1075 if (!song.brokenShortcutSlides) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,0));
1076 if (song.e1e2AlsoTakePriority) lastSlide=0x1337; // ...
1077 } else {
1078 chan[i].inPorta=false;
1079 if (!song.brokenShortcutSlides) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
1080 }
1081 break;
1082 case 0xe3: // vibrato shape
1083 chan[i].vibratoShape=effectVal;
1084 dispatchCmd(DivCommand(DIV_CMD_HINT_VIBRATO_SHAPE,i,chan[i].vibratoShape));
1085 break;
1086 case 0xe4: // vibrato fine
1087 chan[i].vibratoFine=effectVal;
1088 dispatchCmd(DivCommand(DIV_CMD_HINT_VIBRATO_RANGE,i,chan[i].vibratoFine));
1089 break;
1090 case 0xe5: // pitch
1091 chan[i].pitch=effectVal-0x80;
1092 if (sysOfChan[i]==DIV_SYSTEM_YM2151) { // YM2151 pitch oddity
1093 chan[i].pitch*=2;
1094 if (chan[i].pitch<-128) chan[i].pitch=-128;
1095 if (chan[i].pitch>127) chan[i].pitch=127;
1096 }
1097 //chan[i].pitch+=globalPitch;
1098 dispatchCmd(DivCommand(DIV_CMD_PITCH,i,chan[i].pitch+(((chan[i].vibratoDepth*vibTable[chan[i].vibratoPos]*chan[i].vibratoFine)>>4)/15)));
1099 dispatchCmd(DivCommand(DIV_CMD_HINT_PITCH,i,chan[i].pitch));
1100 break;
1101 case 0xe6: // Delayed legato
1102 // why does this have to follow FamiTracker verbatim
1103 // couldn't you do better?
1104 if ((effectVal&15)!=0) {
1105 chan[i].legatoDelay=(((effectVal&0xf0)>>4)&7)+1;
1106 if (effectVal&128) {
1107 chan[i].legatoTarget=-(effectVal&15);
1108 } else {
1109 chan[i].legatoTarget=(effectVal&15);
1110 }
1111 } else {
1112 chan[i].legatoDelay=-1;
1113 chan[i].legatoTarget=0;
1114 }
1115 break;
1116 case 0xe7: // delayed macro release
1117 // "Bruh"
1118 if (effectVal>0 && (song.delayBehavior==2 || effectVal<nextSpeed)) {
1119 chan[i].cut=effectVal+1;
1120 chan[i].cutType=2;
1121 }
1122 break;
1123 case 0xe8: // delayed legato up
1124 // see? you COULD do better!
1125 if ((effectVal&15)!=0) {
1126 chan[i].legatoDelay=((effectVal&0xf0)>>4)+1;
1127 chan[i].legatoTarget=(effectVal&15);
1128 } else {
1129 chan[i].legatoDelay=-1;
1130 chan[i].legatoTarget=0;
1131 }
1132 break;
1133 case 0xe9: // delayed legato down
1134 if ((effectVal&15)!=0) {
1135 chan[i].legatoDelay=((effectVal&0xf0)>>4)+1;
1136 chan[i].legatoTarget=-(effectVal&15);
1137 } else {
1138 chan[i].legatoDelay=-1;
1139 chan[i].legatoTarget=0;
1140 }
1141 break;
1142 case 0xea: // legato mode
1143 chan[i].legato=effectVal;
1144 break;
1145 case 0xeb: // sample bank
1146 dispatchCmd(DivCommand(DIV_CMD_SAMPLE_BANK,i,effectVal));
1147 break;
1148 case 0xec: // delayed note cut
1149 if (effectVal>0 && (song.delayBehavior==2 || effectVal<nextSpeed)) {
1150 chan[i].cut=effectVal+1;
1151 chan[i].cutType=0;
1152 }
1153 break;
1154 case 0xee: // external command
1155 //printf("\x1b[1;36m%d: extern command %d\x1b[m\n",i,effectVal);
1156 extValue=effectVal;
1157 extValuePresent=true;
1158 dispatchCmd(DivCommand(DIV_CMD_EXTERNAL,i,effectVal));
1159 break;
1160 case 0xef: // global pitch
1161 globalPitch+=(signed char)(effectVal-0x80);
1162 break;
1163 case 0xf0: // set Hz by tempo
1164 divider=(double)effectVal*2.0/5.0;
1165 if (divider<1) divider=1;
1166 cycles=got.rate/divider;
1167 clockDrift=0;
1168 subticks=0;
1169 break;
1170 case 0xf3: // fine volume ramp up
1171 // tremolo and vol slides are incompatible
1172 chan[i].tremoloDepth=0;
1173 chan[i].tremoloRate=0;
1174 chan[i].volSpeed=effectVal;
1175 chan[i].volSpeedTarget=-1;
1176 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,chan[i].volSpeed));
1177 break;
1178 case 0xf4: // fine volume ramp down
1179 // tremolo and vol slides are incompatible
1180 chan[i].tremoloDepth=0;
1181 chan[i].tremoloRate=0;
1182 chan[i].volSpeed=-effectVal;
1183 chan[i].volSpeedTarget=-1;
1184 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,chan[i].volSpeed));
1185 break;
1186 case 0xf5: // disable macro
1187 dispatchCmd(DivCommand(DIV_CMD_MACRO_OFF,i,effectVal&0xff));
1188 break;
1189 case 0xf6: // enable macro
1190 dispatchCmd(DivCommand(DIV_CMD_MACRO_ON,i,effectVal&0xff));
1191 break;
1192 case 0xf7: // restart macro
1193 dispatchCmd(DivCommand(DIV_CMD_MACRO_RESTART,i,effectVal&0xff));
1194 break;
1195 case 0xf8: // single volume ramp up
1196 chan[i].volSpeed=0; // add compat flag?
1197 chan[i].volSpeedTarget=-1;
1198 chan[i].volume=MIN(chan[i].volume+effectVal*256,chan[i].volMax);
1199 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1200 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1201 break;
1202 case 0xf9: // single volume ramp down
1203 chan[i].volSpeed=0; // add compat flag?
1204 chan[i].volSpeedTarget=-1;
1205 chan[i].volume=MAX(chan[i].volume-effectVal*256,0);
1206 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1207 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1208 break;
1209 case 0xfa: // fast volume ramp
1210 if (effectVal!=0) {
1211 if ((effectVal&15)!=0) {
1212 chan[i].volSpeed=-(effectVal&15)*256;
1213 } else {
1214 chan[i].volSpeed=(effectVal>>4)*256;
1215 }
1216 // tremolo and vol slides are incompatible
1217 chan[i].tremoloDepth=0;
1218 chan[i].tremoloRate=0;
1219 } else {
1220 chan[i].volSpeed=0;
1221 }
1222 chan[i].volSpeedTarget=-1;
1223 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,chan[i].volSpeed));
1224 break;
1225 case 0xfc: // delayed note release
1226 if (song.delayBehavior==2 || effectVal<nextSpeed) {
1227 chan[i].cut=effectVal+1;
1228 chan[i].cutType=1;
1229 }
1230 break;
1231
1232 case 0xff: // stop song
1233 shallStopSched=true;
1234 logV("scheduling stop");
1235 break;
1236 }
1237 }
1238
1239 if (sampleOffSet) {
1240 dispatchCmd(DivCommand(DIV_CMD_SAMPLE_POS,i,chan[i].sampleOff));
1241 }
1242
1243 if (panChanged) {
1244 dispatchCmd(DivCommand(DIV_CMD_PANNING,i,chan[i].panL,chan[i].panR));
1245 dispatchCmd(DivCommand(DIV_CMD_HINT_PANNING,i,chan[i].panL,chan[i].panR));
1246 }
1247 if (surroundPanChanged) {
1248 dispatchCmd(DivCommand(DIV_CMD_SURROUND_PANNING,i,2,chan[i].panRL));
1249 dispatchCmd(DivCommand(DIV_CMD_SURROUND_PANNING,i,3,chan[i].panRR));
1250 }
1251
1252 if (insChanged && (chan[i].inPorta || calledPorta) && song.newInsTriggersInPorta) {
1253 dispatchCmd(DivCommand(DIV_CMD_NOTE_ON,i,DIV_NOTE_NULL));
1254 }
1255
1256 if (chan[i].doNote) {
1257 if (!song.continuousVibrato) {
1258 chan[i].vibratoPos=0;
1259 }
1260 dispatchCmd(DivCommand(DIV_CMD_PITCH,i,chan[i].pitch+(((chan[i].vibratoDepth*vibTable[chan[i].vibratoPos]*chan[i].vibratoFine)>>4)/15)));
1261 if (chan[i].legato && (!chan[i].inPorta || song.brokenPortaLegato)) {
1262 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note));
1263 dispatchCmd(DivCommand(DIV_CMD_HINT_LEGATO,i,chan[i].note));
1264 } else {
1265 if (chan[i].inPorta && chan[i].keyOn && !chan[i].shorthandPorta) {
1266 if (song.e1e2StopOnSameNote && chan[i].wasShorthandPorta) {
1267 chan[i].portaSpeed=-1;
1268 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1269 if (!song.brokenShortcutSlides) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
1270 chan[i].wasShorthandPorta=false;
1271 chan[i].inPorta=false;
1272 } else {
1273 chan[i].portaNote=chan[i].note;
1274 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1275 }
1276 } else if (!chan[i].noteOnInhibit) {
1277 dispatchCmd(DivCommand(DIV_CMD_NOTE_ON,i,chan[i].note,chan[i].volume>>8));
1278 chan[i].releasing=false;
1279 if (song.resetArpPhaseOnNewNote) {
1280 chan[i].arpStage=-1;
1281 }
1282 chan[i].goneThroughNote=true;
1283 chan[i].wentThroughNote=true;
1284 keyHit[i]=true;
1285 }
1286 }
1287 chan[i].doNote=false;
1288 if (!chan[i].keyOn && chan[i].scheduledSlideReset) {
1289 chan[i].portaNote=-1;
1290 chan[i].portaSpeed=-1;
1291 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1292 chan[i].scheduledSlideReset=false;
1293 chan[i].inPorta=false;
1294 }
1295 if (!chan[i].keyOn && chan[i].volume>chan[i].volMax) {
1296 chan[i].volume=chan[i].volMax;
1297 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1298 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1299 }
1300 chan[i].keyOn=true;
1301 chan[i].keyOff=false;
1302 }
1303 chan[i].nowYouCanStop=true;
1304 chan[i].shorthandPorta=false;
1305 chan[i].noteOnInhibit=false;
1306
1307 // post effects
1308 for (int j=0; j<curPat[i].effectCols; j++) {
1309 short effect=pat->data[whatRow][4+(j<<1)];
1310 short effectVal=pat->data[whatRow][5+(j<<1)];
1311
1312 if (effectVal==-1) effectVal=0;
1313 effectVal&=255;
1314 if (!perSystemPostEffect(i,effect,effectVal)) {
1315 switch (effect) {
1316 case 0xf1: // single pitch ramp up
1317 case 0xf2: // single pitch ramp down
1318 if (effect==0xf1) {
1319 chan[i].portaNote=song.limitSlides?0x60:255;
1320 } else {
1321 chan[i].portaNote=song.limitSlides?disCont[dispatchOfChan[i]].dispatch->getPortaFloor(dispatchChanOfChan[i]):-60;
1322 }
1323 chan[i].portaSpeed=effectVal;
1324 chan[i].portaStop=true;
1325 chan[i].nowYouCanStop=false;
1326 chan[i].stopOnOff=false;
1327 chan[i].scheduledSlideReset=false;
1328 chan[i].inPorta=false;
1329 if (!song.arpNonPorta) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,true,0));
1330 dispatchCmd(DivCommand(DIV_CMD_NOTE_PORTA,i,chan[i].portaSpeed*(song.linearPitch==2?song.pitchSlideSpeed:1),chan[i].portaNote));
1331 chan[i].portaNote=-1;
1332 chan[i].portaSpeed=-1;
1333 chan[i].inPorta=false;
1334 if (!song.arpNonPorta) dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
1335 break;
1336 }
1337 }
1338 }
1339 }
1340
1341 void DivEngine::nextRow() {
1342 static char pb[4096];
1343 static char pb1[4096];
1344 static char pb2[4096];
1345 static char pb3[4096];
1346 if (view==DIV_STATUS_PATTERN && !skipping) {
1347 strcpy(pb1,"");
1348 strcpy(pb3,"");
1349 for (int i=0; i<chans; i++) {
1350 snprintf(pb,4095," %.2x",curOrders->ord[i][curOrder]);
1351 strcat(pb1,pb);
1352
1353 DivPattern* pat=curPat[i].getPattern(curOrders->ord[i][curOrder],false);
1354 snprintf(pb2,4095,"\x1b[37m %s",
1355 formatNote(pat->data[curRow][0],pat->data[curRow][1]));
1356 strcat(pb3,pb2);
1357 if (pat->data[curRow][3]==-1) {
1358 strcat(pb3,"\x1b[m--");
1359 } else {
1360 snprintf(pb2,4095,"\x1b[1;32m%.2x",pat->data[curRow][3]);
1361 strcat(pb3,pb2);
1362 }
1363 if (pat->data[curRow][2]==-1) {
1364 strcat(pb3,"\x1b[m--");
1365 } else {
1366 snprintf(pb2,4095,"\x1b[0;36m%.2x",pat->data[curRow][2]);
1367 strcat(pb3,pb2);
1368 }
1369 for (int j=0; j<curPat[i].effectCols; j++) {
1370 if (pat->data[curRow][4+(j<<1)]==-1) {
1371 strcat(pb3,"\x1b[m--");
1372 } else {
1373 snprintf(pb2,4095,"\x1b[1;31m%.2x",pat->data[curRow][4+(j<<1)]);
1374 strcat(pb3,pb2);
1375 }
1376 if (pat->data[curRow][5+(j<<1)]==-1) {
1377 strcat(pb3,"\x1b[m--");
1378 } else {
1379 snprintf(pb2,4095,"\x1b[1;37m%.2x",pat->data[curRow][5+(j<<1)]);
1380 strcat(pb3,pb2);
1381 }
1382 }
1383 }
1384 printf("| %.2x:%s | \x1b[1;33m%3d%s\x1b[m\n",curOrder,pb1,curRow,pb3);
1385 }
1386
1387 if (curSubSong->hilightA>0) {
1388 if ((curRow%curSubSong->hilightA)==0) {
1389 pendingMetroTick=1;
1390 elapsedBeats++;
1391 }
1392 }
1393 if (curSubSong->hilightB>0) {
1394 if ((curRow%curSubSong->hilightB)==0) {
1395 pendingMetroTick=2;
1396 elapsedBars++;
1397 elapsedBeats=0;
1398 }
1399 }
1400
1401 if (!stepPlay) {
1402 playPosLock.lock();
1403 prevOrder=curOrder;
1404 prevRow=curRow;
1405 playPosLock.unlock();
1406 }
1407
1408 for (int i=0; i<chans; i++) {
1409 // try to find pre effects
1410 processRowPre(i);
1411 }
1412
1413 for (int i=0; i<chans; i++) {
1414 if (song.delayBehavior!=2) {
1415 chan[i].rowDelay=0;
1416 }
1417 processRow(i,false);
1418 }
1419
1420 walked[((curOrder<<5)+(curRow>>3))&8191]|=1<<(curRow&7);
1421
1422 if (changeOrd!=-1) {
1423 if (repeatPattern) {
1424 curRow=0;
1425 changeOrd=-1;
1426 } else {
1427 curRow=changePos;
1428 changePos=0;
1429 if (changeOrd==-2) changeOrd=curOrder+1;
1430 // old loop detection routine
1431 //if (changeOrd<=curOrder) endOfSong=true;
1432 curOrder=changeOrd;
1433 if (curOrder>=curSubSong->ordersLen) {
1434 curOrder=0;
1435 endOfSong=true;
1436 memset(walked,0,8192);
1437 }
1438 changeOrd=-1;
1439 }
1440 if (haltOn==DIV_HALT_PATTERN) halted=true;
1441 } else if (playing) if (++curRow>=curSubSong->patLen) {
1442 if (shallStopSched) {
1443 curRow=curSubSong->patLen-1;
1444 } else {
1445 nextOrder();
1446 }
1447 if (haltOn==DIV_HALT_PATTERN) halted=true;
1448 }
1449
1450 // new loop detection routine
1451 if (!endOfSong && walked[((curOrder<<5)+(curRow>>3))&8191]&(1<<(curRow&7)) && !shallStopSched) {
1452 logV("loop reached");
1453 endOfSong=true;
1454 memset(walked,0,8192);
1455 }
1456
1457 prevSpeed=nextSpeed;
1458 if (song.brokenSpeedSel) {
1459 unsigned char speed2=(speeds.len>=2)?speeds.val[1]:speeds.val[0];
1460 unsigned char speed1=speeds.val[0];
1461
1462 if ((curSubSong->patLen&1) && curOrder&1) {
1463 ticks=((curRow&1)?speed2:speed1)*(curSubSong->timeBase+1);
1464 nextSpeed=(curRow&1)?speed1:speed2;
1465 } else {
1466 ticks=((curRow&1)?speed1:speed2)*(curSubSong->timeBase+1);
1467 nextSpeed=(curRow&1)?speed2:speed1;
1468 }
1469 } else {
1470 ticks=speeds.val[curSpeed]*(curSubSong->timeBase+1);
1471 curSpeed++;
1472 if (curSpeed>=speeds.len) curSpeed=0;
1473 nextSpeed=speeds.val[curSpeed];
1474 }
1475
1476 /*
1477 if (skipping) {
1478 ticks=1;
1479 }*/
1480
1481 // post row details
1482 for (int i=0; i<chans; i++) {
1483 DivPattern* pat=curPat[i].getPattern(curOrders->ord[i][curOrder],false);
1484 if (!(pat->data[curRow][0]==0 && pat->data[curRow][1]==0)) {
1485 if (pat->data[curRow][0]!=100 && pat->data[curRow][0]!=101 && pat->data[curRow][0]!=102) {
1486 if (!chan[i].legato) {
1487 bool wantPreNote=false;
1488 if (disCont[dispatchOfChan[i]].dispatch!=NULL) {
1489 wantPreNote=disCont[dispatchOfChan[i]].dispatch->getWantPreNote();
1490 if (wantPreNote) {
1491 bool doPreparePreNote=true;
1492 int addition=0;
1493
1494 for (int j=0; j<curPat[i].effectCols; j++) {
1495 if (!song.preNoteNoEffect) {
1496 if (pat->data[curRow][4+(j<<1)]==0x03 && pat->data[curRow][5+(j<<1)]!=0 && pat->data[curRow][5+(j<<1)]!=-1) {
1497 doPreparePreNote=false;
1498 break;
1499 }
1500 if (pat->data[curRow][4+(j<<1)]==0x06 && pat->data[curRow][5+(j<<1)]!=0 && pat->data[curRow][5+(j<<1)]!=-1) {
1501 doPreparePreNote=false;
1502 break;
1503 }
1504 if (pat->data[curRow][4+(j<<1)]==0xea) {
1505 if (pat->data[curRow][5+(j<<1)]>0) {
1506 doPreparePreNote=false;
1507 break;
1508 }
1509 }
1510 }
1511 if (pat->data[curRow][4+(j<<1)]==0xed) {
1512 if (pat->data[curRow][5+(j<<1)]>0) {
1513 addition=pat->data[curRow][5+(j<<1)]&255;
1514 break;
1515 }
1516 }
1517 }
1518 if (doPreparePreNote) dispatchCmd(DivCommand(DIV_CMD_PRE_NOTE,i,ticks+addition));
1519 }
1520 }
1521
1522 if (song.oneTickCut) {
1523 bool doPrepareCut=true;
1524 int addition=0;
1525
1526 for (int j=0; j<curPat[i].effectCols; j++) {
1527 if (pat->data[curRow][4+(j<<1)]==0x03 && pat->data[curRow][5+(j<<1)]!=0 && pat->data[curRow][5+(j<<1)]!=-1) {
1528 doPrepareCut=false;
1529 break;
1530 }
1531 if (pat->data[curRow][4+(j<<1)]==0x06 && pat->data[curRow][5+(j<<1)]!=0 && pat->data[curRow][5+(j<<1)]!=-1) {
1532 doPrepareCut=false;
1533 break;
1534 }
1535 if (pat->data[curRow][4+(j<<1)]==0xea) {
1536 if (pat->data[curRow][5+(j<<1)]>0) {
1537 doPrepareCut=false;
1538 break;
1539 }
1540 }
1541 if (pat->data[curRow][4+(j<<1)]==0xed) {
1542 if (pat->data[curRow][5+(j<<1)]>0) {
1543 addition=pat->data[curRow][5+(j<<1)]&255;
1544 break;
1545 }
1546 }
1547 }
1548 if (doPrepareCut && !wantPreNote && chan[i].cut<=0) {
1549 chan[i].cut=ticks+addition;
1550 chan[i].cutType=0;
1551 }
1552 }
1553 }
1554 }
1555 }
1556 }
1557
1558 if (haltOn==DIV_HALT_ROW) halted=true;
1559 firstTick=true;
1560 }
1561
1562 bool DivEngine::nextTick(bool noAccum, bool inhibitLowLat) {
1563 bool ret=false;
1564 if (divider<1) divider=1;
1565
1566 if (lowLatency && !skipping && !inhibitLowLat) {
1567 tickMult=1000/divider;
1568 if (tickMult<1) tickMult=1;
1569 } else {
1570 tickMult=1;
1571 }
1572
1573 cycles=got.rate/(divider*tickMult);
1574 clockDrift+=fmod(got.rate,(double)(divider*tickMult));
1575 if (clockDrift>=(divider*tickMult)) {
1576 clockDrift-=(divider*tickMult);
1577 cycles++;
1578 }
1579
1580 // don't let user play anything during export
1581 if (exporting) pendingNotes.clear();
1582
1583 if (!pendingNotes.empty()) {
1584 bool isOn[DIV_MAX_CHANS];
1585 memset(isOn,0,DIV_MAX_CHANS*sizeof(bool));
1586
1587 for (int i=pendingNotes.size()-1; i>=0; i--) {
1588 if (pendingNotes[i].channel<0 || pendingNotes[i].channel>=chans) continue;
1589 if (pendingNotes[i].on) {
1590 isOn[pendingNotes[i].channel]=true;
1591 } else {
1592 if (isOn[pendingNotes[i].channel]) {
1593 //logV("erasing off -> on sequence in %d",pendingNotes[i].channel);
1594 pendingNotes[i].nop=true;
1595 }
1596 }
1597 }
1598 }
1599
1600 while (!pendingNotes.empty()) {
1601 DivNoteEvent& note=pendingNotes.front();
1602 if (note.nop || note.channel<0 || note.channel>=chans) {
1603 pendingNotes.pop_front();
1604 continue;
1605 }
1606 if (note.insChange) {
1607 dispatchCmd(DivCommand(DIV_CMD_INSTRUMENT,note.channel,note.ins,0));
1608 pendingNotes.pop_front();
1609 continue;
1610 }
1611 if (note.on) {
1612 if (!(midiIsDirect && midiIsDirectProgram && note.fromMIDI)) {
1613 dispatchCmd(DivCommand(DIV_CMD_INSTRUMENT,note.channel,note.ins,1));
1614 }
1615 if (note.volume>=0 && !disCont[dispatchOfChan[note.channel]].dispatch->isVolGlobal()) {
1616 float curvedVol=pow((float)note.volume/127.0f,midiVolExp);
1617 int mappedVol=disCont[dispatchOfChan[note.channel]].dispatch->mapVelocity(dispatchChanOfChan[note.channel],curvedVol);
1618 dispatchCmd(DivCommand(DIV_CMD_VOLUME,note.channel,mappedVol));
1619 }
1620 dispatchCmd(DivCommand(DIV_CMD_NOTE_ON,note.channel,note.note));
1621 keyHit[note.channel]=true;
1622 chan[note.channel].note = note.note;
1623 chan[note.channel].releasing=false;
1624 chan[note.channel].noteOnInhibit=true;
1625 chan[note.channel].lastIns=note.ins;
1626 } else {
1627 DivMacroInt* macroInt=disCont[dispatchOfChan[note.channel]].dispatch->getChanMacroInt(dispatchChanOfChan[note.channel]);
1628 if (macroInt!=NULL) {
1629 if (macroInt->hasRelease && !disCont[dispatchOfChan[note.channel]].dispatch->isVolGlobal()) {
1630 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF_ENV,note.channel));
1631 } else {
1632 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF,note.channel));
1633 }
1634 } else {
1635 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF,note.channel));
1636 }
1637 }
1638 pendingNotes.pop_front();
1639 }
1640
1641 if (!freelance) {
1642 if (--subticks<=0) {
1643 subticks=tickMult;
1644
1645 // apply delayed rows before potentially advancing to a new row, which would overwrite the
1646 // delayed row's state before it has a chance to do anything. a typical example would be
1647 // a delay scheduling a note-on to be simultaneous with the next row, and the next row also
1648 // containing a delayed note. if we don't apply the delayed row first,
1649 for (int i=0; i<chans; i++) {
1650 // delay effects
1651 if (chan[i].rowDelay>0) {
1652 if (--chan[i].rowDelay==0) {
1653 processRow(i,true);
1654 }
1655 }
1656 }
1657
1658 if (stepPlay!=1) {
1659 tempoAccum+=(skipping && virtualTempoN<virtualTempoD)?virtualTempoD:virtualTempoN;
1660 while (tempoAccum>=virtualTempoD) {
1661 tempoAccum-=virtualTempoD;
1662 if (--ticks<=0) {
1663 ret=endOfSong;
1664 if (shallStopSched) {
1665 logV("acknowledging scheduled stop");
1666 shallStop=true;
1667 break;
1668 } else if (endOfSong) {
1669 if (song.loopModality!=2) {
1670 playSub(true);
1671 }
1672 }
1673 endOfSong=false;
1674 if (stepPlay==2) {
1675 stepPlay=1;
1676 playPosLock.lock();
1677 prevOrder=curOrder;
1678 prevRow=curRow;
1679 playPosLock.unlock();
1680 }
1681 nextRow();
1682 break;
1683 }
1684 }
1685 // under no circumstances shall the accumulator become this large
1686 if (tempoAccum>1023) tempoAccum=1023;
1687 }
1688
1689 // process stuff
1690 if (!shallStop) for (int i=0; i<chans; i++) {
1691 // retrigger
1692 if (chan[i].retrigSpeed) {
1693 if (--chan[i].retrigTick<0) {
1694 chan[i].retrigTick=chan[i].retrigSpeed-1;
1695 dispatchCmd(DivCommand(DIV_CMD_NOTE_ON,i,DIV_NOTE_NULL));
1696 keyHit[i]=true;
1697 }
1698 }
1699
1700 // volume slides and tremolo
1701 if (!song.noSlidesOnFirstTick || !firstTick) {
1702 if (chan[i].volSpeed!=0) {
1703 chan[i].volume=(chan[i].volume&0xff)|(dispatchCmd(DivCommand(DIV_CMD_GET_VOLUME,i))<<8);
1704 int preSpeedVol=chan[i].volume;
1705 chan[i].volume+=chan[i].volSpeed;
1706 if (chan[i].volSpeedTarget!=-1) {
1707 bool atTarget=false;
1708 if (chan[i].volSpeed>0) {
1709 atTarget=(chan[i].volume>=chan[i].volSpeedTarget);
1710 } else if (chan[i].volSpeed<0) {
1711 atTarget=(chan[i].volume<=chan[i].volSpeedTarget);
1712 } else {
1713 atTarget=true;
1714 chan[i].volSpeedTarget=chan[i].volume;
1715 }
1716
1717 if (atTarget) {
1718 if (chan[i].volSpeed>0) {
1719 chan[i].volume=MAX(preSpeedVol,chan[i].volSpeedTarget);
1720 } else if (chan[i].volSpeed<0) {
1721 chan[i].volume=MIN(preSpeedVol,chan[i].volSpeedTarget);
1722 }
1723 chan[i].volSpeed=0;
1724 chan[i].volSpeedTarget=-1;
1725 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1726 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1727 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,0));
1728 }
1729 }
1730 if (chan[i].volume>chan[i].volMax) {
1731 chan[i].volume=chan[i].volMax;
1732 chan[i].volSpeed=0;
1733 chan[i].volSpeedTarget=-1;
1734 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1735 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1736 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,0));
1737 } else if (chan[i].volume<0) {
1738 chan[i].volSpeed=0;
1739 dispatchCmd(DivCommand(DIV_CMD_HINT_VOL_SLIDE,i,0));
1740 if (song.legacyVolumeSlides) {
1741 chan[i].volume=chan[i].volMax+1;
1742 } else {
1743 chan[i].volume=0;
1744 }
1745 chan[i].volSpeedTarget=-1;
1746 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1747 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1748 } else {
1749 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1750 }
1751 } else if (chan[i].tremoloDepth>0) {
1752 chan[i].tremoloPos+=chan[i].tremoloRate;
1753 chan[i].tremoloPos&=127;
1754 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,MAX(0,chan[i].volume-(tremTable[chan[i].tremoloPos]*chan[i].tremoloDepth))>>8));
1755 }
1756 }
1757
1758 // panning slides
1759 if (chan[i].panSpeed!=0) {
1760 int newPanL=chan[i].panL;
1761 int newPanR=chan[i].panR;
1762 if (chan[i].panSpeed>0) { // right
1763 if (newPanR>=0xff) {
1764 newPanL-=chan[i].panSpeed;
1765 } else {
1766 newPanR+=chan[i].panSpeed;
1767 }
1768 } else { // left
1769 if (newPanL>=0xff) {
1770 newPanR+=chan[i].panSpeed;
1771 } else {
1772 newPanL-=chan[i].panSpeed;
1773 }
1774 }
1775
1776 if (newPanL<0) newPanL=0;
1777 if (newPanL>0xff) newPanL=0xff;
1778 if (newPanR<0) newPanR=0;
1779 if (newPanR>0xff) newPanR=0xff;
1780
1781 chan[i].panL=newPanL;
1782 chan[i].panR=newPanR;
1783
1784 dispatchCmd(DivCommand(DIV_CMD_PANNING,i,chan[i].panL,chan[i].panR));
1785 } else if (chan[i].panDepth>0) {
1786 chan[i].panPos+=chan[i].panRate;
1787 chan[i].panPos&=255;
1788
1789 // calculate inverted...
1790 switch (chan[i].panPos&0xc0) {
1791 case 0: // center -> right
1792 chan[i].panL=((chan[i].panPos&0x3f)<<2);
1793 chan[i].panR=0;
1794 break;
1795 case 0x40: // right -> center
1796 chan[i].panL=0xff-((chan[i].panPos&0x3f)<<2);
1797 chan[i].panR=0;
1798 break;
1799 case 0x80: // center -> left
1800 chan[i].panL=0;
1801 chan[i].panR=((chan[i].panPos&0x3f)<<2);
1802 break;
1803 case 0xc0: // left -> center
1804 chan[i].panL=0;
1805 chan[i].panR=0xff-((chan[i].panPos&0x3f)<<2);
1806 break;
1807 }
1808
1809 // multiply by depth
1810 chan[i].panL=(chan[i].panL*chan[i].panDepth)/15;
1811 chan[i].panR=(chan[i].panR*chan[i].panDepth)/15;
1812
1813 // then invert it to get final panning
1814 chan[i].panL^=0xff;
1815 chan[i].panR^=0xff;
1816
1817 dispatchCmd(DivCommand(DIV_CMD_PANNING,i,chan[i].panL,chan[i].panR));
1818 }
1819
1820 // vibrato
1821 if (chan[i].vibratoDepth>0) {
1822 chan[i].vibratoPos+=chan[i].vibratoRate;
1823 while (chan[i].vibratoPos>=64) chan[i].vibratoPos-=64;
1824
1825 chan[i].vibratoPosGiant+=chan[i].vibratoRate;
1826 while (chan[i].vibratoPosGiant>=512) chan[i].vibratoPosGiant-=512;
1827
1828 int vibratoOut=0;
1829 switch (chan[i].vibratoShape) {
1830 case 1: // sine, up only
1831 vibratoOut=MAX(0,vibTable[chan[i].vibratoPos]);
1832 break;
1833 case 2: // sine, down only
1834 vibratoOut=MIN(0,vibTable[chan[i].vibratoPos]);
1835 break;
1836 case 3: // triangle
1837 vibratoOut=(chan[i].vibratoPos&31);
1838 if (chan[i].vibratoPos&16) {
1839 vibratoOut=32-(chan[i].vibratoPos&31);
1840 }
1841 if (chan[i].vibratoPos&32) {
1842 vibratoOut=-vibratoOut;
1843 }
1844 vibratoOut<<=3;
1845 break;
1846 case 4: // ramp up
1847 vibratoOut=chan[i].vibratoPos<<1;
1848 break;
1849 case 5: // ramp down
1850 vibratoOut=-chan[i].vibratoPos<<1;
1851 break;
1852 case 6: // square
1853 vibratoOut=(chan[i].vibratoPos>=32)?-127:127;
1854 break;
1855 case 7: // random (TODO: use LFSR)
1856 vibratoOut=(rand()&255)-128;
1857 break;
1858 case 8: // square up
1859 vibratoOut=(chan[i].vibratoPos>=32)?0:127;
1860 break;
1861 case 9: // square down
1862 vibratoOut=(chan[i].vibratoPos>=32)?0:-127;
1863 break;
1864 case 10: // half sine up
1865 vibratoOut=vibTable[chan[i].vibratoPos>>1];
1866 break;
1867 case 11: // half sine down
1868 vibratoOut=vibTable[32|(chan[i].vibratoPos>>1)];
1869 break;
1870 default: // sine
1871 vibratoOut=vibTable[chan[i].vibratoPos];
1872 break;
1873 }
1874 dispatchCmd(DivCommand(DIV_CMD_PITCH,i,chan[i].pitch+(((chan[i].vibratoDepth*vibratoOut*chan[i].vibratoFine)>>4)/15)));
1875 }
1876
1877 // delayed legato
1878 if (chan[i].legatoDelay>0) {
1879 if (--chan[i].legatoDelay<1) {
1880 chan[i].note+=chan[i].legatoTarget;
1881 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note));
1882 dispatchCmd(DivCommand(DIV_CMD_HINT_LEGATO,i,chan[i].note));
1883 chan[i].legatoDelay=-1;
1884 chan[i].legatoTarget=0;
1885 }
1886 }
1887
1888 // portamento and pitch slides
1889 if (!song.noSlidesOnFirstTick || !firstTick) {
1890 if ((chan[i].keyOn || chan[i].keyOff) && chan[i].portaSpeed>0) {
1891 if (dispatchCmd(DivCommand(DIV_CMD_NOTE_PORTA,i,chan[i].portaSpeed*(song.linearPitch==2?song.pitchSlideSpeed:1),chan[i].portaNote))==2 && chan[i].portaStop && song.targetResetsSlides) {
1892 chan[i].portaSpeed=0;
1893 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1894 chan[i].oldNote=chan[i].note;
1895 chan[i].note=chan[i].portaNote;
1896 chan[i].inPorta=false;
1897 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note));
1898 dispatchCmd(DivCommand(DIV_CMD_HINT_LEGATO,i,chan[i].note));
1899 }
1900 }
1901 }
1902
1903 // note cut
1904 if (chan[i].cut>0) {
1905 if (--chan[i].cut<1) {
1906 if (chan[i].cutType==2) {
1907 dispatchCmd(DivCommand(DIV_CMD_ENV_RELEASE,i));
1908 chan[i].releasing=true;
1909 } else {
1910 chan[i].oldNote=chan[i].note;
1911 //chan[i].note=-1;
1912 if (chan[i].inPorta && song.noteOffResetsSlides) {
1913 chan[i].keyOff=true;
1914 chan[i].keyOn=false;
1915 if (chan[i].stopOnOff) {
1916 chan[i].portaNote=-1;
1917 chan[i].portaSpeed=-1;
1918 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1919 chan[i].stopOnOff=false;
1920 }
1921 if (disCont[dispatchOfChan[i]].dispatch->keyOffAffectsPorta(dispatchChanOfChan[i])) {
1922 chan[i].portaNote=-1;
1923 chan[i].portaSpeed=-1;
1924 dispatchCmd(DivCommand(DIV_CMD_HINT_PORTA,i,CLAMP(chan[i].portaNote,-128,127),MAX(chan[i].portaSpeed,0)));
1925 }
1926 dispatchCmd(DivCommand(DIV_CMD_PRE_PORTA,i,false,0));
1927 chan[i].scheduledSlideReset=true;
1928 }
1929 if (chan[i].cutType==1) {
1930 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF_ENV,i));
1931 } else {
1932 dispatchCmd(DivCommand(DIV_CMD_NOTE_OFF,i));
1933 }
1934 chan[i].releasing=true;
1935 }
1936 }
1937 }
1938
1939 // volume cut/mute
1940 if (chan[i].volCut>0) {
1941 if (--chan[i].volCut<1) {
1942 chan[i].volume=0;
1943 dispatchCmd(DivCommand(DIV_CMD_VOLUME,i,chan[i].volume>>8));
1944 dispatchCmd(DivCommand(DIV_CMD_HINT_VOLUME,i,chan[i].volume>>8));
1945 }
1946 }
1947
1948 // arpeggio
1949 if (chan[i].resetArp) {
1950 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note));
1951 dispatchCmd(DivCommand(DIV_CMD_HINT_LEGATO,i,chan[i].note));
1952 chan[i].resetArp=false;
1953 }
1954 if (song.rowResetsArpPos && firstTick) {
1955 chan[i].arpStage=-1;
1956 }
1957 if (chan[i].arp!=0 && !chan[i].arpYield && chan[i].portaSpeed<1) {
1958 if (--chan[i].arpTicks<1) {
1959 chan[i].arpTicks=curSubSong->arpLen;
1960 chan[i].arpStage++;
1961 if (chan[i].arpStage>2) chan[i].arpStage=0;
1962 switch (chan[i].arpStage) {
1963 case 0:
1964 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note));
1965 break;
1966 case 1:
1967 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note+(chan[i].arp>>4)));
1968 break;
1969 case 2:
1970 dispatchCmd(DivCommand(DIV_CMD_LEGATO,i,chan[i].note+(chan[i].arp&15)));
1971 break;
1972 }
1973 }
1974 } else {
1975 chan[i].arpYield=false;
1976 }
1977 }
1978 }
1979 } else {
1980 // still tick the subtick counter
1981 if (--subticks<=0) {
1982 subticks=tickMult;
1983 }
1984 }
1985
1986 if (subticks==tickMult && cmdStreamInt) {
1987 if (!cmdStreamInt->tick()) {
1988 // !!!
1989 }
1990 }
1991
1992
1993 firstTick=false;
1994
1995 if (shallStop) {
1996 freelance=false;
1997 playing=false;
1998 extValuePresent=false;
1999 stepPlay=0;
2000 remainingLoops=-1;
2001 sPreview.sample=-1;
2002 sPreview.wave=-1;
2003 sPreview.pos=0;
2004 sPreview.dir=false;
2005 ret=true;
2006 shallStop=false;
2007 shallStopSched=false;
2008 // reset all chan oscs
2009 for (int i=0; i<chans; i++) {
2010 DivDispatchOscBuffer* buf=disCont[dispatchOfChan[i]].dispatch->getOscBuffer(dispatchChanOfChan[i]);
2011 if (buf!=NULL) {
2012 buf->reset();
2013 }
2014 }
2015 return ret;
2016 }
2017
2018 // system tick
2019 for (int i=0; i<song.systemLen; i++) disCont[i].dispatch->tick(subticks==tickMult);
2020
2021 if (!freelance) {
2022 if (stepPlay!=1) {
2023 if (!noAccum) {
2024 double dt=divider*tickMult;
2025 if (skipping) {
2026 dt*=(double)virtualTempoN/(double)MAX(1,virtualTempoD);
2027 }
2028 totalTicksR++;
2029 totalTicks+=1000000/dt;
2030 totalTicksOff+=fmod(1000000.0,dt);
2031 while (totalTicksOff>=dt) {
2032 totalTicksOff-=dt;
2033 totalTicks++;
2034 }
2035 }
2036 if (totalTicks>=1000000) {
2037 totalTicks-=1000000;
2038 if (totalSeconds<0x7fffffff) totalSeconds++;
2039 cmdsPerSecond=totalCmds-lastCmds;
2040 lastCmds=totalCmds;
2041 }
2042 }
2043
2044 if (consoleMode && !disableStatusOut && subticks<=1 && !skipping) fprintf(stderr,"\x1b[2K> %d:%.2d:%.2d.%.2d %.2x/%.2x:%.3d/%.3d %4dcmd/s\x1b[G",totalSeconds/3600,(totalSeconds/60)%60,totalSeconds%60,totalTicks/10000,curOrder,curSubSong->ordersLen,curRow,curSubSong->patLen,cmdsPerSecond);
2045 }
2046
2047 if (haltOn==DIV_HALT_TICK) halted=true;
2048
2049 return ret;
2050 }
2051
2052 int DivEngine::getBufferPos() {
2053 return bufferPos;
2054 }
2055
2056 void DivEngine::runMidiClock(int totalCycles) {
2057 if (freelance) return;
2058 midiClockCycles-=totalCycles;
2059 while (midiClockCycles<=0) {
2060 curMidiClock++;
2061 if (output) if (!skipping && output->midiOut!=NULL && midiOutClock) {
2062 output->midiOut->send(TAMidiMessage(TA_MIDI_CLOCK,0,0));
2063 }
2064
2065 double hl=curSubSong->hilightA;
2066 if (hl<=0.0) hl=4.0;
2067 double timeBase=curSubSong->timeBase+1;
2068 double speedSum=0;
2069 double vD=virtualTempoD;
2070 for (int i=0; i<MIN(16,speeds.len); i++) {
2071 speedSum+=speeds.val[i];
2072 }
2073 speedSum/=MAX(1,speeds.len);
2074 if (timeBase<1.0) timeBase=1.0;
2075 if (speedSum<1.0) speedSum=1.0;
2076 if (vD<1) vD=1;
2077 double bpm=((24.0*divider)/(timeBase*hl*speedSum))*(double)virtualTempoN/vD;
2078 if (bpm<1.0) bpm=1.0;
2079 int increment=got.rate/(bpm);
2080 if (increment<1) increment=1;
2081
2082 midiClockCycles+=increment;
2083 midiClockDrift+=fmod(got.rate,(double)(bpm));
2084 if (midiClockDrift>=(bpm)) {
2085 midiClockDrift-=(bpm);
2086 midiClockCycles++;
2087 }
2088 }
2089 }
2090
2091 void DivEngine::runMidiTime(int totalCycles) {
2092 if (freelance) return;
2093 if (got.rate<1) return;
2094 midiTimeCycles-=totalCycles;
2095 while (midiTimeCycles<=0) {
2096 if (curMidiTimePiece==0) {
2097 curMidiTimeCode=curMidiTime;
2098 }
2099 if (!(curMidiTimePiece&3)) curMidiTime++;
2100
2101 double frameRate=96.0;
2102 int timeRate=midiOutTimeRate;
2103 if (timeRate<1 || timeRate>4) {
2104 if (curSubSong->hz>=47.98 && curSubSong->hz<=48.02) {
2105 timeRate=1;
2106 } else if (curSubSong->hz>=49.98 && curSubSong->hz<=50.02) {
2107 timeRate=2;
2108 } else if (curSubSong->hz>=59.9 && curSubSong->hz<=60.11) {
2109 timeRate=4;
2110 } else {
2111 timeRate=4;
2112 }
2113 }
2114
2115 int hour=0;
2116 int minute=0;
2117 int second=0;
2118 int frame=0;
2119 int drop=0;
2120 int actualTime=curMidiTimeCode;
2121
2122 switch (timeRate) {
2123 case 1: // 24
2124 frameRate=96.0;
2125 hour=(actualTime/(60*60*24))%24;
2126 minute=(actualTime/(60*24))%60;
2127 second=(actualTime/24)%60;
2128 frame=actualTime%24;
2129 break;
2130 case 2: // 25
2131 frameRate=100.0;
2132 hour=(actualTime/(60*60*25))%24;
2133 minute=(actualTime/(60*25))%60;
2134 second=(actualTime/25)%60;
2135 frame=actualTime%25;
2136 break;
2137 case 3: // 29.97 (NTSC drop)
2138 frameRate=120.0*(1000.0/1001.0);
2139
2140 // drop
2141 drop=((actualTime/(30*60))-(actualTime/(30*600)))*2;
2142 actualTime+=drop;
2143
2144 hour=(actualTime/(60*60*30))%24;
2145 minute=(actualTime/(60*30))%60;
2146 second=(actualTime/30)%60;
2147 frame=actualTime%30;
2148 break;
2149 case 4: // 30 (NTSC non-drop)
2150 default:
2151 frameRate=120.0;
2152 hour=(actualTime/(60*60*30))%24;
2153 minute=(actualTime/(60*30))%60;
2154 second=(actualTime/30)%60;
2155 frame=actualTime%30;
2156 break;
2157 }
2158
2159 if (output) if (!skipping && output->midiOut!=NULL && midiOutTime) {
2160 unsigned char val=0;
2161 switch (curMidiTimePiece) {
2162 case 0:
2163 val=frame&15;
2164 break;
2165 case 1:
2166 val=frame>>4;
2167 break;
2168 case 2:
2169 val=second&15;
2170 break;
2171 case 3:
2172 val=second>>4;
2173 break;
2174 case 4:
2175 val=minute&15;
2176 break;
2177 case 5:
2178 val=minute>>4;
2179 break;
2180 case 6:
2181 val=hour&15;
2182 break;
2183 case 7:
2184 val=(hour>>4)|((timeRate-1)<<1);
2185 break;
2186 }
2187 val|=curMidiTimePiece<<4;
2188 output->midiOut->send(TAMidiMessage(TA_MIDI_MTC_FRAME,val,0));
2189 }
2190 curMidiTimePiece=(curMidiTimePiece+1)&7;
2191
2192 midiTimeCycles+=got.rate/(frameRate);
2193 midiTimeDrift+=fmod(got.rate,(double)(frameRate));
2194 if (midiTimeDrift>=(frameRate)) {
2195 midiTimeDrift-=(frameRate);
2196 midiTimeCycles++;
2197 }
2198 }
2199 }
2200
2201 void _runDispatch1(void* d) {
2202 }
2203
2204 void _runDispatch2(void* d) {
2205
2206 }
2207
2208 void DivEngine::nextBuf(float** in, float** out, int inChans, int outChans, unsigned int size) {
2209 lastNBIns=inChans;
2210 lastNBOuts=outChans;
2211 lastNBSize=size;
2212
2213 if (!size) {
2214 logW("nextBuf called with size 0!");
2215 return;
2216 }
2217 lastLoopPos=-1;
2218
2219 if (out!=NULL) {
2220 for (int i=0; i<outChans; i++) {
2221 memset(out[i],0,size*sizeof(float));
2222 }
2223 }
2224
2225 if (softLocked) {
2226 if (!isBusy.try_lock()) {
2227 logV("audio is soft-locked (%d)",softLockCount++);
2228 return;
2229 }
2230 } else {
2231 isBusy.lock();
2232 }
2233 got.bufsize=size;
2234
2235 std::chrono::steady_clock::time_point ts_processBegin=std::chrono::steady_clock::now();
2236
2237 if (renderPool==NULL) {
2238 unsigned int howManyThreads=song.systemLen;
2239 if (howManyThreads<2) howManyThreads=0;
2240 if (howManyThreads>renderPoolThreads) howManyThreads=renderPoolThreads;
2241 renderPool=new DivWorkPool(howManyThreads);
2242 }
2243
2244 // process MIDI events (TODO: everything)
2245 if (output) if (output->midiIn) while (!output->midiIn->queue.empty()) {
2246 TAMidiMessage& msg=output->midiIn->queue.front();
2247 if (midiDebug) {
2248 if (msg.type==TA_MIDI_SYSEX) {
2249 logD("MIDI debug: %.2X SysEx",msg.type);
2250 } else {
2251 logD("MIDI debug: %.2X %.2X %.2X",msg.type,msg.data[0],msg.data[1]);
2252 }
2253 }
2254 int ins=-1;
2255 if ((ins=midiCallback(msg))!=-3) {
2256 int chan=msg.type&15;
2257 switch (msg.type&0xf0) {
2258 case TA_MIDI_NOTE_OFF: {
2259 if (midiIsDirect) {
2260 if (chan<0 || chan>=chans) break;
2261 pendingNotes.push_back(DivNoteEvent(chan,-1,-1,-1,false,false,true));
2262 } else {
2263 autoNoteOff(msg.type&15,msg.data[0]-12,msg.data[1]);
2264 }
2265 if (!playing) {
2266 reset();
2267 freelance=true;
2268 playing=true;
2269 }
2270 break;
2271 }
2272 case TA_MIDI_NOTE_ON: {
2273 if (msg.data[1]==0) {
2274 if (midiIsDirect) {
2275 if (chan<0 || chan>=chans) break;
2276 pendingNotes.push_back(DivNoteEvent(chan,-1,-1,-1,false,false,true));
2277 } else {
2278 autoNoteOff(msg.type&15,msg.data[0]-12,msg.data[1]);
2279 }
2280 } else {
2281 if (midiIsDirect) {
2282 if (chan<0 || chan>=chans) break;
2283 pendingNotes.push_back(DivNoteEvent(chan,ins,msg.data[0]-12,msg.data[1],true,false,true));
2284 } else {
2285 autoNoteOn(msg.type&15,ins,msg.data[0]-12,msg.data[1]);
2286 }
2287 }
2288 break;
2289 }
2290 case TA_MIDI_PROGRAM: {
2291 if (midiIsDirect && midiIsDirectProgram) {
2292 pendingNotes.push_back(DivNoteEvent(chan,msg.data[0],0,0,false,true,true));
2293 }
2294 break;
2295 }
2296 }
2297 } else if (midiDebug) {
2298 logD("callback wants ignore");
2299 }
2300 //logD("%.2x",msg.type);
2301 output->midiIn->queue.pop();
2302 }
2303
2304 // process sample/wave preview
2305 if (((sPreview.sample>=0 && sPreview.sample<(int)song.sample.size()) || (sPreview.wave>=0 && sPreview.wave<(int)song.wave.size())) && !exporting) {
2306 unsigned int samp_bbOff=0;
2307 unsigned int prevAvail=blip_samples_avail(samp_bb);
2308 if (prevAvail>size) prevAvail=size;
2309 if (prevAvail>0) {
2310 blip_read_samples(samp_bb,samp_bbOut,prevAvail,0);
2311 samp_bbOff=prevAvail;
2312 }
2313 size_t prevtotal=blip_clocks_needed(samp_bb,size-prevAvail);
2314
2315 if (sPreview.sample>=0 && sPreview.sample<(int)song.sample.size()) {
2316 DivSample* s=song.sample[sPreview.sample];
2317
2318 for (size_t i=0; i<prevtotal; i++) {
2319 if (sPreview.pos>=(int)s->samples || (sPreview.pEnd>=0 && sPreview.pos>=sPreview.pEnd)) {
2320 samp_temp=0;
2321 } else {
2322 samp_temp=s->data16[sPreview.pos];
2323 if (--sPreview.posSub<=0) {
2324 sPreview.posSub=sPreview.rateMul;
2325 if (sPreview.dir) {
2326 sPreview.pos--;
2327 } else {
2328 sPreview.pos++;
2329 }
2330 }
2331 }
2332 blip_add_delta(samp_bb,i,samp_temp-samp_prevSample);
2333 samp_prevSample=samp_temp;
2334
2335 if (sPreview.dir) { // backward
2336 if (sPreview.pos<s->loopStart || (sPreview.pBegin>=0 && sPreview.pos<sPreview.pBegin)) {
2337 if (s->isLoopable() && sPreview.pos<s->loopEnd) {
2338 switch (s->loopMode) {
2339 case DivSampleLoopMode::DIV_SAMPLE_LOOP_FORWARD:
2340 sPreview.pos=s->loopStart;
2341 sPreview.dir=false;
2342 break;
2343 case DivSampleLoopMode::DIV_SAMPLE_LOOP_BACKWARD:
2344 sPreview.pos=s->loopEnd-1;
2345 sPreview.dir=true;
2346 break;
2347 case DivSampleLoopMode::DIV_SAMPLE_LOOP_PINGPONG:
2348 sPreview.pos=s->loopStart;
2349 sPreview.dir=false;
2350 break;
2351 default:
2352 break;
2353 }
2354 }
2355 }
2356 } else { // forward
2357 if (sPreview.pos>=s->loopEnd || (sPreview.pEnd>=0 && sPreview.pos>=sPreview.pEnd)) {
2358 if (s->isLoopable() && sPreview.pos>=s->loopStart) {
2359 switch (s->loopMode) {
2360 case DivSampleLoopMode::DIV_SAMPLE_LOOP_FORWARD:
2361 sPreview.pos=s->loopStart;
2362 sPreview.dir=false;
2363 break;
2364 case DivSampleLoopMode::DIV_SAMPLE_LOOP_BACKWARD:
2365 sPreview.pos=s->loopEnd-1;
2366 sPreview.dir=true;
2367 break;
2368 case DivSampleLoopMode::DIV_SAMPLE_LOOP_PINGPONG:
2369 sPreview.pos=s->loopEnd-1;
2370 sPreview.dir=true;
2371 break;
2372 default:
2373 break;
2374 }
2375 }
2376 }
2377 }
2378 }
2379 if (sPreview.dir) { // backward
2380 if (sPreview.pos<=s->loopStart || (sPreview.pBegin>=0 && sPreview.pos<=sPreview.pBegin)) {
2381 if (s->isLoopable() && sPreview.pos>=s->loopStart) {
2382 switch (s->loopMode) {
2383 case DivSampleLoopMode::DIV_SAMPLE_LOOP_FORWARD:
2384 sPreview.pos=s->loopStart;
2385 sPreview.dir=false;
2386 break;
2387 case DivSampleLoopMode::DIV_SAMPLE_LOOP_BACKWARD:
2388 sPreview.pos=s->loopEnd-1;
2389 sPreview.dir=true;
2390 break;
2391 case DivSampleLoopMode::DIV_SAMPLE_LOOP_PINGPONG:
2392 sPreview.pos=s->loopStart;
2393 sPreview.dir=false;
2394 break;
2395 default:
2396 break;
2397 }
2398 } else if (sPreview.pos<0) {
2399 sPreview.sample=-1;
2400 }
2401 }
2402 } else { // forward
2403 if (sPreview.pos>=s->loopEnd || (sPreview.pEnd>=0 && sPreview.pos>=sPreview.pEnd)) {
2404 if (s->isLoopable() && sPreview.pos>=s->loopStart) {
2405 switch (s->loopMode) {
2406 case DivSampleLoopMode::DIV_SAMPLE_LOOP_FORWARD:
2407 sPreview.pos=s->loopStart;
2408 sPreview.dir=false;
2409 break;
2410 case DivSampleLoopMode::DIV_SAMPLE_LOOP_BACKWARD:
2411 sPreview.pos=s->loopEnd-1;
2412 sPreview.dir=true;
2413 break;
2414 case DivSampleLoopMode::DIV_SAMPLE_LOOP_PINGPONG:
2415 sPreview.pos=s->loopEnd-1;
2416 sPreview.dir=true;
2417 break;
2418 default:
2419 break;
2420 }
2421 } else if (sPreview.pos>=(int)s->samples) {
2422 sPreview.sample=-1;
2423 }
2424 }
2425 }
2426 } else if (sPreview.wave>=0 && sPreview.wave<(int)song.wave.size()) {
2427 DivWavetable* wave=song.wave[sPreview.wave];
2428 for (size_t i=0; i<prevtotal; i++) {
2429 if (wave->max<=0) {
2430 samp_temp=0;
2431 } else {
2432 samp_temp=((MIN(wave->data[sPreview.pos],wave->max)<<14)/wave->max)-8192;
2433 }
2434 if (--sPreview.posSub<=0) {
2435 sPreview.posSub=sPreview.rateMul;
2436 if (++sPreview.pos>=wave->len) {
2437 sPreview.pos=0;
2438 }
2439 }
2440 blip_add_delta(samp_bb,i,samp_temp-samp_prevSample);
2441 samp_prevSample=samp_temp;
2442 }
2443 }
2444
2445 blip_end_frame(samp_bb,prevtotal);
2446 blip_read_samples(samp_bb,samp_bbOut+samp_bbOff,size-samp_bbOff,0);
2447 } else {
2448 memset(samp_bbOut,0,size*sizeof(short));
2449 }
2450
2451 // process audio
2452 bool mustPlay=playing && !halted;
2453 if (mustPlay) {
2454 // logic starts here
2455 for (int i=0; i<song.systemLen; i++) {
2456 disCont[i].runPos=0;
2457 }
2458
2459 if (metroTickLen<size) {
2460 if (metroTick!=NULL) delete[] metroTick;
2461 metroTick=new unsigned char[size];
2462 metroTickLen=size;
2463 }
2464
2465 memset(metroTick,0,size);
2466
2467 int attempts=0;
2468 int runLeftG=size;
2469 while (++attempts<(int)size) {
2470 // -1. set bufferPos
2471 bufferPos=size-runLeftG;
2472
2473 // 0. check if we've halted
2474 if (halted) break;
2475 // 1. check whether we are done with all buffers
2476 if (runLeftG<=0) break;
2477
2478 // 2. check whether we gonna tick
2479 if (cycles<=0) {
2480 // we have to tick
2481 if (nextTick()) {
2482 /*totalTicks=0;
2483 totalSeconds=0;*/
2484 lastLoopPos=size-runLeftG;
2485 logD("last loop pos: %d for a size of %d and runLeftG of %d",lastLoopPos,size,runLeftG);
2486 totalLoops++;
2487 if (remainingLoops>0) {
2488 remainingLoops--;
2489 if (!remainingLoops) {
2490 logI("end of song!");
2491 remainingLoops=-1;
2492 playing=false;
2493 freelance=false;
2494 extValuePresent=false;
2495 break;
2496 }
2497 }
2498 }
2499 if (pendingMetroTick) {
2500 unsigned int realPos=size-runLeftG;
2501 if (realPos>=size) realPos=size-1;
2502 metroTick[realPos]=pendingMetroTick;
2503 pendingMetroTick=0;
2504 }
2505 } else {
2506 // 3. run MIDI clock
2507 int midiTotal=MIN(cycles,runLeftG);
2508 runMidiClock(midiTotal);
2509
2510 // 4. run MIDI timecode
2511 runMidiTime(midiTotal);
2512
2513 // 5. tick the clock and fill buffers as needed
2514 if (cycles<runLeftG) {
2515 // run until the end of this tick
2516 for (int i=0; i<song.systemLen; i++) {
2517 disCont[i].cycles=cycles;
2518 disCont[i].size=size;
2519 renderPool->push([](void* d) {
2520 DivDispatchContainer* dc=(DivDispatchContainer*)d;
2521
2522 int lastAvail=blip_samples_avail(dc->bb[0]);
2523 if (lastAvail>0) {
2524 if (lastAvail>=dc->cycles) {
2525 dc->flush(dc->runPos,dc->cycles);
2526 dc->runPos+=dc->cycles;
2527 return;
2528 } else {
2529 dc->flush(dc->runPos,lastAvail);
2530 dc->runPos+=lastAvail;
2531 dc->cycles-=lastAvail;
2532 }
2533 }
2534
2535 int total=blip_clocks_needed(dc->bb[0],dc->cycles);
2536 if (total>(int)dc->bbInLen) {
2537 logD("growing dispatch %p bbIn to %d",(void*)dc,total+256);
2538 dc->grow(total+256);
2539 }
2540 dc->acquire(total);
2541 dc->fillBuf(total,dc->runPos,dc->cycles);
2542 dc->runPos+=dc->cycles;
2543 },&disCont[i]);
2544 }
2545 renderPool->wait();
2546 runLeftG-=cycles;
2547 cycles=0;
2548 } else {
2549 // run until the end of this audio buffer
2550 cycles-=runLeftG;
2551 for (int i=0; i<song.systemLen; i++) {
2552 disCont[i].cycles=runLeftG;
2553 renderPool->push([](void* d) {
2554 DivDispatchContainer* dc=(DivDispatchContainer*)d;
2555
2556 int lastAvail=blip_samples_avail(dc->bb[0]);
2557 if (lastAvail>0) {
2558 if (lastAvail>=dc->cycles) {
2559 dc->flush(dc->runPos,dc->cycles);
2560 dc->runPos+=dc->cycles;
2561 return;
2562 } else {
2563 dc->flush(dc->runPos,lastAvail);
2564 dc->runPos+=lastAvail;
2565 dc->cycles-=lastAvail;
2566 }
2567 }
2568
2569 int total=blip_clocks_needed(dc->bb[0],dc->cycles);
2570 if (total>(int)dc->bbInLen) {
2571 logD("growing dispatch %p bbIn to %d",(void*)dc,total+256);
2572 dc->grow(total+256);
2573 }
2574 dc->acquire(total);
2575 dc->fillBuf(total,dc->runPos,dc->cycles);
2576 },&disCont[i]);
2577 }
2578 runLeftG=0;
2579 renderPool->wait();
2580 }
2581 }
2582 }
2583
2584 //logD("attempts: %d",attempts);
2585 if (attempts>=(int)(size+10)) {
2586 logE("hang detected! stopping! at %d seconds %d micro (%d>=%d)",totalSeconds,totalTicks,attempts,(int)size);
2587 freelance=false;
2588 playing=false;
2589 extValuePresent=false;
2590 }
2591 totalProcessed=size-runLeftG;
2592
2593 for (int i=0; i<song.systemLen; i++) {
2594 if (size<disCont[i].lastAvail) {
2595 logW("%d: size<lastAvail! %d<%d",i,size,disCont[i].lastAvail);
2596 continue;
2597 }
2598 disCont[i].size=size;
2599 /*
2600 renderPool->push([](void* d) {
2601 DivDispatchContainer* dc=(DivDispatchContainer*)d;
2602 dc->fillBuf(dc->runtotal,dc->lastAvail,dc->size-dc->lastAvail);
2603 },&disCont[i]);*/
2604 }
2605 renderPool->wait();
2606 }
2607
2608 // process metronome
2609 if (metroBufLen<size || metroBuf==NULL) {
2610 if (metroBuf!=NULL) delete[] metroBuf;
2611 metroBuf=new float[size];
2612 metroBufLen=size;
2613 }
2614
2615 memset(metroBuf,0,metroBufLen*sizeof(float));
2616
2617 if (mustPlay && metronome && !freelance) {
2618 for (size_t i=0; i<size; i++) {
2619 if (metroTick[i]) {
2620 if (metroTick[i]==2) {
2621 metroFreq=1400/got.rate;
2622 } else {
2623 metroFreq=1050/got.rate;
2624 }
2625 metroPos=0;
2626 metroAmp=0.7f;
2627 }
2628 if (metroAmp>0.0f) {
2629 for (int j=0; j<outChans; j++) {
2630 metroBuf[i]=(sin(metroPos*2*M_PI))*metroAmp*metroVol;
2631 }
2632 }
2633 metroAmp-=0.0003f;
2634 if (metroAmp<0.0f) metroAmp=0.0f;
2635 metroPos+=metroFreq;
2636 while (metroPos>=1) metroPos--;
2637 }
2638 }
2639
2640 // resolve patchbay
2641 for (unsigned int i: song.patchbay) {
2642 const unsigned short srcPort=i>>16;
2643 const unsigned short destPort=i&0xffff;
2644
2645 const unsigned short srcPortSet=srcPort>>4;
2646 const unsigned short destPortSet=destPort>>4;
2647 const unsigned char srcSubPort=srcPort&15;
2648 const unsigned char destSubPort=destPort&15;
2649
2650 // null portset
2651 if (destPortSet==0xfff) continue;
2652
2653 // system outputs
2654 if (destPortSet==0x000) {
2655 if (destSubPort>=outChans) continue;
2656
2657 // chip outputs
2658 if (srcPortSet<song.systemLen && playing && !halted) {
2659 if (srcSubPort<disCont[srcPortSet].dispatch->getOutputCount()) {
2660 float vol=song.systemVol[srcPortSet]*disCont[srcPortSet].dispatch->getPostAmp()*song.masterVol;
2661
2662 switch (destSubPort&3) {
2663 case 0:
2664 vol*=MIN(1.0f,1.0f-song.systemPan[srcPortSet])*MIN(1.0f,1.0f+song.systemPanFR[srcPortSet]);
2665 break;
2666 case 1:
2667 vol*=MIN(1.0f,1.0f+song.systemPan[srcPortSet])*MIN(1.0f,1.0f+song.systemPanFR[srcPortSet]);
2668 break;
2669 case 2:
2670 vol*=MIN(1.0f,1.0f-song.systemPan[srcPortSet])*MIN(1.0f,1.0f-song.systemPanFR[srcPortSet]);
2671 break;
2672 case 3:
2673 vol*=MIN(1.0f,1.0f+song.systemPan[srcPortSet])*MIN(1.0f,1.0f-song.systemPanFR[srcPortSet]);
2674 break;
2675 }
2676
2677 for (size_t j=0; j<size; j++) {
2678 out[destSubPort][j]+=((float)disCont[srcPortSet].bbOut[srcSubPort][j]/32768.0)*vol;
2679 }
2680 }
2681 } else if (srcPortSet==0xffd) {
2682 // sample preview
2683 for (size_t j=0; j<size; j++) {
2684 out[destSubPort][j]+=previewVol*(samp_bbOut[j]/32768.0);
2685 }
2686 } else if (srcPortSet==0xffe && playing && !halted) {
2687 // metronome
2688 for (size_t j=0; j<size; j++) {
2689 out[destSubPort][j]+=metroBuf[j];
2690 }
2691 }
2692
2693 // nothing/invalid
2694 }
2695
2696 // nothing/invalid
2697 }
2698
2699 // dump to oscillator buffer
2700 for (unsigned int i=0; i<size; i++) {
2701 for (int j=0; j<outChans; j++) {
2702 if (oscBuf[j]==NULL) continue;
2703 oscBuf[j][oscWritePos]=out[j][i];
2704 }
2705 if (++oscWritePos>=32768) oscWritePos=0;
2706 }
2707 oscSize=size;
2708
2709 // force mono audio (if enabled)
2710 if (forceMono && outChans>1) {
2711 for (size_t i=0; i<size; i++) {
2712 float chanSum=out[0][i];
2713 for (int j=1; j<outChans; j++) {
2714 chanSum+=out[j][i];
2715 }
2716 out[0][i]=chanSum/outChans;
2717 for (int j=1; j<outChans; j++) {
2718 out[j][i]=out[0][i];
2719 }
2720 }
2721 }
2722
2723 // clamp output (if enabled)
2724 if (clampSamples) {
2725 for (size_t i=0; i<size; i++) {
2726 for (int j=0; j<outChans; j++) {
2727 if (out[j][i]<-1.0) out[j][i]=-1.0;
2728 if (out[j][i]>1.0) out[j][i]=1.0;
2729 }
2730 }
2731 }
2732 isBusy.unlock();
2733
2734 std::chrono::steady_clock::time_point ts_processEnd=std::chrono::steady_clock::now();
2735
2736 processTime=std::chrono::duration_cast<std::chrono::nanoseconds>(ts_processEnd-ts_processBegin).count();
2737 }