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