Support the 2014 version of SMPTE 428-7 in render_text.cc and use it
[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()
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         return Pango::Layout::create (context);
67 }
68
69
70 static void
71 setup_layout (Glib::RefPtr<Pango::Layout> layout, string font_name, string markup)
72 {
73         layout->set_alignment (Pango::ALIGN_LEFT);
74         Pango::FontDescription font (font_name);
75         layout->set_font_description (font);
76         layout->set_markup (markup);
77 }
78
79
80 string
81 marked_up (list<StringText> subtitles, int target_height, float fade_factor, string font_name)
82 {
83         auto constexpr pixels_to_1024ths_point = 72 * 1024 / 96;
84
85         auto make_span = [target_height, fade_factor](StringText const& subtitle, string text, string extra_attribute) {
86                 string span;
87                 span += "<span ";
88                 if (subtitle.italic()) {
89                         span += "style=\"italic\" ";
90                 }
91                 if (subtitle.bold()) {
92                         span += "weight=\"bold\" ";
93                 }
94                 if (subtitle.underline()) {
95                         span += "underline=\"single\" ";
96                 }
97                 span += "size=\"" + dcp::raw_convert<string>(lrintf(subtitle.size_in_pixels(target_height) * pixels_to_1024ths_point)) + "\" ";
98                 /* Between 1-65535 inclusive, apparently... */
99                 span += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
100                 span += "color=\"#" + subtitle.colour().to_rgb_string() + "\"";
101                 if (!extra_attribute.empty()) {
102                         span += " " + extra_attribute;
103                 }
104                 span += ">";
105
106                 boost::algorithm::replace_all(text, "&", "&amp;");
107                 boost::algorithm::replace_all(text, "<", "&lt;");
108                 boost::algorithm::replace_all(text, ">", "&gt;");
109
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(shared_ptr<const dcpomatic::Font> font)
179 {
180         auto font_file = default_font_file ();
181
182         if (font && font->file()) {
183                 font_file = *font->file();
184         }
185
186         return FontConfig::instance()->make_font_available(font_file);
187 }
188
189
190 static float
191 calculate_fade_factor (StringText const& first, DCPTime time, int frame_rate)
192 {
193         float fade_factor = 1;
194
195         /* Round the fade start/end to the nearest frame start.  Otherwise if a subtitle starts just after
196            the start of a frame it will be faded out.
197         */
198         auto const fade_in_start = DCPTime::from_seconds(first.in().as_seconds()).round(frame_rate);
199         auto const fade_in_end = fade_in_start + DCPTime::from_seconds (first.fade_up_time().as_seconds ());
200
201         if (fade_in_start <= time && time <= fade_in_end && fade_in_start != fade_in_end) {
202                 fade_factor *= DCPTime(time - fade_in_start).seconds() / DCPTime(fade_in_end - fade_in_start).seconds();
203         }
204
205         if (time < fade_in_start) {
206                 fade_factor = 0;
207         }
208
209         /* first.out() may be zero if we don't know when this subtitle will finish.  We can only think about
210          * fading out if we _do_ know when it will finish.
211          */
212         if (first.out() != dcp::Time()) {
213                 auto const fade_out_end = DCPTime::from_seconds (first.out().as_seconds()).round(frame_rate);
214                 auto const fade_out_start = fade_out_end - DCPTime::from_seconds(first.fade_down_time().as_seconds());
215
216                 if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
217                         fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
218                 }
219                 if (time > fade_out_end) {
220                         fade_factor = 0;
221                 }
222         }
223
224         return fade_factor;
225 }
226
227
228 static int
229 x_position (StringText const& first, int target_width, int layout_width)
230 {
231         int x = 0;
232         switch (first.h_align()) {
233         case dcp::HAlign::LEFT:
234                 /* h_position is distance between left of frame and left of subtitle */
235                 x = first.h_position() * target_width;
236                 break;
237         case dcp::HAlign::CENTER:
238                 /* h_position is distance between centre of frame and centre of subtitle */
239                 x = (0.5 + first.h_position()) * target_width - layout_width / 2;
240                 break;
241         case dcp::HAlign::RIGHT:
242                 /* h_position is distance between right of frame and right of subtitle */
243                 x = (1.0 - first.h_position()) * target_width - layout_width;
244                 break;
245         }
246
247         return x;
248 }
249
250
251 static int
252 y_position (StringText const& first, int target_height, int baseline_to_bottom, int layout_height)
253 {
254         int y = 0;
255         switch (first.valign_standard) {
256         case dcp::SubtitleStandard::INTEROP:
257         case dcp::SubtitleStandard::SMPTE_2014:
258                 switch (first.v_align()) {
259                 case dcp::VAlign::TOP:
260                         /* v_position is distance from top of frame to subtitle baseline */
261                         y = first.v_position() * target_height - (layout_height - baseline_to_bottom);
262                         break;
263                 case dcp::VAlign::CENTER:
264                         /* v_position is distance from centre of frame to subtitle baseline */
265                         y = (0.5 + first.v_position()) * target_height - (layout_height - baseline_to_bottom);
266                         break;
267                 case dcp::VAlign::BOTTOM:
268                         /* v_position is distance from bottom of frame to subtitle baseline */
269                         y = (1.0 - first.v_position()) * target_height - (layout_height - baseline_to_bottom);
270                         break;
271                 }
272                 break;
273         case dcp::SubtitleStandard::SMPTE_2007:
274         case dcp::SubtitleStandard::SMPTE_2010:
275                 switch (first.v_align()) {
276                 case dcp::VAlign::TOP:
277                         /* v_position is distance from top of frame to top of subtitle */
278                         y = first.v_position() * target_height;
279                         break;
280                 case dcp::VAlign::CENTER:
281                         /* v_position is distance from centre of frame to centre of subtitle */
282                         y = (0.5 + first.v_position()) * target_height - layout_height / 2;
283                         break;
284                 case dcp::VAlign::BOTTOM:
285                         /* v_position is distance from bottom of frame to bottom of subtitle */
286                         y = (1.0 - first.v_position()) * target_height - layout_height;
287                         break;
288                 }
289         }
290
291         return y;
292 }
293
294
295 /** @param subtitles A list of subtitles that are all on the same line,
296  *  at the same time and with the same fade in/out.
297  */
298 static PositionImage
299 render_line (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
300 {
301         /* XXX: this method can only handle italic / bold changes mid-line,
302            nothing else yet.
303         */
304
305         DCPOMATIC_ASSERT (!subtitles.empty ());
306         auto const& first = subtitles.front ();
307
308         auto const font_name = setup_font(first.font);
309         auto const fade_factor = calculate_fade_factor (first, time, frame_rate);
310         auto const markup = marked_up (subtitles, target.height, fade_factor, font_name);
311         auto layout = create_layout ();
312         setup_layout (layout, font_name, markup);
313         auto ink = layout->get_ink_extents();
314         dcp::Size size{ink.get_width() / Pango::SCALE, ink.get_height() / Pango::SCALE};
315
316         /* Calculate x and y scale factors.  These are only used to stretch
317            the font away from its normal aspect ratio.
318         */
319         float x_scale = 1;
320         float y_scale = 1;
321         if (fabs (first.aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
322                 if (first.aspect_adjust() < 1) {
323                         x_scale = max (0.25f, first.aspect_adjust ());
324                         y_scale = 1;
325                 } else {
326                         x_scale = 1;
327                         y_scale = 1 / min (4.0f, first.aspect_adjust ());
328                 }
329         }
330
331         auto const border_width = first.effect() == dcp::Effect::BORDER ? (first.outline_width * target.width / 2048.0) : 0;
332         size.width += 2 * ceil (border_width);
333         size.height += 2 * ceil (border_width);
334
335         size.width *= x_scale;
336         size.height *= y_scale;
337
338         /* Shuffle the subtitle over by the border width (if we have any) so it's not cut off */
339         int const x_offset = (-ink.get_x() / Pango::SCALE) + ceil(border_width);
340         int const y_offset = -ink.get_y() / Pango::SCALE + ceil(border_width);
341
342         auto image = create_image (size);
343         auto surface = create_surface (image);
344         auto context = Cairo::Context::create (surface);
345
346         context->set_line_width (1);
347         context->scale (x_scale, y_scale);
348         layout->update_from_cairo_context (context);
349
350         if (first.effect() == dcp::Effect::SHADOW) {
351                 /* Drop-shadow effect */
352                 set_source_rgba (context, first.effect_colour(), fade_factor);
353                 context->move_to (x_offset + 4, y_offset + 4);
354                 layout->add_to_cairo_context (context);
355                 context->fill ();
356         }
357
358         if (first.effect() == dcp::Effect::BORDER) {
359                 /* Border effect */
360                 set_source_rgba (context, first.effect_colour(), fade_factor);
361                 context->set_line_width (border_width);
362                 context->set_line_join (Cairo::LINE_JOIN_ROUND);
363                 context->move_to (x_offset, y_offset);
364                 layout->add_to_cairo_context (context);
365                 context->stroke ();
366         }
367
368         /* The actual subtitle */
369
370         set_source_rgba (context, first.colour(), fade_factor);
371
372         context->move_to (x_offset, y_offset);
373         layout->add_to_cairo_context (context);
374         context->fill ();
375
376         context->set_line_width (0.5);
377         context->move_to (x_offset, y_offset);
378         layout->add_to_cairo_context (context);
379         context->stroke ();
380
381         int const x = x_position (first, target.width, size.width);
382         int const y = y_position (first, target.height, ink.get_y() / Pango::SCALE, size.height);
383         return PositionImage (image, Position<int>(max (0, x), max(0, y)));
384 }
385
386
387 /** @param time Time of the frame that these subtitles are going on.
388  *  @param target Size of the container that this subtitle will end up in.
389  *  @param frame_rate DCP frame rate.
390  */
391 list<PositionImage>
392 render_text (list<StringText> subtitles, dcp::Size target, DCPTime time, int frame_rate)
393 {
394         list<StringText> pending;
395         list<PositionImage> images;
396
397         for (auto const& i: subtitles) {
398                 if (!pending.empty() && (i.v_align() != pending.back().v_align() || fabs(i.v_position() - pending.back().v_position()) > 1e-4)) {
399                         images.push_back(render_line(pending, target, time, frame_rate));
400                         pending.clear ();
401                 }
402                 pending.push_back (i);
403         }
404
405         if (!pending.empty()) {
406                 images.push_back(render_line(pending, target, time, frame_rate));
407         }
408
409         return images;
410 }
411
412
413 float
414 FontMetrics::height(StringText const& subtitle)
415 {
416         return get(subtitle)->second.second;
417 }
418
419
420 float
421 FontMetrics::baseline_to_bottom(StringText const& subtitle)
422 {
423         return get(subtitle)->second.first;
424 }
425
426
427 FontMetrics::Cache::iterator
428 FontMetrics::get(StringText const& subtitle)
429 {
430         auto id = Identifier(subtitle);
431
432         auto iter = _cache.find(id);
433         if (iter != _cache.end()) {
434                 return iter;
435         }
436
437         auto const font_name = setup_font(subtitle.font);
438         auto layout = create_layout();
439         auto copy = subtitle;
440         copy.set_text("Qypjg");
441         setup_layout(layout, font_name, marked_up({copy}, _target_height, 1, font_name));
442         auto ink = layout->get_ink_extents();
443         auto const scale = float(_target_height * Pango::SCALE);
444         return _cache.insert({id, { ink.get_y() / scale, ink.get_height() / scale}}).first;
445 }
446
447
448 FontMetrics::Identifier::Identifier(StringText const& subtitle)
449         : font(subtitle.font)
450         , size(subtitle.size())
451         , aspect_adjust(subtitle.aspect_adjust())
452 {
453
454 }
455
456
457 bool
458 FontMetrics::Identifier::operator<(FontMetrics::Identifier const& other) const
459 {
460         if (font != other.font) {
461                 return font < other.font;
462         }
463
464         if (size != other.size) {
465             return size < other.size;
466         }
467
468         return aspect_adjust < other.aspect_adjust;
469 }
470