00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00028 #include "avcodec.h"
00029 #include "ass.h"
00030 #include "libavutil/bprint.h"
00031
00032 static const struct {
00033 const char *from;
00034 const char *to;
00035 } webvtt_tag_replace[] = {
00036 {"<i>", "{\\i1}"}, {"</i>", "{\\i0}"},
00037 {"<b>", "{\\b1}"}, {"</b>", "{\\b0}"},
00038 {"<u>", "{\\u1}"}, {"</u>", "{\\u0}"},
00039 {"{", "\\{"}, {"}", "\\}"},
00040 };
00041
00042 static int webvtt_event_to_ass(AVBPrint *buf, const char *p)
00043 {
00044 int i, skip = 0;
00045
00046 while (*p) {
00047
00048 for (i = 0; i < FF_ARRAY_ELEMS(webvtt_tag_replace); i++) {
00049 const char *from = webvtt_tag_replace[i].from;
00050 const size_t len = strlen(from);
00051 if (!strncmp(p, from, len)) {
00052 av_bprintf(buf, "%s", webvtt_tag_replace[i].to);
00053 p += len;
00054 break;
00055 }
00056 }
00057 if (!*p)
00058 break;
00059
00060 if (*p == '<')
00061 skip = 1;
00062 else if (*p == '>')
00063 skip = 0;
00064 else if (p[0] == '\n' && p[1])
00065 av_bprintf(buf, "\\N");
00066 else if (!skip && *p != '\r')
00067 av_bprint_chars(buf, *p, 1);
00068 p++;
00069 }
00070 av_bprintf(buf, "\r\n");
00071 return 0;
00072 }
00073
00074 static int webvtt_decode_frame(AVCodecContext *avctx,
00075 void *data, int *got_sub_ptr, AVPacket *avpkt)
00076 {
00077 AVSubtitle *sub = data;
00078 const char *ptr = avpkt->data;
00079 AVBPrint buf;
00080
00081 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
00082 if (ptr && avpkt->size > 0 && !webvtt_event_to_ass(&buf, ptr)) {
00083 int ts_start = av_rescale_q(avpkt->pts, avctx->time_base, (AVRational){1,100});
00084 int ts_duration = avpkt->duration != -1 ?
00085 av_rescale_q(avpkt->duration, avctx->time_base, (AVRational){1,100}) : -1;
00086 ff_ass_add_rect(sub, buf.str, ts_start, ts_duration, 0);
00087 }
00088 *got_sub_ptr = sub->num_rects > 0;
00089 av_bprint_finalize(&buf, NULL);
00090 return avpkt->size;
00091 }
00092
00093 AVCodec ff_webvtt_decoder = {
00094 .name = "webvtt",
00095 .long_name = NULL_IF_CONFIG_SMALL("WebVTT subtitle"),
00096 .type = AVMEDIA_TYPE_SUBTITLE,
00097 .id = AV_CODEC_ID_WEBVTT,
00098 .decode = webvtt_decode_frame,
00099 .init = ff_ass_subtitle_header_default,
00100 };