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