]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/ffmpeg_producer.cpp
2.0.0.2: ffmpeg_producer: Improved pre-rolling and file read load.
[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 "input.h"\r
25 #include "audio/audio_decoder.h"\r
26 #include "video/video_decoder.h"\r
27 \r
28 #include <common/utility/timer.h>\r
29 #include <common/diagnostics/graph.h>\r
30 \r
31 #include <core/producer/frame/basic_frame.h>\r
32 #include <core/mixer/write_frame.h>\r
33 #include <core/producer/frame/audio_transform.h>\r
34 #include <core/video_format.h>\r
35 \r
36 #include <common/env.h>\r
37 \r
38 #include <tbb/parallel_invoke.h>\r
39 \r
40 #include <boost/timer.hpp>\r
41 #include <boost/range/algorithm.hpp>\r
42 #include <boost/range/algorithm_ext.hpp>\r
43 \r
44 #include <deque>\r
45 \r
46 namespace caspar {\r
47         \r
48 struct ffmpeg_producer : public core::frame_producer\r
49 {\r
50         static const size_t                                             DECODED_PACKET_BUFFER_SIZE = 4;\r
51         static const size_t                                             MAX_PACKET_OFFSET = 64; // Avoid infinite looping.\r
52 \r
53         const std::wstring                                              filename_;\r
54         const bool                                                              loop_;\r
55         \r
56         const safe_ptr<diagnostics::graph>              graph_;\r
57         boost::timer                                                    frame_timer_;\r
58                 \r
59         std::deque<safe_ptr<core::write_frame>> video_frame_buffer_;    \r
60         std::deque<std::vector<short>>                  audio_chunk_buffer_;\r
61                         \r
62         const safe_ptr<core::frame_factory>             frame_factory_;\r
63 \r
64         input                                                                   input_; \r
65         std::unique_ptr<video_decoder>                  video_decoder_;\r
66         std::unique_ptr<audio_decoder>                  audio_decoder_;\r
67 public:\r
68         explicit ffmpeg_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, bool loop, int start, int length) \r
69                 : filename_(filename)\r
70                 , loop_(loop) \r
71                 , graph_(diagnostics::create_graph(narrow(print())))\r
72                 , frame_factory_(frame_factory)         \r
73                 , input_(safe_ptr<diagnostics::graph>(graph_), filename_, loop_, start)\r
74         {\r
75                 graph_->add_guide("frame-time", 0.5);\r
76                 graph_->set_color("frame-time",  diagnostics::color(1.0f, 0.0f, 0.0f));\r
77                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));           \r
78                 \r
79                 double frame_time = 1.0f/input_.fps();\r
80                 double format_frame_time = 1.0/frame_factory->get_video_format_desc().fps;\r
81                 if(abs(frame_time - format_frame_time) > 0.0001 && abs(frame_time - format_frame_time/2) > 0.0001)\r
82                         CASPAR_LOG(warning) << print() << L" Invalid framerate detected. This may cause distorted audio during playback. frame-time: " << frame_time;\r
83 \r
84                 try\r
85                 {                       \r
86                         video_decoder_.reset(input_.get_video_codec_context() ? \r
87                                 new video_decoder(*input_.get_video_codec_context(), frame_factory) : nullptr);\r
88                 }\r
89                 catch(...)\r
90                 {\r
91                         CASPAR_LOG_CURRENT_EXCEPTION();\r
92                         CASPAR_LOG(warning) << print() << " failed to initialize video-decoder.";\r
93                 }\r
94                 \r
95                 try\r
96                 {                       \r
97                         audio_decoder_.reset(input_.get_audio_codec_context() ? \r
98                                 new audio_decoder(*input_.get_audio_codec_context(), frame_factory->get_video_format_desc()) : nullptr);\r
99                 }\r
100                 catch(...)\r
101                 {\r
102                         CASPAR_LOG_CURRENT_EXCEPTION();\r
103                         CASPAR_LOG(warning) << print() << " failed to initialize audio-decoder.";\r
104                 }               \r
105 \r
106                 if(!video_decoder_ && !audio_decoder_)\r
107                 {\r
108                         BOOST_THROW_EXCEPTION(\r
109                                 caspar_exception() <<\r
110                                 source_info(narrow(print())) << \r
111                                 msg_info("Failed to initialize any decoder"));\r
112                 }\r
113                         \r
114                 // Pre-roll since first frames can be heavy.\r
115                 while(video_frame_buffer_.size() < DECODED_PACKET_BUFFER_SIZE && \r
116                           audio_chunk_buffer_.size() < DECODED_PACKET_BUFFER_SIZE && \r
117                           input_.has_packet())\r
118                 {\r
119                         try_decode_packet();\r
120                 }\r
121         }\r
122 \r
123         virtual safe_ptr<core::basic_frame> receive()\r
124         {\r
125                 frame_timer_.restart();\r
126 \r
127                 std::shared_ptr<core::basic_frame> frame;       \r
128                 for(size_t n = 0; !frame && input_.has_packet() && n < MAX_PACKET_OFFSET ; ++n) \r
129                         frame = try_get_frame();\r
130                                 \r
131                 graph_->update_value("frame-time", static_cast<float>(frame_timer_.elapsed()*frame_factory_->get_video_format_desc().fps*0.5));\r
132                                         \r
133                 if(frame)\r
134                         return make_safe(frame);\r
135                 \r
136                 if(!input_.is_running())\r
137                         return core::basic_frame::eof();\r
138 \r
139                 if(!video_decoder_ && !audio_decoder_)\r
140                         return core::basic_frame::eof();\r
141                         \r
142                 graph_->add_tag("underflow");\r
143                 return core::basic_frame::late();       \r
144         }\r
145         \r
146         virtual std::wstring print() const\r
147         {\r
148                 return L"ffmpeg[" + boost::filesystem::wpath(filename_).filename() + L"]";\r
149         }\r
150         \r
151         void try_decode_packet()\r
152         {\r
153                 tbb::parallel_invoke\r
154                 (\r
155                         [&]\r
156                         {\r
157                                 if(video_frame_buffer_.size() < DECODED_PACKET_BUFFER_SIZE)\r
158                                         try_decode_video_packet(input_.get_video_packet());\r
159                         }, \r
160                         [&]\r
161                         {\r
162                                 if(audio_chunk_buffer_.size() < DECODED_PACKET_BUFFER_SIZE)\r
163                                         try_decode_audio_packet(input_.get_audio_packet());\r
164                         }\r
165                 );      \r
166         }\r
167 \r
168         void try_decode_video_packet(std::shared_ptr<AVPacket>&& video_packet)\r
169         {\r
170                 if(!video_decoder_)\r
171                         return;\r
172 \r
173                 try\r
174                 {\r
175                         boost::range::push_back(video_frame_buffer_, video_decoder_->execute(std::move(video_packet)));\r
176                 }\r
177                 catch(...)\r
178                 {\r
179                         CASPAR_LOG_CURRENT_EXCEPTION();\r
180                         video_decoder_.reset();\r
181                         CASPAR_LOG(warning) << print() << " removed video-stream.";\r
182                 }\r
183         }\r
184 \r
185         void try_decode_audio_packet(std::shared_ptr<AVPacket>&& audio_packet)\r
186         {\r
187                 if(!audio_decoder_)\r
188                         return;\r
189 \r
190                 try\r
191                 {\r
192                         boost::range::push_back(audio_chunk_buffer_, audio_decoder_->execute(std::move(audio_packet)));\r
193                 }\r
194                 catch(...)\r
195                 {\r
196                         CASPAR_LOG_CURRENT_EXCEPTION();\r
197                         audio_decoder_.reset();\r
198                         CASPAR_LOG(warning) << print() << " removed audio-stream.";\r
199                 }\r
200         }\r
201 \r
202         std::shared_ptr<core::basic_frame> try_get_frame()\r
203         {               \r
204                 try_decode_packet();\r
205 \r
206                 std::shared_ptr<core::write_frame> frame;       \r
207 \r
208                 if(!video_frame_buffer_.empty() && !audio_chunk_buffer_.empty())\r
209                 {\r
210                         frame = video_frame_buffer_.front();                            \r
211                         video_frame_buffer_.pop_front();\r
212                                 \r
213                         frame->audio_data() = std::move(audio_chunk_buffer_.front());\r
214                         audio_chunk_buffer_.pop_front();        \r
215                 }\r
216                 else if(!video_frame_buffer_.empty() && !audio_decoder_)\r
217                 {\r
218                         frame = std::move(video_frame_buffer_.front());                         \r
219                         video_frame_buffer_.pop_front();\r
220                         frame->get_audio_transform().set_has_audio(false);      \r
221                 }\r
222                 else if(!audio_chunk_buffer_.empty() && !video_decoder_)\r
223                 {\r
224                         frame = frame_factory_->create_frame(this, 1, 1);\r
225                         std::fill(frame->image_data().begin(), frame->image_data().end(), 0);\r
226                                 \r
227                         frame->audio_data() = std::move(audio_chunk_buffer_.front());\r
228                         audio_chunk_buffer_.pop_front();\r
229                 }\r
230                 \r
231                 return frame;   \r
232         }\r
233 };\r
234 \r
235 safe_ptr<core::frame_producer> create_ffmpeg_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
236 {               \r
237         static const std::vector<std::wstring> extensions = boost::assign::list_of\r
238                 (L"mpg")(L"mpeg")(L"avi")(L"mov")(L"qt")(L"webm")(L"dv")(L"mp4")(L"f4v")(L"flv")(L"mkv")(L"mka")(L"wmv")(L"wma")(L"ogg")(L"divx")(L"xvid")(L"wav")(L"mp3")(L"m2v");\r
239         std::wstring filename = env::media_folder() + L"\\" + params[0];\r
240         \r
241         auto ext = boost::find_if(extensions, [&](const std::wstring& ex)\r
242         {                                       \r
243                 return boost::filesystem::is_regular_file(boost::filesystem::wpath(filename).replace_extension(ex));\r
244         });\r
245 \r
246         if(ext == extensions.end())\r
247                 return core::frame_producer::empty();\r
248 \r
249         std::wstring path = filename + L"." + *ext;\r
250         bool loop = boost::find(params, L"LOOP") != params.end();\r
251 \r
252         static const boost::wregex expr(L"\\((?<START>\\d+)(,(?<LENGTH>\\d+)?)?\\)");//(,(?<END>\\d+))?\\]"); // boost::regex has no repeated captures?\r
253         boost::wsmatch what;\r
254         auto it = std::find_if(params.begin(), params.end(), [&](const std::wstring& str)\r
255         {\r
256                 return boost::regex_match(str, what, expr);\r
257         });\r
258 \r
259         int start = -1;\r
260         int length = -1;\r
261 \r
262         if(it != params.end())\r
263         {\r
264                 start = lexical_cast_or_default(what["START"].str(), -1);\r
265                 if(what["LENGTH"].matched)\r
266                         length = lexical_cast_or_default(what["LENGTH"].str(), -1);\r
267         }\r
268         \r
269         return make_safe<ffmpeg_producer>(frame_factory, path, loop, start, length);\r
270 }\r
271 \r
272 }