]> 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/util.h"\r
30 #include "../../ffmpeg/producer/muxer/frame_muxer.h"\r
31 \r
32 #include <common/log/log.h>\r
33 #include <common/diagnostics/graph.h>\r
34 #include <common/exception/exceptions.h>\r
35 \r
36 #include <core/mixer/write_frame.h>\r
37 #include <core/producer/frame/frame_transform.h>\r
38 #include <core/producer/frame/frame_factory.h>\r
39 \r
40 #include <agents.h>\r
41 #include <agents_extras.h>\r
42 #include <ppl.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 <algorithm>\r
72 #include <functional>\r
73 \r
74 namespace caspar { namespace decklink {\r
75                 \r
76 typedef std::pair<CComPtr<IDeckLinkVideoInputFrame>, CComPtr<IDeckLinkAudioInputPacket>> frame_packet;\r
77 \r
78 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback\r
79 {       \r
80         Concurrency::ITarget<frame_packet>&     target_;\r
81 \r
82         CComPtr<IDeckLink>                                      decklink_;\r
83         CComQIPtr<IDeckLinkInput>                       input_;\r
84         \r
85         const std::wstring                                      model_name_;\r
86         const core::video_format_desc           format_desc_;\r
87         const size_t                                            device_index_;\r
88 \r
89         safe_ptr<diagnostics::graph>            graph_;\r
90         boost::timer                                            tick_timer_;\r
91         boost::timer                                            frame_timer_;\r
92 \r
93 public:\r
94         decklink_producer(Concurrency::ITarget<frame_packet>& target, const core::video_format_desc& format_desc, size_t device_index)\r
95                 : target_(target)\r
96                 , decklink_(get_device(device_index))\r
97                 , input_(decklink_)\r
98                 , model_name_(get_model_name(decklink_))\r
99                 , format_desc_(format_desc)\r
100                 , device_index_(device_index)\r
101         {               \r
102                 graph_->add_guide("tick-time", 0.5);\r
103                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
104                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
105                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
106                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
107                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
108                 graph_->set_text(narrow(print()));\r
109                 diagnostics::register_graph(graph_);\r
110 \r
111                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
112                 \r
113                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
114                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
115                         BOOST_THROW_EXCEPTION(caspar_exception() \r
116                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
117                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
118 \r
119                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels))) \r
120                         BOOST_THROW_EXCEPTION(caspar_exception() \r
121                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
122                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
123                         \r
124                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
125                         BOOST_THROW_EXCEPTION(caspar_exception() \r
126                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
127                                                                         << boost::errinfo_api_function("SetCallback"));\r
128                         \r
129                 if(FAILED(input_->StartStreams()))\r
130                         BOOST_THROW_EXCEPTION(caspar_exception() \r
131                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
132                                                                         << boost::errinfo_api_function("StartStreams"));\r
133 \r
134                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
135         }\r
136 \r
137         ~decklink_producer()\r
138         {\r
139                 Concurrency::scoped_oversubcription_token oversubscribe;\r
140                 if(input_ != nullptr) \r
141                 {\r
142                         input_->StopStreams();\r
143                         input_->DisableVideoInput();\r
144                 }\r
145         }\r
146 \r
147         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}\r
148         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}\r
149         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}\r
150                 \r
151         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)\r
152         {\r
153                 return S_OK;\r
154         }\r
155 \r
156         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)\r
157         {       \r
158                 if(!Concurrency::asend(target_, frame_packet(CComPtr<IDeckLinkVideoInputFrame>(video), CComPtr<IDeckLinkAudioInputPacket>(audio))))\r
159                         graph_->add_tag("dropped-frame");\r
160                 return S_OK;\r
161         }\r
162                 \r
163         std::wstring print() const\r
164         {\r
165                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
166         }\r
167 };\r
168         \r
169 class decklink_producer_proxy : public Concurrency::agent, public core::frame_producer\r
170 {               \r
171         safe_ptr<diagnostics::graph>                                                                                            graph_;\r
172 \r
173         Concurrency::unbounded_buffer<ffmpeg::frame_muxer2::video_source_element_t>     video_frames_;\r
174         Concurrency::unbounded_buffer<ffmpeg::frame_muxer2::audio_source_element_t>     audio_buffers_;\r
175         Concurrency::overwrite_buffer<ffmpeg::frame_muxer2::target_element_t>           muxed_frames_;\r
176 \r
177         const core::video_format_desc           format_desc_;\r
178         const size_t                                            device_index_;\r
179 \r
180         safe_ptr<core::basic_frame>                     last_frame_;\r
181         const int64_t                                           length_;\r
182                         \r
183         ffmpeg::frame_muxer2                            muxer_;\r
184 \r
185         mutable Concurrency::single_assignment<std::wstring> print_;\r
186         \r
187         tbb::atomic<bool> is_running_;\r
188 public:\r
189 \r
190         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
191                 : muxed_frames_(1)\r
192                 , format_desc_(format_desc)\r
193                 , device_index_(device_index)\r
194                 , last_frame_(core::basic_frame::empty())\r
195                 , length_(length)\r
196                 , muxer_(&video_frames_, &audio_buffers_, muxed_frames_, format_desc.fps, frame_factory)\r
197         {\r
198                 diagnostics::register_graph(graph_);\r
199                 is_running_ = true;\r
200                 agent::start();\r
201         }\r
202 \r
203         ~decklink_producer_proxy()\r
204         {\r
205                 is_running_ = false;\r
206                 agent::wait(this);\r
207         }\r
208                                 \r
209         virtual safe_ptr<core::basic_frame> receive(int)\r
210         {\r
211                 auto frame = core::basic_frame::late();\r
212 \r
213                 try\r
214                 {\r
215                         last_frame_ = frame = Concurrency::receive(muxed_frames_, 10).first;\r
216                 }\r
217                 catch(Concurrency::operation_timed_out&)\r
218                 {               \r
219                         graph_->add_tag("underflow");   \r
220                 }\r
221 \r
222                 return frame;\r
223         }\r
224 \r
225         virtual safe_ptr<core::basic_frame> last_frame() const\r
226         {\r
227                 return disable_audio(last_frame_);\r
228         }\r
229         \r
230         virtual int64_t nb_frames() const \r
231         {\r
232                 return length_;\r
233         }\r
234         \r
235         std::wstring print() const\r
236         {\r
237                 return print_.value();\r
238         }\r
239 \r
240         virtual void run()\r
241         {\r
242                 try\r
243                 {\r
244                         struct co_init\r
245                         {\r
246                                 co_init()  {CoInitialize(NULL);}\r
247                                 ~co_init() {CoUninitialize();}\r
248                         } init;\r
249                         \r
250                         Concurrency::overwrite_buffer<frame_packet> input_buffer;\r
251 \r
252                         std::unique_ptr<decklink_producer> producer;\r
253                         {                               \r
254                                 Concurrency::scoped_oversubcription_token oversubscribe;\r
255                                 producer.reset(new decklink_producer(input_buffer, format_desc_, device_index_));\r
256                         }\r
257 \r
258                         Concurrency::send(print_, producer->print());\r
259 \r
260                         while(is_running_)\r
261                         {\r
262                                 auto packet = Concurrency::receive(input_buffer);\r
263                                 auto video  = packet.first;\r
264                                 auto audio  = packet.second;\r
265                                 \r
266                                 void* bytes = nullptr;\r
267                                 if(FAILED(video->GetBytes(&bytes)) || !bytes)\r
268                                         continue;\r
269                         \r
270                                 safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
271                                 avcodec_get_frame_defaults(av_frame.get());\r
272                                                 \r
273                                 av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
274                                 av_frame->linesize[0]           = video->GetRowBytes();                 \r
275                                 av_frame->format                        = PIX_FMT_UYVY422;\r
276                                 av_frame->width                         = video->GetWidth();\r
277                                 av_frame->height                        = video->GetHeight();\r
278                                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
279                                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
280                                         \r
281                                 Concurrency::send(video_frames_, av_frame);                                     \r
282                                 \r
283                                 // It is assumed that audio is always equal or ahead of video.\r
284                                 if(audio && SUCCEEDED(audio->GetBytes(&bytes)))\r
285                                 {\r
286                                         auto sample_frame_count = audio->GetSampleFrameCount();\r
287                                         auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
288                                         Concurrency::send(audio_buffers_, make_safe<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels));\r
289                                 }\r
290                                 else\r
291                                         Concurrency::send(audio_buffers_, make_safe<core::audio_buffer>(format_desc_.audio_samples_per_frame, 0));      \r
292                         }\r
293 \r
294                 }\r
295                 catch(...)\r
296                 {\r
297                         CASPAR_LOG_CURRENT_EXCEPTION();\r
298                 }\r
299                 \r
300                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
301 \r
302                 done();\r
303         }\r
304 };\r
305 \r
306 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
307 {\r
308         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
309                 return core::frame_producer::empty();\r
310         \r
311         std::vector<std::wstring> params2 = params;\r
312         std::for_each(std::begin(params2), std::end(params2), std::bind(&boost::to_upper<std::wstring>, std::placeholders::_1, std::locale()));\r
313 \r
314         auto device_index       = core::get_param(L"DEVICE", params2, 1);\r
315         auto filter_str         = core::get_param<std::wstring>(L"FILTER", params2, L"");       \r
316         auto length                     = core::get_param(L"LENGTH", params2, std::numeric_limits<int64_t>::max());     \r
317         \r
318         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
319         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
320 \r
321         auto format_desc        = core::video_format_desc::get(core::get_param<std::wstring>(L"FORMAT", params2, L"INVALID"));\r
322 \r
323         if(format_desc.format == core::video_format::invalid)\r
324                 format_desc = frame_factory->get_video_format_desc();\r
325                         \r
326         return make_safe<decklink_producer_proxy>(frame_factory, format_desc, device_index, filter_str, length);\r
327 }\r
328 \r
329 }}