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 "../util/swf.h"
34 #include <core/video_format.h>
36 #include <core/frame/frame.h>
37 #include <core/frame/draw_frame.h>
38 #include <core/frame/frame_factory.h>
39 #include <core/frame/pixel_format.h>
40 #include <core/producer/frame_producer.h>
41 #include <core/monitor/monitor.h>
42 #include <core/help/help_repository.h>
43 #include <core/help/help_sink.h>
45 #include <common/env.h>
46 #include <common/executor.h>
47 #include <common/lock.h>
48 #include <common/diagnostics/graph.h>
49 #include <common/prec_timer.h>
50 #include <common/array.h>
52 #include <boost/filesystem.hpp>
53 #include <boost/property_tree/ptree.hpp>
54 #include <boost/thread.hpp>
55 #include <boost/timer.hpp>
56 #include <boost/algorithm/string.hpp>
58 #include <tbb/spin_mutex.h>
64 namespace caspar { namespace flash {
69 bitmap(int width, int height)
71 , hdc_(CreateCompatibleDC(0), DeleteDC)
74 memset(&info, 0, sizeof(BITMAPINFO));
75 info.bmiHeader.biBitCount = 32;
76 info.bmiHeader.biCompression = BI_RGB;
77 info.bmiHeader.biHeight = static_cast<LONG>(-height);
78 info.bmiHeader.biPlanes = 1;
79 info.bmiHeader.biSize = sizeof(BITMAPINFO);
80 info.bmiHeader.biWidth = static_cast<LONG>(width);
82 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);
83 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get());
86 CASPAR_THROW_EXCEPTION(bad_alloc());
89 operator HDC() {return static_cast<HDC>(hdc_.get());}
91 BYTE* data() { return bmp_data_;}
92 const BYTE* data() const { return bmp_data_;}
96 std::shared_ptr<void> hdc_;
97 std::shared_ptr<void> bmp_;
102 std::wstring video_mode;
103 std::wstring filename;
108 template_host get_template_host(const core::video_format_desc& desc)
112 std::vector<template_host> template_hosts;
113 for (auto& xml_mapping : env::properties().get_child(L"configuration.template-hosts"))
117 template_host template_host;
118 template_host.video_mode = xml_mapping.second.get(L"video-mode", L"");
119 template_host.filename = xml_mapping.second.get(L"filename", L"cg.fth");
120 template_host.width = xml_mapping.second.get(L"width", desc.width);
121 template_host.height = xml_mapping.second.get(L"height", desc.height);
122 template_hosts.push_back(template_host);
127 auto template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == desc.name;});
128 if(template_host_it == template_hosts.end())
129 template_host_it = boost::find_if(template_hosts, [&](template_host template_host){return template_host.video_mode == L"";});
131 if(template_host_it != template_hosts.end())
132 return *template_host_it;
136 template_host template_host;
137 template_host.filename = L"cg.fth";
139 for(auto it = boost::filesystem::directory_iterator(env::template_folder()); it != boost::filesystem::directory_iterator(); ++it)
141 if(boost::iequals(it->path().extension().wstring(), L"." + desc.name))
143 template_host.filename = it->path().filename().wstring();
148 template_host.width = desc.square_width;
149 template_host.height = desc.square_height;
150 return template_host;
157 HRESULT result_ = CoInitialize(nullptr);
162 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Failed to initialize com-context for flash-player"));
167 if(SUCCEEDED(result_))
172 core::monitor::subject& monitor_subject_;
174 const std::wstring filename_;
178 const std::shared_ptr<core::frame_factory> frame_factory_;
180 CComObject<caspar::flash::FlashAxContainer>* ax_ = nullptr;
181 core::draw_frame head_ = core::draw_frame::empty();
182 bitmap bmp_ { width_, height_ };
184 spl::shared_ptr<diagnostics::graph> graph_;
190 flash_renderer(core::monitor::subject& monitor_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)
191 : monitor_subject_(monitor_subject)
193 , filename_(filename)
196 , frame_factory_(frame_factory)
197 , bmp_(width, height)
199 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
200 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));
201 graph_->set_color("sync", diagnostics::color(0.8f, 0.3f, 0.2f));
203 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))
204 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to create FlashAxContainer"));
206 ax_->set_print([this]{return print();});
208 if(FAILED(ax_->CreateAxControl()))
209 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Create FlashAxControl"));
211 CComPtr<IShockwaveFlash> spFlash;
212 if(FAILED(ax_->QueryControl(&spFlash)))
213 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Query FlashAxControl"));
215 if(FAILED(spFlash->put_Playing(true)) )
216 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to start playing Flash"));
218 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))
219 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Load Template Host"));
221 if(FAILED(spFlash->put_ScaleMode(2))) //Exact fit. Scale without respect to the aspect ratio.
222 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(print() + L" Failed to Set Scale Mode"));
224 ax_->SetSize(width_, height_);
229 CASPAR_LOG(info) << print() << L" Initialized.";
236 ax_->DestroyAxControl();
239 graph_->set_value("tick-time", 0.0f);
240 graph_->set_value("frame-time", 0.0f);
241 CASPAR_LOG(info) << print() << L" Uninitialized.";
244 std::wstring call(const std::wstring& param)
248 CASPAR_LOG(trace) << print() << " Call: " << param;
250 if(!ax_->FlashCall(param, result))
251 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)));
252 graph_->set_tag("param");
257 void tick(double sync)
259 const float frame_time = 1.0f/ax_->GetFPS();
262 timer_.tick(frame_time*sync); // This will block the thread.
264 graph_->set_tag("sync");
266 graph_->set_value("sync", sync);
267 monitor_subject_ << core::monitor::message("/sync") % sync;
272 while(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) // DO NOT REMOVE THE MESSAGE DISPATCH LOOP. Without this some stuff doesn't work!
274 if(msg.message == WM_TIMER && msg.wParam == 3 && msg.lParam == 0) // We tick this inside FlashAxContainer
277 TranslateMessage(&msg);
278 DispatchMessage(&msg);
282 core::draw_frame render()
284 const float frame_time = 1.0f/fps();
286 boost::timer frame_timer;
288 if(ax_->InvalidRect())
290 A_memset(bmp_.data(), 0, width_*height_*4);
291 ax_->DrawControl(bmp_);
293 core::pixel_format_desc desc = core::pixel_format::bgra;
294 desc.planes.push_back(core::pixel_format_desc::plane(width_, height_, 4));
295 auto frame = frame_factory_->create_frame(this, desc);
297 A_memcpy(frame.image_data(0).begin(), bmp_.data(), width_*height_*4);
298 head_ = core::draw_frame(std::move(frame));
301 graph_->set_value("frame-time", static_cast<float>(frame_timer.elapsed()/frame_time)*0.5f);
302 monitor_subject_ << core::monitor::message("/renderer/profiler/time") % frame_timer.elapsed() % frame_time;
306 bool is_empty() const
308 return ax_->IsEmpty();
313 return ax_->GetFPS();
318 return L"flash-player[" + boost::filesystem::wpath(filename_).filename().wstring()
319 + L"|" + boost::lexical_cast<std::wstring>(width_)
320 + L"x" + boost::lexical_cast<std::wstring>(height_)
325 struct flash_producer : public core::frame_producer_base
327 core::monitor::subject monitor_subject_;
328 const std::wstring filename_;
329 const spl::shared_ptr<core::frame_factory> frame_factory_;
330 const core::video_format_desc format_desc_;
333 core::constraints constraints_ { static_cast<double>(width_), static_cast<double>(height_) };
334 const int buffer_size_ = env::properties().get(L"configuration.flash.buffer-depth", format_desc_.fps > 30.0 ? 4 : 2);
336 tbb::atomic<int> fps_;
338 spl::shared_ptr<diagnostics::graph> graph_;
340 std::queue<core::draw_frame> frame_buffer_;
341 tbb::concurrent_bounded_queue<core::draw_frame> output_buffer_;
343 core::draw_frame last_frame_;
345 boost::timer tick_timer_;
346 std::unique_ptr<flash_renderer> renderer_;
348 executor executor_ = L"flash_producer";
350 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)
351 : filename_(filename)
352 , frame_factory_(frame_factory)
353 , format_desc_(format_desc)
354 , width_(width > 0 ? width : format_desc.width)
355 , height_(height > 0 ? height : format_desc.height)
359 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f));
360 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
361 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.9f));
362 graph_->set_text(print());
363 diagnostics::register_graph(graph_);
365 CASPAR_LOG(info) << print() << L" Initialized";
370 executor_.invoke([this]
373 }, task_priority::high_priority);
378 core::draw_frame receive_impl() override
380 auto frame = last_frame_;
382 if(output_buffer_.try_pop(frame))
383 executor_.begin_invoke(std::bind(&flash_producer::next, this));
385 graph_->set_tag("late-frame");
387 monitor_subject_ << core::monitor::message("/host/path") % filename_
388 << core::monitor::message("/host/width") % width_
389 << core::monitor::message("/host/height") % height_
390 << core::monitor::message("/host/fps") % fps_
391 << core::monitor::message("/buffer") % output_buffer_.size() % buffer_size_;
393 return last_frame_ = frame;
396 core::constraints& pixel_constraints() override
401 std::future<std::wstring> call(const std::vector<std::wstring>& params) override
403 auto param = boost::algorithm::join(params, L" ");
405 return executor_.begin_invoke([this, param]() -> std::wstring
411 renderer_.reset(new flash_renderer(monitor_subject_, graph_, frame_factory_, filename_, width_, height_));
413 while(output_buffer_.size() < buffer_size_)
414 output_buffer_.push(core::draw_frame::empty());
417 return renderer_->call(param);
421 CASPAR_LOG_CURRENT_EXCEPTION();
422 renderer_.reset(nullptr);
429 std::wstring print() const override
431 return L"flash[" + boost::filesystem::path(filename_).wstring() + L"|" + boost::lexical_cast<std::wstring>(fps_) + L"]";
434 std::wstring name() const override
439 boost::property_tree::wptree info() const override
441 boost::property_tree::wptree info;
442 info.add(L"type", L"flash");
446 core::monitor::subject& monitor_output()
448 return monitor_subject_;
455 double ratio = std::min(1.0, static_cast<double>(output_buffer_.size())/static_cast<double>(std::max(1, buffer_size_ - 1)));
456 double sync = 2*ratio - ratio*ratio;
457 renderer_->tick(sync);
463 frame_buffer_.push(core::draw_frame::empty());
465 tick_timer_.restart();
467 if(frame_buffer_.empty())
470 auto frame = renderer_->render();
472 if(abs(renderer_->fps()/2.0 - format_desc_.fps) < 2.0) // flash == 2 * format -> interlace
475 if(format_desc_.field_mode != core::field_mode::progressive)
476 frame = core::draw_frame::interlace(frame, renderer_->render(), format_desc_.field_mode);
478 frame_buffer_.push(frame);
480 else if(abs(renderer_->fps() - format_desc_.fps/2.0) < 2.0) // format == 2 * flash -> duplicate
482 frame_buffer_.push(frame);
483 frame_buffer_.push(frame);
485 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple
487 frame_buffer_.push(frame);
490 fps_.fetch_and_store(static_cast<int>(renderer_->fps()*100.0));
491 graph_->set_text(print());
493 if(renderer_->is_empty())
497 graph_->set_value("tick-time", static_cast<float>(tick_timer_.elapsed()/fps_)*0.5f);
498 monitor_subject_ << core::monitor::message("/profiler/time") % tick_timer_.elapsed() % fps_;
500 output_buffer_.push(std::move(frame_buffer_.front()));
505 spl::shared_ptr<core::frame_producer> create_producer(const core::frame_producer_dependencies& dependencies, const std::vector<std::wstring>& params)
507 auto template_host = get_template_host(dependencies.format_desc);
509 auto filename = env::template_folder() + L"\\" + template_host.filename;
511 if(!boost::filesystem::exists(filename))
512 CASPAR_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(u8(filename)));
514 return create_destroy_proxy(spl::make_shared<flash_producer>(dependencies.frame_factory, dependencies.format_desc, filename, template_host.width, template_host.height));
517 void describe_swf_producer(core::help_sink& sink, const core::help_repository& repo)
519 sink.short_description(L"Plays flash files (.swf files).");
520 sink.syntax(L"[swf_file:string]");
521 sink.para()->text(L"Plays flash files (.swf files). The file should reside under the media folder.");
522 sink.para()->text(L"Examples:");
523 sink.example(L">> PLAY 1-10 folder/swf_file");
526 spl::shared_ptr<core::frame_producer> create_swf_producer(const core::frame_producer_dependencies& dependencies, const std::vector<std::wstring>& params)
528 auto filename = env::media_folder() + L"\\" + params.at(0) + L".swf";
530 if (!boost::filesystem::exists(filename))
531 return core::frame_producer::empty();
533 swf_t::header_t header(filename);
535 return create_destroy_proxy(
536 spl::make_shared<flash_producer>(dependencies.frame_factory, dependencies.format_desc, filename, header.frame_width, header.frame_height));
539 std::wstring find_template(const std::wstring& template_name)
541 if(boost::filesystem::exists(template_name + L".ft"))
542 return template_name + L".ft";
544 if(boost::filesystem::exists(template_name + L".ct"))
545 return template_name + L".ct";
547 if(boost::filesystem::exists(template_name + L".swf"))
548 return template_name + L".swf";