]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
Refactored to use non-static data member initializers where it makes sense. Mixes...
[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/property_tree/ptree.hpp>
51 #include <boost/timer.hpp>
52
53 #if defined(_MSC_VER)
54 #pragma warning (push)
55 #pragma warning (disable : 4244)
56 #endif
57 extern "C" 
58 {
59         #define __STDC_CONSTANT_MACROS
60         #define __STDC_LIMIT_MACROS
61         #include <libavcodec/avcodec.h>
62 }
63 #if defined(_MSC_VER)
64 #pragma warning (pop)
65 #endif
66
67 #pragma warning(push)
68 #pragma warning(disable : 4996)
69
70         #include <atlbase.h>
71
72         #include <atlcom.h>
73         #include <atlhost.h>
74
75 #pragma warning(push)
76
77 #include <functional>
78
79 namespace caspar { namespace decklink {
80                 
81 class decklink_producer : boost::noncopyable, public IDeckLinkInputCallback
82 {       
83         const int                                                                               device_index_;
84         core::monitor::subject                                                  monitor_subject_;
85         spl::shared_ptr<diagnostics::graph>                             graph_;
86         boost::timer                                                                    tick_timer_;
87
88         CComPtr<IDeckLink>                                                              decklink_                       = get_device(device_index_);
89         CComQIPtr<IDeckLinkInput>                                               input_                          = decklink_;
90         CComQIPtr<IDeckLinkAttributes >                                 attributes_                     = decklink_;
91         
92         const std::wstring                                                              model_name_                     = get_model_name(decklink_);
93         const std::wstring                                                              filter_;
94         
95         core::video_format_desc                                                 in_format_desc_;
96         core::video_format_desc                                                 out_format_desc_;
97         std::vector<int>                                                                audio_cadence_          = out_format_desc_.audio_cadence;
98         boost::circular_buffer<size_t>                                  sync_buffer_            { audio_cadence_.size() };
99         spl::shared_ptr<core::frame_factory>                    frame_factory_;
100         ffmpeg::frame_muxer                                                             muxer_                          { in_format_desc_.fps, frame_factory_, out_format_desc_, filter_ };
101                         
102         core::constraints                                                               constraints_            { in_format_desc_.width, in_format_desc_.height };
103
104         tbb::concurrent_bounded_queue<core::draw_frame> frame_buffer_;
105
106         std::exception_ptr                                                              exception_;             
107
108 public:
109         decklink_producer(
110                         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                 : device_index_(device_index)
116                 , filter_(filter)
117                 , in_format_desc_(in_format_desc)
118                 , out_format_desc_(out_format_desc)
119                 , frame_factory_(frame_factory)
120         {       
121                 frame_buffer_.set_capacity(2);
122                 
123                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
124                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
125                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));
126                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
127                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));
128                 graph_->set_text(print());
129                 diagnostics::register_graph(graph_);
130                 
131                 auto display_mode = get_display_mode(input_, in_format_desc.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);
132                 
133                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)
134                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) 
135                         CASPAR_THROW_EXCEPTION(caspar_exception() 
136                                                                         << msg_info(print() + L" Could not enable video input.")
137                                                                         << boost::errinfo_api_function("EnableVideoInput"));
138
139                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, static_cast<int>(in_format_desc.audio_channels)))) 
140                         CASPAR_THROW_EXCEPTION(caspar_exception() 
141                                                                         << msg_info(print() + L" Could not enable audio input.")
142                                                                         << boost::errinfo_api_function("EnableAudioInput"));
143                         
144                 if (FAILED(input_->SetCallback(this)) != S_OK)
145                         CASPAR_THROW_EXCEPTION(caspar_exception() 
146                                                                         << msg_info(print() + L" Failed to set input callback.")
147                                                                         << boost::errinfo_api_function("SetCallback"));
148                         
149                 if(FAILED(input_->StartStreams()))
150                         CASPAR_THROW_EXCEPTION(caspar_exception() 
151                                                                         << msg_info(print() + L" Failed to start input stream.")
152                                                                         << boost::errinfo_api_function("StartStreams"));
153
154                 CASPAR_LOG(info) << print() << L" Initialized";
155         }
156
157         ~decklink_producer()
158         {
159                 if(input_ != nullptr) 
160                 {
161                         input_->StopStreams();
162                         input_->DisableVideoInput();
163                 }
164         }
165
166         core::constraints& pixel_constraints()
167         {
168                 return constraints_;
169         }
170
171         virtual HRESULT STDMETHODCALLTYPE       QueryInterface (REFIID, LPVOID*)        {return E_NOINTERFACE;}
172         virtual ULONG STDMETHODCALLTYPE         AddRef ()                                                       {return 1;}
173         virtual ULONG STDMETHODCALLTYPE         Release ()                                                      {return 1;}
174                 
175         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents /*notificationEvents*/, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags /*detectedSignalFlags*/)
176         {
177                 return S_OK;
178         }
179
180         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame* video, IDeckLinkAudioInputPacket* audio)
181         {       
182                 if(!video)
183                         return S_OK;
184
185                 try
186                 {
187                         graph_->set_value("tick-time", tick_timer_.elapsed()*out_format_desc_.fps*0.5);
188                         tick_timer_.restart();
189
190                         boost::timer frame_timer;       
191                         
192                         // Video
193
194                         void* video_bytes = nullptr;
195                         if(FAILED(video->GetBytes(&video_bytes)) || !video_bytes)
196                                 return S_OK;
197                         
198                         auto video_frame = ffmpeg::create_frame();
199                                                 
200                         video_frame->data[0]                    = reinterpret_cast<uint8_t*>(video_bytes);
201                         video_frame->linesize[0]                = video->GetRowBytes();                 
202                         video_frame->format                             = PIX_FMT_UYVY422;
203                         video_frame->width                              = video->GetWidth();
204                         video_frame->height                             = video->GetHeight();
205                         video_frame->interlaced_frame   = in_format_desc_.field_mode != core::field_mode::progressive;
206                         video_frame->top_field_first    = in_format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
207                                 
208                         monitor_subject_
209                                         << core::monitor::message("/file/name")                                 % model_name_
210                                         << core::monitor::message("/file/path")                                 % device_index_
211                                         << core::monitor::message("/file/video/width")                  % video->GetWidth()
212                                         << core::monitor::message("/file/video/height")                 % video->GetHeight()
213                                         << core::monitor::message("/file/video/field")                  % u8(!video_frame->interlaced_frame ? "progressive" : (video_frame->top_field_first ? "upper" : "lower"))
214                                         << core::monitor::message("/file/audio/sample-rate")    % 48000
215                                         << core::monitor::message("/file/audio/channels")               % 2
216                                         << core::monitor::message("/file/audio/format")                 % u8(av_get_sample_fmt_name(AV_SAMPLE_FMT_S32))
217                                         << core::monitor::message("/file/fps")                                  % in_format_desc_.fps;
218
219                         // Audio
220
221                         void* audio_bytes = nullptr;
222                         if(FAILED(audio->GetBytes(&audio_bytes)) || !audio_bytes)
223                                 return S_OK;
224                         
225                         auto audio_frame = ffmpeg::create_frame();
226
227                         audio_frame->data[0]            = reinterpret_cast<uint8_t*>(audio_bytes);
228                         audio_frame->linesize[0]        = audio->GetSampleFrameCount()*out_format_desc_.audio_channels*sizeof(int32_t);
229                         audio_frame->nb_samples         = audio->GetSampleFrameCount();
230                         audio_frame->format                     = AV_SAMPLE_FMT_S32;
231                                                 
232                         // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
233                         // This cadence fills the audio mixer most optimally.
234
235                         sync_buffer_.push_back(audio->GetSampleFrameCount());           
236                         if(!boost::range::equal(sync_buffer_, audio_cadence_))
237                         {
238                                 CASPAR_LOG(trace) << print() << L" Syncing audio.";
239                                 return S_OK;
240                         }
241                         boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
242                         
243                         // PUSH
244
245                         muxer_.push_video(video_frame); 
246                         muxer_.push_audio(audio_frame);                                                                                 
247                         
248                         // POLL
249
250                         auto frame = core::draw_frame::late();
251                         if(!muxer_.empty())
252                         {
253                                 frame = std::move(muxer_.front());
254                                 muxer_.pop();
255
256                                 if(!frame_buffer_.try_push(frame))
257                                 {
258                                         auto dummy = core::draw_frame::empty();
259                                         frame_buffer_.try_pop(dummy);
260                                         frame_buffer_.try_push(frame);
261                                                 
262                                         graph_->set_tag("dropped-frame");
263                                 }
264                         }
265                         
266                         graph_->set_value("frame-time", frame_timer.elapsed()*out_format_desc_.fps*0.5);        
267                         monitor_subject_ << core::monitor::message("/profiler/time") % frame_timer.elapsed() % out_format_desc_.fps;
268
269                         graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      
270                         monitor_subject_ << core::monitor::message("/buffer") % frame_buffer_.size() % frame_buffer_.capacity();
271                 }
272                 catch(...)
273                 {
274                         exception_ = std::current_exception();
275                         return E_FAIL;
276                 }
277
278                 return S_OK;
279         }
280         
281         core::draw_frame get_frame()
282         {
283                 if(exception_ != nullptr)
284                         std::rethrow_exception(exception_);
285                 
286                 core::draw_frame frame = core::draw_frame::late();
287                 if(!frame_buffer_.try_pop(frame))
288                         graph_->set_tag("late-frame");
289                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      
290                 return frame;
291         }
292         
293         std::wstring print() const
294         {
295                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"|" + in_format_desc_.name + L"]";
296         }
297
298         core::monitor::subject& monitor_output()
299         {
300                 return monitor_subject_;
301         }
302 };
303         
304 class decklink_producer_proxy : public core::frame_producer_base
305 {               
306         std::unique_ptr<decklink_producer>      producer_;
307         const uint32_t                                          length_;
308         executor                                                        executor_;
309 public:
310         explicit decklink_producer_proxy(const core::video_format_desc& in_format_desc,
311                                                                          const spl::shared_ptr<core::frame_factory>& frame_factory, 
312                                                                          const core::video_format_desc& out_format_desc, 
313                                                                          int device_index,
314                                                                          const std::wstring& filter_str, uint32_t length)
315                 : executor_(L"decklink_producer[" + boost::lexical_cast<std::wstring>(device_index) + L"]")
316                 , length_(length)
317         {
318                 executor_.invoke([=]
319                 {
320                         CoInitialize(nullptr);
321                         producer_.reset(new decklink_producer(in_format_desc, device_index, frame_factory, out_format_desc, filter_str));
322                 });
323         }
324
325         ~decklink_producer_proxy()
326         {               
327                 executor_.invoke([=]
328                 {
329                         producer_.reset();
330                         CoUninitialize();
331                 });
332         }
333
334         core::monitor::subject& monitor_output()
335         {
336                 return producer_->monitor_output();
337         }
338         
339         // frame_producer
340                                 
341         core::draw_frame receive_impl() override
342         {               
343                 return producer_->get_frame();
344         }
345
346         core::constraints& pixel_constraints() override
347         {
348                 return producer_->pixel_constraints();
349         }
350                         
351         uint32_t nb_frames() const override
352         {
353                 return length_;
354         }
355         
356         std::wstring print() const override
357         {
358                 return producer_->print();
359         }
360         
361         std::wstring name() const override
362         {
363                 return L"decklink";
364         }
365
366         boost::property_tree::wptree info() const override
367         {
368                 boost::property_tree::wptree info;
369                 info.add(L"type", L"decklink");
370                 return info;
371         }
372 };
373
374 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)
375 {
376         if(params.empty() || !boost::iequals(params[0], "decklink"))
377                 return core::frame_producer::empty();
378
379         auto device_index       = get_param(L"DEVICE", params, -1);
380         if(device_index == -1)
381                 device_index = boost::lexical_cast<int>(params.at(1));
382         
383         auto filter_str         = get_param(L"FILTER", params);         
384         auto length                     = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());   
385         auto in_format_desc = core::video_format_desc(get_param(L"FORMAT", params, L"INVALID"));
386                 
387         if(in_format_desc.format == core::video_format::invalid)
388                 in_format_desc = out_format_desc;
389                         
390         return create_destroy_proxy(spl::make_shared<decklink_producer_proxy>(in_format_desc, frame_factory, out_format_desc, device_index, filter_str, length));
391 }
392
393 }}