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