]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/ffmpeg_producer.cpp
2.0.2: ffmpeg_producer: Improved nb_frames accuracy.
[casparcg] / modules / ffmpeg / producer / ffmpeg_producer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\r
5 *\r
6 *    CasparCG is free software: you can redistribute it and/or modify\r
7 *    it under the terms of the GNU General Public License as published by\r
8 *    the Free Software Foundation, either version 3 of the License, or\r
9 *    (at your option) any later version.\r
10 *\r
11 *    CasparCG is distributed in the hope that it will be useful,\r
12 *    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 *    GNU General Public License for more details.\r
15 \r
16 *    You should have received a copy of the GNU General Public License\r
17 *    along with CasparCG.  If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 */\r
20 #include "../stdafx.h"\r
21 \r
22 #include "ffmpeg_producer.h"\r
23 \r
24 #include "../ffmpeg_error.h"\r
25 \r
26 #include "muxer/frame_muxer.h"\r
27 #include "input/input.h"\r
28 #include "util/util.h"\r
29 #include "audio/audio_decoder.h"\r
30 #include "video/video_decoder.h"\r
31 \r
32 #include <common/env.h>\r
33 #include <common/utility/assert.h>\r
34 #include <common/diagnostics/graph.h>\r
35 \r
36 #include <core/video_format.h>\r
37 #include <core/producer/frame_producer.h>\r
38 #include <core/producer/frame/frame_factory.h>\r
39 #include <core/producer/frame/basic_frame.h>\r
40 #include <core/producer/frame/frame_transform.h>\r
41 \r
42 #include <boost/algorithm/string.hpp>\r
43 #include <boost/assign.hpp>\r
44 #include <boost/timer.hpp>\r
45 #include <boost/foreach.hpp>\r
46 #include <boost/filesystem.hpp>\r
47 #include <boost/range/algorithm/find_if.hpp>\r
48 #include <boost/range/algorithm/find.hpp>\r
49 #include <boost/regex.hpp>\r
50 \r
51 #include <tbb/parallel_invoke.h>\r
52 \r
53 #include <limits>\r
54 #include <memory>\r
55 #include <queue>\r
56 \r
57 namespace caspar { namespace ffmpeg {\r
58                                 \r
59 struct ffmpeg_producer : public core::frame_producer\r
60 {\r
61         const std::wstring                                                              filename_;\r
62         \r
63         const safe_ptr<diagnostics::graph>                              graph_;\r
64         boost::timer                                                                    frame_timer_;\r
65         boost::timer                                                                    video_timer_;\r
66         boost::timer                                                                    audio_timer_;\r
67                                         \r
68         const safe_ptr<core::frame_factory>                             frame_factory_;\r
69         const core::video_format_desc                                   format_desc_;\r
70 \r
71         input                                                                                   input_; \r
72         std::unique_ptr<video_decoder>                                  video_decoder_;\r
73         std::unique_ptr<audio_decoder>                                  audio_decoder_; \r
74         std::unique_ptr<frame_muxer>                                    muxer_;\r
75 \r
76         const int                                                                               start_;\r
77         const bool                                                                              loop_;\r
78         const size_t                                                                    length_;\r
79 \r
80         safe_ptr<core::basic_frame>                                             last_frame_;\r
81         \r
82         std::queue<safe_ptr<core::basic_frame>>                 frame_buffer_;\r
83         \r
84 public:\r
85         explicit ffmpeg_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, const std::wstring& filter, bool loop, int start, size_t length) \r
86                 : filename_(filename)\r
87                 , frame_factory_(frame_factory)         \r
88                 , format_desc_(frame_factory->get_video_format_desc())\r
89                 , input_(graph_, filename_, loop, start, length)\r
90                 , start_(start)\r
91                 , loop_(loop)\r
92                 , length_(length)\r
93                 , last_frame_(core::basic_frame::empty())\r
94         {\r
95                 graph_->add_guide("frame-time", 0.5);\r
96                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
97                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   \r
98                 diagnostics::register_graph(graph_);\r
99                 \r
100                 try\r
101                 {\r
102                         video_decoder_.reset(new video_decoder(input_.context()));\r
103                 }\r
104                 catch(averror_stream_not_found&)\r
105                 {\r
106                         CASPAR_LOG(warning) << "No video-stream found. Running without video."; \r
107                 }\r
108                 catch(...)\r
109                 {\r
110                         CASPAR_LOG_CURRENT_EXCEPTION();\r
111                         CASPAR_LOG(warning) << "Failed to open video-stream. Running without video.";   \r
112                 }\r
113 \r
114                 try\r
115                 {\r
116                         audio_decoder_.reset(new audio_decoder(input_.context(), frame_factory->get_video_format_desc()));\r
117                 }\r
118                 catch(averror_stream_not_found&)\r
119                 {\r
120                         CASPAR_LOG(warning) << "No audio-stream found. Running without audio."; \r
121                 }\r
122                 catch(...)\r
123                 {\r
124                         CASPAR_LOG_CURRENT_EXCEPTION();\r
125                         CASPAR_LOG(warning) << "Failed to open audio-stream. Running without audio.";           \r
126                 }       \r
127 \r
128                 muxer_.reset(new frame_muxer(video_decoder_ ? video_decoder_->fps() : frame_factory->get_video_format_desc().fps, frame_factory, filter));\r
129         }\r
130 \r
131         // frame_producer\r
132         \r
133         virtual safe_ptr<core::basic_frame> receive(int hints) override\r
134         {               \r
135                 frame_timer_.restart();\r
136                 \r
137                 for(int n = 0; n < 16 && frame_buffer_.size() < 2; ++n)\r
138                         try_decode_frame(hints);\r
139                 \r
140                 graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
141                                 \r
142                 if(frame_buffer_.empty() && input_.eof())\r
143                         return last_frame();\r
144 \r
145                 if(frame_buffer_.empty())\r
146                 {\r
147                         graph_->add_tag("underflow");   \r
148                         return core::basic_frame::late();                       \r
149                 }\r
150                 \r
151                 last_frame_ = frame_buffer_.front();    \r
152                 frame_buffer_.pop();\r
153 \r
154                 graph_->set_text(print());\r
155 \r
156                 return last_frame_;\r
157         }\r
158 \r
159         virtual safe_ptr<core::basic_frame> last_frame() const override\r
160         {\r
161                 return disable_audio(last_frame_);\r
162         }\r
163 \r
164         virtual int64_t nb_frames() const override\r
165         {\r
166                 if(loop_)\r
167                         return std::numeric_limits<int64_t>::max();\r
168 \r
169                 // This function estimates nb_frames until input has read all packets for one loop, at which point the count should be accurate.\r
170 \r
171                 int64_t nb_frames = input_.nb_frames();\r
172                 if(input_.nb_loops() < 1) // input still hasn't counted all frames\r
173                 {\r
174                         auto video_nb_frames = video_decoder_ ? video_decoder_->nb_frames() : std::numeric_limits<int64_t>::max();\r
175                         //auto audio_nb_frames = audio_decoder_ ? audio_decoder_->nb_frames() : std::numeric_limits<int64_t>::max();\r
176 \r
177                         nb_frames = std::max(nb_frames, video_nb_frames);\r
178                 }\r
179 \r
180                 nb_frames = std::min(static_cast<int64_t>(length_), nb_frames);\r
181                 nb_frames = muxer_->calc_nb_frames(nb_frames);\r
182                 \r
183                 return nb_frames - start_;\r
184         }\r
185 \r
186         virtual boost::unique_future<std::wstring> call(const std::wstring& param) override\r
187         {\r
188                 boost::promise<std::wstring> promise;\r
189                 promise.set_value(do_call(param));\r
190                 return promise.get_future();\r
191         }\r
192                                 \r
193         virtual std::wstring print() const override\r
194         {\r
195                 if(video_decoder_)\r
196                 {\r
197                         return L"ffmpeg[" + boost::filesystem::wpath(filename_).filename() + L"|" \r
198                                                           + boost::lexical_cast<std::wstring>(video_decoder_->width()) + L"x" + boost::lexical_cast<std::wstring>(video_decoder_->height())\r
199                                                           + (video_decoder_->is_progressive() ? L"p" : L"i")  + boost::lexical_cast<std::wstring>(video_decoder_->is_progressive() ? video_decoder_->fps() : 2.0 * video_decoder_->fps())\r
200                                                           + L"|" + boost::lexical_cast<std::wstring>(nb_frames()) + L"]";\r
201                 }\r
202                 \r
203                 return L"ffmpeg[" + boost::filesystem::wpath(filename_).filename() + L"]";\r
204         }\r
205 \r
206         // ffmpeg_producer\r
207                                 \r
208         std::wstring do_call(const std::wstring& param)\r
209         {\r
210                 static const boost::wregex loop_exp(L"LOOP\\s*(?<VALUE>\\d?)", boost::regex::icase);\r
211                 static const boost::wregex seek_exp(L"SEEK\\s+(?<VALUE>\\d+)", boost::regex::icase);\r
212                 \r
213                 boost::wsmatch what;\r
214                 if(boost::regex_match(param, what, loop_exp))\r
215                 {\r
216                         if(!what["VALUE"].str().empty())\r
217                                 input_.loop(boost::lexical_cast<bool>(what["VALUE"].str()));\r
218                         return boost::lexical_cast<std::wstring>(input_.loop());\r
219                 }\r
220                 if(boost::regex_match(param, what, seek_exp))\r
221                 {\r
222                         input_.seek(boost::lexical_cast<int64_t>(what["VALUE"].str()));\r
223                         return L"";\r
224                 }\r
225 \r
226                 BOOST_THROW_EXCEPTION(invalid_argument());\r
227         }\r
228 \r
229         void try_decode_frame(int hints)\r
230         {\r
231                 std::shared_ptr<AVPacket> pkt;\r
232 \r
233                 for(int n = 0; n < 32 && ((video_decoder_ && !video_decoder_->ready()) || (audio_decoder_ && !audio_decoder_->ready())) && input_.try_pop(pkt); ++n)\r
234                 {\r
235                         if(video_decoder_)\r
236                                 video_decoder_->push(pkt);\r
237                         if(audio_decoder_)\r
238                                 audio_decoder_->push(pkt);\r
239                 }\r
240                 \r
241                 std::shared_ptr<AVFrame>                        video;\r
242                 std::shared_ptr<core::audio_buffer> audio;\r
243 \r
244                 tbb::parallel_invoke(\r
245                 [&]\r
246                 {\r
247                         if(!muxer_->video_ready() && video_decoder_)                    \r
248                                 video = video_decoder_->poll();                 \r
249                 },\r
250                 [&]\r
251                 {               \r
252                         if(!muxer_->audio_ready() && audio_decoder_)                    \r
253                                 audio = audio_decoder_->poll();                 \r
254                 });\r
255 \r
256                 muxer_->push(video, hints);\r
257                 muxer_->push(audio);\r
258 \r
259                 if(!audio_decoder_)\r
260                 {\r
261                         if(video == flush_video())\r
262                                 muxer_->push(flush_audio());\r
263                         else if(!muxer_->audio_ready())\r
264                                 muxer_->push(empty_audio());\r
265                 }\r
266 \r
267                 if(!video_decoder_)\r
268                 {\r
269                         if(audio == flush_audio())\r
270                                 muxer_->push(flush_video(), 0);\r
271                         else if(!muxer_->video_ready())\r
272                                 muxer_->push(empty_video(), 0);\r
273                 }\r
274                 \r
275                 for(auto frame = muxer_->poll(); frame; frame = muxer_->poll())\r
276                         frame_buffer_.push(make_safe_ptr(frame));\r
277         }\r
278 };\r
279 \r
280 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
281 {               \r
282         static const std::vector<std::wstring> extensions = boost::assign::list_of\r
283                 (L"mpg")(L"mpeg")(L"m2v")(L"m4v")(L"mp3")(L"mp4")(L"mpga")\r
284                 (L"avi")\r
285                 (L"mov")\r
286                 (L"qt")\r
287                 (L"webm")\r
288                 (L"dv")         \r
289                 (L"f4v")(L"flv")\r
290                 (L"mkv")(L"mka")\r
291                 (L"wmv")(L"wma")(L"wav")\r
292                 (L"rm")(L"ram")\r
293                 (L"ogg")(L"ogv")(L"oga")(L"ogx")\r
294                 (L"divx")(L"xvid");\r
295 \r
296         std::wstring filename = env::media_folder() + L"\\" + params[0];\r
297         \r
298         auto ext = boost::find_if(extensions, [&](const std::wstring& ex)\r
299         {                                       \r
300                 return boost::filesystem::is_regular_file(boost::filesystem::wpath(filename + L"." + ex));\r
301         });\r
302 \r
303         if(ext == extensions.end())\r
304                 return core::frame_producer::empty();\r
305 \r
306         auto path               = filename + L"." + *ext;\r
307         auto loop               = boost::range::find(params, L"LOOP") != params.end();\r
308         auto start              = core::get_param(L"SEEK", params, 0);\r
309         auto length             = core::get_param(L"LENGTH", params, std::numeric_limits<size_t>::max());\r
310         auto filter_str = core::get_param<std::wstring>(L"FILTER", params, L"");        \r
311                 \r
312         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
313         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
314         \r
315         return create_destroy_proxy(make_safe<ffmpeg_producer>(frame_factory, path, filter_str, loop, start, length));\r
316 }\r
317 \r
318 }}