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