]> 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/env.h>\r
38 #include <common/diagnostics/graph.h>\r
39 #include <common/memory/memcpy.h>\r
40 #include <common/memory/memclr.h>\r
41 #include <common/utility/timer.h>\r
42 \r
43 #include <boost/filesystem.hpp>\r
44 #include <boost/thread.hpp>\r
45 #include <boost/timer.hpp>\r
46 \r
47 #include <functional>\r
48 \r
49 #include <agents.h>\r
50 #include <agents_extras.h>\r
51 #include <concrt_extras.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         std::vector<template_host> template_hosts;\r
100         BOOST_FOREACH(auto& xml_mapping, env::properties().get_child("configuration.producers.template-hosts"))\r
101         {\r
102                 try\r
103                 {\r
104                         template_host template_host;\r
105                         template_host.field_mode                = xml_mapping.second.get("video-mode", narrow(desc.name));\r
106                         template_host.filename                  = xml_mapping.second.get("filename", "cg.fth");\r
107                         template_host.width                             = xml_mapping.second.get("width", desc.width);\r
108                         template_host.height                    = xml_mapping.second.get("height", desc.height);\r
109                         template_hosts.push_back(template_host);\r
110                 }\r
111                 catch(...){}\r
112         }\r
113 \r
114         auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.field_mode == narrow(desc.name);});\r
115         if(template_host_it == template_hosts.end())\r
116                 template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.field_mode == "";});\r
117 \r
118         if(template_host_it != template_hosts.end())\r
119                 return *template_host_it;\r
120         \r
121         template_host template_host;\r
122         template_host.filename = "cg.fth";\r
123         template_host.width = desc.width;\r
124         template_host.height = desc.height;\r
125         return template_host;\r
126 }\r
127 \r
128 class flash_renderer\r
129 {       \r
130         const std::wstring filename_;\r
131 \r
132         const safe_ptr<core::frame_factory> frame_factory_;\r
133         \r
134         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
135         safe_ptr<core::basic_frame> head_;\r
136         bitmap bmp_;\r
137         \r
138         safe_ptr<diagnostics::graph> graph_;\r
139         boost::timer frame_timer_;\r
140         boost::timer tick_timer_;\r
141 \r
142         high_prec_timer timer_;\r
143 \r
144         const size_t width_;\r
145         const size_t height_;\r
146         \r
147 public:\r
148         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
149                 : filename_(filename)\r
150                 , frame_factory_(make_safe<core::concrt_frame_factory>(frame_factory))\r
151                 , graph_(graph)\r
152                 , ax_(nullptr)\r
153                 , head_(core::basic_frame::empty())\r
154                 , bmp_(width, height)\r
155                 , width_(width)\r
156                 , height_(height)\r
157         {               \r
158                 graph_->add_guide("frame-time", 0.5f);\r
159                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
160                 graph_->add_guide("tick-time", 0.5);\r
161                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));\r
162                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));       \r
163                 graph_->set_color("skip-sync", diagnostics::color(0.8f, 0.3f, 0.2f));                   \r
164                 \r
165                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
166                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to create FlashAxContainer"));\r
167                 \r
168                 ax_->set_print([this]{return L"flash_renderer";});\r
169 \r
170                 if(FAILED(ax_->CreateAxControl()))\r
171                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Create FlashAxControl"));\r
172                 \r
173                 CComPtr<IShockwaveFlash> spFlash;\r
174                 if(FAILED(ax_->QueryControl(&spFlash)))\r
175                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Query FlashAxControl"));\r
176                                                                                                 \r
177                 if(FAILED(spFlash->put_Playing(true)) )\r
178                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start playing Flash"));\r
179 \r
180                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
181                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Load Template Host"));\r
182                                                                                 \r
183                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
184                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Set Scale Mode"));\r
185                                                 \r
186                 ax_->SetSize(width_, height_);          \r
187         \r
188                 CASPAR_LOG(info) << print() << L" Thread started.";\r
189                 CASPAR_LOG(info) << print() << L" Successfully initialized with template-host: " << filename << L" width: " << width_ << L" height: " << height_ << L".";\r
190         }\r
191 \r
192         ~flash_renderer()\r
193         {               \r
194                 if(ax_)\r
195                 {\r
196                         ax_->DestroyAxControl();\r
197                         ax_->Release();\r
198                 }\r
199                 CASPAR_LOG(info) << print() << L" Thread ended.";\r
200         }\r
201         \r
202         void param(const std::wstring& param)\r
203         {               \r
204                 if(!ax_->FlashCall(param))\r
205                         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
206                 graph_->add_tag("param");\r
207         }\r
208         \r
209         safe_ptr<core::basic_frame> render_frame(bool has_underflow)\r
210         {\r
211                 const float frame_time = 1.0f/ax_->GetFPS();\r
212 \r
213                 graph_->update_value("tick-time", static_cast<float>(tick_timer_.elapsed()/frame_time)*0.5f);\r
214                 tick_timer_.restart();\r
215 \r
216                 if(ax_->IsEmpty())\r
217                         return core::basic_frame::empty();              \r
218                 \r
219                 if(!has_underflow)              \r
220                 {\r
221                         Concurrency::scoped_oversubcription_token oversubscribe;\r
222                         timer_.tick(frame_time); // This will block the thread.\r
223                         //Concurrency::wait(std::max<int>(0, frame_time-3));\r
224                 }\r
225                 else\r
226                         graph_->add_tag("skip-sync");\r
227                         \r
228                 frame_timer_.restart();\r
229 \r
230                 ax_->Tick();\r
231                 if(ax_->InvalidRect())\r
232                 {                       \r
233                         fast_memclr(bmp_.data(), width_*height_*4);\r
234                         ax_->DrawControl(bmp_);\r
235                 \r
236                         auto frame = frame_factory_->create_frame(this, width_, height_);\r
237                         fast_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
238                         frame->commit();\r
239                         head_ = frame;\r
240                 }               \r
241                                 \r
242                 graph_->update_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
243                 return head_;\r
244         }\r
245 \r
246         double fps() const\r
247         {\r
248                 return ax_->GetFPS();   \r
249         }\r
250         \r
251         std::wstring print()\r
252         {\r
253                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"]";               \r
254         }\r
255 };\r
256 \r
257 struct flash_producer : public Concurrency::agent, public core::frame_producer\r
258 {       \r
259         Concurrency::unbounded_buffer<std::wstring>                                     params_;\r
260         Concurrency::bounded_buffer<safe_ptr<core::basic_frame>>        frames_;\r
261 \r
262         tbb::atomic<bool>                                                                                       is_running_;\r
263                 \r
264         const safe_ptr<core::frame_factory>                                                     frame_factory_;\r
265         const std::wstring                                                                                      filename_;      \r
266         tbb::atomic<int>                                                                                        fps_;\r
267         const int                                                                                                       width_;\r
268         const int                                                                                                       height_;\r
269                 \r
270         mutable Concurrency::overwrite_buffer<safe_ptr<core::basic_frame>> last_frame_;\r
271 \r
272         safe_ptr<diagnostics::graph>                                                            graph_;\r
273                                 \r
274 public:\r
275         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, size_t width, size_t height) \r
276                 : frames_(frame_factory->get_video_format_desc().fps > 30.0 ? 2 : 1)\r
277                 , frame_factory_(frame_factory)\r
278                 , filename_(filename)           \r
279                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
280                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
281                 , graph_(diagnostics::create_graph("", false))\r
282         {       \r
283                 if(!boost::filesystem::exists(filename))\r
284                         BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(narrow(filename)));  \r
285                 \r
286                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   \r
287 \r
288                 Concurrency::send(last_frame_, core::basic_frame::empty());\r
289                 \r
290                 fps_            = 0;\r
291                 is_running_ = true;\r
292 \r
293                 graph_->start();\r
294                 start();\r
295         }\r
296 \r
297         ~flash_producer()\r
298         {\r
299                 is_running_ = false;\r
300                 auto frame = core::basic_frame::empty();\r
301                 while(Concurrency::try_receive(frames_, frame)){}\r
302                 agent::wait(this);\r
303         }\r
304         \r
305         virtual void run()\r
306         {               \r
307                 try\r
308                 {\r
309                         struct co_init\r
310                         {\r
311                                 co_init()  {CoInitialize(NULL);}\r
312                                 ~co_init() {CoUninitialize();}\r
313                         } init;\r
314 \r
315                         flash_renderer renderer(graph_, frame_factory_, filename_, width_, height_);\r
316 \r
317                         is_running_ = true;\r
318                         while(is_running_)\r
319                         {\r
320                                 std::wstring param;\r
321                                 while(is_running_ && Concurrency::try_receive(params_, param))\r
322                                         renderer.param(param);\r
323                         \r
324                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
325 \r
326                                 if(abs(renderer.fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
327                                 {\r
328                                         auto frame1 = renderer.render_frame(false);\r
329                                         auto frame2 = renderer.render_frame(false);\r
330                                         Concurrency::send(last_frame_, frame2);\r
331                                         Concurrency::send(frames_, core::basic_frame::interlace(frame1, frame2, format_desc.field_mode));\r
332                                 }\r
333                                 else if(abs(renderer.fps()- format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
334                                 {\r
335                                         auto frame = renderer.render_frame(false);\r
336                                         Concurrency::send(last_frame_, frame);\r
337                                         Concurrency::send(frames_, frame);\r
338                                         Concurrency::send(frames_, frame);\r
339                                 }\r
340                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
341                                 {\r
342                                         auto frame = renderer.render_frame(false);\r
343                                         Concurrency::send(last_frame_, frame);\r
344                                         Concurrency::send(frames_, frame);\r
345                                 }\r
346 \r
347                                 fps_ = static_cast<int>(renderer.fps()*100.0);\r
348                                 graph_->update_text(narrow(print()));\r
349                         }\r
350                 }\r
351                 catch(...)\r
352                 {\r
353                         CASPAR_LOG_CURRENT_EXCEPTION();\r
354                 }\r
355                 \r
356                 is_running_ = false;\r
357                 done();\r
358         }\r
359         \r
360         // frame_producer\r
361                 \r
362         virtual safe_ptr<core::basic_frame> receive(int)\r
363         {                                               \r
364                 auto frame = core::basic_frame::late();\r
365 \r
366                 try\r
367                 {\r
368                         frame = Concurrency::receive(frames_, 5);\r
369                 }\r
370                 catch(Concurrency::operation_timed_out&)\r
371                 {                       \r
372                         graph_->add_tag("underflow");\r
373                 }\r
374 \r
375                 return frame;\r
376         }\r
377 \r
378         virtual safe_ptr<core::basic_frame> last_frame() const\r
379         {\r
380                 return last_frame_.value();\r
381         }               \r
382         \r
383         virtual void param(const std::wstring& param) \r
384         {       \r
385                 if(!is_running_.fetch_and_store(true))\r
386                 {\r
387                         agent::wait(this);\r
388                         start();\r
389                 }\r
390                 Concurrency::asend(params_, param);\r
391         }\r
392                 \r
393         virtual std::wstring print() const\r
394         { \r
395                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";              \r
396         }       \r
397 };\r
398 \r
399 safe_ptr<core::frame_producer> create_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
400 {\r
401         auto template_host = get_template_host(frame_factory->get_video_format_desc());\r
402         \r
403         return make_safe<flash_producer>(frame_factory, env::template_folder() + L"\\" + widen(template_host.filename), template_host.width, template_host.height);\r
404 }\r
405 \r
406 std::wstring find_template(const std::wstring& template_name)\r
407 {\r
408         if(boost::filesystem::exists(template_name + L".ft")) \r
409                 return template_name + L".ft";\r
410         \r
411         if(boost::filesystem::exists(template_name + L".ct"))\r
412                 return template_name + L".ct";\r
413 \r
414         return L"";\r
415 }\r
416 \r
417 }}