]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
2.0.0.2: Decoupled mixer project.
[casparcg] / modules / decklink / producer / decklink_producer.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_producer.h"\r
24 \r
25 #include "../interop/DeckLinkAPI_h.h" // TODO: Change this\r
26 #include "../util/util.h" // TODO: Change this\r
27 \r
28 #include <common/diagnostics/graph.h>\r
29 #include <common/concurrency/executor.h>\r
30 #include <common/exception/exceptions.h>\r
31 #include <common/utility/timer.h>\r
32 \r
33 #include <core/producer/frame/write_frame.h>\r
34 \r
35 #include <tbb/concurrent_queue.h>\r
36 #include <tbb/atomic.h>\r
37 \r
38 #include <boost/algorithm/string.hpp>\r
39 \r
40 #pragma warning(push)\r
41 #pragma warning(disable : 4996)\r
42 \r
43         #include <atlbase.h>\r
44 \r
45         #include <atlcom.h>\r
46         #include <atlhost.h>\r
47 \r
48 #pragma warning(push)\r
49 \r
50 #include <functional>\r
51 \r
52 namespace caspar { \r
53 \r
54 class decklink_input : public IDeckLinkInputCallback\r
55 {\r
56         struct co_init\r
57         {\r
58                 co_init(){CoInitialize(nullptr);}\r
59                 ~co_init(){CoUninitialize();}\r
60         } co_;\r
61 \r
62         printer parent_printer_;\r
63         const core::video_format_desc format_desc_;\r
64         std::wstring model_name_;\r
65         const size_t device_index_;\r
66 \r
67         std::shared_ptr<diagnostics::graph> graph_;\r
68         timer perf_timer_;\r
69 \r
70         CComPtr<IDeckLink>                      decklink_;\r
71         CComQIPtr<IDeckLinkInput>       input_;\r
72         IDeckLinkDisplayMode*           d_mode_;\r
73 \r
74         std::vector<short>                      audio_data_;\r
75 \r
76         std::shared_ptr<core::frame_factory> frame_factory_;\r
77 \r
78         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>> frame_buffer_;\r
79         safe_ptr<core::basic_frame> tail_;\r
80 \r
81 public:\r
82 \r
83         decklink_input(const core::video_format_desc& format_desc, size_t device_index, const std::shared_ptr<core::frame_factory>& frame_factory, const printer& parent_printer)\r
84                 : parent_printer_(parent_printer)\r
85                 , format_desc_(format_desc)\r
86                 , device_index_(device_index)\r
87                 , model_name_(L"DECKLINK")\r
88                 , frame_factory_(frame_factory)\r
89                 , tail_(core::basic_frame::empty())\r
90         {\r
91                 frame_buffer_.set_capacity(4);\r
92                 \r
93                 CComPtr<IDeckLinkIterator> pDecklinkIterator;\r
94                 if(FAILED(pDecklinkIterator.CoCreateInstance(CLSID_CDeckLinkIterator)))\r
95                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " No Decklink drivers installed."));\r
96 \r
97                 size_t n = 0;\r
98                 while(n < device_index_ && pDecklinkIterator->Next(&decklink_) == S_OK){++n;}   \r
99 \r
100                 if(n != device_index_ || !decklink_)\r
101                         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
102 \r
103                 input_ = decklink_;\r
104 \r
105                 BSTR pModelName;\r
106                 decklink_->GetModelName(&pModelName);\r
107                 model_name_ = std::wstring(pModelName);\r
108 \r
109                 graph_ = diagnostics::create_graph(boost::bind(&decklink_input::print, this));\r
110                 graph_->add_guide("tick-time", 0.5);\r
111                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
112                 \r
113                 unsigned long decklinkVideoFormat = GetDecklinkVideoFormat(format_desc.format);\r
114                 if(decklinkVideoFormat == ULONG_MAX) \r
115                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
116 \r
117                 d_mode_ = get_display_mode((BMDDisplayMode)decklinkVideoFormat);\r
118                 if(d_mode_ == nullptr) \r
119                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
120 \r
121                 BMDDisplayModeSupport displayModeSupport;\r
122                 if(FAILED(input_->DoesSupportVideoMode((BMDDisplayMode)decklinkVideoFormat, bmdFormat8BitYUV, bmdVideoOutputFlagDefault, &displayModeSupport, nullptr)))\r
123                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
124 \r
125                 // NOTE: bmdFormat8BitARGB does not seem to work with Decklink HD Extreme 3D\r
126                 if(FAILED(input_->EnableVideoInput((BMDDisplayMode)decklinkVideoFormat, bmdFormat8BitYUV, 0))) \r
127                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable video input."));\r
128 \r
129                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
130                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable audio input."));\r
131                         \r
132                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
133                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to set input callback."));\r
134                         \r
135                 if(FAILED(input_->StartStreams()))\r
136                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start input stream."));\r
137 \r
138                 CASPAR_LOG(info) << print() << " successfully initialized decklink for " << format_desc_.name;\r
139         }\r
140 \r
141         ~decklink_input()\r
142         {\r
143                 if(input_ != nullptr) \r
144                 {\r
145                         input_->StopStreams();\r
146                         input_->DisableVideoInput();\r
147                 }\r
148         }\r
149 \r
150         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
151         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
152         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
153                 \r
154         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
155         {\r
156                 d_mode_ = newDisplayMode;\r
157                 return S_OK;\r
158         }\r
159 \r
160         // TODO: Enable audio input\r
161         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
162         {       \r
163                 graph_->update_value("tick-time", static_cast<float>(perf_timer_.elapsed()/format_desc_.interval*0.5));\r
164                 perf_timer_.reset();\r
165 \r
166                 if(!video)\r
167                         return S_OK;            \r
168                                 \r
169                 void* bytes = nullptr;\r
170                 if(FAILED(video->GetBytes(&bytes)))\r
171                         return S_OK;\r
172 \r
173                 core::pixel_format_desc desc;\r
174                 desc.pix_fmt = core::pixel_format::ycbcr;\r
175                 desc.planes.push_back(core::pixel_format_desc::plane(d_mode_->GetWidth(),   d_mode_->GetHeight(), 1));\r
176                 desc.planes.push_back(core::pixel_format_desc::plane(d_mode_->GetWidth()/2, d_mode_->GetHeight(), 1));\r
177                 desc.planes.push_back(core::pixel_format_desc::plane(d_mode_->GetWidth()/2, d_mode_->GetHeight(), 1));                  \r
178                 auto frame = frame_factory_->create_frame(desc);\r
179 \r
180                 unsigned char* data = reinterpret_cast<unsigned char*>(bytes);\r
181                 int frame_size = (d_mode_->GetWidth() * 16 / 8) * d_mode_->GetHeight();\r
182 \r
183                 // Convert to planar YUV422\r
184                 unsigned char* y  = frame->image_data(0).begin();\r
185                 unsigned char* cb = frame->image_data(1).begin();\r
186                 unsigned char* cr = frame->image_data(2).begin();\r
187                 \r
188                 tbb::parallel_for(tbb::blocked_range<size_t>(0, frame_size/4), [&](const tbb::blocked_range<size_t>& r)\r
189                 {\r
190                         for(auto n = r.begin(); n != r.end(); ++n)\r
191                         {\r
192                                 cb[n]     = data[n*4+0];\r
193                                 y [n*2+0] = data[n*4+1];\r
194                                 cr[n]     = data[n*4+2];\r
195                                 y [n*2+1] = data[n*4+3];\r
196                         }\r
197                 });\r
198 \r
199                 if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
200                 {\r
201                         auto sample_frame_count = audio->GetSampleFrameCount();\r
202                         auto audio_data = reinterpret_cast<short*>(bytes);\r
203                         audio_data_.insert(audio_data_.end(), audio_data, audio_data + sample_frame_count*2);\r
204 \r
205                         if(audio_data_.size() > 3840)\r
206                         {\r
207                                 frame->audio_data() = std::vector<short>(audio_data_.begin(), audio_data_.begin() + 3840);\r
208                                 audio_data_.erase(audio_data_.begin(), audio_data_.begin() + 3840);\r
209                                 frame_buffer_.try_push(frame);\r
210                         }\r
211                 }\r
212                 else\r
213                         frame_buffer_.try_push(frame);\r
214 \r
215                 return S_OK;\r
216         }\r
217 \r
218         IDeckLinkDisplayMode* get_display_mode(BMDDisplayMode mode)\r
219         {       \r
220                 CComPtr<IDeckLinkDisplayModeIterator>   iterator;\r
221                 IDeckLinkDisplayMode*                                   d_mode;\r
222         \r
223                 if (input_->GetDisplayModeIterator(&iterator) != S_OK)\r
224                         return nullptr;\r
225 \r
226                 while (iterator->Next(&d_mode) == S_OK)\r
227                 {\r
228                         if(d_mode->GetDisplayMode() == mode)\r
229                                 return d_mode;\r
230                 }\r
231                 return nullptr;\r
232         }\r
233 \r
234         safe_ptr<core::basic_frame> get_frame()\r
235         {\r
236                 frame_buffer_.try_pop(tail_);\r
237                 return tail_;\r
238         }\r
239 \r
240         std::wstring print() const\r
241         {\r
242                 return (parent_printer_ ? parent_printer_() + L"/" : L"") + L" [" + model_name_ + L"device:" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
243         }\r
244 };\r
245         \r
246 class decklink_producer : public core::frame_producer\r
247 {       \r
248         const size_t device_index_;\r
249         printer parent_printer_;\r
250 \r
251         std::unique_ptr<decklink_input> input_;\r
252         \r
253         const core::video_format_desc format_desc_;\r
254         \r
255         executor executor_;\r
256 public:\r
257 \r
258         explicit decklink_producer(const core::video_format_desc& format_desc, size_t device_index)\r
259                 : format_desc_(format_desc) \r
260                 , device_index_(device_index){}\r
261 \r
262         ~decklink_producer()\r
263         {       \r
264                 executor_.invoke([this]\r
265                 {\r
266                         input_ = nullptr;\r
267                 });\r
268         }\r
269 \r
270         virtual void initialize(const safe_ptr<core::frame_factory>& frame_factory)\r
271         {\r
272                 executor_.start();\r
273                 executor_.invoke([=]\r
274                 {\r
275                         input_.reset(new decklink_input(format_desc_, device_index_, frame_factory, parent_printer_));\r
276                 });\r
277         }\r
278 \r
279         virtual void set_parent_printer(const printer& parent_printer) { parent_printer_ = parent_printer;}\r
280         \r
281         virtual safe_ptr<core::basic_frame> receive()\r
282         {\r
283                 return input_->get_frame();\r
284         }\r
285         \r
286         std::wstring print() const\r
287         {\r
288                 return  (parent_printer_ ? parent_printer_() + L"/" : L"") + (input_ ? input_->print() : L"Unknown Decklink [input-" + boost::lexical_cast<std::wstring>(device_index_) + L"]");\r
289         }\r
290 };\r
291 \r
292 safe_ptr<core::frame_producer> create_decklink_producer(const std::vector<std::wstring>& params)\r
293 {\r
294         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
295                 return core::frame_producer::empty();\r
296 \r
297         size_t device_index = 1;\r
298         if(params.size() > 1)\r
299         {\r
300                 try{device_index = boost::lexical_cast<int>(params[1]);}\r
301                 catch(boost::bad_lexical_cast&){}\r
302         }\r
303 \r
304         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
305         if(params.size() > 2)\r
306         {\r
307                 format_desc = core::video_format_desc::get(params[2]);\r
308                 format_desc = format_desc.format != core::video_format::invalid ? format_desc : core::video_format_desc::get(L"PAL");\r
309         }\r
310 \r
311         return make_safe<decklink_producer>(format_desc, device_index);\r
312 }\r
313 \r
314 }