VideoPaintable.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/NumberFormat.h>
  8. #include <LibGUI/Event.h>
  9. #include <LibGfx/AntiAliasingPainter.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/HTML/HTMLMediaElement.h>
  12. #include <LibWeb/HTML/HTMLVideoElement.h>
  13. #include <LibWeb/HTML/VideoTrackList.h>
  14. #include <LibWeb/Layout/VideoBox.h>
  15. #include <LibWeb/Painting/BorderRadiusCornerClipper.h>
  16. #include <LibWeb/Painting/VideoPaintable.h>
  17. namespace Web::Painting {
  18. static constexpr auto control_box_color = Gfx::Color::from_rgb(0x26'26'26);
  19. static constexpr auto control_highlight_color = Gfx::Color::from_rgb(0x1d'99'f3);
  20. static constexpr Gfx::Color control_button_color(bool is_hovered)
  21. {
  22. if (!is_hovered)
  23. return Color::White;
  24. return control_highlight_color;
  25. }
  26. JS::NonnullGCPtr<VideoPaintable> VideoPaintable::create(Layout::VideoBox const& layout_box)
  27. {
  28. return layout_box.heap().allocate_without_realm<VideoPaintable>(layout_box);
  29. }
  30. VideoPaintable::VideoPaintable(Layout::VideoBox const& layout_box)
  31. : PaintableBox(layout_box)
  32. {
  33. }
  34. Layout::VideoBox& VideoPaintable::layout_box()
  35. {
  36. return static_cast<Layout::VideoBox&>(layout_node());
  37. }
  38. Layout::VideoBox const& VideoPaintable::layout_box() const
  39. {
  40. return static_cast<Layout::VideoBox const&>(layout_node());
  41. }
  42. void VideoPaintable::paint(PaintContext& context, PaintPhase phase) const
  43. {
  44. if (!is_visible())
  45. return;
  46. // FIXME: This should be done at a different level.
  47. if (is_out_of_view(context))
  48. return;
  49. PaintableBox::paint(context, phase);
  50. if (phase != PaintPhase::Foreground)
  51. return;
  52. auto video_rect = context.rounded_device_rect(absolute_rect());
  53. context.painter().add_clip_rect(video_rect.to_type<int>());
  54. ScopedCornerRadiusClip corner_clip { context, context.painter(), video_rect, normalized_border_radii_data(ShrinkRadiiForBorders::Yes) };
  55. auto const& video_element = layout_box().dom_node();
  56. auto const& layout_mouse_position = video_element.layout_mouse_position({});
  57. Optional<DevicePixelPoint> mouse_position;
  58. if (layout_mouse_position.has_value() && document().hovered_node() == &video_element)
  59. mouse_position = context.rounded_device_point(*layout_mouse_position);
  60. auto const& current_frame = video_element.current_frame();
  61. auto const& poster_frame = video_element.poster_frame();
  62. auto current_playback_position = video_element.current_playback_position();
  63. auto ready_state = video_element.ready_state();
  64. enum class Representation {
  65. Unknown,
  66. FirstVideoFrame,
  67. CurrentVideoFrame,
  68. LastRenderedVideoFrame,
  69. PosterFrame,
  70. TransparentBlack,
  71. };
  72. auto representation = Representation::Unknown;
  73. // https://html.spec.whatwg.org/multipage/media.html#the-video-element:the-video-element-7
  74. // A video element represents what is given for the first matching condition in the list below:
  75. // -> When no video data is available (the element's readyState attribute is either HAVE_NOTHING, or HAVE_METADATA
  76. // but no video data has yet been obtained at all, or the element's readyState attribute is any subsequent value
  77. // but the media resource does not have a video channel)
  78. if (ready_state == HTML::HTMLMediaElement::ReadyState::HaveNothing
  79. || (ready_state >= HTML::HTMLMediaElement::ReadyState::HaveMetadata && video_element.video_tracks()->length() == 0)) {
  80. // The video element represents its poster frame, if any, or else transparent black with no intrinsic dimensions.
  81. representation = poster_frame ? Representation::PosterFrame : Representation::TransparentBlack;
  82. }
  83. // -> When the video element is paused, the current playback position is the first frame of video, and the element's
  84. // show poster flag is set
  85. else if (video_element.paused() && current_playback_position == 0 && video_element.show_poster()) {
  86. // The video element represents its poster frame, if any, or else the first frame of the video.
  87. representation = poster_frame ? Representation::PosterFrame : Representation::FirstVideoFrame;
  88. }
  89. // -> When the video element is paused, and the frame of video corresponding to the current playback position
  90. // is not available (e.g. because the video is seeking or buffering)
  91. // -> When the video element is neither potentially playing nor paused (e.g. when seeking or stalled)
  92. else if (
  93. (video_element.paused() && current_playback_position != current_frame.position)
  94. || (!video_element.potentially_playing() && !video_element.paused())) {
  95. // The video element represents the last frame of the video to have been rendered.
  96. representation = Representation::LastRenderedVideoFrame;
  97. }
  98. // -> When the video element is paused
  99. else if (video_element.paused()) {
  100. // The video element represents the frame of video corresponding to the current playback position.
  101. representation = Representation::CurrentVideoFrame;
  102. }
  103. // -> Otherwise (the video element has a video channel and is potentially playing)
  104. else {
  105. // The video element represents the frame of video at the continuously increasing "current" position. When the
  106. // current playback position changes such that the last frame rendered is no longer the frame corresponding to
  107. // the current playback position in the video, the new frame must be rendered.
  108. representation = Representation::CurrentVideoFrame;
  109. }
  110. auto paint_frame = [&](auto const& frame) {
  111. auto scaling_mode = to_gfx_scaling_mode(computed_values().image_rendering(), frame->rect(), video_rect.to_type<int>());
  112. context.painter().draw_scaled_bitmap(video_rect.to_type<int>(), *frame, frame->rect(), 1.f, scaling_mode);
  113. };
  114. auto paint_transparent_black = [&]() {
  115. static constexpr auto transparent_black = Gfx::Color::from_argb(0x00'00'00'00);
  116. context.painter().fill_rect(video_rect.to_type<int>(), transparent_black);
  117. };
  118. auto paint_user_agent_controls = video_element.has_attribute(HTML::AttributeNames::controls) || video_element.is_scripting_disabled();
  119. switch (representation) {
  120. case Representation::FirstVideoFrame:
  121. case Representation::CurrentVideoFrame:
  122. case Representation::LastRenderedVideoFrame:
  123. // FIXME: We likely need to cache all (or a subset of) decoded video frames along with their position. We at least
  124. // will need the first video frame and the last-rendered video frame.
  125. if (current_frame.frame)
  126. paint_frame(current_frame.frame);
  127. if (paint_user_agent_controls)
  128. paint_loaded_video_controls(context, video_element, video_rect, mouse_position);
  129. break;
  130. case Representation::PosterFrame:
  131. VERIFY(poster_frame);
  132. paint_frame(poster_frame);
  133. if (paint_user_agent_controls)
  134. paint_placeholder_video_controls(context, video_rect, mouse_position);
  135. break;
  136. case Representation::TransparentBlack:
  137. paint_transparent_black();
  138. if (paint_user_agent_controls)
  139. paint_placeholder_video_controls(context, video_rect, mouse_position);
  140. break;
  141. case Representation::Unknown:
  142. VERIFY_NOT_REACHED();
  143. }
  144. }
  145. void VideoPaintable::paint_loaded_video_controls(PaintContext& context, HTML::HTMLVideoElement const& video_element, DevicePixelRect video_rect, Optional<DevicePixelPoint> const& mouse_position) const
  146. {
  147. auto maximum_control_box_size = context.rounded_device_pixels(30);
  148. auto playback_padding = context.rounded_device_pixels(5);
  149. auto is_hovered = document().hovered_node() == &video_element;
  150. auto is_paused = video_element.paused();
  151. if (!is_hovered && !is_paused)
  152. return;
  153. auto control_box_rect = video_rect;
  154. if (control_box_rect.height() > maximum_control_box_size)
  155. control_box_rect.take_from_top(control_box_rect.height() - maximum_control_box_size);
  156. context.painter().fill_rect(control_box_rect.to_type<int>(), control_box_color.with_alpha(0xd0));
  157. layout_box().dom_node().cached_layout_boxes({}).control_box_rect = context.scale_to_css_rect(control_box_rect);
  158. control_box_rect = paint_control_bar_playback_button(context, video_element, control_box_rect, mouse_position);
  159. control_box_rect.take_from_left(playback_padding);
  160. control_box_rect = paint_control_bar_timeline(context, video_element, control_box_rect, mouse_position);
  161. control_box_rect.take_from_left(playback_padding);
  162. control_box_rect = paint_control_bar_timestamp(context, video_element, control_box_rect);
  163. control_box_rect.take_from_left(playback_padding);
  164. }
  165. DevicePixelRect VideoPaintable::paint_control_bar_playback_button(PaintContext& context, HTML::HTMLVideoElement const& video_element, DevicePixelRect control_box_rect, Optional<DevicePixelPoint> const& mouse_position) const
  166. {
  167. auto maximum_playback_button_size = context.rounded_device_pixels(15);
  168. auto maximum_playback_button_offset_x = context.rounded_device_pixels(15);
  169. auto playback_button_size = min(maximum_playback_button_size, control_box_rect.height() / 2);
  170. auto playback_button_offset_x = min(maximum_playback_button_offset_x, control_box_rect.width());
  171. auto playback_button_offset_y = (control_box_rect.height() - playback_button_size) / 2;
  172. auto playback_button_location = control_box_rect.top_left().translated(playback_button_offset_x, playback_button_offset_y);
  173. auto playback_button_hover_rect = DevicePixelRect {
  174. control_box_rect.top_left(),
  175. { playback_button_size + playback_button_offset_x * 2, control_box_rect.height() }
  176. };
  177. layout_box().dom_node().cached_layout_boxes({}).playback_button_rect = context.scale_to_css_rect(playback_button_hover_rect);
  178. auto playback_button_is_hovered = mouse_position.has_value() && playback_button_hover_rect.contains(*mouse_position);
  179. auto playback_button_color = control_button_color(playback_button_is_hovered);
  180. if (video_element.paused()) {
  181. Array<Gfx::IntPoint, 3> play_button_coordinates { {
  182. { 0, 0 },
  183. { static_cast<int>(playback_button_size), static_cast<int>(playback_button_size) / 2 },
  184. { 0, static_cast<int>(playback_button_size) },
  185. } };
  186. context.painter().draw_triangle(playback_button_location.to_type<int>(), play_button_coordinates, playback_button_color);
  187. } else {
  188. DevicePixelRect pause_button_left_rect {
  189. playback_button_location,
  190. { maximum_playback_button_size / 3, playback_button_size }
  191. };
  192. DevicePixelRect pause_button_right_rect {
  193. playback_button_location.translated(maximum_playback_button_size * 2 / 3, 0),
  194. { maximum_playback_button_size / 3, playback_button_size }
  195. };
  196. context.painter().fill_rect(pause_button_left_rect.to_type<int>(), playback_button_color);
  197. context.painter().fill_rect(pause_button_right_rect.to_type<int>(), playback_button_color);
  198. }
  199. control_box_rect.take_from_left(playback_button_hover_rect.width());
  200. return control_box_rect;
  201. }
  202. DevicePixelRect VideoPaintable::paint_control_bar_timeline(PaintContext& context, HTML::HTMLVideoElement const& video_element, DevicePixelRect control_box_rect, Optional<DevicePixelPoint> const& mouse_position) const
  203. {
  204. auto maximum_timeline_button_size = context.rounded_device_pixels(16);
  205. auto timeline_rect = control_box_rect;
  206. timeline_rect.set_width(min(control_box_rect.width() * 6 / 10, timeline_rect.width()));
  207. layout_box().dom_node().cached_layout_boxes({}).timeline_rect = context.scale_to_css_rect(timeline_rect);
  208. auto playback_percentage = video_element.current_time() / video_element.duration();
  209. auto playback_position = static_cast<double>(static_cast<int>(timeline_rect.width())) * playback_percentage;
  210. auto timeline_button_size = min(maximum_timeline_button_size, timeline_rect.height() / 2);
  211. auto timeline_button_offset_x = static_cast<DevicePixels>(round(playback_position));
  212. Gfx::AntiAliasingPainter painter { context.painter() };
  213. auto playback_timelime_scrub_rect = timeline_rect;
  214. playback_timelime_scrub_rect.shrink(0, timeline_rect.height() - timeline_button_size / 2);
  215. auto timeline_past_rect = playback_timelime_scrub_rect;
  216. timeline_past_rect.set_width(timeline_button_offset_x);
  217. painter.fill_rect_with_rounded_corners(timeline_past_rect.to_type<int>(), control_highlight_color.lightened(), 4);
  218. auto timeline_future_rect = playback_timelime_scrub_rect;
  219. timeline_future_rect.take_from_left(timeline_button_offset_x);
  220. painter.fill_rect_with_rounded_corners(timeline_future_rect.to_type<int>(), Color::Black, 4);
  221. auto timeline_button_rect = timeline_rect;
  222. timeline_button_rect.shrink(timeline_rect.width() - timeline_button_size, timeline_rect.height() - timeline_button_size);
  223. timeline_button_rect.set_x(timeline_rect.x() + timeline_button_offset_x - timeline_button_size / 2);
  224. auto timeline_is_hovered = mouse_position.has_value() && timeline_rect.contains(*mouse_position);
  225. auto timeline_color = control_button_color(timeline_is_hovered);
  226. painter.fill_ellipse(timeline_button_rect.to_type<int>(), timeline_color);
  227. control_box_rect.take_from_left(timeline_rect.width() + timeline_button_size / 2);
  228. return control_box_rect;
  229. }
  230. DevicePixelRect VideoPaintable::paint_control_bar_timestamp(PaintContext& context, HTML::HTMLVideoElement const& video_element, DevicePixelRect control_box_rect) const
  231. {
  232. auto current_time = human_readable_digital_time(round(video_element.current_time()));
  233. auto duration = human_readable_digital_time(round(video_element.duration()));
  234. auto timestamp = String::formatted("{} / {}", current_time, duration).release_value_but_fixme_should_propagate_errors();
  235. auto timestamp_size = static_cast<DevicePixels::Type>(ceilf(context.painter().font().width(timestamp)));
  236. if (timestamp_size > control_box_rect.width())
  237. return control_box_rect;
  238. auto timestamp_rect = control_box_rect;
  239. timestamp_rect.set_width(timestamp_size);
  240. auto const& scaled_font = layout_node().scaled_font(context);
  241. context.painter().draw_text(timestamp_rect.to_type<int>(), timestamp, scaled_font, Gfx::TextAlignment::CenterLeft, Color::White);
  242. control_box_rect.take_from_left(timestamp_rect.width());
  243. return control_box_rect;
  244. }
  245. void VideoPaintable::paint_placeholder_video_controls(PaintContext& context, DevicePixelRect video_rect, Optional<DevicePixelPoint> const& mouse_position) const
  246. {
  247. auto maximum_control_box_size = context.rounded_device_pixels(100);
  248. auto maximum_playback_button_size = context.rounded_device_pixels(40);
  249. auto center = video_rect.center();
  250. auto control_box_size = min(maximum_control_box_size, min(video_rect.width(), video_rect.height()) * 4 / 5);
  251. auto control_box_offset_x = control_box_size / 2;
  252. auto control_box_offset_y = control_box_size / 2;
  253. auto control_box_location = center.translated(-control_box_offset_x, -control_box_offset_y);
  254. DevicePixelRect control_box_rect { control_box_location, { control_box_size, control_box_size } };
  255. auto playback_button_size = min(maximum_playback_button_size, min(video_rect.width(), video_rect.height()) * 2 / 5);
  256. auto playback_button_offset_x = playback_button_size / 2;
  257. auto playback_button_offset_y = playback_button_size / 2;
  258. // We want to center the play button on its center of mass, which is not the midpoint of its vertices.
  259. // To do so, reduce its desired x offset by a factor of tan(30 degrees) / 2 (about 0.288685).
  260. playback_button_offset_x -= 0.288685f * static_cast<float>(static_cast<DevicePixels::Type>(playback_button_offset_x));
  261. auto playback_button_location = center.translated(-playback_button_offset_x, -playback_button_offset_y);
  262. Array<Gfx::IntPoint, 3> play_button_coordinates { {
  263. { 0, 0 },
  264. { static_cast<int>(playback_button_size), static_cast<int>(playback_button_size) / 2 },
  265. { 0, static_cast<int>(playback_button_size) },
  266. } };
  267. auto playback_button_is_hovered = mouse_position.has_value() && control_box_rect.contains(*mouse_position);
  268. auto playback_button_color = control_button_color(playback_button_is_hovered);
  269. Gfx::AntiAliasingPainter painter { context.painter() };
  270. painter.fill_ellipse(control_box_rect.to_type<int>(), control_box_color);
  271. context.painter().draw_triangle(playback_button_location.to_type<int>(), play_button_coordinates, playback_button_color);
  272. }
  273. VideoPaintable::DispatchEventOfSameName VideoPaintable::handle_mouseup(Badge<EventHandler>, CSSPixelPoint position, unsigned button, unsigned)
  274. {
  275. if (button != GUI::MouseButton::Primary)
  276. return DispatchEventOfSameName::Yes;
  277. auto& video_element = layout_box().dom_node();
  278. auto const& cached_layout_boxes = video_element.cached_layout_boxes({});
  279. // FIXME: This runs from outside the context of any user script, so we do not have a running execution
  280. // context. This pushes one to allow the promise creation hook to run.
  281. auto& environment_settings = document().relevant_settings_object();
  282. environment_settings.prepare_to_run_script();
  283. ScopeGuard guard { [&] { environment_settings.clean_up_after_running_script(); } };
  284. auto toggle_playback = [&]() -> WebIDL::ExceptionOr<void> {
  285. if (video_element.paused())
  286. TRY(video_element.play());
  287. else
  288. TRY(video_element.pause());
  289. return {};
  290. };
  291. if (cached_layout_boxes.control_box_rect.has_value() && cached_layout_boxes.control_box_rect->contains(position)) {
  292. if (cached_layout_boxes.playback_button_rect.has_value() && cached_layout_boxes.playback_button_rect->contains(position)) {
  293. toggle_playback().release_value_but_fixme_should_propagate_errors();
  294. return DispatchEventOfSameName::Yes;
  295. }
  296. if (cached_layout_boxes.timeline_rect.has_value() && cached_layout_boxes.timeline_rect->contains(position)) {
  297. auto x_offset = position.x() - cached_layout_boxes.timeline_rect->x();
  298. auto x_percentage = static_cast<float>(x_offset) / static_cast<float>(cached_layout_boxes.timeline_rect->width());
  299. auto position = static_cast<double>(x_percentage) * video_element.duration();
  300. video_element.set_current_time(position);
  301. return DispatchEventOfSameName::Yes;
  302. }
  303. return DispatchEventOfSameName::No;
  304. }
  305. toggle_playback().release_value_but_fixme_should_propagate_errors();
  306. return DispatchEventOfSameName::Yes;
  307. }
  308. VideoPaintable::DispatchEventOfSameName VideoPaintable::handle_mousemove(Badge<EventHandler>, CSSPixelPoint position, unsigned, unsigned)
  309. {
  310. auto& video_element = layout_box().dom_node();
  311. if (absolute_rect().contains(position)) {
  312. video_element.set_layout_mouse_position({}, position);
  313. return DispatchEventOfSameName::Yes;
  314. }
  315. video_element.set_layout_mouse_position({}, {});
  316. return DispatchEventOfSameName::No;
  317. }
  318. }