]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
f1933b7f928cdfa4a8b8e619b5a113ab9cf40647
[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                                                                                            tick_timer_;\r
161         boost::timer                                                                                            frame_timer_;\r
162         \r
163         std::vector<short>                                                                                      audio_data_;\r
164 \r
165         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
166 \r
167         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
168         safe_ptr<core::basic_frame>                                                                     tail_;\r
169 \r
170         std::exception_ptr                                                                                      exception_;\r
171         frame_filter                                                                                            filter_;\r
172 \r
173 public:\r
174         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
175                 : decklink_(get_device(device_index))\r
176                 , input_(decklink_)\r
177                 , model_name_(get_model_name(decklink_))\r
178                 , format_desc_(format_desc)\r
179                 , device_index_(device_index)\r
180                 , frame_factory_(frame_factory)\r
181                 , tail_(core::basic_frame::empty())\r
182                 , filter_(narrow(filter_str), frame_factory_)\r
183         {\r
184                 frame_buffer_.set_capacity(2);\r
185                 \r
186                 graph_ = diagnostics::create_graph(boost::bind(&decklink_producer::print, this));\r
187                 graph_->add_guide("tick-time", 0.5);\r
188                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
189                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
190                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
191                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
192                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
193                 \r
194                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
195                 \r
196                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
197                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
198                         BOOST_THROW_EXCEPTION(caspar_exception() \r
199                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
200                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
201 \r
202                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
203                         BOOST_THROW_EXCEPTION(caspar_exception() \r
204                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
205                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
206                         \r
207                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
208                         BOOST_THROW_EXCEPTION(caspar_exception() \r
209                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
210                                                                         << boost::errinfo_api_function("SetCallback"));\r
211                         \r
212                 if(FAILED(input_->StartStreams()))\r
213                         BOOST_THROW_EXCEPTION(caspar_exception() \r
214                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
215                                                                         << boost::errinfo_api_function("StartStreams"));\r
216 \r
217                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
218         }\r
219 \r
220         ~decklink_producer()\r
221         {\r
222                 if(input_ != nullptr) \r
223                 {\r
224                         input_->StopStreams();\r
225                         input_->DisableVideoInput();\r
226                 }\r
227         }\r
228 \r
229         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
230         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
231         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
232                 \r
233         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
234         {\r
235                 return S_OK;\r
236         }\r
237 \r
238         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
239         {       \r
240                 if(!video || video->GetWidth() != static_cast<int>(format_desc_.width) || video->GetHeight() != static_cast<int>(format_desc_.height))\r
241                         return S_OK;\r
242 \r
243                 try\r
244                 {\r
245                         auto result = core::basic_frame::empty();\r
246 \r
247                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
248                         tick_timer_.restart();\r
249 \r
250                         frame_timer_.restart();\r
251                                                 \r
252                         core::pixel_format_desc desc;\r
253                         desc.pix_fmt = core::pixel_format::ycbcr;\r
254                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width,   format_desc_.height, 1));\r
255                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width/2, format_desc_.height, 1));\r
256                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width/2, format_desc_.height, 1));                    \r
257                         auto frame = frame_factory_->create_frame(this, desc);\r
258                                                 \r
259                         void* bytes = nullptr;\r
260                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
261                                 return S_OK;\r
262 \r
263                         unsigned char* data = reinterpret_cast<unsigned char*>(bytes);\r
264                         const size_t frame_size = (format_desc_.width * 16 / 8) * format_desc_.height;\r
265 \r
266                         // Convert to planar YUV422\r
267                         unsigned char* y  = frame->image_data(0).begin();\r
268                         unsigned char* cb = frame->image_data(1).begin();\r
269                         unsigned char* cr = frame->image_data(2).begin();\r
270                 \r
271                         tbb::parallel_for(tbb::blocked_range<size_t>(0, frame_size/4), [&](const tbb::blocked_range<size_t>& r)\r
272                         {\r
273                                 for(auto n = r.begin(); n != r.end(); ++n)\r
274                                 {\r
275                                         cb[n]     = data[n*4+0];\r
276                                         y [n*2+0] = data[n*4+1];\r
277                                         cr[n]     = data[n*4+2];\r
278                                         y [n*2+1] = data[n*4+3];\r
279                                 }\r
280                         });\r
281                         frame->set_type(format_desc_.mode);\r
282                         \r
283                         // It is assumed that audio is always equal or ahead of video.\r
284                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
285                         {\r
286                                 const size_t audio_samples = static_cast<size_t>(48000.0 / format_desc_.fps);\r
287                                 const size_t audio_nchannels = 2;\r
288 \r
289                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
290                                 auto audio_data = reinterpret_cast<short*>(bytes);\r
291                                 audio_data_.insert(audio_data_.end(), audio_data, audio_data + sample_frame_count*2);\r
292 \r
293                                 if(audio_data_.size() > audio_samples*audio_nchannels)\r
294                                 {\r
295                                         frame->audio_data() = std::vector<short>(audio_data_.begin(), audio_data_.begin() +  audio_samples*audio_nchannels);\r
296                                         audio_data_.erase(audio_data_.begin(), audio_data_.begin() +  audio_samples*audio_nchannels);\r
297                                 }\r
298                         }\r
299                 \r
300                         filter_.execute(frame, result);         \r
301                         \r
302                         if(!frame_buffer_.try_push(result))\r
303                                 graph_->add_tag("dropped-frame");\r
304                         \r
305                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
306 \r
307                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
308                 }\r
309                 catch(...)\r
310                 {\r
311                         exception_ = std::current_exception();\r
312                         return E_FAIL;\r
313                 }\r
314 \r
315                 return S_OK;\r
316         }\r
317         \r
318         safe_ptr<core::basic_frame> get_frame()\r
319         {\r
320                 if(exception_ != nullptr)\r
321                         std::rethrow_exception(exception_);\r
322 \r
323                 if(!frame_buffer_.try_pop(tail_))\r
324                         graph_->add_tag("late-frame");\r
325                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
326                 return tail_;\r
327         }\r
328         \r
329         std::wstring print() const\r
330         {\r
331                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
332         }\r
333 };\r
334         \r
335 class decklink_producer_proxy : public core::frame_producer\r
336 {               \r
337         com_context<decklink_producer> context_;\r
338 public:\r
339 \r
340         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
341                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
342         {\r
343                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
344         }\r
345                                 \r
346         virtual safe_ptr<core::basic_frame> receive()\r
347         {\r
348                 return context_->get_frame();\r
349         }\r
350         \r
351         std::wstring print() const\r
352         {\r
353                 return context_->print();\r
354         }\r
355 };\r
356 \r
357 safe_ptr<core::frame_producer> create_decklink_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
358 {\r
359         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
360                 return core::frame_producer::empty();\r
361 \r
362         size_t device_index = 1;\r
363         if(params.size() > 1)\r
364                 device_index = lexical_cast_or_default(params[1], 1);\r
365 \r
366         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
367         if(params.size() > 2)\r
368         {\r
369                 auto desc = core::video_format_desc::get(params[2]);\r
370                 if(desc.format != core::video_format::invalid)\r
371                         format_desc = desc;\r
372         }\r
373         \r
374         std::wstring filter_str = L"";\r
375 \r
376         auto filter_it = std::find(params.begin(), params.end(), L"FILTER");\r
377         if(filter_it != params.end())\r
378         {\r
379                 if(++filter_it != params.end())\r
380                         filter_str = *filter_it;\r
381         }\r
382 \r
383         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str);\r
384 }\r
385 \r
386 }