]>
Commit | Line | Data |
---|---|---|
19a03940 | 1 | import contextlib |
adbc4ec4 THD |
2 | import http.client |
3 | import json | |
4 | import math | |
95d8f7ea S |
5 | import os |
6 | import time | |
7 | ||
4c7853de | 8 | try: |
9 | import concurrent.futures | |
10 | can_threaded_download = True | |
11 | except ImportError: | |
12 | can_threaded_download = False | |
13 | ||
95d8f7ea S |
14 | from .common import FileDownloader |
15 | from .http import HttpFD | |
1d3586d0 | 16 | from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7 |
f8271158 | 17 | from ..compat import compat_os_name, compat_struct_pack, compat_urllib_error |
95d8f7ea | 18 | from ..utils import ( |
4c7853de | 19 | DownloadError, |
95d8f7ea | 20 | encodeFilename, |
f8271158 | 21 | error_to_compat_str, |
69035555 | 22 | sanitized_Request, |
a539f065 | 23 | traverse_obj, |
95d8f7ea S |
24 | ) |
25 | ||
26 | ||
27 | class HttpQuietDownloader(HttpFD): | |
28 | def to_screen(self, *args, **kargs): | |
29 | pass | |
30 | ||
bd93fd5d | 31 | def report_retry(self, err, count, retries): |
32 | super().to_screen( | |
33 | f'[download] Got server HTTP error: {err}. Retrying (attempt {count} of {self.format_retries(retries)}) ...') | |
34 | ||
95d8f7ea S |
35 | |
36 | class FragmentFD(FileDownloader): | |
37 | """ | |
38 | A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests). | |
16a8b798 S |
39 | |
40 | Available options: | |
41 | ||
9603b660 S |
42 | fragment_retries: Number of times to retry a fragment for HTTP error (DASH |
43 | and hlsnative only) | |
44 | skip_unavailable_fragments: | |
45 | Skip unavailable fragments (DASH and hlsnative only) | |
0eee52f3 S |
46 | keep_fragments: Keep downloaded fragments on disk after downloading is |
47 | finished | |
59a7a13e | 48 | concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads |
e8e73840 | 49 | _no_ytdl_file: Don't use .ytdl file |
290f64db | 50 | |
7a5c1cfe | 51 | For each incomplete fragment download yt-dlp keeps on disk a special |
290f64db | 52 | bookkeeping file with download state and metadata (in future such files will |
7a5c1cfe | 53 | be used for any incomplete download handled by yt-dlp). This file is |
290f64db S |
54 | used to properly handle resuming, check download file consistency and detect |
55 | potential errors. The file has a .ytdl extension and represents a standard | |
56 | JSON file of the following format: | |
57 | ||
58 | extractor: | |
59 | Dictionary of extractor related data. TBD. | |
60 | ||
61 | downloader: | |
62 | Dictionary of downloader related data. May contain following data: | |
63 | current_fragment: | |
64 | Dictionary with current (being downloaded) fragment data: | |
85f6de25 | 65 | index: 0-based index of current fragment among all fragments |
290f64db S |
66 | fragment_count: |
67 | Total count of fragments | |
50534b71 | 68 | |
85f6de25 | 69 | This feature is experimental and file format may change in future. |
95d8f7ea S |
70 | """ |
71 | ||
75a24854 | 72 | def report_retry_fragment(self, err, frag_index, count, retries): |
721f26b8 | 73 | self.to_screen( |
4c7853de | 74 | '\r[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s) ...' |
75a24854 | 75 | % (error_to_compat_str(err), frag_index, count, self.format_retries(retries))) |
721f26b8 | 76 | |
b4b855eb | 77 | def report_skip_fragment(self, frag_index, err=None): |
78 | err = f' {err};' if err else '' | |
79 | self.to_screen(f'[download]{err} Skipping fragment {frag_index:d} ...') | |
9603b660 | 80 | |
69035555 S |
81 | def _prepare_url(self, info_dict, url): |
82 | headers = info_dict.get('http_headers') | |
83 | return sanitized_Request(url, None, headers) if headers else url | |
84 | ||
3ba7740d | 85 | def _prepare_and_start_frag_download(self, ctx, info_dict): |
95d8f7ea | 86 | self._prepare_frag_download(ctx) |
3ba7740d | 87 | self._start_frag_download(ctx, info_dict) |
95d8f7ea | 88 | |
e8e73840 | 89 | def __do_ytdl_file(self, ctx): |
adbc4ec4 | 90 | return ctx['live'] is not True and ctx['tmpfilename'] != '-' and not self.params.get('_no_ytdl_file') |
adb4b03c | 91 | |
d3f0687c | 92 | def _read_ytdl_file(self, ctx): |
500a86a5 | 93 | assert 'ytdl_corrupt' not in ctx |
205a0654 | 94 | stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'r') |
500a86a5 | 95 | try: |
4d49884c F |
96 | ytdl_data = json.loads(stream.read()) |
97 | ctx['fragment_index'] = ytdl_data['downloader']['current_fragment']['index'] | |
98 | if 'extra_state' in ytdl_data['downloader']: | |
99 | ctx['extra_state'] = ytdl_data['downloader']['extra_state'] | |
500a86a5 S |
100 | except Exception: |
101 | ctx['ytdl_corrupt'] = True | |
102 | finally: | |
103 | stream.close() | |
d3f0687c S |
104 | |
105 | def _write_ytdl_file(self, ctx): | |
205a0654 | 106 | frag_index_stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'w') |
ad3dc496 | 107 | try: |
108 | downloader = { | |
109 | 'current_fragment': { | |
110 | 'index': ctx['fragment_index'], | |
111 | }, | |
112 | } | |
113 | if 'extra_state' in ctx: | |
114 | downloader['extra_state'] = ctx['extra_state'] | |
115 | if ctx.get('fragment_count') is not None: | |
116 | downloader['fragment_count'] = ctx['fragment_count'] | |
117 | frag_index_stream.write(json.dumps({'downloader': downloader})) | |
118 | finally: | |
119 | frag_index_stream.close() | |
d3f0687c | 120 | |
273762c8 | 121 | def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None): |
d3f0687c | 122 | fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index']) |
38d70284 | 123 | fragment_info_dict = { |
75a24854 RA |
124 | 'url': frag_url, |
125 | 'http_headers': headers or info_dict.get('http_headers'), | |
273762c8 | 126 | 'request_data': request_data, |
bd50a52b | 127 | 'ctx_id': ctx.get('ctx_id'), |
38d70284 | 128 | } |
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): |
5fa1702c S |
163 | if 'live' not in ctx: |
164 | ctx['live'] = False | |
5efaf43c S |
165 | if not ctx['live']: |
166 | total_frags_str = '%d' % ctx['total_frags'] | |
167 | ad_frags = ctx.get('ad_frags', 0) | |
168 | if ad_frags: | |
169 | total_frags_str += ' (not including %d ad)' % ad_frags | |
170 | else: | |
171 | total_frags_str = 'unknown (live)' | |
86e5f3ed | 172 | self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}') |
95d8f7ea S |
173 | self.report_destination(ctx['filename']) |
174 | dl = HttpQuietDownloader( | |
175 | self.ydl, | |
176 | { | |
93c8410d | 177 | 'continuedl': self.params.get('continuedl', True), |
bd93fd5d | 178 | 'quiet': self.params.get('quiet'), |
95d8f7ea | 179 | 'noprogress': True, |
d800609c | 180 | 'ratelimit': self.params.get('ratelimit'), |
6828c809 | 181 | 'retries': self.params.get('retries', 0), |
7097bffb | 182 | 'nopart': self.params.get('nopart', False), |
3b9d9f43 | 183 | 'test': False, |
95d8f7ea S |
184 | } |
185 | ) | |
186 | tmpfilename = self.temp_name(ctx['filename']) | |
75a24854 RA |
187 | open_mode = 'wb' |
188 | resume_len = 0 | |
d3f0687c | 189 | |
75a24854 RA |
190 | # Establish possible resume length |
191 | if os.path.isfile(encodeFilename(tmpfilename)): | |
192 | open_mode = 'ab' | |
193 | resume_len = os.path.getsize(encodeFilename(tmpfilename)) | |
d3f0687c | 194 | |
adb4b03c S |
195 | # Should be initialized before ytdl file check |
196 | ctx.update({ | |
197 | 'tmpfilename': tmpfilename, | |
198 | 'fragment_index': 0, | |
199 | }) | |
d3f0687c | 200 | |
adb4b03c S |
201 | if self.__do_ytdl_file(ctx): |
202 | if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))): | |
203 | self._read_ytdl_file(ctx) | |
500a86a5 S |
204 | is_corrupt = ctx.get('ytdl_corrupt') is True |
205 | is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0 | |
206 | if is_corrupt or is_inconsistent: | |
207 | message = ( | |
208 | '.ytdl file is corrupt' if is_corrupt else | |
209 | 'Inconsistent state of incomplete fragment download') | |
6f3b4a98 | 210 | self.report_warning( |
5ef7d9bd | 211 | '%s. Restarting from the beginning ...' % message) |
e7c3e334 | 212 | ctx['fragment_index'] = resume_len = 0 |
500a86a5 S |
213 | if 'ytdl_corrupt' in ctx: |
214 | del ctx['ytdl_corrupt'] | |
e7c3e334 | 215 | self._write_ytdl_file(ctx) |
adb4b03c S |
216 | else: |
217 | self._write_ytdl_file(ctx) | |
e7c3e334 | 218 | assert ctx['fragment_index'] == 0 |
d3f0687c | 219 | |
205a0654 | 220 | dest_stream, tmpfilename = self.sanitize_open(tmpfilename, open_mode) |
75a24854 | 221 | |
95d8f7ea S |
222 | ctx.update({ |
223 | 'dl': dl, | |
224 | 'dest_stream': dest_stream, | |
225 | 'tmpfilename': tmpfilename, | |
75a24854 RA |
226 | # Total complete fragments downloaded so far in bytes |
227 | 'complete_frags_downloaded_bytes': resume_len, | |
95d8f7ea S |
228 | }) |
229 | ||
3ba7740d | 230 | def _start_frag_download(self, ctx, info_dict): |
3bce4ff7 | 231 | resume_len = ctx['complete_frags_downloaded_bytes'] |
95d8f7ea | 232 | total_frags = ctx['total_frags'] |
bd50a52b | 233 | ctx_id = ctx.get('ctx_id') |
95d8f7ea S |
234 | # This dict stores the download progress, it's updated by the progress |
235 | # hook | |
236 | state = { | |
237 | 'status': 'downloading', | |
3bce4ff7 | 238 | 'downloaded_bytes': resume_len, |
3e0304fe RA |
239 | 'fragment_index': ctx['fragment_index'], |
240 | 'fragment_count': total_frags, | |
95d8f7ea S |
241 | 'filename': ctx['filename'], |
242 | 'tmpfilename': ctx['tmpfilename'], | |
b83b782d S |
243 | } |
244 | ||
245 | start = time.time() | |
246 | ctx.update({ | |
247 | 'started': start, | |
bd93fd5d | 248 | 'fragment_started': start, |
709185a2 S |
249 | # Amount of fragment's bytes downloaded by the time of the previous |
250 | # frag progress hook invocation | |
b83b782d S |
251 | 'prev_frag_downloaded_bytes': 0, |
252 | }) | |
95d8f7ea S |
253 | |
254 | def frag_progress_hook(s): | |
255 | if s['status'] not in ('downloading', 'finished'): | |
256 | return | |
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'] |
5fa1702c S |
286 | if not ctx['live']: |
287 | state['eta'] = self.calc_eta( | |
3bce4ff7 | 288 | start, time_now, estimated_size - resume_len, |
289 | state['downloaded_bytes'] - resume_len) | |
bd93fd5d | 290 | ctx['speed'] = state['speed'] = self.calc_speed( |
291 | ctx['fragment_started'], time_now, frag_downloaded_bytes) | |
b83b782d | 292 | ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes |
3ba7740d | 293 | self._hook_progress(state, info_dict) |
95d8f7ea S |
294 | |
295 | ctx['dl'].add_progress_hook(frag_progress_hook) | |
296 | ||
297 | return start | |
298 | ||
3ba7740d | 299 | def _finish_frag_download(self, ctx, info_dict): |
95d8f7ea | 300 | ctx['dest_stream'].close() |
adb4b03c S |
301 | if self.__do_ytdl_file(ctx): |
302 | ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename'])) | |
303 | if os.path.isfile(ytdl_filename): | |
45806d44 | 304 | self.try_remove(ytdl_filename) |
95d8f7ea | 305 | elapsed = time.time() - ctx['started'] |
0ff2c1ec S |
306 | |
307 | if ctx['tmpfilename'] == '-': | |
308 | downloaded_bytes = ctx['complete_frags_downloaded_bytes'] | |
309 | else: | |
310 | self.try_rename(ctx['tmpfilename'], ctx['filename']) | |
38d70284 | 311 | if self.params.get('updatetime', True): |
312 | filetime = ctx.get('fragment_filetime') | |
313 | if filetime: | |
19a03940 | 314 | with contextlib.suppress(Exception): |
38d70284 | 315 | os.utime(ctx['filename'], (time.time(), filetime)) |
0ff2c1ec | 316 | downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename'])) |
95d8f7ea S |
317 | |
318 | self._hook_progress({ | |
0ff2c1ec S |
319 | 'downloaded_bytes': downloaded_bytes, |
320 | 'total_bytes': downloaded_bytes, | |
95d8f7ea S |
321 | 'filename': ctx['filename'], |
322 | 'status': 'finished', | |
323 | 'elapsed': elapsed, | |
bd50a52b THD |
324 | 'ctx_id': ctx.get('ctx_id'), |
325 | 'max_progress': ctx.get('max_progress'), | |
326 | 'progress_idx': ctx.get('progress_idx'), | |
3ba7740d | 327 | }, info_dict) |
5219cb3e | 328 | |
329 | def _prepare_external_frag_download(self, ctx): | |
330 | if 'live' not in ctx: | |
331 | ctx['live'] = False | |
332 | if not ctx['live']: | |
333 | total_frags_str = '%d' % ctx['total_frags'] | |
334 | ad_frags = ctx.get('ad_frags', 0) | |
335 | if ad_frags: | |
336 | total_frags_str += ' (not including %d ad)' % ad_frags | |
337 | else: | |
338 | total_frags_str = 'unknown (live)' | |
86e5f3ed | 339 | self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}') |
5219cb3e | 340 | |
341 | tmpfilename = self.temp_name(ctx['filename']) | |
342 | ||
343 | # Should be initialized before ytdl file check | |
344 | ctx.update({ | |
345 | 'tmpfilename': tmpfilename, | |
346 | 'fragment_index': 0, | |
347 | }) | |
4c7853de | 348 | |
1009f67c | 349 | def decrypter(self, info_dict): |
350 | _key_cache = {} | |
351 | ||
352 | def _get_key(url): | |
353 | if url not in _key_cache: | |
354 | _key_cache[url] = self.ydl.urlopen(self._prepare_url(info_dict, url)).read() | |
355 | return _key_cache[url] | |
356 | ||
357 | def decrypt_fragment(fragment, frag_content): | |
358 | decrypt_info = fragment.get('decrypt_info') | |
359 | if not decrypt_info or decrypt_info['METHOD'] != 'AES-128': | |
360 | return frag_content | |
361 | iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', fragment['media_sequence']) | |
362 | decrypt_info['KEY'] = decrypt_info.get('KEY') or _get_key(info_dict.get('_decryption_key_url') or decrypt_info['URI']) | |
363 | # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block | |
364 | # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded, | |
365 | # not what it decrypts to. | |
366 | if self.params.get('test', False): | |
367 | return frag_content | |
1d3586d0 | 368 | return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv)) |
1009f67c | 369 | |
370 | return decrypt_fragment | |
371 | ||
bd50a52b THD |
372 | def download_and_append_fragments_multiple(self, *args, pack_func=None, finish_func=None): |
373 | ''' | |
374 | @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ... | |
375 | all args must be either tuple or list | |
376 | ''' | |
adbc4ec4 | 377 | interrupt_trigger = [True] |
bd50a52b THD |
378 | max_progress = len(args) |
379 | if max_progress == 1: | |
380 | return self.download_and_append_fragments(*args[0], pack_func=pack_func, finish_func=finish_func) | |
adbc4ec4 | 381 | max_workers = self.params.get('concurrent_fragment_downloads', 1) |
49a57e70 | 382 | if max_progress > 1: |
383 | self._prepare_multiline_status(max_progress) | |
a539f065 | 384 | is_live = any(traverse_obj(args, (..., 2, 'is_live'), default=[])) |
bd50a52b THD |
385 | |
386 | def thread_func(idx, ctx, fragments, info_dict, tpe): | |
387 | ctx['max_progress'] = max_progress | |
388 | ctx['progress_idx'] = idx | |
adbc4ec4 THD |
389 | return self.download_and_append_fragments( |
390 | ctx, fragments, info_dict, pack_func=pack_func, finish_func=finish_func, | |
391 | tpe=tpe, interrupt_trigger=interrupt_trigger) | |
bd50a52b THD |
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 | ||
adbc4ec4 | 398 | if compat_os_name == 'nt': |
a44ca5a4 | 399 | def future_result(future): |
a539f065 LNO |
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: | |
a44ca5a4 | 408 | def future_result(future): |
a539f065 LNO |
409 | return future.result() |
410 | ||
f0734e11 L |
411 | def interrupt_trigger_iter(fg): |
412 | for f in fg: | |
413 | if not interrupt_trigger[0]: | |
414 | break | |
415 | yield f | |
416 | ||
a539f065 | 417 | spins = [] |
bd50a52b | 418 | for idx, (ctx, fragments, info_dict) in enumerate(args): |
adbc4ec4 | 419 | tpe = FTPE(math.ceil(max_workers / max_progress)) |
f0734e11 | 420 | job = tpe.submit(thread_func, idx, ctx, interrupt_trigger_iter(fragments), info_dict, tpe) |
bd50a52b THD |
421 | spins.append((tpe, job)) |
422 | ||
423 | result = True | |
424 | for tpe, job in spins: | |
425 | try: | |
a44ca5a4 | 426 | result = result and future_result(job) |
adbc4ec4 THD |
427 | except KeyboardInterrupt: |
428 | interrupt_trigger[0] = False | |
bd50a52b THD |
429 | finally: |
430 | tpe.shutdown(wait=True) | |
a539f065 | 431 | if not interrupt_trigger[0] and not is_live: |
adbc4ec4 | 432 | raise KeyboardInterrupt() |
a539f065 LNO |
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 | |
819e0531 | 435 | return result |
bd50a52b | 436 | |
adbc4ec4 THD |
437 | def download_and_append_fragments( |
438 | self, ctx, fragments, info_dict, *, pack_func=None, finish_func=None, | |
439 | tpe=None, interrupt_trigger=None): | |
440 | if not interrupt_trigger: | |
441 | interrupt_trigger = (True, ) | |
442 | ||
4c7853de | 443 | fragment_retries = self.params.get('fragment_retries', 0) |
adbc4ec4 THD |
444 | is_fatal = ( |
445 | ((lambda _: False) if info_dict.get('is_live') else (lambda idx: idx == 0)) | |
446 | if self.params.get('skip_unavailable_fragments', True) else (lambda _: True)) | |
447 | ||
4c7853de | 448 | if not pack_func: |
449 | pack_func = lambda frag_content, _: frag_content | |
450 | ||
451 | def download_fragment(fragment, ctx): | |
a539f065 | 452 | if not interrupt_trigger[0]: |
d71fd412 | 453 | return |
a539f065 | 454 | |
4c7853de | 455 | frag_index = ctx['fragment_index'] = fragment['frag_index'] |
185bf310 | 456 | ctx['last_error'] = None |
d9d8b857 | 457 | headers = info_dict.get('http_headers', {}).copy() |
4c7853de | 458 | byte_range = fragment.get('byte_range') |
459 | if byte_range: | |
460 | headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1) | |
461 | ||
462 | # Never skip the first fragment | |
d71fd412 | 463 | fatal, count = is_fatal(fragment.get('index') or (frag_index - 1)), 0 |
4c7853de | 464 | while count <= fragment_retries: |
465 | try: | |
d71fd412 LNO |
466 | if self._download_fragment(ctx, fragment['url'], info_dict, headers): |
467 | break | |
468 | return | |
adbc4ec4 | 469 | except (compat_urllib_error.HTTPError, http.client.IncompleteRead) as err: |
4c7853de | 470 | # Unavailable (possibly temporary) fragments may be served. |
471 | # First we try to retry then either skip or abort. | |
472 | # See https://github.com/ytdl-org/youtube-dl/issues/10165, | |
473 | # https://github.com/ytdl-org/youtube-dl/issues/10448). | |
474 | count += 1 | |
185bf310 | 475 | ctx['last_error'] = err |
4c7853de | 476 | if count <= fragment_retries: |
477 | self.report_retry_fragment(err, frag_index, count, fragment_retries) | |
478 | except DownloadError: | |
479 | # Don't retry fragment if error occurred during HTTP downloading | |
480 | # itself since it has own retry settings | |
481 | if not fatal: | |
482 | break | |
483 | raise | |
484 | ||
d71fd412 | 485 | if count > fragment_retries and fatal: |
4c7853de | 486 | ctx['dest_stream'].close() |
487 | self.report_error('Giving up after %s fragment retries' % fragment_retries) | |
4c7853de | 488 | |
4c7853de | 489 | def append_fragment(frag_content, frag_index, ctx): |
a44ca5a4 | 490 | if frag_content: |
491 | self._append_fragment(ctx, pack_func(frag_content, frag_index)) | |
492 | elif not is_fatal(frag_index - 1): | |
493 | self.report_skip_fragment(frag_index, 'fragment not found') | |
494 | else: | |
495 | ctx['dest_stream'].close() | |
496 | self.report_error(f'fragment {frag_index} not found, unable to continue') | |
497 | return False | |
4c7853de | 498 | return True |
499 | ||
1009f67c | 500 | decrypt_fragment = self.decrypter(info_dict) |
501 | ||
adbc4ec4 THD |
502 | max_workers = math.ceil( |
503 | self.params.get('concurrent_fragment_downloads', 1) / ctx.get('max_progress', 1)) | |
4c7853de | 504 | if can_threaded_download and max_workers > 1: |
505 | ||
506 | def _download_fragment(fragment): | |
723d44b9 | 507 | ctx_copy = ctx.copy() |
d71fd412 LNO |
508 | download_fragment(fragment, ctx_copy) |
509 | return fragment, fragment['frag_index'], ctx_copy.get('fragment_filename_sanitized') | |
4c7853de | 510 | |
511 | self.report_warning('The download speed shown is only of one thread. This is a known issue and patches are welcome') | |
bd50a52b | 512 | with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool: |
d71fd412 | 513 | for fragment, frag_index, frag_filename in pool.map(_download_fragment, fragments): |
4c7853de | 514 | ctx['fragment_filename_sanitized'] = frag_filename |
515 | ctx['fragment_index'] = frag_index | |
d71fd412 | 516 | result = append_fragment(decrypt_fragment(fragment, self._read_fragment(ctx)), frag_index, ctx) |
4c7853de | 517 | if not result: |
518 | return False | |
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() | |
3ba7740d | 537 | self._finish_frag_download(ctx, info_dict) |
8e897ed2 | 538 | return True |