• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "config_components.h"
34 #if CONFIG_SUBTITLES_FILTER
35 # include "libavcodec/avcodec.h"
36 # include "libavformat/avformat.h"
37 #endif
38 #include "libavutil/avstring.h"
39 #include "libavutil/imgutils.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/parseutils.h"
42 #include "drawutils.h"
43 #include "avfilter.h"
44 #include "internal.h"
45 #include "formats.h"
46 #include "video.h"
47 
48 typedef struct AssContext {
49     const AVClass *class;
50     ASS_Library  *library;
51     ASS_Renderer *renderer;
52     ASS_Track    *track;
53     char *filename;
54     char *fontsdir;
55     char *charenc;
56     char *force_style;
57     int stream_index;
58     int alpha;
59     uint8_t rgba_map[4];
60     int     pix_step[4];       ///< steps per pixel for each plane of the main output
61     int original_w, original_h;
62     int shaping;
63     FFDrawContext draw;
64 } AssContext;
65 
66 #define OFFSET(x) offsetof(AssContext, x)
67 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
68 
69 #define COMMON_OPTIONS \
70     {"filename",       "set the filename of file to read",                         OFFSET(filename),   AV_OPT_TYPE_STRING,     {.str = NULL},  0, 0, FLAGS }, \
71     {"f",              "set the filename of file to read",                         OFFSET(filename),   AV_OPT_TYPE_STRING,     {.str = NULL},  0, 0, FLAGS }, \
72     {"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 }, \
73     {"fontsdir",       "set the directory containing the fonts to read",           OFFSET(fontsdir),   AV_OPT_TYPE_STRING,     {.str = NULL},  0, 0, FLAGS }, \
74     {"alpha",          "enable processing of alpha channel",                       OFFSET(alpha),      AV_OPT_TYPE_BOOL,       {.i64 = 0   },         0,        1, FLAGS }, \
75 
76 /* libass supports a log level ranging from 0 to 7 */
77 static const int ass_libavfilter_log_level_map[] = {
78     [0] = AV_LOG_FATAL,     /* MSGL_FATAL */
79     [1] = AV_LOG_ERROR,     /* MSGL_ERR */
80     [2] = AV_LOG_WARNING,   /* MSGL_WARN */
81     [3] = AV_LOG_WARNING,   /* <undefined> */
82     [4] = AV_LOG_INFO,      /* MSGL_INFO */
83     [5] = AV_LOG_INFO,      /* <undefined> */
84     [6] = AV_LOG_VERBOSE,   /* MSGL_V */
85     [7] = AV_LOG_DEBUG,     /* MSGL_DBG2 */
86 };
87 
ass_log(int ass_level,const char * fmt,va_list args,void * ctx)88 static void ass_log(int ass_level, const char *fmt, va_list args, void *ctx)
89 {
90     const int ass_level_clip = av_clip(ass_level, 0,
91         FF_ARRAY_ELEMS(ass_libavfilter_log_level_map) - 1);
92     const int level = ass_libavfilter_log_level_map[ass_level_clip];
93 
94     av_vlog(ctx, level, fmt, args);
95     av_log(ctx, level, "\n");
96 }
97 
init(AVFilterContext * ctx)98 static av_cold int init(AVFilterContext *ctx)
99 {
100     AssContext *ass = ctx->priv;
101 
102     if (!ass->filename) {
103         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
104         return AVERROR(EINVAL);
105     }
106 
107     ass->library = ass_library_init();
108     if (!ass->library) {
109         av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
110         return AVERROR(EINVAL);
111     }
112     ass_set_message_cb(ass->library, ass_log, ctx);
113 
114     ass_set_fonts_dir(ass->library, ass->fontsdir);
115     ass_set_extract_fonts(ass->library, 1);
116 
117     ass->renderer = ass_renderer_init(ass->library);
118     if (!ass->renderer) {
119         av_log(ctx, AV_LOG_ERROR, "Could not initialize libass renderer.\n");
120         return AVERROR(EINVAL);
121     }
122 
123     return 0;
124 }
125 
uninit(AVFilterContext * ctx)126 static av_cold void uninit(AVFilterContext *ctx)
127 {
128     AssContext *ass = ctx->priv;
129 
130     if (ass->track)
131         ass_free_track(ass->track);
132     if (ass->renderer)
133         ass_renderer_done(ass->renderer);
134     if (ass->library)
135         ass_library_done(ass->library);
136 }
137 
query_formats(AVFilterContext * ctx)138 static int query_formats(AVFilterContext *ctx)
139 {
140     return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
141 }
142 
config_input(AVFilterLink * inlink)143 static int config_input(AVFilterLink *inlink)
144 {
145     AssContext *ass = inlink->dst->priv;
146 
147     ff_draw_init(&ass->draw, inlink->format, ass->alpha ? FF_DRAW_PROCESS_ALPHA : 0);
148 
149     ass_set_frame_size  (ass->renderer, inlink->w, inlink->h);
150     if (ass->original_w && ass->original_h) {
151         ass_set_pixel_aspect(ass->renderer, (double)inlink->w / inlink->h /
152                              ((double)ass->original_w / ass->original_h));
153         ass_set_storage_size(ass->renderer, ass->original_w, ass->original_h);
154     } else
155         ass_set_storage_size(ass->renderer, inlink->w, inlink->h);
156 
157     if (ass->shaping != -1)
158         ass_set_shaper(ass->renderer, ass->shaping);
159 
160     return 0;
161 }
162 
163 /* libass stores an RGBA color in the format RRGGBBTT, where TT is the transparency level */
164 #define AR(c)  ( (c)>>24)
165 #define AG(c)  (((c)>>16)&0xFF)
166 #define AB(c)  (((c)>>8) &0xFF)
167 #define AA(c)  ((0xFF-(c)) &0xFF)
168 
overlay_ass_image(AssContext * ass,AVFrame * picref,const ASS_Image * image)169 static void overlay_ass_image(AssContext *ass, AVFrame *picref,
170                               const ASS_Image *image)
171 {
172     for (; image; image = image->next) {
173         uint8_t rgba_color[] = {AR(image->color), AG(image->color), AB(image->color), AA(image->color)};
174         FFDrawColor color;
175         ff_draw_color(&ass->draw, &color, rgba_color);
176         ff_blend_mask(&ass->draw, &color,
177                       picref->data, picref->linesize,
178                       picref->width, picref->height,
179                       image->bitmap, image->stride, image->w, image->h,
180                       3, 0, image->dst_x, image->dst_y);
181     }
182 }
183 
filter_frame(AVFilterLink * inlink,AVFrame * picref)184 static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
185 {
186     AVFilterContext *ctx = inlink->dst;
187     AVFilterLink *outlink = ctx->outputs[0];
188     AssContext *ass = ctx->priv;
189     int detect_change = 0;
190     double time_ms = picref->pts * av_q2d(inlink->time_base) * 1000;
191     ASS_Image *image = ass_render_frame(ass->renderer, ass->track,
192                                         time_ms, &detect_change);
193 
194     if (detect_change)
195         av_log(ctx, AV_LOG_DEBUG, "Change happened at time ms:%f\n", time_ms);
196 
197     overlay_ass_image(ass, picref, image);
198 
199     return ff_filter_frame(outlink, picref);
200 }
201 
202 static const AVFilterPad ass_inputs[] = {
203     {
204         .name             = "default",
205         .type             = AVMEDIA_TYPE_VIDEO,
206         .flags            = AVFILTERPAD_FLAG_NEEDS_WRITABLE,
207         .filter_frame     = filter_frame,
208         .config_props     = config_input,
209     },
210 };
211 
212 static const AVFilterPad ass_outputs[] = {
213     {
214         .name = "default",
215         .type = AVMEDIA_TYPE_VIDEO,
216     },
217 };
218 
219 #if CONFIG_ASS_FILTER
220 
221 static const AVOption ass_options[] = {
222     COMMON_OPTIONS
223     {"shaping", "set shaping engine", OFFSET(shaping), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, FLAGS, "shaping_mode"},
224         {"auto", NULL,                 0, AV_OPT_TYPE_CONST, {.i64 = -1},                  INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
225         {"simple",  "simple shaping",  0, AV_OPT_TYPE_CONST, {.i64 = ASS_SHAPING_SIMPLE},  INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
226         {"complex", "complex shaping", 0, AV_OPT_TYPE_CONST, {.i64 = ASS_SHAPING_COMPLEX}, INT_MIN, INT_MAX, FLAGS, "shaping_mode"},
227     {NULL},
228 };
229 
230 AVFILTER_DEFINE_CLASS(ass);
231 
init_ass(AVFilterContext * ctx)232 static av_cold int init_ass(AVFilterContext *ctx)
233 {
234     AssContext *ass = ctx->priv;
235     int ret = init(ctx);
236 
237     if (ret < 0)
238         return ret;
239 
240     /* Initialize fonts */
241     ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
242 
243     ass->track = ass_read_file(ass->library, ass->filename, NULL);
244     if (!ass->track) {
245         av_log(ctx, AV_LOG_ERROR,
246                "Could not create a libass track when reading file '%s'\n",
247                ass->filename);
248         return AVERROR(EINVAL);
249     }
250     return 0;
251 }
252 
253 const AVFilter ff_vf_ass = {
254     .name          = "ass",
255     .description   = NULL_IF_CONFIG_SMALL("Render ASS subtitles onto input video using the libass library."),
256     .priv_size     = sizeof(AssContext),
257     .init          = init_ass,
258     .uninit        = uninit,
259     FILTER_INPUTS(ass_inputs),
260     FILTER_OUTPUTS(ass_outputs),
261     FILTER_QUERY_FUNC(query_formats),
262     .priv_class    = &ass_class,
263 };
264 #endif
265 
266 #if CONFIG_SUBTITLES_FILTER
267 
268 static const AVOption subtitles_options[] = {
269     COMMON_OPTIONS
270     {"charenc",      "set input character encoding", OFFSET(charenc),      AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
271     {"stream_index", "set stream index",             OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1,       INT_MAX,  FLAGS},
272     {"si",           "set stream index",             OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1,       INT_MAX,  FLAGS},
273     {"force_style",  "force subtitle style",         OFFSET(force_style),  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
274     {NULL},
275 };
276 
277 static const char * const font_mimetypes[] = {
278     "font/ttf",
279     "font/otf",
280     "font/sfnt",
281     "font/woff",
282     "font/woff2",
283     "application/font-sfnt",
284     "application/font-woff",
285     "application/x-truetype-font",
286     "application/vnd.ms-opentype",
287     "application/x-font-ttf",
288     NULL
289 };
290 
attachment_is_font(AVStream * st)291 static int attachment_is_font(AVStream * st)
292 {
293     const AVDictionaryEntry *tag = NULL;
294     int n;
295 
296     tag = av_dict_get(st->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE);
297 
298     if (tag) {
299         for (n = 0; font_mimetypes[n]; n++) {
300             if (av_strcasecmp(font_mimetypes[n], tag->value) == 0)
301                 return 1;
302         }
303     }
304     return 0;
305 }
306 
307 AVFILTER_DEFINE_CLASS(subtitles);
308 
init_subtitles(AVFilterContext * ctx)309 static av_cold int init_subtitles(AVFilterContext *ctx)
310 {
311     int j, ret, sid;
312     int k = 0;
313     AVDictionary *codec_opts = NULL;
314     AVFormatContext *fmt = NULL;
315     AVCodecContext *dec_ctx = NULL;
316     const AVCodec *dec;
317     const AVCodecDescriptor *dec_desc;
318     AVStream *st;
319     AVPacket pkt;
320     AssContext *ass = ctx->priv;
321 
322     /* Init libass */
323     ret = init(ctx);
324     if (ret < 0)
325         return ret;
326     ass->track = ass_new_track(ass->library);
327     if (!ass->track) {
328         av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");
329         return AVERROR(EINVAL);
330     }
331 
332     /* Open subtitles file */
333     ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);
334     if (ret < 0) {
335         av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);
336         goto end;
337     }
338     ret = avformat_find_stream_info(fmt, NULL);
339     if (ret < 0)
340         goto end;
341 
342     /* Locate subtitles stream */
343     if (ass->stream_index < 0)
344         ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);
345     else {
346         ret = -1;
347         if (ass->stream_index < fmt->nb_streams) {
348             for (j = 0; j < fmt->nb_streams; j++) {
349                 if (fmt->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
350                     if (ass->stream_index == k) {
351                         ret = j;
352                         break;
353                     }
354                     k++;
355                 }
356             }
357         }
358     }
359 
360     if (ret < 0) {
361         av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",
362                ass->filename);
363         goto end;
364     }
365     sid = ret;
366     st = fmt->streams[sid];
367 
368     /* Load attached fonts */
369     for (j = 0; j < fmt->nb_streams; j++) {
370         AVStream *st = fmt->streams[j];
371         if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT &&
372             attachment_is_font(st)) {
373             const AVDictionaryEntry *tag = NULL;
374             tag = av_dict_get(st->metadata, "filename", NULL,
375                               AV_DICT_MATCH_CASE);
376 
377             if (tag) {
378                 av_log(ctx, AV_LOG_DEBUG, "Loading attached font: %s\n",
379                        tag->value);
380                 ass_add_font(ass->library, tag->value,
381                              st->codecpar->extradata,
382                              st->codecpar->extradata_size);
383             } else {
384                 av_log(ctx, AV_LOG_WARNING,
385                        "Font attachment has no filename, ignored.\n");
386             }
387         }
388     }
389 
390     /* Initialize fonts */
391     ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);
392 
393     /* Open decoder */
394     dec = avcodec_find_decoder(st->codecpar->codec_id);
395     if (!dec) {
396         av_log(ctx, AV_LOG_ERROR, "Failed to find subtitle codec %s\n",
397                avcodec_get_name(st->codecpar->codec_id));
398         ret = AVERROR_DECODER_NOT_FOUND;
399         goto end;
400     }
401     dec_desc = avcodec_descriptor_get(st->codecpar->codec_id);
402     if (dec_desc && !(dec_desc->props & AV_CODEC_PROP_TEXT_SUB)) {
403         av_log(ctx, AV_LOG_ERROR,
404                "Only text based subtitles are currently supported\n");
405         ret = AVERROR_PATCHWELCOME;
406         goto end;
407     }
408     if (ass->charenc)
409         av_dict_set(&codec_opts, "sub_charenc", ass->charenc, 0);
410 
411     dec_ctx = avcodec_alloc_context3(dec);
412     if (!dec_ctx) {
413         ret = AVERROR(ENOMEM);
414         goto end;
415     }
416 
417     ret = avcodec_parameters_to_context(dec_ctx, st->codecpar);
418     if (ret < 0)
419         goto end;
420 
421     /*
422      * This is required by the decoding process in order to rescale the
423      * timestamps: in the current API the decoded subtitles have their pts
424      * expressed in AV_TIME_BASE, and thus the lavc internals need to know the
425      * stream time base in order to achieve the rescaling.
426      *
427      * That API is old and needs to be reworked to match behaviour with A/V.
428      */
429     dec_ctx->pkt_timebase = st->time_base;
430 
431     ret = avcodec_open2(dec_ctx, NULL, &codec_opts);
432     if (ret < 0)
433         goto end;
434 
435     if (ass->force_style) {
436         char **list = NULL;
437         char *temp = NULL;
438         char *ptr = av_strtok(ass->force_style, ",", &temp);
439         int i = 0;
440         while (ptr) {
441             av_dynarray_add(&list, &i, ptr);
442             if (!list) {
443                 ret = AVERROR(ENOMEM);
444                 goto end;
445             }
446             ptr = av_strtok(NULL, ",", &temp);
447         }
448         av_dynarray_add(&list, &i, NULL);
449         if (!list) {
450             ret = AVERROR(ENOMEM);
451             goto end;
452         }
453         ass_set_style_overrides(ass->library, list);
454         av_free(list);
455     }
456     /* Decode subtitles and push them into the renderer (libass) */
457     if (dec_ctx->subtitle_header)
458         ass_process_codec_private(ass->track,
459                                   dec_ctx->subtitle_header,
460                                   dec_ctx->subtitle_header_size);
461     while (av_read_frame(fmt, &pkt) >= 0) {
462         int i, got_subtitle;
463         AVSubtitle sub = {0};
464 
465         if (pkt.stream_index == sid) {
466             ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);
467             if (ret < 0) {
468                 av_log(ctx, AV_LOG_WARNING, "Error decoding: %s (ignored)\n",
469                        av_err2str(ret));
470             } else if (got_subtitle) {
471                 const int64_t start_time = av_rescale_q(sub.pts, AV_TIME_BASE_Q, av_make_q(1, 1000));
472                 const int64_t duration   = sub.end_display_time;
473                 for (i = 0; i < sub.num_rects; i++) {
474                     char *ass_line = sub.rects[i]->ass;
475                     if (!ass_line)
476                         break;
477                     ass_process_chunk(ass->track, ass_line, strlen(ass_line),
478                                       start_time, duration);
479                 }
480             }
481         }
482         av_packet_unref(&pkt);
483         avsubtitle_free(&sub);
484     }
485 
486 end:
487     av_dict_free(&codec_opts);
488     avcodec_free_context(&dec_ctx);
489     avformat_close_input(&fmt);
490     return ret;
491 }
492 
493 const AVFilter ff_vf_subtitles = {
494     .name          = "subtitles",
495     .description   = NULL_IF_CONFIG_SMALL("Render text subtitles onto input video using the libass library."),
496     .priv_size     = sizeof(AssContext),
497     .init          = init_subtitles,
498     .uninit        = uninit,
499     FILTER_INPUTS(ass_inputs),
500     FILTER_OUTPUTS(ass_outputs),
501     FILTER_QUERY_FUNC(query_formats),
502     .priv_class    = &subtitles_class,
503 };
504 #endif
505