]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
2.1.0: Some mayor refactoring.
[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/producer/frame/basic_frame.h>\r
35 #include <core/producer/frame/frame_factory.h>\r
36 #include <core/producer/frame/pixel_format.h>\r
37 #include <core/mixer/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(size_t width, size_t 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         const std::wstring filename_;\r
149 \r
150         const std::shared_ptr<core::frame_factory> frame_factory_;\r
151         \r
152         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
153         safe_ptr<core::basic_frame> head_;\r
154         bitmap bmp_;\r
155         \r
156         safe_ptr<diagnostics::graph> graph_;\r
157         boost::timer frame_timer_;\r
158         boost::timer tick_timer_;\r
159 \r
160         prec_timer timer_;\r
161 \r
162         const int width_;\r
163         const int height_;\r
164         \r
165 public:\r
166         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
167                 : graph_(graph)\r
168                 , filename_(filename)\r
169                 , frame_factory_(frame_factory)\r
170                 , ax_(nullptr)\r
171                 , head_(core::basic_frame::empty())\r
172                 , bmp_(width, height)\r
173                 , width_(width)\r
174                 , height_(height)\r
175         {               \r
176                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
177                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));\r
178                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));       \r
179                 graph_->set_color("skip-sync", diagnostics::color(0.8f, 0.3f, 0.2f));                   \r
180                 \r
181                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
182                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to create FlashAxContainer"));\r
183                 \r
184                 ax_->set_print([this]{return print();});\r
185 \r
186                 if(FAILED(ax_->CreateAxControl()))\r
187                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Create FlashAxControl"));\r
188                 \r
189                 CComPtr<IShockwaveFlash> spFlash;\r
190                 if(FAILED(ax_->QueryControl(&spFlash)))\r
191                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Query FlashAxControl"));\r
192                                                                                                 \r
193                 if(FAILED(spFlash->put_Playing(true)) )\r
194                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to start playing Flash"));\r
195 \r
196                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
197                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Load Template Host"));\r
198                                                                                 \r
199                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
200                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Set Scale Mode"));\r
201                                                 \r
202                 ax_->SetSize(width_, height_);          \r
203         \r
204                 CASPAR_LOG(info) << print() << L" Initialized.";\r
205         }\r
206 \r
207         ~flash_renderer()\r
208         {               \r
209                 if(ax_)\r
210                 {\r
211                         ax_->DestroyAxControl();\r
212                         ax_->Release();\r
213                 }\r
214                 CASPAR_LOG(info) << print() << L" Uninitialized.";\r
215         }\r
216         \r
217         std::wstring call(const std::wstring& param)\r
218         {               \r
219                 std::wstring result;\r
220 \r
221                 if(!ax_->FlashCall(param, result))\r
222                         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
223                 graph_->set_tag("param");\r
224 \r
225                 return result;\r
226         }\r
227         \r
228         safe_ptr<core::basic_frame> render_frame(bool has_underflow)\r
229         {\r
230                 float frame_time = 1.0f/ax_->GetFPS();\r
231 \r
232                 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()/frame_time)*0.5f);\r
233                 tick_timer_.restart();\r
234 \r
235                 if(ax_->IsEmpty())\r
236                         return core::basic_frame::empty();              \r
237                 \r
238                 if(!has_underflow)                      \r
239                         timer_.tick(frame_time); // This will block the thread.\r
240                 else\r
241                         graph_->set_tag("skip-sync");\r
242                         \r
243                 frame_timer_.restart();\r
244 \r
245                 ax_->Tick();\r
246                 if(ax_->InvalidRect())\r
247                 {                       \r
248                         A_memset(bmp_.data(), 0, width_*height_*4);\r
249                         ax_->DrawControl(bmp_);\r
250                 \r
251                         core::pixel_format_desc desc;\r
252                         desc.pix_fmt = core::pixel_format::bgra;\r
253                         desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));\r
254                         auto frame = frame_factory_->create_frame(this, desc);\r
255 \r
256                         A_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
257                         frame->commit();\r
258                         head_ = frame;\r
259                 }               \r
260                                 \r
261                 graph_->set_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
262                 return head_;\r
263         }\r
264 \r
265         bool is_empty() const\r
266         {\r
267                 return ax_->IsEmpty();\r
268         }\r
269 \r
270         double fps() const\r
271         {\r
272                 return ax_->GetFPS();   \r
273         }\r
274         \r
275         std::wstring print()\r
276         {\r
277                 return L"flash-player[" + boost::filesystem::wpath(filename_).filename().wstring() \r
278                                   + L"|" + boost::lexical_cast<std::wstring>(width_)\r
279                                   + L"x" + boost::lexical_cast<std::wstring>(height_)\r
280                                   + L"]";               \r
281         }\r
282 };\r
283 \r
284 struct flash_producer : public core::frame_producer\r
285 {       \r
286         const std::wstring                                                                                      filename_;      \r
287         const safe_ptr<core::frame_factory>                                                     frame_factory_;\r
288 \r
289         tbb::atomic<int>                                                                                        fps_;\r
290 \r
291         safe_ptr<diagnostics::graph> graph_;\r
292 \r
293         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
294 \r
295         mutable tbb::spin_mutex                                                                         last_frame_mutex_;\r
296         safe_ptr<core::basic_frame>                                                                     last_frame_;\r
297                 \r
298         int                                                                                                                     width_;\r
299         int                                                                                                                     height_;\r
300 \r
301         tbb::atomic<bool>                                                                                       is_running_;\r
302         std::unique_ptr<flash_renderer>                                                         renderer_;\r
303 \r
304         executor                                                                                                        executor_;      \r
305 public:\r
306         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
307                 : filename_(filename)           \r
308                 , frame_factory_(frame_factory)\r
309                 , last_frame_(core::basic_frame::empty())\r
310                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
311                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
312                 , executor_(L"flash_producer")\r
313         {       \r
314                 fps_ = 0;\r
315                 is_running_ = true;\r
316 \r
317                 graph_->set_color("output-buffer-count", diagnostics::color(1.0f, 1.0f, 0.0f));          \r
318                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   \r
319                 graph_->set_text(print());\r
320                 diagnostics::register_graph(graph_);\r
321                 \r
322                 frame_buffer_.set_capacity(frame_factory_->get_video_format_desc().fps > 30.0 ? 2 : 1);\r
323 \r
324                 executor_.begin_invoke([]\r
325                 {\r
326                         ::CoInitialize(nullptr);\r
327                 });                     \r
328         }\r
329 \r
330         ~flash_producer()\r
331         {\r
332                 is_running_ = false;\r
333 \r
334                 safe_ptr<core::basic_frame> frame;\r
335                 for(int n = 0; n < 3; ++n)\r
336                         frame_buffer_.try_pop(frame);\r
337 \r
338                 executor_.invoke([this]\r
339                 {\r
340                         renderer_.reset();\r
341                         ::CoUninitialize();\r
342                 });\r
343         }\r
344 \r
345         // frame_producer\r
346                 \r
347         virtual safe_ptr<core::basic_frame> receive(int) override\r
348         {                               \r
349                 graph_->set_value("output-buffer-count", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));\r
350 \r
351                 auto frame = core::basic_frame::late();\r
352                 if(!frame_buffer_.try_pop(frame) && renderer_)\r
353                         graph_->set_tag("underflow");\r
354 \r
355                 return frame;\r
356         }\r
357 \r
358         virtual safe_ptr<core::basic_frame> last_frame() const override\r
359         {\r
360                 return lock(last_frame_mutex_, [this]\r
361                 {\r
362                         return last_frame_;\r
363                 });\r
364         }               \r
365         \r
366         virtual boost::unique_future<std::wstring> call(const std::wstring& param) override\r
367         {       \r
368                 return executor_.begin_invoke([=]() -> std::wstring\r
369                 {\r
370                         if(!is_running_)\r
371                                 return L"";\r
372 \r
373                         if(!renderer_)\r
374                         {\r
375                                 renderer_.reset(new flash_renderer(safe_ptr<diagnostics::graph>(graph_), frame_factory_, filename_, width_, height_));\r
376                                 while(frame_buffer_.try_push(core::basic_frame::empty()));\r
377                                 render(renderer_.get());\r
378                         }\r
379 \r
380                         try\r
381                         {\r
382                                 return renderer_->call(param);  \r
383 \r
384                                 //const auto& format_desc = frame_factory_->get_video_format_desc();\r
385                                 //if(abs(context_->fps() - format_desc.fps) > 0.01 && abs(context_->fps()/2.0 - format_desc.fps) > 0.01)\r
386                                 //      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
387                         }\r
388                         catch(...)\r
389                         {\r
390                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
391                                 renderer_.reset(nullptr);\r
392                                 frame_buffer_.push(core::basic_frame::empty());\r
393                         }\r
394 \r
395                         return L"";\r
396                 }, high_priority);\r
397         }\r
398                 \r
399         virtual std::wstring print() const override\r
400         { \r
401                 return L"flash[" + boost::filesystem::wpath(filename_).filename().wstring() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";            \r
402         }       \r
403 \r
404         virtual boost::property_tree::wptree info() const override\r
405         {\r
406                 boost::property_tree::wptree info;\r
407                 info.add(L"type", L"flash-producer");\r
408                 return info;\r
409         }\r
410 \r
411         // flash_producer\r
412         \r
413         safe_ptr<core::basic_frame> render_frame()\r
414         {\r
415                 auto frame = renderer_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());          \r
416                 lock(last_frame_mutex_, [&]\r
417                 {\r
418                         last_frame_ = make_safe<core::basic_frame>(frame);\r
419                 });\r
420                 return frame;\r
421         }\r
422 \r
423         void render(const flash_renderer* renderer)\r
424         {               \r
425                 executor_.begin_invoke([=]\r
426                 {\r
427                         if(!is_running_ || renderer_.get() != renderer) // Since initialize will start a new recursive call make sure the recursive calls are only for a specific instance.\r
428                                 return;\r
429 \r
430                         try\r
431                         {               \r
432                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
433 \r
434                                 if(abs(renderer_->fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
435                                 {\r
436                                         auto frame1 = render_frame();\r
437                                         auto frame2 = render_frame();\r
438                                         frame_buffer_.push(core::basic_frame::interlace(frame1, frame2, format_desc.field_mode));\r
439                                 }\r
440                                 else if(abs(renderer_->fps()- format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
441                                 {\r
442                                         auto frame = render_frame();\r
443                                         frame_buffer_.push(frame);\r
444                                         frame_buffer_.push(frame);\r
445                                 }\r
446                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
447                                 {\r
448                                         auto frame = render_frame();\r
449                                         frame_buffer_.push(frame);\r
450                                 }\r
451 \r
452                                 if(renderer_->is_empty())\r
453                                 {\r
454                                         renderer_.reset(nullptr);\r
455                                         return;\r
456                                 }\r
457 \r
458                                 graph_->set_value("output-buffer-count", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));        \r
459                                 fps_.fetch_and_store(static_cast<int>(renderer_->fps()*100.0));                         \r
460                                 graph_->set_text(print());\r
461 \r
462                                 render(renderer);\r
463                         }\r
464                         catch(...)\r
465                         {\r
466                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
467                                 renderer_.reset(nullptr);\r
468                                 frame_buffer_.push(core::basic_frame::empty());\r
469                         }\r
470                 });\r
471         }\r
472 };\r
473 \r
474 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
475 {\r
476         auto template_host = get_template_host(frame_factory->get_video_format_desc());\r
477         \r
478         auto filename = env::template_folder() + L"\\" + template_host.filename;\r
479         \r
480         if(!boost::filesystem::exists(filename))\r
481                 BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(u8(filename)));      \r
482 \r
483         return create_producer_print_proxy(\r
484                    create_producer_destroy_proxy(\r
485                         make_safe<flash_producer>(frame_factory, filename, template_host.width, template_host.height)));\r
486 }\r
487 \r
488 std::wstring find_template(const std::wstring& template_name)\r
489 {\r
490         if(boost::filesystem::exists(template_name + L".ft")) \r
491                 return template_name + L".ft";\r
492         \r
493         if(boost::filesystem::exists(template_name + L".ct"))\r
494                 return template_name + L".ct";\r
495         \r
496         if(boost::filesystem::exists(template_name + L".swf"))\r
497                 return template_name + L".swf";\r
498 \r
499         return L"";\r
500 }\r
501 \r
502 }}