PipeOutputPlugin.cxx 2.33 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 43
	static PipeOutput *Create(EventLoop &event_loop,
				  const ConfigBlock &block);
44

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

	void Close() {
		pclose(fh);
	}

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

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

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

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

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

	return nbytes;
84 85
}

86
typedef AudioOutputWrapper<PipeOutput> Wrapper;
87

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