PipeOutputPlugin.cxx 2.28 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h"
21
#include "PipeOutputPlugin.hxx"
22
#include "../OutputAPI.hxx"
23
#include "../Wrapper.hxx"
24
#include "system/Error.hxx"
25

26
#include <string>
27
#include <stdexcept>
28

29 30
#include <stdio.h>

31
class PipeOutput {
32
	friend struct AudioOutputWrapper<PipeOutput>;
33

34
	AudioOutput base;
35

36
	const std::string cmd;
37
	FILE *fh;
38

39
	PipeOutput(const ConfigBlock &block);
40

41
public:
42
	static PipeOutput *Create(const ConfigBlock &block);
43

44
	void Open(AudioFormat &audio_format);
45 46 47 48 49

	void Close() {
		pclose(fh);
	}

50
	size_t Play(const void *chunk, size_t size);
51 52
};

53 54 55
PipeOutput::PipeOutput(const ConfigBlock &block)
	:base(pipe_output_plugin, block),
	 cmd(block.GetBlockValue("command", ""))
56
{
57 58
	if (cmd.empty())
		throw std::runtime_error("No \"command\" parameter specified");
59 60
}

61
inline PipeOutput *
62
PipeOutput::Create(const ConfigBlock &block)
63
{
64
	return new PipeOutput(block);
65 66
}

67 68
inline void
PipeOutput::Open(gcc_unused AudioFormat &audio_format)
69
{
70
	fh = popen(cmd.c_str(), "w");
71 72
	if (fh == nullptr)
		throw FormatErrno("Error opening pipe \"%s\"", cmd.c_str());
73 74
}

75
inline size_t
76
PipeOutput::Play(const void *chunk, size_t size)
77 78 79
{
	size_t nbytes = fwrite(chunk, 1, size, fh);
	if (nbytes == 0)
80
		throw MakeErrno("Write error on pipe");
81 82

	return nbytes;
83 84
}

85
typedef AudioOutputWrapper<PipeOutput> Wrapper;
86

87
const struct AudioOutputPlugin pipe_output_plugin = {
88 89
	"pipe",
	nullptr,
90 91
	&Wrapper::Init,
	&Wrapper::Finish,
92 93
	nullptr,
	nullptr,
94 95
	&Wrapper::Open,
	&Wrapper::Close,
96 97
	nullptr,
	nullptr,
98
	&Wrapper::Play,
99 100 101 102
	nullptr,
	nullptr,
	nullptr,
	nullptr,
103
};