Allow building with C++17 and updated libxml++/pangomm/cairomm.
[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 "util.h"
29 #include <dcp/raw_convert.h>
30 #include <dcp/warnings.h>
31 #include <cairomm/cairomm.h>
32 LIBDCP_DISABLE_WARNINGS
33 #include <pangomm.h>
34 LIBDCP_ENABLE_WARNINGS
35 #include <pango/pangocairo.h>
36 #include <boost/algorithm/string.hpp>
37 #include <iostream>
38
39
40 using std::cerr;
41 using std::cout;
42 using std::make_pair;
43 using std::make_shared;
44 using std::max;
45 using std::min;
46 using std::pair;
47 using std::shared_ptr;
48 using std::string;
49 using std::vector;
50 using boost::optional;
51 using namespace dcpomatic;
52
53
54 #if CAIROMM_MAJOR_VERSION == 1 && CAIROMM_MINOR_VERSION <= 14
55 #define DCPOMATIC_OLD_CAIROMM_API
56 #endif
57
58 #if PANGOMM_MAJOR_VERSION == 2 && PANGOMM_MINOR_VERSION <= 46
59 #define DCPOMATIC_OLD_PANGOMM_API
60 #endif
61
62
63 /** Create a Pango layout using a dummy context which we can use to calculate the size
64  *  of the text we will render.  Then we can transfer the layout over to the real context
65  *  for the actual render.
66  */
67 static Glib::RefPtr<Pango::Layout>
68 create_layout(string font_name, string markup)
69 {
70         auto c_font_map = pango_cairo_font_map_new ();
71         DCPOMATIC_ASSERT (c_font_map);
72         auto font_map = Glib::wrap (c_font_map);
73         auto c_context = pango_font_map_create_context (c_font_map);
74         DCPOMATIC_ASSERT (c_context);
75         auto context = Glib::wrap (c_context);
76         auto layout = Pango::Layout::create(context);
77
78 #ifdef DCPOMATIC_OLD_PANGOMM_API
79         layout->set_alignment(Pango::ALIGN_LEFT);
80 #else
81         layout->set_alignment(Pango::Alignment::LEFT);
82 #endif
83         Pango::FontDescription font (font_name);
84         layout->set_font_description (font);
85         layout->set_markup (markup);
86
87         return layout;
88 }
89
90
91 string
92 marked_up(vector<StringText> subtitles, int target_height, float fade_factor, string font_name)
93 {
94         auto constexpr pixels_to_1024ths_point = 72 * 1024 / 96;
95
96         auto make_span = [target_height, fade_factor](StringText const& subtitle, string text, string extra_attribute) {
97                 string span;
98                 span += "<span ";
99                 if (subtitle.italic()) {
100                         span += "style=\"italic\" ";
101                 }
102                 if (subtitle.bold()) {
103                         span += "weight=\"bold\" ";
104                 }
105                 if (subtitle.underline()) {
106                         span += "underline=\"single\" ";
107                 }
108                 span += "size=\"" + dcp::raw_convert<string>(lrintf(subtitle.size_in_pixels(target_height) * pixels_to_1024ths_point)) + "\" ";
109                 /* Between 1-65535 inclusive, apparently... */
110                 span += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
111                 span += "color=\"#" + subtitle.colour().to_rgb_string() + "\"";
112                 if (!extra_attribute.empty()) {
113                         span += " " + extra_attribute;
114                 }
115                 span += ">";
116
117                 boost::algorithm::replace_all(text, "&", "&amp;");
118                 boost::algorithm::replace_all(text, "<", "&lt;");
119                 boost::algorithm::replace_all(text, ">", "&gt;");
120                 boost::algorithm::replace_all(text, "\n", "");
121
122                 span += text;
123                 span += "</span>";
124                 return span;
125         };
126
127         string out;
128         for (auto const& i: subtitles) {
129                 if (std::abs(i.space_before()) > dcp::SPACE_BEFORE_EPSILON) {
130                         /* We need to insert some horizontal space into the layout.  The only way I can find to do this
131                          * is to write a " " with some special letter_spacing.  As far as I can see, such a space will
132                          * be written with letter_spacing either side.  This means that to get a horizontal space x we
133                          * need to write a " " with letter spacing (x - s) / 2, where s is the width of the " ".
134                          */
135                         auto layout = create_layout(font_name, make_span(i, " ", {}));
136                         int space_width;
137                         int dummy;
138                         layout->get_pixel_size(space_width, dummy);
139                         auto spacing = ((i.space_before() * i.size_in_pixels(target_height) - space_width) / 2) * pixels_to_1024ths_point;
140                         out += make_span(i, " ", "letter_spacing=\"" + dcp::raw_convert<string>(spacing) + "\"");
141                 }
142
143                 out += make_span(i, i.text(), {});
144         }
145
146         return out;
147 }
148
149
150 static void
151 set_source_rgba (Cairo::RefPtr<Cairo::Context> context, dcp::Colour colour, float fade_factor)
152 {
153         context->set_source_rgba (float(colour.r) / 255, float(colour.g) / 255, float(colour.b) / 255, fade_factor);
154 }
155
156
157 static shared_ptr<Image>
158 create_image (dcp::Size size)
159 {
160         /* FFmpeg BGRA means first byte blue, second byte green, third byte red, fourth byte alpha.
161          * This must be COMPACT as we're using it with Cairo::ImageSurface::create
162          */
163         auto image = make_shared<Image>(AV_PIX_FMT_BGRA, size, Image::Alignment::COMPACT);
164         image->make_black ();
165         return image;
166 }
167
168
169 static Cairo::RefPtr<Cairo::ImageSurface>
170 create_surface (shared_ptr<Image> image)
171 {
172         /* XXX: I don't think it's guaranteed that format_stride_for_width will return a stride without any padding,
173          * so it's lucky that this works.
174          */
175         DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
176         DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_BGRA);
177         return Cairo::ImageSurface::create (
178                 image->data()[0],
179 #ifdef DCPOMATIC_OLD_CAIROMM_API
180                 Cairo::FORMAT_ARGB32,
181 #else
182                 Cairo::ImageSurface::Format::ARGB32,
183 #endif
184                 image->size().width,
185                 image->size().height,
186                 /* Cairo ARGB32 means first byte blue, second byte green, third byte red, fourth byte alpha */
187                 Cairo::ImageSurface::format_stride_for_width(
188 #ifdef DCPOMATIC_OLD_CAIROMM_API
189                         Cairo::FORMAT_ARGB32,
190 #else
191                         Cairo::ImageSurface::Format::ARGB32,
192 #endif
193                         image->size().width
194                         )
195                 );
196 }
197
198
199 static float
200 calculate_fade_factor (StringText const& first, DCPTime time, int frame_rate)
201 {
202         float fade_factor = 1;
203
204         /* Round the fade start/end to the nearest frame start.  Otherwise if a subtitle starts just after
205            the start of a frame it will be faded out.
206         */
207         auto const fade_in_start = DCPTime::from_seconds(first.in().as_seconds()).round(frame_rate);
208         auto const fade_in_end = fade_in_start + DCPTime::from_seconds (first.fade_up_time().as_seconds ());
209
210         if (fade_in_start <= time && time <= fade_in_end && fade_in_start != fade_in_end) {
211                 fade_factor *= DCPTime(time - fade_in_start).seconds() / DCPTime(fade_in_end - fade_in_start).seconds();
212         }
213
214         if (time < fade_in_start) {
215                 fade_factor = 0;
216         }
217
218         /* first.out() may be zero if we don't know when this subtitle will finish.  We can only think about
219          * fading out if we _do_ know when it will finish.
220          */
221         if (first.out() != dcp::Time()) {
222                 auto const fade_out_end = DCPTime::from_seconds (first.out().as_seconds()).round(frame_rate);
223                 auto const fade_out_start = fade_out_end - DCPTime::from_seconds(first.fade_down_time().as_seconds());
224
225                 if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
226                         fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
227                 }
228                 if (time > fade_out_end) {
229                         fade_factor = 0;
230                 }
231         }
232
233         return fade_factor;
234 }
235
236
237 static int
238 x_position(dcp::HAlign align, float position, int target_width, int layout_width)
239 {
240         int x = 0;
241         switch (align) {
242         case dcp::HAlign::LEFT:
243                 /* h_position is distance between left of frame and left of subtitle */
244                 x = position * target_width;
245                 break;
246         case dcp::HAlign::CENTER:
247                 /* h_position is distance between centre of frame and centre of subtitle */
248                 x = (0.5 + position) * target_width - layout_width / 2;
249                 break;
250         case dcp::HAlign::RIGHT:
251                 /* h_position is distance between right of frame and right of subtitle */
252                 x = (1.0 - position) * target_width - layout_width;
253                 break;
254         }
255
256         return x;
257 }
258
259
260 /** @param align_standard Standard with which to interpret this subtitle's position.
261  *  @param align alignment.
262  *  @param position position (between 0 and 1)
263  *  @param target_height Height of the target screen (in pixels).
264  *  @param baseline_to_bottom Distance from text baseline to the bottom of the bounding box (in pixels).
265  *  @param layout_height Height of the subtitle bounding box (in pixels).
266  *  @return y position of the top of the subtitle bounding box (in pixels) from the top of the screen.
267  */
268 static int
269 y_position(dcp::SubtitleStandard standard, dcp::VAlign align, float position, int target_height, int baseline_to_bottom, int layout_height)
270 {
271         int y = 0;
272         switch (standard) {
273         case dcp::SubtitleStandard::INTEROP:
274         case dcp::SubtitleStandard::SMPTE_2014:
275                 switch (align) {
276                 case dcp::VAlign::TOP:
277                         /* position is distance from top of frame to subtitle baseline */
278                         y = position * target_height - (layout_height - baseline_to_bottom);
279                         break;
280                 case dcp::VAlign::CENTER:
281                         /* position is distance from centre of frame to subtitle baseline */
282                         y = (0.5 + position) * target_height - (layout_height - baseline_to_bottom);
283                         break;
284                 case dcp::VAlign::BOTTOM:
285                         /* position is distance from bottom of frame to subtitle baseline */
286                         y = (1.0 - position) * target_height - (layout_height - baseline_to_bottom);
287                         break;
288                 }
289                 break;
290         case dcp::SubtitleStandard::SMPTE_2007:
291         case dcp::SubtitleStandard::SMPTE_2010:
292                 switch (align) {
293                 case dcp::VAlign::TOP:
294                         /* v_position is distance from top of frame to top of subtitle */
295                         y = position * target_height;
296                         break;
297                 case dcp::VAlign::CENTER:
298                         /* v_position is distance from centre of frame to centre of subtitle */
299                         y = (0.5 + position) * target_height - layout_height / 2;
300                         break;
301                 case dcp::VAlign::BOTTOM:
302                         /* v_position is distance from bottom of frame to bottom of subtitle */
303                         y = (1.0 - position) * target_height - layout_height;
304                         break;
305                 }
306         }
307
308         return y;
309 }
310
311
312 struct Layout
313 {
314         Position<int> position;
315         int baseline_position;
316         dcp::Size size;
317         Glib::RefPtr<Pango::Layout> pango;
318
319         int baseline_to_bottom(int border_width)
320         {
321                 return position.y + size.height - baseline_position - border_width;
322         }
323 };
324
325
326 /** @param subtitles A list of subtitles that are all on the same line,
327  *  at the same time and with the same fade in/out.
328  */
329 static Layout
330 setup_layout(vector<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
331 {
332         DCPOMATIC_ASSERT(!subtitles.empty());
333         auto const& first = subtitles.front();
334
335         auto const font_name = FontConfig::instance()->make_font_available(first.font);
336         auto const fade_factor = calculate_fade_factor(first, time, frame_rate);
337         auto const markup = marked_up(subtitles, target.height, fade_factor, font_name);
338         auto layout = create_layout(font_name, markup);
339         auto ink = layout->get_ink_extents();
340
341         Layout description;
342         description.position = { ink.get_x() / Pango::SCALE, ink.get_y() / Pango::SCALE };
343         description.baseline_position = layout->get_baseline() / Pango::SCALE;
344         description.size = { ink.get_width() / Pango::SCALE, ink.get_height() / Pango::SCALE };
345         description.pango = layout;
346
347         return description;
348 }
349
350
351 static
352 int
353 border_width_for_subtitle(StringText const& subtitle, dcp::Size target)
354 {
355         return subtitle.effect() == dcp::Effect::BORDER ? (subtitle.outline_width * target.width / 2048.0) : 0;
356 }
357
358
359 /** @param subtitles A list of subtitles that are all on the same line,
360  *  at the same time and with the same fade in/out.
361  */
362 static PositionImage
363 render_line(vector<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
364 {
365         /* XXX: this method can only handle italic / bold changes mid-line,
366            nothing else yet.
367         */
368
369         DCPOMATIC_ASSERT(!subtitles.empty ());
370         auto const& first = subtitles.front();
371         auto const fade_factor = calculate_fade_factor(first, time, frame_rate);
372
373         auto layout = setup_layout(subtitles, target, time, frame_rate);
374
375         /* Calculate x and y scale factors.  These are only used to stretch
376            the font away from its normal aspect ratio.
377         */
378         float x_scale = 1;
379         float y_scale = 1;
380         if (fabs (first.aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
381                 if (first.aspect_adjust() < 1) {
382                         x_scale = max (0.25f, first.aspect_adjust ());
383                         y_scale = 1;
384                 } else {
385                         x_scale = 1;
386                         y_scale = 1 / min (4.0f, first.aspect_adjust ());
387                 }
388         }
389
390         auto const border_width = border_width_for_subtitle(first, target);
391         layout.size.width += 2 * ceil (border_width);
392         layout.size.height += 2 * ceil (border_width);
393
394         layout.size.width *= x_scale;
395         layout.size.height *= y_scale;
396
397         /* Shuffle the subtitle over by the border width (if we have any) so it's not cut off */
398         int const x_offset = -layout.position.x + ceil(border_width);
399         int const y_offset = -layout.position.y + ceil(border_width);
400
401         auto image = create_image(layout.size);
402         auto surface = create_surface (image);
403         auto context = Cairo::Context::create (surface);
404
405         context->set_line_width (1);
406         context->scale (x_scale, y_scale);
407         layout.pango->update_from_cairo_context(context);
408
409         if (first.effect() == dcp::Effect::SHADOW) {
410                 /* Drop-shadow effect */
411                 set_source_rgba (context, first.effect_colour(), fade_factor);
412                 context->move_to (x_offset + 4, y_offset + 4);
413                 layout.pango->add_to_cairo_context(context);
414                 context->fill ();
415         }
416
417         if (first.effect() == dcp::Effect::BORDER) {
418                 /* Border effect */
419                 set_source_rgba (context, first.effect_colour(), fade_factor);
420                 context->set_line_width (border_width);
421 #ifdef DCPOMATIC_OLD_CAIROMM_API
422                 context->set_line_join (Cairo::LINE_JOIN_ROUND);
423 #else
424                 context->set_line_join (Cairo::Context::LineJoin::ROUND);
425 #endif
426                 context->move_to (x_offset, y_offset);
427                 layout.pango->add_to_cairo_context (context);
428                 context->stroke ();
429         }
430
431         /* The actual subtitle */
432
433         set_source_rgba (context, first.colour(), fade_factor);
434
435         context->move_to (x_offset, y_offset);
436         layout.pango->add_to_cairo_context (context);
437         context->fill ();
438
439         context->set_line_width (0.5);
440         context->move_to (x_offset, y_offset);
441         layout.pango->add_to_cairo_context (context);
442         context->stroke ();
443
444         int const x = x_position(first.h_align(), first.h_position(), target.width, layout.size.width);
445         int const y = y_position(first.valign_standard, first.v_align(), first.v_position(), target.height, layout.baseline_to_bottom(border_width), layout.size.height);
446         return PositionImage (image, Position<int>(max (0, x), max(0, y)));
447 }
448
449
450 /** @param time Time of the frame that these subtitles are going on.
451  *  @param target Size of the container that this subtitle will end up in.
452  *  @param frame_rate DCP frame rate.
453  */
454 vector<PositionImage>
455 render_text(vector<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
456 {
457         vector<StringText> pending;
458         vector<PositionImage> images;
459
460         for (auto const& i: subtitles) {
461                 if (!pending.empty()) {
462                         auto const last = pending.back();
463                         auto const different_v = i.v_align() != last.v_align() || fabs(i.v_position() - last.v_position()) > 1e-4;
464                         auto const different_h = i.h_align() != last.h_align() || fabs(i.h_position() - pending.back().h_position()) > 1e-4;
465                         if (different_v || different_h) {
466                                 /* We need a new line if any new positioning (horizontal or vertical) changes for this section */
467                                 images.push_back(render_line(pending, target, time, frame_rate));
468                                 pending.clear ();
469                         }
470                 }
471                 pending.push_back (i);
472         }
473
474         if (!pending.empty()) {
475                 images.push_back(render_line(pending, target, time, frame_rate));
476         }
477
478         return images;
479 }
480
481
482 vector<dcpomatic::Rect<int>>
483 bounding_box(vector<StringText> subtitles, dcp::Size target, optional<dcp::SubtitleStandard> override_standard)
484 {
485         vector<StringText> pending;
486         vector<dcpomatic::Rect<int>> rects;
487
488         auto use_pending = [&pending, &rects, target, override_standard]() {
489                 auto const& subtitle = pending.front();
490                 auto standard = override_standard.get_value_or(subtitle.valign_standard);
491                 /* We can provide dummy values for time and frame rate here as they are only used to calculate fades */
492                 auto layout = setup_layout(pending, target, DCPTime(), 24);
493                 int const x = x_position(subtitle.h_align(), subtitle.h_position(), target.width, layout.size.width);
494                 auto const border_width = border_width_for_subtitle(subtitle, target);
495                 int const y = y_position(standard, subtitle.v_align(), subtitle.v_position(), target.height, layout.baseline_to_bottom(border_width), layout.size.height);
496                 rects.push_back({Position<int>(x, y), layout.size.width, layout.size.height});
497         };
498
499         for (auto const& i: subtitles) {
500                 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
501                         use_pending();
502                         pending.clear();
503                 }
504                 pending.push_back(i);
505         }
506
507         if (!pending.empty()) {
508                 use_pending();
509         }
510
511         return rects;
512 }
513
514
515 float
516 FontMetrics::height(StringText const& subtitle)
517 {
518         return get(subtitle)->second.second;
519 }
520
521
522 float
523 FontMetrics::baseline_to_bottom(StringText const& subtitle)
524 {
525         return get(subtitle)->second.first;
526 }
527
528
529 FontMetrics::Cache::iterator
530 FontMetrics::get(StringText const& subtitle)
531 {
532         auto id = Identifier(subtitle);
533
534         auto iter = _cache.find(id);
535         if (iter != _cache.end()) {
536                 return iter;
537         }
538
539         auto const font_name = FontConfig::instance()->make_font_available(subtitle.font);
540         auto copy = subtitle;
541         copy.set_text("Qypjg");
542         auto layout = create_layout(font_name, marked_up({copy}, _target_height, 1, font_name));
543         auto ink = layout->get_ink_extents();
544         auto const scale = float(_target_height * Pango::SCALE);
545         return _cache.insert({id, { ink.get_y() / scale, ink.get_height() / scale}}).first;
546 }
547
548
549 FontMetrics::Identifier::Identifier(StringText const& subtitle)
550         : font(subtitle.font)
551         , size(subtitle.size())
552         , aspect_adjust(subtitle.aspect_adjust())
553 {
554
555 }
556
557
558 bool
559 FontMetrics::Identifier::operator<(FontMetrics::Identifier const& other) const
560 {
561         if (font != other.font) {
562                 return font < other.font;
563         }
564
565         if (size != other.size) {
566                 return size < other.size;
567         }
568
569         return aspect_adjust < other.aspect_adjust;
570 }
571