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.

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