]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/filter/audio_filter.cpp
[ffmpeg] Remove redundant av_frame_alloc()/av_frame_free() RAII pairs all over the...
[casparcg] / modules / ffmpeg / producer / filter / audio_filter.cpp
1 /*
2 * Copyright 2013 Sveriges Television AB http://casparcg.com/
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../../StdAfx.h"
23
24 #include "audio_filter.h"
25
26 #include "../../ffmpeg_error.h"
27 #include "../../ffmpeg.h"
28 #include "../util/util.h"
29
30 #include <common/assert.h>
31 #include <common/except.h>
32
33 #include <boost/algorithm/string.hpp>
34 #include <boost/thread.hpp>
35 #include <boost/format.hpp>
36 #include <boost/rational.hpp>
37
38 #include <cstdio>
39 #include <sstream>
40 #include <string>
41 #include <algorithm>
42
43 #if defined(_MSC_VER)
44 #pragma warning (push)
45 #pragma warning (disable : 4244)
46 #endif
47 extern "C"
48 {
49         #include <libavutil/avutil.h>
50         #include <libavutil/imgutils.h>
51         #include <libavutil/opt.h>
52         #include <libavfilter/avfilter.h>
53         #include <libavfilter/avcodec.h>
54         #include <libavfilter/buffersink.h>
55         #include <libavfilter/buffersrc.h>
56 }
57 #if defined(_MSC_VER)
58 #pragma warning (pop)
59 #endif
60
61 namespace caspar { namespace ffmpeg {
62
63 std::string create_sourcefilter_str(const audio_input_pad& input_pad, std::string name)
64 {
65         const auto asrc_options = (boost::format("abuffer=time_base=%1%/%2%:sample_rate=%3%:sample_fmt=%4%:channel_layout=0x%|5$x| [%6%]")
66                 % input_pad.time_base.numerator() % input_pad.time_base.denominator()
67                 % input_pad.sample_rate
68                 % av_get_sample_fmt_name(input_pad.sample_fmt)
69                 % input_pad.audio_channel_layout
70                 % name).str();
71
72         return asrc_options;
73 }
74
75 std::string create_filter_list(const std::vector<std::string>& items)
76 {
77         return boost::join(items, "|");
78 }
79
80 std::string channel_layout_to_string(int64_t channel_layout)
81 {
82         return (boost::format("0x%|1$x|") % channel_layout).str();
83 }
84
85 std::string create_sinkfilter_str(const audio_output_pad& output_pad, std::string name)
86 {
87         const auto asink_options = (boost::format("[%4%] abuffersink")//=sample_fmts=%1%:channel_layouts=%2%:sample_rates=%3%")
88                 % create_filter_list(cpplinq::from(output_pad.sample_fmts)
89                                 .select(&av_get_sample_fmt_name)
90                                 .select([](const char* str) { return std::string(str); })
91                                 .to_vector())
92                 % create_filter_list(cpplinq::from(output_pad.sample_fmts)
93                                 .select(&channel_layout_to_string)
94                                 .to_vector())
95                 % create_filter_list(cpplinq::from(output_pad.sample_rates)
96                                 .select([](int samplerate) { return boost::lexical_cast<std::string>(samplerate); })
97                                 .to_vector())
98                 % name).str();
99
100         return asink_options;
101 }
102
103 struct audio_filter::implementation
104 {
105         std::string                                             filtergraph_;
106
107         std::shared_ptr<AVFilterGraph>  audio_graph_;
108         std::vector<AVFilterContext*>   audio_graph_inputs_;
109         std::vector<AVFilterContext*>   audio_graph_outputs_;
110
111         implementation(
112                 std::vector<audio_input_pad> input_pads,
113                 std::vector<audio_output_pad> output_pads,
114                 const std::string& filtergraph)
115                 : filtergraph_(boost::to_lower_copy(filtergraph))
116         {
117                 if (input_pads.empty())
118                         CASPAR_THROW_EXCEPTION(invalid_argument() << msg_info("input_pads cannot be empty"));
119
120                 if (output_pads.empty())
121                         CASPAR_THROW_EXCEPTION(invalid_argument() << msg_info("output_pads cannot be empty"));
122
123                 audio_graph_.reset(
124                         avfilter_graph_alloc(),
125                         [](AVFilterGraph* p)
126                 {
127                         avfilter_graph_free(&p);
128                 });
129
130                 std::vector<std::string> complete_filter_graph;
131
132                 {
133                         int i = 0;
134                         for (auto& input_pad : input_pads)
135                                 complete_filter_graph.push_back(create_sourcefilter_str(input_pad, "a:" + boost::lexical_cast<std::string>(i++)));
136                 }
137
138                 if (filtergraph_.empty())
139                         complete_filter_graph.push_back("[a:0] anull [aout:0]");
140                 else
141                         complete_filter_graph.push_back(filtergraph_);
142
143                 {
144                         int i = 0;
145                         for (auto& output_pad : output_pads)
146                                 complete_filter_graph.push_back(create_sinkfilter_str(output_pad, "aout:" + boost::lexical_cast<std::string>(i++)));
147                 }
148
149                 configure_filtergraph(
150                                 *audio_graph_,
151                                 boost::join(complete_filter_graph, ";"),
152                                 audio_graph_inputs_,
153                                 audio_graph_outputs_);
154
155                 if (is_logging_quiet_for_thread())
156                         CASPAR_LOG(trace)
157                                 <<      u16(std::string("\n")
158                                         + avfilter_graph_dump(
159                                                         audio_graph_.get(),
160                                                         nullptr));
161                 else
162                         CASPAR_LOG(debug)
163                                 << u16(std::string("\n")
164                                         + avfilter_graph_dump(
165                                                 audio_graph_.get(),
166                                                 nullptr));
167         }
168
169         void configure_filtergraph(
170                         AVFilterGraph& graph,
171                         const std::string& filtergraph,
172                         std::vector<AVFilterContext*>& source_contexts,
173                         std::vector<AVFilterContext*>& sink_contexts)
174         {
175                 AVFilterInOut* outputs  = nullptr;
176                 AVFilterInOut* inputs   = nullptr;
177
178                 FF(avfilter_graph_parse2(
179                                 &graph,
180                                 filtergraph.c_str(),
181                                 &inputs,
182                                 &outputs));
183
184                 // Workaround because outputs and inputs are not filled in for some reason
185                 for (unsigned i = 0; i < graph.nb_filters; ++i)
186                 {
187                         auto filter = graph.filters[i];
188
189                         if (std::string(filter->filter->name) == "abuffer")
190                                 source_contexts.push_back(filter);
191
192                         if (std::string(filter->filter->name) == "abuffersink")
193                                 sink_contexts.push_back(filter);
194                 }
195
196                 for (AVFilterInOut* iter = inputs; iter; iter = iter->next)
197                         source_contexts.push_back(iter->filter_ctx);
198
199                 for (AVFilterInOut* iter = outputs; iter; iter = iter->next)
200                         sink_contexts.push_back(iter->filter_ctx);
201
202                 FF(avfilter_graph_config(
203                         &graph,
204                         nullptr));
205         }
206
207         void push(int input_pad_id, const std::shared_ptr<AVFrame>& src_av_frame)
208         {
209                 FF(av_buffersrc_add_frame(
210                         audio_graph_inputs_.at(input_pad_id),
211                         src_av_frame.get()));
212         }
213
214         std::shared_ptr<AVFrame> poll(int output_pad_id)
215         {
216                 auto filt_frame = create_frame();
217
218                 const auto ret = av_buffersink_get_frame(
219                         audio_graph_outputs_.at(output_pad_id),
220                         filt_frame.get());
221
222                 if(ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
223                         return nullptr;
224
225                 FF_RET(ret, "poll");
226
227                 return filt_frame;
228         }
229 };
230
231 audio_filter::audio_filter(
232                 std::vector<audio_input_pad> input_pads,
233                 std::vector<audio_output_pad> output_pads,
234                 const std::string& filtergraph)
235         : impl_(new implementation(std::move(input_pads), std::move(output_pads), filtergraph))
236 {
237 }
238 audio_filter::audio_filter(audio_filter&& other) : impl_(std::move(other.impl_)){}
239 audio_filter& audio_filter::operator=(audio_filter&& other){impl_ = std::move(other.impl_); return *this;}
240 void audio_filter::push(int input_pad_id, const std::shared_ptr<AVFrame>& frame){impl_->push(input_pad_id, frame);}
241 std::shared_ptr<AVFrame> audio_filter::poll(int output_pad_id){return impl_->poll(output_pad_id);}
242 std::wstring audio_filter::filter_str() const{return u16(impl_->filtergraph_);}
243 std::vector<spl::shared_ptr<AVFrame>> audio_filter::poll_all(int output_pad_id)
244 {
245         std::vector<spl::shared_ptr<AVFrame>> frames;
246         for(auto frame = poll(output_pad_id); frame; frame = poll(output_pad_id))
247                 frames.push_back(spl::make_shared_ptr(frame));
248         return frames;
249 }
250
251 }}