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