]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
2.1.0: -ffmpeg_producer: Always de-interlace interlaced content. Fixed PAUSE with...
[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 <core/video_format.h>\r
33 \r
34 #include <core/frame/frame.h>\r
35 #include <core/frame/draw_frame.h>\r
36 #include <core/frame/frame_factory.h>\r
37 #include <core/frame/pixel_format.h>\r
38 #include <core/monitor/monitor.h>\r
39 \r
40 #include <common/env.h>\r
41 #include <common/executor.h>\r
42 #include <common/lock.h>\r
43 #include <common/diagnostics/graph.h>\r
44 #include <common/prec_timer.h>\r
45 #include <common/array.h>\r
46 \r
47 #include <boost/filesystem.hpp>\r
48 #include <boost/property_tree/ptree.hpp>\r
49 #include <boost/thread.hpp>\r
50 #include <boost/timer.hpp>\r
51 #include <boost/algorithm/string.hpp>\r
52 \r
53 #include <tbb/spin_mutex.h>\r
54 \r
55 #include <asmlib.h>\r
56 \r
57 #include <functional>\r
58 \r
59 namespace caspar { namespace flash {\r
60                 \r
61 class bitmap\r
62 {\r
63 public:\r
64         bitmap(int width, int 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 = static_cast<LONG>(-height);\r
73                 info.bmiHeader.biPlanes = 1;\r
74                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
75                 info.bmiHeader.biWidth = static_cast<LONG>(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         int                       width;\r
100         int                       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::filesystem::directory_iterator(env::template_folder()); it != boost::filesystem::directory_iterator(); ++it)\r
135         {\r
136                 if(boost::iequals(it->path().extension().wstring(), L"." + desc.name))\r
137                 {\r
138                         template_host.filename = it->path().filename().wstring();\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         monitor::basic_subject&                                         event_subject_;\r
169 \r
170         const std::wstring                                                      filename_;\r
171 \r
172         const std::shared_ptr<core::frame_factory>      frame_factory_;\r
173         \r
174         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
175         core::draw_frame                                                        head_;\r
176         bitmap                                                                          bmp_;\r
177         \r
178         spl::shared_ptr<diagnostics::graph>                     graph_;\r
179         \r
180         prec_timer                                                                      timer_;\r
181 \r
182         const int                                                                       width_;\r
183         const int                                                                       height_;\r
184         \r
185 public:\r
186         flash_renderer(monitor::basic_subject& event_subject, const spl::shared_ptr<diagnostics::graph>& graph, const std::shared_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
187                 : event_subject_(event_subject)\r
188                 , graph_(graph)\r
189                 , filename_(filename)\r
190                 , frame_factory_(frame_factory)\r
191                 , ax_(nullptr)\r
192                 , head_(core::draw_frame::empty())\r
193                 , bmp_(width, height)\r
194                 , width_(width)\r
195                 , height_(height)\r
196         {               \r
197                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
198                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));       \r
199                 graph_->set_color("sync", diagnostics::color(0.8f, 0.3f, 0.2f));                        \r
200                 \r
201                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
202                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to create FlashAxContainer"));\r
203                 \r
204                 ax_->set_print([this]{return print();});\r
205 \r
206                 if(FAILED(ax_->CreateAxControl()))\r
207                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Create FlashAxControl"));\r
208                 \r
209                 CComPtr<IShockwaveFlash> spFlash;\r
210                 if(FAILED(ax_->QueryControl(&spFlash)))\r
211                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Query FlashAxControl"));\r
212                                                                                                 \r
213                 if(FAILED(spFlash->put_Playing(true)) )\r
214                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to start playing Flash"));\r
215 \r
216                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
217                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Load Template Host"));\r
218                                                                                 \r
219                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
220                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Set Scale Mode"));\r
221                                                 \r
222                 ax_->SetSize(width_, height_);          \r
223 \r
224                 tick(false);\r
225                 render();\r
226 \r
227                 CASPAR_LOG(info) << print() << L" Initialized.";\r
228         }\r
229 \r
230         ~flash_renderer()\r
231         {               \r
232                 if(ax_)\r
233                 {\r
234                         ax_->DestroyAxControl();\r
235                         ax_->Release();\r
236                 }\r
237                 graph_->set_value("tick-time", 0.0f);\r
238                 graph_->set_value("frame-time", 0.0f);\r
239                 CASPAR_LOG(info) << print() << L" Uninitialized.";\r
240         }\r
241         \r
242         std::wstring call(const std::wstring& param)\r
243         {               \r
244                 std::wstring result;\r
245 \r
246                 CASPAR_LOG(trace) << print() << " Call: " << param;\r
247 \r
248                 if(!ax_->FlashCall(param, result))\r
249                         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
250                 graph_->set_tag("param");\r
251 \r
252                 return result;\r
253         }\r
254 \r
255         void tick(double sync)\r
256         {               \r
257                 const float frame_time = 1.0f/ax_->GetFPS();\r
258 \r
259                 if(sync > 0.00001)                      \r
260                         timer_.tick(frame_time*sync); // This will block the thread.\r
261                 else\r
262                         graph_->set_tag("sync");\r
263 \r
264                 graph_->set_value("sync", sync);\r
265                 event_subject_ << monitor::event("sync") % sync;\r
266                 \r
267                 ax_->Tick();\r
268                                         \r
269                 MSG msg;\r
270                 while(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) // DO NOT REMOVE THE MESSAGE DISPATCH LOOP. Without this some stuff doesn't work!  \r
271                 {\r
272                         if(msg.message == WM_TIMER && msg.wParam == 3 && msg.lParam == 0) // We tick this inside FlashAxContainer\r
273                                 continue;\r
274                         \r
275                         TranslateMessage(&msg);\r
276                         DispatchMessage(&msg);                  \r
277                 }\r
278         }\r
279         \r
280         core::draw_frame render()\r
281         {                       \r
282                 const float frame_time = 1.0f/fps();\r
283 \r
284                 boost::timer frame_timer;\r
285 \r
286                 if(ax_->InvalidRect())\r
287                 {                       \r
288                         A_memset(bmp_.data(), 0, width_*height_*4);\r
289                         ax_->DrawControl(bmp_);\r
290                 \r
291                         core::pixel_format_desc desc = core::pixel_format::bgra;\r
292                         desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));\r
293                         auto frame = frame_factory_->create_frame(this, desc, fps(), core::field_mode::progressive);\r
294 \r
295                         A_memcpy(frame.image_data(0).begin(), bmp_.data(), width_*height_*4);\r
296                         head_ = core::draw_frame(std::move(frame));     \r
297                 }               \r
298                                                                                 \r
299                 graph_->set_value("frame-time", static_cast<float>(frame_timer.elapsed()/frame_time)*0.5f);\r
300                 event_subject_ << monitor::event("renderer/profiler/time") % frame_timer.elapsed() % frame_time;\r
301                 return head_;\r
302         }\r
303         \r
304         bool is_empty() const\r
305         {\r
306                 return ax_->IsEmpty();\r
307         }\r
308 \r
309         double fps() const\r
310         {\r
311                 return ax_->GetFPS();   \r
312         }\r
313         \r
314         std::wstring print()\r
315         {\r
316                 return L"flash-player[" + boost::filesystem::wpath(filename_).filename().wstring() \r
317                                   + L"|" + boost::lexical_cast<std::wstring>(width_)\r
318                                   + L"x" + boost::lexical_cast<std::wstring>(height_)\r
319                                   + L"]";               \r
320         }\r
321 };\r
322 \r
323 struct flash_producer : public core::frame_producer_impl\r
324 {       \r
325         monitor::basic_subject                                                  event_subject_;\r
326         const std::wstring                                                              filename_;      \r
327         const spl::shared_ptr<core::frame_factory>              frame_factory_;\r
328         const core::video_format_desc                                   format_desc_;\r
329         const int                                                                               width_;\r
330         const int                                                                               height_;\r
331         const int                                                                               buffer_size_;\r
332 \r
333         tbb::atomic<int>                                                                fps_;\r
334 \r
335         spl::shared_ptr<diagnostics::graph>                             graph_;\r
336 \r
337         std::queue<core::draw_frame>                                    frame_buffer_;\r
338         tbb::concurrent_bounded_queue<core::draw_frame> output_buffer_;\r
339                                 \r
340         boost::timer                                                                    tick_timer_;\r
341         std::unique_ptr<flash_renderer>                                 renderer_;\r
342         \r
343         executor                                                                                executor_;      \r
344 public:\r
345         flash_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, const std::wstring& filename, int width, int height) \r
346                 : filename_(filename)           \r
347                 , frame_factory_(frame_factory)\r
348                 , format_desc_(format_desc)\r
349                 , width_(width > 0 ? width : format_desc.width)\r
350                 , height_(height > 0 ? height : format_desc.height)\r
351                 , buffer_size_(env::properties().get(L"configuration.flash.buffer-depth", 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("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f));\r
357                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));\r
358                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.9f));\r
359                 graph_->set_text(print());\r
360                 diagnostics::register_graph(graph_);\r
361 \r
362                 CASPAR_LOG(info) << print() << L" Initialized";\r
363         }\r
364 \r
365         ~flash_producer()\r
366         {\r
367                 executor_.invoke([this]\r
368                 {\r
369                         renderer_.reset();\r
370                 }, task_priority::high_priority);\r
371         }\r
372 \r
373         // frame_producer\r
374                 \r
375         core::draw_frame receive_impl() override\r
376         {                                       \r
377                 auto frame = core::draw_frame::late();\r
378                 \r
379                 if(output_buffer_.try_pop(frame))                       \r
380                         executor_.begin_invoke(std::bind(&flash_producer::next, this));         \r
381                 else            \r
382                         graph_->set_tag("late-frame");          \r
383                                 \r
384                 event_subject_ << monitor::event("host/path")   % filename_\r
385                                            << monitor::event("host/width")      % width_\r
386                                            << monitor::event("host/height") % height_\r
387                                            << monitor::event("host/fps")        % fps_\r
388                                            << monitor::event("buffer")          % output_buffer_.size() % buffer_size_;\r
389 \r
390                 return frame;\r
391         }\r
392                 \r
393         boost::unique_future<std::wstring> call(const std::wstring& param) override\r
394         {       \r
395                 return executor_.begin_invoke([this, param]() -> std::wstring\r
396                 {                       \r
397                         try\r
398                         {\r
399                                 if(!renderer_)\r
400                                 {\r
401                                         renderer_.reset(new flash_renderer(event_subject_, graph_, frame_factory_, filename_, width_, height_));\r
402 \r
403                                         while(output_buffer_.size() < buffer_size_)\r
404                                                 output_buffer_.push(core::draw_frame::empty());\r
405                                 }\r
406 \r
407                                 return renderer_->call(param);  \r
408                         }\r
409                         catch(...)\r
410                         {\r
411                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
412                                 renderer_.reset(nullptr);\r
413                         }\r
414 \r
415                         return L"";\r
416                 });\r
417         }\r
418                 \r
419         std::wstring print() const override\r
420         { \r
421                 return L"flash[" + boost::filesystem::path(filename_).wstring() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";                \r
422         }       \r
423 \r
424         std::wstring name() const override\r
425         {\r
426                 return L"flash";\r
427         }\r
428 \r
429         boost::property_tree::wptree info() const override\r
430         {\r
431                 boost::property_tree::wptree info;\r
432                 info.add(L"type", L"flash");\r
433                 return info;\r
434         }\r
435 \r
436         void subscribe(const monitor::observable::observer_ptr& o) override\r
437         {\r
438                 event_subject_.subscribe(o);\r
439         }\r
440 \r
441         void unsubscribe(const monitor::observable::observer_ptr& o) override\r
442         {\r
443                 event_subject_.unsubscribe(o);\r
444         }\r
445 \r
446         // flash_producer\r
447         \r
448         void tick()\r
449         {\r
450                 double ratio = std::min(1.0, static_cast<double>(output_buffer_.size())/static_cast<double>(std::max(1, buffer_size_ - 1)));\r
451                 double sync  = 2*ratio - ratio*ratio;\r
452                 renderer_->tick(sync);\r
453         }\r
454         \r
455         void next()\r
456         {       \r
457                 if(!renderer_)\r
458                         frame_buffer_.push(core::draw_frame::empty());\r
459 \r
460                 tick_timer_.restart();                          \r
461 \r
462                 if(frame_buffer_.empty())\r
463                 {                                       \r
464                         tick();\r
465                         auto frame = renderer_->render();\r
466 \r
467                         if(abs(renderer_->fps()/2.0 - format_desc_.fps) < 2.0) // flash == 2 * format -> interlace\r
468                         {                                       \r
469                                 tick();\r
470                                 if(format_desc_.field_mode != core::field_mode::progressive)\r
471                                         frame = core::draw_frame::interlace(frame, renderer_->render(), format_desc_.field_mode);\r
472                                 \r
473                                 frame_buffer_.push(frame);\r
474                         }\r
475                         else if(abs(renderer_->fps() - format_desc_.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
476                         {\r
477                                 frame_buffer_.push(frame);\r
478                                 frame_buffer_.push(frame);\r
479                         }\r
480                         else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
481                         {\r
482                                 frame_buffer_.push(frame);\r
483                         }\r
484                                                 \r
485                         fps_.fetch_and_store(static_cast<int>(renderer_->fps()*100.0));                         \r
486                         graph_->set_text(print());\r
487                         \r
488                         if(renderer_->is_empty())                       \r
489                                 renderer_.reset();\r
490                 }\r
491 \r
492                 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()/fps_)*0.5f);\r
493                 event_subject_ << monitor::event("profiler/time") % tick_timer_.elapsed() % fps_;\r
494 \r
495                 output_buffer_.push(std::move(frame_buffer_.front()));\r
496                 frame_buffer_.pop();\r
497         }\r
498 };\r
499 \r
500 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, const std::vector<std::wstring>& params)\r
501 {\r
502         auto template_host = get_template_host(format_desc);\r
503         \r
504         auto filename = env::template_folder() + L"\\" + template_host.filename;\r
505         \r
506         if(!boost::filesystem::exists(filename))\r
507                 BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(u8(filename)));      \r
508 \r
509         return spl::make_shared<flash_producer>(frame_factory, format_desc, filename, template_host.width, template_host.height);\r
510 }\r
511 \r
512 std::wstring find_template(const std::wstring& template_name)\r
513 {\r
514         if(boost::filesystem::exists(template_name + L".ft")) \r
515                 return template_name + L".ft";\r
516         \r
517         if(boost::filesystem::exists(template_name + L".ct"))\r
518                 return template_name + L".ct";\r
519         \r
520         if(boost::filesystem::exists(template_name + L".swf"))\r
521                 return template_name + L".swf";\r
522 \r
523         return L"";\r
524 }\r
525 \r
526 }}