]> git.sesse.net Git - casparcg/blob - modules/decklink/consumer/decklink_consumer.cpp
2.0.0.2: Misc typos.
[casparcg] / modules / decklink / consumer / decklink_consumer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\r
5 *\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
10 *\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
15 \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
18 *\r
19 */\r
20 \r
21 #include "../StdAfx.h"\r
22  \r
23 #include "decklink_consumer.h"\r
24 \r
25 #include "../util/util.h"\r
26 \r
27 #include "../interop/DeckLinkAPI_h.h"\r
28 \r
29 #include <core/video_format.h>\r
30 \r
31 #include <core/consumer/frame/read_frame.h>\r
32 \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
37 \r
38 #include <tbb/concurrent_queue.h>\r
39 \r
40 #include <boost/circular_buffer.hpp>\r
41 \r
42 #include <array>\r
43 \r
44 #pragma warning(push)\r
45 #pragma warning(disable : 4996)\r
46 \r
47         #include <atlbase.h>\r
48 \r
49         #include <atlcom.h>\r
50         #include <atlhost.h>\r
51 \r
52 #pragma warning(push)\r
53 \r
54 namespace caspar { \r
55         \r
56 struct decklink_output : public IDeckLinkVideoOutputCallback, public IDeckLinkAudioOutputCallback, boost::noncopyable\r
57 {               \r
58         struct co_init\r
59         {\r
60                 co_init(){CoInitialize(nullptr);}\r
61                 ~co_init(){CoUninitialize();}\r
62         } co_;\r
63         \r
64         std::wstring    model_name_;\r
65         const size_t    device_index_;\r
66         tbb::atomic<bool> is_running_;\r
67 \r
68         std::shared_ptr<diagnostics::graph> graph_;\r
69         timer perf_timer_;\r
70 \r
71         std::array<std::pair<void*, CComPtr<IDeckLinkMutableVideoFrame>>, 3> reserved_frames_;\r
72         boost::circular_buffer<std::vector<short>> audio_container_;\r
73         \r
74         const bool              embed_audio_;\r
75         const bool              internal_key;\r
76 \r
77         CComPtr<IDeckLink>                      decklink_;\r
78         CComQIPtr<IDeckLinkOutput>      output_;\r
79         CComQIPtr<IDeckLinkKeyer>       keyer_;\r
80         \r
81         core::video_format_desc format_desc_;\r
82 \r
83         BMDTimeScale frame_time_scale_;\r
84         BMDTimeValue frame_duration_;\r
85         unsigned long frames_scheduled_;\r
86         unsigned long audio_scheduled_;\r
87         \r
88         tbb::concurrent_bounded_queue<std::shared_ptr<const core::read_frame>> video_frame_buffer_;\r
89         tbb::concurrent_bounded_queue<std::shared_ptr<const core::read_frame>> audio_frame_buffer_;\r
90 \r
91 public:\r
92         decklink_output(const core::video_format_desc& format_desc,size_t device_index, bool embed_audio, bool internalKey) \r
93                 :  model_name_(L"DECKLINK")\r
94                 , device_index_(device_index)\r
95                 , audio_container_(5)\r
96                 , embed_audio_(embed_audio)\r
97                 , internal_key(internalKey)\r
98                 , frames_scheduled_(0)\r
99                 , audio_scheduled_(0)\r
100                 , format_desc_(format_desc)\r
101         {\r
102                 is_running_ = true;\r
103                 format_desc_ = format_desc;\r
104                 CComPtr<IDeckLinkIterator> pDecklinkIterator;\r
105                 if(FAILED(pDecklinkIterator.CoCreateInstance(CLSID_CDeckLinkIterator)))\r
106                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " No Decklink drivers installed."));\r
107                 \r
108                 size_t n = 0;\r
109                 while(n < device_index_ && pDecklinkIterator->Next(&decklink_) == S_OK){++n;}   \r
110 \r
111                 if(n != device_index_ || !decklink_)\r
112                         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
113 \r
114                 output_ = decklink_;\r
115                 keyer_ = decklink_;\r
116 \r
117                 BSTR pModelName;\r
118                 decklink_->GetModelName(&pModelName);\r
119                 model_name_ = std::wstring(pModelName);\r
120                                 \r
121                 graph_ = diagnostics::create_graph(narrow(print()));\r
122                 graph_->add_guide("tick-time", 0.5);\r
123                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
124                 \r
125                 auto display_mode = get_display_mode(output_.p, format_desc_.format);\r
126                 if(display_mode == nullptr) \r
127                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
128                 \r
129                 display_mode->GetFrameRate(&frame_duration_, &frame_time_scale_);\r
130 \r
131                 BMDDisplayModeSupport displayModeSupport;\r
132                 if(FAILED(output_->DoesSupportVideoMode(display_mode->GetDisplayMode(), bmdFormat8BitBGRA, bmdVideoOutputFlagDefault, &displayModeSupport, nullptr)))\r
133                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
134                 \r
135                 if(embed_audio_)\r
136                 {\r
137                         if(FAILED(output_->EnableAudioOutput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2, bmdAudioOutputStreamTimestamped)))\r
138                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable audio output."));\r
139                                 \r
140                         if(FAILED(output_->SetAudioCallback(this)))\r
141                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not set audio callback."));\r
142 \r
143                         CASPAR_LOG(info) << print() << L" Enabled embedded-audio.";\r
144                 }\r
145 \r
146                 if(FAILED(output_->EnableVideoOutput(display_mode->GetDisplayMode(), bmdVideoOutputFlagDefault))) \r
147                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable video output."));\r
148 \r
149                 if(FAILED(output_->SetScheduledFrameCompletionCallback(this)))\r
150                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to set playback completion callback."));\r
151                         \r
152                 if(internal_key) \r
153                 {\r
154                         if(FAILED(keyer_->Enable(FALSE)))                       \r
155                                 CASPAR_LOG(error) << print() << L" Failed to enable internal keyer.";                   \r
156                         else if(FAILED(keyer_->SetLevel(255)))                  \r
157                                 CASPAR_LOG(error) << print() << L" Failed to set key-level to max.";\r
158                         else\r
159                                 CASPAR_LOG(info) << print() << L" Successfully configured internal keyer.";             \r
160                 }\r
161                 else\r
162                 {\r
163                         if(FAILED(keyer_->Enable(TRUE)))                        \r
164                                 CASPAR_LOG(error) << print() << L" Failed to enable external keyer.";   \r
165                         else\r
166                                 CASPAR_LOG(info) << print() << L" Successfully configured external keyer.";                     \r
167                 }\r
168                 \r
169                 for(size_t n = 0; n < reserved_frames_.size(); ++n)\r
170                 {\r
171                         if(FAILED(output_->CreateVideoFrame(format_desc_.width, format_desc_.height, format_desc_.size/format_desc_.height, bmdFormat8BitBGRA, bmdFrameFlagDefault, &reserved_frames_[n].second)))\r
172                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to create frame."));\r
173 \r
174                         if(FAILED(reserved_frames_[n].second->GetBytes(&reserved_frames_[n].first)))\r
175                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to get frame bytes."));\r
176                 }\r
177                                         \r
178                 auto buffer_size = static_cast<size_t>(frame_time_scale_/frame_duration_)/4;\r
179                 for(size_t n = 0; n < buffer_size; ++n)\r
180                         schedule_next_video(core::read_frame::empty());\r
181 \r
182                 video_frame_buffer_.set_capacity(buffer_size);\r
183                 audio_frame_buffer_.set_capacity(buffer_size);\r
184                 for(size_t n = 0; n < std::max<size_t>(2, buffer_size-2); ++n)\r
185                 {\r
186                         video_frame_buffer_.try_push(core::read_frame::empty());\r
187                         if(embed_audio_)\r
188                                 audio_frame_buffer_.try_push(core::read_frame::empty());\r
189                 }\r
190                 \r
191                 if(FAILED(output_->StartScheduledPlayback(0, frame_time_scale_, 1.0))) \r
192                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to schedule playback."));\r
193                 \r
194                 CASPAR_LOG(info) << print() << L" Successfully initialized for " << format_desc_.name;  \r
195         }\r
196 \r
197         ~decklink_output()\r
198         {               \r
199                 is_running_ = false;\r
200                 video_frame_buffer_.try_push(core::read_frame::empty());\r
201                 audio_frame_buffer_.try_push(core::read_frame::empty());\r
202 \r
203                 if(output_ != nullptr) \r
204                 {\r
205                         output_->StopScheduledPlayback(0, nullptr, 0);\r
206                         if(embed_audio_)\r
207                                 output_->DisableAudioOutput();\r
208                         output_->DisableVideoOutput();\r
209                 }\r
210                 CASPAR_LOG(info) << print() << L" Shutting down.";      \r
211         }\r
212                         \r
213         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
214         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
215         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
216         \r
217         virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted (IDeckLinkVideoFrame* /*completedFrame*/, BMDOutputFrameCompletionResult /*result*/)\r
218         {\r
219                 if(!is_running_)\r
220                         return S_OK;\r
221 \r
222                 std::shared_ptr<const core::read_frame> frame;  \r
223                 video_frame_buffer_.pop(frame);         \r
224                 schedule_next_video(safe_ptr<const core::read_frame>(frame));\r
225 \r
226                 return S_OK;\r
227         }\r
228 \r
229         virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped (void)\r
230         {\r
231                 return S_OK;\r
232         }\r
233                 \r
234         virtual HRESULT STDMETHODCALLTYPE RenderAudioSamples (BOOL /*preroll*/)\r
235         {\r
236                 if(!is_running_)\r
237                         return S_OK;\r
238 \r
239                 std::shared_ptr<const core::read_frame> frame;\r
240                 audio_frame_buffer_.pop(frame);\r
241                 schedule_next_audio(safe_ptr<const core::read_frame>(frame));\r
242 \r
243                 return S_OK;\r
244         }\r
245 \r
246         void schedule_next_audio(const safe_ptr<const core::read_frame>& frame)\r
247         {\r
248                 static std::vector<short> silence(48000, 0);\r
249 \r
250                 int audio_samples = static_cast<size_t>(48000.0 / format_desc_.fps);\r
251 \r
252                 auto frame_audio_data = frame->audio_data().empty() ? silence.data() : const_cast<short*>(frame->audio_data().begin());\r
253 \r
254                 audio_container_.push_back(std::vector<short>(frame_audio_data, frame_audio_data+audio_samples*2));\r
255 \r
256                 if(FAILED(output_->ScheduleAudioSamples(audio_container_.back().data(), audio_samples, (audio_scheduled_++) * audio_samples, 48000, nullptr)))\r
257                         CASPAR_LOG(error) << print() << L" Failed to schedule audio.";\r
258         }\r
259                         \r
260         void schedule_next_video(const safe_ptr<const core::read_frame>& frame)\r
261         {\r
262                 if(!frame->image_data().empty())\r
263                         std::copy(frame->image_data().begin(), frame->image_data().end(), static_cast<char*>(reserved_frames_.front().first));\r
264                 else\r
265                         std::fill_n(static_cast<int*>(reserved_frames_.front().first), 0, format_desc_.size/4);\r
266 \r
267                 if(FAILED(output_->ScheduleVideoFrame(reserved_frames_.front().second, (frames_scheduled_++) * frame_duration_, frame_duration_, frame_time_scale_)))\r
268                         CASPAR_LOG(error) << print() << L" Failed to schedule video.";\r
269 \r
270                 std::rotate(reserved_frames_.begin(), reserved_frames_.begin() + 1, reserved_frames_.end());\r
271                 graph_->update_value("tick-time", static_cast<float>(perf_timer_.elapsed()/format_desc_.interval*0.5));\r
272                 perf_timer_.reset();\r
273         }\r
274 \r
275         void send(const safe_ptr<const core::read_frame>& frame)\r
276         {\r
277                 video_frame_buffer_.push(frame);\r
278                 if(embed_audio_)\r
279                         audio_frame_buffer_.push(frame);\r
280         }\r
281 \r
282         std::wstring print() const\r
283         {\r
284                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
285         }\r
286 };\r
287 \r
288 struct decklink_consumer::implementation\r
289 {\r
290         std::unique_ptr<decklink_output> input_;\r
291         size_t device_index_;\r
292         bool embed_audio_;\r
293         bool internal_key_;\r
294 \r
295         executor executor_;\r
296 public:\r
297 \r
298         implementation(size_t device_index, bool embed_audio, bool internal_key)\r
299                 : device_index_(device_index)\r
300                 , embed_audio_(embed_audio)\r
301                 , internal_key_(internal_key)\r
302                 , executor_(L"DECKLINK[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
303         {\r
304                 executor_.start();\r
305         }\r
306 \r
307         ~implementation()\r
308         {\r
309                 executor_.invoke([&]\r
310                 {\r
311                         input_ = nullptr;\r
312                 });\r
313         }\r
314 \r
315         void initialize(const core::video_format_desc& format_desc)\r
316         {\r
317                 executor_.invoke([&]\r
318                 {\r
319                         input_.reset(new decklink_output(format_desc, device_index_, embed_audio_, internal_key_));\r
320                 });\r
321         }\r
322         \r
323         void send(const safe_ptr<const core::read_frame>& frame)\r
324         {\r
325                 input_->send(frame);\r
326         }\r
327 \r
328         size_t buffer_depth() const\r
329         {\r
330                 return 1;\r
331         }\r
332 \r
333         std::wstring print() const\r
334         {\r
335                 return input_->print();\r
336         }\r
337 };\r
338 \r
339 decklink_consumer::decklink_consumer(size_t device_index, bool embed_audio, bool internalKey) : impl_(new implementation(device_index, embed_audio, internalKey)){}\r
340 decklink_consumer::decklink_consumer(decklink_consumer&& other) : impl_(std::move(other.impl_)){}\r
341 void decklink_consumer::initialize(const core::video_format_desc& format_desc){impl_->initialize(format_desc);}\r
342 void decklink_consumer::send(const safe_ptr<const core::read_frame>& frame){impl_->send(frame);}\r
343 size_t decklink_consumer::buffer_depth() const{return impl_->buffer_depth();}\r
344 std::wstring decklink_consumer::print() const{return impl_->print();}\r
345         \r
346 safe_ptr<core::frame_consumer> create_decklink_consumer(const std::vector<std::wstring>& params)\r
347 {\r
348         if(params.size() < 1 || params[0] != L"DECKLINK")\r
349                 return core::frame_consumer::empty();\r
350         \r
351         int device_index = 1;\r
352         bool embed_audio = false;\r
353         bool internal_key = false;\r
354 \r
355         if(params.size() > 1) \r
356                 device_index = lexical_cast_or_default<int>(params[2], device_index);\r
357 \r
358         if(params.size() > 2)\r
359                 embed_audio = lexical_cast_or_default<bool>(params[3], embed_audio);\r
360         \r
361         if(params.size() > 3) \r
362                 internal_key = lexical_cast_or_default<bool>(params[4], internal_key);\r
363 \r
364         return make_safe<decklink_consumer>(device_index, embed_audio, internal_key);\r
365 }\r
366 \r
367 }