]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/hls.py
[docs,build] Change all pycryptodome references to pycryptodomex
[yt-dlp.git] / yt_dlp / downloader / hls.py
CommitLineData
f0b5d6af
PH
1from __future__ import unicode_literals
2
f0b5d6af 3import re
4a2f19ab 4import io
e154c651 5import binascii
3bc2ddcc 6
dbf5416a 7from ..downloader import get_suitable_downloader
edf65256 8from .fragment import FragmentFD
0d66bd0e 9from .external import FFmpegFD
f9a5affa 10
e154c651 11from ..compat import (
7687c8ac 12 compat_pycrypto_AES,
e154c651 13 compat_urlparse,
e154c651 14)
1cc79574 15from ..utils import (
e154c651 16 parse_m3u8_attributes,
aaf44a2f 17 update_url_query,
4a2f19ab 18 bug_reports_message,
3bc2ddcc 19)
4a2f19ab 20from .. import webvtt
3bc2ddcc
JMF
21
22
12b84ac8 23class HlsFD(FragmentFD):
0a473f2f 24 """
25 Download segments in a m3u8 manifest. External downloaders can take over
52a8a1e1 26 the fragment downloads by supporting the 'm3u8_frag_urls' protocol and
0a473f2f 27 re-defining 'supports_manifest' function
28 """
f0b5d6af 29
f9a5affa
S
30 FD_NAME = 'hlsnative'
31
0d66bd0e 32 @staticmethod
edf65256 33 def can_download(manifest, info_dict, allow_unplayable_formats=False):
63ad4d43 34 UNSUPPORTED_FEATURES = [
f5974637 35 # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]
1e236d7e 36
c15c47d1
S
37 # Live streams heuristic does not always work (e.g. geo restricted to Germany
38 # 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 39 # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]
1e236d7e
S
40
41 # This heuristic also is not correct since segments may not be appended as well.
633b444f
S
42 # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite
43 # no segments will definitely be appended to the end of the playlist.
1e236d7e 44 # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of
51c4d85c 45 # # event media playlists [4]
b1bb77d7 46 # r'#EXT-X-MAP:', # media initialization [5]
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
63ad4d43 52 ]
53 if not allow_unplayable_formats:
54 UNSUPPORTED_FEATURES += [
55 r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]
56 ]
0a473f2f 57
58 def check_results():
59 yield not info_dict.get('is_live')
0a473f2f 60 for feature in UNSUPPORTED_FEATURES:
61 yield not re.search(feature, manifest)
62 return all(check_results())
0d66bd0e 63
f0b5d6af 64 def real_download(self, filename, info_dict):
f9a5affa
S
65 man_url = info_dict['url']
66 self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
69035555 67
c5a49ff0
S
68 urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))
69 man_url = urlh.geturl()
70 s = urlh.read().decode('utf-8', 'ignore')
0d66bd0e 71
7687c8ac 72 can_download, message = self.can_download(s, info_dict, self.params.get('allow_unplayable_formats')), None
73 if can_download and not compat_pycrypto_AES and '#EXT-X-KEY:METHOD=AES-128' in s:
74 if FFmpegFD.available():
49e7e9c3 75 can_download, message = False, 'The stream has AES-128 encryption and pycryptodomex is not available'
7687c8ac 76 else:
49e7e9c3 77 message = ('The stream has AES-128 encryption and neither ffmpeg nor pycryptodomex are available; '
7687c8ac 78 'Decryption will be performed natively, but will be extremely slow')
79 if not can_download:
80 message = message or 'Unsupported features have been detected'
2bfaf89b 81 fd = FFmpegFD(self.ydl, self.params)
7687c8ac 82 self.report_warning(f'{message}; extraction will be delegated to {fd.get_basename()}')
2bfaf89b 83 return fd.real_download(filename, info_dict)
7687c8ac 84 elif message:
85 self.report_warning(message)
0d66bd0e 86
5dcd8e1d 87 is_webvtt = info_dict['ext'] == 'vtt'
88 if is_webvtt:
89 real_downloader = None # Packing the fragments is not currently supported for external downloader
90 else:
96fccc10 91 real_downloader = get_suitable_downloader(
a46a815b 92 info_dict, self.params, None, protocol='m3u8_frag_urls', to_stdout=(filename == '-'))
0a473f2f 93 if real_downloader and not real_downloader.supports_manifest(s):
94 real_downloader = None
beb4b92a 95 if real_downloader:
96 self.to_screen(
97 '[%s] Fragment downloads will be delegated to %s' % (self.FD_NAME, real_downloader.get_basename()))
0a473f2f 98
f1ab3b7d 99 def is_ad_fragment_start(s):
3089bc74
S
100 return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s
101 or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad'))
74c42d9e 102
f1ab3b7d 103 def is_ad_fragment_end(s):
3089bc74
S
104 return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s
105 or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment'))
f1ab3b7d 106
d7009caa 107 fragments = []
5219cb3e 108
74c42d9e
S
109 media_frags = 0
110 ad_frags = 0
111 ad_frag_next = False
f0b5d6af
PH
112 for line in s.splitlines():
113 line = line.strip()
74c42d9e
S
114 if not line:
115 continue
116 if line.startswith('#'):
f1ab3b7d 117 if is_ad_fragment_start(line):
a9ee4f6e 118 ad_frag_next = True
f1ab3b7d
RA
119 elif is_ad_fragment_end(line):
120 ad_frag_next = False
74c42d9e
S
121 continue
122 if ad_frag_next:
f1ab3b7d 123 ad_frags += 1
74c42d9e
S
124 continue
125 media_frags += 1
f0b5d6af 126
f9a5affa 127 ctx = {
f0b5d6af 128 'filename': filename,
74c42d9e
S
129 'total_frags': media_frags,
130 'ad_frags': ad_frags,
f9a5affa
S
131 }
132
5219cb3e 133 if real_downloader:
134 self._prepare_external_frag_download(ctx)
135 else:
3ba7740d 136 self._prepare_and_start_frag_download(ctx, info_dict)
f9a5affa 137
4a2f19ab
F
138 extra_state = ctx.setdefault('extra_state', {})
139
310c2ed2 140 format_index = info_dict.get('format_index')
b8079a40 141 extra_query = None
aaf44a2f 142 extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
b8079a40
RA
143 if extra_param_to_segment_url:
144 extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
e154c651 145 i = 0
146 media_sequence = 0
147 decrypt_info = {'METHOD': 'NONE'}
f5974637 148 byte_range = {}
310c2ed2 149 discontinuity_count = 0
75a24854 150 frag_index = 0
74c42d9e 151 ad_frag_next = False
e154c651 152 for line in s.splitlines():
153 line = line.strip()
154 if line:
155 if not line.startswith('#'):
310c2ed2 156 if format_index and discontinuity_count != format_index:
157 continue
74c42d9e 158 if ad_frag_next:
74c42d9e 159 continue
75a24854 160 frag_index += 1
3e0304fe 161 if frag_index <= ctx['fragment_index']:
75a24854 162 continue
e154c651 163 frag_url = (
164 line
165 if re.match(r'^https?://', line)
166 else compat_urlparse.urljoin(man_url, line))
b8079a40
RA
167 if extra_query:
168 frag_url = update_url_query(frag_url, extra_query)
5219cb3e 169
4cf1e5d2 170 fragments.append({
171 'frag_index': frag_index,
172 'url': frag_url,
173 'decrypt_info': decrypt_info,
174 'byte_range': byte_range,
175 'media_sequence': media_sequence,
176 })
d9d8b857 177 media_sequence += 1
5219cb3e 178
b1bb77d7 179 elif line.startswith('#EXT-X-MAP'):
310c2ed2 180 if format_index and discontinuity_count != format_index:
181 continue
b1bb77d7 182 if frag_index > 0:
183 self.report_error(
beb4b92a 184 'Initialization fragment found after media fragments, unable to download')
b1bb77d7 185 return False
186 frag_index += 1
187 map_info = parse_m3u8_attributes(line[11:])
188 frag_url = (
189 map_info.get('URI')
190 if re.match(r'^https?://', map_info.get('URI'))
191 else compat_urlparse.urljoin(man_url, map_info.get('URI')))
192 if extra_query:
193 frag_url = update_url_query(frag_url, extra_query)
4cf1e5d2 194
195 fragments.append({
196 'frag_index': frag_index,
197 'url': frag_url,
198 'decrypt_info': decrypt_info,
199 'byte_range': byte_range,
200 'media_sequence': media_sequence
201 })
d9d8b857 202 media_sequence += 1
b1bb77d7 203
204 if map_info.get('BYTERANGE'):
205 splitted_byte_range = map_info.get('BYTERANGE').split('@')
206 sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']
207 byte_range = {
208 'start': sub_range_start,
209 'end': sub_range_start + int(splitted_byte_range[0]),
210 }
b1bb77d7 211
212 elif line.startswith('#EXT-X-KEY'):
213 decrypt_url = decrypt_info.get('URI')
214 decrypt_info = parse_m3u8_attributes(line[11:])
215 if decrypt_info['METHOD'] == 'AES-128':
216 if 'IV' in decrypt_info:
217 decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
218 if not re.match(r'^https?://', decrypt_info['URI']):
219 decrypt_info['URI'] = compat_urlparse.urljoin(
220 man_url, decrypt_info['URI'])
221 if extra_query:
222 decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
223 if decrypt_url != decrypt_info['URI']:
224 decrypt_info['KEY'] = None
b1bb77d7 225
226 elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
227 media_sequence = int(line[22:])
228 elif line.startswith('#EXT-X-BYTERANGE'):
229 splitted_byte_range = line[17:].split('@')
230 sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']
231 byte_range = {
232 'start': sub_range_start,
233 'end': sub_range_start + int(splitted_byte_range[0]),
234 }
235 elif is_ad_fragment_start(line):
236 ad_frag_next = True
237 elif is_ad_fragment_end(line):
238 ad_frag_next = False
310c2ed2 239 elif line.startswith('#EXT-X-DISCONTINUITY'):
240 discontinuity_count += 1
4cf1e5d2 241 i += 1
b1bb77d7 242
4cf1e5d2 243 # We only download the first fragment during the test
4c7853de 244 if self.params.get('test', False):
4cf1e5d2 245 fragments = [fragments[0] if fragments else None]
f9a5affa 246
5219cb3e 247 if real_downloader:
248 info_copy = info_dict.copy()
d7009caa 249 info_copy['fragments'] = fragments
5219cb3e 250 fd = real_downloader(self.ydl, self.params)
251 # TODO: Make progress updates work without hooking twice
252 # for ph in self._progress_hooks:
253 # fd.add_progress_hook(ph)
8e897ed2 254 return fd.real_download(filename, info_copy)
333217f4 255
bd4d1ea3 256 if is_webvtt:
257 def pack_fragment(frag_content, frag_index):
258 output = io.StringIO()
259 adjust = 0
7a6742b5
F
260 overflow = False
261 mpegts_last = None
bd4d1ea3 262 for block in webvtt.parse_fragment(frag_content):
263 if isinstance(block, webvtt.CueBlock):
7a6742b5
F
264 extra_state['webvtt_mpegts_last'] = mpegts_last
265 if overflow:
266 extra_state['webvtt_mpegts_adjust'] += 1
267 overflow = False
bd4d1ea3 268 block.start += adjust
269 block.end += adjust
270
271 dedup_window = extra_state.setdefault('webvtt_dedup_window', [])
bd4d1ea3 272
25a3f4f5
F
273 ready = []
274
bd4d1ea3 275 i = 0
25a3f4f5 276 is_new = True
bd4d1ea3 277 while i < len(dedup_window):
25a3f4f5
F
278 wcue = dedup_window[i]
279 wblock = webvtt.CueBlock.from_json(wcue)
280 i += 1
281 if wblock.hinges(block):
282 wcue['end'] = block.end
283 is_new = False
284 continue
285 if wblock == block:
286 is_new = False
287 continue
288 if wblock.end > block.start:
4a2f19ab 289 continue
25a3f4f5
F
290 ready.append(wblock)
291 i -= 1
bd4d1ea3 292 del dedup_window[i]
bd4d1ea3 293
25a3f4f5
F
294 if is_new:
295 dedup_window.append(block.as_json)
296 for block in ready:
297 block.write_into(output)
bd4d1ea3 298
25a3f4f5
F
299 # we only emit cues once they fall out of the duplicate window
300 continue
bd4d1ea3 301 elif isinstance(block, webvtt.Magic):
302 # take care of MPEG PES timestamp overflow
303 if block.mpegts is None:
304 block.mpegts = 0
305 extra_state.setdefault('webvtt_mpegts_adjust', 0)
306 block.mpegts += extra_state['webvtt_mpegts_adjust'] << 33
307 if block.mpegts < extra_state.get('webvtt_mpegts_last', 0):
7a6742b5 308 overflow = True
bd4d1ea3 309 block.mpegts += 1 << 33
7a6742b5 310 mpegts_last = block.mpegts
bd4d1ea3 311
312 if frag_index == 1:
313 extra_state['webvtt_mpegts'] = block.mpegts or 0
314 extra_state['webvtt_local'] = block.local or 0
315 # XXX: block.local = block.mpegts = None ?
316 else:
317 if block.mpegts is not None and block.local is not None:
318 adjust = (
319 (block.mpegts - extra_state.get('webvtt_mpegts', 0))
320 - (block.local - extra_state.get('webvtt_local', 0))
321 )
322 continue
323 elif isinstance(block, webvtt.HeaderBlock):
324 if frag_index != 1:
325 # XXX: this should probably be silent as well
326 # or verify that all segments contain the same data
327 self.report_warning(bug_reports_message(
328 'Discarding a %s block found in the middle of the stream; '
329 'if the subtitles display incorrectly,'
330 % (type(block).__name__)))
331 continue
332 block.write_into(output)
333
334 return output.getvalue().encode('utf-8')
25a3f4f5
F
335
336 def fin_fragments():
337 dedup_window = extra_state.get('webvtt_dedup_window')
338 if not dedup_window:
339 return b''
340
341 output = io.StringIO()
342 for cue in dedup_window:
343 webvtt.CueBlock.from_json(cue).write_into(output)
344
345 return output.getvalue().encode('utf-8')
346
347 self.download_and_append_fragments(
348 ctx, fragments, info_dict, pack_func=pack_fragment, finish_func=fin_fragments)
bd4d1ea3 349 else:
25a3f4f5 350 return self.download_and_append_fragments(ctx, fragments, info_dict)