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