]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
3ab2706499a86fd5b4aac598139009f8271334e0
[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 "../../ffmpeg/producer/filter/filter.h"\r
29 #include "../../ffmpeg/producer/util.h"\r
30 #include "../../ffmpeg/producer/frame_muxer.h"\r
31 \r
32 #include <common/log/log.h>\r
33 #include <common/diagnostics/graph.h>\r
34 #include <common/concurrency/com_context.h>\r
35 #include <common/exception/exceptions.h>\r
36 #include <common/memory/memclr.h>\r
37 \r
38 #include <core/mixer/write_frame.h>\r
39 #include <core/producer/frame/frame_transform.h>\r
40 #include <core/producer/frame/frame_factory.h>\r
41 \r
42 #include <tbb/concurrent_queue.h>\r
43 \r
44 #include <boost/algorithm/string.hpp>\r
45 #include <boost/foreach.hpp>\r
46 #include <boost/timer.hpp>\r
47 \r
48 #if defined(_MSC_VER)\r
49 #pragma warning (push)\r
50 #pragma warning (disable : 4244)\r
51 #endif\r
52 extern "C" \r
53 {\r
54         #define __STDC_CONSTANT_MACROS\r
55         #define __STDC_LIMIT_MACROS\r
56         #include <libavcodec/avcodec.h>\r
57 }\r
58 #if defined(_MSC_VER)\r
59 #pragma warning (pop)\r
60 #endif\r
61 \r
62 #pragma warning(push)\r
63 #pragma warning(disable : 4996)\r
64 \r
65         #include <atlbase.h>\r
66 \r
67         #include <atlcom.h>\r
68         #include <atlhost.h>\r
69 \r
70 #pragma warning(push)\r
71 \r
72 #include <functional>\r
73 \r
74 namespace caspar { \r
75                 \r
76 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback\r
77 {       \r
78         CComPtr<IDeckLink>                                                                                      decklink_;\r
79         CComQIPtr<IDeckLinkInput>                                                                       input_;\r
80         \r
81         const std::wstring                                                                                      model_name_;\r
82         const core::video_format_desc                                                           format_desc_;\r
83         const size_t                                                                                            device_index_;\r
84 \r
85         std::shared_ptr<diagnostics::graph>                                                     graph_;\r
86         boost::timer                                                                                            tick_timer_;\r
87         boost::timer                                                                                            frame_timer_;\r
88                 \r
89         safe_ptr<core::frame_factory>                                                           frame_factory_;\r
90 \r
91         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
92 \r
93         std::exception_ptr                                                                                      exception_;\r
94         filter                                                                                                          filter_;\r
95                 \r
96         frame_muxer                                                                                                     muxer_;\r
97 \r
98 public:\r
99         decklink_producer(const core::video_format_desc& format_desc, size_t device_index, const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filter)\r
100                 : decklink_(get_device(device_index))\r
101                 , input_(decklink_)\r
102                 , model_name_(get_model_name(decklink_))\r
103                 , format_desc_(format_desc)\r
104                 , device_index_(device_index)\r
105                 , frame_factory_(frame_factory)\r
106                 , filter_(filter)\r
107                 , muxer_(double_rate(filter) ? format_desc.fps * 2.0 : format_desc.fps, frame_factory)\r
108         {\r
109                 frame_buffer_.set_capacity(2);\r
110                 \r
111                 graph_ = diagnostics::create_graph(boost::bind(&decklink_producer::print, this));\r
112                 graph_->add_guide("tick-time", 0.5);\r
113                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
114                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
115                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
116                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
117                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
118                 \r
119                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
120                 \r
121                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
122                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
123                         BOOST_THROW_EXCEPTION(caspar_exception() \r
124                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
125                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
126 \r
127                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2))) \r
128                         BOOST_THROW_EXCEPTION(caspar_exception() \r
129                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
130                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
131                         \r
132                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
133                         BOOST_THROW_EXCEPTION(caspar_exception() \r
134                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
135                                                                         << boost::errinfo_api_function("SetCallback"));\r
136                         \r
137                 if(FAILED(input_->StartStreams()))\r
138                         BOOST_THROW_EXCEPTION(caspar_exception() \r
139                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
140                                                                         << boost::errinfo_api_function("StartStreams"));\r
141 \r
142                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
143         }\r
144 \r
145         ~decklink_producer()\r
146         {\r
147                 if(input_ != nullptr) \r
148                 {\r
149                         input_->StopStreams();\r
150                         input_->DisableVideoInput();\r
151                 }\r
152         }\r
153 \r
154         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
155         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
156         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
157                 \r
158         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
159         {\r
160                 return S_OK;\r
161         }\r
162 \r
163         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
164         {       \r
165                 if(!video)\r
166                         return S_OK;\r
167 \r
168                 try\r
169                 {\r
170                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
171                         tick_timer_.restart();\r
172 \r
173                         frame_timer_.restart();\r
174 \r
175                         void* bytes = nullptr;\r
176                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
177                                 return S_OK;\r
178                         \r
179                         safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
180                         avcodec_get_frame_defaults(av_frame.get());\r
181                                                 \r
182                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
183                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
184                         av_frame->format                        = PIX_FMT_UYVY422;\r
185                         av_frame->width                         = video->GetWidth();\r
186                         av_frame->height                        = video->GetHeight();\r
187                         av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
188                         av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
189                                         \r
190                         BOOST_FOREACH(auto& av_frame2, filter_.execute(av_frame))\r
191                                 muxer_.push(av_frame2);         \r
192                                                                         \r
193                         // It is assumed that audio is always equal or ahead of video.\r
194                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
195                         {\r
196                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
197                                 auto audio_data = reinterpret_cast<short*>(bytes);\r
198                                 muxer_.push(std::make_shared<std::vector<int32_t>>(audio_data, audio_data + sample_frame_count*2));\r
199                         }\r
200                         else\r
201                                 muxer_.push(std::make_shared<std::vector<int32_t>>(frame_factory_->get_video_format_desc().audio_samples_per_frame, 0));\r
202                                         \r
203                         muxer_.commit();\r
204 \r
205                         while(!muxer_.empty())\r
206                         {\r
207                                 if(!frame_buffer_.try_push(muxer_.pop()))\r
208                                         graph_->add_tag("dropped-frame");\r
209                         }\r
210 \r
211                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
212 \r
213                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
214                 }\r
215                 catch(...)\r
216                 {\r
217                         exception_ = std::current_exception();\r
218                         return E_FAIL;\r
219                 }\r
220 \r
221                 return S_OK;\r
222         }\r
223         \r
224         safe_ptr<core::basic_frame> get_frame()\r
225         {\r
226                 if(exception_ != nullptr)\r
227                         std::rethrow_exception(exception_);\r
228 \r
229                 safe_ptr<core::basic_frame> frame = core::basic_frame::late();\r
230                 if(!frame_buffer_.try_pop(frame))\r
231                         graph_->add_tag("late-frame");\r
232                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
233                 return frame;\r
234         }\r
235         \r
236         std::wstring print() const\r
237         {\r
238                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
239         }\r
240 };\r
241         \r
242 class decklink_producer_proxy : public core::frame_producer\r
243 {               \r
244         safe_ptr<core::basic_frame>     last_frame_;\r
245         com_context<decklink_producer> context_;\r
246 public:\r
247 \r
248         explicit decklink_producer_proxy(const safe_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, size_t device_index, const std::wstring& filter_str = L"")\r
249                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
250                 , last_frame_(core::basic_frame::empty())\r
251         {\r
252                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
253         }\r
254                                 \r
255         virtual safe_ptr<core::basic_frame> receive(int)\r
256         {\r
257                 auto frame = context_->get_frame();\r
258                 if(frame != core::basic_frame::late())\r
259                         last_frame_ = frame;\r
260                 return frame;\r
261         }\r
262 \r
263         virtual safe_ptr<core::basic_frame> last_frame() const\r
264         {\r
265                 return disable_audio(last_frame_);\r
266         }\r
267         \r
268         std::wstring print() const\r
269         {\r
270                 return context_->print();\r
271         }\r
272 };\r
273 \r
274 safe_ptr<core::frame_producer> create_decklink_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
275 {\r
276         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
277                 return core::frame_producer::empty();\r
278 \r
279         size_t device_index = 1;\r
280         if(params.size() > 1)\r
281                 device_index = lexical_cast_or_default(params[1], 1);\r
282 \r
283         core::video_format_desc format_desc = core::video_format_desc::get(L"PAL");\r
284         if(params.size() > 2)\r
285         {\r
286                 auto desc = core::video_format_desc::get(params[2]);\r
287                 if(desc.format != core::video_format::invalid)\r
288                         format_desc = desc;\r
289         }\r
290         \r
291         std::wstring filter_str = L"";\r
292 \r
293         auto filter_it = std::find(params.begin(), params.end(), L"FILTER");\r
294         if(filter_it != params.end())\r
295         {\r
296                 if(++filter_it != params.end())\r
297                         filter_str = *filter_it;\r
298         }\r
299 \r
300         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str);\r
301 }\r
302 \r
303 }