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