]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
2.0.0.2: Refactoring. Working on re-enabling filter functionality.
[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 \r
31 #include <common/diagnostics/graph.h>\r
32 #include <common/concurrency/com_context.h>\r
33 #include <common/exception/exceptions.h>\r
34 #include <common/memory/memclr.h>\r
35 \r
36 #include <core/mixer/write_frame.h>\r
37 #include <core/producer/frame/audio_transform.h>\r
38 #include <core/producer/frame/frame_factory.h>\r
39 #include <core/producer/frame_muxer.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 : 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         std::vector<int16_t>                                                                            audio_samples_;\r
89         \r
90         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
91 \r
92         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
93         safe_ptr<core::basic_frame>                                                                     tail_;\r
94 \r
95         std::exception_ptr                                                                                      exception_;\r
96         std::unique_ptr<filter>                                                                         filter_;\r
97                 \r
98         core::frame_muxer                                                                                       muxer_;\r
99 \r
100 public:\r
101         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
102                 : decklink_(get_device(device_index))\r
103                 , input_(decklink_)\r
104                 , model_name_(get_model_name(decklink_))\r
105                 , format_desc_(format_desc)\r
106                 , device_index_(device_index)\r
107                 , frame_factory_(frame_factory)\r
108                 , tail_(core::basic_frame::empty())\r
109                 , filter_(filter.empty() ? nullptr : new caspar::filter(filter))\r
110                 , muxer_(double_rate(filter) ? format_desc.fps * 2.0 : format_desc.fps, frame_factory->get_video_format_desc().mode, frame_factory->get_video_format_desc().fps)\r
111         {\r
112                 frame_buffer_.set_capacity(2);\r
113                 \r
114                 graph_ = diagnostics::create_graph(boost::bind(&decklink_producer::print, this));\r
115                 graph_->add_guide("tick-time", 0.5);\r
116                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
117                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
118                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
119                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
120                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
121                 \r
122                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
123                 \r
124                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
125                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
126                         BOOST_THROW_EXCEPTION(caspar_exception() \r
127                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
128                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
129 \r
130                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
131                         BOOST_THROW_EXCEPTION(caspar_exception() \r
132                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
133                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
134                         \r
135                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
136                         BOOST_THROW_EXCEPTION(caspar_exception() \r
137                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
138                                                                         << boost::errinfo_api_function("SetCallback"));\r
139                         \r
140                 if(FAILED(input_->StartStreams()))\r
141                         BOOST_THROW_EXCEPTION(caspar_exception() \r
142                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
143                                                                         << boost::errinfo_api_function("StartStreams"));\r
144 \r
145                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
146         }\r
147 \r
148         ~decklink_producer()\r
149         {\r
150                 if(input_ != nullptr) \r
151                 {\r
152                         input_->StopStreams();\r
153                         input_->DisableVideoInput();\r
154                 }\r
155         }\r
156 \r
157         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
158         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
159         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
160                 \r
161         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
162         {\r
163                 return S_OK;\r
164         }\r
165 \r
166         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
167         {       \r
168                 if(!video)\r
169                         return S_OK;\r
170 \r
171                 try\r
172                 {\r
173                         auto result = core::basic_frame::empty();\r
174 \r
175                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
176                         tick_timer_.restart();\r
177 \r
178                         frame_timer_.restart();\r
179                                                 \r
180                         core::pixel_format_desc desc;\r
181                         desc.pix_fmt = core::pixel_format::ycbcr;\r
182                         desc.planes.push_back(core::pixel_format_desc::plane(video->GetWidth(),   video->GetHeight(), 1));\r
183                         desc.planes.push_back(core::pixel_format_desc::plane(video->GetWidth()/2, video->GetHeight(), 1));\r
184                         desc.planes.push_back(core::pixel_format_desc::plane(video->GetWidth()/2, video->GetHeight(), 1));                      \r
185                         auto frame = frame_factory_->create_frame(this, desc);\r
186                                                 \r
187                         void* bytes = nullptr;\r
188                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
189                                 return S_OK;\r
190 \r
191                         unsigned char* data = reinterpret_cast<unsigned char*>(bytes);\r
192                         const size_t frame_size = (format_desc_.width * 16 / 8) * format_desc_.height;\r
193 \r
194                         // Convert to planar YUV422\r
195                         unsigned char* y  = frame->image_data(0).begin();\r
196                         unsigned char* cb = frame->image_data(1).begin();\r
197                         unsigned char* cr = frame->image_data(2).begin();\r
198                 \r
199                         tbb::parallel_for(tbb::blocked_range<size_t>(0, frame_size/4), [&](const tbb::blocked_range<size_t>& r)\r
200                         {\r
201                                 for(auto n = r.begin(); n != r.end(); ++n)\r
202                                 {\r
203                                         cb[n]     = data[n*4+0];\r
204                                         y [n*2+0] = data[n*4+1];\r
205                                         cr[n]     = data[n*4+2];\r
206                                         y [n*2+1] = data[n*4+3];\r
207                                 }\r
208                         });\r
209                         frame->set_type(format_desc_.mode);\r
210                         \r
211                         std::vector<safe_ptr<core::write_frame>> frames;\r
212 \r
213                         if(filter_)\r
214                         {\r
215                                 filter_->push(as_av_frame(frame));\r
216                                 auto av_frames = filter_->poll();\r
217                                 BOOST_FOREACH(auto& av_frame, av_frames)\r
218                                         frames.push_back(make_write_frame(this, av_frame, frame_factory_));\r
219                         }\r
220                         else\r
221                         {\r
222                                 frame->commit();\r
223                                 frames.push_back(frame);\r
224                         }\r
225 \r
226                         BOOST_FOREACH(auto frame, frames)\r
227                                 muxer_.push(frame);\r
228                                                 \r
229                         // It is assumed that audio is always equal or ahead of video.\r
230                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
231                         {\r
232                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
233                                 auto audio_data = reinterpret_cast<short*>(bytes);\r
234                                 audio_samples_.insert(audio_samples_.end(), audio_data, audio_data + sample_frame_count*2);\r
235 \r
236                                 if(audio_samples_.size() > frame_factory_->get_video_format_desc().audio_samples_per_frame)\r
237                                 {\r
238                                         const auto begin = audio_samples_.begin();\r
239                                         const auto end   = begin +  frame_factory_->get_video_format_desc().audio_samples_per_frame;\r
240                                         muxer_.push(std::vector<int16_t>(begin, end));\r
241                                         audio_samples_.erase(begin, end);\r
242                                 }\r
243                         }\r
244                         else\r
245                                 muxer_.push(std::vector<int16_t>(frame_factory_->get_video_format_desc().audio_samples_per_frame, 0));\r
246                                         \r
247                         while(!muxer_.empty())\r
248                         {\r
249                                 if(!frame_buffer_.try_push(muxer_.pop()))\r
250                                         graph_->add_tag("dropped-frame");\r
251                         }\r
252 \r
253                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
254 \r
255                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
256                 }\r
257                 catch(...)\r
258                 {\r
259                         exception_ = std::current_exception();\r
260                         return E_FAIL;\r
261                 }\r
262 \r
263                 return S_OK;\r
264         }\r
265         \r
266         safe_ptr<core::basic_frame> get_frame()\r
267         {\r
268                 if(exception_ != nullptr)\r
269                         std::rethrow_exception(exception_);\r
270 \r
271                 if(!frame_buffer_.try_pop(tail_))\r
272                         graph_->add_tag("late-frame");\r
273                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
274                 return tail_;\r
275         }\r
276         \r
277         std::wstring print() const\r
278         {\r
279                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
280         }\r
281 };\r
282         \r
283 class decklink_producer_proxy : public core::frame_producer\r
284 {               \r
285         com_context<decklink_producer> context_;\r
286 public:\r
287 \r
288         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
289                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
290         {\r
291                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
292         }\r
293                                 \r
294         virtual safe_ptr<core::basic_frame> receive()\r
295         {\r
296                 return context_->get_frame();\r
297         }\r
298         \r
299         std::wstring print() const\r
300         {\r
301                 return context_->print();\r
302         }\r
303 };\r
304 \r
305 safe_ptr<core::frame_producer> create_decklink_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
306 {\r
307         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
308                 return core::frame_producer::empty();\r
309 \r
310         size_t device_index = 1;\r
311         if(params.size() > 1)\r
312                 device_index = lexical_cast_or_default(params[1], 1);\r
313 \r
314         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
315         if(params.size() > 2)\r
316         {\r
317                 auto desc = core::video_format_desc::get(params[2]);\r
318                 if(desc.format != core::video_format::invalid)\r
319                         format_desc = desc;\r
320         }\r
321         \r
322         std::wstring filter_str = L"";\r
323 \r
324         auto filter_it = std::find(params.begin(), params.end(), L"FILTER");\r
325         if(filter_it != params.end())\r
326         {\r
327                 if(++filter_it != params.end())\r
328                         filter_str = *filter_it;\r
329         }\r
330 \r
331         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str);\r
332 }\r
333 \r
334 }