]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
git-svn-id: https://casparcg.svn.sourceforge.net/svnroot/casparcg/server/branches...
[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_.try_pop(frame))\r
251                         {\r
252                                 if(!frame_buffer_.try_push(frame))\r
253                                 {\r
254                                         auto dummy = core::draw_frame::empty();\r
255                                         frame_buffer_.try_pop(dummy);\r
256                                         frame_buffer_.try_push(frame);\r
257                                                 \r
258                                         graph_->set_tag("dropped-frame");\r
259                                 }\r
260                         }\r
261                         \r
262                         graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);        \r
263                         event_subject_ << monitor::event("profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;\r
264 \r
265                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
266                         event_subject_ << monitor::event("buffer") % frame_buffer_.size() % frame_buffer_.capacity();\r
267                 }\r
268                 catch(...)\r
269                 {\r
270                         exception_ = std::current_exception();\r
271                         return E_FAIL;\r
272                 }\r
273 \r
274                 return S_OK;\r
275         }\r
276         \r
277         core::draw_frame get_frame()\r
278         {\r
279                 if(exception_ != nullptr)\r
280                         std::rethrow_exception(exception_);\r
281                 \r
282                 core::draw_frame frame = core::draw_frame::late();\r
283                 if(!frame_buffer_.try_pop(frame))\r
284                         graph_->set_tag("late-frame");\r
285                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
286                 return frame;\r
287         }\r
288         \r
289         std::wstring print() const\r
290         {\r
291                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";\r
292         }\r
293 \r
294         void subscribe(const monitor::observable::observer_ptr& o)\r
295         {\r
296                 event_subject_.subscribe(o);\r
297         }\r
298 \r
299         void unsubscribe(const monitor::observable::observer_ptr& o)\r
300         {\r
301                 event_subject_.unsubscribe(o);\r
302         }\r
303 };\r
304         \r
305 class decklink_producer_proxy : public core::frame_producer\r
306 {               \r
307         std::unique_ptr<decklink_producer>      producer_;\r
308         const uint32_t                                          length_;\r
309         core::draw_frame                                        last_frame_;\r
310         executor                                                        executor_;\r
311 public:\r
312         explicit decklink_producer_proxy(const core::video_format_desc& in_format_desc,\r
313                                                                          const spl::shared_ptr<core::frame_factory>& frame_factory, \r
314                                                                          const core::video_format_desc& out_format_desc, \r
315                                                                          int device_index,\r
316                                                                          const std::wstring& filter_str, uint32_t length)\r
317                 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
318                 , length_(length)\r
319                 , last_frame_(core::draw_frame::empty())\r
320         {\r
321                 executor_.invoke([=]\r
322                 {\r
323                         CoInitialize(nullptr);\r
324                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, filter_str));\r
325                 });\r
326         }\r
327 \r
328         ~decklink_producer_proxy()\r
329         {               \r
330                 executor_.invoke([=]\r
331                 {\r
332                         producer_.reset();\r
333                         CoUninitialize();\r
334                 });\r
335         }\r
336 \r
337         void subscribe(const monitor::observable::observer_ptr& o) override\r
338         {\r
339                 producer_->subscribe(o);\r
340         }\r
341 \r
342         void unsubscribe(const monitor::observable::observer_ptr& o) override\r
343         {\r
344                 producer_->unsubscribe(o);\r
345         }\r
346         \r
347         // frame_producer\r
348                                 \r
349         core::draw_frame receive() override\r
350         {\r
351                 auto frame = producer_->get_frame();\r
352 \r
353                 if(frame != core::draw_frame::late())\r
354                         last_frame_ = frame;\r
355 \r
356                 return frame;\r
357         }\r
358 \r
359         core::draw_frame last_frame() const override\r
360         {\r
361                 return core::draw_frame::still(last_frame_);\r
362         }\r
363                 \r
364         uint32_t nb_frames() const override\r
365         {\r
366                 return length_;\r
367         }\r
368         \r
369         std::wstring print() const override\r
370         {\r
371                 return producer_->print();\r
372         }\r
373         \r
374         std::wstring name() const override\r
375         {\r
376                 return L"decklink";\r
377         }\r
378 \r
379         boost::property_tree::wptree info() const override\r
380         {\r
381                 boost::property_tree::wptree info;\r
382                 info.add(L"type", L"decklink");\r
383                 return info;\r
384         }\r
385 };\r
386 \r
387 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
388 {\r
389         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
390                 return core::frame_producer::empty();\r
391 \r
392         auto device_index       = get_param(L"DEVICE", params, -1);\r
393         if(device_index == -1)\r
394                 device_index = boost::lexical_cast<int>(params.at(1));\r
395         \r
396         auto filter_str         = get_param(L"FILTER", params);         \r
397         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   \r
398         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));\r
399         \r
400         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
401         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
402         \r
403         if(in_format_desc.format == core::video_format::invalid)\r
404                 in_format_desc = out_format_desc;\r
405                         \r
406         return spl::make_shared<decklink_producer_proxy>(in_format_desc, frame_factory, out_format_desc, device_index, filter_str, length);\r
407 }\r
408 \r
409 }}