5 from . import get_suitable_downloader
6 from .external
import FFmpegFD
7 from .fragment
import FragmentFD
9 from ..compat
import compat_urlparse
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
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'
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')
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
75 if has_drm
and not self
.params
.get('allow_unplayable_formats'):
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')
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
)
85 self
.report_warning(message
)
87 is_webvtt
= info_dict
['ext'] == 'vtt'
89 real_downloader
= None # Packing the fragments is not currently supported for external downloader
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
96 self
.to_screen(f
'[{self.FD_NAME}] Fragment downloads will be delegated to {real_downloader.get_basename()}')
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'))
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'))
111 for line
in s
.splitlines():
115 if line
.startswith('#'):
116 if is_ad_fragment_start(line
):
118 elif is_ad_fragment_end(line
):
127 'filename': filename
,
128 'total_frags': media_frags
,
129 'ad_frags': ad_frags
,
133 self
._prepare
_external
_frag
_download
(ctx
)
135 self
._prepare
_and
_start
_frag
_download
(ctx
, info_dict
)
137 extra_state
= ctx
.setdefault('extra_state', {})
139 format_index
= info_dict
.get('format_index')
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
)
146 decrypt_info
= {'METHOD': 'NONE'}
148 discontinuity_count
= 0
151 for line
in s
.splitlines():
154 if not line
.startswith('#'):
155 if format_index
and discontinuity_count
!= format_index
:
160 if frag_index
<= ctx
['fragment_index']:
164 if re
.match(r
'^https?://', line
)
165 else compat_urlparse
.urljoin(man_url
, line
))
167 frag_url
= update_url_query(frag_url
, extra_query
)
170 'frag_index': frag_index
,
172 'decrypt_info': decrypt_info
,
173 'byte_range': byte_range
,
174 'media_sequence': media_sequence
,
178 elif line
.startswith('#EXT-X-MAP'):
179 if format_index
and discontinuity_count
!= format_index
:
183 'Initialization fragment found after media fragments, unable to download')
186 map_info
= parse_m3u8_attributes(line
[11:])
189 if re
.match(r
'^https?://', map_info
.get('URI'))
190 else compat_urlparse
.urljoin(man_url
, map_info
.get('URI')))
192 frag_url
= update_url_query(frag_url
, extra_query
)
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']
198 'start': sub_range_start
,
199 'end': sub_range_start
+ int(splitted_byte_range
[0]),
203 'frag_index': frag_index
,
205 'decrypt_info': decrypt_info
,
206 'byte_range': byte_range
,
207 'media_sequence': media_sequence
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'])
221 decrypt_info
['URI'] = update_url_query(decrypt_info
['URI'], extra_query
)
222 if decrypt_url
!= decrypt_info
['URI']:
223 decrypt_info
['KEY'] = None
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']
231 'start': sub_range_start
,
232 'end': sub_range_start
+ int(splitted_byte_range
[0]),
234 elif is_ad_fragment_start(line
):
236 elif is_ad_fragment_end(line
):
238 elif line
.startswith('#EXT-X-DISCONTINUITY'):
239 discontinuity_count
+= 1
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]
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
)
255 def pack_fragment(frag_content
, frag_index
):
256 output
= io
.StringIO()
260 for block
in webvtt
.parse_fragment(frag_content
):
261 if isinstance(block
, webvtt
.CueBlock
):
262 extra_state
['webvtt_mpegts_last'] = mpegts_last
264 extra_state
['webvtt_mpegts_adjust'] += 1
266 block
.start
+= adjust
269 dedup_window
= extra_state
.setdefault('webvtt_dedup_window', [])
275 while i
< len(dedup_window
):
276 wcue
= dedup_window
[i
]
277 wblock
= webvtt
.CueBlock
.from_json(wcue
)
279 if wblock
.hinges(block
):
280 wcue
['end'] = block
.end
286 if wblock
.end
> block
.start
:
293 dedup_window
.append(block
.as_json
)
295 block
.write_into(output
)
297 # we only emit cues once they fall out of the duplicate window
299 elif isinstance(block
, webvtt
.Magic
):
300 # take care of MPEG PES timestamp overflow
301 if block
.mpegts
is None:
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):
307 block
.mpegts
+= 1 << 33
308 mpegts_last
= block
.mpegts
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 ?
315 if block
.mpegts
is not None and block
.local
is not None:
317 (block
.mpegts
- extra_state
.get('webvtt_mpegts', 0))
318 - (block
.local
- extra_state
.get('webvtt_local', 0))
321 elif isinstance(block
, webvtt
.HeaderBlock
):
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
__)))
330 block
.write_into(output
)
332 return output
.getvalue().encode()
335 dedup_window
= extra_state
.get('webvtt_dedup_window')
339 output
= io
.StringIO()
340 for cue
in dedup_window
:
341 webvtt
.CueBlock
.from_json(cue
).write_into(output
)
343 return output
.getvalue().encode()
345 self
.download_and_append_fragments(
346 ctx
, fragments
, info_dict
, pack_func
=pack_fragment
, finish_func
=fin_fragments
)
348 return self
.download_and_append_fragments(ctx
, fragments
, info_dict
)