FfmpegFilter.cxx 2.61 KB
Newer Older
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
/*
 * Copyright 2003-2019 The Music Player Daemon Project
 * 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.
 *
 * 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.
 */

#include "FfmpegFilter.hxx"
#include "lib/ffmpeg/SampleFormat.hxx"
#include "util/ConstBuffer.hxx"

extern "C" {
#include <libavfilter/buffersrc.h>
#include <libavfilter/buffersink.h>
}

29 30
#include <string.h>

31 32 33 34 35 36 37 38 39
FfmpegFilter::FfmpegFilter(const AudioFormat &in_audio_format,
			   const AudioFormat &_out_audio_format,
			   Ffmpeg::FilterGraph &&_graph,
			   Ffmpeg::FilterContext &&_buffer_src,
			   Ffmpeg::FilterContext &&_buffer_sink) noexcept
	:Filter(_out_audio_format),
	 graph(std::move(_graph)),
	 buffer_src(std::move(_buffer_src)),
	 buffer_sink(std::move(_buffer_sink)),
40 41 42
	 in_format(Ffmpeg::ToFfmpegSampleFormat(in_audio_format.format)),
	 in_sample_rate(in_audio_format.sample_rate),
	 in_channels(in_audio_format.channels),
43 44 45 46 47 48 49 50 51 52
	 in_audio_frame_size(in_audio_format.GetFrameSize()),
	 out_audio_frame_size(_out_audio_format.GetFrameSize())
{
}

ConstBuffer<void>
FfmpegFilter::FilterPCM(ConstBuffer<void> src)
{
	/* submit source data into the FFmpeg audio buffer source */

53 54 55 56 57
	frame.Unref();
	frame->format = in_format;
	frame->sample_rate = in_sample_rate;
	frame->channels = in_channels;
	frame->nb_samples = src.size / in_audio_frame_size;
58

59
	frame.GetBuffer();
60

61
	memcpy(frame.GetData(0), src.data, src.size);
62

63
	int err = av_buffersrc_add_frame(buffer_src.get(), frame.get());
64 65 66 67 68
	if (err < 0)
		throw MakeFfmpegError(err, "av_buffersrc_write_frame() failed");

	/* collect filtered data from the FFmpeg audio buffer sink */

69
	frame.Unref();
70

71
	err = av_buffersink_get_frame(buffer_sink.get(), frame.get());
72 73 74 75 76 77 78 79 80 81
	if (err < 0) {
		if (err == AVERROR(EAGAIN) || err == AVERROR_EOF)
			return nullptr;

		throw MakeFfmpegError(err, "av_buffersink_get_frame() failed");
	}

	/* TODO: call av_buffersink_get_frame() repeatedly?  Not
	   possible with MPD's current Filter API */

82
	return {frame.GetData(0), frame->nb_samples * GetOutAudioFormat().GetFrameSize()};
83
}