94b41285627270868d97a95792659445cae102ce
[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 string
59 marked_up (list<StringText> subtitles, int target_height, float fade_factor)
60 {
61         string out;
62
63         for (auto const& i: subtitles) {
64                 out += "<span ";
65                 if (i.italic()) {
66                         out += "style=\"italic\" ";
67                 }
68                 if (i.bold()) {
69                         out += "weight=\"bold\" ";
70                 }
71                 if (i.underline()) {
72                         out += "underline=\"single\" ";
73                 }
74                 out += "size=\"" + dcp::raw_convert<string>(i.size_in_pixels(target_height) * 72 * 1024 / 96) + "\" ";
75                 /* Between 1-65535 inclusive, apparently... */
76                 out += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
77                 out += "color=\"#" + i.colour().to_rgb_string() + "\">";
78                 out += i.text();
79                 out += "</span>";
80         }
81
82         return out;
83 }
84
85
86 static void
87 set_source_rgba (Cairo::RefPtr<Cairo::Context> context, dcp::Colour colour, float fade_factor)
88 {
89         context->set_source_rgba (float(colour.r) / 255, float(colour.g) / 255, float(colour.b) / 255, fade_factor);
90 }
91
92
93 static shared_ptr<Image>
94 create_image (dcp::Size size)
95 {
96         /* FFmpeg BGRA means first byte blue, second byte green, third byte red, fourth byte alpha.
97          * This must be COMPACT as we're using it with Cairo::ImageSurface::create
98          */
99         auto image = make_shared<Image>(AV_PIX_FMT_BGRA, size, Image::Alignment::COMPACT);
100         image->make_black ();
101         return image;
102 }
103
104
105 static Cairo::RefPtr<Cairo::ImageSurface>
106 create_surface (shared_ptr<Image> image)
107 {
108         /* XXX: I don't think it's guaranteed that format_stride_for_width will return a stride without any padding,
109          * so it's lucky that this works.
110          */
111         DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
112         DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_BGRA);
113         return Cairo::ImageSurface::create (
114                 image->data()[0],
115                 Cairo::FORMAT_ARGB32,
116                 image->size().width,
117                 image->size().height,
118                 /* Cairo ARGB32 means first byte blue, second byte green, third byte red, fourth byte alpha */
119                 Cairo::ImageSurface::format_stride_for_width (Cairo::FORMAT_ARGB32, image->size().width)
120                 );
121 }
122
123
124 static string
125 setup_font (StringText const& subtitle, list<shared_ptr<Font>> const& fonts)
126 {
127         if (!fc_config) {
128                 fc_config = FcInitLoadConfig ();
129         }
130
131         auto font_file = default_font_file ();
132
133         for (auto i: fonts) {
134                 if (i->id() == subtitle.font() && i->file()) {
135                         font_file = i->file().get();
136                 }
137         }
138
139         auto existing = fc_config_fonts.cbegin ();
140         while (existing != fc_config_fonts.end() && existing->first != font_file) {
141                 ++existing;
142         }
143
144         string font_name;
145         if (existing != fc_config_fonts.end ()) {
146                 font_name = existing->second;
147         } else {
148                 /* Make this font available to DCP-o-matic */
149                 FcConfigAppFontAddFile (fc_config, reinterpret_cast<FcChar8 const *>(font_file.string().c_str()));
150                 auto pattern = FcPatternBuild (
151                         0, FC_FILE, FcTypeString, font_file.string().c_str(), static_cast<char *>(0)
152                         );
153                 auto object_set = FcObjectSetBuild (FC_FAMILY, FC_STYLE, FC_LANG, FC_FILE, static_cast<char *> (0));
154                 auto font_set = FcFontList (fc_config, pattern, object_set);
155                 if (font_set) {
156                         for (int i = 0; i < font_set->nfont; ++i) {
157                                 FcPattern* font = font_set->fonts[i];
158                                 FcChar8* file;
159                                 FcChar8* family;
160                                 FcChar8* style;
161                                 if (
162                                         FcPatternGetString (font, FC_FILE, 0, &file) == FcResultMatch &&
163                                         FcPatternGetString (font, FC_FAMILY, 0, &family) == FcResultMatch &&
164                                         FcPatternGetString (font, FC_STYLE, 0, &style) == FcResultMatch
165                                         ) {
166                                         font_name = reinterpret_cast<char const *> (family);
167                                 }
168                         }
169
170                         FcFontSetDestroy (font_set);
171                 }
172
173                 FcObjectSetDestroy (object_set);
174                 FcPatternDestroy (pattern);
175
176                 fc_config_fonts.push_back (make_pair(font_file, font_name));
177         }
178
179         FcConfigSetCurrent (fc_config);
180         return font_name;
181 }
182
183
184 static float
185 calculate_fade_factor (StringText const& first, DCPTime time, int frame_rate)
186 {
187         float fade_factor = 1;
188
189         /* Round the fade start/end to the nearest frame start.  Otherwise if a subtitle starts just after
190            the start of a frame it will be faded out.
191         */
192         auto const fade_in_start = DCPTime::from_seconds(first.in().as_seconds()).round(frame_rate);
193         auto const fade_in_end = fade_in_start + DCPTime::from_seconds (first.fade_up_time().as_seconds ());
194         auto const fade_out_end =  DCPTime::from_seconds (first.out().as_seconds()).round(frame_rate);
195         auto const fade_out_start = fade_out_end - DCPTime::from_seconds (first.fade_down_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         if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
201                 fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
202         }
203         if (time < fade_in_start || time > fade_out_end) {
204                 fade_factor = 0;
205         }
206
207         return fade_factor;
208 }
209
210
211 static int
212 x_position (StringText const& first, int target_width, int layout_width)
213 {
214         int x = 0;
215         switch (first.h_align()) {
216         case dcp::HAlign::LEFT:
217                 /* h_position is distance between left of frame and left of subtitle */
218                 x = first.h_position() * target_width;
219                 break;
220         case dcp::HAlign::CENTER:
221                 /* h_position is distance between centre of frame and centre of subtitle */
222                 x = (0.5 + first.h_position()) * target_width - layout_width / 2;
223                 break;
224         case dcp::HAlign::RIGHT:
225                 /* h_position is distance between right of frame and right of subtitle */
226                 x = (1.0 - first.h_position()) * target_width - layout_width;
227                 break;
228         }
229
230         return x;
231 }
232
233
234 static int
235 y_position (StringText const& first, int target_height, int layout_height)
236 {
237         int y = 0;
238         switch (first.v_align()) {
239         case dcp::VAlign::TOP:
240                 /* SMPTE says that v_position is the distance between top
241                    of frame and top of subtitle, but this doesn't always seem to be
242                    the case in practice; Gunnar Ásgeirsson's Dolby server appears
243                    to put VAlign::TOP subs with v_position as the distance between top
244                    of frame and bottom of subtitle.
245                 */
246                 y = first.v_position() * target_height - layout_height;
247                 break;
248         case dcp::VAlign::CENTER:
249                 /* v_position is distance between centre of frame and centre of subtitle */
250                 y = (0.5 + first.v_position()) * target_height - layout_height / 2;
251                 break;
252         case dcp::VAlign::BOTTOM:
253                 /* v_position is distance between bottom of frame and bottom of subtitle */
254                 y = (1.0 - first.v_position()) * target_height - layout_height;
255                 break;
256         }
257
258         return y;
259 }
260
261
262 static void
263 setup_layout (Glib::RefPtr<Pango::Layout> layout, string font_name, string markup)
264 {
265         layout->set_alignment (Pango::ALIGN_LEFT);
266         Pango::FontDescription font (font_name);
267         layout->set_font_description (font);
268         layout->set_markup (markup);
269 }
270
271
272 /** Create a Pango layout using a dummy context which we can use to calculate the size
273  *  of the text we will render.  Then we can transfer the layout over to the real context
274  *  for the actual render.
275  */
276 static Glib::RefPtr<Pango::Layout>
277 create_layout()
278 {
279         auto c_font_map = pango_cairo_font_map_new ();
280         DCPOMATIC_ASSERT (c_font_map);
281         auto font_map = Glib::wrap (c_font_map);
282         auto c_context = pango_font_map_create_context (c_font_map);
283         DCPOMATIC_ASSERT (c_context);
284         auto context = Glib::wrap (c_context);
285         return Pango::Layout::create (context);
286 }
287
288
289 /** @param subtitles A list of subtitles that are all on the same line,
290  *  at the same time and with the same fade in/out.
291  */
292 static PositionImage
293 render_line (list<StringText> subtitles, list<shared_ptr<Font>> fonts, dcp::Size target, DCPTime time, int frame_rate)
294 {
295         /* XXX: this method can only handle italic / bold changes mid-line,
296            nothing else yet.
297         */
298
299         DCPOMATIC_ASSERT (!subtitles.empty ());
300         auto const& first = subtitles.front ();
301
302         auto const font_name = setup_font (first, fonts);
303         auto const fade_factor = calculate_fade_factor (first, time, frame_rate);
304         auto const markup = marked_up (subtitles, target.height, fade_factor);
305         auto layout = create_layout ();
306         setup_layout (layout, font_name, markup);
307         dcp::Size size;
308         layout->get_pixel_size (size.width, size.height);
309
310         /* Calculate x and y scale factors.  These are only used to stretch
311            the font away from its normal aspect ratio.
312         */
313         float x_scale = 1;
314         float y_scale = 1;
315         if (fabs (first.aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
316                 if (first.aspect_adjust() < 1) {
317                         x_scale = max (0.25f, first.aspect_adjust ());
318                         y_scale = 1;
319                 } else {
320                         x_scale = 1;
321                         y_scale = 1 / min (4.0f, first.aspect_adjust ());
322                 }
323         }
324
325         auto const border_width = first.effect() == dcp::Effect::BORDER ? (first.outline_width * target.width / 2048.0) : 0;
326         size.width += 2 * ceil (border_width);
327         size.height += 2 * ceil (border_width);
328
329         size.width *= x_scale;
330         size.height *= y_scale;
331
332         /* Shuffle the subtitle over by the border width (if we have any) so it's not cut off */
333         int const x_offset = ceil (border_width);
334         /* Move down a bit so that accents on capital letters can be seen */
335         int const y_offset = target.height / 100.0;
336
337         size.width += x_offset;
338         size.height += y_offset;
339
340         auto image = create_image (size);
341         auto surface = create_surface (image);
342         auto context = Cairo::Context::create (surface);
343
344         context->set_line_width (1);
345         context->scale (x_scale, y_scale);
346         layout->update_from_cairo_context (context);
347
348         if (first.effect() == dcp::Effect::SHADOW) {
349                 /* Drop-shadow effect */
350                 set_source_rgba (context, first.effect_colour(), fade_factor);
351                 context->move_to (x_offset + 4, y_offset + 4);
352                 layout->add_to_cairo_context (context);
353                 context->fill ();
354         }
355
356         if (first.effect() == dcp::Effect::BORDER) {
357                 /* Border effect */
358                 set_source_rgba (context, first.effect_colour(), fade_factor);
359                 context->set_line_width (border_width);
360                 context->set_line_join (Cairo::LINE_JOIN_ROUND);
361                 context->move_to (x_offset, y_offset);
362                 layout->add_to_cairo_context (context);
363                 context->stroke ();
364         }
365
366         /* The actual subtitle */
367
368         set_source_rgba (context, first.colour(), fade_factor);
369
370         context->move_to (x_offset, y_offset);
371         layout->add_to_cairo_context (context);
372         context->fill ();
373
374         context->set_line_width (0.5);
375         context->move_to (x_offset, y_offset);
376         layout->add_to_cairo_context (context);
377         context->stroke ();
378
379         int const x = x_position (first, target.width, size.width);
380         int const y = y_position (first, target.height, size.height);
381         return PositionImage (image, Position<int>(max (0, x), max(0, y)));
382 }
383
384
385 /** @param time Time of the frame that these subtitles are going on.
386  *  @param target Size of the container that this subtitle will end up in.
387  *  @param frame_rate DCP frame rate.
388  */
389 list<PositionImage>
390 render_text (list<StringText> subtitles, list<shared_ptr<Font>> fonts, dcp::Size target, DCPTime time, int frame_rate)
391 {
392         list<StringText> pending;
393         list<PositionImage> images;
394
395         for (auto const& i: subtitles) {
396                 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
397                         images.push_back (render_line (pending, fonts, target, time, frame_rate));
398                         pending.clear ();
399                 }
400                 pending.push_back (i);
401         }
402
403         if (!pending.empty()) {
404                 images.push_back (render_line (pending, fonts, target, time, frame_rate));
405         }
406
407         return images;
408 }