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