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