Fix the build for older macOS.
[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 "image.h"
26 #include "render_text.h"
27 #include "types.h"
28 #include "util.h"
29 #include "warnings.h"
30 #include <dcp/raw_convert.h>
31 #include <fontconfig/fontconfig.h>
32 #include <cairomm/cairomm.h>
33 DCPOMATIC_DISABLE_WARNINGS
34 #include <pangomm.h>
35 DCPOMATIC_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::list;
44 using std::make_pair;
45 using std::make_shared;
46 using std::max;
47 using std::min;
48 using std::pair;
49 using std::shared_ptr;
50 using std::string;
51 using namespace dcpomatic;
52
53
54 static FcConfig* fc_config = nullptr;
55 static list<pair<boost::filesystem::path, string>> fc_config_fonts;
56
57
58 /** Create a Pango layout using a dummy context which we can use to calculate the size
59  *  of the text we will render.  Then we can transfer the layout over to the real context
60  *  for the actual render.
61  */
62 static Glib::RefPtr<Pango::Layout>
63 create_layout()
64 {
65         auto c_font_map = pango_cairo_font_map_new ();
66         DCPOMATIC_ASSERT (c_font_map);
67         auto font_map = Glib::wrap (c_font_map);
68         auto c_context = pango_font_map_create_context (c_font_map);
69         DCPOMATIC_ASSERT (c_context);
70         auto context = Glib::wrap (c_context);
71         return Pango::Layout::create (context);
72 }
73
74
75 static void
76 setup_layout (Glib::RefPtr<Pango::Layout> layout, string font_name, string markup)
77 {
78         layout->set_alignment (Pango::ALIGN_LEFT);
79         Pango::FontDescription font (font_name);
80         layout->set_font_description (font);
81         layout->set_markup (markup);
82 }
83
84
85 string
86 marked_up (list<StringText> subtitles, int target_height, float fade_factor, string font_name)
87 {
88         auto constexpr pixels_to_1024ths_point = 72 * 1024 / 96;
89
90         auto make_span = [target_height, fade_factor](StringText const& subtitle, string text, string extra_attribute) {
91                 string span;
92                 span += "<span ";
93                 if (subtitle.italic()) {
94                         span += "style=\"italic\" ";
95                 }
96                 if (subtitle.bold()) {
97                         span += "weight=\"bold\" ";
98                 }
99                 if (subtitle.underline()) {
100                         span += "underline=\"single\" ";
101                 }
102                 span += "size=\"" + dcp::raw_convert<string>(subtitle.size_in_pixels(target_height) * pixels_to_1024ths_point) + "\" ";
103                 /* Between 1-65535 inclusive, apparently... */
104                 span += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
105                 span += "color=\"#" + subtitle.colour().to_rgb_string() + "\"";
106                 if (!extra_attribute.empty()) {
107                         span += " " + extra_attribute;
108                 }
109                 span += ">";
110                 span += text;
111                 span += "</span>";
112                 return span;
113         };
114
115         string out;
116         for (auto const& i: subtitles) {
117                 if (std::abs(i.space_before()) > dcp::SPACE_BEFORE_EPSILON) {
118                         /* We need to insert some horizontal space into the layout.  The only way I can find to do this
119                          * is to write a " " with some special letter_spacing.  As far as I can see, such a space will
120                          * be written with letter_spacing either side.  This means that to get a horizontal space x we
121                          * need to write a " " with letter spacing (x - s) / 2, where s is the width of the " ".
122                          */
123                         auto layout = create_layout();
124                         setup_layout(layout, font_name, make_span(i, " ", {}));
125                         int space_width;
126                         int dummy;
127                         layout->get_pixel_size(space_width, dummy);
128                         auto spacing = ((i.space_before() * i.size_in_pixels(target_height) - space_width) / 2) * pixels_to_1024ths_point;
129                         out += make_span(i, " ", "letter_spacing=\"" + dcp::raw_convert<string>(spacing) + "\"");
130                 }
131
132                 out += make_span(i, i.text(), {});
133         }
134
135         return out;
136 }
137
138
139 static void
140 set_source_rgba (Cairo::RefPtr<Cairo::Context> context, dcp::Colour colour, float fade_factor)
141 {
142         context->set_source_rgba (float(colour.r) / 255, float(colour.g) / 255, float(colour.b) / 255, fade_factor);
143 }
144
145
146 static shared_ptr<Image>
147 create_image (dcp::Size size)
148 {
149         /* FFmpeg BGRA means first byte blue, second byte green, third byte red, fourth byte alpha.
150          * This must be COMPACT as we're using it with Cairo::ImageSurface::create
151          */
152         auto image = make_shared<Image>(AV_PIX_FMT_BGRA, size, Image::Alignment::COMPACT);
153         image->make_black ();
154         return image;
155 }
156
157
158 static Cairo::RefPtr<Cairo::ImageSurface>
159 create_surface (shared_ptr<Image> image)
160 {
161         /* XXX: I don't think it's guaranteed that format_stride_for_width will return a stride without any padding,
162          * so it's lucky that this works.
163          */
164         DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
165         DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_BGRA);
166         return Cairo::ImageSurface::create (
167                 image->data()[0],
168                 Cairo::FORMAT_ARGB32,
169                 image->size().width,
170                 image->size().height,
171                 /* Cairo ARGB32 means first byte blue, second byte green, third byte red, fourth byte alpha */
172                 Cairo::ImageSurface::format_stride_for_width (Cairo::FORMAT_ARGB32, image->size().width)
173                 );
174 }
175
176
177 static string
178 setup_font (StringText const& subtitle, list<shared_ptr<Font>> const& fonts)
179 {
180         if (!fc_config) {
181                 fc_config = FcInitLoadConfig ();
182         }
183
184         auto font_file = default_font_file ();
185
186         for (auto i: fonts) {
187                 if (i->id() == subtitle.font() && i->file()) {
188                         font_file = i->file().get();
189                 }
190         }
191
192         auto existing = fc_config_fonts.cbegin ();
193         while (existing != fc_config_fonts.end() && existing->first != font_file) {
194                 ++existing;
195         }
196
197         string font_name;
198         if (existing != fc_config_fonts.end ()) {
199                 font_name = existing->second;
200         } else {
201                 /* Make this font available to DCP-o-matic */
202                 FcConfigAppFontAddFile (fc_config, reinterpret_cast<FcChar8 const *>(font_file.string().c_str()));
203                 auto pattern = FcPatternBuild (
204                         0, FC_FILE, FcTypeString, font_file.string().c_str(), static_cast<char *>(0)
205                         );
206                 auto object_set = FcObjectSetBuild (FC_FAMILY, FC_STYLE, FC_LANG, FC_FILE, static_cast<char *> (0));
207                 auto font_set = FcFontList (fc_config, pattern, object_set);
208                 if (font_set) {
209                         for (int i = 0; i < font_set->nfont; ++i) {
210                                 FcPattern* font = font_set->fonts[i];
211                                 FcChar8* file;
212                                 FcChar8* family;
213                                 FcChar8* style;
214                                 if (
215                                         FcPatternGetString (font, FC_FILE, 0, &file) == FcResultMatch &&
216                                         FcPatternGetString (font, FC_FAMILY, 0, &family) == FcResultMatch &&
217                                         FcPatternGetString (font, FC_STYLE, 0, &style) == FcResultMatch
218                                         ) {
219                                         font_name = reinterpret_cast<char const *> (family);
220                                 }
221                         }
222
223                         FcFontSetDestroy (font_set);
224                 }
225
226                 FcObjectSetDestroy (object_set);
227                 FcPatternDestroy (pattern);
228
229                 fc_config_fonts.push_back (make_pair(font_file, font_name));
230         }
231
232         FcConfigSetCurrent (fc_config);
233         return font_name;
234 }
235
236
237 static float
238 calculate_fade_factor (StringText const& first, DCPTime time, int frame_rate)
239 {
240         float fade_factor = 1;
241
242         /* Round the fade start/end to the nearest frame start.  Otherwise if a subtitle starts just after
243            the start of a frame it will be faded out.
244         */
245         auto const fade_in_start = DCPTime::from_seconds(first.in().as_seconds()).round(frame_rate);
246         auto const fade_in_end = fade_in_start + DCPTime::from_seconds (first.fade_up_time().as_seconds ());
247
248         if (fade_in_start <= time && time <= fade_in_end && fade_in_start != fade_in_end) {
249                 fade_factor *= DCPTime(time - fade_in_start).seconds() / DCPTime(fade_in_end - fade_in_start).seconds();
250         }
251
252         if (time < fade_in_start) {
253                 fade_factor = 0;
254         }
255
256         /* first.out() may be zero if we don't know when this subtitle will finish.  We can only think about
257          * fading out if we _do_ know when it will finish.
258          */
259         if (first.out() != dcp::Time()) {
260                 auto const fade_out_end = DCPTime::from_seconds (first.out().as_seconds()).round(frame_rate);
261                 auto const fade_out_start = fade_out_end - DCPTime::from_seconds(first.fade_down_time().as_seconds());
262
263                 if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
264                         fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
265                 }
266                 if (time > fade_out_end) {
267                         fade_factor = 0;
268                 }
269         }
270
271         return fade_factor;
272 }
273
274
275 static int
276 x_position (StringText const& first, int target_width, int layout_width)
277 {
278         int x = 0;
279         switch (first.h_align()) {
280         case dcp::HAlign::LEFT:
281                 /* h_position is distance between left of frame and left of subtitle */
282                 x = first.h_position() * target_width;
283                 break;
284         case dcp::HAlign::CENTER:
285                 /* h_position is distance between centre of frame and centre of subtitle */
286                 x = (0.5 + first.h_position()) * target_width - layout_width / 2;
287                 break;
288         case dcp::HAlign::RIGHT:
289                 /* h_position is distance between right of frame and right of subtitle */
290                 x = (1.0 - first.h_position()) * target_width - layout_width;
291                 break;
292         }
293
294         return x;
295 }
296
297
298 static int
299 y_position (StringText const& first, int target_height, int layout_height)
300 {
301         int y = 0;
302         switch (first.v_align()) {
303         case dcp::VAlign::TOP:
304                 /* SMPTE says that v_position is the distance between top
305                    of frame and top of subtitle, but this doesn't always seem to be
306                    the case in practice; Gunnar Ásgeirsson's Dolby server appears
307                    to put VAlign::TOP subs with v_position as the distance between top
308                    of frame and bottom of subtitle.
309                 */
310                 y = first.v_position() * target_height - layout_height;
311                 break;
312         case dcp::VAlign::CENTER:
313                 /* v_position is distance between centre of frame and centre of subtitle */
314                 y = (0.5 + first.v_position()) * target_height - layout_height / 2;
315                 break;
316         case dcp::VAlign::BOTTOM:
317                 /* v_position is distance between bottom of frame and bottom of subtitle */
318                 y = (1.0 - first.v_position()) * target_height - layout_height;
319                 break;
320         }
321
322         return y;
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, list<shared_ptr<Font>> fonts, 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
339         auto const font_name = setup_font (first, fonts);
340         auto const fade_factor = calculate_fade_factor (first, time, frame_rate);
341         auto const markup = marked_up (subtitles, target.height, fade_factor, font_name);
342         auto layout = create_layout ();
343         setup_layout (layout, font_name, markup);
344         dcp::Size size;
345         layout->get_pixel_size (size.width, size.height);
346
347         /* Calculate x and y scale factors.  These are only used to stretch
348            the font away from its normal aspect ratio.
349         */
350         float x_scale = 1;
351         float y_scale = 1;
352         if (fabs (first.aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
353                 if (first.aspect_adjust() < 1) {
354                         x_scale = max (0.25f, first.aspect_adjust ());
355                         y_scale = 1;
356                 } else {
357                         x_scale = 1;
358                         y_scale = 1 / min (4.0f, first.aspect_adjust ());
359                 }
360         }
361
362         auto const border_width = first.effect() == dcp::Effect::BORDER ? (first.outline_width * target.width / 2048.0) : 0;
363         size.width += 2 * ceil (border_width);
364         size.height += 2 * ceil (border_width);
365
366         size.width *= x_scale;
367         size.height *= y_scale;
368
369         /* Shuffle the subtitle over by the border width (if we have any) so it's not cut off */
370         int const x_offset = ceil (border_width);
371         /* Move down a bit so that accents on capital letters can be seen */
372         int const y_offset = target.height / 100.0;
373
374         size.width += x_offset;
375         size.height += y_offset;
376
377         auto image = create_image (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->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->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->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->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->add_to_cairo_context (context);
414         context->stroke ();
415
416         int const x = x_position (first, target.width, size.width);
417         int const y = y_position (first, target.height, 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 list<PositionImage>
427 render_text (list<StringText> subtitles, list<shared_ptr<Font>> fonts, dcp::Size target, DCPTime time, int frame_rate)
428 {
429         list<StringText> pending;
430         list<PositionImage> images;
431
432         for (auto const& i: subtitles) {
433                 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
434                         images.push_back (render_line (pending, fonts, target, time, frame_rate));
435                         pending.clear ();
436                 }
437                 pending.push_back (i);
438         }
439
440         if (!pending.empty()) {
441                 images.push_back (render_line (pending, fonts, target, time, frame_rate));
442         }
443
444         return images;
445 }