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