vf_subtitles.c 16 KB

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