1 import concurrent
.futures
9 from .common
import FileDownloader
10 from .http
import HttpFD
11 from ..aes
import aes_cbc_decrypt_bytes
, unpad_pkcs7
12 from ..compat
import compat_os_name
, compat_struct_pack
, compat_urllib_error
22 class HttpQuietDownloader(HttpFD
):
23 def to_screen(self
, *args
, **kargs
):
26 console_title
= to_screen
29 class FragmentFD(FileDownloader
):
31 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
35 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
37 skip_unavailable_fragments:
38 Skip unavailable fragments (DASH and hlsnative only)
39 keep_fragments: Keep downloaded fragments on disk after downloading is
41 concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
42 _no_ytdl_file: Don't use .ytdl file
44 For each incomplete fragment download yt-dlp keeps on disk a special
45 bookkeeping file with download state and metadata (in future such files will
46 be used for any incomplete download handled by yt-dlp). This file is
47 used to properly handle resuming, check download file consistency and detect
48 potential errors. The file has a .ytdl extension and represents a standard
49 JSON file of the following format:
52 Dictionary of extractor related data. TBD.
55 Dictionary of downloader related data. May contain following data:
57 Dictionary with current (being downloaded) fragment data:
58 index: 0-based index of current fragment among all fragments
60 Total count of fragments
62 This feature is experimental and file format may change in future.
65 def report_retry_fragment(self
, err
, frag_index
, count
, retries
):
67 '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...'
68 % (error_to_compat_str(err
), frag_index
, count
, self
.format_retries(retries
)))
69 self
.sleep_retry('fragment', count
)
71 def report_skip_fragment(self
, frag_index
, err
=None):
72 err
= f
' {err};' if err
else ''
73 self
.to_screen(f
'[download]{err} Skipping fragment {frag_index:d} ...')
75 def _prepare_url(self
, info_dict
, url
):
76 headers
= info_dict
.get('http_headers')
77 return sanitized_Request(url
, None, headers
) if headers
else url
79 def _prepare_and_start_frag_download(self
, ctx
, info_dict
):
80 self
._prepare
_frag
_download
(ctx
)
81 self
._start
_frag
_download
(ctx
, info_dict
)
83 def __do_ytdl_file(self
, ctx
):
84 return ctx
['live'] is not True and ctx
['tmpfilename'] != '-' and not self
.params
.get('_no_ytdl_file')
86 def _read_ytdl_file(self
, ctx
):
87 assert 'ytdl_corrupt' not in ctx
88 stream
, _
= self
.sanitize_open(self
.ytdl_filename(ctx
['filename']), 'r')
90 ytdl_data
= json
.loads(stream
.read())
91 ctx
['fragment_index'] = ytdl_data
['downloader']['current_fragment']['index']
92 if 'extra_state' in ytdl_data
['downloader']:
93 ctx
['extra_state'] = ytdl_data
['downloader']['extra_state']
95 ctx
['ytdl_corrupt'] = True
99 def _write_ytdl_file(self
, ctx
):
100 frag_index_stream
, _
= self
.sanitize_open(self
.ytdl_filename(ctx
['filename']), 'w')
103 'current_fragment': {
104 'index': ctx
['fragment_index'],
107 if 'extra_state' in ctx
:
108 downloader
['extra_state'] = ctx
['extra_state']
109 if ctx
.get('fragment_count') is not None:
110 downloader
['fragment_count'] = ctx
['fragment_count']
111 frag_index_stream
.write(json
.dumps({'downloader': downloader}
))
113 frag_index_stream
.close()
115 def _download_fragment(self
, ctx
, frag_url
, info_dict
, headers
=None, request_data
=None):
116 fragment_filename
= '%s-Frag%d' % (ctx
['tmpfilename'], ctx
['fragment_index'])
117 fragment_info_dict
= {
119 'http_headers': headers
or info_dict
.get('http_headers'),
120 'request_data': request_data
,
121 'ctx_id': ctx
.get('ctx_id'),
123 success
, _
= ctx
['dl'].download(fragment_filename
, fragment_info_dict
)
126 if fragment_info_dict
.get('filetime'):
127 ctx
['fragment_filetime'] = fragment_info_dict
.get('filetime')
128 ctx
['fragment_filename_sanitized'] = fragment_filename
131 def _read_fragment(self
, ctx
):
132 if not ctx
.get('fragment_filename_sanitized'):
135 down
, frag_sanitized
= self
.sanitize_open(ctx
['fragment_filename_sanitized'], 'rb')
136 except FileNotFoundError
:
140 ctx
['fragment_filename_sanitized'] = frag_sanitized
141 frag_content
= down
.read()
145 def _append_fragment(self
, ctx
, frag_content
):
147 ctx
['dest_stream'].write(frag_content
)
148 ctx
['dest_stream'].flush()
150 if self
.__do
_ytdl
_file
(ctx
):
151 self
._write
_ytdl
_file
(ctx
)
152 if not self
.params
.get('keep_fragments', False):
153 self
.try_remove(encodeFilename(ctx
['fragment_filename_sanitized']))
154 del ctx
['fragment_filename_sanitized']
156 def _prepare_frag_download(self
, ctx
):
157 if 'live' not in ctx
:
160 total_frags_str
= '%d' % ctx
['total_frags']
161 ad_frags
= ctx
.get('ad_frags', 0)
163 total_frags_str
+= ' (not including %d ad)' % ad_frags
165 total_frags_str
= 'unknown (live)'
166 self
.to_screen(f
'[{self.FD_NAME}] Total fragments: {total_frags_str}')
167 self
.report_destination(ctx
['filename'])
168 dl
= HttpQuietDownloader(self
.ydl
, {
173 tmpfilename
= self
.temp_name(ctx
['filename'])
177 # Establish possible resume length
178 if os
.path
.isfile(encodeFilename(tmpfilename
)):
180 resume_len
= os
.path
.getsize(encodeFilename(tmpfilename
))
182 # Should be initialized before ytdl file check
184 'tmpfilename': tmpfilename
,
188 if self
.__do
_ytdl
_file
(ctx
):
189 if os
.path
.isfile(encodeFilename(self
.ytdl_filename(ctx
['filename']))):
190 self
._read
_ytdl
_file
(ctx
)
191 is_corrupt
= ctx
.get('ytdl_corrupt') is True
192 is_inconsistent
= ctx
['fragment_index'] > 0 and resume_len
== 0
193 if is_corrupt
or is_inconsistent
:
195 '.ytdl file is corrupt' if is_corrupt
else
196 'Inconsistent state of incomplete fragment download')
198 '%s. Restarting from the beginning ...' % message
)
199 ctx
['fragment_index'] = resume_len
= 0
200 if 'ytdl_corrupt' in ctx
:
201 del ctx
['ytdl_corrupt']
202 self
._write
_ytdl
_file
(ctx
)
204 self
._write
_ytdl
_file
(ctx
)
205 assert ctx
['fragment_index'] == 0
207 dest_stream
, tmpfilename
= self
.sanitize_open(tmpfilename
, open_mode
)
211 'dest_stream': dest_stream
,
212 'tmpfilename': tmpfilename
,
213 # Total complete fragments downloaded so far in bytes
214 'complete_frags_downloaded_bytes': resume_len
,
217 def _start_frag_download(self
, ctx
, info_dict
):
218 resume_len
= ctx
['complete_frags_downloaded_bytes']
219 total_frags
= ctx
['total_frags']
220 ctx_id
= ctx
.get('ctx_id')
221 # This dict stores the download progress, it's updated by the progress
224 'status': 'downloading',
225 'downloaded_bytes': resume_len
,
226 'fragment_index': ctx
['fragment_index'],
227 'fragment_count': total_frags
,
228 'filename': ctx
['filename'],
229 'tmpfilename': ctx
['tmpfilename'],
235 'fragment_started': start
,
236 # Amount of fragment's bytes downloaded by the time of the previous
237 # frag progress hook invocation
238 'prev_frag_downloaded_bytes': 0,
241 def frag_progress_hook(s
):
242 if s
['status'] not in ('downloading', 'finished'):
245 if ctx_id
is not None and s
.get('ctx_id') != ctx_id
:
248 state
['max_progress'] = ctx
.get('max_progress')
249 state
['progress_idx'] = ctx
.get('progress_idx')
251 time_now
= time
.time()
252 state
['elapsed'] = time_now
- start
253 frag_total_bytes
= s
.get('total_bytes') or 0
254 s
['fragment_info_dict'] = s
.pop('info_dict', {})
257 (ctx
['complete_frags_downloaded_bytes'] + frag_total_bytes
)
258 / (state
['fragment_index'] + 1) * total_frags
)
259 state
['total_bytes_estimate'] = estimated_size
261 if s
['status'] == 'finished':
262 state
['fragment_index'] += 1
263 ctx
['fragment_index'] = state
['fragment_index']
264 state
['downloaded_bytes'] += frag_total_bytes
- ctx
['prev_frag_downloaded_bytes']
265 ctx
['complete_frags_downloaded_bytes'] = state
['downloaded_bytes']
266 ctx
['speed'] = state
['speed'] = self
.calc_speed(
267 ctx
['fragment_started'], time_now
, frag_total_bytes
)
268 ctx
['fragment_started'] = time
.time()
269 ctx
['prev_frag_downloaded_bytes'] = 0
271 frag_downloaded_bytes
= s
['downloaded_bytes']
272 state
['downloaded_bytes'] += frag_downloaded_bytes
- ctx
['prev_frag_downloaded_bytes']
274 state
['eta'] = self
.calc_eta(
275 start
, time_now
, estimated_size
- resume_len
,
276 state
['downloaded_bytes'] - resume_len
)
277 ctx
['speed'] = state
['speed'] = self
.calc_speed(
278 ctx
['fragment_started'], time_now
, frag_downloaded_bytes
)
279 ctx
['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
280 self
._hook
_progress
(state
, info_dict
)
282 ctx
['dl'].add_progress_hook(frag_progress_hook
)
286 def _finish_frag_download(self
, ctx
, info_dict
):
287 ctx
['dest_stream'].close()
288 if self
.__do
_ytdl
_file
(ctx
):
289 ytdl_filename
= encodeFilename(self
.ytdl_filename(ctx
['filename']))
290 if os
.path
.isfile(ytdl_filename
):
291 self
.try_remove(ytdl_filename
)
292 elapsed
= time
.time() - ctx
['started']
294 if ctx
['tmpfilename'] == '-':
295 downloaded_bytes
= ctx
['complete_frags_downloaded_bytes']
297 self
.try_rename(ctx
['tmpfilename'], ctx
['filename'])
298 if self
.params
.get('updatetime', True):
299 filetime
= ctx
.get('fragment_filetime')
301 with contextlib
.suppress(Exception):
302 os
.utime(ctx
['filename'], (time
.time(), filetime
))
303 downloaded_bytes
= os
.path
.getsize(encodeFilename(ctx
['filename']))
305 self
._hook
_progress
({
306 'downloaded_bytes': downloaded_bytes
,
307 'total_bytes': downloaded_bytes
,
308 'filename': ctx
['filename'],
309 'status': 'finished',
311 'ctx_id': ctx
.get('ctx_id'),
312 'max_progress': ctx
.get('max_progress'),
313 'progress_idx': ctx
.get('progress_idx'),
316 def _prepare_external_frag_download(self
, ctx
):
317 if 'live' not in ctx
:
320 total_frags_str
= '%d' % ctx
['total_frags']
321 ad_frags
= ctx
.get('ad_frags', 0)
323 total_frags_str
+= ' (not including %d ad)' % ad_frags
325 total_frags_str
= 'unknown (live)'
326 self
.to_screen(f
'[{self.FD_NAME}] Total fragments: {total_frags_str}')
328 tmpfilename
= self
.temp_name(ctx
['filename'])
330 # Should be initialized before ytdl file check
332 'tmpfilename': tmpfilename
,
336 def decrypter(self
, info_dict
):
340 if url
not in _key_cache
:
341 _key_cache
[url
] = self
.ydl
.urlopen(self
._prepare
_url
(info_dict
, url
)).read()
342 return _key_cache
[url
]
344 def decrypt_fragment(fragment
, frag_content
):
345 decrypt_info
= fragment
.get('decrypt_info')
346 if not decrypt_info
or decrypt_info
['METHOD'] != 'AES-128':
348 iv
= decrypt_info
.get('IV') or compat_struct_pack('>8xq', fragment
['media_sequence'])
349 decrypt_info
['KEY'] = decrypt_info
.get('KEY') or _get_key(info_dict
.get('_decryption_key_url') or decrypt_info
['URI'])
350 # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
351 # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
352 # not what it decrypts to.
353 if self
.params
.get('test', False):
355 return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content
, decrypt_info
['KEY'], iv
))
357 return decrypt_fragment
359 def download_and_append_fragments_multiple(self
, *args
, pack_func
=None, finish_func
=None):
361 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
362 all args must be either tuple or list
364 interrupt_trigger
= [True]
365 max_progress
= len(args
)
366 if max_progress
== 1:
367 return self
.download_and_append_fragments(*args
[0], pack_func
=pack_func
, finish_func
=finish_func
)
368 max_workers
= self
.params
.get('concurrent_fragment_downloads', 1)
370 self
._prepare
_multiline
_status
(max_progress
)
371 is_live
= any(traverse_obj(args
, (..., 2, 'is_live'), default
=[]))
373 def thread_func(idx
, ctx
, fragments
, info_dict
, tpe
):
374 ctx
['max_progress'] = max_progress
375 ctx
['progress_idx'] = idx
376 return self
.download_and_append_fragments(
377 ctx
, fragments
, info_dict
, pack_func
=pack_func
, finish_func
=finish_func
,
378 tpe
=tpe
, interrupt_trigger
=interrupt_trigger
)
380 class FTPE(concurrent
.futures
.ThreadPoolExecutor
):
381 # has to stop this or it's going to wait on the worker thread itself
382 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
385 if compat_os_name
== 'nt':
386 def future_result(future
):
389 return future
.result(0.1)
390 except KeyboardInterrupt:
392 except concurrent
.futures
.TimeoutError
:
395 def future_result(future
):
396 return future
.result()
398 def interrupt_trigger_iter(fg
):
400 if not interrupt_trigger
[0]:
405 for idx
, (ctx
, fragments
, info_dict
) in enumerate(args
):
406 tpe
= FTPE(math
.ceil(max_workers
/ max_progress
))
407 job
= tpe
.submit(thread_func
, idx
, ctx
, interrupt_trigger_iter(fragments
), info_dict
, tpe
)
408 spins
.append((tpe
, job
))
411 for tpe
, job
in spins
:
413 result
= result
and future_result(job
)
414 except KeyboardInterrupt:
415 interrupt_trigger
[0] = False
417 tpe
.shutdown(wait
=True)
418 if not interrupt_trigger
[0] and not is_live
:
419 raise KeyboardInterrupt()
420 # we expect the user wants to stop and DO WANT the preceding postprocessors to run;
421 # so returning a intermediate result here instead of KeyboardInterrupt on live
424 def download_and_append_fragments(
425 self
, ctx
, fragments
, info_dict
, *, pack_func
=None, finish_func
=None,
426 tpe
=None, interrupt_trigger
=None):
427 if not interrupt_trigger
:
428 interrupt_trigger
= (True, )
430 fragment_retries
= self
.params
.get('fragment_retries', 0)
432 ((lambda _
: False) if info_dict
.get('is_live') else (lambda idx
: idx
== 0))
433 if self
.params
.get('skip_unavailable_fragments', True) else (lambda _
: True))
436 pack_func
= lambda frag_content
, _
: frag_content
438 def download_fragment(fragment
, ctx
):
439 if not interrupt_trigger
[0]:
442 frag_index
= ctx
['fragment_index'] = fragment
['frag_index']
443 ctx
['last_error'] = None
444 headers
= info_dict
.get('http_headers', {}).copy()
445 byte_range
= fragment
.get('byte_range')
447 headers
['Range'] = 'bytes=%d-%d' % (byte_range
['start'], byte_range
['end'] - 1)
449 # Never skip the first fragment
450 fatal
, count
= is_fatal(fragment
.get('index') or (frag_index
- 1)), 0
451 while count
<= fragment_retries
:
453 if self
._download
_fragment
(ctx
, fragment
['url'], info_dict
, headers
):
456 except (compat_urllib_error
.HTTPError
, http
.client
.IncompleteRead
) as err
:
457 # Unavailable (possibly temporary) fragments may be served.
458 # First we try to retry then either skip or abort.
459 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
460 # https://github.com/ytdl-org/youtube-dl/issues/10448).
462 ctx
['last_error'] = err
463 if count
<= fragment_retries
:
464 self
.report_retry_fragment(err
, frag_index
, count
, fragment_retries
)
465 except DownloadError
:
466 # Don't retry fragment if error occurred during HTTP downloading
467 # itself since it has own retry settings
472 if count
> fragment_retries
and fatal
:
473 ctx
['dest_stream'].close()
474 self
.report_error('Giving up after %s fragment retries' % fragment_retries
)
476 def append_fragment(frag_content
, frag_index
, ctx
):
478 self
._append
_fragment
(ctx
, pack_func(frag_content
, frag_index
))
479 elif not is_fatal(frag_index
- 1):
480 self
.report_skip_fragment(frag_index
, 'fragment not found')
482 ctx
['dest_stream'].close()
483 self
.report_error(f
'fragment {frag_index} not found, unable to continue')
487 decrypt_fragment
= self
.decrypter(info_dict
)
489 max_workers
= math
.ceil(
490 self
.params
.get('concurrent_fragment_downloads', 1) / ctx
.get('max_progress', 1))
492 def _download_fragment(fragment
):
493 ctx_copy
= ctx
.copy()
494 download_fragment(fragment
, ctx_copy
)
495 return fragment
, fragment
['frag_index'], ctx_copy
.get('fragment_filename_sanitized')
497 self
.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome')
498 with tpe
or concurrent
.futures
.ThreadPoolExecutor(max_workers
) as pool
:
499 for fragment
, frag_index
, frag_filename
in pool
.map(_download_fragment
, fragments
):
500 ctx
['fragment_filename_sanitized'] = frag_filename
501 ctx
['fragment_index'] = frag_index
502 result
= append_fragment(decrypt_fragment(fragment
, self
._read
_fragment
(ctx
)), frag_index
, ctx
)
506 for fragment
in fragments
:
507 if not interrupt_trigger
[0]:
510 download_fragment(fragment
, ctx
)
511 result
= append_fragment(
512 decrypt_fragment(fragment
, self
._read
_fragment
(ctx
)), fragment
['frag_index'], ctx
)
513 except KeyboardInterrupt:
514 if info_dict
.get('is_live'):
520 if finish_func
is not None:
521 ctx
['dest_stream'].write(finish_func())
522 ctx
['dest_stream'].flush()
523 self
._finish
_frag
_download
(ctx
, info_dict
)