]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
06eca9c28f462bf51425f5dd52056ca27f1eb232
[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/producer/frame/frame_factory.h>\r
37 #include <core/mixer/write_frame.h>\r
38 #include <core/producer/frame/audio_transform.h>\r
39 \r
40 #include <tbb/concurrent_queue.h>\r
41 #include <tbb/atomic.h>\r
42 #include <tbb/task_group.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 frame_filter\r
76 {\r
77         std::unique_ptr<filter>                                 filter_;\r
78         safe_ptr<core::frame_factory>                   frame_factory_;\r
79         std::deque<std::vector<int16_t>>                audio_buffer_;\r
80         tbb::task_group                                                 task_group_;\r
81 \r
82         std::vector<safe_ptr<AVFrame>>                  buffer_;\r
83 \r
84 public:\r
85         frame_filter(const std::string& filter_str, const safe_ptr<core::frame_factory>& frame_factory) \r
86                 : filter_(filter_str.empty() ? nullptr : new filter(filter_str))\r
87                 , frame_factory_(frame_factory)\r
88         {\r
89         }\r
90 \r
91         bool execute(const safe_ptr<core::write_frame>& input_frame, safe_ptr<core::basic_frame>& output_frame)\r
92         {               \r
93                 if(!filter_)\r
94                 {\r
95                         input_frame->commit();\r
96                         output_frame = input_frame;\r
97                         return true;\r
98                 }\r
99                 \r
100                 auto desc = input_frame->get_pixel_format_desc();\r
101 \r
102                 auto av_frame = as_av_frame(input_frame);\r
103 \r
104                 audio_buffer_.push_back(std::move(input_frame->audio_data()));\r
105                 \r
106                 task_group_.wait();\r
107 \r
108                 filter_->push(av_frame);                \r
109                 \r
110                 bool result = try_pop(output_frame);\r
111 \r
112                 task_group_.run([this]\r
113                 {\r
114                         buffer_ = filter_->poll();\r
115                 });\r
116 \r
117                 return result;  \r
118         }\r
119 \r
120 private:                \r
121 \r
122         bool try_pop(safe_ptr<core::basic_frame>& output)\r
123         {\r
124                 if(buffer_.empty())\r
125                         return false;\r
126 \r
127                 auto audio_data = std::move(audio_buffer_.front());\r
128                 audio_buffer_.pop_back();\r
129 \r
130                 if(buffer_.size() == 2)\r
131                 {\r
132                         auto frame1 = make_write_frame(this, buffer_[0], frame_factory_);\r
133                         auto frame2 = make_write_frame(this, buffer_[1], frame_factory_);\r
134                         frame1->audio_data() = std::move(audio_data);\r
135                         frame2->get_audio_transform().set_has_audio(false);\r
136                         output = core::basic_frame::interlace(frame1, frame2, frame_factory_->get_video_format_desc().mode);\r
137                 }\r
138                 else if(buffer_.size() > 0)\r
139                 {\r
140                         auto frame1 = make_write_frame(this, buffer_[0], frame_factory_);\r
141                         frame1->audio_data() = std::move(audio_data);\r
142                         output = frame1;\r
143                 }\r
144                 buffer_.clear();\r
145 \r
146                 return true;\r
147         }\r
148 };\r
149         \r
150 class decklink_producer : public IDeckLinkInputCallback\r
151 {       \r
152         CComPtr<IDeckLink>                                                                                      decklink_;\r
153         CComQIPtr<IDeckLinkInput>                                                                       input_;\r
154         \r
155         const std::wstring                                                                                      model_name_;\r
156         const core::video_format_desc                                                           format_desc_;\r
157         const size_t                                                                                            device_index_;\r
158 \r
159         std::shared_ptr<diagnostics::graph>                                                     graph_;\r
160         boost::timer                                                                                            perf_timer_;\r
161         \r
162         std::vector<short>                                                                                      audio_data_;\r
163 \r
164         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
165 \r
166         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
167         safe_ptr<core::basic_frame>                                                                     tail_;\r
168 \r
169         std::exception_ptr                                                                                      exception_;\r
170         frame_filter                                                                                            filter_;\r
171 \r
172 public:\r
173         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_str)\r
174                 : decklink_(get_device(device_index))\r
175                 , input_(decklink_)\r
176                 , model_name_(get_model_name(decklink_))\r
177                 , format_desc_(format_desc)\r
178                 , device_index_(device_index)\r
179                 , frame_factory_(frame_factory)\r
180                 , tail_(core::basic_frame::empty())\r
181                 , filter_(narrow(filter_str), frame_factory_)\r
182         {\r
183                 frame_buffer_.set_capacity(2);\r
184                 \r
185                 graph_ = diagnostics::create_graph(boost::bind(&decklink_producer::print, this));\r
186                 graph_->add_guide("tick-time", 0.5);\r
187                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
188                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
189                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
190                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
191                 \r
192                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
193                 \r
194                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
195                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
196                         BOOST_THROW_EXCEPTION(caspar_exception() \r
197                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
198                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
199 \r
200                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
201                         BOOST_THROW_EXCEPTION(caspar_exception() \r
202                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
203                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
204                         \r
205                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
206                         BOOST_THROW_EXCEPTION(caspar_exception() \r
207                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
208                                                                         << boost::errinfo_api_function("SetCallback"));\r
209                         \r
210                 if(FAILED(input_->StartStreams()))\r
211                         BOOST_THROW_EXCEPTION(caspar_exception() \r
212                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
213                                                                         << boost::errinfo_api_function("StartStreams"));\r
214 \r
215                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
216         }\r
217 \r
218         ~decklink_producer()\r
219         {\r
220                 if(input_ != nullptr) \r
221                 {\r
222                         input_->StopStreams();\r
223                         input_->DisableVideoInput();\r
224                 }\r
225         }\r
226 \r
227         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
228         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
229         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
230                 \r
231         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
232         {\r
233                 return S_OK;\r
234         }\r
235 \r
236         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
237         {       \r
238                 if(!video || video->GetWidth() != static_cast<int>(format_desc_.width) || video->GetHeight() != static_cast<int>(format_desc_.height))\r
239                         return S_OK;\r
240 \r
241                 try\r
242                 {\r
243                         auto result = core::basic_frame::empty();\r
244 \r
245                         graph_->update_value("tick-time", perf_timer_.elapsed()*format_desc_.fps*0.5);\r
246                         perf_timer_.restart();\r
247                                                 \r
248                         core::pixel_format_desc desc;\r
249                         desc.pix_fmt = core::pixel_format::ycbcr;\r
250                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width,   format_desc_.height, 1));\r
251                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width/2, format_desc_.height, 1));\r
252                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width/2, format_desc_.height, 1));                    \r
253                         auto frame = frame_factory_->create_frame(this, desc);\r
254                                                 \r
255                         void* bytes = nullptr;\r
256                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
257                                 return S_OK;\r
258 \r
259                         unsigned char* data = reinterpret_cast<unsigned char*>(bytes);\r
260                         const size_t frame_size = (format_desc_.width * 16 / 8) * format_desc_.height;\r
261 \r
262                         // Convert to planar YUV422\r
263                         unsigned char* y  = frame->image_data(0).begin();\r
264                         unsigned char* cb = frame->image_data(1).begin();\r
265                         unsigned char* cr = frame->image_data(2).begin();\r
266                 \r
267                         tbb::parallel_for(tbb::blocked_range<size_t>(0, frame_size/4), [&](const tbb::blocked_range<size_t>& r)\r
268                         {\r
269                                 for(auto n = r.begin(); n != r.end(); ++n)\r
270                                 {\r
271                                         cb[n]     = data[n*4+0];\r
272                                         y [n*2+0] = data[n*4+1];\r
273                                         cr[n]     = data[n*4+2];\r
274                                         y [n*2+1] = data[n*4+3];\r
275                                 }\r
276                         });\r
277                         frame->set_type(format_desc_.mode);\r
278                         \r
279                         // It is assumed that audio is always equal or ahead of video.\r
280                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
281                         {\r
282                                 const size_t audio_samples = static_cast<size_t>(48000.0 / format_desc_.fps);\r
283                                 const size_t audio_nchannels = 2;\r
284 \r
285                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
286                                 auto audio_data = reinterpret_cast<short*>(bytes);\r
287                                 audio_data_.insert(audio_data_.end(), audio_data, audio_data + sample_frame_count*2);\r
288 \r
289                                 if(audio_data_.size() > audio_samples*audio_nchannels)\r
290                                 {\r
291                                         frame->audio_data() = std::vector<short>(audio_data_.begin(), audio_data_.begin() +  audio_samples*audio_nchannels);\r
292                                         audio_data_.erase(audio_data_.begin(), audio_data_.begin() +  audio_samples*audio_nchannels);\r
293                                 }\r
294                         }\r
295                 \r
296                         filter_.execute(frame, result);         \r
297                         \r
298                         if(!frame_buffer_.try_push(result))\r
299                                 graph_->add_tag("dropped-frame");\r
300 \r
301                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
302                 }\r
303                 catch(...)\r
304                 {\r
305                         exception_ = std::current_exception();\r
306                         return E_FAIL;\r
307                 }\r
308 \r
309                 return S_OK;\r
310         }\r
311         \r
312         safe_ptr<core::basic_frame> get_frame()\r
313         {\r
314                 if(exception_ != nullptr)\r
315                         std::rethrow_exception(exception_);\r
316 \r
317                 if(!frame_buffer_.try_pop(tail_))\r
318                         graph_->add_tag("late-frame");\r
319                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
320                 return tail_;\r
321         }\r
322         \r
323         std::wstring print() const\r
324         {\r
325                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
326         }\r
327 };\r
328         \r
329 class decklink_producer_proxy : public core::frame_producer\r
330 {               \r
331         com_context<decklink_producer> context_;\r
332 public:\r
333 \r
334         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
335                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
336         {\r
337                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
338         }\r
339                                 \r
340         virtual safe_ptr<core::basic_frame> receive()\r
341         {\r
342                 return context_->get_frame();\r
343         }\r
344         \r
345         std::wstring print() const\r
346         {\r
347                 return context_->print();\r
348         }\r
349 };\r
350 \r
351 safe_ptr<core::frame_producer> create_decklink_producer(const safe_ptr<core::frame_factory>& frame_factory, 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         size_t device_index = 1;\r
357         if(params.size() > 1)\r
358                 device_index = lexical_cast_or_default(params[1], 1);\r
359 \r
360         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
361         if(params.size() > 2)\r
362         {\r
363                 auto desc = core::video_format_desc::get(params[2]);\r
364                 if(desc.format != core::video_format::invalid)\r
365                         format_desc = desc;\r
366         }\r
367         \r
368         std::wstring filter_str = L"";\r
369 \r
370         auto filter_it = std::find(params.begin(), params.end(), L"FILTER");\r
371         if(filter_it != params.end())\r
372         {\r
373                 if(++filter_it != params.end())\r
374                         filter_str = *filter_it;\r
375         }\r
376 \r
377         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str);\r
378 }\r
379 \r
380 }