Debian Codegraph @

src/engine/export/tiuna.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 "tiuna.h"
21 #include "../engine.h"
22 #include "../ta-log.h"
23 #include <fmt/printf.h>
24 #include <algorithm>
25 #include <map>
26 #include <tuple>
27 #include <vector>
28
29 struct TiunaNew {
30 short pitch;
31 signed char ins;
32 signed char vol;
33 short sync;
34 TiunaNew():
35 pitch(-1),
36 ins(-1),
37 vol(-1),
38 sync(-1) {}
39 };
40
41 struct TiunaLast {
42 short pitch;
43 signed char ins;
44 signed char vol;
45 int tick;
46 bool forcePitch;
47 TiunaLast():
48 pitch(0),
49 ins(0),
50 vol(0),
51 tick(1),
52 forcePitch(true) {}
53 };
54
55 struct TiunaCmd {
56 signed char pitchChange;
57 short pitchSet;
58 signed char ins;
59 signed char vol;
60 short sync;
61 short wait;
62 TiunaCmd():
63 pitchChange(-1),
64 pitchSet(-1),
65 ins(-1),
66 vol(-1),
67 sync(-1),
68 wait(-1) {}
69 };
70
71 struct TiunaBytes {
72 unsigned char ch;
73 int ticks;
74 unsigned char size;
75 unsigned char buf[16];
76 friend bool operator==(const TiunaBytes& l, const TiunaBytes& r) {
77 if (l.size!=r.size) return false;
78 if (l.ticks!=r.ticks) return false;
79 return memcmp(l.buf,r.buf,l.size)==0;
80 }
81 TiunaBytes(unsigned char c, int t, unsigned char s, std::initializer_list<unsigned char> b):
82 ch(c),
83 ticks(t),
84 size(s) {
85 // because C++14 does not support data() on initializer_list
86 unsigned char p=0;
87 for (unsigned char i: b) {
88 buf[p++]=i;
89 }
90 }
91 TiunaBytes():
92 ch(0),
93 ticks(0),
94 size(0) {
95 memset(buf,0,16);
96 }
97 };
98
99 struct TiunaMatch {
100 int pos;
101 int endPos;
102 int size;
103 int id;
104 TiunaMatch(int p, int ep, int s, int _i):
105 pos(p),
106 endPos(ep),
107 size(s),
108 id(_i) {}
109 TiunaMatch():
110 pos(0),
111 endPos(0),
112 size(0),
113 id(0) {}
114 };
115
116 struct TiunaMatches {
117 int bytesSaved;
118 int length;
119 int ticks;
120 std::vector<int> pos;
121 TiunaMatches():
122 bytesSaved(INT32_MIN),
123 length(0),
124 ticks(0) {}
125 };
126
127 static void writeCmd(std::vector<TiunaBytes>& cmds, TiunaCmd& cmd, unsigned char ch, int& lastWait, int fromTick, int toTick) {
128 while (fromTick<toTick) {
129 int val=MIN(toTick-fromTick,256);
130 if (lastWait!=val) {
131 cmd.wait=val;
132 lastWait=val;
133 }
134 TiunaBytes nbuf;
135 unsigned char vcw1=0x80;
136 unsigned char vcw2=0;
137 unsigned char vcwLen=0;
138 unsigned char nlen=0;
139 nbuf.ch=ch;
140 nbuf.ticks=val;
141 if (cmd.sync>=0) {
142 nbuf.buf[nlen++]=0b00111110;
143 nbuf.buf[nlen++]=cmd.sync;
144 }
145 if (cmd.wait>=17) {
146 nbuf.buf[nlen++]=0b00111111;
147 nbuf.buf[nlen++]=cmd.wait-1;
148 }
149 if (cmd.pitchChange>=0) {
150 nbuf.buf[nlen++]=0b01000000|cmd.pitchChange;
151 }
152 if (cmd.pitchSet>=0) {
153 nbuf.buf[nlen++]=0b01100000|(cmd.pitchSet>>8);
154 nbuf.buf[nlen++]=cmd.pitchSet&0xff;
155 }
156 if (cmd.vol>=1) {
157 vcw1|=0x40|cmd.vol;
158 vcwLen++;
159 }
160 if (cmd.ins>=0) {
161 vcw1|=0x20;
162 if (vcwLen==0) vcw1|=cmd.ins;
163 else vcw2=cmd.ins;
164 vcwLen++;
165 }
166 if (cmd.wait>=1 && cmd.wait<17) {
167 unsigned char val=cmd.wait-1;
168 vcw1|=0x10;
169 if (vcwLen==0) vcw1|=val;
170 else if (vcwLen==1) vcw2=val;
171 else vcw2|=(val<<4);
172 vcwLen++;
173 }
174 nbuf.buf[nlen++]=vcw1;
175 if (vcwLen>=2) nbuf.buf[nlen++]=vcw2;
176 nbuf.size=nlen;
177 cmds.push_back(nbuf);
178 cmd=TiunaCmd();
179 fromTick+=val;
180 }
181 }
182
183 void DivExportTiuna::run() {
184 int loopOrder, loopOrderRow, loopEnd;
185 int tick=0;
186 SafeWriter* w;
187 std::map<int,TiunaCmd> allCmds[2];
188
189 // config
190 String baseLabel=conf.getString("baseLabel","twin");
191 int firstBankSize=conf.getInt("firstBankSize",1024);
192 int otherBankSize=conf.getInt("otherBankSize",4096-48);
193 int tiaIdx=conf.getInt("sysToExport",-1);
194
195 e->stop();
196 e->repeatPattern=false;
197 e->shallStop=false;
198 e->setOrder(0);
199 e->synchronizedSoft([&]() {
200 // determine loop point
201 // bool stopped=false;
202 loopOrder=0;
203 loopOrderRow=0;
204 loopEnd=0;
205 e->walkSong(loopOrder,loopOrderRow,loopEnd);
206 logAppendf("loop point: %d %d",loopOrder,loopOrderRow);
207
208 w=new SafeWriter;
209 w->init();
210
211 if (tiaIdx<0 || tiaIdx>=e->song.systemLen) {
212 tiaIdx=-1;
213 for (int i=0; i<e->song.systemLen; i++) {
214 if (e->song.system[i]==DIV_SYSTEM_TIA) {
215 tiaIdx=i;
216 break;
217 }
218 }
219 if (tiaIdx<0) {
220 logAppend("ERROR: selected TIA system not found");
221 failed=true;
222 running=false;
223 return;
224 }
225 } else if (e->song.system[tiaIdx]!=DIV_SYSTEM_TIA) {
226 logAppend("ERROR: selected chip is not a TIA!");
227 failed=true;
228 running=false;
229 return;
230 }
231
232 e->disCont[tiaIdx].dispatch->toggleRegisterDump(true);
233
234 // write patterns
235 // bool writeLoop=false;
236 logAppend("recording sequence...");
237 bool done=false;
238 e->playSub(false);
239
240 // int loopTick=-1;
241 TiunaLast last[2];
242 TiunaNew news[2];
243 while (!done) {
244 // TODO implement loop
245 // if (loopTick<0 && loopOrder==curOrder && loopOrderRow==curRow
246 // && (ticks-((tempoAccum+virtualTempoN)/virtualTempoD))<=0
247 // ) {
248 // writeLoop=true;
249 // loopTick=tick;
250 // // invalidate last register state so it always force an absolute write after loop
251 // for (int i=0; i<2; i++) {
252 // last[i]=TiunaLast();
253 // last[i].pitch=-1;
254 // last[i].ins=-1;
255 // last[i].vol=-1;
256 // }
257 // }
258 if (e->nextTick(false,true) || !e->playing) {
259 // stopped=!playing;
260 done=true;
261 break;
262 }
263 for (int i=0; i<2; i++) {
264 news[i]=TiunaNew();
265 }
266 // get register dumps
267 std::vector<DivRegWrite>& writes=e->disCont[tiaIdx].dispatch->getRegisterWrites();
268 for (const DivRegWrite& i: writes) {
269 switch (i.addr) {
270 case 0xfffe0000:
271 case 0xfffe0001:
272 news[i.addr&1].pitch=i.val;
273 break;
274 case 0xfffe0002:
275 news[0].sync=i.val;
276 break;
277 case 0x15:
278 case 0x16:
279 news[i.addr-0x15].ins=i.val;
280 break;
281 case 0x19:
282 case 0x1a:
283 news[i.addr-0x19].vol=i.val;
284 break;
285 default: break;
286 }
287 }
288 writes.clear();
289 // collect changes
290 for (int i=0; i<2; i++) {
291 TiunaCmd cmds;
292 bool hasCmd=false;
293 if (news[i].pitch>=0 && (last[i].forcePitch || news[i].pitch!=last[i].pitch)) {
294 int dt=news[i].pitch-last[i].pitch;
295 if (!last[i].forcePitch && abs(dt)<=16) {
296 if (dt<0) cmds.pitchChange=15-dt;
297 else cmds.pitchChange=dt-1;
298 }
299 else cmds.pitchSet=news[i].pitch;
300 last[i].pitch=news[i].pitch;
301 last[i].forcePitch=false;
302 hasCmd=true;
303 }
304 if (news[i].ins>=0 && news[i].ins!=last[i].ins) {
305 cmds.ins=news[i].ins;
306 last[i].ins=news[i].ins;
307 hasCmd=true;
308 }
309 if (news[i].vol>=0 && news[i].vol!=last[i].vol) {
310 cmds.vol=(news[i].vol-last[i].vol)&0xf;
311 last[i].vol=news[i].vol;
312 hasCmd=true;
313 }
314 if (news[i].sync>=0) {
315 cmds.sync=news[i].sync;
316 hasCmd=true;
317 }
318 if (hasCmd) allCmds[i][tick]=cmds;
319 }
320 e->cmdStream.clear();
321 tick++;
322 }
323 for (int i=0; i<e->song.systemLen; i++) {
324 e->disCont[i].dispatch->getRegisterWrites().clear();
325 e->disCont[i].dispatch->toggleRegisterDump(false);
326 }
327
328 e->remainingLoops=-1;
329 e->playing=false;
330 e->freelance=false;
331 e->extValuePresent=false;
332 });
333
334 if (failed) return;
335
336 // render commands
337 logAppend("rendering commands...");
338 std::vector<TiunaBytes> renderedCmds;
339 w->writeText(fmt::format(
340 "; Generated by Furnace " DIV_VERSION "\n"
341 "; Name: {}\n"
342 "; Author: {}\n"
343 "; Album: {}\n"
344 "; Subsong #{}: {}\n\n",
345 e->song.name,e->song.author,e->song.category,e->curSubSongIndex+1,e->curSubSong->name
346 ));
347 for (int i=0; i<2; i++) {
348 TiunaCmd lastCmd;
349 int lastTick=0;
350 int lastWait=0;
351 // bool looped=false;
352 for (auto& kv: allCmds[i]) {
353 // if (!looped && !stopped && loopTick>=0 && kv.first>=loopTick) {
354 // writeCmd(w,&lastCmd,&lastWait,loopTick-lastTick);
355 // w->writeText(".loop\n");
356 // lastTick=loopTick;
357 // looped=true;
358 // }
359 writeCmd(renderedCmds,lastCmd,i,lastWait,lastTick,kv.first);
360 lastTick=kv.first;
361 lastCmd=kv.second;
362 }
363 writeCmd(renderedCmds,lastCmd,i,lastWait,lastTick,tick);
364 // if (stopped || loopTick<0) w->writeText(".loop\n db 0\n");
365 }
366 // compress commands
367 std::vector<TiunaMatch> confirmedMatches;
368 std::vector<int> callTicks;
369 int cmId=0;
370 int cmdSize=renderedCmds.size();
371 bool* processed=new bool[cmdSize];
372 memset(processed,0,cmdSize*sizeof(bool));
373 logAppend("compressing! this may take a while.");
374 int maxCmId=(MAX(firstBankSize/1024,1))*256;
375 int lastMaxPMVal=100000;
376 logAppendf("max cmId: %d",maxCmId);
377 logAppendf("commands: %d",cmdSize);
378 while (firstBankSize>768 && cmId<maxCmId) {
379 if (mustAbort) {
380 logAppend("aborted!");
381 failed=true;
382 running=false;
383 delete[] processed;
384 return;
385 }
386
387 float theOtherSide=pow(1.0/float(MAX(1,lastMaxPMVal)),0.2)*0.98;
388 progress[0].amount=theOtherSide+(1.0-theOtherSide)*((float)cmId/(float)maxCmId);
389
390 logAppendf("start CM %04x...",cmId);
391 std::map<int,TiunaMatches> potentialMatches;
392 for (int i=0; i<cmdSize-1;) {
393 // continue and skip if it's part of previous confirmed matches
394 while (i<cmdSize-1 && processed[i]) i++;
395 if (i>=cmdSize-1) break;
396 progress[1].amount=(float)i/(float)(cmdSize-1);
397 std::vector<TiunaMatch> match;
398 int ch=renderedCmds[i].ch;
399 for (int j=i+1; j<cmdSize;) {
400 if (processed[i]) break;
401 //while (j<cmdSize && processed[i]) j++;
402 if (j>=cmdSize) break;
403 int k=0;
404 int ticks=0;
405 int size=0;
406 while (
407 (i+k)<j && (i+k)<cmdSize && (j+k)<cmdSize &&
408 (ticks+renderedCmds[i+k].ticks)<=256 &&
409 // match runs can't cross channels
410 // as channel end command would be insterted there later
411 renderedCmds[i+k].ch==ch &&
412 renderedCmds[j+k].ch==ch &&
413 renderedCmds[i+k]==renderedCmds[j+k] &&
414 !processed[i+k] && !processed[j+k]
415 ) {
416 ticks+=renderedCmds[i+k].ticks;
417 size+=renderedCmds[i+k].size;
418 k++;
419 }
420 if (size>2) match.push_back(TiunaMatch(j,j+k,size,0));
421 if (k==0) k++;
422 j+=k;
423 }
424 if (match.empty()) {
425 i++;
426 continue;
427 }
428 // find a length that results in most bytes saved
429 TiunaMatches matches;
430 int curSize=0;
431 int curLength=1;
432 int curTicks=0;
433 while (true) {
434 int bytesSaved=-4;
435 bool found=false;
436 for (const TiunaMatch& j: match) {
437 if ((j.endPos-j.pos)>=curLength) {
438 if (!found) {
439 found=true;
440 curSize+=renderedCmds[i+curLength-1].size;
441 curTicks+=renderedCmds[i+curLength-1].ticks;
442 }
443 bytesSaved+=curSize-2;
444 }
445 }
446 if (!found) break;
447 if (bytesSaved>matches.bytesSaved) {
448 matches.length=curLength;
449 matches.bytesSaved=bytesSaved;
450 matches.ticks=curTicks;
451 }
452 curLength++;
453 }
454 if (matches.bytesSaved>0) {
455 matches.pos.push_back(i);
456 for (const TiunaMatch& j: match) {
457 if ((j.endPos-j.pos)>=matches.length) {
458 matches.pos.push_back(j.pos);
459 }
460 }
461 potentialMatches[i]=matches;
462 }
463 i++;
464 }
465 if (potentialMatches.empty()) {
466 logAppend("potentialMatches is empty");
467 break;
468 }
469 int maxPMIdx=0;
470 int maxPMVal=0;
471 for (const auto& i: potentialMatches) {
472 if (i.second.bytesSaved>maxPMVal) {
473 maxPMVal=i.second.bytesSaved;
474 maxPMIdx=i.first;
475 }
476 }
477 int maxPMLen=potentialMatches[maxPMIdx].length;
478 for (const int i: potentialMatches[maxPMIdx].pos) {
479 confirmedMatches.push_back({i,i+maxPMLen,0,cmId});
480 memset(processed+i,1,maxPMLen);
481 //std::fill(processed.begin()+i,processed.begin()+(i+maxPMLen),true);
482 }
483 callTicks.push_back(potentialMatches[maxPMIdx].ticks);
484 logAppendf("CM %04x added: pos=%d,len=%d,matches=%d,saved=%d",cmId,maxPMIdx,maxPMLen,potentialMatches[maxPMIdx].pos.size(),maxPMVal);
485 lastMaxPMVal=maxPMVal;
486 cmId++;
487 }
488 progress[0].amount=1.0f;
489 progress[1].amount=1.0f;
490 logAppend("generating data...");
491 delete[] processed;
492 std::sort(confirmedMatches.begin(),confirmedMatches.end(),[](const TiunaMatch& l, const TiunaMatch& r){
493 return l.pos<r.pos;
494 });
495 // ignore last call IDs >256 that don't fill up a page
496 // as they tends to increase the final size due to page alignment
497 int cmIdLen=cmId>256?(cmId&~255):cmId;
498 // overlap check
499 for (int i=1; i<(int)confirmedMatches.size(); i++) {
500 if (confirmedMatches[i-1].endPos<=confirmedMatches[i].pos) continue;
501 logAppend("ERROR: impossible overlap found in matches list, please report");
502 failed=true;
503 running=false;
504 return;
505 }
506
507 // write commands
508 int totalSize=0;
509 int cnt=cmIdLen;
510 w->writeText(fmt::format(" .section {0}_bank0\n .align $100\n{0}_calltable",baseLabel));
511 while (cnt>0) {
512 int cnt2=MIN(cnt,256);
513 w->writeText("\n .byte ");
514 for (int j=0; j<cnt2; j++) {
515 w->writeText(fmt::format("<{}_c{},",baseLabel,cmIdLen-cnt+j));
516 }
517 for (int j=cnt2; j<256; j++) {
518 w->writeText("0,");
519 }
520 w->seek(-1,SEEK_CUR);
521 w->writeText("\n .byte ");
522 for (int j=0; j<cnt2; j++) {
523 w->writeText(fmt::format(">{}_c{},",baseLabel,cmIdLen-cnt+j));
524 }
525 for (int j=cnt2; j<256; j++) {
526 w->writeText("0,");
527 }
528 w->seek(-1,SEEK_CUR);
529 w->writeText("\n .byte ");
530 for (int j=0; j<cnt2; j++) {
531 w->writeText(fmt::format("{}_c{}>>13,",baseLabel,cmIdLen-cnt+j));
532 }
533 for (int j=cnt2; j<256; j++) {
534 w->writeText("0,");
535 }
536 w->seek(-1,SEEK_CUR);
537 w->writeText("\n .byte ");
538 for (int j=0; j<cnt2; j++) {
539 w->writeText(fmt::format("{},",callTicks[cmIdLen-cnt+j]&0xff));
540 }
541 w->seek(-1,SEEK_CUR);
542 totalSize+=768+cnt2;
543 cnt-=cnt2;
544 }
545 w->writeC('\n');
546 if (totalSize>firstBankSize) {
547 logAppend("ERROR: first bank is not large enough to contain call table");
548 failed=true;
549 running=false;
550 return;
551 }
552
553 int curBank=0;
554 int bankSize=totalSize;
555 int maxBankSize=firstBankSize;
556 int curCh=-1;
557 std::vector<bool> callVisited=std::vector<bool>(cmIdLen,false);
558 auto cmIter=confirmedMatches.begin();
559 for (int i=0; i<(int)renderedCmds.size(); i++) {
560 int writeCall=-1;
561 TiunaBytes cmd=renderedCmds[i];
562 if (cmIter!=confirmedMatches.end() && i==cmIter->pos) {
563 if (cmIter->id<cmIdLen) {
564 if (callVisited[cmIter->id]) {
565 unsigned char idLo=cmIter->id&0xff;
566 unsigned char idHi=cmIter->id>>8;
567 cmd=TiunaBytes(cmd.ch,0,2,{idHi,idLo});
568 i=cmIter->endPos-1;
569 } else {
570 writeCall=cmIter->id;
571 callVisited[writeCall]=true;
572 }
573 }
574 cmIter++;
575 }
576 if (cmd.ch!=curCh) {
577 if (curCh>=0) {
578 w->writeText(" .text x\"e0\"\n");
579 totalSize++;
580 bankSize++;
581 }
582 if (bankSize+cmd.size>=maxBankSize) {
583 maxBankSize=otherBankSize;
584 curBank++;
585 w->writeText(fmt::format(" .endsection\n\n .section {}_bank{}",baseLabel,curBank));
586 bankSize=0;
587 }
588 w->writeText(fmt::format("\n{}_ch{}\n",baseLabel,cmd.ch));
589 curCh=cmd.ch;
590 }
591 if (bankSize+cmd.size+1>=maxBankSize) {
592 maxBankSize=otherBankSize;
593 curBank++;
594 w->writeText(fmt::format(" .text x\"c0\"\n .endsection\n\n .section {}_bank{}\n",baseLabel,curBank));
595 totalSize++;
596 bankSize=0;
597 }
598 if (writeCall>=0) {
599 w->writeText(fmt::format("{}_c{}\n",baseLabel,writeCall));
600 }
601 w->writeText(" .text x\"");
602 for (int j=0; j<cmd.size; j++) {
603 w->writeText(fmt::format("{:02x}",cmd.buf[j]));
604 }
605 w->writeText("\"\n");
606 totalSize+=cmd.size;
607 bankSize+=cmd.size;
608 }
609 w->writeText(" .text x\"e0\"\n .endsection\n");
610 totalSize++;
611 logAppendf("total size: %d bytes (%d banks)",totalSize,curBank+1);
612
613 output.push_back(DivROMExportOutput("export.asm",w));
614
615 logAppend("finished!");
616
617 running=false;
618 }
619
620 bool DivExportTiuna::go(DivEngine* eng) {
621 progress[0].name="Compression";
622 progress[0].amount=0.0f;
623 progress[1].name="Confirmed Matches";
624 progress[1].amount=0.0f;
625
626 e=eng;
627 running=true;
628 failed=false;
629 mustAbort=false;
630 exportThread=new std::thread(&DivExportTiuna::run,this);
631 return true;
632 }
633
634 void DivExportTiuna::wait() {
635 if (exportThread!=NULL) {
636 exportThread->join();
637 delete exportThread;
638 }
639 }
640
641 void DivExportTiuna::abort() {
642 mustAbort=true;
643 wait();
644 }
645
646 bool DivExportTiuna::isRunning() {
647 return running;
648 }
649
650 bool DivExportTiuna::hasFailed() {
651 return failed;
652 }
653
654 DivROMExportProgress DivExportTiuna::getProgress(int index) {
655 if (index<0 || index>2) return progress[2];
656 return progress[index];
657 }