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