vf_subtitles.c 16 KB

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