WarpZones:
[divverent/darkplaces.git] / snd_ogg.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_ogg.h"
28 #include "snd_wav.h"
29
30 #ifdef LINK_TO_LIBVORBIS
31 #define OV_EXCLUDE_STATIC_CALLBACKS
32 #include <ogg/ogg.h>
33 #include <vorbis/vorbisfile.h>
34
35 #define qov_clear ov_clear
36 #define qov_info ov_info
37 #define qov_comment ov_comment
38 #define qov_open_callbacks ov_open_callbacks
39 #define qov_pcm_seek ov_pcm_seek
40 #define qov_pcm_total ov_pcm_total
41 #define qov_read ov_read
42 #define qvorbis_comment_query vorbis_comment_query
43
44 qboolean OGG_OpenLibrary (void) {return true;}
45 void OGG_CloseLibrary (void) {}
46 #else
47
48 /*
49 =================================================================
50
51   Minimal set of definitions from the Ogg Vorbis lib
52   (C) COPYRIGHT 1994-2001 by the XIPHOPHORUS Company
53   http://www.xiph.org/
54
55   WARNING: for a matter of simplicity, several pointer types are
56   casted to "void*", and most enumerated values are not included
57
58 =================================================================
59 */
60
61 #ifdef _MSC_VER
62 typedef __int64 ogg_int64_t;
63 #else
64 typedef long long ogg_int64_t;
65 #endif
66
67 typedef struct
68 {
69         size_t  (*read_func)    (void *ptr, size_t size, size_t nmemb, void *datasource);
70         int             (*seek_func)    (void *datasource, ogg_int64_t offset, int whence);
71         int             (*close_func)   (void *datasource);
72         long    (*tell_func)    (void *datasource);
73 } ov_callbacks;
74
75 typedef struct
76 {
77         unsigned char   *data;
78         int                             storage;
79         int                             fill;
80         int                             returned;
81         int                             unsynced;
82         int                             headerbytes;
83         int                             bodybytes;
84 } ogg_sync_state;
85
86 typedef struct
87 {
88         int             version;
89         int             channels;
90         long    rate;
91         long    bitrate_upper;
92         long    bitrate_nominal;
93         long    bitrate_lower;
94         long    bitrate_window;
95         void    *codec_setup;
96 } vorbis_info;
97
98 typedef struct
99 {
100         unsigned char   *body_data;
101         long                    body_storage;
102         long                    body_fill;
103         long                    body_returned;
104         int                             *lacing_vals;
105         ogg_int64_t             *granule_vals;
106         long                    lacing_storage;
107         long                    lacing_fill;
108         long                    lacing_packet;
109         long                    lacing_returned;
110         unsigned char   header[282];
111         int                             header_fill;
112         int                             e_o_s;
113         int                             b_o_s;
114         long                    serialno;
115         long                    pageno;
116         ogg_int64_t             packetno;
117         ogg_int64_t             granulepos;
118 } ogg_stream_state;
119
120 typedef struct
121 {
122         int                     analysisp;
123         vorbis_info     *vi;
124         float           **pcm;
125         float           **pcmret;
126         int                     pcm_storage;
127         int                     pcm_current;
128         int                     pcm_returned;
129         int                     preextrapolate;
130         int                     eofflag;
131         long            lW;
132         long            W;
133         long            nW;
134         long            centerW;
135         ogg_int64_t     granulepos;
136         ogg_int64_t     sequence;
137         ogg_int64_t     glue_bits;
138         ogg_int64_t     time_bits;
139         ogg_int64_t     floor_bits;
140         ogg_int64_t     res_bits;
141         void            *backend_state;
142 } vorbis_dsp_state;
143
144 typedef struct
145 {
146         long                    endbyte;
147         int                             endbit;
148         unsigned char   *buffer;
149         unsigned char   *ptr;
150         long                    storage;
151 } oggpack_buffer;
152
153 typedef struct
154 {
155         float                           **pcm;
156         oggpack_buffer          opb;
157         long                            lW;
158         long                            W;
159         long                            nW;
160         int                                     pcmend;
161         int                                     mode;
162         int                                     eofflag;
163         ogg_int64_t                     granulepos;
164         ogg_int64_t                     sequence;
165         vorbis_dsp_state        *vd;
166         void                            *localstore;
167         long                            localtop;
168         long                            localalloc;
169         long                            totaluse;
170         void                            *reap;  // VOIDED POINTER
171         long                            glue_bits;
172         long                            time_bits;
173         long                            floor_bits;
174         long                            res_bits;
175         void                            *internal;
176 } vorbis_block;
177
178 typedef struct
179 {
180         char **user_comments;
181         int   *comment_lengths;
182         int    comments;
183         char  *vendor;
184 } vorbis_comment;
185
186 typedef struct
187 {
188         void                            *datasource;
189         int                                     seekable;
190         ogg_int64_t                     offset;
191         ogg_int64_t                     end;
192         ogg_sync_state          oy;
193         int                                     links;
194         ogg_int64_t                     *offsets;
195         ogg_int64_t                     *dataoffsets;
196         long                            *serialnos;
197         ogg_int64_t                     *pcmlengths;
198         vorbis_info                     *vi;
199         vorbis_comment          *vc;
200         ogg_int64_t                     pcm_offset;
201         int                                     ready_state;
202         long                            current_serialno;
203         int                                     current_link;
204         double                          bittrack;
205         double                          samptrack;
206         ogg_stream_state        os;
207         vorbis_dsp_state        vd;
208         vorbis_block            vb;
209         ov_callbacks            callbacks;
210 } OggVorbis_File;
211
212
213 /*
214 =================================================================
215
216   DarkPlaces definitions
217
218 =================================================================
219 */
220
221 // Functions exported from the vorbisfile library
222 static int (*qov_clear) (OggVorbis_File *vf);
223 static vorbis_info* (*qov_info) (OggVorbis_File *vf,int link);
224 static vorbis_comment* (*qov_comment) (OggVorbis_File *vf,int link);
225 static char * (*qvorbis_comment_query) (vorbis_comment *vc, char *tag, int count);
226 static int (*qov_open_callbacks) (void *datasource, OggVorbis_File *vf,
227                                                                   char *initial, long ibytes,
228                                                                   ov_callbacks callbacks);
229 static int (*qov_pcm_seek) (OggVorbis_File *vf,ogg_int64_t pos);
230 static ogg_int64_t (*qov_pcm_total) (OggVorbis_File *vf,int i);
231 static long (*qov_read) (OggVorbis_File *vf,char *buffer,int length,
232                                                  int bigendianp,int word,int sgned,int *bitstream);
233
234 static dllfunction_t vorbisfilefuncs[] =
235 {
236         {"ov_clear",                            (void **) &qov_clear},
237         {"ov_info",                                     (void **) &qov_info},
238         {"ov_comment",                          (void **) &qov_comment},
239         {"ov_open_callbacks",           (void **) &qov_open_callbacks},
240         {"ov_pcm_seek",                         (void **) &qov_pcm_seek},
241         {"ov_pcm_total",                        (void **) &qov_pcm_total},
242         {"ov_read",                                     (void **) &qov_read},
243         {NULL, NULL}
244 };
245
246 static dllfunction_t vorbisfuncs[] =
247 {
248         {"vorbis_comment_query",        (void **) &qvorbis_comment_query},
249         {NULL, NULL}
250 };
251
252 // Handles for the Vorbis and Vorbisfile DLLs
253 static dllhandle_t vo_dll = NULL;
254 static dllhandle_t vf_dll = NULL;
255
256
257 /*
258 =================================================================
259
260   DLL load & unload
261
262 =================================================================
263 */
264
265 /*
266 ====================
267 OGG_OpenLibrary
268
269 Try to load the VorbisFile DLL
270 ====================
271 */
272 qboolean OGG_OpenLibrary (void)
273 {
274         const char* dllnames_vo [] =
275         {
276 #if defined(WIN32)
277                 "libvorbis.dll",
278                 "vorbis.dll",
279 #elif defined(MACOSX)
280                 "libvorbis.dylib",
281 #else
282                 "libvorbis.so.0",
283                 "libvorbis.so",
284 #endif
285                 NULL
286         };
287         const char* dllnames_vf [] =
288         {
289 #if defined(WIN32)
290                 "libvorbisfile.dll",
291                 "vorbisfile.dll",
292 #elif defined(MACOSX)
293                 "libvorbisfile.dylib",
294 #else
295                 "libvorbisfile.so.3",
296                 "libvorbisfile.so",
297 #endif
298                 NULL
299         };
300
301         // Already loaded?
302         if (vf_dll)
303                 return true;
304
305 // COMMANDLINEOPTION: Sound: -novorbis disables ogg vorbis sound support
306         if (COM_CheckParm("-novorbis"))
307                 return false;
308
309         // Load the DLLs
310         // We need to load both by hand because some OSes seem to not load
311         // the vorbis DLL automatically when loading the VorbisFile DLL
312         return Sys_LoadLibrary (dllnames_vo, &vo_dll, vorbisfuncs) && Sys_LoadLibrary (dllnames_vf, &vf_dll, vorbisfilefuncs);
313 }
314
315
316 /*
317 ====================
318 OGG_CloseLibrary
319
320 Unload the VorbisFile DLL
321 ====================
322 */
323 void OGG_CloseLibrary (void)
324 {
325         Sys_UnloadLibrary (&vf_dll);
326         Sys_UnloadLibrary (&vo_dll);
327 }
328
329 #endif
330
331 /*
332 =================================================================
333
334         Ogg Vorbis decoding
335
336 =================================================================
337 */
338
339 typedef struct
340 {
341         unsigned char *buffer;
342         ogg_int64_t ind, buffsize;
343 } ov_decode_t;
344
345 static size_t ovcb_read (void *ptr, size_t size, size_t nb, void *datasource)
346 {
347         ov_decode_t *ov_decode = (ov_decode_t*)datasource;
348         size_t remain, len;
349
350         remain = ov_decode->buffsize - ov_decode->ind;
351         len = size * nb;
352         if (remain < len)
353                 len = remain - remain % size;
354
355         memcpy (ptr, ov_decode->buffer + ov_decode->ind, len);
356         ov_decode->ind += len;
357
358         return len / size;
359 }
360
361 static int ovcb_seek (void *datasource, ogg_int64_t offset, int whence)
362 {
363         ov_decode_t *ov_decode = (ov_decode_t*)datasource;
364
365         switch (whence)
366         {
367                 case SEEK_SET:
368                         break;
369                 case SEEK_CUR:
370                         offset += ov_decode->ind;
371                         break;
372                 case SEEK_END:
373                         offset += ov_decode->buffsize;
374                         break;
375                 default:
376                         return -1;
377         }
378         if (offset < 0 || offset > ov_decode->buffsize)
379                 return -1;
380
381         ov_decode->ind = offset;
382         return 0;
383 }
384
385 static int ovcb_close (void *ov_decode)
386 {
387         return 0;
388 }
389
390 static long ovcb_tell (void *ov_decode)
391 {
392         return ((ov_decode_t*)ov_decode)->ind;
393 }
394
395 // Per-sfx data structure
396 typedef struct
397 {
398         unsigned char   *file;
399         size_t                  filesize;
400         snd_format_t    format;
401         unsigned int    total_length;
402         char                    name[128];
403 } ogg_stream_persfx_t;
404
405 // Per-channel data structure
406 typedef struct
407 {
408         OggVorbis_File  vf;
409         ov_decode_t             ov_decode;
410         unsigned int    sb_offset;
411         int                             bs;
412         snd_buffer_t    sb;             // must be at the end due to its dynamically allocated size
413 } ogg_stream_perchannel_t;
414
415
416 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
417
418 /*
419 ====================
420 OGG_FetchSound
421 ====================
422 */
423 static const snd_buffer_t* OGG_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes)
424 {
425         ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)*chfetcherpointer;
426         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcher;
427         snd_buffer_t* sb;
428         int newlength, done, ret;
429         unsigned int real_start;
430         unsigned int factor;
431
432         // If there's no fetcher structure attached to the channel yet
433         if (per_ch == NULL)
434         {
435                 size_t buff_len, memsize;
436                 snd_format_t sb_format;
437
438                 sb_format.speed = snd_renderbuffer->format.speed;
439                 sb_format.width = per_sfx->format.width;
440                 sb_format.channels = per_sfx->format.channels;
441
442                 buff_len = STREAM_BUFFER_SIZE(&sb_format);
443                 memsize = sizeof (*per_ch) - sizeof (per_ch->sb.samples) + buff_len;
444                 per_ch = (ogg_stream_perchannel_t *)Mem_Alloc (snd_mempool, memsize);
445
446                 // Open it with the VorbisFile API
447                 per_ch->ov_decode.buffer = per_sfx->file;
448                 per_ch->ov_decode.ind = 0;
449                 per_ch->ov_decode.buffsize = per_sfx->filesize;
450                 if (qov_open_callbacks (&per_ch->ov_decode, &per_ch->vf, NULL, 0, callbacks) < 0)
451                 {
452                         Con_Printf("error while reading Ogg Vorbis stream \"%s\"\n", per_sfx->name);
453                         Mem_Free (per_ch);
454                         return NULL;
455                 }
456                 per_ch->bs = 0;
457
458                 per_ch->sb_offset = 0;
459                 per_ch->sb.format = sb_format;
460                 per_ch->sb.nbframes = 0;
461                 per_ch->sb.maxframes = buff_len / (per_ch->sb.format.channels * per_ch->sb.format.width);
462
463                 *chfetcherpointer = per_ch;
464         }
465
466         real_start = *start;
467
468         sb = &per_ch->sb;
469         factor = per_sfx->format.width * per_sfx->format.channels;
470
471         // If the stream buffer can't contain that much samples anyway
472         if (nbsampleframes > sb->maxframes)
473         {
474                 Con_Printf ("OGG_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes);
475                 return NULL;
476         }
477
478         // If the data we need has already been decompressed in the sfxbuffer, just return it
479         if (per_ch->sb_offset <= real_start && per_ch->sb_offset + sb->nbframes >= real_start + nbsampleframes)
480         {
481                 *start = per_ch->sb_offset;
482                 return sb;
483         }
484
485         newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start;
486
487         // If we need to skip some data before decompressing the rest, or if the stream has looped
488         if (newlength < 0 || per_ch->sb_offset > real_start)
489         {
490                 unsigned int time_start;
491                 ogg_int64_t ogg_start;
492                 int err;
493
494                 if (real_start > (unsigned int)per_sfx->total_length)
495                 {
496                         Con_Printf ("OGG_FetchSound: asked for a start position after the end of the sfx! (%u > %u)\n",
497                                                 real_start, per_sfx->total_length);
498                         return NULL;
499                 }
500
501                 // We work with 200ms (1/5 sec) steps to avoid rounding errors
502                 time_start = real_start * 5 / snd_renderbuffer->format.speed;
503                 ogg_start = time_start * (per_sfx->format.speed / 5);
504                 err = qov_pcm_seek (&per_ch->vf, ogg_start);
505                 if (err != 0)
506                 {
507                         Con_Printf ("OGG_FetchSound: qov_pcm_seek(..., %d) returned %d\n",
508                                                 real_start, err);
509                         return NULL;
510                 }
511                 sb->nbframes = 0;
512
513                 real_start = (unsigned int) ((float)ogg_start / per_sfx->format.speed * snd_renderbuffer->format.speed);
514                 if (*start - real_start + nbsampleframes > sb->maxframes)
515                 {
516                         Con_Printf ("OGG_FetchSound: stream buffer too small after seek (%u sample frames required)\n",
517                                                 *start - real_start + nbsampleframes);
518                         per_ch->sb_offset = real_start;
519                         return NULL;
520                 }
521         }
522         // Else, move forward the samples we need to keep in the sound buffer
523         else
524         {
525                 memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor);
526                 sb->nbframes = newlength;
527         }
528
529         per_ch->sb_offset = real_start;
530
531         // We add more than one frame of sound to the buffer:
532         // 1- to ensure we won't lose many samples during the resampling process
533         // 2- to reduce calls to OGG_FetchSound to regulate workload
534         newlength = (int)(per_sfx->format.speed*STREAM_BUFFER_FILL);
535         if (newlength + sb->nbframes > sb->maxframes)
536         {
537                 Con_Printf ("OGG_FetchSound: stream buffer overflow (%u sample frames / %u)\n",
538                                         sb->format.speed + sb->nbframes, sb->maxframes);
539                 return NULL;
540         }
541         newlength *= factor; // convert from sample frames to bytes
542         if(newlength > (int)sizeof(resampling_buffer))
543                 newlength = sizeof(resampling_buffer);
544
545         // Decompress in the resampling_buffer
546         done = 0;
547         while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), mem_bigendian, 2, 1, &per_ch->bs)) > 0)
548                 done += ret;
549
550         Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
551
552         *start = per_ch->sb_offset;
553         return sb;
554 }
555
556
557 /*
558 ====================
559 OGG_FetchEnd
560 ====================
561 */
562 static void OGG_FetchEnd (void *chfetcherdata)
563 {
564         ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)chfetcherdata;
565
566         if (per_ch != NULL)
567         {
568                 // Free the ogg vorbis decoder
569                 qov_clear (&per_ch->vf);
570
571                 Mem_Free (per_ch);
572         }
573 }
574
575
576 /*
577 ====================
578 OGG_FreeSfx
579 ====================
580 */
581 static void OGG_FreeSfx (void *sfxfetcherdata)
582 {
583         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcherdata;
584
585         // Free the Ogg Vorbis file
586         Mem_Free(per_sfx->file);
587
588         // Free the stream structure
589         Mem_Free(per_sfx);
590 }
591
592
593 /*
594 ====================
595 OGG_GetFormat
596 ====================
597 */
598 static const snd_format_t* OGG_GetFormat (sfx_t* sfx)
599 {
600         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
601         return &per_sfx->format;
602 }
603
604 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd, OGG_FreeSfx, OGG_GetFormat };
605
606 static void OGG_DecodeTags(vorbis_comment *vc, unsigned int *start, unsigned int *length, double samplesfactor, unsigned int numsamples, double *peak, double *gaindb)
607 {
608         const char *startcomment = NULL, *lengthcomment = NULL, *endcomment = NULL, *thiscomment = NULL;
609
610         *start = numsamples;
611         *length = numsamples;
612         *peak = 0.0;
613         *gaindb = 0.0;
614
615         if(!vc)
616                 return;
617
618         thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
619         if(thiscomment)
620                 *peak = atof(thiscomment);
621         thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
622         if(thiscomment)
623                 *gaindb = atof(thiscomment);
624         
625         startcomment = qvorbis_comment_query(vc, "LOOP_START", 0); // DarkPlaces, and some Japanese app
626         if(startcomment)
627         {
628                 endcomment = qvorbis_comment_query(vc, "LOOP_END", 0);
629                 if(!endcomment)
630                         lengthcomment = qvorbis_comment_query(vc, "LOOP_LENGTH", 0);
631         }
632         else
633         {
634                 startcomment = qvorbis_comment_query(vc, "LOOPSTART", 0); // RPG Maker VX
635                 if(startcomment)
636                 {
637                         lengthcomment = qvorbis_comment_query(vc, "LOOPLENGTH", 0);
638                         if(!lengthcomment)
639                                 endcomment = qvorbis_comment_query(vc, "LOOPEND", 0);
640                 }
641                 else
642                 {
643                         startcomment = qvorbis_comment_query(vc, "LOOPPOINT", 0); // Sonic Robo Blast 2
644                 }
645         }
646
647         if(startcomment)
648         {
649                 *start = (unsigned int) bound(0, atof(startcomment) * samplesfactor, numsamples);
650                 if(endcomment)
651                         *length = (unsigned int) bound(0, atof(endcomment) * samplesfactor, numsamples);
652                 else if(lengthcomment)
653                         *length = (unsigned int) bound(0, *start + atof(lengthcomment) * samplesfactor, numsamples);
654         }
655 }
656
657 /*
658 ====================
659 OGG_LoadVorbisFile
660
661 Load an Ogg Vorbis file into memory
662 ====================
663 */
664 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *sfx)
665 {
666         unsigned char *data;
667         fs_offset_t filesize;
668         ov_decode_t ov_decode;
669         OggVorbis_File vf;
670         vorbis_info *vi;
671         vorbis_comment *vc;
672         ogg_int64_t len, buff_len;
673         double peak, gaindb;
674
675 #ifndef LINK_TO_LIBVORBIS
676         if (!vf_dll)
677                 return false;
678 #endif
679
680         // Already loaded?
681         if (sfx->fetcher != NULL)
682                 return true;
683
684         // Load the file
685         data = FS_LoadFile (filename, snd_mempool, false, &filesize);
686         if (data == NULL)
687                 return false;
688
689         if (developer_loading.integer >= 2)
690                 Con_Printf ("Loading Ogg Vorbis file \"%s\"\n", filename);
691
692         // Open it with the VorbisFile API
693         ov_decode.buffer = data;
694         ov_decode.ind = 0;
695         ov_decode.buffsize = filesize;
696         if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
697         {
698                 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
699                 Mem_Free(data);
700                 return false;
701         }
702
703         // Get the stream information
704         vi = qov_info (&vf, -1);
705         if (vi->channels < 1 || vi->channels > 2)
706         {
707                 Con_Printf("%s has an unsupported number of channels (%i)\n",
708                                         sfx->name, vi->channels);
709                 qov_clear (&vf);
710                 Mem_Free(data);
711                 return false;
712         }
713
714         len = qov_pcm_total (&vf, -1) * vi->channels * 2;  // 16 bits => "* 2"
715
716         // Decide if we go for a stream or a simple PCM cache
717         buff_len = (int)ceil (STREAM_BUFFER_DURATION * snd_renderbuffer->format.speed) * 2 * vi->channels;
718         if (snd_streaming.integer && (len > (ogg_int64_t)filesize + 3 * buff_len || snd_streaming.integer >= 2))
719         {
720                 ogg_stream_persfx_t* per_sfx;
721
722                 if (developer_loading.integer >= 2)
723                         Con_Printf ("Ogg sound file \"%s\" will be streamed\n", filename);
724                 per_sfx = (ogg_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
725                 strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name));
726                 sfx->memsize += sizeof (*per_sfx);
727                 per_sfx->file = data;
728                 per_sfx->filesize = filesize;
729                 sfx->memsize += filesize;
730
731                 per_sfx->format.speed = vi->rate;
732                 per_sfx->format.width = 2;  // We always work with 16 bits samples
733                 per_sfx->format.channels = vi->channels;
734
735                 sfx->fetcher_data = per_sfx;
736                 sfx->fetcher = &ogg_fetcher;
737                 sfx->flags |= SFXFLAG_STREAMED;
738                 sfx->total_length = (int)((size_t)len / (per_sfx->format.channels * 2) * ((double)snd_renderbuffer->format.speed / per_sfx->format.speed));
739                 vc = qov_comment(&vf, -1);
740                 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, (double)snd_renderbuffer->format.speed / (double)per_sfx->format.speed, sfx->total_length, &peak, &gaindb);
741                 per_sfx->total_length = sfx->total_length;
742                 qov_clear (&vf);
743         }
744         else
745         {
746                 char *buff;
747                 ogg_int64_t done;
748                 int bs;
749                 long ret;
750                 snd_buffer_t *sb;
751                 snd_format_t ogg_format;
752
753                 if (developer_loading.integer >= 2)
754                         Con_Printf ("Ogg sound file \"%s\" will be cached\n", filename);
755
756                 // Decode it
757                 buff = (char *)Mem_Alloc (snd_mempool, (int)len);
758                 done = 0;
759                 bs = 0;
760                 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), mem_bigendian, 2, 1, &bs)) > 0)
761                         done += ret;
762
763                 // Build the sound buffer
764                 ogg_format.speed = vi->rate;
765                 ogg_format.channels = vi->channels;
766                 ogg_format.width = 2;  // We always work with 16 bits samples
767                 sb = Snd_CreateSndBuffer ((unsigned char *)buff, (size_t)done / (vi->channels * 2), &ogg_format, snd_renderbuffer->format.speed);
768                 if (sb == NULL)
769                 {
770                         qov_clear (&vf);
771                         Mem_Free (data);
772                         Mem_Free (buff);
773                         return false;
774                 }
775
776                 sfx->fetcher = &wav_fetcher;
777                 sfx->fetcher_data = sb;
778
779                 sfx->total_length = sb->nbframes;
780                 sfx->memsize += sb->maxframes * sb->format.channels * sb->format.width + sizeof (*sb) - sizeof (sb->samples);
781
782                 sfx->flags &= ~SFXFLAG_STREAMED;
783                 vc = qov_comment(&vf, -1);
784                 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, (double)snd_renderbuffer->format.speed / (double)sb->format.speed, sfx->total_length, &peak, &gaindb);
785                 sb->nbframes = sfx->total_length;
786                 qov_clear (&vf);
787                 Mem_Free (data);
788                 Mem_Free (buff);
789         }
790
791         if(peak)
792         {
793                 sfx->volume_mult = min(1.0f / peak, exp(gaindb * 0.05f * log(10.0f)));
794                 sfx->volume_peak = peak;
795                 if (developer_loading.integer >= 2)
796                         Con_Printf ("Ogg sound file \"%s\" uses ReplayGain (gain %f, peak %f)\n", filename, sfx->volume_mult, sfx->volume_peak);
797         }
798
799         return true;
800 }