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