]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/ffmpeg_producer.cpp
2.0. ffmpeg_producer: Fixed data race and frame timing.
[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/assert.h>\r
29 #include <common/utility/timer.h>\r
30 #include <common/diagnostics/graph.h>\r
31 \r
32 #include <core/producer/frame/basic_frame.h>\r
33 #include <core/mixer/write_frame.h>\r
34 #include <core/producer/frame/audio_transform.h>\r
35 #include <core/video_format.h>\r
36 \r
37 #include <common/env.h>\r
38 \r
39 #include <tbb/parallel_invoke.h>\r
40 #include <tbb/task_group.h>\r
41 \r
42 #include <boost/timer.hpp>\r
43 #include <boost/range/algorithm.hpp>\r
44 #include <boost/range/algorithm_ext.hpp>\r
45 \r
46 #include <deque>\r
47 \r
48 namespace caspar {\r
49         \r
50 struct ffmpeg_producer : public core::frame_producer\r
51 {\r
52         const std::wstring                                              filename_;\r
53         \r
54         const safe_ptr<diagnostics::graph>              graph_;\r
55         boost::timer                                                    frame_timer_;\r
56                                         \r
57         const safe_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 \r
63         std::deque<std::pair<int, std::vector<int16_t>>> audio_chunks_;\r
64         std::deque<std::pair<int, safe_ptr<core::write_frame>>> video_frames_;\r
65         \r
66         tbb::task_group                                                 task_group_;\r
67 public:\r
68         explicit ffmpeg_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, const std::wstring& filter_str, bool loop, int start, int length) \r
69                 : filename_(filename)\r
70                 , graph_(diagnostics::create_graph(narrow(print())))\r
71                 , frame_factory_(frame_factory)         \r
72                 , input_(safe_ptr<diagnostics::graph>(graph_), filename_, loop, start, length)\r
73         {\r
74                 graph_->add_guide("frame-time", 0.5);\r
75                 graph_->set_color("frame-time",  diagnostics::color(1.0f, 0.0f, 0.0f));\r
76                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));           \r
77                 \r
78                 double frame_time = 1.0f/input_.fps();\r
79                 double format_frame_time = 1.0/frame_factory->get_video_format_desc().fps;\r
80                 if(abs(frame_time - format_frame_time) > 0.0001 && abs(frame_time - format_frame_time/2) > 0.0001)\r
81                         CASPAR_LOG(warning) << print() << L" Invalid framerate detected. This may cause distorted audio during playback. frame-time: " << frame_time;\r
82                 \r
83                 video_decoder_.reset(input_.get_video_codec_context() ? \r
84                         new video_decoder(input_, frame_factory, narrow(filter_str)) : nullptr);\r
85                         \r
86                 audio_decoder_.reset(input_.get_audio_codec_context() ? \r
87                         new audio_decoder(input_, frame_factory->get_video_format_desc()) : nullptr);           \r
88                                         \r
89                 // Fill buffers.\r
90                 for(size_t n = 0; n < 2; ++n)\r
91                         decode_packets();\r
92         }\r
93 \r
94         virtual safe_ptr<core::basic_frame> receive()\r
95         {               \r
96                 // "receive" is called on the same thread as the gpu mixer runs. Minimize "receive" time in order to allow gpu and cpu to run in parallel. \r
97                 task_group_.wait();\r
98 \r
99                 auto result = get_frame();\r
100 \r
101                 task_group_.run([=]\r
102                 {\r
103                         frame_timer_.restart();\r
104                         decode_packets();\r
105                         graph_->update_value("frame-time", static_cast<float>(frame_timer_.elapsed()*frame_factory_->get_video_format_desc().fps*0.5));\r
106                 });                             \r
107                                         \r
108                 return result;\r
109         }\r
110         \r
111         virtual std::wstring print() const\r
112         {\r
113                 return L"ffmpeg[" + boost::filesystem::wpath(filename_).filename() + L"]";\r
114         }\r
115 \r
116         void decode_packets()\r
117         {\r
118                 tbb::parallel_invoke\r
119                 (\r
120                         [&]\r
121                         {\r
122                                 try\r
123                                 {\r
124                                         if(video_decoder_ && video_frames_.size() < 3)\r
125                                                 boost::range::push_back(video_frames_, video_decoder_->receive());              \r
126                                 }\r
127                                 catch(...)\r
128                                 {\r
129                                         CASPAR_LOG_CURRENT_EXCEPTION();\r
130                                         video_decoder_.reset();\r
131                                 }\r
132                         }, \r
133                         [&]\r
134                         {\r
135                                 try\r
136                                 {\r
137                                         if(audio_decoder_ && audio_chunks_.size() < 3)\r
138                                                 boost::range::push_back(audio_chunks_, audio_decoder_->receive());              \r
139                                 }\r
140                                 catch(...)\r
141                                 {\r
142                                         CASPAR_LOG_CURRENT_EXCEPTION();\r
143                                         audio_decoder_.reset();\r
144                                 }\r
145                         }\r
146                 );\r
147                 \r
148                 // If video is on first frame, sync with audio\r
149                 if(audio_decoder_ && video_decoder_ && !video_frames_.empty() && !audio_chunks_.empty() &&\r
150                    video_frames_.front().first == 0 && audio_chunks_.front().first != 0)\r
151                 {\r
152                         audio_decoder_->restart(); // Notify decoder to wait for eof which was sent with video eof.\r
153                         audio_chunks_ = audio_decoder_->receive();              \r
154                 }\r
155                 \r
156                 CASPAR_ASSERT(!(video_decoder_ && audio_decoder_ && !video_frames_.empty() && !audio_chunks_.empty()) ||\r
157                                       video_frames_.front().first == audio_chunks_.front().first);\r
158         }\r
159 \r
160         // FIXME: Don't re-interlace when going from 50i to 50p, maybe do this inside decoder?\r
161         safe_ptr<core::basic_frame> get_video_frame(std::vector<int16_t>&& audio_chunk)\r
162         {\r
163                 auto frame = std::move(video_frames_.front().second);   \r
164                 auto frame_number = video_frames_.front().first;\r
165                 video_frames_.pop_front();\r
166                                 \r
167                 frame->audio_data() = std::move(audio_chunk);\r
168                 if(frame->audio_data().empty())\r
169                         frame->get_audio_transform().set_has_audio(false);      \r
170 \r
171                 if(!video_frames_.empty()) // interlace if we have double frames\r
172                 {\r
173                         if(video_frames_.front().first == frame_number)\r
174                         {\r
175                                 auto frame2 = std::move(video_frames_.front().second);  \r
176                                 video_frames_.pop_front();\r
177                                 frame2->get_audio_transform().set_has_audio(false);     \r
178 \r
179                                 return core::basic_frame::interlace(frame, frame2, frame_factory_->get_video_format_desc().mode);\r
180                         }\r
181                 }\r
182 \r
183                 return frame;\r
184         }\r
185 \r
186         safe_ptr<core::basic_frame> get_frame()\r
187         {               \r
188                 if(video_decoder_ && audio_decoder_ && !video_frames_.empty() && !audio_chunks_.empty())\r
189                 {\r
190                         auto audio_chunk = std::move(audio_chunks_.front().second);\r
191                         audio_chunks_.pop_front();\r
192                                                 \r
193                         return get_video_frame(std::move(audio_chunk));\r
194                 }\r
195                 else if(video_decoder_ && !audio_decoder_ && !video_frames_.empty())\r
196                 {                                               \r
197                         return get_video_frame(std::vector<int16_t>());\r
198                 }\r
199                 else if(audio_decoder_ && !video_decoder_ && !audio_chunks_.empty())\r
200                 {\r
201                         auto frame = frame_factory_->create_frame(this, 1, 1);\r
202                         std::fill(frame->image_data().begin(), frame->image_data().end(), 0);\r
203                                 \r
204                         frame->audio_data() = std::move(audio_chunks_.front().second);\r
205                         audio_chunks_.pop_front();\r
206 \r
207                         return frame;\r
208                 }\r
209                 else if(!input_.is_running() || (!video_decoder_ && !audio_decoder_))\r
210                 {\r
211                         return core::basic_frame::eof();\r
212                 }\r
213                 else\r
214                 {\r
215                         graph_->add_tag("underflow");\r
216                         return core::basic_frame::late();\r
217                 }\r
218         }\r
219 };\r
220 \r
221 safe_ptr<core::frame_producer> create_ffmpeg_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
222 {               \r
223         static const std::vector<std::wstring> extensions = boost::assign::list_of\r
224                 (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
225         std::wstring filename = env::media_folder() + L"\\" + params[0];\r
226         \r
227         auto ext = boost::find_if(extensions, [&](const std::wstring& ex)\r
228         {                                       \r
229                 return boost::filesystem::is_regular_file(boost::filesystem::wpath(filename + L"." + ex));\r
230         });\r
231 \r
232         if(ext == extensions.end())\r
233                 return core::frame_producer::empty();\r
234 \r
235         std::wstring path = filename + L"." + *ext;\r
236         bool loop = boost::find(params, L"LOOP") != params.end();\r
237 \r
238         int start = -1;\r
239         int length = -1;\r
240         \r
241         auto seek_it = std::find(params.begin(), params.end(), L"SEEK");\r
242         if(seek_it != params.end())\r
243         {\r
244                 if(++seek_it != params.end())\r
245                         start = boost::lexical_cast<int>(*seek_it);\r
246         }\r
247         \r
248         std::wstring filter_str = L"";\r
249 \r
250         auto filter_it = std::find(params.begin(), params.end(), L"FILTER");\r
251         if(filter_it != params.end())\r
252         {\r
253                 if(++filter_it != params.end())\r
254                         filter_str = *filter_it;\r
255         }\r
256 \r
257         return make_safe<ffmpeg_producer>(frame_factory, path, filter_str, loop, start, length);\r
258 }\r
259 \r
260 }