]> icculus.org git repositories - divverent/darkplaces.git/blob - snd_modplug.c
don't parse \ characters when reading sav files or map entities, let the
[divverent/darkplaces.git] / snd_modplug.c
1 /*
2         Copyright (C) 2003-2005  Mathieu Olivier
3
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.
8
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.
12
13         See the GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21
22 */
23
24
25 #include "quakedef.h"
26 #include "snd_main.h"
27 #include "snd_modplug.h"
28
29 #ifdef SND_MODPLUG_STATIC
30
31 #include <libmodplug/modplug.h>
32 qboolean ModPlug_OpenLibrary (void)
33 {
34         return true; // statically linked
35 }
36 void ModPlug_CloseLibrary (void)
37 {
38 }
39 #define modplug_dll 1
40
41 #else
42 // BEGIN SECTION FROM modplug.h
43
44         /*
45          * This source code is public domain.
46          *
47          * Authors: Kenton Varda <temporal@gauge3d.org> (C interface wrapper)
48          */
49
50         enum _ModPlug_Flags
51         {
52                         MODPLUG_ENABLE_OVERSAMPLING     = 1 << 0,  /* Enable oversampling (*highly* recommended) */
53                         MODPLUG_ENABLE_NOISE_REDUCTION  = 1 << 1,  /* Enable noise reduction */
54                         MODPLUG_ENABLE_REVERB           = 1 << 2,  /* Enable reverb */
55                         MODPLUG_ENABLE_MEGABASS         = 1 << 3,  /* Enable megabass */
56                         MODPLUG_ENABLE_SURROUND         = 1 << 4   /* Enable surround sound. */
57         };
58
59         enum _ModPlug_ResamplingMode
60         {
61                         MODPLUG_RESAMPLE_NEAREST = 0,  /* No interpolation (very fast, extremely bad sound quality) */
62                         MODPLUG_RESAMPLE_LINEAR  = 1,  /* Linear interpolation (fast, good quality) */
63                         MODPLUG_RESAMPLE_SPLINE  = 2,  /* Cubic spline interpolation (high quality) */
64                         MODPLUG_RESAMPLE_FIR     = 3   /* 8-tap fir filter (extremely high quality) */
65         };
66
67         typedef struct _ModPlug_Settings
68         {
69                         int mFlags;  /* One or more of the MODPLUG_ENABLE_* flags above, bitwise-OR'ed */
70                         
71                         /* Note that ModPlug always decodes sound at 44100kHz, 32 bit, stereo and then
72                          * down-mixes to the settings you choose. */
73                         int mChannels;       /* Number of channels - 1 for mono or 2 for stereo */
74                         int mBits;           /* Bits per sample - 8, 16, or 32 */
75                         int mFrequency;      /* Sampling rate - 11025, 22050, or 44100 */
76                         int mResamplingMode; /* One of MODPLUG_RESAMPLE_*, above */
77                         
78                         int mReverbDepth;    /* Reverb level 0(quiet)-100(loud)      */
79                         int mReverbDelay;    /* Reverb delay in ms, usually 40-200ms */
80                         int mBassAmount;     /* XBass level 0(quiet)-100(loud)       */
81                         int mBassRange;      /* XBass cutoff in Hz 10-100            */
82                         int mSurroundDepth;  /* Surround level 0(quiet)-100(heavy)   */
83                         int mSurroundDelay;  /* Surround delay in ms, usually 5-40ms */
84                         int mLoopCount;      /* Number of times to loop.  Zero prevents looping.
85                                                                         -1 loops forever. */
86         } ModPlug_Settings;
87
88         struct _ModPlugFile;
89         typedef struct _ModPlugFile ModPlugFile;
90
91 // END SECTION FROM modplug.h
92
93 static ModPlugFile* (*ModPlug_Load) (const void* data, int size);
94 static void (*ModPlug_Unload) (ModPlugFile* file);
95 static int (*ModPlug_Read) (ModPlugFile* file, void* buffer, int size);
96 static void (*ModPlug_Seek) (ModPlugFile* file, int millisecond);
97 static void (*ModPlug_GetSettings) (ModPlug_Settings* settings);
98 static void (*ModPlug_SetSettings) (const ModPlug_Settings* settings);
99
100 static dllfunction_t modplugfuncs[] =
101 {
102         {"ModPlug_Load",                        (void **) &ModPlug_Load},
103         {"ModPlug_Unload",                      (void **) &ModPlug_Unload},
104         {"ModPlug_Read",                        (void **) &ModPlug_Read},
105         {"ModPlug_Seek",                        (void **) &ModPlug_Seek},
106         {"ModPlug_GetSettings",         (void **) &ModPlug_GetSettings},
107         {"ModPlug_SetSettings",         (void **) &ModPlug_SetSettings},
108         {NULL, NULL}
109 };
110
111 // Handles for the modplug and modplugfile DLLs
112 static dllhandle_t modplug_dll = NULL;
113
114 /*
115 =================================================================
116
117   DLL load & unload
118
119 =================================================================
120 */
121
122 /*
123 ====================
124 ModPlug_OpenLibrary
125
126 Try to load the modplugFile DLL
127 ====================
128 */
129 qboolean ModPlug_OpenLibrary (void)
130 {
131         const char* dllnames_modplug [] =
132         {
133 #if defined(WIN64)
134                 "libmodplug64.dll",
135 #elif defined(WIN32)
136                 "libmodplug-0.dll",
137                 "modplug.dll",
138 #elif defined(MACOSX)
139                 "libmodplug.dylib",
140 #else
141                 "libmodplug.so.0",
142                 "libmodplug.so",
143 #endif
144                 NULL
145         };
146
147         // Already loaded?
148         if (modplug_dll)
149                 return true;
150
151 // COMMANDLINEOPTION: Sound: -nomodplug disables modplug sound support
152         if (COM_CheckParm("-nomodplug"))
153                 return false;
154
155         // Load the DLLs
156         // We need to load both by hand because some OSes seem to not load
157         // the modplug DLL automatically when loading the modplugFile DLL
158         return Sys_LoadLibrary (dllnames_modplug, &modplug_dll, modplugfuncs);
159 }
160
161
162 /*
163 ====================
164 ModPlug_CloseLibrary
165
166 Unload the modplugFile DLL
167 ====================
168 */
169 void ModPlug_CloseLibrary (void)
170 {
171         Sys_UnloadLibrary (&modplug_dll);
172 }
173 #endif
174
175
176 /*
177 =================================================================
178
179         modplug decoding
180
181 =================================================================
182 */
183
184 #define STREAM_BUFFER_DURATION 1.5f     // 1.5 sec
185 #define STREAM_BUFFER_SIZE(format_ptr) ((int)(ceil (STREAM_BUFFER_DURATION * ((format_ptr)->speed * (format_ptr)->width * (format_ptr)->channels))))
186 // We work with 1 sec sequences, so this buffer must be able to contain
187 // 1 sec of sound of the highest quality (48 KHz, 16 bit samples, stereo)
188 static unsigned char resampling_buffer [48000 * 2 * 2];
189
190
191 // Per-sfx data structure
192 typedef struct
193 {
194         unsigned char   *file;
195         size_t                  filesize;
196         snd_format_t    format;
197         unsigned int    total_length;
198         char                    name[128];
199         sfx_t           *sfx;
200 } modplug_stream_persfx_t;
201
202 // Per-channel data structure
203 typedef struct
204 {
205         ModPlugFile     *mf;
206         unsigned int    sb_offset;
207         int                             bs;
208         snd_buffer_t    sb;             // must be at the end due to its dynamically allocated size
209 } modplug_stream_perchannel_t;
210
211
212 /*
213 ====================
214 ModPlug_FetchSound
215 ====================
216 */
217 static const snd_buffer_t* ModPlug_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes)
218 {
219         modplug_stream_perchannel_t* per_ch = (modplug_stream_perchannel_t *)*chfetcherpointer;
220         modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfxfetcher;
221         snd_buffer_t* sb;
222         int newlength, done, ret;
223         unsigned int real_start;
224         unsigned int factor;
225
226         // If there's no fetcher structure attached to the channel yet
227         if (per_ch == NULL)
228         {
229                 size_t buff_len, memsize;
230                 snd_format_t sb_format;
231
232                 sb_format.speed = snd_renderbuffer->format.speed;
233                 sb_format.width = per_sfx->format.width;
234                 sb_format.channels = per_sfx->format.channels;
235
236                 buff_len = STREAM_BUFFER_SIZE(&sb_format);
237                 memsize = sizeof (*per_ch) - sizeof (per_ch->sb.samples) + buff_len;
238                 per_ch = (modplug_stream_perchannel_t *)Mem_Alloc (snd_mempool, memsize);
239
240                 // Open it with the modplugFile API
241                 per_ch->mf = ModPlug_Load(per_sfx->file, per_sfx->filesize);
242                 if (!per_ch->mf)
243                 {
244                         Con_Printf("error while reading ModPlug stream \"%s\"\n", per_sfx->name);
245                         Mem_Free (per_ch);
246                         return NULL;
247                 }
248                 per_ch->bs = 0;
249
250                 per_ch->sb_offset = 0;
251                 per_ch->sb.format = sb_format;
252                 per_ch->sb.nbframes = 0;
253                 per_ch->sb.maxframes = buff_len / (per_ch->sb.format.channels * per_ch->sb.format.width);
254
255                 *chfetcherpointer = per_ch;
256         }
257
258         real_start = *start;
259
260         sb = &per_ch->sb;
261         factor = per_sfx->format.width * per_sfx->format.channels;
262
263         // If the stream buffer can't contain that much samples anyway
264         if (nbsampleframes > sb->maxframes)
265         {
266                 Con_Printf ("ModPlug_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes);
267                 return NULL;
268         }
269
270         // If the data we need has already been decompressed in the sfxbuffer, just return it
271         if (per_ch->sb_offset <= real_start && per_ch->sb_offset + sb->nbframes >= real_start + nbsampleframes)
272         {
273                 *start = per_ch->sb_offset;
274                 return sb;
275         }
276
277         newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start;
278
279         // If we need to skip some data before decompressing the rest, or if the stream has looped
280         if (newlength < 0 || per_ch->sb_offset > real_start)
281         {
282                 unsigned int time_start;
283                 unsigned int modplug_start;
284
285                 /*
286                 MODs loop on their own, so any position is valid!
287                 if (real_start > (unsigned int)per_sfx->total_length)
288                 {
289                         Con_Printf ("ModPlug_FetchSound: asked for a start position after the end of the sfx! (%u > %u)\n",
290                                                 real_start, per_sfx->total_length);
291                         return NULL;
292                 }
293                 */
294
295                 // We work with 200ms (1/5 sec) steps to avoid rounding errors
296                 time_start = real_start * 5 / snd_renderbuffer->format.speed;
297                 modplug_start = time_start * (1000 / 5);
298
299                 Con_DPrintf("warning: mod file needed to seek (to %d)\n", modplug_start);
300
301                 ModPlug_Seek(per_ch->mf, modplug_start);
302                 sb->nbframes = 0;
303
304                 real_start = (float)modplug_start / 1000 * snd_renderbuffer->format.speed;
305                 if (*start - real_start + nbsampleframes > sb->maxframes)
306                 {
307                         Con_Printf ("ModPlug_FetchSound: stream buffer too small after seek (%u sample frames required)\n",
308                                                 *start - real_start + nbsampleframes);
309                         per_ch->sb_offset = real_start;
310                         return NULL;
311                 }
312         }
313         // Else, move forward the samples we need to keep in the sound buffer
314         else
315         {
316                 memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor);
317                 sb->nbframes = newlength;
318         }
319
320         per_ch->sb_offset = real_start;
321
322         // We add exactly 1 sec of sound to the buffer:
323         // 1- to ensure we won't lose any sample during the resampling process
324         // 2- to force one call to ModPlug_FetchSound per second to regulate the workload
325         if (sb->format.speed + sb->nbframes > sb->maxframes)
326         {
327                 Con_Printf ("ModPlug_FetchSound: stream buffer overflow (%u sample frames / %u)\n",
328                                         sb->format.speed + sb->nbframes, sb->maxframes);
329                 return NULL;
330         }
331         newlength = per_sfx->format.speed * factor;  // -> 1 sec of sound before resampling
332         if(newlength > (int)sizeof(resampling_buffer))
333                 newlength = sizeof(resampling_buffer);
334
335         // Decompress in the resampling_buffer
336         done = 0;
337         while ((ret = ModPlug_Read (per_ch->mf, (char *)&resampling_buffer[done], (int)(newlength - done))) > 0)
338                 done += ret;
339         if(done < newlength)
340         {
341                 // Argh. We didn't get as many samples as we wanted. Probably
342                 // libmodplug forgot what mLoopCount==-1 means... basically, this means
343                 // we can't loop like this. Try to let DP fix it later...
344                 per_sfx->sfx->total_length = (real_start + ((size_t)done / (size_t)factor));
345                 per_sfx->sfx->loopstart = 0;
346
347                 if(newlength != done)
348                         Con_DPrintf("ModPlug_Fetch: wanted: %d, got: %d\n", newlength, done);
349         }
350
351         Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
352
353         *start = per_ch->sb_offset;
354         return sb;
355 }
356
357
358 /*
359 ====================
360 ModPlug_FetchEnd
361 ====================
362 */
363 static void ModPlug_FetchEnd (void *chfetcherdata)
364 {
365         modplug_stream_perchannel_t* per_ch = (modplug_stream_perchannel_t *)chfetcherdata;
366
367         if (per_ch != NULL)
368         {
369                 // Free the modplug decoder
370                 ModPlug_Unload (per_ch->mf);
371
372                 Mem_Free (per_ch);
373         }
374 }
375
376
377 /*
378 ====================
379 ModPlug_FreeSfx
380 ====================
381 */
382 static void ModPlug_FreeSfx (void *sfxfetcherdata)
383 {
384         modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfxfetcherdata;
385
386         // Free the modplug file
387         Mem_Free(per_sfx->file);
388
389         // Free the stream structure
390         Mem_Free(per_sfx);
391 }
392
393
394 /*
395 ====================
396 ModPlug_GetFormat
397 ====================
398 */
399 static const snd_format_t* ModPlug_GetFormat (sfx_t* sfx)
400 {
401         modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfx->fetcher_data;
402         return &per_sfx->format;
403 }
404
405 static const snd_fetcher_t modplug_fetcher = { ModPlug_FetchSound, ModPlug_FetchEnd, ModPlug_FreeSfx, ModPlug_GetFormat };
406
407
408 /*
409 ====================
410 ModPlug_LoadmodplugFile
411
412 Load an modplug file into memory
413 ====================
414 */
415 qboolean ModPlug_LoadModPlugFile (const char *filename, sfx_t *sfx)
416 {
417         unsigned char *data;
418         fs_offset_t filesize;
419         ModPlugFile *mf;
420         modplug_stream_persfx_t* per_sfx;
421         ModPlug_Settings s;
422
423         if (!modplug_dll)
424                 return false;
425
426         // Already loaded?
427         if (sfx->fetcher != NULL)
428                 return true;
429
430         // Load the file
431         data = FS_LoadFile (filename, snd_mempool, false, &filesize);
432         if (data == NULL)
433                 return false;
434
435         if (developer_loading.integer >= 2)
436                 Con_Printf ("Loading ModPlug file \"%s\"\n", filename);
437
438         ModPlug_GetSettings(&s);
439         s.mFlags = MODPLUG_ENABLE_OVERSAMPLING | MODPLUG_ENABLE_NOISE_REDUCTION | MODPLUG_ENABLE_REVERB;
440         s.mChannels = 2;
441         s.mBits = 16;
442         s.mFrequency = 44100;
443         s.mResamplingMode = MODPLUG_RESAMPLE_SPLINE;
444         s.mLoopCount = -1;
445         ModPlug_SetSettings(&s);
446
447         // Open it with the modplugFile API
448         if (!(mf = ModPlug_Load (data, filesize)))
449         {
450                 Con_Printf ("error while opening ModPlug file \"%s\"\n", filename);
451                 Mem_Free(data);
452                 return false;
453         }
454
455         if (developer_loading.integer >= 2)
456                 Con_Printf ("\"%s\" will be streamed\n", filename);
457         per_sfx = (modplug_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
458         strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name));
459         sfx->memsize += sizeof (*per_sfx);
460         per_sfx->file = data;
461         per_sfx->filesize = filesize;
462         sfx->memsize += filesize;
463
464         per_sfx->format.speed = 44100; // modplug always works at that rate
465         per_sfx->format.width = 2;  // We always work with 16 bits samples
466         per_sfx->format.channels = 2; // stereo rulez ;) (MAYBE default to mono because Amiga MODs sound better then?)
467         per_sfx->sfx = sfx;
468
469         sfx->fetcher_data = per_sfx;
470         sfx->fetcher = &modplug_fetcher;
471         sfx->flags |= SFXFLAG_STREAMED;
472         sfx->total_length = 2147384647; // they always loop
473         sfx->loopstart = sfx->total_length; // modplug does it
474
475         return true;
476 }