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