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