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.

132 lines
5.4 KiB

  1. from __future__ import unicode_literals
  2. import os.path
  3. import re
  4. import binascii
  5. try:
  6. from Crypto.Cipher import AES
  7. can_decrypt_frag = True
  8. except ImportError:
  9. can_decrypt_frag = False
  10. from .fragment import FragmentFD
  11. from .external import FFmpegFD
  12. from ..compat import (
  13. compat_urlparse,
  14. compat_struct_pack,
  15. )
  16. from ..utils import (
  17. encodeFilename,
  18. sanitize_open,
  19. parse_m3u8_attributes,
  20. )
  21. class HlsFD(FragmentFD):
  22. """ A limited implementation that does not require ffmpeg """
  23. FD_NAME = 'hlsnative'
  24. @staticmethod
  25. def can_download(manifest):
  26. UNSUPPORTED_FEATURES = (
  27. r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]
  28. r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]
  29. # Live streams heuristic does not always work (e.g. geo restricted to Germany
  30. # http://hls-geo.daserste.de/i/videoportal/Film/c_620000/622873/format,716451,716457,716450,716458,716459,.mp4.csmil/index_4_av.m3u8?null=0)
  31. # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]
  32. # This heuristic also is not correct since segments may not be appended as well.
  33. # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite
  34. # no segments will definitely be appended to the end of the playlist.
  35. # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of
  36. # # event media playlists [4]
  37. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4
  38. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
  39. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2
  40. # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5
  41. )
  42. check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]
  43. check_results.append(can_decrypt_frag or '#EXT-X-KEY:METHOD=AES-128' not in manifest)
  44. return all(check_results)
  45. def real_download(self, filename, info_dict):
  46. man_url = info_dict['url']
  47. self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
  48. manifest = self.ydl.urlopen(man_url).read()
  49. s = manifest.decode('utf-8', 'ignore')
  50. if not self.can_download(s):
  51. self.report_warning(
  52. 'hlsnative has detected features it does not support, '
  53. 'extraction will be delegated to ffmpeg')
  54. fd = FFmpegFD(self.ydl, self.params)
  55. for ph in self._progress_hooks:
  56. fd.add_progress_hook(ph)
  57. return fd.real_download(filename, info_dict)
  58. total_frags = 0
  59. for line in s.splitlines():
  60. line = line.strip()
  61. if line and not line.startswith('#'):
  62. total_frags += 1
  63. ctx = {
  64. 'filename': filename,
  65. 'total_frags': total_frags,
  66. }
  67. self._prepare_and_start_frag_download(ctx)
  68. i = 0
  69. media_sequence = 0
  70. decrypt_info = {'METHOD': 'NONE'}
  71. frags_filenames = []
  72. for line in s.splitlines():
  73. line = line.strip()
  74. if line:
  75. if not line.startswith('#'):
  76. frag_url = (
  77. line
  78. if re.match(r'^https?://', line)
  79. else compat_urlparse.urljoin(man_url, line))
  80. frag_filename = '%s-Frag%d' % (ctx['tmpfilename'], i)
  81. success = ctx['dl'].download(frag_filename, {'url': frag_url})
  82. if not success:
  83. return False
  84. down, frag_sanitized = sanitize_open(frag_filename, 'rb')
  85. frag_content = down.read()
  86. down.close()
  87. if decrypt_info['METHOD'] == 'AES-128':
  88. iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
  89. frag_content = AES.new(
  90. decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
  91. ctx['dest_stream'].write(frag_content)
  92. frags_filenames.append(frag_sanitized)
  93. # We only download the first fragment during the test
  94. if self.params.get('test', False):
  95. break
  96. i += 1
  97. media_sequence += 1
  98. elif line.startswith('#EXT-X-KEY'):
  99. decrypt_info = parse_m3u8_attributes(line[11:])
  100. if decrypt_info['METHOD'] == 'AES-128':
  101. if 'IV' in decrypt_info:
  102. decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:])
  103. if not re.match(r'^https?://', decrypt_info['URI']):
  104. decrypt_info['URI'] = compat_urlparse.urljoin(
  105. man_url, decrypt_info['URI'])
  106. decrypt_info['KEY'] = self.ydl.urlopen(decrypt_info['URI']).read()
  107. elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
  108. media_sequence = int(line[22:])
  109. self._finish_frag_download(ctx)
  110. for frag_file in frags_filenames:
  111. os.remove(encodeFilename(frag_file))
  112. return True