]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
da8a34d26e89691d5d43b2aafc85f3c2cef7fadd
[casparcg] / modules / flash / producer / flash_producer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\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 */\r
20  \r
21 #include "../stdafx.h"\r
22 \r
23 #if defined(_MSC_VER)\r
24 #pragma warning (disable : 4146)\r
25 #pragma warning (disable : 4244)\r
26 #endif\r
27 \r
28 #include "flash_producer.h"\r
29 #include "FlashAxContainer.h"\r
30 \r
31 #include <core/video_format.h>\r
32 \r
33 #include <core/producer/frame/basic_frame.h>\r
34 #include <core/producer/frame/frame_factory.h>\r
35 #include <core/mixer/write_frame.h>\r
36 \r
37 #include <common/env.h>\r
38 #include <common/concurrency/com_context.h>\r
39 #include <common/diagnostics/graph.h>\r
40 #include <common/memory/memcpy.h>\r
41 #include <common/memory/memclr.h>\r
42 #include <common/utility/timer.h>\r
43 \r
44 #include <boost/filesystem.hpp>\r
45 #include <boost/thread.hpp>\r
46 #include <boost/timer.hpp>\r
47 #include <boost/algorithm/string.hpp>\r
48 \r
49 #include <functional>\r
50 \r
51 #include <tbb/spin_mutex.h>\r
52 \r
53 namespace caspar { namespace flash {\r
54                 \r
55 class bitmap\r
56 {\r
57 public:\r
58         bitmap(size_t width, size_t height)\r
59                 : bmp_data_(nullptr)\r
60                 , hdc_(CreateCompatibleDC(0), DeleteDC)\r
61         {       \r
62                 BITMAPINFO info;\r
63                 memset(&info, 0, sizeof(BITMAPINFO));\r
64                 info.bmiHeader.biBitCount = 32;\r
65                 info.bmiHeader.biCompression = BI_RGB;\r
66                 info.bmiHeader.biHeight = -height;\r
67                 info.bmiHeader.biPlanes = 1;\r
68                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
69                 info.bmiHeader.biWidth = width;\r
70 \r
71                 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);\r
72                 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get()); \r
73 \r
74                 if(!bmp_data_)\r
75                         BOOST_THROW_EXCEPTION(std::bad_alloc());\r
76         }\r
77 \r
78         operator HDC() {return static_cast<HDC>(hdc_.get());}\r
79 \r
80         BYTE* data() { return bmp_data_;}\r
81         const BYTE* data() const { return bmp_data_;}\r
82 \r
83 private:\r
84         BYTE* bmp_data_;        \r
85         std::shared_ptr<void> hdc_;\r
86         std::shared_ptr<void> bmp_;\r
87 };\r
88 \r
89 struct template_host\r
90 {\r
91         std::string  field_mode;\r
92         std::string  filename;\r
93         size_t           width;\r
94         size_t           height;\r
95 };\r
96 \r
97 template_host get_template_host(const core::video_format_desc& desc)\r
98 {\r
99         try\r
100         {\r
101                 std::vector<template_host> template_hosts;\r
102                 BOOST_FOREACH(auto& xml_mapping, env::properties().get_child("configuration.template-hosts"))\r
103                 {\r
104                         try\r
105                         {\r
106                                 template_host template_host;\r
107                                 template_host.field_mode                = xml_mapping.second.get("video-mode", narrow(desc.name));\r
108                                 template_host.filename                  = xml_mapping.second.get("filename", "cg.fth");\r
109                                 template_host.width                             = xml_mapping.second.get("width", desc.width);\r
110                                 template_host.height                    = xml_mapping.second.get("height", desc.height);\r
111                                 template_hosts.push_back(template_host);\r
112                         }\r
113                         catch(...){}\r
114                 }\r
115 \r
116                 auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.field_mode == narrow(desc.name);});\r
117                 if(template_host_it == template_hosts.end())\r
118                         template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.field_mode == "";});\r
119 \r
120                 if(template_host_it != template_hosts.end())\r
121                         return *template_host_it;\r
122         }\r
123         catch(...)\r
124         {\r
125         }\r
126                 \r
127         template_host template_host;\r
128         template_host.filename = "cg.fth";\r
129 \r
130         for(auto it = boost::filesystem2::wdirectory_iterator(env::template_folder()); it != boost::filesystem2::wdirectory_iterator(); ++it)\r
131         {\r
132                 if(boost::iequals(it->path().extension(), L"." + desc.name))\r
133                 {\r
134                         template_host.filename = narrow(it->filename());\r
135                         break;\r
136                 }\r
137         }\r
138 \r
139         template_host.width = desc.square_width;\r
140         template_host.height = desc.square_height;\r
141         return template_host;\r
142 }\r
143 \r
144 class flash_renderer\r
145 {       \r
146         const std::wstring filename_;\r
147 \r
148         const std::shared_ptr<core::frame_factory> frame_factory_;\r
149         \r
150         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
151         safe_ptr<core::basic_frame> head_;\r
152         bitmap bmp_;\r
153         \r
154         safe_ptr<diagnostics::graph> graph_;\r
155         boost::timer frame_timer_;\r
156         boost::timer tick_timer_;\r
157 \r
158         high_prec_timer timer_;\r
159 \r
160         const size_t width_;\r
161         const size_t height_;\r
162         \r
163 public:\r
164         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
165                 : graph_(graph)\r
166                 , filename_(filename)\r
167                 , frame_factory_(frame_factory)\r
168                 , ax_(nullptr)\r
169                 , head_(core::basic_frame::empty())\r
170                 , bmp_(width, height)\r
171                 , width_(width)\r
172                 , height_(height)\r
173         {               \r
174                 graph_->add_guide("frame-time", 0.5f);\r
175                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
176                 graph_->add_guide("tick-time", 0.5);\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() << msg_info(narrow(print()) + " Failed to create FlashAxContainer"));\r
183                 \r
184                 ax_->set_print([this]{return L"flash_renderer";});\r
185 \r
186                 if(FAILED(ax_->CreateAxControl()))\r
187                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " 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() << msg_info(narrow(print()) + " Failed to Query FlashAxControl"));\r
192                                                                                                 \r
193                 if(FAILED(spFlash->put_Playing(true)) )\r
194                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " 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() << msg_info(narrow(print()) + " 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() << msg_info(narrow(print()) + " Failed to Set Scale Mode"));\r
201                                                 \r
202                 ax_->SetSize(width_, height_);          \r
203         \r
204                 CASPAR_LOG(info) << print() << L" Successfully initialized with template-host: " << filename << L" width: " << width_ << L" height: " << height_ << L".";\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_->add_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_->update_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_->add_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                         fast_memclr(bmp_.data(), width_*height_*4);\r
249                         ax_->DrawControl(bmp_);\r
250                 \r
251                         auto frame = frame_factory_->create_frame(this, width_, height_);\r
252                         fast_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
253                         frame->commit();\r
254                         head_ = frame;\r
255                 }               \r
256                                 \r
257                 graph_->update_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
258                 return head_;\r
259         }\r
260 \r
261         bool is_empty() const\r
262         {\r
263                 return ax_->IsEmpty();\r
264         }\r
265 \r
266         double fps() const\r
267         {\r
268                 return ax_->GetFPS();   \r
269         }\r
270         \r
271         std::wstring print()\r
272         {\r
273                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"]";               \r
274         }\r
275 };\r
276 \r
277 struct flash_producer : public core::frame_producer\r
278 {       \r
279         const std::wstring filename_;   \r
280         const safe_ptr<core::frame_factory> frame_factory_;\r
281 \r
282         tbb::atomic<int> fps_;\r
283 \r
284         safe_ptr<diagnostics::graph> graph_;\r
285 \r
286         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>> frame_buffer_;\r
287 \r
288         mutable tbb::spin_mutex         last_frame_mutex_;\r
289         safe_ptr<core::basic_frame>     last_frame_;\r
290                                 \r
291         com_context<flash_renderer> context_;   \r
292 \r
293         int width_;\r
294         int height_;\r
295 public:\r
296         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, size_t width, size_t height) \r
297                 : filename_(filename)           \r
298                 , frame_factory_(frame_factory)\r
299                 , context_(L"flash_producer")\r
300                 , last_frame_(core::basic_frame::empty())\r
301                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
302                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
303         {       \r
304                 if(!boost::filesystem::exists(filename))\r
305                         BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(narrow(filename)));  \r
306 \r
307                 fps_ = 0;\r
308 \r
309                 graph_->set_color("output-buffer-count", diagnostics::color(1.0f, 1.0f, 0.0f));          \r
310                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   \r
311                 graph_->set_text(print());\r
312                 diagnostics::register_graph(graph_);\r
313                 \r
314                 frame_buffer_.set_capacity(frame_factory_->get_video_format_desc().fps > 30.0 ? 2 : 1);\r
315 \r
316                 initialize();                           \r
317         }\r
318 \r
319         ~flash_producer()\r
320         {\r
321                 frame_buffer_.clear();\r
322         }\r
323 \r
324         // frame_producer\r
325                 \r
326         virtual safe_ptr<core::basic_frame> receive(int) override\r
327         {                               \r
328                 graph_->set_value("output-buffer-count", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));\r
329 \r
330                 auto frame = core::basic_frame::late();\r
331                 if(!frame_buffer_.try_pop(frame) && context_)\r
332                         graph_->add_tag("underflow");\r
333 \r
334                 return frame;\r
335         }\r
336 \r
337         virtual safe_ptr<core::basic_frame> last_frame() const override\r
338         {\r
339                 tbb::spin_mutex::scoped_lock lock(last_frame_mutex_);\r
340                 return last_frame_;\r
341         }               \r
342         \r
343         virtual boost::unique_future<std::wstring> call(const std::wstring& param) override\r
344         {       \r
345                 return context_.begin_invoke([=]() -> std::wstring\r
346                 {\r
347                         if(!context_)\r
348                                 initialize();\r
349 \r
350                         try\r
351                         {\r
352                                 return context_->call(param);   \r
353 \r
354                                 //const auto& format_desc = frame_factory_->get_video_format_desc();\r
355                                 //if(abs(context_->fps() - format_desc.fps) > 0.01 && abs(context_->fps()/2.0 - format_desc.fps) > 0.01)\r
356                                 //      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
357                         }\r
358                         catch(...)\r
359                         {\r
360                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
361                                 context_.reset(nullptr);\r
362                                 frame_buffer_.push(core::basic_frame::empty());\r
363                         }\r
364 \r
365                         return L"";\r
366                 });\r
367         }\r
368                 \r
369         virtual std::wstring print() const override\r
370         { \r
371                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";              \r
372         }       \r
373 \r
374         // flash_producer\r
375 \r
376         void initialize()\r
377         {\r
378                 context_.reset([&]{return new flash_renderer(safe_ptr<diagnostics::graph>(graph_), frame_factory_, filename_, width_, height_);});\r
379                 while(frame_buffer_.try_push(core::basic_frame::empty())){}             \r
380                 render(context_.get());\r
381         }\r
382 \r
383         safe_ptr<core::basic_frame> render_frame()\r
384         {\r
385                 auto frame = context_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());           \r
386                 tbb::spin_mutex::scoped_lock lock(last_frame_mutex_);\r
387                 last_frame_ = make_safe<core::basic_frame>(frame);\r
388                 return frame;\r
389         }\r
390 \r
391         void render(const flash_renderer* renderer)\r
392         {               \r
393                 context_.begin_invoke([=]\r
394                 {\r
395                         if(context_.get() != renderer) // Since initialize will start a new recursive call make sure the recursive calls are only for a specific instance.\r
396                                 return;\r
397 \r
398                         try\r
399                         {               \r
400                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
401 \r
402                                 if(abs(context_->fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
403                                 {\r
404                                         auto frame1 = render_frame();\r
405                                         auto frame2 = render_frame();\r
406                                         frame_buffer_.push(core::basic_frame::interlace(frame1, frame2, format_desc.field_mode));\r
407                                 }\r
408                                 else if(abs(context_->fps()- format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
409                                 {\r
410                                         auto frame = render_frame();\r
411                                         frame_buffer_.push(frame);\r
412                                         frame_buffer_.push(frame);\r
413                                 }\r
414                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
415                                 {\r
416                                         auto frame = render_frame();\r
417                                         frame_buffer_.push(frame);\r
418                                 }\r
419 \r
420                                 if(context_->is_empty())\r
421                                 {\r
422                                         context_.reset(nullptr);\r
423                                         return;\r
424                                 }\r
425 \r
426                                 graph_->set_value("output-buffer-count", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));        \r
427                                 fps_.fetch_and_store(static_cast<int>(context_->fps()*100.0));                          \r
428                                 graph_->set_text(narrow(print()));\r
429 \r
430                                 render(renderer);\r
431                         }\r
432                         catch(...)\r
433                         {\r
434                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
435                                 context_.reset(nullptr);\r
436                                 frame_buffer_.push(core::basic_frame::empty());\r
437                         }\r
438                 });\r
439         }\r
440 };\r
441 \r
442 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
443 {\r
444         auto template_host = get_template_host(frame_factory->get_video_format_desc());\r
445         \r
446         return create_producer_destroy_proxy(make_safe<flash_producer>(frame_factory, env::template_folder() + L"\\" + widen(template_host.filename), template_host.width, template_host.height));\r
447 }\r
448 \r
449 std::wstring find_template(const std::wstring& template_name)\r
450 {\r
451         if(boost::filesystem::exists(template_name + L".ft")) \r
452                 return template_name + L".ft";\r
453         \r
454         if(boost::filesystem::exists(template_name + L".ct"))\r
455                 return template_name + L".ct";\r
456         \r
457         if(boost::filesystem::exists(template_name + L".swf"))\r
458                 return template_name + L".swf";\r
459 \r
460         return L"";\r
461 }\r
462 \r
463 }}