]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/external.py
Standardize retry mechanism (#1649)
[yt-dlp.git] / yt_dlp / downloader / external.py
CommitLineData
c487cf00 1import enum
222516d9 2import os.path
f0298f65 3import re
222516d9 4import subprocess
12b84ac8 5import sys
f0298f65 6import time
5219cb3e 7
1009f67c 8from .fragment import FragmentFD
14f25df2 9from ..compat import functools
f8271158 10from ..postprocessor.ffmpeg import EXT_TO_OUT_FORMATS, FFmpegPostProcessor
222516d9 11from ..utils import (
f8271158 12 Popen,
be5c1ae8 13 RetryManager,
f8271158 14 _configuration_args,
15 check_executable,
28787f16 16 classproperty,
f8271158 17 cli_bool_option,
1195a38f
S
18 cli_option,
19 cli_valueless_option,
af6793f8 20 determine_ext,
74f8654a 21 encodeArgument,
f8271158 22 encodeFilename,
12b84ac8 23 handle_youtubedl_headers,
af6793f8 24 remove_end,
0a5a191a 25 traverse_obj,
222516d9
PH
26)
27
28
c487cf00 29class Features(enum.Enum):
30 TO_STDOUT = enum.auto()
31 MULTIPLE_FORMATS = enum.auto()
32
33
1009f67c 34class ExternalFD(FragmentFD):
5219cb3e 35 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps')
c487cf00 36 SUPPORTED_FEATURES = ()
f0c9fb96 37 _CAPTURE_STDERR = True
5219cb3e 38
222516d9
PH
39 def real_download(self, filename, info_dict):
40 self.report_destination(filename)
41 tmpfilename = self.temp_name(filename)
42
e7db6759 43 try:
f0298f65 44 started = time.time()
e7db6759
S
45 retval = self._call_downloader(tmpfilename, info_dict)
46 except KeyboardInterrupt:
47 if not info_dict.get('is_live'):
48 raise
49 # Live stream downloading cancellation should be considered as
50 # correct and expected termination thus all postprocessing
51 # should take place
52 retval = 0
53 self.to_screen('[%s] Interrupted by user' % self.get_basename())
54
222516d9 55 if retval == 0:
f0298f65
S
56 status = {
57 'filename': filename,
58 'status': 'finished',
59 'elapsed': time.time() - started,
60 }
61 if filename != '-':
80aa2460 62 fsize = os.path.getsize(encodeFilename(tmpfilename))
86e5f3ed 63 self.to_screen(f'\r[{self.get_basename()}] Downloaded {fsize} bytes')
80aa2460 64 self.try_rename(tmpfilename, filename)
f0298f65 65 status.update({
80aa2460
JH
66 'downloaded_bytes': fsize,
67 'total_bytes': fsize,
80aa2460 68 })
3ba7740d 69 self._hook_progress(status, info_dict)
222516d9
PH
70 return True
71 else:
72 self.to_stderr('\n')
73 self.report_error('%s exited with code %d' % (
74 self.get_basename(), retval))
75 return False
76
77 @classmethod
78 def get_basename(cls):
79 return cls.__name__[:-2].lower()
80
28787f16 81 @classproperty
82 def EXE_NAME(cls):
83 return cls.get_basename()
84
2762dbb1 85 @functools.cached_property
222516d9 86 def exe(self):
28787f16 87 return self.EXE_NAME
222516d9 88
99cbe98c 89 @classmethod
7f7de7f9 90 def available(cls, path=None):
28787f16 91 path = check_executable(
92 cls.EXE_NAME if path in (None, cls.get_basename()) else path,
93 [cls.AVAILABLE_OPT])
94 if not path:
95 return False
96 cls.exe = path
97 return path
99cbe98c 98
222516d9
PH
99 @classmethod
100 def supports(cls, info_dict):
c487cf00 101 return all((
102 not info_dict.get('to_stdout') or Features.TO_STDOUT in cls.SUPPORTED_FEATURES,
103 '+' not in info_dict['protocol'] or Features.MULTIPLE_FORMATS in cls.SUPPORTED_FEATURES,
104 all(proto in cls.SUPPORTED_PROTOCOLS for proto in info_dict['protocol'].split('+')),
105 ))
222516d9 106
2cb99ebb 107 @classmethod
7f7de7f9 108 def can_download(cls, info_dict, path=None):
109 return cls.available(path) and cls.supports(info_dict)
2cb99ebb 110
bf812ef7 111 def _option(self, command_option, param):
1195a38f 112 return cli_option(self.params, command_option, param)
bf812ef7 113
266b0ad6 114 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
1195a38f 115 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
266b0ad6 116
dc534b67 117 def _valueless_option(self, command_option, param, expected_value=True):
1195a38f 118 return cli_valueless_option(self.params, command_option, param, expected_value)
f30c2e8e 119
330690a2 120 def _configuration_args(self, keys=None, *args, **kwargs):
121 return _configuration_args(
28787f16 122 self.get_basename(), self.params.get('external_downloader_args'), self.EXE_NAME,
330690a2 123 keys, *args, **kwargs)
c75f0b36 124
222516d9
PH
125 def _call_downloader(self, tmpfilename, info_dict):
126 """ Either overwrite this or implement _make_cmd """
74f8654a 127 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
222516d9 128
74f8654a 129 self._debug_cmd(cmd)
222516d9 130
fc5c8b64 131 if 'fragments' not in info_dict:
f0c9fb96 132 _, stderr, returncode = Popen.run(
133 cmd, text=True, stderr=subprocess.PIPE if self._CAPTURE_STDERR else None)
134 if returncode and stderr:
135 self.to_stderr(stderr)
136 return returncode
fc5c8b64 137
fc5c8b64 138 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
139
be5c1ae8 140 retry_manager = RetryManager(self.params.get('fragment_retries'), self.report_retry,
141 frag_index=None, fatal=not skip_unavailable_fragments)
142 for retry in retry_manager:
f0c9fb96 143 _, stderr, returncode = Popen.run(cmd, text=True, stderr=subprocess.PIPE)
144 if not returncode:
fc5c8b64 145 break
146 # TODO: Decide whether to retry based on error code
147 # https://aria2.github.io/manual/en/html/aria2c.html#exit-status
f0c9fb96 148 if stderr:
149 self.to_stderr(stderr)
be5c1ae8 150 retry.error = Exception()
151 continue
152 if not skip_unavailable_fragments and retry_manager.error:
153 return -1
fc5c8b64 154
155 decrypt_fragment = self.decrypter(info_dict)
205a0654 156 dest, _ = self.sanitize_open(tmpfilename, 'wb')
fc5c8b64 157 for frag_index, fragment in enumerate(info_dict['fragments']):
158 fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index)
159 try:
205a0654 160 src, _ = self.sanitize_open(fragment_filename, 'rb')
86e5f3ed 161 except OSError as err:
fc5c8b64 162 if skip_unavailable_fragments and frag_index > 1:
b4b855eb 163 self.report_skip_fragment(frag_index, err)
fc5c8b64 164 continue
b4b855eb 165 self.report_error(f'Unable to open fragment {frag_index}; {err}')
fc5c8b64 166 return -1
167 dest.write(decrypt_fragment(fragment, src.read()))
168 src.close()
169 if not self.params.get('keep_fragments', False):
45806d44 170 self.try_remove(encodeFilename(fragment_filename))
fc5c8b64 171 dest.close()
45806d44 172 self.try_remove(encodeFilename('%s.frag.urls' % tmpfilename))
fc5c8b64 173 return 0
222516d9
PH
174
175
384b6202 176class CurlFD(ExternalFD):
91ee320b 177 AVAILABLE_OPT = '-V'
f0c9fb96 178 _CAPTURE_STDERR = False # curl writes the progress to stderr
99cbe98c 179
384b6202 180 def _make_cmd(self, tmpfilename, info_dict):
af14914b 181 cmd = [self.exe, '--location', '-o', tmpfilename, '--compressed']
002ea8fe 182 if info_dict.get('http_headers') is not None:
183 for key, val in info_dict['http_headers'].items():
86e5f3ed 184 cmd += ['--header', f'{key}: {val}']
002ea8fe 185
98e698f1
RA
186 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
187 cmd += self._valueless_option('--silent', 'noprogress')
188 cmd += self._valueless_option('--verbose', 'verbose')
189 cmd += self._option('--limit-rate', 'ratelimit')
37b239b3
S
190 retry = self._option('--retry', 'retries')
191 if len(retry) == 2:
192 if retry[1] in ('inf', 'infinite'):
193 retry[1] = '2147483647'
194 cmd += retry
98e698f1 195 cmd += self._option('--max-filesize', 'max_filesize')
9f3da138 196 cmd += self._option('--interface', 'source_address')
e7a8c303 197 cmd += self._option('--proxy', 'proxy')
dc534b67 198 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
c75f0b36 199 cmd += self._configuration_args()
384b6202
PH
200 cmd += ['--', info_dict['url']]
201 return cmd
202
203
e0ac5214 204class AxelFD(ExternalFD):
91ee320b 205 AVAILABLE_OPT = '-V'
99cbe98c 206
e0ac5214 207 def _make_cmd(self, tmpfilename, info_dict):
208 cmd = [self.exe, '-o', tmpfilename]
002ea8fe 209 if info_dict.get('http_headers') is not None:
210 for key, val in info_dict['http_headers'].items():
86e5f3ed 211 cmd += ['-H', f'{key}: {val}']
e0ac5214 212 cmd += self._configuration_args()
213 cmd += ['--', info_dict['url']]
214 return cmd
215
216
222516d9 217class WgetFD(ExternalFD):
91ee320b 218 AVAILABLE_OPT = '--version'
99cbe98c 219
222516d9 220 def _make_cmd(self, tmpfilename, info_dict):
af14914b 221 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto']
002ea8fe 222 if info_dict.get('http_headers') is not None:
223 for key, val in info_dict['http_headers'].items():
86e5f3ed 224 cmd += ['--header', f'{key}: {val}']
8c80603f
S
225 cmd += self._option('--limit-rate', 'ratelimit')
226 retry = self._option('--tries', 'retries')
227 if len(retry) == 2:
228 if retry[1] in ('inf', 'infinite'):
229 retry[1] = '0'
230 cmd += retry
9f3da138 231 cmd += self._option('--bind-address', 'source_address')
8a23db95 232 proxy = self.params.get('proxy')
233 if proxy:
234 for var in ('http_proxy', 'https_proxy'):
86e5f3ed 235 cmd += ['--execute', f'{var}={proxy}']
dc534b67 236 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
c75f0b36 237 cmd += self._configuration_args()
222516d9
PH
238 cmd += ['--', info_dict['url']]
239 return cmd
240
241
384b6202 242class Aria2cFD(ExternalFD):
91ee320b 243 AVAILABLE_OPT = '-v'
52a8a1e1 244 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
99cbe98c 245
0a473f2f 246 @staticmethod
247 def supports_manifest(manifest):
248 UNSUPPORTED_FEATURES = [
249 r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1]
250 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
251 ]
252 check_results = (not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES)
253 return all(check_results)
254
384b6202 255 def _make_cmd(self, tmpfilename, info_dict):
2b3bf01c 256 cmd = [self.exe, '-c',
257 '--console-log-level=warn', '--summary-interval=0', '--download-result=hide',
dcd55f76 258 '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16']
2b3bf01c 259 if 'fragments' in info_dict:
260 cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true']
ff0f78e1 261 else:
262 cmd += ['--min-split-size', '1M']
2b3bf01c 263
002ea8fe 264 if info_dict.get('http_headers') is not None:
265 for key, val in info_dict['http_headers'].items():
86e5f3ed 266 cmd += ['--header', f'{key}: {val}']
691d5823 267 cmd += self._option('--max-overall-download-limit', 'ratelimit')
9f3da138 268 cmd += self._option('--interface', 'source_address')
bf812ef7 269 cmd += self._option('--all-proxy', 'proxy')
266b0ad6 270 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
71f47617 271 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
f44afb54 272 cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=')
2b3bf01c 273 cmd += self._configuration_args()
274
eb55bad5 275 # aria2c strips out spaces from the beginning/end of filenames and paths.
276 # We work around this issue by adding a "./" to the beginning of the
277 # filename and relative path, and adding a "/" at the end of the path.
278 # See: https://github.com/yt-dlp/yt-dlp/issues/276
279 # https://github.com/ytdl-org/youtube-dl/issues/20312
280 # https://github.com/aria2/aria2/issues/1373
2b3bf01c 281 dn = os.path.dirname(tmpfilename)
282 if dn:
eb55bad5 283 if not os.path.isabs(dn):
86e5f3ed 284 dn = f'.{os.path.sep}{dn}'
eb55bad5 285 cmd += ['--dir', dn + os.path.sep]
2b3bf01c 286 if 'fragments' not in info_dict:
86e5f3ed 287 cmd += ['--out', f'.{os.path.sep}{os.path.basename(tmpfilename)}']
5219cb3e 288 cmd += ['--auto-file-renaming=false']
2b3bf01c 289
d7009caa 290 if 'fragments' in info_dict:
fe845284 291 cmd += ['--file-allocation=none', '--uri-selector=inorder']
5219cb3e 292 url_list_file = '%s.frag.urls' % tmpfilename
293 url_list = []
fe845284 294 for frag_index, fragment in enumerate(info_dict['fragments']):
295 fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index)
296 url_list.append('%s\n\tout=%s' % (fragment['url'], fragment_filename))
205a0654 297 stream, _ = self.sanitize_open(url_list_file, 'wb')
0f06bcd7 298 stream.write('\n'.join(url_list).encode())
539d158c 299 stream.close()
5219cb3e 300 cmd += ['-i', url_list_file]
301 else:
302 cmd += ['--', info_dict['url']]
384b6202
PH
303 return cmd
304
906e2f0e
JMF
305
306class HttpieFD(ExternalFD):
52a8a1e1 307 AVAILABLE_OPT = '--version'
28787f16 308 EXE_NAME = 'http'
99cbe98c 309
906e2f0e
JMF
310 def _make_cmd(self, tmpfilename, info_dict):
311 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
002ea8fe 312
313 if info_dict.get('http_headers') is not None:
314 for key, val in info_dict['http_headers'].items():
86e5f3ed 315 cmd += [f'{key}:{val}']
906e2f0e
JMF
316 return cmd
317
12b84ac8 318
319class FFmpegFD(ExternalFD):
6251555f 320 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments')
c487cf00 321 SUPPORTED_FEATURES = (Features.TO_STDOUT, Features.MULTIPLE_FORMATS)
12b84ac8 322
99cbe98c 323 @classmethod
52a8a1e1 324 def available(cls, path=None):
325 # TODO: Fix path for ffmpeg
dbf5416a 326 # Fixme: This may be wrong when --ffmpeg-location is used
99cbe98c 327 return FFmpegPostProcessor().available
328
e36d50c5 329 def on_process_started(self, proc, stdin):
330 """ Override this in subclasses """
331 pass
332
dbf5416a 333 @classmethod
d5fe04f5 334 def can_merge_formats(cls, info_dict, params):
dbf5416a 335 return (
336 info_dict.get('requested_formats')
337 and info_dict.get('protocol')
338 and not params.get('allow_unplayable_formats')
339 and 'no-direct-merge' not in params.get('compat_opts', [])
340 and cls.can_download(info_dict))
341
12b84ac8 342 def _call_downloader(self, tmpfilename, info_dict):
18e674b4 343 urls = [f['url'] for f in info_dict.get('requested_formats', [])] or [info_dict['url']]
12b84ac8 344 ffpp = FFmpegPostProcessor(downloader=self)
77dea16a 345 if not ffpp.available:
e3b771a8 346 self.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
77dea16a 347 return False
12b84ac8 348 ffpp.check_version()
349
350 args = [ffpp.executable, '-y']
351
a609e61a
S
352 for log_level in ('quiet', 'verbose'):
353 if self.params.get(log_level, False):
354 args += ['-loglevel', log_level]
355 break
2ec1759f 356 if not self.params.get('verbose'):
357 args += ['-hide_banner']
a609e61a 358
0a5a191a 359 args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[])
bb36a55c 360
0a5a191a 361 # These exists only for compatibility. Extractors should use
362 # info_dict['downloader_options']['ffmpeg_args'] instead
1d485a1a 363 args += info_dict.get('_ffmpeg_args') or []
36fce548
RA
364 seekable = info_dict.get('_seekable')
365 if seekable is not None:
366 # setting -seekable prevents ffmpeg from guessing if the server
367 # supports seeking(by adding the header `Range: bytes=0-`), which
368 # can cause problems in some cases
067aa17e 369 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
36fce548
RA
370 # http://trac.ffmpeg.org/ticket/6125#comment:10
371 args += ['-seekable', '1' if seekable else '0']
372
00828e2c
E
373 http_headers = None
374 if info_dict.get('http_headers'):
375 youtubedl_headers = handle_youtubedl_headers(info_dict['http_headers'])
376 http_headers = [
377 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
378 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
12b84ac8 379 '-headers',
00828e2c
E
380 ''.join(f'{key}: {val}\r\n' for key, val in youtubedl_headers.items())
381 ]
12b84ac8 382
e62d9c5c
S
383 env = None
384 proxy = self.params.get('proxy')
385 if proxy:
386 if not re.match(r'^[\da-zA-Z]+://', proxy):
387 proxy = 'http://%s' % proxy
20bad91d
YCH
388
389 if proxy.startswith('socks'):
390 self.report_warning(
6c9b71bc
YCH
391 '%s does not support SOCKS proxies. Downloading is likely to fail. '
392 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
20bad91d 393
e62d9c5c
S
394 # Since December 2015 ffmpeg supports -http_proxy option (see
395 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
396 # We could switch to the following code if we are able to detect version properly
397 # args += ['-http_proxy', proxy]
398 env = os.environ.copy()
ac668111 399 env['HTTP_PROXY'] = proxy
400 env['http_proxy'] = proxy
e62d9c5c 401
4230c489 402 protocol = info_dict.get('protocol')
403
404 if protocol == 'rtmp':
405 player_url = info_dict.get('player_url')
406 page_url = info_dict.get('page_url')
407 app = info_dict.get('app')
408 play_path = info_dict.get('play_path')
409 tc_url = info_dict.get('tc_url')
410 flash_version = info_dict.get('flash_version')
411 live = info_dict.get('rtmp_live', False)
d7d86fdd 412 conn = info_dict.get('rtmp_conn')
4230c489 413 if player_url is not None:
414 args += ['-rtmp_swfverify', player_url]
415 if page_url is not None:
416 args += ['-rtmp_pageurl', page_url]
417 if app is not None:
418 args += ['-rtmp_app', app]
419 if play_path is not None:
420 args += ['-rtmp_playpath', play_path]
421 if tc_url is not None:
422 args += ['-rtmp_tcurl', tc_url]
423 if flash_version is not None:
424 args += ['-rtmp_flashver', flash_version]
425 if live:
426 args += ['-rtmp_live', 'live']
d7d86fdd
RA
427 if isinstance(conn, list):
428 for entry in conn:
429 args += ['-rtmp_conn', entry]
c487cf00 430 elif isinstance(conn, str):
d7d86fdd 431 args += ['-rtmp_conn', conn]
4230c489 432
5ec1b6b7 433 start_time, end_time = info_dict.get('section_start') or 0, info_dict.get('section_end')
434
330690a2 435 for i, url in enumerate(urls):
00828e2c
E
436 if http_headers is not None and re.match(r'^https?://', url):
437 args += http_headers
5ec1b6b7 438 if start_time:
439 args += ['-ss', str(start_time)]
440 if end_time:
441 args += ['-t', str(end_time - start_time)]
442
330690a2 443 args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', url]
6b6c16ca 444
5ec1b6b7 445 if not (start_time or end_time) or not self.params.get('force_keyframes_at_cuts'):
446 args += ['-c', 'copy']
447
6251555f 448 if info_dict.get('requested_formats') or protocol == 'http_dash_segments':
449 for (i, fmt) in enumerate(info_dict.get('requested_formats') or [info_dict]):
450 stream_number = fmt.get('manifest_stream_number', 0)
234416e4 451 args.extend(['-map', f'{i}:{stream_number}'])
6d0fe752
JH
452
453 if self.params.get('test', False):
c487cf00 454 args += ['-fs', str(self._TEST_FILE_SIZE)]
6d0fe752 455
e5611e8e 456 ext = info_dict['ext']
f5436c5d 457 if protocol in ('m3u8', 'm3u8_native'):
9bd20204 458 use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts')
459 if use_mpegts is None:
460 use_mpegts = info_dict.get('is_live')
461 if use_mpegts:
12b84ac8 462 args += ['-f', 'mpegts']
463 else:
8bdc1494 464 args += ['-f', 'mp4']
8913ef74 465 if (ffpp.basename == 'ffmpeg' and ffpp._features.get('needs_adtstoasc')) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')):
8bdc1494 466 args += ['-bsf:a', 'aac_adtstoasc']
4230c489 467 elif protocol == 'rtmp':
468 args += ['-f', 'flv']
e5611e8e 469 elif ext == 'mp4' and tmpfilename == '-':
470 args += ['-f', 'mpegts']
af6793f8 471 elif ext == 'unknown_video':
472 ext = determine_ext(remove_end(tmpfilename, '.part'))
473 if ext == 'unknown_video':
474 self.report_warning(
475 'The video format is unknown and cannot be downloaded by ffmpeg. '
476 'Explicitly set the extension in the filename to attempt download in that format')
477 else:
478 self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename')
479 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
12b84ac8 480 else:
e5611e8e 481 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
12b84ac8 482
6251555f 483 args += self._configuration_args(('_o1', '_o', ''))
330690a2 484
12b84ac8 485 args = [encodeArgument(opt) for opt in args]
d868f43c 486 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
12b84ac8 487 self._debug_cmd(args)
488
f0c9fb96 489 with Popen(args, stdin=subprocess.PIPE, env=env) as proc:
490 if url in ('-', 'pipe:'):
491 self.on_process_started(proc, proc.stdin)
492 try:
493 retval = proc.wait()
494 except BaseException as e:
495 # subprocces.run would send the SIGKILL signal to ffmpeg and the
496 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
497 # produces a file that is playable (this is mostly useful for live
498 # streams). Note that Windows is not affected and produces playable
499 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
500 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and url not in ('-', 'pipe:'):
501 proc.communicate_or_kill(b'q')
502 else:
503 proc.kill(timeout=None)
504 raise
505 return retval
12b84ac8 506
507
508class AVconvFD(FFmpegFD):
509 pass
510
582be358 511
28787f16 512_BY_NAME = {
513 klass.get_basename(): klass
222516d9 514 for name, klass in globals().items()
1009f67c 515 if name.endswith('FD') and name not in ('ExternalFD', 'FragmentFD')
28787f16 516}
517
518_BY_EXE = {klass.EXE_NAME: klass for klass in _BY_NAME.values()}
222516d9
PH
519
520
521def list_external_downloaders():
522 return sorted(_BY_NAME.keys())
523
524
525def get_external_downloader(external_downloader):
526 """ Given the name of the executable, see whether we support the given
527 downloader . """
6c4d20cd
S
528 # Drop .exe extension on Windows
529 bn = os.path.splitext(os.path.basename(external_downloader))[0]
28787f16 530 return _BY_NAME.get(bn, _BY_EXE.get(bn))