]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
2.0.0.2:
[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"\r
26 #include "../util/util.h"\r
27 \r
28 #include <common/diagnostics/graph.h>\r
29 #include <common/concurrency/com_context.h>\r
30 #include <common/exception/exceptions.h>\r
31 #include <common/memory/memclr.h>\r
32 #include <common/utility/timer.h>\r
33 \r
34 #include <core/producer/frame/frame_factory.h>\r
35 #include <core/producer/frame/write_frame.h>\r
36 \r
37 #include <tbb/concurrent_queue.h>\r
38 #include <tbb/atomic.h>\r
39 \r
40 #include <boost/algorithm/string.hpp>\r
41 #include <boost/timer.hpp>\r
42 \r
43 #pragma warning(push)\r
44 #pragma warning(disable : 4996)\r
45 \r
46         #include <atlbase.h>\r
47 \r
48         #include <atlcom.h>\r
49         #include <atlhost.h>\r
50 \r
51 #pragma warning(push)\r
52 \r
53 #include <functional>\r
54 \r
55 namespace caspar { \r
56 \r
57 class decklink_producer : public IDeckLinkInputCallback\r
58 {       \r
59         CComPtr<IDeckLink>                              decklink_;\r
60         CComQIPtr<IDeckLinkInput>               input_;\r
61         \r
62         const std::wstring model_name_;\r
63         const core::video_format_desc format_desc_;\r
64         const size_t device_index_;\r
65 \r
66         std::shared_ptr<diagnostics::graph> graph_;\r
67         boost::timer perf_timer_;\r
68         \r
69         std::vector<short>                      audio_data_;\r
70 \r
71         std::shared_ptr<core::frame_factory> frame_factory_;\r
72 \r
73         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>> frame_buffer_;\r
74         safe_ptr<core::basic_frame> tail_;\r
75 \r
76         std::exception_ptr exception_;\r
77 \r
78 public:\r
79         decklink_producer(const core::video_format_desc& format_desc, size_t device_index, const std::shared_ptr<core::frame_factory>& frame_factory)\r
80                 : decklink_(get_device(device_index))\r
81                 , input_(decklink_)\r
82                 , model_name_(get_model_name(decklink_))\r
83                 , format_desc_(format_desc)\r
84                 , device_index_(device_index)\r
85                 , frame_factory_(frame_factory)\r
86                 , tail_(core::basic_frame::empty())\r
87         {\r
88                 frame_buffer_.set_capacity(2);\r
89                 \r
90                 graph_ = diagnostics::create_graph(boost::bind(&decklink_producer::print, this));\r
91                 graph_->add_guide("tick-time", 0.5);\r
92                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
93                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
94                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
95                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
96                 \r
97                 auto display_mode = get_display_mode(input_, format_desc_.format);\r
98                 if(!display_mode) \r
99                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
100                 \r
101                 // NOTE: For some reason the code below fails even for PAL.\r
102                 //BMDDisplayModeSupport displayModeSupport;\r
103                 //if(FAILED(input_->DoesSupportVideoMode(display_mode->GetDisplayMode(), bmdFormat8BitBGRA, bmdVideoOutputFlagDefault, &displayModeSupport, nullptr)) || displayModeSupport == bmdDisplayModeNotSupported)\r
104                 //      BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Card does not support requested videoformat."));\r
105                 //else if(displayModeSupport == bmdDisplayModeSupportedWithConversion)\r
106                 //      CASPAR_LOG(warning) << print() << " Display mode is supported with conversion.";\r
107 \r
108                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
109                 if(FAILED(input_->EnableVideoInput(display_mode->GetDisplayMode(), bmdFormat8BitYUV, 0))) \r
110                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable video input."));\r
111 \r
112                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
113                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Could not enable audio input."));\r
114                         \r
115                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
116                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to set input callback."));\r
117                         \r
118                 if(FAILED(input_->StartStreams()))\r
119                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start input stream."));\r
120 \r
121                 CASPAR_LOG(info) << print() << " successfully initialized decklink for " << format_desc_.name;\r
122         }\r
123 \r
124         ~decklink_producer()\r
125         {\r
126                 if(input_ != nullptr) \r
127                 {\r
128                         input_->StopStreams();\r
129                         input_->DisableVideoInput();\r
130                 }\r
131         }\r
132 \r
133         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
134         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
135         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
136                 \r
137         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
138         {\r
139                 return S_OK;\r
140         }\r
141 \r
142         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
143         {       \r
144                 try\r
145                 {\r
146                         graph_->update_value("tick-time", static_cast<float>(perf_timer_.elapsed()/format_desc_.interval*0.5));\r
147                         perf_timer_.restart();\r
148                                                 \r
149                         core::pixel_format_desc desc;\r
150                         desc.pix_fmt = core::pixel_format::ycbcr;\r
151                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width,   format_desc_.height, 1));\r
152                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width/2, format_desc_.height, 1));\r
153                         desc.planes.push_back(core::pixel_format_desc::plane(format_desc_.width/2, format_desc_.height, 1));                    \r
154                         auto frame = frame_factory_->create_frame(this, desc);\r
155                                                 \r
156                         void* bytes = nullptr;\r
157                         video->GetBytes(&bytes);\r
158                         unsigned char* data = reinterpret_cast<unsigned char*>(bytes);\r
159                         const size_t frame_size = (format_desc_.width * 16 / 8) * format_desc_.height;\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), [&](const tbb::blocked_range<size_t>& r)\r
167                         {\r
168                                 for(auto n = r.begin(); n != r.end(); ++n)\r
169                                 {\r
170                                         cb[n]     = data[n*4+0];\r
171                                         y [n*2+0] = data[n*4+1];\r
172                                         cr[n]     = data[n*4+2];\r
173                                         y [n*2+1] = data[n*4+3];\r
174                                 }\r
175                         });\r
176 \r
177                         // It is assumed that audio is always equal or ahead of video.\r
178                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
179                         {\r
180                                 const size_t audio_samples = static_cast<size_t>(48000.0 / format_desc_.fps);\r
181                                 const size_t audio_nchannels = 2;\r
182 \r
183                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
184                                 auto audio_data = reinterpret_cast<short*>(bytes);\r
185                                 audio_data_.insert(audio_data_.end(), audio_data, audio_data + sample_frame_count*2);\r
186 \r
187                                 if(audio_data_.size() > audio_samples*audio_nchannels)\r
188                                 {\r
189                                         frame->audio_data() = std::vector<short>(audio_data_.begin(), audio_data_.begin() +  audio_samples*audio_nchannels);\r
190                                         audio_data_.erase(audio_data_.begin(), audio_data_.begin() +  audio_samples*audio_nchannels);\r
191                                 }\r
192                         }\r
193 \r
194                         if(!frame_buffer_.try_push(frame))\r
195                                 graph_->add_tag("dropped-frame");\r
196                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
197                 }\r
198                 catch(...)\r
199                 {\r
200                         exception_ = std::current_exception();\r
201                         return E_FAIL;\r
202                 }\r
203 \r
204                 return S_OK;\r
205         }\r
206         \r
207         safe_ptr<core::basic_frame> get_frame()\r
208         {\r
209                 if(exception_ != nullptr)\r
210                         std::rethrow_exception(exception_);\r
211 \r
212                 if(!frame_buffer_.try_pop(tail_))\r
213                         graph_->add_tag("late-frame");\r
214                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
215                 return tail_;\r
216         }\r
217         \r
218         std::wstring print() const\r
219         {\r
220                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
221         }\r
222 };\r
223         \r
224 class decklink_producer_proxy : public core::frame_producer\r
225 {               \r
226         com_context<decklink_producer> context_;\r
227 public:\r
228 \r
229         explicit decklink_producer_proxy(const safe_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, size_t device_index)\r
230                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
231         {\r
232                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory);}); \r
233         }\r
234                                 \r
235         virtual safe_ptr<core::basic_frame> receive()\r
236         {\r
237                 return context_->get_frame();\r
238         }\r
239         \r
240         std::wstring print() const\r
241         {\r
242                 return context_->print();\r
243         }\r
244 };\r
245 \r
246 safe_ptr<core::frame_producer> create_decklink_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
247 {\r
248         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
249                 return core::frame_producer::empty();\r
250 \r
251         size_t device_index = 1;\r
252         if(params.size() > 1)\r
253                 device_index = lexical_cast_or_default(params[1], 1);\r
254 \r
255         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
256         if(params.size() > 2)\r
257         {\r
258                 auto desc = core::video_format_desc::get(params[2]);\r
259                 if(desc.format != core::video_format::invalid)\r
260                         format_desc = desc;\r
261         }\r
262 \r
263         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index);\r
264 }\r
265 \r
266 }