hls.py 7.9 KB

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