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