external.py 27 KB

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