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