]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
git-svn-id: https://casparcg.svn.sourceforge.net/svnroot/casparcg/server/branches...
[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/concurrency/throw_away.h>\r
38 #include <common/diagnostics/graph.h>\r
39 #include <common/env.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 \r
48 #include <functional>\r
49 \r
50 #include <agents.h>\r
51 #include <agents_extras.h>\r
52 #include <concrt_extras.h>\r
53 \r
54 using namespace Concurrency;\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 = -height;\r
70                 info.bmiHeader.biPlanes = 1;\r
71                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
72                 info.bmiHeader.biWidth = 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::string  field_mode;\r
95         std::string  filename;\r
96         size_t           width;\r
97         size_t           height;\r
98 };\r
99 \r
100 template_host get_template_host(const core::video_format_desc& desc)\r
101 {\r
102         std::vector<template_host> template_hosts;\r
103         BOOST_FOREACH(auto& xml_mapping, env::properties().get_child("configuration.producers.template-hosts"))\r
104         {\r
105                 try\r
106                 {\r
107                         template_host template_host;\r
108                         template_host.field_mode                = xml_mapping.second.get("video-mode", narrow(desc.name));\r
109                         template_host.filename                  = xml_mapping.second.get("filename", "cg.fth");\r
110                         template_host.width                             = xml_mapping.second.get("width", desc.width);\r
111                         template_host.height                    = xml_mapping.second.get("height", desc.height);\r
112                         template_hosts.push_back(template_host);\r
113                 }\r
114                 catch(...){}\r
115         }\r
116 \r
117         auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.field_mode == narrow(desc.name);});\r
118         if(template_host_it == template_hosts.end())\r
119                 template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.field_mode == "";});\r
120 \r
121         if(template_host_it != template_hosts.end())\r
122                 return *template_host_it;\r
123         \r
124         template_host template_host;\r
125         template_host.filename = "cg.fth";\r
126         template_host.width = desc.width;\r
127         template_host.height = desc.height;\r
128         return template_host;\r
129 }\r
130 \r
131 class flash_player\r
132 {\r
133         const std::wstring      filename_;\r
134         const size_t            width_;\r
135         const size_t            height_;\r
136         CComObject<caspar::flash::FlashAxContainer>*    ax_;\r
137 public:\r
138         flash_player(const std::wstring& filename, size_t width, size_t height)\r
139                 : filename_(filename)\r
140                 , width_(width)\r
141                 , height_(height)\r
142         {               \r
143                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
144                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to create FlashAxContainer"));\r
145                 \r
146                 ax_->set_print([this]{return L"flash_renderer";});\r
147 \r
148                 if(FAILED(ax_->CreateAxControl()))\r
149                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Create FlashAxControl"));\r
150                 \r
151                 CComPtr<IShockwaveFlash> spFlash;\r
152                 if(FAILED(ax_->QueryControl(&spFlash)))\r
153                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Query FlashAxControl"));\r
154                                                                                                 \r
155                 if(FAILED(spFlash->put_Playing(true)) )\r
156                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start playing Flash"));\r
157 \r
158                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
159                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Load Template Host"));\r
160                                                                                 \r
161                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
162                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Set Scale Mode"));\r
163                                                 \r
164                 ax_->SetSize(width, height);    \r
165 \r
166                 CASPAR_LOG(info) << "Initialized" << print();\r
167         }\r
168 \r
169         ~flash_player()\r
170         {\r
171                 if(ax_)\r
172                 {\r
173                         ax_->DestroyAxControl();\r
174                         ax_->Release();\r
175                 }\r
176                 CASPAR_LOG(info) << "Uninitialized " << print();\r
177         }\r
178 \r
179         bool is_empty() const\r
180         {\r
181                 return ax_->IsEmpty();\r
182         }\r
183 \r
184         void tick()\r
185         {\r
186                 ax_->Tick();\r
187         }\r
188 \r
189         bool invalid_rect() const\r
190         {\r
191                 return ax_->InvalidRect();\r
192         }\r
193 \r
194         bool draw_control(HDC targetDC)\r
195         {\r
196                 return ax_->DrawControl(targetDC);\r
197         }\r
198 \r
199         bool flash_call(const std::wstring& param)\r
200         {\r
201                 return ax_->FlashCall(param);\r
202         }\r
203 \r
204         double fps() const\r
205         {\r
206                 return ax_->GetFPS();\r
207         }\r
208 \r
209         std::wstring print()\r
210         {\r
211                 return L"flash-player[" + boost::filesystem::wpath(filename_).filename() + L"|" + boost::lexical_cast<std::wstring>(width_) + L"|" + boost::lexical_cast<std::wstring>(height_) + L"]";         \r
212         }\r
213 };\r
214 \r
215 class flash_renderer\r
216 {       \r
217         const std::wstring                                                              filename_;\r
218 \r
219         const safe_ptr<core::frame_factory>                             frame_factory_;\r
220         safe_ptr<diagnostics::graph>                                    graph_;\r
221 \r
222         high_prec_timer                                                                 timer_;\r
223         safe_ptr<core::basic_frame>                                             head_;\r
224         bitmap                                                                                  bmp_;\r
225 \r
226         const size_t                                                                    width_;\r
227         const size_t                                                                    height_;\r
228                         \r
229         boost::timer                                                                    frame_timer_;\r
230         boost::timer                                                                    tick_timer_;\r
231 \r
232         std::unique_ptr<flash_player>                                   player_;\r
233         \r
234 public:\r
235         flash_renderer(const safe_ptr<diagnostics::graph>& graph, const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
236                 : filename_(filename)\r
237                 , frame_factory_(frame_factory)\r
238                 , graph_(graph)\r
239                 , head_(core::basic_frame::empty())\r
240                 , bmp_(width, height)\r
241                 , width_(width)\r
242                 , height_(height)\r
243         {               \r
244                 graph_->add_guide("frame-time", 0.5f);\r
245                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
246                 graph_->add_guide("tick-time", 0.5);\r
247                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));\r
248                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));               \r
249         }\r
250                 \r
251         bool param(const std::wstring& param)\r
252         {               \r
253                 if(!player_)\r
254                         player_.reset(new flash_player(filename_, width_, height_));\r
255 \r
256                 bool success = player_->flash_call(param); \r
257                 if(!success)\r
258                         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
259                 else\r
260                         graph_->add_tag("param");\r
261                 return success;\r
262         }\r
263         \r
264         safe_ptr<core::basic_frame> operator()()\r
265         {\r
266                 if(player_ && player_->is_empty())\r
267                         player_.reset();\r
268 \r
269                 if(!player_)\r
270                 {\r
271                         graph_->update_value("tick-time", 0.0);\r
272                         return core::basic_frame::empty();      \r
273                 }\r
274 \r
275                 const float frame_time = 1.0f/player_->fps();\r
276 \r
277                 graph_->update_value("tick-time", static_cast<float>(tick_timer_.elapsed()/frame_time)*0.5f);\r
278                 tick_timer_.restart();\r
279                 \r
280                 Concurrency::scoped_oversubcription_token oversubscribe;\r
281                 timer_.tick(frame_time); // This will block the thread.\r
282                 //Concurrency::wait(std::max<int>(0, frame_time-3));\r
283                         \r
284                 frame_timer_.restart();\r
285 \r
286                 player_->tick();\r
287                 if(player_->invalid_rect())\r
288                 {                       \r
289                         fast_memclr(bmp_.data(), width_*height_*4);\r
290                         player_->draw_control(bmp_);\r
291                 \r
292                         auto frame = frame_factory_->create_frame(this, width_, height_);\r
293                         fast_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
294                         frame->commit();\r
295                         head_ = frame;\r
296                 }               \r
297                                 \r
298                 graph_->update_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
299                 return head_;\r
300         }\r
301 \r
302         double fps() const\r
303         {\r
304                 return player_ ? player_->fps() : 0.0;  \r
305         }\r
306         \r
307         std::wstring print()\r
308         {\r
309                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"]";               \r
310         }\r
311 };\r
312 \r
313 struct flash_producer : public Concurrency::agent, public core::frame_producer\r
314 {       \r
315         unbounded_buffer<std::wstring>                                                          params_;\r
316         bounded_buffer<safe_ptr<core::basic_frame>>                                     frames_;\r
317 \r
318         tbb::atomic<bool>                                                                                       is_running_;\r
319                 \r
320         const safe_ptr<core::frame_factory>                                                     frame_factory_;\r
321         const std::wstring                                                                                      filename_;      \r
322         tbb::atomic<int>                                                                                        fps_;\r
323         const int                                                                                                       width_;\r
324         const int                                                                                                       height_;\r
325                 \r
326         mutable overwrite_buffer<safe_ptr<core::basic_frame>>           last_frame_;\r
327 \r
328         safe_ptr<diagnostics::graph>                                                            graph_;\r
329                                 \r
330 public:\r
331         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, size_t width, size_t height) \r
332                 : frames_(frame_factory->get_video_format_desc().fps > 30.0 ? 2 : 1)\r
333                 , frame_factory_(frame_factory)\r
334                 , filename_(filename)           \r
335                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
336                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
337         {       \r
338                 if(!boost::filesystem::exists(filename))\r
339                         BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(narrow(filename)));  \r
340                 \r
341                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));\r
342                 graph_->set_text(print());\r
343                 diagnostics::register_graph(graph_);\r
344 \r
345                 Concurrency::send(last_frame_, core::basic_frame::empty());\r
346                 \r
347                 fps_            = 0;\r
348                 is_running_ = true;\r
349 \r
350                 start();\r
351         }\r
352 \r
353         ~flash_producer()\r
354         {\r
355                 is_running_ = false;\r
356                 link_throw_away(frames_);\r
357                 agent::wait(this);\r
358         }\r
359         \r
360         virtual void run()\r
361         {               \r
362                 try\r
363                 {\r
364                         struct co_init\r
365                         {\r
366                                 co_init()  {CoInitialize(NULL);}\r
367                                 ~co_init() {CoUninitialize();}\r
368                         } init;\r
369 \r
370                         flash_renderer renderer(graph_, frame_factory_, filename_, width_, height_);\r
371 \r
372                         is_running_ = true;\r
373                         while(is_running_)\r
374                         {\r
375                                 std::wstring param;\r
376                                 while(is_running_ && Concurrency::try_receive(params_, param))\r
377                                         renderer.param(param);\r
378                         \r
379                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
380 \r
381                                 if(abs(renderer.fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
382                                 {\r
383                                         auto frame1 = renderer();\r
384                                         auto frame2 = renderer();\r
385                                         send(last_frame_, frame2);\r
386                                         send(frames_, core::basic_frame::interlace(frame1, frame2, format_desc.field_mode));\r
387                                 }\r
388                                 else if(abs(renderer.fps()- format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
389                                 {\r
390                                         auto frame = renderer();\r
391                                         send(last_frame_, frame);\r
392                                         send(frames_, frame);\r
393                                         send(frames_, frame);\r
394                                 }\r
395                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
396                                 {\r
397                                         auto frame = renderer();\r
398                                         send(last_frame_, frame);\r
399                                         send(frames_, frame);\r
400                                 }\r
401 \r
402                                 fps_ = static_cast<int>(renderer.fps()*100.0);\r
403                                 graph_->set_text(narrow(print()));\r
404                         }\r
405                 }\r
406                 catch(...)\r
407                 {\r
408                         CASPAR_LOG_CURRENT_EXCEPTION();\r
409                 }\r
410                 \r
411                 is_running_ = false;\r
412                 done();\r
413         }\r
414         \r
415         // frame_producer\r
416                 \r
417         virtual safe_ptr<core::basic_frame> receive(int)\r
418         {                                               \r
419                 auto frame = core::basic_frame::late();\r
420 \r
421                 try\r
422                 {\r
423                         frame = Concurrency::receive(frames_, 5);\r
424                 }\r
425                 catch(operation_timed_out&)\r
426                 {                       \r
427                         graph_->add_tag("underflow");\r
428                 }\r
429 \r
430                 return frame;\r
431         }\r
432 \r
433         virtual safe_ptr<core::basic_frame> last_frame() const\r
434         {\r
435                 return last_frame_.value();\r
436         }               \r
437         \r
438         virtual bool param(const std::wstring& param) \r
439         {       \r
440                 if(!is_running_.fetch_and_store(true))\r
441                 {\r
442                         agent::wait(this);\r
443                         start();\r
444                 }\r
445                 asend(params_, param);\r
446                 return true;\r
447         }\r
448                 \r
449         virtual std::wstring print() const\r
450         { \r
451                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";              \r
452         }       \r
453 };\r
454 \r
455 safe_ptr<core::frame_producer> create_flash_producer(const safe_ptr<core::frame_factory> frame_factory, const std::vector<std::wstring>& params)\r
456 {               \r
457         static const std::vector<std::wstring> extensions = boost::assign::list_of\r
458                 (L"swf");\r
459 \r
460         std::wstring filename = env::media_folder() + L"\\" + params[0];\r
461         \r
462         auto ext = boost::find_if(extensions, [&](const std::wstring& ex)\r
463         {                                       \r
464                 return boost::filesystem::is_regular_file(boost::filesystem::wpath(filename + L"." + ex));\r
465         });\r
466 \r
467         if(ext == extensions.end())\r
468                 return core::frame_producer::empty();\r
469                 \r
470         auto path = filename + L"." + *ext;\r
471         return make_safe<flash_producer>(frame_factory, path, 0, 0);\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         return make_safe<flash_producer>(frame_factory, env::template_folder() + L"\\" + widen(template_host.filename), template_host.width, template_host.height);\r
479 }\r
480 \r
481 std::wstring find_template(const std::wstring& template_name)\r
482 {\r
483         if(boost::filesystem::exists(template_name + L".ft")) \r
484                 return template_name + L".ft";\r
485         \r
486         if(boost::filesystem::exists(template_name + L".ct"))\r
487                 return template_name + L".ct";\r
488 \r
489         return L"";\r
490 }\r
491 \r
492 }}