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