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