]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/fragment.py
[docs] Minor documentation improvements
[yt-dlp.git] / yt_dlp / downloader / fragment.py
CommitLineData
95d8f7ea
S
1from __future__ import division, unicode_literals
2
3import os
4import time
ea0c2f21 5import json
bd50a52b 6from math import ceil
95d8f7ea 7
4c7853de 8try:
9 import concurrent.futures
10 can_threaded_download = True
11except ImportError:
12 can_threaded_download = False
13
95d8f7ea
S
14from .common import FileDownloader
15from .http import HttpFD
edf65256 16from ..aes import aes_cbc_decrypt_bytes
4c7853de 17from ..compat import (
18 compat_urllib_error,
19 compat_struct_pack,
20)
95d8f7ea 21from ..utils import (
4c7853de 22 DownloadError,
2e99cd30 23 error_to_compat_str,
95d8f7ea
S
24 encodeFilename,
25 sanitize_open,
69035555 26 sanitized_Request,
95d8f7ea
S
27)
28
29
30class HttpQuietDownloader(HttpFD):
31 def to_screen(self, *args, **kargs):
32 pass
33
bd93fd5d 34 def report_retry(self, err, count, retries):
35 super().to_screen(
36 f'[download] Got server HTTP error: {err}. Retrying (attempt {count} of {self.format_retries(retries)}) ...')
37
95d8f7ea
S
38
39class FragmentFD(FileDownloader):
40 """
41 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
16a8b798
S
42
43 Available options:
44
9603b660
S
45 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
46 and hlsnative only)
47 skip_unavailable_fragments:
48 Skip unavailable fragments (DASH and hlsnative only)
0eee52f3
S
49 keep_fragments: Keep downloaded fragments on disk after downloading is
50 finished
59a7a13e 51 concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
e8e73840 52 _no_ytdl_file: Don't use .ytdl file
290f64db 53
7a5c1cfe 54 For each incomplete fragment download yt-dlp keeps on disk a special
290f64db 55 bookkeeping file with download state and metadata (in future such files will
7a5c1cfe 56 be used for any incomplete download handled by yt-dlp). This file is
290f64db
S
57 used to properly handle resuming, check download file consistency and detect
58 potential errors. The file has a .ytdl extension and represents a standard
59 JSON file of the following format:
60
61 extractor:
62 Dictionary of extractor related data. TBD.
63
64 downloader:
65 Dictionary of downloader related data. May contain following data:
66 current_fragment:
67 Dictionary with current (being downloaded) fragment data:
85f6de25 68 index: 0-based index of current fragment among all fragments
290f64db
S
69 fragment_count:
70 Total count of fragments
50534b71 71
85f6de25 72 This feature is experimental and file format may change in future.
95d8f7ea
S
73 """
74
75a24854 75 def report_retry_fragment(self, err, frag_index, count, retries):
721f26b8 76 self.to_screen(
4c7853de 77 '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...'
75a24854 78 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
721f26b8 79
b4b855eb 80 def report_skip_fragment(self, frag_index, err=None):
81 err = f' {err};' if err else ''
82 self.to_screen(f'[download]{err} Skipping fragment {frag_index:d} ...')
9603b660 83
69035555
S
84 def _prepare_url(self, info_dict, url):
85 headers = info_dict.get('http_headers')
86 return sanitized_Request(url, None, headers) if headers else url
87
3ba7740d 88 def _prepare_and_start_frag_download(self, ctx, info_dict):
95d8f7ea 89 self._prepare_frag_download(ctx)
3ba7740d 90 self._start_frag_download(ctx, info_dict)
95d8f7ea 91
e8e73840 92 def __do_ytdl_file(self, ctx):
93 return not ctx['live'] and not ctx['tmpfilename'] == '-' and not self.params.get('_no_ytdl_file')
adb4b03c 94
d3f0687c 95 def _read_ytdl_file(self, ctx):
500a86a5 96 assert 'ytdl_corrupt' not in ctx
d3f0687c 97 stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
500a86a5 98 try:
4d49884c
F
99 ytdl_data = json.loads(stream.read())
100 ctx['fragment_index'] = ytdl_data['downloader']['current_fragment']['index']
101 if 'extra_state' in ytdl_data['downloader']:
102 ctx['extra_state'] = ytdl_data['downloader']['extra_state']
500a86a5
S
103 except Exception:
104 ctx['ytdl_corrupt'] = True
105 finally:
106 stream.close()
d3f0687c
S
107
108 def _write_ytdl_file(self, ctx):
109 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
ad3dc496 110 try:
111 downloader = {
112 'current_fragment': {
113 'index': ctx['fragment_index'],
114 },
115 }
116 if 'extra_state' in ctx:
117 downloader['extra_state'] = ctx['extra_state']
118 if ctx.get('fragment_count') is not None:
119 downloader['fragment_count'] = ctx['fragment_count']
120 frag_index_stream.write(json.dumps({'downloader': downloader}))
121 finally:
122 frag_index_stream.close()
d3f0687c 123
273762c8 124 def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None):
d3f0687c 125 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
38d70284 126 fragment_info_dict = {
75a24854
RA
127 'url': frag_url,
128 'http_headers': headers or info_dict.get('http_headers'),
273762c8 129 'request_data': request_data,
bd50a52b 130 'ctx_id': ctx.get('ctx_id'),
38d70284 131 }
132 success = ctx['dl'].download(fragment_filename, fragment_info_dict)
75a24854
RA
133 if not success:
134 return False, None
38d70284 135 if fragment_info_dict.get('filetime'):
136 ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
4c7853de 137 ctx['fragment_filename_sanitized'] = fragment_filename
138 return True, self._read_fragment(ctx)
139
140 def _read_fragment(self, ctx):
141 down, frag_sanitized = sanitize_open(ctx['fragment_filename_sanitized'], 'rb')
d3f0687c
S
142 ctx['fragment_filename_sanitized'] = frag_sanitized
143 frag_content = down.read()
75a24854 144 down.close()
4c7853de 145 return frag_content
75a24854
RA
146
147 def _append_fragment(self, ctx, frag_content):
d3f0687c
S
148 try:
149 ctx['dest_stream'].write(frag_content)
593f2f79 150 ctx['dest_stream'].flush()
d3f0687c 151 finally:
adb4b03c 152 if self.__do_ytdl_file(ctx):
d3f0687c 153 self._write_ytdl_file(ctx)
0eee52f3 154 if not self.params.get('keep_fragments', False):
99081da9 155 os.remove(encodeFilename(ctx['fragment_filename_sanitized']))
d3f0687c 156 del ctx['fragment_filename_sanitized']
75a24854 157
95d8f7ea 158 def _prepare_frag_download(self, ctx):
5fa1702c
S
159 if 'live' not in ctx:
160 ctx['live'] = False
5efaf43c
S
161 if not ctx['live']:
162 total_frags_str = '%d' % ctx['total_frags']
163 ad_frags = ctx.get('ad_frags', 0)
164 if ad_frags:
165 total_frags_str += ' (not including %d ad)' % ad_frags
166 else:
167 total_frags_str = 'unknown (live)'
5fa1702c 168 self.to_screen(
5efaf43c 169 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
95d8f7ea
S
170 self.report_destination(ctx['filename'])
171 dl = HttpQuietDownloader(
172 self.ydl,
173 {
174 'continuedl': True,
bd93fd5d 175 'quiet': self.params.get('quiet'),
95d8f7ea 176 'noprogress': True,
d800609c 177 'ratelimit': self.params.get('ratelimit'),
6828c809 178 'retries': self.params.get('retries', 0),
7097bffb 179 'nopart': self.params.get('nopart', False),
95d8f7ea
S
180 'test': self.params.get('test', False),
181 }
182 )
183 tmpfilename = self.temp_name(ctx['filename'])
75a24854
RA
184 open_mode = 'wb'
185 resume_len = 0
d3f0687c 186
75a24854
RA
187 # Establish possible resume length
188 if os.path.isfile(encodeFilename(tmpfilename)):
189 open_mode = 'ab'
190 resume_len = os.path.getsize(encodeFilename(tmpfilename))
d3f0687c 191
adb4b03c
S
192 # Should be initialized before ytdl file check
193 ctx.update({
194 'tmpfilename': tmpfilename,
195 'fragment_index': 0,
196 })
d3f0687c 197
adb4b03c
S
198 if self.__do_ytdl_file(ctx):
199 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
200 self._read_ytdl_file(ctx)
500a86a5
S
201 is_corrupt = ctx.get('ytdl_corrupt') is True
202 is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
203 if is_corrupt or is_inconsistent:
204 message = (
205 '.ytdl file is corrupt' if is_corrupt else
206 'Inconsistent state of incomplete fragment download')
6f3b4a98 207 self.report_warning(
5ef7d9bd 208 '%s. Restarting from the beginning ...' % message)
e7c3e334 209 ctx['fragment_index'] = resume_len = 0
500a86a5
S
210 if 'ytdl_corrupt' in ctx:
211 del ctx['ytdl_corrupt']
e7c3e334 212 self._write_ytdl_file(ctx)
adb4b03c
S
213 else:
214 self._write_ytdl_file(ctx)
e7c3e334 215 assert ctx['fragment_index'] == 0
d3f0687c 216
75a24854
RA
217 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
218
95d8f7ea
S
219 ctx.update({
220 'dl': dl,
221 'dest_stream': dest_stream,
222 'tmpfilename': tmpfilename,
75a24854
RA
223 # Total complete fragments downloaded so far in bytes
224 'complete_frags_downloaded_bytes': resume_len,
95d8f7ea
S
225 })
226
3ba7740d 227 def _start_frag_download(self, ctx, info_dict):
3bce4ff7 228 resume_len = ctx['complete_frags_downloaded_bytes']
95d8f7ea 229 total_frags = ctx['total_frags']
bd50a52b 230 ctx_id = ctx.get('ctx_id')
95d8f7ea
S
231 # This dict stores the download progress, it's updated by the progress
232 # hook
233 state = {
234 'status': 'downloading',
3bce4ff7 235 'downloaded_bytes': resume_len,
3e0304fe
RA
236 'fragment_index': ctx['fragment_index'],
237 'fragment_count': total_frags,
95d8f7ea
S
238 'filename': ctx['filename'],
239 'tmpfilename': ctx['tmpfilename'],
b83b782d
S
240 }
241
242 start = time.time()
243 ctx.update({
244 'started': start,
bd93fd5d 245 'fragment_started': start,
709185a2
S
246 # Amount of fragment's bytes downloaded by the time of the previous
247 # frag progress hook invocation
b83b782d
S
248 'prev_frag_downloaded_bytes': 0,
249 })
95d8f7ea
S
250
251 def frag_progress_hook(s):
252 if s['status'] not in ('downloading', 'finished'):
253 return
254
bd50a52b
THD
255 if ctx_id is not None and s.get('ctx_id') != ctx_id:
256 return
257
258 state['max_progress'] = ctx.get('max_progress')
259 state['progress_idx'] = ctx.get('progress_idx')
260
5fa1702c 261 time_now = time.time()
2c2f1efd 262 state['elapsed'] = time_now - start
3c91e416 263 frag_total_bytes = s.get('total_bytes') or 0
3ba7740d 264 s['fragment_info_dict'] = s.pop('info_dict', {})
5fa1702c
S
265 if not ctx['live']:
266 estimated_size = (
3089bc74
S
267 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
268 / (state['fragment_index'] + 1) * total_frags)
5fa1702c 269 state['total_bytes_estimate'] = estimated_size
95d8f7ea 270
709185a2 271 if s['status'] == 'finished':
3e0304fe
RA
272 state['fragment_index'] += 1
273 ctx['fragment_index'] = state['fragment_index']
b83b782d
S
274 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
275 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
bd93fd5d 276 ctx['speed'] = state['speed'] = self.calc_speed(
277 ctx['fragment_started'], time_now, frag_total_bytes)
278 ctx['fragment_started'] = time.time()
b83b782d 279 ctx['prev_frag_downloaded_bytes'] = 0
709185a2
S
280 else:
281 frag_downloaded_bytes = s['downloaded_bytes']
b83b782d 282 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
5fa1702c
S
283 if not ctx['live']:
284 state['eta'] = self.calc_eta(
3bce4ff7 285 start, time_now, estimated_size - resume_len,
286 state['downloaded_bytes'] - resume_len)
bd93fd5d 287 ctx['speed'] = state['speed'] = self.calc_speed(
288 ctx['fragment_started'], time_now, frag_downloaded_bytes)
b83b782d 289 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
3ba7740d 290 self._hook_progress(state, info_dict)
95d8f7ea
S
291
292 ctx['dl'].add_progress_hook(frag_progress_hook)
293
294 return start
295
3ba7740d 296 def _finish_frag_download(self, ctx, info_dict):
95d8f7ea 297 ctx['dest_stream'].close()
adb4b03c
S
298 if self.__do_ytdl_file(ctx):
299 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
300 if os.path.isfile(ytdl_filename):
301 os.remove(ytdl_filename)
95d8f7ea 302 elapsed = time.time() - ctx['started']
0ff2c1ec
S
303
304 if ctx['tmpfilename'] == '-':
305 downloaded_bytes = ctx['complete_frags_downloaded_bytes']
306 else:
307 self.try_rename(ctx['tmpfilename'], ctx['filename'])
38d70284 308 if self.params.get('updatetime', True):
309 filetime = ctx.get('fragment_filetime')
310 if filetime:
311 try:
312 os.utime(ctx['filename'], (time.time(), filetime))
313 except Exception:
314 pass
0ff2c1ec 315 downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename']))
95d8f7ea
S
316
317 self._hook_progress({
0ff2c1ec
S
318 'downloaded_bytes': downloaded_bytes,
319 'total_bytes': downloaded_bytes,
95d8f7ea
S
320 'filename': ctx['filename'],
321 'status': 'finished',
322 'elapsed': elapsed,
bd50a52b
THD
323 'ctx_id': ctx.get('ctx_id'),
324 'max_progress': ctx.get('max_progress'),
325 'progress_idx': ctx.get('progress_idx'),
3ba7740d 326 }, info_dict)
5219cb3e 327
328 def _prepare_external_frag_download(self, ctx):
329 if 'live' not in ctx:
330 ctx['live'] = False
331 if not ctx['live']:
332 total_frags_str = '%d' % ctx['total_frags']
333 ad_frags = ctx.get('ad_frags', 0)
334 if ad_frags:
335 total_frags_str += ' (not including %d ad)' % ad_frags
336 else:
337 total_frags_str = 'unknown (live)'
338 self.to_screen(
339 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
340
341 tmpfilename = self.temp_name(ctx['filename'])
342
343 # Should be initialized before ytdl file check
344 ctx.update({
345 'tmpfilename': tmpfilename,
346 'fragment_index': 0,
347 })
4c7853de 348
1009f67c 349 def decrypter(self, info_dict):
350 _key_cache = {}
351
352 def _get_key(url):
353 if url not in _key_cache:
354 _key_cache[url] = self.ydl.urlopen(self._prepare_url(info_dict, url)).read()
355 return _key_cache[url]
356
357 def decrypt_fragment(fragment, frag_content):
358 decrypt_info = fragment.get('decrypt_info')
359 if not decrypt_info or decrypt_info['METHOD'] != 'AES-128':
360 return frag_content
361 iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', fragment['media_sequence'])
362 decrypt_info['KEY'] = decrypt_info.get('KEY') or _get_key(info_dict.get('_decryption_key_url') or decrypt_info['URI'])
363 # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
364 # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
365 # not what it decrypts to.
366 if self.params.get('test', False):
367 return frag_content
2cda6b40 368 decrypted_data = aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv)
7687c8ac 369 return decrypted_data[:-decrypted_data[-1]]
1009f67c 370
371 return decrypt_fragment
372
bd50a52b
THD
373 def download_and_append_fragments_multiple(self, *args, pack_func=None, finish_func=None):
374 '''
375 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
376 all args must be either tuple or list
377 '''
378 max_progress = len(args)
379 if max_progress == 1:
380 return self.download_and_append_fragments(*args[0], pack_func=pack_func, finish_func=finish_func)
381 max_workers = self.params.get('concurrent_fragment_downloads', max_progress)
49a57e70 382 if max_progress > 1:
383 self._prepare_multiline_status(max_progress)
bd50a52b
THD
384
385 def thread_func(idx, ctx, fragments, info_dict, tpe):
386 ctx['max_progress'] = max_progress
387 ctx['progress_idx'] = idx
388 return self.download_and_append_fragments(ctx, fragments, info_dict, pack_func=pack_func, finish_func=finish_func, tpe=tpe)
389
390 class FTPE(concurrent.futures.ThreadPoolExecutor):
391 # has to stop this or it's going to wait on the worker thread itself
392 def __exit__(self, exc_type, exc_val, exc_tb):
393 pass
394
395 spins = []
396 for idx, (ctx, fragments, info_dict) in enumerate(args):
397 tpe = FTPE(ceil(max_workers / max_progress))
398 job = tpe.submit(thread_func, idx, ctx, fragments, info_dict, tpe)
399 spins.append((tpe, job))
400
401 result = True
402 for tpe, job in spins:
403 try:
404 result = result and job.result()
405 finally:
406 tpe.shutdown(wait=True)
819e0531 407 return result
bd50a52b
THD
408
409 def download_and_append_fragments(self, ctx, fragments, info_dict, *, pack_func=None, finish_func=None, tpe=None):
4c7853de 410 fragment_retries = self.params.get('fragment_retries', 0)
bd4d1ea3 411 is_fatal = (lambda idx: idx == 0) if self.params.get('skip_unavailable_fragments', True) else (lambda _: True)
4c7853de 412 if not pack_func:
413 pack_func = lambda frag_content, _: frag_content
414
415 def download_fragment(fragment, ctx):
416 frag_index = ctx['fragment_index'] = fragment['frag_index']
d9d8b857 417 headers = info_dict.get('http_headers', {}).copy()
4c7853de 418 byte_range = fragment.get('byte_range')
419 if byte_range:
420 headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
421
422 # Never skip the first fragment
bd4d1ea3 423 fatal = is_fatal(fragment.get('index') or (frag_index - 1))
4c7853de 424 count, frag_content = 0, None
425 while count <= fragment_retries:
426 try:
427 success, frag_content = self._download_fragment(ctx, fragment['url'], info_dict, headers)
428 if not success:
429 return False, frag_index
430 break
431 except compat_urllib_error.HTTPError as err:
432 # Unavailable (possibly temporary) fragments may be served.
433 # First we try to retry then either skip or abort.
434 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
435 # https://github.com/ytdl-org/youtube-dl/issues/10448).
436 count += 1
437 if count <= fragment_retries:
438 self.report_retry_fragment(err, frag_index, count, fragment_retries)
439 except DownloadError:
440 # Don't retry fragment if error occurred during HTTP downloading
441 # itself since it has own retry settings
442 if not fatal:
443 break
444 raise
445
446 if count > fragment_retries:
447 if not fatal:
448 return False, frag_index
449 ctx['dest_stream'].close()
450 self.report_error('Giving up after %s fragment retries' % fragment_retries)
451 return False, frag_index
452 return frag_content, frag_index
453
4c7853de 454 def append_fragment(frag_content, frag_index, ctx):
455 if not frag_content:
bd4d1ea3 456 if not is_fatal(frag_index - 1):
b4b855eb 457 self.report_skip_fragment(frag_index, 'fragment not found')
4c7853de 458 return True
459 else:
460 ctx['dest_stream'].close()
461 self.report_error(
462 'fragment %s not found, unable to continue' % frag_index)
463 return False
464 self._append_fragment(ctx, pack_func(frag_content, frag_index))
465 return True
466
1009f67c 467 decrypt_fragment = self.decrypter(info_dict)
468
4c7853de 469 max_workers = self.params.get('concurrent_fragment_downloads', 1)
470 if can_threaded_download and max_workers > 1:
471
472 def _download_fragment(fragment):
723d44b9 473 ctx_copy = ctx.copy()
474 frag_content, frag_index = download_fragment(fragment, ctx_copy)
475 return fragment, frag_content, frag_index, ctx_copy.get('fragment_filename_sanitized')
4c7853de 476
477 self.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome')
bd50a52b 478 with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
4c7853de 479 for fragment, frag_content, frag_index, frag_filename in pool.map(_download_fragment, fragments):
480 ctx['fragment_filename_sanitized'] = frag_filename
481 ctx['fragment_index'] = frag_index
482 result = append_fragment(decrypt_fragment(fragment, frag_content), frag_index, ctx)
483 if not result:
484 return False
485 else:
486 for fragment in fragments:
487 frag_content, frag_index = download_fragment(fragment, ctx)
488 result = append_fragment(decrypt_fragment(fragment, frag_content), frag_index, ctx)
489 if not result:
490 return False
491
25a3f4f5
F
492 if finish_func is not None:
493 ctx['dest_stream'].write(finish_func())
494 ctx['dest_stream'].flush()
3ba7740d 495 self._finish_frag_download(ctx, info_dict)
8e897ed2 496 return True