Debian Codegraph @

src/engine/cmdStreamOps.cpp

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "engine.h"
21 #include "../ta-log.h"
22 #include <stack>
23 #include <unordered_map>
24
25 int DivCS::getCmdLength(unsigned char ext) {
26 switch (ext) {
27 case DIV_CMD_SAMPLE_MODE:
28 case DIV_CMD_SAMPLE_FREQ:
29 case DIV_CMD_SAMPLE_BANK:
30 case DIV_CMD_SAMPLE_DIR:
31 case DIV_CMD_FM_HARD_RESET:
32 case DIV_CMD_FM_LFO:
33 case DIV_CMD_FM_LFO_WAVE:
34 case DIV_CMD_FM_LFO2:
35 case DIV_CMD_FM_LFO2_WAVE:
36 case DIV_CMD_FM_FB:
37 case DIV_CMD_FM_EXTCH:
38 case DIV_CMD_FM_AM_DEPTH:
39 case DIV_CMD_FM_PM_DEPTH:
40 case DIV_CMD_STD_NOISE_FREQ:
41 case DIV_CMD_STD_NOISE_MODE:
42 case DIV_CMD_WAVE:
43 case DIV_CMD_GB_SWEEP_TIME:
44 case DIV_CMD_GB_SWEEP_DIR:
45 case DIV_CMD_PCE_LFO_MODE:
46 case DIV_CMD_PCE_LFO_SPEED:
47 case DIV_CMD_NES_DMC:
48 case DIV_CMD_C64_CUTOFF:
49 case DIV_CMD_C64_RESONANCE:
50 case DIV_CMD_C64_FILTER_MODE:
51 case DIV_CMD_C64_RESET_TIME:
52 case DIV_CMD_C64_RESET_MASK:
53 case DIV_CMD_C64_FILTER_RESET:
54 case DIV_CMD_C64_DUTY_RESET:
55 case DIV_CMD_C64_EXTENDED:
56 case DIV_CMD_AY_ENVELOPE_SET:
57 case DIV_CMD_AY_ENVELOPE_LOW:
58 case DIV_CMD_AY_ENVELOPE_HIGH:
59 case DIV_CMD_AY_ENVELOPE_SLIDE:
60 case DIV_CMD_AY_NOISE_MASK_AND:
61 case DIV_CMD_AY_NOISE_MASK_OR:
62 case DIV_CMD_AY_AUTO_ENVELOPE:
63 case DIV_CMD_FDS_MOD_DEPTH:
64 case DIV_CMD_FDS_MOD_HIGH:
65 case DIV_CMD_FDS_MOD_LOW:
66 case DIV_CMD_FDS_MOD_POS:
67 case DIV_CMD_FDS_MOD_WAVE:
68 case DIV_CMD_SAA_ENVELOPE:
69 case DIV_CMD_AMIGA_FILTER:
70 case DIV_CMD_AMIGA_AM:
71 case DIV_CMD_AMIGA_PM:
72 case DIV_CMD_MACRO_OFF:
73 case DIV_CMD_MACRO_ON:
74 case DIV_CMD_MACRO_RESTART:
75 case DIV_CMD_QSOUND_ECHO_FEEDBACK:
76 case DIV_CMD_QSOUND_ECHO_LEVEL:
77 case DIV_CMD_QSOUND_SURROUND:
78 case DIV_CMD_X1_010_ENVELOPE_SHAPE:
79 case DIV_CMD_X1_010_ENVELOPE_ENABLE:
80 case DIV_CMD_X1_010_ENVELOPE_MODE:
81 case DIV_CMD_X1_010_ENVELOPE_PERIOD:
82 case DIV_CMD_X1_010_ENVELOPE_SLIDE:
83 case DIV_CMD_X1_010_AUTO_ENVELOPE:
84 case DIV_CMD_X1_010_SAMPLE_BANK_SLOT:
85 case DIV_CMD_WS_SWEEP_TIME:
86 case DIV_CMD_WS_SWEEP_AMOUNT:
87 case DIV_CMD_N163_WAVE_POSITION:
88 case DIV_CMD_N163_WAVE_LENGTH:
89 case DIV_CMD_N163_WAVE_UNUSED1:
90 case DIV_CMD_N163_WAVE_UNUSED2:
91 case DIV_CMD_N163_WAVE_LOADPOS:
92 case DIV_CMD_N163_WAVE_LOADLEN:
93 case DIV_CMD_N163_WAVE_UNUSED3:
94 case DIV_CMD_N163_CHANNEL_LIMIT:
95 case DIV_CMD_N163_GLOBAL_WAVE_LOAD:
96 case DIV_CMD_N163_GLOBAL_WAVE_LOADPOS:
97 case DIV_CMD_N163_UNUSED4:
98 case DIV_CMD_N163_UNUSED5:
99 case DIV_CMD_SU_SYNC_PERIOD_LOW:
100 case DIV_CMD_SU_SYNC_PERIOD_HIGH:
101 case DIV_CMD_ADPCMA_GLOBAL_VOLUME:
102 case DIV_CMD_SNES_ECHO:
103 case DIV_CMD_SNES_PITCH_MOD:
104 case DIV_CMD_SNES_INVERT:
105 case DIV_CMD_SNES_GAIN_MODE:
106 case DIV_CMD_SNES_GAIN:
107 case DIV_CMD_SNES_ECHO_ENABLE:
108 case DIV_CMD_SNES_ECHO_DELAY:
109 case DIV_CMD_SNES_ECHO_VOL_LEFT:
110 case DIV_CMD_SNES_ECHO_VOL_RIGHT:
111 case DIV_CMD_SNES_ECHO_FEEDBACK:
112 case DIV_CMD_NES_ENV_MODE:
113 case DIV_CMD_NES_LENGTH:
114 case DIV_CMD_NES_COUNT_MODE:
115 case DIV_CMD_FM_AM2_DEPTH:
116 case DIV_CMD_FM_PM2_DEPTH:
117 case DIV_CMD_ES5506_ENVELOPE_LVRAMP:
118 case DIV_CMD_ES5506_ENVELOPE_RVRAMP:
119 case DIV_CMD_ES5506_PAUSE:
120 case DIV_CMD_ES5506_FILTER_MODE:
121 case DIV_CMD_SNES_GLOBAL_VOL_LEFT:
122 case DIV_CMD_SNES_GLOBAL_VOL_RIGHT:
123 case DIV_CMD_NES_LINEAR_LENGTH:
124 case DIV_CMD_EXTERNAL:
125 case DIV_CMD_C64_AD:
126 case DIV_CMD_C64_SR:
127 case DIV_CMD_DAVE_HIGH_PASS:
128 case DIV_CMD_DAVE_RING_MOD:
129 case DIV_CMD_DAVE_SWAP_COUNTERS:
130 case DIV_CMD_DAVE_LOW_PASS:
131 case DIV_CMD_DAVE_CLOCK_DIV:
132 case DIV_CMD_MINMOD_ECHO:
133 case DIV_CMD_FDS_MOD_AUTO:
134 case DIV_CMD_FM_OPMASK:
135 case DIV_CMD_MULTIPCM_MIX_FM:
136 case DIV_CMD_MULTIPCM_MIX_PCM:
137 case DIV_CMD_MULTIPCM_LFO:
138 case DIV_CMD_MULTIPCM_VIB:
139 case DIV_CMD_MULTIPCM_AM:
140 case DIV_CMD_MULTIPCM_AR:
141 case DIV_CMD_MULTIPCM_D1R:
142 case DIV_CMD_MULTIPCM_DL:
143 case DIV_CMD_MULTIPCM_D2R:
144 case DIV_CMD_MULTIPCM_RC:
145 case DIV_CMD_MULTIPCM_RR:
146 case DIV_CMD_MULTIPCM_DAMP:
147 case DIV_CMD_MULTIPCM_PSEUDO_REVERB:
148 case DIV_CMD_MULTIPCM_LFO_RESET:
149 case DIV_CMD_MULTIPCM_LEVEL_DIRECT:
150 case DIV_CMD_SID3_SPECIAL_WAVE:
151 case DIV_CMD_SID3_RING_MOD_SRC:
152 case DIV_CMD_SID3_HARD_SYNC_SRC:
153 case DIV_CMD_SID3_PHASE_MOD_SRC:
154 case DIV_CMD_SID3_WAVE_MIX:
155 case DIV_CMD_SID3_1_BIT_NOISE:
156 case DIV_CMD_SID3_CHANNEL_INVERSION:
157 case DIV_CMD_SID3_FILTER_CONNECTION:
158 case DIV_CMD_SID3_FILTER_MATRIX:
159 case DIV_CMD_SID3_FILTER_ENABLE:
160 case DIV_CMD_SID3_PHASE_RESET:
161 case DIV_CMD_SID3_NOISE_PHASE_RESET:
162 case DIV_CMD_SID3_ENVELOPE_RESET:
163 case DIV_CMD_SID3_CUTOFF_SCALING:
164 case DIV_CMD_SID3_RESONANCE_SCALING:
165 case DIV_CMD_WS_GLOBAL_SPEAKER_VOLUME:
166 case DIV_CMD_FM_ALG:
167 case DIV_CMD_FM_FMS:
168 case DIV_CMD_FM_AMS:
169 case DIV_CMD_FM_FMS2:
170 case DIV_CMD_FM_AMS2:
171 return 1;
172 case DIV_CMD_FM_TL:
173 case DIV_CMD_FM_AM:
174 case DIV_CMD_FM_AR:
175 case DIV_CMD_FM_DR:
176 case DIV_CMD_FM_SL:
177 case DIV_CMD_FM_D2R:
178 case DIV_CMD_FM_RR:
179 case DIV_CMD_FM_DT:
180 case DIV_CMD_FM_DT2:
181 case DIV_CMD_FM_RS:
182 case DIV_CMD_FM_KSR:
183 case DIV_CMD_FM_VIB:
184 case DIV_CMD_FM_SUS:
185 case DIV_CMD_FM_WS:
186 case DIV_CMD_FM_SSG:
187 case DIV_CMD_FM_REV:
188 case DIV_CMD_FM_EG_SHIFT:
189 case DIV_CMD_FM_MULT:
190 case DIV_CMD_FM_FINE:
191 case DIV_CMD_AY_IO_WRITE:
192 case DIV_CMD_AY_AUTO_PWM:
193 case DIV_CMD_SURROUND_PANNING:
194 case DIV_CMD_SU_SWEEP_PERIOD_LOW:
195 case DIV_CMD_SU_SWEEP_PERIOD_HIGH:
196 case DIV_CMD_SU_SWEEP_BOUND:
197 case DIV_CMD_SU_SWEEP_ENABLE:
198 case DIV_CMD_SNES_ECHO_FIR:
199 case DIV_CMD_ES5506_FILTER_K1_SLIDE:
200 case DIV_CMD_ES5506_FILTER_K2_SLIDE:
201 case DIV_CMD_ES5506_ENVELOPE_K1RAMP:
202 case DIV_CMD_ES5506_ENVELOPE_K2RAMP:
203 case DIV_CMD_ESFM_OP_PANNING:
204 case DIV_CMD_ESFM_OUTLVL:
205 case DIV_CMD_ESFM_MODIN:
206 case DIV_CMD_ESFM_ENV_DELAY:
207 case DIV_CMD_POWERNOISE_COUNTER_LOAD:
208 case DIV_CMD_POWERNOISE_IO_WRITE:
209 case DIV_CMD_BIFURCATOR_STATE_LOAD:
210 case DIV_CMD_BIFURCATOR_PARAMETER:
211 case DIV_CMD_SID3_LFSR_FEEDBACK_BITS:
212 case DIV_CMD_SID3_FILTER_DISTORTION:
213 case DIV_CMD_SID3_FILTER_OUTPUT_VOLUME:
214 case DIV_CMD_C64_PW_SLIDE:
215 case DIV_CMD_C64_CUTOFF_SLIDE:
216 return 2;
217 case DIV_CMD_C64_FINE_DUTY:
218 case DIV_CMD_C64_FINE_CUTOFF:
219 case DIV_CMD_LYNX_LFSR_LOAD:
220 case DIV_CMD_QSOUND_ECHO_DELAY:
221 case DIV_CMD_ES5506_ENVELOPE_COUNT:
222 return 2;
223 case DIV_CMD_ES5506_FILTER_K1:
224 case DIV_CMD_ES5506_FILTER_K2:
225 return 4;
226 case DIV_CMD_FM_FIXFREQ:
227 return 2;
228 case DIV_CMD_NES_SWEEP:
229 return 2;
230 case DIV_CMD_SAMPLE_POS:
231 return 4;
232 default:
233 return 0;
234 }
235 return 0;
236 }
237
238 int DivCS::getInsLength(unsigned char ins, unsigned char ext, unsigned char* speedDial) {
239 switch (ins) {
240 case 0xb8: // ins
241 case 0xc0: // pre porta
242 case 0xc1: // arp time
243 case 0xc3: // vib range
244 case 0xc4: // vib shape
245 case 0xc5: // pitch
246 case 0xc6: // arpeggio
247 case 0xc7: // volume
248 case 0xca: // legato
249 case 0xcc: // tremolo
250 case 0xcd: // panbrello
251 case 0xce: // pan slide
252 case 0xdd: // waitc
253 case 0xc2: // vibrato
254 return 2;
255 case 0xcf: // pan
256 case 0xc8: // vol slide
257 case 0xc9: // porta
258 return 3;
259 // speed dial commands
260 case 0xe0: case 0xe1: case 0xe2: case 0xe3:
261 case 0xe4: case 0xe5: case 0xe6: case 0xe7:
262 case 0xe8: case 0xe9: case 0xea: case 0xeb:
263 case 0xec: case 0xed: case 0xee: case 0xef:
264 if (speedDial==NULL) return 0;
265 return 1+getCmdLength(speedDial[ins&15]);
266 case 0xd0: // opt
267 return 4;
268 case 0xd7: // cmd
269 // determine length from secondary
270 if (ext==0) return 0;
271 return 2+getCmdLength(ext);
272 case 0xd8: // call
273 case 0xdc: // waits
274 return 3;
275 case 0xd4: // callsym
276 case 0xd5: // calli
277 case 0xda: // jmp
278 case 0xdb: // rate
279 case 0xcb: // volporta
280 return 5;
281 }
282 return 1;
283 }
284
285 void writeCommandValues(SafeWriter* w, const DivCommand& c, bool bigEndian) {
286 switch (c.cmd) {
287 case DIV_CMD_NOTE_ON:
288 if (c.value==DIV_NOTE_NULL) {
289 w->writeC(0xb4);
290 } else {
291 w->writeC(CLAMP(c.value+60,0,0xb3));
292 }
293 break;
294 case DIV_CMD_NOTE_OFF:
295 w->writeC(0xb5);
296 break;
297 case DIV_CMD_NOTE_OFF_ENV:
298 w->writeC(0xb6);
299 break;
300 case DIV_CMD_ENV_RELEASE:
301 w->writeC(0xb7);
302 break;
303 case DIV_CMD_INSTRUMENT:
304 w->writeC(0xb8);
305 break;
306 case DIV_CMD_PRE_PORTA:
307 w->writeC(0xc0);
308 break;
309 case DIV_CMD_HINT_ARP_TIME:
310 w->writeC(0xc1);
311 break;
312 case DIV_CMD_HINT_VIBRATO:
313 w->writeC(0xc2);
314 break;
315 case DIV_CMD_HINT_VIBRATO_RANGE:
316 w->writeC(0xc3);
317 break;
318 case DIV_CMD_HINT_VIBRATO_SHAPE:
319 w->writeC(0xc4);
320 break;
321 case DIV_CMD_HINT_PITCH:
322 w->writeC(0xc5);
323 break;
324 case DIV_CMD_HINT_ARPEGGIO:
325 w->writeC(0xc6);
326 break;
327 case DIV_CMD_HINT_VOLUME:
328 w->writeC(0xc7);
329 break;
330 case DIV_CMD_HINT_VOL_SLIDE:
331 w->writeC(0xc8);
332 break;
333 case DIV_CMD_HINT_PORTA:
334 w->writeC(0xc9);
335 break;
336 case DIV_CMD_HINT_LEGATO:
337 w->writeC(0xca);
338 break;
339 case DIV_CMD_HINT_VOL_SLIDE_TARGET:
340 w->writeC(0xcb);
341 break;
342 case DIV_CMD_HINT_TREMOLO:
343 w->writeC(0xcc);
344 break;
345 case DIV_CMD_HINT_PANBRELLO:
346 w->writeC(0xcd);
347 break;
348 case DIV_CMD_HINT_PAN_SLIDE:
349 w->writeC(0xce);
350 break;
351 case DIV_CMD_HINT_PANNING:
352 w->writeC(0xcf);
353 break;
354 default:
355 w->writeC(0xd7);
356 w->writeC(c.cmd);
357 break;
358 }
359 switch (c.cmd) {
360 case DIV_CMD_HINT_LEGATO:
361 if (c.value==DIV_NOTE_NULL) {
362 w->writeC(0xff);
363 } else {
364 w->writeC(c.value+60);
365 }
366 break;
367 case DIV_CMD_NOTE_ON:
368 case DIV_CMD_NOTE_OFF:
369 case DIV_CMD_NOTE_OFF_ENV:
370 case DIV_CMD_ENV_RELEASE:
371 break;
372 case DIV_CMD_INSTRUMENT:
373 case DIV_CMD_HINT_VIBRATO_RANGE:
374 case DIV_CMD_HINT_VIBRATO_SHAPE:
375 case DIV_CMD_HINT_PITCH:
376 case DIV_CMD_HINT_VOLUME:
377 case DIV_CMD_HINT_TREMOLO:
378 case DIV_CMD_HINT_PANBRELLO:
379 case DIV_CMD_HINT_PAN_SLIDE:
380 case DIV_CMD_HINT_ARPEGGIO:
381 case DIV_CMD_HINT_ARP_TIME:
382 case DIV_CMD_HINT_VIBRATO:
383 w->writeC(c.value);
384 break;
385 case DIV_CMD_HINT_PANNING:
386 w->writeC(c.value);
387 w->writeC(c.value2);
388 break;
389 case DIV_CMD_HINT_PORTA: {
390 unsigned char val=CLAMP(c.value+60,0,255);
391 w->writeC(val);
392 w->writeC(c.value2);
393 break;
394 }
395 case DIV_CMD_PRE_PORTA:
396 w->writeC((c.value?0x80:0)|(c.value2?0x40:0));
397 break;
398 case DIV_CMD_HINT_VOL_SLIDE:
399 if (bigEndian) {
400 w->writeS_BE(c.value);
401 } else {
402 w->writeS(c.value);
403 }
404 break;
405 case DIV_CMD_HINT_VOL_SLIDE_TARGET:
406 if (bigEndian) {
407 w->writeS_BE(c.value);
408 w->writeS_BE(c.value2);
409 } else {
410 w->writeS(c.value);
411 w->writeS(c.value2);
412 }
413 break;
414 case DIV_CMD_SAMPLE_MODE:
415 case DIV_CMD_SAMPLE_FREQ:
416 case DIV_CMD_SAMPLE_BANK:
417 case DIV_CMD_SAMPLE_DIR:
418 case DIV_CMD_FM_HARD_RESET:
419 case DIV_CMD_FM_LFO:
420 case DIV_CMD_FM_LFO_WAVE:
421 case DIV_CMD_FM_LFO2:
422 case DIV_CMD_FM_LFO2_WAVE:
423 case DIV_CMD_FM_FB:
424 case DIV_CMD_FM_EXTCH:
425 case DIV_CMD_FM_AM_DEPTH:
426 case DIV_CMD_FM_PM_DEPTH:
427 case DIV_CMD_STD_NOISE_FREQ:
428 case DIV_CMD_STD_NOISE_MODE:
429 case DIV_CMD_WAVE:
430 case DIV_CMD_GB_SWEEP_TIME:
431 case DIV_CMD_GB_SWEEP_DIR:
432 case DIV_CMD_PCE_LFO_MODE:
433 case DIV_CMD_PCE_LFO_SPEED:
434 case DIV_CMD_NES_DMC:
435 case DIV_CMD_C64_CUTOFF:
436 case DIV_CMD_C64_RESONANCE:
437 case DIV_CMD_C64_FILTER_MODE:
438 case DIV_CMD_C64_RESET_TIME:
439 case DIV_CMD_C64_RESET_MASK:
440 case DIV_CMD_C64_FILTER_RESET:
441 case DIV_CMD_C64_DUTY_RESET:
442 case DIV_CMD_C64_EXTENDED:
443 case DIV_CMD_AY_ENVELOPE_SET:
444 case DIV_CMD_AY_ENVELOPE_LOW:
445 case DIV_CMD_AY_ENVELOPE_HIGH:
446 case DIV_CMD_AY_ENVELOPE_SLIDE:
447 case DIV_CMD_AY_NOISE_MASK_AND:
448 case DIV_CMD_AY_NOISE_MASK_OR:
449 case DIV_CMD_AY_AUTO_ENVELOPE:
450 case DIV_CMD_FDS_MOD_DEPTH:
451 case DIV_CMD_FDS_MOD_HIGH:
452 case DIV_CMD_FDS_MOD_LOW:
453 case DIV_CMD_FDS_MOD_POS:
454 case DIV_CMD_FDS_MOD_WAVE:
455 case DIV_CMD_SAA_ENVELOPE:
456 case DIV_CMD_AMIGA_FILTER:
457 case DIV_CMD_AMIGA_AM:
458 case DIV_CMD_AMIGA_PM:
459 case DIV_CMD_MACRO_OFF:
460 case DIV_CMD_MACRO_ON:
461 case DIV_CMD_MACRO_RESTART:
462 case DIV_CMD_QSOUND_ECHO_FEEDBACK:
463 case DIV_CMD_QSOUND_ECHO_LEVEL:
464 case DIV_CMD_QSOUND_SURROUND:
465 case DIV_CMD_X1_010_ENVELOPE_SHAPE:
466 case DIV_CMD_X1_010_ENVELOPE_ENABLE:
467 case DIV_CMD_X1_010_ENVELOPE_MODE:
468 case DIV_CMD_X1_010_ENVELOPE_PERIOD:
469 case DIV_CMD_X1_010_ENVELOPE_SLIDE:
470 case DIV_CMD_X1_010_AUTO_ENVELOPE:
471 case DIV_CMD_X1_010_SAMPLE_BANK_SLOT:
472 case DIV_CMD_WS_SWEEP_TIME:
473 case DIV_CMD_WS_SWEEP_AMOUNT:
474 case DIV_CMD_N163_WAVE_POSITION:
475 case DIV_CMD_N163_WAVE_LENGTH:
476 case DIV_CMD_N163_WAVE_UNUSED1:
477 case DIV_CMD_N163_WAVE_UNUSED2:
478 case DIV_CMD_N163_WAVE_LOADPOS:
479 case DIV_CMD_N163_WAVE_LOADLEN:
480 case DIV_CMD_N163_WAVE_UNUSED3:
481 case DIV_CMD_N163_CHANNEL_LIMIT:
482 case DIV_CMD_N163_GLOBAL_WAVE_LOAD:
483 case DIV_CMD_N163_GLOBAL_WAVE_LOADPOS:
484 case DIV_CMD_N163_UNUSED4:
485 case DIV_CMD_N163_UNUSED5:
486 case DIV_CMD_SU_SYNC_PERIOD_LOW:
487 case DIV_CMD_SU_SYNC_PERIOD_HIGH:
488 case DIV_CMD_ADPCMA_GLOBAL_VOLUME:
489 case DIV_CMD_SNES_ECHO:
490 case DIV_CMD_SNES_PITCH_MOD:
491 case DIV_CMD_SNES_INVERT:
492 case DIV_CMD_SNES_GAIN_MODE:
493 case DIV_CMD_SNES_GAIN:
494 case DIV_CMD_SNES_ECHO_ENABLE:
495 case DIV_CMD_SNES_ECHO_DELAY:
496 case DIV_CMD_SNES_ECHO_VOL_LEFT:
497 case DIV_CMD_SNES_ECHO_VOL_RIGHT:
498 case DIV_CMD_SNES_ECHO_FEEDBACK:
499 case DIV_CMD_NES_ENV_MODE:
500 case DIV_CMD_NES_LENGTH:
501 case DIV_CMD_NES_COUNT_MODE:
502 case DIV_CMD_FM_AM2_DEPTH:
503 case DIV_CMD_FM_PM2_DEPTH:
504 case DIV_CMD_ES5506_ENVELOPE_LVRAMP:
505 case DIV_CMD_ES5506_ENVELOPE_RVRAMP:
506 case DIV_CMD_ES5506_PAUSE:
507 case DIV_CMD_ES5506_FILTER_MODE:
508 case DIV_CMD_SNES_GLOBAL_VOL_LEFT:
509 case DIV_CMD_SNES_GLOBAL_VOL_RIGHT:
510 case DIV_CMD_NES_LINEAR_LENGTH:
511 case DIV_CMD_EXTERNAL:
512 case DIV_CMD_C64_AD:
513 case DIV_CMD_C64_SR:
514 case DIV_CMD_DAVE_HIGH_PASS:
515 case DIV_CMD_DAVE_RING_MOD:
516 case DIV_CMD_DAVE_SWAP_COUNTERS:
517 case DIV_CMD_DAVE_LOW_PASS:
518 case DIV_CMD_DAVE_CLOCK_DIV:
519 case DIV_CMD_MINMOD_ECHO:
520 case DIV_CMD_FDS_MOD_AUTO:
521 case DIV_CMD_FM_OPMASK:
522 case DIV_CMD_MULTIPCM_MIX_FM:
523 case DIV_CMD_MULTIPCM_MIX_PCM:
524 case DIV_CMD_MULTIPCM_LFO:
525 case DIV_CMD_MULTIPCM_VIB:
526 case DIV_CMD_MULTIPCM_AM:
527 case DIV_CMD_MULTIPCM_AR:
528 case DIV_CMD_MULTIPCM_D1R:
529 case DIV_CMD_MULTIPCM_DL:
530 case DIV_CMD_MULTIPCM_D2R:
531 case DIV_CMD_MULTIPCM_RC:
532 case DIV_CMD_MULTIPCM_RR:
533 case DIV_CMD_MULTIPCM_DAMP:
534 case DIV_CMD_MULTIPCM_PSEUDO_REVERB:
535 case DIV_CMD_MULTIPCM_LFO_RESET:
536 case DIV_CMD_MULTIPCM_LEVEL_DIRECT:
537 case DIV_CMD_SID3_SPECIAL_WAVE:
538 case DIV_CMD_SID3_RING_MOD_SRC:
539 case DIV_CMD_SID3_HARD_SYNC_SRC:
540 case DIV_CMD_SID3_PHASE_MOD_SRC:
541 case DIV_CMD_SID3_WAVE_MIX:
542 case DIV_CMD_SID3_1_BIT_NOISE:
543 case DIV_CMD_SID3_CHANNEL_INVERSION:
544 case DIV_CMD_SID3_FILTER_CONNECTION:
545 case DIV_CMD_SID3_FILTER_MATRIX:
546 case DIV_CMD_SID3_FILTER_ENABLE:
547 case DIV_CMD_SID3_PHASE_RESET:
548 case DIV_CMD_SID3_NOISE_PHASE_RESET:
549 case DIV_CMD_SID3_ENVELOPE_RESET:
550 case DIV_CMD_SID3_CUTOFF_SCALING:
551 case DIV_CMD_SID3_RESONANCE_SCALING:
552 case DIV_CMD_WS_GLOBAL_SPEAKER_VOLUME:
553 case DIV_CMD_FM_ALG:
554 case DIV_CMD_FM_FMS:
555 case DIV_CMD_FM_AMS:
556 case DIV_CMD_FM_FMS2:
557 case DIV_CMD_FM_AMS2:
558 w->writeC(c.value);
559 break;
560 case DIV_CMD_FM_TL:
561 case DIV_CMD_FM_AM:
562 case DIV_CMD_FM_AR:
563 case DIV_CMD_FM_DR:
564 case DIV_CMD_FM_SL:
565 case DIV_CMD_FM_D2R:
566 case DIV_CMD_FM_RR:
567 case DIV_CMD_FM_DT:
568 case DIV_CMD_FM_DT2:
569 case DIV_CMD_FM_RS:
570 case DIV_CMD_FM_KSR:
571 case DIV_CMD_FM_VIB:
572 case DIV_CMD_FM_SUS:
573 case DIV_CMD_FM_WS:
574 case DIV_CMD_FM_SSG:
575 case DIV_CMD_FM_REV:
576 case DIV_CMD_FM_EG_SHIFT:
577 case DIV_CMD_FM_MULT:
578 case DIV_CMD_FM_FINE:
579 case DIV_CMD_AY_IO_WRITE:
580 case DIV_CMD_AY_AUTO_PWM:
581 case DIV_CMD_SURROUND_PANNING:
582 case DIV_CMD_SU_SWEEP_PERIOD_LOW:
583 case DIV_CMD_SU_SWEEP_PERIOD_HIGH:
584 case DIV_CMD_SU_SWEEP_BOUND:
585 case DIV_CMD_SU_SWEEP_ENABLE:
586 case DIV_CMD_SNES_ECHO_FIR:
587 case DIV_CMD_ES5506_FILTER_K1_SLIDE:
588 case DIV_CMD_ES5506_FILTER_K2_SLIDE:
589 case DIV_CMD_ES5506_ENVELOPE_K1RAMP:
590 case DIV_CMD_ES5506_ENVELOPE_K2RAMP:
591 case DIV_CMD_ESFM_OP_PANNING:
592 case DIV_CMD_ESFM_OUTLVL:
593 case DIV_CMD_ESFM_MODIN:
594 case DIV_CMD_ESFM_ENV_DELAY:
595 case DIV_CMD_POWERNOISE_COUNTER_LOAD:
596 case DIV_CMD_POWERNOISE_IO_WRITE:
597 case DIV_CMD_BIFURCATOR_STATE_LOAD:
598 case DIV_CMD_BIFURCATOR_PARAMETER:
599 case DIV_CMD_SID3_LFSR_FEEDBACK_BITS:
600 case DIV_CMD_SID3_FILTER_DISTORTION:
601 case DIV_CMD_SID3_FILTER_OUTPUT_VOLUME:
602 case DIV_CMD_C64_PW_SLIDE:
603 case DIV_CMD_C64_CUTOFF_SLIDE:
604 w->writeC(c.value);
605 w->writeC(c.value2);
606 break;
607 case DIV_CMD_C64_FINE_DUTY:
608 case DIV_CMD_C64_FINE_CUTOFF:
609 case DIV_CMD_LYNX_LFSR_LOAD:
610 case DIV_CMD_QSOUND_ECHO_DELAY:
611 case DIV_CMD_ES5506_ENVELOPE_COUNT:
612 if (bigEndian) {
613 w->writeS_BE(c.value);
614 } else {
615 w->writeS(c.value);
616 }
617 break;
618 case DIV_CMD_ES5506_FILTER_K1:
619 case DIV_CMD_ES5506_FILTER_K2:
620 if (bigEndian) {
621 w->writeS_BE(c.value);
622 w->writeS_BE(c.value2);
623 } else {
624 w->writeS(c.value);
625 w->writeS(c.value2);
626 }
627 break;
628 case DIV_CMD_FM_FIXFREQ:
629 if (bigEndian) {
630 w->writeS_BE((c.value<<12)|(c.value2&0x7ff));
631 } else {
632 w->writeS((c.value<<12)|(c.value2&0x7ff));
633 }
634 break;
635 case DIV_CMD_NES_SWEEP:
636 w->writeC((c.value?8:0)|(c.value2&0x77));
637 break;
638 case DIV_CMD_SAMPLE_POS:
639 if (bigEndian) {
640 w->writeI_BE(c.value);
641 } else {
642 w->writeI(c.value);
643 }
644 break;
645 default:
646 logW("unimplemented command %s!",cmdName[c.cmd]);
647 break;
648 }
649 // padding (TODO: optimize)
650 while (w->tell()&7) w->writeC(0);
651 }
652
653 #define _EXT(b,x,l) (((size_t)((x)+1)<(size_t)(l))?(b[(x)+1]):0)
654
655 using namespace DivCS;
656
657 int estimateBlockSize(unsigned char* buf, size_t len, unsigned char* speedDial) {
658 int ret=0;
659 for (size_t i=0; i<len; i+=8) {
660 ret+=getInsLength(buf[i],buf[i+1],speedDial);
661 }
662 return ret;
663 }
664
665 void reloc8(unsigned char* buf, size_t len, unsigned int sourceAddr, unsigned int destAddr) {
666 unsigned int delta=destAddr-sourceAddr;
667 for (size_t i=0; i<len; i+=8) {
668 switch (buf[i]) {
669 case 0xd5: // calli
670 case 0xda: { // jmp
671 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<16)|(buf[i+4]<<24);
672 addr+=delta;
673 buf[i+1]=addr&0xff;
674 buf[i+2]=(addr>>8)&0xff;
675 buf[i+3]=(addr>>16)&0xff;
676 buf[i+4]=(addr>>24)&0xff;
677 break;
678 }
679 case 0xd8: { // call
680 unsigned int addr=buf[i+1]|(buf[i+2]<<8);
681 addr+=delta;
682 if (addr>0xffff) {
683 buf[i]=0xd5;
684 buf[i+1]=addr&0xff;
685 buf[i+2]=(addr>>8)&0xff;
686 buf[i+3]=(addr>>16)&0xff;
687 buf[i+4]=(addr>>24)&0xff;
688 } else {
689 buf[i+1]=addr&0xff;
690 buf[i+2]=(addr>>8)&0xff;
691 }
692 break;
693 }
694 }
695 }
696 }
697
698 void reloc(unsigned char* buf, size_t len, unsigned int sourceAddr, unsigned int destAddr, unsigned char* speedDial, bool bigEndian) {
699 unsigned int delta=destAddr-sourceAddr;
700 for (size_t i=0; i<len;) {
701 int insLen=getInsLength(buf[i],_EXT(buf,i,len),speedDial);
702 if (insLen<1) {
703 logE("INS %x NOT IMPLEMENTED...",buf[i]);
704 break;
705 }
706 switch (buf[i]) {
707 case 0xd5: // calli
708 case 0xda: { // jmp
709 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<16)|(buf[i+4]<<24);
710 addr+=delta;
711 if (bigEndian) {
712 buf[i+1]=(addr>>24)&0xff;
713 buf[i+2]=(addr>>16)&0xff;
714 buf[i+3]=(addr>>8)&0xff;
715 buf[i+4]=addr&0xff;
716 } else {
717 buf[i+1]=addr&0xff;
718 buf[i+2]=(addr>>8)&0xff;
719 buf[i+3]=(addr>>16)&0xff;
720 buf[i+4]=(addr>>24)&0xff;
721 }
722 break;
723 }
724 case 0xd8: { // call
725 unsigned short addr=buf[i+1]|(buf[i+2]<<8);
726 addr+=delta;
727 if (bigEndian) {
728 buf[i+1]=(addr>>8)&0xff;
729 buf[i+2]=addr&0xff;
730 } else {
731 buf[i+1]=addr&0xff;
732 buf[i+2]=(addr>>8)&0xff;
733 }
734 break;
735 }
736 }
737 i+=insLen;
738 }
739 }
740
741 SafeWriter* stripNops(SafeWriter* s) {
742 std::unordered_map<unsigned int,unsigned int> addrTable;
743 SafeWriter* oldStream=s;
744 unsigned char* buf=oldStream->getFinalBuf();
745 s=new SafeWriter;
746 s->init();
747
748 // prepare address map
749 size_t addr=0;
750 for (size_t i=0; i<oldStream->size(); i+=8) {
751 addrTable[i]=addr;
752 if (buf[i]!=0xd1) addr+=8;
753 }
754
755 // translate addresses
756 for (size_t i=0; i<oldStream->size(); i+=8) {
757 switch (buf[i]) {
758 case 0xd5: // calli
759 case 0xda: { // jmp
760 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<16)|(buf[i+4]<<24);
761 assert(!(addr&7));
762 if (addr>=oldStream->size()) {
763 logE("OUT OF BOUNDS!");
764 abort();
765 }
766 if (buf[addr]==0xd1) {
767 logE("POINTS TO NOP");
768 abort();
769 }
770 try {
771 addr=addrTable[addr];
772 buf[i+1]=addr&0xff;
773 buf[i+2]=(addr>>8)&0xff;
774 buf[i+3]=(addr>>16)&0xff;
775 buf[i+4]=(addr>>24)&0xff;
776 } catch (std::out_of_range& e) {
777 logW("address %x is not mappable!",addr);
778 abort();
779 }
780 break;
781 }
782 case 0xd8: { // call
783 unsigned int addr=buf[i+1]|(buf[i+2]<<8);
784 try {
785 addr=addrTable[addr];
786 buf[i+1]=addr&0xff;
787 buf[i+2]=(addr>>8)&0xff;
788 } catch (std::out_of_range& e) {
789 logW("address %x is not mappable!",addr);
790 }
791 break;
792 }
793 }
794 if (buf[i]!=0xd1) {
795 s->write(&buf[i],8);
796 }
797 }
798
799 oldStream->finish();
800 delete oldStream;
801 return s;
802 }
803
804 SafeWriter* stripNopsPacked(SafeWriter* s, unsigned char* speedDial, unsigned int* chanStreamOff) {
805 std::unordered_map<unsigned int,unsigned int> addrTable;
806 SafeWriter* oldStream=s;
807 unsigned char* buf=oldStream->getFinalBuf();
808 s=new SafeWriter;
809 s->init();
810
811 // prepare address map
812 size_t addr=0;
813 for (size_t i=0; i<oldStream->size();) {
814 int insLen=getInsLength(buf[i],_EXT(buf,i,oldStream->size()),speedDial);
815 if (insLen<1) {
816 logE("INS %x NOT IMPLEMENTED...",buf[i]);
817 break;
818 }
819 addrTable[i]=addr;
820 if (buf[i]!=0xd1 && buf[i]!=0xd0) addr+=insLen;
821 i+=insLen;
822 }
823
824 // translate addresses
825 for (size_t i=0; i<oldStream->size();) {
826 int insLen=getInsLength(buf[i],_EXT(buf,i,oldStream->size()),speedDial);
827 if (insLen<1) {
828 logE("INS %x NOT IMPLEMENTED...",buf[i]);
829 break;
830 }
831 switch (buf[i]) {
832 case 0xd0: // ext (for channel offsets)
833 if (buf[i+3]==0) {
834 int ch=buf[i+1];
835 if (ch>=0 && ch<DIV_MAX_CHANS) {
836 chanStreamOff[ch]=addrTable[i];
837 }
838 }
839 break;
840 case 0xd5: // calli
841 case 0xda: { // jmp
842 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<8)|(buf[i+4]<<24);
843 try {
844 addr=addrTable[addr];
845 buf[i+1]=addr&0xff;
846 buf[i+2]=(addr>>8)&0xff;
847 buf[i+3]=(addr>>16)&0xff;
848 buf[i+4]=(addr>>24)&0xff;
849 } catch (std::out_of_range& e) {
850 logW("address %x is not mappable!",addr);
851 }
852 break;
853 }
854 case 0xd8: { // call
855 unsigned int addr=buf[i+1]|(buf[i+2]<<8);
856 try {
857 addr=addrTable[addr];
858 buf[i+1]=addr&0xff;
859 buf[i+2]=(addr>>8)&0xff;
860 if (addr>0xffff) { // this may never happen but it's here just in case
861 logW("address %x is out of range for 16-bit call!",addr);
862 }
863 } catch (std::out_of_range& e) {
864 logW("address %x is not mappable!",addr);
865 }
866 break;
867 }
868 }
869 if (buf[i]!=0xd1 && buf[i]!=0xd0) {
870 s->write(&buf[i],insLen);
871 }
872 i+=insLen;
873 }
874
875
876 oldStream->finish();
877 delete oldStream;
878 return s;
879 }
880
881 struct BlockMatch {
882 size_t orig, block;
883 unsigned int len;
884 bool done;
885 BlockMatch(size_t o, size_t b, unsigned int l):
886 orig(o), block(b), len(l), done(false) {}
887 BlockMatch():
888 orig(0), block(0), len(0), done(false) {}
889 };
890
891 struct MatchBenefit {
892 size_t index;
893 int benefit;
894 unsigned int len;
895 MatchBenefit(size_t i, int b, unsigned int l):
896 index(i), benefit(b), len(l) {}
897 MatchBenefit():
898 index(0), benefit(0), len(0) {}
899 };
900
901 #define OVERLAPS(a1,a2,b1,b2) ((b1)<(a2) && (b2)>(a1))
902
903 #define MIN_MATCH_SIZE 32
904
905 SafeWriter* findSubBlocks(SafeWriter* stream, std::vector<SafeWriter*>& subBlocks, unsigned char* speedDial, DivCSProgress* progress) {
906 unsigned char* buf=stream->getFinalBuf();
907 size_t matchSize=MIN_MATCH_SIZE;
908 std::vector<BlockMatch> matches;
909 std::vector<BlockMatch> workMatches;
910 std::vector<size_t> origs;
911 MatchBenefit bestBenefit;
912
913 matches.clear();
914
915 if (progress!=NULL) {
916 progress->findTotal=stream->size();
917 progress->optStage=0;
918 }
919
920 // fast match algorithm
921 // search for small matches, and then find bigger ones
922 logD("finding possible matches");
923 for (size_t i=0; i<stream->size(); i+=8) {
924 if (!(i&2047)) {
925 if (progress!=NULL) progress->findCurrent=i;
926 }
927 bool storedOrig=false;
928 for (size_t j=i+matchSize; j<stream->size(); j+=8) {
929 if (memcmp(&buf[i],&buf[j],matchSize)==0) {
930 if (!storedOrig) {
931 // store index to the first match somewhere else for the sake of speed
932 origs.push_back(matches.size());
933 storedOrig=true;
934 }
935 // store this match for later
936 matches.push_back(BlockMatch(i,j,matchSize));
937 }
938 }
939 }
940
941 logD("%d candidates",(int)matches.size());
942 logD("%d origs",(int)origs.size());
943
944 if (progress!=NULL) {
945 if ((int)matches.size()>progress->optTotal) progress->optTotal=matches.size();
946 progress->optCurrent=matches.size();
947 progress->origCount=origs.size();
948 progress->findCurrent=stream->size();
949 progress->optStage=1;
950 }
951
952 // quit if there isn't anything
953 if (matches.empty()) return stream;
954
955 // search for bigger matches
956 for (size_t i=0; i<matches.size(); i++) {
957 if ((i&8191)==0) {
958 logV("match %d of %d",i,(int)matches.size());
959 }
960 if ((i&1023)==0) {
961 if (progress!=NULL) progress->expandCurrent=i;
962 }
963 BlockMatch& b=matches[i];
964
965 size_t finalLen=b.len;
966 size_t origPos=b.orig+b.len;
967 size_t blockPos=b.block+b.len;
968 while (true) {
969 // origPos is guaranteed to be before blockPos
970 if (blockPos>=stream->size()) {
971 break;
972 }
973
974 if (buf[origPos]!=buf[blockPos]) {
975 break;
976 }
977 origPos++;
978 blockPos++;
979 finalLen++;
980 }
981
982 finalLen&=~7;
983 b.len=finalLen;
984 }
985
986 if (progress!=NULL) {
987 progress->expandCurrent=matches.size();
988 progress->optStage=2;
989 }
990
991 // new code MAN... WHY...
992 // basically the workflow should be:
993 // - test every block position
994 // - test every length from MIN_MATCH_SIZE to largest length
995 // - check for overlap, bad matches and all of that
996 // - for bad matches, fortunately we can use length for a speed-up... but first make it right
997 // - add weighted benefit to a list (DEBUG..... remove once it's stable)
998 // - pick largest benefit from list
999 // - make sub-blocks!!!
1000 logD("testing %d match groups for benefit",(int)origs.size());
1001 size_t origIndex=0;
1002 for (size_t i=0; i<origs.size(); i++) {
1003 size_t begin=origs[i];
1004 size_t end=(i+1<origs.size())?origs[i+1]:matches.size();
1005 size_t minSize=MIN_MATCH_SIZE;
1006 std::vector<BlockMatch> testLenMatches;
1007
1008 if (progress!=NULL) progress->origCurrent=origIndex;
1009
1010 origIndex++;
1011
1012 if (!(i&255)) logV("orig %d of %d",(int)i,(int)origs.size());
1013
1014 // test all lengths
1015 for (size_t len=minSize; true; len+=8) {
1016 testLenMatches.clear();
1017 // filter matches
1018 for (size_t _k=begin; _k<end; _k++) {
1019 BlockMatch& k=matches[_k];
1020 // match length shall be greater than or equal to current length
1021 if (len>k.len) continue;
1022
1023 // check for bad matches, which include:
1024 // - match overlapping with itself
1025 // - block only consisting of calls
1026 // - block containing a ret, jmp or stop
1027
1028 // 1. self-overlapping
1029 if (OVERLAPS(k.orig,k.orig+len,k.block,k.block+len)) continue;
1030
1031 // 2. only calls and jmp/ret/stop
1032 bool metCriteria=true;
1033 for (size_t l=k.orig; l<k.orig+len; l+=8) {
1034 if (buf[l]==0xd4 || buf[l]==0xd5) {
1035 metCriteria=false;
1036 break;
1037 }
1038 }
1039 if (!metCriteria) continue;
1040
1041 // 3. jmp/ret/stop
1042 for (size_t l=k.orig; l<k.orig+len; l+=8) {
1043 if (buf[l]==0xd9 || buf[l]==0xda || buf[l]==0xdf) {
1044 metCriteria=false;
1045 break;
1046 }
1047 }
1048 if (!metCriteria) continue;
1049
1050 // all criteria met
1051 testLenMatches.push_back(k);
1052 }
1053
1054 // get out if no further matches (trying with bigger sizes is guaranteed to fail)
1055 if (testLenMatches.empty()) {
1056 break;
1057 }
1058
1059 // check for overlapping matches
1060 size_t overlapPos=testLenMatches[0].orig;
1061 size_t validCount=0;
1062 for (BlockMatch& k: testLenMatches) {
1063 //logV("test %d with %d",(int)overlapPos,(int)k.block);
1064 if (OVERLAPS(overlapPos,overlapPos+len,k.block,k.block+len)) {
1065 k.done=true;
1066 //logW("overlap");
1067 } else {
1068 validCount++;
1069 }
1070 overlapPos=k.block;
1071 }
1072
1073
1074 // calculate (weighted) benefit
1075 const int blockSize=estimateBlockSize(&buf[testLenMatches[0].orig],len,speedDial);
1076 const int gains=((blockSize-3)*validCount)-4;
1077 int finalBenefit=gains*2+len*3;
1078 if (gains<1) finalBenefit=-1;
1079
1080 // check whether this set of matches has greater benefit
1081 if (finalBenefit>bestBenefit.benefit) {
1082 //logD("- %x (%d): %d = %d",(int)i,(int)len,(int)testLenMatches.size(),finalBenefit);
1083 bestBenefit=MatchBenefit(begin,finalBenefit,len);
1084 // copy matches so we don't have to select them later
1085 workMatches=testLenMatches;
1086 }
1087 }
1088 }
1089
1090 // quit if there isn't benefit
1091 if (bestBenefit.benefit<1) return stream;
1092
1093 // quit if there's nothing to work on
1094 if (workMatches.empty()) return stream;
1095
1096 // pick best benefit
1097 logI("BEST BENEFIT: %d in %x with size %u",bestBenefit.benefit,(int)bestBenefit.index,bestBenefit.len);
1098
1099 // work on matches with this benefit
1100 size_t bestOrig=matches[bestBenefit.index].orig;
1101 logI("match count %d",(int)workMatches.size());
1102
1103 if (progress!=NULL) {
1104 progress->optStage=3;
1105 progress->origCurrent=origs.size();
1106 }
1107
1108 // make sub-block
1109 size_t subBlockID=subBlocks.size();
1110 logV("new sub-block %d",(int)subBlockID);
1111
1112 assert(!(bestOrig&7));
1113
1114 // isolate this sub-block
1115 SafeWriter* newBlock=new SafeWriter;
1116 newBlock->init();
1117 newBlock->write(&buf[bestOrig],bestBenefit.len);
1118 newBlock->writeC(0xd9); // ret
1119 // padding
1120 newBlock->writeC(0);
1121 newBlock->writeC(0);
1122 newBlock->writeC(0);
1123 newBlock->writeC(0);
1124 newBlock->writeC(0);
1125 newBlock->writeC(0);
1126 newBlock->writeC(0);
1127 subBlocks.push_back(newBlock);
1128
1129 // insert call on the original block
1130 buf[bestOrig]=0xd4;
1131 buf[bestOrig+1]=subBlockID&0xff;
1132 buf[bestOrig+2]=(subBlockID>>8)&0xff;
1133 buf[bestOrig+3]=(subBlockID>>16)&0xff;
1134 buf[bestOrig+4]=(subBlockID>>24)&0xff;
1135 buf[bestOrig+5]=0;
1136 buf[bestOrig+6]=0;
1137 buf[bestOrig+7]=0;
1138
1139 // replace the rest with nop
1140 for (size_t j=bestOrig+8; j<bestOrig+bestBenefit.len; j++) {
1141 buf[j]=0xd1;
1142 }
1143
1144 // set matches to this sub-block
1145 for (BlockMatch& i: workMatches) {
1146 // skip invalid matches
1147 if (i.done) continue;
1148
1149 assert(!(i.block&7));
1150
1151 // set match to this sub-block
1152 buf[i.block]=0xd4;
1153 buf[i.block+1]=subBlockID&0xff;
1154 buf[i.block+2]=(subBlockID>>8)&0xff;
1155 buf[i.block+3]=(subBlockID>>16)&0xff;
1156 buf[i.block+4]=(subBlockID>>24)&0xff;
1157 buf[i.block+5]=0;
1158 buf[i.block+6]=0;
1159 buf[i.block+7]=0;
1160
1161 // replace the rest with nop
1162 for (size_t j=i.block+8; j<i.block+bestBenefit.len; j++) {
1163 buf[j]=0xd1;
1164 }
1165 }
1166
1167 logV("done!");
1168
1169 // remove nop's
1170 stream=stripNops(stream);
1171 buf=stream->getFinalBuf();
1172
1173 return stream;
1174 }
1175
1176 SafeWriter* packStream(SafeWriter* s, unsigned char* speedDial) {
1177 std::unordered_map<unsigned int,unsigned int> addrTable;
1178 SafeWriter* oldStream=s;
1179 unsigned char* buf=oldStream->getFinalBuf();
1180 s=new SafeWriter;
1181 s->init();
1182
1183 // prepare address map
1184 size_t addr=0;
1185 for (size_t i=0; i<oldStream->size(); i+=8) {
1186 addrTable[i]=addr;
1187 addr+=getInsLength(buf[i],_EXT(buf,i,oldStream->size()),speedDial);
1188 }
1189
1190 // translate addresses and write stream
1191 for (size_t i=0; i<oldStream->size(); i+=8) {
1192 int insLen=getInsLength(buf[i],_EXT(buf,i,oldStream->size()),speedDial);
1193 if (insLen<1) {
1194 logE("INS %x NOT IMPLEMENTED...",buf[i]);
1195 break;
1196 }
1197 switch (buf[i]) {
1198 case 0xd5: { // calli
1199 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<16)|(buf[i+4]<<24);
1200 try {
1201 addr=addrTable[addr];
1202 // check whether we have sufficient room to turn this into a 16-bit call
1203 if (addr<0xff00) {
1204 buf[i]=0xd8;
1205 buf[i+1]=addr&0xff;
1206 buf[i+2]=(addr>>8)&0xff;
1207 buf[i+3]=0xd1;
1208 buf[i+4]=0xd1;
1209 } else {
1210 buf[i]=0xd5;
1211 buf[i+1]=addr&0xff;
1212 buf[i+2]=(addr>>8)&0xff;
1213 buf[i+3]=(addr>>16)&0xff;
1214 buf[i+4]=(addr>>24)&0xff;
1215 }
1216 } catch (std::out_of_range& e) {
1217 logW("address %x is not mappable!",addr);
1218 }
1219 break;
1220 }
1221 case 0xda: { // jmp
1222 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<16)|(buf[i+4]<<24);
1223 try {
1224 addr=addrTable[addr];
1225 buf[i+1]=addr&0xff;
1226 buf[i+2]=(addr>>8)&0xff;
1227 buf[i+3]=(addr>>16)&0xff;
1228 buf[i+4]=(addr>>24)&0xff;
1229 } catch (std::out_of_range& e) {
1230 logW("address %x is not mappable!",addr);
1231 }
1232 break;
1233 }
1234 case 0xd8: { // call
1235 logW("16-bit call should NEVER be generated. aborting!");
1236 abort();
1237 break;
1238 }
1239 }
1240 s->write(&buf[i],insLen);
1241 }
1242
1243 oldStream->finish();
1244 delete oldStream;
1245 return s;
1246 }
1247
1248 SafeWriter* DivEngine::saveCommand(DivCSProgress* progress, DivCSOptions options) {
1249 stop();
1250 repeatPattern=false;
1251 shallStop=false;
1252 setOrder(0);
1253 BUSY_BEGIN_SOFT;
1254 // determine loop point
1255 int loopOrder=0;
1256 int loopRow=0;
1257 int loopEnd=0;
1258 walkSong(loopOrder,loopRow,loopEnd);
1259 logI("loop point: %d %d",loopOrder,loopRow);
1260
1261 int cmdPopularity[256];
1262 int delayPopularity[256];
1263
1264 int sortedCmdPopularity[16];
1265 int sortedDelayPopularity[16];
1266 unsigned char sortedCmd[16];
1267 unsigned char sortedDelay[16];
1268
1269 SafeWriter* globalStream;
1270 SafeWriter* chanStream[DIV_MAX_CHANS];
1271 unsigned int chanStreamOff[DIV_MAX_CHANS];
1272 unsigned int chanStackSize[DIV_MAX_CHANS];
1273 std::vector<size_t> tickPos[DIV_MAX_CHANS];
1274 int loopTick=-1;
1275
1276 memset(cmdPopularity,0,256*sizeof(int));
1277 memset(delayPopularity,0,256*sizeof(int));
1278 memset(chanStream,0,DIV_MAX_CHANS*sizeof(void*));
1279 memset(chanStreamOff,0,DIV_MAX_CHANS*sizeof(unsigned int));
1280 memset(chanStackSize,0,DIV_MAX_CHANS*sizeof(unsigned int));
1281 memset(sortedCmdPopularity,0,16*sizeof(int));
1282 memset(sortedDelayPopularity,0,16*sizeof(int));
1283 memset(sortedCmd,0,16);
1284 memset(sortedDelay,0,16);
1285
1286 SafeWriter* w=new SafeWriter;
1287 w->init();
1288
1289 globalStream=new SafeWriter;
1290 globalStream->init();
1291
1292 // write header
1293 w->write("FCS",4);
1294 w->writeS(chans);
1295 // flags
1296 w->writeC((options.longPointers?1:0)|(options.bigEndian?2:0));
1297 // reserved
1298 w->writeC(0);
1299 // preset delays and speed dial
1300 for (int i=0; i<32; i++) {
1301 w->writeC(0);
1302 }
1303 // offsets
1304 for (int i=0; i<chans; i++) {
1305 chanStream[i]=new SafeWriter;
1306 chanStream[i]->init();
1307 if (options.longPointers) {
1308 w->writeI(0);
1309 } else {
1310 w->writeS(0);
1311 }
1312 }
1313 // max stack sizes
1314 for (int i=0; i<chans; i++) {
1315 w->writeC(0);
1316 }
1317
1318 // play the song ourselves
1319 bool done=false;
1320 playSub(false);
1321
1322 int tick=0;
1323 bool oldCmdStreamEnabled=cmdStreamEnabled;
1324 cmdStreamEnabled=true;
1325 double curDivider=divider;
1326
1327 // PASS 0: play the song and log channel command streams
1328 // song beginning marker
1329 for (int i=0; i<chans; i++) {
1330 chanStream[i]->writeC(0xd0);
1331 chanStream[i]->writeC(i);
1332 chanStream[i]->writeC(0x00);
1333 chanStream[i]->writeC(0x00);
1334 // padding
1335 chanStream[i]->writeC(0x00);
1336 chanStream[i]->writeC(0x00);
1337 chanStream[i]->writeC(0x00);
1338 chanStream[i]->writeC(0x00);
1339 }
1340 while (!done) {
1341 for (int i=0; i<chans; i++) {
1342 tickPos[i].push_back(chanStream[i]->tell());
1343 }
1344 if (loopTick==-1) {
1345 if (loopOrder==curOrder && loopRow==curRow) {
1346 if ((ticks-((tempoAccum+virtualTempoN)/virtualTempoD))<=0) {
1347 logI("loop is on tick %d",tick);
1348 loopTick=tick;
1349 // loop marker
1350 for (int i=0; i<chans; i++) {
1351 chanStream[i]->writeC(0xd0);
1352 chanStream[i]->writeC(i);
1353 chanStream[i]->writeC(0x00);
1354 chanStream[i]->writeC(0x01);
1355 // padding
1356 chanStream[i]->writeC(0x00);
1357 chanStream[i]->writeC(0x00);
1358 chanStream[i]->writeC(0x00);
1359 chanStream[i]->writeC(0x00);
1360 }
1361 }
1362 }
1363 }
1364 if (nextTick(false,true) || !playing) {
1365 done=true;
1366 break;
1367 }
1368 // get command stream
1369 if (curDivider!=divider) {
1370 curDivider=divider;
1371 chanStream[0]->writeC(0xdb);
1372 chanStream[0]->writeI((int)(curDivider*65536));
1373 // padding
1374 chanStream[0]->writeC(0x00);
1375 chanStream[0]->writeC(0x00);
1376 chanStream[0]->writeC(0x00);
1377 }
1378 for (DivCommand& i: cmdStream) {
1379 switch (i.cmd) {
1380 // strip away hinted/useless commands
1381 case DIV_CMD_GET_VOLUME:
1382 case DIV_CMD_VOLUME:
1383 case DIV_CMD_PANNING:
1384 case DIV_CMD_NOTE_PORTA:
1385 case DIV_CMD_LEGATO:
1386 case DIV_CMD_PITCH:
1387 case DIV_CMD_PRE_NOTE:
1388 break;
1389 default:
1390 cmdPopularity[i.cmd]++;
1391 writeCommandValues(chanStream[i.chan],i,options.bigEndian);
1392 break;
1393 }
1394 }
1395 cmdStream.clear();
1396 for (int i=0; i<chans; i++) {
1397 chanStream[i]->writeC(0xde);
1398 // padding
1399 chanStream[i]->writeC(0x00);
1400 chanStream[i]->writeC(0x00);
1401 chanStream[i]->writeC(0x00);
1402 chanStream[i]->writeC(0x00);
1403 chanStream[i]->writeC(0x00);
1404 chanStream[i]->writeC(0x00);
1405 chanStream[i]->writeC(0x00);
1406 }
1407 tick++;
1408 }
1409 if (!playing || loopTick<0) {
1410 for (int i=0; i<chans; i++) {
1411 chanStream[i]->writeC(0xdf);
1412 // padding
1413 chanStream[i]->writeC(0x00);
1414 chanStream[i]->writeC(0x00);
1415 chanStream[i]->writeC(0x00);
1416 chanStream[i]->writeC(0x00);
1417 chanStream[i]->writeC(0x00);
1418 chanStream[i]->writeC(0x00);
1419 chanStream[i]->writeC(0x00);
1420 }
1421 } else {
1422 for (int i=0; i<chans; i++) {
1423 if ((int)tickPos[i].size()>loopTick) {
1424 chanStream[i]->writeC(0xda);
1425 chanStream[i]->writeI(tickPos[i][loopTick]);
1426 logD("chan %d loop addr: %x",i,tickPos[i][loopTick]);
1427 // padding
1428 chanStream[i]->writeC(0x00);
1429 chanStream[i]->writeC(0x00);
1430 chanStream[i]->writeC(0x00);
1431 } else {
1432 logW("chan %d unable to find loop addr!",i);
1433 chanStream[i]->writeC(0xdf);
1434 // padding
1435 chanStream[i]->writeC(0x00);
1436 chanStream[i]->writeC(0x00);
1437 chanStream[i]->writeC(0x00);
1438 chanStream[i]->writeC(0x00);
1439 chanStream[i]->writeC(0x00);
1440 chanStream[i]->writeC(0x00);
1441 chanStream[i]->writeC(0x00);
1442 }
1443 }
1444 }
1445 logV("%d",tick);
1446 cmdStreamEnabled=oldCmdStreamEnabled;
1447
1448 remainingLoops=-1;
1449 playing=false;
1450 freelance=false;
1451 extValuePresent=false;
1452 BUSY_END;
1453
1454 // PASS 1: optimize command calls
1455 if (!options.noCmdCallOpt) {
1456 // calculate command usage
1457 int sortCand=-1;
1458 int sortPos=0;
1459 while (sortPos<16) {
1460 sortCand=-1;
1461 for (int i=DIV_CMD_SAMPLE_MODE; i<256; i++) {
1462 if (cmdPopularity[i]) {
1463 if (sortCand==-1) {
1464 sortCand=i;
1465 } else if (cmdPopularity[sortCand]<cmdPopularity[i]) {
1466 sortCand=i;
1467 }
1468 }
1469 }
1470 if (sortCand==-1) break;
1471
1472 sortedCmdPopularity[sortPos]=cmdPopularity[sortCand];
1473 sortedCmd[sortPos]=sortCand;
1474 cmdPopularity[sortCand]=0;
1475 sortPos++;
1476 }
1477
1478 // set speed dial commands
1479 for (int h=0; h<chans; h++) {
1480 unsigned char* buf=chanStream[h]->getFinalBuf();
1481 for (size_t i=0; i<chanStream[h]->size(); i+=8) {
1482 if (buf[i]==0xd7) {
1483 // find whether this command is in speed dial
1484 for (int j=0; j<16; j++) {
1485 if (buf[i+1]==sortedCmd[j]) {
1486 buf[i]=0xe0+j;
1487 // move everything to the left
1488 for (int k=i+2; k<(int)i+8; k++) {
1489 buf[k-1]=buf[k];
1490 }
1491 break;
1492 }
1493 }
1494 }
1495 }
1496 }
1497 }
1498
1499 // PASS 2: condense delays
1500 if (!options.noDelayCondense) {
1501 // calculate delay usage
1502 for (int h=0; h<chans; h++) {
1503 unsigned char* buf=chanStream[h]->getFinalBuf();
1504 int delayCount=0;
1505 for (size_t i=0; i<chanStream[h]->size(); i+=8) {
1506 if (buf[i]==0xde) {
1507 delayCount++;
1508 } else {
1509 if (delayCount>1 && delayCount<=255) {
1510 delayPopularity[delayCount]++;
1511 }
1512 delayCount=0;
1513 }
1514 }
1515 }
1516
1517 // preset delays
1518 int sortCand=-1;
1519 int sortPos=0;
1520 while (sortPos<16) {
1521 sortCand=-1;
1522 for (int i=0; i<256; i++) {
1523 if (delayPopularity[i]) {
1524 if (sortCand==-1) {
1525 sortCand=i;
1526 } else if (delayPopularity[sortCand]<delayPopularity[i]) {
1527 sortCand=i;
1528 }
1529 }
1530 }
1531 if (sortCand==-1) break;
1532
1533 sortedDelayPopularity[sortPos]=delayPopularity[sortCand];
1534 sortedDelay[sortPos]=sortCand;
1535 delayPopularity[sortCand]=0;
1536 sortPos++;
1537 }
1538
1539 // condense delays
1540 for (int h=0; h<chans; h++) {
1541 unsigned char* buf=chanStream[h]->getFinalBuf();
1542 int delayPos=-1;
1543 int delayCount=0;
1544 int delayLast=0;
1545 for (size_t i=0; i<chanStream[h]->size(); i+=8) {
1546 if (buf[i]==0xde) {
1547 if (delayPos==-1) delayPos=i;
1548 delayCount++;
1549 delayLast=i;
1550 } else {
1551 // finish the last delay if any
1552 if (delayPos!=-1) {
1553 if (delayCount>1) {
1554 if (delayLast<delayPos) {
1555 logE("delayLast<delayPos! %d<%d",delayLast,delayPos);
1556 } else {
1557 // write condensed delay and fill the rest with nop
1558 if (delayCount>255) {
1559 buf[delayPos++]=0xdc;
1560 buf[delayPos++]=delayCount&0xff;
1561 buf[delayPos++]=(delayCount>>8)&0xff;
1562 } else {
1563 bool foundShort=false;
1564 for (int j=0; j<16; j++) {
1565 if (sortedDelay[j]==delayCount) {
1566 buf[delayPos++]=0xf0+j;
1567 foundShort=true;
1568 break;
1569 }
1570 }
1571 if (!foundShort) {
1572 buf[delayPos++]=0xdd;
1573 buf[delayPos++]=delayCount;
1574 }
1575 }
1576 // padding
1577 while (delayPos&7) buf[delayPos++]=0;
1578 // fill with nop
1579 for (int j=delayPos; j<=delayLast; j++) {
1580 buf[j]=0xd1;
1581 }
1582 }
1583 }
1584 delayPos=-1;
1585 delayCount=0;
1586 }
1587 }
1588 }
1589 }
1590 }
1591
1592 // PASS 3: note off + one-tick wait
1593 // optimize one-tick gaps sometimes used in songs
1594 for (int h=0; h<chans; h++) {
1595 unsigned char* buf=chanStream[h]->getFinalBuf();
1596 if (chanStream[h]->size()<8) continue;
1597 for (size_t i=0; i<chanStream[h]->size()-8; i+=8) {
1598 // find note off
1599 if (buf[i]==0xb5) {
1600 // check for contiguous wait 1
1601 if (buf[i+8]==0xde) {
1602 // turn it into 0xf6 (note off + wait 1) and change the next one to nop
1603 buf[i]=0xd6;
1604 buf[i+8]=0xd1;
1605
1606 // skip the next instruction
1607 i+=8;
1608 }
1609 }
1610 }
1611 }
1612
1613 // PASS 4: remove nop's
1614 // this includes modifying call addresses to compensate
1615 for (int h=0; h<chans; h++) {
1616 chanStream[h]=stripNops(chanStream[h]);
1617 }
1618
1619 // PASS 5: put all channels together
1620 for (int i=0; i<chans; i++) {
1621 chanStreamOff[i]=globalStream->tell();
1622 logI("- %d: off %x size %ld",i,chanStreamOff[i],chanStream[i]->size());
1623 reloc8(chanStream[i]->getFinalBuf(),chanStream[i]->size(),0,globalStream->tell());
1624 globalStream->write(chanStream[i]->getFinalBuf(),chanStream[i]->size());
1625 chanStream[i]->finish();
1626 delete chanStream[i];
1627 }
1628
1629 // PASS 6: find sub-blocks and isolate them
1630 if (!options.noSubBlock) {
1631 std::vector<SafeWriter*> subBlocks;
1632 size_t beforeSize=globalStream->size();
1633
1634 // 6 is the minimum size that can be reliably optimized
1635 logI("finding sub-blocks");
1636
1637 bool haveBlocks=false;
1638 subBlocks.clear();
1639 // repeat until no more sub-blocks are produced
1640 do {
1641 logD("iteration...");
1642 globalStream=findSubBlocks(globalStream,subBlocks,sortedCmd,progress);
1643
1644 haveBlocks=!subBlocks.empty();
1645 // insert sub-blocks and resolve symbols
1646 logI("%d sub-blocks total",(int)subBlocks.size());
1647 std::vector<size_t> blockOff;
1648 blockOff.clear();
1649 globalStream->seek(0,SEEK_END);
1650 for (size_t i=0; i<subBlocks.size(); i++) {
1651 SafeWriter* block=subBlocks[i];
1652
1653 // write sub-block
1654 blockOff.push_back(globalStream->tell());
1655 logV("block size: %d",(int)block->size());
1656 assert(!(block->size()&7));
1657 globalStream->write(block->getFinalBuf(),block->size());
1658 }
1659
1660 for (SafeWriter* block: subBlocks) {
1661 block->finish();
1662 delete block;
1663 }
1664 subBlocks.clear();
1665
1666 // resolve symbols
1667 unsigned char* buf=globalStream->getFinalBuf();
1668 for (size_t j=0; j<globalStream->size(); j+=8) {
1669 if (buf[j]==0xd4) { // callsym
1670 unsigned int addr=buf[j+1]|(buf[j+2]<<8)|(buf[j+3]<<16)|(buf[j+4]<<24);
1671 if (addr<blockOff.size()) {
1672 // turn it into call
1673 addr=blockOff[addr];
1674 buf[j]=0xd5;
1675 buf[j+1]=addr&0xff;
1676 buf[j+2]=(addr>>8)&0xff;
1677 buf[j+3]=(addr>>16)&0xff;
1678 buf[j+4]=(addr>>24)&0xff;
1679 } else {
1680 logE("requested symbol %d is out of bounds!",addr);
1681 abort();
1682 }
1683 }
1684 }
1685 } while (haveBlocks);
1686
1687 size_t afterSize=globalStream->size();
1688 logI("(before: %d - after: %d)",(int)beforeSize,(int)afterSize);
1689 assert(!(globalStream->size()&7));
1690 }
1691
1692 // PASS 7: pack stream
1693 globalStream=packStream(globalStream,sortedCmd);
1694
1695 // PASS 8: remove nop's which may be produced by 32-bit call conversion
1696 // also find new offsets
1697 globalStream=stripNopsPacked(globalStream,sortedCmd,chanStreamOff);
1698
1699 for (int h=0; h<chans; h++) {
1700 chanStreamOff[h]+=w->tell();
1701 }
1702
1703 // write results (convert addresses to big-endian if necessary)
1704 reloc(globalStream->getFinalBuf(),globalStream->size(),0,w->tell(),sortedCmd,options.bigEndian);
1705 w->write(globalStream->getFinalBuf(),globalStream->size());
1706
1707 // calculate max stack sizes
1708 for (int h=0; h<chans; h++) {
1709 std::stack<unsigned int> callStack;
1710 unsigned int maxStackSize=0;
1711 unsigned char* buf=w->getFinalBuf();
1712 bool done=false;
1713 for (size_t i=chanStreamOff[h]; i<w->size();) {
1714 int insLen=getInsLength(buf[i],_EXT(buf,i,w->size()),sortedCmd);
1715 if (insLen<1) {
1716 logE("%d: INS %x NOT IMPLEMENTED...",h,buf[i]);
1717 break;
1718 }
1719 switch (buf[i]) {
1720 case 0xd5: { // calli
1721 unsigned int addr=buf[i+1]|(buf[i+2]<<8)|(buf[i+3]<<16)|(buf[i+4]<<24);
1722 callStack.push(i+insLen);
1723 if (callStack.size()>maxStackSize) maxStackSize=callStack.size();
1724 i=addr;
1725 insLen=0;
1726 break;
1727 }
1728 case 0xd8: { // call
1729 unsigned short addr=buf[i+1]|(buf[i+2]<<8);
1730 callStack.push(i+insLen);
1731 if (callStack.size()>maxStackSize) maxStackSize=callStack.size();
1732 i=addr;
1733 insLen=0;
1734 break;
1735 }
1736 case 0xd9: { // ret
1737 if (callStack.empty()) {
1738 logE("%d: trying to ret with empty stack!",h);
1739 done=true;
1740 break;
1741 }
1742 i=callStack.top();
1743 insLen=0;
1744 callStack.pop();
1745 break;
1746 }
1747 case 0xda: // jmp
1748 case 0xdf: // stop
1749 done=true;
1750 break;
1751 }
1752 if (maxStackSize>255) {
1753 logE("%d: stack overflow!",h);
1754 break;
1755 }
1756 if (done) break;
1757 i+=insLen;
1758 }
1759
1760 chanStackSize[h]=maxStackSize;
1761 }
1762
1763 globalStream->finish();
1764 delete globalStream;
1765
1766 w->seek(40,SEEK_SET);
1767 for (int i=0; i<chans; i++) {
1768 if (options.longPointers) {
1769 if (options.bigEndian) {
1770 w->writeI_BE(chanStreamOff[i]);
1771 } else {
1772 w->writeI(chanStreamOff[i]);
1773 }
1774 } else {
1775 if (options.bigEndian) {
1776 w->writeS_BE(chanStreamOff[i]);
1777 } else {
1778 w->writeS(chanStreamOff[i]);
1779 }
1780 }
1781 }
1782
1783 logD("maximum stack sizes:");
1784 unsigned int cumulativeStackSize=0;
1785 for (int i=0; i<chans; i++) {
1786 w->writeC(chanStackSize[i]);
1787 logD("- %d: %d",i,chanStackSize[i]);
1788 cumulativeStackSize+=chanStackSize[i];
1789 }
1790 logD("(total stack size: %d)",cumulativeStackSize);
1791
1792 logD("delay popularity:");
1793 w->seek(8,SEEK_SET);
1794 for (int i=0; i<16; i++) {
1795 w->writeC(sortedDelay[i]);
1796 if (sortedDelayPopularity[i]) logD("- %d: %d",sortedDelay[i],sortedDelayPopularity[i]);
1797 }
1798
1799 logD("command popularity:");
1800 for (int i=0; i<16; i++) {
1801 w->writeC(sortedCmd[i]);
1802 if (sortedCmdPopularity[i]) logD("- %s ($%.2x): %d",cmdName[sortedCmd[i]],sortedCmd[i],sortedCmdPopularity[i]);
1803 }
1804
1805 return w;
1806 }