1 from __future__
import division
, unicode_literals
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
17 from ..compat
import (
30 class HttpQuietDownloader(HttpFD
):
31 def to_screen(self
, *args
, **kargs
):
35 class FragmentFD(FileDownloader
):
37 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
41 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
43 skip_unavailable_fragments:
44 Skip unavailable fragments (DASH and hlsnative only)
45 keep_fragments: Keep downloaded fragments on disk after downloading is
47 _no_ytdl_file: Don't use .ytdl file
49 For each incomplete fragment download yt-dlp keeps on disk a special
50 bookkeeping file with download state and metadata (in future such files will
51 be used for any incomplete download handled by yt-dlp). This file is
52 used to properly handle resuming, check download file consistency and detect
53 potential errors. The file has a .ytdl extension and represents a standard
54 JSON file of the following format:
57 Dictionary of extractor related data. TBD.
60 Dictionary of downloader related data. May contain following data:
62 Dictionary with current (being downloaded) fragment data:
63 index: 0-based index of current fragment among all fragments
65 Total count of fragments
67 This feature is experimental and file format may change in future.
70 def report_retry_fragment(self
, err
, frag_index
, count
, retries
):
72 '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...'
73 % (error_to_compat_str(err
), frag_index
, count
, self
.format_retries(retries
)))
75 def report_skip_fragment(self
, frag_index
):
76 self
.to_screen('[download] Skipping fragment %d ...' % frag_index
)
78 def _prepare_url(self
, info_dict
, url
):
79 headers
= info_dict
.get('http_headers')
80 return sanitized_Request(url
, None, headers
) if headers
else url
82 def _prepare_and_start_frag_download(self
, ctx
, info_dict
):
83 self
._prepare
_frag
_download
(ctx
)
84 self
._start
_frag
_download
(ctx
, info_dict
)
86 def __do_ytdl_file(self
, ctx
):
87 return not ctx
['live'] and not ctx
['tmpfilename'] == '-' and not self
.params
.get('_no_ytdl_file')
89 def _read_ytdl_file(self
, ctx
):
90 assert 'ytdl_corrupt' not in ctx
91 stream
, _
= sanitize_open(self
.ytdl_filename(ctx
['filename']), 'r')
93 ytdl_data
= json
.loads(stream
.read())
94 ctx
['fragment_index'] = ytdl_data
['downloader']['current_fragment']['index']
95 if 'extra_state' in ytdl_data
['downloader']:
96 ctx
['extra_state'] = ytdl_data
['downloader']['extra_state']
98 ctx
['ytdl_corrupt'] = True
102 def _write_ytdl_file(self
, ctx
):
103 frag_index_stream
, _
= sanitize_open(self
.ytdl_filename(ctx
['filename']), 'w')
106 'current_fragment': {
107 'index': ctx
['fragment_index'],
110 if 'extra_state' in ctx
:
111 downloader
['extra_state'] = ctx
['extra_state']
112 if ctx
.get('fragment_count') is not None:
113 downloader
['fragment_count'] = ctx
['fragment_count']
114 frag_index_stream
.write(json
.dumps({'downloader': downloader}
))
116 frag_index_stream
.close()
118 def _download_fragment(self
, ctx
, frag_url
, info_dict
, headers
=None, request_data
=None):
119 fragment_filename
= '%s-Frag%d' % (ctx
['tmpfilename'], ctx
['fragment_index'])
120 fragment_info_dict
= {
122 'http_headers': headers
or info_dict
.get('http_headers'),
123 'request_data': request_data
,
124 'ctx_id': ctx
.get('ctx_id'),
126 success
= ctx
['dl'].download(fragment_filename
, fragment_info_dict
)
129 if fragment_info_dict
.get('filetime'):
130 ctx
['fragment_filetime'] = fragment_info_dict
.get('filetime')
131 ctx
['fragment_filename_sanitized'] = fragment_filename
132 return True, self
._read
_fragment
(ctx
)
134 def _read_fragment(self
, ctx
):
135 down
, frag_sanitized
= sanitize_open(ctx
['fragment_filename_sanitized'], 'rb')
136 ctx
['fragment_filename_sanitized'] = frag_sanitized
137 frag_content
= down
.read()
141 def _append_fragment(self
, ctx
, frag_content
):
143 ctx
['dest_stream'].write(frag_content
)
144 ctx
['dest_stream'].flush()
146 if self
.__do
_ytdl
_file
(ctx
):
147 self
._write
_ytdl
_file
(ctx
)
148 if not self
.params
.get('keep_fragments', False):
149 os
.remove(encodeFilename(ctx
['fragment_filename_sanitized']))
150 del ctx
['fragment_filename_sanitized']
152 def _prepare_frag_download(self
, ctx
):
153 if 'live' not in ctx
:
156 total_frags_str
= '%d' % ctx
['total_frags']
157 ad_frags
= ctx
.get('ad_frags', 0)
159 total_frags_str
+= ' (not including %d ad)' % ad_frags
161 total_frags_str
= 'unknown (live)'
163 '[%s] Total fragments: %s' % (self
.FD_NAME
, total_frags_str
))
164 self
.report_destination(ctx
['filename'])
165 dl
= HttpQuietDownloader(
171 'ratelimit': self
.params
.get('ratelimit'),
172 'retries': self
.params
.get('retries', 0),
173 'nopart': self
.params
.get('nopart', False),
174 'test': self
.params
.get('test', False),
177 tmpfilename
= self
.temp_name(ctx
['filename'])
181 # Establish possible resume length
182 if os
.path
.isfile(encodeFilename(tmpfilename
)):
184 resume_len
= os
.path
.getsize(encodeFilename(tmpfilename
))
186 # Should be initialized before ytdl file check
188 'tmpfilename': tmpfilename
,
192 if self
.__do
_ytdl
_file
(ctx
):
193 if os
.path
.isfile(encodeFilename(self
.ytdl_filename(ctx
['filename']))):
194 self
._read
_ytdl
_file
(ctx
)
195 is_corrupt
= ctx
.get('ytdl_corrupt') is True
196 is_inconsistent
= ctx
['fragment_index'] > 0 and resume_len
== 0
197 if is_corrupt
or is_inconsistent
:
199 '.ytdl file is corrupt' if is_corrupt
else
200 'Inconsistent state of incomplete fragment download')
202 '%s. Restarting from the beginning ...' % message
)
203 ctx
['fragment_index'] = resume_len
= 0
204 if 'ytdl_corrupt' in ctx
:
205 del ctx
['ytdl_corrupt']
206 self
._write
_ytdl
_file
(ctx
)
208 self
._write
_ytdl
_file
(ctx
)
209 assert ctx
['fragment_index'] == 0
211 dest_stream
, tmpfilename
= sanitize_open(tmpfilename
, open_mode
)
215 'dest_stream': dest_stream
,
216 'tmpfilename': tmpfilename
,
217 # Total complete fragments downloaded so far in bytes
218 'complete_frags_downloaded_bytes': resume_len
,
221 def _start_frag_download(self
, ctx
, info_dict
):
222 resume_len
= ctx
['complete_frags_downloaded_bytes']
223 total_frags
= ctx
['total_frags']
224 ctx_id
= ctx
.get('ctx_id')
225 # This dict stores the download progress, it's updated by the progress
228 'status': 'downloading',
229 'downloaded_bytes': resume_len
,
230 'fragment_index': ctx
['fragment_index'],
231 'fragment_count': total_frags
,
232 'filename': ctx
['filename'],
233 'tmpfilename': ctx
['tmpfilename'],
239 # Amount of fragment's bytes downloaded by the time of the previous
240 # frag progress hook invocation
241 'prev_frag_downloaded_bytes': 0,
244 def frag_progress_hook(s
):
245 if s
['status'] not in ('downloading', 'finished'):
248 if ctx_id
is not None and s
.get('ctx_id') != ctx_id
:
251 state
['max_progress'] = ctx
.get('max_progress')
252 state
['progress_idx'] = ctx
.get('progress_idx')
254 time_now
= time
.time()
255 state
['elapsed'] = time_now
- start
256 frag_total_bytes
= s
.get('total_bytes') or 0
257 s
['fragment_info_dict'] = s
.pop('info_dict', {})
260 (ctx
['complete_frags_downloaded_bytes'] + frag_total_bytes
)
261 / (state
['fragment_index'] + 1) * total_frags
)
262 state
['total_bytes_estimate'] = estimated_size
264 if s
['status'] == 'finished':
265 state
['fragment_index'] += 1
266 ctx
['fragment_index'] = state
['fragment_index']
267 state
['downloaded_bytes'] += frag_total_bytes
- ctx
['prev_frag_downloaded_bytes']
268 ctx
['complete_frags_downloaded_bytes'] = state
['downloaded_bytes']
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 state
['speed'] = s
.get('speed') or ctx
.get('speed')
278 ctx
['speed'] = state
['speed']
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 os
.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')
302 os
.utime(ctx
['filename'], (time
.time(), filetime
))
305 downloaded_bytes
= os
.path
.getsize(encodeFilename(ctx
['filename']))
307 self
._hook
_progress
({
308 'downloaded_bytes': downloaded_bytes
,
309 'total_bytes': downloaded_bytes
,
310 'filename': ctx
['filename'],
311 'status': 'finished',
313 'ctx_id': ctx
.get('ctx_id'),
314 'max_progress': ctx
.get('max_progress'),
315 'progress_idx': ctx
.get('progress_idx'),
318 def _prepare_external_frag_download(self
, ctx
):
319 if 'live' not in ctx
:
322 total_frags_str
= '%d' % ctx
['total_frags']
323 ad_frags
= ctx
.get('ad_frags', 0)
325 total_frags_str
+= ' (not including %d ad)' % ad_frags
327 total_frags_str
= 'unknown (live)'
329 '[%s] Total fragments: %s' % (self
.FD_NAME
, total_frags_str
))
331 tmpfilename
= self
.temp_name(ctx
['filename'])
333 # Should be initialized before ytdl file check
335 'tmpfilename': tmpfilename
,
339 def decrypter(self
, info_dict
):
343 if url
not in _key_cache
:
344 _key_cache
[url
] = self
.ydl
.urlopen(self
._prepare
_url
(info_dict
, url
)).read()
345 return _key_cache
[url
]
347 def decrypt_fragment(fragment
, frag_content
):
348 decrypt_info
= fragment
.get('decrypt_info')
349 if not decrypt_info
or decrypt_info
['METHOD'] != 'AES-128':
351 iv
= decrypt_info
.get('IV') or compat_struct_pack('>8xq', fragment
['media_sequence'])
352 decrypt_info
['KEY'] = decrypt_info
.get('KEY') or _get_key(info_dict
.get('_decryption_key_url') or decrypt_info
['URI'])
353 # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
354 # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
355 # not what it decrypts to.
356 if self
.params
.get('test', False):
358 return aes_cbc_decrypt_bytes(frag_content
, decrypt_info
['KEY'], iv
)
360 return decrypt_fragment
362 def download_and_append_fragments_multiple(self
, *args
, pack_func
=None, finish_func
=None):
364 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
365 all args must be either tuple or list
367 max_progress
= len(args
)
368 if max_progress
== 1:
369 return self
.download_and_append_fragments(*args
[0], pack_func
=pack_func
, finish_func
=finish_func
)
370 max_workers
= self
.params
.get('concurrent_fragment_downloads', max_progress
)
371 self
._prepare
_multiline
_status
(max_progress
)
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(ctx
, fragments
, info_dict
, pack_func
=pack_func
, finish_func
=finish_func
, tpe
=tpe
)
378 class FTPE(concurrent
.futures
.ThreadPoolExecutor
):
379 # has to stop this or it's going to wait on the worker thread itself
380 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
384 for idx
, (ctx
, fragments
, info_dict
) in enumerate(args
):
385 tpe
= FTPE(ceil(max_workers
/ max_progress
))
386 job
= tpe
.submit(thread_func
, idx
, ctx
, fragments
, info_dict
, tpe
)
387 spins
.append((tpe
, job
))
390 for tpe
, job
in spins
:
392 result
= result
and job
.result()
394 tpe
.shutdown(wait
=True)
396 self
._finish
_multiline
_status
()
399 def download_and_append_fragments(self
, ctx
, fragments
, info_dict
, *, pack_func
=None, finish_func
=None, tpe
=None):
400 fragment_retries
= self
.params
.get('fragment_retries', 0)
401 is_fatal
= (lambda idx
: idx
== 0) if self
.params
.get('skip_unavailable_fragments', True) else (lambda _
: True)
403 pack_func
= lambda frag_content
, _
: frag_content
405 def download_fragment(fragment
, ctx
):
406 frag_index
= ctx
['fragment_index'] = fragment
['frag_index']
407 headers
= info_dict
.get('http_headers', {}).copy()
408 byte_range
= fragment
.get('byte_range')
410 headers
['Range'] = 'bytes=%d-%d' % (byte_range
['start'], byte_range
['end'] - 1)
412 # Never skip the first fragment
413 fatal
= is_fatal(fragment
.get('index') or (frag_index
- 1))
414 count
, frag_content
= 0, None
415 while count
<= fragment_retries
:
417 success
, frag_content
= self
._download
_fragment
(ctx
, fragment
['url'], info_dict
, headers
)
419 return False, frag_index
421 except compat_urllib_error
.HTTPError
as err
:
422 # Unavailable (possibly temporary) fragments may be served.
423 # First we try to retry then either skip or abort.
424 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
425 # https://github.com/ytdl-org/youtube-dl/issues/10448).
427 if count
<= fragment_retries
:
428 self
.report_retry_fragment(err
, frag_index
, count
, fragment_retries
)
429 except DownloadError
:
430 # Don't retry fragment if error occurred during HTTP downloading
431 # itself since it has own retry settings
436 if count
> fragment_retries
:
438 return False, frag_index
439 ctx
['dest_stream'].close()
440 self
.report_error('Giving up after %s fragment retries' % fragment_retries
)
441 return False, frag_index
442 return frag_content
, frag_index
444 def append_fragment(frag_content
, frag_index
, ctx
):
446 if not is_fatal(frag_index
- 1):
447 self
.report_skip_fragment(frag_index
)
450 ctx
['dest_stream'].close()
452 'fragment %s not found, unable to continue' % frag_index
)
454 self
._append
_fragment
(ctx
, pack_func(frag_content
, frag_index
))
457 decrypt_fragment
= self
.decrypter(info_dict
)
459 max_workers
= self
.params
.get('concurrent_fragment_downloads', 1)
460 if can_threaded_download
and max_workers
> 1:
462 def _download_fragment(fragment
):
463 ctx_copy
= ctx
.copy()
464 frag_content
, frag_index
= download_fragment(fragment
, ctx_copy
)
465 return fragment
, frag_content
, frag_index
, ctx_copy
.get('fragment_filename_sanitized')
467 self
.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome')
468 with tpe
or concurrent
.futures
.ThreadPoolExecutor(max_workers
) as pool
:
469 for fragment
, frag_content
, frag_index
, frag_filename
in pool
.map(_download_fragment
, fragments
):
470 ctx
['fragment_filename_sanitized'] = frag_filename
471 ctx
['fragment_index'] = frag_index
472 result
= append_fragment(decrypt_fragment(fragment
, frag_content
), frag_index
, ctx
)
476 for fragment
in fragments
:
477 frag_content
, frag_index
= download_fragment(fragment
, ctx
)
478 result
= append_fragment(decrypt_fragment(fragment
, frag_content
), frag_index
, ctx
)
482 if finish_func
is not None:
483 ctx
['dest_stream'].write(finish_func())
484 ctx
['dest_stream'].flush()
485 self
._finish
_frag
_download
(ctx
, info_dict
)