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