]> git.sesse.net Git - casparcg/blob - modules/bluefish/consumer/bluefish_consumer.cpp
* Enforce help descriptions for consumers in code.
[casparcg] / modules / bluefish / consumer / bluefish_consumer.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 "bluefish_consumer.h"
25 #include "../util/blue_velvet.h"
26 #include "../util/memory.h"
27
28 #include <core/video_format.h>
29 #include <core/frame/frame.h>
30 #include <core/help/help_repository.h>
31 #include <core/help/help_sink.h>
32
33 #include <common/executor.h>
34 #include <common/diagnostics/graph.h>
35 #include <common/array.h>
36 #include <common/memshfl.h>
37 #include <common/param.h>
38
39 #include <core/consumer/frame_consumer.h>
40 #include <core/mixer/audio/audio_util.h>
41
42 #include <tbb/concurrent_queue.h>
43
44 #include <common/assert.h>
45 #include <boost/lexical_cast.hpp>
46 #include <boost/timer.hpp>
47 #include <boost/range/algorithm.hpp>
48 #include <boost/property_tree/ptree.hpp>
49 #include <boost/algorithm/string.hpp>
50
51 #include <asmlib.h>
52
53 #include <memory>
54 #include <array>
55
56 namespace caspar { namespace bluefish { 
57                         
58 struct bluefish_consumer : boost::noncopyable
59 {
60         spl::shared_ptr<CBlueVelvet4>                           blue_;
61         const unsigned int                                      device_index_;
62         const core::video_format_desc           format_desc_;
63         const int                                                       channel_index_;
64
65         const std::wstring                                      model_name_;
66
67         spl::shared_ptr<diagnostics::graph>             graph_;
68         boost::timer                                            frame_timer_;
69         boost::timer                                            tick_timer_;
70         boost::timer                                            sync_timer_;    
71                         
72         unsigned int                                            vid_fmt_;
73
74         std::array<blue_dma_buffer_ptr, 4>      reserved_frames_;       
75         tbb::concurrent_bounded_queue<core::const_frame> frame_buffer_;
76         
77         const bool                                                      embedded_audio_;
78         const bool                                                      key_only_;
79                 
80         executor                                                        executor_;
81 public:
82         bluefish_consumer(const core::video_format_desc& format_desc, int device_index, bool embedded_audio, bool key_only, int channel_index) 
83                 : blue_(create_blue(device_index))
84                 , device_index_(device_index)
85                 , format_desc_(format_desc) 
86                 , channel_index_(channel_index)
87                 , model_name_(get_card_desc(*blue_))
88                 , vid_fmt_(get_video_mode(*blue_, format_desc))
89                 , embedded_audio_(embedded_audio)
90                 , key_only_(key_only)
91                 , executor_(print())
92         {
93                 executor_.set_capacity(1);
94
95                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
96                 graph_->set_color("sync-time", diagnostics::color(1.0f, 0.0f, 0.0f));
97                 graph_->set_color("frame-time", diagnostics::color(0.5f, 1.0f, 0.2f));
98                 graph_->set_text(print());
99                 diagnostics::register_graph(graph_);
100                         
101                 //Setting output Video mode
102                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_MODE, vid_fmt_))) 
103                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set videomode."));
104
105                 //Select Update Mode for output
106                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_UPDATE_TYPE, UPD_FMT_FRAME))) 
107                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set update type."));
108         
109                 disable_video_output();
110
111                 //Enable dual link output
112                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_DUAL_LINK_OUTPUT, 1)))
113                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to enable dual link."));
114
115                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_DUAL_LINK_OUTPUT_SIGNAL_FORMAT_TYPE, Signal_FormatType_4224)))
116                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set dual link format type to 4:2:2:4."));
117                         
118                 //Select output memory format
119                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_MEMORY_FORMAT, MEM_FMT_ARGB_PC))) 
120                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set memory format."));
121                 
122                 //Select image orientation
123                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_IMAGE_ORIENTATION, ImageOrientation_Normal)))
124                         CASPAR_LOG(warning) << print() << L" Failed to set image orientation to normal.";       
125
126                 // Select data range
127                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_RGB_DATA_RANGE, CGR_RANGE))) 
128                         CASPAR_LOG(warning) << print() << L" Failed to set RGB data range to CGR.";     
129                 
130                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_PREDEFINED_COLOR_MATRIX, vid_fmt_ == VID_FMT_PAL ? MATRIX_601_CGR : MATRIX_709_CGR)))
131                         CASPAR_LOG(warning) << print() << L" Failed to set colormatrix to " << (vid_fmt_ == VID_FMT_PAL ? L"601 CGR" : L"709 CGR") << L".";
132
133                 if(!embedded_audio_)
134                 {
135                         if(BLUE_FAIL(set_card_property(blue_, EMBEDEDDED_AUDIO_OUTPUT, 0))) 
136                                 CASPAR_LOG(warning) << TEXT("BLUECARD ERROR: Failed to disable embedded audio.");                       
137                         CASPAR_LOG(info) << print() << TEXT(" Disabled embedded-audio.");
138                 }
139                 else
140                 {
141                         if(BLUE_FAIL(set_card_property(blue_, EMBEDEDDED_AUDIO_OUTPUT, blue_emb_audio_enable | blue_emb_audio_group1_enable))) 
142                                 CASPAR_LOG(warning) << print() << TEXT(" Failed to enable embedded audio.");                    
143                         CASPAR_LOG(info) << print() << TEXT(" Enabled embedded-audio.");
144                 }
145                 
146                 if (blue_->has_output_key()) 
147                 {
148                         int dummy = TRUE; int v4444 = FALSE; int invert = FALSE; int white = FALSE;
149                         blue_->set_output_key(dummy, v4444, invert, white);
150                 }
151
152                 if(blue_->GetHDCardType(device_index_) != CRD_HD_INVALID) 
153                         blue_->Set_DownConverterSignalType(vid_fmt_ == VID_FMT_PAL ? SD_SDI : HD_SDI);  
154         
155                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_OUTPUT_ENGINE, VIDEO_ENGINE_FRAMESTORE))) 
156                         CASPAR_LOG(warning) << print() << TEXT(" Failed to set video engine."); 
157                 
158                 enable_video_output();
159                                                 
160                 int n = 0;
161                 boost::range::generate(reserved_frames_, [&]{return std::make_shared<blue_dma_buffer>(static_cast<int>(format_desc_.size), n++);});
162         }
163
164         ~bluefish_consumer()
165         {
166                 try
167                 {
168                         executor_.invoke([&]
169                         {
170                                 disable_video_output();
171                                 blue_->device_detach();         
172                         });
173                 }
174                 catch(...)
175                 {
176                         CASPAR_LOG_CURRENT_EXCEPTION();
177                 }
178         }
179         
180         void enable_video_output()
181         {
182                 if(!BLUE_PASS(set_card_property(blue_, VIDEO_BLACKGENERATOR, 0)))
183                         CASPAR_LOG(error) << print() << TEXT(" Failed to disable video output.");       
184         }
185
186         void disable_video_output()
187         {
188                 blue_->video_playback_stop(0,0);
189                 if(!BLUE_PASS(set_card_property(blue_, VIDEO_BLACKGENERATOR, 1)))
190                         CASPAR_LOG(error)<< print() << TEXT(" Failed to disable video output.");                
191         }
192         
193         std::future<bool> send(core::const_frame& frame)
194         {                                       
195                 return executor_.begin_invoke([=]() -> bool
196                 {
197                         try
198                         {       
199                                 display_frame(frame);                           
200                                 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()*format_desc_.fps*0.5));
201                                 tick_timer_.restart();
202                         }
203                         catch(...)
204                         {
205                                 CASPAR_LOG_CURRENT_EXCEPTION();
206                         }
207
208                         return true;
209                 });
210         }
211
212         void display_frame(core::const_frame frame)
213         {
214                 // Sync
215
216                 sync_timer_.restart();
217                 unsigned long n_field = 0;
218                 blue_->wait_output_video_synch(UPD_FMT_FRAME, n_field);
219                 graph_->set_value("sync-time", sync_timer_.elapsed()*format_desc_.fps*0.5);
220                 
221                 frame_timer_.restart();         
222
223                 // Copy to local buffers
224                 
225                 if(!frame.image_data().empty())
226                 {
227                         if(key_only_)                                           
228                                 aligned_memshfl(reserved_frames_.front()->image_data(), frame.image_data().begin(), frame.image_data().size(), 0x0F0F0F0F, 0x0B0B0B0B, 0x07070707, 0x03030303);
229                         else
230                                 A_memcpy(reserved_frames_.front()->image_data(), frame.image_data().begin(), frame.image_data().size());
231                 }
232                 else
233                         A_memset(reserved_frames_.front()->image_data(), 0, reserved_frames_.front()->image_size());
234                                                                 
235
236                 // Send and display
237
238                 if(embedded_audio_)
239                 {               
240                         auto frame_audio = core::audio_32_to_24(frame.audio_data());                    
241                         encode_hanc(reinterpret_cast<BLUE_UINT32*>(reserved_frames_.front()->hanc_data()), 
242                                                 frame_audio.data(), 
243                                                 static_cast<int>(frame.audio_data().size()/format_desc_.audio_channels), 
244                                                 static_cast<int>(format_desc_.audio_channels));
245                                                                 
246                         blue_->system_buffer_write_async(const_cast<uint8_t*>(reserved_frames_.front()->image_data()), 
247                                                                                         static_cast<unsigned long>(reserved_frames_.front()->image_size()), 
248                                                                                         nullptr, 
249                                                                                         BlueImage_HANC_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_IMAGE));
250
251                         blue_->system_buffer_write_async(reserved_frames_.front()->hanc_data(),
252                                                                                         static_cast<unsigned long>(reserved_frames_.front()->hanc_size()), 
253                                                                                         nullptr,                 
254                                                                                         BlueImage_HANC_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_HANC));
255
256                         if(BLUE_FAIL(blue_->render_buffer_update(BlueBuffer_Image_HANC(reserved_frames_.front()->id()))))
257                                 CASPAR_LOG(warning) << print() << TEXT(" render_buffer_update failed.");
258                 }
259                 else
260                 {
261                         blue_->system_buffer_write_async(const_cast<uint8_t*>(reserved_frames_.front()->image_data()),
262                                                                                         static_cast<unsigned long>(reserved_frames_.front()->image_size()), 
263                                                                                         nullptr,                 
264                                                                                         BlueImage_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_IMAGE));
265                         
266                         if(BLUE_FAIL(blue_->render_buffer_update(BlueBuffer_Image(reserved_frames_.front()->id()))))
267                                 CASPAR_LOG(warning) << print() << TEXT(" render_buffer_update failed.");
268                 }
269
270                 boost::range::rotate(reserved_frames_, std::begin(reserved_frames_)+1);
271                 
272                 graph_->set_value("frame-time", static_cast<float>(frame_timer_.elapsed()*format_desc_.fps*0.5));
273         }
274
275         void encode_hanc(BLUE_UINT32* hanc_data, void* audio_data, int audio_samples, int audio_nchannels)
276         {       
277                 const auto sample_type = AUDIO_CHANNEL_24BIT | AUDIO_CHANNEL_LITTLEENDIAN;
278                 const auto emb_audio_flag = blue_emb_audio_enable | blue_emb_audio_group1_enable;
279                 
280                 hanc_stream_info_struct hanc_stream_info;
281                 memset(&hanc_stream_info, 0, sizeof(hanc_stream_info));
282                 
283                 hanc_stream_info.AudioDBNArray[0] = -1;
284                 hanc_stream_info.AudioDBNArray[1] = -1;
285                 hanc_stream_info.AudioDBNArray[2] = -1;
286                 hanc_stream_info.AudioDBNArray[3] = -1;
287                 hanc_stream_info.hanc_data_ptr    = hanc_data;
288                 hanc_stream_info.video_mode               = vid_fmt_;           
289                 
290                 if (!is_epoch_card(*blue_))
291                         encode_hanc_frame(&hanc_stream_info, audio_data, audio_nchannels, audio_samples, sample_type, emb_audio_flag);  
292                 else
293                         encode_hanc_frame_ex(blue_->has_video_cardtype(), &hanc_stream_info, audio_data, audio_nchannels, audio_samples, sample_type, emb_audio_flag);
294         }
295         
296         std::wstring print() const
297         {
298                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(channel_index_) + L"-" + 
299                         boost::lexical_cast<std::wstring>(device_index_) + L"|" +  format_desc_.name + L"]";
300         }
301 };
302
303 struct bluefish_consumer_proxy : public core::frame_consumer
304 {
305         core::monitor::subject                          monitor_subject_;
306
307         std::unique_ptr<bluefish_consumer>      consumer_;
308         const int                                                       device_index_;
309         const bool                                                      embedded_audio_;
310         const bool                                                      key_only_;
311
312         std::vector<int>                                        audio_cadence_;
313         core::video_format_desc                         format_desc_;
314
315 public:
316
317         bluefish_consumer_proxy(int device_index, bool embedded_audio, bool key_only)
318                 : device_index_(device_index)
319                 , embedded_audio_(embedded_audio)
320                 , key_only_(key_only)
321         {
322         }
323         
324         // frame_consumer
325         
326         void initialize(const core::video_format_desc& format_desc, int channel_index) override
327         {
328                 format_desc_ = format_desc;
329                 audio_cadence_ = format_desc.audio_cadence;
330
331                 consumer_.reset();
332                 consumer_.reset(new bluefish_consumer(format_desc, device_index_, embedded_audio_, key_only_, channel_index));
333         }
334         
335         std::future<bool> send(core::const_frame frame) override
336         {
337                 CASPAR_VERIFY(audio_cadence_.front() * format_desc_.audio_channels == static_cast<size_t>(frame.audio_data().size()));
338                 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
339                 return consumer_->send(frame);
340         }
341                 
342         std::wstring print() const override
343         {
344                 return consumer_ ? consumer_->print() : L"[bluefish_consumer]";
345         }
346
347         std::wstring name() const override
348         {
349                 return L"bluefish";
350         }
351
352         boost::property_tree::wptree info() const override
353         {
354                 boost::property_tree::wptree info;
355                 info.add(L"type", L"bluefish");
356                 info.add(L"key-only", key_only_);
357                 info.add(L"device", device_index_);
358                 info.add(L"embedded-audio", embedded_audio_);
359                 return info;
360         }
361
362         int buffer_depth() const override
363         {
364                 return 1;
365         }
366         
367         int index() const override
368         {
369                 return 400 + device_index_;
370         }
371
372         core::monitor::subject& monitor_output()
373         {
374                 return monitor_subject_;
375         }
376 };      
377
378
379 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
380 {
381         sink.short_description(L"Sends video on an SDI output using Bluefish video cards.");
382         sink.syntax(L"BLUEFISH {[device_index:int]|1} {[embedded_audio:EMBEDDED_AUDIO]} {[key_only:KEY_ONLY]}");
383         sink.para()
384                 ->text(L"Sends video on an SDI output using Bluefish video cards. Multiple video cards can be ")
385                 ->text(L"installed in the same machine and used at the same time, they will be addressed via ")
386                 ->text(L"different ")->code(L"device_index")->text(L" parameters.");
387         sink.para()->text(L"Specify ")->code(L"embedded_audio")->text(L" to embed audio into the SDI signal.");
388         sink.para()
389                 ->text(L"Specifying ")->code(L"key_only")->text(L" will extract only the alpha channel from the ")
390                 ->text(L"channel. This is useful when you have two SDI video cards, and neither has native support ")
391                 ->text(L"for separate fill/key output");
392         sink.para()->text(L"Examples:");
393         sink.example(L">> ADD 1 BLUEFISH", L"uses the default device_index of 1.");
394         sink.example(L">> ADD 1 BLUEFISH 2", L"for device_index 2.");
395         sink.example(
396                 L">> ADD 1 BLUEFISH 1 EMBEDDED_AUDIO\n"
397                 L">> ADD 1 BLUEFISH 2 KEY_ONLY", L"uses device with index 1 as fill output with audio and device with index 2 as key output.");
398 }
399
400 spl::shared_ptr<core::frame_consumer> create_consumer(
401                 const std::vector<std::wstring>& params, core::interaction_sink*)
402 {
403         if(params.size() < 1 || !boost::iequals(params.at(0), L"BLUEFISH"))
404                 return core::frame_consumer::empty();
405
406         const auto device_index = params.size() > 1 ? boost::lexical_cast<int>(params.at(1)) : 1;
407
408         const auto embedded_audio       = contains_param(L"EMBEDDED_AUDIO", params);
409         const auto key_only                     = contains_param(L"KEY_ONLY", params);
410
411         return spl::make_shared<bluefish_consumer_proxy>(device_index, embedded_audio, key_only);
412 }
413
414 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(
415                 const boost::property_tree::wptree& ptree, core::interaction_sink*)
416 {       
417         const auto device_index         = ptree.get(L"device",                  1);
418         const auto embedded_audio       = ptree.get(L"embedded-audio",  false);
419         const auto key_only                     = ptree.get(L"key-only",                false);
420
421         return spl::make_shared<bluefish_consumer_proxy>(device_index, embedded_audio, key_only);
422 }
423
424 }}