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