PipeOutputPlugin.cxx 2.01 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "PipeOutputPlugin.hxx"
21
#include "../OutputAPI.hxx"
22
#include "system/Error.hxx"
23

24
#include <string>
25
#include <stdexcept>
26

27 28
#include <stdio.h>

29
class PipeOutput final : AudioOutput {
30
	const std::string cmd;
31
	FILE *fh;
32

Max Kellermann's avatar
Max Kellermann committed
33
	explicit PipeOutput(const ConfigBlock &block);
34

35
public:
36 37 38 39
	static AudioOutput *Create(EventLoop &,
				   const ConfigBlock &block) {
		return new PipeOutput(block);
	}
40

41 42
private:
	void Open(AudioFormat &audio_format) override;
43

44
	void Close() noexcept override {
45 46 47
		pclose(fh);
	}

48
	size_t Play(const void *chunk, size_t size) override;
49 50
};

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

59
inline void
Rosen Penev's avatar
Rosen Penev committed
60
PipeOutput::Open([[maybe_unused]] AudioFormat &audio_format)
61
{
62
	fh = popen(cmd.c_str(), "w");
63 64
	if (fh == nullptr)
		throw FormatErrno("Error opening pipe \"%s\"", cmd.c_str());
65 66
}

67
inline size_t
68
PipeOutput::Play(const void *chunk, size_t size)
69 70 71
{
	size_t nbytes = fwrite(chunk, 1, size, fh);
	if (nbytes == 0)
72
		throw MakeErrno("Write error on pipe");
73 74

	return nbytes;
75 76
}

77
const struct AudioOutputPlugin pipe_output_plugin = {
78 79
	"pipe",
	nullptr,
80
	&PipeOutput::Create,
81
	nullptr,
82
};