1 /*  _______         ____    __         ___    ___
2  * \    _  \       \    /  \  /       \   \  /   /       '   '  '
3  *  |  | \  \       |  |    ||         |   \/   |         .      .
4  *  |  |  |  |      |  |    ||         ||\  /|  |
5  *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
6  *  |  |  |  |      |  |    ||         ||    |  |         .      .
7  *  |  |_/  /        \  \__//          ||    |  |
8  * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
9  *                                                      /  \
10  *                                                     / .  \
11  * readxm.c - Code to read a Fast Tracker II          / / \  \
12  *            module from an open file.              | <  /   \_
13  *                                                   |  \/ /\   /
14  * By Julien Cugniere. Some bits of code taken        \_  /  > /
15  * from reads3m.c.                                      | \ / /
16  *                                                      |  ' /
17  *                                                       \__/
18  */
19 
20 #include <stdlib.h>
21 #include <string.h>
22 #include <math.h>
23 
24 #include "dumb.h"
25 #include "internal/it.h"
26 
27 
28 
29 /** TODO:
30 
31  * XM_TREMOLO                        doesn't sound quite right...
32  * XM_E_SET_FINETUNE                 todo.
33  * XM_SET_ENVELOPE_POSITION          todo.
34 
35  * VIBRATO conversion needs to be checked (sample/effect/volume). Plus check
36    that effect memory is correct when using XM_VOLSLIDE_VIBRATO.
37    - sample vibrato (instrument vibrato) is now handled correctly. - entheh
38 
39  * XM_E_SET_VIBRATO/TREMOLO_CONTROL: effectvalue&4 -> don't retrig wave when
40    a new instrument is played. In retrigger_note()?. Is it worth implementing?
41 
42  * Lossy fadeout approximation. 0..31 converted to 0 --> won't fade at all.
43 
44  * Replace DUMB's sawtooth by ramp_down/ramp_up. Update XM loader.
45 
46  * A lot of things need to be reset when the end of the song is reached.
47 
48  * It seems that IT and XM don't behave the same way when dealing with
49    mixed loops. When IT encounters multiple SBx (x>0) commands on the same
50    row, it decrements the loop count for all, but only execute the loop of
51    the last one (highest channel). FT2 only decrements the loop count of the
52    last one. Not that I know of any modules using so convoluted combinations!
53 
54  * Maybe we could remove patterns that don't appear in the order table ? Or
55    provide a function to "optimize" a DUMB_IT_SIGDATA ?
56 
57 */
58 
59 
60 
61 #define XM_LINEAR_FREQUENCY        1 /* otherwise, use amiga slides */
62 
63 #define XM_ENTRY_PACKED            128
64 #define XM_ENTRY_NOTE              1
65 #define XM_ENTRY_INSTRUMENT        2
66 #define XM_ENTRY_VOLUME            4
67 #define XM_ENTRY_EFFECT            8
68 #define XM_ENTRY_EFFECTVALUE       16
69 
70 #define XM_NOTE_OFF                97
71 
72 #define XM_ENVELOPE_ON             1
73 #define XM_ENVELOPE_SUSTAIN        2
74 #define XM_ENVELOPE_LOOP           4
75 
76 #define XM_SAMPLE_NO_LOOP          0
77 #define XM_SAMPLE_FORWARD_LOOP     1
78 #define XM_SAMPLE_PINGPONG_LOOP    2
79 #define XM_SAMPLE_16BIT            16
80 #define XM_SAMPLE_STEREO           32
81 
82 #define XM_VIBRATO_SINE            0
83 #define XM_VIBRATO_SQUARE          1
84 #define XM_VIBRATO_RAMP_DOWN       2
85 #define XM_VIBRATO_RAMP_UP         3
86 
87 
88 
89 /* Probably useless :) */
90 static const char xm_convert_vibrato[] = {
91 	IT_VIBRATO_SINE,
92 	IT_VIBRATO_SQUARE,
93 	IT_VIBRATO_SAWTOOTH,
94 	IT_VIBRATO_SAWTOOTH
95 };
96 
97 
98 
99 #define XM_MAX_SAMPLES_PER_INSTRUMENT 16
100 
101 
102 
103 /* Extra data that doesn't fit inside IT_INSTRUMENT */
104 typedef struct XM_INSTRUMENT_EXTRA
105 {
106 	int n_samples;
107 	int vibrato_type;
108 	int vibrato_sweep; /* 0-0xFF */
109 	int vibrato_depth; /* 0-0x0F */
110 	int vibrato_speed; /* 0-0x3F */
111 }
112 XM_INSTRUMENT_EXTRA;
113 
114 
115 
116 /* Frees the original block if it can't resize it or if size is 0, and acts
117  * as malloc if ptr is NULL.
118  */
safe_realloc(void * ptr,size_t size)119 static void *safe_realloc(void *ptr, size_t size)
120 {
121 	if (ptr == NULL)
122 		return malloc(size);
123 
124 	if (size == 0) {
125 		free(ptr);
126 		return NULL;
127 	} else {
128 		void *new_block = realloc(ptr, size);
129 		if (!new_block)
130 			free(ptr);
131 		return new_block;
132 	}
133 }
134 
135 
136 
137 /* The interpretation of the XM volume column is left to the player. Here, we
138  * just filter bad values.
139  */
140 // This function is so tiny now, should we inline it?
it_xm_convert_volume(int volume,IT_ENTRY * entry)141 static void it_xm_convert_volume(int volume, IT_ENTRY *entry)
142 {
143 	entry->mask |= IT_ENTRY_VOLPAN;
144 	entry->volpan = volume;
145 
146 	switch (volume >> 4) {
147 		case 0xA: /* set vibrato speed */
148 		case 0xB: /* vibrato */
149 		case 0xF: /* tone porta */
150 		case 0x6: /* vol slide up */
151 		case 0x7: /* vol slide down */
152 		case 0x8: /* fine vol slide up */
153 		case 0x9: /* fine vol slide down */
154 		case 0xC: /* set panning */
155 		case 0xD: /* pan slide left */
156 		case 0xE: /* pan slide right */
157 		case 0x1: /* set volume */
158 		case 0x2: /* set volume */
159 		case 0x3: /* set volume */
160 		case 0x4: /* set volume */
161 			break;
162 
163 		case 0x5:
164 			if (volume == 0x50)
165 				break; /* set volume */
166 			/* else fall through */
167 
168 		default:
169 			entry->mask &= ~IT_ENTRY_VOLPAN;
170 			break;
171 	}
172 }
173 
174 
175 
it_xm_read_pattern(IT_PATTERN * pattern,DUMBFILE * f,int n_channels,unsigned char * buffer)176 static int it_xm_read_pattern(IT_PATTERN *pattern, DUMBFILE *f, int n_channels, unsigned char *buffer)
177 {
178 	int size;
179 	int pos;
180 	int channel;
181 	int row;
182 	int effect, effectvalue;
183 	IT_ENTRY *entry;
184 
185 	/* pattern header size */
186 	if (dumbfile_igetl(f) != 0x09) {
187 		TRACE("XM error: unexpected pattern header size\n");
188 		return -1;
189 	}
190 
191 	/* pattern data packing type */
192 	if (dumbfile_getc(f) != 0) {
193 		TRACE("XM error: unexpected pattern packing type\n");
194 		return -1;
195 	}
196 
197 	pattern->n_rows = dumbfile_igetw(f);  /* 1..256 */
198 	size = dumbfile_igetw(f);
199 	pattern->n_entries = 0;
200 
201 	if (dumbfile_error(f))
202 		return -1;
203 
204 	if (size == 0)
205 		return 0;
206 
207 	if (size > 1280 * n_channels) {
208 		TRACE("XM error: pattern data size > %d bytes\n", 1280 * n_channels);
209 		return -1;
210 	}
211 
212 	if (dumbfile_getnc(buffer, size, f) < size)
213 		return -1;
214 
215 	/* compute number of entries */
216 	pattern->n_entries = 0;
217 	pos = channel = row = 0;
218 	while (pos < size) {
219 		if (!(buffer[pos] & XM_ENTRY_PACKED) || (buffer[pos] & 31))
220 			pattern->n_entries++;
221 
222 		channel++;
223 		if (channel >= n_channels) {
224 			channel = 0;
225 			row++;
226 			pattern->n_entries++;
227 		}
228 
229 		if (buffer[pos] & XM_ENTRY_PACKED) {
230 			static const char offset[] = { 0, 1, 1, 2, 1, 2, 2, 3,   1, 2, 2, 3, 2, 3, 3, 4,
231 			                               1, 2, 2, 3, 2, 3, 3, 4,   2, 3, 3, 4, 3, 4, 4, 5 };
232 			pos += 1 + offset[buffer[pos] & 31];
233 		} else {
234 			pos += 5;
235 		}
236 	}
237 
238 	if (row != pattern->n_rows) {
239 		TRACE("XM error: wrong number of rows in pattern data\n");
240 		return -1;
241 	}
242 
243 	pattern->entry = malloc(pattern->n_entries * sizeof(*pattern->entry));
244 	if (!pattern->entry)
245 		return -1;
246 
247 	/* read the entries */
248 	entry = pattern->entry;
249 	pos = channel = row = 0;
250 	while (pos < size) {
251 		unsigned char mask;
252 
253 		if (buffer[pos] & XM_ENTRY_PACKED)
254 			mask = buffer[pos++] & 31;
255 		else
256 			mask = 31;
257 
258 		if (mask) {
259 			ASSERT(entry < pattern->entry + pattern->n_entries);
260 
261 			entry->channel = channel;
262 			entry->mask = 0;
263 
264 			if (mask & XM_ENTRY_NOTE) {
265 				int note = buffer[pos++]; /* 1-96 <=> C0-B7 */
266 				entry->note = (note == XM_NOTE_OFF) ? (IT_NOTE_OFF) : (note-1);
267 				entry->mask |= IT_ENTRY_NOTE;
268 			}
269 
270 			if (mask & XM_ENTRY_INSTRUMENT) {
271 				entry->instrument = buffer[pos++]; /* 1-128 */
272 				entry->mask |= IT_ENTRY_INSTRUMENT;
273 			}
274 
275 			if (mask & XM_ENTRY_VOLUME)
276 				it_xm_convert_volume(buffer[pos++], entry);
277 
278 			effect = effectvalue = 0;
279 			if (mask & XM_ENTRY_EFFECT)      effect = buffer[pos++];
280 			if (mask & XM_ENTRY_EFFECTVALUE) effectvalue = buffer[pos++];
281 			_dumb_it_xm_convert_effect(effect, effectvalue, entry);
282 
283 			entry++;
284 		}
285 
286 		channel++;
287 		if (channel >= n_channels) {
288 			channel = 0;
289 			row++;
290 			IT_SET_END_ROW(entry);
291 			entry++;
292 		}
293 	}
294 
295 	return 0;
296 }
297 
298 
299 
it_xm_make_envelope(IT_ENVELOPE * envelope,const unsigned short * data,int y_offset)300 static int it_xm_make_envelope(IT_ENVELOPE *envelope, const unsigned short *data, int y_offset)
301 {
302 	int i, pos;
303 
304 	if (envelope->n_nodes > 12) {
305 		TRACE("XM error: wrong number of envelope nodes (%d)\n", envelope->n_nodes);
306 		envelope->n_nodes = 0;
307 		return -1;
308 	}
309 
310 	pos = 0;
311 	for (i = 0; i < envelope->n_nodes; i++) {
312 		envelope->node_t[i] = data[pos++];
313 		if (data[pos] > 64) {
314 			TRACE("XM error: out-of-range envelope node (node_y[%d]=%d)\n", i, data[pos]);
315 			envelope->n_nodes = 0;
316 			return -1;
317 		}
318 		envelope->node_y[i] = (signed char)(data[pos++] + y_offset);
319 	}
320 
321 	return 0;
322 }
323 
324 
325 
it_xm_read_instrument(IT_INSTRUMENT * instrument,XM_INSTRUMENT_EXTRA * extra,DUMBFILE * f)326 static int it_xm_read_instrument(IT_INSTRUMENT *instrument, XM_INSTRUMENT_EXTRA *extra, DUMBFILE *f)
327 {
328 	unsigned long size, bytes_read;
329 	unsigned short vol_points[24];
330 	unsigned short pan_points[24];
331 	int i, type;
332 
333 	/* Header size. Tends to be more than the actual size of the structure.
334 	 * So unread bytes must be skipped before reading the first sample
335 	 * header.
336 	 */
337 	size = dumbfile_igetl(f);
338 
339 	//memset(instrument, 0, sizeof(*instrument));
340 	dumbfile_skip(f, 22); /* Instrument name */
341 	dumbfile_skip(f, 1);  /* Instrument type. Should be 0, but seems random. */
342 	extra->n_samples = dumbfile_igetw(f);
343 
344 	if (dumbfile_error(f) || (unsigned int)extra->n_samples > XM_MAX_SAMPLES_PER_INSTRUMENT)
345 		return -1;
346 
347 	bytes_read = 4 + 22 + 1 + 2;
348 
349 	if (extra->n_samples) {
350 		/* sample header size */
351 		if (dumbfile_igetl(f) != 0x28) {
352 			TRACE("XM error: unexpected sample header size\n");
353 			return -1;
354 		}
355 
356 		/* sample map */
357 		for (i = 0; i < 96; i++) {
358 			instrument->map_sample[i] = dumbfile_getc(f) + 1;
359 			instrument->map_note[i] = i;
360 		}
361 
362 		if (dumbfile_error(f))
363 			return 1;
364 
365 		/* volume/panning envelopes */
366 		for (i = 0; i < 24; i++)
367 			vol_points[i] = dumbfile_igetw(f);
368 		for (i = 0; i < 24; i++)
369 			pan_points[i] = dumbfile_igetw(f);
370 
371 		instrument->volume_envelope.n_nodes = dumbfile_getc(f);
372 		instrument->pan_envelope.n_nodes = dumbfile_getc(f);
373 
374 		if (dumbfile_error(f))
375 			return -1;
376 
377 		instrument->volume_envelope.sus_loop_start = dumbfile_getc(f);
378 		instrument->volume_envelope.loop_start = dumbfile_getc(f);
379 		instrument->volume_envelope.loop_end = dumbfile_getc(f);
380 
381 		instrument->pan_envelope.sus_loop_start = dumbfile_getc(f);
382 		instrument->pan_envelope.loop_start = dumbfile_getc(f);
383 		instrument->pan_envelope.loop_end = dumbfile_getc(f);
384 
385 		/* The envelope handler for XM files won't use sus_loop_end. */
386 
387 		type = dumbfile_getc(f);
388 		instrument->volume_envelope.flags = 0;
389 		if ((type & XM_ENVELOPE_ON) && instrument->volume_envelope.n_nodes)
390 			instrument->volume_envelope.flags |= IT_ENVELOPE_ON;
391 		if (type & XM_ENVELOPE_LOOP)    instrument->volume_envelope.flags |= IT_ENVELOPE_LOOP_ON;
392 #if 1
393 		if (type & XM_ENVELOPE_SUSTAIN) instrument->volume_envelope.flags |= IT_ENVELOPE_SUSTAIN_LOOP;
394 #else // This is now handled in itrender.c
395 		/* let's avoid fading out when reaching the last envelope node */
396 		if (!(type & XM_ENVELOPE_LOOP)) {
397 			instrument->volume_envelope.loop_start = instrument->volume_envelope.n_nodes-1;
398 			instrument->volume_envelope.loop_end = instrument->volume_envelope.n_nodes-1;
399 		}
400 		instrument->volume_envelope.flags |= IT_ENVELOPE_LOOP_ON;
401 #endif
402 
403 		type = dumbfile_getc(f);
404 		instrument->pan_envelope.flags = 0;
405 		if ((type & XM_ENVELOPE_ON) && instrument->pan_envelope.n_nodes)
406 			instrument->pan_envelope.flags |= IT_ENVELOPE_ON;
407 		if (type & XM_ENVELOPE_LOOP)    instrument->pan_envelope.flags |= IT_ENVELOPE_LOOP_ON; // should this be here?
408 		if (type & XM_ENVELOPE_SUSTAIN) instrument->pan_envelope.flags |= IT_ENVELOPE_SUSTAIN_LOOP;
409 
410 		if (it_xm_make_envelope(&instrument->volume_envelope, vol_points, 0) != 0) {
411 			TRACE("XM error: volume envelope\n");
412 			if (instrument->volume_envelope.flags & IT_ENVELOPE_ON) return -1;
413 		}
414 
415 		if (it_xm_make_envelope(&instrument->pan_envelope, pan_points, -32) != 0) {
416 			TRACE("XM error: pan envelope\n");
417 			if (instrument->pan_envelope.flags & IT_ENVELOPE_ON) return -1;
418 		}
419 
420 		instrument->pitch_envelope.flags = 0;
421 
422 		extra->vibrato_type = dumbfile_getc(f);
423 		extra->vibrato_sweep = dumbfile_getc(f);
424 		extra->vibrato_depth = dumbfile_getc(f);
425 		extra->vibrato_speed = dumbfile_getc(f);
426 
427 		if (dumbfile_error(f) || extra->vibrato_type >= 4)
428 			return -1;
429 
430 		/** WARNING: lossy approximation */
431 		instrument->fadeout = (dumbfile_igetw(f)*128 + 64)/0xFFF;
432 
433 		dumbfile_skip(f, 2); /* reserved */
434 
435 		bytes_read += 4 + 96 + 48 + 48 + 14*1 + 2 + 2;
436 	}
437 
438 	if (dumbfile_skip(f, size - bytes_read))
439 		return -1;
440 
441 	instrument->new_note_action = NNA_NOTE_CUT;
442 	instrument->dup_check_type = DCT_OFF;
443 	instrument->dup_check_action = DCA_NOTE_CUT;
444 	instrument->pp_separation = 0;
445 	instrument->pp_centre = 60; /* C-5 */
446 	instrument->global_volume = 128;
447 	instrument->default_pan = 32;
448 	instrument->random_volume = 0;
449 	instrument->random_pan = 0;
450 	instrument->filter_cutoff = 0;
451 	instrument->filter_resonance = 0;
452 
453 	return 0;
454 }
455 
456 
457 
458 /* I (entheh) have two XM files saved by a very naughty program. After a
459  * 16-bit sample, it saved a rogue byte. The length of the sample was indeed
460  * an odd number, incremented to include the rogue byte.
461  *
462  * In this function we are converting sample lengths and loop points so they
463  * are measured in samples. This means we forget about the extra bytes, and
464  * they don't get skipped. So we fail trying to read the next instrument.
465  *
466  * To get around this, this function returns the number of rogue bytes that
467  * won't be accounted for by reading sample->length samples. It returns a
468  * negative number on failure.
469  */
it_xm_read_sample_header(IT_SAMPLE * sample,DUMBFILE * f)470 static int it_xm_read_sample_header(IT_SAMPLE *sample, DUMBFILE *f)
471 {
472 	int type;
473 	int relative_note_number; /* relative to C4 */
474 	int finetune;
475 	int roguebytes;
476 	int roguebytesmask;
477 
478 	sample->length         = dumbfile_igetl(f);
479 	sample->loop_start     = dumbfile_igetl(f);
480 	sample->loop_end       = sample->loop_start + dumbfile_igetl(f);
481 	sample->global_volume  = 64;
482 	sample->default_volume = dumbfile_getc(f);
483 	finetune               = (signed char)dumbfile_getc(f); /* -128..127 <=> -1 semitone .. +127/128 of a semitone */
484 	type                   = dumbfile_getc(f);
485 	sample->default_pan    = (dumbfile_getc(f)*64)/255 | 128; /* 0-255 */
486 	relative_note_number   = (signed char)dumbfile_getc(f);
487 
488 	dumbfile_skip(f, 1);  /* reserved */
489 	dumbfile_skip(f, 22); /* sample name */
490 
491 	if (dumbfile_error(f))
492 		return -1;
493 
494 	sample->C5_speed = (long)(16726.0*pow(DUMB_SEMITONE_BASE, relative_note_number)*pow(DUMB_PITCH_BASE, finetune*2));
495 
496 	sample->flags = IT_SAMPLE_EXISTS;
497 
498 	roguebytes = (int)sample->length;
499 	roguebytesmask = 3;
500 
501 	if (type & XM_SAMPLE_16BIT) {
502 		sample->flags |= IT_SAMPLE_16BIT;
503 		sample->length >>= 1;
504 		sample->loop_start >>= 1;
505 		sample->loop_end >>= 1;
506 	} else
507 		roguebytesmask >>= 1;
508 
509 	if (type & XM_SAMPLE_STEREO) {
510 		sample->flags |= IT_SAMPLE_STEREO;
511 		sample->length >>= 1;
512 		sample->loop_start >>= 1;
513 		sample->loop_end >>= 1;
514 	} else
515 		roguebytesmask >>= 1;
516 
517 	roguebytes &= roguebytesmask;
518 
519 	if ((unsigned int)sample->loop_start < (unsigned int)sample->loop_end) {
520 		if (type & XM_SAMPLE_FORWARD_LOOP) sample->flags |= IT_SAMPLE_LOOP;
521 		if (type & XM_SAMPLE_PINGPONG_LOOP) sample->flags |= IT_SAMPLE_LOOP | IT_SAMPLE_PINGPONG_LOOP;
522 	}
523 
524 	if (sample->length <= 0)
525 		sample->flags &= ~IT_SAMPLE_EXISTS;
526 	else if ((unsigned int)sample->loop_end > (unsigned int)sample->length)
527 		sample->flags &= ~IT_SAMPLE_LOOP;
528 	else if ((unsigned int)sample->loop_start >= (unsigned int)sample->loop_end)
529 		sample->flags &= ~IT_SAMPLE_LOOP;
530 
531 	return roguebytes;
532 }
533 
534 
535 
it_xm_read_sample_data(IT_SAMPLE * sample,unsigned char roguebytes,DUMBFILE * f)536 static int it_xm_read_sample_data(IT_SAMPLE *sample, unsigned char roguebytes, DUMBFILE *f)
537 {
538 	int old;
539 	long i;
540 	long truncated_size;
541 
542 	if (!(sample->flags & IT_SAMPLE_EXISTS))
543 		return dumbfile_skip(f, roguebytes);
544 
545 	/* let's get rid of the sample data coming after the end of the loop */
546 	if ((sample->flags & IT_SAMPLE_LOOP) && sample->loop_end < sample->length) {
547 		truncated_size = sample->length - sample->loop_end;
548 		sample->length = sample->loop_end;
549 	} else {
550 		truncated_size = 0;
551 	}
552 
553 	sample->left = malloc(sample->length * sizeof(*sample->left));
554 	if (!sample->left)
555 		return -1;
556 
557 	if (sample->flags & IT_SAMPLE_STEREO) {
558 		sample->right = malloc(sample->length * sizeof(*sample->right));
559 		if (!sample->right)
560 			return -1;
561 	}
562 
563 	/* sample data is stored as signed delta values */
564 	old = 0;
565 	if (sample->flags & IT_SAMPLE_16BIT) {
566 		for (i = 0; i < sample->length; i++) {
567 			old = sample->left[i] = (int)(signed short)(old + dumbfile_igetw(f));
568 			sample->left[i] <<= 8;
569 		}
570 	} else {
571 		for (i = 0; i < sample->length; i++) {
572 			old = sample->left[i] = (int)(signed char)(old + dumbfile_getc(f));
573 			sample->left[i] <<= 16;
574 		}
575 	}
576 
577 	/* skip truncated data */
578 	dumbfile_skip(f, (sample->flags & IT_SAMPLE_16BIT) ? (2*truncated_size) : (truncated_size));
579 
580 	if (sample->flags & IT_SAMPLE_STEREO) {
581 		old = 0;
582 		if (sample->flags & IT_SAMPLE_16BIT) {
583 			for (i = 0; i < sample->length; i++) {
584 				old = sample->right[i] = (int)(signed short)(old + dumbfile_igetw(f));
585 				sample->right[i] <<= 8;
586 			}
587 		} else {
588 			for (i = 0; i < sample->length; i++) {
589 				old = sample->right[i] = (int)(signed char)(old + dumbfile_getc(f));
590 				sample->right[i] <<= 16;
591 			}
592 		}
593 		/* skip truncated data */
594 		dumbfile_skip(f, (sample->flags & IT_SAMPLE_16BIT) ? (2*truncated_size) : (truncated_size));
595 	}
596 
597 	dumbfile_skip(f, roguebytes);
598 
599 	if (dumbfile_error(f))
600 		return -1;
601 
602 	return 0;
603 }
604 
605 
606 
607 /* "Real programmers don't document. If it was hard to write,
608  *  it should be hard to understand."
609  *
610  * (Never trust the documentation provided with a tracker.
611  *  Real files are the only truth...)
612  */
it_xm_load_sigdata(DUMBFILE * f)613 static DUMB_IT_SIGDATA *it_xm_load_sigdata(DUMBFILE *f)
614 {
615 	DUMB_IT_SIGDATA *sigdata;
616 	char id_text[18];
617 
618 	int flags;
619 	int n_channels;
620 	int total_samples;
621 	int i, j;
622 
623 	/* check ID text */
624 	if (dumbfile_getnc(id_text, 17, f) < 17)
625 		return NULL;
626 	id_text[17] = 0;
627 	if (strcmp(id_text, "Extended Module: ") != 0) {
628 		TRACE("XM error: Not an Extended Module\n");
629 		return NULL;
630 	}
631 
632 	/* song name */
633 	if (dumbfile_skip(f, 20))
634 		return NULL;
635 
636 	if (dumbfile_getc(f) != 0x1A) {
637 		TRACE("XM error: 0x1A not found\n");
638 		return NULL;
639 	}
640 
641 	/* tracker name */
642 	if (dumbfile_skip(f, 20))
643 		return NULL;
644 
645 	/* version number */
646 	if (dumbfile_igetw(f) != 0x0104) {
647 		TRACE("XM error: wrong format version\n");
648 		return NULL;
649 	}
650 
651 	/*
652 		------------------
653 		---   Header   ---
654 		------------------
655 	*/
656 
657 	/* header size */
658 	if (dumbfile_igetl(f) != 0x0114) {
659 		TRACE("XM error: unexpected header size\n");
660 		return NULL;
661 	}
662 
663 	sigdata = malloc(sizeof(*sigdata));
664 	if (!sigdata)
665 		return NULL;
666 
667 	sigdata->order = NULL;
668 	sigdata->instrument = NULL;
669 	sigdata->sample = NULL;
670 	sigdata->pattern = NULL;
671 	sigdata->midi = NULL;
672 	sigdata->checkpoint = NULL;
673 
674 	sigdata->n_samples        = 0;
675 	sigdata->n_orders         = dumbfile_igetw(f);
676 	sigdata->restart_position = dumbfile_igetw(f);
677 	n_channels                = dumbfile_igetw(f); /* max 32 but we'll be lenient */
678 	sigdata->n_patterns       = dumbfile_igetw(f);
679 	sigdata->n_instruments    = dumbfile_igetw(f); /* max 128 */
680 	flags                     = dumbfile_igetw(f);
681 	sigdata->speed            = dumbfile_igetw(f);
682 	sigdata->tempo            = dumbfile_igetw(f);
683 
684 	/* sanity checks */
685 	if (dumbfile_error(f) || sigdata->n_orders <= 0 || sigdata->n_orders > 256 || sigdata->n_patterns > 256 || sigdata->n_instruments > 128 || n_channels > DUMB_IT_N_CHANNELS) {
686 		_dumb_it_unload_sigdata(sigdata);
687 		return NULL;
688 	}
689 
690 	//if (sigdata->restart_position >= sigdata->n_orders)
691 		//sigdata->restart_position = 0;
692 
693 	/* order table */
694 	sigdata->order = malloc(sigdata->n_orders*sizeof(*sigdata->order));
695 	if (!sigdata->order) {
696 		_dumb_it_unload_sigdata(sigdata);
697 		return NULL;
698 	}
699 	dumbfile_getnc(sigdata->order, sigdata->n_orders, f);
700 	dumbfile_skip(f, 256 - sigdata->n_orders);
701 
702 	if (dumbfile_error(f)) {
703 		_dumb_it_unload_sigdata(sigdata);
704 		return NULL;
705 	}
706 
707 	/*
708 		--------------------
709 		---   Patterns   ---
710 		--------------------
711 	*/
712 
713 	sigdata->pattern = malloc(sigdata->n_patterns * sizeof(*sigdata->pattern));
714 	if (!sigdata->pattern) {
715 		_dumb_it_unload_sigdata(sigdata);
716 		return NULL;
717 	}
718 	for (i = 0; i < sigdata->n_patterns; i++)
719 		sigdata->pattern[i].entry = NULL;
720 
721 	{
722 		unsigned char *buffer = malloc(1280 * n_channels); /* 256 rows * 5 bytes */
723 		if (!buffer) {
724 			_dumb_it_unload_sigdata(sigdata);
725 			return NULL;
726 		}
727 		for (i = 0; i < sigdata->n_patterns; i++) {
728 			if (it_xm_read_pattern(&sigdata->pattern[i], f, n_channels, buffer) != 0) {
729 				free(buffer);
730 				_dumb_it_unload_sigdata(sigdata);
731 				return NULL;
732 			}
733 		}
734 		free(buffer);
735 	}
736 
737 	/*
738 		-----------------------------------
739 		---   Instruments and Samples   ---
740 		-----------------------------------
741 	*/
742 
743 	sigdata->instrument = malloc(sigdata->n_instruments * sizeof(*sigdata->instrument));
744 	if (!sigdata->instrument) {
745 		_dumb_it_unload_sigdata(sigdata);
746 		return NULL;
747 	}
748 
749 	/* With XM, samples are not global, they're part of an instrument. In a
750 	 * file, each instrument is stored with its samples. Because of this, I
751 	 * don't know how to find how many samples are present in the file. Thus
752 	 * I have to do n_instruments reallocation on sigdata->sample.
753 	 * Looking at FT2, it doesn't seem possible to have more than 16 samples
754 	 * per instrument (even though n_samples is stored as 2 bytes). So maybe
755 	 * we could allocate a 128*16 array of samples, and shrink it back to the
756 	 * correct size when we know it?
757 	 * Alternatively, I could allocate samples by blocks of N (still O(n)),
758 	 * or double the number of allocated samples when I need more (O(log n)).
759 	 */
760 	total_samples = 0;
761 	sigdata->sample = NULL;
762 
763 	for (i = 0; i < sigdata->n_instruments; i++) {
764 		XM_INSTRUMENT_EXTRA extra;
765 
766 		if (it_xm_read_instrument(&sigdata->instrument[i], &extra, f) < 0) {
767 			TRACE("XM error: instrument %d\n", i+1);
768 			_dumb_it_unload_sigdata(sigdata);
769 			return NULL;
770 		}
771 
772 		if (extra.n_samples) {
773 			unsigned char roguebytes[XM_MAX_SAMPLES_PER_INSTRUMENT];
774 
775 			/* adjust instrument sample map (make indices absolute) */
776 			for (j = 0; j < 96; j++)
777 				sigdata->instrument[i].map_sample[j] += total_samples;
778 
779 			sigdata->sample = safe_realloc(sigdata->sample, sizeof(*sigdata->sample)*(total_samples+extra.n_samples));
780 			if (!sigdata->sample) {
781 				_dumb_it_unload_sigdata(sigdata);
782 				return NULL;
783 			}
784 			for (j = total_samples; j < total_samples+extra.n_samples; j++)
785 				sigdata->sample[j].right = sigdata->sample[j].left = NULL;
786 
787 			/* read instrument's samples */
788 			for (j = 0; j < extra.n_samples; j++) {
789 				IT_SAMPLE *sample = &sigdata->sample[total_samples+j];
790 				int b = it_xm_read_sample_header(sample, f);
791 				if (b < 0) {
792 					_dumb_it_unload_sigdata(sigdata);
793 					return NULL;
794 				}
795 				roguebytes[j] = b;
796 				// Any reason why these can't be set inside it_xm_read_sample_header()?
797 				sample->vibrato_speed = extra.vibrato_speed;
798 				sample->vibrato_depth = extra.vibrato_depth;
799 				sample->vibrato_rate = extra.vibrato_sweep;
800 				/* Rate and sweep don't match, but the difference is
801 				 * accounted for in itrender.c.
802 				 */
803 				sample->vibrato_waveform = xm_convert_vibrato[extra.vibrato_type];
804 			}
805 			for (j = 0; j < extra.n_samples; j++) {
806 				if (it_xm_read_sample_data(&sigdata->sample[total_samples+j], roguebytes[j], f) != 0) {
807 					_dumb_it_unload_sigdata(sigdata);
808 					return NULL;
809 				}
810 			}
811 			total_samples += extra.n_samples;
812 		}
813 	}
814 
815 	sigdata->n_samples = total_samples;
816 
817 	sigdata->flags = IT_WAS_AN_XM | IT_OLD_EFFECTS | IT_COMPATIBLE_GXX | IT_STEREO | IT_USE_INSTRUMENTS;
818 	// Are we OK with IT_COMPATIBLE_GXX off?
819 	//
820 	// When specifying note + instr + tone portamento, and an old note is still playing (even after note off):
821 	// - If Compatible Gxx is on, the new note will be triggered only if the instrument _changes_.
822 	// - If Compatible Gxx is off, the new note will always be triggered, provided the instrument is specified.
823 	// - FT2 seems to do the latter (unconfirmed).
824 
825 	// Err, wait. XM playback has its own code. The change made to the IT
826 	// playbackc code didn't affect XM playback. Forget this then. There's
827 	// still a bug in XM playback though, and it'll need some investigation...
828 	// tomorrow...
829 
830 	// UPDATE: IT_COMPATIBLE_GXX is required to be on, so that tone porta has
831 	// separate memory from portamento.
832 
833 	if (flags & XM_LINEAR_FREQUENCY)
834 		sigdata->flags |= IT_LINEAR_SLIDES;
835 
836 	sigdata->global_volume = 128;
837 	sigdata->mixing_volume = 48;
838 	sigdata->pan_separation = 128;
839 
840 	memset(sigdata->channel_volume, 64, DUMB_IT_N_CHANNELS);
841 	memset(sigdata->channel_pan, 32, DUMB_IT_N_CHANNELS);
842 
843 	_dumb_it_fix_invalid_orders(sigdata);
844 
845 	return sigdata;
846 }
847 
848 
849 
850 #if 0 // no fucking way, dude!
851 
852 /* The length returned is the time required to play from the beginning of the
853  * file to the last row of the last order (which is when the player will
854  * loop). Depending on the song, the sound might stop sooner.
855  * Due to fixed point roundoffs, I think this is only reliable to the second.
856  * Full precision could be achieved by using a double during the computation,
857  * or maybe a LONG_LONG.
858  */
859 long it_compute_length(const DUMB_IT_SIGDATA *sigdata)
860 {
861 	IT_PATTERN *pattern;
862 	int tempo, speed;
863 	int loop_start[IT_N_CHANNELS];
864 	char loop_count[IT_N_CHANNELS];
865 	int order, entry;
866 	int row_first_entry = 0;
867 	int jump, jump_dest;
868 	int delay, fine_delay;
869 	int i;
870 	long t;
871 
872 	if (!sigdata)
873 		return 0;
874 
875 	tempo = sigdata->tempo;
876 	speed = sigdata->speed;
877 	order = entry = 0;
878 	jump = jump_dest = 0;
879 	t = 0;
880 
881 	/* for each PATTERN */
882 	for (order = 0; order < sigdata->n_orders; order++) {
883 
884 		if (sigdata->order[order] == IT_ORDER_END) break;
885 		if (sigdata->order[order] == IT_ORDER_SKIP) continue;
886 
887 		for (i = 0; i < IT_N_CHANNELS; i++)
888 			loop_count[i] = -1;
889 
890 		pattern = &sigdata->pattern[ sigdata->order[order] ];
891 		entry = 0;
892 		if (jump == IT_BREAK_TO_ROW) {
893 			int row = 0;
894 			while (row < jump_dest)
895 				if (pattern->entry[entry++].channel >= IT_N_CHANNELS)
896 					row++;
897 		}
898 
899 		/* for each ROW */
900 		while (entry < pattern->n_entries) {
901 			row_first_entry = entry;
902 			delay = fine_delay = 0;
903 			jump = 0;
904 
905 			/* for each note NOTE */
906 			while (entry < pattern->n_entries && pattern->entry[entry].channel < IT_N_CHANNELS) {
907 				int value   = pattern->entry[entry].effectvalue;
908 				int channel = pattern->entry[entry].channel;
909 
910 				switch (pattern->entry[entry].effect) {
911 
912 					case IT_SET_SPEED: speed = value; break;
913 
914 					case IT_JUMP_TO_ORDER:
915 						if (value <= order) /* infinite loop */
916 							return 0;
917 						jump = IT_JUMP_TO_ORDER;
918 						jump_dest = value;
919 						break;
920 
921 					case IT_BREAK_TO_ROW:
922 						jump = IT_BREAK_TO_ROW;
923 						jump_dest = value;
924 						break;
925 
926 					case IT_S:
927 						switch (HIGH(value)) {
928 							case IT_S_PATTERN_DELAY:      delay      = LOW(value); break;
929 							case IT_S_FINE_PATTERN_DELAY: fine_delay = LOW(value); break;
930 							case IT_S_PATTERN_LOOP:
931 								if (LOW(value) == 0) {
932 									loop_start[channel] = row_first_entry;
933 								} else {
934 									if (loop_count[channel] == -1)
935 										loop_count[channel] = LOW(value);
936 
937 									if (loop_count[channel]) {
938 										jump = IT_S_PATTERN_LOOP;
939 										jump_dest = loop_start[channel];
940 									}
941 									loop_count[channel]--;
942 								}
943 								break;
944 						}
945 						break;
946 
947 					case IT_SET_SONG_TEMPO:
948 						switch (HIGH(value)) { /* slides happen every non-row frames */
949 							case 0:  tempo = tempo - LOW(value)*(speed-1); break;
950 							case 1:  tempo = tempo + LOW(value)*(speed-1); break;
951 							default: tempo = value;
952 						}
953 						tempo = MID(32, tempo, 255);
954 						break;
955 				}
956 
957 				entry++;
958 			}
959 
960 			/* end of ROW */
961 			entry++;
962 			t += TICK_TIME_DIVIDEND * (speed*(1+delay) + fine_delay) / tempo;
963 
964 			if (jump == IT_JUMP_TO_ORDER) {
965 				order = jump_dest - 1;
966 				break;
967 			} else if (jump == IT_BREAK_TO_ROW)
968 				break;
969 			else if (jump == IT_S_PATTERN_LOOP)
970 				entry = jump_dest - 1;
971 		}
972 
973 		/* end of PATTERN */
974 	}
975 
976 	return t;
977 }
978 
979 #endif /* 0 */
980 
981 
982 
dumb_read_xm(DUMBFILE * f)983 DUH *dumb_read_xm(DUMBFILE *f)
984 {
985 	sigdata_t *sigdata;
986 	long length;
987 
988 	DUH_SIGTYPE_DESC *descptr = &_dumb_sigtype_it;
989 
990 	sigdata = it_xm_load_sigdata(f);
991 
992 	if (!sigdata)
993 		return NULL;
994 
995 	length = _dumb_it_build_checkpoints(sigdata);
996 
997 	return make_duh(length, 1, &descptr, &sigdata);
998 }
999