]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
2.0.0.2: Increased warning level.
[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         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
83                 : parent_printer_(parent_printer)\r
84                 , format_desc_(format_desc)\r
85                 , device_index_(device_index)\r
86                 , model_name_(L"DECKLINK")\r
87                 , frame_factory_(frame_factory)\r
88                 , tail_(core::basic_frame::empty())\r
89         {\r
90                 frame_buffer_.set_capacity(4);\r
91                 \r
92                 CComPtr<IDeckLinkIterator> pDecklinkIterator;\r
93                 if(FAILED(pDecklinkIterator.CoCreateInstance(CLSID_CDeckLinkIterator)))\r
94                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " No Decklink drivers installed."));\r
95 \r
96                 size_t n = 0;\r
97                 while(n < device_index_ && pDecklinkIterator->Next(&decklink_) == S_OK){++n;}   \r
98 \r
99                 if(n != device_index_ || !decklink_)\r
100                         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
101 \r
102                 input_ = decklink_;\r
103 \r
104                 BSTR pModelName;\r
105                 decklink_->GetModelName(&pModelName);\r
106                 model_name_ = std::wstring(pModelName);\r
107 \r
108                 graph_ = diagnostics::create_graph(boost::bind(&decklink_input::print, this));\r
109                 graph_->add_guide("tick-time", 0.5);\r
110                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
111                 \r
112                 unsigned long decklinkVideoFormat = GetDecklinkVideoFormat(format_desc.format);\r
113                 if(decklinkVideoFormat == ULONG_MAX) \r
114                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
115 \r
116                 d_mode_ = get_display_mode((BMDDisplayMode)decklinkVideoFormat);\r
117                 if(d_mode_ == nullptr) \r
118                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
119 \r
120                 BMDDisplayModeSupport displayModeSupport;\r
121                 if(FAILED(input_->DoesSupportVideoMode((BMDDisplayMode)decklinkVideoFormat, bmdFormat8BitYUV, bmdVideoOutputFlagDefault, &displayModeSupport, nullptr)))\r
122                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
123 \r
124                 // NOTE: bmdFormat8BitARGB does not seem to work with Decklink HD Extreme 3D\r
125                 if(FAILED(input_->EnableVideoInput((BMDDisplayMode)decklinkVideoFormat, bmdFormat8BitYUV, 0))) \r
126                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable video input."));\r
127 \r
128                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
129                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable audio input."));\r
130                         \r
131                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
132                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to set input callback."));\r
133                         \r
134                 if(FAILED(input_->StartStreams()))\r
135                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start input stream."));\r
136 \r
137                 CASPAR_LOG(info) << print() << " successfully initialized decklink for " << format_desc_.name;\r
138         }\r
139 \r
140         ~decklink_input()\r
141         {\r
142                 if(input_ != nullptr) \r
143                 {\r
144                         input_->StopStreams();\r
145                         input_->DisableVideoInput();\r
146                 }\r
147         }\r
148 \r
149         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
150         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
151         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
152                 \r
153         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
154         {\r
155                 d_mode_ = newDisplayMode;\r
156                 return S_OK;\r
157         }\r
158 \r
159         // TODO: Enable audio input\r
160         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
161         {       \r
162                 graph_->update_value("tick-time", static_cast<float>(perf_timer_.elapsed()/format_desc_.interval*0.5));\r
163                 perf_timer_.reset();\r
164 \r
165                 if(!video)\r
166                         return S_OK;            \r
167                                 \r
168                 void* bytes = nullptr;\r
169                 if(FAILED(video->GetBytes(&bytes)))\r
170                         return S_OK;\r
171 \r
172                 core::pixel_format_desc desc;\r
173                 desc.pix_fmt = core::pixel_format::ycbcr;\r
174                 desc.planes.push_back(core::pixel_format_desc::plane(d_mode_->GetWidth(),   d_mode_->GetHeight(), 1));\r
175                 desc.planes.push_back(core::pixel_format_desc::plane(d_mode_->GetWidth()/2, 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                 auto frame = frame_factory_->create_frame(desc);\r
178 \r
179                 unsigned char* data = reinterpret_cast<unsigned char*>(bytes);\r
180                 int frame_size = (d_mode_->GetWidth() * 16 / 8) * d_mode_->GetHeight();\r
181 \r
182                 // Convert to planar YUV422\r
183                 unsigned char* y  = frame->image_data(0).begin();\r
184                 unsigned char* cb = frame->image_data(1).begin();\r
185                 unsigned char* cr = frame->image_data(2).begin();\r
186                 \r
187                 tbb::parallel_for(tbb::blocked_range<size_t>(0, frame_size/4), [&](const tbb::blocked_range<size_t>& r)\r
188                 {\r
189                         for(auto n = r.begin(); n != r.end(); ++n)\r
190                         {\r
191                                 cb[n]     = data[n*4+0];\r
192                                 y [n*2+0] = data[n*4+1];\r
193                                 cr[n]     = data[n*4+2];\r
194                                 y [n*2+1] = data[n*4+3];\r
195                         }\r
196                 });\r
197 \r
198                 if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
199                 {\r
200                         auto sample_frame_count = audio->GetSampleFrameCount();\r
201                         auto audio_data = reinterpret_cast<short*>(bytes);\r
202                         audio_data_.insert(audio_data_.end(), audio_data, audio_data + sample_frame_count*2);\r
203 \r
204                         if(audio_data_.size() > 3840)\r
205                         {\r
206                                 frame->audio_data() = std::vector<short>(audio_data_.begin(), audio_data_.begin() + 3840);\r
207                                 audio_data_.erase(audio_data_.begin(), audio_data_.begin() + 3840);\r
208                                 frame_buffer_.try_push(frame);\r
209                         }\r
210                 }\r
211                 else\r
212                         frame_buffer_.try_push(frame);\r
213 \r
214                 return S_OK;\r
215         }\r
216 \r
217         IDeckLinkDisplayMode* get_display_mode(BMDDisplayMode mode)\r
218         {       \r
219                 CComPtr<IDeckLinkDisplayModeIterator>   iterator;\r
220                 IDeckLinkDisplayMode*                                   d_mode;\r
221         \r
222                 if (input_->GetDisplayModeIterator(&iterator) != S_OK)\r
223                         return nullptr;\r
224 \r
225                 while (iterator->Next(&d_mode) == S_OK)\r
226                 {\r
227                         if(d_mode->GetDisplayMode() == mode)\r
228                                 return d_mode;\r
229                 }\r
230                 return nullptr;\r
231         }\r
232 \r
233         safe_ptr<core::basic_frame> get_frame()\r
234         {\r
235                 frame_buffer_.try_pop(tail_);\r
236                 return tail_;\r
237         }\r
238 \r
239         std::wstring print() const\r
240         {\r
241                 return (parent_printer_ ? parent_printer_() + L"/" : L"") + L" [" + model_name_ + L"device:" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
242         }\r
243 };\r
244         \r
245 class decklink_producer : public core::frame_producer\r
246 {       \r
247         const size_t device_index_;\r
248         printer parent_printer_;\r
249 \r
250         std::unique_ptr<decklink_input> input_;\r
251         \r
252         const core::video_format_desc format_desc_;\r
253         \r
254         executor executor_;\r
255 public:\r
256 \r
257         explicit decklink_producer(const core::video_format_desc& format_desc, size_t device_index)\r
258                 : format_desc_(format_desc) \r
259                 , device_index_(device_index)\r
260                 , executor_(print()){}\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 }