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