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