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.

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