]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
Misc modifications to fix problems found by static code analysis and some simplificat...
[casparcg] / modules / decklink / producer / decklink_producer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../stdafx.h"
23
24 #include "decklink_producer.h"
25
26 #include "../interop/DeckLinkAPI_h.h"
27 #include "../util/util.h"
28
29 #include "../../ffmpeg/producer/filter/filter.h"
30 #include "../../ffmpeg/producer/util/util.h"
31 #include "../../ffmpeg/producer/muxer/frame_muxer.h"
32 #include "../../ffmpeg/producer/muxer/display_mode.h"
33
34 #include <common/executor.h>
35 #include <common/diagnostics/graph.h>
36 #include <common/except.h>
37 #include <common/log.h>
38 #include <common/param.h>
39
40 #include <core/frame/frame.h>
41 #include <core/frame/draw_frame.h>
42 #include <core/frame/frame_transform.h>
43 #include <core/frame/frame_factory.h>
44 #include <core/monitor/monitor.h>
45 #include <core/mixer/audio/audio_mixer.h>
46
47 #include <tbb/concurrent_queue.h>
48
49 #include <boost/algorithm/string.hpp>
50 #include <boost/foreach.hpp>
51 #include <boost/property_tree/ptree.hpp>
52 #include <boost/timer.hpp>
53
54 #if defined(_MSC_VER)
55 #pragma warning (push)
56 #pragma warning (disable : 4244)
57 #endif
58 extern "C" 
59 {
60         #define __STDC_CONSTANT_MACROS
61         #define __STDC_LIMIT_MACROS
62         #include <libavcodec/avcodec.h>
63 }
64 #if defined(_MSC_VER)
65 #pragma warning (pop)
66 #endif
67
68 #pragma warning(push)
69 #pragma warning(disable : 4996)
70
71         #include <atlbase.h>
72
73         #include <atlcom.h>
74         #include <atlhost.h>
75
76 #pragma warning(push)
77
78 #include <functional>
79
80 namespace caspar { namespace decklink {
81                 
82 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
83 {       
84         monitor::basic_subject                                                  event_subject_;
85         spl::shared_ptr<diagnostics::graph>                             graph_;
86         boost::timer                                                                    tick_timer_;
87
88         CComPtr<IDeckLink>                                                              decklink_;
89         CComQIPtr<IDeckLinkInput>                                               input_;
90         CComQIPtr<IDeckLinkAttributes >                                 attributes_;
91         
92         const std::wstring                                                              model_name_;
93         const int                                                                               device_index_;
94         const std::wstring                                                              filter_;
95         
96         std::vector<int>                                                                audio_cadence_;
97         boost::circular_buffer<size_t>                                  sync_buffer_;
98         ffmpeg::frame_muxer                                                             muxer_;
99                         
100         spl::shared_ptr<core::frame_factory>                    frame_factory_;
101         core::video_format_desc                                                 in_format_desc_;
102         core::video_format_desc                                                 out_format_desc_;
103         core::constraints                                                               constraints_;
104
105         tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;
106
107         std::exception_ptr                                                              exception_;             
108
109 public:
110         decklink_producer(const core::video_format_desc& in_format_desc, 
111                                           int device_index, 
112                                           const spl::shared_ptr<core::frame_factory>& frame_factory, 
113                                           const core::video_format_desc& out_format_desc, 
114                                           const std::wstring& filter)
115                 : decklink_(get_device(device_index))
116                 , input_(decklink_)
117                 , attributes_(decklink_)
118                 , model_name_(get_model_name(decklink_))
119                 , device_index_(device_index)
120                 , filter_(filter)
121                 , in_format_desc_(in_format_desc)
122                 , out_format_desc_(out_format_desc)
123                 , constraints_(in_format_desc.width, in_format_desc.height)
124                 , muxer_(in_format_desc.fps, frame_factory, out_format_desc, filter)
125                 , audio_cadence_(out_format_desc.audio_cadence)
126                 , sync_buffer_(out_format_desc.audio_cadence.size())
127                 , frame_factory_(frame_factory)
128         {       
129                 frame_buffer_.set_capacity(2);
130                 
131                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
132                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
133                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
134                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
135                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
136                 graph_->set_text(print());
137                 diagnostics::register_graph(graph_);
138                 
139                 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
140                 
141                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
142                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) 
143                         CASPAR_THROW_EXCEPTION(caspar_exception() 
144                                                                         << msg_info(print() + L" Could not enable video input.")
145                                                                         << boost::errinfo_api_function("EnableVideoInput"));
146
147                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(in_format_desc.audio_channels)))) 
148                         CASPAR_THROW_EXCEPTION(caspar_exception() 
149                                                                         << msg_info(print() + L" Could not enable audio input.")
150                                                                         << boost::errinfo_api_function("EnableAudioInput"));
151                         
152                 if (FAILED(input_->SetCallback(this)) != S_OK)
153                         CASPAR_THROW_EXCEPTION(caspar_exception() 
154                                                                         << msg_info(print() + L" Failed to set input callback.")
155                                                                         << boost::errinfo_api_function("SetCallback"));
156                         
157                 if(FAILED(input_->StartStreams()))
158                         CASPAR_THROW_EXCEPTION(caspar_exception() 
159                                                                         << msg_info(print() + L" Failed to start input stream.")
160                                                                         << boost::errinfo_api_function("StartStreams"));
161
162                 CASPAR_LOG(info) << print() << L" Initialized";
163         }
164
165         ~decklink_producer()
166         {
167                 if(input_ != nullptr) 
168                 {
169                         input_->StopStreams();
170                         input_->DisableVideoInput();
171                 }
172         }
173
174         core::constraints& pixel_constraints()
175         {
176                 return constraints_;
177         }
178
179         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}
180         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}
181         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}
182                 
183         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
184         {
185                 return S_OK;
186         }
187
188         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
189         {       
190                 if(!video)
191                         return S_OK;
192
193                 try
194                 {
195                         graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);
196                         tick_timer_.restart();
197
198                         boost::timer frame_timer;       
199                         
200                         // Video
201
202                         void* video_bytes = nullptr;
203                         if(FAILED(video->GetBytes(&video_bytes)) || !video_bytes)
204                                 return S_OK;
205                         
206                         auto video_frame = ffmpeg::create_frame();
207                                                 
208                         video_frame->data[0]                    = reinterpret_cast<uint8_t*>(video_bytes);
209                         video_frame->linesize[0]                = video->GetRowBytes();                 
210                         video_frame->format                             = PIX_FMT_UYVY422;
211                         video_frame->width                              = video->GetWidth();
212                         video_frame->height                             = video->GetHeight();
213                         video_frame->interlaced_frame   = in_format_desc_.field_mode != core::field_mode::progressive;
214                         video_frame->top_field_first    = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
215                                 
216                         event_subject_  << monitor::event("file/name")                          % model_name_
217                                                         << monitor::event("file/path")                          % device_index_
218                                                         << monitor::event("file/video/width")           % video->GetWidth()
219                                                         << monitor::event("file/video/height")          % video->GetHeight()
220                                                         << monitor::event("file/video/field")           % u8(!video_frame->interlaced_frame ? "progressive" : (video_frame->top_field_first ? "upper" : "lower"))
221                                                         << monitor::event("file/audio/sample-rate")     % 48000
222                                                         << monitor::event("file/audio/channels")        % 2
223                                                         << monitor::event("file/audio/format")          % u8(av_get_sample_fmt_name(AV_SAMPLE_FMT_S32))
224                                                         << monitor::event("file/fps")                           % in_format_desc_.fps;
225
226                         // Audio
227
228                         void* audio_bytes = nullptr;
229                         if(FAILED(audio->GetBytes(&audio_bytes)) || !audio_bytes)
230                                 return S_OK;
231                         
232                         auto audio_frame = ffmpeg::create_frame();
233
234                         audio_frame->data[0]            = reinterpret_cast<uint8_t*>(audio_bytes);
235                         audio_frame->linesize[0]        = audio->GetSampleFrameCount()*out_format_desc_.audio_channels*sizeof(int32_t);
236                         audio_frame->nb_samples         = audio->GetSampleFrameCount();
237                         audio_frame->format                     = AV_SAMPLE_FMT_S32;
238                                                 
239                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
240                         // This cadence fills the audio mixer most optimally.
241
242                         sync_buffer_.push_back(audio->GetSampleFrameCount()*out_format_desc_.audio_channels);           
243                         if(!boost::range::equal(sync_buffer_, audio_cadence_))
244                         {
245                                 CASPAR_LOG(trace) << print() << L" Syncing audio.";
246                                 return S_OK;
247                         }
248                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
249                         
250                         // PUSH
251
252                         muxer_.push_video(video_frame); 
253                         muxer_.push_audio(audio_frame);                                                                                 
254                         
255                         // POLL
256
257                         auto frame = core::draw_frame::late();
258                         if(!muxer_.empty())
259                         {
260                                 frame = std::move(muxer_.front());
261                                 muxer_.pop();
262
263                                 if(!frame_buffer_.try_push(frame))
264                                 {
265                                         auto dummy = core::draw_frame::empty();
266                                         frame_buffer_.try_pop(dummy);
267                                         frame_buffer_.try_push(frame);
268                                                 
269                                         graph_->set_tag("dropped-frame");
270                                 }
271                         }
272                         
273                         graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);        
274                         event_subject_ << monitor::event("profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;
275
276                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      
277                         event_subject_ << monitor::event("buffer") % frame_buffer_.size() % frame_buffer_.capacity();
278                 }
279                 catch(...)
280                 {
281                         exception_ = std::current_exception();
282                         return E_FAIL;
283                 }
284
285                 return S_OK;
286         }
287         
288         core::draw_frame get_frame()
289         {
290                 if(exception_ != nullptr)
291                         std::rethrow_exception(exception_);
292                 
293                 core::draw_frame frame = core::draw_frame::late();
294                 if(!frame_buffer_.try_pop(frame))
295                         graph_->set_tag("late-frame");
296                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      
297                 return frame;
298         }
299         
300         std::wstring print() const
301         {
302                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";
303         }
304
305         void subscribe(const monitor::observable::observer_ptr& o)
306         {
307                 event_subject_.subscribe(o);
308         }
309
310         void unsubscribe(const monitor::observable::observer_ptr& o)
311         {
312                 event_subject_.unsubscribe(o);
313         }
314 };
315         
316 class decklink_producer_proxy : public core::frame_producer_base
317 {               
318         std::unique_ptr<decklink_producer>      producer_;
319         const uint32_t                                          length_;
320         executor                                                        executor_;
321 public:
322         explicit decklink_producer_proxy(const core::video_format_desc& in_format_desc,
323                                                                          const spl::shared_ptr<core::frame_factory>& frame_factory, 
324                                                                          const core::video_format_desc& out_format_desc, 
325                                                                          int device_index,
326                                                                          const std::wstring& filter_str, uint32_t length)
327                 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
328                 , length_(length)
329         {
330                 executor_.invoke([=]
331                 {
332                         CoInitialize(nullptr);
333                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, filter_str));
334                 });
335         }
336
337         ~decklink_producer_proxy()
338         {               
339                 executor_.invoke([=]
340                 {
341                         producer_.reset();
342                         CoUninitialize();
343                 });
344         }
345
346         void subscribe(const monitor::observable::observer_ptr& o) override
347         {
348                 producer_->subscribe(o);
349         }
350
351         void unsubscribe(const monitor::observable::observer_ptr& o) override
352         {
353                 producer_->unsubscribe(o);
354         }
355         
356         // frame_producer
357                                 
358         core::draw_frame receive_impl() override
359         {               
360                 return producer_->get_frame();
361         }
362
363         core::constraints& pixel_constraints() override
364         {
365                 return producer_->pixel_constraints();
366         }
367                         
368         uint32_t nb_frames() const override
369         {
370                 return length_;
371         }
372         
373         std::wstring print() const override
374         {
375                 return producer_->print();
376         }
377         
378         std::wstring name() const override
379         {
380                 return L"decklink";
381         }
382
383         boost::property_tree::wptree info() const override
384         {
385                 boost::property_tree::wptree info;
386                 info.add(L"type", L"decklink");
387                 return info;
388         }
389 };
390
391 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& out_format_desc, const std::vector<std::wstring>& params)
392 {
393         if(params.empty() || !boost::iequals(params[0], "decklink"))
394                 return core::frame_producer::empty();
395
396         auto device_index       = get_param(L"DEVICE", params, -1);
397         if(device_index == -1)
398                 device_index = boost::lexical_cast<int>(params.at(1));
399         
400         auto filter_str         = get_param(L"FILTER", params);         
401         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   
402         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
403                 
404         if(in_format_desc.format == core::video_format::invalid)
405                 in_format_desc = out_format_desc;
406                         
407         return create_destroy_proxy(spl::make_shared<decklink_producer_proxy>(in_format_desc, frame_factory, out_format_desc, device_index, filter_str, length));
408 }
409
410 }}