]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
- Implemented real-time state notification using OSC-UDP.
[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/concurrency/com_context.h>\r
35 #include <common/diagnostics/graph.h>\r
36 #include <common/exception/exceptions.h>\r
37 #include <common/log/log.h>\r
38 #include <common/memory/memclr.h>\r
39 #include <common/utility/param.h>\r
40 \r
41 #include <core/monitor/monitor.h>\r
42 #include <core/mixer/write_frame.h>\r
43 #include <core/producer/frame/frame_transform.h>\r
44 #include <core/producer/frame/frame_factory.h>\r
45 \r
46 #include <tbb/concurrent_queue.h>\r
47 \r
48 #include <boost/algorithm/string.hpp>\r
49 #include <boost/foreach.hpp>\r
50 #include <boost/property_tree/ptree.hpp>\r
51 #include <boost/timer.hpp>\r
52 \r
53 #if defined(_MSC_VER)\r
54 #pragma warning (push)\r
55 #pragma warning (disable : 4244)\r
56 #endif\r
57 extern "C" \r
58 {\r
59         #define __STDC_CONSTANT_MACROS\r
60         #define __STDC_LIMIT_MACROS\r
61         #include <libavcodec/avcodec.h>\r
62 }\r
63 #if defined(_MSC_VER)\r
64 #pragma warning (pop)\r
65 #endif\r
66 \r
67 #pragma warning(push)\r
68 #pragma warning(disable : 4996)\r
69 \r
70         #include <atlbase.h>\r
71 \r
72         #include <atlcom.h>\r
73         #include <atlhost.h>\r
74 \r
75 #pragma warning(push)\r
76 \r
77 #include <functional>\r
78 \r
79 namespace caspar { namespace decklink {\r
80                 \r
81 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback\r
82 {       \r
83         core::monitor::subject                                                                          monitor_subject_;\r
84         safe_ptr<diagnostics::graph>                                                            graph_;\r
85         boost::timer                                                                                            tick_timer_;\r
86         boost::timer                                                                                            frame_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 size_t                                                                                            device_index_;\r
94         const std::wstring                                                                                      filter_;\r
95         \r
96         core::video_format_desc                                                                         format_desc_;\r
97         std::vector<size_t>                                                                                     audio_cadence_;\r
98         boost::circular_buffer<size_t>                                                          sync_buffer_;\r
99         ffmpeg::frame_muxer                                                                                     muxer_;\r
100                         \r
101         tbb::atomic<int>                                                                                        hints_;\r
102         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
103 \r
104         tbb::concurrent_bounded_queue<safe_ptr<core::basic_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& format_desc, size_t device_index, const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filter, std::size_t buffer_depth)\r
110                 : decklink_(get_device(device_index))\r
111                 , input_(decklink_)\r
112                 , attributes_(decklink_)\r
113                 , model_name_(get_model_name(decklink_))\r
114                 , device_index_(device_index)\r
115                 , filter_(filter)\r
116                 , format_desc_(format_desc)\r
117                 , audio_cadence_(format_desc.audio_cadence)\r
118                 , muxer_(format_desc.fps, frame_factory, false, filter)\r
119                 , sync_buffer_(format_desc.audio_cadence.size())\r
120                 , frame_factory_(frame_factory)\r
121         {               \r
122                 hints_ = 0;\r
123                 frame_buffer_.set_capacity(buffer_depth);\r
124                 \r
125                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
126                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
127                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
128                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
129                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
130                 graph_->set_text(print());\r
131                 diagnostics::register_graph(graph_);\r
132                 \r
133                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
134                                 \r
135                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
136                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, bmdVideoInputFlagDefault))) \r
137                         BOOST_THROW_EXCEPTION(caspar_exception() \r
138                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
139                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
140 \r
141                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels))) \r
142                         BOOST_THROW_EXCEPTION(caspar_exception() \r
143                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
144                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
145                         \r
146                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
147                         BOOST_THROW_EXCEPTION(caspar_exception() \r
148                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
149                                                                         << boost::errinfo_api_function("SetCallback"));\r
150                         \r
151                 if(FAILED(input_->StartStreams()))\r
152                         BOOST_THROW_EXCEPTION(caspar_exception() \r
153                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
154                                                                         << boost::errinfo_api_function("StartStreams"));\r
155         }\r
156 \r
157         ~decklink_producer()\r
158         {\r
159                 if(input_ != nullptr) \r
160                 {\r
161                         input_->StopStreams();\r
162                         input_->DisableVideoInput();\r
163                 }\r
164         }\r
165 \r
166         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
167         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
168         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
169                 \r
170         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
171         {\r
172                 return S_OK;\r
173         }\r
174 \r
175         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
176         {       \r
177                 if(!video)\r
178                         return S_OK;\r
179 \r
180                 try\r
181                 {\r
182                         graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
183                         tick_timer_.restart();\r
184 \r
185                         frame_timer_.restart();\r
186 \r
187                         // PUSH\r
188 \r
189                         void* bytes = nullptr;\r
190                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
191                                 return S_OK;\r
192                         \r
193                         safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
194                         avcodec_get_frame_defaults(av_frame.get());\r
195                                                 \r
196                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
197                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
198                         av_frame->format                        = PIX_FMT_UYVY422;\r
199                         av_frame->width                         = video->GetWidth();\r
200                         av_frame->height                        = video->GetHeight();\r
201                         av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
202                         av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
203                                 \r
204                         std::shared_ptr<core::audio_buffer> audio_buffer;\r
205 \r
206                         // It is assumed that audio is always equal or ahead of video.\r
207                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)\r
208                         {\r
209                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
210                                 auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
211                                 audio_buffer = std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels);\r
212                         }\r
213                         else                    \r
214                                 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0);\r
215                         \r
216                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)\r
217                         // This cadence fills the audio mixer most optimally.\r
218 \r
219                         sync_buffer_.push_back(audio_buffer->size());           \r
220                         if(!boost::range::equal(sync_buffer_, audio_cadence_))\r
221                         {\r
222                                 CASPAR_LOG(trace) << print() << L" Syncing audio.";\r
223                                 return S_OK;\r
224                         }\r
225 \r
226                         muxer_.push(audio_buffer);\r
227                         muxer_.push(av_frame, hints_);  \r
228                                                                                         \r
229                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);\r
230                         \r
231                         // POLL\r
232                         \r
233                         for(auto frame = muxer_.poll(); frame; frame = muxer_.poll())\r
234                         {\r
235                                 if(!frame_buffer_.try_push(make_safe_ptr(frame)))\r
236                                 {\r
237                                         auto dummy = core::basic_frame::empty();\r
238                                         frame_buffer_.try_pop(dummy);\r
239 \r
240                                         frame_buffer_.try_push(make_safe_ptr(frame));\r
241 \r
242                                         graph_->set_tag("dropped-frame");\r
243                                 }\r
244                         }\r
245 \r
246                         graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
247 \r
248                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
249                 }\r
250                 catch(...)\r
251                 {\r
252                         exception_ = std::current_exception();\r
253                         return E_FAIL;\r
254                 }\r
255 \r
256                 return S_OK;\r
257         }\r
258         \r
259         safe_ptr<core::basic_frame> get_frame(int hints)\r
260         {\r
261                 if(exception_ != nullptr)\r
262                         std::rethrow_exception(exception_);\r
263 \r
264                 hints_ = hints;\r
265 \r
266                 safe_ptr<core::basic_frame> frame = core::basic_frame::late();\r
267                 if(!frame_buffer_.try_pop(frame))\r
268                         graph_->set_tag("late-frame");\r
269                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
270                 return frame;\r
271         }\r
272         \r
273         std::wstring print() const\r
274         {\r
275                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + format_desc_.name + L"]";\r
276         }\r
277 \r
278         core::monitor::source& monitor_output()\r
279         {\r
280                 return monitor_subject_;\r
281         }\r
282 };\r
283         \r
284 class decklink_producer_proxy : public core::frame_producer\r
285 {               \r
286         safe_ptr<core::basic_frame>             last_frame_;\r
287         com_context<decklink_producer>  context_;\r
288         const uint32_t                                  length_;\r
289 public:\r
290 \r
291         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, uint32_t length, std::size_t buffer_depth)\r
292                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
293                 , last_frame_(core::basic_frame::empty())\r
294                 , length_(length)\r
295         {\r
296                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str, buffer_depth);}); \r
297         }\r
298         \r
299         // frame_producer\r
300                                 \r
301         virtual safe_ptr<core::basic_frame> receive(int hints) override\r
302         {\r
303                 auto frame = context_->get_frame(hints);\r
304                 if(frame != core::basic_frame::late())\r
305                         last_frame_ = frame;\r
306                 return frame;\r
307         }\r
308 \r
309         virtual safe_ptr<core::basic_frame> last_frame() const override\r
310         {\r
311                 return disable_audio(last_frame_);\r
312         }\r
313         \r
314         virtual uint32_t nb_frames() const override\r
315         {\r
316                 return length_;\r
317         }\r
318         \r
319         std::wstring print() const override\r
320         {\r
321                 return context_->print();\r
322         }\r
323 \r
324         virtual boost::property_tree::wptree info() const override\r
325         {\r
326                 boost::property_tree::wptree info;\r
327                 info.add(L"type", L"decklink-producer");\r
328                 return info;\r
329         }\r
330 \r
331         core::monitor::source& monitor_output()\r
332         {\r
333                 return context_->monitor_output();\r
334         }\r
335 };\r
336 \r
337 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
338 {\r
339         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
340                 return core::frame_producer::empty();\r
341 \r
342         auto device_index       = get_param(L"DEVICE", params, -1);\r
343         if(device_index == -1)\r
344                 device_index = boost::lexical_cast<int>(params.at(1));\r
345         auto filter_str         = get_param(L"FILTER", params);         \r
346         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   \r
347         auto buffer_depth       = get_param(L"BUFFER", params, 2);      \r
348         auto format_desc        = core::video_format_desc::get(get_param(L"FORMAT", params, L"INVALID"));\r
349         \r
350         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
351         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
352         \r
353         if(format_desc.format == core::video_format::invalid)\r
354                 format_desc = frame_factory->get_video_format_desc();\r
355                         \r
356         return create_producer_print_proxy(\r
357                    create_producer_destroy_proxy(\r
358                         make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length, buffer_depth)));\r
359 }\r
360 \r
361 }}