]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/external.py
[extractor/slideslive] Fix extractor (#5737)
[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
af7a5eef 255 @staticmethod
256 def _aria2c_filename(fn):
257 return fn if os.path.isabs(fn) else f'.{os.path.sep}{fn}'
258
384b6202 259 def _make_cmd(self, tmpfilename, info_dict):
2b3bf01c 260 cmd = [self.exe, '-c',
261 '--console-log-level=warn', '--summary-interval=0', '--download-result=hide',
dcd55f76 262 '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16']
2b3bf01c 263 if 'fragments' in info_dict:
264 cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true']
ff0f78e1 265 else:
266 cmd += ['--min-split-size', '1M']
2b3bf01c 267
002ea8fe 268 if info_dict.get('http_headers') is not None:
269 for key, val in info_dict['http_headers'].items():
86e5f3ed 270 cmd += ['--header', f'{key}: {val}']
691d5823 271 cmd += self._option('--max-overall-download-limit', 'ratelimit')
9f3da138 272 cmd += self._option('--interface', 'source_address')
bf812ef7 273 cmd += self._option('--all-proxy', 'proxy')
266b0ad6 274 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
71f47617 275 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
f44afb54 276 cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=')
2b3bf01c 277 cmd += self._configuration_args()
278
eb55bad5 279 # aria2c strips out spaces from the beginning/end of filenames and paths.
280 # We work around this issue by adding a "./" to the beginning of the
281 # filename and relative path, and adding a "/" at the end of the path.
282 # See: https://github.com/yt-dlp/yt-dlp/issues/276
283 # https://github.com/ytdl-org/youtube-dl/issues/20312
284 # https://github.com/aria2/aria2/issues/1373
2b3bf01c 285 dn = os.path.dirname(tmpfilename)
286 if dn:
af7a5eef 287 cmd += ['--dir', self._aria2c_filename(dn) + os.path.sep]
2b3bf01c 288 if 'fragments' not in info_dict:
af7a5eef 289 cmd += ['--out', self._aria2c_filename(os.path.basename(tmpfilename))]
5219cb3e 290 cmd += ['--auto-file-renaming=false']
2b3bf01c 291
d7009caa 292 if 'fragments' in info_dict:
fe845284 293 cmd += ['--file-allocation=none', '--uri-selector=inorder']
5219cb3e 294 url_list_file = '%s.frag.urls' % tmpfilename
295 url_list = []
fe845284 296 for frag_index, fragment in enumerate(info_dict['fragments']):
297 fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index)
af7a5eef 298 url_list.append('%s\n\tout=%s' % (fragment['url'], self._aria2c_filename(fragment_filename)))
205a0654 299 stream, _ = self.sanitize_open(url_list_file, 'wb')
0f06bcd7 300 stream.write('\n'.join(url_list).encode())
539d158c 301 stream.close()
af7a5eef 302 cmd += ['-i', self._aria2c_filename(url_list_file)]
5219cb3e 303 else:
304 cmd += ['--', info_dict['url']]
384b6202
PH
305 return cmd
306
906e2f0e
JMF
307
308class HttpieFD(ExternalFD):
52a8a1e1 309 AVAILABLE_OPT = '--version'
28787f16 310 EXE_NAME = 'http'
99cbe98c 311
906e2f0e
JMF
312 def _make_cmd(self, tmpfilename, info_dict):
313 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
002ea8fe 314
315 if info_dict.get('http_headers') is not None:
316 for key, val in info_dict['http_headers'].items():
86e5f3ed 317 cmd += [f'{key}:{val}']
906e2f0e
JMF
318 return cmd
319
12b84ac8 320
321class FFmpegFD(ExternalFD):
6251555f 322 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments')
c487cf00 323 SUPPORTED_FEATURES = (Features.TO_STDOUT, Features.MULTIPLE_FORMATS)
12b84ac8 324
99cbe98c 325 @classmethod
52a8a1e1 326 def available(cls, path=None):
327 # TODO: Fix path for ffmpeg
dbf5416a 328 # Fixme: This may be wrong when --ffmpeg-location is used
99cbe98c 329 return FFmpegPostProcessor().available
330
e36d50c5 331 def on_process_started(self, proc, stdin):
332 """ Override this in subclasses """
333 pass
334
dbf5416a 335 @classmethod
d5fe04f5 336 def can_merge_formats(cls, info_dict, params):
dbf5416a 337 return (
338 info_dict.get('requested_formats')
339 and info_dict.get('protocol')
340 and not params.get('allow_unplayable_formats')
341 and 'no-direct-merge' not in params.get('compat_opts', [])
342 and cls.can_download(info_dict))
343
12b84ac8 344 def _call_downloader(self, tmpfilename, info_dict):
18e674b4 345 urls = [f['url'] for f in info_dict.get('requested_formats', [])] or [info_dict['url']]
12b84ac8 346 ffpp = FFmpegPostProcessor(downloader=self)
77dea16a 347 if not ffpp.available:
e3b771a8 348 self.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
77dea16a 349 return False
12b84ac8 350 ffpp.check_version()
351
352 args = [ffpp.executable, '-y']
353
a609e61a
S
354 for log_level in ('quiet', 'verbose'):
355 if self.params.get(log_level, False):
356 args += ['-loglevel', log_level]
357 break
2ec1759f 358 if not self.params.get('verbose'):
359 args += ['-hide_banner']
a609e61a 360
0a5a191a 361 args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[])
bb36a55c 362
0a5a191a 363 # These exists only for compatibility. Extractors should use
364 # info_dict['downloader_options']['ffmpeg_args'] instead
1d485a1a 365 args += info_dict.get('_ffmpeg_args') or []
36fce548
RA
366 seekable = info_dict.get('_seekable')
367 if seekable is not None:
368 # setting -seekable prevents ffmpeg from guessing if the server
369 # supports seeking(by adding the header `Range: bytes=0-`), which
370 # can cause problems in some cases
067aa17e 371 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
36fce548
RA
372 # http://trac.ffmpeg.org/ticket/6125#comment:10
373 args += ['-seekable', '1' if seekable else '0']
374
00828e2c
E
375 http_headers = None
376 if info_dict.get('http_headers'):
377 youtubedl_headers = handle_youtubedl_headers(info_dict['http_headers'])
378 http_headers = [
379 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
380 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
12b84ac8 381 '-headers',
00828e2c
E
382 ''.join(f'{key}: {val}\r\n' for key, val in youtubedl_headers.items())
383 ]
12b84ac8 384
e62d9c5c
S
385 env = None
386 proxy = self.params.get('proxy')
387 if proxy:
388 if not re.match(r'^[\da-zA-Z]+://', proxy):
389 proxy = 'http://%s' % proxy
20bad91d
YCH
390
391 if proxy.startswith('socks'):
392 self.report_warning(
6c9b71bc
YCH
393 '%s does not support SOCKS proxies. Downloading is likely to fail. '
394 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
20bad91d 395
e62d9c5c
S
396 # Since December 2015 ffmpeg supports -http_proxy option (see
397 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
398 # We could switch to the following code if we are able to detect version properly
399 # args += ['-http_proxy', proxy]
400 env = os.environ.copy()
ac668111 401 env['HTTP_PROXY'] = proxy
402 env['http_proxy'] = proxy
e62d9c5c 403
4230c489 404 protocol = info_dict.get('protocol')
405
406 if protocol == 'rtmp':
407 player_url = info_dict.get('player_url')
408 page_url = info_dict.get('page_url')
409 app = info_dict.get('app')
410 play_path = info_dict.get('play_path')
411 tc_url = info_dict.get('tc_url')
412 flash_version = info_dict.get('flash_version')
413 live = info_dict.get('rtmp_live', False)
d7d86fdd 414 conn = info_dict.get('rtmp_conn')
4230c489 415 if player_url is not None:
416 args += ['-rtmp_swfverify', player_url]
417 if page_url is not None:
418 args += ['-rtmp_pageurl', page_url]
419 if app is not None:
420 args += ['-rtmp_app', app]
421 if play_path is not None:
422 args += ['-rtmp_playpath', play_path]
423 if tc_url is not None:
424 args += ['-rtmp_tcurl', tc_url]
425 if flash_version is not None:
426 args += ['-rtmp_flashver', flash_version]
427 if live:
428 args += ['-rtmp_live', 'live']
d7d86fdd
RA
429 if isinstance(conn, list):
430 for entry in conn:
431 args += ['-rtmp_conn', entry]
c487cf00 432 elif isinstance(conn, str):
d7d86fdd 433 args += ['-rtmp_conn', conn]
4230c489 434
5ec1b6b7 435 start_time, end_time = info_dict.get('section_start') or 0, info_dict.get('section_end')
436
330690a2 437 for i, url in enumerate(urls):
00828e2c
E
438 if http_headers is not None and re.match(r'^https?://', url):
439 args += http_headers
5ec1b6b7 440 if start_time:
441 args += ['-ss', str(start_time)]
442 if end_time:
443 args += ['-t', str(end_time - start_time)]
444
330690a2 445 args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', url]
6b6c16ca 446
5ec1b6b7 447 if not (start_time or end_time) or not self.params.get('force_keyframes_at_cuts'):
448 args += ['-c', 'copy']
449
6251555f 450 if info_dict.get('requested_formats') or protocol == 'http_dash_segments':
451 for (i, fmt) in enumerate(info_dict.get('requested_formats') or [info_dict]):
452 stream_number = fmt.get('manifest_stream_number', 0)
234416e4 453 args.extend(['-map', f'{i}:{stream_number}'])
6d0fe752
JH
454
455 if self.params.get('test', False):
c487cf00 456 args += ['-fs', str(self._TEST_FILE_SIZE)]
6d0fe752 457
e5611e8e 458 ext = info_dict['ext']
f5436c5d 459 if protocol in ('m3u8', 'm3u8_native'):
9bd20204 460 use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts')
461 if use_mpegts is None:
462 use_mpegts = info_dict.get('is_live')
463 if use_mpegts:
12b84ac8 464 args += ['-f', 'mpegts']
465 else:
8bdc1494 466 args += ['-f', 'mp4']
8913ef74 467 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 468 args += ['-bsf:a', 'aac_adtstoasc']
4230c489 469 elif protocol == 'rtmp':
470 args += ['-f', 'flv']
e5611e8e 471 elif ext == 'mp4' and tmpfilename == '-':
472 args += ['-f', 'mpegts']
af6793f8 473 elif ext == 'unknown_video':
474 ext = determine_ext(remove_end(tmpfilename, '.part'))
475 if ext == 'unknown_video':
476 self.report_warning(
477 'The video format is unknown and cannot be downloaded by ffmpeg. '
478 'Explicitly set the extension in the filename to attempt download in that format')
479 else:
480 self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename')
481 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
12b84ac8 482 else:
e5611e8e 483 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
12b84ac8 484
6251555f 485 args += self._configuration_args(('_o1', '_o', ''))
330690a2 486
12b84ac8 487 args = [encodeArgument(opt) for opt in args]
d868f43c 488 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
12b84ac8 489 self._debug_cmd(args)
490
f0c9fb96 491 with Popen(args, stdin=subprocess.PIPE, env=env) as proc:
492 if url in ('-', 'pipe:'):
493 self.on_process_started(proc, proc.stdin)
494 try:
495 retval = proc.wait()
496 except BaseException as e:
497 # subprocces.run would send the SIGKILL signal to ffmpeg and the
498 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
499 # produces a file that is playable (this is mostly useful for live
500 # streams). Note that Windows is not affected and produces playable
501 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
502 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and url not in ('-', 'pipe:'):
503 proc.communicate_or_kill(b'q')
504 else:
505 proc.kill(timeout=None)
506 raise
507 return retval
12b84ac8 508
509
510class AVconvFD(FFmpegFD):
511 pass
512
582be358 513
28787f16 514_BY_NAME = {
515 klass.get_basename(): klass
222516d9 516 for name, klass in globals().items()
1009f67c 517 if name.endswith('FD') and name not in ('ExternalFD', 'FragmentFD')
28787f16 518}
519
222516d9
PH
520
521def list_external_downloaders():
522 return sorted(_BY_NAME.keys())
523
524
525def get_external_downloader(external_downloader):
e1eabd7b 526 """ Given the name of the executable, see whether we support the given downloader """
6c4d20cd 527 bn = os.path.splitext(os.path.basename(external_downloader))[0]
e1eabd7b 528 return _BY_NAME.get(bn) or next((
529 klass for klass in _BY_NAME.values() if klass.EXE_NAME in bn
530 ), None)