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.

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