]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
2.1.0: Refactored safe_ptr into *safe* spl::shared_ptr and spl::unique_ptr.
[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/draw_frame.h>\r
35 #include <core/frame/frame_factory.h>\r
36 #include <core/frame/pixel_format.h>\r
37 #include <core/mixer/gpu/write_frame.h>\r
38 \r
39 #include <common/env.h>\r
40 #include <common/concurrency/executor.h>\r
41 #include <common/concurrency/lock.h>\r
42 #include <common/diagnostics/graph.h>\r
43 #include <common/prec_timer.h>\r
44 \r
45 #include <boost/filesystem.hpp>\r
46 #include <boost/property_tree/ptree.hpp>\r
47 #include <boost/thread.hpp>\r
48 #include <boost/timer.hpp>\r
49 #include <boost/algorithm/string.hpp>\r
50 \r
51 #include <tbb/spin_mutex.h>\r
52 \r
53 #include <asmlib.h>\r
54 \r
55 #include <functional>\r
56 \r
57 namespace caspar { namespace flash {\r
58                 \r
59 class bitmap\r
60 {\r
61 public:\r
62         bitmap(int width, int height)\r
63                 : bmp_data_(nullptr)\r
64                 , hdc_(CreateCompatibleDC(0), DeleteDC)\r
65         {       \r
66                 BITMAPINFO info;\r
67                 memset(&info, 0, sizeof(BITMAPINFO));\r
68                 info.bmiHeader.biBitCount = 32;\r
69                 info.bmiHeader.biCompression = BI_RGB;\r
70                 info.bmiHeader.biHeight = static_cast<LONG>(-height);\r
71                 info.bmiHeader.biPlanes = 1;\r
72                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
73                 info.bmiHeader.biWidth = static_cast<LONG>(width);\r
74 \r
75                 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);\r
76                 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get()); \r
77 \r
78                 if(!bmp_data_)\r
79                         BOOST_THROW_EXCEPTION(std::bad_alloc());\r
80         }\r
81 \r
82         operator HDC() {return static_cast<HDC>(hdc_.get());}\r
83 \r
84         BYTE* data() { return bmp_data_;}\r
85         const BYTE* data() const { return bmp_data_;}\r
86 \r
87 private:\r
88         BYTE* bmp_data_;        \r
89         std::shared_ptr<void> hdc_;\r
90         std::shared_ptr<void> bmp_;\r
91 };\r
92 \r
93 struct template_host\r
94 {\r
95         std::wstring  video_mode;\r
96         std::wstring  filename;\r
97         int                       width;\r
98         int                       height;\r
99 };\r
100 \r
101 template_host get_template_host(const core::video_format_desc& desc)\r
102 {\r
103         try\r
104         {\r
105                 std::vector<template_host> template_hosts;\r
106                 BOOST_FOREACH(auto& xml_mapping, env::properties().get_child(L"configuration.template-hosts"))\r
107                 {\r
108                         try\r
109                         {\r
110                                 template_host template_host;\r
111                                 template_host.video_mode                = xml_mapping.second.get(L"video-mode", L"");\r
112                                 template_host.filename                  = xml_mapping.second.get(L"filename",   L"cg.fth");\r
113                                 template_host.width                             = xml_mapping.second.get(L"width",              desc.width);\r
114                                 template_host.height                    = xml_mapping.second.get(L"height",             desc.height);\r
115                                 template_hosts.push_back(template_host);\r
116                         }\r
117                         catch(...){}\r
118                 }\r
119 \r
120                 auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == desc.name;});\r
121                 if(template_host_it == template_hosts.end())\r
122                         template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == L"";});\r
123 \r
124                 if(template_host_it != template_hosts.end())\r
125                         return *template_host_it;\r
126         }\r
127         catch(...){}\r
128                 \r
129         template_host template_host;\r
130         template_host.filename = L"cg.fth";\r
131 \r
132         for(auto it = boost::filesystem::directory_iterator(env::template_folder()); it != boost::filesystem::directory_iterator(); ++it)\r
133         {\r
134                 if(boost::iequals(it->path().extension().wstring(), L"." + desc.name))\r
135                 {\r
136                         template_host.filename = it->path().filename().wstring();\r
137                         break;\r
138                 }\r
139         }\r
140 \r
141         template_host.width =  desc.square_width;\r
142         template_host.height = desc.square_height;\r
143         return template_host;\r
144 }\r
145 \r
146 class flash_renderer\r
147 {       \r
148         struct com_init\r
149         {\r
150                 HRESULT result_;\r
151 \r
152                 com_init()\r
153                         : result_(CoInitialize(nullptr))\r
154                 {\r
155                         if(FAILED(result_))\r
156                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to initialize com-context for flash-player"));\r
157                 }\r
158 \r
159                 ~com_init()\r
160                 {\r
161                         if(SUCCEEDED(result_))\r
162                                 ::CoUninitialize();\r
163                 }\r
164         } com_init_;\r
165 \r
166         const std::wstring filename_;\r
167 \r
168         const std::shared_ptr<core::frame_factory> frame_factory_;\r
169         \r
170         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
171         spl::shared_ptr<core::draw_frame> head_;\r
172         bitmap bmp_;\r
173         \r
174         spl::shared_ptr<diagnostics::graph> graph_;\r
175         boost::timer frame_timer_;\r
176         boost::timer tick_timer_;\r
177 \r
178         prec_timer timer_;\r
179 \r
180         const int width_;\r
181         const int height_;\r
182         \r
183 public:\r
184         flash_renderer(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
185                 : graph_(graph)\r
186                 , filename_(filename)\r
187                 , frame_factory_(frame_factory)\r
188                 , ax_(nullptr)\r
189                 , head_(core::draw_frame::empty())\r
190                 , bmp_(width, height)\r
191                 , width_(width)\r
192                 , height_(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("skip-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(print() + L" 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(print() + L" 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(print() + L" Failed to Query FlashAxControl"));\r
210                                                                                                 \r
211                 if(FAILED(spFlash->put_Playing(true)) )\r
212                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" 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(print() + L" 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(print() + L" 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         spl::shared_ptr<core::draw_frame> render_frame(bool 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::draw_frame::empty();               \r
260                 \r
261                 if(sync)                        \r
262                         timer_.tick(frame_time); // This will block the thread.\r
263                 else\r
264                         graph_->set_tag("skip-sync");\r
265                         \r
266                 frame_timer_.restart();\r
267 \r
268                 ax_->Tick();\r
269                 if(ax_->InvalidRect())\r
270                 {                       \r
271                         A_memset(bmp_.data(), 0, width_*height_*4);\r
272                         ax_->DrawControl(bmp_);\r
273                 \r
274                         core::pixel_format_desc desc = core::pixel_format::bgra;\r
275                         desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));\r
276                         auto frame = frame_factory_->create_frame(this, desc);\r
277 \r
278                         A_memcpy(frame->image_data(0).begin(), bmp_.data(), width_*height_*4);\r
279                         head_ = frame;\r
280                 }               \r
281                                         \r
282                 MSG msg;\r
283                 while(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) // DO NOT REMOVE THE MESSAGE DISPATCH LOOP. Without this some stuff doesn't work!  \r
284                 {\r
285                         if(msg.message == WM_TIMER && msg.wParam == 3 && msg.lParam == 0) // We tick this inside FlashAxContainer\r
286                                 continue;\r
287                         \r
288                         TranslateMessage(&msg);\r
289                         DispatchMessage(&msg);                  \r
290                 }\r
291                                                                                 \r
292                 graph_->set_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
293                 return head_;\r
294         }\r
295 \r
296         bool is_empty() const\r
297         {\r
298                 return ax_->IsEmpty();\r
299         }\r
300 \r
301         double fps() const\r
302         {\r
303                 return ax_->GetFPS();   \r
304         }\r
305         \r
306         std::wstring print()\r
307         {\r
308                 return L"flash-player[" + boost::filesystem::wpath(filename_).filename().wstring() \r
309                                   + L"|" + boost::lexical_cast<std::wstring>(width_)\r
310                                   + L"x" + boost::lexical_cast<std::wstring>(height_)\r
311                                   + L"]";               \r
312         }\r
313 };\r
314 \r
315 struct flash_producer : public core::frame_producer\r
316 {       \r
317         const std::wstring                                                                                      filename_;      \r
318         const spl::shared_ptr<core::frame_factory>                                                      frame_factory_;\r
319         const int                                                                                                       width_;\r
320         const int                                                                                                       height_;\r
321         const int                                                                                                       buffer_size_;\r
322 \r
323         tbb::atomic<int>                                                                                        fps_;\r
324         tbb::atomic<bool>                                                                                       sync_;\r
325 \r
326         spl::shared_ptr<diagnostics::graph>                                                             graph_;\r
327 \r
328         std::queue<spl::shared_ptr<core::draw_frame>>                                           frame_buffer_;\r
329         tbb::concurrent_bounded_queue<spl::shared_ptr<core::draw_frame>>        output_buffer_;\r
330         \r
331         mutable tbb::spin_mutex                                                                         last_frame_mutex_;\r
332         spl::shared_ptr<core::draw_frame>                                                                       last_frame_;\r
333                 \r
334         std::unique_ptr<flash_renderer>                                                         renderer_;\r
335 \r
336         executor                                                                                                        executor_;      \r
337 public:\r
338         flash_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
339                 : filename_(filename)           \r
340                 , frame_factory_(frame_factory)\r
341                 , last_frame_(core::draw_frame::empty())\r
342                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
343                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
344                 , buffer_size_(env::properties().get(L"configuration.flash.buffer-depth", frame_factory_->get_video_format_desc().fps > 30.0 ? 3 : 2))\r
345                 , executor_(L"flash_producer")\r
346         {       \r
347                 sync_ = true;\r
348                 fps_ = 0;\r
349          \r
350                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f));\r
351                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.9f));\r
352                 graph_->set_text(print());\r
353                 diagnostics::register_graph(graph_);\r
354         }\r
355 \r
356         ~flash_producer()\r
357         {\r
358                 executor_.invoke([this]\r
359                 {\r
360                         renderer_.reset();\r
361                 }, task_priority::high_priority);\r
362         }\r
363 \r
364         // frame_producer\r
365                 \r
366         virtual spl::shared_ptr<core::draw_frame> receive(int) override\r
367         {                                       \r
368                 auto frame = core::draw_frame::late();\r
369                 \r
370                 graph_->set_value("buffer-size", static_cast<float>(output_buffer_.size())/static_cast<float>(buffer_size_));\r
371                 sync_ = output_buffer_.size() == buffer_size_;\r
372 \r
373                 if(output_buffer_.try_pop(frame))       \r
374                         next();\r
375                 else\r
376                         graph_->set_tag("late-frame");\r
377                                                 \r
378                 return frame;\r
379         }\r
380 \r
381         virtual spl::shared_ptr<core::draw_frame> last_frame() const override\r
382         {\r
383                 return lock(last_frame_mutex_, [this]\r
384                 {\r
385                         return last_frame_;\r
386                 });\r
387         }               \r
388         \r
389         virtual boost::unique_future<std::wstring> call(const std::wstring& param) override\r
390         {       \r
391                 return executor_.begin_invoke([this, param]() -> std::wstring\r
392                 {                       \r
393                         try\r
394                         {\r
395                                 if(!renderer_)\r
396                                 {\r
397                                         renderer_.reset(new flash_renderer(graph_, frame_factory_, filename_, width_, height_));\r
398 \r
399                                         while(output_buffer_.size() < buffer_size_)\r
400                                                 output_buffer_.push(core::draw_frame::empty());\r
401                                 }\r
402 \r
403                                 return renderer_->call(param);  \r
404 \r
405                                 //const auto& format_desc = frame_factory_->get_video_format_desc();\r
406                                 //if(abs(context_->fps() - format_desc.fps) > 0.01 && abs(context_->fps()/2.0 - format_desc.fps) > 0.01)\r
407                                 //      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
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         virtual 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         virtual boost::property_tree::wptree info() const override\r
425         {\r
426                 boost::property_tree::wptree info;\r
427                 info.add(L"type", L"flash-producer");\r
428                 return info;\r
429         }\r
430 \r
431         // flash_producer\r
432         \r
433         void next()\r
434         {       \r
435                 executor_.begin_invoke([this]\r
436                 {\r
437                         if(!renderer_)\r
438                                 frame_buffer_.push(core::draw_frame::empty());\r
439 \r
440                         if(frame_buffer_.empty())\r
441                         {\r
442                                 auto format_desc = frame_factory_->get_video_format_desc();\r
443                                         \r
444                                 if(abs(renderer_->fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
445                                 {\r
446                                         auto frame1 = render_frame();\r
447                                         auto frame2 = render_frame();\r
448                                         frame_buffer_.push(core::draw_frame::interlace(frame1, frame2, format_desc.field_mode));\r
449                                 }\r
450                                 else if(abs(renderer_->fps() - format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
451                                 {\r
452                                         auto frame = render_frame();\r
453                                         frame_buffer_.push(frame);\r
454                                         frame_buffer_.push(frame);\r
455                                 }\r
456                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
457                                 {\r
458                                         auto frame = render_frame();\r
459                                         frame_buffer_.push(frame);\r
460                                 }\r
461                                                 \r
462                                 fps_.fetch_and_store(static_cast<int>(renderer_->fps()*100.0));                         \r
463                                 graph_->set_text(print());\r
464                         \r
465                                 if(renderer_->is_empty())                       \r
466                                         renderer_.reset();\r
467                         }\r
468 \r
469                         output_buffer_.push(std::move(frame_buffer_.front()));\r
470                         frame_buffer_.pop();\r
471                 });\r
472         }\r
473 \r
474         spl::shared_ptr<core::draw_frame> render_frame()\r
475         {       \r
476                 auto frame = renderer_->render_frame(sync_);\r
477                 lock(last_frame_mutex_, [&]\r
478                 {\r
479                         last_frame_ = frame;\r
480                 });\r
481                 return frame;\r
482         }\r
483 };\r
484 \r
485 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
486 {\r
487         auto template_host = get_template_host(frame_factory->get_video_format_desc());\r
488         \r
489         auto filename = env::template_folder() + L"\\" + template_host.filename;\r
490         \r
491         if(!boost::filesystem::exists(filename))\r
492                 BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(u8(filename)));      \r
493 \r
494         return spl::make_shared<flash_producer>(frame_factory, filename, template_host.width, template_host.height);\r
495 }\r
496 \r
497 std::wstring find_template(const std::wstring& template_name)\r
498 {\r
499         if(boost::filesystem::exists(template_name + L".ft")) \r
500                 return template_name + L".ft";\r
501         \r
502         if(boost::filesystem::exists(template_name + L".ct"))\r
503                 return template_name + L".ct";\r
504         \r
505         if(boost::filesystem::exists(template_name + L".swf"))\r
506                 return template_name + L".swf";\r
507 \r
508         return L"";\r
509 }\r
510 \r
511 }}