options.py 91 KB

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