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
32 =================================================================
34 Minimal set of definitions from the Ogg Vorbis lib
35 (C) COPYRIGHT 1994-2001 by the XIPHOPHORUS Company
38 WARNING: for a matter of simplicity, several pointer types are
39 casted to "void*", and most enumerated values are not included
41 =================================================================
45 typedef __int64 ogg_int64_t;
47 typedef long long ogg_int64_t;
52 size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
53 int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
54 int (*close_func) (void *datasource);
55 long (*tell_func) (void *datasource);
83 unsigned char *body_data;
88 ogg_int64_t *granule_vals;
93 unsigned char header[282];
100 ogg_int64_t granulepos;
118 ogg_int64_t granulepos;
119 ogg_int64_t sequence;
120 ogg_int64_t glue_bits;
121 ogg_int64_t time_bits;
122 ogg_int64_t floor_bits;
123 ogg_int64_t res_bits;
131 unsigned char *buffer;
146 ogg_int64_t granulepos;
147 ogg_int64_t sequence;
148 vorbis_dsp_state *vd;
153 void *reap; // VOIDED POINTER
163 char **user_comments;
164 int *comment_lengths;
177 ogg_int64_t *offsets;
178 ogg_int64_t *dataoffsets;
180 ogg_int64_t *pcmlengths;
183 ogg_int64_t pcm_offset;
185 long current_serialno;
192 ov_callbacks callbacks;
197 =================================================================
199 DarkPlaces definitions
201 =================================================================
204 // Functions exported from the vorbisfile library
205 static int (*qov_clear) (OggVorbis_File *vf);
206 static vorbis_info* (*qov_info) (OggVorbis_File *vf,int link);
207 static vorbis_comment* (*qov_comment) (OggVorbis_File *vf,int link);
208 static char * (*qvorbis_comment_query) (vorbis_comment *vc, char *tag, int count);
209 static int (*qov_open_callbacks) (void *datasource, OggVorbis_File *vf,
210 char *initial, long ibytes,
211 ov_callbacks callbacks);
212 static int (*qov_pcm_seek) (OggVorbis_File *vf,ogg_int64_t pos);
213 static ogg_int64_t (*qov_pcm_total) (OggVorbis_File *vf,int i);
214 static long (*qov_read) (OggVorbis_File *vf,char *buffer,int length,
215 int bigendianp,int word,int sgned,int *bitstream);
217 static dllfunction_t vorbisfilefuncs[] =
219 {"ov_clear", (void **) &qov_clear},
220 {"ov_info", (void **) &qov_info},
221 {"ov_comment", (void **) &qov_comment},
222 {"ov_open_callbacks", (void **) &qov_open_callbacks},
223 {"ov_pcm_seek", (void **) &qov_pcm_seek},
224 {"ov_pcm_total", (void **) &qov_pcm_total},
225 {"ov_read", (void **) &qov_read},
229 static dllfunction_t vorbisfuncs[] =
231 {"vorbis_comment_query", (void **) &qvorbis_comment_query},
235 // Handles for the Vorbis and Vorbisfile DLLs
236 static dllhandle_t vo_dll = NULL;
237 static dllhandle_t vf_dll = NULL;
241 unsigned char *buffer;
242 ogg_int64_t ind, buffsize;
246 static size_t ovcb_read (void *ptr, size_t size, size_t nb, void *datasource)
248 ov_decode_t *ov_decode = (ov_decode_t*)datasource;
251 remain = ov_decode->buffsize - ov_decode->ind;
254 len = remain - remain % size;
256 memcpy (ptr, ov_decode->buffer + ov_decode->ind, len);
257 ov_decode->ind += len;
262 static int ovcb_seek (void *datasource, ogg_int64_t offset, int whence)
264 ov_decode_t *ov_decode = (ov_decode_t*)datasource;
271 offset += ov_decode->ind;
274 offset += ov_decode->buffsize;
279 if (offset < 0 || offset > ov_decode->buffsize)
282 ov_decode->ind = offset;
286 static int ovcb_close (void *ov_decode)
291 static long ovcb_tell (void *ov_decode)
293 return ((ov_decode_t*)ov_decode)->ind;
298 =================================================================
302 =================================================================
309 Try to load the VorbisFile DLL
312 qboolean OGG_OpenLibrary (void)
314 const char* dllnames_vo [] =
321 #elif defined(MACOSX)
329 const char* dllnames_vf [] =
332 "libvorbisfile64.dll",
336 #elif defined(MACOSX)
337 "libvorbisfile.dylib",
339 "libvorbisfile.so.3",
349 // COMMANDLINEOPTION: Sound: -novorbis disables ogg vorbis sound support
350 if (COM_CheckParm("-novorbis"))
354 // We need to load both by hand because some OSes seem to not load
355 // the vorbis DLL automatically when loading the VorbisFile DLL
356 if (! Sys_LoadLibrary (dllnames_vo, &vo_dll, vorbisfuncs) ||
357 ! Sys_LoadLibrary (dllnames_vf, &vf_dll, vorbisfilefuncs))
359 Sys_UnloadLibrary (&vo_dll);
360 Con_Printf ("Ogg Vorbis support disabled\n");
364 Con_Printf ("Ogg Vorbis support enabled\n");
373 Unload the VorbisFile DLL
376 void OGG_CloseLibrary (void)
378 Sys_UnloadLibrary (&vf_dll);
379 Sys_UnloadLibrary (&vo_dll);
384 =================================================================
388 =================================================================
391 #define STREAM_BUFFER_DURATION 1.5f // 1.5 sec
392 #define STREAM_BUFFER_SIZE(format_ptr) ((int)(ceil (STREAM_BUFFER_DURATION * ((format_ptr)->speed * (format_ptr)->width * (format_ptr)->channels))))
394 // We work with 1 sec sequences, so this buffer must be able to contain
395 // 1 sec of sound of the highest quality (48 KHz, 16 bit samples, stereo)
396 static unsigned char resampling_buffer [48000 * 2 * 2];
399 // Per-sfx data structure
405 unsigned int total_length;
407 } ogg_stream_persfx_t;
409 // Per-channel data structure
413 ov_decode_t ov_decode;
414 unsigned int sb_offset;
416 snd_buffer_t sb; // must be at the end due to its dynamically allocated size
417 } ogg_stream_perchannel_t;
420 static const ov_callbacks callbacks = {ovcb_read, ovcb_seek, ovcb_close, ovcb_tell};
427 static const snd_buffer_t* OGG_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes)
429 ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)*chfetcherpointer;
430 ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcher;
432 int newlength, done, ret, bigendian;
433 unsigned int real_start;
436 // If there's no fetcher structure attached to the channel yet
439 size_t buff_len, memsize;
440 snd_format_t sb_format;
442 sb_format.speed = snd_renderbuffer->format.speed;
443 sb_format.width = per_sfx->format.width;
444 sb_format.channels = per_sfx->format.channels;
446 buff_len = STREAM_BUFFER_SIZE(&sb_format);
447 memsize = sizeof (*per_ch) - sizeof (per_ch->sb.samples) + buff_len;
448 per_ch = (ogg_stream_perchannel_t *)Mem_Alloc (snd_mempool, memsize);
450 // Open it with the VorbisFile API
451 per_ch->ov_decode.buffer = per_sfx->file;
452 per_ch->ov_decode.ind = 0;
453 per_ch->ov_decode.buffsize = per_sfx->filesize;
454 if (qov_open_callbacks (&per_ch->ov_decode, &per_ch->vf, NULL, 0, callbacks) < 0)
456 Con_Printf("error while reading Ogg Vorbis stream \"%s\"\n", per_sfx->name);
462 per_ch->sb_offset = 0;
463 per_ch->sb.format = sb_format;
464 per_ch->sb.nbframes = 0;
465 per_ch->sb.maxframes = buff_len / (per_ch->sb.format.channels * per_ch->sb.format.width);
467 *chfetcherpointer = per_ch;
473 factor = per_sfx->format.width * per_sfx->format.channels;
475 // If the stream buffer can't contain that much samples anyway
476 if (nbsampleframes > sb->maxframes)
478 Con_Printf ("OGG_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes);
482 // If the data we need has already been decompressed in the sfxbuffer, just return it
483 if (per_ch->sb_offset <= real_start && per_ch->sb_offset + sb->nbframes >= real_start + nbsampleframes)
485 *start = per_ch->sb_offset;
489 newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start;
491 // If we need to skip some data before decompressing the rest, or if the stream has looped
492 if (newlength < 0 || per_ch->sb_offset > real_start)
494 unsigned int time_start;
495 ogg_int64_t ogg_start;
498 if (real_start > (unsigned int)per_sfx->total_length)
500 Con_Printf ("OGG_FetchSound: asked for a start position after the end of the sfx! (%u > %u)\n",
501 real_start, per_sfx->total_length);
505 // We work with 200ms (1/5 sec) steps to avoid rounding errors
506 time_start = real_start * 5 / snd_renderbuffer->format.speed;
507 ogg_start = time_start * (per_sfx->format.speed / 5);
508 err = qov_pcm_seek (&per_ch->vf, ogg_start);
511 Con_Printf ("OGG_FetchSound: qov_pcm_seek(..., %d) returned %d\n",
517 real_start = (float)ogg_start / per_sfx->format.speed * snd_renderbuffer->format.speed;
518 if (*start - real_start + nbsampleframes > sb->maxframes)
520 Con_Printf ("OGG_FetchSound: stream buffer too small after seek (%u sample frames required)\n",
521 *start - real_start + nbsampleframes);
522 per_ch->sb_offset = real_start;
526 // Else, move forward the samples we need to keep in the sound buffer
529 memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor);
530 sb->nbframes = newlength;
533 per_ch->sb_offset = real_start;
535 // We add exactly 1 sec of sound to the buffer:
536 // 1- to ensure we won't lose any sample during the resampling process
537 // 2- to force one call to OGG_FetchSound per second to regulate the workload
538 if (sb->format.speed + sb->nbframes > sb->maxframes)
540 Con_Printf ("OGG_FetchSound: stream buffer overflow (%u sample frames / %u)\n",
541 sb->format.speed + sb->nbframes, sb->maxframes);
544 newlength = per_sfx->format.speed * factor; // -> 1 sec of sound before resampling
545 if(newlength > (int)sizeof(resampling_buffer))
546 newlength = sizeof(resampling_buffer);
548 // Decompress in the resampling_buffer
549 #if BYTE_ORDER == BIG_ENDIAN
555 while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), bigendian, 2, 1, &per_ch->bs)) > 0)
558 Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
560 *start = per_ch->sb_offset;
570 static void OGG_FetchEnd (void *chfetcherdata)
572 ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)chfetcherdata;
576 // Free the ogg vorbis decoder
577 qov_clear (&per_ch->vf);
589 static void OGG_FreeSfx (void *sfxfetcherdata)
591 ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcherdata;
593 // Free the Ogg Vorbis file
594 Mem_Free(per_sfx->file);
596 // Free the stream structure
606 static const snd_format_t* OGG_GetFormat (sfx_t* sfx)
608 ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfx->fetcher_data;
609 return &per_sfx->format;
612 static const snd_fetcher_t ogg_fetcher = { OGG_FetchSound, OGG_FetchEnd, OGG_FreeSfx, OGG_GetFormat };
619 Load an Ogg Vorbis file into memory
622 qboolean OGG_LoadVorbisFile (const char *filename, sfx_t *sfx)
625 const char *thiscomment;
626 fs_offset_t filesize;
627 ov_decode_t ov_decode;
631 ogg_int64_t len, buff_len;
640 if (sfx->fetcher != NULL)
644 data = FS_LoadFile (filename, snd_mempool, false, &filesize);
648 Con_DPrintf ("Loading Ogg Vorbis file \"%s\"\n", filename);
650 // Open it with the VorbisFile API
651 ov_decode.buffer = data;
653 ov_decode.buffsize = filesize;
654 if (qov_open_callbacks (&ov_decode, &vf, NULL, 0, callbacks) < 0)
656 Con_Printf ("error while opening Ogg Vorbis file \"%s\"\n", filename);
661 // Get the stream information
662 vi = qov_info (&vf, -1);
663 if (vi->channels < 1 || vi->channels > 2)
665 Con_Printf("%s has an unsupported number of channels (%i)\n",
666 sfx->name, vi->channels);
672 len = qov_pcm_total (&vf, -1) * vi->channels * 2; // 16 bits => "* 2"
674 // Decide if we go for a stream or a simple PCM cache
675 buff_len = (int)ceil (STREAM_BUFFER_DURATION * (snd_renderbuffer->format.speed * 2 * vi->channels));
676 if (snd_streaming.integer && len > (ogg_int64_t)filesize + 3 * buff_len)
678 ogg_stream_persfx_t* per_sfx;
680 Con_DPrintf ("\"%s\" will be streamed\n", filename);
681 per_sfx = (ogg_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx));
682 strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name));
683 sfx->memsize += sizeof (*per_sfx);
684 per_sfx->file = data;
685 per_sfx->filesize = filesize;
686 sfx->memsize += filesize;
688 per_sfx->format.speed = vi->rate;
689 per_sfx->format.width = 2; // We always work with 16 bits samples
690 per_sfx->format.channels = vi->channels;
692 sfx->fetcher_data = per_sfx;
693 sfx->fetcher = &ogg_fetcher;
694 sfx->flags |= SFXFLAG_STREAMED;
695 per_sfx->total_length = sfx->total_length = (int)((size_t)len / (per_sfx->format.channels * 2) * ((double)snd_renderbuffer->format.speed / per_sfx->format.speed));
696 sfx->loopstart = sfx->total_length;
697 vc = qov_comment(&vf, -1);
700 thiscomment = qvorbis_comment_query(vc, "LOOP_START", 0);
702 sfx->loopstart = bound(0, (unsigned int) (atof(thiscomment) * (double)snd_renderbuffer->format.speed / (double)per_sfx->format.speed), sfx->total_length);
703 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
705 peak = atof(thiscomment);
706 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
708 gaindb = atof(thiscomment);
718 snd_format_t ogg_format;
720 Con_DPrintf ("\"%s\" will be cached\n", filename);
723 buff = (char *)Mem_Alloc (snd_mempool, (int)len);
726 #if BYTE_ORDER == BIG_ENDIAN
731 while ((ret = qov_read (&vf, &buff[done], (int)(len - done), bigendian, 2, 1, &bs)) > 0)
734 // Build the sound buffer
735 ogg_format.speed = vi->rate;
736 ogg_format.channels = vi->channels;
737 ogg_format.width = 2; // We always work with 16 bits samples
738 sb = Snd_CreateSndBuffer ((unsigned char *)buff, (size_t)done / (vi->channels * 2), &ogg_format, snd_renderbuffer->format.speed);
747 sfx->fetcher = &wav_fetcher;
748 sfx->fetcher_data = sb;
750 sfx->total_length = sb->nbframes;
751 sfx->memsize += sb->maxframes * sb->format.channels * sb->format.width + sizeof (*sb) - sizeof (sb->samples);
753 sfx->loopstart = sfx->total_length;
754 sfx->flags &= ~SFXFLAG_STREAMED;
755 vc = qov_comment(&vf, -1);
758 thiscomment = qvorbis_comment_query(vc, "LOOP_START", 0);
760 sfx->loopstart = bound(0, (unsigned int) (atoi(thiscomment) * (double)snd_renderbuffer->format.speed / (double)sb->format.speed), sfx->total_length);
761 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_PEAK", 0);
763 peak = atof(thiscomment);
764 thiscomment = qvorbis_comment_query(vc, "REPLAYGAIN_TRACK_GAIN", 0);
766 gaindb = atof(thiscomment);
776 sfx->volume_mult = min(1 / peak, exp(gaindb * 0.05 * log(10)));
777 sfx->volume_peak = peak;
778 Con_DPrintf ("\"%s\" uses ReplayGain (gain %f, peak %f)\n", filename, sfx->volume_mult, sfx->volume_peak);