]> git.sesse.net Git - casparcg/blob - modules/decklink/producer/decklink_producer.cpp
dd932f2a0a4a35dd006660c21c250eee9938da42
[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/util/util.h"\r
29 #include "../../ffmpeg/producer/muxer/frame_muxer.h"\r
30 \r
31 #include <common/concurrency/governor.h>\r
32 #include <common/diagnostics/graph.h>\r
33 #include <common/exception/exceptions.h>\r
34 #include <common/log/log.h>\r
35 #include <common/utility/co_init.h>\r
36 \r
37 #include <core/producer/frame/frame_factory.h>\r
38 #include <core/producer/frame/basic_frame.h>\r
39 \r
40 #include <agents.h>\r
41 \r
42 #include <boost/algorithm/string.hpp>\r
43 #include <boost/timer.hpp>\r
44 \r
45 #if defined(_MSC_VER)\r
46 #pragma warning (push)\r
47 #pragma warning (disable : 4244)\r
48 #endif\r
49 extern "C" \r
50 {\r
51         #define __STDC_CONSTANT_MACROS\r
52         #define __STDC_LIMIT_MACROS\r
53         #include <libavcodec/avcodec.h>\r
54 }\r
55 #if defined(_MSC_VER)\r
56 #pragma warning (pop)\r
57 #endif\r
58 \r
59 namespace caspar { namespace decklink {\r
60                 \r
61 class decklink_producer : public core::frame_producer, public IDeckLinkInputCallback\r
62 {               \r
63         safe_ptr<diagnostics::graph>                                                                                            graph_;\r
64         \r
65         const core::video_format_desc                                                                                           format_desc_;\r
66         const size_t                                                                                                                            device_index_;\r
67 \r
68         safe_ptr<core::basic_frame>                                                                                                     last_frame_;\r
69         const int64_t                                                                                                                           length_;\r
70         int64_t                                                                                                                                         frame_number_;\r
71         \r
72         CComPtr<IDeckLink>                                                                                                                      decklink_;\r
73         CComQIPtr<IDeckLinkInput>                                                                                                       input_;\r
74 \r
75         const std::wstring                                                                                                                      model_name_;\r
76 \r
77         Concurrency::unbounded_buffer<ffmpeg::frame_muxer2::video_source_element_t>     video_;\r
78         Concurrency::unbounded_buffer<ffmpeg::frame_muxer2::audio_source_element_t>     audio_;\r
79         Concurrency::unbounded_buffer<ffmpeg::frame_muxer2::target_element_t>           frames_;\r
80                         \r
81         ffmpeg::frame_muxer2                                                                                                            muxer_;\r
82                 \r
83         governor                                                                                                                                        governor_;\r
84 \r
85 public:\r
86         decklink_producer(const co_init& com, 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
87                 : format_desc_(format_desc)\r
88                 , device_index_(device_index)\r
89                 , length_(length)\r
90                 , frame_number_(0)\r
91                 , decklink_(get_device(device_index))\r
92                 , input_(decklink_)\r
93                 , model_name_(get_model_name(decklink_))\r
94                 , muxer_(&video_, &audio_, frames_, format_desc.fps, frame_factory, filter_str)\r
95                 , governor_(1)\r
96         {               \r
97                 graph_->add_guide("tick-time", 0.5);\r
98                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
99                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));\r
100                 graph_->set_color("frame-time", diagnostics::color(1.0f, 0.0f, 0.0f));\r
101                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
102                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
103                 graph_->set_text(narrow(print()));\r
104                 diagnostics::register_graph(graph_);\r
105                 \r
106                 auto display_mode = get_display_mode(input_, format_desc_.format, bmdFormat8BitYUV, bmdVideoInputFlagDefault);\r
107                 \r
108                 Concurrency::scoped_oversubcription_token oversubscribe;\r
109                 \r
110                 // NOTE: bmdFormat8BitARGB is currently not supported by any decklink card. (2011-05-08)\r
111                 if(FAILED(input_->EnableVideoInput(display_mode, bmdFormat8BitYUV, 0))) \r
112                         BOOST_THROW_EXCEPTION(caspar_exception() \r
113                                                                         << msg_info(narrow(print()) + " Could not enable video input.")\r
114                                                                         << boost::errinfo_api_function("EnableVideoInput"));\r
115 \r
116                 if(FAILED(input_->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType32bitInteger, format_desc_.audio_channels))) \r
117                         BOOST_THROW_EXCEPTION(caspar_exception() \r
118                                                                         << msg_info(narrow(print()) + " Could not enable audio input.")\r
119                                                                         << boost::errinfo_api_function("EnableAudioInput"));\r
120                         \r
121                 if (FAILED(input_->SetCallback(this)) != S_OK)\r
122                         BOOST_THROW_EXCEPTION(caspar_exception() \r
123                                                                         << msg_info(narrow(print()) + " Failed to set input callback.")\r
124                                                                         << boost::errinfo_api_function("SetCallback"));\r
125                         \r
126                 if(FAILED(input_->StartStreams()))\r
127                         BOOST_THROW_EXCEPTION(caspar_exception() \r
128                                                                         << msg_info(narrow(print()) + " Failed to start input stream.")\r
129                                                                         << boost::errinfo_api_function("StartStreams"));\r
130 \r
131                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";\r
132         }\r
133 \r
134         ~decklink_producer()\r
135         {\r
136                 governor_.cancel();\r
137                 \r
138                 send(video_, ffmpeg::eof_video());\r
139                 send(audio_, ffmpeg::eof_audio());\r
140 \r
141                 Concurrency::scoped_oversubcription_token oversubscribe;\r
142                 if(input_ != nullptr) \r
143                 {\r
144                         input_->StopStreams();\r
145                         input_->DisableVideoInput();\r
146                 }\r
147 \r
148                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized.";\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* raw_video, IDeckLinkAudioInputPacket* raw_audio)\r
161         {       \r
162                 try\r
163                 {\r
164                         ticket_t ticket;\r
165                         if(!governor_.try_acquire(ticket))\r
166                         {\r
167                                 graph_->add_tag("dropped-frame");\r
168                                 return S_OK;\r
169                         }\r
170 \r
171                         CComPtr<IDeckLinkVideoInputFrame>  video = raw_video;\r
172                         CComPtr<IDeckLinkAudioInputPacket> audio = raw_audio;\r
173 \r
174                         void* bytes = nullptr;\r
175 \r
176                         if(!video || FAILED(video->GetBytes(&bytes)) || !bytes)\r
177                                 return S_OK;\r
178                         \r
179                         safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
180                         avcodec_get_frame_defaults(av_frame.get());\r
181                 \r
182                         av_frame = safe_ptr<AVFrame>(av_frame.get(), [av_frame, video, ticket](AVFrame*){});\r
183                                                                 \r
184                         av_frame->data[0]                       = reinterpret_cast<uint8_t*>(bytes);\r
185                         av_frame->linesize[0]           = video->GetRowBytes();                 \r
186                         av_frame->format                        = PIX_FMT_UYVY422;\r
187                         av_frame->width                         = video->GetWidth();\r
188                         av_frame->height                        = video->GetHeight();\r
189                         av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
190                         av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
191                                         \r
192                         Concurrency::send(video_, av_frame);\r
193 \r
194                         // It is assumed that audio is always equal or ahead of video.\r
195                         if(!audio || FAILED(audio->GetBytes(&bytes)) || !bytes)\r
196                                 Concurrency::send(audio_, make_safe<core::audio_buffer>(format_desc_.audio_samples_per_frame, 0));      \r
197                         else\r
198                         {\r
199                                 auto sample_frame_count = audio->GetSampleFrameCount();\r
200                                 auto audio_data = reinterpret_cast<int32_t*>(bytes);\r
201                                 auto audio_buffer = make_safe<core::audio_buffer>(audio_data, audio_data + sample_frame_count*format_desc_.audio_channels);                     \r
202                                 audio_buffer = safe_ptr<core::audio_buffer>(audio_buffer.get(), [audio_buffer, audio, ticket](core::audio_buffer*){});\r
203                                 Concurrency::send(audio_, audio_buffer);\r
204                         }\r
205                 }\r
206                 catch(...)\r
207                 {\r
208                         CASPAR_LOG_CURRENT_EXCEPTION();\r
209                         return E_FAIL;\r
210                 }\r
211                 \r
212                 return S_OK;\r
213         }\r
214                 \r
215         virtual safe_ptr<core::basic_frame> receive(int)\r
216         {\r
217                 auto frame = core::basic_frame::late();\r
218 \r
219                 try\r
220                 {\r
221                         if(frame_number_ > length_)\r
222                                 return core::basic_frame::eof();\r
223 \r
224                         last_frame_ = frame = Concurrency::receive(frames_, 10).first;\r
225                         ++frame_number_;\r
226                 }\r
227                 catch(Concurrency::operation_timed_out&)\r
228                 {               \r
229                         graph_->add_tag("underflow");   \r
230                 }\r
231 \r
232                 return frame;\r
233         }\r
234 \r
235         virtual safe_ptr<core::basic_frame> last_frame() const\r
236         {\r
237                 return disable_audio(last_frame_);\r
238         }\r
239         \r
240         virtual int64_t nb_frames() const \r
241         {\r
242                 return length_;\r
243         }\r
244         \r
245         virtual std::wstring print() const\r
246         {\r
247                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
248         }\r
249 };\r
250         \r
251 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
252 {\r
253         if(params.empty() || !boost::iequals(params[0], "decklink"))\r
254                 return core::frame_producer::empty();\r
255         \r
256         std::vector<std::wstring> params2 = params;\r
257         std::for_each(std::begin(params2), std::end(params2), std::bind(&boost::to_upper<std::wstring>, std::placeholders::_1, std::locale()));\r
258 \r
259         auto device_index       = core::get_param(L"DEVICE", params2, 1);\r
260         auto filter_str         = core::get_param<std::wstring>(L"FILTER", params2, L"");       \r
261         auto length                     = core::get_param(L"LENGTH", params2, std::numeric_limits<int64_t>::max());     \r
262         \r
263         boost::replace_all(filter_str, L"DEINTERLACE", L"YADIF=0:-1");\r
264         boost::replace_all(filter_str, L"DEINTERLACE_BOB", L"YADIF=1:-1");\r
265 \r
266         auto format_desc        = core::video_format_desc::get(core::get_param<std::wstring>(L"FORMAT", params2, L"INVALID"));\r
267 \r
268         if(format_desc.format == core::video_format::invalid)\r
269                 format_desc = frame_factory->get_video_format_desc();\r
270                         \r
271         co_init com;\r
272         return make_safe<decklink_producer>(com, frame_factory, format_desc, device_index, filter_str, length);\r
273 }\r
274 \r
275 }}