1 from __future__
import division
, unicode_literals
10 import concurrent
.futures
11 can_threaded_download
= True
13 can_threaded_download
= False
15 from .common
import FileDownloader
16 from .http
import HttpFD
17 from ..aes
import aes_cbc_decrypt_bytes
18 from ..compat
import (
32 class HttpQuietDownloader(HttpFD
):
33 def to_screen(self
, *args
, **kargs
):
36 def report_retry(self
, err
, count
, retries
):
38 f
'[download] Got server HTTP error: {err}. Retrying (attempt {count} of {self.format_retries(retries)}) ...')
41 class FragmentFD(FileDownloader
):
43 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
47 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
49 skip_unavailable_fragments:
50 Skip unavailable fragments (DASH and hlsnative only)
51 keep_fragments: Keep downloaded fragments on disk after downloading is
53 concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
54 _no_ytdl_file: Don't use .ytdl file
56 For each incomplete fragment download yt-dlp keeps on disk a special
57 bookkeeping file with download state and metadata (in future such files will
58 be used for any incomplete download handled by yt-dlp). This file is
59 used to properly handle resuming, check download file consistency and detect
60 potential errors. The file has a .ytdl extension and represents a standard
61 JSON file of the following format:
64 Dictionary of extractor related data. TBD.
67 Dictionary of downloader related data. May contain following data:
69 Dictionary with current (being downloaded) fragment data:
70 index: 0-based index of current fragment among all fragments
72 Total count of fragments
74 This feature is experimental and file format may change in future.
77 def report_retry_fragment(self
, err
, frag_index
, count
, retries
):
79 '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...'
80 % (error_to_compat_str(err
), frag_index
, count
, self
.format_retries(retries
)))
82 def report_skip_fragment(self
, frag_index
, err
=None):
83 err
= f
' {err};' if err
else ''
84 self
.to_screen(f
'[download]{err} Skipping fragment {frag_index:d} ...')
86 def _prepare_url(self
, info_dict
, url
):
87 headers
= info_dict
.get('http_headers')
88 return sanitized_Request(url
, None, headers
) if headers
else url
90 def _prepare_and_start_frag_download(self
, ctx
, info_dict
):
91 self
._prepare
_frag
_download
(ctx
)
92 self
._start
_frag
_download
(ctx
, info_dict
)
94 def __do_ytdl_file(self
, ctx
):
95 return ctx
['live'] is not True and ctx
['tmpfilename'] != '-' and not self
.params
.get('_no_ytdl_file')
97 def _read_ytdl_file(self
, ctx
):
98 assert 'ytdl_corrupt' not in ctx
99 stream
, _
= sanitize_open(self
.ytdl_filename(ctx
['filename']), 'r')
101 ytdl_data
= json
.loads(stream
.read())
102 ctx
['fragment_index'] = ytdl_data
['downloader']['current_fragment']['index']
103 if 'extra_state' in ytdl_data
['downloader']:
104 ctx
['extra_state'] = ytdl_data
['downloader']['extra_state']
106 ctx
['ytdl_corrupt'] = True
110 def _write_ytdl_file(self
, ctx
):
111 frag_index_stream
, _
= sanitize_open(self
.ytdl_filename(ctx
['filename']), 'w')
114 'current_fragment': {
115 'index': ctx
['fragment_index'],
118 if 'extra_state' in ctx
:
119 downloader
['extra_state'] = ctx
['extra_state']
120 if ctx
.get('fragment_count') is not None:
121 downloader
['fragment_count'] = ctx
['fragment_count']
122 frag_index_stream
.write(json
.dumps({'downloader': downloader}
))
124 frag_index_stream
.close()
126 def _download_fragment(self
, ctx
, frag_url
, info_dict
, headers
=None, request_data
=None):
127 fragment_filename
= '%s-Frag%d' % (ctx
['tmpfilename'], ctx
['fragment_index'])
128 fragment_info_dict
= {
130 'http_headers': headers
or info_dict
.get('http_headers'),
131 'request_data': request_data
,
132 'ctx_id': ctx
.get('ctx_id'),
134 success
= ctx
['dl'].download(fragment_filename
, fragment_info_dict
)
137 if fragment_info_dict
.get('filetime'):
138 ctx
['fragment_filetime'] = fragment_info_dict
.get('filetime')
139 ctx
['fragment_filename_sanitized'] = fragment_filename
140 return True, self
._read
_fragment
(ctx
)
142 def _read_fragment(self
, ctx
):
143 down
, frag_sanitized
= sanitize_open(ctx
['fragment_filename_sanitized'], 'rb')
144 ctx
['fragment_filename_sanitized'] = frag_sanitized
145 frag_content
= down
.read()
149 def _append_fragment(self
, ctx
, frag_content
):
151 ctx
['dest_stream'].write(frag_content
)
152 ctx
['dest_stream'].flush()
154 if self
.__do
_ytdl
_file
(ctx
):
155 self
._write
_ytdl
_file
(ctx
)
156 if not self
.params
.get('keep_fragments', False):
157 os
.remove(encodeFilename(ctx
['fragment_filename_sanitized']))
158 del ctx
['fragment_filename_sanitized']
160 def _prepare_frag_download(self
, ctx
):
161 if 'live' not in ctx
:
164 total_frags_str
= '%d' % ctx
['total_frags']
165 ad_frags
= ctx
.get('ad_frags', 0)
167 total_frags_str
+= ' (not including %d ad)' % ad_frags
169 total_frags_str
= 'unknown (live)'
171 '[%s] Total fragments: %s' % (self
.FD_NAME
, total_frags_str
))
172 self
.report_destination(ctx
['filename'])
173 dl
= HttpQuietDownloader(
177 'quiet': self
.params
.get('quiet'),
179 'ratelimit': self
.params
.get('ratelimit'),
180 'retries': self
.params
.get('retries', 0),
181 'nopart': self
.params
.get('nopart', False),
182 'test': self
.params
.get('test', False),
185 tmpfilename
= self
.temp_name(ctx
['filename'])
189 # Establish possible resume length
190 if os
.path
.isfile(encodeFilename(tmpfilename
)):
192 resume_len
= os
.path
.getsize(encodeFilename(tmpfilename
))
194 # Should be initialized before ytdl file check
196 'tmpfilename': tmpfilename
,
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
:
207 '.ytdl file is corrupt' if is_corrupt
else
208 'Inconsistent state of incomplete fragment download')
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
)
216 self
._write
_ytdl
_file
(ctx
)
217 assert ctx
['fragment_index'] == 0
219 dest_stream
, tmpfilename
= sanitize_open(tmpfilename
, open_mode
)
223 'dest_stream': dest_stream
,
224 'tmpfilename': tmpfilename
,
225 # Total complete fragments downloaded so far in bytes
226 'complete_frags_downloaded_bytes': resume_len
,
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
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'],
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,
253 def frag_progress_hook(s
):
254 if s
['status'] not in ('downloading', 'finished'):
257 if ctx_id
is not None and s
.get('ctx_id') != ctx_id
:
260 state
['max_progress'] = ctx
.get('max_progress')
261 state
['progress_idx'] = ctx
.get('progress_idx')
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', {})
269 (ctx
['complete_frags_downloaded_bytes'] + frag_total_bytes
)
270 / (state
['fragment_index'] + 1) * total_frags
)
271 state
['total_bytes_estimate'] = estimated_size
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
283 frag_downloaded_bytes
= s
['downloaded_bytes']
284 state
['downloaded_bytes'] += frag_downloaded_bytes
- ctx
['prev_frag_downloaded_bytes']
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
)
294 ctx
['dl'].add_progress_hook(frag_progress_hook
)
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 os
.remove(ytdl_filename
)
304 elapsed
= time
.time() - ctx
['started']
306 if ctx
['tmpfilename'] == '-':
307 downloaded_bytes
= ctx
['complete_frags_downloaded_bytes']
309 self
.try_rename(ctx
['tmpfilename'], ctx
['filename'])
310 if self
.params
.get('updatetime', True):
311 filetime
= ctx
.get('fragment_filetime')
314 os
.utime(ctx
['filename'], (time
.time(), filetime
))
317 downloaded_bytes
= os
.path
.getsize(encodeFilename(ctx
['filename']))
319 self
._hook
_progress
({
320 'downloaded_bytes': downloaded_bytes
,
321 'total_bytes': downloaded_bytes
,
322 'filename': ctx
['filename'],
323 'status': 'finished',
325 'ctx_id': ctx
.get('ctx_id'),
326 'max_progress': ctx
.get('max_progress'),
327 'progress_idx': ctx
.get('progress_idx'),
330 def _prepare_external_frag_download(self
, ctx
):
331 if 'live' not in ctx
:
334 total_frags_str
= '%d' % ctx
['total_frags']
335 ad_frags
= ctx
.get('ad_frags', 0)
337 total_frags_str
+= ' (not including %d ad)' % ad_frags
339 total_frags_str
= 'unknown (live)'
341 '[%s] Total fragments: %s' % (self
.FD_NAME
, total_frags_str
))
343 tmpfilename
= self
.temp_name(ctx
['filename'])
345 # Should be initialized before ytdl file check
347 'tmpfilename': tmpfilename
,
351 def decrypter(self
, info_dict
):
355 if url
not in _key_cache
:
356 _key_cache
[url
] = self
.ydl
.urlopen(self
._prepare
_url
(info_dict
, url
)).read()
357 return _key_cache
[url
]
359 def decrypt_fragment(fragment
, frag_content
):
360 decrypt_info
= fragment
.get('decrypt_info')
361 if not decrypt_info
or decrypt_info
['METHOD'] != 'AES-128':
363 iv
= decrypt_info
.get('IV') or compat_struct_pack('>8xq', fragment
['media_sequence'])
364 decrypt_info
['KEY'] = decrypt_info
.get('KEY') or _get_key(info_dict
.get('_decryption_key_url') or decrypt_info
['URI'])
365 # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
366 # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
367 # not what it decrypts to.
368 if self
.params
.get('test', False):
370 decrypted_data
= aes_cbc_decrypt_bytes(frag_content
, decrypt_info
['KEY'], iv
)
371 return decrypted_data
[:-decrypted_data
[-1]]
373 return decrypt_fragment
375 def download_and_append_fragments_multiple(self
, *args
, pack_func
=None, finish_func
=None):
377 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
378 all args must be either tuple or list
380 interrupt_trigger
= [True]
381 max_progress
= len(args
)
382 if max_progress
== 1:
383 return self
.download_and_append_fragments(*args
[0], pack_func
=pack_func
, finish_func
=finish_func
)
384 max_workers
= self
.params
.get('concurrent_fragment_downloads', 1)
386 self
._prepare
_multiline
_status
(max_progress
)
388 def thread_func(idx
, ctx
, fragments
, info_dict
, tpe
):
389 ctx
['max_progress'] = max_progress
390 ctx
['progress_idx'] = idx
391 return self
.download_and_append_fragments(
392 ctx
, fragments
, info_dict
, pack_func
=pack_func
, finish_func
=finish_func
,
393 tpe
=tpe
, interrupt_trigger
=interrupt_trigger
)
395 class FTPE(concurrent
.futures
.ThreadPoolExecutor
):
396 # has to stop this or it's going to wait on the worker thread itself
397 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
401 if compat_os_name
== 'nt':
402 self
.report_warning('Ctrl+C does not work on Windows when used with parallel threads. '
403 'This is a known issue and patches are welcome')
404 for idx
, (ctx
, fragments
, info_dict
) in enumerate(args
):
405 tpe
= FTPE(math
.ceil(max_workers
/ max_progress
))
406 job
= tpe
.submit(thread_func
, idx
, ctx
, fragments
, info_dict
, tpe
)
407 spins
.append((tpe
, job
))
410 for tpe
, job
in spins
:
412 result
= result
and job
.result()
413 except KeyboardInterrupt:
414 interrupt_trigger
[0] = False
416 tpe
.shutdown(wait
=True)
417 if not interrupt_trigger
[0]:
418 raise KeyboardInterrupt()
421 def download_and_append_fragments(
422 self
, ctx
, fragments
, info_dict
, *, pack_func
=None, finish_func
=None,
423 tpe
=None, interrupt_trigger
=None):
424 if not interrupt_trigger
:
425 interrupt_trigger
= (True, )
427 fragment_retries
= self
.params
.get('fragment_retries', 0)
429 ((lambda _
: False) if info_dict
.get('is_live') else (lambda idx
: idx
== 0))
430 if self
.params
.get('skip_unavailable_fragments', True) else (lambda _
: True))
433 pack_func
= lambda frag_content
, _
: frag_content
435 def download_fragment(fragment
, ctx
):
436 frag_index
= ctx
['fragment_index'] = fragment
['frag_index']
437 if not interrupt_trigger
[0]:
438 return False, frag_index
439 headers
= info_dict
.get('http_headers', {}).copy()
440 byte_range
= fragment
.get('byte_range')
442 headers
['Range'] = 'bytes=%d-%d' % (byte_range
['start'], byte_range
['end'] - 1)
444 # Never skip the first fragment
445 fatal
= is_fatal(fragment
.get('index') or (frag_index
- 1))
446 count
, frag_content
= 0, None
447 while count
<= fragment_retries
:
449 success
, frag_content
= self
._download
_fragment
(ctx
, fragment
['url'], info_dict
, headers
)
451 return False, frag_index
453 except (compat_urllib_error
.HTTPError
, http
.client
.IncompleteRead
) as err
:
454 # Unavailable (possibly temporary) fragments may be served.
455 # First we try to retry then either skip or abort.
456 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
457 # https://github.com/ytdl-org/youtube-dl/issues/10448).
459 if count
<= fragment_retries
:
460 self
.report_retry_fragment(err
, frag_index
, count
, fragment_retries
)
461 except DownloadError
:
462 # Don't retry fragment if error occurred during HTTP downloading
463 # itself since it has own retry settings
468 if count
> fragment_retries
:
470 return False, frag_index
471 ctx
['dest_stream'].close()
472 self
.report_error('Giving up after %s fragment retries' % fragment_retries
)
473 return False, frag_index
474 return frag_content
, frag_index
476 def append_fragment(frag_content
, frag_index
, ctx
):
478 if not is_fatal(frag_index
- 1):
479 self
.report_skip_fragment(frag_index
, 'fragment not found')
482 ctx
['dest_stream'].close()
484 'fragment %s not found, unable to continue' % frag_index
)
486 self
._append
_fragment
(ctx
, pack_func(frag_content
, frag_index
))
489 decrypt_fragment
= self
.decrypter(info_dict
)
491 max_workers
= math
.ceil(
492 self
.params
.get('concurrent_fragment_downloads', 1) / ctx
.get('max_progress', 1))
493 if can_threaded_download
and max_workers
> 1:
495 def _download_fragment(fragment
):
496 ctx_copy
= ctx
.copy()
497 frag_content
, frag_index
= download_fragment(fragment
, ctx_copy
)
498 return fragment
, frag_content
, frag_index
, ctx_copy
.get('fragment_filename_sanitized')
500 self
.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome')
501 with tpe
or concurrent
.futures
.ThreadPoolExecutor(max_workers
) as pool
:
502 for fragment
, frag_content
, frag_index
, frag_filename
in pool
.map(_download_fragment
, fragments
):
503 if not interrupt_trigger
[0]:
505 ctx
['fragment_filename_sanitized'] = frag_filename
506 ctx
['fragment_index'] = frag_index
507 result
= append_fragment(decrypt_fragment(fragment
, frag_content
), frag_index
, ctx
)
511 for fragment
in fragments
:
512 if not interrupt_trigger
[0]:
514 frag_content
, frag_index
= download_fragment(fragment
, ctx
)
515 result
= append_fragment(decrypt_fragment(fragment
, frag_content
), frag_index
, ctx
)
519 if finish_func
is not None:
520 ctx
['dest_stream'].write(finish_func())
521 ctx
['dest_stream'].flush()
522 self
._finish
_frag
_download
(ctx
, info_dict
)