]> git.sesse.net Git - casparcg/blob - modules/bluefish/consumer/bluefish_consumer.cpp
2.0.0.2: Use boost::timer instead of handwritten timer.
[casparcg] / modules / bluefish / consumer / bluefish_consumer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\r
5 *\r
6 *    CasparCG is free software: you can redistribute it and/or modify\r
7 *    it under the terms of the GNU General Public License as published by\r
8 *    the Free Software Foundation, either version 3 of the License, or\r
9 *    (at your option) any later version.\r
10 *\r
11 *    CasparCG is distributed in the hope that it will be useful,\r
12 *    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 *    GNU General Public License for more details.\r
15 \r
16 *    You should have received a copy of the GNU General Public License\r
17 *    along with CasparCG.  If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 */\r
20  \r
21 #include "../StdAfx.h"\r
22 \r
23 #include "bluefish_consumer.h"\r
24 #include "../util/util.h"\r
25 #include "../util/memory.h"\r
26 \r
27 #include <core/consumer/frame/read_frame.h>\r
28 \r
29 #include <common/concurrency/executor.h>\r
30 #include <common/diagnostics/graph.h>\r
31 #include <common/memory/memcpy.h>\r
32 #include <common/utility/timer.h>\r
33 \r
34 #include <tbb/concurrent_queue.h>\r
35 \r
36 #include <boost/timer.hpp>\r
37 \r
38 #include <BlueVelvet4.h>\r
39 #include <BlueHancUtils.h>\r
40 \r
41 #include <memory>\r
42 #include <array>\r
43 \r
44 namespace caspar { \r
45         \r
46 CBlueVelvet4* (*BlueVelvetFactory4)() = nullptr;\r
47 const char*     (*BlueVelvetVersion)() = nullptr;\r
48 BLUE_UINT32 (*encode_hanc_frame)(struct hanc_stream_info_struct * hanc_stream_ptr, void * audio_pcm_ptr,BLUE_UINT32 no_audio_ch,BLUE_UINT32 no_audio_samples,BLUE_UINT32 nTypeOfSample,BLUE_UINT32 emb_audio_flag) = nullptr;\r
49 BLUE_UINT32 (*encode_hanc_frame_ex)(BLUE_UINT32 card_type, struct hanc_stream_info_struct * hanc_stream_ptr, void * audio_pcm_ptr, BLUE_UINT32 no_audio_ch,     BLUE_UINT32 no_audio_samples, BLUE_UINT32 nTypeOfSample, BLUE_UINT32 emb_audio_flag) = nullptr;\r
50 \r
51 void blue_velvet_initialize()\r
52 {\r
53 #ifdef _DEBUG\r
54         auto module = LoadLibrary(L"BlueVelvet3_d.dll");\r
55 #else\r
56         auto module = LoadLibrary(L"BlueVelvet3.dll");\r
57 #endif\r
58         if(!module)\r
59                 BOOST_THROW_EXCEPTION(file_not_found() << msg_info("Could not find BlueVelvet3.dll"));\r
60         static std::shared_ptr<void> lib(module, FreeLibrary);\r
61         BlueVelvetFactory4 = reinterpret_cast<decltype(BlueVelvetFactory4)>(GetProcAddress(module, "BlueVelvetFactory4"));\r
62         BlueVelvetVersion = reinterpret_cast<decltype(BlueVelvetVersion)>(GetProcAddress(module, "BlueVelvetVersion"));\r
63 }\r
64 \r
65 void blue_hanc_initialize()\r
66 {\r
67 #ifdef _DEBUG\r
68         auto module = LoadLibrary(L"BlueHancUtils_d.dll");\r
69 #else\r
70         auto module = LoadLibrary(L"BlueHancUtils.dll");\r
71 #endif\r
72         if(!module)\r
73                 BOOST_THROW_EXCEPTION(file_not_found() << msg_info("Could not find BlueHancUtils.dll"));\r
74         static std::shared_ptr<void> lib(module, FreeLibrary);\r
75         encode_hanc_frame = reinterpret_cast<decltype(encode_hanc_frame)>(GetProcAddress(module, "encode_hanc_frame"));\r
76         encode_hanc_frame_ex = reinterpret_cast<decltype(encode_hanc_frame_ex)>(GetProcAddress(module, "encode_hanc_frame_ex"));\r
77 }\r
78 \r
79 void blue_initialize()\r
80 {\r
81         blue_velvet_initialize();\r
82         blue_hanc_initialize();\r
83 }\r
84                 \r
85 struct bluefish_consumer::implementation : boost::noncopyable\r
86 {\r
87         std::wstring            model_name_;\r
88         const unsigned int      device_index_;\r
89 \r
90         std::shared_ptr<diagnostics::graph> graph_;\r
91         boost::timer perf_timer_;\r
92 \r
93         boost::unique_future<void> active_;\r
94                         \r
95         std::shared_ptr<CBlueVelvet4> blue_;\r
96         \r
97         core::video_format_desc format_desc_;\r
98                 \r
99         unsigned long   mem_fmt_;\r
100         unsigned long   upd_fmt_;\r
101         EVideoMode              vid_fmt_; \r
102         unsigned long   res_fmt_; \r
103         unsigned long   engine_mode_;\r
104         \r
105         std::array<blue_dma_buffer_ptr, 3> reserved_frames_;    \r
106 \r
107         const bool embed_audio_;\r
108 \r
109         executor executor_;\r
110 public:\r
111         implementation::implementation(unsigned int device_index, bool embed_audio) \r
112                 : model_name_(L"BLUEFISH")\r
113                 , device_index_(device_index) \r
114                 , mem_fmt_(MEM_FMT_ARGB_PC)\r
115                 , upd_fmt_(UPD_FMT_FRAME)\r
116                 , vid_fmt_(VID_FMT_INVALID) \r
117                 , res_fmt_(RES_FMT_NORMAL) \r
118                 , engine_mode_(VIDEO_ENGINE_FRAMESTORE)         \r
119                 , embed_audio_(embed_audio)\r
120                 , executor_(print())\r
121         {\r
122                 if(!BlueVelvetFactory4 || (embed_audio_ && (!encode_hanc_frame || !encode_hanc_frame)))\r
123                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info("Bluefish drivers not found."));\r
124         }\r
125 \r
126         ~implementation()\r
127         {\r
128                 if(executor_.is_running())\r
129                 {\r
130                         executor_.invoke([&]\r
131                         {\r
132                                 disable_video_output();\r
133 \r
134                                 if(blue_)\r
135                                         blue_->device_detach();         \r
136                         });\r
137                 }\r
138                 \r
139                 CASPAR_LOG(info) << print() << L" Shutting down.";      \r
140         }\r
141 \r
142         void initialize(const core::video_format_desc& format_desc)\r
143         {               \r
144                 format_desc_ = format_desc;\r
145 \r
146                 blue_.reset(BlueVelvetFactory4());\r
147 \r
148                 if(BLUE_FAIL(blue_->device_attach(device_index_, FALSE))) \r
149                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to attach device."));\r
150         \r
151                 int videoCardType = blue_->has_video_cardtype();\r
152                 model_name_ = get_card_desc(videoCardType);\r
153 \r
154                 graph_ = diagnostics::create_graph(narrow(print()));\r
155                 graph_->add_guide("tick-time", 0.5);\r
156                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
157                         \r
158                 //void* pBlueDevice = blue_attach_to_device(1);\r
159                 //EBlueConnectorPropertySetting video_routing[1];\r
160                 //auto channel = BLUE_VIDEO_OUTPUT_CHANNEL_A;\r
161                 //video_routing[0].channel = channel;   \r
162                 //video_routing[0].propType = BLUE_CONNECTOR_PROP_SINGLE_LINK;\r
163                 //video_routing[0].connector = channel == BLUE_VIDEO_OUTPUT_CHANNEL_A ? BLUE_CONNECTOR_SDI_OUTPUT_A : BLUE_CONNECTOR_SDI_OUTPUT_B;\r
164                 //blue_set_connector_property(pBlueDevice, 1, video_routing);\r
165                 //blue_detach_from_device(&pBlueDevice);\r
166                 \r
167                 auto desiredVideoFormat = vid_fmt_from_video_format(format_desc_.format);\r
168                 int videoModeCount = blue_->count_video_mode();\r
169                 for(int videoModeIndex = 1; videoModeIndex <= videoModeCount; ++videoModeIndex) \r
170                 {\r
171                         EVideoMode videoMode = blue_->enum_video_mode(videoModeIndex);\r
172                         if(videoMode == desiredVideoFormat) \r
173                                 vid_fmt_ = videoMode;                   \r
174                 }\r
175                 if(vid_fmt_ == VID_FMT_INVALID)\r
176                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to set videomode."));\r
177                 \r
178                 // Set default video output channel\r
179                 //if(BLUE_FAIL(set_card_property(blue_, DEFAULT_VIDEO_OUTPUT_CHANNEL, channel)))\r
180                 //      CASPAR_LOG(error) << TEXT("BLUECARD ERROR: Failed to set default channel. (device ") << device_index_ << TEXT(")");\r
181 \r
182                 //Setting output Video mode\r
183                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_MODE, vid_fmt_))) \r
184                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to set videomode."));\r
185 \r
186                 //Select Update Mode for output\r
187                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_UPDATE_TYPE, upd_fmt_))) \r
188                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to set update type."));\r
189         \r
190                 disable_video_output();\r
191 \r
192                 //Enable dual link output\r
193                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_DUAL_LINK_OUTPUT, 1)))\r
194                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to enable dual link."));\r
195 \r
196                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_DUAL_LINK_OUTPUT_SIGNAL_FORMAT_TYPE, Signal_FormatType_4224)))\r
197                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to set dual link format type to 4:2:2:4."));\r
198                         \r
199                 //Select output memory format\r
200                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_MEMORY_FORMAT, mem_fmt_))) \r
201                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to set memory format."));\r
202                 \r
203                 //Select image orientation\r
204                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_IMAGE_ORIENTATION, ImageOrientation_Normal)))\r
205                         CASPAR_LOG(warning) << print() << TEXT(" Failed to set image orientation to normal.");  \r
206 \r
207                 // Select data range\r
208                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_RGB_DATA_RANGE, CGR_RANGE))) \r
209                         CASPAR_LOG(warning) << print() << TEXT(" Failed to set RGB data range to CGR.");        \r
210                 \r
211                 if(BLUE_FAIL(set_card_property(blue_, VIDEO_PREDEFINED_COLOR_MATRIX, vid_fmt_ == VID_FMT_PAL ? MATRIX_601_CGR : MATRIX_709_CGR)))\r
212                         CASPAR_LOG(warning) << print() << TEXT(" Failed to set colormatrix to ") << (vid_fmt_ == VID_FMT_PAL ? TEXT("601 CGR") : TEXT("709 CGR")) << TEXT(".");\r
213 \r
214                 if(!embed_audio_)\r
215                 {\r
216                         if(BLUE_FAIL(set_card_property(blue_, EMBEDEDDED_AUDIO_OUTPUT, 0))) \r
217                                 CASPAR_LOG(warning) << TEXT("BLUECARD ERROR: Failed to disable embedded audio.");                       \r
218                         CASPAR_LOG(info) << print() << TEXT(" Disabled embedded-audio.");\r
219                 }\r
220                 else\r
221                 {\r
222                         if(BLUE_FAIL(set_card_property(blue_, EMBEDEDDED_AUDIO_OUTPUT, blue_emb_audio_enable | blue_emb_audio_group1_enable))) \r
223                                 CASPAR_LOG(warning) << print() << TEXT(" Failed to enable embedded audio.");                    \r
224                         CASPAR_LOG(info) << print() << TEXT(" Enabled embedded-audio.");\r
225                 }\r
226                 \r
227                 if (blue_->has_output_key()) \r
228                 {\r
229                         int dummy = TRUE; int v4444 = FALSE; int invert = FALSE; int white = FALSE;\r
230                         blue_->set_output_key(dummy, v4444, invert, white);\r
231                 }\r
232 \r
233                 if(blue_->GetHDCardType(device_index_) != CRD_HD_INVALID) \r
234                         blue_->Set_DownConverterSignalType(vid_fmt_ == VID_FMT_PAL ? SD_SDI : HD_SDI);  \r
235         \r
236                 if(BLUE_FAIL(blue_->set_video_engine(engine_mode_)))\r
237                         BOOST_THROW_EXCEPTION(bluefish_exception() << msg_info(narrow(print()) + " Failed to set video engine."));\r
238 \r
239                 enable_video_output();\r
240                                                 \r
241                 for(size_t n = 0; n < reserved_frames_.size(); ++n)\r
242                         reserved_frames_[n] = std::make_shared<blue_dma_buffer>(format_desc_.size, n);          \r
243                                 \r
244                 executor_.start();\r
245                 active_ = executor_.begin_invoke([]{});\r
246 \r
247                 CASPAR_LOG(info) << print() << TEXT(" Successfully initialized for ") << format_desc_ << TEXT(".");\r
248         }\r
249                 \r
250         void enable_video_output()\r
251         {\r
252                 if(!BLUE_PASS(set_card_property(blue_, VIDEO_BLACKGENERATOR, 0)))\r
253                         CASPAR_LOG(error) << print() << TEXT(" Failed to disable video output.");       \r
254         }\r
255 \r
256         void disable_video_output()\r
257         {\r
258                 if(!BLUE_PASS(set_card_property(blue_, VIDEO_BLACKGENERATOR, 1)))\r
259                         CASPAR_LOG(error)<< print() << TEXT(" Failed to disable video output.");                \r
260         }\r
261 \r
262         virtual void send(const safe_ptr<const core::read_frame>& frame)\r
263         {                       \r
264                 static std::vector<short> silence(MAX_HANC_BUFFER_SIZE, 0);\r
265                 \r
266                 size_t audio_samples = static_cast<size_t>(48000.0 / format_desc_.fps);\r
267                 size_t audio_nchannels = 2;\r
268                 \r
269                 active_.get();\r
270                 active_ = executor_.begin_invoke([=]\r
271                 {\r
272                         try\r
273                         {\r
274                                 fast_memcpy(reserved_frames_.front()->image_data(), frame->image_data().begin(), frame->image_data().size());\r
275                                 \r
276                                 if(embed_audio_)\r
277                                 {               \r
278                                         auto frame_audio_data = frame->audio_data().empty() ? silence.data() : const_cast<short*>(frame->audio_data().begin());\r
279 \r
280                                         encode_hanc(reinterpret_cast<BLUE_UINT32*>(reserved_frames_.front()->hanc_data()), frame_audio_data, audio_samples, audio_nchannels);\r
281                                                                 \r
282                                         blue_->system_buffer_write_async(const_cast<unsigned char*>(reserved_frames_.front()->image_data()), \r
283                                                                                                         reserved_frames_.front()->image_size(), \r
284                                                                                                         nullptr, \r
285                                                                                                         BlueImage_HANC_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_IMAGE));\r
286 \r
287                                         blue_->system_buffer_write_async(reserved_frames_.front()->hanc_data(),\r
288                                                                                                         reserved_frames_.front()->hanc_size(), \r
289                                                                                                         nullptr,                 \r
290                                                                                                         BlueImage_HANC_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_HANC));\r
291 \r
292                                         if(BLUE_FAIL(blue_->render_buffer_update(BlueBuffer_Image_HANC(reserved_frames_.front()->id()))))\r
293                                                 CASPAR_LOG(warning) << print() << TEXT(" render_buffer_update failed.");\r
294                                 }\r
295                                 else\r
296                                 {\r
297                                         blue_->system_buffer_write_async(const_cast<unsigned char*>(reserved_frames_.front()->image_data()),\r
298                                                                                                         reserved_frames_.front()->image_size(), \r
299                                                                                                         nullptr,                 \r
300                                                                                                         BlueImage_DMABuffer(reserved_frames_.front()->id(), BLUE_DATA_IMAGE));\r
301                         \r
302                                         if(BLUE_FAIL(blue_->render_buffer_update(BlueBuffer_Image(reserved_frames_.front()->id()))))\r
303                                                 CASPAR_LOG(warning) << print() << TEXT(" render_buffer_update failed.");\r
304                                 }\r
305 \r
306                                 unsigned long n_field = 0;\r
307                                 blue_->wait_output_video_synch(UPD_FMT_FRAME, n_field);\r
308 \r
309                                 std::rotate(reserved_frames_.begin(), reserved_frames_.begin() + 1, reserved_frames_.end());\r
310                                 graph_->update_value("tick-time", static_cast<float>(perf_timer_.elapsed()/format_desc_.interval*0.5));\r
311                                 perf_timer_.restart();\r
312                         }\r
313                         catch(...)\r
314                         {\r
315                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
316                         }\r
317                 });\r
318         }\r
319 \r
320         virtual size_t buffer_depth() const{return 1;}\r
321 \r
322         void encode_hanc(BLUE_UINT32* hanc_data, void* audio_data, size_t audio_samples, size_t audio_nchannels)\r
323         {       \r
324                 auto card_type = blue_->has_video_cardtype();\r
325                 auto sample_type = (AUDIO_CHANNEL_16BIT | AUDIO_CHANNEL_LITTLEENDIAN);\r
326                 \r
327                 hanc_stream_info_struct hanc_stream_info;\r
328                 memset(&hanc_stream_info, 0, sizeof(hanc_stream_info));\r
329                 \r
330                 hanc_stream_info.AudioDBNArray[0] = -1;\r
331                 hanc_stream_info.AudioDBNArray[1] = -1;\r
332                 hanc_stream_info.AudioDBNArray[2] = -1;\r
333                 hanc_stream_info.AudioDBNArray[3] = -1;\r
334                 hanc_stream_info.hanc_data_ptr = hanc_data;\r
335                 hanc_stream_info.video_mode = vid_fmt_;\r
336                 \r
337                 auto emb_audio_flag = (blue_emb_audio_enable | blue_emb_audio_group1_enable);\r
338 \r
339                 if (!is_epoch_card(card_type))\r
340                         encode_hanc_frame(&hanc_stream_info, audio_data, audio_nchannels, audio_samples, sample_type, emb_audio_flag);  \r
341                 else\r
342                         encode_hanc_frame_ex(card_type, &hanc_stream_info, audio_data, audio_nchannels, audio_samples, sample_type, emb_audio_flag);\r
343         }\r
344         \r
345         std::wstring print() const\r
346         {\r
347                 return model_name_ + L" [" + boost::lexical_cast<std::wstring>(device_index_) + L"]";\r
348         }\r
349 };\r
350 \r
351 bluefish_consumer::bluefish_consumer(unsigned int device_index, bool embed_audio) : impl_(new implementation(device_index, embed_audio)){}      \r
352 bluefish_consumer::bluefish_consumer(bluefish_consumer&& other) : impl_(std::move(other.impl_)){}\r
353 void bluefish_consumer::initialize(const core::video_format_desc& format_desc)\r
354 {\r
355         // TODO: Ugly\r
356         impl_.reset(new implementation(impl_->device_index_, impl_->embed_audio_));\r
357         impl_->initialize(format_desc);\r
358 }\r
359 void bluefish_consumer::send(const safe_ptr<const core::read_frame>& frame){impl_->send(frame);}\r
360 size_t bluefish_consumer::buffer_depth() const{return impl_->buffer_depth();}\r
361 std::wstring bluefish_consumer::print() const {return impl_->print();}  \r
362 \r
363 std::wstring get_bluefish_version()\r
364 {\r
365         try\r
366         {\r
367                 blue_initialize();\r
368         }\r
369         catch(...)\r
370         {\r
371                 return L"Not found";\r
372         }\r
373         if(!BlueVelvetVersion)\r
374                 return L"Unknown";\r
375 \r
376         return widen(std::string(BlueVelvetVersion()));\r
377 }\r
378 \r
379 std::vector<std::wstring> get_bluefish_device_list()\r
380 {\r
381         std::vector<std::wstring> devices;\r
382 \r
383         try\r
384         {               \r
385                 if(!BlueVelvetFactory4)\r
386                         return devices;\r
387 \r
388                 std::shared_ptr<CBlueVelvet4> blue(BlueVelvetFactory4());\r
389 \r
390                 for(int n = 1; BLUE_PASS(blue->device_attach(n, FALSE)); ++n)\r
391                 {                               \r
392                         devices.push_back(L"[" + boost::lexical_cast<std::wstring>(n) + L"] " + get_card_desc(blue->has_video_cardtype()));\r
393                         blue->device_detach();          \r
394                 }\r
395         }\r
396         catch(...){}\r
397 \r
398         return devices;\r
399 }\r
400 \r
401 safe_ptr<core::frame_consumer> create_bluefish_consumer(const std::vector<std::wstring>& params)\r
402 {\r
403         if(params.size() < 1 || params[0] != L"BLUEFISH")\r
404                 return core::frame_consumer::empty();\r
405                 \r
406         int device_index = 1;\r
407         bool embed_audio = false;\r
408 \r
409         if(params.size() > 1)\r
410                 device_index = lexical_cast_or_default<int>(params[2]);\r
411 \r
412         if(params.size() > 2) \r
413                 embed_audio = lexical_cast_or_default<bool>(params[3]);\r
414 \r
415         return make_safe<bluefish_consumer>(device_index, embed_audio);\r
416 }\r
417 \r
418 }