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