summaryrefslogtreecommitdiff
path: root/decoders/mpg123_decoder.cpp
blob: 13e9861c861e6147bb4641169a1022a2e3be34a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "mpg123_decoder.h"

#include <boost/format.hpp>

#include <iostream>
#include <stdexcept>

DecoderMpg123::DecoderMpg123(const std::string& filename) {
	int error;
	handle = mpg123_new("generic", &error);
	if(error) {
		throw std::runtime_error(mpg123_plain_strerror(error));
	}

	error = mpg123_open(handle, filename.c_str());
	if(error) {
		throw std::runtime_error(mpg123_plain_strerror(error));
	}

	long rate;
	int channels, enc;
	mpg123_getformat(handle, &rate, &channels, &enc);
	std::cout << boost::format("mpg123: %li Hz, %i channels, encoding value %i") % rate % channels % enc << std::endl;
	this->samplerate = rate;
	this->channels = channels;

	mpg123_format_none(handle);
	mpg123_format(handle, rate, channels, MPG123_ENC_SIGNED_16);
}

DecoderMpg123::~DecoderMpg123() {
	mpg123_close(handle);
	mpg123_delete(handle);
}

std::size_t DecoderMpg123::read(char* buf, std::size_t buf_size) {
	char src_data[0x2000];
	int error = MPG123_NEED_MORE;
	size_t output_written;

	error = mpg123_read(handle, (unsigned char*)buf, buf_size, &output_written);

	if(error == MPG123_NEW_FORMAT) {
		long rate;
		int channels, enc;
		mpg123_getformat(handle, &rate, &channels, &enc);
		std::cout << boost::format("mpg123: New format: %li Hz, %i channels, encoding value %i") % rate % channels % enc << std::endl;
		error = mpg123_read(handle, (unsigned char*)buf, buf_size, &output_written);
	}

	if(error != MPG123_OK && error != MPG123_DONE) {
		throw std::runtime_error(mpg123_plain_strerror(error));
	}

	return output_written;
}