]> 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 #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 { namespace decklink {\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         safe_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         ffmpeg::filter                                                                                          filter_;\r
95                 \r
96         ffmpeg::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_(ffmpeg::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_->add_guide("tick-time", 0.5);\r
112                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
113                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
114                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
115                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
116                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
117                 graph_->set_text(print());\r
118                 diagnostics::register_graph(graph_);\r
119                 \r
120                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
121                 \r
122                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
123                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
124                         BOOST_THROW_EXCEPTION(caspar_exception() \r
125                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
126                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
127 \r
128                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels))) \r
129                         BOOST_THROW_EXCEPTION(caspar_exception() \r
130                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
131                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
132                         \r
133                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
134                         BOOST_THROW_EXCEPTION(caspar_exception() \r
135                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
136                                                                         << boost::errinfo_api_function("SetCallback"));\r
137                         \r
138                 if(FAILED(input_->StartStreams()))\r
139                         BOOST_THROW_EXCEPTION(caspar_exception() \r
140                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
141                                                                         << boost::errinfo_api_function("StartStreams"));\r
142 \r
143                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
144         }\r
145 \r
146         ~decklink_producer()\r
147         {\r
148                 if(input_ != nullptr) \r
149                 {\r
150                         input_->StopStreams();\r
151                         input_->DisableVideoInput();\r
152                 }\r
153         }\r
154 \r
155         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
156         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
157         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
158                 \r
159         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
160         {\r
161                 return S_OK;\r
162         }\r
163 \r
164         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
165         {       \r
166                 if(!video)\r
167                         return S_OK;\r
168 \r
169                 try\r
170                 {\r
171                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);\r
172                         tick_timer_.restart();\r
173 \r
174                         frame_timer_.restart();\r
175 \r
176                         void* bytes = nullptr;\r
177                         if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
178                                 return S_OK;\r
179                         \r
180                         safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
181                         avcodec_get_frame_defaults(av_frame.get());\r
182                                                 \r
183                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
184                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
185                         av_frame->format                        = PIX_FMT_UYVY422;\r
186                         av_frame->width                         = video->GetWidth();\r
187                         av_frame->height                        = video->GetHeight();\r
188                         av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
189                         av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
190                                         \r
191                         BOOST_FOREACH(auto& av_frame2, filter_.execute(av_frame))\r
192                                 muxer_.push(av_frame2);         \r
193                                                                         \r
194                         // It is assumed that audio is always equal or ahead of video.\r
195                         if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
196                         {\r
197                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
198                                 auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
199                                 muxer_.push(std::make_shared<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels));\r
200                         }\r
201                         else\r
202                                 muxer_.push(std::make_shared<core::audio_buffer>(frame_factory_->get_video_format_desc().audio_samples_per_frame, 0));\r
203                                         \r
204                         muxer_.commit();\r
205 \r
206                         while(!muxer_.empty())\r
207                         {\r
208                                 if(!frame_buffer_.try_push(muxer_.pop()))\r
209                                         graph_->add_tag("dropped-frame");\r
210                         }\r
211 \r
212                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
213 \r
214                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
215                 }\r
216                 catch(...)\r
217                 {\r
218                         exception_ = std::current_exception();\r
219                         return E_FAIL;\r
220                 }\r
221 \r
222                 return S_OK;\r
223         }\r
224         \r
225         safe_ptr<core::basic_frame> get_frame()\r
226         {\r
227                 if(exception_ != nullptr)\r
228                         std::rethrow_exception(exception_);\r
229 \r
230                 safe_ptr<core::basic_frame> frame = core::basic_frame::late();\r
231                 if(!frame_buffer_.try_pop(frame))\r
232                         graph_->add_tag("late-frame");\r
233                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
234                 return frame;\r
235         }\r
236         \r
237         std::wstring print() const\r
238         {\r
239                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
240         }\r
241 };\r
242         \r
243 class decklink_producer_proxy : public core::frame_producer\r
244 {               \r
245         safe_ptr<core::basic_frame>             last_frame_;\r
246         com_context<decklink_producer>  context_;\r
247         const int64_t                                   length_;\r
248 public:\r
249 \r
250         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, int64_t length)\r
251                 : context_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")\r
252                 , last_frame_(core::basic_frame::empty())\r
253                 , length_(length)\r
254         {\r
255                 context_.reset([&]{return new decklink_producer(format_desc, device_index, frame_factory, filter_str);}); \r
256         }\r
257 \r
258         ~decklink_producer_proxy()\r
259         {\r
260                 auto str = print();\r
261                 context_.reset();\r
262                 CASPAR_LOG(info) << str << L" Successfully Uninitialized.";     \r
263         }\r
264                                 \r
265         virtual safe_ptr<core::basic_frame> receive(int)\r
266         {\r
267                 auto frame = context_->get_frame();\r
268                 if(frame != core::basic_frame::late())\r
269                         last_frame_ = frame;\r
270                 return frame;\r
271         }\r
272 \r
273         virtual safe_ptr<core::basic_frame> last_frame() const\r
274         {\r
275                 return disable_audio(last_frame_);\r
276         }\r
277         \r
278         virtual int64_t nb_frames() const \r
279         {\r
280                 return length_;\r
281         }\r
282         \r
283         std::wstring print() const\r
284         {\r
285                 return context_->print();\r
286         }\r
287 };\r
288 \r
289 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
290 {\r
291         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
292                 return core::frame_producer::empty();\r
293 \r
294         auto device_index       = core::get_param(L"DEVICE", params, 1);\r
295         auto filter_str         = core::get_param<std::wstring>(L"FILTER", params, L"");        \r
296         auto length                     = core::get_param(L"LENGTH", params, std::numeric_limits<int64_t>::max());      \r
297         \r
298         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
299         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
300 \r
301         auto format_desc        = core::video_format_desc::get(core::get_param<std::wstring>(L"FORMAT", params, L"INVALID"));\r
302 \r
303         if(format_desc.format == core::video_format::invalid)\r
304                 format_desc = frame_factory->get_video_format_desc();\r
305                         \r
306         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length);\r
307 }\r
308 \r
309 }}