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