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/executor.h>
\r
35 #include <common/diagnostics/graph.h>
\r
36 #include <common/except.h>
\r
37 #include <common/log.h>
\r
38 #include <common/utility/param.h>
\r
40 #include <core/mixer/gpu/write_frame.h>
\r
41 #include <core/frame/frame_transform.h>
\r
42 #include <core/frame/frame_factory.h>
\r
44 #include <tbb/concurrent_queue.h>
\r
46 #include <boost/algorithm/string.hpp>
\r
47 #include <boost/foreach.hpp>
\r
48 #include <boost/property_tree/ptree.hpp>
\r
49 #include <boost/timer.hpp>
\r
51 #if defined(_MSC_VER)
\r
52 #pragma warning (push)
\r
53 #pragma warning (disable : 4244)
\r
57 #define __STDC_CONSTANT_MACROS
\r
58 #define __STDC_LIMIT_MACROS
\r
59 #include <libavcodec/avcodec.h>
\r
61 #if defined(_MSC_VER)
\r
62 #pragma warning (pop)
\r
65 #pragma warning(push)
\r
66 #pragma warning(disable : 4996)
\r
68 #include <atlbase.h>
\r
71 #include <atlhost.h>
\r
73 #pragma warning(push)
\r
75 #include <functional>
\r
77 namespace caspar { namespace decklink {
\r
79 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
\r
81 CComPtr<IDeckLink> decklink_;
\r
82 CComQIPtr<IDeckLinkInput> input_;
\r
84 const std::wstring model_name_;
\r
85 const core::video_format_desc format_desc_;
\r
86 const size_t device_index_;
\r
88 safe_ptr<diagnostics::graph> graph_;
\r
89 boost::timer tick_timer_;
\r
90 boost::timer frame_timer_;
\r
92 tbb::atomic<int> flags_;
\r
93 safe_ptr<core::frame_factory> frame_factory_;
\r
94 std::vector<int> audio_cadence_;
\r
96 tbb::concurrent_bounded_queue<safe_ptr<core::draw_frame>> frame_buffer_;
\r
98 std::exception_ptr exception_;
\r
100 ffmpeg::frame_muxer muxer_;
\r
102 boost::circular_buffer<size_t> sync_buffer_;
\r
105 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)
\r
106 : decklink_(get_device(device_index))
\r
107 , input_(decklink_)
\r
108 , model_name_(get_model_name(decklink_))
\r
109 , format_desc_(format_desc)
\r
110 , device_index_(device_index)
\r
111 , frame_factory_(frame_factory)
\r
112 , audio_cadence_(frame_factory->get_video_format_desc().audio_cadence)
\r
113 , muxer_(format_desc.fps, frame_factory, filter)
\r
114 , sync_buffer_(format_desc.audio_cadence.size())
\r
117 frame_buffer_.set_capacity(2);
\r
119 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
\r
120 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
\r
121 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
\r
122 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
\r
123 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
\r
124 graph_->set_text(print());
\r
125 diagnostics::register_graph(graph_);
\r
127 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
\r
129 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
\r
130 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0)))
\r
131 BOOST_THROW_EXCEPTION(caspar_exception()
\r
132 << msg_info(print() + L" Could not enable video input.")
\r
133 << boost::errinfo_api_function("EnableVideoInput"));
\r
135 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels)))
\r
136 BOOST_THROW_EXCEPTION(caspar_exception()
\r
137 << msg_info(print() + L" Could not enable audio input.")
\r
138 << boost::errinfo_api_function("EnableAudioInput"));
\r
140 if (FAILED(input_->SetCallback(this)) != S_OK)
\r
141 BOOST_THROW_EXCEPTION(caspar_exception()
\r
142 << msg_info(print() + L" Failed to set input callback.")
\r
143 << boost::errinfo_api_function("SetCallback"));
\r
145 if(FAILED(input_->StartStreams()))
\r
146 BOOST_THROW_EXCEPTION(caspar_exception()
\r
147 << msg_info(print() + L" Failed to start input stream.")
\r
148 << boost::errinfo_api_function("StartStreams"));
\r
151 ~decklink_producer()
\r
153 if(input_ != nullptr)
\r
155 input_->StopStreams();
\r
156 input_->DisableVideoInput();
\r
160 virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID, LPVOID*) {return E_NOINTERFACE;}
\r
161 virtual ULONG STDMETHODCALLTYPE AddRef () {return 1;}
\r
162 virtual ULONG STDMETHODCALLTYPE Release () {return 1;}
\r
164 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
\r
169 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
\r
176 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
\r
177 tick_timer_.restart();
\r
179 frame_timer_.restart();
\r
183 void* bytes = nullptr;
\r
184 if(FAILED(video->GetBytes(&bytes)) || !bytes)
\r
187 safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
188 avcodec_get_frame_defaults(av_frame.get());
\r
190 av_frame->data[0] = reinterpret_cast<uint8_t*>(bytes);
\r
191 av_frame->linesize[0] = video->GetRowBytes();
\r
192 av_frame->format = PIX_FMT_UYVY422;
\r
193 av_frame->width = video->GetWidth();
\r
194 av_frame->height = video->GetHeight();
\r
195 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
196 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
\r
198 std::shared_ptr<core::audio_buffer> audio_buffer;
\r
200 // It is assumed that audio is always equal or ahead of video.
\r
201 if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)
\r
203 auto sample_frame_count = audio->GetSampleFrameCount();
\r
204 auto audio_data = reinterpret_cast<int32_t*>(bytes);
\r
205 audio_buffer = std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels);
\r
208 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0);
\r
210 // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
\r
211 // This cadence fills the audio mixer most optimally.
\r
213 sync_buffer_.push_back(audio_buffer->size());
\r
214 if(!boost::range::equal(sync_buffer_, audio_cadence_))
\r
216 CASPAR_LOG(trace) << print() << L" Syncing audio.";
\r
220 muxer_.push(audio_buffer);
\r
221 muxer_.push(av_frame, flags_);
\r
223 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
\r
227 for(auto frame = muxer_.poll(); frame; frame = muxer_.poll())
\r
229 if(!frame_buffer_.try_push(make_safe_ptr(frame)))
\r
230 graph_->set_tag("dropped-frame");
\r
233 graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);
\r
235 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
239 exception_ = std::current_exception();
\r
246 safe_ptr<core::draw_frame> get_frame(int flags)
\r
248 if(exception_ != nullptr)
\r
249 std::rethrow_exception(exception_);
\r
253 safe_ptr<core::draw_frame> frame = core::draw_frame::late();
\r
254 if(!frame_buffer_.try_pop(frame))
\r
255 graph_->set_tag("late-frame");
\r
256 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
260 std::wstring print() const
\r
262 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";
\r
266 class decklink_producer_proxy : public core::frame_producer
\r
268 safe_ptr<core::draw_frame> last_frame_;
\r
269 std::unique_ptr<decklink_producer> producer_;
\r
270 const uint32_t length_;
\r
271 executor executor_;
\r
273 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)
\r
274 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
\r
275 , last_frame_(core::draw_frame::empty())
\r
278 executor_.invoke([=]
\r
280 CoInitialize(nullptr);
\r
281 producer_.reset(new decklink_producer(format_desc, device_index, frame_factory, filter_str));
\r
285 ~decklink_producer_proxy()
\r
287 executor_.invoke([=]
\r
296 virtual safe_ptr<core::draw_frame> receive(int flags) override
\r
298 auto frame = producer_->get_frame(flags);
\r
299 if(frame != core::draw_frame::late())
\r
300 last_frame_ = frame;
\r
304 virtual safe_ptr<core::draw_frame> last_frame() const override
\r
306 return last_frame_;
\r
309 virtual uint32_t nb_frames() const override
\r
314 std::wstring print() const override
\r
316 return producer_->print();
\r
319 virtual boost::property_tree::wptree info() const override
\r
321 boost::property_tree::wptree info;
\r
322 info.add(L"type", L"decklink-producer");
\r
327 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)
\r
329 if(params.empty() || !boost::iequals(params[0], "decklink"))
\r
330 return core::frame_producer::empty();
\r
332 auto device_index = get_param(L"DEVICE", params, 1);
\r
333 auto filter_str = get_param(L"FILTER", params);
\r
334 auto length = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
\r
335 auto format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
\r
337 boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");
\r
338 boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");
\r
340 if(format_desc.format == core::video_format::invalid)
\r
341 format_desc = frame_factory->get_video_format_desc();
\r
343 return create_producer_print_proxy(
\r
344 create_producer_destroy_proxy(
\r
345 make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length)));
\r