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