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