FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vf_subtitles.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011 Baptiste Coudurier
3  * Copyright (c) 2011 Stefano Sabatini
4  * Copyright (c) 2012 Clément Bœsch
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 /**
24  * @file
25  * Libass subtitles burning filter.
26  *
27  * @see{http://www.matroska.org/technical/specs/subtitles/ssa.html}
28  */
29 
30 #include <ass/ass.h>
31 
32 #include "config.h"
33 #if CONFIG_SUBTITLES_FILTER
34 # include "libavcodec/avcodec.h"
35 # include "libavformat/avformat.h"
36 #endif
37 #include "libavutil/avstring.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/parseutils.h"
41 #include "drawutils.h"
42 #include "avfilter.h"
43 #include "internal.h"
44 #include "formats.h"
45 #include "video.h"
46 
47 typedef struct {
48  const AVClass *class;
49  ASS_Library *library;
50  ASS_Renderer *renderer;
51  ASS_Track *track;
52  char *filename;
53  char *charenc;
54  uint8_t rgba_map[4];
55  int pix_step[4]; ///< steps per pixel for each plane of the main output
56  int original_w, original_h;
58 } AssContext;
59 
60 #define OFFSET(x) offsetof(AssContext, x)
61 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
62 
63 #define COMMON_OPTIONS \
64  {"filename", "set the filename of file to read", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS }, \
65  {"f", "set the filename of file to read", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS }, \
66  {"original_size", "set the size of the original video (used to scale fonts)", OFFSET(original_w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS }, \
67 
68 /* libass supports a log level ranging from 0 to 7 */
69 static const int ass_libavfilter_log_level_map[] = {
70  AV_LOG_QUIET, /* 0 */
71  AV_LOG_PANIC, /* 1 */
72  AV_LOG_FATAL, /* 2 */
73  AV_LOG_ERROR, /* 3 */
74  AV_LOG_WARNING, /* 4 */
75  AV_LOG_INFO, /* 5 */
76  AV_LOG_VERBOSE, /* 6 */
77  AV_LOG_DEBUG, /* 7 */
78 };
79 
80 static void ass_log(int ass_level, const char *fmt, va_list args, void *ctx)
81 {
82  int level = ass_libavfilter_log_level_map[ass_level];
83 
84  av_vlog(ctx, level, fmt, args);
85  av_log(ctx, level, "\n");
86 }
87 
88 static av_cold int init(AVFilterContext *ctx)
89 {
90  AssContext *ass = ctx->priv;
91 
92  if (!ass->filename) {
93  av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
94  return AVERROR(EINVAL);
95  }
96 
97  ass->library = ass_library_init();
98  if (!ass->library) {
99  av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
100  return AVERROR(EINVAL);
101  }
102  ass_set_message_cb(ass->library, ass_log, ctx);
103 
104  ass->renderer = ass_renderer_init(ass->library);
105  if (!ass->renderer) {
106  av_log(ctx, AV_LOG_ERROR, "Could not initialize libass renderer.\n");
107  return AVERROR(EINVAL);
108  }
109 
110  return 0;
111 }
112 
113 static av_cold void uninit(AVFilterContext *ctx)
114 {
115  AssContext *ass = ctx->priv;
116 
117  if (ass->track)
118  ass_free_track(ass->track);
119  if (ass->renderer)
120  ass_renderer_done(ass->renderer);
121  if (ass->library)
122  ass_library_done(ass->library);
123 }
124 
126 {
128  return 0;
129 }
130 
131 static int config_input(AVFilterLink *inlink)
132 {
133  AssContext *ass = inlink->dst->priv;
134 
135  ff_draw_init(&ass->draw, inlink->format, 0);
136 
137  ass_set_frame_size (ass->renderer, inlink->w, inlink->h);
138  if (ass->original_w && ass->original_h)
139  ass_set_aspect_ratio(ass->renderer, (double)inlink->w / inlink->h,
140  (double)ass->original_w / ass->original_h);
141 
142  return 0;
143 }
144 
145 /* libass stores an RGBA color in the format RRGGBBTT, where TT is the transparency level */
146 #define AR(c) ( (c)>>24)
147 #define AG(c) (((c)>>16)&0xFF)
148 #define AB(c) (((c)>>8) &0xFF)
149 #define AA(c) ((0xFF-c) &0xFF)
150 
151 static void overlay_ass_image(AssContext *ass, AVFrame *picref,
152  const ASS_Image *image)
153 {
154  for (; image; image = image->next) {
155  uint8_t rgba_color[] = {AR(image->color), AG(image->color), AB(image->color), AA(image->color)};
157  ff_draw_color(&ass->draw, &color, rgba_color);
158  ff_blend_mask(&ass->draw, &color,
159  picref->data, picref->linesize,
160  picref->width, picref->height,
161  image->bitmap, image->stride, image->w, image->h,
162  3, 0, image->dst_x, image->dst_y);
163  }
164 }
165 
166 static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
167 {
168  AVFilterContext *ctx = inlink->dst;
169  AVFilterLink *outlink = ctx->outputs[0];
170  AssContext *ass = ctx->priv;
171  int detect_change = 0;
172  double time_ms = picref->pts * av_q2d(inlink->time_base) * 1000;
173  ASS_Image *image = ass_render_frame(ass->renderer, ass->track,
174  time_ms, &detect_change);
175 
176  if (detect_change)
177  av_log(ctx, AV_LOG_DEBUG, "Change happened at time ms:%f\n", time_ms);
178 
179  overlay_ass_image(ass, picref, image);
180 
181  return ff_filter_frame(outlink, picref);
182 }
183 
184 static const AVFilterPad ass_inputs[] = {
185  {
186  .name = "default",
187  .type = AVMEDIA_TYPE_VIDEO,
188  .filter_frame = filter_frame,
189  .config_props = config_input,
190  .needs_writable = 1,
191  },
192  { NULL }
193 };
194 
195 static const AVFilterPad ass_outputs[] = {
196  {
197  .name = "default",
198  .type = AVMEDIA_TYPE_VIDEO,
199  },
200  { NULL }
201 };
202 
203 #if CONFIG_ASS_FILTER
204 
205 static const AVOption ass_options[] = {
207  {NULL},
208 };
209 
211 
212 static av_cold int init_ass(AVFilterContext *ctx)
213 {
214  AssContext *ass = ctx->priv;
215  int ret = init(ctx);
216 
217  if (ret < 0)
218  return ret;
219 
220  /* Initialize fonts */
221  ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
222 
223  ass->track = ass_read_file(ass->library, ass->filename, NULL);
224  if (!ass->track) {
225  av_log(ctx, AV_LOG_ERROR,
226  "Could not create a libass track when reading file '%s'\n",
227  ass->filename);
228  return AVERROR(EINVAL);
229  }
230  return 0;
231 }
232 
233 AVFilter ff_vf_ass = {
234  .name = "ass",
235  .description = NULL_IF_CONFIG_SMALL("Render ASS subtitles onto input video using the libass library."),
236  .priv_size = sizeof(AssContext),
237  .init = init_ass,
238  .uninit = uninit,
240  .inputs = ass_inputs,
241  .outputs = ass_outputs,
242  .priv_class = &ass_class,
243 };
244 #endif
245 
246 #if CONFIG_SUBTITLES_FILTER
247 
248 static const AVOption subtitles_options[] = {
250  {"charenc", "set input character encoding", OFFSET(charenc), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
251  {NULL},
252 };
253 
254 static const char *font_mimetypes[] = {
255  "application/x-truetype-font",
256  "application/vnd.ms-opentype",
257  "application/x-font-ttf",
258  NULL
259 };
260 
261 static int attachment_is_font(AVStream * st)
262 {
263  const AVDictionaryEntry *tag = NULL;
264  int n;
265 
266  tag = av_dict_get(st->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE);
267 
268  if (tag) {
269  for (n = 0; font_mimetypes[n]; n++) {
270  if (av_strcasecmp(font_mimetypes[n], tag->value) == 0)
271  return 1;
272  }
273  }
274  return 0;
275 }
276 
277 AVFILTER_DEFINE_CLASS(subtitles);
278 
279 static av_cold int init_subtitles(AVFilterContext *ctx)
280 {
281  int j, ret, sid;
282  AVDictionary *codec_opts = NULL;
283  AVFormatContext *fmt = NULL;
284  AVCodecContext *dec_ctx = NULL;
285  AVCodec *dec = NULL;
286  const AVCodecDescriptor *dec_desc;
287  AVStream *st;
288  AVPacket pkt;
289  AssContext *ass = ctx->priv;
290 
291  /* Init libass */
292  ret = init(ctx);
293  if (ret < 0)
294  return ret;
295  ass->track = ass_new_track(ass->library);
296  if (!ass->track) {
297  av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");
298  return AVERROR(EINVAL);
299  }
300 
301  /* Open subtitles file */
302  ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);
303  if (ret < 0) {
304  av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);
305  goto end;
306  }
307  ret = avformat_find_stream_info(fmt, NULL);
308  if (ret < 0)
309  goto end;
310 
311  /* Locate subtitles stream */
312  ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);
313  if (ret < 0) {
314  av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",
315  ass->filename);
316  goto end;
317  }
318  sid = ret;
319  st = fmt->streams[sid];
320 
321  /* Load attached fonts */
322  for (j = 0; j < fmt->nb_streams; j++) {
323  AVStream *st = fmt->streams[j];
325  attachment_is_font(st)) {
326  const AVDictionaryEntry *tag = NULL;
327  tag = av_dict_get(st->metadata, "filename", NULL,
329 
330  if (tag) {
331  av_log(ctx, AV_LOG_DEBUG, "Loading attached font: %s\n",
332  tag->value);
333  ass_add_font(ass->library, tag->value,
334  st->codec->extradata,
335  st->codec->extradata_size);
336  } else {
337  av_log(ctx, AV_LOG_WARNING,
338  "Font attachment has no filename, ignored.\n");
339  }
340  }
341  }
342 
343  /* Initialize fonts */
344  ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
345 
346  /* Open decoder */
347  dec_ctx = st->codec;
348  dec = avcodec_find_decoder(dec_ctx->codec_id);
349  if (!dec) {
350  av_log(ctx, AV_LOG_ERROR, "Failed to find subtitle codec %s\n",
351  avcodec_get_name(dec_ctx->codec_id));
352  return AVERROR(EINVAL);
353  }
354  dec_desc = avcodec_descriptor_get(dec_ctx->codec_id);
355  if (dec_desc && !(dec_desc->props & AV_CODEC_PROP_TEXT_SUB)) {
356  av_log(ctx, AV_LOG_ERROR,
357  "Only text based subtitles are currently supported\n");
358  return AVERROR_PATCHWELCOME;
359  }
360  if (ass->charenc)
361  av_dict_set(&codec_opts, "sub_charenc", ass->charenc, 0);
362  ret = avcodec_open2(dec_ctx, dec, &codec_opts);
363  if (ret < 0)
364  goto end;
365 
366  /* Decode subtitles and push them into the renderer (libass) */
367  if (dec_ctx->subtitle_header)
368  ass_process_codec_private(ass->track,
369  dec_ctx->subtitle_header,
370  dec_ctx->subtitle_header_size);
371  av_init_packet(&pkt);
372  pkt.data = NULL;
373  pkt.size = 0;
374  while (av_read_frame(fmt, &pkt) >= 0) {
375  int i, got_subtitle;
376  AVSubtitle sub = {0};
377 
378  if (pkt.stream_index == sid) {
379  ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);
380  if (ret < 0) {
381  av_log(ctx, AV_LOG_WARNING, "Error decoding: %s (ignored)\n",
382  av_err2str(ret));
383  } else if (got_subtitle) {
384  for (i = 0; i < sub.num_rects; i++) {
385  char *ass_line = sub.rects[i]->ass;
386  if (!ass_line)
387  break;
388  ass_process_data(ass->track, ass_line, strlen(ass_line));
389  }
390  }
391  }
392  av_free_packet(&pkt);
393  avsubtitle_free(&sub);
394  }
395 
396 end:
397  av_dict_free(&codec_opts);
398  if (dec_ctx)
399  avcodec_close(dec_ctx);
400  if (fmt)
401  avformat_close_input(&fmt);
402  return ret;
403 }
404 
405 AVFilter ff_vf_subtitles = {
406  .name = "subtitles",
407  .description = NULL_IF_CONFIG_SMALL("Render text subtitles onto input video using the libass library."),
408  .priv_size = sizeof(AssContext),
409  .init = init_subtitles,
410  .uninit = uninit,
412  .inputs = ass_inputs,
413  .outputs = ass_outputs,
414  .priv_class = &subtitles_class,
415 };
416 #endif