pass -d2 for proper debug symbols
[dosdemo] / libs / mikmod / loaders / load_it.c
1 /*      MikMod sound library
2         (c) 1998, 1999, 2000, 2001, 2002 Miodrag Vallat and others - see file
3         AUTHORS for complete list.
4
5         This library is free software; you can redistribute it and/or modify
6         it under the terms of the GNU Library General Public License as
7         published by the Free Software Foundation; either version 2 of
8         the License, or (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 Library General Public License for more details.
14
15         You should have received a copy of the GNU Library General Public
16         License along with this library; if not, write to the Free Software
17         Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18         02111-1307, USA.
19 */
20
21 /*==============================================================================
22
23   $Id$
24
25   Impulse tracker (IT) module loader
26
27 ==============================================================================*/
28
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #include <stdio.h>
38 #ifdef HAVE_MEMORY_H
39 #include <memory.h>
40 #endif
41 #include <string.h>
42
43 #include "mikmod_internals.h"
44 #include "mikmod_ctype.h"
45
46 #ifdef SUNOS
47 extern int fprintf(FILE *, const char *, ...);
48 #endif
49
50 /*========== Module structure */
51
52 /* header */
53 typedef struct ITHEADER {
54         CHAR    songname[26];
55         UBYTE   blank01[2];
56         UWORD   ordnum;
57         UWORD   insnum;
58         UWORD   smpnum;
59         UWORD   patnum;
60         UWORD   cwt;            /* Created with tracker (y.xx = 0x0yxx) */
61         UWORD   cmwt;           /* Compatible with tracker ver > than val. */
62         UWORD   flags;
63         UWORD   special;        /* bit 0 set = song message attached */
64         UBYTE   globvol;
65         UBYTE   mixvol;         /* mixing volume [ignored] */
66         UBYTE   initspeed;
67         UBYTE   inittempo;
68         UBYTE   pansep;         /* panning separation between channels */
69         UBYTE   zerobyte;
70         UWORD   msglength;
71         ULONG   msgoffset;
72         UBYTE   blank02[4];
73         UBYTE   pantable[64];
74         UBYTE   voltable[64];
75 } ITHEADER;
76
77 /* sample information */
78 typedef struct ITSAMPLE {
79         CHAR    filename[12];
80         UBYTE   zerobyte;
81         UBYTE   globvol;
82         UBYTE   flag;
83         UBYTE   volume;
84         UBYTE   panning;
85         CHAR    sampname[28];
86         UWORD   convert;        /* sample conversion flag */
87         ULONG   length;
88         ULONG   loopbeg;
89         ULONG   loopend;
90         ULONG   c5spd;
91         ULONG   susbegin;
92         ULONG   susend;
93         ULONG   sampoffset;
94         UBYTE   vibspeed;
95         UBYTE   vibdepth;
96         UBYTE   vibrate;
97         UBYTE   vibwave;        /* 0=sine, 1=rampdown, 2=square, 3=random (speed ignored) */
98 } ITSAMPLE;
99
100 /* instrument information */
101
102 #define ITENVCNT 25
103 #define ITNOTECNT 120
104 typedef struct ITINSTHEADER {
105         ULONG   size;                   /* (dword) Instrument size */
106         CHAR    filename[12];   /* (char) Instrument filename */
107         UBYTE   zerobyte;               /* (byte) Instrument type (always 0) */
108         UBYTE   volflg;
109         UBYTE   volpts;
110         UBYTE   volbeg;                 /* (byte) Volume loop start (node) */
111         UBYTE   volend;                 /* (byte) Volume loop end (node) */
112         UBYTE   volsusbeg;              /* (byte) Volume sustain begin (node) */
113         UBYTE   volsusend;              /* (byte) Volume Sustain end (node) */
114         UBYTE   panflg;
115         UBYTE   panpts;
116         UBYTE   panbeg;                 /* (byte) channel loop start (node) */
117         UBYTE   panend;                 /* (byte) channel loop end (node) */
118         UBYTE   pansusbeg;              /* (byte) channel sustain begin (node) */
119         UBYTE   pansusend;              /* (byte) channel Sustain end (node) */
120         UBYTE   pitflg;
121         UBYTE   pitpts;
122         UBYTE   pitbeg;                 /* (byte) pitch loop start (node) */
123         UBYTE   pitend;                 /* (byte) pitch loop end (node) */
124         UBYTE   pitsusbeg;              /* (byte) pitch sustain begin (node) */
125         UBYTE   pitsusend;              /* (byte) pitch Sustain end (node) */
126         UWORD   blank;
127         UBYTE   globvol;
128         UBYTE   chanpan;
129         UWORD   fadeout;                /* Envelope end / NNA volume fadeout */
130         UBYTE   dnc;                    /* Duplicate note check */
131         UBYTE   dca;                    /* Duplicate check action */
132         UBYTE   dct;                    /* Duplicate check type */
133         UBYTE   nna;                    /* New Note Action [0,1,2,3] */
134         UWORD   trkvers;                /* tracker version used to save [files only] */
135         UBYTE   ppsep;                  /* Pitch-pan Separation */
136         UBYTE   ppcenter;               /* Pitch-pan Center */
137         UBYTE   rvolvar;                /* random volume varations */
138         UBYTE   rpanvar;                /* random panning varations */
139         UWORD   numsmp;                 /* Number of samples in instrument [files only] */
140         CHAR    name[26];               /* Instrument name */
141         UBYTE   blank01[6];
142         UWORD   samptable[ITNOTECNT];/* sample for each note [note / samp pairs] */
143         UBYTE   volenv[200];         /* volume envelope (IT 1.x stuff) */
144         UBYTE   oldvoltick[ITENVCNT];/* volume tick position (IT 1.x stuff) */
145         UBYTE   volnode[ITENVCNT];   /* amplitude of volume nodes */
146         UWORD   voltick[ITENVCNT];   /* tick value of volume nodes */
147         SBYTE   pannode[ITENVCNT];   /* panenv - node points */
148         UWORD   pantick[ITENVCNT];   /* tick value of panning nodes */
149         SBYTE   pitnode[ITENVCNT];   /* pitchenv - node points */
150         UWORD   pittick[ITENVCNT];   /* tick value of pitch nodes */
151 } ITINSTHEADER;
152
153 /* unpacked note */
154
155 typedef struct ITNOTE {
156         UBYTE note,ins,volpan,cmd,inf;
157 } ITNOTE;
158
159 /*========== Loader data */
160
161 static ULONG *paraptr=NULL;     /* parapointer array (see IT docs) */
162 static ITHEADER *mh=NULL;
163 static ITNOTE *itpat=NULL;      /* allocate to space for one full pattern */
164 static UBYTE *mask=NULL;        /* arrays allocated to 64 elements and used for */
165 static ITNOTE *last=NULL;       /* uncompressing IT's pattern information */
166 static int numtrk=0;
167 static unsigned int old_effect;         /* if set, use S3M old-effects stuffs */
168
169 static const CHAR* IT_Version[]={
170         "ImpulseTracker  .  ",
171         "Compressed ImpulseTracker  .  ",
172         "ImpulseTracker 2.14p3",
173         "Compressed ImpulseTracker 2.14p3",
174         "ImpulseTracker 2.14p4",
175         "Compressed ImpulseTracker 2.14p4",
176 };
177
178 /* table for porta-to-note command within volume/panning column */
179 static const UBYTE portatable[10]= {0,1,4,8,16,32,64,96,128,255};
180
181 /*========== Loader code */
182
183 static BOOL IT_Test(void)
184 {
185         UBYTE id[4];
186
187         if(!_mm_read_UBYTES(id,4,modreader)) return 0;
188         if(!memcmp(id,"IMPM",4)) return 1;
189         return 0;
190 }
191
192 static BOOL IT_Init(void)
193 {
194         if(!(mh=(ITHEADER*)MikMod_malloc(sizeof(ITHEADER)))) return 0;
195         if(!(poslookup=(UBYTE*)MikMod_malloc(256*sizeof(UBYTE)))) return 0;
196         if(!(itpat=(ITNOTE*)MikMod_malloc(200*64*sizeof(ITNOTE)))) return 0;
197         if(!(mask=(UBYTE*)MikMod_malloc(64*sizeof(UBYTE)))) return 0;
198         if(!(last=(ITNOTE*)MikMod_malloc(64*sizeof(ITNOTE)))) return 0;
199
200         return 1;
201 }
202
203 static void IT_Cleanup(void)
204 {
205         FreeLinear();
206
207         MikMod_free(mh);
208         MikMod_free(poslookup);
209         MikMod_free(itpat);
210         MikMod_free(mask);
211         MikMod_free(last);
212         MikMod_free(paraptr);
213         MikMod_free(origpositions);
214         mh=NULL;
215         poslookup=NULL;
216         itpat=NULL;
217         mask=NULL;
218         last=NULL;
219         paraptr=NULL;
220         origpositions=NULL;
221 }
222
223 /* Because so many IT files have 64 channels as the set number used, but really
224    only use far less (usually from 8 to 24 still), I had to make this function,
225    which determines the number of channels that are actually USED by a pattern.
226
227    NOTE: You must first seek to the file location of the pattern before calling
228    this procedure.
229
230    Returns 0 on error
231 */
232 static BOOL IT_GetNumChannels(UWORD patrows)
233 {
234         int row=0,flag,ch;
235
236         do {
237                 if((flag=_mm_read_UBYTE(modreader))==EOF) {
238                         _mm_errno=MMERR_LOADING_PATTERN;
239                         return 0;
240                 }
241                 if(!flag)
242                         row++;
243                 else {
244                         ch=(flag-1)&63;
245                         remap[ch]=0;
246                         if(flag & 128) mask[ch]=_mm_read_UBYTE(modreader);
247                         if(mask[ch]&1)   _mm_skip_BYTE(modreader);
248                         if(mask[ch]&2)   _mm_skip_BYTE(modreader);
249                         if(mask[ch]&4)   _mm_skip_BYTE(modreader);
250                         if(mask[ch]&8) { _mm_skip_BYTE(modreader);_mm_skip_BYTE(modreader); }
251                 }
252         } while(row<patrows);
253
254         return 1;
255 }
256
257 static UBYTE* IT_ConvertTrack(ITNOTE* tr,UWORD numrows)
258 {
259         int t;
260         UBYTE note,ins,volpan;
261
262         UniReset();
263
264         for(t=0;t<numrows;t++) {
265                 note=tr[t*of.numchn].note;
266                 ins=tr[t*of.numchn].ins;
267                 volpan=tr[t*of.numchn].volpan;
268
269                 if(note!=255) {
270                         if(note==253)
271                                 UniWriteByte(UNI_KEYOFF);
272                         else if(note==254) {
273                                 UniPTEffect(0xc,-1);    /* note cut command */
274                                 volpan=255;
275                         } else
276                                 UniNote(note);
277                 }
278
279                 if((ins)&&(ins<100))
280                         UniInstrument(ins-1);
281                 else if(ins==253)
282                         UniWriteByte(UNI_KEYOFF);
283                 else if(ins!=255) { /* crap */
284                         _mm_errno=MMERR_LOADING_PATTERN;
285                         return NULL;
286                 }
287
288                 /* process volume / panning column
289                    volume / panning effects do NOT all share the same memory address
290                    yet. */
291                 if(volpan<=64)
292                         UniVolEffect(VOL_VOLUME,volpan);
293                 else if(volpan==65) /* fine volume slide up (65-74) - A0 case */
294                         UniVolEffect(VOL_VOLSLIDE,0);
295                 else if(volpan<=74)     { /* fine volume slide up (65-74) - general case */
296                         UniVolEffect(VOL_VOLSLIDE,0x0f+((volpan-65)<<4));
297                 } else if(volpan==75)   /* fine volume slide down (75-84) - B0 case */
298                         UniVolEffect(VOL_VOLSLIDE,0);
299                 else if(volpan<=84) {   /* fine volume slide down (75-84) - general case*/
300                         UniVolEffect(VOL_VOLSLIDE,0xf0+(volpan-75));
301                 } else if(volpan<=94)   /* volume slide up (85-94) */
302                         UniVolEffect(VOL_VOLSLIDE,((volpan-85)<<4));
303                 else if(volpan<=104)/* volume slide down (95-104) */
304                         UniVolEffect(VOL_VOLSLIDE,(volpan-95));
305                 else if(volpan<=114)/* pitch slide down (105-114) */
306                         UniVolEffect(VOL_PITCHSLIDEDN,(volpan-105));
307                 else if(volpan<=124)/* pitch slide up (115-124) */
308                         UniVolEffect(VOL_PITCHSLIDEUP,(volpan-115));
309                 else if(volpan<=127) { /* crap */
310                         _mm_errno=MMERR_LOADING_PATTERN;
311                         return NULL;
312                 } else if(volpan<=192)
313                         UniVolEffect(VOL_PANNING,((volpan-128)==64)?255:((volpan-128)<<2));
314                 else if(volpan<=202)/* portamento to note */
315                         UniVolEffect(VOL_PORTAMENTO,portatable[volpan-193]);
316                 else if(volpan<=212)/* vibrato */
317                         UniVolEffect(VOL_VIBRATO,(volpan-203));
318                 else if((volpan!=239)&&(volpan!=255)) { /* crap */
319                         _mm_errno=MMERR_LOADING_PATTERN;
320                         return NULL;
321                 }
322
323                 S3MIT_ProcessCmd(tr[t*of.numchn].cmd,tr[t*of.numchn].inf,
324                     old_effect|S3MIT_IT);
325
326                 UniNewline();
327         }
328         return UniDup();
329 }
330
331 static BOOL IT_ReadPattern(UWORD patrows)
332 {
333         int row=0,flag,ch,blah;
334         ITNOTE *itt=itpat,dummy,*n,*l;
335
336         memset(itt,255,200*64*sizeof(ITNOTE));
337
338         do {
339                 if((flag=_mm_read_UBYTE(modreader))==EOF) {
340                         _mm_errno = MMERR_LOADING_PATTERN;
341                         return 0;
342                 }
343                 if(!flag) {
344                         itt=&itt[of.numchn];
345                         row++;
346                 } else {
347                         ch=remap[(flag-1)&63];
348                         if(ch!=-1) {
349                                 n=&itt[ch];
350                                 l=&last[ch];
351                         } else
352                                 n=l=&dummy;
353
354                         if(flag&128) mask[ch]=_mm_read_UBYTE(modreader);
355                         if(mask[ch]&1)
356                                 /* convert IT note off to internal note off */
357                                 if((l->note=n->note=_mm_read_UBYTE(modreader))==255)
358                                         l->note=n->note=253;
359                         if(mask[ch]&2)
360                                 l->ins=n->ins=_mm_read_UBYTE(modreader);
361                         if(mask[ch]&4)
362                                 l->volpan=n->volpan=_mm_read_UBYTE(modreader);
363                         if(mask[ch]&8) {
364                                 l->cmd=n->cmd=_mm_read_UBYTE(modreader);
365                                 l->inf=n->inf=_mm_read_UBYTE(modreader);
366                         }
367                         if(mask[ch]&16)
368                                 n->note=l->note;
369                         if(mask[ch]&32)
370                                 n->ins=l->ins;
371                         if(mask[ch]&64)
372                                 n->volpan=l->volpan;
373                         if(mask[ch]&128) {
374                                 n->cmd=l->cmd;
375                                 n->inf=l->inf;
376                         }
377                 }
378         } while(row<patrows);
379
380         for(blah=0;blah<of.numchn;blah++) {
381                 if(!(of.tracks[numtrk++]=IT_ConvertTrack(&itpat[blah],patrows)))
382                         return 0;
383         }
384
385         return 1;
386 }
387
388 static void LoadMidiString(MREADER* r,CHAR* dest)
389 {
390         CHAR *curp,*lastp;
391
392         _mm_read_UBYTES(dest,32,r);
393         curp=lastp=dest;
394         /* remove blanks and uppercase all */
395         while(*lastp) {
396                 if(mik_isalnum((int)*lastp)) *(curp++)=mik_toupper((int)*lastp);
397                 lastp++;
398         }
399         *curp=0;
400 }
401
402 /* Load embedded midi information for resonant filters */
403 static void IT_LoadMidiConfiguration(MREADER* r)
404 {
405         int i;
406
407         memset(filtermacros,0,sizeof(filtermacros));
408         memset(filtersettings,0,sizeof(filtersettings));
409
410         if (r) { /* information is embedded in file */
411                 UWORD dat;
412                 CHAR midiline[33];
413
414                 dat=_mm_read_I_UWORD(r);
415                 _mm_fseek(r,8*dat+0x120,SEEK_CUR);
416
417                 /* read midi macros */
418                 for(i=0;i<UF_MAXMACRO;i++) {
419                         LoadMidiString(r,midiline);
420                         if((!strncmp(midiline,"F0F00",5))&&
421                            ((midiline[5]=='0')||(midiline[5]=='1')))
422                                         filtermacros[i]=(midiline[5]-'0')|0x80;
423                 }
424
425                 /* read standalone filters */
426                 for(i=0x80;i<0x100;i++) {
427                         LoadMidiString(r,midiline);
428                         if((!strncmp(midiline,"F0F00",5))&&
429                            ((midiline[5]=='0')||(midiline[5]=='1'))) {
430                                 filtersettings[i].filter=(midiline[5]-'0')|0x80;
431                                 dat=(midiline[6])?(midiline[6]-'0'):0;
432                                 if(midiline[7])dat=(dat<<4)|(midiline[7]-'0');
433                                 filtersettings[i].inf=dat;
434                         }
435                 }
436         } else { /* use default information */
437                 filtermacros[0]=FILT_CUT;
438                 for(i=0x80;i<0x90;i++) {
439                         filtersettings[i].filter=FILT_RESONANT;
440                         filtersettings[i].inf=(i&0x7f)<<3;
441                 }
442         }
443         activemacro=0;
444         for(i=0;i<0x80;i++) {
445                 filtersettings[i].filter=filtermacros[0];
446                 filtersettings[i].inf=i;
447         }
448 }
449
450 static BOOL IT_Load(BOOL curious)
451 {
452         int t,u,lp;
453         INSTRUMENT *d;
454         SAMPLE *q;
455         /*BOOL compressed=0;*/
456
457         numtrk=0;
458         filters=0;
459
460         /* try to read module header */
461         _mm_read_I_ULONG(modreader);    /* kill the 4 byte header */
462         _mm_read_string(mh->songname,26,modreader);
463         _mm_read_UBYTES(mh->blank01,2,modreader);
464         mh->ordnum      =_mm_read_I_UWORD(modreader);
465         mh->insnum      =_mm_read_I_UWORD(modreader);
466         mh->smpnum      =_mm_read_I_UWORD(modreader);
467         mh->patnum      =_mm_read_I_UWORD(modreader);
468         mh->cwt         =_mm_read_I_UWORD(modreader);
469         mh->cmwt        =_mm_read_I_UWORD(modreader);
470         mh->flags       =_mm_read_I_UWORD(modreader);
471         mh->special     =_mm_read_I_UWORD(modreader);
472         mh->globvol     =_mm_read_UBYTE(modreader);
473         mh->mixvol      =_mm_read_UBYTE(modreader);
474         mh->initspeed   =_mm_read_UBYTE(modreader);
475         mh->inittempo   =_mm_read_UBYTE(modreader);
476         mh->pansep      =_mm_read_UBYTE(modreader);
477         mh->zerobyte    =_mm_read_UBYTE(modreader);
478         mh->msglength   =_mm_read_I_UWORD(modreader);
479         mh->msgoffset   =_mm_read_I_ULONG(modreader);
480         _mm_read_UBYTES(mh->blank02,4,modreader);
481         _mm_read_UBYTES(mh->pantable,64,modreader);
482         _mm_read_UBYTES(mh->voltable,64,modreader);
483
484         if(_mm_eof(modreader)) {
485                 _mm_errno=MMERR_LOADING_HEADER;
486                 return 0;
487         }
488
489         /* set module variables */
490         of.songname    = DupStr(mh->songname,26,0); /* make a cstr of songname  */
491         of.reppos      = 0;
492         of.numpat      = mh->patnum;
493         of.numins      = mh->insnum;
494         of.numsmp      = mh->smpnum;
495         of.initspeed   = mh->initspeed;
496         of.inittempo   = mh->inittempo;
497         of.initvolume  = mh->globvol;
498         of.flags      |= UF_BGSLIDES | UF_ARPMEM;
499         if (!(mh->flags & 1))
500                         of.flags |= UF_PANNING;
501         of.bpmlimit=32;
502
503         if(mh->songname[25]) {
504                 of.numvoices=1+mh->songname[25];
505 #ifdef MIKMOD_DEBUG
506                 fprintf(stderr,"Embedded IT limitation to %d voices\n",of.numvoices);
507 #endif
508         }
509
510         /* set the module type */
511         /* 2.17 : IT 2.14p4 */
512         /* 2.16 : IT 2.14p3 with resonant filters */
513         /* 2.15 : IT 2.14p3 (improved compression) */
514         if((mh->cwt<=0x219)&&(mh->cwt>=0x217))
515                 of.modtype=MikMod_strdup(IT_Version[mh->cmwt<0x214?4:5]);
516         else if (mh->cwt>=0x215)
517                 of.modtype=MikMod_strdup(IT_Version[mh->cmwt<0x214?2:3]);
518         else {
519                 of.modtype = MikMod_strdup(IT_Version[mh->cmwt<0x214?0:1]);
520                 of.modtype[mh->cmwt<0x214?15:26] = (mh->cwt>>8)+'0';
521                 of.modtype[mh->cmwt<0x214?17:28] = ((mh->cwt>>4)&0xf)+'0';
522                 of.modtype[mh->cmwt<0x214?18:29] = ((mh->cwt)&0xf)+'0';
523         }
524
525         if(mh->flags&8)
526                 of.flags |= UF_XMPERIODS | UF_LINEAR;
527
528         if((mh->cwt>=0x106)&&(mh->flags&16))
529                 old_effect=S3MIT_OLDSTYLE;
530         else
531                 old_effect=0;
532
533         /* set panning positions */
534         if (mh->flags & 1)
535                 for(t=0;t<64;t++) {
536                         mh->pantable[t]&=0x7f;
537                         if(mh->pantable[t]<64)
538                                 of.panning[t]=mh->pantable[t]<<2;
539                         else if(mh->pantable[t]==64)
540                                 of.panning[t]=255;
541                         else if(mh->pantable[t]==100)
542                                 of.panning[t]=PAN_SURROUND;
543                         else if(mh->pantable[t]==127)
544                                 of.panning[t]=PAN_CENTER;
545                         else {
546                                 _mm_errno=MMERR_LOADING_HEADER;
547                                 return 0;
548                         }
549                 }
550         else
551                 for(t=0;t<64;t++)
552                         of.panning[t]=PAN_CENTER;
553
554         /* set channel volumes */
555         memcpy(of.chanvol,mh->voltable,64);
556
557         /* read the order data */
558         if(!AllocPositions(mh->ordnum)) return 0;
559         if(!(origpositions=(UWORD*)MikMod_calloc(mh->ordnum,sizeof(UWORD)))) return 0;
560
561         for(t=0;t<mh->ordnum;t++) {
562                 origpositions[t]=_mm_read_UBYTE(modreader);
563                 if((origpositions[t]>mh->patnum)&&(origpositions[t]<254))
564                         origpositions[t]=255;
565         }
566
567         if(_mm_eof(modreader)) {
568                 _mm_errno = MMERR_LOADING_HEADER;
569                 return 0;
570         }
571
572         poslookupcnt=mh->ordnum;
573         S3MIT_CreateOrders(curious);
574
575         if(!(paraptr=(ULONG*)MikMod_malloc((mh->insnum+mh->smpnum+of.numpat)*
576                                        sizeof(ULONG)))) return 0;
577
578         /* read the instrument, sample, and pattern parapointers */
579         _mm_read_I_ULONGS(paraptr,mh->insnum+mh->smpnum+of.numpat,modreader);
580
581         if(_mm_eof(modreader)) {
582                 _mm_errno = MMERR_LOADING_HEADER;
583                 return 0;
584         }
585
586         /* Check for and load midi information for resonant filters */
587         if(mh->cmwt>=0x216) {
588                 if(mh->special&8) {
589                         IT_LoadMidiConfiguration(modreader);
590                         if(_mm_eof(modreader)) {
591                                 _mm_errno = MMERR_LOADING_HEADER;
592                                 return 0;
593                         }
594                 } else
595                         IT_LoadMidiConfiguration(NULL);
596                 filters=1;
597         }
598
599         /* Check for and load song comment */
600         if((mh->special&1)&&(mh->cwt>=0x104)&&(mh->msglength)) {
601                 _mm_fseek(modreader,(long)(mh->msgoffset),SEEK_SET);
602                 if(!ReadComment(mh->msglength)) return 0;
603         }
604
605         if(!(mh->flags&4)) of.numins=of.numsmp;
606         if(!AllocSamples()) return 0;
607
608         if(!AllocLinear()) return 0;
609
610         /* Load all samples */
611         q = of.samples;
612         for(t=0;t<mh->smpnum;t++) {
613                 ITSAMPLE s;
614
615                 /* seek to sample position */
616                 _mm_fseek(modreader,(long)(paraptr[mh->insnum+t]+4),SEEK_SET);
617
618                 /* load sample info */
619                 _mm_read_string(s.filename,12,modreader);
620                 s.zerobyte    = _mm_read_UBYTE(modreader);
621                 s.globvol     = _mm_read_UBYTE(modreader);
622                 s.flag        = _mm_read_UBYTE(modreader);
623                 s.volume      = _mm_read_UBYTE(modreader);
624                 _mm_read_string(s.sampname,26,modreader);
625                 s.convert     = _mm_read_UBYTE(modreader);
626                 s.panning     = _mm_read_UBYTE(modreader);
627                 s.length      = _mm_read_I_ULONG(modreader);
628                 s.loopbeg     = _mm_read_I_ULONG(modreader);
629                 s.loopend     = _mm_read_I_ULONG(modreader);
630                 s.c5spd       = _mm_read_I_ULONG(modreader);
631                 s.susbegin    = _mm_read_I_ULONG(modreader);
632                 s.susend      = _mm_read_I_ULONG(modreader);
633                 s.sampoffset  = _mm_read_I_ULONG(modreader);
634                 s.vibspeed    = _mm_read_UBYTE(modreader);
635                 s.vibdepth    = _mm_read_UBYTE(modreader);
636                 s.vibrate     = _mm_read_UBYTE(modreader);
637                 s.vibwave     = _mm_read_UBYTE(modreader);
638
639                 /* Generate an error if c5spd is > 512k, or samplelength > 256 megs
640                    (nothing would EVER be that high) */
641
642                 if(_mm_eof(modreader)||(s.c5spd>0x7ffffL)||(s.length>0xfffffffUL)) {
643                         _mm_errno = MMERR_LOADING_SAMPLEINFO;
644                         return 0;
645                 }
646
647                 /* Reality check for sample loop information */
648                 if((s.flag&16)&&
649                    ((s.loopbeg>0xfffffffUL)||(s.loopend>0xfffffffUL))) {
650                         _mm_errno = MMERR_LOADING_SAMPLEINFO;
651                         return 0;
652                 }
653
654                 q->samplename = DupStr(s.sampname,26,0);
655                 q->speed      = s.c5spd / 2;
656                 q->panning    = ((s.panning&127)==64)?255:(s.panning&127)<<2;
657                 q->length     = s.length;
658                 q->loopstart  = s.loopbeg;
659                 q->loopend    = s.loopend;
660                 q->volume     = s.volume;
661                 q->globvol    = s.globvol;
662                 q->seekpos    = s.sampoffset;
663
664                 /* Convert speed to XM linear finetune */
665                 if(of.flags&UF_LINEAR)
666                         q->speed=speed_to_finetune(s.c5spd,t);
667
668                 if(s.panning&128) q->flags|=SF_OWNPAN;
669
670                 if(s.vibrate) {
671                         q->vibflags |= AV_IT;
672                         q->vibtype   = s.vibwave;
673                         q->vibsweep  = s.vibrate * 2;
674                         q->vibdepth  = s.vibdepth;
675                         q->vibrate   = s.vibspeed;
676                 }
677
678                 if(s.flag&2) q->flags|=SF_16BITS;
679                 if((s.flag&8)&&(mh->cwt>=0x214)) {
680                         q->flags|=SF_ITPACKED;
681                         /*compressed=1;*/
682                 }
683                 if(s.flag&16) q->flags|=SF_LOOP;
684                 if(s.flag&64) q->flags|=SF_BIDI;
685
686                 if(mh->cwt>=0x200) {
687                         if(s.convert&1) q->flags|=SF_SIGNED;
688                         if(s.convert&4) q->flags|=SF_DELTA;
689                 }
690                 q++;
691         }
692
693         /* Load instruments if instrument mode flag enabled */
694         if(mh->flags&4) {
695                 if(!AllocInstruments()) return 0;
696                 d=of.instruments;
697                 of.flags|=UF_NNA|UF_INST;
698
699                 for(t=0;t<mh->insnum;t++) {
700                         ITINSTHEADER ih;
701
702                         /* seek to instrument position */
703                         _mm_fseek(modreader,paraptr[t]+4,SEEK_SET);
704
705                         /* load instrument info */
706                         _mm_read_string(ih.filename,12,modreader);
707                         ih.zerobyte  = _mm_read_UBYTE(modreader);
708                         if(mh->cwt<0x200) {
709                                 /* load IT 1.xx inst header */
710                                 ih.volflg    = _mm_read_UBYTE(modreader);
711                                 ih.volbeg    = _mm_read_UBYTE(modreader);
712                                 ih.volend    = _mm_read_UBYTE(modreader);
713                                 ih.volsusbeg = _mm_read_UBYTE(modreader);
714                                 ih.volsusend = _mm_read_UBYTE(modreader);
715                                 _mm_read_I_UWORD(modreader);
716                                 ih.fadeout   = _mm_read_I_UWORD(modreader);
717                                 ih.nna       = _mm_read_UBYTE(modreader);
718                                 ih.dnc       = _mm_read_UBYTE(modreader);
719                         } else {
720                                 /* Read IT200+ header */
721                                 ih.nna       = _mm_read_UBYTE(modreader);
722                                 ih.dct       = _mm_read_UBYTE(modreader);
723                                 ih.dca       = _mm_read_UBYTE(modreader);
724                                 ih.fadeout   = _mm_read_I_UWORD(modreader);
725                                 ih.ppsep     = _mm_read_UBYTE(modreader);
726                                 ih.ppcenter  = _mm_read_UBYTE(modreader);
727                                 ih.globvol   = _mm_read_UBYTE(modreader);
728                                 ih.chanpan   = _mm_read_UBYTE(modreader);
729                                 ih.rvolvar   = _mm_read_UBYTE(modreader);
730                                 ih.rpanvar   = _mm_read_UBYTE(modreader);
731                         }
732
733                         ih.trkvers   = _mm_read_I_UWORD(modreader);
734                         ih.numsmp    = _mm_read_UBYTE(modreader);
735                         _mm_skip_BYTE(modreader);
736                         _mm_read_string(ih.name,26,modreader);
737                         _mm_read_UBYTES(ih.blank01,6,modreader);
738                         _mm_read_I_UWORDS(ih.samptable,ITNOTECNT,modreader);
739                         if(mh->cwt<0x200) {
740                                 /* load IT 1xx volume envelope */
741                                 _mm_read_UBYTES(ih.volenv,200,modreader);
742                                 for(lp=0;lp<ITENVCNT;lp++) {
743                                         ih.oldvoltick[lp] = _mm_read_UBYTE(modreader);
744                                         ih.volnode[lp]    = _mm_read_UBYTE(modreader);
745                                 }
746                         } else {
747                                 /* load IT 2xx volume, pan and pitch envelopes */
748 #if defined __STDC__ || defined _MSC_VER || defined MPW_C
749 #define IT_LoadEnvelope(name,type)                                                                              \
750                                 ih. name##flg   =_mm_read_UBYTE(modreader);                             \
751                                 ih. name##pts   =_mm_read_UBYTE(modreader);                             \
752                                 if (ih. name##pts > ITENVCNT)                                                   \
753                                         ih. name##pts = ITENVCNT;                                                       \
754                                 ih. name##beg   =_mm_read_UBYTE(modreader);                             \
755                                 ih. name##end   =_mm_read_UBYTE(modreader);                             \
756                                 ih. name##susbeg=_mm_read_UBYTE(modreader);                             \
757                                 ih. name##susend=_mm_read_UBYTE(modreader);                             \
758                                 for(lp=0;lp<ITENVCNT;lp++) {                                                    \
759                                         ih. name##node[lp]=_mm_read_##type (modreader);         \
760                                         ih. name##tick[lp]=_mm_read_I_UWORD(modreader);         \
761                                 }                                                                                                               \
762                                 _mm_skip_BYTE(modreader)
763 #else
764 #define IT_LoadEnvelope(name,type)                                                                              \
765                                 ih. name/**/flg   =_mm_read_UBYTE(modreader);                   \
766                                 ih. name/**/pts   =_mm_read_UBYTE(modreader);                   \
767                                 if (ih. name/**/pts > ITENVCNT)                                                 \
768                                         ih. name/**/pts = ITENVCNT;                                                     \
769                                 ih. name/**/beg   =_mm_read_UBYTE(modreader);                   \
770                                 ih. name/**/end   =_mm_read_UBYTE(modreader);                   \
771                                 ih. name/**/susbeg=_mm_read_UBYTE(modreader);                   \
772                                 ih. name/**/susend=_mm_read_UBYTE(modreader);                   \
773                                 for(lp=0;lp<ITENVCNT;lp++) {                                                    \
774                                         ih. name/**/node[lp]=_mm_read_/**/type (modreader);     \
775                                         ih. name/**/tick[lp]=_mm_read_I_UWORD(modreader);       \
776                                 }                                                                                                               \
777                                 _mm_skip_BYTE(modreader)
778 #endif
779
780                                 IT_LoadEnvelope(vol,UBYTE);
781                                 IT_LoadEnvelope(pan,SBYTE);
782                                 IT_LoadEnvelope(pit,SBYTE);
783 #undef IT_LoadEnvelope
784                         }
785
786                         if(_mm_eof(modreader)) {
787                                 _mm_errno = MMERR_LOADING_SAMPLEINFO;
788                                 return 0;
789                         }
790
791                         d->volflg|=EF_VOLENV;
792                         d->insname = DupStr(ih.name,26,0);
793                         d->nnatype = ih.nna & NNA_MASK;
794
795                         if(mh->cwt<0x200) {
796                                 d->volfade=ih.fadeout<< 6;
797                                 if(ih.dnc) {
798                                         d->dct=DCT_NOTE;
799                                         d->dca=DCA_CUT;
800                                 }
801
802                                 if(ih.volflg&1) d->volflg|=EF_ON;
803                                 if(ih.volflg&2) d->volflg|=EF_LOOP;
804                                 if(ih.volflg&4) d->volflg|=EF_SUSTAIN;
805
806                                 /* XM conversion of IT envelope Array */
807                                 d->volbeg    = ih.volbeg;
808                                 d->volend    = ih.volend;
809                                 d->volsusbeg = ih.volsusbeg;
810                                 d->volsusend = ih.volsusend;
811
812                                 if(ih.volflg&1) {
813                                         for(u=0;u<ITENVCNT;u++)
814                                                 if(ih.oldvoltick[d->volpts]!=0xff) {
815                                                         d->volenv[d->volpts].val=(ih.volnode[d->volpts]<<2);
816                                                         d->volenv[d->volpts].pos=ih.oldvoltick[d->volpts];
817                                                         d->volpts++;
818                                                 } else
819                                                         break;
820                                 }
821                         } else {
822                                 d->panning=((ih.chanpan&127)==64)?255:(ih.chanpan&127)<<2;
823                                 if(!(ih.chanpan&128)) d->flags|=IF_OWNPAN;
824
825                                 if(!(ih.ppsep & 128)) {
826                                         d->pitpansep=ih.ppsep<<2;
827                                         d->pitpancenter=ih.ppcenter;
828                                         d->flags|=IF_PITCHPAN;
829                                 }
830                                 d->globvol=ih.globvol>>1;
831                                 d->volfade=ih.fadeout<<5;
832                                 d->dct    =ih.dct;
833                                 d->dca    =ih.dca;
834
835                                 if(mh->cwt>=0x204) {
836                                         d->rvolvar = ih.rvolvar;
837                                         d->rpanvar = ih.rpanvar;
838                                 }
839
840 #if defined __STDC__ || defined _MSC_VER || defined MPW_C
841 #define IT_ProcessEnvelope(name)                                                                                \
842                                 if(ih. name##flg&1) d-> name##flg|=EF_ON;                               \
843                                 if(ih. name##flg&2) d-> name##flg|=EF_LOOP;                             \
844                                 if(ih. name##flg&4) d-> name##flg|=EF_SUSTAIN;                  \
845                                 d-> name##pts=ih. name##pts;                                                    \
846                                 d-> name##beg=ih. name##beg;                                                    \
847                                 d-> name##end=ih. name##end;                                                    \
848                                 d-> name##susbeg=ih. name##susbeg;                                              \
849                                 d-> name##susend=ih. name##susend;                                              \
850                                                                                                                                                 \
851                                 for(u=0;u<ih. name##pts;u++)                                                    \
852                                         d-> name##env[u].pos=ih. name##tick[u];                         \
853                                                                                                                                                 \
854                                 if((d-> name##flg&EF_ON)&&(d-> name##pts<2))                    \
855                                         d-> name##flg&=~EF_ON
856 #else
857 #define IT_ProcessEnvelope(name)                                                                        \
858                                 if(ih. name/**/flg&1) d-> name/**/flg|=EF_ON;           \
859                                 if(ih. name/**/flg&2) d-> name/**/flg|=EF_LOOP;         \
860                                 if(ih. name/**/flg&4) d-> name/**/flg|=EF_SUSTAIN;      \
861                                 d-> name/**/pts=ih. name/**/pts;                                        \
862                                 d-> name/**/beg=ih. name/**/beg;                                        \
863                                 d-> name/**/end=ih. name/**/end;                                        \
864                                 d-> name/**/susbeg=ih. name/**/susbeg;                          \
865                                 d-> name/**/susend=ih. name/**/susend;                          \
866                                                                                                                                         \
867                                 for(u=0;u<ih. name/**/pts;u++)                                          \
868                                         d-> name/**/env[u].pos=ih. name/**/tick[u];             \
869                                                                                                                                         \
870                                 if((d-> name/**/flg&EF_ON)&&(d-> name/**/pts<2))        \
871                                         d-> name/**/flg&=~EF_ON
872 #endif
873
874                                 IT_ProcessEnvelope(vol);
875
876                                 for(u=0;u<ih.volpts;u++)
877                                         d->volenv[u].val=(ih.volnode[u]<<2);
878
879                                 IT_ProcessEnvelope(pan);
880                                 for(u=0;u<ih.panpts;u++)
881                                         d->panenv[u].val=
882                                           ih.pannode[u]==32?255:(ih.pannode[u]+32)<<2;
883
884                                 IT_ProcessEnvelope(pit);
885                                 for(u=0;u<ih.pitpts;u++)
886                                         d->pitenv[u].val=ih.pitnode[u]+32;
887 #undef IT_ProcessEnvelope
888
889                                 if(ih.pitflg&0x80) {
890                                         /* filter envelopes not supported yet */
891                                         d->pitflg&=~EF_ON;
892                                         ih.pitpts=ih.pitbeg=ih.pitend=0;
893 #ifdef MIKMOD_DEBUG
894                                         {
895                                                 static int warn=0;
896
897                                                 if(!warn)
898                                                         fprintf(stderr, "\rFilter envelopes not supported yet\n");
899                                                 warn=1;
900                                         }
901 #endif
902                                 }
903                         }
904
905                         for(u=0;u<ITNOTECNT;u++) {
906                                 d->samplenote[u]=(ih.samptable[u]&255);
907                                 d->samplenumber[u]=
908                                   (ih.samptable[u]>>8)?((ih.samptable[u]>>8)-1):0xffff;
909                                 if(d->samplenumber[u]>=of.numsmp)
910                                         d->samplenote[u]=255;
911                                 else if (of.flags&UF_LINEAR) {
912                                         int note=(int)d->samplenote[u]+noteindex[d->samplenumber[u]];
913                                         d->samplenote[u]=(note<0)?0:(note>255?255:note);
914                                 }
915                         }
916
917                         d++;
918                 }
919         } else if(of.flags & UF_LINEAR) {
920                 if(!AllocInstruments()) return 0;
921                 d=of.instruments;
922                 of.flags|=UF_INST;
923
924                 for(t=0;t<mh->smpnum;t++,d++)
925                         for(u=0;u<ITNOTECNT;u++) {
926                                 if(d->samplenumber[u]>=of.numsmp)
927                                         d->samplenote[u]=255;
928                                 else {
929                                         int note=(int)d->samplenote[u]+noteindex[d->samplenumber[u]];
930                                         d->samplenote[u]=(note<0)?0:(note>255?255:note);
931                                 }
932                         }
933         }
934
935         /* Figure out how many channels this song actually uses */
936         of.numchn=0;
937         memset(remap,-1,UF_MAXCHAN*sizeof(UBYTE));
938         for(t=0;t<of.numpat;t++) {
939                 UWORD packlen;
940
941                 /* seek to pattern position */
942                 if(paraptr[mh->insnum+mh->smpnum+t]) { /* 0 -> empty 64 row pattern */
943                         _mm_fseek(modreader,((long)paraptr[mh->insnum+mh->smpnum+t]),SEEK_SET);
944                         _mm_read_I_UWORD(modreader);
945                         /* read pattern length (# of rows)
946                            Impulse Tracker never creates patterns with less than 32 rows,
947                            but some other trackers do, so we only check for more than 256
948                            rows */
949                         packlen=_mm_read_I_UWORD(modreader);
950                         if(packlen>256) {
951                                 _mm_errno=MMERR_LOADING_PATTERN;
952                                 return 0;
953                         }
954                         _mm_read_I_ULONG(modreader);
955                         if(!IT_GetNumChannels(packlen)) return 0;
956                 }
957         }
958
959         /* give each of them a different number */
960         for(t=0;t<UF_MAXCHAN;t++)
961                 if(!remap[t])
962                         remap[t]=of.numchn++;
963
964         of.numtrk = of.numpat*of.numchn;
965         if(of.numvoices)
966                 if (of.numvoices<of.numchn) of.numvoices=of.numchn;
967
968         if(!AllocPatterns()) return 0;
969         if(!AllocTracks()) return 0;
970
971         for(t=0;t<of.numpat;t++) {
972                 UWORD packlen;
973
974                 /* seek to pattern position */
975                 if(!paraptr[mh->insnum+mh->smpnum+t]) { /* 0 -> empty 64 row pattern */
976                         of.pattrows[t]=64;
977                         for(u=0;u<of.numchn;u++) {
978                                 int k;
979
980                                 UniReset();
981                                 for(k=0;k<64;k++) UniNewline();
982                                 of.tracks[numtrk++]=UniDup();
983                         }
984                 } else {
985                         _mm_fseek(modreader,((long)paraptr[mh->insnum+mh->smpnum+t]),SEEK_SET);
986                         packlen=_mm_read_I_UWORD(modreader);
987                         (void)packlen; /* unused */
988                         of.pattrows[t]=_mm_read_I_UWORD(modreader);
989                         _mm_read_I_ULONG(modreader);
990                         if(!IT_ReadPattern(of.pattrows[t])) return 0;
991                 }
992         }
993
994         return 1;
995 }
996
997 static CHAR *IT_LoadTitle(void)
998 {
999         CHAR s[26];
1000
1001         _mm_fseek(modreader,4,SEEK_SET);
1002         if(!_mm_read_UBYTES(s,26,modreader)) return NULL;
1003
1004         return(DupStr(s,26,0));
1005 }
1006
1007 /*========== Loader information */
1008
1009 MIKMODAPI MLOADER load_it={
1010         NULL,
1011         "IT",
1012         "IT (Impulse Tracker)",
1013         IT_Init,
1014         IT_Test,
1015         IT_Load,
1016         IT_Cleanup,
1017         IT_LoadTitle
1018 };
1019
1020 /* ex:set ts=4: */