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
25 #include "darkplaces.h"
31 #ifdef LINK_TO_LIBVORBIS
32 #define OV_EXCLUDE_STATIC_CALLBACKS
34 #include <vorbis/vorbisfile.h>
36 #define qov_clear ov_clear
37 #define qov_info ov_info
38 #define qov_comment ov_comment
39 #define qov_open_callbacks ov_open_callbacks
40 #define qov_pcm_seek ov_pcm_seek
41 #define qov_pcm_total ov_pcm_total
42 #define qov_read ov_read
43 #define qvorbis_comment_query vorbis_comment_query
45 qbool OGG_OpenLibrary (void) {return true;}
46 void OGG_CloseLibrary (void) {}
50 =================================================================
52 Minimal set of definitions from the Ogg Vorbis lib
53 (C) COPYRIGHT 1994-2001 by the XIPHOPHORUS Company
56 WARNING: for a matter of simplicity, several pointer types are
57 casted to "void*", and most enumerated values are not included
59 =================================================================
63 typedef __int64 ogg_int64_t;
65 typedef long long ogg_int64_t;
70 size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
71 int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
72 int (*close_func) (void *datasource);
73 long (*tell_func) (void *datasource);
101 unsigned char *body_data;
106 ogg_int64_t *granule_vals;
110 long lacing_returned;
111 unsigned char header[282];
117 ogg_int64_t packetno;
118 ogg_int64_t granulepos;
136 ogg_int64_t granulepos;
137 ogg_int64_t sequence;
138 ogg_int64_t glue_bits;
139 ogg_int64_t time_bits;
140 ogg_int64_t floor_bits;
141 ogg_int64_t res_bits;
149 unsigned char *buffer;
164 ogg_int64_t granulepos;
165 ogg_int64_t sequence;
166 vorbis_dsp_state *vd;
171 void *reap; // VOIDED POINTER
181 char **user_comments;
182 int *comment_lengths;
195 ogg_int64_t *offsets;
196 ogg_int64_t *dataoffsets;
198 ogg_int64_t *pcmlengths;
201 ogg_int64_t pcm_offset;
203 long current_serialno;
210 ov_callbacks callbacks;
215 =================================================================
217 DarkPlaces definitions
219 =================================================================
222 // Functions exported from the vorbisfile library
223 static int (*qov_clear) (OggVorbis_File *vf);
224 static vorbis_info* (*qov_info) (OggVorbis_File *vf,int link);
225 static vorbis_comment* (*qov_comment) (OggVorbis_File *vf,int link);
226 static char * (*qvorbis_comment_query) (vorbis_comment *vc, const char *tag, int count);
227 static int (*qov_open_callbacks) (void *datasource, OggVorbis_File *vf,
228 char *initial, long ibytes,
229 ov_callbacks callbacks);
230 static int (*qov_pcm_seek) (OggVorbis_File *vf,ogg_int64_t pos);
231 static ogg_int64_t (*qov_pcm_total) (OggVorbis_File *vf,int i);
232 static long (*qov_read) (OggVorbis_File *vf,char *buffer,int length,
233 int bigendianp,int word,int sgned,int *bitstream);
235 static dllfunction_t vorbisfilefuncs[] =
237 {"ov_clear", (void **) &qov_clear},
238 {"ov_info", (void **) &qov_info},
239 {"ov_comment", (void **) &qov_comment},
240 {"ov_open_callbacks", (void **) &qov_open_callbacks},
241 {"ov_pcm_seek", (void **) &qov_pcm_seek},
242 {"ov_pcm_total", (void **) &qov_pcm_total},
243 {"ov_read", (void **) &qov_read},
247 static dllfunction_t vorbisfuncs[] =
249 {"vorbis_comment_query", (void **) &qvorbis_comment_query},
253 // Handles for the Vorbis and Vorbisfile DLLs
254 static dllhandle_t vo_dll = NULL;
255 static dllhandle_t vf_dll = NULL;
259 =================================================================
263 =================================================================
270 Try to load the VorbisFile DLL
273 qbool OGG_OpenLibrary (void)
275 const char* dllnames_vo [] =
281 #elif defined(MACOSX)
289 const char* dllnames_vf [] =
292 "libvorbisfile-3.dll",
295 #elif defined(MACOSX)
296 "libvorbisfile.dylib",
298 "libvorbisfile.so.3",
308 // COMMANDLINEOPTION: Sound: -novorbis disables ogg vorbis sound support
309 if (Sys_CheckParm("-novorbis"))
313 // We need to load both by hand because some OSes seem to not load
314 // the vorbis DLL automatically when loading the VorbisFile DLL
315 return Sys_LoadLibrary (dllnames_vo, &vo_dll, vorbisfuncs) && Sys_LoadLibrary (dllnames_vf, &vf_dll, vorbisfilefuncs);
323 Unload the VorbisFile DLL
326 void OGG_CloseLibrary (void)
328 Sys_UnloadLibrary (&vf_dll);
329 Sys_UnloadLibrary (&vo_dll);
335 =================================================================
339 =================================================================
344 unsigned char *buffer;
345 ogg_int64_t ind, buffsize;
348 static size_t ovcb_read (void *ptr, size_t size, size_t nb, void *datasource)
350 ov_decode_t *ov_decode = (ov_decode_t*)datasource;
353 remain = ov_decode->buffsize - ov_decode->ind;
356 len = remain - remain % size;
358 memcpy (ptr, ov_decode->buffer + ov_decode->ind, len);
359 ov_decode->ind += len;
364 static int ovcb_seek (void *datasource, ogg_int64_t offset, int whence)
366 ov_decode_t *ov_decode = (ov_decode_t*)datasource;
373 offset += ov_decode->ind;
376 offset += ov_decode->buffsize;
381 if (offset < 0 || offset > ov_decode->buffsize)
384 ov_decode->ind = offset;
388 static int ovcb_close (void *ov_decode)
393 static long ovcb_tell (void *ov_decode)
395 return ((ov_decode_t*)ov_decode)->ind;
398 // Per-sfx data structure
403 } ogg_stream_persfx_t;
405 // Per-channel data structure
409 ov_decode_t ov_decode;
411 int buffer_firstframe;
412 int buffer_numframes;
413 unsigned char buffer[STREAM_BUFFERSIZE*4];
414 } ogg_stream_perchannel_t;
417 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
424 static void OGG_GetSamplesFloat (channel_t *ch, sfx_t *sfx, int firstsampleframe, int numsampleframes, float *outsamplesfloat)
426 ogg_stream_perchannel_t *per_ch = (ogg_stream_perchannel_t *)ch->fetcher_data;
427 ogg_stream_persfx_t *per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
428 int f = sfx->format.width * sfx->format.channels; // bytes per frame in the buffer
431 int newlength, done, ret;
433 // if this channel does not yet have a channel fetcher, make one
436 // allocate a struct to keep track of our file position and buffer
437 per_ch = (ogg_stream_perchannel_t *)Mem_Alloc(snd_mempool, sizeof(*per_ch));
438 // begin decoding the file
439 per_ch->ov_decode.buffer = per_sfx->file;
440 per_ch->ov_decode.ind = 0;
441 per_ch->ov_decode.buffsize = per_sfx->filesize;
442 if (qov_open_callbacks(&per_ch->ov_decode, &per_ch->vf, NULL, 0, callbacks) < 0)
444 // this never happens - this function succeeded earlier on the same data
449 per_ch->buffer_firstframe = 0;
450 per_ch->buffer_numframes = 0;
451 // attach the struct to our channel
452 ch->fetcher_data = (void *)per_ch;
455 // if the request is too large for our buffer, loop...
456 while (numsampleframes * f > (int)sizeof(per_ch->buffer))
458 done = sizeof(per_ch->buffer) / f;
459 OGG_GetSamplesFloat(ch, sfx, firstsampleframe, done, outsamplesfloat);
460 firstsampleframe += done;
461 numsampleframes -= done;
462 outsamplesfloat += done * sfx->format.channels;
465 // seek if the request is before the current buffer (loop back)
466 // seek if the request starts beyond the current buffer by at least one frame (channel was zero volume for a while)
467 // do not seek if the request overlaps the buffer end at all (expected behavior)
468 if (per_ch->buffer_firstframe > firstsampleframe || per_ch->buffer_firstframe + per_ch->buffer_numframes < firstsampleframe)
470 // we expect to decode forward from here so this will be our new buffer start
471 per_ch->buffer_firstframe = firstsampleframe;
472 per_ch->buffer_numframes = 0;
473 ret = qov_pcm_seek(&per_ch->vf, (ogg_int64_t)firstsampleframe);
476 // LadyHavoc: we can't Con_Printf here, not thread safe...
477 //Con_Printf("OGG_FetchSound: qov_pcm_seek(..., %d) returned %d\n", firstsampleframe, ret);
482 // decompress the file as needed
483 if (firstsampleframe + numsampleframes > per_ch->buffer_firstframe + per_ch->buffer_numframes)
485 // first slide the buffer back, discarding any data preceding the range we care about
486 int offset = firstsampleframe - per_ch->buffer_firstframe;
487 int keeplength = per_ch->buffer_numframes - offset;
489 memmove(per_ch->buffer, per_ch->buffer + offset * sfx->format.width * sfx->format.channels, keeplength * sfx->format.width * sfx->format.channels);
490 per_ch->buffer_firstframe = firstsampleframe;
491 per_ch->buffer_numframes -= offset;
492 // decompress as much as we can fit in the buffer
493 newlength = sizeof(per_ch->buffer) - per_ch->buffer_numframes * f;
495 while (newlength > done && (ret = qov_read(&per_ch->vf, (char *)per_ch->buffer + per_ch->buffer_numframes * f + done, (int)(newlength - done), mem_bigendian, 2, 1, &per_ch->bs)) > 0)
497 // clear the missing space if any
498 if (done < newlength)
499 memset(per_ch->buffer + done, 0, newlength - done);
500 // we now have more data in the buffer
501 per_ch->buffer_numframes += done / f;
504 // convert the sample format for the caller
505 buf = (short *)((char *)per_ch->buffer + (firstsampleframe - per_ch->buffer_firstframe) * f);
506 len = numsampleframes * sfx->format.channels;
507 for (i = 0;i < len;i++)
508 outsamplesfloat[i] = buf[i] * (1.0f / 32768.0f);
517 static void OGG_StopChannel(channel_t *ch)
519 ogg_stream_perchannel_t *per_ch = (ogg_stream_perchannel_t *)ch->fetcher_data;
522 // release the vorbis decompressor
523 qov_clear(&per_ch->vf);
534 static void OGG_FreeSfx(sfx_t *sfx)
536 ogg_stream_persfx_t *per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
537 // free the complete file we were keeping around
538 Mem_Free(per_sfx->file);
539 // free the file information structure
544 static const snd_fetcher_t ogg_fetcher = {OGG_GetSamplesFloat, OGG_StopChannel, OGG_FreeSfx};
546 static void OGG_DecodeTags(vorbis_comment *vc, unsigned int *start, unsigned int *length, unsigned int numsamples, double *peak, double *gaindb)
548 const char *startcomment = NULL, *lengthcomment = NULL, *endcomment = NULL, *thiscomment = NULL;
551 *length = numsamples;
558 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
560 *peak = atof(thiscomment);
561 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
563 *gaindb = atof(thiscomment);
565 startcomment = qvorbis_comment_query(vc, "LOOP_START", 0); // DarkPlaces, and some Japanese app
568 endcomment = qvorbis_comment_query(vc, "LOOP_END", 0);
570 lengthcomment = qvorbis_comment_query(vc, "LOOP_LENGTH", 0);
574 startcomment = qvorbis_comment_query(vc, "LOOPSTART", 0); // RPG Maker VX
577 lengthcomment = qvorbis_comment_query(vc, "LOOPLENGTH", 0);
579 endcomment = qvorbis_comment_query(vc, "LOOPEND", 0);
583 startcomment = qvorbis_comment_query(vc, "LOOPPOINT", 0); // Sonic Robo Blast 2
589 *start = (unsigned int) bound(0, atof(startcomment), numsamples);
591 *length = (unsigned int) bound(0, atof(endcomment), numsamples);
592 else if(lengthcomment)
593 *length = (unsigned int) bound(0, *start + atof(lengthcomment), numsamples);
601 Load an Ogg Vorbis file into memory
604 qbool OGG_LoadVorbisFile(const char *filename, sfx_t *sfx)
607 fs_offset_t filesize;
608 ov_decode_t ov_decode;
614 #ifndef LINK_TO_LIBVORBIS
619 // Return if already loaded
620 if (sfx->fetcher != NULL)
623 // Load the file completely
624 data = FS_LoadFile(filename, snd_mempool, false, &filesize);
628 if (developer_loading.integer >= 2)
629 Con_Printf("Loading Ogg Vorbis file \"%s\"\n", filename);
631 // Open it with the VorbisFile API
632 ov_decode.buffer = data;
634 ov_decode.buffsize = filesize;
635 if (qov_open_callbacks(&ov_decode, &vf, NULL, 0, callbacks) < 0)
637 Con_Printf("error while opening Ogg Vorbis file \"%s\"\n", filename);
642 // Get the stream information
643 vi = qov_info(&vf, -1);
644 if (vi->channels < 1 || vi->channels > 2)
646 Con_Printf("%s has an unsupported number of channels (%i)\n",
647 sfx->name, vi->channels);
653 sfx->format.speed = vi->rate;
654 sfx->format.channels = vi->channels;
655 sfx->format.width = 2; // We always work with 16 bits samples
657 sfx->total_length = qov_pcm_total(&vf, -1);
659 if (snd_streaming.integer && (snd_streaming.integer >= 2 || sfx->total_length > max(sizeof(ogg_stream_perchannel_t), snd_streaming_length.value * sfx->format.speed)))
661 // large sounds use the OGG fetcher to decode the file on demand (but the entire file is held in memory)
662 ogg_stream_persfx_t* per_sfx;
663 if (developer_loading.integer >= 2)
664 Con_Printf("Ogg sound file \"%s\" will be streamed\n", filename);
665 per_sfx = (ogg_stream_persfx_t *)Mem_Alloc(snd_mempool, sizeof(*per_sfx));
666 sfx->memsize += sizeof (*per_sfx);
667 per_sfx->file = data;
668 per_sfx->filesize = filesize;
669 sfx->memsize += filesize;
670 sfx->fetcher_data = per_sfx;
671 sfx->fetcher = &ogg_fetcher;
672 sfx->flags |= SFXFLAG_STREAMED;
673 vc = qov_comment(&vf, -1);
674 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, sfx->total_length, &peak, &gaindb);
679 // small sounds are entirely loaded and use the PCM fetcher
685 if (developer_loading.integer >= 2)
686 Con_Printf ("Ogg sound file \"%s\" will be cached\n", filename);
687 len = sfx->total_length * sfx->format.channels * sfx->format.width;
688 sfx->flags &= ~SFXFLAG_STREAMED;
690 sfx->fetcher = &wav_fetcher;
691 sfx->fetcher_data = Mem_Alloc(snd_mempool, (size_t)len);
692 buff = (char *)sfx->fetcher_data;
695 while ((ret = qov_read(&vf, &buff[done], (int)(len - done), mem_bigendian, 2, 1, &bs)) > 0)
697 vc = qov_comment(&vf, -1);
698 OGG_DecodeTags(vc, &sfx->loopstart, &sfx->total_length, sfx->total_length, &peak, &gaindb);
705 sfx->volume_mult = min(1.0f / peak, exp(gaindb * 0.05f * log(10.0f)));
706 sfx->volume_peak = peak;
707 if (developer_loading.integer >= 2)
708 Con_Printf ("Ogg sound file \"%s\" uses ReplayGain (gain %f, peak %f)\n", filename, sfx->volume_mult, sfx->volume_peak);
712 sfx->volume_mult = min(1.0f / peak, exp(gaindb * 0.05f * log(10.0f)));
713 sfx->volume_peak = 1.0; // if peak is not defined, we won't trust it
714 if (developer_loading.integer >= 2)
715 Con_Printf ("Ogg sound file \"%s\" uses ReplayGain (gain %f, peak not defined and assumed to be %f)\n", filename, sfx->volume_mult, sfx->volume_peak);