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