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