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