1 /*  _______         ____    __         ___    ___
2  * \    _  \       \    /  \  /       \   \  /   /       '   '  '
3  *  |  | \  \       |  |    ||         |   \/   |         .      .
4  *  |  |  |  |      |  |    ||         ||\  /|  |
5  *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
6  *  |  |  |  |      |  |    ||         ||    |  |         .      .
7  *  |  |_/  /        \  \__//          ||    |  |
8  * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
9  *                                                      /  \
10  *                                                     / .  \
11  * reads3m.c - Code to read a ScreamTracker 3         / / \  \
12  *             module from an open file.             | <  /   \_
13  *                                                   |  \/ /\   /
14  * By entheh.                                         \_  /  > /
15  *                                                      | \ / /
16  *                                                      |  ' /
17  *                                                       \__/
18  */
19 
20 // IT_STEREO... :o
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include "dumb.h"
25 #include "internal/it.h"
26 
27 
28 
29 /** WARNING: this is duplicated in itread.c */
it_seek(DUMBFILE * f,long offset)30 static int it_seek(DUMBFILE *f, long offset)
31 {
32 	long pos = dumbfile_pos(f);
33 
34 	if (pos > offset)
35 		return -1;
36 
37 	if (pos < offset)
38 		if (dumbfile_skip(f, offset - pos))
39 			return -1;
40 
41 	return 0;
42 }
43 
44 
45 
it_s3m_read_sample_header(IT_SAMPLE * sample,long * offset,DUMBFILE * f)46 static int it_s3m_read_sample_header(IT_SAMPLE *sample, long *offset, DUMBFILE *f)
47 {
48 	unsigned char type;
49 	int flags;
50 
51 	type = dumbfile_getc(f);
52 
53 	if (type > 1) {
54 		/** WARNING: no adlib support */
55 	}
56 
57 	/* Skip DOS Filename */
58 	dumbfile_skip(f, 13);
59 
60 	*offset = dumbfile_igetw(f) << 4;
61 
62 	sample->length = dumbfile_igetl(f);
63 	sample->loop_start = dumbfile_igetl(f);
64 	sample->loop_end = dumbfile_igetl(f);
65 
66 	sample->default_volume = dumbfile_getc(f);
67 
68 	dumbfile_skip(f, 1);
69 
70 	if (dumbfile_getc(f) != 0)
71 		/* Sample is packed apparently (or error reading from file). We don't
72 		 * know how to read packed samples.
73 		 */
74 		return -1;
75 
76 	flags = dumbfile_getc(f);
77 
78 	sample->C5_speed = dumbfile_igetl(f) << 1;
79 
80 	/* Skip four unused bytes, three internal variables and sample name. */
81 	dumbfile_skip(f, 4+2+2+4+28);
82 
83 	if (type == 0) {
84 		/* Looks like no-existy. Anyway, there's for sure no 'SCRS'... */
85 		sample->flags &= ~IT_SAMPLE_EXISTS;
86 		return dumbfile_error(f);
87 	}
88 
89 	if (dumbfile_mgetl(f) != DUMB_ID('S','C','R','S'))
90 		return -1;
91 
92 	sample->global_volume = 64;
93 
94 	sample->flags = IT_SAMPLE_EXISTS;
95 	if (flags & 1) sample->flags |= IT_SAMPLE_LOOP;
96 	if (flags & 2) sample->flags |= IT_SAMPLE_STEREO;
97 	if (flags & 4) sample->flags |= IT_SAMPLE_16BIT;
98 
99 	sample->default_pan = 0; // 0 = don't use, or 160 = centre?
100 
101 	if (sample->length <= 0)
102 		sample->flags &= ~IT_SAMPLE_EXISTS;
103 	else if (sample->flags & IT_SAMPLE_LOOP) {
104 		if ((unsigned int)sample->loop_end > (unsigned int)sample->length)
105 			sample->flags &= ~IT_SAMPLE_LOOP;
106 		else if ((unsigned int)sample->loop_start >= (unsigned int)sample->loop_end)
107 			sample->flags &= ~IT_SAMPLE_LOOP;
108 		else
109 			/* ScreamTracker seems not to save what comes after the loop end
110 			 * point, but rather to assume it is a duplicate of what comes at
111 			 * the loop start point. I am not completely sure of this though.
112 			 * It is easy to evade; simply truncate the sample.
113 			 */
114 			sample->length = sample->loop_end;
115 	}
116 
117 
118 	//Do we need to set all these?
119 	sample->vibrato_speed = 0;
120 	sample->vibrato_depth = 0;
121 	sample->vibrato_rate = 0;
122 	sample->vibrato_waveform = IT_VIBRATO_SINE;
123 
124 	return dumbfile_error(f);
125 }
126 
127 
128 
it_s3m_read_sample_data(IT_SAMPLE * sample,int ffi,DUMBFILE * f)129 static int it_s3m_read_sample_data(IT_SAMPLE *sample, int ffi, DUMBFILE *f)
130 {
131 	long n;
132 
133 	sample->left = malloc(sample->length * sizeof(*sample->left));
134 	if (!sample->left)
135 		return -1;
136 
137 	if (sample->flags & IT_SAMPLE_STEREO) {
138 		sample->right = malloc(sample->length * sizeof(*sample->right));
139 		if (!sample->right)
140 			return -1;
141 	}
142 
143 	if (sample->flags & IT_SAMPLE_STEREO) {
144 		if (sample->flags & IT_SAMPLE_16BIT) {
145 			for (n = 0; n < sample->length; n++)
146 				sample->left[n] = (int)(signed short)dumbfile_igetw(f) << 8;
147 			for (n = 0; n < sample->length; n++)
148 				sample->right[n] = (int)(signed short)dumbfile_igetw(f) << 8;
149 		} else {
150 			for (n = 0; n < sample->length; n++)
151 				sample->left[n] = (int)(signed char)dumbfile_getc(f) << 16;
152 			for (n = 0; n < sample->length; n++)
153 				sample->right[n] = (int)(signed char)dumbfile_getc(f) << 16;
154 		}
155 	} else if (sample->flags & IT_SAMPLE_16BIT)
156 		for (n = 0; n < sample->length; n++)
157 			sample->left[n] = (int)(signed short)dumbfile_igetw(f) << 8;
158 	else
159 		for (n = 0; n < sample->length; n++)
160 			sample->left[n] = (int)(signed char)dumbfile_getc(f) << 16;
161 
162 	if (dumbfile_error(f))
163 		return -1;
164 
165 	if (ffi != 1) {
166 		/* Convert to signed. */
167 		for (n = 0; n < sample->length; n++)
168 			sample->left[n] ^= 0xFF800000;
169 
170 		if (sample->right)
171 			for (n = 0; n < sample->length; n++)
172 				sample->right[n] ^= 0xFF800000;
173 	}
174 
175 	return 0;
176 }
177 
178 
179 
it_s3m_read_pattern(IT_PATTERN * pattern,DUMBFILE * f,unsigned char * buffer)180 static int it_s3m_read_pattern(IT_PATTERN *pattern, DUMBFILE *f, unsigned char *buffer)
181 {
182 	int buflen = 0;
183 	int bufpos = 0;
184 
185 	IT_ENTRY *entry;
186 
187 	unsigned char channel;
188 
189 	/* Haha, this is hilarious!
190 	 *
191 	 * Well, after some experimentation, it seems that different S3M writers
192 	 * define the format in different ways. The S3M docs say that the first
193 	 * two bytes hold the "length of [the] packed pattern", and the packed
194 	 * pattern data follow. Judging by the contents of ARMANI.S3M, packaged
195 	 * with ScreamTracker itself, the measure of length _includes_ the two
196 	 * bytes used to store the length; in other words, we should read
197 	 * (length - 2) more bytes. However, aryx.s3m, packaged with ModPlug
198 	 * Tracker, excludes these two bytes, so (length) more bytes must be
199 	 * read.
200 	 *
201 	 * Call me crazy, but I just find it insanely funny that the format was
202 	 * misunderstood in this way :D
203 	 *
204 	 * Now we can't just risk reading two extra bytes, because then we
205 	 * overshoot, and DUMBFILEs don't support backward seeking (for a good
206 	 * reason). Luckily, there is a way. We can read the data little by
207 	 * little, and stop when we have 64 rows in memory. Provided we protect
208 	 * against buffer overflow, this method should work with all sensibly
209 	 * written S3M files. If you find one for which it does not work, please
210 	 * let me know at entheh@users.sf.net so I can look at it.
211 	 */
212 
213 	/* Discard the length. */
214 	dumbfile_skip(f, 2);
215 
216 	if (dumbfile_error(f))
217 		return -1;
218 
219 	pattern->n_rows = 0;
220 	pattern->n_entries = 0;
221 
222 	/* Read in the pattern data, little by little, and work out how many
223 	 * entries we need room for. Sorry, but this is just so funny...
224 	 */
225 	for (;;) {
226 		unsigned char b = buffer[buflen++] = dumbfile_getc(f);
227 
228 #if 1
229 		static const unsigned char used[8] = {0, 2, 1, 3, 2, 4, 3, 5};
230 		channel = b & 31;
231 		b >>= 5;
232 		pattern->n_entries++;
233 		if (b) {
234 			if (buflen + used[b] >= 65536) return -1;
235 			dumbfile_getnc(buffer + buflen, used[b], f);
236 			buflen += used[b];
237 		} else {
238 			/* End of row */
239 			if (++pattern->n_rows == 64) break;
240 			if (buflen >= 65536) return -1;
241 		}
242 #else
243 		if (b == 0) {
244 			/* End of row */
245 			pattern->n_entries++;
246 			if (++pattern->n_rows == 64) break;
247 			if (buflen >= 65536) return -1;
248 		} else {
249 			static const unsigned char used[8] = {0, 2, 1, 3, 2, 4, 3, 5};
250 			channel = b & 31;
251 			b >>= 5;
252 			if (b) {
253 				pattern->n_entries++;
254 				if (buflen + used[b] >= 65536) return -1;
255 				dumbfile_getnc(buffer + buflen, used[b], f);
256 				buflen += used[b];
257 			}
258 		}
259 #endif
260 
261 		/* We have ensured that buflen < 65536 at this point, so it is safe
262 		 * to iterate and read at least one more byte without checking.
263 		 * However, now would be a good time to check for errors reading from
264 		 * the file.
265 		 */
266 
267 		if (dumbfile_error(f))
268 			return -1;
269 	}
270 
271 	pattern->entry = malloc(pattern->n_entries * sizeof(*pattern->entry));
272 
273 	if (!pattern->entry)
274 		return -1;
275 
276 	entry = pattern->entry;
277 
278 	while (bufpos < buflen) {
279 		unsigned char b = buffer[bufpos++];
280 
281 #if 1
282 		if (!(b & ~31))
283 #else
284 		if (b == 0)
285 #endif
286 		{
287 			/* End of row */
288 			IT_SET_END_ROW(entry);
289 			entry++;
290 			continue;
291 		}
292 
293 		channel = b & 31;
294 
295 		if (b & 224) {
296 			entry->mask = 0;
297 			entry->channel = channel;
298 
299 			if (b & 32) {
300 				unsigned char n = buffer[bufpos++];
301 				if (n != 255) {
302 					if (n == 254)
303 						entry->note = IT_NOTE_CUT;
304 					else
305 						entry->note = (n >> 4) * 12 + (n & 15);
306 					entry->mask |= IT_ENTRY_NOTE;
307 				}
308 
309 				entry->instrument = buffer[bufpos++];
310 				if (entry->instrument)
311 					entry->mask |= IT_ENTRY_INSTRUMENT;
312 			}
313 
314 			if (b & 64) {
315 				entry->volpan = buffer[bufpos++];
316 				if (entry->volpan != 255)
317 					entry->mask |= IT_ENTRY_VOLPAN;
318 			}
319 
320 			if (b & 128) {
321 				entry->effect = buffer[bufpos++];
322 				entry->effectvalue = buffer[bufpos++];
323 				if (entry->effect != 255) {
324 					entry->mask |= IT_ENTRY_EFFECT;
325 					if (entry->effect == IT_BREAK_TO_ROW)
326 						entry->effectvalue -= (entry->effectvalue >> 4) * 6;
327 				}
328 				/** WARNING: ARGH! CONVERT TEH EFFECTS!@~ */
329 			}
330 
331 			entry++;
332 		}
333 	}
334 
335 	ASSERT(entry == pattern->entry + pattern->n_entries);
336 
337 	return 0;
338 }
339 
340 
341 
342 /** WARNING: this is duplicated in itread.c - also bad practice to use the same struct name unless they are unified in a header */
343 /* Currently we assume the sample data are stored after the sample headers in
344  * module files. This assumption may be unjustified; let me know if you have
345  * trouble.
346  */
347 
348 #define IT_COMPONENT_INSTRUMENT 1
349 #define IT_COMPONENT_PATTERN    2
350 #define IT_COMPONENT_SAMPLE     3
351 
352 typedef struct IT_COMPONENT
353 {
354 	unsigned char type;
355 	unsigned char n;
356 	long offset;
357 	short sampfirst; /* component[sampfirst] = first sample data after this */
358 	short sampnext; /* sampnext is used to create linked lists of sample data */
359 }
360 IT_COMPONENT;
361 
362 
363 
it_component_compare(const void * e1,const void * e2)364 static int it_component_compare(const void *e1, const void *e2)
365 {
366 	return ((const IT_COMPONENT *)e1)->offset -
367 	       ((const IT_COMPONENT *)e2)->offset;
368 }
369 
370 
371 
it_s3m_load_sigdata(DUMBFILE * f)372 static DUMB_IT_SIGDATA *it_s3m_load_sigdata(DUMBFILE *f)
373 {
374 	DUMB_IT_SIGDATA *sigdata;
375 
376 	int flags, cwtv, ffi;
377 	int default_pan_present;
378 
379 	IT_COMPONENT *component;
380 	int n_components = 0;
381 
382 	int n;
383 
384 	unsigned char *buffer;
385 
386 	/* Skip song name. */
387 	if (dumbfile_skip(f, 28)) return NULL;
388 
389 	if (dumbfile_getc(f) != 0x1A) return NULL;
390 	if (dumbfile_getc(f) != 16) return NULL;
391 
392 	if (dumbfile_skip(f, 2)) return NULL;
393 
394 	sigdata = malloc(sizeof(*sigdata));
395 
396 	if (!sigdata)
397 		return NULL;
398 
399 	sigdata->order = NULL;
400 	sigdata->instrument = NULL;
401 	sigdata->sample = NULL;
402 	sigdata->pattern = NULL;
403 	sigdata->midi = NULL;
404 	sigdata->checkpoint = NULL;
405 
406 	sigdata->n_orders = dumbfile_igetw(f);
407 	sigdata->n_instruments = 0;
408 	sigdata->n_samples = dumbfile_igetw(f);
409 	sigdata->n_patterns = dumbfile_igetw(f);
410 
411 	if (dumbfile_error(f) || sigdata->n_orders <= 0 || sigdata->n_samples > 256 || sigdata->n_patterns > 256) {
412 		_dumb_it_unload_sigdata(sigdata);
413 		return NULL;
414 	}
415 
416 	sigdata->order = malloc(sigdata->n_orders);
417 	if (!sigdata->order) {
418 		_dumb_it_unload_sigdata(sigdata);
419 		return NULL;
420 	}
421 
422 	if (sigdata->n_samples) {
423 		sigdata->sample = malloc(sigdata->n_samples * sizeof(*sigdata->sample));
424 		if (!sigdata->sample) {
425 			_dumb_it_unload_sigdata(sigdata);
426 			return NULL;
427 		}
428 		for (n = 0; n < sigdata->n_samples; n++)
429 			sigdata->sample[n].right = sigdata->sample[n].left = NULL;
430 	}
431 
432 	if (sigdata->n_patterns) {
433 		sigdata->pattern = malloc(sigdata->n_patterns * sizeof(*sigdata->pattern));
434 		if (!sigdata->pattern) {
435 			_dumb_it_unload_sigdata(sigdata);
436 			return NULL;
437 		}
438 		for (n = 0; n < sigdata->n_patterns; n++)
439 			sigdata->pattern[n].entry = NULL;
440 	}
441 
442 	flags = dumbfile_igetw(f);
443 
444 	cwtv = dumbfile_igetw(f);
445 
446 	if (cwtv == 0x1300) {
447 		/** WARNING: volume slides on every frame */
448 	}
449 
450 	ffi = dumbfile_igetw(f);
451 
452 	/** WARNING: which ones? */
453 	sigdata->flags = IT_STEREO | IT_OLD_EFFECTS | IT_COMPATIBLE_GXX;
454 
455 	if (dumbfile_mgetl(f) != DUMB_ID('S','C','R','M')) {
456 		_dumb_it_unload_sigdata(sigdata);
457 		return NULL;
458 	}
459 
460 	sigdata->global_volume = dumbfile_getc(f) << 1;
461 	sigdata->speed = dumbfile_getc(f);
462 	if (sigdata->speed == 0) sigdata->speed = 6; // Should we? What about tempo?
463 	sigdata->tempo = dumbfile_getc(f);
464 	/*master_volume = */dumbfile_getc(f); // 7 bits; +128 for stereo
465 	//what do we do with master_volume? it's not the same as mixing volume...
466 	sigdata->mixing_volume = 48;
467 
468 	/* Skip GUS Ultra Click Removal byte. */
469 	dumbfile_getc(f);
470 
471 	default_pan_present = dumbfile_getc(f);
472 
473 	dumbfile_skip(f, 8);
474 
475 	/* Skip Special Custom Data Pointer. */
476 	/** WARNING: investigate this? */
477 	dumbfile_igetw(f);
478 
479 	/* Channel settings for 32 channels, 255=unused, +128=disabled */
480 	{
481 		int i;
482 		for (i = 0; i < 32; i++) {
483 			int c = dumbfile_getc(f);
484 			if (!(c & (128 | 16))) { /* +128=disabled, +16=Adlib */
485 				sigdata->channel_volume[i] = 64;
486 				sigdata->channel_pan[i] = c & 8 ? 12 : 3;
487 				/** WARNING: ah, but it should be 7 for mono... */
488 			} else {
489 				/** WARNING: this could be improved if we support channel muting... */
490 				sigdata->channel_volume[i] = 0;
491 				sigdata->channel_pan[i] = 7;
492 			}
493 		}
494 	}
495 
496 	/* Orders, byte each, length = sigdata->n_orders (should be even) */
497 	dumbfile_getnc(sigdata->order, sigdata->n_orders, f);
498 	sigdata->restart_position = 0;
499 
500 	component = malloc(768*sizeof(*component));
501 	if (!component) {
502 		_dumb_it_unload_sigdata(sigdata);
503 		return NULL;
504 	}
505 
506 	for (n = 0; n < sigdata->n_samples; n++) {
507 		component[n_components].type = IT_COMPONENT_SAMPLE;
508 		component[n_components].n = n;
509 		component[n_components].offset = dumbfile_igetw(f) << 4;
510 		component[n_components].sampfirst = -1;
511 		n_components++;
512 	}
513 
514 	for (n = 0; n < sigdata->n_patterns; n++) {
515 		long offset = dumbfile_igetw(f) << 4;
516 		if (offset) {
517 			component[n_components].type = IT_COMPONENT_PATTERN;
518 			component[n_components].n = n;
519 			component[n_components].offset = offset;
520 			component[n_components].sampfirst = -1;
521 			n_components++;
522 		} else {
523 			/** WARNING: Empty 64-row pattern ... ? (this does happen!) */
524 			sigdata->pattern[n].n_rows = 64;
525 			sigdata->pattern[n].n_entries = 0;
526 		}
527 	}
528 
529 	qsort(component, n_components, sizeof(IT_COMPONENT), &it_component_compare);
530 
531 	/* I found a really dumb S3M file that claimed to contain default pan
532 	 * data but didn't contain any. Programs would load it by reading part of
533 	 * the first instrument header, assuming the data to be default pan
534 	 * positions, and then rereading the instrument module. We cannot do this
535 	 * without obfuscating the file input model, so we insert an extra check
536 	 * here that we won't overrun the start of the first component.
537 	 */
538 	if (default_pan_present == 252 && component[0].offset >= dumbfile_pos(f) + 32) {
539 		/* Channel default pan positions */
540 		int i;
541 		for (i = 0; i < 32; i++) {
542 			int c = dumbfile_getc(f);
543 			if (c & 32)
544 				sigdata->channel_pan[i] = c & 15;
545 		}
546 	}
547 
548 	{
549 		int i;
550 		for (i = 0; i < 32; i++) {
551 			sigdata->channel_pan[i] -= (sigdata->channel_pan[i] & 8) >> 3;
552 			sigdata->channel_pan[i] = ((int)sigdata->channel_pan[i] << 5) / 7;
553 		}
554 	}
555 
556 	/** WARNING: is this right? */
557 	sigdata->pan_separation = 64;
558 
559 	if (dumbfile_error(f)) {
560 		free(component);
561 		_dumb_it_unload_sigdata(sigdata);
562 		return NULL;
563 	}
564 
565 	buffer = malloc(65536);
566 	if (!buffer) {
567 		free(component);
568 		_dumb_it_unload_sigdata(sigdata);
569 		return NULL;
570 	}
571 
572 	for (n = 0; n < n_components; n++) {
573 		long offset;
574 		int m;
575 
576 		if (it_seek(f, component[n].offset)) {
577 			free(buffer);
578 			free(component);
579 			_dumb_it_unload_sigdata(sigdata);
580 			return NULL;
581 		}
582 
583 		switch (component[n].type) {
584 
585 			case IT_COMPONENT_PATTERN:
586 				if (it_s3m_read_pattern(&sigdata->pattern[component[n].n], f, buffer)) {
587 					free(buffer);
588 					free(component);
589 					_dumb_it_unload_sigdata(sigdata);
590 					return NULL;
591 				}
592 				break;
593 
594 			case IT_COMPONENT_SAMPLE:
595 				if (it_s3m_read_sample_header(&sigdata->sample[component[n].n], &offset, f)) {
596 					free(buffer);
597 					free(component);
598 					_dumb_it_unload_sigdata(sigdata);
599 					return NULL;
600 				}
601 
602 				if (sigdata->sample[component[n].n].flags & IT_SAMPLE_EXISTS) {
603 					short *sample;
604 
605 					for (m = n + 1; m < n_components; m++)
606 						if (component[m].offset > offset)
607 							break;
608 					m--;
609 
610 					sample = &component[m].sampfirst;
611 
612 					while (*sample >= 0 && component[*sample].offset <= offset)
613 						sample = &component[*sample].sampnext;
614 
615 					component[n].sampnext = *sample;
616 					*sample = n;
617 
618 					component[n].offset = offset;
619 				}
620 		}
621 
622 		m = component[n].sampfirst;
623 
624 		while (m >= 0) {
625 			if (it_seek(f, component[m].offset)) {
626 				free(buffer);
627 				free(component);
628 				_dumb_it_unload_sigdata(sigdata);
629 				return NULL;
630 			}
631 
632 			if (it_s3m_read_sample_data(&sigdata->sample[component[m].n], ffi, f)) {
633 				free(buffer);
634 				free(component);
635 				_dumb_it_unload_sigdata(sigdata);
636 				return NULL;
637 			}
638 
639 			m = component[m].sampnext;
640 		}
641 	}
642 
643 	free(buffer);
644 	free(component);
645 
646 	_dumb_it_fix_invalid_orders(sigdata);
647 
648 	return sigdata;
649 }
650 
651 
652 
dumb_read_s3m(DUMBFILE * f)653 DUH *dumb_read_s3m(DUMBFILE *f)
654 {
655 	sigdata_t *sigdata;
656 	long length;
657 
658 	DUH_SIGTYPE_DESC *descptr = &_dumb_sigtype_it;
659 
660 	sigdata = it_s3m_load_sigdata(f);
661 
662 	if (!sigdata)
663 		return NULL;
664 
665 	length = _dumb_it_build_checkpoints(sigdata);
666 
667 	return make_duh(length, 1, &descptr, &sigdata);
668 }
669