]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
7afb1bdfdd1f9d097acfbd241cf7a054e9ab5c44
[casparcg] / modules / flash / producer / flash_producer.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\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 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 #include "../stdafx.h"\r
23 \r
24 #if defined(_MSC_VER)\r
25 #pragma warning (disable : 4146)\r
26 #pragma warning (disable : 4244)\r
27 #endif\r
28 \r
29 #include "flash_producer.h"\r
30 #include "FlashAxContainer.h"\r
31 \r
32 #include "../util/swf.h"\r
33 \r
34 #include <core/video_format.h>\r
35 \r
36 #include <core/producer/frame/basic_frame.h>\r
37 #include <core/producer/frame/frame_factory.h>\r
38 #include <core/mixer/write_frame.h>\r
39 \r
40 #include <common/env.h>\r
41 #include <common/concurrency/executor.h>\r
42 #include <common/concurrency/lock.h>\r
43 #include <common/diagnostics/graph.h>\r
44 #include <common/memory/memcpy.h>\r
45 #include <common/memory/memclr.h>\r
46 #include <common/utility/timer.h>\r
47 \r
48 #include <boost/filesystem.hpp>\r
49 #include <boost/property_tree/ptree.hpp>\r
50 #include <boost/thread.hpp>\r
51 #include <boost/timer.hpp>\r
52 #include <boost/algorithm/string.hpp>\r
53 \r
54 #include <functional>\r
55 \r
56 #include <tbb/spin_mutex.h>\r
57 \r
58 namespace caspar { namespace flash {\r
59                 \r
60 class bitmap\r
61 {\r
62 public:\r
63         bitmap(size_t width, size_t height)\r
64                 : bmp_data_(nullptr)\r
65                 , hdc_(CreateCompatibleDC(0), DeleteDC)\r
66         {       \r
67                 BITMAPINFO info;\r
68                 memset(&info, 0, sizeof(BITMAPINFO));\r
69                 info.bmiHeader.biBitCount = 32;\r
70                 info.bmiHeader.biCompression = BI_RGB;\r
71                 info.bmiHeader.biHeight = -height;\r
72                 info.bmiHeader.biPlanes = 1;\r
73                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
74                 info.bmiHeader.biWidth = width;\r
75 \r
76                 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);\r
77                 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get()); \r
78 \r
79                 if(!bmp_data_)\r
80                         BOOST_THROW_EXCEPTION(std::bad_alloc());\r
81         }\r
82 \r
83         operator HDC() {return static_cast<HDC>(hdc_.get());}\r
84 \r
85         BYTE* data() { return bmp_data_;}\r
86         const BYTE* data() const { return bmp_data_;}\r
87 \r
88 private:\r
89         BYTE* bmp_data_;        \r
90         std::shared_ptr<void> hdc_;\r
91         std::shared_ptr<void> bmp_;\r
92 };\r
93 \r
94 struct template_host\r
95 {\r
96         std::wstring  video_mode;\r
97         std::wstring  filename;\r
98         size_t            width;\r
99         size_t            height;\r
100 };\r
101 \r
102 template_host get_template_host(const core::video_format_desc& desc)\r
103 {\r
104         try\r
105         {\r
106                 std::vector<template_host> template_hosts;\r
107                 BOOST_FOREACH(auto& xml_mapping, env::properties().get_child(L"configuration.template-hosts"))\r
108                 {\r
109                         try\r
110                         {\r
111                                 template_host template_host;\r
112                                 template_host.video_mode                = xml_mapping.second.get(L"video-mode", L"");\r
113                                 template_host.filename                  = xml_mapping.second.get(L"filename",   L"cg.fth");\r
114                                 template_host.width                             = xml_mapping.second.get(L"width",              desc.width);\r
115                                 template_host.height                    = xml_mapping.second.get(L"height",             desc.height);\r
116                                 template_hosts.push_back(template_host);\r
117                         }\r
118                         catch(...){}\r
119                 }\r
120 \r
121                 auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == desc.name;});\r
122                 if(template_host_it == template_hosts.end())\r
123                         template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == L"";});\r
124 \r
125                 if(template_host_it != template_hosts.end())\r
126                         return *template_host_it;\r
127         }\r
128         catch(...){}\r
129                 \r
130         template_host template_host;\r
131         template_host.filename = L"cg.fth";\r
132 \r
133         for(auto it = boost::filesystem2::wdirectory_iterator(env::template_folder()); it != boost::filesystem2::wdirectory_iterator(); ++it)\r
134         {\r
135                 if(boost::iequals(it->path().extension(), L"." + desc.name))\r
136                 {\r
137                         template_host.filename = it->filename();\r
138                         break;\r
139                 }\r
140         }\r
141 \r
142         template_host.width =  desc.square_width;\r
143         template_host.height = desc.square_height;\r
144         return template_host;\r
145 }\r
146 \r
147 class flash_renderer\r
148 {       \r
149         struct com_init\r
150         {\r
151                 HRESULT result_;\r
152 \r
153                 com_init()\r
154                         : result_(CoInitialize(nullptr))\r
155                 {\r
156                         if(FAILED(result_))\r
157                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to initialize com-context for flash-player"));\r
158                 }\r
159 \r
160                 ~com_init()\r
161                 {\r
162                         if(SUCCEEDED(result_))\r
163                                 ::CoUninitialize();\r
164                 }\r
165         } com_init_;\r
166         \r
167         const safe_ptr<diagnostics::graph>                              graph_;\r
168         const size_t                                                                    width_;\r
169         const size_t                                                                    height_;\r
170         const std::wstring                                                              filename_;\r
171         const std::shared_ptr<core::frame_factory>              frame_factory_;\r
172         \r
173         CComObject<caspar::flash::FlashAxContainer>*    ax_;\r
174         safe_ptr<core::basic_frame>                                             head_;\r
175         bitmap                                                                                  bmp_;\r
176         \r
177         boost::timer                                                                    frame_timer_;\r
178         boost::timer                                                                    tick_timer_;\r
179 \r
180         high_prec_timer                                                                 timer_;\r
181         \r
182 public:\r
183         flash_renderer(const safe_ptr<diagnostics::graph>& graph, const std::shared_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
184                 : graph_(graph)\r
185                 , width_(width)\r
186                 , height_(height)\r
187                 , filename_(filename)\r
188                 , frame_factory_(frame_factory)\r
189                 , ax_(nullptr)\r
190                 , head_(core::basic_frame::empty())\r
191                 , bmp_(width, height)\r
192         {               \r
193                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
194                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));\r
195                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));       \r
196                 graph_->set_color("sync", diagnostics::color(0.8f, 0.3f, 0.2f));                        \r
197                 \r
198                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
199                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to create FlashAxContainer"));\r
200                 \r
201                 ax_->set_print([this]{return print();});\r
202 \r
203                 if(FAILED(ax_->CreateAxControl()))\r
204                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Create FlashAxControl"));\r
205                 \r
206                 CComPtr<IShockwaveFlash> spFlash;\r
207                 if(FAILED(ax_->QueryControl(&spFlash)))\r
208                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Query FlashAxControl"));\r
209                                                                                                 \r
210                 if(FAILED(spFlash->put_Playing(true)) )\r
211                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start playing Flash"));\r
212 \r
213                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
214                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Load Template Host"));\r
215                                                                                 \r
216                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
217                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Set Scale Mode"));\r
218                                                 \r
219                 ax_->SetSize(width_, height_);          \r
220                 render_frame(false);\r
221         \r
222                 CASPAR_LOG(info) << print() << L" Initialized.";\r
223         }\r
224 \r
225         ~flash_renderer()\r
226         {               \r
227                 if(ax_)\r
228                 {\r
229                         ax_->DestroyAxControl();\r
230                         ax_->Release();\r
231                 }\r
232                 graph_->set_value("tick-time", 0.0f);\r
233                 graph_->set_value("frame-time", 0.0f);\r
234                 CASPAR_LOG(info) << print() << L" Uninitialized.";\r
235         }\r
236         \r
237         std::wstring call(const std::wstring& param)\r
238         {               \r
239                 std::wstring result;\r
240 \r
241                 CASPAR_LOG(trace) << print() << " Call: " << param;\r
242 \r
243                 if(!ax_->FlashCall(param, result))\r
244                         CASPAR_LOG(warning) << print() << L" Flash call failed:" << param;//BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Flash function call failed.") << arg_name_info("param") << arg_value_info(narrow(param)));\r
245                 graph_->set_tag("param");\r
246 \r
247                 return result;\r
248         }\r
249         \r
250         safe_ptr<core::basic_frame> render_frame(double sync)\r
251         {\r
252                 float frame_time = 1.0f/ax_->GetFPS();\r
253 \r
254                 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()/frame_time)*0.5f);\r
255                 tick_timer_.restart();\r
256 \r
257                 if(ax_->IsEmpty())\r
258                         return core::basic_frame::empty();              \r
259                 \r
260                 if(sync > 0.00001)                      \r
261                         timer_.tick(frame_time*sync); // This will block the thread.\r
262                 else\r
263                         graph_->set_tag("sync");\r
264 \r
265                 graph_->set_value("sync", sync);\r
266                         \r
267                 frame_timer_.restart();\r
268 \r
269                 ax_->Tick();\r
270                 if(ax_->InvalidRect())\r
271                 {\r
272                         fast_memclr(bmp_.data(), width_*height_*4);\r
273                         ax_->DrawControl(bmp_);\r
274                 \r
275                         core::pixel_format_desc desc;\r
276                         desc.pix_fmt = core::pixel_format::bgra;\r
277                         desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));\r
278                         auto frame = frame_factory_->create_frame(this, desc);\r
279 \r
280                         if(frame->image_data().size() == static_cast<int>(width_*height_*4))\r
281                         {\r
282                                 fast_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
283                                 frame->commit();\r
284                                 head_ = frame;\r
285                         }\r
286                 }               \r
287                                         \r
288                 MSG msg;\r
289                 while(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) // DO NOT REMOVE THE MESSAGE DISPATCH LOOP. Without this some stuff doesn't work!  \r
290                 {\r
291                         if(msg.message == WM_TIMER && msg.wParam == 3 && msg.lParam == 0) // We tick this inside FlashAxContainer\r
292                                 continue;\r
293                         \r
294                         TranslateMessage(&msg);\r
295                         DispatchMessage(&msg);                  \r
296                 }\r
297                                                                                 \r
298                 graph_->set_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
299                 return head_;\r
300         }\r
301 \r
302         bool is_empty() const\r
303         {\r
304                 return ax_->IsEmpty();\r
305         }\r
306 \r
307         double fps() const\r
308         {\r
309                 return ax_->GetFPS();   \r
310         }\r
311         \r
312         std::wstring print()\r
313         {\r
314                 return L"flash-player[" + boost::filesystem::wpath(filename_).filename() \r
315                                   + L"|" + boost::lexical_cast<std::wstring>(width_)\r
316                                   + L"x" + boost::lexical_cast<std::wstring>(height_)\r
317                                   + L"]";               \r
318         }\r
319 };\r
320 \r
321 struct flash_producer : public core::frame_producer\r
322 {       \r
323         const std::wstring                                                                                      filename_;      \r
324         const safe_ptr<core::frame_factory>                                                     frame_factory_;\r
325         const int                                                                                                       width_;\r
326         const int                                                                                                       height_;\r
327         const int                                                                                                       buffer_size_;\r
328 \r
329         tbb::atomic<int>                                                                                        fps_;\r
330 \r
331         safe_ptr<diagnostics::graph>                                                            graph_;\r
332 \r
333         std::queue<safe_ptr<core::basic_frame>>                                         frame_buffer_;\r
334         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      output_buffer_;\r
335         \r
336         mutable tbb::spin_mutex                                                                         last_frame_mutex_;\r
337         safe_ptr<core::basic_frame>                                                                     last_frame_;\r
338                 \r
339         std::unique_ptr<flash_renderer>                                                         renderer_;\r
340 \r
341         executor                                                                                                        executor_;      \r
342 public:\r
343         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, size_t width, size_t height) \r
344                 : filename_(filename)           \r
345                 , frame_factory_(frame_factory)\r
346                 , last_frame_(core::basic_frame::empty())\r
347                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
348                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
349                 , buffer_size_(env::properties().get(L"configuration.flash.buffer-depth", frame_factory_->get_video_format_desc().fps > 30.0 ? 4 : 2))\r
350                 , executor_(L"flash_producer")\r
351         {       \r
352                 fps_ = 0;\r
353          \r
354                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.9f));\r
355                 graph_->set_text(print());\r
356                 diagnostics::register_graph(graph_);\r
357                 \r
358                 renderer_.reset(new flash_renderer(graph_, frame_factory_, filename_, width_, height_));\r
359 \r
360                 while(output_buffer_.size() < buffer_size_)\r
361                         output_buffer_.push(core::basic_frame::empty());\r
362         }\r
363 \r
364         ~flash_producer()\r
365         {\r
366                 executor_.invoke([this]\r
367                 {\r
368                         renderer_.reset();\r
369                 }, high_priority);\r
370         }\r
371 \r
372         // frame_producer\r
373                 \r
374         virtual safe_ptr<core::basic_frame> receive(int) override\r
375         {                                       \r
376                 auto frame = core::basic_frame::late();\r
377                 \r
378                 if(output_buffer_.try_pop(frame))       \r
379                         next();\r
380                 else\r
381                         graph_->set_tag("late-frame");\r
382 \r
383                 return frame;\r
384         }\r
385 \r
386         virtual safe_ptr<core::basic_frame> last_frame() const override\r
387         {\r
388                 return lock(last_frame_mutex_, [this]\r
389                 {\r
390                         return last_frame_;\r
391                 });\r
392         }               \r
393         \r
394         virtual boost::unique_future<std::wstring> call(const std::wstring& param) override\r
395         {       \r
396                 return executor_.begin_invoke([this, param]() -> std::wstring\r
397                 {                       \r
398                         try\r
399                         {\r
400                                 if(!renderer_)\r
401                                 {\r
402                                         renderer_.reset(new flash_renderer(graph_, frame_factory_, filename_, width_, height_));\r
403 \r
404                                         while(output_buffer_.size() < buffer_size_)\r
405                                                 output_buffer_.push(core::basic_frame::empty());\r
406                                 }\r
407 \r
408                                 return renderer_->call(param);  \r
409 \r
410                                 //const auto& format_desc = frame_factory_->get_video_format_desc();\r
411                                 //if(abs(context_->fps() - format_desc.fps) > 0.01 && abs(context_->fps()/2.0 - format_desc.fps) > 0.01)\r
412                                 //      CASPAR_LOG(warning) << print() << " Invalid frame-rate: " << context_->fps() << L". Should be either " << format_desc.fps << L" or " << format_desc.fps*2.0 << L".";\r
413                         }\r
414                         catch(...)\r
415                         {\r
416                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
417                                 renderer_.reset(nullptr);\r
418                         }\r
419 \r
420                         return L"";\r
421                 });\r
422         }\r
423                 \r
424         virtual std::wstring print() const override\r
425         { \r
426                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";              \r
427         }       \r
428 \r
429         virtual boost::property_tree::wptree info() const override\r
430         {\r
431                 boost::property_tree::wptree info;\r
432                 info.add(L"type", L"flash-producer");\r
433                 return info;\r
434         }\r
435 \r
436         // flash_producer\r
437         \r
438         void next()\r
439         {       \r
440                 executor_.begin_invoke([this]\r
441                 {\r
442                         if(!renderer_)\r
443                                 frame_buffer_.push(core::basic_frame::empty());\r
444 \r
445                         if(frame_buffer_.empty())\r
446                         {\r
447                                 auto format_desc = frame_factory_->get_video_format_desc();\r
448                                         \r
449                                 if(abs(renderer_->fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
450                                 {\r
451                                         auto frame1 = render_frame();\r
452                                         auto frame2 = render_frame();\r
453                                         frame_buffer_.push(core::basic_frame::interlace(frame1, frame2, format_desc.field_mode));\r
454                                 }\r
455                                 else if(abs(renderer_->fps() - format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
456                                 {\r
457                                         auto frame = render_frame();\r
458                                         frame_buffer_.push(frame);\r
459                                         frame_buffer_.push(frame);\r
460                                 }\r
461                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
462                                 {\r
463                                         auto frame = render_frame();\r
464                                         frame_buffer_.push(frame);\r
465                                 }\r
466                                                 \r
467                                 fps_.fetch_and_store(static_cast<int>(renderer_->fps()*100.0));                         \r
468                                 graph_->set_text(print());\r
469                         \r
470                                 if(renderer_->is_empty())                       \r
471                                         renderer_.reset();\r
472                         }\r
473 \r
474                         output_buffer_.push(std::move(frame_buffer_.front()));\r
475                         frame_buffer_.pop();\r
476                 });\r
477         }\r
478 \r
479         safe_ptr<core::basic_frame> render_frame()\r
480         {       \r
481                 double ratio = std::min(1.0, static_cast<double>(output_buffer_.size())/static_cast<double>(std::max(1, buffer_size_ - 1)));\r
482                 double sync  = 2*ratio - ratio*ratio;\r
483 \r
484                 auto frame = renderer_->render_frame(sync);\r
485                 lock(last_frame_mutex_, [&]\r
486                 {\r
487                         last_frame_ = frame;\r
488                 });\r
489                 return frame;\r
490         }\r
491 };\r
492 \r
493 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
494 {\r
495         auto template_host = get_template_host(frame_factory->get_video_format_desc());\r
496         \r
497         auto filename = env::template_folder() + L"\\" + template_host.filename;\r
498         \r
499         if(!boost::filesystem::exists(filename))\r
500                 BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(narrow(filename)));  \r
501 \r
502         return create_producer_destroy_proxy(\r
503                    create_producer_print_proxy(\r
504                         make_safe<flash_producer>(frame_factory, filename, template_host.width, template_host.height)));\r
505 }\r
506 \r
507 safe_ptr<core::frame_producer> create_swf_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params) \r
508 {\r
509         auto filename = env::media_folder() + L"\\" + params.at(0) + L".swf";\r
510         \r
511         if(!boost::filesystem::exists(filename))\r
512                 return core::frame_producer::empty();\r
513 \r
514         swf_t::header_t header(filename);\r
515 \r
516         return create_producer_destroy_proxy(\r
517                    create_producer_print_proxy(\r
518                         make_safe<flash_producer>(frame_factory, filename, header.frame_width, header.frame_height)));\r
519 }\r
520 \r
521 std::wstring find_template(const std::wstring& template_name)\r
522 {\r
523         if(boost::filesystem::exists(template_name + L".ft")) \r
524                 return template_name + L".ft";\r
525         \r
526         if(boost::filesystem::exists(template_name + L".ct"))\r
527                 return template_name + L".ct";\r
528         \r
529         if(boost::filesystem::exists(template_name + L".swf"))\r
530                 return template_name + L".swf";\r
531 \r
532         return L"";\r
533 }\r
534 \r
535 }}