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;
55 int pix_step[4]; ///< steps per pixel for each plane of the main output
56 int original_w, original_h;
60 #define OFFSET(x) offsetof(AssContext, x)
61 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
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 }, \
68 /* libass supports a log level ranging from 0 to 7 */
69 static const int ass_libavfilter_log_level_map[] = {
74 AV_LOG_WARNING, /* 4 */
76 AV_LOG_VERBOSE, /* 6 */
80 static void ass_log(int ass_level, const char *fmt, va_list args, void *ctx)
82 int level = ass_libavfilter_log_level_map[ass_level];
84 av_vlog(ctx, level, fmt, args);
85 av_log(ctx, level, "\n");
88 static av_cold int init(AVFilterContext *ctx)
90 AssContext *ass = ctx->priv;
93 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
94 return AVERROR(EINVAL);
97 ass->library = ass_library_init();
99 av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
100 return AVERROR(EINVAL);
102 ass_set_message_cb(ass->library, ass_log, ctx);
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);
113 static av_cold void uninit(AVFilterContext *ctx)
115 AssContext *ass = ctx->priv;
118 ass_free_track(ass->track);
120 ass_renderer_done(ass->renderer);
122 ass_library_done(ass->library);
125 static int query_formats(AVFilterContext *ctx)
127 ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
131 static int config_input(AVFilterLink *inlink)
133 AssContext *ass = inlink->dst->priv;
135 ff_draw_init(&ass->draw, inlink->format, 0);
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);
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)
151 static void overlay_ass_image(AssContext *ass, AVFrame *picref,
152 const ASS_Image *image)
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);
166 static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
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);
177 av_log(ctx, AV_LOG_DEBUG, "Change happened at time ms:%f\n", time_ms);
179 overlay_ass_image(ass, picref, image);
181 return ff_filter_frame(outlink, picref);
184 static const AVFilterPad ass_inputs[] = {
187 .type = AVMEDIA_TYPE_VIDEO,
188 .filter_frame = filter_frame,
189 .config_props = config_input,
195 static const AVFilterPad ass_outputs[] = {
198 .type = AVMEDIA_TYPE_VIDEO,
203 #if CONFIG_ASS_FILTER
205 static const AVOption ass_options[] = {
210 AVFILTER_DEFINE_CLASS(ass);
212 static av_cold int init_ass(AVFilterContext *ctx)
214 AssContext *ass = ctx->priv;
220 /* Initialize fonts */
221 ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
223 ass->track = ass_read_file(ass->library, ass->filename, NULL);
225 av_log(ctx, AV_LOG_ERROR,
226 "Could not create a libass track when reading file '%s'\n",
228 return AVERROR(EINVAL);
233 AVFilter ff_vf_ass = {
235 .description = NULL_IF_CONFIG_SMALL("Render ASS subtitles onto input video using the libass library."),
236 .priv_size = sizeof(AssContext),
239 .query_formats = query_formats,
240 .inputs = ass_inputs,
241 .outputs = ass_outputs,
242 .priv_class = &ass_class,
246 #if CONFIG_SUBTITLES_FILTER
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},
254 static const char *font_mimetypes[] = {
255 "application/x-truetype-font",
256 "application/vnd.ms-opentype",
257 "application/x-font-ttf",
261 static int attachment_is_font(AVStream * st)
263 const AVDictionaryEntry *tag = NULL;
266 tag = av_dict_get(st->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE);
269 for (n = 0; font_mimetypes[n]; n++) {
270 if (av_strcasecmp(font_mimetypes[n], tag->value) == 0)
277 AVFILTER_DEFINE_CLASS(subtitles);
279 static av_cold int init_subtitles(AVFilterContext *ctx)
282 AVDictionary *codec_opts = NULL;
283 AVFormatContext *fmt = NULL;
284 AVCodecContext *dec_ctx = NULL;
286 const AVCodecDescriptor *dec_desc;
289 AssContext *ass = ctx->priv;
295 ass->track = ass_new_track(ass->library);
297 av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");
298 return AVERROR(EINVAL);
301 /* Open subtitles file */
302 ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);
304 av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);
307 ret = avformat_find_stream_info(fmt, NULL);
311 /* Locate subtitles stream */
312 ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);
314 av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",
319 st = fmt->streams[sid];
321 /* Load attached fonts */
322 for (j = 0; j < fmt->nb_streams; j++) {
323 AVStream *st = fmt->streams[j];
324 if (st->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT &&
325 attachment_is_font(st)) {
326 const AVDictionaryEntry *tag = NULL;
327 tag = av_dict_get(st->metadata, "filename", NULL,
331 av_log(ctx, AV_LOG_DEBUG, "Loading attached font: %s\n",
333 ass_add_font(ass->library, tag->value,
334 st->codec->extradata,
335 st->codec->extradata_size);
337 av_log(ctx, AV_LOG_WARNING,
338 "Font attachment has no filename, ignored.\n");
343 /* Initialize fonts */
344 ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
348 dec = avcodec_find_decoder(dec_ctx->codec_id);
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);
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;
361 av_dict_set(&codec_opts, "sub_charenc", ass->charenc, 0);
362 ret = avcodec_open2(dec_ctx, dec, &codec_opts);
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);
374 while (av_read_frame(fmt, &pkt) >= 0) {
376 AVSubtitle sub = {0};
378 if (pkt.stream_index == sid) {
379 ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);
381 av_log(ctx, AV_LOG_WARNING, "Error decoding: %s (ignored)\n",
383 } else if (got_subtitle) {
384 for (i = 0; i < sub.num_rects; i++) {
385 char *ass_line = sub.rects[i]->ass;
388 ass_process_data(ass->track, ass_line, strlen(ass_line));
392 av_free_packet(&pkt);
393 avsubtitle_free(&sub);
397 av_dict_free(&codec_opts);
399 avcodec_close(dec_ctx);
401 avformat_close_input(&fmt);
405 AVFilter ff_vf_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,
411 .query_formats = query_formats,
412 .inputs = ass_inputs,
413 .outputs = ass_outputs,
414 .priv_class = &subtitles_class,