Supporters update.
[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 "types.h"
29 #include "util.h"
30 #include <dcp/raw_convert.h>
31 #include <dcp/warnings.h>
32 #include <cairomm/cairomm.h>
33 LIBDCP_DISABLE_WARNINGS
34 #include <pangomm.h>
35 LIBDCP_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 /** 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()
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         return Pango::Layout::create (context);
68 }
69
70
71 static void
72 setup_layout (Glib::RefPtr<Pango::Layout> layout, string font_name, string markup)
73 {
74         layout->set_alignment (Pango::ALIGN_LEFT);
75         Pango::FontDescription font (font_name);
76         layout->set_font_description (font);
77         layout->set_markup (markup);
78 }
79
80
81 string
82 marked_up (list<StringText> subtitles, int target_height, float fade_factor, string font_name)
83 {
84         auto constexpr pixels_to_1024ths_point = 72 * 1024 / 96;
85
86         auto make_span = [target_height, fade_factor](StringText const& subtitle, string text, string extra_attribute) {
87                 string span;
88                 span += "<span ";
89                 if (subtitle.italic()) {
90                         span += "style=\"italic\" ";
91                 }
92                 if (subtitle.bold()) {
93                         span += "weight=\"bold\" ";
94                 }
95                 if (subtitle.underline()) {
96                         span += "underline=\"single\" ";
97                 }
98                 span += "size=\"" + dcp::raw_convert<string>(lrintf(subtitle.size_in_pixels(target_height) * pixels_to_1024ths_point)) + "\" ";
99                 /* Between 1-65535 inclusive, apparently... */
100                 span += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
101                 span += "color=\"#" + subtitle.colour().to_rgb_string() + "\"";
102                 if (!extra_attribute.empty()) {
103                         span += " " + extra_attribute;
104                 }
105                 span += ">";
106                 span += text;
107                 span += "</span>";
108                 return span;
109         };
110
111         string out;
112         for (auto const& i: subtitles) {
113                 if (std::abs(i.space_before()) > dcp::SPACE_BEFORE_EPSILON) {
114                         /* We need to insert some horizontal space into the layout.  The only way I can find to do this
115                          * is to write a " " with some special letter_spacing.  As far as I can see, such a space will
116                          * be written with letter_spacing either side.  This means that to get a horizontal space x we
117                          * need to write a " " with letter spacing (x - s) / 2, where s is the width of the " ".
118                          */
119                         auto layout = create_layout();
120                         setup_layout(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 (StringText const& subtitle)
175 {
176         auto font_file = default_font_file ();
177
178         if (subtitle.font && subtitle.font->file()) {
179                 font_file = *subtitle.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 (StringText const& first, int target_width, int layout_width)
226 {
227         int x = 0;
228         switch (first.h_align()) {
229         case dcp::HAlign::LEFT:
230                 /* h_position is distance between left of frame and left of subtitle */
231                 x = first.h_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 + first.h_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 - first.h_position()) * target_width - layout_width;
240                 break;
241         }
242
243         return x;
244 }
245
246
247 static int
248 y_position (StringText const& first, int target_height, int baseline_to_bottom, int layout_height)
249 {
250         int y = 0;
251         switch (first.valign_standard) {
252         case dcp::Standard::INTEROP:
253                 switch (first.v_align()) {
254                 case dcp::VAlign::TOP:
255                         /* v_position is distance from top of frame to subtitle baseline */
256                         y = first.v_position() * target_height - (layout_height - baseline_to_bottom);
257                         break;
258                 case dcp::VAlign::CENTER:
259                         /* v_position is distance from centre of frame to subtitle baseline */
260                         y = (0.5 + first.v_position()) * target_height - (layout_height - baseline_to_bottom);
261                         break;
262                 case dcp::VAlign::BOTTOM:
263                         /* v_position is distance from bottom of frame to subtitle baseline */
264                         y = (1.0 - first.v_position()) * target_height - (layout_height - baseline_to_bottom);
265                         break;
266                 }
267                 break;
268         case dcp::Standard::SMPTE:
269                 switch (first.v_align()) {
270                 case dcp::VAlign::TOP:
271                         /* v_position is distance from top of frame to top of subtitle */
272                         y = first.v_position() * target_height;
273                         break;
274                 case dcp::VAlign::CENTER:
275                         /* v_position is distance from centre of frame to centre of subtitle */
276                         y = (0.5 + first.v_position()) * target_height - layout_height / 2;
277                         break;
278                 case dcp::VAlign::BOTTOM:
279                         /* v_position is distance from bottom of frame to bottom of subtitle */
280                         y = (1.0 - first.v_position()) * target_height - layout_height;
281                         break;
282                 }
283         }
284
285         return y;
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, 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);
303         auto const fade_factor = calculate_fade_factor (first, time, frame_rate);
304         auto const markup = marked_up (subtitles, target.height, fade_factor, font_name);
305         auto layout = create_layout ();
306         setup_layout (layout, font_name, markup);
307         auto ink = layout->get_ink_extents();
308         dcp::Size size{ink.get_width() / Pango::SCALE, ink.get_height() / Pango::SCALE};
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 = (-ink.get_x() / Pango::SCALE) + ceil(border_width);
334         int const y_offset = -ink.get_y() / Pango::SCALE + ceil(border_width);
335
336         auto image = create_image (size);
337         auto surface = create_surface (image);
338         auto context = Cairo::Context::create (surface);
339
340         context->set_line_width (1);
341         context->scale (x_scale, y_scale);
342         layout->update_from_cairo_context (context);
343
344         if (first.effect() == dcp::Effect::SHADOW) {
345                 /* Drop-shadow effect */
346                 set_source_rgba (context, first.effect_colour(), fade_factor);
347                 context->move_to (x_offset + 4, y_offset + 4);
348                 layout->add_to_cairo_context (context);
349                 context->fill ();
350         }
351
352         if (first.effect() == dcp::Effect::BORDER) {
353                 /* Border effect */
354                 set_source_rgba (context, first.effect_colour(), fade_factor);
355                 context->set_line_width (border_width);
356                 context->set_line_join (Cairo::LINE_JOIN_ROUND);
357                 context->move_to (x_offset, y_offset);
358                 layout->add_to_cairo_context (context);
359                 context->stroke ();
360         }
361
362         /* The actual subtitle */
363
364         set_source_rgba (context, first.colour(), fade_factor);
365
366         context->move_to (x_offset, y_offset);
367         layout->add_to_cairo_context (context);
368         context->fill ();
369
370         context->set_line_width (0.5);
371         context->move_to (x_offset, y_offset);
372         layout->add_to_cairo_context (context);
373         context->stroke ();
374
375         int const x = x_position (first, target.width, size.width);
376         int const y = y_position (first, target.height, ink.get_y() / Pango::SCALE, size.height);
377         return PositionImage (image, Position<int>(max (0, x), max(0, y)));
378 }
379
380
381 /** @param time Time of the frame that these subtitles are going on.
382  *  @param target Size of the container that this subtitle will end up in.
383  *  @param frame_rate DCP frame rate.
384  */
385 list<PositionImage>
386 render_text (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
387 {
388         list<StringText> pending;
389         list<PositionImage> images;
390
391         for (auto const& i: subtitles) {
392                 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
393                         images.push_back(render_line(pending, target, time, frame_rate));
394                         pending.clear ();
395                 }
396                 pending.push_back (i);
397         }
398
399         if (!pending.empty()) {
400                 images.push_back(render_line(pending, target, time, frame_rate));
401         }
402
403         return images;
404 }