logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

hls.py (10181B)


  1. from __future__ import unicode_literals
  2. import re
  3. import binascii
  4. try:
  5. from Crypto.Cipher import AES
  6. can_decrypt_frag = True
  7. except ImportError:
  8. can_decrypt_frag = False
  9. from .fragment import FragmentFD
  10. from .external import FFmpegFD
  11. from ..compat import (
  12. compat_urllib_error,
  13. compat_urlparse,
  14. compat_struct_pack,
  15. )
  16. from ..utils import (
  17. parse_m3u8_attributes,
  18. update_url_query,
  19. )
  20. class HlsFD(FragmentFD):
  21. """ A limited implementation that does not require ffmpeg """
  22. FD_NAME = 'hlsnative'
  23. @staticmethod
  24. def can_download(manifest, info_dict):
  25. UNSUPPORTED_FEATURES = (
  26. r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]
  27. # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]
  28. # Live streams heuristic does not always work (e.g. geo restricted to Germany
  29. # 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)
  30. # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]
  31. # This heuristic also is not correct since segments may not be appended as well.
  32. # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite
  33. # no segments will definitely be appended to the end of the playlist.
  34. # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of
  35. # # event media playlists [4]
  36. r'#EXT-X-MAP:', # media initialization [5]
  37. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4
  38. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
  39. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2
  40. # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5
  41. # 5. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.5
  42. )
  43. check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]
  44. is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest
  45. check_results.append(can_decrypt_frag or not is_aes128_enc)
  46. check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest))
  47. check_results.append(not info_dict.get('is_live'))
  48. return all(check_results)
  49. def real_download(self, filename, info_dict):
  50. man_url = info_dict['url']
  51. self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
  52. urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))
  53. man_url = urlh.geturl()
  54. s = urlh.read().decode('utf-8', 'ignore')
  55. if not self.can_download(s, info_dict):
  56. if info_dict.get('extra_param_to_segment_url') or info_dict.get('_decryption_key_url'):
  57. self.report_error('pycrypto not found. Please install it.')
  58. return False
  59. self.report_warning(
  60. 'hlsnative has detected features it does not support, '
  61. 'extraction will be delegated to ffmpeg')
  62. fd = FFmpegFD(self.ydl, self.params)
  63. for ph in self._progress_hooks:
  64. fd.add_progress_hook(ph)
  65. return fd.real_download(filename, info_dict)
  66. def is_ad_fragment_start(s):
  67. return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s
  68. or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad'))
  69. def is_ad_fragment_end(s):
  70. return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s
  71. or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment'))
  72. media_frags = 0
  73. ad_frags = 0
  74. ad_frag_next = False
  75. for line in s.splitlines():
  76. line = line.strip()
  77. if not line:
  78. continue
  79. if line.startswith('#'):
  80. if is_ad_fragment_start(line):
  81. ad_frag_next = True
  82. elif is_ad_fragment_end(line):
  83. ad_frag_next = False
  84. continue
  85. if ad_frag_next:
  86. ad_frags += 1
  87. continue
  88. media_frags += 1
  89. ctx = {
  90. 'filename': filename,
  91. 'total_frags': media_frags,
  92. 'ad_frags': ad_frags,
  93. }
  94. self._prepare_and_start_frag_download(ctx)
  95. fragment_retries = self.params.get('fragment_retries', 0)
  96. skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
  97. test = self.params.get('test', False)
  98. extra_query = None
  99. extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
  100. if extra_param_to_segment_url:
  101. extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
  102. i = 0
  103. media_sequence = 0
  104. decrypt_info = {'METHOD': 'NONE'}
  105. byte_range = {}
  106. frag_index = 0
  107. ad_frag_next = False
  108. for line in s.splitlines():
  109. line = line.strip()
  110. if line:
  111. if not line.startswith('#'):
  112. if ad_frag_next:
  113. continue
  114. frag_index += 1
  115. if frag_index <= ctx['fragment_index']:
  116. continue
  117. frag_url = (
  118. line
  119. if re.match(r'^https?://', line)
  120. else compat_urlparse.urljoin(man_url, line))
  121. if extra_query:
  122. frag_url = update_url_query(frag_url, extra_query)
  123. count = 0
  124. headers = info_dict.get('http_headers', {})
  125. if byte_range:
  126. headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
  127. while count <= fragment_retries:
  128. try:
  129. success, frag_content = self._download_fragment(
  130. ctx, frag_url, info_dict, headers)
  131. if not success:
  132. return False
  133. break
  134. except compat_urllib_error.HTTPError as err:
  135. # Unavailable (possibly temporary) fragments may be served.
  136. # First we try to retry then either skip or abort.
  137. # See https://github.com/ytdl-org/youtube-dl/issues/10165,
  138. # https://github.com/ytdl-org/youtube-dl/issues/10448).
  139. count += 1
  140. if count <= fragment_retries:
  141. self.report_retry_fragment(err, frag_index, count, fragment_retries)
  142. if count > fragment_retries:
  143. if skip_unavailable_fragments:
  144. i += 1
  145. media_sequence += 1
  146. self.report_skip_fragment(frag_index)
  147. continue
  148. self.report_error(
  149. 'giving up after %s fragment retries' % fragment_retries)
  150. return False
  151. if decrypt_info['METHOD'] == 'AES-128':
  152. iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
  153. decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen(
  154. self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read()
  155. # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
  156. # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
  157. # not what it decrypts to.
  158. if not test:
  159. frag_content = AES.new(
  160. decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
  161. self._append_fragment(ctx, frag_content)
  162. # We only download the first fragment during the test
  163. if test:
  164. break
  165. i += 1
  166. media_sequence += 1
  167. elif line.startswith('#EXT-X-KEY'):
  168. decrypt_url = decrypt_info.get('URI')
  169. decrypt_info = parse_m3u8_attributes(line[11:])
  170. if decrypt_info['METHOD'] == 'AES-128':
  171. if 'IV' in decrypt_info:
  172. decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
  173. if not re.match(r'^https?://', decrypt_info['URI']):
  174. decrypt_info['URI'] = compat_urlparse.urljoin(
  175. man_url, decrypt_info['URI'])
  176. if extra_query:
  177. decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
  178. if decrypt_url != decrypt_info['URI']:
  179. decrypt_info['KEY'] = None
  180. elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
  181. media_sequence = int(line[22:])
  182. elif line.startswith('#EXT-X-BYTERANGE'):
  183. splitted_byte_range = line[17:].split('@')
  184. sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']
  185. byte_range = {
  186. 'start': sub_range_start,
  187. 'end': sub_range_start + int(splitted_byte_range[0]),
  188. }
  189. elif is_ad_fragment_start(line):
  190. ad_frag_next = True
  191. elif is_ad_fragment_end(line):
  192. ad_frag_next = False
  193. self._finish_frag_download(ctx)
  194. return True