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