2 Copyright (C) 2014-2016 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
21 #include "render_subtitles.h"
26 #include "dcpomatic_assert.h"
27 #include <dcp/raw_convert.h>
28 #include <fontconfig/fontconfig.h>
29 #include <cairomm/cairomm.h>
31 #ifndef DCPOMATIC_HAVE_SHOW_IN_CAIRO_CONTEXT
32 #include <pango/pangocairo.h>
34 #include <boost/foreach.hpp>
45 using boost::shared_ptr;
46 using boost::optional;
48 static FcConfig* fc_config = 0;
49 static list<pair<FontFiles, string> > fc_config_fonts;
52 marked_up (list<SubtitleString> subtitles, int target_height, float fade_factor)
56 BOOST_FOREACH (SubtitleString const & i, subtitles) {
59 out += "style=\"italic\" ";
62 out += "weight=\"bold\" ";
65 out += "underline=\"single\" ";
67 out += "size=\"" + dcp::raw_convert<string>(i.size_in_pixels(target_height) * 72 * 1024 / 96) + "\" ";
68 /* Between 1-65535 inclusive, apparently... */
69 out += "alpha=\"" + dcp::raw_convert<string>(int(floor(fade_factor * 65534)) + 1) + "\" ";
70 out += "color=\"#" + i.colour().to_rgb_string() + "\">";
79 set_source_rgba (Cairo::RefPtr<Cairo::Context> context, dcp::Colour colour, float fade_factor)
81 context->set_source_rgba (float(colour.r) / 255, float(colour.g) / 255, float(colour.b) / 255, fade_factor);
84 /** @param subtitles A list of subtitles that are all on the same line,
85 * at the same time and with the same fade in/out.
88 render_line (list<SubtitleString> subtitles, list<shared_ptr<Font> > fonts, dcp::Size target, DCPTime time, int frame_rate)
90 /* XXX: this method can only handle italic / bold changes mid-line,
94 DCPOMATIC_ASSERT (!subtitles.empty ());
96 /* Calculate x and y scale factors. These are only used to stretch
97 the font away from its normal aspect ratio.
101 if (fabs (subtitles.front().aspect_adjust() - 1.0) > dcp::ASPECT_ADJUST_EPSILON) {
102 if (subtitles.front().aspect_adjust() < 1) {
103 xscale = max (0.25f, subtitles.front().aspect_adjust ());
107 yscale = 1 / min (4.0f, subtitles.front().aspect_adjust ());
111 /* Make an empty bitmap as wide as target and at
112 least tall enough for this subtitle.
116 BOOST_FOREACH (dcp::SubtitleString const & i, subtitles) {
117 largest = max (largest, i.size());
119 /* Basic guess on height... */
120 int height = largest * target.height / (11 * 72);
123 /* ...and add a bit more for luck */
124 height += target.height / 11;
126 /* FFmpeg BGRA means first byte blue, second byte green, third byte red, fourth byte alpha */
127 shared_ptr<Image> image (new Image (AV_PIX_FMT_BGRA, dcp::Size (target.width, height), false));
128 image->make_black ();
130 #ifdef DCPOMATIC_HAVE_FORMAT_STRIDE_FOR_WIDTH
131 Cairo::RefPtr<Cairo::ImageSurface> surface = Cairo::ImageSurface::create (
133 Cairo::FORMAT_ARGB32,
135 image->size().height,
136 /* Cairo ARGB32 means first byte blue, second byte green, third byte red, fourth byte alpha */
137 Cairo::ImageSurface::format_stride_for_width (Cairo::FORMAT_ARGB32, image->size().width)
140 /* Centos 5 does not have Cairo::ImageSurface::format_stride_for_width, so just use width * 4
141 which I hope is safe (if slow)
143 Cairo::RefPtr<Cairo::ImageSurface> surface = Cairo::ImageSurface::create (
145 Cairo::FORMAT_ARGB32,
147 image->size().height,
148 image->size().width * 4
152 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (surface);
155 fc_config = FcConfigCreate ();
158 FontFiles font_files;
161 font_files.set (FontFiles::NORMAL, shared_path () / "LiberationSans-Regular.ttf");
162 font_files.set (FontFiles::ITALIC, shared_path () / "LiberationSans-Italic.ttf");
163 font_files.set (FontFiles::BOLD, shared_path () / "LiberationSans-Bold.ttf");
164 } catch (boost::filesystem::filesystem_error& e) {
168 /* Hack: try the debian/ubuntu locations if getting the shared path failed */
170 if (!font_files.get(FontFiles::NORMAL) || !boost::filesystem::exists(font_files.get(FontFiles::NORMAL).get())) {
171 font_files.set (FontFiles::NORMAL, "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf");
173 if (!font_files.get(FontFiles::ITALIC) || !boost::filesystem::exists(font_files.get(FontFiles::ITALIC).get())) {
174 font_files.set (FontFiles::ITALIC, "/usr/share/fonts/truetype/liberation/LiberationSans-Italic.ttf");
176 if (!font_files.get(FontFiles::BOLD) || !boost::filesystem::exists(font_files.get(FontFiles::BOLD).get())) {
177 font_files.set (FontFiles::BOLD, "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf");
180 BOOST_FOREACH (shared_ptr<Font> i, fonts) {
181 if (i->id() == subtitles.front().font() && i->file(FontFiles::NORMAL)) {
182 font_files = i->files ();
186 list<pair<FontFiles, string> >::const_iterator existing = fc_config_fonts.begin ();
187 while (existing != fc_config_fonts.end() && existing->first != font_files) {
192 if (existing != fc_config_fonts.end ()) {
193 font_name = existing->second;
195 /* Make this font available to DCP-o-matic */
196 for (int i = 0; i < FontFiles::VARIANTS; ++i) {
197 if (font_files.get(static_cast<FontFiles::Variant>(i))) {
198 FcConfigAppFontAddFile (
200 reinterpret_cast<FcChar8 const *> (font_files.get(static_cast<FontFiles::Variant>(i)).get().string().c_str())
205 FcPattern* pattern = FcPatternBuild (
206 0, FC_FILE, FcTypeString, font_files.get(FontFiles::NORMAL).get().string().c_str(), static_cast<char *> (0)
208 FcObjectSet* object_set = FcObjectSetBuild (FC_FAMILY, FC_STYLE, FC_LANG, FC_FILE, static_cast<char *> (0));
209 FcFontSet* font_set = FcFontList (fc_config, pattern, object_set);
211 for (int i = 0; i < font_set->nfont; ++i) {
212 FcPattern* font = font_set->fonts[i];
217 FcPatternGetString (font, FC_FILE, 0, &file) == FcResultMatch &&
218 FcPatternGetString (font, FC_FAMILY, 0, &family) == FcResultMatch &&
219 FcPatternGetString (font, FC_STYLE, 0, &style) == FcResultMatch
221 font_name = reinterpret_cast<char const *> (family);
225 FcFontSetDestroy (font_set);
228 FcObjectSetDestroy (object_set);
229 FcPatternDestroy (pattern);
231 fc_config_fonts.push_back (make_pair (font_files, font_name));
234 FcConfigSetCurrent (fc_config);
236 Glib::RefPtr<Pango::Layout> layout = Pango::Layout::create (context);
238 layout->set_alignment (Pango::ALIGN_LEFT);
240 context->set_line_width (1);
242 /* Compute fade factor */
243 float fade_factor = 1;
245 /* Round the fade start/end to the nearest frame start. Otherwise if a subtitle starts just after
246 the start of a frame it will be faded out.
248 DCPTime const fade_in_start = DCPTime::from_seconds(subtitles.front().in().as_seconds()).round(frame_rate);
249 DCPTime const fade_in_end = fade_in_start + DCPTime::from_seconds (subtitles.front().fade_up_time().as_seconds ());
250 DCPTime const fade_out_end = DCPTime::from_seconds (subtitles.front().out().as_seconds()).round(frame_rate);
251 DCPTime const fade_out_start = fade_out_end - DCPTime::from_seconds (subtitles.front().fade_down_time().as_seconds ());
253 if (fade_in_start <= time && time <= fade_in_end && fade_in_start != fade_in_end) {
254 fade_factor *= DCPTime(time - fade_in_start).seconds() / DCPTime(fade_in_end - fade_in_start).seconds();
256 if (fade_out_start <= time && time <= fade_out_end && fade_out_start != fade_out_end) {
257 fade_factor *= 1 - DCPTime(time - fade_out_start).seconds() / DCPTime(fade_out_end - fade_out_start).seconds();
259 if (time < fade_in_start || time > fade_out_end) {
263 /* Render the subtitle at the top left-hand corner of image */
265 Pango::FontDescription font (font_name);
266 layout->set_font_description (font);
267 layout->set_markup (marked_up (subtitles, target.height, fade_factor));
269 context->scale (xscale, yscale);
270 layout->update_from_cairo_context (context);
272 /* Shuffle the subtitle over very slightly if it has a border so that the left-hand
273 side of the first character's border is not cut off.
275 int const x_offset = subtitles.front().effect() == dcp::BORDER ? (target.width / 600.0) : 0;
276 /* Move down a bit so that accents on capital letters can be seen */
277 int const y_offset = target.height / 100.0;
279 if (subtitles.front().effect() == dcp::SHADOW) {
280 /* Drop-shadow effect */
281 set_source_rgba (context, subtitles.front().effect_colour(), fade_factor);
282 context->move_to (x_offset + 4, y_offset + 4);
283 layout->add_to_cairo_context (context);
287 if (subtitles.front().effect() == dcp::BORDER) {
288 /* Border effect; stroke the subtitle with a large (arbitrarily chosen) line width */
289 set_source_rgba (context, subtitles.front().effect_colour(), fade_factor);
290 context->set_line_width (subtitles.front().outline_width * target.width / 2048.0);
291 context->set_line_join (Cairo::LINE_JOIN_ROUND);
292 context->move_to (x_offset, y_offset);
293 layout->add_to_cairo_context (context);
297 /* The actual subtitle */
299 context->set_line_width (0);
300 context->move_to (x_offset, y_offset);
301 #ifdef DCPOMATIC_HAVE_SHOW_IN_CAIRO_CONTEXT
302 layout->show_in_cairo_context (context);
304 pango_cairo_show_layout (context->cobj(), layout->gobj());
309 layout->get_pixel_size (layout_width, layout_height);
310 layout_width *= xscale;
311 layout_height *= yscale;
314 switch (subtitles.front().h_align ()) {
315 case dcp::HALIGN_LEFT:
316 /* h_position is distance between left of frame and left of subtitle */
317 x = subtitles.front().h_position() * target.width;
319 case dcp::HALIGN_CENTER:
320 /* h_position is distance between centre of frame and centre of subtitle */
321 x = (0.5 + subtitles.front().h_position()) * target.width - layout_width / 2;
323 case dcp::HALIGN_RIGHT:
324 /* h_position is distance between right of frame and right of subtitle */
325 x = (1.0 - subtitles.front().h_position()) * target.width - layout_width;
330 switch (subtitles.front().v_align ()) {
331 case dcp::VALIGN_TOP:
332 /* SMPTE says that v_position is the distance between top
333 of frame and top of subtitle, but this doesn't always seem to be
334 the case in practice; Gunnar Ásgeirsson's Dolby server appears
335 to put VALIGN_TOP subs with v_position as the distance between top
336 of frame and bottom of subtitle.
338 y = subtitles.front().v_position() * target.height - layout_height;
340 case dcp::VALIGN_CENTER:
341 /* v_position is distance between centre of frame and centre of subtitle */
342 y = (0.5 + subtitles.front().v_position()) * target.height - layout_height / 2;
344 case dcp::VALIGN_BOTTOM:
345 /* v_position is distance between bottom of frame and bottom of subtitle */
346 y = (1.0 - subtitles.front().v_position()) * target.height - layout_height;
350 return PositionImage (image, Position<int> (max (0, x), max (0, y)));
353 /** @param time Time of the frame that these subtitles are going on.
354 * @param frame_rate DCP frame rate.
357 render_subtitles (list<SubtitleString> subtitles, list<shared_ptr<Font> > fonts, dcp::Size target, DCPTime time, int frame_rate)
359 list<SubtitleString> pending;
360 list<PositionImage> images;
362 BOOST_FOREACH (SubtitleString const & i, subtitles) {
363 if (!pending.empty() && fabs (i.v_position() - pending.back().v_position()) > 1e-4) {
364 images.push_back (render_line (pending, fonts, target, time, frame_rate));
367 pending.push_back (i);
370 if (!pending.empty ()) {
371 images.push_back (render_line (pending, fonts, target, time, frame_rate));