2 Copyright (C) 2003-2005 Mathieu Olivier
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.
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.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to:
18 Free Software Foundation, Inc.
19 59 Temple Place - Suite 330
20 Boston, MA 02111-1307, USA
30 #ifdef LINK_TO_LIBVORBIS
31 #define OV_EXCLUDE_STATIC_CALLBACKS
33 #include <vorbis/vorbisfile.h>
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
44 qboolean OGG_OpenLibrary (void) {return true;}
45 void OGG_CloseLibrary (void) {}
49 =================================================================
51 Minimal set of definitions from the Ogg Vorbis lib
52 (C) COPYRIGHT 1994-2001 by the XIPHOPHORUS Company
55 WARNING: for a matter of simplicity, several pointer types are
56 casted to "void*", and most enumerated values are not included
58 =================================================================
62 typedef __int64 ogg_int64_t;
64 typedef long long ogg_int64_t;
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);
100 unsigned char *body_data;
105 ogg_int64_t *granule_vals;
109 long lacing_returned;
110 unsigned char header[282];
116 ogg_int64_t packetno;
117 ogg_int64_t granulepos;
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;
148 unsigned char *buffer;
163 ogg_int64_t granulepos;
164 ogg_int64_t sequence;
165 vorbis_dsp_state *vd;
170 void *reap; // VOIDED POINTER
180 char **user_comments;
181 int *comment_lengths;
194 ogg_int64_t *offsets;
195 ogg_int64_t *dataoffsets;
197 ogg_int64_t *pcmlengths;
200 ogg_int64_t pcm_offset;
202 long current_serialno;
209 ov_callbacks callbacks;
214 =================================================================
216 DarkPlaces definitions
218 =================================================================
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);
234 static dllfunction_t vorbisfilefuncs[] =
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},
246 static dllfunction_t vorbisfuncs[] =
248 {"vorbis_comment_query", (void **) &qvorbis_comment_query},
252 // Handles for the Vorbis and Vorbisfile DLLs
253 static dllhandle_t vo_dll = NULL;
254 static dllhandle_t vf_dll = NULL;
258 =================================================================
262 =================================================================
269 Try to load the VorbisFile DLL
272 qboolean OGG_OpenLibrary (void)
274 const char* dllnames_vo [] =
280 #elif defined(MACOSX)
288 const char* dllnames_vf [] =
291 "libvorbisfile-3.dll",
294 #elif defined(MACOSX)
295 "libvorbisfile.dylib",
297 "libvorbisfile.so.3",
307 // COMMANDLINEOPTION: Sound: -novorbis disables ogg vorbis sound support
308 if (COM_CheckParm("-novorbis"))
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);
322 Unload the VorbisFile DLL
325 void OGG_CloseLibrary (void)
327 Sys_UnloadLibrary (&vf_dll);
328 Sys_UnloadLibrary (&vo_dll);
334 =================================================================
338 =================================================================
343 unsigned char *buffer;
344 ogg_int64_t ind, buffsize;
347 static size_t ovcb_read (void *ptr, size_t size, size_t nb, void *datasource)
349 ov_decode_t *ov_decode = (ov_decode_t*)datasource;
352 remain = ov_decode->buffsize - ov_decode->ind;
355 len = remain - remain % size;
357 memcpy (ptr, ov_decode->buffer + ov_decode->ind, len);
358 ov_decode->ind += len;
363 static int ovcb_seek (void *datasource, ogg_int64_t offset, int whence)
365 ov_decode_t *ov_decode = (ov_decode_t*)datasource;
372 offset += ov_decode->ind;
375 offset += ov_decode->buffsize;
380 if (offset < 0 || offset > ov_decode->buffsize)
383 ov_decode->ind = offset;
387 static int ovcb_close (void *ov_decode)
392 static long ovcb_tell (void *ov_decode)
394 return ((ov_decode_t*)ov_decode)->ind;
397 // Per-sfx data structure
403 unsigned int total_length;
405 } ogg_stream_persfx_t;
407 // Per-channel data structure
411 ov_decode_t ov_decode;
412 unsigned int sb_offset;
414 snd_buffer_t sb; // must be at the end due to its dynamically allocated size
415 } ogg_stream_perchannel_t;
418 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
425 static const snd_buffer_t* OGG_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes)
427 ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)*chfetcherpointer;
428 ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcher;
430 int newlength, done, ret;
431 unsigned int real_start;
434 // If there's no fetcher structure attached to the channel yet
437 size_t buff_len, memsize;
438 snd_format_t sb_format;
440 sb_format.speed = snd_renderbuffer->format.speed;
441 sb_format.width = per_sfx->format.width;
442 sb_format.channels = per_sfx->format.channels;
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);
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)
454 Con_Printf("error while reading Ogg Vorbis stream \"%s\"\n", per_sfx->name);
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);
465 *chfetcherpointer = per_ch;
471 factor = per_sfx->format.width * per_sfx->format.channels;
473 // If the stream buffer can't contain that much samples anyway
474 if (nbsampleframes > sb->maxframes)
476 Con_Printf ("OGG_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes);
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)
483 *start = per_ch->sb_offset;
487 newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start;
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)
492 unsigned int time_start;
493 ogg_int64_t ogg_start;
496 if (real_start > (unsigned int)per_sfx->total_length)
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);
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);
509 Con_Printf ("OGG_FetchSound: qov_pcm_seek(..., %d) returned %d\n",
515 real_start = (unsigned int) ((float)ogg_start / per_sfx->format.speed * snd_renderbuffer->format.speed);
516 if (*start - real_start + nbsampleframes > sb->maxframes)
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;
524 // Else, move forward the samples we need to keep in the sound buffer
527 memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor);
528 sb->nbframes = newlength;
531 per_ch->sb_offset = real_start;
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)
539 Con_Printf ("OGG_FetchSound: stream buffer overflow (%u sample frames / %u)\n",
540 sb->format.speed + sb->nbframes, sb->maxframes);
543 newlength *= factor; // convert from sample frames to bytes
544 if(newlength > (int)sizeof(resampling_buffer))
545 newlength = sizeof(resampling_buffer);
547 // Decompress in the resampling_buffer
549 while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), mem_bigendian, 2, 1, &per_ch->bs)) > 0)
552 Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
554 *start = per_ch->sb_offset;
564 static void OGG_FetchEnd (void *chfetcherdata)
566 ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)chfetcherdata;
570 // Free the ogg vorbis decoder
571 qov_clear (&per_ch->vf);
583 static void OGG_FreeSfx (void *sfxfetcherdata)
585 ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcherdata;
587 // Free the Ogg Vorbis file
588 Mem_Free(per_sfx->file);
590 // Free the stream structure
600 static const snd_format_t* OGG_GetFormat (sfx_t* sfx)
602 ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
603 return &per_sfx->format;
606 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd, OGG_FreeSfx, OGG_GetFormat };
608 static void OGG_DecodeTags(vorbis_comment *vc, unsigned int *start, unsigned int *length, double samplesfactor, unsigned int numsamples, double *peak, double *gaindb)
610 const char *startcomment = NULL, *lengthcomment = NULL, *endcomment = NULL, *thiscomment = NULL;
613 *length = numsamples;
620 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
622 *peak = atof(thiscomment);
623 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
625 *gaindb = atof(thiscomment);
627 startcomment = qvorbis_comment_query(vc, "LOOP_START", 0); // DarkPlaces, and some Japanese app
630 endcomment = qvorbis_comment_query(vc, "LOOP_END", 0);
632 lengthcomment = qvorbis_comment_query(vc, "LOOP_LENGTH", 0);
636 startcomment = qvorbis_comment_query(vc, "LOOPSTART", 0); // RPG Maker VX
639 lengthcomment = qvorbis_comment_query(vc, "LOOPLENGTH", 0);
641 endcomment = qvorbis_comment_query(vc, "LOOPEND", 0);
645 startcomment = qvorbis_comment_query(vc, "LOOPPOINT", 0); // Sonic Robo Blast 2
651 *start = (unsigned int) bound(0, atof(startcomment) * samplesfactor, numsamples);
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);
663 Load an Ogg Vorbis file into memory
666 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *sfx)
669 fs_offset_t filesize;
670 ov_decode_t ov_decode;
674 ogg_int64_t len, buff_len;
677 #ifndef LINK_TO_LIBVORBIS
683 if (sfx->fetcher != NULL)
687 data = FS_LoadFile (filename, snd_mempool, false, &filesize);
691 if (developer_loading.integer >= 2)
692 Con_Printf ("Loading Ogg Vorbis file \"%s\"\n", filename);
694 // Open it with the VorbisFile API
695 ov_decode.buffer = data;
697 ov_decode.buffsize = filesize;
698 if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
700 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
705 // Get the stream information
706 vi = qov_info (&vf, -1);
707 if (vi->channels < 1 || vi->channels > 2)
709 Con_Printf("%s has an unsupported number of channels (%i)\n",
710 sfx->name, vi->channels);
716 len = qov_pcm_total (&vf, -1) * vi->channels * 2; // 16 bits => "* 2"
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))
722 ogg_stream_persfx_t* per_sfx;
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;
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;
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;
753 snd_format_t ogg_format;
755 if (developer_loading.integer >= 2)
756 Con_Printf ("Ogg sound file \"%s\" will be cached\n", filename);
759 buff = (char *)Mem_Alloc (snd_mempool, (int)len);
762 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), mem_bigendian, 2, 1, &bs)) > 0)
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);
778 sfx->fetcher = &wav_fetcher;
779 sfx->fetcher_data = sb;
781 sfx->total_length = sb->nbframes;
782 sfx->memsize += sb->maxframes * sb->format.channels * sb->format.width + sizeof (*sb) - sizeof (sb->samples);
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;
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);