]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/fragment.py
[downloader/fragment] Improve `--live-from-start` for YouTube livestreams (#2870)
[yt-dlp.git] / yt_dlp / downloader / fragment.py
CommitLineData
95d8f7ea
S
1from __future__ import division, unicode_literals
2
adbc4ec4
THD
3import http.client
4import json
5import math
95d8f7ea
S
6import os
7import time
8
4c7853de 9try:
10 import concurrent.futures
11 can_threaded_download = True
12except ImportError:
13 can_threaded_download = False
14
95d8f7ea
S
15from .common import FileDownloader
16from .http import HttpFD
1d3586d0 17from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
4c7853de 18from ..compat import (
adbc4ec4 19 compat_os_name,
4c7853de 20 compat_urllib_error,
21 compat_struct_pack,
22)
95d8f7ea 23from ..utils import (
4c7853de 24 DownloadError,
2e99cd30 25 error_to_compat_str,
95d8f7ea 26 encodeFilename,
69035555 27 sanitized_Request,
a539f065 28 traverse_obj,
95d8f7ea
S
29)
30
31
32class HttpQuietDownloader(HttpFD):
33 def to_screen(self, *args, **kargs):
34 pass
35
bd93fd5d 36 def report_retry(self, err, count, retries):
37 super().to_screen(
38 f'[download] Got server HTTP error: {err}. Retrying (attempt {count} of {self.format_retries(retries)}) ...')
39
95d8f7ea
S
40
41class FragmentFD(FileDownloader):
42 """
43 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
16a8b798
S
44
45 Available options:
46
9603b660
S
47 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
48 and hlsnative only)
49 skip_unavailable_fragments:
50 Skip unavailable fragments (DASH and hlsnative only)
0eee52f3
S
51 keep_fragments: Keep downloaded fragments on disk after downloading is
52 finished
59a7a13e 53 concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
e8e73840 54 _no_ytdl_file: Don't use .ytdl file
290f64db 55
7a5c1cfe 56 For each incomplete fragment download yt-dlp keeps on disk a special
290f64db 57 bookkeeping file with download state and metadata (in future such files will
7a5c1cfe 58 be used for any incomplete download handled by yt-dlp). This file is
290f64db
S
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:
62
63 extractor:
64 Dictionary of extractor related data. TBD.
65
66 downloader:
67 Dictionary of downloader related data. May contain following data:
68 current_fragment:
69 Dictionary with current (being downloaded) fragment data:
85f6de25 70 index: 0-based index of current fragment among all fragments
290f64db
S
71 fragment_count:
72 Total count of fragments
50534b71 73
85f6de25 74 This feature is experimental and file format may change in future.
95d8f7ea
S
75 """
76
75a24854 77 def report_retry_fragment(self, err, frag_index, count, retries):
721f26b8 78 self.to_screen(
4c7853de 79 '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...'
75a24854 80 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
721f26b8 81
b4b855eb 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} ...')
9603b660 85
69035555
S
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
89
3ba7740d 90 def _prepare_and_start_frag_download(self, ctx, info_dict):
95d8f7ea 91 self._prepare_frag_download(ctx)
3ba7740d 92 self._start_frag_download(ctx, info_dict)
95d8f7ea 93
e8e73840 94 def __do_ytdl_file(self, ctx):
adbc4ec4 95 return ctx['live'] is not True and ctx['tmpfilename'] != '-' and not self.params.get('_no_ytdl_file')
adb4b03c 96
d3f0687c 97 def _read_ytdl_file(self, ctx):
500a86a5 98 assert 'ytdl_corrupt' not in ctx
205a0654 99 stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
500a86a5 100 try:
4d49884c
F
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']
500a86a5
S
105 except Exception:
106 ctx['ytdl_corrupt'] = True
107 finally:
108 stream.close()
d3f0687c
S
109
110 def _write_ytdl_file(self, ctx):
205a0654 111 frag_index_stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
ad3dc496 112 try:
113 downloader = {
114 'current_fragment': {
115 'index': ctx['fragment_index'],
116 },
117 }
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}))
123 finally:
124 frag_index_stream.close()
d3f0687c 125
273762c8 126 def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None):
d3f0687c 127 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
38d70284 128 fragment_info_dict = {
75a24854
RA
129 'url': frag_url,
130 'http_headers': headers or info_dict.get('http_headers'),
273762c8 131 'request_data': request_data,
bd50a52b 132 'ctx_id': ctx.get('ctx_id'),
38d70284 133 }
134 success = ctx['dl'].download(fragment_filename, fragment_info_dict)
75a24854
RA
135 if not success:
136 return False, None
38d70284 137 if fragment_info_dict.get('filetime'):
138 ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
4c7853de 139 ctx['fragment_filename_sanitized'] = fragment_filename
140 return True, self._read_fragment(ctx)
141
142 def _read_fragment(self, ctx):
205a0654 143 down, frag_sanitized = self.sanitize_open(ctx['fragment_filename_sanitized'], 'rb')
d3f0687c
S
144 ctx['fragment_filename_sanitized'] = frag_sanitized
145 frag_content = down.read()
75a24854 146 down.close()
4c7853de 147 return frag_content
75a24854
RA
148
149 def _append_fragment(self, ctx, frag_content):
d3f0687c
S
150 try:
151 ctx['dest_stream'].write(frag_content)
593f2f79 152 ctx['dest_stream'].flush()
d3f0687c 153 finally:
adb4b03c 154 if self.__do_ytdl_file(ctx):
d3f0687c 155 self._write_ytdl_file(ctx)
0eee52f3 156 if not self.params.get('keep_fragments', False):
99081da9 157 os.remove(encodeFilename(ctx['fragment_filename_sanitized']))
d3f0687c 158 del ctx['fragment_filename_sanitized']
75a24854 159
95d8f7ea 160 def _prepare_frag_download(self, ctx):
5fa1702c
S
161 if 'live' not in ctx:
162 ctx['live'] = False
5efaf43c
S
163 if not ctx['live']:
164 total_frags_str = '%d' % ctx['total_frags']
165 ad_frags = ctx.get('ad_frags', 0)
166 if ad_frags:
167 total_frags_str += ' (not including %d ad)' % ad_frags
168 else:
169 total_frags_str = 'unknown (live)'
5fa1702c 170 self.to_screen(
5efaf43c 171 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
95d8f7ea
S
172 self.report_destination(ctx['filename'])
173 dl = HttpQuietDownloader(
174 self.ydl,
175 {
176 'continuedl': True,
bd93fd5d 177 'quiet': self.params.get('quiet'),
95d8f7ea 178 'noprogress': True,
d800609c 179 'ratelimit': self.params.get('ratelimit'),
6828c809 180 'retries': self.params.get('retries', 0),
7097bffb 181 'nopart': self.params.get('nopart', False),
95d8f7ea
S
182 'test': self.params.get('test', False),
183 }
184 )
185 tmpfilename = self.temp_name(ctx['filename'])
75a24854
RA
186 open_mode = 'wb'
187 resume_len = 0
d3f0687c 188
75a24854
RA
189 # Establish possible resume length
190 if os.path.isfile(encodeFilename(tmpfilename)):
191 open_mode = 'ab'
192 resume_len = os.path.getsize(encodeFilename(tmpfilename))
d3f0687c 193
adb4b03c
S
194 # Should be initialized before ytdl file check
195 ctx.update({
196 'tmpfilename': tmpfilename,
197 'fragment_index': 0,
198 })
d3f0687c 199
adb4b03c
S
200 if self.__do_ytdl_file(ctx):
201 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
202 self._read_ytdl_file(ctx)
500a86a5
S
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:
206 message = (
207 '.ytdl file is corrupt' if is_corrupt else
208 'Inconsistent state of incomplete fragment download')
6f3b4a98 209 self.report_warning(
5ef7d9bd 210 '%s. Restarting from the beginning ...' % message)
e7c3e334 211 ctx['fragment_index'] = resume_len = 0
500a86a5
S
212 if 'ytdl_corrupt' in ctx:
213 del ctx['ytdl_corrupt']
e7c3e334 214 self._write_ytdl_file(ctx)
adb4b03c
S
215 else:
216 self._write_ytdl_file(ctx)
e7c3e334 217 assert ctx['fragment_index'] == 0
d3f0687c 218
205a0654 219 dest_stream, tmpfilename = self.sanitize_open(tmpfilename, open_mode)
75a24854 220
95d8f7ea
S
221 ctx.update({
222 'dl': dl,
223 'dest_stream': dest_stream,
224 'tmpfilename': tmpfilename,
75a24854
RA
225 # Total complete fragments downloaded so far in bytes
226 'complete_frags_downloaded_bytes': resume_len,
95d8f7ea
S
227 })
228
3ba7740d 229 def _start_frag_download(self, ctx, info_dict):
3bce4ff7 230 resume_len = ctx['complete_frags_downloaded_bytes']
95d8f7ea 231 total_frags = ctx['total_frags']
bd50a52b 232 ctx_id = ctx.get('ctx_id')
95d8f7ea
S
233 # This dict stores the download progress, it's updated by the progress
234 # hook
235 state = {
236 'status': 'downloading',
3bce4ff7 237 'downloaded_bytes': resume_len,
3e0304fe
RA
238 'fragment_index': ctx['fragment_index'],
239 'fragment_count': total_frags,
95d8f7ea
S
240 'filename': ctx['filename'],
241 'tmpfilename': ctx['tmpfilename'],
b83b782d
S
242 }
243
244 start = time.time()
245 ctx.update({
246 'started': start,
bd93fd5d 247 'fragment_started': start,
709185a2
S
248 # Amount of fragment's bytes downloaded by the time of the previous
249 # frag progress hook invocation
b83b782d
S
250 'prev_frag_downloaded_bytes': 0,
251 })
95d8f7ea
S
252
253 def frag_progress_hook(s):
254 if s['status'] not in ('downloading', 'finished'):
255 return
256
bd50a52b
THD
257 if ctx_id is not None and s.get('ctx_id') != ctx_id:
258 return
259
260 state['max_progress'] = ctx.get('max_progress')
261 state['progress_idx'] = ctx.get('progress_idx')
262
5fa1702c 263 time_now = time.time()
2c2f1efd 264 state['elapsed'] = time_now - start
3c91e416 265 frag_total_bytes = s.get('total_bytes') or 0
3ba7740d 266 s['fragment_info_dict'] = s.pop('info_dict', {})
5fa1702c
S
267 if not ctx['live']:
268 estimated_size = (
3089bc74
S
269 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
270 / (state['fragment_index'] + 1) * total_frags)
5fa1702c 271 state['total_bytes_estimate'] = estimated_size
95d8f7ea 272
709185a2 273 if s['status'] == 'finished':
3e0304fe
RA
274 state['fragment_index'] += 1
275 ctx['fragment_index'] = state['fragment_index']
b83b782d
S
276 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
277 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
bd93fd5d 278 ctx['speed'] = state['speed'] = self.calc_speed(
279 ctx['fragment_started'], time_now, frag_total_bytes)
280 ctx['fragment_started'] = time.time()
b83b782d 281 ctx['prev_frag_downloaded_bytes'] = 0
709185a2
S
282 else:
283 frag_downloaded_bytes = s['downloaded_bytes']
b83b782d 284 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
5fa1702c
S
285 if not ctx['live']:
286 state['eta'] = self.calc_eta(
3bce4ff7 287 start, time_now, estimated_size - resume_len,
288 state['downloaded_bytes'] - resume_len)
bd93fd5d 289 ctx['speed'] = state['speed'] = self.calc_speed(
290 ctx['fragment_started'], time_now, frag_downloaded_bytes)
b83b782d 291 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
3ba7740d 292 self._hook_progress(state, info_dict)
95d8f7ea
S
293
294 ctx['dl'].add_progress_hook(frag_progress_hook)
295
296 return start
297
3ba7740d 298 def _finish_frag_download(self, ctx, info_dict):
95d8f7ea 299 ctx['dest_stream'].close()
adb4b03c
S
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)
95d8f7ea 304 elapsed = time.time() - ctx['started']
0ff2c1ec
S
305
306 if ctx['tmpfilename'] == '-':
307 downloaded_bytes = ctx['complete_frags_downloaded_bytes']
308 else:
309 self.try_rename(ctx['tmpfilename'], ctx['filename'])
38d70284 310 if self.params.get('updatetime', True):
311 filetime = ctx.get('fragment_filetime')
312 if filetime:
313 try:
314 os.utime(ctx['filename'], (time.time(), filetime))
315 except Exception:
316 pass
0ff2c1ec 317 downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename']))
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)
5219cb3e 329
330 def _prepare_external_frag_download(self, ctx):
331 if 'live' not in ctx:
332 ctx['live'] = False
333 if not ctx['live']:
334 total_frags_str = '%d' % ctx['total_frags']
335 ad_frags = ctx.get('ad_frags', 0)
336 if ad_frags:
337 total_frags_str += ' (not including %d ad)' % ad_frags
338 else:
339 total_frags_str = 'unknown (live)'
340 self.to_screen(
341 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
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):
360 decrypt_info = fragment.get('decrypt_info')
361 if not decrypt_info or decrypt_info['METHOD'] != 'AES-128':
362 return frag_content
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):
369 return frag_content
1d3586d0 370 return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv))
1009f67c 371
372 return decrypt_fragment
373
bd50a52b
THD
374 def download_and_append_fragments_multiple(self, *args, pack_func=None, finish_func=None):
375 '''
376 @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
377 all args must be either tuple or list
378 '''
adbc4ec4 379 interrupt_trigger = [True]
bd50a52b
THD
380 max_progress = len(args)
381 if max_progress == 1:
382 return self.download_and_append_fragments(*args[0], pack_func=pack_func, finish_func=finish_func)
adbc4ec4 383 max_workers = self.params.get('concurrent_fragment_downloads', 1)
49a57e70 384 if max_progress > 1:
385 self._prepare_multiline_status(max_progress)
a539f065 386 is_live = any(traverse_obj(args, (..., 2, 'is_live'), default=[]))
bd50a52b
THD
387
388 def thread_func(idx, ctx, fragments, info_dict, tpe):
389 ctx['max_progress'] = max_progress
390 ctx['progress_idx'] = idx
adbc4ec4
THD
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)
bd50a52b
THD
394
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):
398 pass
399
adbc4ec4 400 if compat_os_name == 'nt':
a539f065
LNO
401 def bindoj_result(future):
402 while True:
403 try:
404 return future.result(0.1)
405 except KeyboardInterrupt:
406 raise
407 except concurrent.futures.TimeoutError:
408 continue
409 else:
410 def bindoj_result(future):
411 return future.result()
412
413 spins = []
bd50a52b 414 for idx, (ctx, fragments, info_dict) in enumerate(args):
adbc4ec4 415 tpe = FTPE(math.ceil(max_workers / max_progress))
a539f065
LNO
416
417 def interrupt_trigger_iter():
418 for f in fragments:
419 if not interrupt_trigger[0]:
420 break
421 yield f
422
423 job = tpe.submit(thread_func, idx, ctx, interrupt_trigger_iter(), info_dict, tpe)
bd50a52b
THD
424 spins.append((tpe, job))
425
426 result = True
427 for tpe, job in spins:
428 try:
a539f065 429 result = result and bindoj_result(job)
adbc4ec4
THD
430 except KeyboardInterrupt:
431 interrupt_trigger[0] = False
bd50a52b
THD
432 finally:
433 tpe.shutdown(wait=True)
a539f065 434 if not interrupt_trigger[0] and not is_live:
adbc4ec4 435 raise KeyboardInterrupt()
a539f065
LNO
436 # we expect the user wants to stop and DO WANT the preceding postprocessors to run;
437 # so returning a intermediate result here instead of KeyboardInterrupt on live
819e0531 438 return result
bd50a52b 439
adbc4ec4
THD
440 def download_and_append_fragments(
441 self, ctx, fragments, info_dict, *, pack_func=None, finish_func=None,
442 tpe=None, interrupt_trigger=None):
443 if not interrupt_trigger:
444 interrupt_trigger = (True, )
445
4c7853de 446 fragment_retries = self.params.get('fragment_retries', 0)
adbc4ec4
THD
447 is_fatal = (
448 ((lambda _: False) if info_dict.get('is_live') else (lambda idx: idx == 0))
449 if self.params.get('skip_unavailable_fragments', True) else (lambda _: True))
450
4c7853de 451 if not pack_func:
452 pack_func = lambda frag_content, _: frag_content
453
454 def download_fragment(fragment, ctx):
a539f065
LNO
455 if not interrupt_trigger[0]:
456 return False, fragment['frag_index']
457
4c7853de 458 frag_index = ctx['fragment_index'] = fragment['frag_index']
185bf310 459 ctx['last_error'] = None
d9d8b857 460 headers = info_dict.get('http_headers', {}).copy()
4c7853de 461 byte_range = fragment.get('byte_range')
462 if byte_range:
463 headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
464
465 # Never skip the first fragment
bd4d1ea3 466 fatal = is_fatal(fragment.get('index') or (frag_index - 1))
4c7853de 467 count, frag_content = 0, None
468 while count <= fragment_retries:
469 try:
470 success, frag_content = self._download_fragment(ctx, fragment['url'], info_dict, headers)
471 if not success:
472 return False, frag_index
473 break
adbc4ec4 474 except (compat_urllib_error.HTTPError, http.client.IncompleteRead) as err:
4c7853de 475 # Unavailable (possibly temporary) fragments may be served.
476 # First we try to retry then either skip or abort.
477 # See https://github.com/ytdl-org/youtube-dl/issues/10165,
478 # https://github.com/ytdl-org/youtube-dl/issues/10448).
479 count += 1
185bf310 480 ctx['last_error'] = err
4c7853de 481 if count <= fragment_retries:
482 self.report_retry_fragment(err, frag_index, count, fragment_retries)
483 except DownloadError:
484 # Don't retry fragment if error occurred during HTTP downloading
485 # itself since it has own retry settings
486 if not fatal:
487 break
488 raise
489
490 if count > fragment_retries:
491 if not fatal:
492 return False, frag_index
493 ctx['dest_stream'].close()
494 self.report_error('Giving up after %s fragment retries' % fragment_retries)
495 return False, frag_index
496 return frag_content, frag_index
497
4c7853de 498 def append_fragment(frag_content, frag_index, ctx):
499 if not frag_content:
bd4d1ea3 500 if not is_fatal(frag_index - 1):
b4b855eb 501 self.report_skip_fragment(frag_index, 'fragment not found')
4c7853de 502 return True
503 else:
504 ctx['dest_stream'].close()
505 self.report_error(
506 'fragment %s not found, unable to continue' % frag_index)
507 return False
508 self._append_fragment(ctx, pack_func(frag_content, frag_index))
509 return True
510
1009f67c 511 decrypt_fragment = self.decrypter(info_dict)
512
adbc4ec4
THD
513 max_workers = math.ceil(
514 self.params.get('concurrent_fragment_downloads', 1) / ctx.get('max_progress', 1))
4c7853de 515 if can_threaded_download and max_workers > 1:
516
517 def _download_fragment(fragment):
723d44b9 518 ctx_copy = ctx.copy()
519 frag_content, frag_index = download_fragment(fragment, ctx_copy)
520 return fragment, frag_content, frag_index, ctx_copy.get('fragment_filename_sanitized')
4c7853de 521
522 self.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome')
bd50a52b 523 with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
4c7853de 524 for fragment, frag_content, frag_index, frag_filename in pool.map(_download_fragment, fragments):
525 ctx['fragment_filename_sanitized'] = frag_filename
526 ctx['fragment_index'] = frag_index
527 result = append_fragment(decrypt_fragment(fragment, frag_content), frag_index, ctx)
528 if not result:
529 return False
530 else:
531 for fragment in fragments:
adbc4ec4
THD
532 if not interrupt_trigger[0]:
533 break
4c7853de 534 frag_content, frag_index = download_fragment(fragment, ctx)
535 result = append_fragment(decrypt_fragment(fragment, frag_content), frag_index, ctx)
536 if not result:
537 return False
538
25a3f4f5
F
539 if finish_func is not None:
540 ctx['dest_stream'].write(finish_func())
541 ctx['dest_stream'].flush()
3ba7740d 542 self._finish_frag_download(ctx, info_dict)
8e897ed2 543 return True