2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
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.
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.
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/>.
19 * Author: Robert Nagy, ronag89@gmail.com
22 #include "../stdafx.h"
24 #include "decklink_producer.h"
26 #include "../interop/DeckLinkAPI_h.h"
27 #include "../util/util.h"
29 #include "../../ffmpeg/producer/filter/filter.h"
30 #include "../../ffmpeg/producer/util/util.h"
31 #include "../../ffmpeg/producer/muxer/frame_muxer.h"
32 #include "../../ffmpeg/producer/muxer/display_mode.h"
34 #include <common/executor.h>
35 #include <common/diagnostics/graph.h>
36 #include <common/except.h>
37 #include <common/log.h>
38 #include <common/param.h>
40 #include <core/frame/frame.h>
41 #include <core/frame/draw_frame.h>
42 #include <core/frame/frame_transform.h>
43 #include <core/frame/frame_factory.h>
44 #include <core/monitor/monitor.h>
45 #include <core/mixer/audio/audio_mixer.h>
47 #include <tbb/concurrent_queue.h>
49 #include <boost/algorithm/string.hpp>
50 #include <boost/foreach.hpp>
51 #include <boost/property_tree/ptree.hpp>
52 #include <boost/timer.hpp>
55 #pragma warning (push)
56 #pragma warning (disable : 4244)
60 #define __STDC_CONSTANT_MACROS
61 #define __STDC_LIMIT_MACROS
62 #include <libavcodec/avcodec.h>
69 #pragma warning(disable : 4996)
80 namespace caspar { namespace decklink {
82 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
84 monitor::basic_subject event_subject_;
85 spl::shared_ptr<diagnostics::graph> graph_;
86 boost::timer tick_timer_;
88 CComPtr<IDeckLink> decklink_;
89 CComQIPtr<IDeckLinkInput> input_;
90 CComQIPtr<IDeckLinkAttributes > attributes_;
92 const std::wstring model_name_;
93 const int device_index_;
94 const std::wstring filter_;
96 std::vector<int> audio_cadence_;
97 boost::circular_buffer<size_t> sync_buffer_;
98 ffmpeg::frame_muxer muxer_;
100 spl::shared_ptr<core::frame_factory> frame_factory_;
101 core::video_format_desc in_format_desc_;
102 core::video_format_desc out_format_desc_;
104 tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;
106 std::exception_ptr exception_;
109 decklink_producer(const core::video_format_desc& in_format_desc,
111 const spl::shared_ptr<core::frame_factory>& frame_factory,
112 const core::video_format_desc& out_format_desc,
113 const std::wstring& filter)
114 : decklink_(get_device(device_index))
116 , attributes_(decklink_)
117 , model_name_(get_model_name(decklink_))
118 , device_index_(device_index)
120 , in_format_desc_(in_format_desc)
121 , out_format_desc_(out_format_desc)
122 , muxer_(in_format_desc.fps, frame_factory, out_format_desc, filter)
123 , audio_cadence_(out_format_desc.audio_cadence)
124 , sync_buffer_(out_format_desc.audio_cadence.size())
125 , frame_factory_(frame_factory)
127 frame_buffer_.set_capacity(2);
129 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
130 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
131 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
132 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
133 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
134 graph_->set_text(print());
135 diagnostics::register_graph(graph_);
137 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
139 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
140 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0)))
141 CASPAR_THROW_EXCEPTION(caspar_exception()
142 << msg_info(print() + L" Could not enable video input.")
143 << boost::errinfo_api_function("EnableVideoInput"));
145 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(in_format_desc.audio_channels))))
146 CASPAR_THROW_EXCEPTION(caspar_exception()
147 << msg_info(print() + L" Could not enable audio input.")
148 << boost::errinfo_api_function("EnableAudioInput"));
150 if (FAILED(input_->SetCallback(this)) != S_OK)
151 CASPAR_THROW_EXCEPTION(caspar_exception()
152 << msg_info(print() + L" Failed to set input callback.")
153 << boost::errinfo_api_function("SetCallback"));
155 if(FAILED(input_->StartStreams()))
156 CASPAR_THROW_EXCEPTION(caspar_exception()
157 << msg_info(print() + L" Failed to start input stream.")
158 << boost::errinfo_api_function("StartStreams"));
160 CASPAR_LOG(info) << print() << L" Initialized";
165 if(input_ != nullptr)
167 input_->StopStreams();
168 input_->DisableVideoInput();
172 virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID, LPVOID*) {return E_NOINTERFACE;}
173 virtual ULONG STDMETHODCALLTYPE AddRef () {return 1;}
174 virtual ULONG STDMETHODCALLTYPE Release () {return 1;}
176 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
181 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
188 graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);
189 tick_timer_.restart();
191 boost::timer frame_timer;
195 void* video_bytes = nullptr;
196 if(FAILED(video->GetBytes(&video_bytes)) || !video_bytes)
199 auto video_frame = ffmpeg::create_frame();
201 video_frame->data[0] = reinterpret_cast<uint8_t*>(video_bytes);
202 video_frame->linesize[0] = video->GetRowBytes();
203 video_frame->format = PIX_FMT_UYVY422;
204 video_frame->width = video->GetWidth();
205 video_frame->height = video->GetHeight();
206 video_frame->interlaced_frame = in_format_desc_.field_mode != core::field_mode::progressive;
207 video_frame->top_field_first = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
209 event_subject_ << monitor::event("file/name") % model_name_
210 << monitor::event("file/path") % device_index_
211 << monitor::event("file/video/width") % video->GetWidth()
212 << monitor::event("file/video/height") % video->GetHeight()
213 << monitor::event("file/video/field") % u8(!video_frame->interlaced_frame ? "progressive" : (video_frame->top_field_first ? "upper" : "lower"))
214 << monitor::event("file/audio/sample-rate") % 48000
215 << monitor::event("file/audio/channels") % 2
216 << monitor::event("file/audio/format") % u8(av_get_sample_fmt_name(AV_SAMPLE_FMT_S32))
217 << monitor::event("file/fps") % in_format_desc_.fps;
221 std::shared_ptr<core::audio_buffer> audio_buffer;
223 void* audio_bytes = nullptr;
224 if(FAILED(audio->GetBytes(&audio_bytes)) || !audio_bytes)
227 auto audio_frame = ffmpeg::create_frame();
229 audio_frame->data[0] = reinterpret_cast<uint8_t*>(audio_bytes);
230 audio_frame->linesize[0] = audio->GetSampleFrameCount()*out_format_desc_.audio_channels*sizeof(int32_t);
231 audio_frame->nb_samples = audio->GetSampleFrameCount();
232 audio_frame->format = AV_SAMPLE_FMT_S32;
234 // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
235 // This cadence fills the audio mixer most optimally.
237 sync_buffer_.push_back(audio->GetSampleFrameCount()*out_format_desc_.audio_channels);
238 if(!boost::range::equal(sync_buffer_, audio_cadence_))
240 CASPAR_LOG(trace) << print() << L" Syncing audio.";
243 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
247 muxer_.push_video(video_frame);
248 muxer_.push_audio(audio_frame);
252 auto frame = core::draw_frame::late();
255 frame = std::move(muxer_.front());
258 if(!frame_buffer_.try_push(frame))
260 auto dummy = core::draw_frame::empty();
261 frame_buffer_.try_pop(dummy);
262 frame_buffer_.try_push(frame);
264 graph_->set_tag("dropped-frame");
268 graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);
269 event_subject_ << monitor::event("profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;
271 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
272 event_subject_ << monitor::event("buffer") % frame_buffer_.size() % frame_buffer_.capacity();
276 exception_ = std::current_exception();
283 core::draw_frame get_frame()
285 if(exception_ != nullptr)
286 std::rethrow_exception(exception_);
288 core::draw_frame frame = core::draw_frame::late();
289 if(!frame_buffer_.try_pop(frame))
290 graph_->set_tag("late-frame");
291 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));
295 std::wstring print() const
297 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";
300 void subscribe(const monitor::observable::observer_ptr& o)
302 event_subject_.subscribe(o);
305 void unsubscribe(const monitor::observable::observer_ptr& o)
307 event_subject_.unsubscribe(o);
311 class decklink_producer_proxy : public core::frame_producer_base
313 std::unique_ptr<decklink_producer> producer_;
314 const uint32_t length_;
317 explicit decklink_producer_proxy(const core::video_format_desc& in_format_desc,
318 const spl::shared_ptr<core::frame_factory>& frame_factory,
319 const core::video_format_desc& out_format_desc,
321 const std::wstring& filter_str, uint32_t length)
322 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
327 CoInitialize(nullptr);
328 producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, filter_str));
332 ~decklink_producer_proxy()
341 void subscribe(const monitor::observable::observer_ptr& o) override
343 producer_->subscribe(o);
346 void unsubscribe(const monitor::observable::observer_ptr& o) override
348 producer_->unsubscribe(o);
353 core::draw_frame receive_impl() override
355 return producer_->get_frame();
358 uint32_t nb_frames() const override
363 std::wstring print() const override
365 return producer_->print();
368 std::wstring name() const override
373 boost::property_tree::wptree info() const override
375 boost::property_tree::wptree info;
376 info.add(L"type", L"decklink");
381 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& out_format_desc, const std::vector<std::wstring>& params)
383 if(params.empty() || !boost::iequals(params[0], "decklink"))
384 return core::frame_producer::empty();
386 auto device_index = get_param(L"DEVICE", params, -1);
387 if(device_index == -1)
388 device_index = boost::lexical_cast<int>(params.at(1));
390 auto filter_str = get_param(L"FILTER", params);
391 auto length = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
392 auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
394 if(in_format_desc.format == core::video_format::invalid)
395 in_format_desc = out_format_desc;
397 return create_destroy_proxy(spl::make_shared<decklink_producer_proxy>(in_format_desc, frame_factory, out_format_desc, device_index, filter_str, length));