reduced memory usage of sound in Nexuiz by about 70MB by using shorter
[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
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         char **user_comments;
164         int   *comment_lengths;
165         int    comments;
166         char  *vendor;
167 } vorbis_comment;
168
169 typedef struct
170 {
171         void                            *datasource;
172         int                                     seekable;
173         ogg_int64_t                     offset;
174         ogg_int64_t                     end;
175         ogg_sync_state          oy;
176         int                                     links;
177         ogg_int64_t                     *offsets;
178         ogg_int64_t                     *dataoffsets;
179         long                            *serialnos;
180         ogg_int64_t                     *pcmlengths;
181         vorbis_info                     *vi;
182         vorbis_comment          *vc;
183         ogg_int64_t                     pcm_offset;
184         int                                     ready_state;
185         long                            current_serialno;
186         int                                     current_link;
187         double                          bittrack;
188         double                          samptrack;
189         ogg_stream_state        os;
190         vorbis_dsp_state        vd;
191         vorbis_block            vb;
192         ov_callbacks            callbacks;
193 } OggVorbis_File;
194
195
196 /*
197 =================================================================
198
199   DarkPlaces definitions
200
201 =================================================================
202 */
203
204 // Functions exported from the vorbisfile library
205 static int (*qov_clear) (OggVorbis_File *vf);
206 static vorbis_info* (*qov_info) (OggVorbis_File *vf,int link);
207 static vorbis_comment* (*qov_comment) (OggVorbis_File *vf,int link);
208 static char * (*qvorbis_comment_query) (vorbis_comment *vc, char *tag, int count);
209 static int (*qov_open_callbacks) (void *datasource, OggVorbis_File *vf,
210                                                                   char *initial, long ibytes,
211                                                                   ov_callbacks callbacks);
212 static int (*qov_pcm_seek) (OggVorbis_File *vf,ogg_int64_t pos);
213 static ogg_int64_t (*qov_pcm_total) (OggVorbis_File *vf,int i);
214 static long (*qov_read) (OggVorbis_File *vf,char *buffer,int length,
215                                                  int bigendianp,int word,int sgned,int *bitstream);
216
217 static dllfunction_t vorbisfilefuncs[] =
218 {
219         {"ov_clear",                            (void **) &qov_clear},
220         {"ov_info",                                     (void **) &qov_info},
221         {"ov_comment",                          (void **) &qov_comment},
222         {"ov_open_callbacks",           (void **) &qov_open_callbacks},
223         {"ov_pcm_seek",                         (void **) &qov_pcm_seek},
224         {"ov_pcm_total",                        (void **) &qov_pcm_total},
225         {"ov_read",                                     (void **) &qov_read},
226         {NULL, NULL}
227 };
228
229 static dllfunction_t vorbisfuncs[] =
230 {
231         {"vorbis_comment_query",        (void **) &qvorbis_comment_query},
232         {NULL, NULL}
233 };
234
235 // Handles for the Vorbis and Vorbisfile DLLs
236 static dllhandle_t vo_dll = NULL;
237 static dllhandle_t vf_dll = NULL;
238
239 typedef struct
240 {
241         unsigned char *buffer;
242         ogg_int64_t ind, buffsize;
243 } ov_decode_t;
244
245
246 static size_t ovcb_read (void *ptr, size_t size, size_t nb, void *datasource)
247 {
248         ov_decode_t *ov_decode = (ov_decode_t*)datasource;
249         size_t remain, len;
250
251         remain = ov_decode->buffsize - ov_decode->ind;
252         len = size * nb;
253         if (remain < len)
254                 len = remain - remain % size;
255
256         memcpy (ptr, ov_decode->buffer + ov_decode->ind, len);
257         ov_decode->ind += len;
258
259         return len / size;
260 }
261
262 static int ovcb_seek (void *datasource, ogg_int64_t offset, int whence)
263 {
264         ov_decode_t *ov_decode = (ov_decode_t*)datasource;
265
266         switch (whence)
267         {
268                 case SEEK_SET:
269                         break;
270                 case SEEK_CUR:
271                         offset += ov_decode->ind;
272                         break;
273                 case SEEK_END:
274                         offset += ov_decode->buffsize;
275                         break;
276                 default:
277                         return -1;
278         }
279         if (offset < 0 || offset > ov_decode->buffsize)
280                 return -1;
281
282         ov_decode->ind = offset;
283         return 0;
284 }
285
286 static int ovcb_close (void *ov_decode)
287 {
288         return 0;
289 }
290
291 static long ovcb_tell (void *ov_decode)
292 {
293         return ((ov_decode_t*)ov_decode)->ind;
294 }
295
296
297 /*
298 =================================================================
299
300   DLL load & unload
301
302 =================================================================
303 */
304
305 /*
306 ====================
307 OGG_OpenLibrary
308
309 Try to load the VorbisFile DLL
310 ====================
311 */
312 qboolean OGG_OpenLibrary (void)
313 {
314         const char* dllnames_vo [] =
315         {
316 #if defined(WIN64)
317                 "libvorbis64.dll",
318 #elif defined(WIN32)
319                 "libvorbis.dll",
320                 "vorbis.dll",
321 #elif defined(MACOSX)
322                 "libvorbis.dylib",
323 #else
324                 "libvorbis.so.0",
325                 "libvorbis.so",
326 #endif
327                 NULL
328         };
329         const char* dllnames_vf [] =
330         {
331 #if defined(WIN64)
332                 "libvorbisfile64.dll",
333 #elif defined(WIN32)
334                 "libvorbisfile.dll",
335                 "vorbisfile.dll",
336 #elif defined(MACOSX)
337                 "libvorbisfile.dylib",
338 #else
339                 "libvorbisfile.so.3",
340                 "libvorbisfile.so",
341 #endif
342                 NULL
343         };
344
345         // Already loaded?
346         if (vf_dll)
347                 return true;
348
349 // COMMANDLINEOPTION: Sound: -novorbis disables ogg vorbis sound support
350         if (COM_CheckParm("-novorbis"))
351                 return false;
352
353         // Load the DLLs
354         // We need to load both by hand because some OSes seem to not load
355         // the vorbis DLL automatically when loading the VorbisFile DLL
356         return Sys_LoadLibrary (dllnames_vo, &vo_dll, vorbisfuncs) && Sys_LoadLibrary (dllnames_vf, &vf_dll, vorbisfilefuncs);
357 }
358
359
360 /*
361 ====================
362 OGG_CloseLibrary
363
364 Unload the VorbisFile DLL
365 ====================
366 */
367 void OGG_CloseLibrary (void)
368 {
369         Sys_UnloadLibrary (&vf_dll);
370         Sys_UnloadLibrary (&vo_dll);
371 }
372
373
374 /*
375 =================================================================
376
377         Ogg Vorbis decoding
378
379 =================================================================
380 */
381
382 // Per-sfx data structure
383 typedef struct
384 {
385         unsigned char   *file;
386         size_t                  filesize;
387         snd_format_t    format;
388         unsigned int    total_length;
389         char                    name[128];
390 } ogg_stream_persfx_t;
391
392 // Per-channel data structure
393 typedef struct
394 {
395         OggVorbis_File  vf;
396         ov_decode_t             ov_decode;
397         unsigned int    sb_offset;
398         int                             bs;
399         snd_buffer_t    sb;             // must be at the end due to its dynamically allocated size
400 } ogg_stream_perchannel_t;
401
402
403 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
404
405 /*
406 ====================
407 OGG_FetchSound
408 ====================
409 */
410 static const snd_buffer_t* OGG_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes)
411 {
412         ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)*chfetcherpointer;
413         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcher;
414         snd_buffer_t* sb;
415         int newlength, done, ret, bigendian;
416         unsigned int real_start;
417         unsigned int factor;
418
419         // If there's no fetcher structure attached to the channel yet
420         if (per_ch == NULL)
421         {
422                 size_t buff_len, memsize;
423                 snd_format_t sb_format;
424
425                 sb_format.speed = snd_renderbuffer->format.speed;
426                 sb_format.width = per_sfx->format.width;
427                 sb_format.channels = per_sfx->format.channels;
428
429                 buff_len = STREAM_BUFFER_SIZE(&sb_format);
430                 memsize = sizeof (*per_ch) - sizeof (per_ch->sb.samples) + buff_len;
431                 per_ch = (ogg_stream_perchannel_t *)Mem_Alloc (snd_mempool, memsize);
432
433                 // Open it with the VorbisFile API
434                 per_ch->ov_decode.buffer = per_sfx->file;
435                 per_ch->ov_decode.ind = 0;
436                 per_ch->ov_decode.buffsize = per_sfx->filesize;
437                 if (qov_open_callbacks (&per_ch->ov_decode, &per_ch->vf, NULL, 0, callbacks) < 0)
438                 {
439                         Con_Printf("error while reading Ogg Vorbis stream \"%s\"\n", per_sfx->name);
440                         Mem_Free (per_ch);
441                         return NULL;
442                 }
443                 per_ch->bs = 0;
444
445                 per_ch->sb_offset = 0;
446                 per_ch->sb.format = sb_format;
447                 per_ch->sb.nbframes = 0;
448                 per_ch->sb.maxframes = buff_len / (per_ch->sb.format.channels * per_ch->sb.format.width);
449
450                 *chfetcherpointer = per_ch;
451         }
452
453         real_start = *start;
454
455         sb = &per_ch->sb;
456         factor = per_sfx->format.width * per_sfx->format.channels;
457
458         // If the stream buffer can't contain that much samples anyway
459         if (nbsampleframes > sb->maxframes)
460         {
461                 Con_Printf ("OGG_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes);
462                 return NULL;
463         }
464
465         // If the data we need has already been decompressed in the sfxbuffer, just return it
466         if (per_ch->sb_offset <= real_start && per_ch->sb_offset + sb->nbframes >= real_start + nbsampleframes)
467         {
468                 *start = per_ch->sb_offset;
469                 return sb;
470         }
471
472         newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start;
473
474         // If we need to skip some data before decompressing the rest, or if the stream has looped
475         if (newlength < 0 || per_ch->sb_offset > real_start)
476         {
477                 unsigned int time_start;
478                 ogg_int64_t ogg_start;
479                 int err;
480
481                 if (real_start > (unsigned int)per_sfx->total_length)
482                 {
483                         Con_Printf ("OGG_FetchSound: asked for a start position after the end of the sfx! (%u > %u)\n",
484                                                 real_start, per_sfx->total_length);
485                         return NULL;
486                 }
487
488                 // We work with 200ms (1/5 sec) steps to avoid rounding errors
489                 time_start = real_start * 5 / snd_renderbuffer->format.speed;
490                 ogg_start = time_start * (per_sfx->format.speed / 5);
491                 err = qov_pcm_seek (&per_ch->vf, ogg_start);
492                 if (err != 0)
493                 {
494                         Con_Printf ("OGG_FetchSound: qov_pcm_seek(..., %d) returned %d\n",
495                                                 real_start, err);
496                         return NULL;
497                 }
498                 sb->nbframes = 0;
499
500                 real_start = (unsigned int) ((float)ogg_start / per_sfx->format.speed * snd_renderbuffer->format.speed);
501                 if (*start - real_start + nbsampleframes > sb->maxframes)
502                 {
503                         Con_Printf ("OGG_FetchSound: stream buffer too small after seek (%u sample frames required)\n",
504                                                 *start - real_start + nbsampleframes);
505                         per_ch->sb_offset = real_start;
506                         return NULL;
507                 }
508         }
509         // Else, move forward the samples we need to keep in the sound buffer
510         else
511         {
512                 memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor);
513                 sb->nbframes = newlength;
514         }
515
516         per_ch->sb_offset = real_start;
517
518         // We add exactly 1 sec of sound to the buffer:
519         // 1- to ensure we won't lose any sample during the resampling process
520         // 2- to force one call to OGG_FetchSound per second to regulate the workload
521         if ((int)(sb->format.speed * STREAM_BUFFER_FILL) + sb->nbframes > sb->maxframes)
522         {
523                 Con_Printf ("OGG_FetchSound: stream buffer overflow (%u sample frames / %u)\n",
524                                         sb->format.speed + sb->nbframes, sb->maxframes);
525                 return NULL;
526         }
527         newlength = (int)(per_sfx->format.speed*STREAM_BUFFER_FILL) * factor;  // -> 1 sec of sound before resampling
528         if(newlength > (int)sizeof(resampling_buffer))
529                 newlength = sizeof(resampling_buffer);
530
531         // Decompress in the resampling_buffer
532 #if BYTE_ORDER == BIG_ENDIAN
533         bigendian = 1;
534 #else
535         bigendian = 0;
536 #endif
537         done = 0;
538         while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), bigendian, 2, 1, &per_ch->bs)) > 0)
539                 done += ret;
540
541         Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
542
543         *start = per_ch->sb_offset;
544         return sb;
545 }
546
547
548 /*
549 ====================
550 OGG_FetchEnd
551 ====================
552 */
553 static void OGG_FetchEnd (void *chfetcherdata)
554 {
555         ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)chfetcherdata;
556
557         if (per_ch != NULL)
558         {
559                 // Free the ogg vorbis decoder
560                 qov_clear (&per_ch->vf);
561
562                 Mem_Free (per_ch);
563         }
564 }
565
566
567 /*
568 ====================
569 OGG_FreeSfx
570 ====================
571 */
572 static void OGG_FreeSfx (void *sfxfetcherdata)
573 {
574         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcherdata;
575
576         // Free the Ogg Vorbis file
577         Mem_Free(per_sfx->file);
578
579         // Free the stream structure
580         Mem_Free(per_sfx);
581 }
582
583
584 /*
585 ====================
586 OGG_GetFormat
587 ====================
588 */
589 static const snd_format_t* OGG_GetFormat (sfx_t* sfx)
590 {
591         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
592         return &per_sfx->format;
593 }
594
595 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd, OGG_FreeSfx, OGG_GetFormat };
596
597 static void OGG_DecodeTags(vorbis_comment *vc, unsigned int *start, unsigned int *length, double samplesfactor, unsigned int numsamples, double *peak, double *gaindb)
598 {
599         const char *startcomment = NULL, *lengthcomment = NULL, *endcomment = NULL, *thiscomment = NULL;
600
601         *start = numsamples;
602         *length = numsamples;
603         *peak = 0.0;
604         *gaindb = 0.0;
605
606         if(!vc)
607                 return;
608
609         thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
610         if(thiscomment)
611                 *peak = atof(thiscomment);
612         thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
613         if(thiscomment)
614                 *gaindb = atof(thiscomment);
615         
616         startcomment = qvorbis_comment_query(vc, "LOOP_START", 0); // DarkPlaces, and some Japanese app
617         if(startcomment)
618         {
619                 endcomment = qvorbis_comment_query(vc, "LOOP_END", 0);
620                 if(!endcomment)
621                         lengthcomment = qvorbis_comment_query(vc, "LOOP_LENGTH", 0);
622         }
623         else
624         {
625                 startcomment = qvorbis_comment_query(vc, "LOOPSTART", 0); // RPG Maker VX
626                 if(startcomment)
627                 {
628                         lengthcomment = qvorbis_comment_query(vc, "LOOPLENGTH", 0);
629                         if(!lengthcomment)
630                                 endcomment = qvorbis_comment_query(vc, "LOOPEND", 0);
631                 }
632                 else
633                 {
634                         startcomment = qvorbis_comment_query(vc, "LOOPPOINT", 0); // Sonic Robo Blast 2
635                 }
636         }
637
638         if(startcomment)
639         {
640                 *start = (unsigned int) bound(0, atof(startcomment) * samplesfactor, numsamples);
641                 if(endcomment)
642                         *length = (unsigned int) bound(0, atof(endcomment) * samplesfactor, numsamples);
643                 else if(lengthcomment)
644                         *length = (unsigned int) bound(0, *start + atof(lengthcomment) * samplesfactor, numsamples);
645         }
646 }
647
648 /*
649 ====================
650 OGG_LoadVorbisFile
651
652 Load an Ogg Vorbis file into memory
653 ====================
654 */
655 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *sfx)
656 {
657         unsigned char *data;
658         fs_offset_t filesize;
659         ov_decode_t ov_decode;
660         OggVorbis_File vf;
661         vorbis_info *vi;
662         vorbis_comment *vc;
663         ogg_int64_t len, buff_len;
664         double peak, gaindb;
665
666         if (!vf_dll)
667                 return false;
668
669         // Already loaded?
670         if (sfx->fetcher != NULL)
671                 return true;
672
673         // Load the file
674         data = FS_LoadFile (filename, snd_mempool, false, &filesize);
675         if (data == NULL)
676                 return false;
677
678         if (developer_loading.integer >= 2)
679                 Con_Printf ("Loading Ogg Vorbis file \"%s\"\n", filename);
680
681         // Open it with the VorbisFile API
682         ov_decode.buffer = data;
683         ov_decode.ind = 0;
684         ov_decode.buffsize = filesize;
685         if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
686         {
687                 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
688                 Mem_Free(data);
689                 return false;
690         }
691
692         // Get the stream information
693         vi = qov_info (&vf, -1);
694         if (vi->channels < 1 || vi->channels > 2)
695         {
696                 Con_Printf("%s has an unsupported number of channels (%i)\n",
697                                         sfx->name, vi->channels);
698                 qov_clear (&vf);
699                 Mem_Free(data);
700                 return false;
701         }
702
703         len = qov_pcm_total (&vf, -1) * vi->channels * 2;  // 16 bits => "* 2"
704
705         // Decide if we go for a stream or a simple PCM cache
706         buff_len = (int)ceil (STREAM_BUFFER_DURATION * snd_renderbuffer->format.speed) * 2 * vi->channels;
707         if (snd_streaming.integer && len > (ogg_int64_t)filesize + 3 * buff_len)
708         {
709                 ogg_stream_persfx_t* per_sfx;
710
711                 if (developer_loading.integer >= 2)
712                         Con_Printf ("Ogg sound file \"%s\" will be streamed\n", filename);
713                 per_sfx = (ogg_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
714                 strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name));
715                 sfx->memsize += sizeof (*per_sfx);
716                 per_sfx->file = data;
717                 per_sfx->filesize = filesize;
718                 sfx->memsize += filesize;
719
720                 per_sfx->format.speed = vi->rate;
721                 per_sfx->format.width = 2;  // We always work with 16 bits samples
722                 per_sfx->format.channels = vi->channels;
723
724                 sfx->fetcher_data = per_sfx;
725                 sfx->fetcher = &ogg_fetcher;
726                 sfx->flags |= SFXFLAG_STREAMED;
727                 sfx->total_length = (int)((size_t)len / (per_sfx->format.channels * 2) * ((double)snd_renderbuffer->format.speed / per_sfx->format.speed));
728                 vc = qov_comment(&vf, -1);
729                 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, (double)snd_renderbuffer->format.speed / (double)per_sfx->format.speed, sfx->total_length, &peak, &gaindb);
730                 per_sfx->total_length = sfx->total_length;
731                 qov_clear (&vf);
732         }
733         else
734         {
735                 char *buff;
736                 ogg_int64_t done;
737                 int bs, bigendian;
738                 long ret;
739                 snd_buffer_t *sb;
740                 snd_format_t ogg_format;
741
742                 if (developer_loading.integer >= 2)
743                         Con_Printf ("Ogg sound file \"%s\" will be cached\n", filename);
744
745                 // Decode it
746                 buff = (char *)Mem_Alloc (snd_mempool, (int)len);
747                 done = 0;
748                 bs = 0;
749 #if BYTE_ORDER == BIG_ENDIAN
750                 bigendian = 1;
751 #else
752                 bigendian = 0;
753 #endif
754                 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), bigendian, 2, 1, &bs)) > 0)
755                         done += ret;
756
757                 // Build the sound buffer
758                 ogg_format.speed = vi->rate;
759                 ogg_format.channels = vi->channels;
760                 ogg_format.width = 2;  // We always work with 16 bits samples
761                 sb = Snd_CreateSndBuffer ((unsigned char *)buff, (size_t)done / (vi->channels * 2), &ogg_format, snd_renderbuffer->format.speed);
762                 if (sb == NULL)
763                 {
764                         qov_clear (&vf);
765                         Mem_Free (data);
766                         Mem_Free (buff);
767                         return false;
768                 }
769
770                 sfx->fetcher = &wav_fetcher;
771                 sfx->fetcher_data = sb;
772
773                 sfx->total_length = sb->nbframes;
774                 sfx->memsize += sb->maxframes * sb->format.channels * sb->format.width + sizeof (*sb) - sizeof (sb->samples);
775
776                 sfx->flags &= ~SFXFLAG_STREAMED;
777                 vc = qov_comment(&vf, -1);
778                 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, (double)snd_renderbuffer->format.speed / (double)sb->format.speed, sfx->total_length, &peak, &gaindb);
779                 sb->nbframes = sfx->total_length;
780                 qov_clear (&vf);
781                 Mem_Free (data);
782                 Mem_Free (buff);
783         }
784
785         if(peak)
786         {
787                 sfx->volume_mult = min(1.0f / peak, exp(gaindb * 0.05f * log(10.0f)));
788                 sfx->volume_peak = peak;
789                 if (developer_loading.integer >= 2)
790                         Con_Printf ("Ogg sound file \"%s\" uses ReplayGain (gain %f, peak %f)\n", filename, sfx->volume_mult, sfx->volume_peak);
791         }
792
793         return true;
794 }