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