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