You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

417 lines
12KB

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