]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
* Added logging of severe diagnostics events to log at warning level. graph::set_tag...
[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/monitor/monitor.h>
47 #include <core/mixer/audio/audio_mixer.h>
48 #include <core/help/help_repository.h>
49 #include <core/help/help_sink.h>
50
51 #include <tbb/concurrent_queue.h>
52
53 #include <boost/algorithm/string.hpp>
54 #include <boost/property_tree/ptree.hpp>
55
56 #if defined(_MSC_VER)
57 #pragma warning (push)
58 #pragma warning (disable : 4244)
59 #endif
60 extern "C" 
61 {
62         #define __STDC_CONSTANT_MACROS
63         #define __STDC_LIMIT_MACROS
64         #include <libavcodec/avcodec.h>
65 }
66 #if defined(_MSC_VER)
67 #pragma warning (pop)
68 #endif
69
70 #include "../decklink_api.h"
71
72 #include <functional>
73
74 namespace caspar { namespace decklink {
75
76 core::audio_channel_layout get_adjusted_channel_layout(core::audio_channel_layout layout)
77 {
78         if (layout.num_channels <= 2)
79                 layout.num_channels = 2;
80         else if (layout.num_channels <= 8)
81                 layout.num_channels = 8;
82         else
83                 layout.num_channels = 16;
84
85         return layout;
86 }
87                 
88 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
89 {       
90         const int                                                                               device_index_;
91         core::monitor::subject                                                  monitor_subject_;
92         spl::shared_ptr<diagnostics::graph>                             graph_;
93         caspar::timer                                                                   tick_timer_;
94
95         com_ptr<IDeckLink>                                                              decklink_                       = get_device(device_index_);
96         com_iface_ptr<IDeckLinkInput>                                   input_                          = iface_cast<IDeckLinkInput>(decklink_);
97         com_iface_ptr<IDeckLinkAttributes>                              attributes_                     = iface_cast<IDeckLinkAttributes>(decklink_);
98         
99         const std::wstring                                                              model_name_                     = get_model_name(decklink_);
100         const std::wstring                                                              filter_;
101         
102         core::video_format_desc                                                 in_format_desc_;
103         core::video_format_desc                                                 out_format_desc_;
104         std::vector<int>                                                                audio_cadence_          = out_format_desc_.audio_cadence;
105         boost::circular_buffer<size_t>                                  sync_buffer_            { audio_cadence_.size() };
106         spl::shared_ptr<core::frame_factory>                    frame_factory_;
107         core::audio_channel_layout                                              channel_layout_;
108         ffmpeg::frame_muxer                                                             muxer_                          { in_format_desc_.fps, frame_factory_, out_format_desc_, channel_layout_, filter_ };
109                         
110         core::constraints                                                               constraints_            { in_format_desc_.width, in_format_desc_.height };
111
112         tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;
113
114         std::exception_ptr                                                              exception_;
115
116 public:
117         decklink_producer(
118                         const core::video_format_desc& in_format_desc, 
119                         int device_index, 
120                         const spl::shared_ptr<core::frame_factory>& frame_factory, 
121                         const core::video_format_desc& out_format_desc,
122                         const core::audio_channel_layout& channel_layout,
123                         const std::wstring& filter)
124                 : device_index_(device_index)
125                 , filter_(filter)
126                 , in_format_desc_(in_format_desc)
127                 , out_format_desc_(out_format_desc)
128                 , frame_factory_(frame_factory)
129                 , channel_layout_(get_adjusted_channel_layout(channel_layout))
130         {
131                 frame_buffer_.set_capacity(2);
132                 
133                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
134                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
135                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
136                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
137                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
138                 graph_->set_text(print());
139                 diagnostics::register_graph(graph_);
140                 
141                 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
142                 
143                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
144                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) 
145                         CASPAR_THROW_EXCEPTION(caspar_exception() 
146                                                                         << msg_info(print() + L" Could not enable video input.")
147                                                                         << boost::errinfo_api_function("EnableVideoInput"));
148
149                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(channel_layout_.num_channels))))
150                         CASPAR_THROW_EXCEPTION(caspar_exception()
151                                                                         << msg_info(print() + L" Could not enable audio input.")
152                                                                         << boost::errinfo_api_function("EnableAudioInput"));
153                         
154                 if (FAILED(input_->SetCallback(this)) != S_OK)
155                         CASPAR_THROW_EXCEPTION(caspar_exception() 
156                                                                         << msg_info(print() + L" Failed to set input callback.")
157                                                                         << boost::errinfo_api_function("SetCallback"));
158                         
159                 if(FAILED(input_->StartStreams()))
160                         CASPAR_THROW_EXCEPTION(caspar_exception() 
161                                                                         << msg_info(print() + L" Failed to start input stream.")
162                                                                         << boost::errinfo_api_function("StartStreams"));
163
164                 CASPAR_LOG(info) << print() << L" Initialized";
165         }
166
167         ~decklink_producer()
168         {
169                 if(input_ != nullptr) 
170                 {
171                         input_->StopStreams();
172                         input_->DisableVideoInput();
173                 }
174         }
175
176         core::constraints& pixel_constraints()
177         {
178                 return constraints_;
179         }
180
181         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}
182         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}
183         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}
184                 
185         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
186         {
187                 return S_OK;
188         }
189
190         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
191         {       
192                 if(!video)
193                         return S_OK;
194
195                 try
196                 {
197                         graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);
198                         tick_timer_.restart();
199
200                         caspar::timer frame_timer;
201                         
202                         // Video
203
204                         void* video_bytes = nullptr;
205                         if(FAILED(video->GetBytes(&video_bytes)) || !video_bytes)
206                                 return S_OK;
207                         
208                         auto video_frame = ffmpeg::create_frame();
209                                                 
210                         video_frame->data[0]                    = reinterpret_cast<uint8_t*>(video_bytes);
211                         video_frame->linesize[0]                = video->GetRowBytes();                 
212                         video_frame->format                             = PIX_FMT_UYVY422;
213                         video_frame->width                              = video->GetWidth();
214                         video_frame->height                             = video->GetHeight();
215                         video_frame->interlaced_frame   = in_format_desc_.field_mode != core::field_mode::progressive;
216                         video_frame->top_field_first    = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
217                                 
218                         monitor_subject_
219                                         << core::monitor::message("/file/name")                                 % model_name_
220                                         << core::monitor::message("/file/path")                                 % device_index_
221                                         << core::monitor::message("/file/video/width")                  % video->GetWidth()
222                                         << core::monitor::message("/file/video/height")                 % video->GetHeight()
223                                         << core::monitor::message("/file/video/field")                  % u8(!video_frame->interlaced_frame ? "progressive" : (video_frame->top_field_first ? "upper" : "lower"))
224                                         << core::monitor::message("/file/audio/sample-rate")    % 48000
225                                         << core::monitor::message("/file/audio/channels")               % 2
226                                         << core::monitor::message("/file/audio/format")                 % u8(av_get_sample_fmt_name(AV_SAMPLE_FMT_S32))
227                                         << core::monitor::message("/file/fps")                                  % in_format_desc_.fps;
228
229                         // Audio
230
231                         void* audio_bytes = nullptr;
232                         if(FAILED(audio->GetBytes(&audio_bytes)) || !audio_bytes)
233                                 return S_OK;
234                         
235                         auto audio_frame = ffmpeg::create_frame();
236
237                         audio_frame->data[0]            = reinterpret_cast<uint8_t*>(audio_bytes);
238                         audio_frame->linesize[0]        = audio->GetSampleFrameCount() * channel_layout_.num_channels * sizeof(int32_t);
239                         audio_frame->nb_samples         = audio->GetSampleFrameCount();
240                         audio_frame->format                     = AV_SAMPLE_FMT_S32;
241                                                 
242                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
243                         // This cadence fills the audio mixer most optimally.
244
245                         sync_buffer_.push_back(audio->GetSampleFrameCount());           
246                         if(!boost::range::equal(sync_buffer_, audio_cadence_))
247                         {
248                                 CASPAR_LOG(trace) << print() << L" Syncing audio.";
249                                 return S_OK;
250                         }
251                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
252                         
253                         // PUSH
254
255                         muxer_.push_video(video_frame); 
256                         muxer_.push_audio(audio_frame);                                                                                 
257                         
258                         // POLL
259
260                         auto frame = core::draw_frame::late();
261                         if(!muxer_.empty())
262                         {
263                                 frame = std::move(muxer_.front());
264                                 muxer_.pop();
265
266                                 if(!frame_buffer_.try_push(frame))
267                                 {
268                                         auto dummy = core::draw_frame::empty();
269                                         frame_buffer_.try_pop(dummy);
270                                         frame_buffer_.try_push(frame);
271                                                 
272                                         graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
273                                 }
274                         }
275                         
276                         graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);        
277                         monitor_subject_ << core::monitor::message("/profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;
278
279                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      
280                         monitor_subject_ << core::monitor::message("/buffer") % frame_buffer_.size() % frame_buffer_.capacity();
281                 }
282                 catch(...)
283                 {
284                         exception_ = std::current_exception();
285                         return E_FAIL;
286                 }
287
288                 return S_OK;
289         }
290         
291         core::draw_frame get_frame()
292         {
293                 if(exception_ != nullptr)
294                         std::rethrow_exception(exception_);
295                 
296                 core::draw_frame frame = core::draw_frame::late();
297                 if(!frame_buffer_.try_pop(frame))
298                         graph_->set_tag(diagnostics::tag_severity::WARNING, "late-frame");
299                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      
300                 return frame;
301         }
302         
303         std::wstring print() const
304         {
305                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";
306         }
307
308         core::monitor::subject& monitor_output()
309         {
310                 return monitor_subject_;
311         }
312 };
313         
314 class decklink_producer_proxy : public core::frame_producer_base
315 {               
316         std::unique_ptr<decklink_producer>      producer_;
317         const uint32_t                                          length_;
318         executor                                                        executor_;
319 public:
320         explicit decklink_producer_proxy(
321                         const core::video_format_desc& in_format_desc,
322                         const spl::shared_ptr<core::frame_factory>& frame_factory,
323                         const core::video_format_desc& out_format_desc,
324                         const core::audio_channel_layout& channel_layout,
325                         int device_index,
326                         const std::wstring& filter_str,
327                         uint32_t length)
328                 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
329                 , length_(length)
330         {
331                 executor_.invoke([=]
332                 {
333                         com_initialize();
334                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, channel_layout, filter_str));
335                 });
336         }
337
338         ~decklink_producer_proxy()
339         {               
340                 executor_.invoke([=]
341                 {
342                         producer_.reset();
343                         com_uninitialize();
344                 });
345         }
346
347         core::monitor::subject& monitor_output()
348         {
349                 return producer_->monitor_output();
350         }
351         
352         // frame_producer
353                                 
354         core::draw_frame receive_impl() override
355         {               
356                 return producer_->get_frame();
357         }
358
359         core::constraints& pixel_constraints() override
360         {
361                 return producer_->pixel_constraints();
362         }
363                         
364         uint32_t nb_frames() const override
365         {
366                 return length_;
367         }
368         
369         std::wstring print() const override
370         {
371                 return producer_->print();
372         }
373         
374         std::wstring name() const override
375         {
376                 return L"decklink";
377         }
378
379         boost::property_tree::wptree info() const override
380         {
381                 boost::property_tree::wptree info;
382                 info.add(L"type", L"decklink");
383                 return info;
384         }
385 };
386
387 void describe_producer(core::help_sink& sink, const core::help_repository& repo)
388 {
389         sink.short_description(L"Allows video sources to be input from BlackMagic Design cards.");
390         sink.syntax(L"DECKLINK [device:int],DEVICE [device:int] {FILTER [filter:string]} {LENGTH [length:int]} {FORMAT [format:string]} {CHANNEL_LAYOUT [channel_layout:string]}");
391         sink.para()->text(L"Allows video sources to be input from BlackMagic Design cards. Parameters:");
392         sink.definitions()
393                 ->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.")
394                 ->item(L"filter", L"If specified, sets an FFmpeg video filter to use.")
395                 ->item(L"length", L"Optionally specify a limit on how many frames to produce.")
396                 ->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.")
397                 ->item(L"channel_layout", L"Specifies what audio channel layout to expect on the incoming SDI/HDMI signal. If not specified, stereo is assumed.");
398         sink.para()->text(L"Examples:");
399         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.");
400         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.");
401         sink.example(L">> PLAY 1-10 DECKLINK DEVICE 2 LENGTH 1000", L"Play using decklink device 2 but only produce 1000 frames.");
402         sink.example(L">> PLAY 1-10 DECKLINK DEVICE 2 CHANNEL_LAYOUT smpte", L"Play using decklink device 2 and expect smpte surround sound.");
403 }
404
405 spl::shared_ptr<core::frame_producer> create_producer(const core::frame_producer_dependencies& dependencies, const std::vector<std::wstring>& params)
406 {
407         if(params.empty() || !boost::iequals(params.at(0), "decklink"))
408                 return core::frame_producer::empty();
409
410         auto device_index       = get_param(L"DEVICE", params, -1);
411         if(device_index == -1)
412                 device_index = boost::lexical_cast<int>(params.at(1));
413         
414         auto filter_str         = get_param(L"FILTER", params);         
415         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   
416         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
417                 
418         if(in_format_desc.format == core::video_format::invalid)
419                 in_format_desc = dependencies.format_desc;
420
421         auto channel_layout_spec        = get_param(L"CHANNEL_LAYOUT", params);
422         auto channel_layout                     = *core::audio_channel_layout_repository::get_default()->get_layout(L"stereo");
423
424         if (!channel_layout_spec.empty())
425         {
426                 auto found_layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout_spec);
427
428                 if (!found_layout)
429                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(L"Channel layout not found."));
430
431                 channel_layout = *found_layout;
432         }
433                         
434         return create_destroy_proxy(spl::make_shared<decklink_producer_proxy>(
435                         in_format_desc,
436                         dependencies.frame_factory,
437                         dependencies.format_desc,
438                         channel_layout,
439                         device_index,
440                         filter_str,
441                         length));
442 }
443
444 }}