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