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