]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
Fix a few Clang warnings.
[casparcg] / modules / decklink / producer / decklink_producer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../StdAfx.h"
23
24 #include "decklink_producer.h"
25
26 #include "../util/util.h"
27
28 #include "../../ffmpeg/producer/filter/filter.h"
29 #include "../../ffmpeg/producer/util/util.h"
30 #include "../../ffmpeg/producer/muxer/frame_muxer.h"
31 #include "../../ffmpeg/producer/muxer/display_mode.h"
32
33 #include <common/executor.h>
34 #include <common/diagnostics/graph.h>
35 #include <common/except.h>
36 #include <common/log.h>
37 #include <common/param.h>
38 #include <common/timer.h>
39
40 #include <core/frame/audio_channel_layout.h>
41 #include <core/frame/frame.h>
42 #include <core/frame/draw_frame.h>
43 #include <core/frame/frame_transform.h>
44 #include <core/frame/frame_factory.h>
45 #include <core/producer/frame_producer.h>
46 #include <core/producer/framerate/framerate_producer.h>
47 #include <core/monitor/monitor.h>
48 #include <core/diagnostics/call_context.h>
49 #include <core/mixer/audio/audio_mixer.h>
50 #include <core/help/help_repository.h>
51 #include <core/help/help_sink.h>
52
53 #include <tbb/concurrent_queue.h>
54
55 #include <boost/algorithm/string.hpp>
56 #include <boost/property_tree/ptree.hpp>
57 #include <boost/range/adaptor/transformed.hpp>
58
59 #if defined(_MSC_VER)
60 #pragma warning (push)
61 #pragma warning (disable : 4244)
62 #endif
63 extern "C"
64 {
65         #define __STDC_CONSTANT_MACROS
66         #define __STDC_LIMIT_MACROS
67         #include <libavcodec/avcodec.h>
68 }
69 #if defined(_MSC_VER)
70 #pragma warning (pop)
71 #endif
72
73 #include "../decklink_api.h"
74
75 #include <functional>
76
77 namespace caspar { namespace decklink {
78 core::audio_channel_layout get_adjusted_channel_layout(core::audio_channel_layout layout)
79 {
80         if (layout.num_channels <= 2)
81                 layout.num_channels = 2;
82         else if (layout.num_channels <= 8)
83                 layout.num_channels = 8;
84         else
85                 layout.num_channels = 16;
86
87         return layout;
88 }
89
90 template <typename T>
91 std::wstring to_string(const T& cadence)
92 {
93         return boost::join(cadence | boost::adaptors::transformed([](size_t i) { return std::to_wstring(i); }), L", ");
94 }
95
96 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
97 {
98         const int                                                                               device_index_;
99         core::monitor::subject                                                  monitor_subject_;
100         spl::shared_ptr<diagnostics::graph>                             graph_;
101         caspar::timer                                                                   tick_timer_;
102
103         com_ptr<IDeckLink>                                                              decklink_                       = get_device(device_index_);
104         com_iface_ptr<IDeckLinkInput>                                   input_                          = iface_cast<IDeckLinkInput>(decklink_);
105         com_iface_ptr<IDeckLinkAttributes>                              attributes_                     = iface_cast<IDeckLinkAttributes>(decklink_);
106
107         const std::wstring                                                              model_name_                     = get_model_name(decklink_);
108         const std::wstring                                                              filter_;
109
110         core::video_format_desc                                                 in_format_desc_;
111         core::video_format_desc                                                 out_format_desc_;
112         std::vector<int>                                                                audio_cadence_          = in_format_desc_.audio_cadence;
113         boost::circular_buffer<size_t>                                  sync_buffer_            { audio_cadence_.size() };
114         spl::shared_ptr<core::frame_factory>                    frame_factory_;
115         core::audio_channel_layout                                              channel_layout_;
116         ffmpeg::frame_muxer                                                             muxer_                          {
117                                                                                                                                                         in_format_desc_.framerate,
118                                                                                                                                                         { ffmpeg::create_input_pad(in_format_desc_, channel_layout_.num_channels) },
119                                                                                                                                                         frame_factory_,
120                                                                                                                                                         out_format_desc_,
121                                                                                                                                                         channel_layout_,
122                                                                                                                                                         filter_,
123                                                                                                                                                         ffmpeg::filter::is_deinterlacing(filter_)
124                                                                                                                                                 };
125
126         core::constraints                                                               constraints_            { double(in_format_desc_.width), double(in_format_desc_.height) };
127
128         tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;
129         core::draw_frame                                                                last_frame_                     = core::draw_frame::empty();
130
131         std::exception_ptr                                                              exception_;
132
133 public:
134         decklink_producer(
135                         const core::video_format_desc& in_format_desc,
136                         int device_index,
137                         const spl::shared_ptr<core::frame_factory>& frame_factory,
138                         const core::video_format_desc& out_format_desc,
139                         const core::audio_channel_layout& channel_layout,
140                         const std::wstring& filter)
141                 : device_index_(device_index)
142                 , filter_(filter)
143                 , in_format_desc_(in_format_desc)
144                 , out_format_desc_(out_format_desc)
145                 , frame_factory_(frame_factory)
146                 , channel_layout_(get_adjusted_channel_layout(channel_layout))
147         {
148                 frame_buffer_.set_capacity(4);
149
150                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
151                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
152                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
153                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
154                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
155                 graph_->set_text(print());
156                 diagnostics::register_graph(graph_);
157
158                 bool will_attempt_dma;
159                 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault, will_attempt_dma);
160
161                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
162                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0)))
163                         CASPAR_THROW_EXCEPTION(caspar_exception()
164                                                                         << msg_info(print() + L" Could not enable video input.")
165                                                                         << boost::errinfo_api_function("EnableVideoInput"));
166
167                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(channel_layout_.num_channels))))
168                         CASPAR_THROW_EXCEPTION(caspar_exception()
169                                                                         << msg_info(print() + L" Could not enable audio input.")
170                                                                         << boost::errinfo_api_function("EnableAudioInput"));
171
172                 if (FAILED(input_->SetCallback(this)) != S_OK)
173                         CASPAR_THROW_EXCEPTION(caspar_exception()
174                                                                         << msg_info(print() + L" Failed to set input callback.")
175                                                                         << boost::errinfo_api_function("SetCallback"));
176
177                 if(FAILED(input_->StartStreams()))
178                         CASPAR_THROW_EXCEPTION(caspar_exception()
179                                                                         << msg_info(print() + L" Failed to start input stream.")
180                                                                         << boost::errinfo_api_function("StartStreams"));
181
182                 // Wait for first frame until returning or give up after 2 seconds.
183                 caspar::timer timeout_timer;
184
185                 while (frame_buffer_.size() < 1 && timeout_timer.elapsed() < 2.0)
186                         boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
187
188                 CASPAR_LOG(info) << print() << L" Initialized";
189         }
190
191         ~decklink_producer()
192         {
193                 if(input_ != nullptr)
194                 {
195                         input_->StopStreams();
196                         input_->DisableVideoInput();
197                 }
198         }
199
200         core::constraints& pixel_constraints()
201         {
202                 return constraints_;
203         }
204
205         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}
206         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}
207         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}
208
209         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
210         {
211                 return S_OK;
212         }
213
214         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
215         {
216                 ensure_gpf_handler_installed_for_thread("decklink-VideoInputFrameArrived");
217                 if(!video)
218                         return S_OK;
219
220                 try
221                 {
222                         graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);
223                         tick_timer_.restart();
224
225                         caspar::timer frame_timer;
226
227                         // Video
228
229                         void* video_bytes = nullptr;
230                         if(FAILED(video->GetBytes(&video_bytes)) || !video_bytes)
231                                 return S_OK;
232
233                         auto video_frame = ffmpeg::create_frame();
234
235                         video_frame->data[0]                    = reinterpret_cast<uint8_t*>(video_bytes);
236                         video_frame->linesize[0]                = video->GetRowBytes();
237                         video_frame->format                             = AVPixelFormat::AV_PIX_FMT_UYVY422;
238                         video_frame->width                              = video->GetWidth();
239                         video_frame->height                             = video->GetHeight();
240                         video_frame->interlaced_frame   = in_format_desc_.field_mode != core::field_mode::progressive;
241                         video_frame->top_field_first    = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
242                         video_frame->key_frame                  = 1;
243
244                         monitor_subject_
245                                         << core::monitor::message("/file/name")                                 % model_name_
246                                         << core::monitor::message("/file/path")                                 % device_index_
247                                         << core::monitor::message("/file/video/width")                  % video->GetWidth()
248                                         << core::monitor::message("/file/video/height")                 % video->GetHeight()
249                                         << core::monitor::message("/file/video/field")                  % u8(!video_frame->interlaced_frame ? "progressive" : (video_frame->top_field_first ? "upper" : "lower"))
250                                         << core::monitor::message("/file/audio/sample-rate")    % 48000
251                                         << core::monitor::message("/file/audio/channels")               % 2
252                                         << core::monitor::message("/file/audio/format")                 % u8(av_get_sample_fmt_name(AV_SAMPLE_FMT_S32))
253                                         << core::monitor::message("/file/fps")                                  % in_format_desc_.fps;
254
255                         // Audio
256
257                         std::shared_ptr<core::mutable_audio_buffer>     audio_buffer;
258                         void*                                                                           audio_bytes             = nullptr;
259
260                         // It is assumed that audio is always equal or ahead of video.
261                         if (audio && SUCCEEDED(audio->GetBytes(&audio_bytes)) && audio_bytes)
262                         {
263                                 auto sample_frame_count = audio->GetSampleFrameCount();
264                                 auto audio_data = reinterpret_cast<int32_t*>(audio_bytes);
265
266                                 audio_buffer = std::make_shared<core::mutable_audio_buffer>(
267                                         audio_data,
268                                         audio_data + sample_frame_count * channel_layout_.num_channels);
269                         }
270                         else
271                                 audio_buffer = std::make_shared<core::mutable_audio_buffer>(audio_cadence_.front() * channel_layout_.num_channels, 0);
272
273                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
274                         // This cadence fills the audio mixer most optimally.
275
276                         sync_buffer_.push_back(audio_buffer->size() / channel_layout_.num_channels);
277                         if(!boost::range::equal(sync_buffer_, audio_cadence_))
278                         {
279                                 CASPAR_LOG(trace) << print() << L" Syncing audio. Expected cadence: " << to_string(audio_cadence_) << L" Got cadence: " << to_string(sync_buffer_);
280                                 return S_OK;
281                         }
282                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
283
284                         // PUSH
285
286                         muxer_.push({ audio_buffer });
287                         muxer_.push(static_cast<std::shared_ptr<AVFrame>>(video_frame));
288
289                         // POLL
290
291                         for (auto frame = muxer_.poll(); frame != core::draw_frame::empty(); frame = muxer_.poll())
292                         {
293                                 if (!frame_buffer_.try_push(frame))
294                                 {
295                                         auto dummy = core::draw_frame::empty();
296                                         frame_buffer_.try_pop(dummy);
297
298                                         frame_buffer_.try_push(frame);
299
300                                         graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
301                                 }
302                         }
303
304                         graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);
305                         monitor_subject_ << core::monitor::message("/profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;
306
307                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
308                         monitor_subject_ << core::monitor::message("/buffer") % frame_buffer_.size() % frame_buffer_.capacity();
309                 }
310                 catch(...)
311                 {
312                         exception_ = std::current_exception();
313                         return E_FAIL;
314                 }
315
316                 return S_OK;
317         }
318
319         core::draw_frame get_frame()
320         {
321                 if(exception_ != nullptr)
322                         std::rethrow_exception(exception_);
323
324                 core::draw_frame frame = last_frame_;
325
326                 if (!frame_buffer_.try_pop(frame))
327                         graph_->set_tag(diagnostics::tag_severity::WARNING, "late-frame");
328                 else
329                         last_frame_ = frame;
330
331                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size()) / static_cast<float>(frame_buffer_.capacity()));
332
333                 return frame;
334         }
335
336         std::wstring print() const
337         {
338                 return model_name_ + L" [" + std::to_wstring(device_index_) + L"|" + in_format_desc_.name + L"]";
339         }
340
341         boost::rational<int> get_out_framerate() const
342         {
343                 return muxer_.out_framerate();
344         }
345
346         core::monitor::subject& monitor_output()
347         {
348                 return monitor_subject_;
349         }
350 };
351
352 class decklink_producer_proxy : public core::frame_producer_base
353 {
354         std::unique_ptr<decklink_producer>      producer_;
355         const uint32_t                                          length_;
356         executor                                                        executor_;
357 public:
358         explicit decklink_producer_proxy(
359                         const core::video_format_desc& in_format_desc,
360                         const spl::shared_ptr<core::frame_factory>& frame_factory,
361                         const core::video_format_desc& out_format_desc,
362                         const core::audio_channel_layout& channel_layout,
363                         int device_index,
364                         const std::wstring& filter_str,
365                         uint32_t length)
366                 : executor_(L"decklink_producer[" + std::to_wstring(device_index) + L"]")
367                 , length_(length)
368         {
369                 auto ctx = core::diagnostics::call_context::for_thread();
370                 executor_.invoke([=]
371                 {
372                         core::diagnostics::call_context::for_thread() = ctx;
373                         com_initialize();
374                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, channel_layout, filter_str));
375                 });
376         }
377
378         ~decklink_producer_proxy()
379         {
380                 executor_.invoke([=]
381                 {
382                         producer_.reset();
383                         com_uninitialize();
384                 });
385         }
386
387         core::monitor::subject& monitor_output() override
388         {
389                 return producer_->monitor_output();
390         }
391
392         // frame_producer
393
394         core::draw_frame receive_impl() override
395         {
396                 return producer_->get_frame();
397         }
398
399         core::constraints& pixel_constraints() override
400         {
401                 return producer_->pixel_constraints();
402         }
403
404         uint32_t nb_frames() const override
405         {
406                 return length_;
407         }
408
409         std::wstring print() const override
410         {
411                 return producer_->print();
412         }
413
414         std::wstring name() const override
415         {
416                 return L"decklink";
417         }
418
419         boost::property_tree::wptree info() const override
420         {
421                 boost::property_tree::wptree info;
422                 info.add(L"type", L"decklink");
423                 return info;
424         }
425
426         boost::rational<int> get_out_framerate() const
427         {
428                 return producer_->get_out_framerate();
429         }
430 };
431
432 void describe_producer(core::help_sink& sink, const core::help_repository& repo)
433 {
434         sink.short_description(L"Allows video sources to be input from BlackMagic Design cards.");
435         sink.syntax(L"DECKLINK [device:int],DEVICE [device:int] {FILTER [filter:string]} {LENGTH [length:int]} {FORMAT [format:string]} {CHANNEL_LAYOUT [channel_layout:string]}");
436         sink.para()->text(L"Allows video sources to be input from BlackMagic Design cards. Parameters:");
437         sink.definitions()
438                 ->item(L"device", L"The decklink device to stream the input from. See the Blackmagic control panel for the order of devices in your system.")
439                 ->item(L"filter", L"If specified, sets an FFmpeg video filter to use.")
440                 ->item(L"length", L"Optionally specify a limit on how many frames to produce.")
441                 ->item(L"format", L"Specifies what video format to expect on the incoming SDI/HDMI signal. If not specified the video format of the channel is assumed.")
442                 ->item(L"channel_layout", L"Specifies what audio channel layout to expect on the incoming SDI/HDMI signal. If not specified, stereo is assumed.");
443         sink.para()->text(L"Examples:");
444         sink.example(L">> PLAY 1-10 DECKLINK DEVICE 2", L"Play using decklink device 2 expecting the video signal to have the same video format as the channel.");
445         sink.example(L">> PLAY 1-10 DECKLINK DEVICE 2 FORMAT PAL FILTER yadif=1:-1", L"Play using decklink device 2 expecting the video signal to be in PAL and deinterlace it.");
446         sink.example(L">> PLAY 1-10 DECKLINK DEVICE 2 LENGTH 1000", L"Play using decklink device 2 but only produce 1000 frames.");
447         sink.example(L">> PLAY 1-10 DECKLINK DEVICE 2 CHANNEL_LAYOUT smpte", L"Play using decklink device 2 and expect smpte surround sound.");
448 }
449
450 spl::shared_ptr<core::frame_producer> create_producer(const core::frame_producer_dependencies& dependencies, const std::vector<std::wstring>& params)
451 {
452         if(params.empty() || !boost::iequals(params.at(0), "decklink"))
453                 return core::frame_producer::empty();
454
455         auto device_index       = get_param(L"DEVICE", params, -1);
456         if(device_index == -1)
457                 device_index = std::stoi(params.at(1));
458
459         auto filter_str         = get_param(L"FILTER", params);
460         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
461         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
462
463         if(in_format_desc.format == core::video_format::invalid)
464                 in_format_desc = dependencies.format_desc;
465
466         auto channel_layout_spec        = get_param(L"CHANNEL_LAYOUT", params);
467         auto channel_layout                     = *core::audio_channel_layout_repository::get_default()->get_layout(L"stereo");
468
469         if (!channel_layout_spec.empty())
470         {
471                 auto found_layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout_spec);
472
473                 if (!found_layout)
474                         CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Channel layout not found."));
475
476                 channel_layout = *found_layout;
477         }
478
479         boost::ireplace_all(filter_str, L"DEINTERLACE_BOB",     L"YADIF=1:-1");
480         boost::ireplace_all(filter_str, L"DEINTERLACE_LQ",      L"SEPARATEFIELDS");
481         boost::ireplace_all(filter_str, L"DEINTERLACE",         L"YADIF=0:-1");
482
483         auto producer = spl::make_shared<decklink_producer_proxy>(
484                         in_format_desc,
485                         dependencies.frame_factory,
486                         dependencies.format_desc,
487                         channel_layout,
488                         device_index,
489                         filter_str,
490                         length);
491
492         auto get_source_framerate       = [=] { return producer->get_out_framerate(); };
493         auto target_framerate           = dependencies.format_desc.framerate;
494
495         return core::create_destroy_proxy(core::create_framerate_producer(
496                         producer,
497                         get_source_framerate,
498                         target_framerate,
499                         dependencies.format_desc.field_mode,
500                         dependencies.format_desc.audio_cadence));
501 }
502 }}