options.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  1. import collections
  2. import contextlib
  3. import optparse
  4. import os.path
  5. import re
  6. import shlex
  7. import string
  8. import sys
  9. from .compat import compat_expanduser, compat_get_terminal_size, compat_getenv
  10. from .cookies import SUPPORTED_BROWSERS, SUPPORTED_KEYRINGS
  11. from .downloader.external import list_external_downloaders
  12. from .postprocessor import (
  13. FFmpegExtractAudioPP,
  14. FFmpegSubtitlesConvertorPP,
  15. FFmpegThumbnailsConvertorPP,
  16. FFmpegVideoRemuxerPP,
  17. SponsorBlockPP,
  18. )
  19. from .postprocessor.modify_chapters import DEFAULT_SPONSORBLOCK_CHAPTER_TITLE
  20. from .update import detect_variant
  21. from .utils import (
  22. OUTTMPL_TYPES,
  23. POSTPROCESS_WHEN,
  24. Config,
  25. expand_path,
  26. get_executable_path,
  27. join_nonempty,
  28. remove_end,
  29. write_string,
  30. )
  31. from .version import __version__
  32. def parseOpts(overrideArguments=None, ignore_config_files='if_override'):
  33. root = Config(create_parser())
  34. if ignore_config_files == 'if_override':
  35. ignore_config_files = overrideArguments is not None
  36. def _readUserConf(package_name, default=[]):
  37. # .config
  38. xdg_config_home = compat_getenv('XDG_CONFIG_HOME') or compat_expanduser('~/.config')
  39. userConfFile = os.path.join(xdg_config_home, package_name, 'config')
  40. if not os.path.isfile(userConfFile):
  41. userConfFile = os.path.join(xdg_config_home, '%s.conf' % package_name)
  42. userConf = Config.read_file(userConfFile, default=None)
  43. if userConf is not None:
  44. return userConf, userConfFile
  45. # appdata
  46. appdata_dir = compat_getenv('appdata')
  47. if appdata_dir:
  48. userConfFile = os.path.join(appdata_dir, package_name, 'config')
  49. userConf = Config.read_file(userConfFile, default=None)
  50. if userConf is None:
  51. userConfFile += '.txt'
  52. userConf = Config.read_file(userConfFile, default=None)
  53. if userConf is not None:
  54. return userConf, userConfFile
  55. # home
  56. userConfFile = os.path.join(compat_expanduser('~'), '%s.conf' % package_name)
  57. userConf = Config.read_file(userConfFile, default=None)
  58. if userConf is None:
  59. userConfFile += '.txt'
  60. userConf = Config.read_file(userConfFile, default=None)
  61. if userConf is not None:
  62. return userConf, userConfFile
  63. return default, None
  64. def add_config(label, path, user=False):
  65. """ Adds config and returns whether to continue """
  66. if root.parse_known_args()[0].ignoreconfig:
  67. return False
  68. # Multiple package names can be given here
  69. # Eg: ('yt-dlp', 'youtube-dlc', 'youtube-dl') will look for
  70. # the configuration file of any of these three packages
  71. for package in ('yt-dlp',):
  72. if user:
  73. args, current_path = _readUserConf(package, default=None)
  74. else:
  75. current_path = os.path.join(path, '%s.conf' % package)
  76. args = Config.read_file(current_path, default=None)
  77. if args is not None:
  78. root.append_config(args, current_path, label=label)
  79. return True
  80. return True
  81. def load_configs():
  82. yield not ignore_config_files
  83. yield add_config('Portable', get_executable_path())
  84. yield add_config('Home', expand_path(root.parse_known_args()[0].paths.get('home', '')).strip())
  85. yield add_config('User', None, user=True)
  86. yield add_config('System', '/etc')
  87. opts = optparse.Values({'verbose': True, 'print_help': False})
  88. try:
  89. try:
  90. if overrideArguments:
  91. root.append_config(overrideArguments, label='Override')
  92. else:
  93. root.append_config(sys.argv[1:], label='Command-line')
  94. loaded_all_configs = all(load_configs())
  95. except ValueError as err:
  96. raise root.parser.error(err)
  97. if loaded_all_configs:
  98. # If ignoreconfig is found inside the system configuration file,
  99. # the user configuration is removed
  100. if root.parse_known_args()[0].ignoreconfig:
  101. user_conf = next((i for i, conf in enumerate(root.configs) if conf.label == 'User'), None)
  102. if user_conf is not None:
  103. root.configs.pop(user_conf)
  104. opts, args = root.parse_args()
  105. except optparse.OptParseError:
  106. with contextlib.suppress(optparse.OptParseError):
  107. opts, _ = root.parse_known_args(strict=False)
  108. raise
  109. except (SystemExit, KeyboardInterrupt):
  110. opts.verbose = False
  111. raise
  112. finally:
  113. verbose = opts.verbose and f'\n{root}'.replace('\n| ', '\n[debug] ')[1:]
  114. if verbose:
  115. write_string(f'{verbose}\n')
  116. if opts.print_help:
  117. if verbose:
  118. write_string('\n')
  119. root.parser.print_help()
  120. if opts.print_help:
  121. sys.exit()
  122. return root.parser, opts, args
  123. class _YoutubeDLHelpFormatter(optparse.IndentedHelpFormatter):
  124. def __init__(self):
  125. # No need to wrap help messages if we're on a wide console
  126. max_width = compat_get_terminal_size().columns or 80
  127. # The % is chosen to get a pretty output in README.md
  128. super().__init__(width=max_width, max_help_position=int(0.45 * max_width))
  129. @staticmethod
  130. def format_option_strings(option):
  131. """ ('-o', '--option') -> -o, --format METAVAR """
  132. opts = join_nonempty(
  133. option._short_opts and option._short_opts[0],
  134. option._long_opts and option._long_opts[0],
  135. delim=', ')
  136. if option.takes_value():
  137. opts += f' {option.metavar}'
  138. return opts
  139. class _YoutubeDLOptionParser(optparse.OptionParser):
  140. # optparse is deprecated since python 3.2. So assume a stable interface even for private methods
  141. ALIAS_TRIGGER_LIMIT = 100
  142. def __init__(self):
  143. super().__init__(
  144. prog='yt-dlp' if detect_variant() == 'source' else None,
  145. version=__version__,
  146. usage='%prog [OPTIONS] URL [URL...]',
  147. epilog='See full documentation at https://github.com/yt-dlp/yt-dlp#readme',
  148. formatter=_YoutubeDLHelpFormatter(),
  149. conflict_handler='resolve',
  150. )
  151. _UNKNOWN_OPTION = (optparse.BadOptionError, optparse.AmbiguousOptionError)
  152. _BAD_OPTION = optparse.OptionValueError
  153. def parse_known_args(self, args=None, values=None, strict=True):
  154. """Same as parse_args, but ignore unknown switches. Similar to argparse.parse_known_args"""
  155. self.rargs, self.largs = self._get_args(args), []
  156. self.values = values or self.get_default_values()
  157. while self.rargs:
  158. try:
  159. self._process_args(self.largs, self.rargs, self.values)
  160. except optparse.OptParseError as err:
  161. if isinstance(err, self._UNKNOWN_OPTION):
  162. self.largs.append(err.opt_str)
  163. elif strict:
  164. if isinstance(err, self._BAD_OPTION):
  165. self.error(str(err))
  166. raise
  167. return self.check_values(self.values, self.largs)
  168. def error(self, msg):
  169. msg = f'{self.get_prog_name()}: error: {str(msg).strip()}\n'
  170. raise optparse.OptParseError(f'{self.get_usage()}\n{msg}' if self.usage else msg)
  171. def _get_args(self, args):
  172. return sys.argv[1:] if args is None else list(args)
  173. def _match_long_opt(self, opt):
  174. """Improve ambigious argument resolution by comparing option objects instead of argument strings"""
  175. try:
  176. return super()._match_long_opt(opt)
  177. except optparse.AmbiguousOptionError as e:
  178. if len({self._long_opt[p] for p in e.possibilities}) == 1:
  179. return e.possibilities[0]
  180. raise
  181. def create_parser():
  182. def _list_from_options_callback(option, opt_str, value, parser, append=True, delim=',', process=str.strip):
  183. # append can be True, False or -1 (prepend)
  184. current = list(getattr(parser.values, option.dest)) if append else []
  185. value = list(filter(None, [process(value)] if delim is None else map(process, value.split(delim))))
  186. setattr(
  187. parser.values, option.dest,
  188. current + value if append is True else value + current)
  189. def _set_from_options_callback(
  190. option, opt_str, value, parser, delim=',', allowed_values=None, aliases={},
  191. process=lambda x: x.lower().strip()):
  192. current = set(getattr(parser.values, option.dest))
  193. values = [process(value)] if delim is None else list(map(process, value.split(delim)[::-1]))
  194. while values:
  195. actual_val = val = values.pop()
  196. if not val:
  197. raise optparse.OptionValueError(f'Invalid {option.metavar} for {opt_str}: {value}')
  198. if val == 'all':
  199. current.update(allowed_values)
  200. elif val == '-all':
  201. current = set()
  202. elif val in aliases:
  203. values.extend(aliases[val])
  204. else:
  205. if val[0] == '-':
  206. val = val[1:]
  207. current.discard(val)
  208. else:
  209. current.update([val])
  210. if allowed_values is not None and val not in allowed_values:
  211. raise optparse.OptionValueError(f'wrong {option.metavar} for {opt_str}: {actual_val}')
  212. setattr(parser.values, option.dest, current)
  213. def _dict_from_options_callback(
  214. option, opt_str, value, parser,
  215. allowed_keys=r'[\w-]+', delimiter=':', default_key=None, process=None, multiple_keys=True,
  216. process_key=str.lower, append=False):
  217. out_dict = dict(getattr(parser.values, option.dest))
  218. multiple_args = not isinstance(value, str)
  219. if multiple_keys:
  220. allowed_keys = fr'({allowed_keys})(,({allowed_keys}))*'
  221. mobj = re.match(
  222. fr'(?i)(?P<keys>{allowed_keys}){delimiter}(?P<val>.*)$',
  223. value[0] if multiple_args else value)
  224. if mobj is not None:
  225. keys, val = mobj.group('keys').split(','), mobj.group('val')
  226. if multiple_args:
  227. val = [val, *value[1:]]
  228. elif default_key is not None:
  229. keys, val = [default_key], value
  230. else:
  231. raise optparse.OptionValueError(
  232. f'wrong {opt_str} formatting; it should be {option.metavar}, not "{value}"')
  233. try:
  234. keys = map(process_key, keys) if process_key else keys
  235. val = process(val) if process else val
  236. except Exception as err:
  237. raise optparse.OptionValueError(f'wrong {opt_str} formatting; {err}')
  238. for key in keys:
  239. out_dict[key] = out_dict.get(key, []) + [val] if append else val
  240. setattr(parser.values, option.dest, out_dict)
  241. parser = _YoutubeDLOptionParser()
  242. alias_group = optparse.OptionGroup(parser, 'Aliases')
  243. Formatter = string.Formatter()
  244. def _create_alias(option, opt_str, value, parser):
  245. aliases, opts = value
  246. try:
  247. nargs = len({i if f == '' else f
  248. for i, (_, f, _, _) in enumerate(Formatter.parse(opts)) if f is not None})
  249. opts.format(*map(str, range(nargs))) # validate
  250. except Exception as err:
  251. raise optparse.OptionValueError(f'wrong {opt_str} OPTIONS formatting; {err}')
  252. if alias_group not in parser.option_groups:
  253. parser.add_option_group(alias_group)
  254. aliases = (x if x.startswith('-') else f'--{x}' for x in map(str.strip, aliases.split(',')))
  255. try:
  256. alias_group.add_option(
  257. *aliases, help=opts, nargs=nargs, type='str' if nargs else None,
  258. dest='_triggered_aliases', default=collections.defaultdict(int),
  259. metavar=' '.join(f'ARG{i}' for i in range(nargs)), action='callback',
  260. callback=_alias_callback, callback_kwargs={'opts': opts, 'nargs': nargs})
  261. except Exception as err:
  262. raise optparse.OptionValueError(f'wrong {opt_str} formatting; {err}')
  263. def _alias_callback(option, opt_str, value, parser, opts, nargs):
  264. counter = getattr(parser.values, option.dest)
  265. counter[opt_str] += 1
  266. if counter[opt_str] > parser.ALIAS_TRIGGER_LIMIT:
  267. raise optparse.OptionValueError(f'Alias {opt_str} exceeded invocation limit')
  268. if nargs == 1:
  269. value = [value]
  270. assert (nargs == 0 and value is None) or len(value) == nargs
  271. parser.rargs[:0] = shlex.split(
  272. opts if value is None else opts.format(*map(shlex.quote, value)))
  273. general = optparse.OptionGroup(parser, 'General Options')
  274. general.add_option(
  275. '-h', '--help', dest='print_help', action='store_true',
  276. help='Print this help text and exit')
  277. general.add_option(
  278. '--version',
  279. action='version',
  280. help='Print program version and exit')
  281. general.add_option(
  282. '-U', '--update',
  283. action='store_true', dest='update_self',
  284. help='Update this program to latest version')
  285. general.add_option(
  286. '--no-update',
  287. action='store_false', dest='update_self',
  288. help='Do not update (default)')
  289. general.add_option(
  290. '-i', '--ignore-errors',
  291. action='store_true', dest='ignoreerrors',
  292. help='Ignore download and postprocessing errors. The download will be considered successful even if the postprocessing fails')
  293. general.add_option(
  294. '--no-abort-on-error',
  295. action='store_const', dest='ignoreerrors', const='only_download',
  296. help='Continue with next video on download errors; e.g. to skip unavailable videos in a playlist (default)')
  297. general.add_option(
  298. '--abort-on-error', '--no-ignore-errors',
  299. action='store_false', dest='ignoreerrors',
  300. help='Abort downloading of further videos if an error occurs (Alias: --no-ignore-errors)')
  301. general.add_option(
  302. '--dump-user-agent',
  303. action='store_true', dest='dump_user_agent', default=False,
  304. help='Display the current user-agent and exit')
  305. general.add_option(
  306. '--list-extractors',
  307. action='store_true', dest='list_extractors', default=False,
  308. help='List all supported extractors and exit')
  309. general.add_option(
  310. '--extractor-descriptions',
  311. action='store_true', dest='list_extractor_descriptions', default=False,
  312. help='Output descriptions of all supported extractors and exit')
  313. general.add_option(
  314. '--force-generic-extractor',
  315. action='store_true', dest='force_generic_extractor', default=False,
  316. help='Force extraction to use the generic extractor')
  317. general.add_option(
  318. '--default-search',
  319. dest='default_search', metavar='PREFIX',
  320. help=(
  321. 'Use this prefix for unqualified URLs. '
  322. 'Eg: "gvsearch2:python" downloads two videos from google videos for the search term "python". '
  323. 'Use the value "auto" to let yt-dlp guess ("auto_warning" to emit a warning when guessing). '
  324. '"error" just throws an error. The default value "fixup_error" repairs broken URLs, '
  325. 'but emits an error if this is not possible instead of searching'))
  326. general.add_option(
  327. '--ignore-config', '--no-config',
  328. action='store_true', dest='ignoreconfig',
  329. help=(
  330. 'Don\'t load any more configuration files except those given by --config-locations. '
  331. 'For backward compatibility, if this option is found inside the system configuration file, the user configuration is not loaded. '
  332. '(Alias: --no-config)'))
  333. general.add_option(
  334. '--no-config-locations',
  335. action='store_const', dest='config_locations', const=[],
  336. help=(
  337. 'Do not load any custom configuration files (default). When given inside a '
  338. 'configuration file, ignore all previous --config-locations defined in the current file'))
  339. general.add_option(
  340. '--config-locations',
  341. dest='config_locations', metavar='PATH', action='append',
  342. help=(
  343. 'Location of the main configuration file; either the path to the config or its containing directory '
  344. '("-" for stdin). Can be used multiple times and inside other configuration files'))
  345. general.add_option(
  346. '--flat-playlist',
  347. action='store_const', dest='extract_flat', const='in_playlist', default=False,
  348. help='Do not extract the videos of a playlist, only list them')
  349. general.add_option(
  350. '--no-flat-playlist',
  351. action='store_false', dest='extract_flat',
  352. help='Extract the videos of a playlist')
  353. general.add_option(
  354. '--live-from-start',
  355. action='store_true', dest='live_from_start',
  356. help='Download livestreams from the start. Currently only supported for YouTube (Experimental)')
  357. general.add_option(
  358. '--no-live-from-start',
  359. action='store_false', dest='live_from_start',
  360. help='Download livestreams from the current time (default)')
  361. general.add_option(
  362. '--wait-for-video',
  363. dest='wait_for_video', metavar='MIN[-MAX]', default=None,
  364. help=(
  365. 'Wait for scheduled streams to become available. '
  366. 'Pass the minimum number of seconds (or range) to wait between retries'))
  367. general.add_option(
  368. '--no-wait-for-video',
  369. dest='wait_for_video', action='store_const', const=None,
  370. help='Do not wait for scheduled streams (default)')
  371. general.add_option(
  372. '--mark-watched',
  373. action='store_true', dest='mark_watched', default=False,
  374. help='Mark videos watched (even with --simulate)')
  375. general.add_option(
  376. '--no-mark-watched',
  377. action='store_false', dest='mark_watched',
  378. help='Do not mark videos watched (default)')
  379. general.add_option(
  380. '--no-colors',
  381. action='store_true', dest='no_color', default=False,
  382. help='Do not emit color codes in output')
  383. general.add_option(
  384. '--compat-options',
  385. metavar='OPTS', dest='compat_opts', default=set(), type='str',
  386. action='callback', callback=_set_from_options_callback,
  387. callback_kwargs={
  388. 'allowed_values': {
  389. 'filename', 'filename-sanitization', 'format-sort', 'abort-on-error', 'format-spec', 'no-playlist-metafiles',
  390. 'multistreams', 'no-live-chat', 'playlist-index', 'list-formats', 'no-direct-merge',
  391. 'no-youtube-channel-redirect', 'no-youtube-unavailable-videos', 'no-attach-info-json', 'embed-metadata',
  392. 'embed-thumbnail-atomicparsley', 'seperate-video-versions', 'no-clean-infojson', 'no-keep-subs', 'no-certifi',
  393. }, 'aliases': {
  394. 'youtube-dl': ['-multistreams', 'all'],
  395. 'youtube-dlc': ['-no-youtube-channel-redirect', '-no-live-chat', 'all'],
  396. }
  397. }, help=(
  398. 'Options that can help keep compatibility with youtube-dl or youtube-dlc '
  399. 'configurations by reverting some of the changes made in yt-dlp. '
  400. 'See "Differences in default behavior" for details'))
  401. general.add_option(
  402. '--alias', metavar='ALIASES OPTIONS', dest='_', type='str', nargs=2,
  403. action='callback', callback=_create_alias,
  404. help=(
  405. 'Create aliases for an option string. Unless an alias starts with a dash "-", it is prefixed with "--". '
  406. 'Arguments are parsed according to the Python string formatting mini-language. '
  407. 'Eg: --alias get-audio,-X "-S=aext:{0},abr -x --audio-format {0}" creates options '
  408. '"--get-audio" and "-X" that takes an argument (ARG0) and expands to '
  409. '"-S=aext:ARG0,abr -x --audio-format ARG0". All defined aliases are listed in the --help output. '
  410. 'Alias options can trigger more aliases; so be carefull to avoid defining recursive options. '
  411. f'As a safety measure, each alias may be triggered a maximum of {_YoutubeDLOptionParser.ALIAS_TRIGGER_LIMIT} times. '
  412. 'This option can be used multiple times'))
  413. network = optparse.OptionGroup(parser, 'Network Options')
  414. network.add_option(
  415. '--proxy', dest='proxy',
  416. default=None, metavar='URL',
  417. help=(
  418. 'Use the specified HTTP/HTTPS/SOCKS proxy. To enable SOCKS proxy, specify a proper scheme. '
  419. 'Eg: socks5://user:pass@127.0.0.1:1080/. Pass in an empty string (--proxy "") for direct connection'))
  420. network.add_option(
  421. '--socket-timeout',
  422. dest='socket_timeout', type=float, default=None, metavar='SECONDS',
  423. help='Time to wait before giving up, in seconds')
  424. network.add_option(
  425. '--source-address',
  426. metavar='IP', dest='source_address', default=None,
  427. help='Client-side IP address to bind to',
  428. )
  429. network.add_option(
  430. '-4', '--force-ipv4',
  431. action='store_const', const='0.0.0.0', dest='source_address',
  432. help='Make all connections via IPv4',
  433. )
  434. network.add_option(
  435. '-6', '--force-ipv6',
  436. action='store_const', const='::', dest='source_address',
  437. help='Make all connections via IPv6',
  438. )
  439. geo = optparse.OptionGroup(parser, 'Geo-restriction')
  440. geo.add_option(
  441. '--geo-verification-proxy',
  442. dest='geo_verification_proxy', default=None, metavar='URL',
  443. help=(
  444. 'Use this proxy to verify the IP address for some geo-restricted sites. '
  445. 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading'))
  446. geo.add_option(
  447. '--cn-verification-proxy',
  448. dest='cn_verification_proxy', default=None, metavar='URL',
  449. help=optparse.SUPPRESS_HELP)
  450. geo.add_option(
  451. '--geo-bypass',
  452. action='store_true', dest='geo_bypass', default=True,
  453. help='Bypass geographic restriction via faking X-Forwarded-For HTTP header (default)')
  454. geo.add_option(
  455. '--no-geo-bypass',
  456. action='store_false', dest='geo_bypass',
  457. help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')
  458. geo.add_option(
  459. '--geo-bypass-country', metavar='CODE',
  460. dest='geo_bypass_country', default=None,
  461. help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')
  462. geo.add_option(
  463. '--geo-bypass-ip-block', metavar='IP_BLOCK',
  464. dest='geo_bypass_ip_block', default=None,
  465. help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')
  466. selection = optparse.OptionGroup(parser, 'Video Selection')
  467. selection.add_option(
  468. '--playlist-start',
  469. dest='playliststart', metavar='NUMBER', default=1, type=int,
  470. help=optparse.SUPPRESS_HELP)
  471. selection.add_option(
  472. '--playlist-end',
  473. dest='playlistend', metavar='NUMBER', default=None, type=int,
  474. help=optparse.SUPPRESS_HELP)
  475. selection.add_option(
  476. '-I', '--playlist-items',
  477. dest='playlist_items', metavar='ITEM_SPEC', default=None,
  478. help=(
  479. 'Comma seperated playlist_index of the videos to download. '
  480. 'You can specify a range using "[START]:[STOP][:STEP]". For backward compatibility, START-STOP is also supported. '
  481. 'Use negative indices to count from the right and negative STEP to download in reverse order. '
  482. 'Eg: "-I 1:3,7,-5::2" used on a playlist of size 15 will download the videos at index 1,2,3,7,11,13,15'))
  483. selection.add_option(
  484. '--match-title',
  485. dest='matchtitle', metavar='REGEX',
  486. help=optparse.SUPPRESS_HELP)
  487. selection.add_option(
  488. '--reject-title',
  489. dest='rejecttitle', metavar='REGEX',
  490. help=optparse.SUPPRESS_HELP)
  491. selection.add_option(
  492. '--min-filesize',
  493. metavar='SIZE', dest='min_filesize', default=None,
  494. help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
  495. selection.add_option(
  496. '--max-filesize',
  497. metavar='SIZE', dest='max_filesize', default=None,
  498. help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
  499. selection.add_option(
  500. '--date',
  501. metavar='DATE', dest='date', default=None,
  502. help=(
  503. 'Download only videos uploaded on this date. The date can be "YYYYMMDD" or in the format '
  504. '[now|today|yesterday][-N[day|week|month|year]]. Eg: --date today-2weeks'))
  505. selection.add_option(
  506. '--datebefore',
  507. metavar='DATE', dest='datebefore', default=None,
  508. help=(
  509. 'Download only videos uploaded on or before this date. '
  510. 'The date formats accepted is the same as --date'))
  511. selection.add_option(
  512. '--dateafter',
  513. metavar='DATE', dest='dateafter', default=None,
  514. help=(
  515. 'Download only videos uploaded on or after this date. '
  516. 'The date formats accepted is the same as --date'))
  517. selection.add_option(
  518. '--min-views',
  519. metavar='COUNT', dest='min_views', default=None, type=int,
  520. help=optparse.SUPPRESS_HELP)
  521. selection.add_option(
  522. '--max-views',
  523. metavar='COUNT', dest='max_views', default=None, type=int,
  524. help=optparse.SUPPRESS_HELP)
  525. selection.add_option(
  526. '--match-filters',
  527. metavar='FILTER', dest='match_filter', action='append',
  528. help=(
  529. 'Generic video filter. Any "OUTPUT TEMPLATE" field can be compared with a '
  530. 'number or a string using the operators defined in "Filtering formats". '
  531. 'You can also simply specify a field to match if the field is present, '
  532. 'use "!field" to check if the field is not present, and "&" to check multiple conditions. '
  533. 'Use a "\\" to escape "&" or quotes if needed. If used multiple times, '
  534. 'the filter matches if atleast one of the conditions are met. Eg: --match-filter '
  535. '!is_live --match-filter "like_count>?100 & description~=\'(?i)\\bcats \\& dogs\\b\'" '
  536. 'matches only videos that are not live OR those that have a like count more than 100 '
  537. '(or the like field is not available) and also has a description '
  538. 'that contains the phrase "cats & dogs" (caseless). '
  539. 'Use "--match-filter -" to interactively ask whether to download each video'))
  540. selection.add_option(
  541. '--no-match-filter',
  542. metavar='FILTER', dest='match_filter', action='store_const', const=None,
  543. help='Do not use generic video filter (default)')
  544. selection.add_option(
  545. '--no-playlist',
  546. action='store_true', dest='noplaylist', default=False,
  547. help='Download only the video, if the URL refers to a video and a playlist')
  548. selection.add_option(
  549. '--yes-playlist',
  550. action='store_false', dest='noplaylist',
  551. help='Download the playlist, if the URL refers to a video and a playlist')
  552. selection.add_option(
  553. '--age-limit',
  554. metavar='YEARS', dest='age_limit', default=None, type=int,
  555. help='Download only videos suitable for the given age')
  556. selection.add_option(
  557. '--download-archive', metavar='FILE',
  558. dest='download_archive',
  559. help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it')
  560. selection.add_option(
  561. '--no-download-archive',
  562. dest='download_archive', action="store_const", const=None,
  563. help='Do not use archive file (default)')
  564. selection.add_option(
  565. '--max-downloads',
  566. dest='max_downloads', metavar='NUMBER', type=int, default=None,
  567. help='Abort after downloading NUMBER files')
  568. selection.add_option(
  569. '--break-on-existing',
  570. action='store_true', dest='break_on_existing', default=False,
  571. help='Stop the download process when encountering a file that is in the archive')
  572. selection.add_option(
  573. '--break-on-reject',
  574. action='store_true', dest='break_on_reject', default=False,
  575. help='Stop the download process when encountering a file that has been filtered out')
  576. selection.add_option(
  577. '--break-per-input',
  578. action='store_true', dest='break_per_url', default=False,
  579. help='Make --break-on-existing, --break-on-reject and --max-downloads act only on the current input URL')
  580. selection.add_option(
  581. '--no-break-per-input',
  582. action='store_false', dest='break_per_url',
  583. help='--break-on-existing and similar options terminates the entire download queue')
  584. selection.add_option(
  585. '--skip-playlist-after-errors', metavar='N',
  586. dest='skip_playlist_after_errors', default=None, type=int,
  587. help='Number of allowed failures until the rest of the playlist is skipped')
  588. selection.add_option(
  589. '--include-ads',
  590. dest='include_ads', action='store_true',
  591. help=optparse.SUPPRESS_HELP)
  592. selection.add_option(
  593. '--no-include-ads',
  594. dest='include_ads', action='store_false',
  595. help=optparse.SUPPRESS_HELP)
  596. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  597. authentication.add_option(
  598. '-u', '--username',
  599. dest='username', metavar='USERNAME',
  600. help='Login with this account ID')
  601. authentication.add_option(
  602. '-p', '--password',
  603. dest='password', metavar='PASSWORD',
  604. help='Account password. If this option is left out, yt-dlp will ask interactively')
  605. authentication.add_option(
  606. '-2', '--twofactor',
  607. dest='twofactor', metavar='TWOFACTOR',
  608. help='Two-factor authentication code')
  609. authentication.add_option(
  610. '-n', '--netrc',
  611. action='store_true', dest='usenetrc', default=False,
  612. help='Use .netrc authentication data')
  613. authentication.add_option(
  614. '--netrc-location',
  615. dest='netrc_location', metavar='PATH',
  616. help='Location of .netrc authentication data; either the path or its containing directory. Defaults to ~/.netrc')
  617. authentication.add_option(
  618. '--video-password',
  619. dest='videopassword', metavar='PASSWORD',
  620. help='Video password (vimeo, youku)')
  621. authentication.add_option(
  622. '--ap-mso',
  623. dest='ap_mso', metavar='MSO',
  624. help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
  625. authentication.add_option(
  626. '--ap-username',
  627. dest='ap_username', metavar='USERNAME',
  628. help='Multiple-system operator account login')
  629. authentication.add_option(
  630. '--ap-password',
  631. dest='ap_password', metavar='PASSWORD',
  632. help='Multiple-system operator account password. If this option is left out, yt-dlp will ask interactively')
  633. authentication.add_option(
  634. '--ap-list-mso',
  635. action='store_true', dest='ap_list_mso', default=False,
  636. help='List all supported multiple-system operators')
  637. authentication.add_option(
  638. '--client-certificate',
  639. dest='client_certificate', metavar='CERTFILE',
  640. help='Path to client certificate file in PEM format. May include the private key')
  641. authentication.add_option(
  642. '--client-certificate-key',
  643. dest='client_certificate_key', metavar='KEYFILE',
  644. help='Path to private key file for client certificate')
  645. authentication.add_option(
  646. '--client-certificate-password',
  647. dest='client_certificate_password', metavar='PASSWORD',
  648. help='Password for client certificate private key, if encrypted. '
  649. 'If not provided, and the key is encrypted, yt-dlp will ask interactively')
  650. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  651. video_format.add_option(
  652. '-f', '--format',
  653. action='store', dest='format', metavar='FORMAT', default=None,
  654. help='Video format code, see "FORMAT SELECTION" for more details')
  655. video_format.add_option(
  656. '-S', '--format-sort', metavar='SORTORDER',
  657. dest='format_sort', default=[], type='str', action='callback',
  658. callback=_list_from_options_callback, callback_kwargs={'append': -1},
  659. help='Sort the formats by the fields given, see "Sorting Formats" for more details')
  660. video_format.add_option(
  661. '--format-sort-force', '--S-force',
  662. action='store_true', dest='format_sort_force', metavar='FORMAT', default=False,
  663. help=(
  664. 'Force user specified sort order to have precedence over all fields, '
  665. 'see "Sorting Formats" for more details (Alias: --S-force)'))
  666. video_format.add_option(
  667. '--no-format-sort-force',
  668. action='store_false', dest='format_sort_force', metavar='FORMAT', default=False,
  669. help='Some fields have precedence over the user specified sort order (default)')
  670. video_format.add_option(
  671. '--video-multistreams',
  672. action='store_true', dest='allow_multiple_video_streams', default=None,
  673. help='Allow multiple video streams to be merged into a single file')
  674. video_format.add_option(
  675. '--no-video-multistreams',
  676. action='store_false', dest='allow_multiple_video_streams',
  677. help='Only one video stream is downloaded for each output file (default)')
  678. video_format.add_option(
  679. '--audio-multistreams',
  680. action='store_true', dest='allow_multiple_audio_streams', default=None,
  681. help='Allow multiple audio streams to be merged into a single file')
  682. video_format.add_option(
  683. '--no-audio-multistreams',
  684. action='store_false', dest='allow_multiple_audio_streams',
  685. help='Only one audio stream is downloaded for each output file (default)')
  686. video_format.add_option(
  687. '--all-formats',
  688. action='store_const', dest='format', const='all',
  689. help=optparse.SUPPRESS_HELP)
  690. video_format.add_option(
  691. '--prefer-free-formats',
  692. action='store_true', dest='prefer_free_formats', default=False,
  693. help=(
  694. 'Prefer video formats with free containers over non-free ones of same quality. '
  695. 'Use with "-S ext" to strictly prefer free containers irrespective of quality'))
  696. video_format.add_option(
  697. '--no-prefer-free-formats',
  698. action='store_false', dest='prefer_free_formats', default=False,
  699. help="Don't give any special preference to free containers (default)")
  700. video_format.add_option(
  701. '--check-formats',
  702. action='store_const', const='selected', dest='check_formats', default=None,
  703. help='Make sure formats are selected only from those that are actually downloadable')
  704. video_format.add_option(
  705. '--check-all-formats',
  706. action='store_true', dest='check_formats',
  707. help='Check all formats for whether they are actually downloadable')
  708. video_format.add_option(
  709. '--no-check-formats',
  710. action='store_false', dest='check_formats',
  711. help='Do not check that the formats are actually downloadable')
  712. video_format.add_option(
  713. '-F', '--list-formats',
  714. action='store_true', dest='listformats',
  715. help='List available formats of each video. Simulate unless --no-simulate is used')
  716. video_format.add_option(
  717. '--list-formats-as-table',
  718. action='store_true', dest='listformats_table', default=True,
  719. help=optparse.SUPPRESS_HELP)
  720. video_format.add_option(
  721. '--list-formats-old', '--no-list-formats-as-table',
  722. action='store_false', dest='listformats_table',
  723. help=optparse.SUPPRESS_HELP)
  724. video_format.add_option(
  725. '--merge-output-format',
  726. action='store', dest='merge_output_format', metavar='FORMAT', default=None,
  727. help=(
  728. 'If a merge is required (e.g. bestvideo+bestaudio), '
  729. 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
  730. 'Ignored if no merge is required'))
  731. video_format.add_option(
  732. '--allow-unplayable-formats',
  733. action='store_true', dest='allow_unplayable_formats', default=False,
  734. help=optparse.SUPPRESS_HELP)
  735. video_format.add_option(
  736. '--no-allow-unplayable-formats',
  737. action='store_false', dest='allow_unplayable_formats',
  738. help=optparse.SUPPRESS_HELP)
  739. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  740. subtitles.add_option(
  741. '--write-subs', '--write-srt',
  742. action='store_true', dest='writesubtitles', default=False,
  743. help='Write subtitle file')
  744. subtitles.add_option(
  745. '--no-write-subs', '--no-write-srt',
  746. action='store_false', dest='writesubtitles',
  747. help='Do not write subtitle file (default)')
  748. subtitles.add_option(
  749. '--write-auto-subs', '--write-automatic-subs',
  750. action='store_true', dest='writeautomaticsub', default=False,
  751. help='Write automatically generated subtitle file (Alias: --write-automatic-subs)')
  752. subtitles.add_option(
  753. '--no-write-auto-subs', '--no-write-automatic-subs',
  754. action='store_false', dest='writeautomaticsub', default=False,
  755. help='Do not write auto-generated subtitles (default) (Alias: --no-write-automatic-subs)')
  756. subtitles.add_option(
  757. '--all-subs',
  758. action='store_true', dest='allsubtitles', default=False,
  759. help=optparse.SUPPRESS_HELP)
  760. subtitles.add_option(
  761. '--list-subs',
  762. action='store_true', dest='listsubtitles', default=False,
  763. help='List available subtitles of each video. Simulate unless --no-simulate is used')
  764. subtitles.add_option(
  765. '--sub-format',
  766. action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
  767. help='Subtitle format; accepts formats preference, Eg: "srt" or "ass/srt/best"')
  768. subtitles.add_option(
  769. '--sub-langs', '--srt-langs',
  770. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  771. default=[], callback=_list_from_options_callback,
  772. help=(
  773. 'Languages of the subtitles to download (can be regex) or "all" separated by commas. (Eg: --sub-langs "en.*,ja") '
  774. 'You can prefix the language code with a "-" to exclude it from the requested languages. (Eg: --sub-langs all,-live_chat) '
  775. 'Use --list-subs for a list of available language tags'))
  776. downloader = optparse.OptionGroup(parser, 'Download Options')
  777. downloader.add_option(
  778. '-N', '--concurrent-fragments',
  779. dest='concurrent_fragment_downloads', metavar='N', default=1, type=int,
  780. help='Number of fragments of a dash/hlsnative video that should be downloaded concurrently (default is %default)')
  781. downloader.add_option(
  782. '-r', '--limit-rate', '--rate-limit',
  783. dest='ratelimit', metavar='RATE',
  784. help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
  785. downloader.add_option(
  786. '--throttled-rate',
  787. dest='throttledratelimit', metavar='RATE',
  788. help='Minimum download rate in bytes per second below which throttling is assumed and the video data is re-extracted (e.g. 100K)')
  789. downloader.add_option(
  790. '-R', '--retries',
  791. dest='retries', metavar='RETRIES', default=10,
  792. help='Number of retries (default is %default), or "infinite"')
  793. downloader.add_option(
  794. '--file-access-retries',
  795. dest='file_access_retries', metavar='RETRIES', default=3,
  796. help='Number of times to retry on file access error (default is %default), or "infinite"')
  797. downloader.add_option(
  798. '--fragment-retries',
  799. dest='fragment_retries', metavar='RETRIES', default=10,
  800. help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
  801. downloader.add_option(
  802. '--retry-sleep',
  803. dest='retry_sleep', metavar='[TYPE:]EXPR', default={}, type='str',
  804. action='callback', callback=_dict_from_options_callback,
  805. callback_kwargs={
  806. 'allowed_keys': 'http|fragment|file_access',
  807. 'default_key': 'http',
  808. }, help=(
  809. 'An expression for the time to sleep between retries in seconds (optionally) prefixed '
  810. 'by the type of retry (file_access, fragment, http (default)) to apply the sleep to. '
  811. 'EXPR can be a number, linear=START[:END[:STEP=1]] or exp=START[:END[:BASE=2]]. '
  812. 'This option can be used multiple times to set the sleep for the different retry types. '
  813. 'Eg: --retry-sleep linear=1::2 --retry-sleep fragment:exp=1:20'))
  814. downloader.add_option(
  815. '--skip-unavailable-fragments', '--no-abort-on-unavailable-fragment',
  816. action='store_true', dest='skip_unavailable_fragments', default=True,
  817. help='Skip unavailable fragments for DASH, hlsnative and ISM downloads (default) (Alias: --no-abort-on-unavailable-fragment)')
  818. downloader.add_option(
  819. '--abort-on-unavailable-fragment', '--no-skip-unavailable-fragments',
  820. action='store_false', dest='skip_unavailable_fragments',
  821. help='Abort download if a fragment is unavailable (Alias: --no-skip-unavailable-fragments)')
  822. downloader.add_option(
  823. '--keep-fragments',
  824. action='store_true', dest='keep_fragments', default=False,
  825. help='Keep downloaded fragments on disk after downloading is finished')
  826. downloader.add_option(
  827. '--no-keep-fragments',
  828. action='store_false', dest='keep_fragments',
  829. help='Delete downloaded fragments after downloading is finished (default)')
  830. downloader.add_option(
  831. '--buffer-size',
  832. dest='buffersize', metavar='SIZE', default='1024',
  833. help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
  834. downloader.add_option(
  835. '--resize-buffer',
  836. action='store_false', dest='noresizebuffer',
  837. help='The buffer size is automatically resized from an initial value of --buffer-size (default)')
  838. downloader.add_option(
  839. '--no-resize-buffer',
  840. action='store_true', dest='noresizebuffer', default=False,
  841. help='Do not automatically adjust the buffer size')
  842. downloader.add_option(
  843. '--http-chunk-size',
  844. dest='http_chunk_size', metavar='SIZE', default=None,
  845. help=(
  846. 'Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
  847. 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)'))
  848. downloader.add_option(
  849. '--test',
  850. action='store_true', dest='test', default=False,
  851. help=optparse.SUPPRESS_HELP)
  852. downloader.add_option(
  853. '--playlist-reverse',
  854. action='store_true', dest='playlist_reverse',
  855. help=optparse.SUPPRESS_HELP)
  856. downloader.add_option(
  857. '--no-playlist-reverse',
  858. action='store_false', dest='playlist_reverse',
  859. help=optparse.SUPPRESS_HELP)
  860. downloader.add_option(
  861. '--playlist-random',
  862. action='store_true', dest='playlist_random',
  863. help='Download playlist videos in random order')
  864. downloader.add_option(
  865. '--lazy-playlist',
  866. action='store_true', dest='lazy_playlist',
  867. help='Process entries in the playlist as they are received. This disables n_entries, --playlist-random and --playlist-reverse')
  868. downloader.add_option(
  869. '--no-lazy-playlist',
  870. action='store_false', dest='lazy_playlist',
  871. help='Process videos in the playlist only after the entire playlist is parsed (default)')
  872. downloader.add_option(
  873. '--xattr-set-filesize',
  874. dest='xattr_set_filesize', action='store_true',
  875. help='Set file xattribute ytdl.filesize with expected file size')
  876. downloader.add_option(
  877. '--hls-prefer-native',
  878. dest='hls_prefer_native', action='store_true', default=None,
  879. help=optparse.SUPPRESS_HELP)
  880. downloader.add_option(
  881. '--hls-prefer-ffmpeg',
  882. dest='hls_prefer_native', action='store_false', default=None,
  883. help=optparse.SUPPRESS_HELP)
  884. downloader.add_option(
  885. '--hls-use-mpegts',
  886. dest='hls_use_mpegts', action='store_true', default=None,
  887. help=(
  888. 'Use the mpegts container for HLS videos; '
  889. 'allowing some players to play the video while downloading, '
  890. 'and reducing the chance of file corruption if download is interrupted. '
  891. 'This is enabled by default for live streams'))
  892. downloader.add_option(
  893. '--no-hls-use-mpegts',
  894. dest='hls_use_mpegts', action='store_false',
  895. help=(
  896. 'Do not use the mpegts container for HLS videos. '
  897. 'This is default when not downloading live streams'))
  898. downloader.add_option(
  899. '--download-sections',
  900. metavar='REGEX', dest='download_ranges', action='append',
  901. help=(
  902. 'Download only chapters whose title matches the given regular expression. '
  903. 'Time ranges prefixed by a "*" can also be used in place of chapters to download the specified range. '
  904. 'Eg: --download-sections "*10:15-15:00" --download-sections "intro". '
  905. 'Needs ffmpeg. This option can be used multiple times to download multiple sections'))
  906. downloader.add_option(
  907. '--downloader', '--external-downloader',
  908. dest='external_downloader', metavar='[PROTO:]NAME', default={}, type='str',
  909. action='callback', callback=_dict_from_options_callback,
  910. callback_kwargs={
  911. 'allowed_keys': 'http|ftp|m3u8|dash|rtsp|rtmp|mms',
  912. 'default_key': 'default',
  913. 'process': str.strip
  914. }, help=(
  915. 'Name or path of the external downloader to use (optionally) prefixed by '
  916. 'the protocols (http, ftp, m3u8, dash, rstp, rtmp, mms) to use it for. '
  917. f'Currently supports native, {", ".join(list_external_downloaders())}. '
  918. 'You can use this option multiple times to set different downloaders for different protocols. '
  919. 'For example, --downloader aria2c --downloader "dash,m3u8:native" will use '
  920. 'aria2c for http/ftp downloads, and the native downloader for dash/m3u8 downloads '
  921. '(Alias: --external-downloader)'))
  922. downloader.add_option(
  923. '--downloader-args', '--external-downloader-args',
  924. metavar='NAME:ARGS', dest='external_downloader_args', default={}, type='str',
  925. action='callback', callback=_dict_from_options_callback,
  926. callback_kwargs={
  927. 'allowed_keys': r'ffmpeg_[io]\d*|%s' % '|'.join(map(re.escape, list_external_downloaders())),
  928. 'default_key': 'default',
  929. 'process': shlex.split
  930. }, help=(
  931. 'Give these arguments to the external downloader. '
  932. 'Specify the downloader name and the arguments separated by a colon ":". '
  933. 'For ffmpeg, arguments can be passed to different positions using the same syntax as --postprocessor-args. '
  934. 'You can use this option multiple times to give different arguments to different downloaders '
  935. '(Alias: --external-downloader-args)'))
  936. workarounds = optparse.OptionGroup(parser, 'Workarounds')
  937. workarounds.add_option(
  938. '--encoding',
  939. dest='encoding', metavar='ENCODING',
  940. help='Force the specified encoding (experimental)')
  941. workarounds.add_option(
  942. '--legacy-server-connect',
  943. action='store_true', dest='legacy_server_connect', default=False,
  944. help='Explicitly allow HTTPS connection to servers that do not support RFC 5746 secure renegotiation')
  945. workarounds.add_option(
  946. '--no-check-certificates',
  947. action='store_true', dest='no_check_certificate', default=False,
  948. help='Suppress HTTPS certificate validation')
  949. workarounds.add_option(
  950. '--prefer-insecure', '--prefer-unsecure',
  951. action='store_true', dest='prefer_insecure',
  952. help='Use an unencrypted connection to retrieve information about the video (Currently supported only for YouTube)')
  953. workarounds.add_option(
  954. '--user-agent',
  955. metavar='UA', dest='user_agent',
  956. help=optparse.SUPPRESS_HELP)
  957. workarounds.add_option(
  958. '--referer',
  959. metavar='URL', dest='referer', default=None,
  960. help=optparse.SUPPRESS_HELP)
  961. workarounds.add_option(
  962. '--add-header',
  963. metavar='FIELD:VALUE', dest='headers', default={}, type='str',
  964. action='callback', callback=_dict_from_options_callback,
  965. callback_kwargs={'multiple_keys': False},
  966. help='Specify a custom HTTP header and its value, separated by a colon ":". You can use this option multiple times',
  967. )
  968. workarounds.add_option(
  969. '--bidi-workaround',
  970. dest='bidi_workaround', action='store_true',
  971. help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
  972. workarounds.add_option(
  973. '--sleep-requests', metavar='SECONDS',
  974. dest='sleep_interval_requests', type=float,
  975. help='Number of seconds to sleep between requests during data extraction')
  976. workarounds.add_option(
  977. '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
  978. dest='sleep_interval', type=float,
  979. help=(
  980. 'Number of seconds to sleep before each download. '
  981. 'This is the minimum time to sleep when used along with --max-sleep-interval '
  982. '(Alias: --min-sleep-interval)'))
  983. workarounds.add_option(
  984. '--max-sleep-interval', metavar='SECONDS',
  985. dest='max_sleep_interval', type=float,
  986. help='Maximum number of seconds to sleep. Can only be used along with --min-sleep-interval')
  987. workarounds.add_option(
  988. '--sleep-subtitles', metavar='SECONDS',
  989. dest='sleep_interval_subtitles', default=0, type=int,
  990. help='Number of seconds to sleep before each subtitle download')
  991. verbosity = optparse.OptionGroup(parser, 'Verbosity and Simulation Options')
  992. verbosity.add_option(
  993. '-q', '--quiet',
  994. action='store_true', dest='quiet', default=False,
  995. help='Activate quiet mode. If used with --verbose, print the log to stderr')
  996. verbosity.add_option(
  997. '--no-warnings',
  998. dest='no_warnings', action='store_true', default=False,
  999. help='Ignore warnings')
  1000. verbosity.add_option(
  1001. '-s', '--simulate',
  1002. action='store_true', dest='simulate', default=None,
  1003. help='Do not download the video and do not write anything to disk')
  1004. verbosity.add_option(
  1005. '--no-simulate',
  1006. action='store_false', dest='simulate',
  1007. help='Download the video even if printing/listing options are used')
  1008. verbosity.add_option(
  1009. '--ignore-no-formats-error',
  1010. action='store_true', dest='ignore_no_formats_error', default=False,
  1011. help=(
  1012. 'Ignore "No video formats" error. Useful for extracting metadata '
  1013. 'even if the videos are not actually available for download (experimental)'))
  1014. verbosity.add_option(
  1015. '--no-ignore-no-formats-error',
  1016. action='store_false', dest='ignore_no_formats_error',
  1017. help='Throw error when no downloadable video formats are found (default)')
  1018. verbosity.add_option(
  1019. '--skip-download', '--no-download',
  1020. action='store_true', dest='skip_download', default=False,
  1021. help='Do not download the video but write all related files (Alias: --no-download)')
  1022. verbosity.add_option(
  1023. '-O', '--print',
  1024. metavar='[WHEN:]TEMPLATE', dest='forceprint', default={}, type='str',
  1025. action='callback', callback=_dict_from_options_callback,
  1026. callback_kwargs={
  1027. 'allowed_keys': 'video|' + '|'.join(map(re.escape, POSTPROCESS_WHEN)),
  1028. 'default_key': 'video',
  1029. 'multiple_keys': False,
  1030. 'append': True,
  1031. }, help=(
  1032. 'Field name or output template to print to screen, optionally prefixed with when to print it, separated by a ":". '
  1033. 'Supported values of "WHEN" are the same as that of --use-postprocessor, and "video" (default). '
  1034. 'Implies --quiet. Implies --simulate unless --no-simulate or later stages of WHEN are used. '
  1035. 'This option can be used multiple times'))
  1036. verbosity.add_option(
  1037. '--print-to-file',
  1038. metavar='[WHEN:]TEMPLATE FILE', dest='print_to_file', default={}, type='str', nargs=2,
  1039. action='callback', callback=_dict_from_options_callback,
  1040. callback_kwargs={
  1041. 'allowed_keys': 'video|' + '|'.join(map(re.escape, POSTPROCESS_WHEN)),
  1042. 'default_key': 'video',
  1043. 'multiple_keys': False,
  1044. 'append': True,
  1045. }, help=(
  1046. 'Append given template to the file. The values of WHEN and TEMPLATE are same as that of --print. '
  1047. 'FILE uses the same syntax as the output template. This option can be used multiple times'))
  1048. verbosity.add_option(
  1049. '-g', '--get-url',
  1050. action='store_true', dest='geturl', default=False,
  1051. help=optparse.SUPPRESS_HELP)
  1052. verbosity.add_option(
  1053. '-e', '--get-title',
  1054. action='store_true', dest='gettitle', default=False,
  1055. help=optparse.SUPPRESS_HELP)
  1056. verbosity.add_option(
  1057. '--get-id',
  1058. action='store_true', dest='getid', default=False,
  1059. help=optparse.SUPPRESS_HELP)
  1060. verbosity.add_option(
  1061. '--get-thumbnail',
  1062. action='store_true', dest='getthumbnail', default=False,
  1063. help=optparse.SUPPRESS_HELP)
  1064. verbosity.add_option(
  1065. '--get-description',
  1066. action='store_true', dest='getdescription', default=False,
  1067. help=optparse.SUPPRESS_HELP)
  1068. verbosity.add_option(
  1069. '--get-duration',
  1070. action='store_true', dest='getduration', default=False,
  1071. help=optparse.SUPPRESS_HELP)
  1072. verbosity.add_option(
  1073. '--get-filename',
  1074. action='store_true', dest='getfilename', default=False,
  1075. help=optparse.SUPPRESS_HELP)
  1076. verbosity.add_option(
  1077. '--get-format',
  1078. action='store_true', dest='getformat', default=False,
  1079. help=optparse.SUPPRESS_HELP)
  1080. verbosity.add_option(
  1081. '-j', '--dump-json',
  1082. action='store_true', dest='dumpjson', default=False,
  1083. help='Quiet, but print JSON information for each video. Simulate unless --no-simulate is used. See "OUTPUT TEMPLATE" for a description of available keys')
  1084. verbosity.add_option(
  1085. '-J', '--dump-single-json',
  1086. action='store_true', dest='dump_single_json', default=False,
  1087. help=(
  1088. 'Quiet, but print JSON information for each url or infojson passed. Simulate unless --no-simulate is used. '
  1089. 'If the URL refers to a playlist, the whole playlist information is dumped in a single line'))
  1090. verbosity.add_option(
  1091. '--print-json',
  1092. action='store_true', dest='print_json', default=False,
  1093. help=optparse.SUPPRESS_HELP)
  1094. verbosity.add_option(
  1095. '--force-write-archive', '--force-write-download-archive', '--force-download-archive',
  1096. action='store_true', dest='force_write_download_archive', default=False,
  1097. help=(
  1098. 'Force download archive entries to be written as far as no errors occur, '
  1099. 'even if -s or another simulation option is used (Alias: --force-download-archive)'))
  1100. verbosity.add_option(
  1101. '--newline',
  1102. action='store_true', dest='progress_with_newline', default=False,
  1103. help='Output progress bar as new lines')
  1104. verbosity.add_option(
  1105. '--no-progress',
  1106. action='store_true', dest='noprogress', default=None,
  1107. help='Do not print progress bar')
  1108. verbosity.add_option(
  1109. '--progress',
  1110. action='store_false', dest='noprogress',
  1111. help='Show progress bar, even if in quiet mode')
  1112. verbosity.add_option(
  1113. '--console-title',
  1114. action='store_true', dest='consoletitle', default=False,
  1115. help='Display progress in console titlebar')
  1116. verbosity.add_option(
  1117. '--progress-template',
  1118. metavar='[TYPES:]TEMPLATE', dest='progress_template', default={}, type='str',
  1119. action='callback', callback=_dict_from_options_callback,
  1120. callback_kwargs={
  1121. 'allowed_keys': '(download|postprocess)(-title)?',
  1122. 'default_key': 'download'
  1123. }, help=(
  1124. 'Template for progress outputs, optionally prefixed with one of "download:" (default), '
  1125. '"download-title:" (the console title), "postprocess:", or "postprocess-title:". '
  1126. 'The video\'s fields are accessible under the "info" key and '
  1127. 'the progress attributes are accessible under "progress" key. E.g.: '
  1128. # TODO: Document the fields inside "progress"
  1129. '--console-title --progress-template "download-title:%(info.id)s-%(progress.eta)s"'))
  1130. verbosity.add_option(
  1131. '-v', '--verbose',
  1132. action='store_true', dest='verbose', default=False,
  1133. help='Print various debugging information')
  1134. verbosity.add_option(
  1135. '--dump-pages', '--dump-intermediate-pages',
  1136. action='store_true', dest='dump_intermediate_pages', default=False,
  1137. help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
  1138. verbosity.add_option(
  1139. '--write-pages',
  1140. action='store_true', dest='write_pages', default=False,
  1141. help='Write downloaded intermediary pages to files in the current directory to debug problems')
  1142. verbosity.add_option(
  1143. '--load-pages',
  1144. action='store_true', dest='load_pages', default=False,
  1145. help=optparse.SUPPRESS_HELP)
  1146. verbosity.add_option(
  1147. '--youtube-print-sig-code',
  1148. action='store_true', dest='youtube_print_sig_code', default=False,
  1149. help=optparse.SUPPRESS_HELP)
  1150. verbosity.add_option(
  1151. '--print-traffic', '--dump-headers',
  1152. dest='debug_printtraffic', action='store_true', default=False,
  1153. help='Display sent and read HTTP traffic')
  1154. verbosity.add_option(
  1155. '-C', '--call-home',
  1156. dest='call_home', action='store_true', default=False,
  1157. # help='Contact the yt-dlp server for debugging')
  1158. help=optparse.SUPPRESS_HELP)
  1159. verbosity.add_option(
  1160. '--no-call-home',
  1161. dest='call_home', action='store_false',
  1162. # help='Do not contact the yt-dlp server for debugging (default)')
  1163. help=optparse.SUPPRESS_HELP)
  1164. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  1165. filesystem.add_option(
  1166. '-a', '--batch-file',
  1167. dest='batchfile', metavar='FILE',
  1168. help=(
  1169. 'File containing URLs to download ("-" for stdin), one URL per line. '
  1170. 'Lines starting with "#", ";" or "]" are considered as comments and ignored'))
  1171. filesystem.add_option(
  1172. '--no-batch-file',
  1173. dest='batchfile', action='store_const', const=None,
  1174. help='Do not read URLs from batch file (default)')
  1175. filesystem.add_option(
  1176. '--id', default=False,
  1177. action='store_true', dest='useid', help=optparse.SUPPRESS_HELP)
  1178. filesystem.add_option(
  1179. '-P', '--paths',
  1180. metavar='[TYPES:]PATH', dest='paths', default={}, type='str',
  1181. action='callback', callback=_dict_from_options_callback,
  1182. callback_kwargs={
  1183. 'allowed_keys': 'home|temp|%s' % '|'.join(map(re.escape, OUTTMPL_TYPES.keys())),
  1184. 'default_key': 'home'
  1185. }, help=(
  1186. 'The paths where the files should be downloaded. '
  1187. 'Specify the type of file and the path separated by a colon ":". '
  1188. 'All the same TYPES as --output are supported. '
  1189. 'Additionally, you can also provide "home" (default) and "temp" paths. '
  1190. 'All intermediary files are first downloaded to the temp path and '
  1191. 'then the final files are moved over to the home path after download is finished. '
  1192. 'This option is ignored if --output is an absolute path'))
  1193. filesystem.add_option(
  1194. '-o', '--output',
  1195. metavar='[TYPES:]TEMPLATE', dest='outtmpl', default={}, type='str',
  1196. action='callback', callback=_dict_from_options_callback,
  1197. callback_kwargs={
  1198. 'allowed_keys': '|'.join(map(re.escape, OUTTMPL_TYPES.keys())),
  1199. 'default_key': 'default'
  1200. }, help='Output filename template; see "OUTPUT TEMPLATE" for details')
  1201. filesystem.add_option(
  1202. '--output-na-placeholder',
  1203. dest='outtmpl_na_placeholder', metavar='TEXT', default='NA',
  1204. help=('Placeholder for unavailable fields in "OUTPUT TEMPLATE" (default: "%default")'))
  1205. filesystem.add_option(
  1206. '--autonumber-size',
  1207. dest='autonumber_size', metavar='NUMBER', type=int,
  1208. help=optparse.SUPPRESS_HELP)
  1209. filesystem.add_option(
  1210. '--autonumber-start',
  1211. dest='autonumber_start', metavar='NUMBER', default=1, type=int,
  1212. help=optparse.SUPPRESS_HELP)
  1213. filesystem.add_option(
  1214. '--restrict-filenames',
  1215. action='store_true', dest='restrictfilenames', default=False,
  1216. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
  1217. filesystem.add_option(
  1218. '--no-restrict-filenames',
  1219. action='store_false', dest='restrictfilenames',
  1220. help='Allow Unicode characters, "&" and spaces in filenames (default)')
  1221. filesystem.add_option(
  1222. '--windows-filenames',
  1223. action='store_true', dest='windowsfilenames', default=False,
  1224. help='Force filenames to be Windows-compatible')
  1225. filesystem.add_option(
  1226. '--no-windows-filenames',
  1227. action='store_false', dest='windowsfilenames',
  1228. help='Make filenames Windows-compatible only if using Windows (default)')
  1229. filesystem.add_option(
  1230. '--trim-filenames', '--trim-file-names', metavar='LENGTH',
  1231. dest='trim_file_name', default=0, type=int,
  1232. help='Limit the filename length (excluding extension) to the specified number of characters')
  1233. filesystem.add_option(
  1234. '-w', '--no-overwrites',
  1235. action='store_false', dest='overwrites', default=None,
  1236. help='Do not overwrite any files')
  1237. filesystem.add_option(
  1238. '--force-overwrites', '--yes-overwrites',
  1239. action='store_true', dest='overwrites',
  1240. help='Overwrite all video and metadata files. This option includes --no-continue')
  1241. filesystem.add_option(
  1242. '--no-force-overwrites',
  1243. action='store_const', dest='overwrites', const=None,
  1244. help='Do not overwrite the video, but overwrite related files (default)')
  1245. filesystem.add_option(
  1246. '-c', '--continue',
  1247. action='store_true', dest='continue_dl', default=True,
  1248. help='Resume partially downloaded files/fragments (default)')
  1249. filesystem.add_option(
  1250. '--no-continue',
  1251. action='store_false', dest='continue_dl',
  1252. help=(
  1253. 'Do not resume partially downloaded fragments. '
  1254. 'If the file is not fragmented, restart download of the entire file'))
  1255. filesystem.add_option(
  1256. '--part',
  1257. action='store_false', dest='nopart', default=False,
  1258. help='Use .part files instead of writing directly into output file (default)')
  1259. filesystem.add_option(
  1260. '--no-part',
  1261. action='store_true', dest='nopart',
  1262. help='Do not use .part files - write directly into output file')
  1263. filesystem.add_option(
  1264. '--mtime',
  1265. action='store_true', dest='updatetime', default=True,
  1266. help='Use the Last-modified header to set the file modification time (default)')
  1267. filesystem.add_option(
  1268. '--no-mtime',
  1269. action='store_false', dest='updatetime',
  1270. help='Do not use the Last-modified header to set the file modification time')
  1271. filesystem.add_option(
  1272. '--write-description',
  1273. action='store_true', dest='writedescription', default=False,
  1274. help='Write video description to a .description file')
  1275. filesystem.add_option(
  1276. '--no-write-description',
  1277. action='store_false', dest='writedescription',
  1278. help='Do not write video description (default)')
  1279. filesystem.add_option(
  1280. '--write-info-json',
  1281. action='store_true', dest='writeinfojson', default=None,
  1282. help='Write video metadata to a .info.json file (this may contain personal information)')
  1283. filesystem.add_option(
  1284. '--no-write-info-json',
  1285. action='store_false', dest='writeinfojson',
  1286. help='Do not write video metadata (default)')
  1287. filesystem.add_option(
  1288. '--write-annotations',
  1289. action='store_true', dest='writeannotations', default=False,
  1290. help=optparse.SUPPRESS_HELP)
  1291. filesystem.add_option(
  1292. '--no-write-annotations',
  1293. action='store_false', dest='writeannotations',
  1294. help=optparse.SUPPRESS_HELP)
  1295. filesystem.add_option(
  1296. '--write-playlist-metafiles',
  1297. action='store_true', dest='allow_playlist_files', default=None,
  1298. help=(
  1299. 'Write playlist metadata in addition to the video metadata '
  1300. 'when using --write-info-json, --write-description etc. (default)'))
  1301. filesystem.add_option(
  1302. '--no-write-playlist-metafiles',
  1303. action='store_false', dest='allow_playlist_files',
  1304. help='Do not write playlist metadata when using --write-info-json, --write-description etc.')
  1305. filesystem.add_option(
  1306. '--clean-info-json', '--clean-infojson',
  1307. action='store_true', dest='clean_infojson', default=None,
  1308. help=(
  1309. 'Remove some private fields such as filenames from the infojson. '
  1310. 'Note that it could still contain some personal information (default)'))
  1311. filesystem.add_option(
  1312. '--no-clean-info-json', '--no-clean-infojson',
  1313. action='store_false', dest='clean_infojson',
  1314. help='Write all fields to the infojson')
  1315. filesystem.add_option(
  1316. '--write-comments', '--get-comments',
  1317. action='store_true', dest='getcomments', default=False,
  1318. help=(
  1319. 'Retrieve video comments to be placed in the infojson. '
  1320. 'The comments are fetched even without this option if the extraction is known to be quick (Alias: --get-comments)'))
  1321. filesystem.add_option(
  1322. '--no-write-comments', '--no-get-comments',
  1323. action='store_false', dest='getcomments',
  1324. help='Do not retrieve video comments unless the extraction is known to be quick (Alias: --no-get-comments)')
  1325. filesystem.add_option(
  1326. '--load-info-json', '--load-info',
  1327. dest='load_info_filename', metavar='FILE',
  1328. help='JSON file containing the video information (created with the "--write-info-json" option)')
  1329. filesystem.add_option(
  1330. '--cookies',
  1331. dest='cookiefile', metavar='FILE',
  1332. help='Netscape formatted file to read cookies from and dump cookie jar in')
  1333. filesystem.add_option(
  1334. '--no-cookies',
  1335. action='store_const', const=None, dest='cookiefile', metavar='FILE',
  1336. help='Do not read/dump cookies from/to file (default)')
  1337. filesystem.add_option(
  1338. '--cookies-from-browser',
  1339. dest='cookiesfrombrowser', metavar='BROWSER[+KEYRING][:PROFILE]',
  1340. help=(
  1341. 'The name of the browser and (optionally) the name/path of '
  1342. 'the profile to load cookies from, separated by a ":". '
  1343. f'Currently supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}. '
  1344. 'By default, the most recently accessed profile is used. '
  1345. 'The keyring used for decrypting Chromium cookies on Linux can be '
  1346. '(optionally) specified after the browser name separated by a "+". '
  1347. f'Currently supported keyrings are: {", ".join(map(str.lower, sorted(SUPPORTED_KEYRINGS)))}'))
  1348. filesystem.add_option(
  1349. '--no-cookies-from-browser',
  1350. action='store_const', const=None, dest='cookiesfrombrowser',
  1351. help='Do not load cookies from browser (default)')
  1352. filesystem.add_option(
  1353. '--cache-dir', dest='cachedir', default=None, metavar='DIR',
  1354. help='Location in the filesystem where youtube-dl can store some downloaded information (such as client ids and signatures) permanently. By default $XDG_CACHE_HOME/yt-dlp or ~/.cache/yt-dlp')
  1355. filesystem.add_option(
  1356. '--no-cache-dir', action='store_false', dest='cachedir',
  1357. help='Disable filesystem caching')
  1358. filesystem.add_option(
  1359. '--rm-cache-dir',
  1360. action='store_true', dest='rm_cachedir',
  1361. help='Delete all filesystem cache files')
  1362. thumbnail = optparse.OptionGroup(parser, 'Thumbnail Options')
  1363. thumbnail.add_option(
  1364. '--write-thumbnail',
  1365. action='callback', dest='writethumbnail', default=False,
  1366. # Should override --no-write-thumbnail, but not --write-all-thumbnail
  1367. callback=lambda option, _, __, parser: setattr(
  1368. parser.values, option.dest, getattr(parser.values, option.dest) or True),
  1369. help='Write thumbnail image to disk')
  1370. thumbnail.add_option(
  1371. '--no-write-thumbnail',
  1372. action='store_false', dest='writethumbnail',
  1373. help='Do not write thumbnail image to disk (default)')
  1374. thumbnail.add_option(
  1375. '--write-all-thumbnails',
  1376. action='store_const', dest='writethumbnail', const='all',
  1377. help='Write all thumbnail image formats to disk')
  1378. thumbnail.add_option(
  1379. '--list-thumbnails',
  1380. action='store_true', dest='list_thumbnails', default=False,
  1381. help='List available thumbnails of each video. Simulate unless --no-simulate is used')
  1382. link = optparse.OptionGroup(parser, 'Internet Shortcut Options')
  1383. link.add_option(
  1384. '--write-link',
  1385. action='store_true', dest='writelink', default=False,
  1386. help='Write an internet shortcut file, depending on the current platform (.url, .webloc or .desktop). The URL may be cached by the OS')
  1387. link.add_option(
  1388. '--write-url-link',
  1389. action='store_true', dest='writeurllink', default=False,
  1390. help='Write a .url Windows internet shortcut. The OS caches the URL based on the file path')
  1391. link.add_option(
  1392. '--write-webloc-link',
  1393. action='store_true', dest='writewebloclink', default=False,
  1394. help='Write a .webloc macOS internet shortcut')
  1395. link.add_option(
  1396. '--write-desktop-link',
  1397. action='store_true', dest='writedesktoplink', default=False,
  1398. help='Write a .desktop Linux internet shortcut')
  1399. postproc = optparse.OptionGroup(parser, 'Post-Processing Options')
  1400. postproc.add_option(
  1401. '-x', '--extract-audio',
  1402. action='store_true', dest='extractaudio', default=False,
  1403. help='Convert video files to audio-only files (requires ffmpeg and ffprobe)')
  1404. postproc.add_option(
  1405. '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  1406. help=(
  1407. 'Format to convert the audio to when -x is used. '
  1408. f'(currently supported: best (default), {", ".join(FFmpegExtractAudioPP.SUPPORTED_EXTS)}). '
  1409. 'You can specify multiple rules using similar syntax as --remux-video'))
  1410. postproc.add_option(
  1411. '--audio-quality', metavar='QUALITY',
  1412. dest='audioquality', default='5',
  1413. help=(
  1414. 'Specify ffmpeg audio quality to use when converting the audio with -x. '
  1415. 'Insert a value between 0 (best) and 10 (worst) for VBR or a specific bitrate like 128K (default %default)'))
  1416. postproc.add_option(
  1417. '--remux-video',
  1418. metavar='FORMAT', dest='remuxvideo', default=None,
  1419. help=(
  1420. 'Remux the video into another container if necessary '
  1421. f'(currently supported: {", ".join(FFmpegVideoRemuxerPP.SUPPORTED_EXTS)}). '
  1422. 'If target container does not support the video/audio codec, remuxing will fail. You can specify multiple rules; '
  1423. 'Eg. "aac>m4a/mov>mp4/mkv" will remux aac to m4a, mov to mp4 and anything else to mkv'))
  1424. postproc.add_option(
  1425. '--recode-video',
  1426. metavar='FORMAT', dest='recodevideo', default=None,
  1427. help='Re-encode the video into another format if necessary. The syntax and supported formats are the same as --remux-video')
  1428. postproc.add_option(
  1429. '--postprocessor-args', '--ppa',
  1430. metavar='NAME:ARGS', dest='postprocessor_args', default={}, type='str',
  1431. action='callback', callback=_dict_from_options_callback,
  1432. callback_kwargs={
  1433. 'allowed_keys': r'\w+(?:\+\w+)?',
  1434. 'default_key': 'default-compat',
  1435. 'process': shlex.split,
  1436. 'multiple_keys': False
  1437. }, help=(
  1438. 'Give these arguments to the postprocessors. '
  1439. 'Specify the postprocessor/executable name and the arguments separated by a colon ":" '
  1440. 'to give the argument to the specified postprocessor/executable. Supported PP are: '
  1441. 'Merger, ModifyChapters, SplitChapters, ExtractAudio, VideoRemuxer, VideoConvertor, '
  1442. 'Metadata, EmbedSubtitle, EmbedThumbnail, SubtitlesConvertor, ThumbnailsConvertor, '
  1443. 'FixupStretched, FixupM4a, FixupM3u8, FixupTimestamp and FixupDuration. '
  1444. 'The supported executables are: AtomicParsley, FFmpeg and FFprobe. '
  1445. 'You can also specify "PP+EXE:ARGS" to give the arguments to the specified executable '
  1446. 'only when being used by the specified postprocessor. Additionally, for ffmpeg/ffprobe, '
  1447. '"_i"/"_o" can be appended to the prefix optionally followed by a number to pass the argument '
  1448. 'before the specified input/output file. Eg: --ppa "Merger+ffmpeg_i1:-v quiet". '
  1449. 'You can use this option multiple times to give different arguments to different '
  1450. 'postprocessors. (Alias: --ppa)'))
  1451. postproc.add_option(
  1452. '-k', '--keep-video',
  1453. action='store_true', dest='keepvideo', default=False,
  1454. help='Keep the intermediate video file on disk after post-processing')
  1455. postproc.add_option(
  1456. '--no-keep-video',
  1457. action='store_false', dest='keepvideo',
  1458. help='Delete the intermediate video file after post-processing (default)')
  1459. postproc.add_option(
  1460. '--post-overwrites',
  1461. action='store_false', dest='nopostoverwrites',
  1462. help='Overwrite post-processed files (default)')
  1463. postproc.add_option(
  1464. '--no-post-overwrites',
  1465. action='store_true', dest='nopostoverwrites', default=False,
  1466. help='Do not overwrite post-processed files')
  1467. postproc.add_option(
  1468. '--embed-subs',
  1469. action='store_true', dest='embedsubtitles', default=False,
  1470. help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
  1471. postproc.add_option(
  1472. '--no-embed-subs',
  1473. action='store_false', dest='embedsubtitles',
  1474. help='Do not embed subtitles (default)')
  1475. postproc.add_option(
  1476. '--embed-thumbnail',
  1477. action='store_true', dest='embedthumbnail', default=False,
  1478. help='Embed thumbnail in the video as cover art')
  1479. postproc.add_option(
  1480. '--no-embed-thumbnail',
  1481. action='store_false', dest='embedthumbnail',
  1482. help='Do not embed thumbnail (default)')
  1483. postproc.add_option(
  1484. '--embed-metadata', '--add-metadata',
  1485. action='store_true', dest='addmetadata', default=False,
  1486. help=(
  1487. 'Embed metadata to the video file. Also embeds chapters/infojson if present '
  1488. 'unless --no-embed-chapters/--no-embed-info-json are used (Alias: --add-metadata)'))
  1489. postproc.add_option(
  1490. '--no-embed-metadata', '--no-add-metadata',
  1491. action='store_false', dest='addmetadata',
  1492. help='Do not add metadata to file (default) (Alias: --no-add-metadata)')
  1493. postproc.add_option(
  1494. '--embed-chapters', '--add-chapters',
  1495. action='store_true', dest='addchapters', default=None,
  1496. help='Add chapter markers to the video file (Alias: --add-chapters)')
  1497. postproc.add_option(
  1498. '--no-embed-chapters', '--no-add-chapters',
  1499. action='store_false', dest='addchapters',
  1500. help='Do not add chapter markers (default) (Alias: --no-add-chapters)')
  1501. postproc.add_option(
  1502. '--embed-info-json',
  1503. action='store_true', dest='embed_infojson', default=None,
  1504. help='Embed the infojson as an attachment to mkv/mka video files')
  1505. postproc.add_option(
  1506. '--no-embed-info-json',
  1507. action='store_false', dest='embed_infojson',
  1508. help='Do not embed the infojson as an attachment to the video file')
  1509. postproc.add_option(
  1510. '--metadata-from-title',
  1511. metavar='FORMAT', dest='metafromtitle',
  1512. help=optparse.SUPPRESS_HELP)
  1513. postproc.add_option(
  1514. '--parse-metadata',
  1515. metavar='FROM:TO', dest='parse_metadata', action='append',
  1516. help=(
  1517. 'Parse additional metadata like title/artist from other fields; '
  1518. 'see "MODIFYING METADATA" for details'))
  1519. postproc.add_option(
  1520. '--replace-in-metadata',
  1521. dest='parse_metadata', metavar='FIELDS REGEX REPLACE', action='append', nargs=3,
  1522. help='Replace text in a metadata field using the given regex. This option can be used multiple times')
  1523. postproc.add_option(
  1524. '--xattrs', '--xattr',
  1525. action='store_true', dest='xattrs', default=False,
  1526. help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  1527. postproc.add_option(
  1528. '--concat-playlist',
  1529. metavar='POLICY', dest='concat_playlist', default='multi_video',
  1530. choices=('never', 'always', 'multi_video'),
  1531. help=(
  1532. 'Concatenate videos in a playlist. One of "never", "always", or '
  1533. '"multi_video" (default; only when the videos form a single show). '
  1534. 'All the video files must have same codecs and number of streams to be concatable. '
  1535. 'The "pl_video:" prefix can be used with "--paths" and "--output" to '
  1536. 'set the output filename for the concatenated files. See "OUTPUT TEMPLATE" for details'))
  1537. postproc.add_option(
  1538. '--fixup',
  1539. metavar='POLICY', dest='fixup', default=None,
  1540. choices=('never', 'ignore', 'warn', 'detect_or_warn', 'force'),
  1541. help=(
  1542. 'Automatically correct known faults of the file. '
  1543. 'One of never (do nothing), warn (only emit a warning), '
  1544. 'detect_or_warn (the default; fix file if we can, warn otherwise), '
  1545. 'force (try fixing even if file already exists)'))
  1546. postproc.add_option(
  1547. '--prefer-avconv', '--no-prefer-ffmpeg',
  1548. action='store_false', dest='prefer_ffmpeg',
  1549. help=optparse.SUPPRESS_HELP)
  1550. postproc.add_option(
  1551. '--prefer-ffmpeg', '--no-prefer-avconv',
  1552. action='store_true', dest='prefer_ffmpeg', default=True,
  1553. help=optparse.SUPPRESS_HELP)
  1554. postproc.add_option(
  1555. '--ffmpeg-location', '--avconv-location', metavar='PATH',
  1556. dest='ffmpeg_location',
  1557. help='Location of the ffmpeg binary; either the path to the binary or its containing directory')
  1558. postproc.add_option(
  1559. '--exec',
  1560. metavar='[WHEN:]CMD', dest='exec_cmd', default={}, type='str',
  1561. action='callback', callback=_dict_from_options_callback,
  1562. callback_kwargs={
  1563. 'allowed_keys': '|'.join(map(re.escape, POSTPROCESS_WHEN)),
  1564. 'default_key': 'after_move',
  1565. 'multiple_keys': False,
  1566. 'append': True,
  1567. }, help=(
  1568. 'Execute a command, optionally prefixed with when to execute it (after_move if unspecified), separated by a ":". '
  1569. 'Supported values of "WHEN" are the same as that of --use-postprocessor. '
  1570. 'Same syntax as the output template can be used to pass any field as arguments to the command. '
  1571. 'After download, an additional field "filepath" that contains the final path of the downloaded file '
  1572. 'is also available, and if no fields are passed, %(filepath)q is appended to the end of the command. '
  1573. 'This option can be used multiple times'))
  1574. postproc.add_option(
  1575. '--no-exec',
  1576. action='store_const', dest='exec_cmd', const={},
  1577. help='Remove any previously defined --exec')
  1578. postproc.add_option(
  1579. '--exec-before-download', metavar='CMD',
  1580. action='append', dest='exec_before_dl_cmd',
  1581. help=optparse.SUPPRESS_HELP)
  1582. postproc.add_option(
  1583. '--no-exec-before-download',
  1584. action='store_const', dest='exec_before_dl_cmd', const=None,
  1585. help=optparse.SUPPRESS_HELP)
  1586. postproc.add_option(
  1587. '--convert-subs', '--convert-sub', '--convert-subtitles',
  1588. metavar='FORMAT', dest='convertsubtitles', default=None,
  1589. help=(
  1590. 'Convert the subtitles to another format (currently supported: %s) '
  1591. '(Alias: --convert-subtitles)' % ', '.join(FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS)))
  1592. postproc.add_option(
  1593. '--convert-thumbnails',
  1594. metavar='FORMAT', dest='convertthumbnails', default=None,
  1595. help=(
  1596. 'Convert the thumbnails to another format '
  1597. f'(currently supported: {", ".join(FFmpegThumbnailsConvertorPP.SUPPORTED_EXTS)}). '
  1598. 'You can specify multiple rules using similar syntax as --remux-video'))
  1599. postproc.add_option(
  1600. '--split-chapters', '--split-tracks',
  1601. dest='split_chapters', action='store_true', default=False,
  1602. help=(
  1603. 'Split video into multiple files based on internal chapters. '
  1604. 'The "chapter:" prefix can be used with "--paths" and "--output" to '
  1605. 'set the output filename for the split files. See "OUTPUT TEMPLATE" for details'))
  1606. postproc.add_option(
  1607. '--no-split-chapters', '--no-split-tracks',
  1608. dest='split_chapters', action='store_false',
  1609. help='Do not split video based on chapters (default)')
  1610. postproc.add_option(
  1611. '--remove-chapters',
  1612. metavar='REGEX', dest='remove_chapters', action='append',
  1613. help=(
  1614. 'Remove chapters whose title matches the given regular expression. '
  1615. 'The syntax is the same as --download-sections. This option can be used multiple times'))
  1616. postproc.add_option(
  1617. '--no-remove-chapters', dest='remove_chapters', action='store_const', const=None,
  1618. help='Do not remove any chapters from the file (default)')
  1619. postproc.add_option(
  1620. '--force-keyframes-at-cuts',
  1621. action='store_true', dest='force_keyframes_at_cuts', default=False,
  1622. help=(
  1623. 'Force keyframes at cuts when downloading/splitting/removing sections. '
  1624. 'This is slow due to needing a re-encode, but the resulting video may have fewer artifacts around the cuts'))
  1625. postproc.add_option(
  1626. '--no-force-keyframes-at-cuts',
  1627. action='store_false', dest='force_keyframes_at_cuts',
  1628. help='Do not force keyframes around the chapters when cutting/splitting (default)')
  1629. _postprocessor_opts_parser = lambda key, val='': (
  1630. *(item.split('=', 1) for item in (val.split(';') if val else [])),
  1631. ('key', remove_end(key, 'PP')))
  1632. postproc.add_option(
  1633. '--use-postprocessor',
  1634. metavar='NAME[:ARGS]', dest='add_postprocessors', default=[], type='str',
  1635. action='callback', callback=_list_from_options_callback,
  1636. callback_kwargs={
  1637. 'delim': None,
  1638. 'process': lambda val: dict(_postprocessor_opts_parser(*val.split(':', 1)))
  1639. }, help=(
  1640. 'The (case sensitive) name of plugin postprocessors to be enabled, '
  1641. 'and (optionally) arguments to be passed to it, separated by a colon ":". '
  1642. 'ARGS are a semicolon ";" delimited list of NAME=VALUE. '
  1643. 'The "when" argument determines when the postprocessor is invoked. '
  1644. 'It can be one of "pre_process" (after video extraction), "after_filter" (after video passes filter), '
  1645. '"before_dl" (before each video download), "post_process" (after each video download; default), '
  1646. '"after_move" (after moving video file to it\'s final locations), '
  1647. '"after_video" (after downloading and processing all formats of a video), '
  1648. 'or "playlist" (at end of playlist). '
  1649. 'This option can be used multiple times to add different postprocessors'))
  1650. sponsorblock = optparse.OptionGroup(parser, 'SponsorBlock Options', description=(
  1651. 'Make chapter entries for, or remove various segments (sponsor, introductions, etc.) '
  1652. 'from downloaded YouTube videos using the SponsorBlock API (https://sponsor.ajay.app)'))
  1653. sponsorblock.add_option(
  1654. '--sponsorblock-mark', metavar='CATS',
  1655. dest='sponsorblock_mark', default=set(), action='callback', type='str',
  1656. callback=_set_from_options_callback, callback_kwargs={
  1657. 'allowed_values': SponsorBlockPP.CATEGORIES.keys(),
  1658. 'aliases': {'default': ['all']}
  1659. }, help=(
  1660. 'SponsorBlock categories to create chapters for, separated by commas. '
  1661. f'Available categories are {", ".join(SponsorBlockPP.CATEGORIES.keys())}, all and default (=all). '
  1662. 'You can prefix the category with a "-" to exclude it. See [1] for description of the categories. '
  1663. 'Eg: --sponsorblock-mark all,-preview [1] https://wiki.sponsor.ajay.app/w/Segment_Categories'))
  1664. sponsorblock.add_option(
  1665. '--sponsorblock-remove', metavar='CATS',
  1666. dest='sponsorblock_remove', default=set(), action='callback', type='str',
  1667. callback=_set_from_options_callback, callback_kwargs={
  1668. 'allowed_values': set(SponsorBlockPP.CATEGORIES.keys()) - set(SponsorBlockPP.POI_CATEGORIES.keys()),
  1669. # Note: From https://wiki.sponsor.ajay.app/w/Types:
  1670. # The filler category is very aggressive.
  1671. # It is strongly recommended to not use this in a client by default.
  1672. 'aliases': {'default': ['all', '-filler']}
  1673. }, help=(
  1674. 'SponsorBlock categories to be removed from the video file, separated by commas. '
  1675. 'If a category is present in both mark and remove, remove takes precedence. '
  1676. 'The syntax and available categories are the same as for --sponsorblock-mark '
  1677. 'except that "default" refers to "all,-filler" '
  1678. f'and {", ".join(SponsorBlockPP.POI_CATEGORIES.keys())} is not available'))
  1679. sponsorblock.add_option(
  1680. '--sponsorblock-chapter-title', metavar='TEMPLATE',
  1681. default=DEFAULT_SPONSORBLOCK_CHAPTER_TITLE, dest='sponsorblock_chapter_title',
  1682. help=(
  1683. 'An output template for the title of the SponsorBlock chapters created by --sponsorblock-mark. '
  1684. 'The only available fields are start_time, end_time, category, categories, name, category_names. '
  1685. 'Defaults to "%default"'))
  1686. sponsorblock.add_option(
  1687. '--no-sponsorblock', default=False,
  1688. action='store_true', dest='no_sponsorblock',
  1689. help='Disable both --sponsorblock-mark and --sponsorblock-remove')
  1690. sponsorblock.add_option(
  1691. '--sponsorblock-api', metavar='URL',
  1692. default='https://sponsor.ajay.app', dest='sponsorblock_api',
  1693. help='SponsorBlock API location, defaults to %default')
  1694. sponsorblock.add_option(
  1695. '--sponskrub',
  1696. action='store_true', dest='sponskrub', default=False,
  1697. help=optparse.SUPPRESS_HELP)
  1698. sponsorblock.add_option(
  1699. '--no-sponskrub',
  1700. action='store_false', dest='sponskrub',
  1701. help=optparse.SUPPRESS_HELP)
  1702. sponsorblock.add_option(
  1703. '--sponskrub-cut', default=False,
  1704. action='store_true', dest='sponskrub_cut',
  1705. help=optparse.SUPPRESS_HELP)
  1706. sponsorblock.add_option(
  1707. '--no-sponskrub-cut',
  1708. action='store_false', dest='sponskrub_cut',
  1709. help=optparse.SUPPRESS_HELP)
  1710. sponsorblock.add_option(
  1711. '--sponskrub-force', default=False,
  1712. action='store_true', dest='sponskrub_force',
  1713. help=optparse.SUPPRESS_HELP)
  1714. sponsorblock.add_option(
  1715. '--no-sponskrub-force',
  1716. action='store_true', dest='sponskrub_force',
  1717. help=optparse.SUPPRESS_HELP)
  1718. sponsorblock.add_option(
  1719. '--sponskrub-location', metavar='PATH',
  1720. dest='sponskrub_path', default='',
  1721. help=optparse.SUPPRESS_HELP)
  1722. sponsorblock.add_option(
  1723. '--sponskrub-args', dest='sponskrub_args', metavar='ARGS',
  1724. help=optparse.SUPPRESS_HELP)
  1725. extractor = optparse.OptionGroup(parser, 'Extractor Options')
  1726. extractor.add_option(
  1727. '--extractor-retries',
  1728. dest='extractor_retries', metavar='RETRIES', default=3,
  1729. help='Number of retries for known extractor errors (default is %default), or "infinite"')
  1730. extractor.add_option(
  1731. '--allow-dynamic-mpd', '--no-ignore-dynamic-mpd',
  1732. action='store_true', dest='dynamic_mpd', default=True,
  1733. help='Process dynamic DASH manifests (default) (Alias: --no-ignore-dynamic-mpd)')
  1734. extractor.add_option(
  1735. '--ignore-dynamic-mpd', '--no-allow-dynamic-mpd',
  1736. action='store_false', dest='dynamic_mpd',
  1737. help='Do not process dynamic DASH manifests (Alias: --no-allow-dynamic-mpd)')
  1738. extractor.add_option(
  1739. '--hls-split-discontinuity',
  1740. dest='hls_split_discontinuity', action='store_true', default=False,
  1741. help='Split HLS playlists to different formats at discontinuities such as ad breaks'
  1742. )
  1743. extractor.add_option(
  1744. '--no-hls-split-discontinuity',
  1745. dest='hls_split_discontinuity', action='store_false',
  1746. help='Do not split HLS playlists to different formats at discontinuities such as ad breaks (default)')
  1747. _extractor_arg_parser = lambda key, vals='': (key.strip().lower().replace('-', '_'), [
  1748. val.replace(r'\,', ',').strip() for val in re.split(r'(?<!\\),', vals)])
  1749. extractor.add_option(
  1750. '--extractor-args',
  1751. metavar='KEY:ARGS', dest='extractor_args', default={}, type='str',
  1752. action='callback', callback=_dict_from_options_callback,
  1753. callback_kwargs={
  1754. 'multiple_keys': False,
  1755. 'process': lambda val: dict(
  1756. _extractor_arg_parser(*arg.split('=', 1)) for arg in val.split(';'))
  1757. }, help=(
  1758. 'Pass these arguments to the extractor. See "EXTRACTOR ARGUMENTS" for details. '
  1759. 'You can use this option multiple times to give arguments for different extractors'))
  1760. extractor.add_option(
  1761. '--youtube-include-dash-manifest', '--no-youtube-skip-dash-manifest',
  1762. action='store_true', dest='youtube_include_dash_manifest', default=True,
  1763. help=optparse.SUPPRESS_HELP)
  1764. extractor.add_option(
  1765. '--youtube-skip-dash-manifest', '--no-youtube-include-dash-manifest',
  1766. action='store_false', dest='youtube_include_dash_manifest',
  1767. help=optparse.SUPPRESS_HELP)
  1768. extractor.add_option(
  1769. '--youtube-include-hls-manifest', '--no-youtube-skip-hls-manifest',
  1770. action='store_true', dest='youtube_include_hls_manifest', default=True,
  1771. help=optparse.SUPPRESS_HELP)
  1772. extractor.add_option(
  1773. '--youtube-skip-hls-manifest', '--no-youtube-include-hls-manifest',
  1774. action='store_false', dest='youtube_include_hls_manifest',
  1775. help=optparse.SUPPRESS_HELP)
  1776. parser.add_option_group(general)
  1777. parser.add_option_group(network)
  1778. parser.add_option_group(geo)
  1779. parser.add_option_group(selection)
  1780. parser.add_option_group(downloader)
  1781. parser.add_option_group(filesystem)
  1782. parser.add_option_group(thumbnail)
  1783. parser.add_option_group(link)
  1784. parser.add_option_group(verbosity)
  1785. parser.add_option_group(workarounds)
  1786. parser.add_option_group(video_format)
  1787. parser.add_option_group(subtitles)
  1788. parser.add_option_group(authentication)
  1789. parser.add_option_group(postproc)
  1790. parser.add_option_group(sponsorblock)
  1791. parser.add_option_group(extractor)
  1792. return parser
  1793. def _hide_login_info(opts):
  1794. write_string(
  1795. 'DeprecationWarning: "yt_dlp.options._hide_login_info" is deprecated and may be removed in a future version. '
  1796. 'Use "yt_dlp.utils.Config.hide_login_info" instead\n')
  1797. return Config.hide_login_info(opts)