summaryrefslogtreecommitdiffstats
path: root/src/jake2/sound/WaveLoader.java
blob: a52f3764f28b05bcd1bab75c388a8368013674cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
 * SND_MEM.java
 * Copyright (C) 2004
 * 
 * $Id: WaveLoader.java,v 1.7 2006-01-01 15:07:30 cawe Exp $
 */
/*
Copyright (C) 1997-2001 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
package jake2.sound;

import jake2.Defines;
import jake2.qcommon.Com;
import jake2.qcommon.FS;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteOrder;

import javax.sound.sampled.*;

/**
 * SND_MEM
 */
public class WaveLoader {

	/** 
	 * The ResampleSfx can squeeze and stretch samples to a default sample rate. 
	 * Since Joal and lwjgl sound drivers support this, we don't need it and the samples
	 * can keep their original sample rate. Use this switch for reactivating resampling.
	 */
	private static boolean DONT_DO_A_RESAMPLING_FOR_JOAL_AND_LWJGL = true;
	
	/**
	 * This is the maximum sample length in bytes which has to be replaced by 
	 * a configurable variable.
	 */
	private static int maxsamplebytes = 2048 * 1024;
	
	/** 
	 * Loads a sound from a wav file. 
	 */
	public static sfxcache_t LoadSound(sfx_t s) {
		if (s.name.charAt(0) == '*')
			return null;

		// see if still in memory
		sfxcache_t sc = s.cache;
		if (sc != null)
			return sc;

		String name;
		// load it in
		if (s.truename != null)
			name = s.truename;
		else
			name = s.name;

		String namebuffer;
		if (name.charAt(0) == '#')
			namebuffer = name.substring(1);
		else
			namebuffer = "sound/" + name;

		byte[] data = FS.LoadFile(namebuffer);

		if (data == null) {
			Com.DPrintf("Couldn't load " + namebuffer + "\n");
			return null;
		}
		
		int size = data.length;

		wavinfo_t info = GetWavinfo(s.name, data, size);

		if (info.channels != 1)
		{
			Com.Printf(s.name + " is a stereo sample - ignoring\n");
			return null;
		}

		float stepscale;
		if (DONT_DO_A_RESAMPLING_FOR_JOAL_AND_LWJGL)
			stepscale = 1; 
		else
			stepscale = (float)info.rate / S.getDefaultSampleRate();
		
		int len = (int) (info.samples / stepscale);
		len = len * info.width * info.channels;

		// TODO: handle max sample bytes with a cvar
		if (len >= maxsamplebytes)
		{
			Com.Printf(s.name + " is too long: " + len + " bytes?! ignoring.\n");
			return null;
		}

		sc = s.cache = new sfxcache_t(len);
		         
        sc.length = info.samples;
        sc.loopstart = info.loopstart;
        sc.speed = info.rate;
        sc.width = info.width;
        sc.stereo = info.channels;

		ResampleSfx(s, sc.speed, sc.width, data, info.dataofs);
		data = null;

		return sc;
	}


	/** 
	 * Converts sample data with respect to the endianess and adjusts 
	 * the sample rate of a loaded sample, see flag DONT_DO_A_RESAMPLING_FOR_JOAL_AND_LWJGL.
	 */
	public static void ResampleSfx (sfx_t sfx, int inrate, int inwidth, byte data[], int offset)
	{
        int             outcount;
        int             srcsample;
        int             i;
        int             sample, samplefrac, fracstep;
        sfxcache_t      sc;
        
        sc = sfx.cache;
        
        if (sc == null)
        	return;

        // again calculate the stretching factor.
        // this is usually 0.5, 1, or 2
        
        float stepscale;
        if (DONT_DO_A_RESAMPLING_FOR_JOAL_AND_LWJGL)
        	stepscale = 1;
        else
        	stepscale = (float)inrate / S.getDefaultSampleRate();  
        outcount = (int) (sc.length/stepscale);
        sc.length = outcount;
        
        if (sc.loopstart != -1)
                sc.loopstart = (int) (sc.loopstart / stepscale);

        // if resampled, sample has now the default sample rate
        if (DONT_DO_A_RESAMPLING_FOR_JOAL_AND_LWJGL == false)
        	sc.speed = S.getDefaultSampleRate();

        sc.width = inwidth;
        sc.stereo = 0;
        samplefrac = 0;
        fracstep = (int) (stepscale * 256);
        
        for (i = 0; i < outcount; i++) {
            srcsample = samplefrac >> 8;
            samplefrac += fracstep;

            if (inwidth == 2) {
                sample = (data[offset + srcsample * 2] & 0xff)
                        + (data[offset + srcsample * 2 + 1] << 8);
            } else {
                sample = ((data[offset + srcsample] & 0xff) - 128) << 8;
            }

            if (sc.width == 2) {
                if (Defines.LITTLE_ENDIAN) {
                    sc.data[i * 2] = (byte) (sample & 0xff);
                    sc.data[i * 2 + 1] = (byte) ((sample >>> 8) & 0xff);
                } else {
                    sc.data[i * 2] = (byte) ((sample >>> 8) & 0xff);
                    sc.data[i * 2 + 1] = (byte) (sample & 0xff);
                }
            } else {
                sc.data[i] = (byte) (sample >> 8);
            }
        }
    }


