OSDN Git Service

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