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