File: sox_audio_source.cpp

package info (click to toggle)
chromaprint 0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,312 kB
  • sloc: cpp: 5,218; ansic: 632; python: 164; sh: 79; makefile: 14
file content (71 lines) | stat: -rw-r--r-- 1,371 bytes parent folder | download | duplicates (4)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <algorithm>
#include <limits>
#include "sox_audio_source.h"

using namespace std;

static const size_t kBufferSize = 2 * 4096;
bool SoxAudioSource::initialized_ = false;

SoxAudioSource::SoxAudioSource(const string &file_name)
	: format_(0), file_name_(file_name)
{
	if (!initialized_) {
		sox_init();
		initialized_ = true;
	}
	buffer_ = new sox_sample_t[kBufferSize];
}

SoxAudioSource::~SoxAudioSource()
{
	Close();
	delete[] buffer_;
}

bool SoxAudioSource::Open()
{
	Close();
	format_ = sox_open_read(file_name_.c_str(), NULL, NULL, NULL);
	return format_ != 0;
}

void SoxAudioSource::Close()
{
	if (format_) {
		sox_close(format_);
		format_ = 0;
	}
}

int SoxAudioSource::SampleRate()
{
	return static_cast<int>(format_->signal.rate);
}

int SoxAudioSource::Channels()
{
	return format_->signal.channels;
}

std::size_t SoxAudioSource::Read(short *buffer, std::size_t size)
{
	size_t remaining = size;
	short *ptr = buffer;
	while (remaining > 0) {
		size_t res = sox_read(format_, buffer_, std::min(remaining, kBufferSize));
		if (res == SOX_EOF || res == 0) {
			break;
		}
		int clips = 0;
		for (size_t i = 0; i < res; i++) {
			// XXX assumes that short is 16-bit
			SOX_SAMPLE_LOCALS;
			*ptr++ = SOX_SAMPLE_TO_SIGNED_16BIT(buffer_[i], clips);
		}
		remaining -= res;
	}
	//cout << "read " << size - remaining << "\n";
	return size - remaining;
}