]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_ogg.c
fix loading of quake lmp/wad textures
[xonotic/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         // this is how much we FETCH...
538         if ((size_t) ((double) newlength * (double)sb->format.speed / (double)per_sfx->format.speed) + sb->nbframes > sb->maxframes)
539         {
540                 Con_Printf ("OGG_FetchSound: stream buffer overflow (%u + %u = %u sample frames / %u)\n",
541                                         (unsigned int) ((double) newlength * (double)sb->format.speed / (double)per_sfx->format.speed), sb->nbframes, (unsigned int) ((double) newlength * (double)sb->format.speed / (double)per_sfx->format.speed) + sb->nbframes, sb->maxframes);
542                 return NULL;
543         }
544         newlength *= factor; // convert from sample frames to bytes
545         if(newlength > (int)sizeof(resampling_buffer))
546                 newlength = sizeof(resampling_buffer);
547
548         // Decompress in the resampling_buffer
549         done = 0;
550         while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), mem_bigendian, 2, 1, &per_ch->bs)) > 0)
551                 done += ret;
552
553         Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
554
555         *start = per_ch->sb_offset;
556         return sb;
557 }
558
559
560 /*
561 ====================
562 OGG_FetchEnd
563 ====================
564 */
565 static void OGG_FetchEnd (void *chfetcherdata)
566 {
567         ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)chfetcherdata;
568
569         if (per_ch != NULL)
570         {
571                 // Free the ogg vorbis decoder
572                 qov_clear (&per_ch->vf);
573
574                 Mem_Free (per_ch);
575         }
576 }
577
578
579 /*
580 ====================
581 OGG_FreeSfx
582 ====================
583 */
584 static void OGG_FreeSfx (void *sfxfetcherdata)
585 {
586         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcherdata;
587
588         // Free the Ogg Vorbis file
589         Mem_Free(per_sfx->file);
590
591         // Free the stream structure
592         Mem_Free(per_sfx);
593 }
594
595
596 /*
597 ====================
598 OGG_GetFormat
599 ====================
600 */
601 static const snd_format_t* OGG_GetFormat (sfx_t* sfx)
602 {
603         ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
604         return &per_sfx->format;
605 }
606
607 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd, OGG_FreeSfx, OGG_GetFormat };
608
609 static void OGG_DecodeTags(vorbis_comment *vc, unsigned int *start, unsigned int *length, double samplesfactor, unsigned int numsamples, double *peak, double *gaindb)
610 {
611         const char *startcomment = NULL, *lengthcomment = NULL, *endcomment = NULL, *thiscomment = NULL;
612
613         *start = numsamples;
614         *length = numsamples;
615         *peak = 0.0;
616         *gaindb = 0.0;
617
618         if(!vc)
619                 return;
620
621         thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
622         if(thiscomment)
623                 *peak = atof(thiscomment);
624         thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
625         if(thiscomment)
626                 *gaindb = atof(thiscomment);
627         
628         startcomment = qvorbis_comment_query(vc, "LOOP_START", 0); // DarkPlaces, and some Japanese app
629         if(startcomment)
630         {
631                 endcomment = qvorbis_comment_query(vc, "LOOP_END", 0);
632                 if(!endcomment)
633                         lengthcomment = qvorbis_comment_query(vc, "LOOP_LENGTH", 0);
634         }
635         else
636         {
637                 startcomment = qvorbis_comment_query(vc, "LOOPSTART", 0); // RPG Maker VX
638                 if(startcomment)
639                 {
640                         lengthcomment = qvorbis_comment_query(vc, "LOOPLENGTH", 0);
641                         if(!lengthcomment)
642                                 endcomment = qvorbis_comment_query(vc, "LOOPEND", 0);
643                 }
644                 else
645                 {
646                         startcomment = qvorbis_comment_query(vc, "LOOPPOINT", 0); // Sonic Robo Blast 2
647                 }
648         }
649
650         if(startcomment)
651         {
652                 *start = (unsigned int) bound(0, atof(startcomment) * samplesfactor, numsamples);
653                 if(endcomment)
654                         *length = (unsigned int) bound(0, atof(endcomment) * samplesfactor, numsamples);
655                 else if(lengthcomment)
656                         *length = (unsigned int) bound(0, *start + atof(lengthcomment) * samplesfactor, numsamples);
657         }
658 }
659
660 /*
661 ====================
662 OGG_LoadVorbisFile
663
664 Load an Ogg Vorbis file into memory
665 ====================
666 */
667 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *sfx)
668 {
669         unsigned char *data;
670         fs_offset_t filesize;
671         ov_decode_t ov_decode;
672         OggVorbis_File vf;
673         vorbis_info *vi;
674         vorbis_comment *vc;
675         ogg_int64_t len, buff_len;
676         double peak, gaindb;
677
678 #ifndef LINK_TO_LIBVORBIS
679         if (!vf_dll)
680                 return false;
681 #endif
682
683         // Already loaded?
684         if (sfx->fetcher != NULL)
685                 return true;
686
687         // Load the file
688         data = FS_LoadFile (filename, snd_mempool, false, &filesize);
689         if (data == NULL)
690                 return false;
691
692         if (developer_loading.integer >= 2)
693                 Con_Printf ("Loading Ogg Vorbis file \"%s\"\n", filename);
694
695         // Open it with the VorbisFile API
696         ov_decode.buffer = data;
697         ov_decode.ind = 0;
698         ov_decode.buffsize = filesize;
699         if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
700         {
701                 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
702                 Mem_Free(data);
703                 return false;
704         }
705
706         // Get the stream information
707         vi = qov_info (&vf, -1);
708         if (vi->channels < 1 || vi->channels > 2)
709         {
710                 Con_Printf("%s has an unsupported number of channels (%i)\n",
711                                         sfx->name, vi->channels);
712                 qov_clear (&vf);
713                 Mem_Free(data);
714                 return false;
715         }
716
717         len = qov_pcm_total (&vf, -1) * vi->channels * 2;  // 16 bits => "* 2"
718
719         // Decide if we go for a stream or a simple PCM cache
720         buff_len = (int)ceil (STREAM_BUFFER_DURATION * snd_renderbuffer->format.speed) * 2 * vi->channels;
721         if (snd_streaming.integer && (len > (ogg_int64_t)filesize + 3 * buff_len || snd_streaming.integer >= 2))
722         {
723                 ogg_stream_persfx_t* per_sfx;
724
725                 if (developer_loading.integer >= 2)
726                         Con_Printf ("Ogg sound file \"%s\" will be streamed\n", filename);
727                 per_sfx = (ogg_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
728                 strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name));
729                 sfx->memsize += sizeof (*per_sfx);
730                 per_sfx->file = data;
731                 per_sfx->filesize = filesize;
732                 sfx->memsize += filesize;
733
734                 per_sfx->format.speed = vi->rate;
735                 per_sfx->format.width = 2;  // We always work with 16 bits samples
736                 per_sfx->format.channels = vi->channels;
737
738                 sfx->fetcher_data = per_sfx;
739                 sfx->fetcher = &ogg_fetcher;
740                 sfx->flags |= SFXFLAG_STREAMED;
741                 sfx->total_length = (int)((size_t)len / (per_sfx->format.channels * 2) * ((double)snd_renderbuffer->format.speed / per_sfx->format.speed));
742                 vc = qov_comment(&vf, -1);
743                 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, (double)snd_renderbuffer->format.speed / (double)per_sfx->format.speed, sfx->total_length, &peak, &gaindb);
744                 per_sfx->total_length = sfx->total_length;
745                 qov_clear (&vf);
746         }
747         else
748         {
749                 char *buff;
750                 ogg_int64_t done;
751                 int bs;
752                 long ret;
753                 snd_buffer_t *sb;
754                 snd_format_t ogg_format;
755
756                 if (developer_loading.integer >= 2)
757                         Con_Printf ("Ogg sound file \"%s\" will be cached\n", filename);
758
759                 // Decode it
760                 buff = (char *)Mem_Alloc (snd_mempool, (int)len);
761                 done = 0;
762                 bs = 0;
763                 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), mem_bigendian, 2, 1, &bs)) > 0)
764                         done += ret;
765
766                 // Build the sound buffer
767                 ogg_format.speed = vi->rate;
768                 ogg_format.channels = vi->channels;
769                 ogg_format.width = 2;  // We always work with 16 bits samples
770                 sb = Snd_CreateSndBuffer ((unsigned char *)buff, (size_t)done / (vi->channels * 2), &ogg_format, snd_renderbuffer->format.speed);
771                 if (sb == NULL)
772                 {
773                         qov_clear (&vf);
774                         Mem_Free (data);
775                         Mem_Free (buff);
776                         return false;
777                 }
778
779                 sfx->fetcher = &wav_fetcher;
780                 sfx->fetcher_data = sb;
781
782                 sfx->total_length = sb->nbframes;
783                 sfx->memsize += sb->maxframes * sb->format.channels * sb->format.width + sizeof (*sb) - sizeof (sb->samples);
784
785                 sfx->flags &= ~SFXFLAG_STREAMED;
786                 vc = qov_comment(&vf, -1);
787                 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, (double)snd_renderbuffer->format.speed / (double)sb->format.speed, sfx->total_length, &peak, &gaindb);
788                 sb->nbframes = sfx->total_length;
789                 qov_clear (&vf);
790                 Mem_Free (data);
791                 Mem_Free (buff);
792         }
793
794         if(peak)
795         {
796                 sfx->volume_mult = min(1.0f / peak, exp(gaindb * 0.05f * log(10.0f)));
797                 sfx->volume_peak = peak;
798                 if (developer_loading.integer >= 2)
799                         Con_Printf ("Ogg sound file \"%s\" uses ReplayGain (gain %f, peak %f)\n", filename, sfx->volume_mult, sfx->volume_peak);
800         }
801
802         return true;
803 }