Debian Codegraph @

src/engine/fileOps/mod.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 "fileOpsCommon.h"
21
22 bool DivEngine::loadMod(unsigned char* file, size_t len) {
23 struct InvalidHeaderException {};
24 bool success=false;
25 int chCount=0;
26 int ordCount=0;
27 std::vector<int> patPtr;
28 char magic[4]={0,0,0,0};
29 short defaultVols[31];
30 int sampLens[31];
31 // 0=arp, 1=pslide, 2=vib, 3=trem, 4=vslide
32 bool fxUsage[DIV_MAX_CHANS][5];
33 SafeReader reader=SafeReader(file,len);
34 warnings="";
35
36 memset(defaultVols,0,31*sizeof(short));
37 memset(sampLens,0,31*sizeof(int));
38 memset(fxUsage,0,DIV_MAX_CHANS*5*sizeof(bool));
39
40 try {
41 DivSong ds;
42 ds.tuning=436.0;
43 ds.version=DIV_VERSION_MOD;
44 ds.linearPitch=0;
45 ds.noSlidesOnFirstTick=true;
46 ds.rowResetsArpPos=true;
47 ds.ignoreJumpAtEnd=false;
48 ds.delayBehavior=0;
49
50 int insCount=31;
51 bool bypassLimits=false;
52
53 // check mod magic bytes
54 if (!reader.seek(1080,SEEK_SET)) {
55 logD("couldn't seek to 1080");
56 throw EndOfFileException(&reader,reader.tell());
57 }
58 if (reader.read(magic,4)!=4) {
59 logD("the magic isn't complete");
60 throw EndOfFileException(&reader,reader.tell());
61 }
62 if (memcmp(magic,"M.K.",4)==0 || memcmp(magic,"M!K!",4)==0 || memcmp(magic,"M&K!",4)==0) {
63 logD("detected a ProTracker module");
64 ds.systemName="Amiga";
65 chCount=4;
66 } else if (memcmp(magic,"CD81",4)==0 || memcmp(magic,"OKTA",4)==0 || memcmp(magic,"OCTA",4)==0) {
67 logD("detected an Oktalyzer/Octalyzer/OctaMED module");
68 ds.systemName="Amiga (8-channel)";
69 chCount=8;
70 } else if (memcmp(magic+1,"CHN",3)==0 && magic[0]>='1' && magic[0]<='9') {
71 logD("detected a FastTracker module");
72 ds.systemName="PC";
73 chCount=magic[0]-'0';
74 } else if (memcmp(magic,"FLT",3)==0 && magic[3]>='1' && magic[3]<='9') {
75 logD("detected a Fairlight module");
76 ds.systemName="Amiga";
77 chCount=magic[3]-'0';
78 } else if (memcmp(magic,"TDZ",3)==0 && magic[3]>='1' && magic[3]<='9') {
79 logD("detected a TakeTracker module");
80 ds.systemName="PC";
81 chCount=magic[3]-'0';
82 } else if ((memcmp(magic+2,"CH",2)==0 || memcmp(magic+2,"CN",2)==0) &&
83 (magic[0]>='1' && magic[0]<='9' && magic[1]>='0' && magic[1]<='9')) {
84 logD("detected a Fast/TakeTracker module");
85 ds.systemName="PC";
86 chCount=((magic[0]-'0')*10)+(magic[1]-'0');
87 } else {
88 insCount=15;
89 logD("possibly a Soundtracker module");
90 ds.systemName="Amiga";
91 chCount=4;
92 }
93
94 // song name
95 if (!reader.seek(0,SEEK_SET)) {
96 logD("couldn't seek to 0");
97 throw EndOfFileException(&reader,reader.tell());
98 }
99 ds.name=reader.readStringLatin1(20);
100 logI("%s",ds.name);
101
102 // samples
103 logD("reading samples... (%d)",insCount);
104 ds.sample.reserve(insCount);
105 for (int i=0; i<insCount; i++) {
106 DivSample* sample=new DivSample;
107 sample->depth=DIV_SAMPLE_DEPTH_8BIT;
108 sample->name=reader.readStringLatin1(22);
109 logD("%d: %s",i+1,sample->name);
110 int slen=((unsigned short)reader.readS_BE())*2;
111 sampLens[i]=slen;
112 if (slen==2) slen=0;
113 signed char fineTune=reader.readC()&0x0f;
114 if (fineTune>=8) fineTune-=16;
115 sample->rate=(int)(pow(2.0,(double)fineTune/96.0)*8363.0);
116 sample->centerRate=sample->rate;
117 defaultVols[i]=reader.readC();
118 int loopStart=reader.readS_BE()*2;
119 int loopLen=reader.readS_BE()*2;
120 int loopEnd=loopStart+loopLen;
121 // bunch of checks since ProTracker abuses those for one-shot samples
122 if (loopStart>loopEnd || loopEnd<4 || loopLen<4) {
123 loopStart=0;
124 loopLen=0;
125 }
126 if (loopLen>=2) {
127 sample->loopStart=loopStart;
128 sample->loopEnd=loopEnd;
129 sample->loop=(sample->loopStart>=0)&&(sample->loopEnd>=0);
130 }
131 sample->init(slen);
132 ds.sample.push_back(sample);
133 }
134 ds.sampleLen=ds.sample.size();
135
136 // orders
137 ds.subsong[0]->ordersLen=ordCount=(unsigned char)reader.readC();
138 if (ds.subsong[0]->ordersLen<1 || ds.subsong[0]->ordersLen>128) {
139 logD("invalid order count!");
140 throw EndOfFileException(&reader,reader.tell());
141 }
142 unsigned char restartPos=reader.readC(); // restart position, unused
143 logD("restart position byte: %.2x",restartPos);
144 if (insCount==15) {
145 if (restartPos>0x60 && restartPos<0x80) {
146 logD("detected a Soundtracker module");
147 } else {
148 logD("no Soundtracker signature found");
149 throw EndOfFileException(&reader,reader.tell());
150 }
151 }
152
153 int patMax=0;
154 for (int i=0; i<128; i++) {
155 unsigned char pat=reader.readC();
156 if (pat>patMax) patMax=pat;
157 for (int j=0; j<chCount; j++) {
158 ds.subsong[0]->orders.ord[j][i]=pat;
159 }
160 }
161
162 if (insCount==15) {
163 if (!reader.seek(600,SEEK_SET)) {
164 logD("couldn't seek to 600");
165 throw EndOfFileException(&reader,reader.tell());
166 }
167 } else {
168 if (!reader.seek(1084,SEEK_SET)) {
169 logD("couldn't seek to 1084");
170 throw EndOfFileException(&reader,reader.tell());
171 }
172 }
173
174 // patterns
175 ds.subsong[0]->patLen=64;
176 for (int ch=0; ch<chCount; ch++) {
177 for (int i=0; i<5; i++) {
178 fxUsage[ch][i]=false;
179 }
180 }
181 for (int pat=0; pat<=patMax; pat++) {
182 DivPattern* chpats[DIV_MAX_CHANS];
183 for (int ch=0; ch<chCount; ch++) {
184 chpats[ch]=ds.subsong[0]->pat[ch].getPattern(pat,true);
185 }
186 for (int row=0; row<64; row++) {
187 for (int ch=0; ch<chCount; ch++) {
188 short* dstrow=chpats[ch]->data[row];
189 unsigned char data[4];
190 reader.read(&data,4);
191 // instrument
192 short ins=(data[0]&0xf0)|(data[2]>>4);
193 if (ins>0) {
194 dstrow[2]=ins-1;
195 dstrow[3]=defaultVols[ins-1];
196 }
197 // note
198 int period=data[1]+((data[0]&0x0f)<<8);
199 if (period>0 && period<0x0fff) {
200 short note=(short)round(log2(3424.0/period)*12);
201 dstrow[0]=((note+11)%12)+1;
202 dstrow[1]=(note-1)/12+1;
203 if (period<114) {
204 bypassLimits=true;
205 }
206 }
207 // effects are done later
208 short fxtyp=data[2]&0x0f;
209 short fxval=data[3];
210 dstrow[4]=fxtyp;
211 dstrow[5]=fxval;
212 switch (fxtyp) {
213 case 0:
214 if (fxval!=0) fxUsage[ch][0]=true;
215 break;
216 case 1: case 2: case 3:
217 fxUsage[ch][1]=true;
218 break;
219 case 4:
220 fxUsage[ch][2]=true;
221 break;
222 case 5:
223 fxUsage[ch][1]=true;
224 fxUsage[ch][4]=true;
225 break;
226 case 6:
227 fxUsage[ch][2]=true;
228 fxUsage[ch][4]=true;
229 break;
230 case 7:
231 fxUsage[ch][3]=true;
232 break;
233 case 10:
234 if (fxval!=0) fxUsage[ch][4]=true;
235 break;
236 }
237 }
238 }
239 }
240
241 // samples
242 size_t pos=reader.tell();
243 logD("reading sample data...");
244 for (int i=0; i<insCount; i++) {
245 logV("- %d: %d %d %d",i,pos,ds.sample[i]->samples,sampLens[i]);
246 if (!reader.seek(pos,SEEK_SET)) {
247 logD("%d: couldn't seek to %d",i,pos);
248 throw EndOfFileException(&reader,reader.tell());
249 }
250 reader.read(ds.sample[i]->data8,ds.sample[i]->samples);
251 pos+=sampLens[i];
252 }
253
254 // convert effects
255 logD("converting module...");
256 for (int ch=0; ch<=chCount; ch++) {
257 unsigned char fxCols=1;
258 for (int pat=0; pat<=patMax; pat++) {
259 auto* data=ds.subsong[0]->pat[ch].getPattern(pat,true)->data;
260 short lastPitchEffect=-1;
261 short lastEffectState[5]={-1,-1,-1,-1,-1};
262 short setEffectState[5]={-1,-1,-1,-1,-1};
263 for (int row=0;row<64;row++) {
264 const short fxUsageTyp[5]={0x00,0x01,0x04,0x07,0xFA};
265 short effectState[5]={0,0,0,0,0};
266 unsigned char curFxCol=0;
267 short fxTyp=data[row][4];
268 short fxVal=data[row][5];
269 auto writeFxCol=[data,row,&curFxCol](short typ, short val) {
270 data[row][4+curFxCol*2]=typ;
271 data[row][5+curFxCol*2]=val;
272 curFxCol++;
273 };
274 writeFxCol(-1,-1);
275 curFxCol=0;
276 switch (fxTyp) {
277 case 0: // arp
278 effectState[0]=fxVal;
279 break;
280 case 5: // vol slide + porta
281 effectState[4]=fxVal;
282 fxTyp=3;
283 fxVal=0;
284 // fall through
285 case 1: // note slide up
286 case 2: // note slide down
287 case 3: // porta
288 if (fxTyp==3 && fxVal==0) {
289 if (setEffectState[1]<0) break;
290 fxVal=setEffectState[1];
291 }
292 setEffectState[1]=fxVal;
293 effectState[1]=fxVal;
294 if ((effectState[1]!=lastEffectState[1]) ||
295 (fxTyp!=lastPitchEffect) ||
296 (effectState[1]!=0 && data[row][0]>0)) {
297 writeFxCol(fxTyp,fxVal);
298 }
299 lastPitchEffect=fxTyp;
300 lastEffectState[1]=fxVal;
301 break;
302 case 6: // vol slide + vibrato
303 effectState[4]=fxVal;
304 fxTyp=4;
305 fxVal=0;
306 // fall through
307 case 4: // vibrato
308 // TODO: handle 0 value?
309 if (fxVal==0) {
310 if (setEffectState[2]<0) break;
311 fxVal=setEffectState[2];
312 }
313 effectState[2]=fxVal;
314 setEffectState[2]=fxVal;
315 break;
316 case 7: // tremolo
317 if (fxVal==0) {
318 if (setEffectState[3]<0) break;
319 fxVal=setEffectState[3];
320 }
321 effectState[3]=fxVal;
322 setEffectState[3]=fxVal;
323 break;
324 case 9: // set offset
325 writeFxCol(0x91,fxVal);
326 break;
327 case 10: // vol slide
328 effectState[4]=fxVal;
329 break;
330 case 11: // jump to pos
331 writeFxCol(fxTyp,fxVal);
332 break;
333 case 12: // set vol
334 data[row][3]=MIN(0x40,fxVal);
335 break;
336 case 13: // break to row (BCD)
337 writeFxCol(fxTyp,((fxVal>>4)*10)+(fxVal&15));
338 break;
339 case 15: // set speed
340 // TODO: somehow handle VBlank tunes
341 // TODO: i am so sorry
342 if (fxVal>0x20 && ds.name!="klisje paa klisje") {
343 writeFxCol(0xf0,fxVal);
344 } else {
345 writeFxCol(0x0f,fxVal);
346 }
347 break;
348 case 14: // extended
349 fxTyp=fxVal>>4;
350 fxVal&=0x0f;
351 switch (fxTyp) {
352 case 0:
353 writeFxCol(0x10,!fxVal);
354 break;
355 case 1: // single note slide up
356 case 2: // single note slide down
357 writeFxCol(fxTyp-1+0xf1,fxVal);
358 break;
359 case 4: // vibrato waveform
360 switch (fxVal&3) {
361 case 0: // sine
362 writeFxCol(0xe3,0x00);
363 break;
364 case 1: // ramp down
365 writeFxCol(0xe3,0x05);
366 break;
367 case 2: // square
368 case 3:
369 writeFxCol(0xe3,0x06);
370 break;
371 }
372 break;
373 case 9: // retrigger
374 writeFxCol(0x0c,fxVal);
375 break;
376 case 10: // single vol slide up
377 case 11: // single vol slide down
378 writeFxCol(fxTyp-10+0xf8,fxVal);
379 break;
380 case 12: // note cut
381 case 13: // note delay
382 writeFxCol(fxTyp-12+0xec,fxVal);
383 break;
384 }
385 break;
386 }
387 for (int i=0; i<5; i++) {
388 // pitch slide and volume slide needs to be kept active on new note
389 // even after target/max is reached
390 if (fxUsage[ch][i] && (effectState[i]!=lastEffectState[i] || (effectState[i]!=0 && i==4 && data[row][3]>=0))) {
391 writeFxCol(fxUsageTyp[i],effectState[i]);
392 }
393 }
394 memcpy(lastEffectState,effectState,sizeof(effectState));
395 if (curFxCol>fxCols) {
396 fxCols=curFxCol;
397 }
398 }
399 }
400 ds.subsong[0]->pat[ch].effectCols=fxCols;
401 }
402
403 ds.subsong[0]->hz=50;
404 ds.systemLen=(chCount+3)/4;
405 for(int i=0; i<ds.systemLen; i++) {
406 ds.system[i]=DIV_SYSTEM_AMIGA;
407 ds.systemFlags[i].set("clockSel",1); // PAL
408 ds.systemFlags[i].set("stereoSep",80);
409 ds.systemFlags[i].set("bypassLimits",bypassLimits);
410 ds.systemFlags[i].set("chipType",(bool)(ds.systemLen>1 || bypassLimits));
411 }
412 for(int i=0; i<chCount; i++) {
413 ds.subsong[0]->chanShow[i]=true;
414 ds.subsong[0]->chanShowChanOsc[i]=true;
415 ds.subsong[0]->chanName[i]=fmt::sprintf("Channel %d",i+1);
416 ds.subsong[0]->chanShortName[i]=fmt::sprintf("C%d",i+1);
417 }
418 for(int i=chCount; i<ds.systemLen*4; i++) {
419 ds.subsong[0]->pat[i].effectCols=1;
420 ds.subsong[0]->chanShow[i]=false;
421 ds.subsong[0]->chanShowChanOsc[i]=false;
422 }
423
424 // instrument creation
425 ds.ins.reserve(insCount);
426 for(int i=0; i<insCount; i++) {
427 DivInstrument* ins=new DivInstrument;
428 ins->type=DIV_INS_AMIGA;
429 ins->amiga.initSample=i;
430 ins->name=ds.sample[i]->name;
431 ds.ins.push_back(ins);
432 }
433 ds.insLen=ds.ins.size();
434
435 // find subsongs
436 ds.findSubSongs(chCount);
437
438 if (active) quitDispatch();
439 BUSY_BEGIN_SOFT;
440 saveLock.lock();
441 song.unload();
442 song=ds;
443 changeSong(0);
444 recalcChans();
445 saveLock.unlock();
446 BUSY_END;
447 if (active) {
448 initDispatch();
449 BUSY_BEGIN;
450 renderSamples();
451 reset();
452 BUSY_END;
453 }
454 success=true;
455 } catch (EndOfFileException& e) {
456 //logE("premature end of file!");
457 lastError="incomplete file";
458 } catch (InvalidHeaderException& e) {
459 //logE("invalid info header!");
460 lastError="invalid info header!";
461 }
462 return success;
463 }
464