]> git.tdb.fi Git - libs/al.git/blob - source/sounddecoder.cpp
Seek back to beginning after reading signature
[libs/al.git] / source / sounddecoder.cpp
1 #include <msp/core/refptr.h>
2 #include <msp/io/file.h>
3 #include <msp/strings/format.h>
4 #include "mp3decoder.h"
5 #include "oggdecoder.h"
6 #include "sounddecoder.h"
7
8 using namespace std;
9
10 namespace Msp {
11 namespace AL {
12
13 unsupported_sound::unsupported_sound(const string &w):
14         runtime_error(w)
15 { }
16
17
18 SoundDecoder::SoundDecoder():
19         source(0),
20         freq(0),
21         size(0),
22         format(MONO8),
23         eof_flag(false)
24 { }
25
26 SoundDecoder::~SoundDecoder()
27 {
28         delete source;
29 }
30
31 SoundDecoder *SoundDecoder::open_file(const string &fn)
32 {
33         RefPtr<IO::BufferedFile> file = new IO::BufferedFile(fn);
34         SoundDecoder *decoder = open_io(*file);
35         decoder->source = file.release();
36         return decoder;
37 }
38
39 SoundDecoder *SoundDecoder::open_io(IO::Seekable &io)
40 {
41         char sig_buf[8];
42         io.read(sig_buf, sizeof(sig_buf));
43         io.seek(0, IO::S_BEG);
44         string signature(sig_buf, sizeof(sig_buf));
45         if(OggDecoder::detect(signature))
46                 return new OggDecoder(io);
47         else if(Mp3Decoder::detect(signature))
48                 return new Mp3Decoder(io);
49         else
50         {
51                 string sig_hex;
52                 for(unsigned i=0; i<sizeof(sig_buf); ++i)
53                 {
54                         if(i)
55                                 sig_hex += ' ';
56                         sig_hex += Msp::format("%02X", static_cast<unsigned char>(sig_buf[i]));
57                 }
58                 throw unsupported_sound(sig_hex);
59         }
60 }
61
62 } // namespace AL
63 } // namespace Msp