Factorized some code in the shared library loaders
[divverent/darkplaces.git] / snd_ogg.c
1 /*
2         Copyright (C) 2003-2004  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_ogg.h"
27
28
29 /*
30 =================================================================
31
32   Minimal set of definitions from the Ogg Vorbis lib
33   (C) COPYRIGHT 1994-2001 by the XIPHOPHORUS Company
34   http://www.xiph.org/
35
36   WARNING: for a matter of simplicity, several pointer types are
37   casted to "void*", and most enumerated values are not included
38
39 =================================================================
40 */
41
42 #ifdef _MSC_VER
43 typedef __int64 ogg_int64_t;
44 #else
45 typedef long long ogg_int64_t;
46 #endif
47
48 typedef struct
49 {
50         size_t  (*read_func)    (void *ptr, size_t size, size_t nmemb, void *datasource);
51         int             (*seek_func)    (void *datasource, ogg_int64_t offset, int whence);
52         int             (*close_func)   (void *datasource);
53         long    (*tell_func)    (void *datasource);
54 } ov_callbacks;
55
56 typedef struct
57 {
58         unsigned char   *data;
59         int                             storage;
60         int                             fill;
61         int                             returned;
62         int                             unsynced;
63         int                             headerbytes;
64         int                             bodybytes;
65 } ogg_sync_state;
66
67 typedef struct
68 {
69         int             version;
70         int             channels;
71         long    rate;
72         long    bitrate_upper;
73         long    bitrate_nominal;
74         long    bitrate_lower;
75         long    bitrate_window;
76         void    *codec_setup;
77 } vorbis_info;
78
79 typedef struct
80 {
81         unsigned char   *body_data;
82         long                    body_storage;
83         long                    body_fill;
84         long                    body_returned;
85         int                             *lacing_vals;
86         ogg_int64_t             *granule_vals;
87         long                    lacing_storage;
88         long                    lacing_fill;
89         long                    lacing_packet;
90         long                    lacing_returned;
91         unsigned char   header[282];
92         int                             header_fill;
93         int                             e_o_s;
94         int                             b_o_s;
95         long                    serialno;
96         long                    pageno;
97         ogg_int64_t             packetno;
98         ogg_int64_t             granulepos;
99 } ogg_stream_state;
100
101 typedef struct
102 {
103         int                     analysisp;
104         vorbis_info     *vi;
105         float           **pcm;
106         float           **pcmret;
107         int                     pcm_storage;
108         int                     pcm_current;
109         int                     pcm_returned;
110         int                     preextrapolate;
111         int                     eofflag;
112         long            lW;
113         long            W;
114         long            nW;
115         long            centerW;
116         ogg_int64_t     granulepos;
117         ogg_int64_t     sequence;
118         ogg_int64_t     glue_bits;
119         ogg_int64_t     time_bits;
120         ogg_int64_t     floor_bits;
121         ogg_int64_t     res_bits;
122         void            *backend_state;
123 } vorbis_dsp_state;
124
125 typedef struct
126 {
127         long                    endbyte;
128         int                             endbit;
129         unsigned char   *buffer;
130         unsigned char   *ptr;
131         long                    storage;
132 } oggpack_buffer;
133
134 typedef struct
135 {
136         float                           **pcm;
137         oggpack_buffer          opb;
138         long                            lW;
139         long                            W;
140         long                            nW;
141         int                                     pcmend;
142         int                                     mode;
143         int                                     eofflag;
144         ogg_int64_t                     granulepos;
145         ogg_int64_t                     sequence;
146         vorbis_dsp_state        *vd;
147         void                            *localstore;
148         long                            localtop;
149         long                            localalloc;
150         long                            totaluse;
151         void                            *reap;  // VOIDED POINTER
152         long                            glue_bits;
153         long                            time_bits;
154         long                            floor_bits;
155         long                            res_bits;
156         void                            *internal;
157 } vorbis_block;
158
159 typedef struct
160 {
161         void                            *datasource;
162         int                                     seekable;
163         ogg_int64_t                     offset;
164         ogg_int64_t                     end;
165         ogg_sync_state          oy;
166         int                                     links;
167         ogg_int64_t                     *offsets;
168         ogg_int64_t                     *dataoffsets;
169         long                            *serialnos;
170         ogg_int64_t                     *pcmlengths;
171         vorbis_info                     *vi;
172         void                            *vc;  // VOIDED POINTER
173         ogg_int64_t                     pcm_offset;
174         int                                     ready_state;
175         long                            current_serialno;
176         int                                     current_link;
177         double                          bittrack;
178         double                          samptrack;
179         ogg_stream_state        os;
180         vorbis_dsp_state        vd;
181         vorbis_block            vb;
182         ov_callbacks            callbacks;
183 } OggVorbis_File;
184
185
186 /*
187 =================================================================
188
189   DarkPlaces definitions
190
191 =================================================================
192 */
193
194 // Functions exported from the vorbisfile library
195 static int (*qov_clear) (OggVorbis_File *vf);
196 static vorbis_info* (*qov_info) (OggVorbis_File *vf,int link);
197 static int (*qov_open_callbacks) (void *datasource, OggVorbis_File *vf,
198                                                                   char *initial, long ibytes,
199                                                                   ov_callbacks callbacks);
200 static int (*qov_pcm_seek) (OggVorbis_File *vf,ogg_int64_t pos);
201 static ogg_int64_t (*qov_pcm_total) (OggVorbis_File *vf,int i);
202 static long (*qov_read) (OggVorbis_File *vf,char *buffer,int length,
203                                                  int bigendianp,int word,int sgned,int *bitstream);
204
205 static dllfunction_t oggvorbisfuncs[] =
206 {
207         {"ov_clear",                    (void **) &qov_clear},
208         {"ov_info",                             (void **) &qov_info},
209         {"ov_open_callbacks",   (void **) &qov_open_callbacks},
210         {"ov_pcm_seek",                 (void **) &qov_pcm_seek},
211         {"ov_pcm_total",                (void **) &qov_pcm_total},
212         {"ov_read",                             (void **) &qov_read},
213         {NULL, NULL}
214 };
215
216 // Handle for the Vorbisfile DLL
217 static dllhandle_t vf_dll = NULL;
218
219 typedef struct
220 {
221         qbyte *buffer;
222         ogg_int64_t ind, buffsize;
223 } ov_decode_t;
224
225
226 static size_t ovcb_read (void *ptr, size_t size, size_t nb, void *datasource)
227 {
228         ov_decode_t *ov_decode = (ov_decode_t*)datasource;
229         size_t remain, len;
230
231         remain = ov_decode->buffsize - ov_decode->ind;
232         len = size * nb;
233         if (remain < len)
234                 len = remain - remain % size;
235
236         memcpy (ptr, ov_decode->buffer + ov_decode->ind, len);
237         ov_decode->ind += len;
238
239         return len / size;
240 }
241
242 static int ovcb_seek (void *datasource, ogg_int64_t offset, int whence)
243 {
244         ov_decode_t *ov_decode = (ov_decode_t*)datasource;
245
246         switch (whence)
247         {
248                 case SEEK_SET:
249                         break;
250                 case SEEK_CUR:
251                         offset += ov_decode->ind;
252                         break;
253                 case SEEK_END:
254                         offset += ov_decode->buffsize;
255                         break;
256                 default:
257                         return -1;
258         }
259         if (offset < 0 || offset > ov_decode->buffsize)
260                 return -1;
261
262         ov_decode->ind = offset;
263         return 0;
264 }
265
266 static int ovcb_close (void *ov_decode)
267 {
268         return 0;
269 }
270
271 static long ovcb_tell (void *ov_decode)
272 {
273         return ((ov_decode_t*)ov_decode)->ind;
274 }
275
276
277 /*
278 =================================================================
279
280   DLL load & unload
281
282 =================================================================
283 */
284
285 /*
286 ====================
287 OGG_OpenLibrary
288
289 Try to load the VorbisFile DLL
290 ====================
291 */
292 qboolean OGG_OpenLibrary (void)
293 {
294         const char* dllname;
295
296         // Already loaded?
297         if (vf_dll)
298                 return true;
299
300 #ifdef WIN32
301         dllname = "vorbisfile.dll";
302 #else
303         dllname = "libvorbisfile.so";
304 #endif
305
306         // Load the DLL
307         if (! Sys_LoadLibrary (dllname, &vf_dll, oggvorbisfuncs))
308         {
309                 Con_Printf ("Ogg Vorbis support disabled\n");
310                 return false;
311         }
312
313         Con_Printf ("Ogg Vorbis support enabled\n");
314         return true;
315 }
316
317
318 /*
319 ====================
320 OGG_CloseLibrary
321
322 Unload the VorbisFile DLL
323 ====================
324 */
325 void OGG_CloseLibrary (void)
326 {
327         Sys_UnloadLibrary (&vf_dll);
328 }
329
330
331 /*
332 =================================================================
333
334         Ogg Vorbis decoding
335
336 =================================================================
337 */
338
339 #define STREAM_BUFFER_SIZE (128 * 1024)
340
341 // Note: it must be able to contain enough samples at 48 KHz (max speed)
342 //       to fill STREAM_BUFFER_SIZE bytes of samples at 8 KHz (min speed)
343 // TODO: dynamically allocate this buffer depending on the shm and min sound speeds
344 static qbyte resampling_buffer [STREAM_BUFFER_SIZE * (48000 / 8000)];
345
346
347 // Per-sfx data structure
348 typedef struct
349 {
350         qbyte   *file;
351         size_t  filesize;
352 } ogg_stream_persfx_t;
353
354 // Per-channel data structure
355 typedef struct
356 {
357         OggVorbis_File  vf;
358         ov_decode_t             ov_decode;
359         int                             bs;
360         snd_format_t    format;
361         sfxbuffer_t             sb;             // must be at the end due to its dynamically allocated size
362 } ogg_stream_perchannel_t;
363
364
365 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
366
367 /*
368 ====================
369 OGG_FetchSound
370 ====================
371 */
372 static const sfxbuffer_t* OGG_FetchSound (channel_t* ch, unsigned int start, unsigned int nbsamples)
373 {
374         ogg_stream_perchannel_t* per_ch;
375         sfxbuffer_t* sb;
376         int newlength, done, ret, bigendian;
377         unsigned int factor;
378
379         per_ch = ch->fetcher_data;
380
381         // If there's no fetcher structure attached to the channel yet
382         if (per_ch == NULL)
383         {
384                 sfx_t* sfx;
385                 vorbis_info *vi;
386                 ogg_stream_persfx_t* per_sfx;
387
388                 sfx = ch->sfx;
389                 per_ch = Mem_Alloc (sfx->mempool, sizeof (*per_ch) - sizeof (per_ch->sb.data) + STREAM_BUFFER_SIZE);
390                 per_sfx = sfx->fetcher_data;
391
392                 // Open it with the VorbisFile API
393                 per_ch->ov_decode.buffer = per_sfx->file;
394                 per_ch->ov_decode.ind = 0;
395                 per_ch->ov_decode.buffsize = per_sfx->filesize;
396                 if (qov_open_callbacks (&per_ch->ov_decode, &per_ch->vf, NULL, 0, callbacks) < 0)
397                 {
398                         Con_Printf("error while reading Ogg Vorbis stream \"%s\"\n", sfx->name);
399                         Mem_Free (per_ch);
400                         return NULL;
401                 }
402
403                 // Get the stream information
404                 vi = qov_info (&per_ch->vf, -1);
405                 per_ch->format.speed = vi->rate;
406                 per_ch->format.width = sfx->format.width;
407                 per_ch->format.channels = sfx->format.channels;
408                 
409                 per_ch->sb.offset = 0;
410                 per_ch->sb.length = 0;
411                 per_ch->bs = 0;
412
413                 ch->fetcher_data = per_ch;
414         }
415
416         sb = &per_ch->sb;
417
418         // If the data we need has already been decompressed in the sfxbuffer, just return it
419         if (sb->offset <= start && sb->offset + sb->length >= start + nbsamples)
420                 return sb;
421
422         newlength = sb->offset + sb->length - start;
423         factor = per_ch->format.width * per_ch->format.channels;
424
425         // If we need to skip some data before decompressing the rest, or if the stream has looped
426         if (newlength < 0 || sb->offset > start)
427         {
428                 if (qov_pcm_seek (&per_ch->vf, (ogg_int64_t)start) != 0)
429                         return NULL;
430
431                 sb->offset = start;
432                 sb->length = 0;
433                 newlength = 0;
434         }
435         // Else, move forward the samples we need to keep in the sfxbuffer
436         else
437         {
438                 memmove (sb->data, sb->data + (start - sb->offset) * factor, newlength * factor);
439                 sb->offset = start;
440                 sb->length = newlength;
441         }
442
443         // How many free bytes do we have in the sfxbuffer now?
444         newlength = STREAM_BUFFER_SIZE - (newlength * factor);
445
446         // Decompress in the resampling_buffer to get STREAM_BUFFER_SIZE samples after resampling
447 #if BYTE_ORDER == LITTLE_ENDIAN
448         bigendian = 0;
449 #else
450         bigendian = 1;
451 #endif
452         done = 0;
453         while ((ret = qov_read (&per_ch->vf, &resampling_buffer[done], (int)(newlength - done), bigendian, 2, 1, &per_ch->bs)) > 0)
454                 done += ret;
455
456         // Resample in the sfxbuffer
457         newlength = ResampleSfx (resampling_buffer, (size_t)done / factor, &per_ch->format, sb->data + sb->length * factor, ch->sfx->name);
458         sb->length += newlength;
459
460         return sb;
461 }
462
463
464 /*
465 ====================
466 OGG_FetchEnd
467 ====================
468 */
469 static void OGG_FetchEnd (channel_t* ch)
470 {
471         ogg_stream_perchannel_t* per_ch;
472
473         per_ch = ch->fetcher_data;
474         if (per_ch != NULL)
475         {
476                 // Free the ogg vorbis decoder
477                 qov_clear (&per_ch->vf);
478
479                 Mem_Free (per_ch);
480                 ch->fetcher_data = NULL;
481         }
482 }
483
484 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd };
485 extern snd_fetcher_t wav_fetcher;
486
487
488 /*
489 ====================
490 OGG_LoadVorbisFile
491
492 Load an Ogg Vorbis file into memory
493 ====================
494 */
495 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *s)
496 {
497         qbyte *data;
498         ov_decode_t ov_decode;
499         OggVorbis_File vf;
500         vorbis_info *vi;
501         ogg_int64_t len;
502
503         if (!vf_dll)
504                 return false;
505
506         Mem_FreePool (&s->mempool);
507         s->mempool = Mem_AllocPool (s->name);
508
509         // Load the file
510         data = FS_LoadFile (filename, s->mempool, false);
511         if (data == NULL)
512         {
513                 Mem_FreePool (&s->mempool);
514                 return false;
515         }
516
517         Con_DPrintf ("Loading Ogg Vorbis file \"%s\"\n", filename);
518
519         // Open it with the VorbisFile API
520         ov_decode.buffer = data;
521         ov_decode.ind = 0;
522         ov_decode.buffsize = fs_filesize;
523         if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
524         {
525                 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
526                 Mem_FreePool (&s->mempool);
527                 return false;
528         }
529
530         // Get the stream information
531         vi = qov_info (&vf, -1);
532         if (vi->channels < 1 || vi->channels > 2)
533         {
534                 Con_Printf("%s has an unsupported number of channels (%i)\n",
535                                         s->name, vi->channels);
536                 qov_clear (&vf);
537                 Mem_FreePool (&s->mempool);
538                 return false;
539         }
540
541         len = qov_pcm_total (&vf, -1) * vi->channels * 2;  // 16 bits => "* 2"
542
543         // Decide if we go for a stream or a simple PCM cache
544         if (snd_streaming.integer && len > fs_filesize + 3 * STREAM_BUFFER_SIZE)
545         {
546                 ogg_stream_persfx_t* per_sfx;
547
548                 Con_DPrintf ("\"%s\" will be streamed\n", filename);
549                 per_sfx = Mem_Alloc (s->mempool, sizeof (*per_sfx));
550                 per_sfx->file = data;
551                 per_sfx->filesize = fs_filesize;
552                 s->fetcher_data = per_sfx;
553                 s->fetcher = &ogg_fetcher;
554                 s->format.speed = shm->format.speed;
555                 s->format.width = 2;  // We always work with 16 bits samples
556                 s->format.channels = vi->channels;
557                 s->loopstart = -1;
558                 s->total_length = (size_t)len / (vi->channels * 2) * (float)(shm->format.speed / vi->rate);
559         }
560         else
561         {
562                 char *buff;
563                 ogg_int64_t done;
564                 int bs, bigendian;
565                 long ret;
566                 sfxbuffer_t *sb;
567
568                 Con_DPrintf ("\"%s\" will be streamed\n", filename);
569
570                 // Decode it
571                 buff = Mem_Alloc (s->mempool, (int)len);
572                 done = 0;
573                 bs = 0;
574 #if BYTE_ORDER == LITTLE_ENDIAN
575                 bigendian = 0;
576 #else
577                 bigendian = 1;
578 #endif
579                 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), bigendian, 2, 1, &bs)) > 0)
580                         done += ret;
581
582                 // Calculate resampled length
583                 len = (double)done * (double)shm->format.speed / (double)vi->rate;
584
585                 // Resample it
586                 sb = Mem_Alloc (s->mempool, (size_t)len + sizeof (*sb) - sizeof (sb->data));
587                 s->fetcher_data = sb;
588                 s->fetcher = &wav_fetcher;
589                 s->format.speed = vi->rate;
590                 s->format.width = 2;  // We always work with 16 bits samples
591                 s->format.channels = vi->channels;
592                 s->loopstart = -1;
593
594                 sb->length = ResampleSfx (buff, (size_t)done / (vi->channels * 2), &s->format, sb->data, s->name);
595                 s->format.speed = shm->format.speed;
596                 s->total_length = sb->length;
597                 sb->offset = 0;
598
599                 qov_clear (&vf);
600                 Mem_Free (data);
601                 Mem_Free (buff);
602         }
603
604         return true;
605 }