webvtt.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. """
  2. A partial parser for WebVTT segments. Interprets enough of the WebVTT stream
  3. to be able to assemble a single stand-alone subtitle file, suitably adjusting
  4. timestamps on the way, while everything else is passed through unmodified.
  5. Regular expressions based on the W3C WebVTT specification
  6. <https://www.w3.org/TR/webvtt1/>. The X-TIMESTAMP-MAP extension is described
  7. in RFC 8216 §3.5 <https://tools.ietf.org/html/rfc8216#section-3.5>.
  8. """
  9. import io
  10. import re
  11. from .utils import int_or_none, timetuple_from_msec
  12. class _MatchParser:
  13. """
  14. An object that maintains the current parsing position and allows
  15. conveniently advancing it as syntax elements are successfully parsed.
  16. """
  17. def __init__(self, string):
  18. self._data = string
  19. self._pos = 0
  20. def match(self, r):
  21. if isinstance(r, re.Pattern):
  22. return r.match(self._data, self._pos)
  23. if isinstance(r, str):
  24. if self._data.startswith(r, self._pos):
  25. return len(r)
  26. return None
  27. raise ValueError(r)
  28. def advance(self, by):
  29. if by is None:
  30. amt = 0
  31. elif isinstance(by, re.Match):
  32. amt = len(by.group(0))
  33. elif isinstance(by, str):
  34. amt = len(by)
  35. elif isinstance(by, int):
  36. amt = by
  37. else:
  38. raise ValueError(by)
  39. self._pos += amt
  40. return by
  41. def consume(self, r):
  42. return self.advance(self.match(r))
  43. def child(self):
  44. return _MatchChildParser(self)
  45. class _MatchChildParser(_MatchParser):
  46. """
  47. A child parser state, which advances through the same data as
  48. its parent, but has an independent position. This is useful when
  49. advancing through syntax elements we might later want to backtrack
  50. from.
  51. """
  52. def __init__(self, parent):
  53. super().__init__(parent._data)
  54. self.__parent = parent
  55. self._pos = parent._pos
  56. def commit(self):
  57. """
  58. Advance the parent state to the current position of this child state.
  59. """
  60. self.__parent._pos = self._pos
  61. return self.__parent
  62. class ParseError(Exception):
  63. def __init__(self, parser):
  64. data = parser._data[parser._pos:parser._pos + 100]
  65. super().__init__(f'Parse error at position {parser._pos} (near {data!r})')
  66. # While the specification <https://www.w3.org/TR/webvtt1/#webvtt-timestamp>
  67. # prescribes that hours must be *2 or more* digits, timestamps with a single
  68. # digit for the hour part has been seen in the wild.
  69. # See https://github.com/yt-dlp/yt-dlp/issues/921
  70. _REGEX_TS = re.compile(r'''(?x)
  71. (?:([0-9]{1,}):)?
  72. ([0-9]{2}):
  73. ([0-9]{2})\.
  74. ([0-9]{3})?
  75. ''')
  76. _REGEX_EOF = re.compile(r'\Z')
  77. _REGEX_NL = re.compile(r'(?:\r\n|[\r\n]|$)')
  78. _REGEX_BLANK = re.compile(r'(?:\r\n|[\r\n])+')
  79. _REGEX_OPTIONAL_WHITESPACE = re.compile(r'[ \t]*')
  80. def _parse_ts(ts):
  81. """
  82. Convert a parsed WebVTT timestamp (a re.Match obtained from _REGEX_TS)
  83. into an MPEG PES timestamp: a tick counter at 90 kHz resolution.
  84. """
  85. return 90 * sum(
  86. int(part or 0) * mult for part, mult in zip(ts.groups(), (3600_000, 60_000, 1000, 1)))
  87. def _format_ts(ts):
  88. """
  89. Convert an MPEG PES timestamp into a WebVTT timestamp.
  90. This will lose sub-millisecond precision.
  91. """
  92. return '%02u:%02u:%02u.%03u' % timetuple_from_msec(int((ts + 45) // 90))
  93. class Block:
  94. """
  95. An abstract WebVTT block.
  96. """
  97. def __init__(self, **kwargs):
  98. for key, val in kwargs.items():
  99. setattr(self, key, val)
  100. @classmethod
  101. def parse(cls, parser):
  102. m = parser.match(cls._REGEX)
  103. if not m:
  104. return None
  105. parser.advance(m)
  106. return cls(raw=m.group(0))
  107. def write_into(self, stream):
  108. stream.write(self.raw)
  109. class HeaderBlock(Block):
  110. """
  111. A WebVTT block that may only appear in the header part of the file,
  112. i.e. before any cue blocks.
  113. """
  114. pass
  115. class Magic(HeaderBlock):
  116. _REGEX = re.compile(r'\ufeff?WEBVTT([ \t][^\r\n]*)?(?:\r\n|[\r\n])')
  117. # XXX: The X-TIMESTAMP-MAP extension is described in RFC 8216 §3.5
  118. # <https://tools.ietf.org/html/rfc8216#section-3.5>, but the RFC
  119. # doesn't specify the exact grammar nor where in the WebVTT
  120. # syntax it should be placed; the below has been devised based
  121. # on usage in the wild
  122. #
  123. # And strictly speaking, the presence of this extension violates
  124. # the W3C WebVTT spec. Oh well.
  125. _REGEX_TSMAP = re.compile(r'X-TIMESTAMP-MAP=')
  126. _REGEX_TSMAP_LOCAL = re.compile(r'LOCAL:')
  127. _REGEX_TSMAP_MPEGTS = re.compile(r'MPEGTS:([0-9]+)')
  128. _REGEX_TSMAP_SEP = re.compile(r'[ \t]*,[ \t]*')
  129. # This was removed from the spec in the 2017 revision;
  130. # the last spec draft to describe this syntax element is
  131. # <https://www.w3.org/TR/2015/WD-webvtt1-20151208/#webvtt-metadata-header>.
  132. # Nevertheless, YouTube keeps serving those
  133. _REGEX_META = re.compile(r'(?:(?!-->)[^\r\n])+:(?:(?!-->)[^\r\n])+(?:\r\n|[\r\n])')
  134. @classmethod
  135. def __parse_tsmap(cls, parser):
  136. parser = parser.child()
  137. while True:
  138. m = parser.consume(cls._REGEX_TSMAP_LOCAL)
  139. if m:
  140. m = parser.consume(_REGEX_TS)
  141. if m is None:
  142. raise ParseError(parser)
  143. local = _parse_ts(m)
  144. if local is None:
  145. raise ParseError(parser)
  146. else:
  147. m = parser.consume(cls._REGEX_TSMAP_MPEGTS)
  148. if m:
  149. mpegts = int_or_none(m.group(1))
  150. if mpegts is None:
  151. raise ParseError(parser)
  152. else:
  153. raise ParseError(parser)
  154. if parser.consume(cls._REGEX_TSMAP_SEP):
  155. continue
  156. if parser.consume(_REGEX_NL):
  157. break
  158. raise ParseError(parser)
  159. parser.commit()
  160. return local, mpegts
  161. @classmethod
  162. def parse(cls, parser):
  163. parser = parser.child()
  164. m = parser.consume(cls._REGEX)
  165. if not m:
  166. raise ParseError(parser)
  167. extra = m.group(1)
  168. local, mpegts, meta = None, None, ''
  169. while not parser.consume(_REGEX_NL):
  170. if parser.consume(cls._REGEX_TSMAP):
  171. local, mpegts = cls.__parse_tsmap(parser)
  172. continue
  173. m = parser.consume(cls._REGEX_META)
  174. if m:
  175. meta += m.group(0)
  176. continue
  177. raise ParseError(parser)
  178. parser.commit()
  179. return cls(extra=extra, mpegts=mpegts, local=local, meta=meta)
  180. def write_into(self, stream):
  181. stream.write('WEBVTT')
  182. if self.extra is not None:
  183. stream.write(self.extra)
  184. stream.write('\n')
  185. if self.local or self.mpegts:
  186. stream.write('X-TIMESTAMP-MAP=LOCAL:')
  187. stream.write(_format_ts(self.local if self.local is not None else 0))
  188. stream.write(',MPEGTS:')
  189. stream.write(str(self.mpegts if self.mpegts is not None else 0))
  190. stream.write('\n')
  191. if self.meta:
  192. stream.write(self.meta)
  193. stream.write('\n')
  194. class StyleBlock(HeaderBlock):
  195. _REGEX = re.compile(r'''(?x)
  196. STYLE[\ \t]*(?:\r\n|[\r\n])
  197. ((?:(?!-->)[^\r\n])+(?:\r\n|[\r\n]))*
  198. (?:\r\n|[\r\n])
  199. ''')
  200. class RegionBlock(HeaderBlock):
  201. _REGEX = re.compile(r'''(?x)
  202. REGION[\ \t]*
  203. ((?:(?!-->)[^\r\n])+(?:\r\n|[\r\n]))*
  204. (?:\r\n|[\r\n])
  205. ''')
  206. class CommentBlock(Block):
  207. _REGEX = re.compile(r'''(?x)
  208. NOTE(?:\r\n|[\ \t\r\n])
  209. ((?:(?!-->)[^\r\n])+(?:\r\n|[\r\n]))*
  210. (?:\r\n|[\r\n])
  211. ''')
  212. class CueBlock(Block):
  213. """
  214. A cue block. The payload is not interpreted.
  215. """
  216. _REGEX_ID = re.compile(r'((?:(?!-->)[^\r\n])+)(?:\r\n|[\r\n])')
  217. _REGEX_ARROW = re.compile(r'[ \t]+-->[ \t]+')
  218. _REGEX_SETTINGS = re.compile(r'[ \t]+((?:(?!-->)[^\r\n])+)')
  219. _REGEX_PAYLOAD = re.compile(r'[^\r\n]+(?:\r\n|[\r\n])?')
  220. @classmethod
  221. def parse(cls, parser):
  222. parser = parser.child()
  223. id_ = None
  224. m = parser.consume(cls._REGEX_ID)
  225. if m:
  226. id_ = m.group(1)
  227. m0 = parser.consume(_REGEX_TS)
  228. if not m0:
  229. return None
  230. if not parser.consume(cls._REGEX_ARROW):
  231. return None
  232. m1 = parser.consume(_REGEX_TS)
  233. if not m1:
  234. return None
  235. m2 = parser.consume(cls._REGEX_SETTINGS)
  236. parser.consume(_REGEX_OPTIONAL_WHITESPACE)
  237. if not parser.consume(_REGEX_NL):
  238. return None
  239. start = _parse_ts(m0)
  240. end = _parse_ts(m1)
  241. settings = m2.group(1) if m2 is not None else None
  242. text = io.StringIO()
  243. while True:
  244. m = parser.consume(cls._REGEX_PAYLOAD)
  245. if not m:
  246. break
  247. text.write(m.group(0))
  248. parser.commit()
  249. return cls(
  250. id=id_,
  251. start=start, end=end, settings=settings,
  252. text=text.getvalue(),
  253. )
  254. def write_into(self, stream):
  255. if self.id is not None:
  256. stream.write(self.id)
  257. stream.write('\n')
  258. stream.write(_format_ts(self.start))
  259. stream.write(' --> ')
  260. stream.write(_format_ts(self.end))
  261. if self.settings is not None:
  262. stream.write(' ')
  263. stream.write(self.settings)
  264. stream.write('\n')
  265. stream.write(self.text)
  266. stream.write('\n')
  267. @property
  268. def as_json(self):
  269. return {
  270. 'id': self.id,
  271. 'start': self.start,
  272. 'end': self.end,
  273. 'text': self.text,
  274. 'settings': self.settings,
  275. }
  276. def __eq__(self, other):
  277. return self.as_json == other.as_json
  278. @classmethod
  279. def from_json(cls, json):
  280. return cls(
  281. id=json['id'],
  282. start=json['start'],
  283. end=json['end'],
  284. text=json['text'],
  285. settings=json['settings'],
  286. )
  287. def hinges(self, other):
  288. if self.text != other.text:
  289. return False
  290. if self.settings != other.settings:
  291. return False
  292. return self.start <= self.end == other.start <= other.end
  293. def parse_fragment(frag_content):
  294. """
  295. A generator that yields (partially) parsed WebVTT blocks when given
  296. a bytes object containing the raw contents of a WebVTT file.
  297. """
  298. parser = _MatchParser(frag_content.decode())
  299. yield Magic.parse(parser)
  300. while not parser.match(_REGEX_EOF):
  301. if parser.consume(_REGEX_BLANK):
  302. continue
  303. block = RegionBlock.parse(parser)
  304. if block:
  305. yield block
  306. continue
  307. block = StyleBlock.parse(parser)
  308. if block:
  309. yield block
  310. continue
  311. block = CommentBlock.parse(parser)
  312. if block:
  313. yield block # XXX: or skip
  314. continue
  315. break
  316. while not parser.match(_REGEX_EOF):
  317. if parser.consume(_REGEX_BLANK):
  318. continue
  319. block = CommentBlock.parse(parser)
  320. if block:
  321. yield block # XXX: or skip
  322. continue
  323. block = CueBlock.parse(parser)
  324. if block:
  325. yield block
  326. continue
  327. raise ParseError(parser)