	static byte[] data_b;
	static int data_p;
	static int iff_end;
	static int last_chunk;
	static int iff_data;
	static int iff_chunk_len;


	static short GetLittleShort() {
		int val = 0;
		val = data_b[data_p] & 0xFF;
		data_p++;
		val |= ((data_b[data_p] & 0xFF) << 8);
		data_p++;
		return (short)val;
	}

	static int GetLittleLong() {
		int val = 0;
		val = data_b[data_p] & 0xFF;
		data_p++;
		val |= ((data_b[data_p] & 0xFF) << 8);
		data_p++;
		val |= ((data_b[data_p] & 0xFF) << 16);
		data_p++;
		val |= ((data_b[data_p] & 0xFF) << 24);
		data_p++;
		return val;
	}

	static void FindNextChunk(String name) {
		while (true) {
			data_p = last_chunk;

			if (data_p >= iff_end) { // didn't find the chunk
				data_p = 0;
				return;
			}

			data_p += 4;

			iff_chunk_len = GetLittleLong();
			
			if (iff_chunk_len < 0) {
				data_p = 0;
				return;
			}
			if (iff_chunk_len > 1024*1024) {
				Com.Println(" Warning: FindNextChunk: length is past the 1 meg sanity limit");
			}
			data_p -= 8;
			last_chunk = data_p + 8 + ((iff_chunk_len + 1) & ~1);
			String s = new String(data_b, data_p, 4);
			if (s.equals(name))
				return;
		}
	}

	static void FindChunk(String name) {
		last_chunk = iff_data;
		FindNextChunk(name);
	}

	/*
	============
	GetWavinfo
	============
	*/
	static wavinfo_t GetWavinfo(String name, byte[] wav, int wavlength) {
		wavinfo_t info = new wavinfo_t();
		int i;
		int format;
		int samples;

		if (wav == null)
			return info;

		iff_data = 0;
		iff_end = wavlength;
		data_b = wav;

		// find "RIFF" chunk
		FindChunk("RIFF");
		String s = new String(data_b, data_p + 8, 4);
		if (!s.equals("WAVE")) {
			Com.Printf("Missing RIFF/WAVE chunks\n");
			return info;
		}

		//	   get "fmt " chunk
		iff_data = data_p + 12;
		//	   DumpChunks ();

		FindChunk("fmt ");
		if (data_p == 0) {
			Com.Printf("Missing fmt chunk\n");
			return info;
		}
		data_p += 8;
		format = GetLittleShort();
		if (format != 1) {
			Com.Printf("Microsoft PCM format only\n");
			return info;
		}

		info.channels = GetLittleShort();
		info.rate = GetLittleLong();
		data_p += 4 + 2;
		info.width = GetLittleShort() / 8;

		//	   get cue chunk
		FindChunk("cue ");
		if (data_p != 0) {
			data_p += 32;
			info.loopstart = GetLittleLong();
			//			Com_Printf("loopstart=%d\n", sfx->loopstart);

			// if the next chunk is a LIST chunk, look for a cue length marker
			FindNextChunk("LIST");
			if (data_p != 0) {
				if (data_b.length >= data_p + 32) {
					s = new String(data_b, data_p + 28, 4);
					if (s.equals("MARK")) { // this is not a proper parse, but
											// it works with cooledit...
						data_p += 24;
						i = GetLittleLong(); // samples in loop
						info.samples = info.loopstart + i;
						//					Com_Printf("looped length: %i\n", i);
					}
				}
			}
		} else
			info.loopstart = -1;

		//	   find data chunk
		FindChunk("data");
		if (data_p == 0) {
			Com.Printf("Missing data chunk\n");
			return info;
		}

		data_p += 4;
		samples = GetLittleLong() / info.width;

		if (info.samples != 0) {
			if (samples < info.samples)
				Com.Error(Defines.ERR_DROP, "Sound " + name + " has a bad loop length");
		} else {
			info.samples = samples;
			if (info.loopstart > 0) info.samples -= info.loopstart;
		}
		
		info.dataofs = data_p;

		return info;
	}

	static class wavinfo_t {
		int rate;
		int width;
		int channels;
		int loopstart;
		int samples;
		int dataofs; // chunk starts this many bytes from file start
	}
}