]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_modplug.c
disable depthfirst rendering on animated models since it doesn't work and should...
[xonotic/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 #define qModPlug_Load ModPlug_Load
41 #define qModPlug_Unload ModPlug_Unload
42 #define qModPlug_Read ModPlug_Read
43 #define qModPlug_Seek ModPlug_Seek
44 #define qModPlug_GetSettings ModPlug_GetSettings
45 #define qModPlug_SetSettings ModPlug_SetSettings
46 #define qModPlug_SetMasterVolume ModPlug_SetMasterVolume
47
48 #else
49 // BEGIN SECTION FROM modplug.h
50
51         /*
52          * This source code is public domain.
53          *
54          * Authors: Kenton Varda <temporal@gauge3d.org> (C interface wrapper)
55          */
56
57         enum _ModPlug_Flags
58         {
59                         MODPLUG_ENABLE_OVERSAMPLING     = 1 << 0,  /* Enable oversampling (*highly* recommended) */
60                         MODPLUG_ENABLE_NOISE_REDUCTION  = 1 << 1,  /* Enable noise reduction */
61                         MODPLUG_ENABLE_REVERB           = 1 << 2,  /* Enable reverb */
62                         MODPLUG_ENABLE_MEGABASS         = 1 << 3,  /* Enable megabass */
63                         MODPLUG_ENABLE_SURROUND         = 1 << 4   /* Enable surround sound. */
64         };
65
66         enum _ModPlug_ResamplingMode
67         {
68                         MODPLUG_RESAMPLE_NEAREST = 0,  /* No interpolation (very fast, extremely bad sound quality) */
69                         MODPLUG_RESAMPLE_LINEAR  = 1,  /* Linear interpolation (fast, good quality) */
70                         MODPLUG_RESAMPLE_SPLINE  = 2,  /* Cubic spline interpolation (high quality) */
71                         MODPLUG_RESAMPLE_FIR     = 3   /* 8-tap fir filter (extremely high quality) */
72         };
73
74         typedef struct _ModPlug_Settings
75         {
76                         int mFlags;  /* One or more of the MODPLUG_ENABLE_* flags above, bitwise-OR'ed */
77                         
78                         /* Note that ModPlug always decodes sound at 44100kHz, 32 bit, stereo and then
79                          * down-mixes to the settings you choose. */
80                         int mChannels;       /* Number of channels - 1 for mono or 2 for stereo */
81                         int mBits;           /* Bits per sample - 8, 16, or 32 */
82                         int mFrequency;      /* Sampling rate - 11025, 22050, or 44100 */
83                         int mResamplingMode; /* One of MODPLUG_RESAMPLE_*, above */
84
85                         int mStereoSeparation; /* Stereo separation, 1 - 256 */
86                         int mMaxMixChannels; /* Maximum number of mixing channels (polyphony), 32 - 256 */
87                         
88                         int mReverbDepth;    /* Reverb level 0(quiet)-100(loud)      */
89                         int mReverbDelay;    /* Reverb delay in ms, usually 40-200ms */
90                         int mBassAmount;     /* XBass level 0(quiet)-100(loud)       */
91                         int mBassRange;      /* XBass cutoff in Hz 10-100            */
92                         int mSurroundDepth;  /* Surround level 0(quiet)-100(heavy)   */
93                         int mSurroundDelay;  /* Surround delay in ms, usually 5-40ms */
94                         int mLoopCount;      /* Number of times to loop.  Zero prevents looping.
95                                                                         -1 loops forever. */
96         } ModPlug_Settings;
97
98         struct _ModPlugFile;
99         typedef struct _ModPlugFile ModPlugFile;
100
101 // END SECTION FROM modplug.h
102
103 static ModPlugFile* (*qModPlug_Load) (const void* data, int size);
104 static void (*qModPlug_Unload) (ModPlugFile* file);
105 static int (*qModPlug_Read) (ModPlugFile* file, void* buffer, int size);
106 static void (*qModPlug_Seek) (ModPlugFile* file, int millisecond);
107 static void (*qModPlug_GetSettings) (ModPlug_Settings* settings);
108 static void (*qModPlug_SetSettings) (const ModPlug_Settings* settings);
109 typedef void (ModPlug_SetMasterVolume_t) (ModPlugFile* file,unsigned int cvol) ;
110 ModPlug_SetMasterVolume_t *qModPlug_SetMasterVolume;
111
112
113 static dllfunction_t modplugfuncs[] =
114 {
115         {"ModPlug_Load",                        (void **) &qModPlug_Load},
116         {"ModPlug_Unload",                      (void **) &qModPlug_Unload},
117         {"ModPlug_Read",                        (void **) &qModPlug_Read},
118         {"ModPlug_Seek",                        (void **) &qModPlug_Seek},
119         {"ModPlug_GetSettings",         (void **) &qModPlug_GetSettings},
120         {"ModPlug_SetSettings",         (void **) &qModPlug_SetSettings},
121         {NULL, NULL}
122 };
123
124 // Handles for the modplug and modplugfile DLLs
125 static dllhandle_t modplug_dll = NULL;
126
127 /*
128 =================================================================
129
130   DLL load & unload
131
132 =================================================================
133 */
134
135 /*
136 ====================
137 ModPlug_OpenLibrary
138
139 Try to load the modplugFile DLL
140 ====================
141 */
142 qboolean ModPlug_OpenLibrary (void)
143 {
144         const char* dllnames_modplug [] =
145         {
146 #if defined(WIN32)
147                 "libmodplug-1.dll",
148                 "modplug.dll",
149 #elif defined(MACOSX)
150                 "libmodplug.dylib",
151 #else
152                 "libmodplug.so.1",
153                 "libmodplug.so",
154 #endif
155                 NULL
156         };
157
158         // Already loaded?
159         if (modplug_dll)
160                 return true;
161
162 // COMMANDLINEOPTION: Sound: -nomodplug disables modplug sound support
163         if (COM_CheckParm("-nomodplug"))
164                 return false;
165
166         // Load the DLLs
167         // We need to load both by hand because some OSes seem to not load
168         // the modplug DLL automatically when loading the modplugFile DLL
169         if(Sys_LoadLibrary (dllnames_modplug, &modplug_dll, modplugfuncs))
170         {
171                 qModPlug_SetMasterVolume = (ModPlug_SetMasterVolume_t *) Sys_GetProcAddress(modplug_dll, "ModPlug_SetMasterVolume");
172                 if(!qModPlug_SetMasterVolume)
173                         Con_Print("Warning: modplug volume control not supported. Try getting a newer version of libmodplug.\n");
174                 return true;
175         }
176         else
177                 return false;
178 }
179
180
181 /*
182 ====================
183 ModPlug_CloseLibrary
184
185 Unload the modplugFile DLL
186 ====================
187 */
188 void ModPlug_CloseLibrary (void)
189 {
190         Sys_UnloadLibrary (&modplug_dll);
191 }
192 #endif
193
194
195 /*
196 =================================================================
197
198         modplug decoding
199
200 =================================================================
201 */
202
203 // Per-sfx data structure
204 typedef struct
205 {
206         unsigned char   *file;
207         size_t                  filesize;
208 } modplug_stream_persfx_t;
209
210 // Per-channel data structure
211 typedef struct
212 {
213         ModPlugFile     *mf;
214         int                             bs;
215         int                             buffer_firstframe;
216         int                             buffer_numframes;
217         unsigned char   buffer[STREAM_BUFFERSIZE*4];
218 } modplug_stream_perchannel_t;
219
220
221 /*
222 ====================
223 ModPlug_GetSamplesFloat
224 ====================
225 */
226 static void ModPlug_GetSamplesFloat(channel_t *ch, sfx_t *sfx, int firstsampleframe, int numsampleframes, float *outsamplesfloat)
227 {
228         modplug_stream_perchannel_t* per_ch = (modplug_stream_perchannel_t *)ch->fetcher_data;
229         modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfx->fetcher_data;
230         int newlength, done, ret;
231         int f = sfx->format.width * sfx->format.channels; // bytes per frame
232         short *buf;
233         int i, len;
234
235         // If there's no fetcher structure attached to the channel yet
236         if (per_ch == NULL)
237         {
238                 per_ch = (modplug_stream_perchannel_t *)Mem_Alloc(snd_mempool, sizeof(*per_ch));
239
240                 // Open it with the modplugFile API
241                 per_ch->mf = qModPlug_Load(per_sfx->file, per_sfx->filesize);
242                 if (!per_ch->mf)
243                 {
244                         // we can't call Con_Printf here, not thread safe
245 //                      Con_Printf("error while reading ModPlug stream \"%s\"\n", per_sfx->name);
246                         Mem_Free(per_ch);
247                         return;
248                 }
249
250 #ifndef SND_MODPLUG_STATIC
251                 if(qModPlug_SetMasterVolume)
252 #endif
253                         qModPlug_SetMasterVolume(per_ch->mf, 512); // max volume, DP scales down!
254
255                 per_ch->bs = 0;
256
257                 per_ch->buffer_firstframe = 0;
258                 per_ch->buffer_numframes = 0;
259                 ch->fetcher_data = per_ch;
260         }
261
262         // if the request is too large for our buffer, loop...
263         while (numsampleframes * f > (int)sizeof(per_ch->buffer))
264         {
265                 done = sizeof(per_ch->buffer) / f;
266                 ModPlug_GetSamplesFloat(ch, sfx, firstsampleframe, done, outsamplesfloat);
267                 firstsampleframe += done;
268                 numsampleframes -= done;
269                 outsamplesfloat += done * sfx->format.channels;
270         }
271
272         // seek if the request is before the current buffer (loop back)
273         // seek if the request starts beyond the current buffer by at least one frame (channel was zero volume for a while)
274         // do not seek if the request overlaps the buffer end at all (expected behavior)
275         if (per_ch->buffer_firstframe > firstsampleframe || per_ch->buffer_firstframe + per_ch->buffer_numframes < firstsampleframe)
276         {
277                 // we expect to decode forward from here so this will be our new buffer start
278                 per_ch->buffer_firstframe = firstsampleframe;
279                 per_ch->buffer_numframes = 0;
280                 // we don't actually seek - we don't care much about timing on silent mod music streams and looping never happens
281                 //qModPlug_Seek(per_ch->mf, firstsampleframe * 1000.0 / sfx->format.speed);
282         }
283
284         // decompress the file as needed
285         if (firstsampleframe + numsampleframes > per_ch->buffer_firstframe + per_ch->buffer_numframes)
286         {
287                 // first slide the buffer back, discarding any data preceding the range we care about
288                 int offset = firstsampleframe - per_ch->buffer_firstframe;
289                 int keeplength = per_ch->buffer_numframes - offset;
290                 if (keeplength > 0)
291                         memmove(per_ch->buffer, per_ch->buffer + offset * sfx->format.width * sfx->format.channels, keeplength * sfx->format.width * sfx->format.channels);
292                 per_ch->buffer_firstframe = firstsampleframe;
293                 per_ch->buffer_numframes -= offset;
294                 // decompress as much as we can fit in the buffer
295                 newlength = sizeof(per_ch->buffer) - per_ch->buffer_numframes * f;
296                 done = 0;
297                 while (newlength > done && (ret = qModPlug_Read(per_ch->mf, (void *)((unsigned char *)per_ch->buffer + done), (int)(newlength - done))) > 0)
298                         done += ret;
299                 // clear the missing space if any
300                 if (done < newlength)
301                 {
302                         memset(per_ch->buffer + done, 0, newlength - done);
303                         // Argh. We didn't get as many samples as we wanted. Probably
304                         // libmodplug forgot what mLoopCount==-1 means... basically, this means
305                         // we can't loop like this. Try to let DP fix it later...
306                         sfx->total_length = firstsampleframe + done / f;
307                         sfx->loopstart = 0;
308                         // can't Con_Printf from this thread
309                         //if (newlength != done)
310                         //      Con_DPrintf("ModPlug_Fetch: wanted: %d, got: %d\n", newlength, done);
311                 }
312                 // we now have more data in the buffer
313                 per_ch->buffer_numframes += done / f;
314         }
315
316         // convert the sample format for the caller
317         buf = (short *)(per_ch->buffer + (firstsampleframe - per_ch->buffer_firstframe) * f);
318         len = numsampleframes * sfx->format.channels;
319         for (i = 0;i < len;i++)
320                 outsamplesfloat[i] = buf[i] * (1.0f / 32768.0f);
321 }
322
323
324 /*
325 ====================
326 ModPlug_StopChannel
327 ====================
328 */
329 static void ModPlug_StopChannel(channel_t *ch)
330 {
331         modplug_stream_perchannel_t *per_ch = (modplug_stream_perchannel_t *)ch->fetcher_data;
332
333         if (per_ch != NULL)
334         {
335                 // Free the modplug decoder
336                 qModPlug_Unload(per_ch->mf);
337
338                 Mem_Free(per_ch);
339         }
340 }
341
342
343 /*
344 ====================
345 ModPlug_FreeSfx
346 ====================
347 */
348 static void ModPlug_FreeSfx (sfx_t *sfx)
349 {
350         modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfx->fetcher_data;
351
352         // Free the modplug file
353         Mem_Free(per_sfx->file);
354
355         // Free the stream structure
356         Mem_Free(per_sfx);
357 }
358
359
360 static const snd_fetcher_t modplug_fetcher = { ModPlug_GetSamplesFloat, ModPlug_StopChannel, ModPlug_FreeSfx };
361
362
363 /*
364 ====================
365 ModPlug_LoadmodplugFile
366
367 Load an modplug file into memory
368 ====================
369 */
370 qboolean ModPlug_LoadModPlugFile (const char *filename, sfx_t *sfx)
371 {
372         unsigned char *data;
373         fs_offset_t filesize;
374         ModPlugFile *mf;
375         modplug_stream_persfx_t* per_sfx;
376         ModPlug_Settings s;
377
378         if (!modplug_dll)
379                 return false;
380
381         // Already loaded?
382         if (sfx->fetcher != NULL)
383                 return true;
384
385         // Load the file
386         data = FS_LoadFile (filename, snd_mempool, false, &filesize);
387         if (data == NULL)
388                 return false;
389
390         if (developer_loading.integer >= 2)
391                 Con_Printf ("Loading ModPlug file \"%s\"\n", filename);
392
393         qModPlug_GetSettings(&s);
394         s.mFlags = MODPLUG_ENABLE_OVERSAMPLING | MODPLUG_ENABLE_NOISE_REDUCTION | MODPLUG_ENABLE_REVERB;
395         s.mChannels = 2;
396         s.mBits = 16;
397         s.mFrequency = 44100;
398         s.mResamplingMode = MODPLUG_RESAMPLE_SPLINE;
399         s.mLoopCount = -1;
400         qModPlug_SetSettings(&s);
401
402         // Open it with the modplugFile API
403         if (!(mf = qModPlug_Load (data, filesize)))
404         {
405                 Con_Printf ("error while opening ModPlug file \"%s\"\n", filename);
406                 Mem_Free(data);
407                 return false;
408         }
409
410 #ifndef SND_MODPLUG_STATIC
411         if(qModPlug_SetMasterVolume)
412 #endif
413                 qModPlug_SetMasterVolume(mf, 512); // max volume, DP scales down!
414
415         if (developer_loading.integer >= 2)
416                 Con_Printf ("\"%s\" will be streamed\n", filename);
417         per_sfx = (modplug_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
418         per_sfx->file = data;
419         per_sfx->filesize = filesize;
420         sfx->memsize += sizeof(*per_sfx);
421         sfx->memsize += filesize;
422         sfx->format.speed = 44100; // modplug always works at that rate
423         sfx->format.width = 2;  // We always work with 16 bits samples
424         sfx->format.channels = 2; // stereo rulez ;) (MAYBE default to mono because Amiga MODs sound better then?)
425         sfx->fetcher_data = per_sfx;
426         sfx->fetcher = &modplug_fetcher;
427         sfx->flags |= SFXFLAG_STREAMED;
428         sfx->total_length = 1<<30; // 2147384647; // they always loop (FIXME this breaks after 6 hours, we need support for a real "infinite" value!)
429         sfx->loopstart = sfx->total_length; // modplug does it
430
431         return true;
432 }