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