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