2 * Copyright (c) 2011 Sveriges Television AB <info@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
29 #include "../../ffmpeg/producer/filter/filter.h"
\r
30 #include "../../ffmpeg/producer/util/util.h"
\r
31 #include "../../ffmpeg/producer/muxer/frame_muxer.h"
\r
32 #include "../../ffmpeg/producer/muxer/display_mode.h"
\r
34 #include <common/concurrency/com_context.h>
\r
35 #include <common/diagnostics/graph.h>
\r
36 #include <common/exception/exceptions.h>
\r
37 #include <common/log/log.h>
\r
38 #include <common/memory/memclr.h>
\r
39 #include <common/utility/param.h>
\r
41 #include <core/monitor/monitor.h>
\r
42 #include <core/mixer/write_frame.h>
\r
43 #include <core/producer/frame/frame_transform.h>
\r
44 #include <core/producer/frame/frame_factory.h>
\r
46 #include <tbb/concurrent_queue.h>
\r
48 #include <boost/algorithm/string.hpp>
\r
49 #include <boost/foreach.hpp>
\r
50 #include <boost/property_tree/ptree.hpp>
\r
51 #include <boost/timer.hpp>
\r
53 #if defined(_MSC_VER)
\r
54 #pragma warning (push)
\r
55 #pragma warning (disable : 4244)
\r
59 #define __STDC_CONSTANT_MACROS
\r
60 #define __STDC_LIMIT_MACROS
\r
61 #include <libavcodec/avcodec.h>
\r
63 #if defined(_MSC_VER)
\r
64 #pragma warning (pop)
\r
67 #pragma warning(push)
\r
68 #pragma warning(disable : 4996)
\r
70 #include <atlbase.h>
\r
73 #include <atlhost.h>
\r
75 #pragma warning(push)
\r
77 #include <functional>
\r
79 namespace caspar { namespace decklink {
\r
81 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
\r
83 core::monitor::subject monitor_subject_;
\r
84 safe_ptr<diagnostics::graph> graph_;
\r
85 boost::timer tick_timer_;
\r
86 boost::timer frame_timer_;
\r
88 CComPtr<IDeckLink> decklink_;
\r
89 CComQIPtr<IDeckLinkInput> input_;
\r
90 CComQIPtr<IDeckLinkAttributes > attributes_;
\r
92 const std::wstring model_name_;
\r
93 const size_t device_index_;
\r
94 const std::wstring filter_;
\r
96 core::video_format_desc format_desc_;
\r
97 std::vector<size_t> audio_cadence_;
\r
98 boost::circular_buffer<size_t> sync_buffer_;
\r
99 ffmpeg::frame_muxer muxer_;
\r
101 tbb::atomic<int> hints_;
\r
102 safe_ptr<core::frame_factory> frame_factory_;
\r
104 tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>> frame_buffer_;
\r
106 std::exception_ptr exception_;
\r
109 decklink_producer(const core::video_format_desc& format_desc, size_t device_index, const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filter, std::size_t buffer_depth)
\r
110 : decklink_(get_device(device_index))
\r
111 , input_(decklink_)
\r
112 , attributes_(decklink_)
\r
113 , model_name_(get_model_name(decklink_))
\r
114 , device_index_(device_index)
\r
116 , format_desc_(format_desc)
\r
117 , audio_cadence_(format_desc.audio_cadence)
\r
118 , muxer_(format_desc.fps, frame_factory, false, filter)
\r
119 , sync_buffer_(format_desc.audio_cadence.size())
\r
120 , frame_factory_(frame_factory)
\r
123 frame_buffer_.set_capacity(buffer_depth);
\r
125 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
\r
126 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
\r
127 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
\r
128 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
\r
129 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
\r
130 graph_->set_text(print());
\r
131 diagnostics::register_graph(graph_);
\r
133 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
\r
135 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
\r
136 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, bmdVideoInputFlagDefault)))
\r
137 BOOST_THROW_EXCEPTION(caspar_exception()
\r
138 << msg_info(narrow(print()) + " Could not enable video input.")
\r
139 << boost::errinfo_api_function("EnableVideoInput"));
\r
141 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels)))
\r
142 BOOST_THROW_EXCEPTION(caspar_exception()
\r
143 << msg_info(narrow(print()) + " Could not enable audio input.")
\r
144 << boost::errinfo_api_function("EnableAudioInput"));
\r
146 if (FAILED(input_->SetCallback(this)) != S_OK)
\r
147 BOOST_THROW_EXCEPTION(caspar_exception()
\r
148 << msg_info(narrow(print()) + " Failed to set input callback.")
\r
149 << boost::errinfo_api_function("SetCallback"));
\r
151 if(FAILED(input_->StartStreams()))
\r
152 BOOST_THROW_EXCEPTION(caspar_exception()
\r
153 << msg_info(narrow(print()) + " Failed to start input stream.")
\r
154 << boost::errinfo_api_function("StartStreams"));
\r
157 ~decklink_producer()
\r
159 if(input_ != nullptr)
\r
161 input_->StopStreams();
\r
162 input_->DisableVideoInput();
\r
166 virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID, LPVOID*) {return E_NOINTERFACE;}
\r
167 virtual ULONG STDMETHODCALLTYPE AddRef () {return 1;}
\r
168 virtual ULONG STDMETHODCALLTYPE Release () {return 1;}
\r
170 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
\r
175 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
\r
182 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
\r
183 tick_timer_.restart();
\r
185 frame_timer_.restart();
\r
189 void* bytes = nullptr;
\r
190 if(FAILED(video->GetBytes(&bytes)) || !bytes)
\r
193 safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
194 avcodec_get_frame_defaults(av_frame.get());
\r
196 av_frame->data[0] = reinterpret_cast<uint8_t*>(bytes);
\r
197 av_frame->linesize[0] = video->GetRowBytes();
\r
198 av_frame->format = PIX_FMT_UYVY422;
\r
199 av_frame->width = video->GetWidth();
\r
200 av_frame->height = video->GetHeight();
\r
201 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
202 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
\r
204 std::shared_ptr<core::audio_buffer> audio_buffer;
\r
206 // It is assumed that audio is always equal or ahead of video.
\r
207 if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)
\r
209 auto sample_frame_count = audio->GetSampleFrameCount();
\r
210 auto audio_data = reinterpret_cast<int32_t*>(bytes);
\r
211 audio_buffer = std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels);
\r
214 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0);
\r
216 // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
\r
217 // This cadence fills the audio mixer most optimally.
\r
219 sync_buffer_.push_back(audio_buffer->size());
\r
220 if(!boost::range::equal(sync_buffer_, audio_cadence_))
\r
222 CASPAR_LOG(trace) << print() << L" Syncing audio.";
\r
226 muxer_.push(audio_buffer);
\r
227 muxer_.push(av_frame, hints_);
\r
229 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
\r
233 for(auto frame = muxer_.poll(); frame; frame = muxer_.poll())
\r
235 if(!frame_buffer_.try_push(make_safe_ptr(frame)))
\r
237 auto dummy = core::basic_frame::empty();
\r
238 frame_buffer_.try_pop(dummy);
\r
240 frame_buffer_.try_push(make_safe_ptr(frame));
\r
242 graph_->set_tag("dropped-frame");
\r
246 graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);
\r
248 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
252 exception_ = std::current_exception();
\r
259 safe_ptr<core::basic_frame> get_frame(int hints)
\r
261 if(exception_ != nullptr)
\r
262 std::rethrow_exception(exception_);
\r
266 safe_ptr<core::basic_frame> frame = core::basic_frame::late();
\r
267 if(!frame_buffer_.try_pop(frame))
\r
268 graph_->set_tag("late-frame");
\r
269 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
273 std::wstring print() const
\r
275 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + format_desc_.name + L"]";
\r
278 core::monitor::source& monitor_output()
\r
280 return monitor_subject_;
\r
284 class decklink_producer_proxy : public core::frame_producer
\r
286 safe_ptr<core::basic_frame> last_frame_;
\r
287 com_context<decklink_producer> context_;
\r
288 const uint32_t length_;
\r
291 explicit decklink_producer_proxy(const safe_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, size_t device_index, const std::wstring& filter_str, uint32_t length, std::size_t buffer_depth)
\r
292 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
\r
293 , last_frame_(core::basic_frame::empty())
\r
296 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str, buffer_depth);});
\r
301 virtual safe_ptr<core::basic_frame> receive(int hints) override
\r
303 auto frame = context_->get_frame(hints);
\r
304 if(frame != core::basic_frame::late())
\r
305 last_frame_ = frame;
\r
309 virtual safe_ptr<core::basic_frame> last_frame() const override
\r
311 return disable_audio(last_frame_);
\r
314 virtual uint32_t nb_frames() const override
\r
319 std::wstring print() const override
\r
321 return context_->print();
\r
324 virtual boost::property_tree::wptree info() const override
\r
326 boost::property_tree::wptree info;
\r
327 info.add(L"type", L"decklink-producer");
\r
331 core::monitor::source& monitor_output()
\r
333 return context_->monitor_output();
\r
337 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)
\r
339 if(params.empty() || !boost::iequals(params[0], "decklink"))
\r
340 return core::frame_producer::empty();
\r
342 auto device_index = get_param(L"DEVICE", params, -1);
\r
343 if(device_index == -1)
\r
344 device_index = boost::lexical_cast<int>(params.at(1));
\r
345 auto filter_str = get_param(L"FILTER", params);
\r
346 auto length = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
\r
347 auto buffer_depth = get_param(L"BUFFER", params, 2);
\r
348 auto format_desc = core::video_format_desc::get(get_param(L"FORMAT", params, L"INVALID"));
\r
350 boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");
\r
351 boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");
\r
353 if(format_desc.format == core::video_format::invalid)
\r
354 format_desc = frame_factory->get_video_format_desc();
\r
356 return create_producer_print_proxy(
\r
357 create_producer_destroy_proxy(
\r
358 make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length, buffer_depth)));
\r