3 This file is part of libmspal
4 Copyright © 2008 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
9 #include <msp/core/except.h>
22 MemorySource(const void *d, unsigned l): data(d), length(l), pos(0) { }
25 size_t memory_read(void *ptr, size_t size, size_t nmemb, void *src)
27 MemorySource &memsrc=*reinterpret_cast<MemorySource *>(src);
28 unsigned len=min(size*nmemb, memsrc.length-memsrc.pos);
29 memcpy(ptr, reinterpret_cast<const char *>(memsrc.data)+memsrc.pos, len);
35 int memory_seek(void *src, ogg_int64_t offset, int whence)
37 MemorySource &memsrc=*reinterpret_cast<MemorySource *>(src);
40 else if(whence==SEEK_CUR)
42 else if(whence==SEEK_END)
43 memsrc.pos=memsrc.length-offset;
44 memsrc.pos=min(memsrc.pos, memsrc.length);
49 void memory_close(void *src)
51 delete reinterpret_cast<MemorySource *>(src);
54 long memory_tell(void *src)
56 MemorySource &memsrc=*reinterpret_cast<MemorySource *>(src);
60 ov_callbacks memory_callbacks=
87 void Sound::open_file(const string &fn)
90 throw InvalidState("Sound has already been opened");
91 if(ov_fopen(const_cast<char *>(fn.c_str()), &ovfile)<0)
92 throw Exception("Could not open ogg vorbis file "+fn);
97 void Sound::open_memory(const void *d, unsigned len)
100 throw InvalidState("Sound has already been opened");
102 MemorySource *src=new MemorySource(d, len);
103 if(ov_open_callbacks(src, &ovfile, 0, 0, memory_callbacks)<0)
106 throw Exception("Could not open ogg vorbis memory block");
112 void Sound::load_data()
115 throw InvalidState("Data has already been loaded");
117 size=ov_pcm_total(&ovfile, 0)*4;
118 char *dptr=new char[size];
120 while(unsigned len=read(dptr+pos, size-pos))
127 void Sound::load_file(const std::string &fn)
134 void Sound::load_memory(const void *d, unsigned len)
143 if(ovfile.datasource)
152 ov_pcm_seek(&ovfile, 0);
155 unsigned Sound::read(char *buf, unsigned len)
159 len=min(len, size-read_pos);
160 memcpy(buf, data+read_pos, len);
164 else if(ovfile.datasource)
167 int res=ov_read(&ovfile, buf, len, 0, 2, 1, §ion);
169 throw Exception("Error reading ogg vorbis file");
175 throw InvalidState("No data available");
178 const char *Sound::get_data() const
181 throw InvalidState("Data has not been loaded");
185 void Sound::open_common()
190 vorbis_info *info=ov_info(&ovfile, -1);
192 switch(info->channels)
194 case 1: format=MONO16; break;
195 case 2: format=STEREO16; break;
196 default: throw Exception("Unsupported number of channels");