2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
19 * Author: Robert Nagy, ronag89@gmail.com
22 #include "../stdafx.h"
25 #pragma warning (disable : 4146)
26 #pragma warning (disable : 4244)
29 #include "flash_producer.h"
30 #include "FlashAxContainer.h"
32 #include <core/video_format.h>
34 #include <core/frame/frame.h>
35 #include <core/frame/draw_frame.h>
36 #include <core/frame/frame_factory.h>
37 #include <core/frame/pixel_format.h>
38 #include <core/monitor/monitor.h>
40 #include <common/env.h>
41 #include <common/executor.h>
42 #include <common/lock.h>
43 #include <common/diagnostics/graph.h>
44 #include <common/prec_timer.h>
45 #include <common/array.h>
47 #include <boost/filesystem.hpp>
48 #include <boost/property_tree/ptree.hpp>
49 #include <boost/thread.hpp>
50 #include <boost/timer.hpp>
51 #include <boost/algorithm/string.hpp>
53 #include <tbb/spin_mutex.h>
59 namespace caspar { namespace flash {
64 bitmap(int width, int height)
66 , hdc_(CreateCompatibleDC(0), DeleteDC)
69 memset(&info, 0, sizeof(BITMAPINFO));
70 info.bmiHeader.biBitCount = 32;
71 info.bmiHeader.biCompression = BI_RGB;
72 info.bmiHeader.biHeight = static_cast<LONG>(-height);
73 info.bmiHeader.biPlanes = 1;
74 info.bmiHeader.biSize = sizeof(BITMAPINFO);
75 info.bmiHeader.biWidth = static_cast<LONG>(width);
77 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);
78 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get());
81 CASPAR_THROW_EXCEPTION(bad_alloc());
84 operator HDC() {return static_cast<HDC>(hdc_.get());}
86 BYTE* data() { return bmp_data_;}
87 const BYTE* data() const { return bmp_data_;}
91 std::shared_ptr<void> hdc_;
92 std::shared_ptr<void> bmp_;
97 std::wstring video_mode;
98 std::wstring filename;
103 template_host get_template_host(const core::video_format_desc& desc)
107 std::vector<template_host> template_hosts;
108 BOOST_FOREACH(auto& xml_mapping, env::properties().get_child(L"configuration.template-hosts"))
112 template_host template_host;
113 template_host.video_mode = xml_mapping.second.get(L"video-mode", L"");
114 template_host.filename = xml_mapping.second.get(L"filename", L"cg.fth");
115 template_host.width = xml_mapping.second.get(L"width", desc.width);
116 template_host.height = xml_mapping.second.get(L"height", desc.height);
117 template_hosts.push_back(template_host);
122 auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == desc.name;});
123 if(template_host_it == template_hosts.end())
124 template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == L"";});
126 if(template_host_it != template_hosts.end())
127 return *template_host_it;
131 template_host template_host;
132 template_host.filename = L"cg.fth";
134 for(auto it = boost::filesystem::directory_iterator(env::template_folder()); it != boost::filesystem::directory_iterator(); ++it)
136 if(boost::iequals(it->path().extension().wstring(), L"." + desc.name))
138 template_host.filename = it->path().filename().wstring();
143 template_host.width = desc.square_width;
144 template_host.height = desc.square_height;
145 return template_host;
155 : result_(CoInitialize(nullptr))
158 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to initialize com-context for flash-player"));
163 if(SUCCEEDED(result_))
168 monitor::basic_subject& event_subject_;
170 const std::wstring filename_;
172 const std::shared_ptr<core::frame_factory> frame_factory_;
174 CComObject<caspar::flash::FlashAxContainer>* ax_;
175 core::draw_frame head_;
178 spl::shared_ptr<diagnostics::graph> graph_;
186 flash_renderer(monitor::basic_subject& event_subject, const spl::shared_ptr<diagnostics::graph>& graph, const std::shared_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height)
187 : event_subject_(event_subject)
189 , filename_(filename)
190 , frame_factory_(frame_factory)
192 , head_(core::draw_frame::empty())
193 , bmp_(width, height)
197 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
198 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));
199 graph_->set_color("sync", diagnostics::color(0.8f, 0.3f, 0.2f));
201 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))
202 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to create FlashAxContainer"));
204 ax_->set_print([this]{return print();});
206 if(FAILED(ax_->CreateAxControl()))
207 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Create FlashAxControl"));
209 CComPtr<IShockwaveFlash> spFlash;
210 if(FAILED(ax_->QueryControl(&spFlash)))
211 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Query FlashAxControl"));
213 if(FAILED(spFlash->put_Playing(true)) )
214 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to start playing Flash"));
216 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))
217 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Load Template Host"));
219 if(FAILED(spFlash->put_ScaleMode(2))) //Exact fit. Scale without respect to the aspect ratio.
220 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Set Scale Mode"));
222 ax_->SetSize(width_, height_);
227 CASPAR_LOG(info) << print() << L" Initialized.";
234 ax_->DestroyAxControl();
237 graph_->set_value("tick-time", 0.0f);
238 graph_->set_value("frame-time", 0.0f);
239 CASPAR_LOG(info) << print() << L" Uninitialized.";
242 std::wstring call(const std::wstring& param)
246 CASPAR_LOG(trace) << print() << " Call: " << param;
248 if(!ax_->FlashCall(param, result))
249 CASPAR_LOG(warning) << print() << L" Flash call failed:" << param;//CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Flash function call failed.") << arg_name_info("param") << arg_value_info(narrow(param)));
250 graph_->set_tag("param");
255 void tick(double sync)
257 const float frame_time = 1.0f/ax_->GetFPS();
260 timer_.tick(frame_time*sync); // This will block the thread.
262 graph_->set_tag("sync");
264 graph_->set_value("sync", sync);
265 event_subject_ << monitor::event("sync") % sync;
270 while(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) // DO NOT REMOVE THE MESSAGE DISPATCH LOOP. Without this some stuff doesn't work!
272 if(msg.message == WM_TIMER && msg.wParam == 3 && msg.lParam == 0) // We tick this inside FlashAxContainer
275 TranslateMessage(&msg);
276 DispatchMessage(&msg);
280 core::draw_frame render()
282 const float frame_time = 1.0f/fps();
284 boost::timer frame_timer;
286 if(ax_->InvalidRect())
288 A_memset(bmp_.data(), 0, width_*height_*4);
289 ax_->DrawControl(bmp_);
291 core::pixel_format_desc desc = core::pixel_format::bgra;
292 desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));
293 auto frame = frame_factory_->create_frame(this, desc);
295 A_memcpy(frame.image_data(0).begin(), bmp_.data(), width_*height_*4);
296 head_ = core::draw_frame(std::move(frame));
299 graph_->set_value("frame-time", static_cast<float>(frame_timer.elapsed()/frame_time)*0.5f);
300 event_subject_ << monitor::event("renderer/profiler/time") % frame_timer.elapsed() % frame_time;
304 bool is_empty() const
306 return ax_->IsEmpty();
311 return ax_->GetFPS();
316 return L"flash-player[" + boost::filesystem::wpath(filename_).filename().wstring()
317 + L"|" + boost::lexical_cast<std::wstring>(width_)
318 + L"x" + boost::lexical_cast<std::wstring>(height_)
323 struct flash_producer : public core::frame_producer_base
325 monitor::basic_subject event_subject_;
326 const std::wstring filename_;
327 const spl::shared_ptr<core::frame_factory> frame_factory_;
328 const core::video_format_desc format_desc_;
331 const int buffer_size_;
333 tbb::atomic<int> fps_;
335 spl::shared_ptr<diagnostics::graph> graph_;
337 std::queue<core::draw_frame> frame_buffer_;
338 tbb::concurrent_bounded_queue<core::draw_frame> output_buffer_;
340 core::draw_frame last_frame_;
342 boost::timer tick_timer_;
343 std::unique_ptr<flash_renderer> renderer_;
347 flash_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, const std::wstring& filename, int width, int height)
348 : filename_(filename)
349 , frame_factory_(frame_factory)
350 , format_desc_(format_desc)
351 , width_(width > 0 ? width : format_desc.width)
352 , height_(height > 0 ? height : format_desc.height)
353 , buffer_size_(env::properties().get(L"configuration.flash.buffer-depth", format_desc.fps > 30.0 ? 4 : 2))
354 , executor_(L"flash_producer")
358 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f));
359 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
360 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.9f));
361 graph_->set_text(print());
362 diagnostics::register_graph(graph_);
364 CASPAR_LOG(info) << print() << L" Initialized";
369 executor_.invoke([this]
372 }, task_priority::high_priority);
377 core::draw_frame receive_impl() override
379 auto frame = last_frame_;
381 if(output_buffer_.try_pop(frame))
382 executor_.begin_invoke(std::bind(&flash_producer::next, this));
384 graph_->set_tag("late-frame");
386 event_subject_ << monitor::event("host/path") % filename_
387 << monitor::event("host/width") % width_
388 << monitor::event("host/height") % height_
389 << monitor::event("host/fps") % fps_
390 << monitor::event("buffer") % output_buffer_.size() % buffer_size_;
392 return last_frame_ = frame;
395 boost::unique_future<std::wstring> call(const std::wstring& param) override
397 return executor_.begin_invoke([this, param]() -> std::wstring
403 renderer_.reset(new flash_renderer(event_subject_, graph_, frame_factory_, filename_, width_, height_));
405 while(output_buffer_.size() < buffer_size_)
406 output_buffer_.push(core::draw_frame::empty());
409 return renderer_->call(param);
413 CASPAR_LOG_CURRENT_EXCEPTION();
414 renderer_.reset(nullptr);
421 std::wstring print() const override
423 return L"flash[" + boost::filesystem::path(filename_).wstring() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";
426 std::wstring name() const override
431 boost::property_tree::wptree info() const override
433 boost::property_tree::wptree info;
434 info.add(L"type", L"flash");
438 void subscribe(const monitor::observable::observer_ptr& o) override
440 event_subject_.subscribe(o);
443 void unsubscribe(const monitor::observable::observer_ptr& o) override
445 event_subject_.unsubscribe(o);
452 double ratio = std::min(1.0, static_cast<double>(output_buffer_.size())/static_cast<double>(std::max(1, buffer_size_ - 1)));
453 double sync = 2*ratio - ratio*ratio;
454 renderer_->tick(sync);
460 frame_buffer_.push(core::draw_frame::empty());
462 tick_timer_.restart();
464 if(frame_buffer_.empty())
467 auto frame = renderer_->render();
469 if(abs(renderer_->fps()/2.0 - format_desc_.fps) < 2.0) // flash == 2 * format -> interlace
472 if(format_desc_.field_mode != core::field_mode::progressive)
473 frame = core::draw_frame::interlace(frame, renderer_->render(), format_desc_.field_mode);
475 frame_buffer_.push(frame);
477 else if(abs(renderer_->fps() - format_desc_.fps/2.0) < 2.0) // format == 2 * flash -> duplicate
479 frame_buffer_.push(frame);
480 frame_buffer_.push(frame);
482 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple
484 frame_buffer_.push(frame);
487 fps_.fetch_and_store(static_cast<int>(renderer_->fps()*100.0));
488 graph_->set_text(print());
490 if(renderer_->is_empty())
494 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()/fps_)*0.5f);
495 event_subject_ << monitor::event("profiler/time") % tick_timer_.elapsed() % fps_;
497 output_buffer_.push(std::move(frame_buffer_.front()));
502 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, const std::vector<std::wstring>& params)
504 auto template_host = get_template_host(format_desc);
506 auto filename = env::template_folder() + L"\\" + template_host.filename;
508 if(!boost::filesystem::exists(filename))
509 CASPAR_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(u8(filename)));
511 return create_destroy_proxy(spl::make_shared<flash_producer>(frame_factory, format_desc, filename, template_host.width, template_host.height));
514 std::wstring find_template(const std::wstring& template_name)
516 if(boost::filesystem::exists(template_name + L".ft"))
517 return template_name + L".ft";
519 if(boost::filesystem::exists(template_name + L".ct"))
520 return template_name + L".ct";
522 if(boost::filesystem::exists(template_name + L".swf"))
523 return template_name + L".swf";