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