2 Copyright (C) 2014-2021 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
6 DCP-o-matic 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 2 of the License, or
9 (at your option) any later version.
11 DCP-o-matic 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 DCP-o-matic. If not, see <http://www.gnu.org/licenses/>.
23 #include "dcpomatic_assert.h"
25 #include "font_config.h"
27 #include "render_text.h"
29 #include <dcp/raw_convert.h>
30 #include <dcp/warnings.h>
31 #include <cairomm/cairomm.h>
32 LIBDCP_DISABLE_WARNINGS
34 LIBDCP_ENABLE_WARNINGS
35 #include <pango/pangocairo.h>
36 #include <boost/algorithm/string.hpp>
44 using std::make_shared;
48 using std::shared_ptr;
50 using boost::optional;
51 using namespace dcpomatic;
54 /** Create a Pango layout using a dummy context which we can use to calculate the size
55 * of the text we will render. Then we can transfer the layout over to the real context
56 * for the actual render.
58 static Glib::RefPtr<Pango::Layout>
59 create_layout(string font_name, string markup)
61 auto c_font_map = pango_cairo_font_map_new ();
62 DCPOMATIC_ASSERT (c_font_map);
63 auto font_map = Glib::wrap (c_font_map);
64 auto c_context = pango_font_map_create_context (c_font_map);
65 DCPOMATIC_ASSERT (c_context);
66 auto context = Glib::wrap (c_context);
67 auto layout = Pango::Layout::create(context);
69 layout->set_alignment (Pango::ALIGN_LEFT);
70 Pango::FontDescription font (font_name);
71 layout->set_font_description (font);
72 layout->set_markup (markup);
79 marked_up (list<StringText> subtitles, int target_height, float fade_factor, string font_name)
81 auto constexpr pixels_to_1024ths_point = 72 * 1024 / 96;
83 auto make_span = [target_height, fade_factor](StringText const& subtitle, string text, string extra_attribute) {
86 if (subtitle.italic()) {
87 span += "style=\"italic\" ";
89 if (subtitle.bold()) {
90 span += "weight=\"bold\" ";
92 if (subtitle.underline()) {
93 span += "underline=\"single\" ";
95 span += "size=\"" + dcp::raw_convert<string>(lrintf(subtitle.size_in_pixels(target_height) * pixels_to_1024ths_point)) + "\" ";
96 /* Between 1-65535 inclusive, apparently... */
97 span += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
98 span += "color=\"#" + subtitle.colour().to_rgb_string() + "\"";
99 if (!extra_attribute.empty()) {
100 span += " " + extra_attribute;
104 boost::algorithm::replace_all(text, "&", "&");
105 boost::algorithm::replace_all(text, "<", "<");
106 boost::algorithm::replace_all(text, ">", ">");
114 for (auto const& i: subtitles) {
115 if (std::abs(i.space_before()) > dcp::SPACE_BEFORE_EPSILON) {
116 /* We need to insert some horizontal space into the layout. The only way I can find to do this
117 * is to write a " " with some special letter_spacing. As far as I can see, such a space will
118 * be written with letter_spacing either side. This means that to get a horizontal space x we
119 * need to write a " " with letter spacing (x - s) / 2, where s is the width of the " ".
121 auto layout = create_layout(font_name, make_span(i, " ", {}));
124 layout->get_pixel_size(space_width, dummy);
125 auto spacing = ((i.space_before() * i.size_in_pixels(target_height) - space_width) / 2) * pixels_to_1024ths_point;
126 out += make_span(i, " ", "letter_spacing=\"" + dcp::raw_convert<string>(spacing) + "\"");
129 out += make_span(i, i.text(), {});
137 set_source_rgba (Cairo::RefPtr<Cairo::Context> context, dcp::Colour colour, float fade_factor)
139 context->set_source_rgba (float(colour.r) / 255, float(colour.g) / 255, float(colour.b) / 255, fade_factor);
143 static shared_ptr<Image>
144 create_image (dcp::Size size)
146 /* FFmpeg BGRA means first byte blue, second byte green, third byte red, fourth byte alpha.
147 * This must be COMPACT as we're using it with Cairo::ImageSurface::create
149 auto image = make_shared<Image>(AV_PIX_FMT_BGRA, size, Image::Alignment::COMPACT);
150 image->make_black ();
155 static Cairo::RefPtr<Cairo::ImageSurface>
156 create_surface (shared_ptr<Image> image)
158 /* XXX: I don't think it's guaranteed that format_stride_for_width will return a stride without any padding,
159 * so it's lucky that this works.
161 DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
162 DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_BGRA);
163 return Cairo::ImageSurface::create (
165 Cairo::FORMAT_ARGB32,
167 image->size().height,
168 /* Cairo ARGB32 means first byte blue, second byte green, third byte red, fourth byte alpha */
169 Cairo::ImageSurface::format_stride_for_width (Cairo::FORMAT_ARGB32, image->size().width)
175 calculate_fade_factor (StringText const& first, DCPTime time, int frame_rate)
177 float fade_factor = 1;
179 /* Round the fade start/end to the nearest frame start. Otherwise if a subtitle starts just after
180 the start of a frame it will be faded out.
182 auto const fade_in_start = DCPTime::from_seconds(first.in().as_seconds()).round(frame_rate);
183 auto const fade_in_end = fade_in_start + DCPTime::from_seconds (first.fade_up_time().as_seconds ());
185 if (fade_in_start <= time && time <= fade_in_end && fade_in_start != fade_in_end) {
186 fade_factor *= DCPTime(time - fade_in_start).seconds() / DCPTime(fade_in_end - fade_in_start).seconds();
189 if (time < fade_in_start) {
193 /* first.out() may be zero if we don't know when this subtitle will finish. We can only think about
194 * fading out if we _do_ know when it will finish.
196 if (first.out() != dcp::Time()) {
197 auto const fade_out_end = DCPTime::from_seconds (first.out().as_seconds()).round(frame_rate);
198 auto const fade_out_start = fade_out_end - DCPTime::from_seconds(first.fade_down_time().as_seconds());
200 if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
201 fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
203 if (time > fade_out_end) {
213 x_position(dcp::HAlign align, float position, int target_width, int layout_width)
217 case dcp::HAlign::LEFT:
218 /* h_position is distance between left of frame and left of subtitle */
219 x = position * target_width;
221 case dcp::HAlign::CENTER:
222 /* h_position is distance between centre of frame and centre of subtitle */
223 x = (0.5 + position) * target_width - layout_width / 2;
225 case dcp::HAlign::RIGHT:
226 /* h_position is distance between right of frame and right of subtitle */
227 x = (1.0 - position) * target_width - layout_width;
235 /** @param align_standard Standard with which to interpret this subtitle's position.
236 * @param align alignment.
237 * @param position position (between 0 and 1)
238 * @param target_height Height of the target screen (in pixels).
239 * @param baseline_to_bottom Distance from text baseline to the bottom of the bounding box (in pixels).
240 * @param layout_height Height of the subtitle bounding box (in pixels).
241 * @return y position of the top of the subtitle bounding box (in pixels) from the top of the screen.
244 y_position(dcp::SubtitleStandard standard, dcp::VAlign align, float position, int target_height, int baseline_to_bottom, int layout_height)
248 case dcp::SubtitleStandard::INTEROP:
249 case dcp::SubtitleStandard::SMPTE_2014:
251 case dcp::VAlign::TOP:
252 /* position is distance from top of frame to subtitle baseline */
253 y = position * target_height - (layout_height - baseline_to_bottom);
255 case dcp::VAlign::CENTER:
256 /* position is distance from centre of frame to subtitle baseline */
257 y = (0.5 + position) * target_height - (layout_height - baseline_to_bottom);
259 case dcp::VAlign::BOTTOM:
260 /* position is distance from bottom of frame to subtitle baseline */
261 y = (1.0 - position) * target_height - (layout_height - baseline_to_bottom);
265 case dcp::SubtitleStandard::SMPTE_2007:
266 case dcp::SubtitleStandard::SMPTE_2010:
268 case dcp::VAlign::TOP:
269 /* v_position is distance from top of frame to top of subtitle */
270 y = position * target_height;
272 case dcp::VAlign::CENTER:
273 /* v_position is distance from centre of frame to centre of subtitle */
274 y = (0.5 + position) * target_height - layout_height / 2;
276 case dcp::VAlign::BOTTOM:
277 /* v_position is distance from bottom of frame to bottom of subtitle */
278 y = (1.0 - position) * target_height - layout_height;
289 Position<int> position;
291 Glib::RefPtr<Pango::Layout> pango;
295 /** @param subtitles A list of subtitles that are all on the same line,
296 * at the same time and with the same fade in/out.
299 setup_layout(list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
301 DCPOMATIC_ASSERT(!subtitles.empty());
302 auto const& first = subtitles.front();
304 auto const font_name = FontConfig::instance()->make_font_available(first.font);
305 auto const fade_factor = calculate_fade_factor(first, time, frame_rate);
306 auto const markup = marked_up(subtitles, target.height, fade_factor, font_name);
307 auto layout = create_layout(font_name, markup);
308 auto ink = layout->get_ink_extents();
309 return { { ink.get_x() / Pango::SCALE, ink.get_y() / Pango::SCALE }, { ink.get_width() / Pango::SCALE, ink.get_height() / Pango::SCALE }, layout };
313 /** @param subtitles A list of subtitles that are all on the same line,
314 * at the same time and with the same fade in/out.
317 render_line (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
319 /* XXX: this method can only handle italic / bold changes mid-line,
323 DCPOMATIC_ASSERT(!subtitles.empty ());
324 auto const& first = subtitles.front();
325 auto const fade_factor = calculate_fade_factor(first, time, frame_rate);
327 auto layout = setup_layout(subtitles, target, time, frame_rate);
329 /* Calculate x and y scale factors. These are only used to stretch
330 the font away from its normal aspect ratio.
334 if (fabs (first.aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
335 if (first.aspect_adjust() < 1) {
336 x_scale = max (0.25f, first.aspect_adjust ());
340 y_scale = 1 / min (4.0f, first.aspect_adjust ());
344 auto const border_width = first.effect() == dcp::Effect::BORDER ? (first.outline_width * target.width / 2048.0) : 0;
345 layout.size.width += 2 * ceil (border_width);
346 layout.size.height += 2 * ceil (border_width);
348 layout.size.width *= x_scale;
349 layout.size.height *= y_scale;
351 /* Shuffle the subtitle over by the border width (if we have any) so it's not cut off */
352 int const x_offset = -layout.position.x + ceil(border_width);
353 int const y_offset = -layout.position.y + ceil(border_width);
355 auto image = create_image(layout.size);
356 auto surface = create_surface (image);
357 auto context = Cairo::Context::create (surface);
359 context->set_line_width (1);
360 context->scale (x_scale, y_scale);
361 layout.pango->update_from_cairo_context(context);
363 if (first.effect() == dcp::Effect::SHADOW) {
364 /* Drop-shadow effect */
365 set_source_rgba (context, first.effect_colour(), fade_factor);
366 context->move_to (x_offset + 4, y_offset + 4);
367 layout.pango->add_to_cairo_context(context);
371 if (first.effect() == dcp::Effect::BORDER) {
373 set_source_rgba (context, first.effect_colour(), fade_factor);
374 context->set_line_width (border_width);
375 context->set_line_join (Cairo::LINE_JOIN_ROUND);
376 context->move_to (x_offset, y_offset);
377 layout.pango->add_to_cairo_context (context);
381 /* The actual subtitle */
383 set_source_rgba (context, first.colour(), fade_factor);
385 context->move_to (x_offset, y_offset);
386 layout.pango->add_to_cairo_context (context);
389 context->set_line_width (0.5);
390 context->move_to (x_offset, y_offset);
391 layout.pango->add_to_cairo_context (context);
394 int const x = x_position(first.h_align(), first.h_position(), target.width, layout.size.width);
395 int const y = y_position(first.valign_standard, first.v_align(), first.v_position(), target.height, layout.position.y, layout.size.height);
396 return PositionImage (image, Position<int>(max (0, x), max(0, y)));
400 /** @param time Time of the frame that these subtitles are going on.
401 * @param target Size of the container that this subtitle will end up in.
402 * @param frame_rate DCP frame rate.
405 render_text (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
407 list<StringText> pending;
408 list<PositionImage> images;
410 for (auto const& i: subtitles) {
411 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
412 images.push_back(render_line(pending, target, time, frame_rate));
415 pending.push_back (i);
418 if (!pending.empty()) {
419 images.push_back(render_line(pending, target, time, frame_rate));
426 list<dcpomatic::Rect<int>>
427 bounding_box(list<StringText> subtitles, dcp::Size target, optional<dcp::SubtitleStandard> override_standard)
429 list<StringText> pending;
430 list<dcpomatic::Rect<int>> rects;
432 auto use_pending = [&pending, &rects, target, override_standard]() {
433 auto const& subtitle = pending.front();
434 auto standard = override_standard.get_value_or(subtitle.valign_standard);
435 /* We can provide dummy values for time and frame rate here as they are only used to calculate fades */
436 auto layout = setup_layout(pending, target, DCPTime(), 24);
437 int const x = x_position(subtitle.h_align(), subtitle.h_position(), target.width, layout.size.width);
438 int const y = y_position(standard, subtitle.v_align(), subtitle.v_position(), target.height, layout.position.y, layout.size.height);
439 rects.push_back({Position<int>(x, y), layout.size.width, layout.size.height});
442 for (auto const& i: subtitles) {
443 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
447 pending.push_back(i);
450 if (!pending.empty()) {
459 FontMetrics::height(StringText const& subtitle)
461 return get(subtitle)->second.second;
466 FontMetrics::baseline_to_bottom(StringText const& subtitle)
468 return get(subtitle)->second.first;
472 FontMetrics::Cache::iterator
473 FontMetrics::get(StringText const& subtitle)
475 auto id = Identifier(subtitle);
477 auto iter = _cache.find(id);
478 if (iter != _cache.end()) {
482 auto const font_name = FontConfig::instance()->make_font_available(subtitle.font);
483 auto copy = subtitle;
484 copy.set_text("Qypjg");
485 auto layout = create_layout(font_name, marked_up({copy}, _target_height, 1, font_name));
486 auto ink = layout->get_ink_extents();
487 auto const scale = float(_target_height * Pango::SCALE);
488 return _cache.insert({id, { ink.get_y() / scale, ink.get_height() / scale}}).first;
492 FontMetrics::Identifier::Identifier(StringText const& subtitle)
493 : font(subtitle.font)
494 , size(subtitle.size())
495 , aspect_adjust(subtitle.aspect_adjust())
502 FontMetrics::Identifier::operator<(FontMetrics::Identifier const& other) const
504 if (font != other.font) {
505 return font < other.font;
508 if (size != other.size) {
509 return size < other.size;
512 return aspect_adjust < other.aspect_adjust;