9 import concurrent
.futures
10 can_threaded_download
= True
12 can_threaded_download
= False
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
27 class HttpQuietDownloader(HttpFD
):
28 def to_screen(self
, *args
, **kargs
):
31 def report_retry(self
, err
, count
, retries
):
33 f
'[download] Got server HTTP error: {err}. Retrying (attempt {count} of {self.format_retries(retries)}) ...')
36 class FragmentFD(FileDownloader
):
38 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
42 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
44 skip_unavailable_fragments:
45 Skip unavailable fragments (DASH and hlsnative only)
46 keep_fragments: Keep downloaded fragments on disk after downloading is
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
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:
59 Dictionary of extractor related data. TBD.
62 Dictionary of downloader related data. May contain following data:
64 Dictionary with current (being downloaded) fragment data:
65 index: 0-based index of current fragment among all fragments
67 Total count of fragments
69 This feature is experimental and file format may change in future.
72 def report_retry_fragment(self
, err
, frag_index
, count
, retries
):
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
)))
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} ...')
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
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
)
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')
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')
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']
101 ctx
['ytdl_corrupt'] = True
105 def _write_ytdl_file(self
, ctx
):
106 frag_index_stream
, _
= self
.sanitize_open(self
.ytdl_filename(ctx
['filename']), 'w')
109 'current_fragment': {
110 'index': ctx
['fragment_index'],
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}
))
119 frag_index_stream
.close()
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
= {
125 'http_headers': headers
or info_dict
.get('http_headers'),
126 'request_data': request_data
,
127 'ctx_id': ctx
.get('ctx_id'),
129 success
= ctx
['dl'].download(fragment_filename
, fragment_info_dict
)
132 if fragment_info_dict
.get('filetime'):
133 ctx
['fragment_filetime'] = fragment_info_dict
.get('filetime')
134 ctx
['fragment_filename_sanitized'] = fragment_filename
137 def _read_fragment(self
, ctx
):
138 if not ctx
.get('fragment_filename_sanitized'):
141 down
, frag_sanitized
= self
.sanitize_open(ctx
['fragment_filename_sanitized'], 'rb')
142 except FileNotFoundError
:
146 ctx
['fragment_filename_sanitized'] = frag_sanitized
147 frag_content
= down
.read()
151 def _append_fragment(self
, ctx
, frag_content
):
153 ctx
['dest_stream'].write(frag_content
)
154 ctx
['dest_stream'].flush()
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']
162 def _prepare_frag_download(self
, ctx
):
163 if 'live' not in ctx
:
166 total_frags_str
= '%d' % ctx
['total_frags']
167 ad_frags
= ctx
.get('ad_frags', 0)
169 total_frags_str
+= ' (not including %d ad)' % ad_frags
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(
177 'continuedl': self
.params
.get('continuedl', True),
178 'quiet': self
.params
.get('quiet'),
180 'ratelimit': self
.params
.get('ratelimit'),
181 'retries': self
.params
.get('retries', 0),
182 'nopart': self
.params
.get('nopart', False),
186 tmpfilename
= self
.temp_name(ctx
['filename'])
190 # Establish possible resume length
191 if os
.path
.isfile(encodeFilename(tmpfilename
)):
193 resume_len
= os
.path
.getsize(encodeFilename(tmpfilename
))
195 # Should be initialized before ytdl file check
197 'tmpfilename': tmpfilename
,
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
:
208 '.ytdl file is corrupt' if is_corrupt
else
209 'Inconsistent state of incomplete fragment download')
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
)
217 self
._write
_ytdl
_file
(ctx
)
218 assert ctx
['fragment_index'] == 0
220 dest_stream
, tmpfilename
= self
.sanitize_open(tmpfilename
, open_mode
)
224 'dest_stream': dest_stream
,
225 'tmpfilename': tmpfilename
,
226 # Total complete fragments downloaded so far in bytes
227 'complete_frags_downloaded_bytes': resume_len
,
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
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'],
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,
254 def frag_progress_hook(s
):
255 if s
['status'] not in ('downloading', 'finished'):
258 if ctx_id
is not None and s
.get('ctx_id') != ctx_id
:
261 state
['max_progress'] = ctx
.get('max_progress')
262 state
['progress_idx'] = ctx
.get('progress_idx')
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', {})
270 (ctx
['complete_frags_downloaded_bytes'] + frag_total_bytes
)
271 / (state
['fragment_index'] + 1) * total_frags
)
272 state
['total_bytes_estimate'] = estimated_size
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
284 frag_downloaded_bytes
= s
['downloaded_bytes']
285 state
['downloaded_bytes'] += frag_downloaded_bytes
- ctx
['prev_frag_downloaded_bytes']
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
)
295 ctx
['dl'].add_progress_hook(frag_progress_hook
)
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']
307 if ctx
['tmpfilename'] == '-':
308 downloaded_bytes
= ctx
['complete_frags_downloaded_bytes']
310 self
.try_rename(ctx
['tmpfilename'], ctx
['filename'])
311 if self
.params
.get('updatetime', True):
312 filetime
= ctx
.get('fragment_filetime')
314 with contextlib
.suppress(Exception):
315 os
.utime(ctx
['filename'], (time
.time(), filetime
))
316 downloaded_bytes
= os
.path
.getsize(encodeFilename(ctx
['filename']))
318 self
._hook
_progress
({
319 'downloaded_bytes': downloaded_bytes
,
320 'total_bytes': downloaded_bytes
,
321 'filename': ctx
['filename'],
322 'status': 'finished',
324 'ctx_id': ctx
.get('ctx_id'),
325 'max_progress': ctx
.get('max_progress'),
326 'progress_idx': ctx
.get('progress_idx'),
329 def _prepare_external_frag_download(self
, ctx
):
330 if 'live' not in ctx
:
333 total_frags_str
= '%d' % ctx
['total_frags']
334 ad_frags
= ctx
.get('ad_frags', 0)
336 total_frags_str
+= ' (not including %d ad)' % ad_frags
338 total_frags_str
= 'unknown (live)'
339 self
.to_screen(f
'[{self.FD_NAME}] Total fragments: {total_frags_str}')
341 tmpfilename
= self
.temp_name(ctx
['filename'])
343 # Should be initialized before ytdl file check
345 'tmpfilename': tmpfilename
,
349 def decrypter(self
, info_dict
):
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
]
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':
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):
368 return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content
, decrypt_info
['KEY'], iv
))
370 return decrypt_fragment
372 def download_and_append_fragments_multiple(self
, *args
, pack_func
=None, finish_func
=None):
374 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
375 all args must be either tuple or list
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)
383 self
._prepare
_multiline
_status
(max_progress
)
384 is_live
= any(traverse_obj(args
, (..., 2, 'is_live'), default
=[]))
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
)
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
):
398 if compat_os_name
== 'nt':
399 def future_result(future
):
402 return future
.result(0.1)
403 except KeyboardInterrupt:
405 except concurrent
.futures
.TimeoutError
:
408 def future_result(future
):
409 return future
.result()
411 def interrupt_trigger_iter(fg
):
413 if not interrupt_trigger
[0]:
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
))
424 for tpe
, job
in spins
:
426 result
= result
and future_result(job
)
427 except KeyboardInterrupt:
428 interrupt_trigger
[0] = False
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
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, )
443 fragment_retries
= self
.params
.get('fragment_retries', 0)
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))
449 pack_func
= lambda frag_content
, _
: frag_content
451 def download_fragment(fragment
, ctx
):
452 if not interrupt_trigger
[0]:
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')
460 headers
['Range'] = 'bytes=%d-%d' % (byte_range
['start'], byte_range
['end'] - 1)
462 # Never skip the first fragment
463 fatal
, count
= is_fatal(fragment
.get('index') or (frag_index
- 1)), 0
464 while count
<= fragment_retries
:
466 if self
._download
_fragment
(ctx
, fragment
['url'], info_dict
, headers
):
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).
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
485 if count
> fragment_retries
and fatal
:
486 ctx
['dest_stream'].close()
487 self
.report_error('Giving up after %s fragment retries' % fragment_retries
)
489 def append_fragment(frag_content
, frag_index
, ctx
):
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')
495 ctx
['dest_stream'].close()
496 self
.report_error(f
'fragment {frag_index} not found, unable to continue')
500 decrypt_fragment
= self
.decrypter(info_dict
)
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:
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')
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
)
520 for fragment
in fragments
:
521 if not interrupt_trigger
[0]:
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'):
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
)