6 from . import get_suitable_downloader
7 from .external
import FFmpegFD
8 from .fragment
import FragmentFD
10 from ..dependencies
import Cryptodome_AES
11 from ..utils
import bug_reports_message
, parse_m3u8_attributes
, update_url_query
14 class HlsFD(FragmentFD
):
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
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]
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]
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
44 if not allow_unplayable_formats
:
45 UNSUPPORTED_FEATURES
+= [
46 r
'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]
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())
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
)
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')
63 can_download
, message
= self
.can_download(s
, info_dict
, self
.params
.get('allow_unplayable_formats')), None
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'
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')
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
81 if has_drm
and not self
.params
.get('allow_unplayable_formats'):
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')
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
)
91 self
.report_warning(message
)
93 is_webvtt
= info_dict
['ext'] == 'vtt'
95 real_downloader
= None # Packing the fragments is not currently supported for external downloader
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
102 self
.to_screen(f
'[{self.FD_NAME}] Fragment downloads will be delegated to {real_downloader.get_basename()}')
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'))
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'))
117 for line
in s
.splitlines():
121 if line
.startswith('#'):
122 if is_ad_fragment_start(line
):
124 elif is_ad_fragment_end(line
):
133 'filename': filename
,
134 'total_frags': media_frags
,
135 'ad_frags': ad_frags
,
139 self
._prepare
_external
_frag
_download
(ctx
)
141 self
._prepare
_and
_start
_frag
_download
(ctx
, info_dict
)
143 extra_state
= ctx
.setdefault('extra_state', {})
145 format_index
= info_dict
.get('format_index')
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
)
152 decrypt_info
= {'METHOD': 'NONE'}
154 discontinuity_count
= 0
157 for line
in s
.splitlines():
160 if not line
.startswith('#'):
161 if format_index
and discontinuity_count
!= format_index
:
166 if frag_index
<= ctx
['fragment_index']:
170 if re
.match(r
'^https?://', line
)
171 else urllib
.parse
.urljoin(man_url
, line
))
173 frag_url
= update_url_query(frag_url
, extra_query
)
176 'frag_index': frag_index
,
178 'decrypt_info': decrypt_info
,
179 'byte_range': byte_range
,
180 'media_sequence': media_sequence
,
184 elif line
.startswith('#EXT-X-MAP'):
185 if format_index
and discontinuity_count
!= format_index
:
189 'Initialization fragment found after media fragments, unable to download')
192 map_info
= parse_m3u8_attributes(line
[11:])
195 if re
.match(r
'^https?://', map_info
.get('URI'))
196 else urllib
.parse
.urljoin(man_url
, map_info
.get('URI')))
198 frag_url
= update_url_query(frag_url
, extra_query
)
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']
204 'start': sub_range_start
,
205 'end': sub_range_start
+ int(splitted_byte_range
[0]),
209 'frag_index': frag_index
,
211 'decrypt_info': decrypt_info
,
212 'byte_range': byte_range
,
213 'media_sequence': media_sequence
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'])
227 decrypt_info
['URI'] = update_url_query(decrypt_info
['URI'], extra_query
)
228 if decrypt_url
!= decrypt_info
['URI']:
229 decrypt_info
['KEY'] = None
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']
237 'start': sub_range_start
,
238 'end': sub_range_start
+ int(splitted_byte_range
[0]),
240 elif is_ad_fragment_start(line
):
242 elif is_ad_fragment_end(line
):
244 elif line
.startswith('#EXT-X-DISCONTINUITY'):
245 discontinuity_count
+= 1
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]
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
)
261 def pack_fragment(frag_content
, frag_index
):
262 output
= io
.StringIO()
266 for block
in webvtt
.parse_fragment(frag_content
):
267 if isinstance(block
, webvtt
.CueBlock
):
268 extra_state
['webvtt_mpegts_last'] = mpegts_last
270 extra_state
['webvtt_mpegts_adjust'] += 1
272 block
.start
+= adjust
275 dedup_window
= extra_state
.setdefault('webvtt_dedup_window', [])
281 while i
< len(dedup_window
):
282 wcue
= dedup_window
[i
]
283 wblock
= webvtt
.CueBlock
.from_json(wcue
)
285 if wblock
.hinges(block
):
286 wcue
['end'] = block
.end
292 if wblock
.end
> block
.start
:
299 dedup_window
.append(block
.as_json
)
301 block
.write_into(output
)
303 # we only emit cues once they fall out of the duplicate window
305 elif isinstance(block
, webvtt
.Magic
):
306 # take care of MPEG PES timestamp overflow
307 if block
.mpegts
is None:
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):
313 block
.mpegts
+= 1 << 33
314 mpegts_last
= block
.mpegts
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 ?
321 if block
.mpegts
is not None and block
.local
is not None:
323 (block
.mpegts
- extra_state
.get('webvtt_mpegts', 0))
324 - (block
.local
- extra_state
.get('webvtt_local', 0))
327 elif isinstance(block
, webvtt
.HeaderBlock
):
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
__)))
336 block
.write_into(output
)
338 return output
.getvalue().encode()
341 dedup_window
= extra_state
.get('webvtt_dedup_window')
345 output
= io
.StringIO()
346 for cue
in dedup_window
:
347 webvtt
.CueBlock
.from_json(cue
).write_into(output
)
349 return output
.getvalue().encode()
351 self
.download_and_append_fragments(
352 ctx
, fragments
, info_dict
, pack_func
=pack_fragment
, finish_func
=fin_fragments
)
354 return self
.download_and_append_fragments(ctx
, fragments
, info_dict
)