]> icculus.org git repositories - divverent/darkplaces.git/blob - snd_ogg.c
Ogg vorbis streaming support; the code decides whether it will cache or stream the...
[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         const dllfunction_t *func;
296
297         // Already loaded?
298         if (vf_dll)
299                 return true;
300
301 #ifdef WIN32
302         dllname = "vorbisfile.dll";
303 #else
304         dllname = "libvorbisfile.so";
305 #endif
306
307         // Initializations
308         for (func = oggvorbisfuncs; func && func->name != NULL; func++)
309                 *func->funcvariable = NULL;
310
311         // Load the DLL
312         if (! (vf_dll = Sys_LoadLibrary (dllname)))
313         {
314                 Con_DPrintf("Can't find %s. Ogg Vorbis support disabled\n", dllname);
315                 return false;
316         }
317
318         // Get the function adresses
319         for (func = oggvorbisfuncs; func && func->name != NULL; func++)
320                 if (!(*func->funcvariable = (void *) Sys_GetProcAddress (vf_dll, func->name)))
321                 {
322                         Con_Printf("missing function \"%s\" - broken Ogg Vorbis library!\n", func->name);
323                         OGG_CloseLibrary ();
324                         return false;
325                 }
326
327         Con_DPrintf("%s loaded. Ogg Vorbis support enabled\n", dllname);
328         return true;
329 }
330
331
332 /*
333 ====================
334 OGG_CloseLibrary
335
336 Unload the VorbisFile DLL
337 ====================
338 */
339 void OGG_CloseLibrary (void)
340 {
341         if (!vf_dll)
342                 return;
343
344         Sys_UnloadLibrary (vf_dll);
345         vf_dll = NULL;
346 }
347
348
349 /*
350 =================================================================
351
352         Ogg Vorbis decoding
353
354 =================================================================
355 */
356
357 #define STREAM_BUFFER_SIZE (128 * 1024)
358
359 // Note: it must be able to contain enough samples at 48 KHz (max speed)
360 //       to fill STREAM_BUFFER_SIZE bytes of samples at 8 KHz (min speed)
361 // TODO: dynamically allocate this buffer depending on the shm and min sound speeds
362 static qbyte resampling_buffer [STREAM_BUFFER_SIZE * (48000 / 8000)];
363
364
365 // Per-sfx data structure
366 typedef struct
367 {
368         qbyte   *file;
369         size_t  filesize;
370 } ogg_stream_persfx_t;
371
372 // Per-channel data structure
373 typedef struct
374 {
375         OggVorbis_File  vf;
376         ov_decode_t             ov_decode;
377         int                             bs;
378         snd_format_t    format;
379         sfxbuffer_t             sb;             // must be at the end due to its dynamically allocated size
380 } ogg_stream_perchannel_t;
381
382
383 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
384
385 /*
386 ====================
387 OGG_FetchSound
388 ====================
389 */
390 static const sfxbuffer_t* OGG_FetchSound (channel_t* ch, unsigned int start, unsigned int nbsamples)
391 {
392         ogg_stream_perchannel_t* per_ch;
393         sfxbuffer_t* sb;
394         int newlength, done, ret, bigendian;
395         unsigned int factor;
396
397         per_ch = ch->fetcher_data;
398
399         // If there's no fetcher structure attached to the channel yet
400         if (per_ch == NULL)
401         {
402                 sfx_t* sfx;
403                 vorbis_info *vi;
404                 ogg_stream_persfx_t* per_sfx;
405
406                 sfx = ch->sfx;
407                 per_ch = Mem_Alloc (sfx->mempool, sizeof (*per_ch) - sizeof (per_ch->sb.data) + STREAM_BUFFER_SIZE);
408                 per_sfx = sfx->fetcher_data;
409
410                 // Open it with the VorbisFile API
411                 per_ch->ov_decode.buffer = per_sfx->file;
412                 per_ch->ov_decode.ind = 0;
413                 per_ch->ov_decode.buffsize = per_sfx->filesize;
414                 if (qov_open_callbacks (&per_ch->ov_decode, &per_ch->vf, NULL, 0, callbacks) < 0)
415                 {
416                         Con_Printf("error while reading Ogg Vorbis stream \"%s\"\n", sfx->name);
417                         Mem_Free (per_ch);
418                         return NULL;
419                 }
420
421                 // Get the stream information
422                 vi = qov_info (&per_ch->vf, -1);
423                 per_ch->format.speed = vi->rate;
424                 per_ch->format.width = sfx->format.width;
425                 per_ch->format.channels = sfx->format.channels;
426                 
427                 per_ch->sb.offset = 0;
428                 per_ch->sb.length = 0;
429                 per_ch->bs = 0;
430
431                 ch->fetcher_data = per_ch;
432         }
433
434         sb = &per_ch->sb;
435
436         // If the data we need has already been decompressed in the sfxbuffer, just return it
437         if (sb->offset <= start && sb->offset + sb->length >= start + nbsamples)
438                 return sb;
439
440         newlength = sb->offset + sb->length - start;
441         factor = per_ch->format.width * per_ch->format.channels;
442
443         // If we need to skip some data before decompressing the rest, or if the stream has looped
444         if (newlength < 0 || sb->offset > start)
445         {
446                 if (qov_pcm_seek (&per_ch->vf, (ogg_int64_t)start) != 0)
447                         return NULL;
448
449                 sb->offset = start;
450                 sb->length = 0;
451                 newlength = 0;
452         }
453         // Else, move forward the samples we need to keep in the sfxbuffer
454         else
455         {
456                 memmove (sb->data, sb->data + (start - sb->offset) * factor, newlength * factor);
457                 sb->offset = start;
458                 sb->length = newlength;
459         }
460
461         // How many free bytes do we have in the sfxbuffer now?
462         newlength = STREAM_BUFFER_SIZE - (newlength * factor);
463
464         // Decompress in the resampling_buffer to get STREAM_BUFFER_SIZE samples after resampling
465 #if BYTE_ORDER == LITTLE_ENDIAN
466         bigendian = 0;
467 #else
468         bigendian = 1;
469 #endif
470         done = 0;
471         while ((ret = qov_read (&per_ch->vf, &resampling_buffer[done], (int)(newlength - done), bigendian, 2, 1, &per_ch->bs)) > 0)
472                 done += ret;
473
474         // Resample in the sfxbuffer
475         newlength = ResampleSfx (resampling_buffer, (size_t)done / factor, &per_ch->format, sb->data + sb->length * factor, ch->sfx->name);
476         sb->length += newlength;
477
478         return sb;
479 }
480
481
482 /*
483 ====================
484 OGG_FetchEnd
485 ====================
486 */
487 static void OGG_FetchEnd (channel_t* ch)
488 {
489         ogg_stream_perchannel_t* per_ch;
490
491         per_ch = ch->fetcher_data;
492         if (per_ch != NULL)
493         {
494                 // Free the ogg vorbis decoder
495                 qov_clear (&per_ch->vf);
496
497                 Mem_Free (per_ch);
498                 ch->fetcher_data = NULL;
499         }
500 }
501
502 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd };
503 extern snd_fetcher_t wav_fetcher;
504
505
506 /*
507 ====================
508 OGG_LoadVorbisFile
509
510 Load an Ogg Vorbis file into memory
511 ====================
512 */
513 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *s)
514 {
515         qbyte *data;
516         ov_decode_t ov_decode;
517         OggVorbis_File vf;
518         vorbis_info *vi;
519         ogg_int64_t len;
520
521         if (!vf_dll)
522                 return false;
523
524         Mem_FreePool (&s->mempool);
525         s->mempool = Mem_AllocPool (s->name);
526
527         // Load the file
528         data = FS_LoadFile (filename, s->mempool, false);
529         if (data == NULL)
530         {
531                 Mem_FreePool (&s->mempool);
532                 return false;
533         }
534
535         Con_DPrintf ("Loading Ogg Vorbis file \"%s\"\n", filename);
536
537         // Open it with the VorbisFile API
538         ov_decode.buffer = data;
539         ov_decode.ind = 0;
540         ov_decode.buffsize = fs_filesize;
541         if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
542         {
543                 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
544                 Mem_FreePool (&s->mempool);
545                 return false;
546         }
547
548         // Get the stream information
549         vi = qov_info (&vf, -1);
550         if (vi->channels < 1 || vi->channels > 2)
551         {
552                 Con_Printf("%s has an unsupported number of channels (%i)\n",
553                                         s->name, vi->channels);
554                 qov_clear (&vf);
555                 Mem_FreePool (&s->mempool);
556                 return false;
557         }
558
559         len = qov_pcm_total (&vf, -1) * vi->channels * 2;  // 16 bits => "* 2"
560
561         // Decide if we go for a stream or a simple PCM cache
562         if (snd_streaming.integer && len > fs_filesize + 3 * STREAM_BUFFER_SIZE)
563         {
564                 ogg_stream_persfx_t* per_sfx;
565
566                 Con_DPrintf ("\"%s\" will be streamed\n", filename);
567                 per_sfx = Mem_Alloc (s->mempool, sizeof (*per_sfx));
568                 per_sfx->file = data;
569                 per_sfx->filesize = fs_filesize;
570                 s->fetcher_data = per_sfx;
571                 s->fetcher = &ogg_fetcher;
572                 s->format.speed = shm->format.speed;
573                 s->format.width = 2;  // We always work with 16 bits samples
574                 s->format.channels = vi->channels;
575                 s->loopstart = -1;
576                 s->total_length = (size_t)len / (vi->channels * 2) * (float)(shm->format.speed / vi->rate);
577         }
578         else
579         {
580                 char *buff;
581                 ogg_int64_t done;
582                 int bs, bigendian;
583                 long ret;
584                 sfxbuffer_t *sb;
585
586                 Con_DPrintf ("\"%s\" will be streamed\n", filename);
587
588                 // Decode it
589                 buff = Mem_Alloc (s->mempool, (int)len);
590                 done = 0;
591                 bs = 0;
592 #if BYTE_ORDER == LITTLE_ENDIAN
593                 bigendian = 0;
594 #else
595                 bigendian = 1;
596 #endif
597                 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), bigendian, 2, 1, &bs)) > 0)
598                         done += ret;
599
600                 // Calculate resampled length
601                 len = (double)done * (double)shm->format.speed / (double)vi->rate;
602
603                 // Resample it
604                 sb = Mem_Alloc (s->mempool, (size_t)len + sizeof (*sb) - sizeof (sb->data));
605                 s->fetcher_data = sb;
606                 s->fetcher = &wav_fetcher;
607                 s->format.speed = vi->rate;
608                 s->format.width = 2;  // We always work with 16 bits samples
609                 s->format.channels = vi->channels;
610                 s->loopstart = -1;
611
612                 sb->length = ResampleSfx (buff, (size_t)done / (vi->channels * 2), &s->format, sb->data, s->name);
613                 s->format.speed = shm->format.speed;
614                 s->total_length = sb->length;
615                 sb->offset = 0;
616
617                 qov_clear (&vf);
618                 Mem_Free (data);
619                 Mem_Free (buff);
620         }
621
622         return true;
623 }