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