]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
2.1.0: Merged trunk.
[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/com_context.h>\r
41 #include <common/diagnostics/graph.h>\r
42 #include <common/utility/timer.h>\r
43 \r
44 #include <boost/filesystem.hpp>\r
45 #include <boost/property_tree/ptree.hpp>\r
46 #include <boost/thread.hpp>\r
47 #include <boost/timer.hpp>\r
48 #include <boost/algorithm/string.hpp>\r
49 \r
50 #include <tbb/spin_mutex.h>\r
51 \r
52 #include <asmlib.h>\r
53 \r
54 #include <functional>\r
55 \r
56 namespace caspar { namespace flash {\r
57                 \r
58 class bitmap\r
59 {\r
60 public:\r
61         bitmap(size_t width, size_t height)\r
62                 : bmp_data_(nullptr)\r
63                 , hdc_(CreateCompatibleDC(0), DeleteDC)\r
64         {       \r
65                 BITMAPINFO info;\r
66                 memset(&info, 0, sizeof(BITMAPINFO));\r
67                 info.bmiHeader.biBitCount = 32;\r
68                 info.bmiHeader.biCompression = BI_RGB;\r
69                 info.bmiHeader.biHeight = static_cast<LONG>(-height);\r
70                 info.bmiHeader.biPlanes = 1;\r
71                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
72                 info.bmiHeader.biWidth = static_cast<LONG>(width);\r
73 \r
74                 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);\r
75                 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get()); \r
76 \r
77                 if(!bmp_data_)\r
78                         BOOST_THROW_EXCEPTION(std::bad_alloc());\r
79         }\r
80 \r
81         operator HDC() {return static_cast<HDC>(hdc_.get());}\r
82 \r
83         BYTE* data() { return bmp_data_;}\r
84         const BYTE* data() const { return bmp_data_;}\r
85 \r
86 private:\r
87         BYTE* bmp_data_;        \r
88         std::shared_ptr<void> hdc_;\r
89         std::shared_ptr<void> bmp_;\r
90 };\r
91 \r
92 struct template_host\r
93 {\r
94         std::wstring  video_mode;\r
95         std::wstring  filename;\r
96         int                       width;\r
97         int                       height;\r
98 };\r
99 \r
100 template_host get_template_host(const core::video_format_desc& desc)\r
101 {\r
102         try\r
103         {\r
104                 std::vector<template_host> template_hosts;\r
105                 BOOST_FOREACH(auto& xml_mapping, env::properties().get_child(L"configuration.template-hosts"))\r
106                 {\r
107                         try\r
108                         {\r
109                                 template_host template_host;\r
110                                 template_host.video_mode                = xml_mapping.second.get(L"video-mode", L"");\r
111                                 template_host.filename                  = xml_mapping.second.get(L"filename",   L"cg.fth");\r
112                                 template_host.width                             = xml_mapping.second.get(L"width",              desc.width);\r
113                                 template_host.height                    = xml_mapping.second.get(L"height",             desc.height);\r
114                                 template_hosts.push_back(template_host);\r
115                         }\r
116                         catch(...){}\r
117                 }\r
118 \r
119                 auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == desc.name;});\r
120                 if(template_host_it == template_hosts.end())\r
121                         template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == L"";});\r
122 \r
123                 if(template_host_it != template_hosts.end())\r
124                         return *template_host_it;\r
125         }\r
126         catch(...){}\r
127                 \r
128         template_host template_host;\r
129         template_host.filename = L"cg.fth";\r
130 \r
131         for(auto it = boost::filesystem::directory_iterator(env::template_folder()); it != boost::filesystem::directory_iterator(); ++it)\r
132         {\r
133                 if(boost::iequals(it->path().extension().wstring(), L"." + desc.name))\r
134                 {\r
135                         template_host.filename = it->path().filename().wstring();\r
136                         break;\r
137                 }\r
138         }\r
139 \r
140         template_host.width =  desc.square_width;\r
141         template_host.height = desc.square_height;\r
142         return template_host;\r
143 }\r
144 \r
145 class flash_renderer\r
146 {       \r
147         const std::wstring filename_;\r
148 \r
149         const std::shared_ptr<core::frame_factory> frame_factory_;\r
150         \r
151         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
152         safe_ptr<core::basic_frame> head_;\r
153         bitmap bmp_;\r
154         \r
155         safe_ptr<diagnostics::graph> graph_;\r
156         boost::timer frame_timer_;\r
157         boost::timer tick_timer_;\r
158 \r
159         high_prec_timer timer_;\r
160 \r
161         const int width_;\r
162         const int height_;\r
163         \r
164 public:\r
165         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
166                 : graph_(graph)\r
167                 , filename_(filename)\r
168                 , frame_factory_(frame_factory)\r
169                 , ax_(nullptr)\r
170                 , head_(core::basic_frame::empty())\r
171                 , bmp_(width, height)\r
172                 , width_(width)\r
173                 , height_(height)\r
174         {               \r
175                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
176                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));\r
177                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));       \r
178                 graph_->set_color("skip-sync", diagnostics::color(0.8f, 0.3f, 0.2f));                   \r
179                 \r
180                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
181                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to create FlashAxContainer"));\r
182                 \r
183                 ax_->set_print([this]{return print();});\r
184 \r
185                 if(FAILED(ax_->CreateAxControl()))\r
186                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Create FlashAxControl"));\r
187                 \r
188                 CComPtr<IShockwaveFlash> spFlash;\r
189                 if(FAILED(ax_->QueryControl(&spFlash)))\r
190                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Query FlashAxControl"));\r
191                                                                                                 \r
192                 if(FAILED(spFlash->put_Playing(true)) )\r
193                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to start playing Flash"));\r
194 \r
195                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
196                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Load Template Host"));\r
197                                                                                 \r
198                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
199                         BOOST_THROW_EXCEPTION(caspar_exception() << wmsg_info(print() + L" Failed to Set Scale Mode"));\r
200                                                 \r
201                 ax_->SetSize(width_, height_);          \r
202         \r
203                 CASPAR_LOG(info) << print() << L" Initialized.";\r
204         }\r
205 \r
206         ~flash_renderer()\r
207         {               \r
208                 if(ax_)\r
209                 {\r
210                         ax_->DestroyAxControl();\r
211                         ax_->Release();\r
212                 }\r
213                 CASPAR_LOG(info) << print() << L" Uninitialized.";\r
214         }\r
215         \r
216         std::wstring call(const std::wstring& param)\r
217         {               \r
218                 std::wstring result;\r
219 \r
220                 if(!ax_->FlashCall(param, result))\r
221                         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
222                 graph_->set_tag("param");\r
223 \r
224                 return result;\r
225         }\r
226         \r
227         safe_ptr<core::basic_frame> render_frame(bool has_underflow)\r
228         {\r
229                 float frame_time = 1.0f/ax_->GetFPS();\r
230 \r
231                 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()/frame_time)*0.5f);\r
232                 tick_timer_.restart();\r
233 \r
234                 if(ax_->IsEmpty())\r
235                         return core::basic_frame::empty();              \r
236                 \r
237                 if(!has_underflow)                      \r
238                         timer_.tick(frame_time); // This will block the thread.\r
239                 else\r
240                         graph_->set_tag("skip-sync");\r
241                         \r
242                 frame_timer_.restart();\r
243 \r
244                 ax_->Tick();\r
245                 if(ax_->InvalidRect())\r
246                 {                       \r
247                         A_memset(bmp_.data(), 0, width_*height_*4);\r
248                         ax_->DrawControl(bmp_);\r
249                 \r
250                         core::pixel_format_desc desc;\r
251                         desc.pix_fmt = core::pixel_format::bgra;\r
252                         desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));\r
253                         auto frame = frame_factory_->create_frame(this, desc);\r
254 \r
255                         A_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
256                         frame->commit();\r
257                         head_ = frame;\r
258                 }               \r
259                                 \r
260                 graph_->set_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
261                 return head_;\r
262         }\r
263 \r
264         bool is_empty() const\r
265         {\r
266                 return ax_->IsEmpty();\r
267         }\r
268 \r
269         double fps() const\r
270         {\r
271                 return ax_->GetFPS();   \r
272         }\r
273         \r
274         std::wstring print()\r
275         {\r
276                 return L"flash-player[" + boost::filesystem::wpath(filename_).filename().wstring() \r
277                                   + L"|" + boost::lexical_cast<std::wstring>(width_)\r
278                                   + L"x" + boost::lexical_cast<std::wstring>(height_)\r
279                                   + L"]";               \r
280         }\r
281 };\r
282 \r
283 struct flash_producer : public core::frame_producer\r
284 {       \r
285         const std::wstring                                                                                      filename_;      \r
286         const safe_ptr<core::frame_factory>                                                     frame_factory_;\r
287 \r
288         tbb::atomic<int>                                                                                        fps_;\r
289 \r
290         safe_ptr<diagnostics::graph> graph_;\r
291 \r
292         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>>      frame_buffer_;\r
293 \r
294         mutable tbb::spin_mutex                                                                         last_frame_mutex_;\r
295         safe_ptr<core::basic_frame>                                                                     last_frame_;\r
296                 \r
297         int                                                                                                                     width_;\r
298         int                                                                                                                     height_;\r
299 \r
300         com_context<flash_renderer>                                                                     context_;       \r
301 \r
302 public:\r
303         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
304                 : filename_(filename)           \r
305                 , frame_factory_(frame_factory)\r
306                 , last_frame_(core::basic_frame::empty())\r
307                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
308                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
309                 , context_(L"flash_producer")\r
310         {       \r
311                 fps_ = 0;\r
312 \r
313                 graph_->set_color("output-buffer-count", diagnostics::color(1.0f, 1.0f, 0.0f));          \r
314                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   \r
315                 graph_->set_text(print());\r
316                 diagnostics::register_graph(graph_);\r
317                 \r
318                 frame_buffer_.set_capacity(frame_factory_->get_video_format_desc().fps > 30.0 ? 2 : 1);\r
319 \r
320                 initialize();                           \r
321         }\r
322 \r
323         ~flash_producer()\r
324         {\r
325                 frame_buffer_.clear();\r
326         }\r
327 \r
328         // frame_producer\r
329                 \r
330         virtual safe_ptr<core::basic_frame> receive(int) override\r
331         {                               \r
332                 graph_->set_value("output-buffer-count", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));\r
333 \r
334                 auto frame = core::basic_frame::late();\r
335                 if(!frame_buffer_.try_pop(frame) && context_)\r
336                         graph_->set_tag("underflow");\r
337 \r
338                 return frame;\r
339         }\r
340 \r
341         virtual safe_ptr<core::basic_frame> last_frame() const override\r
342         {\r
343                 tbb::spin_mutex::scoped_lock lock(last_frame_mutex_);\r
344                 return last_frame_;\r
345         }               \r
346         \r
347         virtual boost::unique_future<std::wstring> call(const std::wstring& param) override\r
348         {       \r
349                 return context_.begin_invoke([=]() -> std::wstring\r
350                 {\r
351                         if(!context_)\r
352                                 initialize();\r
353 \r
354                         try\r
355                         {\r
356                                 return context_->call(param);   \r
357 \r
358                                 //const auto& format_desc = frame_factory_->get_video_format_desc();\r
359                                 //if(abs(context_->fps() - format_desc.fps) > 0.01 && abs(context_->fps()/2.0 - format_desc.fps) > 0.01)\r
360                                 //      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
361                         }\r
362                         catch(...)\r
363                         {\r
364                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
365                                 context_.reset(nullptr);\r
366                                 frame_buffer_.push(core::basic_frame::empty());\r
367                         }\r
368 \r
369                         return L"";\r
370                 });\r
371         }\r
372                 \r
373         virtual std::wstring print() const override\r
374         { \r
375                 return L"flash[" + boost::filesystem::wpath(filename_).filename().wstring() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";            \r
376         }       \r
377 \r
378         virtual boost::property_tree::wptree info() const override\r
379         {\r
380                 boost::property_tree::wptree info;\r
381                 info.add(L"type", L"flash-producer");\r
382                 return info;\r
383         }\r
384 \r
385         // flash_producer\r
386 \r
387         void initialize()\r
388         {\r
389                 context_.reset([&]{return new flash_renderer(safe_ptr<diagnostics::graph>(graph_), frame_factory_, filename_, width_, height_);});\r
390                 while(frame_buffer_.try_push(core::basic_frame::empty())){}             \r
391                 render(context_.get());\r
392         }\r
393 \r
394         safe_ptr<core::basic_frame> render_frame()\r
395         {\r
396                 auto frame = context_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());           \r
397                 tbb::spin_mutex::scoped_lock lock(last_frame_mutex_);\r
398                 last_frame_ = make_safe<core::basic_frame>(frame);\r
399                 return frame;\r
400         }\r
401 \r
402         void render(const flash_renderer* renderer)\r
403         {               \r
404                 context_.begin_invoke([=]\r
405                 {\r
406                         if(context_.get() != renderer) // Since initialize will start a new recursive call make sure the recursive calls are only for a specific instance.\r
407                                 return;\r
408 \r
409                         try\r
410                         {               \r
411                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
412 \r
413                                 if(abs(context_->fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
414                                 {\r
415                                         auto frame1 = render_frame();\r
416                                         auto frame2 = render_frame();\r
417                                         frame_buffer_.push(core::basic_frame::interlace(frame1, frame2, format_desc.field_mode));\r
418                                 }\r
419                                 else if(abs(context_->fps()- format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
420                                 {\r
421                                         auto frame = render_frame();\r
422                                         frame_buffer_.push(frame);\r
423                                         frame_buffer_.push(frame);\r
424                                 }\r
425                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
426                                 {\r
427                                         auto frame = render_frame();\r
428                                         frame_buffer_.push(frame);\r
429                                 }\r
430 \r
431                                 if(context_->is_empty())\r
432                                 {\r
433                                         context_.reset(nullptr);\r
434                                         return;\r
435                                 }\r
436 \r
437                                 graph_->set_value("output-buffer-count", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));        \r
438                                 fps_.fetch_and_store(static_cast<int>(context_->fps()*100.0));                          \r
439                                 graph_->set_text(print());\r
440 \r
441                                 render(renderer);\r
442                         }\r
443                         catch(...)\r
444                         {\r
445                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
446                                 context_.reset(nullptr);\r
447                                 frame_buffer_.push(core::basic_frame::empty());\r
448                         }\r
449                 });\r
450         }\r
451 };\r
452 \r
453 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
454 {\r
455         auto template_host = get_template_host(frame_factory->get_video_format_desc());\r
456         \r
457         auto filename = env::template_folder() + L"\\" + template_host.filename;\r
458         \r
459         if(!boost::filesystem::exists(filename))\r
460                 BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(u8(filename)));      \r
461 \r
462         return create_producer_destroy_proxy(make_safe<flash_producer>(frame_factory, filename, template_host.width, template_host.height));\r
463 }\r
464 \r
465 std::wstring find_template(const std::wstring& template_name)\r
466 {\r
467         if(boost::filesystem::exists(template_name + L".ft")) \r
468                 return template_name + L".ft";\r
469         \r
470         if(boost::filesystem::exists(template_name + L".ct"))\r
471                 return template_name + L".ct";\r
472         \r
473         if(boost::filesystem::exists(template_name + L".swf"))\r
474                 return template_name + L".swf";\r
475 \r
476         return L"";\r
477 }\r
478 \r
479 }}