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