]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/fragment.py
[fd/external] Fixes to cookie handling
[yt-dlp.git] / yt_dlp / downloader / fragment.py
CommitLineData
1d485a1a 1import concurrent.futures
19a03940 2import contextlib
adbc4ec4
THD
3import json
4import math
95d8f7ea 5import os
ac668111 6import struct
95d8f7ea
S
7import time
8
9from .common import FileDownloader
10from .http import HttpFD
1d3586d0 11from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
ac668111 12from ..compat import compat_os_name
3d2623a8 13from ..networking import Request
14from ..networking.exceptions import HTTPError, IncompleteRead
15from ..utils import DownloadError, RetryManager, encodeFilename, traverse_obj
16from ..utils.networking import HTTPHeaderDict
95d8f7ea
S
17
18
19class HttpQuietDownloader(HttpFD):
20 def to_screen(self, *args, **kargs):
21 pass
22
998a3cae 23 to_console_title = to_screen
1d485a1a 24
95d8f7ea
S
25
26class FragmentFD(FileDownloader):
27 """
28 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
16a8b798
S
29
30 Available options:
31
46f1370e 32 fragment_retries: Number of times to retry a fragment for HTTP error
33 (DASH and hlsnative only). Default is 0 for API, but 10 for CLI
9603b660
S
34 skip_unavailable_fragments:
35 Skip unavailable fragments (DASH and hlsnative only)
0eee52f3
S
36 keep_fragments: Keep downloaded fragments on disk after downloading is
37 finished
59a7a13e 38 concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
e8e73840 39 _no_ytdl_file: Don't use .ytdl file
290f64db 40
7a5c1cfe 41 For each incomplete fragment download yt-dlp keeps on disk a special
290f64db 42 bookkeeping file with download state and metadata (in future such files will
7a5c1cfe 43 be used for any incomplete download handled by yt-dlp). This file is
290f64db
S
44 used to properly handle resuming, check download file consistency and detect
45 potential errors. The file has a .ytdl extension and represents a standard
46 JSON file of the following format:
47
48 extractor:
49 Dictionary of extractor related data. TBD.
50
51 downloader:
52 Dictionary of downloader related data. May contain following data:
53 current_fragment:
54 Dictionary with current (being downloaded) fragment data:
85f6de25 55 index: 0-based index of current fragment among all fragments
290f64db
S
56 fragment_count:
57 Total count of fragments
50534b71 58
85f6de25 59 This feature is experimental and file format may change in future.
95d8f7ea
S
60 """
61
75a24854 62 def report_retry_fragment(self, err, frag_index, count, retries):
da4db748 63 self.deprecation_warning('yt_dlp.downloader.FragmentFD.report_retry_fragment is deprecated. '
64 'Use yt_dlp.downloader.FileDownloader.report_retry instead')
be5c1ae8 65 return self.report_retry(err, count, retries, frag_index)
721f26b8 66
b4b855eb 67 def report_skip_fragment(self, frag_index, err=None):
68 err = f' {err};' if err else ''
69 self.to_screen(f'[download]{err} Skipping fragment {frag_index:d} ...')
9603b660 70
69035555
S
71 def _prepare_url(self, info_dict, url):
72 headers = info_dict.get('http_headers')
3d2623a8 73 return Request(url, None, headers) if headers else url
69035555 74
3ba7740d 75 def _prepare_and_start_frag_download(self, ctx, info_dict):
95d8f7ea 76 self._prepare_frag_download(ctx)
3ba7740d 77 self._start_frag_download(ctx, info_dict)
95d8f7ea 78
e8e73840 79 def __do_ytdl_file(self, ctx):
adbc4ec4 80 return ctx['live'] is not True and ctx['tmpfilename'] != '-' and not self.params.get('_no_ytdl_file')
adb4b03c 81
d3f0687c 82 def _read_ytdl_file(self, ctx):
500a86a5 83 assert 'ytdl_corrupt' not in ctx
205a0654 84 stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
500a86a5 85 try:
4d49884c
F
86 ytdl_data = json.loads(stream.read())
87 ctx['fragment_index'] = ytdl_data['downloader']['current_fragment']['index']
88 if 'extra_state' in ytdl_data['downloader']:
89 ctx['extra_state'] = ytdl_data['downloader']['extra_state']
500a86a5
S
90 except Exception:
91 ctx['ytdl_corrupt'] = True
92 finally:
93 stream.close()
d3f0687c
S
94
95 def _write_ytdl_file(self, ctx):
205a0654 96 frag_index_stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
ad3dc496 97 try:
98 downloader = {
99 'current_fragment': {
100 'index': ctx['fragment_index'],
101 },
102 }
103 if 'extra_state' in ctx:
104 downloader['extra_state'] = ctx['extra_state']
105 if ctx.get('fragment_count') is not None:
106 downloader['fragment_count'] = ctx['fragment_count']
107 frag_index_stream.write(json.dumps({'downloader': downloader}))
108 finally:
109 frag_index_stream.close()
d3f0687c 110
273762c8 111 def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None):
d3f0687c 112 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
38d70284 113 fragment_info_dict = {
75a24854
RA
114 'url': frag_url,
115 'http_headers': headers or info_dict.get('http_headers'),
273762c8 116 'request_data': request_data,
bd50a52b 117 'ctx_id': ctx.get('ctx_id'),
38d70284 118 }
4823ec9f 119 frag_resume_len = 0
120 if ctx['dl'].params.get('continuedl', True):
121 frag_resume_len = self.filesize_or_none(self.temp_name(fragment_filename))
122 fragment_info_dict['frag_resume_len'] = ctx['frag_resume_len'] = frag_resume_len
123
3fe75fdc 124 success, _ = ctx['dl'].download(fragment_filename, fragment_info_dict)
75a24854 125 if not success:
d71fd412 126 return False
38d70284 127 if fragment_info_dict.get('filetime'):
128 ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
4c7853de 129 ctx['fragment_filename_sanitized'] = fragment_filename
d71fd412 130 return True
4c7853de 131
132 def _read_fragment(self, ctx):
e06bd880 133 if not ctx.get('fragment_filename_sanitized'):
134 return None
d71fd412
LNO
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
d3f0687c
S
141 ctx['fragment_filename_sanitized'] = frag_sanitized
142 frag_content = down.read()
75a24854 143 down.close()
4c7853de 144 return frag_content
75a24854
RA
145
146 def _append_fragment(self, ctx, frag_content):
d3f0687c
S
147 try:
148 ctx['dest_stream'].write(frag_content)
593f2f79 149 ctx['dest_stream'].flush()
d3f0687c 150 finally:
adb4b03c 151 if self.__do_ytdl_file(ctx):
d3f0687c 152 self._write_ytdl_file(ctx)
0eee52f3 153 if not self.params.get('keep_fragments', False):
45806d44 154 self.try_remove(encodeFilename(ctx['fragment_filename_sanitized']))
d3f0687c 155 del ctx['fragment_filename_sanitized']
75a24854 156
95d8f7ea 157 def _prepare_frag_download(self, ctx):
4823ec9f 158 if not ctx.setdefault('live', False):
5efaf43c
S
159 total_frags_str = '%d' % ctx['total_frags']
160 ad_frags = ctx.get('ad_frags', 0)
161 if ad_frags:
162 total_frags_str += ' (not including %d ad)' % ad_frags
163 else:
164 total_frags_str = 'unknown (live)'
86e5f3ed 165 self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}')
95d8f7ea 166 self.report_destination(ctx['filename'])
666c36d5 167 dl = HttpQuietDownloader(self.ydl, {
168 **self.params,
169 'noprogress': True,
170 'test': False,
424f3bf0 171 'sleep_interval': 0,
172 'max_sleep_interval': 0,
173 'sleep_interval_subtitles': 0,
666c36d5 174 })
95d8f7ea 175 tmpfilename = self.temp_name(ctx['filename'])
75a24854 176 open_mode = 'wb'
d3f0687c 177
75a24854 178 # Establish possible resume length
4823ec9f 179 resume_len = self.filesize_or_none(tmpfilename)
180 if resume_len > 0:
75a24854 181 open_mode = 'ab'
d3f0687c 182
adb4b03c
S
183 # Should be initialized before ytdl file check
184 ctx.update({
185 'tmpfilename': tmpfilename,
186 'fragment_index': 0,
187 })
d3f0687c 188
adb4b03c 189 if self.__do_ytdl_file(ctx):
4823ec9f 190 ytdl_file_exists = os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename'])))
191 continuedl = self.params.get('continuedl', True)
192 if continuedl and ytdl_file_exists:
adb4b03c 193 self._read_ytdl_file(ctx)
500a86a5
S
194 is_corrupt = ctx.get('ytdl_corrupt') is True
195 is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
196 if is_corrupt or is_inconsistent:
197 message = (
198 '.ytdl file is corrupt' if is_corrupt else
199 'Inconsistent state of incomplete fragment download')
6f3b4a98 200 self.report_warning(
5ef7d9bd 201 '%s. Restarting from the beginning ...' % message)
e7c3e334 202 ctx['fragment_index'] = resume_len = 0
500a86a5
S
203 if 'ytdl_corrupt' in ctx:
204 del ctx['ytdl_corrupt']
e7c3e334 205 self._write_ytdl_file(ctx)
4823ec9f 206
adb4b03c 207 else:
4823ec9f 208 if not continuedl:
209 if ytdl_file_exists:
210 self._read_ytdl_file(ctx)
211 ctx['fragment_index'] = resume_len = 0
adb4b03c 212 self._write_ytdl_file(ctx)
e7c3e334 213 assert ctx['fragment_index'] == 0
d3f0687c 214
205a0654 215 dest_stream, tmpfilename = self.sanitize_open(tmpfilename, open_mode)
75a24854 216
95d8f7ea
S
217 ctx.update({
218 'dl': dl,
219 'dest_stream': dest_stream,
220 'tmpfilename': tmpfilename,
75a24854
RA
221 # Total complete fragments downloaded so far in bytes
222 'complete_frags_downloaded_bytes': resume_len,
95d8f7ea
S
223 })
224
3ba7740d 225 def _start_frag_download(self, ctx, info_dict):
3bce4ff7 226 resume_len = ctx['complete_frags_downloaded_bytes']
95d8f7ea 227 total_frags = ctx['total_frags']
bd50a52b 228 ctx_id = ctx.get('ctx_id')
95d8f7ea
S
229 # This dict stores the download progress, it's updated by the progress
230 # hook
231 state = {
232 'status': 'downloading',
3bce4ff7 233 'downloaded_bytes': resume_len,
3e0304fe
RA
234 'fragment_index': ctx['fragment_index'],
235 'fragment_count': total_frags,
95d8f7ea
S
236 'filename': ctx['filename'],
237 'tmpfilename': ctx['tmpfilename'],
b83b782d
S
238 }
239
240 start = time.time()
241 ctx.update({
242 'started': start,
bd93fd5d 243 'fragment_started': start,
709185a2
S
244 # Amount of fragment's bytes downloaded by the time of the previous
245 # frag progress hook invocation
b83b782d
S
246 'prev_frag_downloaded_bytes': 0,
247 })
95d8f7ea
S
248
249 def frag_progress_hook(s):
250 if s['status'] not in ('downloading', 'finished'):
251 return
252
36195c44
M
253 if not total_frags and ctx.get('fragment_count'):
254 state['fragment_count'] = ctx['fragment_count']
255
bd50a52b
THD
256 if ctx_id is not None and s.get('ctx_id') != ctx_id:
257 return
258
259 state['max_progress'] = ctx.get('max_progress')
260 state['progress_idx'] = ctx.get('progress_idx')
261
5fa1702c 262 time_now = time.time()
2c2f1efd 263 state['elapsed'] = time_now - start
3c91e416 264 frag_total_bytes = s.get('total_bytes') or 0
3ba7740d 265 s['fragment_info_dict'] = s.pop('info_dict', {})
5fa1702c
S
266 if not ctx['live']:
267 estimated_size = (
3089bc74
S
268 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
269 / (state['fragment_index'] + 1) * total_frags)
5fa1702c 270 state['total_bytes_estimate'] = estimated_size
95d8f7ea 271
709185a2 272 if s['status'] == 'finished':
3e0304fe
RA
273 state['fragment_index'] += 1
274 ctx['fragment_index'] = state['fragment_index']
b83b782d
S
275 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
276 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
bd93fd5d 277 ctx['speed'] = state['speed'] = self.calc_speed(
278 ctx['fragment_started'], time_now, frag_total_bytes)
279 ctx['fragment_started'] = time.time()
b83b782d 280 ctx['prev_frag_downloaded_bytes'] = 0
709185a2
S
281 else:
282 frag_downloaded_bytes = s['downloaded_bytes']
b83b782d 283 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
bd93fd5d 284 ctx['speed'] = state['speed'] = self.calc_speed(
edbe5b58 285 ctx['fragment_started'], time_now, frag_downloaded_bytes - ctx.get('frag_resume_len', 0))
4823ec9f 286 if not ctx['live']:
287 state['eta'] = self.calc_eta(state['speed'], estimated_size - state['downloaded_bytes'])
b83b782d 288 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
3ba7740d 289 self._hook_progress(state, info_dict)
95d8f7ea
S
290
291 ctx['dl'].add_progress_hook(frag_progress_hook)
292
293 return start
294
3ba7740d 295 def _finish_frag_download(self, ctx, info_dict):
95d8f7ea 296 ctx['dest_stream'].close()
adb4b03c 297 if self.__do_ytdl_file(ctx):
337734d4 298 self.try_remove(self.ytdl_filename(ctx['filename']))
95d8f7ea 299 elapsed = time.time() - ctx['started']
0ff2c1ec 300
814bba39 301 to_file = ctx['tmpfilename'] != '-'
302 if to_file:
edbe5b58 303 downloaded_bytes = self.filesize_or_none(ctx['tmpfilename'])
0ff2c1ec 304 else:
814bba39 305 downloaded_bytes = ctx['complete_frags_downloaded_bytes']
306
307 if not downloaded_bytes:
308 if to_file:
309 self.try_remove(ctx['tmpfilename'])
310 self.report_error('The downloaded file is empty')
311 return False
312 elif to_file:
0ff2c1ec 313 self.try_rename(ctx['tmpfilename'], ctx['filename'])
814bba39 314 filetime = ctx.get('fragment_filetime')
315 if self.params.get('updatetime', True) and filetime:
316 with contextlib.suppress(Exception):
317 os.utime(ctx['filename'], (time.time(), filetime))
95d8f7ea
S
318
319 self._hook_progress({
0ff2c1ec
S
320 'downloaded_bytes': downloaded_bytes,
321 'total_bytes': downloaded_bytes,
95d8f7ea
S
322 'filename': ctx['filename'],
323 'status': 'finished',
324 'elapsed': elapsed,
bd50a52b
THD
325 'ctx_id': ctx.get('ctx_id'),
326 'max_progress': ctx.get('max_progress'),
327 'progress_idx': ctx.get('progress_idx'),
3ba7740d 328 }, info_dict)
814bba39 329 return True
5219cb3e 330
331 def _prepare_external_frag_download(self, ctx):
332 if 'live' not in ctx:
333 ctx['live'] = False
334 if not ctx['live']:
335 total_frags_str = '%d' % ctx['total_frags']
336 ad_frags = ctx.get('ad_frags', 0)
337 if ad_frags:
338 total_frags_str += ' (not including %d ad)' % ad_frags
339 else:
340 total_frags_str = 'unknown (live)'
86e5f3ed 341 self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}')
5219cb3e 342
343 tmpfilename = self.temp_name(ctx['filename'])
344
345 # Should be initialized before ytdl file check
346 ctx.update({
347 'tmpfilename': tmpfilename,
348 'fragment_index': 0,
349 })
4c7853de 350
1009f67c 351 def decrypter(self, info_dict):
352 _key_cache = {}
353
354 def _get_key(url):
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]
358
359 def decrypt_fragment(fragment, frag_content):
be5c1ae8 360 if frag_content is None:
361 return
1009f67c 362 decrypt_info = fragment.get('decrypt_info')
363 if not decrypt_info or decrypt_info['METHOD'] != 'AES-128':
364 return frag_content
ac668111 365 iv = decrypt_info.get('IV') or struct.pack('>8xq', fragment['media_sequence'])
7e68567e 366 decrypt_info['KEY'] = (decrypt_info.get('KEY')
367 or _get_key(traverse_obj(info_dict, ('hls_aes', 'uri')) or decrypt_info['URI']))
1009f67c 368 # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
369 # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
370 # not what it decrypts to.
371 if self.params.get('test', False):
372 return frag_content
1d3586d0 373 return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv))
1009f67c 374
375 return decrypt_fragment
376
814bba39 377 def download_and_append_fragments_multiple(self, *args, **kwargs):
bd50a52b
THD
378 '''
379 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
380 all args must be either tuple or list
381 '''
adbc4ec4 382 interrupt_trigger = [True]
bd50a52b
THD
383 max_progress = len(args)
384 if max_progress == 1:
814bba39 385 return self.download_and_append_fragments(*args[0], **kwargs)
adbc4ec4 386 max_workers = self.params.get('concurrent_fragment_downloads', 1)
49a57e70 387 if max_progress > 1:
388 self._prepare_multiline_status(max_progress)
6839ae1f 389 is_live = any(traverse_obj(args, (..., 2, 'is_live')))
bd50a52b
THD
390
391 def thread_func(idx, ctx, fragments, info_dict, tpe):
392 ctx['max_progress'] = max_progress
393 ctx['progress_idx'] = idx
adbc4ec4 394 return self.download_and_append_fragments(
814bba39 395 ctx, fragments, info_dict, **kwargs, tpe=tpe, interrupt_trigger=interrupt_trigger)
bd50a52b
THD
396
397 class FTPE(concurrent.futures.ThreadPoolExecutor):
398 # has to stop this or it's going to wait on the worker thread itself
399 def __exit__(self, exc_type, exc_val, exc_tb):
400 pass
401
adbc4ec4 402 if compat_os_name == 'nt':
a44ca5a4 403 def future_result(future):
a539f065
LNO
404 while True:
405 try:
406 return future.result(0.1)
407 except KeyboardInterrupt:
408 raise
409 except concurrent.futures.TimeoutError:
410 continue
411 else:
a44ca5a4 412 def future_result(future):
a539f065
LNO
413 return future.result()
414
f0734e11
L
415 def interrupt_trigger_iter(fg):
416 for f in fg:
417 if not interrupt_trigger[0]:
418 break
419 yield f
420
a539f065 421 spins = []
bd50a52b 422 for idx, (ctx, fragments, info_dict) in enumerate(args):
adbc4ec4 423 tpe = FTPE(math.ceil(max_workers / max_progress))
f0734e11 424 job = tpe.submit(thread_func, idx, ctx, interrupt_trigger_iter(fragments), info_dict, tpe)
bd50a52b
THD
425 spins.append((tpe, job))
426
427 result = True
428 for tpe, job in spins:
429 try:
a44ca5a4 430 result = result and future_result(job)
adbc4ec4
THD
431 except KeyboardInterrupt:
432 interrupt_trigger[0] = False
bd50a52b
THD
433 finally:
434 tpe.shutdown(wait=True)
a539f065 435 if not interrupt_trigger[0] and not is_live:
adbc4ec4 436 raise KeyboardInterrupt()
a539f065
LNO
437 # we expect the user wants to stop and DO WANT the preceding postprocessors to run;
438 # so returning a intermediate result here instead of KeyboardInterrupt on live
819e0531 439 return result
bd50a52b 440
adbc4ec4 441 def download_and_append_fragments(
814bba39 442 self, ctx, fragments, info_dict, *, is_fatal=(lambda idx: False),
443 pack_func=(lambda content, idx: content), finish_func=None,
444 tpe=None, interrupt_trigger=(True, )):
adbc4ec4 445
814bba39 446 if not self.params.get('skip_unavailable_fragments', True):
447 is_fatal = lambda _: True
4c7853de 448
449 def download_fragment(fragment, ctx):
a539f065 450 if not interrupt_trigger[0]:
d71fd412 451 return
a539f065 452
4c7853de 453 frag_index = ctx['fragment_index'] = fragment['frag_index']
185bf310 454 ctx['last_error'] = None
3d2623a8 455 headers = HTTPHeaderDict(info_dict.get('http_headers'))
4c7853de 456 byte_range = fragment.get('byte_range')
457 if byte_range:
458 headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
459
460 # Never skip the first fragment
be5c1ae8 461 fatal = is_fatal(fragment.get('index') or (frag_index - 1))
462
463 def error_callback(err, count, retries):
464 if fatal and count > retries:
465 ctx['dest_stream'].close()
466 self.report_retry(err, count, retries, frag_index, fatal)
467 ctx['last_error'] = err
468
469 for retry in RetryManager(self.params.get('fragment_retries'), error_callback):
4c7853de 470 try:
36195c44 471 ctx['fragment_count'] = fragment.get('fragment_count')
f34804b2 472 if not self._download_fragment(
473 ctx, fragment['url'], info_dict, headers, info_dict.get('request_data')):
be5c1ae8 474 return
3d2623a8 475 except (HTTPError, IncompleteRead) as err:
be5c1ae8 476 retry.error = err
477 continue
478 except DownloadError: # has own retry settings
479 if fatal:
480 raise
4c7853de 481
4c7853de 482 def append_fragment(frag_content, frag_index, ctx):
a44ca5a4 483 if frag_content:
484 self._append_fragment(ctx, pack_func(frag_content, frag_index))
485 elif not is_fatal(frag_index - 1):
486 self.report_skip_fragment(frag_index, 'fragment not found')
487 else:
488 ctx['dest_stream'].close()
489 self.report_error(f'fragment {frag_index} not found, unable to continue')
490 return False
4c7853de 491 return True
492
1009f67c 493 decrypt_fragment = self.decrypter(info_dict)
494
adbc4ec4
THD
495 max_workers = math.ceil(
496 self.params.get('concurrent_fragment_downloads', 1) / ctx.get('max_progress', 1))
1d485a1a 497 if max_workers > 1:
4c7853de 498 def _download_fragment(fragment):
723d44b9 499 ctx_copy = ctx.copy()
d71fd412
LNO
500 download_fragment(fragment, ctx_copy)
501 return fragment, fragment['frag_index'], ctx_copy.get('fragment_filename_sanitized')
4c7853de 502
5b28cef7 503 self.report_warning('The download speed shown is only of one thread. This is a known issue')
bd50a52b 504 with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
1890fc63 505 try:
506 for fragment, frag_index, frag_filename in pool.map(_download_fragment, fragments):
507 ctx.update({
508 'fragment_filename_sanitized': frag_filename,
509 'fragment_index': frag_index,
510 })
511 if not append_fragment(decrypt_fragment(fragment, self._read_fragment(ctx)), frag_index, ctx):
512 return False
513 except KeyboardInterrupt:
514 self._finish_multiline_status()
515 self.report_error(
516 'Interrupted by user. Waiting for all threads to shutdown...', is_error=False, tb=False)
517 pool.shutdown(wait=False)
518 raise
4c7853de 519 else:
520 for fragment in fragments:
adbc4ec4
THD
521 if not interrupt_trigger[0]:
522 break
c854208c
LNO
523 try:
524 download_fragment(fragment, ctx)
19a03940 525 result = append_fragment(
526 decrypt_fragment(fragment, self._read_fragment(ctx)), fragment['frag_index'], ctx)
c854208c
LNO
527 except KeyboardInterrupt:
528 if info_dict.get('is_live'):
529 break
530 raise
4c7853de 531 if not result:
532 return False
533
25a3f4f5
F
534 if finish_func is not None:
535 ctx['dest_stream'].write(finish_func())
536 ctx['dest_stream'].flush()
814bba39 537 return self._finish_frag_download(ctx, info_dict)