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