]> git.sesse.net Git - casparcg/blob - modules/bluefish/consumer/bluefish_consumer.cpp
Update previous files to be more in line with CasparCG coding styles.
[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/frame/audio_channel_layout.h>
31 #include <core/help/help_repository.h>
32 #include <core/help/help_sink.h>
33
34 #include <common/executor.h>
35 #include <common/diagnostics/graph.h>
36 #include <common/array.h>
37 #include <common/memshfl.h>
38 #include <common/param.h>
39
40 #include <core/consumer/frame_consumer.h>
41 #include <core/mixer/audio/audio_util.h>
42
43 #include <tbb/concurrent_queue.h>
44 #include <tbb/atomic.h>
45
46 #include <common/assert.h>
47 #include <boost/lexical_cast.hpp>
48 #include <boost/timer.hpp>
49 #include <boost/range/algorithm.hpp>
50 #include <boost/property_tree/ptree.hpp>
51 #include <boost/algorithm/string.hpp>
52
53 #include <asmlib.h>
54
55 #include <memory>
56 #include <array>
57
58 namespace caspar { namespace bluefish { 
59                 
60 enum class hardware_downstream_keyer_mode
61 {
62         disable = 0,
63         enable = 1,
64 };
65
66 enum class hardware_downstream_keyer_audio_source
67 {
68         SDIVideoInput = 1,
69         VideoOutputChannel = 2
70 };
71
72 enum class bluefish_hardware_output_channel
73 {
74         // ** current Bluefish hardware only support 4224  on channels A and C.
75         hardware_4224_channel_a,
76         hardware_4224_channel_c,
77         hardware_422_channel_a,
78         hardware_422_channel_b,
79         hardware_422_channel_c,
80         hardware_422_channel_d,
81         default_output_channel = hardware_422_channel_a
82 };
83
84 EBlueVideoChannel get_bluesdk_videochannel_from_streamid(bluefish_hardware_output_channel streamid)
85 {
86         /*This function would return the corresponding EBlueVideoChannel from the device output channel*/
87         switch (streamid)
88         {
89                 case bluefish_hardware_output_channel::hardware_422_channel_a:  return BLUE_VIDEO_OUTPUT_CHANNEL_A;
90                 case bluefish_hardware_output_channel::hardware_4224_channel_a: return BLUE_VIDEO_OUTPUT_CHANNEL_A;
91                 case bluefish_hardware_output_channel::hardware_422_channel_b:  return BLUE_VIDEO_OUTPUT_CHANNEL_B;
92                 case bluefish_hardware_output_channel::hardware_4224_channel_c: return BLUE_VIDEO_OUTPUT_CHANNEL_C;
93                 case bluefish_hardware_output_channel::hardware_422_channel_c:  return BLUE_VIDEO_OUTPUT_CHANNEL_C;
94                 case bluefish_hardware_output_channel::hardware_422_channel_d:  return BLUE_VIDEO_OUTPUT_CHANNEL_D;
95                 default: return BLUE_VIDEO_OUTPUT_CHANNEL_A;
96         }
97 }
98
99 bool get_videooutput_channel_routing_info_from_streamid(bluefish_hardware_output_channel streamid,
100         EEpochRoutingElements & channelSrcElement,
101         EEpochRoutingElements & sdioutputDstElement)
102 {
103         switch (streamid)
104         {
105         case bluefish_hardware_output_channel::hardware_4224_channel_a: channelSrcElement = EPOCH_SRC_OUTPUT_MEM_INTERFACE_CHA;
106                 sdioutputDstElement = EPOCH_DEST_SDI_OUTPUT_A;
107                 break;
108         case bluefish_hardware_output_channel::hardware_4224_channel_c: channelSrcElement = EPOCH_SRC_OUTPUT_MEM_INTERFACE_CHC;
109                 sdioutputDstElement = EPOCH_DEST_SDI_OUTPUT_C;
110                 break;
111         case bluefish_hardware_output_channel::hardware_422_channel_a:  channelSrcElement = EPOCH_SRC_OUTPUT_MEM_INTERFACE_CHA;
112                 sdioutputDstElement = EPOCH_DEST_SDI_OUTPUT_A;
113                 break;
114         case bluefish_hardware_output_channel::hardware_422_channel_b:  channelSrcElement = EPOCH_SRC_OUTPUT_MEM_INTERFACE_CHB;
115                 sdioutputDstElement = EPOCH_DEST_SDI_OUTPUT_B;
116                 break;
117         case bluefish_hardware_output_channel::hardware_422_channel_c:  channelSrcElement = EPOCH_SRC_OUTPUT_MEM_INTERFACE_CHC;
118                 sdioutputDstElement = EPOCH_DEST_SDI_OUTPUT_C;
119                 break;
120         case bluefish_hardware_output_channel::hardware_422_channel_d:  channelSrcElement = EPOCH_SRC_OUTPUT_MEM_INTERFACE_CHD;
121                 sdioutputDstElement = EPOCH_DEST_SDI_OUTPUT_D;
122                 break;
123         default: return false;
124         }
125         return true;
126 }
127
128 struct bluefish_consumer : boost::noncopyable
129 {
130         spl::shared_ptr<bvc_wrapper>                                                    blue_;
131         const unsigned int                                                                      device_index_;
132         const core::video_format_desc                                           format_desc_;
133         const core::audio_channel_layout                                        channel_layout_;
134         core::audio_channel_remapper                                            channel_remapper_;
135         const int                                                                                       channel_index_;
136
137         const std::wstring                                                                      model_name_;
138
139         spl::shared_ptr<diagnostics::graph>                                     graph_;
140         boost::timer                                                                            frame_timer_;
141         boost::timer                                                                            tick_timer_;
142         boost::timer                                                                            sync_timer_;    
143                         
144         unsigned int                                                                            vid_fmt_;
145
146         std::array<blue_dma_buffer_ptr, 4>                                      reserved_frames_;       
147         tbb::concurrent_bounded_queue<core::const_frame>        frame_buffer_;
148         tbb::atomic<int64_t>                                                            presentation_delay_millis_;
149         core::const_frame                                                                       previous_frame_                         = core::const_frame::empty();
150
151         const bool                                                                                      embedded_audio_;
152         const bool                                                                                      key_only_;
153                 
154         executor                                                                                        executor_;
155         hardware_downstream_keyer_mode                                          hardware_keyer_;
156         hardware_downstream_keyer_audio_source                          keyer_audio_source_;
157         bluefish_hardware_output_channel                                        device_output_channel_;
158 public:
159         bluefish_consumer(
160                         const core::video_format_desc& format_desc,
161                         const core::audio_channel_layout& in_channel_layout,
162                         const core::audio_channel_layout& out_channel_layout,
163                         int device_index,
164                         bool embedded_audio,
165                         bool key_only,
166                         hardware_downstream_keyer_mode keyer,
167                         hardware_downstream_keyer_audio_source keyer_audio_source,
168                         int channel_index,
169                         bluefish_hardware_output_channel device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_a)
170                 : blue_(create_blue(device_index))
171                 , device_index_(device_index)
172                 , format_desc_(format_desc)
173                 , channel_layout_(out_channel_layout)
174                 , channel_remapper_(in_channel_layout, out_channel_layout)
175                 , channel_index_(channel_index)
176                 , model_name_(get_card_desc(*blue_, device_index))
177                 , vid_fmt_(get_video_mode(*blue_, format_desc))
178                 , embedded_audio_(embedded_audio)
179                 , hardware_keyer_(keyer)
180                 , keyer_audio_source_(keyer_audio_source)
181                 , key_only_(key_only)
182                 , executor_(print())
183                 , device_output_channel_(device_output_channel)
184         {
185                 executor_.set_capacity(1);
186                 presentation_delay_millis_ = 0;
187
188                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
189                 graph_->set_color("sync-time", diagnostics::color(1.0f, 0.0f, 0.0f));
190                 graph_->set_color("frame-time", diagnostics::color(0.5f, 1.0f, 0.2f));
191                 graph_->set_text(print());
192                 diagnostics::register_graph(graph_);
193
194                 // Specify the video channel
195                 setup_hardware_output_channel();
196
197                 // Setting output Video mode
198                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_MODE, vid_fmt_)))
199                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set videomode."));
200
201                 // Select Update Mode for output
202                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_UPDATE_TYPE, UPD_FMT_FRAME)))
203                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set update type."));
204         
205                 disable_video_output();
206                 setup_hardware_output_channel_routing();
207                         
208                 //Select output memory format
209                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_MEMORY_FORMAT, MEM_FMT_ARGB_PC)))
210                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set memory format."));
211                 
212                 //Select image orientation
213                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_IMAGE_ORIENTATION, ImageOrientation_Normal)))
214                         CASPAR_LOG(warning) << print() << L" Failed to set image orientation to normal.";       
215
216                 // Select data range
217                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_RGB_DATA_RANGE, CGR_RANGE)))
218                         CASPAR_LOG(warning) << print() << L" Failed to set RGB data range to CGR.";     
219                 
220                 if(!embedded_audio_ || (hardware_keyer_ == hardware_downstream_keyer_mode::enable && keyer_audio_source_ == hardware_downstream_keyer_audio_source::VideoOutputChannel) )
221                 {
222                         if(BLUE_FAIL(blue_->set_card_property32(EMBEDEDDED_AUDIO_OUTPUT, 0)))
223                                 CASPAR_LOG(warning) << TEXT("BLUECARD ERROR: Failed to disable embedded audio.");                       
224                         CASPAR_LOG(info) << print() << TEXT(" Disabled embedded-audio.");
225                 }
226                 else
227                 {
228                         ULONG audio_value =
229                                 EMBEDDED_AUDIO_OUTPUT | blue_emb_audio_group1_enable;
230
231                         if (channel_layout_.num_channels > 4)
232                                 audio_value |= blue_emb_audio_group2_enable;
233
234                         if (channel_layout_.num_channels > 8)
235                                 audio_value |= blue_emb_audio_group3_enable;
236
237                         if (channel_layout_.num_channels > 12)
238                                 audio_value |= blue_emb_audio_group4_enable;
239
240                         if(BLUE_FAIL(blue_->set_card_property32(EMBEDEDDED_AUDIO_OUTPUT, audio_value)))
241                                 CASPAR_LOG(warning) << print() << TEXT(" Failed to enable embedded audio.");                    
242                         CASPAR_LOG(info) << print() << TEXT(" Enabled embedded-audio.");
243                 }
244
245                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_OUTPUT_ENGINE, VIDEO_ENGINE_FRAMESTORE)))
246                         CASPAR_LOG(warning) << print() << TEXT(" Failed to set video engine.");
247
248                 if (is_epoch_card((*blue_)))
249                         setup_hardware_downstream_keyer(hardware_keyer_, keyer_audio_source_);
250
251                 enable_video_output();
252                                                 
253                 int n = 0;
254                 boost::range::generate(reserved_frames_, [&]{return std::make_shared<blue_dma_buffer>(static_cast<int>(format_desc_.size), n++);});
255         }
256
257         ~bluefish_consumer()
258         {
259                 try
260                 {
261                         executor_.invoke([&]
262                         {
263                                 disable_video_output();
264                                 blue_->detach();                
265                         });
266                 }
267                 catch(...)
268                 {
269                         CASPAR_LOG_CURRENT_EXCEPTION();
270                 }
271         }
272
273         void setup_hardware_output_channel()
274         {
275                 // this function would be used to setup the logic video channel in the bluefish hardware
276                 EBlueVideoChannel outVidChannel = get_bluesdk_videochannel_from_streamid(device_output_channel_);
277                 if (is_epoch_card((*blue_)))
278                 {
279                         if (outVidChannel != BLUE_VIDEOCHANNEL_INVALID)
280                         {
281                                 if (BLUE_FAIL(blue_->set_card_property32(DEFAULT_VIDEO_OUTPUT_CHANNEL, outVidChannel)))
282                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(" Failed to set video stream."));
283                         }
284                 }
285         }
286
287         void setup_hardware_output_channel_routing()
288         {
289                 //This function would be used to setup the dual link and any other routing that would be required .
290
291                 if (is_epoch_card(*blue_))
292                 {
293                         EBlueVideoChannel blueVideoOutputChannel = get_bluesdk_videochannel_from_streamid(device_output_channel_);
294                         EEpochRoutingElements srcElement = (EEpochRoutingElements)0;
295                         EEpochRoutingElements dstElement = (EEpochRoutingElements)0;
296                         get_videooutput_channel_routing_info_from_streamid(device_output_channel_, srcElement, dstElement);
297                         bool duallink_4224_enabled = false;
298
299                         if (device_output_channel_ == bluefish_hardware_output_channel::hardware_4224_channel_a || device_output_channel_ == bluefish_hardware_output_channel::hardware_4224_channel_c)
300                                 duallink_4224_enabled = true;
301
302                         // Enable/Disable dual link output
303                         if (BLUE_FAIL(blue_->set_card_property32(VIDEO_DUAL_LINK_OUTPUT, duallink_4224_enabled)))
304                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to enable/disable dual link."));
305
306                         if (!duallink_4224_enabled)
307                         {
308                                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_DUAL_LINK_OUTPUT_SIGNAL_FORMAT_TYPE, Signal_FormatType_Independent_422)))
309                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set dual link format type to 4:2:2."));
310
311                                 ULONG routingValue = EPOCH_SET_ROUTING(srcElement, dstElement, BLUE_CONNECTOR_PROP_SINGLE_LINK);
312                                 if (BLUE_FAIL(blue_->set_card_property32(MR2_ROUTING, routingValue)))
313                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(" Failed to MR 2 routing."));
314
315                                 // If single link 422, but on second channel AND on Neutron we need to set Genlock to Aux.
316                                 if (is_epoch_neutron_1i2o_card((*blue_)))               
317                                 {
318                                         if (blueVideoOutputChannel == BLUE_VIDEO_OUTPUT_CHANNEL_B)
319                                         {
320                                                 ULONG genLockSource = BlueGenlockAux;
321                                                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_GENLOCK_SIGNAL, genLockSource)))
322                                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to set GenLock to Aux Input."));
323                                         }
324                                 }
325                                 if (is_epoch_neutron_3o_card((*blue_)))
326                                 {
327                                         if (blueVideoOutputChannel == BLUE_VIDEO_OUTPUT_CHANNEL_C)
328                                         {
329                                                 ULONG genLockSource = BlueGenlockAux;
330                                                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_GENLOCK_SIGNAL, genLockSource)))
331                                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to set GenLock to Aux Input."));
332                                         }
333                                 }
334                         }
335                         else            // dual Link IS enabled, ie. 4224 Fill and Key
336                         {
337                                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_DUAL_LINK_OUTPUT_SIGNAL_FORMAT_TYPE, Signal_FormatType_4224)))
338                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to set dual link format type to 4:2:2:4."));
339
340                                 if (is_epoch_neutron_1i2o_card((*blue_)))               // Neutron cards require setting the Genlock conector to Aux to enable them to do Dual-Link
341                                 {
342                                         ULONG genLockSource = BlueGenlockAux;
343                                         if (BLUE_FAIL(blue_->set_card_property32(VIDEO_GENLOCK_SIGNAL, genLockSource)))
344                                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to set GenLock to Aux Input."));
345                                 }
346                                 else if (is_epoch_neutron_3o_card((*blue_)))
347                                 {
348                                         if (blueVideoOutputChannel == BLUE_VIDEO_OUTPUT_CHANNEL_C)
349                                         {
350                                                 ULONG genLockSource = BlueGenlockAux;
351                                                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_GENLOCK_SIGNAL, genLockSource)))
352                                                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to set GenLock to Aux Input."));
353                                         }
354                                 }
355                         }
356                 }
357         }
358
359         void setup_hardware_downstream_keyer(hardware_downstream_keyer_mode keyer, hardware_downstream_keyer_audio_source audio_source)
360         {
361                 unsigned int keyer_control_value = 0, card_feature_value = 0;
362                 unsigned int card_connector_value = 0;
363                 unsigned int nOutputStreams = 0;
364                 unsigned int nInputStreams = 0;
365                 unsigned int nInputSDIConnector = 0;
366                 unsigned int nOutputSDIConnector = 0;
367                 if (BLUE_OK(blue_->get_card_property32(CARD_FEATURE_STREAM_INFO, card_feature_value)))
368                 {
369                         nOutputStreams = CARD_FEATURE_GET_SDI_OUTPUT_STREAM_COUNT(card_feature_value);
370                         nInputStreams = CARD_FEATURE_GET_SDI_INPUT_STREAM_COUNT(card_feature_value);
371                 }
372                 if (BLUE_OK(blue_->get_card_property32(CARD_FEATURE_CONNECTOR_INFO, card_connector_value)))
373                 {
374                         nOutputSDIConnector = CARD_FEATURE_GET_SDI_OUTPUT_CONNECTOR_COUNT(card_connector_value);
375                         nInputSDIConnector = CARD_FEATURE_GET_SDI_INPUT_CONNECTOR_COUNT(card_connector_value);
376                 }
377                 if (nInputSDIConnector == 0 || nInputStreams == 0)
378                         return;
379
380                 if (keyer == hardware_downstream_keyer_mode::disable)
381                 {
382                         keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_DISABLED(keyer_control_value);
383                         keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_DISABLE_OVER_BLACK(keyer_control_value);
384                 }
385                 else if (keyer == hardware_downstream_keyer_mode::enable)
386                 {
387                         unsigned int invalidVideoModeFlag = 0;
388                         unsigned int inputVideoSignal = 0;
389                         if (BLUE_FAIL(blue_->get_card_property32(INVALID_VIDEO_MODE_FLAG, invalidVideoModeFlag)))
390                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(" Failed to get invalid video mode flag"));
391
392                         keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_ENABLED(keyer_control_value);
393                         if (BLUE_FAIL(blue_->get_card_property32(VIDEO_INPUT_SIGNAL_VIDEO_MODE, inputVideoSignal)))
394                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(" Failed to get video input signal mode"));
395
396                         if (inputVideoSignal >= invalidVideoModeFlag)
397                                 keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_ENABLE_OVER_BLACK(keyer_control_value);
398                         else
399                                 keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_DISABLE_OVER_BLACK(keyer_control_value);
400                 
401                         // lock to input
402                         if (BLUE_FAIL(blue_->set_card_property32(VIDEO_GENLOCK_SIGNAL, BlueSDI_A_BNC)))
403                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(" Failed to set the genlock to the input for the HW keyer"));
404                 }
405
406                 if (audio_source == hardware_downstream_keyer_audio_source::SDIVideoInput && (keyer == hardware_downstream_keyer_mode::enable))
407                         keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_USE_INPUT_ANCILLARY(keyer_control_value);
408                 else if (audio_source == hardware_downstream_keyer_audio_source::VideoOutputChannel)
409                         keyer_control_value = VIDEO_ONBOARD_KEYER_SET_STATUS_USE_OUTPUT_ANCILLARY(keyer_control_value);
410
411                 if (BLUE_FAIL(blue_->set_card_property32(VIDEO_ONBOARD_KEYER, keyer_control_value)))
412                         CASPAR_LOG(error) << print() << TEXT(" Failed to set keyer control.");
413         }
414
415         void enable_video_output()
416         {
417                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_BLACKGENERATOR, 0)))
418                         CASPAR_LOG(error) << print() << TEXT(" Failed to disable video output.");       
419         }
420
421         void disable_video_output()
422         {
423                 blue_->video_playback_stop(0,0);
424                 if(BLUE_FAIL(blue_->set_card_property32(VIDEO_BLACKGENERATOR, 1)))
425                         CASPAR_LOG(error)<< print() << TEXT(" Failed to disable video output.");                
426         }
427         
428         std::future<bool> send(core::const_frame& frame)
429         {                                       
430                 return executor_.begin_invoke([=]() -> bool
431                 {
432                         try
433                         {       
434                                 display_frame(frame);                           
435                                 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()*format_desc_.fps*0.5));
436                                 tick_timer_.restart();
437                         }
438                         catch(...)
439                         {
440                                 CASPAR_LOG_CURRENT_EXCEPTION();
441                         }
442
443                         return true;
444                 });
445         }
446
447         void display_frame(core::const_frame frame)
448         {
449                 // Sync
450
451                 sync_timer_.restart();
452                 unsigned long n_field = 0;
453                 blue_->wait_video_output_sync(UPD_FMT_FRAME, n_field);
454                 graph_->set_value("sync-time", sync_timer_.elapsed()*format_desc_.fps*0.5);
455                 
456                 frame_timer_.restart();         
457
458                 if (previous_frame_ != core::const_frame::empty())
459                         presentation_delay_millis_ = previous_frame_.get_age_millis();
460
461                 previous_frame_ = frame;
462
463                 // Copy to local buffers
464                 
465                 if(!frame.image_data().empty())
466                 {
467                         if(key_only_)                                           
468                                 aligned_memshfl(reserved_frames_.front()->image_data(), frame.image_data().begin(), frame.image_data().size(), 0x0F0F0F0F, 0x0B0B0B0B, 0x07070707, 0x03030303);
469                         else
470                                 A_memcpy(reserved_frames_.front()->image_data(), frame.image_data().begin(), frame.image_data().size());
471                 }
472                 else
473                         A_memset(reserved_frames_.front()->image_data(), 0, reserved_frames_.front()->image_size());
474                                                                 
475
476                 // Send and display
477
478                 if(embedded_audio_)
479                 {
480                         auto remapped_audio     = channel_remapper_.mix_and_rearrange(frame.audio_data());
481                         auto frame_audio        = core::audio_32_to_24(remapped_audio);
482                         encode_hanc(reinterpret_cast<BLUE_UINT32*>(reserved_frames_.front()->hanc_data()), 
483                                                 frame_audio.data(), 
484                                                 static_cast<int>(frame.audio_data().size()/channel_layout_.num_channels), 
485                                                 static_cast<int>(channel_layout_.num_channels));
486                                                                 
487                         blue_->system_buffer_write(const_cast<uint8_t*>(reserved_frames_.front()->image_data()), 
488                                                                                         static_cast<unsigned long>(reserved_frames_.front()->image_size()),  
489                                                                                         BlueImage_HANC_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_IMAGE), 
490                                                                                         0);
491
492                         blue_->system_buffer_write(reserved_frames_.front()->hanc_data(),
493                                                                                         static_cast<unsigned long>(reserved_frames_.front()->hanc_size()),
494                                                                                         BlueImage_HANC_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_HANC),
495                                                                                         0);
496
497                         if(BLUE_FAIL(blue_->render_buffer_update(BlueBuffer_Image_HANC(reserved_frames_.front()->id()))))
498                                 CASPAR_LOG(warning) << print() << TEXT(" render_buffer_update failed.");
499                 }
500                 else
501                 {
502                         blue_->system_buffer_write(const_cast<uint8_t*>(reserved_frames_.front()->image_data()),
503                                                                                         static_cast<unsigned long>(reserved_frames_.front()->image_size()), 
504                                                                                         BlueImage_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_IMAGE),
505                                                                                         0);
506                         
507                         if(BLUE_FAIL(blue_->render_buffer_update(BlueBuffer_Image(reserved_frames_.front()->id()))))
508                                 CASPAR_LOG(warning) << print() << TEXT(" render_buffer_update failed.");
509                 }
510
511                 boost::range::rotate(reserved_frames_, std::begin(reserved_frames_)+1);
512                 
513                 graph_->set_value("frame-time", static_cast<float>(frame_timer_.elapsed()*format_desc_.fps*0.5));
514         }
515
516         void encode_hanc(BLUE_UINT32* hanc_data, void* audio_data, int audio_samples, int audio_nchannels)
517         {       
518                 const auto sample_type = AUDIO_CHANNEL_24BIT | AUDIO_CHANNEL_LITTLEENDIAN;
519                 auto emb_audio_flag = blue_emb_audio_enable | blue_emb_audio_group1_enable;
520
521                 if (audio_nchannels > 4)
522                         emb_audio_flag |= blue_emb_audio_group2_enable;
523
524                 if (audio_nchannels > 8)
525                         emb_audio_flag |= blue_emb_audio_group3_enable;
526
527                 if (audio_nchannels > 12)
528                         emb_audio_flag |= blue_emb_audio_group4_enable;
529                 
530                 hanc_stream_info_struct hanc_stream_info;
531                 memset(&hanc_stream_info, 0, sizeof(hanc_stream_info));
532                 
533                 hanc_stream_info.AudioDBNArray[0] = -1;
534                 hanc_stream_info.AudioDBNArray[1] = -1;
535                 hanc_stream_info.AudioDBNArray[2] = -1;
536                 hanc_stream_info.AudioDBNArray[3] = -1;
537                 hanc_stream_info.hanc_data_ptr    = hanc_data;
538                 hanc_stream_info.video_mode               = vid_fmt_;           
539                 
540                 int cardType = CRD_INVALID;
541                 blue_->query_card_type(cardType, device_index_);
542                 blue_->encode_hanc_frame(cardType, &hanc_stream_info, audio_data, audio_nchannels, audio_samples, sample_type, emb_audio_flag);
543         }
544         
545         std::wstring print() const
546         {
547                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(channel_index_) + L"-" + 
548                         boost::lexical_cast<std::wstring>(device_index_) + L"|" +  format_desc_.name + L"]";
549         }
550
551         int64_t presentation_delay_millis() const
552         {
553                 return presentation_delay_millis_;
554         }
555 };
556
557 struct bluefish_consumer_proxy : public core::frame_consumer
558 {
559         core::monitor::subject                                  monitor_subject_;
560
561         std::unique_ptr<bluefish_consumer>              consumer_;
562         const int                                                               device_index_;
563         const bool                                                              embedded_audio_;
564         const bool                                                              key_only_;
565
566         std::vector<int>                                                audio_cadence_;
567         core::video_format_desc                                 format_desc_;
568         core::audio_channel_layout                              in_channel_layout_              = core::audio_channel_layout::invalid();
569         core::audio_channel_layout                              out_channel_layout_;
570         hardware_downstream_keyer_mode                  hardware_keyer_;
571         hardware_downstream_keyer_audio_source  hardware_keyer_audio_source_;
572         bluefish_hardware_output_channel                hardware_output_channel_;
573
574 public:
575
576         bluefish_consumer_proxy(int device_index, 
577                                                         bool embedded_audio, 
578                                                         bool key_only, 
579                                                         hardware_downstream_keyer_mode keyer,
580                                                         hardware_downstream_keyer_audio_source keyer_audio_source,
581                                                         const core::audio_channel_layout& out_channel_layout,
582                                                         bluefish_hardware_output_channel hardware_output_channel)
583
584                 : device_index_(device_index)
585                 , embedded_audio_(embedded_audio)
586                 , key_only_(key_only)
587                 , hardware_keyer_(keyer)
588                 , hardware_keyer_audio_source_(keyer_audio_source)
589                 , out_channel_layout_(out_channel_layout)
590                 , hardware_output_channel_(hardware_output_channel)
591         {
592         }
593         
594         // frame_consumer
595         
596         void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout& channel_layout, int channel_index) override
597         {
598                 format_desc_            = format_desc;
599                 in_channel_layout_      = channel_layout;
600                 audio_cadence_          = format_desc.audio_cadence;
601
602                 if (out_channel_layout_ == core::audio_channel_layout::invalid())
603                         out_channel_layout_ = in_channel_layout_;
604
605                 consumer_.reset();
606                 consumer_.reset(new bluefish_consumer(  format_desc, 
607                                                                                                 in_channel_layout_, 
608                                                                                                 out_channel_layout_, 
609                                                                                                 device_index_, 
610                                                                                                 embedded_audio_, 
611                                                                                                 key_only_, 
612                                                                                                 hardware_keyer_,
613                                                                                                 hardware_keyer_audio_source_, 
614                                                                                                 channel_index,
615                                                                                                 hardware_output_channel_));
616         }
617         
618         std::future<bool> send(core::const_frame frame) override
619         {
620                 CASPAR_VERIFY(audio_cadence_.front() * in_channel_layout_.num_channels == static_cast<size_t>(frame.audio_data().size()));
621                 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
622                 return consumer_->send(frame);
623         }
624                 
625         std::wstring print() const override
626         {
627                 return consumer_ ? consumer_->print() : L"[bluefish_consumer]";
628         }
629
630         std::wstring name() const override
631         {
632                 return L"bluefish";
633         }
634
635         boost::property_tree::wptree info() const override
636         {
637                 boost::property_tree::wptree info;
638                 info.add(L"type", L"bluefish");
639                 info.add(L"key-only", key_only_);
640                 info.add(L"device", device_index_);
641                 info.add(L"embedded-audio", embedded_audio_);
642                 info.add(L"presentation-frame-age", presentation_frame_age_millis());
643                 return info;
644         }
645
646         int buffer_depth() const override
647         {
648                 return 1;
649         }
650         
651         int index() const override
652         {
653                 return 400 + device_index_;
654         }
655
656         int64_t presentation_frame_age_millis() const override
657         {
658                 return consumer_ ? consumer_->presentation_delay_millis() : 0;
659         }
660
661         core::monitor::subject& monitor_output()
662         {
663                 return monitor_subject_;
664         }
665 };      
666
667
668 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
669 {
670         sink.short_description(L"Sends video on an SDI output using Bluefish video cards.");
671         sink.syntax(L"BLUEFISH {[device_index:int]|1} {[embedded_audio:EMBEDDED_AUDIO]} {[key_only:KEY_ONLY]} {CHANNEL_LAYOUT [channel_layout:string]}");
672         sink.para()
673                 ->text(L"Sends video on an SDI output using Bluefish video cards. Multiple video cards can be ")
674                 ->text(L"installed in the same machine and used at the same time, they will be addressed via ")
675                 ->text(L"different ")->code(L"device_index")->text(L" parameters.");
676         sink.para()->text(L"Specify ")->code(L"embedded_audio")->text(L" to embed audio into the SDI signal.");
677         sink.para()
678                 ->text(L"Specifying ")->code(L"key_only")->text(L" will extract only the alpha channel from the ")
679                 ->text(L"channel. This is useful when you have two SDI video cards, and neither has native support ")
680                 ->text(L"for separate fill/key output");
681         sink.para()->text(L"Specify ")->code(L"channel_layout")->text(L" to output a different audio channel layout than the channel uses.");
682         sink.para()->text(L"Specify ")->code(L"BF_4224_CHANNELA")->text(L" to use channel A on the card to  be configured to output "
683                 L"4:2:2:4 with fill and key HD-SDI output's A and B on the card.\n"
684                 L"This is the default option\n");
685         sink.para()->text(L"Specify ")->code(L"BF_4224_CHANNELC")->text(L" to use channel C on the card to  be configured to output "
686                 L" 4:2:2:4 with fill and key  HD-SDI output's C and D on the card\n"
687                 L" Channel C 4:2:2:4 support is only available on 4 output variant of Supernova  and SupernovaS+ card\n");
688
689         sink.para()->text(L"Specify ")->code(L"ENABLE_KEYER")->text(L" to enable use of hardware keyer on the bluefish board.\n"
690                 L"\t\t\tUsing this option hardware keyer would key using \n "
691                 L"\t\t\tthe video input on the SDI as background layer \n"
692                 L"\t\t\tand graphics Generated by CasparCG as foreground layer");
693         sink.para()->text(L"Specify ")->code(L"DISABLE_KEYER")->text(L" this option to disable hardware keyer on the bluefish board");
694         sink.para()->text(L"Specify ")->code(L"KEYER_AUDIO_SOURCE_SDIINPUT")->text(L" to enable SDI embedded audio to be transparently passed through the keyer to the SDI output\n");
695         sink.para()->text(L"Specify ")->code(L"KEYER_AUDIO_SOURCE_OUTPUT_CHANNEL")->text(L" to enable keyer to pass the audio provided by CasparCG to the SDI output\n");
696
697         sink.para()->text(L"Examples:");
698         sink.example(L">> ADD 1 BLUEFISH", L"uses the default device_index of 1.");
699         sink.example(L">> ADD 1 BLUEFISH 2", L"for device_index 2.");
700         sink.example(
701                 L">> ADD 1 BLUEFISH 1 EMBEDDED_AUDIO\n"
702                 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.");
703
704 }
705
706
707 spl::shared_ptr<core::frame_consumer> create_consumer(  const std::vector<std::wstring>& params,
708                                                                                                                 core::interaction_sink*,
709                                                                                                                 std::vector<spl::shared_ptr<core::video_channel>> channels)
710 {
711         if(params.size() < 1 || !boost::iequals(params.at(0), L"BLUEFISH"))
712                 return core::frame_consumer::empty();
713
714         const auto device_index = params.size() > 1 ? boost::lexical_cast<int>(params.at(1)) : 1;
715
716         const auto embedded_audio       = contains_param(       L"EMBEDDED_AUDIO",      params);
717         const auto key_only                     = contains_param(       L"KEY_ONLY",            params);
718         const auto channel_layout       = get_param(            L"CHANNEL_LAYOUT",      params);
719         const auto device_stream        = contains_param(       L"SDI-STREAM",          params);
720
721         auto layout = core::audio_channel_layout::invalid();
722
723         if (!channel_layout.empty())
724         {
725                 auto found_layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout);
726
727                 if (!found_layout)
728                         CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Channel layout " + channel_layout + L" not found"));
729
730                 layout = *found_layout;
731         }
732         bluefish_hardware_output_channel device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_a;
733
734         if (contains_param(L"BLUE_4224_CHANNELA", params))
735                 device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_a;
736         else if (contains_param(L"BLUE_4224_CHANNELC", params))
737                 device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_c;
738         else if (contains_param(L"BLUE_422_CHANNELA", params))
739                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_a;
740         else if (contains_param(L"BLUE_422_CHANNELB", params))
741                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_b;
742         else if (contains_param(L"BLUE_422_CHANNELC", params))
743                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_c;
744         else if (contains_param(L"BLUE_422_CHANNELD", params))
745                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_d;
746
747         hardware_downstream_keyer_mode keyer = hardware_downstream_keyer_mode::disable;
748
749         if (contains_param(L"KEYER_DISABLED", params))
750                 keyer = hardware_downstream_keyer_mode::disable;
751         else if (contains_param(L"KEYER_ENABLED", params))
752                 keyer = hardware_downstream_keyer_mode::enable;
753
754         hardware_downstream_keyer_audio_source keyer_audio_source = hardware_downstream_keyer_audio_source::VideoOutputChannel;
755         if (contains_param(L"KEYER_AUDIO_SOURCE_SDIINPUT", params))
756                 keyer_audio_source = hardware_downstream_keyer_audio_source::SDIVideoInput;
757         else
758         if (contains_param(L"KEYER_AUDIO_SOURCE_OUTPUT_CHANNEL", params))
759                 keyer_audio_source = hardware_downstream_keyer_audio_source::VideoOutputChannel;
760
761         return spl::make_shared<bluefish_consumer_proxy>(device_index, embedded_audio, key_only, keyer, keyer_audio_source, layout, device_output_channel);
762 }
763
764 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(
765                                                                                         const boost::property_tree::wptree& ptree, core::interaction_sink*,
766                                                                                         std::vector<spl::shared_ptr<core::video_channel>> channels)
767 {       
768         const auto device_index         = ptree.get(                                            L"device",                      1);
769         const auto embedded_audio       = ptree.get(                                            L"embedded-audio",      false);
770         const auto key_only                     = ptree.get(                                            L"key-only",            false);
771         const auto channel_layout       = ptree.get_optional<std::wstring>(     L"channel-layout");
772         const auto hardware_keyer_value = ptree.get(L"hardware-keyer", L"disabled");
773         const auto keyer_audio_source_value = ptree.get(L"hardware-keyer-audio-source", L"videooutputchannel");
774         const auto device_stream = ptree.get(L"sdi-stream", L"blue_4224_channela");
775
776         auto layout = core::audio_channel_layout::invalid();
777
778         if (channel_layout)
779         {
780                 CASPAR_SCOPED_CONTEXT_MSG("/channel-layout")
781
782                 auto found_layout = core::audio_channel_layout_repository::get_default()->get_layout(*channel_layout);
783
784                 if (!found_layout)
785                         CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Channel layout " + *channel_layout + L" not found"));
786
787                 layout = *found_layout;
788         }
789
790         bluefish_hardware_output_channel device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_a;
791         if (device_stream == L"blue_4224_channela")
792                 device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_a;
793         else if (device_stream == L"blue_4224_channelc")
794                 device_output_channel = bluefish_hardware_output_channel::hardware_4224_channel_c;
795         else if (device_stream == L"blue_422_channela")
796                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_a;
797         else if (device_stream == L"blue_422_channelb")
798                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_b;
799         else if (device_stream == L"blue_422_channelc")
800                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_c;
801         else if (device_stream == L"blue_422_channeld")
802                 device_output_channel = bluefish_hardware_output_channel::hardware_422_channel_d;
803
804         hardware_downstream_keyer_mode keyer_mode = hardware_downstream_keyer_mode::disable;
805         if (hardware_keyer_value == L"disabled")
806         {
807                 keyer_mode = hardware_downstream_keyer_mode::disable;
808         }
809         else if (hardware_keyer_value == L"enabled")
810         {
811                 keyer_mode = hardware_downstream_keyer_mode::enable;
812         }
813
814         hardware_downstream_keyer_audio_source keyer_audio_source = hardware_downstream_keyer_audio_source::VideoOutputChannel;
815         if (keyer_audio_source_value == L"videooutputchannel")
816                 keyer_audio_source = hardware_downstream_keyer_audio_source::VideoOutputChannel;
817         else
818                 if (keyer_audio_source_value == L"sdivideoinput")
819                         keyer_audio_source = hardware_downstream_keyer_audio_source::SDIVideoInput;
820
821         return spl::make_shared<bluefish_consumer_proxy>(device_index, embedded_audio, key_only, keyer_mode, keyer_audio_source, layout, device_output_channel);
822 }
823
824 }}