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