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