vf_subtitles.c 14 KB

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