summaryrefslogtreecommitdiff
path: root/src/lib/external_audio_decoder.cc
blob: 99dd1ded0062ad3c77a136f0452d383077f4c97c (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <sndfile.h>
#include "external_audio_decoder.h"
#include "film.h"
#include "exceptions.h"

using std::vector;
using std::string;
using std::min;
using boost::shared_ptr;

ExternalAudioDecoder::ExternalAudioDecoder (shared_ptr<Film> f, shared_ptr<const Options> o, Job* j)
	: Decoder (f, o, j)
	, AudioDecoder (f, o, j)
{

}

bool
ExternalAudioDecoder::pass ()
{
	vector<string> const files = _film->external_audio ();

	int N = 0;
	for (size_t i = 0; i < files.size(); ++i) {
		if (!files[i].empty()) {
			N = i + 1;
		}
	}

	if (N == 0) {
		return true;
	}

	bool first = true;
	sf_count_t frames = 0;
	
	vector<SNDFILE*> sndfiles;
	for (vector<string>::const_iterator i = files.begin(); i != files.end(); ++i) {
		if (i->empty ()) {
			sndfiles.push_back (0);
		} else {
			SF_INFO info;
			SNDFILE* s = sf_open (i->c_str(), SFM_READ, &info);
			if (!s) {
				throw DecodeError ("could not open external audio file for reading");
			}

			if (info.channels != 1) {
				throw DecodeError ("external audio files must be mono");
			}
			
			sndfiles.push_back (s);

			if (first) {
				/* XXX: nasty magic value */
				AudioStream st ("DVDOMATIC-EXTERNAL", -1, info.samplerate, av_get_default_channel_layout (info.channels));
				_audio_streams.push_back (st);
				_audio_stream = st;
				frames = info.frames;
				first = false;
			} else {
				if (info.frames != frames) {
					throw DecodeError ("external audio files have differing lengths");
				}
			}
		}
	}

	sf_count_t const block = 65536;

	shared_ptr<AudioBuffers> audio (new AudioBuffers (_audio_stream.get().channels(), block));
	while (frames > 0) {
		sf_count_t const this_time = min (block, frames);
		for (size_t i = 0; i < sndfiles.size(); ++i) {
			if (!sndfiles[i]) {
				audio->make_silent (i);
			} else {
				sf_read_float (sndfiles[i], audio->data(i), block);
			}
		}

		Audio (audio);
		frames -= this_time;
	}
	
	return true;
}