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