]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
2.1.0: -Removed LTCG for faster compiling. -Removed audio truncation with mismatch...
[casparcg] / modules / decklink / producer / decklink_producer.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\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 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 #include "../stdafx.h"\r
23 \r
24 #include "decklink_producer.h"\r
25 \r
26 #include "../interop/DeckLinkAPI_h.h"\r
27 #include "../util/util.h"\r
28 \r
29 #include "../../ffmpeg/producer/filter/filter.h"\r
30 #include "../../ffmpeg/producer/util/util.h"\r
31 #include "../../ffmpeg/producer/muxer/frame_muxer.h"\r
32 #include "../../ffmpeg/producer/muxer/display_mode.h"\r
33 \r
34 #include <common/executor.h>\r
35 #include <common/diagnostics/graph.h>\r
36 #include <common/except.h>\r
37 #include <common/log.h>\r
38 #include <common/param.h>\r
39 \r
40 #include <core/frame/frame.h>\r
41 #include <core/frame/draw_frame.h>\r
42 #include <core/frame/frame_transform.h>\r
43 #include <core/frame/frame_factory.h>\r
44 #include <core/monitor/monitor.h>\r
45 #include <core/mixer/audio/audio_mixer.h>\r
46 \r
47 #include <tbb/concurrent_queue.h>\r
48 \r
49 #include <boost/algorithm/string.hpp>\r
50 #include <boost/foreach.hpp>\r
51 #include <boost/property_tree/ptree.hpp>\r
52 #include <boost/timer.hpp>\r
53 \r
54 #if defined(_MSC_VER)\r
55 #pragma warning (push)\r
56 #pragma warning (disable : 4244)\r
57 #endif\r
58 extern "C" \r
59 {\r
60         #define __STDC_CONSTANT_MACROS\r
61         #define __STDC_LIMIT_MACROS\r
62         #include <libavcodec/avcodec.h>\r
63 }\r
64 #if defined(_MSC_VER)\r
65 #pragma warning (pop)\r
66 #endif\r
67 \r
68 #pragma warning(push)\r
69 #pragma warning(disable : 4996)\r
70 \r
71         #include <atlbase.h>\r
72 \r
73         #include <atlcom.h>\r
74         #include <atlhost.h>\r
75 \r
76 #pragma warning(push)\r
77 \r
78 #include <functional>\r
79 \r
80 namespace caspar { namespace decklink {\r
81                 \r
82 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback\r
83 {       \r
84         monitor::basic_subject                                                  event_subject_;\r
85         spl::shared_ptr<diagnostics::graph>                             graph_;\r
86         boost::timer                                                                    tick_timer_;\r
87 \r
88         CComPtr<IDeckLink>                                                              decklink_;\r
89         CComQIPtr<IDeckLinkInput>                                               input_;\r
90         CComQIPtr<IDeckLinkAttributes >                                 attributes_;\r
91         \r
92         const std::wstring                                                              model_name_;\r
93         const int                                                                               device_index_;\r
94         const std::wstring                                                              filter_;\r
95         \r
96         std::vector<int>                                                                audio_cadence_;\r
97         boost::circular_buffer<size_t>                                  sync_buffer_;\r
98         ffmpeg::frame_muxer                                                             muxer_;\r
99                         \r
100         spl::shared_ptr<core::frame_factory>                    frame_factory_;\r
101         core::video_format_desc                                                 in_format_desc_;\r
102         core::video_format_desc                                                 out_format_desc_;\r
103 \r
104         tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;\r
105 \r
106         std::exception_ptr                                                              exception_;             \r
107 \r
108 public:\r
109         decklink_producer(const core::video_format_desc& in_format_desc, \r
110                                           int device_index, \r
111                                           const spl::shared_ptr<core::frame_factory>& frame_factory, \r
112                                           const core::video_format_desc& out_format_desc, \r
113                                           const std::wstring& filter)\r
114                 : decklink_(get_device(device_index))\r
115                 , input_(decklink_)\r
116                 , attributes_(decklink_)\r
117                 , model_name_(get_model_name(decklink_))\r
118                 , device_index_(device_index)\r
119                 , filter_(filter)\r
120                 , in_format_desc_(in_format_desc)\r
121                 , out_format_desc_(out_format_desc)\r
122                 , muxer_(in_format_desc.fps, frame_factory, out_format_desc, filter)\r
123                 , audio_cadence_(out_format_desc.audio_cadence)\r
124                 , sync_buffer_(out_format_desc.audio_cadence.size())\r
125                 , frame_factory_(frame_factory)\r
126         {       \r
127                 frame_buffer_.set_capacity(2);\r
128                 \r
129                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
130                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
131                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
132                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
133                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
134                 graph_->set_text(print());\r
135                 diagnostics::register_graph(graph_);\r
136                 \r
137                 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
138                 \r
139                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
140                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
141                         BOOST_THROW_EXCEPTION(caspar_exception() \r
142                                                                         << msg_info(print() + L" Could not enable video input.")\r
143                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
144 \r
145                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(in_format_desc.audio_channels)))) \r
146                         BOOST_THROW_EXCEPTION(caspar_exception() \r
147                                                                         << msg_info(print() + L" Could not enable audio input.")\r
148                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
149                         \r
150                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
151                         BOOST_THROW_EXCEPTION(caspar_exception() \r
152                                                                         << msg_info(print() + L" Failed to set input callback.")\r
153                                                                         << boost::errinfo_api_function("SetCallback"));\r
154                         \r
155                 if(FAILED(input_->StartStreams()))\r
156                         BOOST_THROW_EXCEPTION(caspar_exception() \r
157                                                                         << msg_info(print() + L" Failed to start input stream.")\r
158                                                                         << boost::errinfo_api_function("StartStreams"));\r
159 \r
160                 CASPAR_LOG(info) << print() << L" Initialized";\r
161         }\r
162 \r
163         ~decklink_producer()\r
164         {\r
165                 if(input_ != nullptr) \r
166                 {\r
167                         input_->StopStreams();\r
168                         input_->DisableVideoInput();\r
169                 }\r
170         }\r
171 \r
172         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
173         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
174         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
175                 \r
176         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
177         {\r
178                 return S_OK;\r
179         }\r
180 \r
181         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
182         {       \r
183                 if(!video)\r
184                         return S_OK;\r
185 \r
186                 try\r
187                 {\r
188                         graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);\r
189                         tick_timer_.restart();\r
190 \r
191                         boost::timer frame_timer;       \r
192 \r
193                         // PUSH\r
194 \r
195                         void* bytes = nullptr;\r
196                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
197                                 return S_OK;\r
198                         \r
199                         std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);      \r
200                         avcodec_get_frame_defaults(av_frame.get());\r
201                                                 \r
202                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
203                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
204                         av_frame->format                        = PIX_FMT_UYVY422;\r
205                         av_frame->width                         = video->GetWidth();\r
206                         av_frame->height                        = video->GetHeight();\r
207                         av_frame->interlaced_frame      = in_format_desc_.field_mode != core::field_mode::progressive;\r
208                         av_frame->top_field_first       = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
209                                 \r
210                         event_subject_  << monitor::event("file/name")                          % model_name_\r
211                                                         << monitor::event("file/path")                          % device_index_\r
212                                                         << monitor::event("file/video/width")           % video->GetWidth()\r
213                                                         << monitor::event("file/video/height")          % video->GetHeight()\r
214                                                         << monitor::event("file/video/field")           % u8(!av_frame->interlaced_frame ? "progressive" : (av_frame->top_field_first ? "upper" : "lower"))\r
215                                                         << monitor::event("file/audio/sample-rate")     % 48000\r
216                                                         << monitor::event("file/audio/channels")        % 2\r
217                                                         << monitor::event("file/audio/format")          % u8(av_get_sample_fmt_name(AV_SAMPLE_FMT_S32))\r
218                                                         << monitor::event("file/fps")                           % in_format_desc_.fps;\r
219 \r
220                         std::shared_ptr<core::audio_buffer> audio_buffer;\r
221 \r
222                         // It is assumed that audio is always equal or ahead of video.\r
223                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)\r
224                         {\r
225                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
226                                 auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
227                                 audio_buffer = std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*out_format_desc_.audio_channels);\r
228                         }\r
229                         else                    \r
230                                 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0);\r
231                         \r
232                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)\r
233                         // This cadence fills the audio mixer most optimally.\r
234 \r
235                         sync_buffer_.push_back(audio_buffer->size());           \r
236                         if(!boost::range::equal(sync_buffer_, audio_cadence_))\r
237                         {\r
238                                 CASPAR_LOG(trace) << print() << L" Syncing audio.";\r
239                                 return S_OK;\r
240                         }\r
241                         \r
242                         muxer_.push(av_frame);  \r
243                         muxer_.push(audio_buffer);\r
244                                                                                         \r
245                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);\r
246                         \r
247                         // POLL\r
248 \r
249                         auto frame = core::draw_frame::late();\r
250                         if(!muxer_.empty())\r
251                         {\r
252                                 frame = std::move(muxer_.front());\r
253                                 muxer_.pop();\r
254 \r
255                                 if(!frame_buffer_.try_push(frame))\r
256                                 {\r
257                                         auto dummy = core::draw_frame::empty();\r
258                                         frame_buffer_.try_pop(dummy);\r
259                                         frame_buffer_.try_push(frame);\r
260                                                 \r
261                                         graph_->set_tag("dropped-frame");\r
262                                 }\r
263                         }\r
264                         \r
265                         graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);        \r
266                         event_subject_ << monitor::event("profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;\r
267 \r
268                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
269                         event_subject_ << monitor::event("buffer") % frame_buffer_.size() % frame_buffer_.capacity();\r
270                 }\r
271                 catch(...)\r
272                 {\r
273                         exception_ = std::current_exception();\r
274                         return E_FAIL;\r
275                 }\r
276 \r
277                 return S_OK;\r
278         }\r
279         \r
280         core::draw_frame get_frame()\r
281         {\r
282                 if(exception_ != nullptr)\r
283                         std::rethrow_exception(exception_);\r
284                 \r
285                 core::draw_frame frame = core::draw_frame::late();\r
286                 if(!frame_buffer_.try_pop(frame))\r
287                         graph_->set_tag("late-frame");\r
288                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
289                 return frame;\r
290         }\r
291         \r
292         std::wstring print() const\r
293         {\r
294                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";\r
295         }\r
296 \r
297         void subscribe(const monitor::observable::observer_ptr& o)\r
298         {\r
299                 event_subject_.subscribe(o);\r
300         }\r
301 \r
302         void unsubscribe(const monitor::observable::observer_ptr& o)\r
303         {\r
304                 event_subject_.unsubscribe(o);\r
305         }\r
306 };\r
307         \r
308 class decklink_producer_proxy : public core::frame_producer_base\r
309 {               \r
310         std::unique_ptr<decklink_producer>      producer_;\r
311         const uint32_t                                          length_;\r
312         executor                                                        executor_;\r
313 public:\r
314         explicit decklink_producer_proxy(const core::video_format_desc& in_format_desc,\r
315                                                                          const spl::shared_ptr<core::frame_factory>& frame_factory, \r
316                                                                          const core::video_format_desc& out_format_desc, \r
317                                                                          int device_index,\r
318                                                                          const std::wstring& filter_str, uint32_t length)\r
319                 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
320                 , length_(length)\r
321         {\r
322                 executor_.invoke([=]\r
323                 {\r
324                         CoInitialize(nullptr);\r
325                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, filter_str));\r
326                 });\r
327         }\r
328 \r
329         ~decklink_producer_proxy()\r
330         {               \r
331                 executor_.invoke([=]\r
332                 {\r
333                         producer_.reset();\r
334                         CoUninitialize();\r
335                 });\r
336         }\r
337 \r
338         void subscribe(const monitor::observable::observer_ptr& o) override\r
339         {\r
340                 producer_->subscribe(o);\r
341         }\r
342 \r
343         void unsubscribe(const monitor::observable::observer_ptr& o) override\r
344         {\r
345                 producer_->unsubscribe(o);\r
346         }\r
347         \r
348         // frame_producer\r
349                                 \r
350         core::draw_frame receive_impl() override\r
351         {               \r
352                 return producer_->get_frame();\r
353         }\r
354                         \r
355         uint32_t nb_frames() const override\r
356         {\r
357                 return length_;\r
358         }\r
359         \r
360         std::wstring print() const override\r
361         {\r
362                 return producer_->print();\r
363         }\r
364         \r
365         std::wstring name() const override\r
366         {\r
367                 return L"decklink";\r
368         }\r
369 \r
370         boost::property_tree::wptree info() const override\r
371         {\r
372                 boost::property_tree::wptree info;\r
373                 info.add(L"type", L"decklink");\r
374                 return info;\r
375         }\r
376 };\r
377 \r
378 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& out_format_desc, const std::vector<std::wstring>& params)\r
379 {\r
380         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
381                 return core::frame_producer::empty();\r
382 \r
383         auto device_index       = get_param(L"DEVICE", params, -1);\r
384         if(device_index == -1)\r
385                 device_index = boost::lexical_cast<int>(params.at(1));\r
386         \r
387         auto filter_str         = get_param(L"FILTER", params);         \r
388         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   \r
389         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));\r
390                 \r
391         if(in_format_desc.format == core::video_format::invalid)\r
392                 in_format_desc = out_format_desc;\r
393                         \r
394         return spl::make_shared<decklink_producer_proxy>(in_format_desc, frame_factory, out_format_desc, device_index, filter_str, length);\r
395 }\r
396 \r
397 }}