summaryrefslogtreecommitdiff
path: root/libs/audiographer/audiographer/sndfile/sndfile_writer.h
blob: d0049360d27c9dc9420a14bd698bccdb4f8b6c0e (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#ifndef AUDIOGRAPHER_SNDFILE_WRITER_H
#define AUDIOGRAPHER_SNDFILE_WRITER_H

#include <string>

#include <boost/format.hpp>

#include "audiographer/flag_debuggable.h"
#include "audiographer/sink.h"
#include "audiographer/types.h"
#include "audiographer/sndfile/sndfile_base.h"
#include "audiographer/broadcast_info.h"

#include "pbd/signals.h"

namespace AudioGrapher
{

/** Writer for audio files using libsndfile.
  * Only short, int and float are valid template parameters
  */
template <typename T = DefaultSampleType>
class SndfileWriter
  : public virtual SndfileBase
  , public Sink<T>
  , public Throwing<>
  , public FlagDebuggable<>
{
  public:
	SndfileWriter (std::string const & path, int format, ChannelCount channels, samplecnt_t samplerate, boost::shared_ptr<BroadcastInfo> broadcast_info)
	  : SndfileHandle (path, Write, format, channels, samplerate)
	  , path (path)
	{
		init();

		if (broadcast_info) {
			broadcast_info->write_to_file (this);
		}
	}

	virtual ~SndfileWriter () {}

	using SndfileHandle::operator=;

	samplecnt_t get_samples_written() const { return samples_written; }
	void       reset_samples_written_count() { samples_written = 0; }

	/// Writes data to file
	virtual void process (ProcessContext<T> const & c)
	{
		check_flags (*this, c);

		if (throw_level (ThrowStrict) && c.channels() != channels()) {
			throw Exception (*this, boost::str (boost::format
				("Wrong number of channels given to process(), %1% instead of %2%")
				% c.channels() % channels()));
		}

		samplecnt_t const written = write (c.data(), c.samples());
		samples_written += written;

		if (throw_level (ThrowProcess) && written != c.samples()) {
			throw Exception (*this, boost::str (boost::format
				("Could not write data to output file (%1%)")
				% strError()));
		}

		if (c.has_flag(ProcessContext<T>::EndOfInput)) {
			writeSync();
			FileWritten (path);
		}
	}

	using Sink<T>::process;

	PBD::Signal1<void, std::string> FileWritten;

  protected:
	/// SndfileHandle has to be constructed directly by deriving classes
	SndfileWriter ()
	{
		init();
	}

	virtual void init()
	{
		samples_written = 0;
		add_supported_flag (ProcessContext<T>::EndOfInput);
	}

  protected:
	std::string path;
	samplecnt_t samples_written;

	private:
	SndfileWriter (SndfileWriter const & other) {}
};

} // namespace

#endif // AUDIOGRAPHER_SNDFILE_WRITER_H