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"
50 ASS_Renderer *renderer;
57 int pix_step[4]; ///< steps per pixel for each plane of the main output
58 int original_w, original_h;
63 #define OFFSET(x) offsetof(AssContext, x)
64 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
66 #define COMMON_OPTIONS \
67 {"filename", "set the filename of file to read", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS }, \
68 {"f", "set the filename of file to read", OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS }, \
69 {"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 }, \
71 /* libass supports a log level ranging from 0 to 7 */
72 static const int ass_libavfilter_log_level_map[] = {
73 [0] = AV_LOG_FATAL, /* MSGL_FATAL */
74 [1] = AV_LOG_ERROR, /* MSGL_ERR */
75 [2] = AV_LOG_WARNING, /* MSGL_WARN */
76 [3] = AV_LOG_WARNING, /* <undefined> */
77 [4] = AV_LOG_INFO, /* MSGL_INFO */
78 [5] = AV_LOG_INFO, /* <undefined> */
79 [6] = AV_LOG_VERBOSE, /* MSGL_V */
80 [7] = AV_LOG_DEBUG, /* MSGL_DBG2 */
83 static void ass_log(int ass_level, const char *fmt, va_list args, void *ctx)
85 const int ass_level_clip = av_clip(ass_level, 0,
86 FF_ARRAY_ELEMS(ass_libavfilter_log_level_map) - 1);
87 const int level = ass_libavfilter_log_level_map[ass_level_clip];
89 av_vlog(ctx, level, fmt, args);
90 av_log(ctx, level, "\n");
93 static av_cold int init(AVFilterContext *ctx)
95 AssContext *ass = ctx->priv;
98 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
99 return AVERROR(EINVAL);
102 ass->library = ass_library_init();
104 av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
105 return AVERROR(EINVAL);
107 ass_set_message_cb(ass->library, ass_log, ctx);
109 ass->renderer = ass_renderer_init(ass->library);
110 if (!ass->renderer) {
111 av_log(ctx, AV_LOG_ERROR, "Could not initialize libass renderer.\n");
112 return AVERROR(EINVAL);
118 static av_cold void uninit(AVFilterContext *ctx)
120 AssContext *ass = ctx->priv;
123 ass_free_track(ass->track);
125 ass_renderer_done(ass->renderer);
127 ass_library_done(ass->library);
130 static int query_formats(AVFilterContext *ctx)
132 ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
136 static int config_input(AVFilterLink *inlink)
138 AssContext *ass = inlink->dst->priv;
140 ff_draw_init(&ass->draw, inlink->format, 0);
142 ass_set_frame_size (ass->renderer, inlink->w, inlink->h);
143 if (ass->original_w && ass->original_h)
144 ass_set_aspect_ratio(ass->renderer, (double)inlink->w / inlink->h,
145 (double)ass->original_w / ass->original_h);
146 if (ass->shaping != -1)
147 ass_set_shaper(ass->renderer, ass->shaping);
152 /* libass stores an RGBA color in the format RRGGBBTT, where TT is the transparency level */
153 #define AR(c) ( (c)>>24)
154 #define AG(c) (((c)>>16)&0xFF)
155 #define AB(c) (((c)>>8) &0xFF)
156 #define AA(c) ((0xFF-(c)) &0xFF)
158 static void overlay_ass_image(AssContext *ass, AVFrame *picref,
159 const ASS_Image *image)
161 for (; image; image = image->next) {
162 uint8_t rgba_color[] = {AR(image->color), AG(image->color), AB(image->color), AA(image->color)};
164 ff_draw_color(&ass->draw, &color, rgba_color);
165 ff_blend_mask(&ass->draw, &color,
166 picref->data, picref->linesize,
167 picref->width, picref->height,
168 image->bitmap, image->stride, image->w, image->h,
169 3, 0, image->dst_x, image->dst_y);
173 static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
175 AVFilterContext *ctx = inlink->dst;
176 AVFilterLink *outlink = ctx->outputs[0];
177 AssContext *ass = ctx->priv;
178 int detect_change = 0;
179 double time_ms = picref->pts * av_q2d(inlink->time_base) * 1000;
180 ASS_Image *image = ass_render_frame(ass->renderer, ass->track,
181 time_ms, &detect_change);
184 av_log(ctx, AV_LOG_DEBUG, "Change happened at time ms:%f\n", time_ms);
186 overlay_ass_image(ass, picref, image);
188 return ff_filter_frame(outlink, picref);
191 static const AVFilterPad ass_inputs[] = {
194 .type = AVMEDIA_TYPE_VIDEO,
195 .filter_frame = filter_frame,
196 .config_props = config_input,
202 static const AVFilterPad ass_outputs[] = {
205 .type = AVMEDIA_TYPE_VIDEO,
210 #if CONFIG_ASS_FILTER
212 static const AVOption ass_options[] = {
214 {"shaping", "set shaping engine", OFFSET(shaping), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, FLAGS, "shaping_mode"},
215 {"auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = -1}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
216 {"simple", "simple shaping", 0, AV_OPT_TYPE_CONST, {.i64 = ASS_SHAPING_SIMPLE}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
217 {"complex", "complex shaping", 0, AV_OPT_TYPE_CONST, {.i64 = ASS_SHAPING_COMPLEX}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
221 AVFILTER_DEFINE_CLASS(ass);
223 static av_cold int init_ass(AVFilterContext *ctx)
225 AssContext *ass = ctx->priv;
231 /* Initialize fonts */
232 ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
234 ass->track = ass_read_file(ass->library, ass->filename, NULL);
236 av_log(ctx, AV_LOG_ERROR,
237 "Could not create a libass track when reading file '%s'\n",
239 return AVERROR(EINVAL);
244 AVFilter ff_vf_ass = {
246 .description = NULL_IF_CONFIG_SMALL("Render ASS subtitles onto input video using the libass library."),
247 .priv_size = sizeof(AssContext),
250 .query_formats = query_formats,
251 .inputs = ass_inputs,
252 .outputs = ass_outputs,
253 .priv_class = &ass_class,
257 #if CONFIG_SUBTITLES_FILTER
259 static const AVOption subtitles_options[] = {
261 {"charenc", "set input character encoding", OFFSET(charenc), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
262 {"stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS},
263 {"si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS},
264 {"force_style", "force subtitle style", OFFSET(force_style), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
268 static const char * const font_mimetypes[] = {
269 "application/x-truetype-font",
270 "application/vnd.ms-opentype",
271 "application/x-font-ttf",
275 static int attachment_is_font(AVStream * st)
277 const AVDictionaryEntry *tag = NULL;
280 tag = av_dict_get(st->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE);
283 for (n = 0; font_mimetypes[n]; n++) {
284 if (av_strcasecmp(font_mimetypes[n], tag->value) == 0)
291 AVFILTER_DEFINE_CLASS(subtitles);
293 static av_cold int init_subtitles(AVFilterContext *ctx)
297 AVDictionary *codec_opts = NULL;
298 AVFormatContext *fmt = NULL;
299 AVCodecContext *dec_ctx = NULL;
301 const AVCodecDescriptor *dec_desc;
304 AssContext *ass = ctx->priv;
310 ass->track = ass_new_track(ass->library);
312 av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");
313 return AVERROR(EINVAL);
316 /* Open subtitles file */
317 ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);
319 av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);
322 ret = avformat_find_stream_info(fmt, NULL);
326 /* Locate subtitles stream */
327 if (ass->stream_index < 0)
328 ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);
331 if (ass->stream_index < fmt->nb_streams) {
332 for (j = 0; j < fmt->nb_streams; j++) {
333 if (fmt->streams[j]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
334 if (ass->stream_index == k) {
345 av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",
350 st = fmt->streams[sid];
352 /* Load attached fonts */
353 for (j = 0; j < fmt->nb_streams; j++) {
354 AVStream *st = fmt->streams[j];
355 if (st->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT &&
356 attachment_is_font(st)) {
357 const AVDictionaryEntry *tag = NULL;
358 tag = av_dict_get(st->metadata, "filename", NULL,
362 av_log(ctx, AV_LOG_DEBUG, "Loading attached font: %s\n",
364 ass_add_font(ass->library, tag->value,
365 st->codec->extradata,
366 st->codec->extradata_size);
368 av_log(ctx, AV_LOG_WARNING,
369 "Font attachment has no filename, ignored.\n");
374 /* Initialize fonts */
375 ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
379 dec = avcodec_find_decoder(dec_ctx->codec_id);
381 av_log(ctx, AV_LOG_ERROR, "Failed to find subtitle codec %s\n",
382 avcodec_get_name(dec_ctx->codec_id));
383 return AVERROR(EINVAL);
385 dec_desc = avcodec_descriptor_get(dec_ctx->codec_id);
386 if (dec_desc && !(dec_desc->props & AV_CODEC_PROP_TEXT_SUB)) {
387 av_log(ctx, AV_LOG_ERROR,
388 "Only text based subtitles are currently supported\n");
389 return AVERROR_PATCHWELCOME;
392 av_dict_set(&codec_opts, "sub_charenc", ass->charenc, 0);
393 ret = avcodec_open2(dec_ctx, dec, &codec_opts);
397 if (ass->force_style) {
400 char *ptr = av_strtok(ass->force_style, ",", &temp);
403 av_dynarray_add(&list, &i, ptr);
405 ret = AVERROR(ENOMEM);
408 ptr = av_strtok(NULL, ",", &temp);
410 av_dynarray_add(&list, &i, NULL);
412 ret = AVERROR(ENOMEM);
415 ass_set_style_overrides(ass->library, list);
418 /* Decode subtitles and push them into the renderer (libass) */
419 if (dec_ctx->subtitle_header)
420 ass_process_codec_private(ass->track,
421 dec_ctx->subtitle_header,
422 dec_ctx->subtitle_header_size);
423 av_init_packet(&pkt);
426 while (av_read_frame(fmt, &pkt) >= 0) {
428 AVSubtitle sub = {0};
430 if (pkt.stream_index == sid) {
431 ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);
433 av_log(ctx, AV_LOG_WARNING, "Error decoding: %s (ignored)\n",
435 } else if (got_subtitle) {
436 for (i = 0; i < sub.num_rects; i++) {
437 char *ass_line = sub.rects[i]->ass;
440 ass_process_data(ass->track, ass_line, strlen(ass_line));
444 av_free_packet(&pkt);
445 avsubtitle_free(&sub);
449 av_dict_free(&codec_opts);
451 avcodec_close(dec_ctx);
453 avformat_close_input(&fmt);
457 AVFilter ff_vf_subtitles = {
459 .description = NULL_IF_CONFIG_SMALL("Render text subtitles onto input video using the libass library."),
460 .priv_size = sizeof(AssContext),
461 .init = init_subtitles,
463 .query_formats = query_formats,
464 .inputs = ass_inputs,
465 .outputs = ass_outputs,
466 .priv_class = &subtitles_class,