2 * Copyright 2013 Sveriges Television AB http://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 "html_producer.h"
24 #include <core/video_format.h>
26 #include <core/monitor/monitor.h>
27 #include <core/frame/draw_frame.h>
28 #include <core/frame/frame_factory.h>
29 #include <core/producer/frame_producer.h>
30 #include <core/interaction/interaction_event.h>
31 #include <core/frame/frame.h>
32 #include <core/frame/pixel_format.h>
33 #include <core/frame/audio_channel_layout.h>
34 #include <core/frame/geometry.h>
35 #include <core/help/help_repository.h>
36 #include <core/help/help_sink.h>
38 #include <common/assert.h>
39 #include <common/env.h>
40 #include <common/executor.h>
41 #include <common/lock.h>
42 #include <common/future.h>
43 #include <common/diagnostics/graph.h>
44 #include <common/prec_timer.h>
45 #include <common/linq.h>
46 #include <common/os/filesystem.h>
48 #include <boost/algorithm/string/predicate.hpp>
49 #include <boost/filesystem.hpp>
50 #include <boost/timer.hpp>
51 #include <boost/log/trivial.hpp>
52 #include <boost/property_tree/ptree.hpp>
54 #include <tbb/atomic.h>
55 #include <tbb/concurrent_queue.h>
58 #pragma warning(disable: 4458)
61 #include <cef_client.h>
62 #include <cef_render_handler.h>
69 #pragma comment (lib, "libcef.lib")
70 #pragma comment (lib, "libcef_dll_wrapper.lib")
72 namespace caspar { namespace html {
76 , public CefRenderHandler
77 , public CefLifeSpanHandler
78 , public CefLoadHandler
81 spl::shared_ptr<diagnostics::graph> graph_;
82 boost::timer tick_timer_;
83 boost::timer frame_timer_;
84 boost::timer paint_timer_;
86 spl::shared_ptr<core::frame_factory> frame_factory_;
87 core::video_format_desc format_desc_;
88 tbb::concurrent_queue<std::wstring> javascript_before_load_;
89 tbb::atomic<bool> loaded_;
90 tbb::atomic<bool> removed_;
91 std::queue<core::draw_frame> frames_;
92 mutable boost::mutex frames_mutex_;
94 core::draw_frame last_frame_;
95 core::draw_frame last_progressive_frame_;
96 mutable boost::mutex last_frame_mutex_;
98 CefRefPtr<CefBrowser> browser_;
105 spl::shared_ptr<core::frame_factory> frame_factory,
106 const core::video_format_desc& format_desc,
107 const std::wstring& url)
109 , frame_factory_(std::move(frame_factory))
110 , format_desc_(format_desc)
111 , last_frame_(core::draw_frame::empty())
112 , last_progressive_frame_(core::draw_frame::empty())
113 , executor_(L"html_producer")
115 graph_->set_color("browser-tick-time", diagnostics::color(0.1f, 1.0f, 0.1f));
116 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
117 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
118 graph_->set_text(print());
119 diagnostics::register_graph(graph_);
123 executor_.begin_invoke([&]{ update(); });
126 core::draw_frame receive()
128 auto frame = last_frame();
129 executor_.begin_invoke([&]{ update(); });
133 core::draw_frame last_frame() const
135 return lock(last_frame_mutex_, [&]
141 void execute_javascript(const std::wstring& javascript)
145 javascript_before_load_.push(javascript);
149 execute_queued_javascript();
150 do_execute_javascript(javascript);
154 CefRefPtr<CefBrowserHost> get_browser_host()
156 return browser_->GetHost();
163 if (browser_ != nullptr)
165 browser_->GetHost()->CloseBrowser(true);
176 bool is_removed() const
183 bool GetViewRect(CefRefPtr<CefBrowser> browser, CefRect &rect)
185 CASPAR_ASSERT(CefCurrentlyOn(TID_UI));
187 rect = CefRect(0, 0, format_desc_.square_width, format_desc_.square_height);
192 CefRefPtr<CefBrowser> browser,
193 PaintElementType type,
194 const RectList &dirtyRects,
199 graph_->set_value("browser-tick-time", paint_timer_.elapsed()
201 * format_desc_.field_count
203 paint_timer_.restart();
204 CASPAR_ASSERT(CefCurrentlyOn(TID_UI));
206 core::pixel_format_desc pixel_desc;
207 pixel_desc.format = core::pixel_format::bgra;
208 pixel_desc.planes.push_back(
209 core::pixel_format_desc::plane(width, height, 4));
210 auto frame = frame_factory_->create_frame(this, pixel_desc, core::audio_channel_layout::invalid());
211 std::memcpy(frame.image_data().begin(), buffer, width * height * 4);
213 lock(frames_mutex_, [&]
215 frames_.push(core::draw_frame(std::move(frame)));
217 size_t max_in_queue = format_desc_.field_count + 1;
219 while (frames_.size() > max_in_queue)
222 graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
227 void OnAfterCreated(CefRefPtr<CefBrowser> browser) override
229 CASPAR_ASSERT(CefCurrentlyOn(TID_UI));
234 void OnBeforeClose(CefRefPtr<CefBrowser> browser) override
236 CASPAR_ASSERT(CefCurrentlyOn(TID_UI));
241 bool DoClose(CefRefPtr<CefBrowser> browser) override
243 CASPAR_ASSERT(CefCurrentlyOn(TID_UI));
248 CefRefPtr<CefRenderHandler> GetRenderHandler() override
253 CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override
258 CefRefPtr<CefLoadHandler> GetLoadHandler() override {
263 CefRefPtr<CefBrowser> browser,
264 CefRefPtr<CefFrame> frame,
265 int httpStatusCode) override
268 execute_queued_javascript();
271 bool OnProcessMessageReceived(
272 CefRefPtr<CefBrowser> browser,
273 CefProcessId source_process,
274 CefRefPtr<CefProcessMessage> message) override
276 auto name = message->GetName().ToString();
278 if (name == REMOVE_MESSAGE_NAME)
284 else if (name == LOG_MESSAGE_NAME)
286 auto args = message->GetArgumentList();
288 static_cast<boost::log::trivial::severity_level>(args->GetInt(0));
289 auto msg = args->GetString(1).ToWString();
291 BOOST_LOG_STREAM_WITH_PARAMS(
293 (boost::log::keywords::severity = severity))
294 << print() << L" [renderer_process] " << msg;
300 void invoke_requested_animation_frames()
303 browser_->SendProcessMessage(
304 CefProcessId::PID_RENDERER,
305 CefProcessMessage::Create(TICK_MESSAGE_NAME));
307 graph_->set_value("tick-time", tick_timer_.elapsed()
309 * format_desc_.field_count
311 tick_timer_.restart();
314 bool try_pop(core::draw_frame& result)
316 return lock(frames_mutex_, [&]() -> bool
318 if (!frames_.empty())
320 result = std::move(frames_.front());
330 core::draw_frame pop()
332 core::draw_frame frame;
336 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(u8(print()) + " No frame in buffer"));
344 invoke_requested_animation_frames();
349 auto num_frames = lock(frames_mutex_, [&]
351 return frames_.size();
354 if (num_frames >= format_desc_.field_count)
356 if (format_desc_.field_mode != core::field_mode::progressive)
360 executor_.yield(caspar::task_priority::lowest_priority);
361 timer.tick(1.0 / (format_desc_.fps * format_desc_.field_count));
362 invoke_requested_animation_frames();
366 lock(last_frame_mutex_, [&]
368 last_progressive_frame_ = frame2;
369 last_frame_ = core::draw_frame::interlace(frame1, frame2, format_desc_.field_mode);
376 lock(last_frame_mutex_, [&]
382 else if (num_frames == 1) // Interlaced but only one frame
383 { // available. Probably the last frame
384 // of some animation sequence.
387 lock(last_frame_mutex_, [&]
389 last_progressive_frame_ = frame;
393 timer.tick(1.0 / (format_desc_.fps * format_desc_.field_count));
394 invoke_requested_animation_frames();
398 if (format_desc_.field_mode != core::field_mode::progressive)
399 lock(last_frame_mutex_, [&]
401 last_frame_ = last_progressive_frame_;
406 void do_execute_javascript(const std::wstring& javascript)
408 html::begin_invoke([=]
410 if (browser_ != nullptr)
411 browser_->GetMainFrame()->ExecuteJavaScript(u8(javascript).c_str(), browser_->GetMainFrame()->GetURL(), 0);
415 void execute_queued_javascript()
417 std::wstring javascript;
419 while (javascript_before_load_.try_pop(javascript))
420 do_execute_javascript(javascript);
423 std::wstring print() const
425 return L"html[" + url_ + L"]";
428 IMPLEMENT_REFCOUNTING(html_client);
432 : public core::frame_producer_base
434 core::monitor::subject monitor_subject_;
435 const std::wstring url_;
436 core::constraints constraints_;
438 CefRefPtr<html_client> client_;
442 const spl::shared_ptr<core::frame_factory>& frame_factory,
443 const core::video_format_desc& format_desc,
444 const std::wstring& url)
447 constraints_.width.set(format_desc.square_width);
448 constraints_.height.set(format_desc.square_height);
452 client_ = new html_client(frame_factory, format_desc, url_);
454 CefWindowInfo window_info;
456 window_info.SetTransparentPainting(true);
457 window_info.SetAsOffScreen(nullptr);
458 //window_info.SetAsWindowless(nullptr, true);
460 CefBrowserSettings browser_settings;
461 browser_settings.web_security = cef_state_t::STATE_DISABLED;
462 CefBrowserHost::CreateBrowser(window_info, client_.get(), url, browser_settings, nullptr);
474 std::wstring name() const override
479 void on_interaction(const core::interaction_event::ptr& event) override
481 if (core::is<core::mouse_move_event>(event))
483 auto move = core::as<core::mouse_move_event>(event);
484 int x = static_cast<int>(move->x * constraints_.width.get());
485 int y = static_cast<int>(move->y * constraints_.height.get());
490 client_->get_browser_host()->SendMouseMoveEvent(e, false);
492 else if (core::is<core::mouse_button_event>(event))
494 auto button = core::as<core::mouse_button_event>(event);
495 int x = static_cast<int>(button->x * constraints_.width.get());
496 int y = static_cast<int>(button->y * constraints_.height.get());
501 client_->get_browser_host()->SendMouseClickEvent(
503 static_cast<CefBrowserHost::MouseButtonType>(button->button),
507 else if (core::is<core::mouse_wheel_event>(event))
509 auto wheel = core::as<core::mouse_wheel_event>(event);
510 int x = static_cast<int>(wheel->x * constraints_.width.get());
511 int y = static_cast<int>(wheel->y * constraints_.height.get());
516 static const int WHEEL_TICKS_AMPLIFICATION = 40;
517 client_->get_browser_host()->SendMouseWheelEvent(
520 wheel->ticks_delta * WHEEL_TICKS_AMPLIFICATION); // delta_y
524 bool collides(double x, double y) const override
529 core::draw_frame receive_impl() override
533 if (client_->is_removed())
536 return core::draw_frame::empty();
539 return client_->receive();
542 return core::draw_frame::empty();
545 std::future<std::wstring> call(const std::vector<std::wstring>& params) override
548 return make_ready_future(std::wstring(L""));
550 auto javascript = params.at(0);
552 client_->execute_javascript(javascript);
554 return make_ready_future(std::wstring(L""));
557 std::wstring print() const override
559 return L"html[" + url_ + L"]";
562 boost::property_tree::wptree info() const override
564 boost::property_tree::wptree info;
565 info.add(L"type", L"html-producer");
569 core::constraints& pixel_constraints() override
574 core::monitor::subject& monitor_output()
576 return monitor_subject_;
580 void describe_producer(core::help_sink& sink, const core::help_repository& repo)
582 sink.short_description(L"Renders a web page in real time.");
583 sink.syntax(L"{[html_filename:string]},{[HTML] [url:string]}");
584 sink.para()->text(L"Embeds an actual web browser and renders the content in realtime.");
586 ->text(L"HTML content can either be stored locally under the ")->code(L"templates")
587 ->text(L" folder or fetched directly via an URL. If a .html file is found with the name ")
588 ->code(L"html_filename")->text(L" under the ")->code(L"templates")->text(L" folder it will be rendered. If the ")
589 ->code(L"[HTML] url")->text(L" syntax is used instead, the URL will be loaded.");
590 sink.para()->text(L"Examples:");
591 sink.example(L">> PLAY 1-10 [HTML] http://www.casparcg.com");
592 sink.example(L">> PLAY 1-10 folder/html_file");
595 spl::shared_ptr<core::frame_producer> create_producer(
596 const core::frame_producer_dependencies& dependencies,
597 const std::vector<std::wstring>& params)
599 const auto filename = env::template_folder() + params.at(0) + L".html";
600 const auto found_filename = find_case_insensitive(filename);
601 const auto html_prefix = boost::iequals(params.at(0), L"[HTML]");
603 if (!found_filename && !html_prefix)
604 return core::frame_producer::empty();
606 const auto url = found_filename
607 ? L"file://" + *found_filename
610 if (!html_prefix && (!boost::algorithm::contains(url, ".") || boost::algorithm::ends_with(url, "_A") || boost::algorithm::ends_with(url, "_ALPHA")))
611 return core::frame_producer::empty();
613 return core::create_destroy_proxy(spl::make_shared<html_producer>(
614 dependencies.frame_factory,
615 dependencies.format_desc,