No-op; fix GPL address and use the explicit-program-name version.
[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         BOOST_FOREACH (dcp::SubtitleString const & i, subtitles) {
204                 if (i.italic() != italic) {
205                         if (i.italic()) {
206                                 marked_up += "<i>";
207                         } else {
208                                 marked_up += "</i>";
209                         }
210                         italic = i.italic ();
211                 }
212
213                 marked_up += i.text ();
214         }
215
216         if (italic) {
217                 marked_up += "</i>";
218         }
219
220         layout->set_markup (marked_up);
221
222         /* Compute fade factor */
223         /* XXX */
224         float fade_factor = 1;
225
226         context->scale (xscale, yscale);
227         layout->update_from_cairo_context (context);
228
229         if (subtitles.front().effect() == dcp::SHADOW) {
230                 /* Drop-shadow effect */
231                 dcp::Colour const ec = subtitles.front().effect_colour ();
232                 context->set_source_rgba (float(ec.r) / 255, float(ec.g) / 255, float(ec.b) / 255, fade_factor);
233                 context->move_to (4, 4);
234                 layout->add_to_cairo_context (context);
235                 context->fill ();
236         }
237
238         /* The actual subtitle */
239
240         dcp::Colour const c = subtitles.front().colour ();
241         context->set_source_rgba (float(c.r) / 255, float(c.g) / 255, float(c.b) / 255, fade_factor);
242         context->move_to (0, 0);
243         layout->add_to_cairo_context (context);
244         context->fill ();
245
246         if (subtitles.front().effect() == dcp::BORDER) {
247                 /* Border effect */
248                 dcp::Colour ec = subtitles.front().effect_colour ();
249                 context->set_source_rgba (float(ec.r) / 255, float(ec.g) / 255, float(ec.b) / 255, fade_factor);
250                 context->move_to (0, 0);
251                 layout->add_to_cairo_context (context);
252                 context->stroke ();
253         }
254
255         int layout_width;
256         int layout_height;
257         layout->get_pixel_size (layout_width, layout_height);
258         layout_width *= xscale;
259         layout_height *= yscale;
260
261         int x = 0;
262         switch (subtitles.front().h_align ()) {
263         case dcp::HALIGN_LEFT:
264                 /* h_position is distance between left of frame and left of subtitle */
265                 x = subtitles.front().h_position() * target.width;
266                 break;
267         case dcp::HALIGN_CENTER:
268                 /* h_position is distance between centre of frame and centre of subtitle */
269                 x = (0.5 + subtitles.front().h_position()) * target.width - layout_width / 2;
270                 break;
271         case dcp::HALIGN_RIGHT:
272                 /* h_position is distance between right of frame and right of subtitle */
273                 x = (1.0 - subtitles.front().h_position()) * target.width - layout_width;
274                 break;
275         }
276
277         int y = 0;
278         switch (subtitles.front().v_align ()) {
279         case dcp::VALIGN_TOP:
280                 /* SMPTE says that v_position is the distance between top
281                    of frame and top of subtitle, but this doesn't always seem to be
282                    the case in practice; Gunnar Ásgeirsson's Dolby server appears
283                    to put VALIGN_TOP subs with v_position as the distance between top
284                    of frame and bottom of subtitle.
285                 */
286                 y = subtitles.front().v_position() * target.height - layout_height;
287                 break;
288         case dcp::VALIGN_CENTER:
289                 /* v_position is distance between centre of frame and centre of subtitle */
290                 y = (0.5 + subtitles.front().v_position()) * target.height - layout_height / 2;
291                 break;
292         case dcp::VALIGN_BOTTOM:
293                 /* v_position is distance between bottom of frame and bottom of subtitle */
294                 y = (1.0 - subtitles.front().v_position()) * target.height - layout_height;
295                 break;
296         }
297
298         return PositionImage (image, Position<int> (max (0, x), max (0, y)));
299 }
300
301 list<PositionImage>
302 render_subtitles (list<dcp::SubtitleString> subtitles, list<shared_ptr<Font> > fonts, dcp::Size target)
303 {
304         list<dcp::SubtitleString> pending;
305         list<PositionImage> images;
306
307         BOOST_FOREACH (dcp::SubtitleString const & i, subtitles) {
308                 if (!pending.empty() && fabs (i.v_position() - pending.back().v_position()) > 1e-4) {
309                         images.push_back (render_line (pending, fonts, target));
310                         pending.clear ();
311                 }
312                 pending.push_back (i);
313         }
314
315         if (!pending.empty ()) {
316                 images.push_back (render_line (pending, fonts, target));
317         }
318
319         return images;
320 }