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.

168 lines
7.3 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):
  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. return all(check_results)
  47. def real_download(self, filename, info_dict):
  48. man_url = info_dict['url']
  49. self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
  50. manifest = self.ydl.urlopen(man_url).read()
  51. s = manifest.decode('utf-8', 'ignore')
  52. if not self.can_download(s):
  53. self.report_warning(
  54. 'hlsnative has detected features it does not support, '
  55. 'extraction will be delegated to ffmpeg')
  56. fd = FFmpegFD(self.ydl, self.params)
  57. for ph in self._progress_hooks:
  58. fd.add_progress_hook(ph)
  59. return fd.real_download(filename, info_dict)
  60. total_frags = 0
  61. for line in s.splitlines():
  62. line = line.strip()
  63. if line and not line.startswith('#'):
  64. total_frags += 1
  65. ctx = {
  66. 'filename': filename,
  67. 'total_frags': total_frags,
  68. }
  69. self._prepare_and_start_frag_download(ctx)
  70. fragment_retries = self.params.get('fragment_retries', 0)
  71. skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
  72. test = self.params.get('test', False)
  73. extra_query = None
  74. extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
  75. if extra_param_to_segment_url:
  76. extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
  77. i = 0
  78. media_sequence = 0
  79. decrypt_info = {'METHOD': 'NONE'}
  80. frags_filenames = []
  81. for line in s.splitlines():
  82. line = line.strip()
  83. if line:
  84. if not line.startswith('#'):
  85. frag_url = (
  86. line
  87. if re.match(r'^https?://', line)
  88. else compat_urlparse.urljoin(man_url, line))
  89. frag_name = 'Frag%d' % i
  90. frag_filename = '%s-%s' % (ctx['tmpfilename'], frag_name)
  91. if extra_query:
  92. frag_url = update_url_query(frag_url, extra_query)
  93. count = 0
  94. while count <= fragment_retries:
  95. try:
  96. success = ctx['dl'].download(frag_filename, {'url': frag_url})
  97. if not success:
  98. return False
  99. down, frag_sanitized = sanitize_open(frag_filename, 'rb')
  100. frag_content = down.read()
  101. down.close()
  102. break
  103. except compat_urllib_error.HTTPError as err:
  104. # Unavailable (possibly temporary) fragments may be served.
  105. # First we try to retry then either skip or abort.
  106. # See https://github.com/rg3/youtube-dl/issues/10165,
  107. # https://github.com/rg3/youtube-dl/issues/10448).
  108. count += 1
  109. if count <= fragment_retries:
  110. self.report_retry_fragment(err, frag_name, count, fragment_retries)
  111. if count > fragment_retries:
  112. if skip_unavailable_fragments:
  113. i += 1
  114. media_sequence += 1
  115. self.report_skip_fragment(frag_name)
  116. continue
  117. self.report_error(
  118. 'giving up after %s fragment retries' % fragment_retries)
  119. return False
  120. if decrypt_info['METHOD'] == 'AES-128':
  121. iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
  122. frag_content = AES.new(
  123. decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
  124. ctx['dest_stream'].write(frag_content)
  125. frags_filenames.append(frag_sanitized)
  126. # We only download the first fragment during the test
  127. if test:
  128. break
  129. i += 1
  130. media_sequence += 1
  131. elif line.startswith('#EXT-X-KEY'):
  132. decrypt_info = parse_m3u8_attributes(line[11:])
  133. if decrypt_info['METHOD'] == 'AES-128':
  134. if 'IV' in decrypt_info:
  135. decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
  136. if not re.match(r'^https?://', decrypt_info['URI']):
  137. decrypt_info['URI'] = compat_urlparse.urljoin(
  138. man_url, decrypt_info['URI'])
  139. if extra_query:
  140. decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
  141. decrypt_info['KEY'] = self.ydl.urlopen(decrypt_info['URI']).read()
  142. elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
  143. media_sequence = int(line[22:])
  144. self._finish_frag_download(ctx)
  145. for frag_file in frags_filenames:
  146. os.remove(encodeFilename(frag_file))
  147. return True