]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/fragment.py
[compat] Split into sub-modules (#2173)
[yt-dlp.git] / yt_dlp / downloader / fragment.py
1 import contextlib
2 import http.client
3 import json
4 import math
5 import os
6 import time
7
8 try:
9 import concurrent.futures
10 can_threaded_download = True
11 except ImportError:
12 can_threaded_download = False
13
14 from .common import FileDownloader
15 from .http import HttpFD
16 from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
17 from ..compat import compat_os_name, compat_struct_pack, compat_urllib_error
18 from ..utils import (
19 DownloadError,
20 encodeFilename,
21 error_to_compat_str,
22 sanitized_Request,
23 traverse_obj,
24 )
25
26
27 class HttpQuietDownloader(HttpFD):
28 def to_screen(self, *args, **kargs):
29 pass
30
31 def report_retry(self, err, count, retries):
32 super().to_screen(
33 f'[download] Got server HTTP error: {err}. Retrying (attempt {count} of {self.format_retries(retries)}) ...')
34
35
36 class FragmentFD(FileDownloader):
37 """
38 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
39
40 Available options:
41
42 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
43 and hlsnative only)
44 skip_unavailable_fragments:
45 Skip unavailable fragments (DASH and hlsnative only)
46 keep_fragments: Keep downloaded fragments on disk after downloading is
47 finished
48 concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
49 _no_ytdl_file: Don't use .ytdl file
50
51 For each incomplete fragment download yt-dlp keeps on disk a special
52 bookkeeping file with download state and metadata (in future such files will
53 be used for any incomplete download handled by yt-dlp). This file is
54 used to properly handle resuming, check download file consistency and detect
55 potential errors. The file has a .ytdl extension and represents a standard
56 JSON file of the following format:
57
58 extractor:
59 Dictionary of extractor related data. TBD.
60
61 downloader:
62 Dictionary of downloader related data. May contain following data:
63 current_fragment:
64 Dictionary with current (being downloaded) fragment data:
65 index: 0-based index of current fragment among all fragments
66 fragment_count:
67 Total count of fragments
68
69 This feature is experimental and file format may change in future.
70 """
71
72 def report_retry_fragment(self, err, frag_index, count, retries):
73 self.to_screen(
74 '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...'
75 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
76
77 def report_skip_fragment(self, frag_index, err=None):
78 err = f' {err};' if err else ''
79 self.to_screen(f'[download]{err} Skipping fragment {frag_index:d} ...')
80
81 def _prepare_url(self, info_dict, url):
82 headers = info_dict.get('http_headers')
83 return sanitized_Request(url, None, headers) if headers else url
84
85 def _prepare_and_start_frag_download(self, ctx, info_dict):
86 self._prepare_frag_download(ctx)
87 self._start_frag_download(ctx, info_dict)
88
89 def __do_ytdl_file(self, ctx):
90 return ctx['live'] is not True and ctx['tmpfilename'] != '-' and not self.params.get('_no_ytdl_file')
91
92 def _read_ytdl_file(self, ctx):
93 assert 'ytdl_corrupt' not in ctx
94 stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
95 try:
96 ytdl_data = json.loads(stream.read())
97 ctx['fragment_index'] = ytdl_data['downloader']['current_fragment']['index']
98 if 'extra_state' in ytdl_data['downloader']:
99 ctx['extra_state'] = ytdl_data['downloader']['extra_state']
100 except Exception:
101 ctx['ytdl_corrupt'] = True
102 finally:
103 stream.close()
104
105 def _write_ytdl_file(self, ctx):
106 frag_index_stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
107 try:
108 downloader = {
109 'current_fragment': {
110 'index': ctx['fragment_index'],
111 },
112 }
113 if 'extra_state' in ctx:
114 downloader['extra_state'] = ctx['extra_state']
115 if ctx.get('fragment_count') is not None:
116 downloader['fragment_count'] = ctx['fragment_count']
117 frag_index_stream.write(json.dumps({'downloader': downloader}))
118 finally:
119 frag_index_stream.close()
120
121 def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None):
122 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
123 fragment_info_dict = {
124 'url': frag_url,
125 'http_headers': headers or info_dict.get('http_headers'),
126 'request_data': request_data,
127 'ctx_id': ctx.get('ctx_id'),
128 }
129 success = ctx['dl'].download(fragment_filename, fragment_info_dict)
130 if not success:
131 return False
132 if fragment_info_dict.get('filetime'):
133 ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
134 ctx['fragment_filename_sanitized'] = fragment_filename
135 return True
136
137 def _read_fragment(self, ctx):
138 if not ctx.get('fragment_filename_sanitized'):
139 return None
140 try:
141 down, frag_sanitized = self.sanitize_open(ctx['fragment_filename_sanitized'], 'rb')
142 except FileNotFoundError:
143 if ctx.get('live'):
144 return None
145 raise
146 ctx['fragment_filename_sanitized'] = frag_sanitized
147 frag_content = down.read()
148 down.close()
149 return frag_content
150
151 def _append_fragment(self, ctx, frag_content):
152 try:
153 ctx['dest_stream'].write(frag_content)
154 ctx['dest_stream'].flush()
155 finally:
156 if self.__do_ytdl_file(ctx):
157 self._write_ytdl_file(ctx)
158 if not self.params.get('keep_fragments', False):
159 self.try_remove(encodeFilename(ctx['fragment_filename_sanitized']))
160 del ctx['fragment_filename_sanitized']
161
162 def _prepare_frag_download(self, ctx):
163 if 'live' not in ctx:
164 ctx['live'] = False
165 if not ctx['live']:
166 total_frags_str = '%d' % ctx['total_frags']
167 ad_frags = ctx.get('ad_frags', 0)
168 if ad_frags:
169 total_frags_str += ' (not including %d ad)' % ad_frags
170 else:
171 total_frags_str = 'unknown (live)'
172 self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}')
173 self.report_destination(ctx['filename'])
174 dl = HttpQuietDownloader(
175 self.ydl,
176 {
177 'continuedl': self.params.get('continuedl', True),
178 'quiet': self.params.get('quiet'),
179 'noprogress': True,
180 'ratelimit': self.params.get('ratelimit'),
181 'retries': self.params.get('retries', 0),
182 'nopart': self.params.get('nopart', False),
183 'test': False,
184 }
185 )
186 tmpfilename = self.temp_name(ctx['filename'])
187 open_mode = 'wb'
188 resume_len = 0
189
190 # Establish possible resume length
191 if os.path.isfile(encodeFilename(tmpfilename)):
192 open_mode = 'ab'
193 resume_len = os.path.getsize(encodeFilename(tmpfilename))
194
195 # Should be initialized before ytdl file check
196 ctx.update({
197 'tmpfilename': tmpfilename,
198 'fragment_index': 0,
199 })
200
201 if self.__do_ytdl_file(ctx):
202 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
203 self._read_ytdl_file(ctx)
204 is_corrupt = ctx.get('ytdl_corrupt') is True
205 is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
206 if is_corrupt or is_inconsistent:
207 message = (
208 '.ytdl file is corrupt' if is_corrupt else
209 'Inconsistent state of incomplete fragment download')
210 self.report_warning(
211 '%s. Restarting from the beginning ...' % message)
212 ctx['fragment_index'] = resume_len = 0
213 if 'ytdl_corrupt' in ctx:
214 del ctx['ytdl_corrupt']
215 self._write_ytdl_file(ctx)
216 else:
217 self._write_ytdl_file(ctx)
218 assert ctx['fragment_index'] == 0
219
220 dest_stream, tmpfilename = self.sanitize_open(tmpfilename, open_mode)
221
222 ctx.update({
223 'dl': dl,
224 'dest_stream': dest_stream,
225 'tmpfilename': tmpfilename,
226 # Total complete fragments downloaded so far in bytes
227 'complete_frags_downloaded_bytes': resume_len,
228 })
229
230 def _start_frag_download(self, ctx, info_dict):
231 resume_len = ctx['complete_frags_downloaded_bytes']
232 total_frags = ctx['total_frags']
233 ctx_id = ctx.get('ctx_id')
234 # This dict stores the download progress, it's updated by the progress
235 # hook
236 state = {
237 'status': 'downloading',
238 'downloaded_bytes': resume_len,
239 'fragment_index': ctx['fragment_index'],
240 'fragment_count': total_frags,
241 'filename': ctx['filename'],
242 'tmpfilename': ctx['tmpfilename'],
243 }
244
245 start = time.time()
246 ctx.update({
247 'started': start,
248 'fragment_started': start,
249 # Amount of fragment's bytes downloaded by the time of the previous
250 # frag progress hook invocation
251 'prev_frag_downloaded_bytes': 0,
252 })
253
254 def frag_progress_hook(s):
255 if s['status'] not in ('downloading', 'finished'):
256 return
257
258 if ctx_id is not None and s.get('ctx_id') != ctx_id:
259 return
260
261 state['max_progress'] = ctx.get('max_progress')
262 state['progress_idx'] = ctx.get('progress_idx')
263
264 time_now = time.time()
265 state['elapsed'] = time_now - start
266 frag_total_bytes = s.get('total_bytes') or 0
267 s['fragment_info_dict'] = s.pop('info_dict', {})
268 if not ctx['live']:
269 estimated_size = (
270 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
271 / (state['fragment_index'] + 1) * total_frags)
272 state['total_bytes_estimate'] = estimated_size
273
274 if s['status'] == 'finished':
275 state['fragment_index'] += 1
276 ctx['fragment_index'] = state['fragment_index']
277 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
278 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
279 ctx['speed'] = state['speed'] = self.calc_speed(
280 ctx['fragment_started'], time_now, frag_total_bytes)
281 ctx['fragment_started'] = time.time()
282 ctx['prev_frag_downloaded_bytes'] = 0
283 else:
284 frag_downloaded_bytes = s['downloaded_bytes']
285 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
286 if not ctx['live']:
287 state['eta'] = self.calc_eta(
288 start, time_now, estimated_size - resume_len,
289 state['downloaded_bytes'] - resume_len)
290 ctx['speed'] = state['speed'] = self.calc_speed(
291 ctx['fragment_started'], time_now, frag_downloaded_bytes)
292 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
293 self._hook_progress(state, info_dict)
294
295 ctx['dl'].add_progress_hook(frag_progress_hook)
296
297 return start
298
299 def _finish_frag_download(self, ctx, info_dict):
300 ctx['dest_stream'].close()
301 if self.__do_ytdl_file(ctx):
302 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
303 if os.path.isfile(ytdl_filename):
304 self.try_remove(ytdl_filename)
305 elapsed = time.time() - ctx['started']
306
307 if ctx['tmpfilename'] == '-':
308 downloaded_bytes = ctx['complete_frags_downloaded_bytes']
309 else:
310 self.try_rename(ctx['tmpfilename'], ctx['filename'])
311 if self.params.get('updatetime', True):
312 filetime = ctx.get('fragment_filetime')
313 if filetime:
314 with contextlib.suppress(Exception):
315 os.utime(ctx['filename'], (time.time(), filetime))
316 downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename']))
317
318 self._hook_progress({
319 'downloaded_bytes': downloaded_bytes,
320 'total_bytes': downloaded_bytes,
321 'filename': ctx['filename'],
322 'status': 'finished',
323 'elapsed': elapsed,
324 'ctx_id': ctx.get('ctx_id'),
325 'max_progress': ctx.get('max_progress'),
326 'progress_idx': ctx.get('progress_idx'),
327 }, info_dict)
328
329 def _prepare_external_frag_download(self, ctx):
330 if 'live' not in ctx:
331 ctx['live'] = False
332 if not ctx['live']:
333 total_frags_str = '%d' % ctx['total_frags']
334 ad_frags = ctx.get('ad_frags', 0)
335 if ad_frags:
336 total_frags_str += ' (not including %d ad)' % ad_frags
337 else:
338 total_frags_str = 'unknown (live)'
339 self.to_screen(f'[{self.FD_NAME}] Total fragments: {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 })
348
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
368 return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv))
369
370 return decrypt_fragment
371
372 def download_and_append_fragments_multiple(self, *args, pack_func=None, finish_func=None):
373 '''
374 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
375 all args must be either tuple or list
376 '''
377 interrupt_trigger = [True]
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', 1)
382 if max_progress > 1:
383 self._prepare_multiline_status(max_progress)
384 is_live = any(traverse_obj(args, (..., 2, 'is_live'), default=[]))
385
386 def thread_func(idx, ctx, fragments, info_dict, tpe):
387 ctx['max_progress'] = max_progress
388 ctx['progress_idx'] = idx
389 return self.download_and_append_fragments(
390 ctx, fragments, info_dict, pack_func=pack_func, finish_func=finish_func,
391 tpe=tpe, interrupt_trigger=interrupt_trigger)
392
393 class FTPE(concurrent.futures.ThreadPoolExecutor):
394 # has to stop this or it's going to wait on the worker thread itself
395 def __exit__(self, exc_type, exc_val, exc_tb):
396 pass
397
398 if compat_os_name == 'nt':
399 def future_result(future):
400 while True:
401 try:
402 return future.result(0.1)
403 except KeyboardInterrupt:
404 raise
405 except concurrent.futures.TimeoutError:
406 continue
407 else:
408 def future_result(future):
409 return future.result()
410
411 def interrupt_trigger_iter(fg):
412 for f in fg:
413 if not interrupt_trigger[0]:
414 break
415 yield f
416
417 spins = []
418 for idx, (ctx, fragments, info_dict) in enumerate(args):
419 tpe = FTPE(math.ceil(max_workers / max_progress))
420 job = tpe.submit(thread_func, idx, ctx, interrupt_trigger_iter(fragments), info_dict, tpe)
421 spins.append((tpe, job))
422
423 result = True
424 for tpe, job in spins:
425 try:
426 result = result and future_result(job)
427 except KeyboardInterrupt:
428 interrupt_trigger[0] = False
429 finally:
430 tpe.shutdown(wait=True)
431 if not interrupt_trigger[0] and not is_live:
432 raise KeyboardInterrupt()
433 # we expect the user wants to stop and DO WANT the preceding postprocessors to run;
434 # so returning a intermediate result here instead of KeyboardInterrupt on live
435 return result
436
437 def download_and_append_fragments(
438 self, ctx, fragments, info_dict, *, pack_func=None, finish_func=None,
439 tpe=None, interrupt_trigger=None):
440 if not interrupt_trigger:
441 interrupt_trigger = (True, )
442
443 fragment_retries = self.params.get('fragment_retries', 0)
444 is_fatal = (
445 ((lambda _: False) if info_dict.get('is_live') else (lambda idx: idx == 0))
446 if self.params.get('skip_unavailable_fragments', True) else (lambda _: True))
447
448 if not pack_func:
449 pack_func = lambda frag_content, _: frag_content
450
451 def download_fragment(fragment, ctx):
452 if not interrupt_trigger[0]:
453 return
454
455 frag_index = ctx['fragment_index'] = fragment['frag_index']
456 ctx['last_error'] = None
457 headers = info_dict.get('http_headers', {}).copy()
458 byte_range = fragment.get('byte_range')
459 if byte_range:
460 headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
461
462 # Never skip the first fragment
463 fatal, count = is_fatal(fragment.get('index') or (frag_index - 1)), 0
464 while count <= fragment_retries:
465 try:
466 if self._download_fragment(ctx, fragment['url'], info_dict, headers):
467 break
468 return
469 except (compat_urllib_error.HTTPError, http.client.IncompleteRead) as err:
470 # Unavailable (possibly temporary) fragments may be served.
471 # First we try to retry then either skip or abort.
472 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
473 # https://github.com/ytdl-org/youtube-dl/issues/10448).
474 count += 1
475 ctx['last_error'] = err
476 if count <= fragment_retries:
477 self.report_retry_fragment(err, frag_index, count, fragment_retries)
478 except DownloadError:
479 # Don't retry fragment if error occurred during HTTP downloading
480 # itself since it has own retry settings
481 if not fatal:
482 break
483 raise
484
485 if count > fragment_retries and fatal:
486 ctx['dest_stream'].close()
487 self.report_error('Giving up after %s fragment retries' % fragment_retries)
488
489 def append_fragment(frag_content, frag_index, ctx):
490 if frag_content:
491 self._append_fragment(ctx, pack_func(frag_content, frag_index))
492 elif not is_fatal(frag_index - 1):
493 self.report_skip_fragment(frag_index, 'fragment not found')
494 else:
495 ctx['dest_stream'].close()
496 self.report_error(f'fragment {frag_index} not found, unable to continue')
497 return False
498 return True
499
500 decrypt_fragment = self.decrypter(info_dict)
501
502 max_workers = math.ceil(
503 self.params.get('concurrent_fragment_downloads', 1) / ctx.get('max_progress', 1))
504 if can_threaded_download and max_workers > 1:
505
506 def _download_fragment(fragment):
507 ctx_copy = ctx.copy()
508 download_fragment(fragment, ctx_copy)
509 return fragment, fragment['frag_index'], ctx_copy.get('fragment_filename_sanitized')
510
511 self.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome')
512 with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
513 for fragment, frag_index, frag_filename in pool.map(_download_fragment, fragments):
514 ctx['fragment_filename_sanitized'] = frag_filename
515 ctx['fragment_index'] = frag_index
516 result = append_fragment(decrypt_fragment(fragment, self._read_fragment(ctx)), frag_index, ctx)
517 if not result:
518 return False
519 else:
520 for fragment in fragments:
521 if not interrupt_trigger[0]:
522 break
523 try:
524 download_fragment(fragment, ctx)
525 result = append_fragment(
526 decrypt_fragment(fragment, self._read_fragment(ctx)), fragment['frag_index'], ctx)
527 except KeyboardInterrupt:
528 if info_dict.get('is_live'):
529 break
530 raise
531 if not result:
532 return False
533
534 if finish_func is not None:
535 ctx['dest_stream'].write(finish_func())
536 ctx['dest_stream'].flush()
537 self._finish_frag_download(ctx, info_dict)
538 return True