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