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