Escape entities just before Pango rendering (#2382).
[dcpomatic.git] / src / lib / render_text.cc
1 /*
2     Copyright (C) 2014-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
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.
10
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.
15
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/>.
18
19 */
20
21
22 #include "cross.h"
23 #include "dcpomatic_assert.h"
24 #include "font.h"
25 #include "font_config.h"
26 #include "image.h"
27 #include "render_text.h"
28 #include "types.h"
29 #include "util.h"
30 #include <dcp/raw_convert.h>
31 #include <dcp/warnings.h>
32 #include <cairomm/cairomm.h>
33 LIBDCP_DISABLE_WARNINGS
34 #include <pangomm.h>
35 LIBDCP_ENABLE_WARNINGS
36 #include <pango/pangocairo.h>
37 #include <boost/algorithm/string.hpp>
38 #include <iostream>
39
40
41 using std::cerr;
42 using std::cout;
43 using std::list;
44 using std::make_pair;
45 using std::make_shared;
46 using std::max;
47 using std::min;
48 using std::pair;
49 using std::shared_ptr;
50 using std::string;
51 using namespace dcpomatic;
52
53
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.
57  */
58 static Glib::RefPtr<Pango::Layout>
59 create_layout()
60 {
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         return Pango::Layout::create (context);
68 }
69
70
71 static void
72 setup_layout (Glib::RefPtr<Pango::Layout> layout, string font_name, string markup)
73 {
74         layout->set_alignment (Pango::ALIGN_LEFT);
75         Pango::FontDescription font (font_name);
76         layout->set_font_description (font);
77         layout->set_markup (markup);
78 }
79
80
81 string
82 marked_up (list<StringText> subtitles, int target_height, float fade_factor, string font_name)
83 {
84         auto constexpr pixels_to_1024ths_point = 72 * 1024 / 96;
85
86         auto make_span = [target_height, fade_factor](StringText const& subtitle, string text, string extra_attribute) {
87                 string span;
88                 span += "<span ";
89                 if (subtitle.italic()) {
90                         span += "style=\"italic\" ";
91                 }
92                 if (subtitle.bold()) {
93                         span += "weight=\"bold\" ";
94                 }
95                 if (subtitle.underline()) {
96                         span += "underline=\"single\" ";
97                 }
98                 span += "size=\"" + dcp::raw_convert<string>(lrintf(subtitle.size_in_pixels(target_height) * pixels_to_1024ths_point)) + "\" ";
99                 /* Between 1-65535 inclusive, apparently... */
100                 span += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
101                 span += "color=\"#" + subtitle.colour().to_rgb_string() + "\"";
102                 if (!extra_attribute.empty()) {
103                         span += " " + extra_attribute;
104                 }
105                 span += ">";
106
107                 boost::algorithm::replace_all(text, "&", "&amp;");
108                 boost::algorithm::replace_all(text, "<", "&lt;");
109                 boost::algorithm::replace_all(text, ">", "&gt;");
110
111                 span += text;
112                 span += "</span>";
113                 return span;
114         };
115
116         string out;
117         for (auto const& i: subtitles) {
118                 if (std::abs(i.space_before()) > dcp::SPACE_BEFORE_EPSILON) {
119                         /* We need to insert some horizontal space into the layout.  The only way I can find to do this
120                          * is to write a " " with some special letter_spacing.  As far as I can see, such a space will
121                          * be written with letter_spacing either side.  This means that to get a horizontal space x we
122                          * need to write a " " with letter spacing (x - s) / 2, where s is the width of the " ".
123                          */
124                         auto layout = create_layout();
125                         setup_layout(layout, font_name, make_span(i, " ", {}));
126                         int space_width;
127                         int dummy;
128                         layout->get_pixel_size(space_width, dummy);
129                         auto spacing = ((i.space_before() * i.size_in_pixels(target_height) - space_width) / 2) * pixels_to_1024ths_point;
130                         out += make_span(i, " ", "letter_spacing=\"" + dcp::raw_convert<string>(spacing) + "\"");
131                 }
132
133                 out += make_span(i, i.text(), {});
134         }
135
136         return out;
137 }
138
139
140 static void
141 set_source_rgba (Cairo::RefPtr<Cairo::Context> context, dcp::Colour colour, float fade_factor)
142 {
143         context->set_source_rgba (float(colour.r) / 255, float(colour.g) / 255, float(colour.b) / 255, fade_factor);
144 }
145
146
147 static shared_ptr<Image>
148 create_image (dcp::Size size)
149 {
150         /* FFmpeg BGRA means first byte blue, second byte green, third byte red, fourth byte alpha.
151          * This must be COMPACT as we're using it with Cairo::ImageSurface::create
152          */
153         auto image = make_shared<Image>(AV_PIX_FMT_BGRA, size, Image::Alignment::COMPACT);
154         image->make_black ();
155         return image;
156 }
157
158
159 static Cairo::RefPtr<Cairo::ImageSurface>
160 create_surface (shared_ptr<Image> image)
161 {
162         /* XXX: I don't think it's guaranteed that format_stride_for_width will return a stride without any padding,
163          * so it's lucky that this works.
164          */
165         DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
166         DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_BGRA);
167         return Cairo::ImageSurface::create (
168                 image->data()[0],
169                 Cairo::FORMAT_ARGB32,
170                 image->size().width,
171                 image->size().height,
172                 /* Cairo ARGB32 means first byte blue, second byte green, third byte red, fourth byte alpha */
173                 Cairo::ImageSurface::format_stride_for_width (Cairo::FORMAT_ARGB32, image->size().width)
174                 );
175 }
176
177
178 static string
179 setup_font(shared_ptr<const dcpomatic::Font> font)
180 {
181         auto font_file = default_font_file ();
182
183         if (font && font->file()) {
184                 font_file = *font->file();
185         }
186
187         return FontConfig::instance()->make_font_available(font_file);
188 }
189
190
191 static float
192 calculate_fade_factor (StringText const& first, DCPTime time, int frame_rate)
193 {
194         float fade_factor = 1;
195
196         /* Round the fade start/end to the nearest frame start.  Otherwise if a subtitle starts just after
197            the start of a frame it will be faded out.
198         */
199         auto const fade_in_start = DCPTime::from_seconds(first.in().as_seconds()).round(frame_rate);
200         auto const fade_in_end = fade_in_start + DCPTime::from_seconds (first.fade_up_time().as_seconds ());
201
202         if (fade_in_start <= time && time <= fade_in_end && fade_in_start != fade_in_end) {
203                 fade_factor *= DCPTime(time - fade_in_start).seconds() / DCPTime(fade_in_end - fade_in_start).seconds();
204         }
205
206         if (time < fade_in_start) {
207                 fade_factor = 0;
208         }
209
210         /* first.out() may be zero if we don't know when this subtitle will finish.  We can only think about
211          * fading out if we _do_ know when it will finish.
212          */
213         if (first.out() != dcp::Time()) {
214                 auto const fade_out_end = DCPTime::from_seconds (first.out().as_seconds()).round(frame_rate);
215                 auto const fade_out_start = fade_out_end - DCPTime::from_seconds(first.fade_down_time().as_seconds());
216
217                 if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
218                         fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
219                 }
220                 if (time > fade_out_end) {
221                         fade_factor = 0;
222                 }
223         }
224
225         return fade_factor;
226 }
227
228
229 static int
230 x_position (StringText const& first, int target_width, int layout_width)
231 {
232         int x = 0;
233         switch (first.h_align()) {
234         case dcp::HAlign::LEFT:
235                 /* h_position is distance between left of frame and left of subtitle */
236                 x = first.h_position() * target_width;
237                 break;
238         case dcp::HAlign::CENTER:
239                 /* h_position is distance between centre of frame and centre of subtitle */
240                 x = (0.5 + first.h_position()) * target_width - layout_width / 2;
241                 break;
242         case dcp::HAlign::RIGHT:
243                 /* h_position is distance between right of frame and right of subtitle */
244                 x = (1.0 - first.h_position()) * target_width - layout_width;
245                 break;
246         }
247
248         return x;
249 }
250
251
252 static int
253 y_position (StringText const& first, int target_height, int baseline_to_bottom, int layout_height)
254 {
255         int y = 0;
256         switch (first.valign_standard) {
257         case dcp::Standard::INTEROP:
258                 switch (first.v_align()) {
259                 case dcp::VAlign::TOP:
260                         /* v_position is distance from top of frame to subtitle baseline */
261                         y = first.v_position() * target_height - (layout_height - baseline_to_bottom);
262                         break;
263                 case dcp::VAlign::CENTER:
264                         /* v_position is distance from centre of frame to subtitle baseline */
265                         y = (0.5 + first.v_position()) * target_height - (layout_height - baseline_to_bottom);
266                         break;
267                 case dcp::VAlign::BOTTOM:
268                         /* v_position is distance from bottom of frame to subtitle baseline */
269                         y = (1.0 - first.v_position()) * target_height - (layout_height - baseline_to_bottom);
270                         break;
271                 }
272                 break;
273         case dcp::Standard::SMPTE:
274                 switch (first.v_align()) {
275                 case dcp::VAlign::TOP:
276                         /* v_position is distance from top of frame to top of subtitle */
277                         y = first.v_position() * target_height;
278                         break;
279                 case dcp::VAlign::CENTER:
280                         /* v_position is distance from centre of frame to centre of subtitle */
281                         y = (0.5 + first.v_position()) * target_height - layout_height / 2;
282                         break;
283                 case dcp::VAlign::BOTTOM:
284                         /* v_position is distance from bottom of frame to bottom of subtitle */
285                         y = (1.0 - first.v_position()) * target_height - layout_height;
286                         break;
287                 }
288         }
289
290         return y;
291 }
292
293
294 /** @param subtitles A list of subtitles that are all on the same line,
295  *  at the same time and with the same fade in/out.
296  */
297 static PositionImage
298 render_line (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
299 {
300         /* XXX: this method can only handle italic / bold changes mid-line,
301            nothing else yet.
302         */
303
304         DCPOMATIC_ASSERT (!subtitles.empty ());
305         auto const& first = subtitles.front ();
306
307         auto const font_name = setup_font(first.font);
308         auto const fade_factor = calculate_fade_factor (first, time, frame_rate);
309         auto const markup = marked_up (subtitles, target.height, fade_factor, font_name);
310         auto layout = create_layout ();
311         setup_layout (layout, font_name, markup);
312         auto ink = layout->get_ink_extents();
313         dcp::Size size{ink.get_width() / Pango::SCALE, ink.get_height() / Pango::SCALE};
314
315         /* Calculate x and y scale factors.  These are only used to stretch
316            the font away from its normal aspect ratio.
317         */
318         float x_scale = 1;
319         float y_scale = 1;
320         if (fabs (first.aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
321                 if (first.aspect_adjust() < 1) {
322                         x_scale = max (0.25f, first.aspect_adjust ());
323                         y_scale = 1;
324                 } else {
325                         x_scale = 1;
326                         y_scale = 1 / min (4.0f, first.aspect_adjust ());
327                 }
328         }
329
330         auto const border_width = first.effect() == dcp::Effect::BORDER ? (first.outline_width * target.width / 2048.0) : 0;
331         size.width += 2 * ceil (border_width);
332         size.height += 2 * ceil (border_width);
333
334         size.width *= x_scale;
335         size.height *= y_scale;
336
337         /* Shuffle the subtitle over by the border width (if we have any) so it's not cut off */
338         int const x_offset = (-ink.get_x() / Pango::SCALE) + ceil(border_width);
339         int const y_offset = -ink.get_y() / Pango::SCALE + ceil(border_width);
340
341         auto image = create_image (size);
342         auto surface = create_surface (image);
343         auto context = Cairo::Context::create (surface);
344
345         context->set_line_width (1);
346         context->scale (x_scale, y_scale);
347         layout->update_from_cairo_context (context);
348
349         if (first.effect() == dcp::Effect::SHADOW) {
350                 /* Drop-shadow effect */
351                 set_source_rgba (context, first.effect_colour(), fade_factor);
352                 context->move_to (x_offset + 4, y_offset + 4);
353                 layout->add_to_cairo_context (context);
354                 context->fill ();
355         }
356
357         if (first.effect() == dcp::Effect::BORDER) {
358                 /* Border effect */
359                 set_source_rgba (context, first.effect_colour(), fade_factor);
360                 context->set_line_width (border_width);
361                 context->set_line_join (Cairo::LINE_JOIN_ROUND);
362                 context->move_to (x_offset, y_offset);
363                 layout->add_to_cairo_context (context);
364                 context->stroke ();
365         }
366
367         /* The actual subtitle */
368
369         set_source_rgba (context, first.colour(), fade_factor);
370
371         context->move_to (x_offset, y_offset);
372         layout->add_to_cairo_context (context);
373         context->fill ();
374
375         context->set_line_width (0.5);
376         context->move_to (x_offset, y_offset);
377         layout->add_to_cairo_context (context);
378         context->stroke ();
379
380         int const x = x_position (first, target.width, size.width);
381         int const y = y_position (first, target.height, ink.get_y() / Pango::SCALE, size.height);
382         return PositionImage (image, Position<int>(max (0, x), max(0, y)));
383 }
384
385
386 /** @param time Time of the frame that these subtitles are going on.
387  *  @param target Size of the container that this subtitle will end up in.
388  *  @param frame_rate DCP frame rate.
389  */
390 list<PositionImage>
391 render_text (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
392 {
393         list<StringText> pending;
394         list<PositionImage> images;
395
396         for (auto const& i: subtitles) {
397                 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
398                         images.push_back(render_line(pending, target, time, frame_rate));
399                         pending.clear ();
400                 }
401                 pending.push_back (i);
402         }
403
404         if (!pending.empty()) {
405                 images.push_back(render_line(pending, target, time, frame_rate));
406         }
407
408         return images;
409 }
410
411
412 float
413 FontMetrics::height(StringText const& subtitle)
414 {
415         return get(subtitle)->second.second;
416 }
417
418
419 float
420 FontMetrics::baseline_to_bottom(StringText const& subtitle)
421 {
422         return get(subtitle)->second.first;
423 }
424
425
426 FontMetrics::Cache::iterator
427 FontMetrics::get(StringText const& subtitle)
428 {
429         auto id = Identifier(subtitle);
430
431         auto iter = _cache.find(id);
432         if (iter != _cache.end()) {
433                 return iter;
434         }
435
436         auto const font_name = setup_font(subtitle.font);
437         auto layout = create_layout();
438         auto copy = subtitle;
439         copy.set_text("Qypjg");
440         setup_layout(layout, font_name, marked_up({copy}, _target_height, 1, font_name));
441         auto ink = layout->get_ink_extents();
442         auto const scale = float(_target_height * Pango::SCALE);
443         return _cache.insert({id, { ink.get_y() / scale, ink.get_height() / scale}}).first;
444 }
445
446
447 FontMetrics::Identifier::Identifier(StringText const& subtitle)
448         : font(subtitle.font)
449         , size(subtitle.size())
450         , aspect_adjust(subtitle.aspect_adjust())
451 {
452
453 }
454
455
456 bool
457 FontMetrics::Identifier::operator<(FontMetrics::Identifier const& other) const
458 {
459         if (font != other.font) {
460                 return font < other.font;
461         }
462
463         if (size != other.size) {
464             return size < other.size;
465         }
466
467         return aspect_adjust < other.aspect_adjust;
468 }
469