2 Copyright (C) 2003-2005 Mathieu Olivier
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to:
18 Free Software Foundation, Inc.
19 59 Temple Place - Suite 330
20 Boston, MA 02111-1307, USA
27 #include "snd_modplug.h"
29 // BEGIN SECTION FROM modplug.h
32 * This source code is public domain.
34 * Authors: Kenton Varda <temporal@gauge3d.org> (C interface wrapper)
39 MODPLUG_ENABLE_OVERSAMPLING = 1 << 0, /* Enable oversampling (*highly* recommended) */
40 MODPLUG_ENABLE_NOISE_REDUCTION = 1 << 1, /* Enable noise reduction */
41 MODPLUG_ENABLE_REVERB = 1 << 2, /* Enable reverb */
42 MODPLUG_ENABLE_MEGABASS = 1 << 3, /* Enable megabass */
43 MODPLUG_ENABLE_SURROUND = 1 << 4 /* Enable surround sound. */
46 enum _ModPlug_ResamplingMode
48 MODPLUG_RESAMPLE_NEAREST = 0, /* No interpolation (very fast, extremely bad sound quality) */
49 MODPLUG_RESAMPLE_LINEAR = 1, /* Linear interpolation (fast, good quality) */
50 MODPLUG_RESAMPLE_SPLINE = 2, /* Cubic spline interpolation (high quality) */
51 MODPLUG_RESAMPLE_FIR = 3 /* 8-tap fir filter (extremely high quality) */
54 typedef struct _ModPlug_Settings
56 int mFlags; /* One or more of the MODPLUG_ENABLE_* flags above, bitwise-OR'ed */
58 /* Note that ModPlug always decodes sound at 44100kHz, 32 bit, stereo and then
59 * down-mixes to the settings you choose. */
60 int mChannels; /* Number of channels - 1 for mono or 2 for stereo */
61 int mBits; /* Bits per sample - 8, 16, or 32 */
62 int mFrequency; /* Sampling rate - 11025, 22050, or 44100 */
63 int mResamplingMode; /* One of MODPLUG_RESAMPLE_*, above */
65 int mReverbDepth; /* Reverb level 0(quiet)-100(loud) */
66 int mReverbDelay; /* Reverb delay in ms, usually 40-200ms */
67 int mBassAmount; /* XBass level 0(quiet)-100(loud) */
68 int mBassRange; /* XBass cutoff in Hz 10-100 */
69 int mSurroundDepth; /* Surround level 0(quiet)-100(heavy) */
70 int mSurroundDelay; /* Surround delay in ms, usually 5-40ms */
71 int mLoopCount; /* Number of times to loop. Zero prevents looping.
76 typedef struct _ModPlugFile ModPlugFile;
78 // END SECTION FROM modplug.h
80 static ModPlugFile* (*ModPlug_Load) (const void* data, int size);
81 static void (*ModPlug_Unload) (ModPlugFile* file);
82 static int (*ModPlug_Read) (ModPlugFile* file, void* buffer, int size);
83 static void (*ModPlug_Seek) (ModPlugFile* file, int millisecond);
84 static void (*ModPlug_GetSettings) (ModPlug_Settings* settings);
85 static void (*ModPlug_SetSettings) (const ModPlug_Settings* settings);
87 static dllfunction_t modplugfuncs[] =
89 {"ModPlug_Load", (void **) &ModPlug_Load},
90 {"ModPlug_Unload", (void **) &ModPlug_Unload},
91 {"ModPlug_Read", (void **) &ModPlug_Read},
92 {"ModPlug_Seek", (void **) &ModPlug_Seek},
93 {"ModPlug_GetSettings", (void **) &ModPlug_GetSettings},
94 {"ModPlug_SetSettings", (void **) &ModPlug_SetSettings},
98 // Handles for the modplug and modplugfile DLLs
99 static dllhandle_t modplug_dll = NULL;
102 =================================================================
106 =================================================================
113 Try to load the modplugFile DLL
116 qboolean ModPlug_OpenLibrary (void)
118 const char* dllnames_modplug [] =
125 #elif defined(MACOSX)
138 // COMMANDLINEOPTION: Sound: -nomodplug disables modplug sound support
139 if (COM_CheckParm("-nomodplug"))
143 // We need to load both by hand because some OSes seem to not load
144 // the modplug DLL automatically when loading the modplugFile DLL
145 if (! Sys_LoadLibrary (dllnames_modplug, &modplug_dll, modplugfuncs))
147 Sys_UnloadLibrary (&modplug_dll);
148 Con_Printf ("ModPlug support disabled\n");
152 Con_Printf ("ModPlug support enabled\n");
161 Unload the modplugFile DLL
164 void ModPlug_CloseLibrary (void)
166 Sys_UnloadLibrary (&modplug_dll);
171 =================================================================
175 =================================================================
178 #define STREAM_BUFFER_DURATION 1.5f // 1.5 sec
179 #define STREAM_BUFFER_SIZE(format_ptr) ((int)(ceil (STREAM_BUFFER_DURATION * ((format_ptr)->speed * (format_ptr)->width * (format_ptr)->channels))))
180 // We work with 1 sec sequences, so this buffer must be able to contain
181 // 1 sec of sound of the highest quality (48 KHz, 16 bit samples, stereo)
182 static unsigned char resampling_buffer [48000 * 2 * 2];
185 // Per-sfx data structure
191 unsigned int total_length;
194 } modplug_stream_persfx_t;
196 // Per-channel data structure
200 unsigned int sb_offset;
202 snd_buffer_t sb; // must be at the end due to its dynamically allocated size
203 } modplug_stream_perchannel_t;
211 static const snd_buffer_t* ModPlug_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes)
213 modplug_stream_perchannel_t* per_ch = (modplug_stream_perchannel_t *)*chfetcherpointer;
214 modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfxfetcher;
216 int newlength, done, ret, bigendian;
217 unsigned int real_start;
220 // If there's no fetcher structure attached to the channel yet
223 size_t buff_len, memsize;
224 snd_format_t sb_format;
226 sb_format.speed = snd_renderbuffer->format.speed;
227 sb_format.width = per_sfx->format.width;
228 sb_format.channels = per_sfx->format.channels;
230 buff_len = STREAM_BUFFER_SIZE(&sb_format);
231 memsize = sizeof (*per_ch) - sizeof (per_ch->sb.samples) + buff_len;
232 per_ch = (modplug_stream_perchannel_t *)Mem_Alloc (snd_mempool, memsize);
234 // Open it with the modplugFile API
235 per_ch->mf = ModPlug_Load(per_sfx->file, per_sfx->filesize);
238 Con_Printf("error while reading ModPlug stream \"%s\"\n", per_sfx->name);
244 per_ch->sb_offset = 0;
245 per_ch->sb.format = sb_format;
246 per_ch->sb.nbframes = 0;
247 per_ch->sb.maxframes = buff_len / (per_ch->sb.format.channels * per_ch->sb.format.width);
249 *chfetcherpointer = per_ch;
255 factor = per_sfx->format.width * per_sfx->format.channels;
257 // If the stream buffer can't contain that much samples anyway
258 if (nbsampleframes > sb->maxframes)
260 Con_Printf ("ModPlug_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes);
264 // If the data we need has already been decompressed in the sfxbuffer, just return it
265 if (per_ch->sb_offset <= real_start && per_ch->sb_offset + sb->nbframes >= real_start + nbsampleframes)
267 *start = per_ch->sb_offset;
271 newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start;
273 // If we need to skip some data before decompressing the rest, or if the stream has looped
274 if (newlength < 0 || per_ch->sb_offset > real_start)
276 unsigned int time_start;
277 unsigned int modplug_start;
280 MODs loop on their own, so any position is valid!
281 if (real_start > (unsigned int)per_sfx->total_length)
283 Con_Printf ("ModPlug_FetchSound: asked for a start position after the end of the sfx! (%u > %u)\n",
284 real_start, per_sfx->total_length);
289 // We work with 200ms (1/5 sec) steps to avoid rounding errors
290 time_start = real_start * 5 / snd_renderbuffer->format.speed;
291 modplug_start = time_start * (1000 / 5);
293 Con_DPrintf("warning: mod file needed to seek (to %d)\n", modplug_start);
295 ModPlug_Seek(per_ch->mf, modplug_start);
298 real_start = (float)modplug_start / 1000 * snd_renderbuffer->format.speed;
299 if (*start - real_start + nbsampleframes > sb->maxframes)
301 Con_Printf ("ModPlug_FetchSound: stream buffer too small after seek (%u sample frames required)\n",
302 *start - real_start + nbsampleframes);
303 per_ch->sb_offset = real_start;
307 // Else, move forward the samples we need to keep in the sound buffer
310 memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor);
311 sb->nbframes = newlength;
314 per_ch->sb_offset = real_start;
316 // We add exactly 1 sec of sound to the buffer:
317 // 1- to ensure we won't lose any sample during the resampling process
318 // 2- to force one call to ModPlug_FetchSound per second to regulate the workload
319 if (sb->format.speed + sb->nbframes > sb->maxframes)
321 Con_Printf ("ModPlug_FetchSound: stream buffer overflow (%u sample frames / %u)\n",
322 sb->format.speed + sb->nbframes, sb->maxframes);
325 newlength = per_sfx->format.speed * factor; // -> 1 sec of sound before resampling
326 if(newlength > (int)sizeof(resampling_buffer))
327 newlength = sizeof(resampling_buffer);
329 // Decompress in the resampling_buffer
330 #if BYTE_ORDER == BIG_ENDIAN
336 while ((ret = ModPlug_Read (per_ch->mf, (char *)&resampling_buffer[done], (int)(newlength - done))) > 0)
340 // Argh. We didn't get as many samples as we wanted. Probably
341 // libmodplug forgot what mLoopCount==-1 means... basically, this means
342 // we can't loop like this. Try to let DP fix it later...
343 per_sfx->sfx->total_length = (real_start + ((size_t)done / (size_t)factor));
344 per_sfx->sfx->loopstart = 0;
346 if(newlength != done)
347 Con_DPrintf("ModPlug_Fetch: wanted: %d, got: %d\n", newlength, done);
350 Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
352 *start = per_ch->sb_offset;
362 static void ModPlug_FetchEnd (void *chfetcherdata)
364 modplug_stream_perchannel_t* per_ch = (modplug_stream_perchannel_t *)chfetcherdata;
368 // Free the modplug decoder
369 ModPlug_Unload (per_ch->mf);
381 static void ModPlug_FreeSfx (void *sfxfetcherdata)
383 modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfxfetcherdata;
385 // Free the modplug file
386 Mem_Free(per_sfx->file);
388 // Free the stream structure
398 static const snd_format_t* ModPlug_GetFormat (sfx_t* sfx)
400 modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfx->fetcher_data;
401 return &per_sfx->format;
404 static const snd_fetcher_t modplug_fetcher = { ModPlug_FetchSound, ModPlug_FetchEnd, ModPlug_FreeSfx, ModPlug_GetFormat };
409 ModPlug_LoadmodplugFile
411 Load an modplug file into memory
414 qboolean ModPlug_LoadModPlugFile (const char *filename, sfx_t *sfx)
417 fs_offset_t filesize;
419 modplug_stream_persfx_t* per_sfx;
426 if (sfx->fetcher != NULL)
430 data = FS_LoadFile (filename, snd_mempool, false, &filesize);
434 Con_DPrintf ("Loading ModPlug file \"%s\"\n", filename);
436 ModPlug_GetSettings(&s);
437 s.mFlags = MODPLUG_ENABLE_OVERSAMPLING | MODPLUG_ENABLE_NOISE_REDUCTION | MODPLUG_ENABLE_REVERB;
440 s.mFrequency = 44100;
441 s.mResamplingMode = MODPLUG_RESAMPLE_SPLINE;
443 ModPlug_SetSettings(&s);
445 // Open it with the modplugFile API
446 if (!(mf = ModPlug_Load (data, filesize)))
448 Con_Printf ("error while opening ModPlug file \"%s\"\n", filename);
453 Con_DPrintf ("\"%s\" will be streamed\n", filename);
454 per_sfx = (modplug_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
455 strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name));
456 sfx->memsize += sizeof (*per_sfx);
457 per_sfx->file = data;
458 per_sfx->filesize = filesize;
459 sfx->memsize += filesize;
461 per_sfx->format.speed = 44100; // modplug always works at that rate
462 per_sfx->format.width = 2; // We always work with 16 bits samples
463 per_sfx->format.channels = 2; // stereo rulez ;) (MAYBE default to mono because Amiga MODs sound better then?)
466 sfx->fetcher_data = per_sfx;
467 sfx->fetcher = &modplug_fetcher;
468 sfx->flags |= SFXFLAG_STREAMED;
469 sfx->total_length = 2147384647; // they always loop
470 sfx->loopstart = sfx->total_length; // modplug does it