]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
d88ff9cf998560367e850d3a72bbf60b4a493b09
[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         CComPtr<IDeckLink>                                                                                      decklink_;\r
83         CComQIPtr<IDeckLinkInput>                                                                       input_;\r
84         \r
85         const std::wstring                                                                                      model_name_;\r
86         const core::video_format_desc                                                           format_desc_;\r
87         const size_t                                                                                            device_index_;\r
88 \r
89         safe_ptr<diagnostics::graph>                                                            graph_;\r
90         boost::timer                                                                                            tick_timer_;\r
91         boost::timer                                                                                            frame_timer_;\r
92                 \r
93         tbb::atomic<int>                                                                                        hints_;\r
94         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
95         std::vector<size_t>                                                                                     audio_cadence_;\r
96 \r
97         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
98 \r
99         std::exception_ptr                                                                                      exception_;\r
100                 \r
101         ffmpeg::frame_muxer                                                                                     muxer_;\r
102 \r
103 public:\r
104         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)\r
105                 : decklink_(get_device(device_index))\r
106                 , input_(decklink_)\r
107                 , model_name_(get_model_name(decklink_))\r
108                 , format_desc_(format_desc)\r
109                 , device_index_(device_index)\r
110                 , frame_factory_(frame_factory)\r
111                 , audio_cadence_(frame_factory->get_video_format_desc().audio_cadence)\r
112                 , muxer_(format_desc.fps, frame_factory, filter, ffmpeg::display_mode::deinterlace)\r
113         {\r
114                 hints_ = 0;\r
115                 frame_buffer_.set_capacity(2);\r
116                 \r
117                 graph_->add_guide("tick-time", 0.5);\r
118                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
119                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
120                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
121                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
122                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
123                 graph_->set_text(print());\r
124                 diagnostics::register_graph(graph_);\r
125                 \r
126                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
127                 \r
128                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
129                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
130                         BOOST_THROW_EXCEPTION(caspar_exception() \r
131                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
132                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
133 \r
134                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels))) \r
135                         BOOST_THROW_EXCEPTION(caspar_exception() \r
136                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
137                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
138                         \r
139                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
140                         BOOST_THROW_EXCEPTION(caspar_exception() \r
141                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
142                                                                         << boost::errinfo_api_function("SetCallback"));\r
143                         \r
144                 if(FAILED(input_->StartStreams()))\r
145                         BOOST_THROW_EXCEPTION(caspar_exception() \r
146                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
147                                                                         << boost::errinfo_api_function("StartStreams"));\r
148                 \r
149                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
150         }\r
151 \r
152         ~decklink_producer()\r
153         {\r
154                 if(input_ != nullptr) \r
155                 {\r
156                         input_->StopStreams();\r
157                         input_->DisableVideoInput();\r
158                 }\r
159         }\r
160 \r
161         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
162         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
163         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
164                 \r
165         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
166         {\r
167                 return S_OK;\r
168         }\r
169 \r
170         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
171         {       \r
172                 if(!video)\r
173                         return S_OK;\r
174 \r
175                 try\r
176                 {\r
177                         muxer_.force_deinterlacing((hints_ & core::frame_producer::DEINTERLACE_HINT) != 0);\r
178 \r
179                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
180                         tick_timer_.restart();\r
181 \r
182                         frame_timer_.restart();\r
183 \r
184                         void* bytes = nullptr;\r
185                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
186                                 return S_OK;\r
187                         \r
188                         safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
189                         avcodec_get_frame_defaults(av_frame.get());\r
190                                                 \r
191                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
192                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
193                         av_frame->format                        = PIX_FMT_UYVY422;\r
194                         av_frame->width                         = video->GetWidth();\r
195                         av_frame->height                        = video->GetHeight();\r
196                         av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
197                         av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
198                                         \r
199                         muxer_.push(av_frame);          \r
200                                                                         \r
201                         // It is assumed that audio is always equal or ahead of video.\r
202                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
203                         {\r
204                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
205                                 auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
206                                 muxer_.push(std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels));\r
207                         }\r
208                         else\r
209                         {\r
210                                 muxer_.push(std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0));\r
211                                 std::rotate(std::begin(audio_cadence_), std::begin(audio_cadence_)+1, std::end(audio_cadence_));\r
212                         }\r
213 \r
214                         for(auto frame = muxer_.poll(); frame; frame = muxer_.poll())\r
215                         {\r
216                                 if(!frame_buffer_.try_push(make_safe_ptr(frame)))\r
217                                         graph_->add_tag("dropped-frame");\r
218                         }\r
219 \r
220                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
221 \r
222                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
223                 }\r
224                 catch(...)\r
225                 {\r
226                         exception_ = std::current_exception();\r
227                         return E_FAIL;\r
228                 }\r
229 \r
230                 return S_OK;\r
231         }\r
232         \r
233         safe_ptr<core::basic_frame> get_frame(int hints)\r
234         {\r
235                 if(exception_ != nullptr)\r
236                         std::rethrow_exception(exception_);\r
237 \r
238                 hints_ = hints;\r
239 \r
240                 safe_ptr<core::basic_frame> frame = core::basic_frame::late();\r
241                 if(!frame_buffer_.try_pop(frame))\r
242                         graph_->add_tag("late-frame");\r
243                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
244                 return frame;\r
245         }\r
246         \r
247         std::wstring print() const\r
248         {\r
249                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
250         }\r
251 };\r
252         \r
253 class decklink_producer_proxy : public core::frame_producer\r
254 {               \r
255         safe_ptr<core::basic_frame>             last_frame_;\r
256         com_context<decklink_producer>  context_;\r
257         const int64_t                                   length_;\r
258 public:\r
259 \r
260         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, int64_t length)\r
261                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
262                 , last_frame_(core::basic_frame::empty())\r
263                 , length_(length)\r
264         {\r
265                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
266         }\r
267 \r
268         ~decklink_producer_proxy()\r
269         {\r
270                 auto str = print();\r
271                 context_.reset();\r
272                 CASPAR_LOG(info) << str << L" Successfully Uninitialized.";     \r
273         }\r
274 \r
275         // frame_producer\r
276                                 \r
277         virtual safe_ptr<core::basic_frame> receive(int hints) override\r
278         {\r
279                 auto frame = context_->get_frame(hints);\r
280                 if(frame != core::basic_frame::late())\r
281                         last_frame_ = frame;\r
282                 return frame;\r
283         }\r
284 \r
285         virtual safe_ptr<core::basic_frame> last_frame() const override\r
286         {\r
287                 return disable_audio(last_frame_);\r
288         }\r
289         \r
290         virtual int64_t nb_frames() const override\r
291         {\r
292                 return length_;\r
293         }\r
294         \r
295         std::wstring print() const override\r
296         {\r
297                 return context_->print();\r
298         }\r
299 \r
300         virtual boost::property_tree::wptree info() const override\r
301         {\r
302                 boost::property_tree::wptree info;\r
303                 info.add(L"type", L"decklink-producer");\r
304                 return info;\r
305         }\r
306 };\r
307 \r
308 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
309 {\r
310         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
311                 return core::frame_producer::empty();\r
312 \r
313         auto device_index       = get_param(L"DEVICE", params, 1);\r
314         auto filter_str         = get_param(L"FILTER", params);         \r
315         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<int64_t>::max());    \r
316         auto format_desc        = core::video_format_desc::get(get_param(L"FORMAT", params, L"INVALID"));\r
317         \r
318         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
319         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
320         \r
321         if(format_desc.format == core::video_format::invalid)\r
322                 format_desc = frame_factory->get_video_format_desc();\r
323                         \r
324         return create_producer_destroy_proxy(make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length));\r
325 }\r
326 \r
327 }}