3 #include "sounddecoder.h"
15 MemorySource(const void *d, unsigned l): data(d), length(l), pos(0) { }
18 size_t memory_read(void *ptr, size_t size, size_t nmemb, void *src)
20 MemorySource &memsrc = *reinterpret_cast<MemorySource *>(src);
21 unsigned len = min<unsigned>(size*nmemb, memsrc.length-memsrc.pos);
22 memcpy(ptr, reinterpret_cast<const char *>(memsrc.data)+memsrc.pos, len);
28 int memory_seek(void *src, ogg_int64_t offset, int whence)
30 MemorySource &memsrc = *reinterpret_cast<MemorySource *>(src);
33 else if(whence==SEEK_CUR)
35 else if(whence==SEEK_END)
36 memsrc.pos = memsrc.length-offset;
37 memsrc.pos = min(memsrc.pos, memsrc.length);
42 int memory_close(void *src)
44 delete reinterpret_cast<MemorySource *>(src);
48 long memory_tell(void *src)
50 MemorySource &memsrc = *reinterpret_cast<MemorySource *>(src);
54 ov_callbacks memory_callbacks=
67 SoundDecoder::SoundDecoder():
70 ovfile.datasource = 0;
73 SoundDecoder::~SoundDecoder()
79 void SoundDecoder::open_file(const string &fn)
82 throw logic_error("Sound has already been opened");
83 if(ov_fopen(const_cast<char *>(fn.c_str()), &ovfile)<0)
84 throw runtime_error("Could not open ogg vorbis file "+fn);
89 void SoundDecoder::open_memory(const void *d, unsigned len)
92 throw logic_error("Sound has already been opened");
94 MemorySource *src = new MemorySource(d, len);
95 if(ov_open_callbacks(src, &ovfile, 0, 0, memory_callbacks)<0)
98 throw runtime_error("Could not open ogg vorbis memory block");
104 void SoundDecoder::open_common()
106 vorbis_info *info = ov_info(&ovfile, -1);
109 size = ov_pcm_total(&ovfile, 0)*info->channels*2;
111 switch(info->channels)
113 case 1: format = MONO16; break;
114 case 2: format = STEREO16; break;
115 default: throw runtime_error("Unsupported number of channels");
119 void SoundDecoder::close()
121 if(ovfile.datasource)
125 void SoundDecoder::rewind()
127 ov_pcm_seek(&ovfile, 0);
130 unsigned SoundDecoder::read(char *buf, unsigned len)
133 int res = ov_read(&ovfile, buf, len, 0, 2, 1, §ion);
135 throw runtime_error("Error reading ogg vorbis file");