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