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/param.h>
\r
40 #include <core/frame/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 spl::shared_ptr<diagnostics::graph> graph_;
\r
82 boost::timer tick_timer_;
\r
83 boost::timer frame_timer_;
\r
85 CComPtr<IDeckLink> decklink_;
\r
86 CComQIPtr<IDeckLinkInput> input_;
\r
87 CComQIPtr<IDeckLinkAttributes > attributes_;
\r
89 const std::wstring model_name_;
\r
90 const size_t device_index_;
\r
91 const std::wstring filter_;
\r
93 core::video_format_desc format_desc_;
\r
94 std::vector<int> audio_cadence_;
\r
95 boost::circular_buffer<size_t> sync_buffer_;
\r
96 ffmpeg::frame_muxer muxer_;
\r
98 tbb::atomic<int> flags_;
\r
99 spl::shared_ptr<core::frame_factory> frame_factory_;
\r
101 tbb::concurrent_bounded_queue<
\r
102 spl::shared_ptr<core::draw_frame>> frame_buffer_;
\r
104 std::exception_ptr exception_;
\r
107 decklink_producer(const core::video_format_desc& format_desc, size_t device_index, const spl::shared_ptr<core::frame_factory>& frame_factory, const std::wstring& filter)
\r
108 : decklink_(get_device(device_index))
\r
109 , input_(decklink_)
\r
110 , attributes_(decklink_)
\r
111 , model_name_(get_model_name(decklink_))
\r
112 , device_index_(device_index)
\r
114 , format_desc_(format_desc)
\r
115 , audio_cadence_(format_desc.audio_cadence)
\r
116 , muxer_(format_desc.fps, frame_factory, filter)
\r
117 , sync_buffer_(format_desc.audio_cadence.size())
\r
118 , frame_factory_(frame_factory)
\r
121 frame_buffer_.set_capacity(2);
\r
123 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
\r
124 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
\r
125 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
\r
126 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
\r
127 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
\r
128 graph_->set_text(print());
\r
129 diagnostics::register_graph(graph_);
\r
131 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
\r
133 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
\r
134 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0)))
\r
135 BOOST_THROW_EXCEPTION(caspar_exception()
\r
136 << msg_info(print() + L" Could not enable video input.")
\r
137 << boost::errinfo_api_function("EnableVideoInput"));
\r
139 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels)))
\r
140 BOOST_THROW_EXCEPTION(caspar_exception()
\r
141 << msg_info(print() + L" Could not enable audio input.")
\r
142 << boost::errinfo_api_function("EnableAudioInput"));
\r
144 if (FAILED(input_->SetCallback(this)) != S_OK)
\r
145 BOOST_THROW_EXCEPTION(caspar_exception()
\r
146 << msg_info(print() + L" Failed to set input callback.")
\r
147 << boost::errinfo_api_function("SetCallback"));
\r
149 if(FAILED(input_->StartStreams()))
\r
150 BOOST_THROW_EXCEPTION(caspar_exception()
\r
151 << msg_info(print() + L" Failed to start input stream.")
\r
152 << boost::errinfo_api_function("StartStreams"));
\r
155 ~decklink_producer()
\r
157 if(input_ != nullptr)
\r
159 input_->StopStreams();
\r
160 input_->DisableVideoInput();
\r
164 virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID, LPVOID*) {return E_NOINTERFACE;}
\r
165 virtual ULONG STDMETHODCALLTYPE AddRef () {return 1;}
\r
166 virtual ULONG STDMETHODCALLTYPE Release () {return 1;}
\r
168 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
\r
173 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
\r
180 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
\r
181 tick_timer_.restart();
\r
183 frame_timer_.restart();
\r
187 void* bytes = nullptr;
\r
188 if(FAILED(video->GetBytes(&bytes)) || !bytes)
\r
191 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
192 avcodec_get_frame_defaults(av_frame.get());
\r
194 av_frame->data[0] = reinterpret_cast<uint8_t*>(bytes);
\r
195 av_frame->linesize[0] = video->GetRowBytes();
\r
196 av_frame->format = PIX_FMT_UYVY422;
\r
197 av_frame->width = video->GetWidth();
\r
198 av_frame->height = video->GetHeight();
\r
199 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
200 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
\r
202 std::shared_ptr<core::audio_buffer> audio_buffer;
\r
204 // It is assumed that audio is always equal or ahead of video.
\r
205 if(audio && SUCCEEDED(audio->GetBytes(&bytes)) && bytes)
\r
207 auto sample_frame_count = audio->GetSampleFrameCount();
\r
208 auto audio_data = reinterpret_cast<int32_t*>(bytes);
\r
209 audio_buffer = std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels);
\r
212 audio_buffer = std::make_shared<core::audio_buffer>(audio_cadence_.front(), 0);
\r
214 // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
\r
215 // This cadence fills the audio mixer most optimally.
\r
217 sync_buffer_.push_back(audio_buffer->size());
\r
218 if(!boost::range::equal(sync_buffer_, audio_cadence_))
\r
220 CASPAR_LOG(trace) << print() << L" Syncing audio.";
\r
224 muxer_.push(audio_buffer);
\r
225 muxer_.push(av_frame, flags_);
\r
227 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
\r
231 for(auto frame = muxer_.poll(); frame; frame = muxer_.poll())
\r
233 if(!frame_buffer_.try_push(spl::make_shared_ptr(frame)))
\r
234 graph_->set_tag("dropped-frame");
\r
237 graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);
\r
239 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
243 exception_ = std::current_exception();
\r
250 spl::shared_ptr<core::draw_frame> get_frame(int flags)
\r
252 if(exception_ != nullptr)
\r
253 std::rethrow_exception(exception_);
\r
257 spl::shared_ptr<core::draw_frame> frame = core::draw_frame::late();
\r
258 if(!frame_buffer_.try_pop(frame))
\r
259 graph_->set_tag("late-frame");
\r
260 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
\r
264 std::wstring print() const
\r
266 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + format_desc_.name + L"]";
\r
270 class decklink_producer_proxy : public core::frame_producer
\r
272 spl::shared_ptr<core::draw_frame> last_frame_;
\r
273 std::unique_ptr<decklink_producer> producer_;
\r
274 const uint32_t length_;
\r
275 executor executor_;
\r
277 explicit decklink_producer_proxy(const spl::shared_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
278 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
\r
279 , last_frame_(core::draw_frame::empty())
\r
282 executor_.invoke([=]
\r
284 CoInitialize(nullptr);
\r
285 producer_.reset(new decklink_producer(format_desc, device_index, frame_factory, filter_str));
\r
289 ~decklink_producer_proxy()
\r
291 executor_.invoke([=]
\r
300 virtual spl::shared_ptr<core::draw_frame> receive(int flags) override
\r
302 auto frame = producer_->get_frame(flags);
\r
303 if(frame != core::draw_frame::late())
\r
304 last_frame_ = frame;
\r
308 virtual spl::shared_ptr<core::draw_frame> last_frame() const override
\r
310 return last_frame_;
\r
313 virtual uint32_t nb_frames() const override
\r
318 std::wstring print() const override
\r
320 return producer_->print();
\r
323 virtual boost::property_tree::wptree info() const override
\r
325 boost::property_tree::wptree info;
\r
326 info.add(L"type", L"decklink-producer");
\r
331 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)
\r
333 if(params.empty() || !boost::iequals(params[0], "decklink"))
\r
334 return core::frame_producer::empty();
\r
336 auto device_index = get_param(L"DEVICE", params, -1);
\r
337 if(device_index == -1)
\r
338 device_index = boost::lexical_cast<int>(params.at(1));
\r
340 auto filter_str = get_param(L"FILTER", params);
\r
341 auto length = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
\r
342 auto format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
\r
344 boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");
\r
345 boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");
\r
347 if(format_desc.format == core::video_format::invalid)
\r
348 format_desc = frame_factory->get_video_format_desc();
\r
350 return core::wrap_producer(spl::make_shared<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length));
\r