]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
2.0. filter: Yadif filter is scalable without extra delay for up to 16 instances...
[casparcg] / modules / decklink / producer / decklink_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  \r
21 #include "../stdafx.h"\r
22 \r
23 #include "decklink_producer.h"\r
24 \r
25 #include "../interop/DeckLinkAPI_h.h"\r
26 #include "../util/util.h"\r
27 \r
28 #include "../../ffmpeg/producer/filter/filter.h"\r
29 #include "../../ffmpeg/producer/util.h"\r
30 #include "../../ffmpeg/producer/frame_muxer.h"\r
31 \r
32 #include <common/diagnostics/graph.h>\r
33 #include <common/concurrency/com_context.h>\r
34 #include <common/exception/exceptions.h>\r
35 #include <common/memory/memclr.h>\r
36 \r
37 #include <core/mixer/write_frame.h>\r
38 #include <core/producer/frame/audio_transform.h>\r
39 #include <core/producer/frame/frame_factory.h>\r
40 \r
41 #include <tbb/concurrent_queue.h>\r
42 #include <tbb/atomic.h>\r
43 \r
44 #include <boost/algorithm/string.hpp>\r
45 #include <boost/timer.hpp>\r
46 \r
47 #if defined(_MSC_VER)\r
48 #pragma warning (push)\r
49 #pragma warning (disable : 4244)\r
50 #endif\r
51 extern "C" \r
52 {\r
53         #define __STDC_CONSTANT_MACROS\r
54         #define __STDC_LIMIT_MACROS\r
55         #include <libavcodec/avcodec.h>\r
56 }\r
57 #if defined(_MSC_VER)\r
58 #pragma warning (pop)\r
59 #endif\r
60 \r
61 #pragma warning(push)\r
62 #pragma warning(disable : 4996)\r
63 \r
64         #include <atlbase.h>\r
65 \r
66         #include <atlcom.h>\r
67         #include <atlhost.h>\r
68 \r
69 #pragma warning(push)\r
70 \r
71 #include <functional>\r
72 \r
73 namespace caspar { \r
74                 \r
75 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback\r
76 {       \r
77         CComPtr<IDeckLink>                                                                                      decklink_;\r
78         CComQIPtr<IDeckLinkInput>                                                                       input_;\r
79         \r
80         const std::wstring                                                                                      model_name_;\r
81         const core::video_format_desc                                                           format_desc_;\r
82         const size_t                                                                                            device_index_;\r
83 \r
84         std::shared_ptr<diagnostics::graph>                                                     graph_;\r
85         boost::timer                                                                                            tick_timer_;\r
86         boost::timer                                                                                            frame_timer_;\r
87                 \r
88         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
89 \r
90         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
91         safe_ptr<core::basic_frame>                                                                     tail_;\r
92 \r
93         std::exception_ptr                                                                                      exception_;\r
94         filter                                                                                                          filter_;\r
95                 \r
96         frame_muxer                                                                                                     muxer_;\r
97 \r
98 public:\r
99         decklink_producer(const core::video_format_desc& format_desc, size_t device_index, const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filter)\r
100                 : decklink_(get_device(device_index))\r
101                 , input_(decklink_)\r
102                 , model_name_(get_model_name(decklink_))\r
103                 , format_desc_(format_desc)\r
104                 , device_index_(device_index)\r
105                 , frame_factory_(frame_factory)\r
106                 , tail_(core::basic_frame::empty())\r
107                 , filter_(filter)\r
108                 , muxer_(double_rate(filter) ? format_desc.fps * 2.0 : format_desc.fps, frame_factory->get_video_format_desc(), frame_factory)\r
109         {\r
110                 frame_buffer_.set_capacity(2);\r
111                 \r
112                 graph_ = diagnostics::create_graph(boost::bind(&decklink_producer::print, this));\r
113                 graph_->add_guide("tick-time", 0.5);\r
114                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
115                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
116                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
117                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
118                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
119                 \r
120                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
121                 \r
122                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
123                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
124                         BOOST_THROW_EXCEPTION(caspar_exception() \r
125                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
126                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
127 \r
128                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
129                         BOOST_THROW_EXCEPTION(caspar_exception() \r
130                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
131                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
132                         \r
133                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
134                         BOOST_THROW_EXCEPTION(caspar_exception() \r
135                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
136                                                                         << boost::errinfo_api_function("SetCallback"));\r
137                         \r
138                 if(FAILED(input_->StartStreams()))\r
139                         BOOST_THROW_EXCEPTION(caspar_exception() \r
140                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
141                                                                         << boost::errinfo_api_function("StartStreams"));\r
142 \r
143                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
144         }\r
145 \r
146         ~decklink_producer()\r
147         {\r
148                 if(input_ != nullptr) \r
149                 {\r
150                         input_->StopStreams();\r
151                         input_->DisableVideoInput();\r
152                 }\r
153         }\r
154 \r
155         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
156         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
157         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
158                 \r
159         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
160         {\r
161                 return S_OK;\r
162         }\r
163 \r
164         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
165         {       \r
166                 if(!video)\r
167                         return S_OK;\r
168 \r
169                 try\r
170                 {\r
171                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
172                         tick_timer_.restart();\r
173 \r
174                         frame_timer_.restart();\r
175 \r
176                         void* bytes = nullptr;\r
177                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
178                                 return S_OK;\r
179                         \r
180                         safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
181                         avcodec_get_frame_defaults(av_frame.get());\r
182                                                 \r
183                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
184                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
185                         av_frame->format                        = PIX_FMT_UYVY422;\r
186                         av_frame->width                         = video->GetWidth();\r
187                         av_frame->height                        = video->GetHeight();\r
188                         av_frame->interlaced_frame      = format_desc_.mode != core::video_mode::progressive;\r
189                         av_frame->top_field_first       = format_desc_.mode == core::video_mode::upper ? 1 : 0;\r
190                                         \r
191                         BOOST_FOREACH(auto& av_frame2, filter_.execute(av_frame))\r
192                                 muxer_.push(make_write_frame(this, av_frame2, frame_factory_));         \r
193                                                                         \r
194                         // It is assumed that audio is always equal or ahead of video.\r
195                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
196                         {\r
197                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
198                                 auto audio_data = reinterpret_cast<short*>(bytes);\r
199                                 muxer_.push(std::make_shared<std::vector<int16_t>>(audio_data, audio_data + sample_frame_count*2));\r
200                         }\r
201                         else\r
202                                 muxer_.push(std::make_shared<std::vector<int16_t>>(frame_factory_->get_video_format_desc().audio_samples_per_frame, 0));\r
203                                         \r
204                         while(!muxer_.empty())\r
205                         {\r
206                                 if(!frame_buffer_.try_push(muxer_.pop()))\r
207                                         graph_->add_tag("dropped-frame");\r
208                         }\r
209 \r
210                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
211 \r
212                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
213                 }\r
214                 catch(...)\r
215                 {\r
216                         exception_ = std::current_exception();\r
217                         return E_FAIL;\r
218                 }\r
219 \r
220                 return S_OK;\r
221         }\r
222         \r
223         safe_ptr<core::basic_frame> get_frame()\r
224         {\r
225                 if(exception_ != nullptr)\r
226                         std::rethrow_exception(exception_);\r
227 \r
228                 if(!frame_buffer_.try_pop(tail_))\r
229                         graph_->add_tag("late-frame");\r
230                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
231                 return tail_;\r
232         }\r
233         \r
234         std::wstring print() const\r
235         {\r
236                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
237         }\r
238 };\r
239         \r
240 class decklink_producer_proxy : public core::frame_producer\r
241 {               \r
242         com_context<decklink_producer> context_;\r
243 public:\r
244 \r
245         explicit decklink_producer_proxy(const safe_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, size_t device_index, const std::wstring& filter_str = L"")\r
246                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
247         {\r
248                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
249         }\r
250                                 \r
251         virtual safe_ptr<core::basic_frame> receive()\r
252         {\r
253                 return context_->get_frame();\r
254         }\r
255         \r
256         std::wstring print() const\r
257         {\r
258                 return context_->print();\r
259         }\r
260 };\r
261 \r
262 safe_ptr<core::frame_producer> create_decklink_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
263 {\r
264         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
265                 return core::frame_producer::empty();\r
266 \r
267         size_t device_index = 1;\r
268         if(params.size() > 1)\r
269                 device_index = lexical_cast_or_default(params[1], 1);\r
270 \r
271         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
272         if(params.size() > 2)\r
273         {\r
274                 auto desc = core::video_format_desc::get(params[2]);\r
275                 if(desc.format != core::video_format::invalid)\r
276                         format_desc = desc;\r
277         }\r
278         \r
279         std::wstring filter_str = L"";\r
280 \r
281         auto filter_it = std::find(params.begin(), params.end(), L"FILTER");\r
282         if(filter_it != params.end())\r
283         {\r
284                 if(++filter_it != params.end())\r
285                         filter_str = *filter_it;\r
286         }\r
287 \r
288         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str);\r
289 }\r
290 \r
291 }