2 * Copyright 2013 Sveriges Television AB http://casparcg.com/
\r
4 * This file is part of CasparCG (www.casparcg.com).
\r
6 * CasparCG is free software: you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation, either version 3 of the License, or
\r
9 * (at your option) any later version.
\r
11 * CasparCG is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
\r
19 * Author: Robert Nagy, ronag89@gmail.com
\r
22 #include "../stdafx.h"
\r
24 #include "decklink_producer.h"
\r
26 #include "../interop/DeckLinkAPI_h.h"
\r
27 #include "../util/util.h"
\r
28 #include "../util/decklink_allocator.h"
\r
30 #include "../../ffmpeg/producer/filter/filter.h"
\r
31 #include "../../ffmpeg/producer/util/util.h"
\r
32 #include "../../ffmpeg/producer/muxer/frame_muxer.h"
\r
33 #include "../../ffmpeg/producer/muxer/display_mode.h"
\r
35 #include <common/concurrency/com_context.h>
\r
36 #include <common/diagnostics/graph.h>
\r
37 #include <common/exception/exceptions.h>
\r
38 #include <common/exception/win32_exception.h>
\r
39 #include <common/log/log.h>
\r
40 #include <common/memory/memclr.h>
\r
42 #include <core/parameters/parameters.h>
\r
43 #include <core/monitor/monitor.h>
\r
44 #include <core/mixer/write_frame.h>
\r
45 #include <core/mixer/audio/audio_util.h>
\r
46 #include <core/producer/frame/frame_transform.h>
\r
47 #include <core/producer/frame/frame_factory.h>
\r
49 #include <tbb/concurrent_queue.h>
\r
51 #include <boost/algorithm/string.hpp>
\r
52 #include <boost/foreach.hpp>
\r
53 #include <boost/property_tree/ptree.hpp>
\r
54 #include <boost/timer.hpp>
\r
56 #if defined(_MSC_VER)
\r
57 #pragma warning (push)
\r
58 #pragma warning (disable : 4244)
\r
62 #define __STDC_CONSTANT_MACROS
\r
63 #define __STDC_LIMIT_MACROS
\r
64 #include <libavcodec/avcodec.h>
\r
66 #if defined(_MSC_VER)
\r
67 #pragma warning (pop)
\r
70 #pragma warning(push)
\r
71 #pragma warning(disable : 4996)
\r
73 #include <atlbase.h>
\r
76 #include <atlhost.h>
\r
78 #pragma warning(push)
\r
80 #include <functional>
\r
82 namespace caspar { namespace decklink {
\r
84 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
\r
86 core::monitor::subject monitor_subject_;
\r
87 safe_ptr<diagnostics::graph> graph_;
\r
88 boost::timer tick_timer_;
\r
89 boost::timer frame_timer_;
\r
91 std::unique_ptr<thread_safe_decklink_allocator> allocator_;
\r
92 CComPtr<IDeckLink> decklink_;
\r
93 CComQIPtr<IDeckLinkInput> input_;
\r
94 CComQIPtr<IDeckLinkAttributes > attributes_;
\r
96 const std::wstring model_name_;
\r
97 const size_t device_index_;
\r
98 const std::wstring filter_;
\r
100 core::video_format_desc format_desc_;
\r
101 std::vector<size_t> audio_cadence_;
\r
102 boost::circular_buffer<size_t> sync_buffer_;
\r
103 ffmpeg::frame_muxer muxer_;
\r
105 tbb::atomic<int> hints_;
\r
106 safe_ptr<core::frame_factory> frame_factory_;
\r
108 tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>> frame_buffer_;
\r
110 std::exception_ptr exception_;
\r
111 int num_input_channels_;
\r
112 core::channel_layout audio_channel_layout_;
\r
116 const core::video_format_desc& format_desc,
\r
117 const core::channel_layout& audio_channel_layout,
\r
118 size_t device_index,
\r
119 const safe_ptr<core::frame_factory>& frame_factory,
\r
120 const std::wstring& filter,
\r
121 std::size_t buffer_depth)
\r
122 : decklink_(get_device(device_index))
\r
123 , input_(decklink_)
\r
124 , attributes_(decklink_)
\r
125 , model_name_(get_model_name(decklink_))
\r
126 , device_index_(device_index)
\r
128 , format_desc_(format_desc)
\r
129 , audio_cadence_(format_desc.audio_cadence)
\r
130 , muxer_(format_desc.fps, frame_factory, false, audio_channel_layout, filter)
\r
131 , sync_buffer_(format_desc.audio_cadence.size())
\r
132 , frame_factory_(frame_factory)
\r
133 , audio_channel_layout_(audio_channel_layout)
\r
136 frame_buffer_.set_capacity(buffer_depth);
\r
138 if (audio_channel_layout.num_channels <= 2)
\r
139 num_input_channels_ = 2;
\r
140 else if (audio_channel_layout.num_channels <= 8)
\r
141 num_input_channels_ = 8;
\r
143 num_input_channels_ = 16;
\r
145 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
\r
146 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
\r
147 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
\r
148 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
\r
149 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
\r
150 graph_->set_text(print());
\r
151 diagnostics::register_graph(graph_);
\r
153 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
\r
155 allocator_.reset(new thread_safe_decklink_allocator(print()));
\r
157 if(FAILED(input_->SetVideoInputFrameMemoryAllocator(allocator_.get())))
\r
158 BOOST_THROW_EXCEPTION(caspar_exception()
\r
159 << msg_info(narrow(print()) + " Could not enable use of custom allocator.")
\r
160 << boost::errinfo_api_function("SetVideoInputFrameMemoryAllocator"));
\r
162 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
\r
163 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, bmdVideoInputFlagDefault)))
\r
164 BOOST_THROW_EXCEPTION(caspar_exception()
\r
165 << msg_info(narrow(print()) + " Could not enable video input.")
\r
166 << boost::errinfo_api_function("EnableVideoInput"));
\r
168 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, num_input_channels_)))
\r
169 BOOST_THROW_EXCEPTION(caspar_exception()
\r
170 << msg_info(narrow(print()) + " Could not enable audio input.")
\r
171 << boost::errinfo_api_function("EnableAudioInput"));
\r
173 if (FAILED(input_->SetCallback(this)) != S_OK)
\r
174 BOOST_THROW_EXCEPTION(caspar_exception()
\r
175 << msg_info(narrow(print()) + " Failed to set input callback.")
\r
176 << boost::errinfo_api_function("SetCallback"));
\r
178 if(FAILED(input_->StartStreams()))
\r
179 BOOST_THROW_EXCEPTION(caspar_exception()
\r
180 << msg_info(narrow(print()) + " Failed to start input stream.")
\r
181 << boost::errinfo_api_function("StartStreams"));
\r
184 ~decklink_producer()
\r
186 if(input_ != nullptr)
\r
188 input_->StopStreams();
\r
189 input_->DisableVideoInput();
\r
193 virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID, LPVOID*) {return E_NOINTERFACE;}
\r
194 virtual ULONG STDMETHODCALLTYPE AddRef () {return 1;}
\r
195 virtual ULONG STDMETHODCALLTYPE Release () {return 1;}
\r
197 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
\r
202 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
\r
204 win32_exception::ensure_handler_installed_for_thread("decklink-VideoInputFrameArrived");
\r
210 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
\r
211 tick_timer_.restart();
\r
213 frame_timer_.restart();
\r
217 void* bytes = nullptr;
\r
218 if(FAILED(video->GetBytes(&bytes)) || !bytes)
\r
221 safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
222 avcodec_get_frame_defaults(av_frame.get());
\r
224 av_frame->data[0] = reinterpret_cast<uint8_t*>(bytes);
\r
225 av_frame->linesize[0] = video->GetRowBytes();
\r
226 av_frame->format = PIX_FMT_UYVY422;
\r
227 av_frame->width = video->GetWidth();
\r
228 av_frame->height = video->GetHeight();
\r
229 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
230 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
\r
232 std::shared_ptr<core::audio_buffer> audio_buffer;
\r
234 // It is assumed that audio is always equal or ahead of video.
\r
235 if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)
\r
237 auto sample_frame_count = audio->GetSampleFrameCount();
\r
238 auto audio_data = reinterpret_cast<int32_t*>(bytes);
\r
240 if (num_input_channels_ == audio_channel_layout_.num_channels)
\r
242 audio_buffer = std::make_shared<core::audio_buffer>(
\r
244 audio_data + sample_frame_count * num_input_channels_);
\r
248 audio_buffer = std::make_shared<core::audio_buffer>();
\r
249 audio_buffer->resize(sample_frame_count * audio_channel_layout_.num_channels, 0);
\r
250 auto src_view = core::make_multichannel_view<int32_t>(
\r
252 audio_data + sample_frame_count * num_input_channels_,
\r
253 audio_channel_layout_,
\r
254 num_input_channels_);
\r
255 auto dst_view = core::make_multichannel_view<int32_t>(
\r
256 audio_buffer->begin(),
\r
257 audio_buffer->end(),
\r
258 audio_channel_layout_);
\r
260 core::rearrange(src_view, dst_view);
\r
264 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front() * audio_channel_layout_.num_channels, 0);
\r
266 // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
\r
267 // This cadence fills the audio mixer most optimally.
\r
269 sync_buffer_.push_back(audio_buffer->size() / audio_channel_layout_.num_channels);
\r
270 if(!boost::range::equal(sync_buffer_, audio_cadence_))
\r
272 CASPAR_LOG(trace) << print() << L" Syncing audio.";
\r
276 muxer_.push(audio_buffer);
\r
277 muxer_.push(av_frame, hints_);
\r
279 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
\r
283 for(auto frame = muxer_.poll(); frame; frame = muxer_.poll())
\r
285 if(!frame_buffer_.try_push(make_safe_ptr(frame)))
\r
287 auto dummy = core::basic_frame::empty();
\r
288 frame_buffer_.try_pop(dummy);
\r
290 frame_buffer_.try_push(make_safe_ptr(frame));
\r
292 graph_->set_tag("dropped-frame");
\r
296 graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);
\r
298 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
302 exception_ = std::current_exception();
\r
309 safe_ptr<core::basic_frame> get_frame(int hints)
\r
311 if(exception_ != nullptr)
\r
312 std::rethrow_exception(exception_);
\r
316 safe_ptr<core::basic_frame> frame = core::basic_frame::late();
\r
317 if(!frame_buffer_.try_pop(frame))
\r
318 graph_->set_tag("late-frame");
\r
319 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
323 std::wstring print() const
\r
325 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + format_desc_.name + L"]";
\r
328 core::monitor::source& monitor_output()
\r
330 return monitor_subject_;
\r
334 class decklink_producer_proxy : public core::frame_producer
\r
336 safe_ptr<core::basic_frame> last_frame_;
\r
337 com_context<decklink_producer> context_;
\r
338 const uint32_t length_;
\r
341 explicit decklink_producer_proxy(
\r
342 const safe_ptr<core::frame_factory>& frame_factory,
\r
343 const core::video_format_desc& format_desc,
\r
344 const core::channel_layout& audio_channel_layout,
\r
345 size_t device_index,
\r
346 const std::wstring& filter_str,
\r
348 std::size_t buffer_depth)
\r
349 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
\r
350 , last_frame_(core::basic_frame::empty())
\r
353 context_.reset([&]{return new decklink_producer(format_desc, audio_channel_layout, device_index, frame_factory, filter_str, buffer_depth);});
\r
358 virtual safe_ptr<core::basic_frame> receive(
\r
359 int hints) override
\r
361 auto frame = context_->get_frame(hints);
\r
362 if(frame != core::basic_frame::late())
\r
363 last_frame_ = frame;
\r
367 virtual safe_ptr<core::basic_frame> last_frame() const override
\r
369 return disable_audio(last_frame_);
\r
372 virtual uint32_t nb_frames() const override
\r
377 std::wstring print() const override
\r
379 return context_->print();
\r
382 virtual boost::property_tree::wptree info() const override
\r
384 boost::property_tree::wptree info;
\r
385 info.add(L"type", L"decklink-producer");
\r
389 core::monitor::source& monitor_output()
\r
391 return context_->monitor_output();
\r
395 safe_ptr<core::frame_producer> create_producer(
\r
396 const safe_ptr<core::frame_factory>& frame_factory,
\r
397 const core::parameters& params)
\r
399 if(params.empty() || !boost::iequals(params[0], "decklink"))
\r
400 return core::frame_producer::empty();
\r
402 auto device_index = params.get(L"DEVICE", -1);
\r
403 if(device_index == -1)
\r
404 device_index = boost::lexical_cast<int>(params.at(1));
\r
405 auto filter_str = params.get(L"FILTER");
\r
406 auto length = params.get(L"LENGTH", std::numeric_limits<uint32_t>::max());
\r
407 auto buffer_depth = params.get(L"BUFFER", 2);
\r
408 auto format_desc = core::video_format_desc::get(params.get(L"FORMAT", L"INVALID"));
\r
409 auto audio_layout = core::create_custom_channel_layout(
\r
410 params.get(L"CHANNEL_LAYOUT", L"STEREO"),
\r
411 core::default_channel_layout_repository());
\r
413 boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");
\r
414 boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");
\r
416 if(format_desc.format == core::video_format::invalid)
\r
417 format_desc = frame_factory->get_video_format_desc();
\r
419 return create_producer_print_proxy(
\r
420 create_producer_destroy_proxy(
\r
421 make_safe<decklink_producer_proxy>(frame_factory, format_desc, audio_layout, device_index, filter_str, length, buffer_depth)));
\r