1 /*	MikMod sound library
2 	(c) 1998, 1999, 2000, 2001 Miodrag Vallat and others - see file AUTHORS
3 	for complete list.
4 
5 	This library is free software; you can redistribute it and/or modify
6 	it under the terms of the GNU Library General Public License as
7 	published by the Free Software Foundation; either version 2 of
8 	the License, or (at your option) any later version.
9 
10 	This program is distributed in the hope that it will be useful,
11 	but WITHOUT ANY WARRANTY; without even the implied warranty of
12 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 	GNU Library General Public License for more details.
14 
15 	You should have received a copy of the GNU Library General Public
16 	License along with this library; if not, write to the Free Software
17 	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18 	02111-1307, USA.
19 */
20 
21 /*==============================================================================
22 
23   $Id$
24 
25   Routines for loading samples. The sample loader utilizes the routines
26   provided by the "registered" sample loader.
27 
28 ==============================================================================*/
29 
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33 
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 
38 #include "mikmod_internals.h"
39 
40 static	int sl_rlength;
41 static	SWORD sl_old;
42 static	SWORD *sl_buffer=NULL;
43 static	SAMPLOAD *musiclist=NULL,*sndfxlist=NULL;
44 
45 /* size of the loader buffer in words */
46 #define SLBUFSIZE 2048
47 
48 /* IT-Compressed status structure */
49 typedef struct ITPACK {
50 	UWORD bits;    /* current number of bits */
51 	UWORD bufbits; /* bits in buffer */
52 	SWORD last;    /* last output */
53 	UBYTE buf;     /* bit buffer */
54 } ITPACK;
55 
SL_Init(SAMPLOAD * s)56 BOOL SL_Init(SAMPLOAD* s)
57 {
58 	if(!sl_buffer)
59 		if(!(sl_buffer=(SWORD*)MikMod_malloc(SLBUFSIZE*sizeof(SWORD)))) return 0;
60 
61 	sl_rlength = s->length;
62 	if(s->infmt & SF_16BITS) sl_rlength>>=1;
63 	sl_old = 0;
64 
65 	return 1;
66 }
67 
SL_Exit(SAMPLOAD * s)68 void SL_Exit(SAMPLOAD *s)
69 {
70 	if(sl_rlength>0) _mm_fseek(s->reader,sl_rlength,SEEK_CUR);
71 
72 	MikMod_free(sl_buffer);
73 	sl_buffer=NULL;
74 }
75 
76 /* unpack a 8bit IT packed sample */
read_itcompr8(ITPACK * status,MREADER * reader,SWORD * out,UWORD count,UWORD * incnt)77 static int read_itcompr8(ITPACK* status,MREADER *reader,SWORD *out,UWORD count,UWORD* incnt)
78 {
79 	SWORD *dest=out,*end=out+count;
80 	UWORD x,y,needbits,havebits,new_count=0;
81 	UWORD bits = status->bits;
82 	UWORD bufbits = status->bufbits;
83 	SBYTE last = status->last;
84 	UBYTE buf = status->buf;
85 
86 	while (dest<end) {
87 		needbits=new_count?3:bits;
88 		x=havebits=0;
89 		while (needbits) {
90 			/* feed buffer */
91 			if (!bufbits) {
92 				if((*incnt)--)
93 					buf=_mm_read_UBYTE(reader);
94 				else
95 					buf=0;
96 				bufbits=8;
97 			}
98 			/* get as many bits as necessary */
99 			y = needbits<bufbits?needbits:bufbits;
100 			x|= (buf & ((1<<y)- 1))<<havebits;
101 			buf>>=y;
102 			bufbits-=y;
103 			needbits-=y;
104 			havebits+=y;
105 		}
106 		if (new_count) {
107 			new_count = 0;
108 			if (++x >= bits)
109 				x++;
110 			bits = x;
111 			continue;
112 		}
113 		if (bits<7) {
114 			if (x==(1<<(bits-1))) {
115 				new_count = 1;
116 				continue;
117 			}
118 		}
119 		else if (bits<9) {
120 			y = (0xff >> (9-bits)) - 4;
121 			if ((x>y)&&(x<=y+8)) {
122 				if ((x-=y)>=bits)
123 					x++;
124 				bits = x;
125 				continue;
126 			}
127 		}
128 		else if (bits<10) {
129 			if (x>=0x100) {
130 				bits=x-0x100+1;
131 				continue;
132 			}
133 		} else {
134 			/* error in compressed data... */
135 			_mm_errno=MMERR_ITPACK_INVALID_DATA;
136 			return 0;
137 		}
138 
139 		if (bits<8) /* extend sign */
140 			x = ((SBYTE)(x <<(8-bits))) >> (8-bits);
141 		*(dest++)= (last+=x) << 8; /* convert to 16 bit */
142 	}
143 	status->bits = bits;
144 	status->bufbits = bufbits;
145 	status->last = last;
146 	status->buf = buf;
147 	return (dest-out);
148 }
149 
150 /* unpack a 16bit IT packed sample */
read_itcompr16(ITPACK * status,MREADER * reader,SWORD * out,UWORD count,UWORD * incnt)151 static int read_itcompr16(ITPACK *status,MREADER *reader,SWORD *out,UWORD count,UWORD* incnt)
152 {
153 	SWORD *dest=out,*end=out+count;
154 	SLONG x,y,needbits,havebits,new_count=0;
155 	UWORD bits = status->bits;
156 	UWORD bufbits = status->bufbits;
157 	SWORD last = status->last;
158 	UBYTE buf = status->buf;
159 
160 	while (dest<end) {
161 		needbits=new_count?4:bits;
162 		x=havebits=0;
163 		while (needbits) {
164 			/* feed buffer */
165 			if (!bufbits) {
166 				if((*incnt)--)
167 					buf=_mm_read_UBYTE(reader);
168 				else
169 					buf=0;
170 				bufbits=8;
171 			}
172 			/* get as many bits as necessary */
173 			y=needbits<bufbits?needbits:bufbits;
174 			x|=(buf &((1<<y)-1))<<havebits;
175 			buf>>=y;
176 			bufbits-=(UWORD)y;
177 			needbits-=(UWORD)y;
178 			havebits+=(UWORD)y;
179 		}
180 		if (new_count) {
181 			new_count = 0;
182 			if (++x >= bits)
183 				x++;
184 			bits = (UWORD)x;
185 			continue;
186 		}
187 		if (bits<7) {
188 			if (x==(1<<(bits-1))) {
189 				new_count=1;
190 				continue;
191 			}
192 		}
193 		else if (bits<17) {
194 			y=(0xffff>>(17-bits))-8;
195 			if ((x>y)&&(x<=y+16)) {
196 				if ((x-=y)>=bits)
197 					x++;
198 				bits = (UWORD)x;
199 				continue;
200 			}
201 		}
202 		else if (bits<18) {
203 			if (x>=0x10000) {
204 				bits=(UWORD)(x-0x10000+1);
205 				continue;
206 			}
207 		} else {
208 			 /* error in compressed data... */
209 			_mm_errno=MMERR_ITPACK_INVALID_DATA;
210 			return 0;
211 		}
212 
213 		if (bits<16) /* extend sign */
214 			x = ((SWORD)(x<<(16-bits)))>>(16-bits);
215 		*(dest++)=(last+=x);
216 	}
217 	status->bits = bits;
218 	status->bufbits = bufbits;
219 	status->last = last;
220 	status->buf = buf;
221 	return (dest-out);
222 }
223 
SL_LoadInternal(void * buffer,UWORD infmt,UWORD outfmt,int scalefactor,ULONG length,MREADER * reader,BOOL dither)224 static int SL_LoadInternal(void* buffer,UWORD infmt,UWORD outfmt,int scalefactor,ULONG length,MREADER* reader,BOOL dither)
225 {
226 	SBYTE *bptr = (SBYTE*)buffer;
227 	SWORD *wptr = (SWORD*)buffer;
228 	int stodo,t,u;
229 
230 	int result,c_block=0;	/* compression bytes until next block */
231 	ITPACK status;
232 	UWORD incnt = 0;
233 
234 	status.buf = 0;
235 	status.last = 0;
236 	status.bufbits = 0;
237 	status.bits = 0;
238 
239 	while(length) {
240 		stodo=(length<SLBUFSIZE)?length:SLBUFSIZE;
241 
242 		if(infmt&SF_ITPACKED) {
243 			sl_rlength=0;
244 			if (!c_block) {
245 				status.bits = (infmt & SF_16BITS) ? 17 : 9;
246 				status.last = status.bufbits = 0;
247 				incnt=_mm_read_I_UWORD(reader);
248 				c_block = (infmt & SF_16BITS) ? 0x4000 : 0x8000;
249 				if(infmt&SF_DELTA) sl_old=0;
250 			}
251 			if (infmt & SF_16BITS) {
252 				if(!(result=read_itcompr16(&status,reader,sl_buffer,stodo,&incnt)))
253 					return 1;
254 			} else {
255 				if(!(result=read_itcompr8(&status,reader,sl_buffer,stodo,&incnt)))
256 					return 1;
257 			}
258 			if(result!=stodo) {
259 				_mm_errno=MMERR_ITPACK_INVALID_DATA;
260 				return 1;
261 			}
262 			c_block -= stodo;
263 		} else {
264 			if(infmt&SF_16BITS) {
265 				if(_mm_eof(reader)) {
266 					_mm_errno=MMERR_NOT_A_STREAM;/* better error? */
267 					return 1;
268 				}
269 				if(infmt&SF_BIG_ENDIAN)
270 					_mm_read_M_SWORDS(sl_buffer,stodo,reader);
271 				else
272 					_mm_read_I_SWORDS(sl_buffer,stodo,reader);
273 			} else {
274 				SBYTE *src;
275 				SWORD *dest;
276 
277 				if(_mm_eof(reader)) {
278 					_mm_errno=MMERR_NOT_A_STREAM;/* better error? */
279 					return 1;
280 				}
281 				reader->Read(reader,sl_buffer,sizeof(SBYTE)*stodo);
282 				src = (SBYTE*)sl_buffer;
283 				dest  = sl_buffer;
284 				src += stodo;dest += stodo;
285 
286 				for(t=0;t<stodo;t++) {
287 					src--;dest--;
288 					*dest = (*src)<<8;
289 				}
290 			}
291 			sl_rlength-=stodo;
292 		}
293 
294 		if(infmt & SF_DELTA)
295 			for(t=0;t<stodo;t++) {
296 				sl_buffer[t] += sl_old;
297 				sl_old = sl_buffer[t];
298 			}
299 
300 		if((infmt^outfmt) & SF_SIGNED)
301 			for(t=0;t<stodo;t++)
302 				sl_buffer[t]^= 0x8000;
303 
304 		if(scalefactor) {
305 			int idx = 0;
306 			SLONG scaleval;
307 
308 			/* Sample Scaling... average values for better results. */
309 			t= 0;
310 			while(t<stodo && length) {
311 				scaleval = 0;
312 				for(u=scalefactor;u && t<stodo;u--,t++)
313 					scaleval+=sl_buffer[t];
314 				sl_buffer[idx++]=(UWORD)(scaleval/(scalefactor-u));
315 				length--;
316 			}
317 			stodo = idx;
318 		} else
319 			length -= stodo;
320 
321 		if (dither) {
322 			if((infmt & SF_STEREO) && !(outfmt & SF_STEREO)) {
323 				/* dither stereo to mono, average together every two samples */
324 				SLONG avgval;
325 				int idx = 0;
326 
327 				t=0;
328 				while(t<stodo && length) {
329 					avgval=sl_buffer[t++];
330 					avgval+=sl_buffer[t++];
331 					sl_buffer[idx++]=(SWORD)(avgval>>1);
332 					length-=2;
333 				}
334 				stodo = idx;
335 			}
336 		}
337 
338 		if(outfmt & SF_16BITS) {
339 			for(t=0;t<stodo;t++)
340 				*(wptr++)=sl_buffer[t];
341 		} else {
342 			for(t=0;t<stodo;t++)
343 				*(bptr++)=sl_buffer[t]>>8;
344 		}
345 	}
346 	return 0;
347 }
348 
SL_Load(void * buffer,SAMPLOAD * smp,ULONG length)349 int SL_Load(void* buffer,SAMPLOAD *smp,ULONG length)
350 {
351 	return SL_LoadInternal(buffer,smp->infmt,smp->outfmt,smp->scalefactor,
352 				length,smp->reader,0);
353 }
354 
355 /* Registers a sample for loading when SL_LoadSamples() is called. */
SL_RegisterSample(SAMPLE * s,int type,MREADER * reader)356 SAMPLOAD* SL_RegisterSample(SAMPLE* s,int type,MREADER* reader)
357 {
358 	SAMPLOAD *news,**samplist,*cruise;
359 
360 	if(type==MD_MUSIC) {
361 		samplist = &musiclist;
362 		cruise = musiclist;
363 	} else
364 	  if (type==MD_SNDFX) {
365 		samplist = &sndfxlist;
366 		cruise = sndfxlist;
367 	} else
368 		return NULL;
369 
370 	/* Allocate and add structure to the END of the list */
371 	if(!(news=(SAMPLOAD*)MikMod_malloc(sizeof(SAMPLOAD)))) return NULL;
372 
373 	if(cruise) {
374 		while(cruise->next) cruise=cruise->next;
375 		cruise->next = news;
376 	} else
377 		*samplist = news;
378 
379 	news->infmt     = s->flags & SF_FORMATMASK;
380 	news->outfmt    = news->infmt;
381 	news->reader    = reader;
382 	news->sample    = s;
383 	news->length    = s->length;
384 	news->loopstart = s->loopstart;
385 	news->loopend   = s->loopend;
386 
387 	return news;
388 }
389 
FreeSampleList(SAMPLOAD * s)390 static void FreeSampleList(SAMPLOAD* s)
391 {
392 	SAMPLOAD *old;
393 
394 	while(s) {
395 		old = s;
396 		s = s->next;
397 		MikMod_free(old);
398 	}
399 }
400 
401 /* Returns the total amount of memory required by the samplelist queue. */
SampleTotal(SAMPLOAD * samplist,int type)402 static ULONG SampleTotal(SAMPLOAD* samplist,int type)
403 {
404 	int total = 0;
405 
406 	while(samplist) {
407 		samplist->sample->flags=
408 		  (samplist->sample->flags&~SF_FORMATMASK)|samplist->outfmt;
409 		total += MD_SampleLength(type,samplist->sample);
410 		samplist=samplist->next;
411 	}
412 
413 	return total;
414 }
415 
RealSpeed(SAMPLOAD * s)416 static ULONG RealSpeed(SAMPLOAD *s)
417 {
418 	return(s->sample->speed/(s->scalefactor?s->scalefactor:1));
419 }
420 
DitherSamples(SAMPLOAD * samplist,int type)421 static int DitherSamples(SAMPLOAD* samplist,int type)
422 {
423 	SAMPLOAD *c2smp=NULL;
424 	ULONG maxsize, speed;
425 	SAMPLOAD *s;
426 
427 	if(!samplist) return 0;
428 
429 	if((maxsize=MD_SampleSpace(type)*1024) != 0)
430 		while(SampleTotal(samplist,type)>maxsize) {
431 			/* First Pass - check for any 16 bit samples */
432 			s = samplist;
433 			while(s) {
434 				if(s->outfmt & SF_16BITS) {
435 					SL_Sample16to8(s);
436 					break;
437 				}
438 				s=s->next;
439 			}
440 			/* Second pass (if no 16bits found above) is to take the sample with
441 			   the highest speed and dither it by half. */
442 			if(!s) {
443 				s = samplist;
444 				speed = 0;
445 				while(s) {
446 					if((s->sample->length) && (RealSpeed(s)>speed)) {
447 						speed=RealSpeed(s);
448 						c2smp=s;
449 					}
450 					s=s->next;
451 				}
452 				if (c2smp)
453 					SL_HalveSample(c2smp,2);
454 			}
455 		}
456 
457 	/* Samples dithered, now load them ! */
458 	s = samplist;
459 	while(s) {
460 		/* sample has to be loaded ? -> increase number of samples, allocate
461 		   memory and load sample. */
462 		if(s->sample->length) {
463 			if(s->sample->seekpos)
464 				_mm_fseek(s->reader, s->sample->seekpos, SEEK_SET);
465 
466 			/* Call the sample load routine of the driver module. It has to
467 			   return a 'handle' (>=0) that identifies the sample. */
468 			s->sample->handle = MD_SampleLoad(s, type);
469 			s->sample->flags  = (s->sample->flags & ~SF_FORMATMASK) | s->outfmt;
470 			if(s->sample->handle<0) {
471 				FreeSampleList(samplist);
472 				if(_mm_errorhandler) _mm_errorhandler();
473 				return 1;
474 			}
475 		}
476 		s = s->next;
477 	}
478 
479 	FreeSampleList(samplist);
480 	return 0;
481 }
482 
SL_LoadSamples(void)483 int SL_LoadSamples(void)
484 {
485 	int rc;
486 
487 	_mm_critical = 0;
488 
489 	if((!musiclist)&&(!sndfxlist)) return 0;
490 	rc=DitherSamples(musiclist,MD_MUSIC)||DitherSamples(sndfxlist,MD_SNDFX);
491 	musiclist=sndfxlist=NULL;
492 
493 	return rc;
494 }
495 
SL_Sample16to8(SAMPLOAD * s)496 void SL_Sample16to8(SAMPLOAD* s)
497 {
498 	s->outfmt &= ~SF_16BITS;
499 	s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
500 }
501 
SL_Sample8to16(SAMPLOAD * s)502 void SL_Sample8to16(SAMPLOAD* s)
503 {
504 	s->outfmt |= SF_16BITS;
505 	s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
506 }
507 
SL_SampleSigned(SAMPLOAD * s)508 void SL_SampleSigned(SAMPLOAD* s)
509 {
510 	s->outfmt |= SF_SIGNED;
511 	s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
512 }
513 
SL_SampleUnsigned(SAMPLOAD * s)514 void SL_SampleUnsigned(SAMPLOAD* s)
515 {
516 	s->outfmt &= ~SF_SIGNED;
517 	s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
518 }
519 
SL_HalveSample(SAMPLOAD * s,int factor)520 void SL_HalveSample(SAMPLOAD* s,int factor)
521 {
522 	s->scalefactor=factor>0?factor:2;
523 
524 	s->sample->divfactor = s->scalefactor;
525 	s->sample->length    = s->length / s->scalefactor;
526 	s->sample->loopstart = s->loopstart / s->scalefactor;
527 	s->sample->loopend   = s->loopend / s->scalefactor;
528 }
529 
530 /* ex:set ts=4: */
531