vf_subtitles.c 15 KB

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