2 * Copyright (c) 2011 Baptiste Coudurier
3 * Copyright (c) 2011 Stefano Sabatini
4 * Copyright (c) 2012 Clément Bœsch
6 * This file is part of FFmpeg.
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.
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.
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
25 * Libass subtitles burning filter.
27 * @see{http://www.matroska.org/technical/specs/subtitles/ssa.html}
33 #if CONFIG_SUBTITLES_FILTER
34 # include "libavcodec/avcodec.h"
35 # include "libavformat/avformat.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/parseutils.h"
41 #include "drawutils.h"
47 typedef struct AssContext {
50 ASS_Renderer *renderer;
59 int pix_step[4]; ///< steps per pixel for each plane of the main output
60 int original_w, original_h;
65 #define OFFSET(x) offsetof(AssContext, x)
66 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
68 #define COMMON_OPTIONS \
69 {"filename", "set the filename of file to read", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS }, \
70 {"f", "set the filename of file to read", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS }, \
71 {"original_size", "set the size of the original video (used to scale fonts)", OFFSET(original_w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, FLAGS }, \
72 {"fontsdir", "set the directory containing the fonts to read", OFFSET(fontsdir), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS }, \
73 {"alpha", "enable processing of alpha channel", OFFSET(alpha), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, FLAGS }, \
75 /* libass supports a log level ranging from 0 to 7 */
76 static const int ass_libavfilter_log_level_map[] = {
77 [0] = AV_LOG_FATAL, /* MSGL_FATAL */
78 [1] = AV_LOG_ERROR, /* MSGL_ERR */
79 [2] = AV_LOG_WARNING, /* MSGL_WARN */
80 [3] = AV_LOG_WARNING, /* <undefined> */
81 [4] = AV_LOG_INFO, /* MSGL_INFO */
82 [5] = AV_LOG_INFO, /* <undefined> */
83 [6] = AV_LOG_VERBOSE, /* MSGL_V */
84 [7] = AV_LOG_DEBUG, /* MSGL_DBG2 */
87 static void ass_log(int ass_level, const char *fmt, va_list args, void *ctx)
89 const int ass_level_clip = av_clip(ass_level, 0,
90 FF_ARRAY_ELEMS(ass_libavfilter_log_level_map) - 1);
91 const int level = ass_libavfilter_log_level_map[ass_level_clip];
93 av_vlog(ctx, level, fmt, args);
94 av_log(ctx, level, "\n");
97 static av_cold int init(AVFilterContext *ctx)
99 AssContext *ass = ctx->priv;
101 if (!ass->filename) {
102 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
103 return AVERROR(EINVAL);
106 ass->library = ass_library_init();
108 av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
109 return AVERROR(EINVAL);
111 ass_set_message_cb(ass->library, ass_log, ctx);
113 ass_set_fonts_dir(ass->library, ass->fontsdir);
115 ass->renderer = ass_renderer_init(ass->library);
116 if (!ass->renderer) {
117 av_log(ctx, AV_LOG_ERROR, "Could not initialize libass renderer.\n");
118 return AVERROR(EINVAL);
124 static av_cold void uninit(AVFilterContext *ctx)
126 AssContext *ass = ctx->priv;
129 ass_free_track(ass->track);
131 ass_renderer_done(ass->renderer);
133 ass_library_done(ass->library);
136 static int query_formats(AVFilterContext *ctx)
138 return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
141 static int config_input(AVFilterLink *inlink)
143 AssContext *ass = inlink->dst->priv;
145 ff_draw_init(&ass->draw, inlink->format, ass->alpha ? FF_DRAW_PROCESS_ALPHA : 0);
147 ass_set_frame_size (ass->renderer, inlink->w, inlink->h);
148 if (ass->original_w && ass->original_h)
149 ass_set_aspect_ratio(ass->renderer, (double)inlink->w / inlink->h,
150 (double)ass->original_w / ass->original_h);
151 if (ass->shaping != -1)
152 ass_set_shaper(ass->renderer, ass->shaping);
157 /* libass stores an RGBA color in the format RRGGBBTT, where TT is the transparency level */
158 #define AR(c) ( (c)>>24)
159 #define AG(c) (((c)>>16)&0xFF)
160 #define AB(c) (((c)>>8) &0xFF)
161 #define AA(c) ((0xFF-(c)) &0xFF)
163 static void overlay_ass_image(AssContext *ass, AVFrame *picref,
164 const ASS_Image *image)
166 for (; image; image = image->next) {
167 uint8_t rgba_color[] = {AR(image->color), AG(image->color), AB(image->color), AA(image->color)};
169 ff_draw_color(&ass->draw, &color, rgba_color);
170 ff_blend_mask(&ass->draw, &color,
171 picref->data, picref->linesize,
172 picref->width, picref->height,
173 image->bitmap, image->stride, image->w, image->h,
174 3, 0, image->dst_x, image->dst_y);
178 static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
180 AVFilterContext *ctx = inlink->dst;
181 AVFilterLink *outlink = ctx->outputs[0];
182 AssContext *ass = ctx->priv;
183 int detect_change = 0;
184 double time_ms = picref->pts * av_q2d(inlink->time_base) * 1000;
185 ASS_Image *image = ass_render_frame(ass->renderer, ass->track,
186 time_ms, &detect_change);
189 av_log(ctx, AV_LOG_DEBUG, "Change happened at time ms:%f\n", time_ms);
191 overlay_ass_image(ass, picref, image);
193 return ff_filter_frame(outlink, picref);
196 static const AVFilterPad ass_inputs[] = {
199 .type = AVMEDIA_TYPE_VIDEO,
200 .filter_frame = filter_frame,
201 .config_props = config_input,
207 static const AVFilterPad ass_outputs[] = {
210 .type = AVMEDIA_TYPE_VIDEO,
215 #if CONFIG_ASS_FILTER
217 static const AVOption ass_options[] = {
219 {"shaping", "set shaping engine", OFFSET(shaping), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, FLAGS, "shaping_mode"},
220 {"auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
221 {"simple", "simple shaping", 0, AV_OPT_TYPE_CONST, {.i64 = ASS_SHAPING_SIMPLE}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
222 {"complex", "complex shaping", 0, AV_OPT_TYPE_CONST, {.i64 = ASS_SHAPING_COMPLEX}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
226 AVFILTER_DEFINE_CLASS(ass);
228 static av_cold int init_ass(AVFilterContext *ctx)
230 AssContext *ass = ctx->priv;
236 /* Initialize fonts */
237 ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
239 ass->track = ass_read_file(ass->library, ass->filename, NULL);
241 av_log(ctx, AV_LOG_ERROR,
242 "Could not create a libass track when reading file '%s'\n",
244 return AVERROR(EINVAL);
249 AVFilter ff_vf_ass = {
251 .description = NULL_IF_CONFIG_SMALL("Render ASS subtitles onto input video using the libass library."),
252 .priv_size = sizeof(AssContext),
255 .query_formats = query_formats,
256 .inputs = ass_inputs,
257 .outputs = ass_outputs,
258 .priv_class = &ass_class,
262 #if CONFIG_SUBTITLES_FILTER
264 static const AVOption subtitles_options[] = {
266 {"charenc", "set input character encoding", OFFSET(charenc), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
267 {"stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS},
268 {"si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS},
269 {"force_style", "force subtitle style", OFFSET(force_style), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
273 static const char * const font_mimetypes[] = {
274 "application/x-truetype-font",
275 "application/vnd.ms-opentype",
276 "application/x-font-ttf",
280 static int attachment_is_font(AVStream * st)
282 const AVDictionaryEntry *tag = NULL;
285 tag = av_dict_get(st->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE);
288 for (n = 0; font_mimetypes[n]; n++) {
289 if (av_strcasecmp(font_mimetypes[n], tag->value) == 0)
296 AVFILTER_DEFINE_CLASS(subtitles);
298 static av_cold int init_subtitles(AVFilterContext *ctx)
302 AVDictionary *codec_opts = NULL;
303 AVFormatContext *fmt = NULL;
304 AVCodecContext *dec_ctx = NULL;
306 const AVCodecDescriptor *dec_desc;
309 AssContext *ass = ctx->priv;
315 ass->track = ass_new_track(ass->library);
317 av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");
318 return AVERROR(EINVAL);
321 /* Open subtitles file */
322 ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);
324 av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);
327 ret = avformat_find_stream_info(fmt, NULL);
331 /* Locate subtitles stream */
332 if (ass->stream_index < 0)
333 ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);
336 if (ass->stream_index < fmt->nb_streams) {
337 for (j = 0; j < fmt->nb_streams; j++) {
338 if (fmt->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
339 if (ass->stream_index == k) {
350 av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",
355 st = fmt->streams[sid];
357 /* Load attached fonts */
358 for (j = 0; j < fmt->nb_streams; j++) {
359 AVStream *st = fmt->streams[j];
360 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT &&
361 attachment_is_font(st)) {
362 const AVDictionaryEntry *tag = NULL;
363 tag = av_dict_get(st->metadata, "filename", NULL,
367 av_log(ctx, AV_LOG_DEBUG, "Loading attached font: %s\n",
369 ass_add_font(ass->library, tag->value,
370 st->codecpar->extradata,
371 st->codecpar->extradata_size);
373 av_log(ctx, AV_LOG_WARNING,
374 "Font attachment has no filename, ignored.\n");
379 /* Initialize fonts */
380 ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
383 dec = avcodec_find_decoder(st->codecpar->codec_id);
385 av_log(ctx, AV_LOG_ERROR, "Failed to find subtitle codec %s\n",
386 avcodec_get_name(st->codecpar->codec_id));
387 ret = AVERROR_DECODER_NOT_FOUND;
390 dec_desc = avcodec_descriptor_get(st->codecpar->codec_id);
391 if (dec_desc && !(dec_desc->props & AV_CODEC_PROP_TEXT_SUB)) {
392 av_log(ctx, AV_LOG_ERROR,
393 "Only text based subtitles are currently supported\n");
394 ret = AVERROR_PATCHWELCOME;
398 av_dict_set(&codec_opts, "sub_charenc", ass->charenc, 0);
399 av_dict_set(&codec_opts, "sub_text_format", "ass", 0);
401 dec_ctx = avcodec_alloc_context3(dec);
403 ret = AVERROR(ENOMEM);
407 ret = avcodec_parameters_to_context(dec_ctx, st->codecpar);
412 * This is required by the decoding process in order to rescale the
413 * timestamps: in the current API the decoded subtitles have their pts
414 * expressed in AV_TIME_BASE, and thus the lavc internals need to know the
415 * stream time base in order to achieve the rescaling.
417 * That API is old and needs to be reworked to match behaviour with A/V.
419 dec_ctx->pkt_timebase = st->time_base;
421 ret = avcodec_open2(dec_ctx, NULL, &codec_opts);
425 if (ass->force_style) {
428 char *ptr = av_strtok(ass->force_style, ",", &temp);
431 av_dynarray_add(&list, &i, ptr);
433 ret = AVERROR(ENOMEM);
436 ptr = av_strtok(NULL, ",", &temp);
438 av_dynarray_add(&list, &i, NULL);
440 ret = AVERROR(ENOMEM);
443 ass_set_style_overrides(ass->library, list);
446 /* Decode subtitles and push them into the renderer (libass) */
447 if (dec_ctx->subtitle_header)
448 ass_process_codec_private(ass->track,
449 dec_ctx->subtitle_header,
450 dec_ctx->subtitle_header_size);
451 while (av_read_frame(fmt, &pkt) >= 0) {
453 AVSubtitle sub = {0};
455 if (pkt.stream_index == sid) {
456 ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);
458 av_log(ctx, AV_LOG_WARNING, "Error decoding: %s (ignored)\n",
460 } else if (got_subtitle) {
461 const int64_t start_time = av_rescale_q(sub.pts, AV_TIME_BASE_Q, av_make_q(1, 1000));
462 const int64_t duration = sub.end_display_time;
463 for (i = 0; i < sub.num_rects; i++) {
464 char *ass_line = sub.rects[i]->ass;
467 ass_process_chunk(ass->track, ass_line, strlen(ass_line),
468 start_time, duration);
472 av_packet_unref(&pkt);
473 avsubtitle_free(&sub);
477 av_dict_free(&codec_opts);
478 avcodec_free_context(&dec_ctx);
479 avformat_close_input(&fmt);
483 AVFilter ff_vf_subtitles = {
485 .description = NULL_IF_CONFIG_SMALL("Render text subtitles onto input video using the libass library."),
486 .priv_size = sizeof(AssContext),
487 .init = init_subtitles,
489 .query_formats = query_formats,
490 .inputs = ass_inputs,
491 .outputs = ass_outputs,
492 .priv_class = &subtitles_class,