]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/hls.py
Completely change project name to yt-dlp (#85)
[yt-dlp.git] / yt_dlp / downloader / hls.py
CommitLineData
f0b5d6af
PH
1from __future__ import unicode_literals
2
f0b5d6af 3import re
e154c651 4import binascii
5try:
6 from Crypto.Cipher import AES
7 can_decrypt_frag = True
8except ImportError:
9 can_decrypt_frag = False
3bc2ddcc 10
5219cb3e 11from ..downloader import _get_real_downloader
f9a5affa 12from .fragment import FragmentFD
0d66bd0e 13from .external import FFmpegFD
f9a5affa 14
e154c651 15from ..compat import (
25afc2a7 16 compat_urllib_error,
e154c651 17 compat_urlparse,
18 compat_struct_pack,
19)
1cc79574 20from ..utils import (
e154c651 21 parse_m3u8_attributes,
aaf44a2f 22 update_url_query,
3bc2ddcc
JMF
23)
24
25
12b84ac8 26class HlsFD(FragmentFD):
27 """ A limited implementation that does not require ffmpeg """
f0b5d6af 28
f9a5affa
S
29 FD_NAME = 'hlsnative'
30
0d66bd0e 31 @staticmethod
d9524b89 32 def can_download(manifest, info_dict, allow_unplayable_formats=False, with_crypto=can_decrypt_frag):
63ad4d43 33 UNSUPPORTED_FEATURES = [
f5974637 34 # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]
1e236d7e 35
c15c47d1
S
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)
2937590e 38 # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]
1e236d7e
S
39
40 # This heuristic also is not correct since segments may not be appended as well.
633b444f
S
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.
1e236d7e 43 # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of
51c4d85c 44 # # event media playlists [4]
b1bb77d7 45 # r'#EXT-X-MAP:', # media initialization [5]
0d66bd0e
S
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
6104cc29 49 # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5
29f7c58a 50 # 5. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.5
63ad4d43 51 ]
52 if not allow_unplayable_formats:
53 UNSUPPORTED_FEATURES += [
54 r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]
55 ]
e154c651 56 check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]
f5974637 57 is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest
d9524b89 58 check_results.append(with_crypto or not is_aes128_enc)
f5974637 59 check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest))
2bfaf89b 60 check_results.append(not info_dict.get('is_live'))
e154c651 61 return all(check_results)
0d66bd0e 62
f0b5d6af 63 def real_download(self, filename, info_dict):
f9a5affa
S
64 man_url = info_dict['url']
65 self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
69035555 66
c5a49ff0
S
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')
0d66bd0e 70
63ad4d43 71 if not self.can_download(s, info_dict, self.params.get('allow_unplayable_formats')):
c712b16d 72 if info_dict.get('extra_param_to_segment_url') or info_dict.get('_decryption_key_url'):
d9524b89 73 self.report_error('pycryptodome not found. Please install it.')
bfa1073e 74 return False
d9524b89 75 if self.can_download(s, info_dict, with_crypto=True):
76 self.report_warning('pycryptodome is needed to download this file with hlsnative')
2bfaf89b
RA
77 self.report_warning(
78 'hlsnative has detected features it does not support, '
79 'extraction will be delegated to ffmpeg')
80 fd = FFmpegFD(self.ydl, self.params)
5219cb3e 81 # TODO: Make progress updates work without hooking twice
82 # for ph in self._progress_hooks:
83 # fd.add_progress_hook(ph)
2bfaf89b 84 return fd.real_download(filename, info_dict)
0d66bd0e 85
5219cb3e 86 real_downloader = _get_real_downloader(info_dict, 'frag_urls', self.params, None)
87
f1ab3b7d 88 def is_ad_fragment_start(s):
3089bc74
S
89 return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s
90 or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad'))
74c42d9e 91
f1ab3b7d 92 def is_ad_fragment_end(s):
3089bc74
S
93 return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s
94 or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment'))
f1ab3b7d 95
5219cb3e 96 fragment_urls = []
97
74c42d9e
S
98 media_frags = 0
99 ad_frags = 0
100 ad_frag_next = False
f0b5d6af
PH
101 for line in s.splitlines():
102 line = line.strip()
74c42d9e
S
103 if not line:
104 continue
105 if line.startswith('#'):
f1ab3b7d 106 if is_ad_fragment_start(line):
a9ee4f6e 107 ad_frag_next = True
f1ab3b7d
RA
108 elif is_ad_fragment_end(line):
109 ad_frag_next = False
74c42d9e
S
110 continue
111 if ad_frag_next:
f1ab3b7d 112 ad_frags += 1
74c42d9e
S
113 continue
114 media_frags += 1
f0b5d6af 115
f9a5affa 116 ctx = {
f0b5d6af 117 'filename': filename,
74c42d9e
S
118 'total_frags': media_frags,
119 'ad_frags': ad_frags,
f9a5affa
S
120 }
121
5219cb3e 122 if real_downloader:
123 self._prepare_external_frag_download(ctx)
124 else:
125 self._prepare_and_start_frag_download(ctx)
f9a5affa 126
25afc2a7
S
127 fragment_retries = self.params.get('fragment_retries', 0)
128 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
129 test = self.params.get('test', False)
130
310c2ed2 131 format_index = info_dict.get('format_index')
b8079a40 132 extra_query = None
aaf44a2f 133 extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
b8079a40
RA
134 if extra_param_to_segment_url:
135 extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
e154c651 136 i = 0
137 media_sequence = 0
138 decrypt_info = {'METHOD': 'NONE'}
7620cd46 139 key_list = []
f5974637 140 byte_range = {}
310c2ed2 141 discontinuity_count = 0
75a24854 142 frag_index = 0
74c42d9e 143 ad_frag_next = False
e154c651 144 for line in s.splitlines():
145 line = line.strip()
b1bb77d7 146 download_frag = False
e154c651 147 if line:
148 if not line.startswith('#'):
310c2ed2 149 if format_index and discontinuity_count != format_index:
150 continue
74c42d9e 151 if ad_frag_next:
74c42d9e 152 continue
75a24854 153 frag_index += 1
3e0304fe 154 if frag_index <= ctx['fragment_index']:
75a24854 155 continue
e154c651 156 frag_url = (
157 line
158 if re.match(r'^https?://', line)
159 else compat_urlparse.urljoin(man_url, line))
b8079a40
RA
160 if extra_query:
161 frag_url = update_url_query(frag_url, extra_query)
5219cb3e 162
163 if real_downloader:
164 fragment_urls.append(frag_url)
165 continue
b1bb77d7 166 download_frag = True
5219cb3e 167
b1bb77d7 168 elif line.startswith('#EXT-X-MAP'):
310c2ed2 169 if format_index and discontinuity_count != format_index:
170 continue
b1bb77d7 171 if frag_index > 0:
172 self.report_error(
173 'initialization fragment found after media fragments, unable to download')
174 return False
175 frag_index += 1
176 map_info = parse_m3u8_attributes(line[11:])
177 frag_url = (
178 map_info.get('URI')
179 if re.match(r'^https?://', map_info.get('URI'))
180 else compat_urlparse.urljoin(man_url, map_info.get('URI')))
181 if extra_query:
182 frag_url = update_url_query(frag_url, extra_query)
183 if real_downloader:
184 fragment_urls.append(frag_url)
185 continue
186
187 if map_info.get('BYTERANGE'):
188 splitted_byte_range = map_info.get('BYTERANGE').split('@')
189 sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']
190 byte_range = {
191 'start': sub_range_start,
192 'end': sub_range_start + int(splitted_byte_range[0]),
193 }
194 download_frag = True
195
196 elif line.startswith('#EXT-X-KEY'):
197 decrypt_url = decrypt_info.get('URI')
198 decrypt_info = parse_m3u8_attributes(line[11:])
199 if decrypt_info['METHOD'] == 'AES-128':
200 if 'IV' in decrypt_info:
201 decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
202 if not re.match(r'^https?://', decrypt_info['URI']):
203 decrypt_info['URI'] = compat_urlparse.urljoin(
204 man_url, decrypt_info['URI'])
205 if extra_query:
206 decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
207 if decrypt_url != decrypt_info['URI']:
208 decrypt_info['KEY'] = None
209 key_data = decrypt_info.copy()
210 key_data['INDEX'] = frag_index
211 key_list.append(key_data)
212
213 elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
214 media_sequence = int(line[22:])
215 elif line.startswith('#EXT-X-BYTERANGE'):
216 splitted_byte_range = line[17:].split('@')
217 sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']
218 byte_range = {
219 'start': sub_range_start,
220 'end': sub_range_start + int(splitted_byte_range[0]),
221 }
222 elif is_ad_fragment_start(line):
223 ad_frag_next = True
224 elif is_ad_fragment_end(line):
225 ad_frag_next = False
310c2ed2 226 elif line.startswith('#EXT-X-DISCONTINUITY'):
227 discontinuity_count += 1
b1bb77d7 228
229 if download_frag:
25afc2a7 230 count = 0
f5974637
RA
231 headers = info_dict.get('http_headers', {})
232 if byte_range:
6e65a2a6 233 headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
25afc2a7
S
234 while count <= fragment_retries:
235 try:
75a24854
RA
236 success, frag_content = self._download_fragment(
237 ctx, frag_url, info_dict, headers)
25afc2a7
S
238 if not success:
239 return False
25afc2a7 240 break
2e99cd30 241 except compat_urllib_error.HTTPError as err:
25afc2a7
S
242 # Unavailable (possibly temporary) fragments may be served.
243 # First we try to retry then either skip or abort.
067aa17e
S
244 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
245 # https://github.com/ytdl-org/youtube-dl/issues/10448).
25afc2a7
S
246 count += 1
247 if count <= fragment_retries:
75a24854 248 self.report_retry_fragment(err, frag_index, count, fragment_retries)
25afc2a7
S
249 if count > fragment_retries:
250 if skip_unavailable_fragments:
251 i += 1
252 media_sequence += 1
75a24854 253 self.report_skip_fragment(frag_index)
25afc2a7
S
254 continue
255 self.report_error(
256 'giving up after %s fragment retries' % fragment_retries)
e154c651 257 return False
5219cb3e 258
e154c651 259 if decrypt_info['METHOD'] == 'AES-128':
8369a4fe 260 iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
538d4f86 261 decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen(
c712b16d 262 self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read()
00dd0cd5 263 # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
264 # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
265 # not what it decrypts to.
266 if not test:
267 frag_content = AES.new(
268 decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
75a24854 269 self._append_fragment(ctx, frag_content)
e154c651 270 # We only download the first fragment during the test
25afc2a7 271 if test:
e154c651 272 break
273 i += 1
274 media_sequence += 1
f9a5affa 275
5219cb3e 276 if real_downloader:
277 info_copy = info_dict.copy()
278 info_copy['url_list'] = fragment_urls
7620cd46 279 info_copy['key_list'] = key_list
5219cb3e 280 fd = real_downloader(self.ydl, self.params)
281 # TODO: Make progress updates work without hooking twice
282 # for ph in self._progress_hooks:
283 # fd.add_progress_hook(ph)
284 success = fd.real_download(filename, info_copy)
285 if not success:
286 return False
287 else:
288 self._finish_frag_download(ctx)
f0b5d6af 289 return True