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.

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