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