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