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