]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
### Mayor refactoring. Simplified frame handling and image_mixer. Separated video...
[casparcg] / modules / decklink / producer / decklink_producer.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\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 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 #include "../stdafx.h"\r
23 \r
24 #include "decklink_producer.h"\r
25 \r
26 #include "../interop/DeckLinkAPI_h.h"\r
27 #include "../util/util.h"\r
28 \r
29 #include "../../ffmpeg/producer/filter/filter.h"\r
30 #include "../../ffmpeg/producer/util/util.h"\r
31 #include "../../ffmpeg/producer/muxer/frame_muxer.h"\r
32 #include "../../ffmpeg/producer/muxer/display_mode.h"\r
33 \r
34 #include <common/concurrency/executor.h>\r
35 #include <common/diagnostics/graph.h>\r
36 #include <common/except.h>\r
37 #include <common/log.h>\r
38 #include <common/param.h>\r
39 \r
40 #include <core/frame/frame.h>\r
41 #include <core/frame/draw_frame.h>\r
42 #include <core/frame/frame_transform.h>\r
43 #include <core/frame/frame_factory.h>\r
44 \r
45 #include <tbb/concurrent_queue.h>\r
46 \r
47 #include <boost/algorithm/string.hpp>\r
48 #include <boost/foreach.hpp>\r
49 #include <boost/property_tree/ptree.hpp>\r
50 #include <boost/timer.hpp>\r
51 \r
52 #if defined(_MSC_VER)\r
53 #pragma warning (push)\r
54 #pragma warning (disable : 4244)\r
55 #endif\r
56 extern "C" \r
57 {\r
58         #define __STDC_CONSTANT_MACROS\r
59         #define __STDC_LIMIT_MACROS\r
60         #include <libavcodec/avcodec.h>\r
61 }\r
62 #if defined(_MSC_VER)\r
63 #pragma warning (pop)\r
64 #endif\r
65 \r
66 #pragma warning(push)\r
67 #pragma warning(disable : 4996)\r
68 \r
69         #include <atlbase.h>\r
70 \r
71         #include <atlcom.h>\r
72         #include <atlhost.h>\r
73 \r
74 #pragma warning(push)\r
75 \r
76 #include <functional>\r
77 \r
78 namespace caspar { namespace decklink {\r
79                 \r
80 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback\r
81 {       \r
82         spl::shared_ptr<diagnostics::graph>                             graph_;\r
83         boost::timer                                                                    tick_timer_;\r
84         boost::timer                                                                    frame_timer_;\r
85 \r
86         CComPtr<IDeckLink>                                                              decklink_;\r
87         CComQIPtr<IDeckLinkInput>                                               input_;\r
88         CComQIPtr<IDeckLinkAttributes >                                 attributes_;\r
89         \r
90         const std::wstring                                                              model_name_;\r
91         const int                                                                               device_index_;\r
92         const std::wstring                                                              filter_;\r
93         \r
94         std::vector<int>                                                                audio_cadence_;\r
95         boost::circular_buffer<size_t>                                  sync_buffer_;\r
96         ffmpeg::frame_muxer                                                             muxer_;\r
97                         \r
98         tbb::atomic<int>                                                                flags_;\r
99         spl::shared_ptr<core::frame_factory>                    frame_factory_;\r
100         core::video_format_desc                                                 in_format_desc_;\r
101         core::video_format_desc                                                 out_format_desc_;\r
102 \r
103         tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;\r
104 \r
105         std::exception_ptr                                                              exception_;             \r
106 \r
107 public:\r
108         decklink_producer(const core::video_format_desc& in_format_desc, \r
109                                           int device_index, \r
110                                           const spl::shared_ptr<core::frame_factory>& frame_factory, \r
111                                           const core::video_format_desc& out_format_desc, \r
112                                           const std::wstring& filter)\r
113                 : decklink_(get_device(device_index))\r
114                 , input_(decklink_)\r
115                 , attributes_(decklink_)\r
116                 , model_name_(get_model_name(decklink_))\r
117                 , device_index_(device_index)\r
118                 , filter_(filter)\r
119                 , in_format_desc_(in_format_desc)\r
120                 , out_format_desc_(out_format_desc)\r
121                 , muxer_(in_format_desc.fps, frame_factory, out_format_desc, filter)\r
122                 , audio_cadence_(out_format_desc.audio_cadence)\r
123                 , sync_buffer_(out_format_desc.audio_cadence.size())\r
124                 , frame_factory_(frame_factory)\r
125         {       \r
126                 flags_ = 0;\r
127                 frame_buffer_.set_capacity(2);\r
128                 \r
129                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
130                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
131                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
132                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
133                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
134                 graph_->set_text(print());\r
135                 diagnostics::register_graph(graph_);\r
136                 \r
137                 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
138                 \r
139                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
140                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
141                         BOOST_THROW_EXCEPTION(caspar_exception() \r
142                                                                         << msg_info(print() + L" Could not enable video input.")\r
143                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
144 \r
145                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(in_format_desc.audio_channels)))) \r
146                         BOOST_THROW_EXCEPTION(caspar_exception() \r
147                                                                         << msg_info(print() + L" Could not enable audio input.")\r
148                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
149                         \r
150                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
151                         BOOST_THROW_EXCEPTION(caspar_exception() \r
152                                                                         << msg_info(print() + L" Failed to set input callback.")\r
153                                                                         << boost::errinfo_api_function("SetCallback"));\r
154                         \r
155                 if(FAILED(input_->StartStreams()))\r
156                         BOOST_THROW_EXCEPTION(caspar_exception() \r
157                                                                         << msg_info(print() + L" Failed to start input stream.")\r
158                                                                         << boost::errinfo_api_function("StartStreams"));\r
159 \r
160                 CASPAR_LOG(info) << print() << L" Initialized";\r
161         }\r
162 \r
163         ~decklink_producer()\r
164         {\r
165                 if(input_ != nullptr) \r
166                 {\r
167                         input_->StopStreams();\r
168                         input_->DisableVideoInput();\r
169                 }\r
170         }\r
171 \r
172         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
173         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
174         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
175                 \r
176         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
177         {\r
178                 return S_OK;\r
179         }\r
180 \r
181         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
182         {       \r
183                 if(!video)\r
184                         return S_OK;\r
185 \r
186                 try\r
187                 {\r
188                         graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);\r
189                         tick_timer_.restart();\r
190 \r
191                         frame_timer_.restart();\r
192 \r
193                         // PUSH\r
194 \r
195                         void* bytes = nullptr;\r
196                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
197                                 return S_OK;\r
198                         \r
199                         spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);      \r
200                         avcodec_get_frame_defaults(av_frame.get());\r
201                                                 \r
202                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
203                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
204                         av_frame->format                        = PIX_FMT_UYVY422;\r
205                         av_frame->width                         = video->GetWidth();\r
206                         av_frame->height                        = video->GetHeight();\r
207                         av_frame->interlaced_frame      = in_format_desc_.field_mode != core::field_mode::progressive;\r
208                         av_frame->top_field_first       = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
209                                 \r
210                         std::shared_ptr<core::audio_buffer> audio_buffer;\r
211 \r
212                         // It is assumed that audio is always equal or ahead of video.\r
213                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)\r
214                         {\r
215                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
216                                 auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
217                                 audio_buffer = std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*out_format_desc_.audio_channels);\r
218                         }\r
219                         else                    \r
220                                 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0);\r
221                         \r
222                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)\r
223                         // This cadence fills the audio mixer most optimally.\r
224 \r
225                         sync_buffer_.push_back(audio_buffer->size());           \r
226                         if(!boost::range::equal(sync_buffer_, audio_cadence_))\r
227                         {\r
228                                 CASPAR_LOG(trace) << print() << L" Syncing audio.";\r
229                                 return S_OK;\r
230                         }\r
231 \r
232                         muxer_.push(audio_buffer);\r
233                         muxer_.push(av_frame, flags_);  \r
234                                                                                         \r
235                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);\r
236                         \r
237                         // POLL\r
238 \r
239                         auto frame = core::draw_frame::late();\r
240                         if(muxer_.try_pop(frame))\r
241                         {\r
242                                 if(!frame_buffer_.try_push(frame))\r
243                                         graph_->set_tag("dropped-frame");\r
244                         }\r
245                         \r
246                         graph_->set_value("frame-time", frame_timer_.elapsed()*out_format_desc_.fps*0.5);\r
247 \r
248                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
249                 }\r
250                 catch(...)\r
251                 {\r
252                         exception_ = std::current_exception();\r
253                         return E_FAIL;\r
254                 }\r
255 \r
256                 return S_OK;\r
257         }\r
258         \r
259         core::draw_frame get_frame(int flags)\r
260         {\r
261                 if(exception_ != nullptr)\r
262                         std::rethrow_exception(exception_);\r
263 \r
264                 flags_ = flags;\r
265 \r
266                 core::draw_frame frame = core::draw_frame::late();\r
267                 if(!frame_buffer_.try_pop(frame))\r
268                         graph_->set_tag("late-frame");\r
269                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
270                 return frame;\r
271         }\r
272         \r
273         std::wstring print() const\r
274         {\r
275                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";\r
276         }\r
277 };\r
278         \r
279 class decklink_producer_proxy : public core::frame_producer\r
280 {               \r
281         std::unique_ptr<decklink_producer>      producer_;\r
282         const uint32_t                                          length_;\r
283         core::draw_frame                                        last_frame_;\r
284         executor                                                        executor_;\r
285 public:\r
286         explicit decklink_producer_proxy(const core::video_format_desc& in_format_desc,\r
287                                                                          const spl::shared_ptr<core::frame_factory>& frame_factory, \r
288                                                                          const core::video_format_desc& out_format_desc, \r
289                                                                          int device_index,\r
290                                                                          const std::wstring& filter_str, uint32_t length)\r
291                 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
292                 , length_(length)\r
293                 , last_frame_(core::draw_frame::empty())\r
294         {\r
295                 executor_.invoke([=]\r
296                 {\r
297                         CoInitialize(nullptr);\r
298                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, filter_str));\r
299                 });\r
300         }\r
301 \r
302         ~decklink_producer_proxy()\r
303         {               \r
304                 executor_.invoke([=]\r
305                 {\r
306                         producer_.reset();\r
307                         CoUninitialize();\r
308                 });\r
309         }\r
310         \r
311         // frame_producer\r
312                                 \r
313         virtual core::draw_frame receive(int flags) override\r
314         {\r
315                 auto frame = producer_->get_frame(flags);\r
316 \r
317                 if(frame != core::draw_frame::late())\r
318                         last_frame_ = frame;\r
319 \r
320                 return frame;\r
321         }\r
322 \r
323         virtual core::draw_frame last_frame() const override\r
324         {\r
325                 return core::draw_frame::still(last_frame_);\r
326         }\r
327                 \r
328         virtual uint32_t nb_frames() const override\r
329         {\r
330                 return length_;\r
331         }\r
332         \r
333         virtual std::wstring print() const override\r
334         {\r
335                 return producer_->print();\r
336         }\r
337         \r
338         virtual std::wstring name() const override\r
339         {\r
340                 return L"decklink";\r
341         }\r
342 \r
343         virtual boost::property_tree::wptree info() const override\r
344         {\r
345                 boost::property_tree::wptree info;\r
346                 info.add(L"type", L"decklink");\r
347                 return info;\r
348         }\r
349 };\r
350 \r
351 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& out_format_desc, const std::vector<std::wstring>& params)\r
352 {\r
353         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
354                 return core::frame_producer::empty();\r
355 \r
356         auto device_index       = get_param(L"DEVICE", params, -1);\r
357         if(device_index == -1)\r
358                 device_index = boost::lexical_cast<int>(params.at(1));\r
359         \r
360         auto filter_str         = get_param(L"FILTER", params);         \r
361         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   \r
362         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));\r
363         \r
364         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
365         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
366         \r
367         if(in_format_desc.format == core::video_format::invalid)\r
368                 in_format_desc = out_format_desc;\r
369                         \r
370         return spl::make_shared<decklink_producer_proxy>(in_format_desc, frame_factory, out_format_desc, device_index, filter_str, length);\r
371 }\r
372 \r
373 }}