Unified Messaging Subsystem
[supertux.git] / src / audio / sound_file.cpp
1 /** Used SDL_mixer and glest source as reference */
2 #include <config.h>
3
4 #include "sound_file.hpp"
5
6 #include <stdio.h>
7 #include <stdint.h>
8 #include <algorithm>
9 #include <stdexcept>
10 #include <sstream>
11 #include <assert.h>
12 #include <physfs.h>
13 #include <vorbis/codec.h>
14 #include <vorbis/vorbisfile.h>
15 #include "msg.hpp"
16
17 class WavSoundFile : public SoundFile
18 {
19 public:
20   WavSoundFile(PHYSFS_file* file);
21   ~WavSoundFile();
22
23   size_t read(void* buffer, size_t buffer_size);
24   void reset();
25
26 private:
27   PHYSFS_file* file;
28   
29   PHYSFS_sint64 datastart;
30 };
31
32 static inline uint32_t read32LE(PHYSFS_file* file)
33 {
34   uint32_t result;
35   if(PHYSFS_readULE32(file, &result) == 0)
36     throw std::runtime_error("file too short");
37
38   return result;
39 }
40
41 static inline uint16_t read16LE(PHYSFS_file* file)
42 {
43   uint16_t result;
44   if(PHYSFS_readULE16(file, &result) == 0)
45     throw std::runtime_error("file too short");
46
47   return result;
48 }
49
50 WavSoundFile::WavSoundFile(PHYSFS_file* file)
51 {
52   this->file = file;
53
54   char magic[4];
55   if(PHYSFS_read(file, magic, sizeof(magic), 1) != 1)
56     throw std::runtime_error("Couldn't read file magic (not a wave file)");
57   if(strncmp(magic, "RIFF", 4) != 0) {
58     msg_debug("MAGIC: " << magic);
59     throw std::runtime_error("file is not a RIFF wav file");
60   }
61
62   uint32_t wavelen = read32LE(file);
63   (void) wavelen;
64   
65   if(PHYSFS_read(file, magic, sizeof(magic), 1) != 1)
66     throw std::runtime_error("Couldn't read chunk header (not a wav file?)");
67   if(strncmp(magic, "WAVE", 4) != 0)
68     throw std::runtime_error("file is not a valid RIFF/WAVE file");
69
70   char chunkmagic[4];
71   uint32_t chunklen;
72
73   // search audio data format chunk
74   do {
75     if(PHYSFS_read(file, chunkmagic, sizeof(chunkmagic), 1) != 1)
76       throw std::runtime_error("EOF while searching format chunk");    
77     chunklen = read32LE(file);
78     
79     if(strncmp(chunkmagic, "fmt ", 4) == 0)
80       break;
81
82     if(strncmp(chunkmagic, "fact", 4) == 0
83         || strncmp(chunkmagic, "LIST", 4) == 0) {
84       // skip chunk
85       if(PHYSFS_seek(file, PHYSFS_tell(file) + chunklen) == 0)
86         throw std::runtime_error("EOF while searching fmt chunk");
87     } else {
88       throw std::runtime_error("complex WAVE files not supported");
89     }
90   } while(true); 
91
92   if(chunklen < 16)
93     throw std::runtime_error("Format chunk too short");
94  
95   // parse format
96   uint16_t encoding = read16LE(file);
97   if(encoding != 1)
98     throw std::runtime_error("only PCM encoding supported");
99   channels = read16LE(file);
100   rate = read32LE(file);
101   uint32_t byterate = read32LE(file);
102   (void) byterate;
103   uint16_t blockalign = read16LE(file);
104   (void) blockalign;
105   bits_per_sample = read16LE(file);
106
107   if(chunklen > 16) {
108     if(PHYSFS_seek(file, PHYSFS_tell(file) + (chunklen-16)) == 0)
109       throw std::runtime_error("EOF while reading reast of format chunk");
110   }
111
112   // set file offset to DATA chunk data
113   do {
114     if(PHYSFS_read(file, chunkmagic, sizeof(chunkmagic), 1) != 1)
115       throw std::runtime_error("EOF while searching data chunk");    
116     chunklen = read32LE(file);
117
118     if(strncmp(chunkmagic, "data", 4) == 0)
119       break;
120
121     // skip chunk
122     if(PHYSFS_seek(file, PHYSFS_tell(file) + chunklen) == 0)
123       throw std::runtime_error("EOF while searching fmt chunk");
124   } while(true);
125
126   datastart = PHYSFS_tell(file);
127   size = static_cast<size_t> (chunklen);
128 }
129
130 WavSoundFile::~WavSoundFile()
131 {
132   PHYSFS_close(file);
133 }
134
135 void
136 WavSoundFile::reset()
137 {
138   if(PHYSFS_seek(file, datastart) == 0)
139     throw std::runtime_error("Couldn't seek to data start");
140 }
141
142 size_t
143 WavSoundFile::read(void* buffer, size_t buffer_size)
144 {
145   PHYSFS_sint64 end = datastart + size;
146   PHYSFS_sint64 cur = PHYSFS_tell(file);
147   if(cur >= end)
148     return 0;
149   
150   size_t readsize = std::min(static_cast<size_t> (end - cur), buffer_size);
151   if(PHYSFS_read(file, buffer, readsize, 1) != 1)
152     throw std::runtime_error("read error while reading samples");
153
154   return readsize;
155 }
156
157 //---------------------------------------------------------------------------
158
159 class OggSoundFile : public SoundFile
160 {
161 public:
162   OggSoundFile(PHYSFS_file* file);
163   ~OggSoundFile();
164
165   size_t read(void* buffer, size_t buffer_size);
166   void reset();
167
168 private:
169   static size_t cb_read(void* ptr, size_t size, size_t nmemb, void* source);
170   static int cb_seek(void* source, ogg_int64_t offset, int whence);
171   static int cb_close(void* source);
172   static long cb_tell(void* source);
173   
174   PHYSFS_file* file;
175   OggVorbis_File vorbis_file;
176 };
177
178 OggSoundFile::OggSoundFile(PHYSFS_file* file)
179 {
180   this->file = file;
181
182   ov_callbacks callbacks = { cb_read, cb_seek, cb_close, cb_tell };
183   ov_open_callbacks(file, &vorbis_file, 0, 0, callbacks);
184
185   vorbis_info* vi = ov_info(&vorbis_file, -1);
186   channels = vi->channels;
187   rate = vi->rate;
188   bits_per_sample = 16;
189   size = static_cast<size_t> (ov_pcm_total(&vorbis_file, -1) * 2);
190 }
191
192 OggSoundFile::~OggSoundFile()
193 {
194   ov_clear(&vorbis_file);
195 }
196
197 size_t
198 OggSoundFile::read(void* _buffer, size_t buffer_size)
199 {
200   char* buffer = reinterpret_cast<char*> (_buffer);
201   int section = 0;
202   size_t totalBytesRead= 0;
203
204   while(buffer_size>0){
205     long bytesRead 
206       = ov_read(&vorbis_file, buffer, static_cast<int> (buffer_size), 0, 2, 1,
207           &section);
208     if(bytesRead==0){
209       break;
210     }
211     buffer_size -= bytesRead;
212     buffer += bytesRead;
213     totalBytesRead += bytesRead;
214   }
215   
216   return totalBytesRead;
217 }
218
219 void
220 OggSoundFile::reset()
221 {
222   ov_raw_seek(&vorbis_file, 0);
223 }
224
225 size_t
226 OggSoundFile::cb_read(void* ptr, size_t size, size_t nmemb, void* source)
227 {
228   PHYSFS_file* file = reinterpret_cast<PHYSFS_file*> (source);
229   
230   PHYSFS_sint64 res 
231     = PHYSFS_read(file, ptr, static_cast<PHYSFS_uint32> (size),
232         static_cast<PHYSFS_uint32> (nmemb));
233   if(res <= 0)
234     return 0;
235
236   return static_cast<size_t> (res);
237 }
238
239 int
240 OggSoundFile::cb_seek(void* source, ogg_int64_t offset, int whence)
241 {
242   PHYSFS_file* file = reinterpret_cast<PHYSFS_file*> (source);
243
244   switch(whence) {
245     case SEEK_SET:
246       if(PHYSFS_seek(file, static_cast<PHYSFS_uint64> (offset)) == 0)
247         return -1;
248       break;
249     case SEEK_CUR:
250       if(PHYSFS_seek(file, PHYSFS_tell(file) + offset) == 0)
251         return -1;
252       break;
253     case SEEK_END:
254       if(PHYSFS_seek(file, PHYSFS_fileLength(file) + offset) == 0)
255         return -1;
256       break;
257     default:
258 #ifdef DEBUG
259       assert(false);
260 #else
261       return -1;
262 #endif
263   }
264   return 0;
265 }
266   
267 int
268 OggSoundFile::cb_close(void* source)
269 {
270   PHYSFS_file* file = reinterpret_cast<PHYSFS_file*> (source);
271   PHYSFS_close(file);
272   return 0;
273 }
274
275 long
276 OggSoundFile::cb_tell(void* source)
277 {
278   PHYSFS_file* file = reinterpret_cast<PHYSFS_file*> (source);
279   return static_cast<long> (PHYSFS_tell(file));
280 }
281
282 //---------------------------------------------------------------------------
283
284 #include <fstream>
285 SoundFile* load_sound_file(const std::string& filename)
286 {
287   PHYSFS_file* file = PHYSFS_openRead(filename.c_str());
288   if(!file) {
289     std::stringstream msg;
290     msg << "Couldn't open '" << filename << "': " << PHYSFS_getLastError();
291     throw std::runtime_error(msg.str());
292   }
293     
294   try {
295     char magic[4];
296     if(PHYSFS_read(file, magic, sizeof(magic), 1) != 1)
297       throw std::runtime_error("Couldn't read magic, file too short");
298     PHYSFS_seek(file, 0);
299     if(strncmp(magic, "RIFF", 4) == 0)
300       return new WavSoundFile(file);
301     else if(strncmp(magic, "OggS", 4) == 0)
302       return new OggSoundFile(file);
303     else
304       throw std::runtime_error("Unknown file format");
305   } catch(std::exception& e) {
306     std::stringstream msg;
307     msg << "Couldn't read '" << filename << "': " << e.what();
308     throw std::runtime_error(msg.str());
309   }
310 }
311