2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>
\r
4 * This file is part of CasparCG.
\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
21 #include "../StdAfx.h"
\r
23 #include "decklink_consumer.h"
\r
25 #include "../util/util.h"
\r
27 #include "../interop/DeckLinkAPI_h.h"
\r
29 #include <core/video_format.h>
\r
31 #include <core/consumer/frame/read_frame.h>
\r
33 #include <common/concurrency/executor.h>
\r
34 #include <common/diagnostics/graph.h>
\r
35 #include <common/exception/exceptions.h>
\r
36 #include <common/utility/timer.h>
\r
38 #include <tbb/concurrent_queue.h>
\r
40 #include <boost/circular_buffer.hpp>
\r
41 #include <boost/timer.hpp>
\r
45 #pragma warning(push)
\r
46 #pragma warning(disable : 4996)
\r
48 #include <atlbase.h>
\r
51 #include <atlhost.h>
\r
53 #pragma warning(push)
\r
57 struct decklink_output : public IDeckLinkVideoOutputCallback, public IDeckLinkAudioOutputCallback, boost::noncopyable
\r
61 co_init(){CoInitialize(nullptr);}
\r
62 ~co_init(){CoUninitialize();}
\r
65 std::wstring model_name_;
\r
66 const size_t device_index_;
\r
67 tbb::atomic<bool> is_running_;
\r
69 std::shared_ptr<diagnostics::graph> graph_;
\r
70 boost::timer perf_timer_;
\r
72 std::array<std::pair<void*, CComPtr<IDeckLinkMutableVideoFrame>>, 3> reserved_frames_;
\r
73 boost::circular_buffer<std::vector<short>> audio_container_;
\r
75 const bool embed_audio_;
\r
76 const bool internal_key;
\r
78 CComPtr<IDeckLink> decklink_;
\r
79 CComQIPtr<IDeckLinkOutput> output_;
\r
80 CComQIPtr<IDeckLinkKeyer> keyer_;
\r
82 core::video_format_desc format_desc_;
\r
84 BMDTimeScale frame_time_scale_;
\r
85 BMDTimeValue frame_duration_;
\r
86 unsigned long frames_scheduled_;
\r
87 unsigned long audio_scheduled_;
\r
89 tbb::concurrent_bounded_queue<std::shared_ptr<const core::read_frame>> video_frame_buffer_;
\r
90 tbb::concurrent_bounded_queue<std::shared_ptr<const core::read_frame>> audio_frame_buffer_;
\r
93 decklink_output(const core::video_format_desc& format_desc,size_t device_index, bool embed_audio, bool internalKey)
\r
94 : model_name_(L"DECKLINK")
\r
95 , device_index_(device_index)
\r
96 , audio_container_(5)
\r
97 , embed_audio_(embed_audio)
\r
98 , internal_key(internalKey)
\r
99 , frames_scheduled_(0)
\r
100 , audio_scheduled_(0)
\r
101 , format_desc_(format_desc)
\r
103 is_running_ = true;
\r
104 format_desc_ = format_desc;
\r
105 CComPtr<IDeckLinkIterator> pDecklinkIterator;
\r
106 if(FAILED(pDecklinkIterator.CoCreateInstance(CLSID_CDeckLinkIterator)))
\r
107 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " No Decklink drivers installed."));
\r
110 while(n < device_index_ && pDecklinkIterator->Next(&decklink_) == S_OK){++n;}
\r
112 if(n != device_index_ || !decklink_)
\r
113 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Decklink card not found.") << arg_name_info("device_index") << arg_value_info(boost::lexical_cast<std::string>(device_index_)));
\r
115 output_ = decklink_;
\r
116 keyer_ = decklink_;
\r
119 decklink_->GetModelName(&pModelName);
\r
120 model_name_ = std::wstring(pModelName);
\r
122 graph_ = diagnostics::create_graph(narrow(print()));
\r
123 graph_->add_guide("tick-time", 0.5);
\r
124 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));
\r
126 auto display_mode = get_display_mode(output_.p, format_desc_.format);
\r
127 if(display_mode == nullptr)
\r
128 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));
\r
130 display_mode->GetFrameRate(&frame_duration_, &frame_time_scale_);
\r
132 BMDDisplayModeSupport displayModeSupport;
\r
133 if(FAILED(output_->DoesSupportVideoMode(display_mode->GetDisplayMode(), bmdFormat8BitBGRA, bmdVideoOutputFlagDefault, &displayModeSupport, nullptr)))
\r
134 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));
\r
138 if(FAILED(output_->EnableAudioOutput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2, bmdAudioOutputStreamTimestamped)))
\r
139 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable audio output."));
\r
141 if(FAILED(output_->SetAudioCallback(this)))
\r
142 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not set audio callback."));
\r
144 CASPAR_LOG(info) << print() << L" Enabled embedded-audio.";
\r
147 if(FAILED(output_->EnableVideoOutput(display_mode->GetDisplayMode(), bmdVideoOutputFlagDefault)))
\r
148 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable video output."));
\r
150 if(FAILED(output_->SetScheduledFrameCompletionCallback(this)))
\r
151 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to set playback completion callback."));
\r
155 if(FAILED(keyer_->Enable(FALSE)))
\r
156 CASPAR_LOG(error) << print() << L" Failed to enable internal keyer.";
\r
157 else if(FAILED(keyer_->SetLevel(255)))
\r
158 CASPAR_LOG(error) << print() << L" Failed to set key-level to max.";
\r
160 CASPAR_LOG(info) << print() << L" Successfully configured internal keyer.";
\r
164 if(FAILED(keyer_->Enable(TRUE)))
\r
165 CASPAR_LOG(error) << print() << L" Failed to enable external keyer.";
\r
167 CASPAR_LOG(info) << print() << L" Successfully configured external keyer.";
\r
170 for(size_t n = 0; n < reserved_frames_.size(); ++n)
\r
172 if(FAILED(output_->CreateVideoFrame(format_desc_.width, format_desc_.height, format_desc_.size/format_desc_.height, bmdFormat8BitBGRA, bmdFrameFlagDefault, &reserved_frames_[n].second)))
\r
173 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to create frame."));
\r
175 if(FAILED(reserved_frames_[n].second->GetBytes(&reserved_frames_[n].first)))
\r
176 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to get frame bytes."));
\r
179 auto buffer_size = static_cast<size_t>(frame_time_scale_/frame_duration_)/4;
\r
180 for(size_t n = 0; n < buffer_size; ++n)
\r
181 schedule_next_video(core::read_frame::empty());
\r
183 video_frame_buffer_.set_capacity(buffer_size);
\r
184 audio_frame_buffer_.set_capacity(buffer_size);
\r
185 for(size_t n = 0; n < std::max<size_t>(2, buffer_size-2); ++n)
\r
187 video_frame_buffer_.try_push(core::read_frame::empty());
\r
189 audio_frame_buffer_.try_push(core::read_frame::empty());
\r
192 if(FAILED(output_->StartScheduledPlayback(0, frame_time_scale_, 1.0)))
\r
193 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to schedule playback."));
\r
195 CASPAR_LOG(info) << print() << L" Successfully initialized for " << format_desc_.name;
\r
200 is_running_ = false;
\r
201 video_frame_buffer_.try_push(core::read_frame::empty());
\r
202 audio_frame_buffer_.try_push(core::read_frame::empty());
\r
204 if(output_ != nullptr)
\r
206 output_->StopScheduledPlayback(0, nullptr, 0);
\r
208 output_->DisableAudioOutput();
\r
209 output_->DisableVideoOutput();
\r
211 CASPAR_LOG(info) << print() << L" Shutting down.";
\r
214 virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID, LPVOID*) {return E_NOINTERFACE;}
\r
215 virtual ULONG STDMETHODCALLTYPE AddRef () {return 1;}
\r
216 virtual ULONG STDMETHODCALLTYPE Release () {return 1;}
\r
218 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted (IDeckLinkVideoFrame* /*completedFrame*/, BMDOutputFrameCompletionResult /*result*/)
\r
223 std::shared_ptr<const core::read_frame> frame;
\r
224 video_frame_buffer_.pop(frame);
\r
225 schedule_next_video(safe_ptr<const core::read_frame>(frame));
\r
230 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped (void)
\r
235 virtual HRESULT STDMETHODCALLTYPE RenderAudioSamples (BOOL /*preroll*/)
\r
240 std::shared_ptr<const core::read_frame> frame;
\r
241 audio_frame_buffer_.pop(frame);
\r
242 schedule_next_audio(safe_ptr<const core::read_frame>(frame));
\r
247 void schedule_next_audio(const safe_ptr<const core::read_frame>& frame)
\r
249 static std::vector<short> silence(48000, 0);
\r
251 int audio_samples = static_cast<size_t>(48000.0 / format_desc_.fps);
\r
253 auto frame_audio_data = frame->audio_data().empty() ? silence.data() : const_cast<short*>(frame->audio_data().begin());
\r
255 audio_container_.push_back(std::vector<short>(frame_audio_data, frame_audio_data+audio_samples*2));
\r
257 if(FAILED(output_->ScheduleAudioSamples(audio_container_.back().data(), audio_samples, (audio_scheduled_++) * audio_samples, 48000, nullptr)))
\r
258 CASPAR_LOG(error) << print() << L" Failed to schedule audio.";
\r
261 void schedule_next_video(const safe_ptr<const core::read_frame>& frame)
\r
263 if(!frame->image_data().empty())
\r
264 std::copy(frame->image_data().begin(), frame->image_data().end(), static_cast<char*>(reserved_frames_.front().first));
\r
266 std::fill_n(static_cast<int*>(reserved_frames_.front().first), 0, format_desc_.size/4);
\r
268 if(FAILED(output_->ScheduleVideoFrame(reserved_frames_.front().second, (frames_scheduled_++) * frame_duration_, frame_duration_, frame_time_scale_)))
\r
269 CASPAR_LOG(error) << print() << L" Failed to schedule video.";
\r
271 std::rotate(reserved_frames_.begin(), reserved_frames_.begin() + 1, reserved_frames_.end());
\r
272 graph_->update_value("tick-time", static_cast<float>(perf_timer_.elapsed()/format_desc_.interval*0.5));
\r
273 perf_timer_.restart();
\r
276 void send(const safe_ptr<const core::read_frame>& frame)
\r
278 video_frame_buffer_.push(frame);
\r
280 audio_frame_buffer_.push(frame);
\r
283 std::wstring print() const
\r
285 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";
\r
289 struct decklink_consumer::implementation
\r
291 std::unique_ptr<decklink_output> output_;
\r
292 size_t device_index_;
\r
294 bool internal_key_;
\r
296 executor executor_;
\r
299 implementation(size_t device_index, bool embed_audio, bool internal_key)
\r
300 : device_index_(device_index)
\r
301 , embed_audio_(embed_audio)
\r
302 , internal_key_(internal_key)
\r
303 , executor_(L"DECKLINK[" + boost::lexical_cast<std::wstring>(device_index) + L"]"){}
\r
307 executor_.invoke([&]
\r
313 void initialize(const core::video_format_desc& format_desc)
\r
315 executor_.invoke([&]
\r
317 output_.reset(new decklink_output(format_desc, device_index_, embed_audio_, internal_key_));
\r
321 void send(const safe_ptr<const core::read_frame>& frame)
\r
323 output_->send(frame);
\r
326 size_t buffer_depth() const
\r
331 std::wstring print() const
\r
333 return output_->print();
\r
337 decklink_consumer::decklink_consumer(size_t device_index, bool embed_audio, bool internalKey) : impl_(new implementation(device_index, embed_audio, internalKey)){}
\r
338 decklink_consumer::decklink_consumer(decklink_consumer&& other) : impl_(std::move(other.impl_)){}
\r
339 void decklink_consumer::initialize(const core::video_format_desc& format_desc){impl_->initialize(format_desc);}
\r
340 void decklink_consumer::send(const safe_ptr<const core::read_frame>& frame){impl_->send(frame);}
\r
341 size_t decklink_consumer::buffer_depth() const{return impl_->buffer_depth();}
\r
342 std::wstring decklink_consumer::print() const{return impl_->print();}
\r
344 safe_ptr<core::frame_consumer> create_decklink_consumer(const std::vector<std::wstring>& params)
\r
346 if(params.size() < 1 || params[0] != L"DECKLINK")
\r
347 return core::frame_consumer::empty();
\r
349 int device_index = 1;
\r
350 bool embed_audio = false;
\r
351 bool internal_key = false;
\r
353 if(params.size() > 1)
\r
354 device_index = lexical_cast_or_default<int>(params[2], device_index);
\r
356 if(params.size() > 2)
\r
357 embed_audio = lexical_cast_or_default<bool>(params[3], embed_audio);
\r
359 if(params.size() > 3)
\r
360 internal_key = lexical_cast_or_default<bool>(params[4], internal_key);
\r
362 return make_safe<decklink_consumer>(device_index, embed_audio, internal_key);
\r