Skip to content
Snippets Groups Projects
options.py 88.6 KiB
Newer Older
pukkandan's avatar
pukkandan committed
import os.path
pukkandan's avatar
pukkandan committed
from .compat import compat_expanduser, compat_get_terminal_size, compat_getenv
from .cookies import SUPPORTED_BROWSERS, SUPPORTED_KEYRINGS
from .downloader.external import list_external_downloaders
pukkandan's avatar
pukkandan committed
from .postprocessor import (
    FFmpegExtractAudioPP,
    FFmpegSubtitlesConvertorPP,
    FFmpegThumbnailsConvertorPP,
    FFmpegVideoRemuxerPP,
from .postprocessor.modify_chapters import DEFAULT_SPONSORBLOCK_CHAPTER_TITLE
pukkandan's avatar
pukkandan committed
from .utils import (
    OUTTMPL_TYPES,
    POSTPROCESS_WHEN,
    Config,
    expand_path,
    get_executable_path,
    join_nonempty,
pukkandan's avatar
pukkandan committed
    remove_end,
    write_string,
)
from .version import __version__
def parseOpts(overrideArguments=None, ignore_config_files='if_override'):
    parser = create_parser()
    root = Config(parser)
    if ignore_config_files == 'if_override':
        ignore_config_files = overrideArguments is not None
    if overrideArguments:
        root.append_config(overrideArguments, label='Override')
    else:
        root.append_config(sys.argv[1:], label='Command-line')
    def _readUserConf(package_name, default=[]):
        # .config
        xdg_config_home = compat_getenv('XDG_CONFIG_HOME') or compat_expanduser('~/.config')
        userConfFile = os.path.join(xdg_config_home, package_name, 'config')
        if not os.path.isfile(userConfFile):
            userConfFile = os.path.join(xdg_config_home, '%s.conf' % package_name)
        userConf = Config.read_file(userConfFile, default=None)
        if userConf is not None:
        # appdata
        appdata_dir = compat_getenv('appdata')
        if appdata_dir:
            userConfFile = os.path.join(appdata_dir, package_name, 'config')
            userConf = Config.read_file(userConfFile, default=None)
            if userConf is None:
                userConf = Config.read_file(userConfFile, default=None)
        if userConf is not None:
        # home
        userConfFile = os.path.join(compat_expanduser('~'), '%s.conf' % package_name)
        userConf = Config.read_file(userConfFile, default=None)
        if userConf is None:
            userConf = Config.read_file(userConfFile, default=None)
        if userConf is not None:
    def add_config(label, path, user=False):
        """ Adds config and returns whether to continue """
        if root.parse_args()[0].ignoreconfig:
            return False
        # Multiple package names can be given here
        # Eg: ('yt-dlp', 'youtube-dlc', 'youtube-dl') will look for
        # the configuration file of any of these three packages
        for package in ('yt-dlp', 'ytdl-patched'):
            if user:
                args, current_path = _readUserConf(package, default=None)
            else:
                current_path = os.path.join(path, '%s.conf' % package)
                args = Config.read_file(current_path, default=None)
            if args is not None:
                root.append_config(args, current_path, label=label)
                return True
        return True

    def load_configs():
        yield not ignore_config_files
        yield add_config('Portable', get_executable_path())
        yield add_config('Home', expand_path(root.parse_args()[0].paths.get('home', '')).strip())
        yield add_config('User', None, user=True)
        yield add_config('System', '/etc')

    if all(load_configs()):
        # If ignoreconfig is found inside the system configuration file,
        # the user configuration is removed
        if root.parse_args()[0].ignoreconfig:
            user_conf = next((i for i, conf in enumerate(root.configs) if conf.label == 'User'), None)
            if user_conf is not None:
                root.configs.pop(user_conf)

    opts, args = root.parse_args()
    if opts.verbose:
        write_string(f'\n{root}'.replace('\n| ', '\n[debug] ')[1:] + '\n')
    return parser, opts, args


class _YoutubeDLHelpFormatter(optparse.IndentedHelpFormatter):
    def __init__(self):
        # No need to wrap help messages if we're on a wide console
        max_width = compat_get_terminal_size().columns or 80
        # 47% is chosen because that is how README.md is currently formatted
        # and moving help text even further to the right is undesirable.
        # This can be reduced in the future to get a prettier output
        super().__init__(width=max_width, max_help_position=int(0.47 * max_width))

    @staticmethod
    def format_option_strings(option):
        """ ('-o', '--option') -> -o, --format METAVAR """
        opts = join_nonempty(
            option._short_opts and option._short_opts[0],
            option._long_opts and option._long_opts[0],
            delim=', ')
        if option.takes_value():
            opts += f' {option.metavar}'
        return opts


class _YoutubeDLOptionParser(optparse.OptionParser):
    # optparse is deprecated since python 3.2. So assume a stable interface even for private methods

    def __init__(self):
        super().__init__(
            prog='yt-dlp',
            version=__version__,
            usage='%prog [OPTIONS] URL [URL...]',
            epilog='See full documentation at  https://github.com/yt-dlp/yt-dlp#readme',
            formatter=_YoutubeDLHelpFormatter(),
            conflict_handler='resolve',
        )

    def _get_args(self, args):
        return sys.argv[1:] if args is None else list(args)

    def _match_long_opt(self, opt):
        """Improve ambigious argument resolution by comparing option objects instead of argument strings"""
        try:
            return super()._match_long_opt(opt)
        except optparse.AmbiguousOptionError as e:
pukkandan's avatar
pukkandan committed
            if len({self._long_opt[p] for p in e.possibilities}) == 1:
                return e.possibilities[0]
            raise


    return _YoutubeDLOptionParser()
    def _list_from_options_callback(option, opt_str, value, parser, append=True, delim=',', process=str.strip):
pukkandan's avatar
pukkandan committed
        # append can be True, False or -1 (prepend)
pukkandan's avatar
pukkandan committed
        current = list(getattr(parser.values, option.dest)) if append else []
        value = list(filter(None, [process(value)] if delim is None else map(process, value.split(delim))))
        setattr(
            parser.values, option.dest,
pukkandan's avatar
pukkandan committed
            current + value if append is True else value + current)
    def _set_from_options_callback(
            option, opt_str, value, parser, delim=',', allowed_values=None, aliases={},
            process=lambda x: x.lower().strip()):
pukkandan's avatar
pukkandan committed
        current = set(getattr(parser.values, option.dest))
        values = [process(value)] if delim is None else list(map(process, value.split(delim)[::-1]))
        while values:
            actual_val = val = values.pop()
pukkandan's avatar
pukkandan committed
            if not val:
                raise optparse.OptionValueError(f'Invalid {option.metavar} for {opt_str}: {value}')
            if val == 'all':
                current.update(allowed_values)
            elif val == '-all':
                current = set()
            elif val in aliases:
                values.extend(aliases[val])
            else:
                if val[0] == '-':
                    val = val[1:]
                    current.discard(val)
                else:
                    current.update([val])
                if allowed_values is not None and val not in allowed_values:
                    raise optparse.OptionValueError(f'wrong {option.metavar} for {opt_str}: {actual_val}')

        setattr(parser.values, option.dest, current)

pukkandan's avatar
pukkandan committed
    def _dict_from_options_callback(
            option, opt_str, value, parser,
            allowed_keys=r'[\w-]+', delimiter=':', default_key=None, process=None, multiple_keys=True,
            process_key=str.lower, append=False):
        out_dict = dict(getattr(parser.values, option.dest))
pukkandan's avatar
pukkandan committed
        multiple_args = not isinstance(value, str)
        if multiple_keys:
pukkandan's avatar
pukkandan committed
            allowed_keys = fr'({allowed_keys})(,({allowed_keys}))*'
pukkandan's avatar
pukkandan committed
        mobj = re.match(
pukkandan's avatar
pukkandan committed
            fr'(?i)(?P<keys>{allowed_keys}){delimiter}(?P<val>.*)$',
pukkandan's avatar
pukkandan committed
            value[0] if multiple_args else value)
            keys, val = mobj.group('keys').split(','), mobj.group('val')
pukkandan's avatar
pukkandan committed
            if multiple_args:
                val = [val, *value[1:]]
        elif default_key is not None:
            keys, val = [default_key], value
        else:
            raise optparse.OptionValueError(
pukkandan's avatar
pukkandan committed
                f'wrong {opt_str} formatting; it should be {option.metavar}, not "{value}"')
            keys = map(process_key, keys) if process_key else keys
            val = process(val) if process else val
        except Exception as err:
            raise optparse.OptionValueError(f'wrong {opt_str} formatting; {err}')
        for key in keys:
            out_dict[key] = out_dict.get(key, []) + [val] if append else val
        setattr(parser.values, option.dest, out_dict)
    parser = _YoutubeDLOptionParser()
    general = optparse.OptionGroup(parser, 'General Options')
    general.add_option(
        '-h', '--help',
        action='help',
testbonn's avatar
testbonn committed
        help='Print this help text and exit')
        '-V', '--version',
testbonn's avatar
testbonn committed
        help='Print program version and exit')
    general.add_option(
        '-U', '--update',
        action='store_true', dest='update_self',
        help='Update this program to latest version')
        '-i', '--ignore-errors',
        action='store_true', dest='ignoreerrors',
        help='Ignore download and postprocessing errors. The download will be considered successful even if the postprocessing fails')
    general.add_option(
        '--no-abort-on-error',
        action='store_const', dest='ignoreerrors', const='only_download',
        help='Continue with next video on download errors; e.g. to skip unavailable videos in a playlist (default)')
        '--abort-on-error', '--no-ignore-errors',
        action='store_false', dest='ignoreerrors',
pukkandan's avatar
pukkandan committed
        help='Abort downloading of further videos if an error occurs (Alias: --no-ignore-errors)')
    general.add_option(
        '--dump-user-agent',
        action='store_true', dest='dump_user_agent', default=False,
        help='Display the current user-agent and exit')
        '--list-extractors',
        action='store_true', dest='list_extractors', default=False,
        help='List all supported extractors and exit')
    general.add_option(
        '--extractor-descriptions',
        action='store_true', dest='list_extractor_descriptions', default=False,
        help='Output descriptions of all supported extractors and exit')
    general.add_option(
        '--force-generic-extractor',
        action='store_true', dest='force_generic_extractor', default=False,
        help='Force extraction to use the generic extractor')
    general.add_option(
        '--default-search',
        dest='default_search', metavar='PREFIX',
pukkandan's avatar
pukkandan committed
        help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for the search term "large apple". Use the value "auto" to let yt-dlp guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching')
        '--ignore-config', '--no-config',
        action='store_true', dest='ignoreconfig',
pukkandan's avatar
pukkandan committed
            'Don\'t load any more configuration files except those given by --config-locations. '
pukkandan's avatar
pukkandan committed
            'For backward compatibility, if this option is found inside the system configuration file, the user configuration is not loaded. '
pukkandan's avatar
pukkandan committed
            '(Alias: --no-config)'))
    general.add_option(
        '--no-config-locations',
        action='store_const', dest='config_locations', const=[],
        help=(
            'Do not load any custom configuration files (default). When given inside a '
            'configuration file, ignore all previous --config-locations defined in the current file'))
    general.add_option(
        '--config-locations',
        dest='config_locations', metavar='PATH', action='append',
        help=(
            'Location of the main configuration file; either the path to the config or its containing directory. '
            'Can be used multiple times and inside other configuration files'))
    general.add_option(
        '--flat-playlist',
        action='store_const', dest='extract_flat', const='in_playlist', default=False,
pukkandan's avatar
pukkandan committed
        help='Do not extract the videos of a playlist, only list them')
    general.add_option(
        '--no-flat-playlist',
        action='store_false', dest='extract_flat',
        help='Extract the videos of a playlist')
    general.add_option(
        '--live-from-start',
        action='store_true', dest='live_from_start',
pukkandan's avatar
pukkandan committed
        help='Download livestreams from the start. Currently only supported for YouTube (Experimental)')
    general.add_option(
        '--no-live-from-start',
        action='store_false', dest='live_from_start',
        help='Download livestreams from the current time (default)')
    general.add_option(
        '--wait-for-video',
        dest='wait_for_video', metavar='MIN[-MAX]', default=None,
        help=(
            'Wait for scheduled streams to become available. '
            'Pass the minimum number of seconds (or range) to wait between retries'))
    general.add_option(
        '--no-wait-for-video',
        dest='wait_for_video', action='store_const', const=None,
        help='Do not wait for scheduled streams (default)')
    general.add_option(
        '--mark-watched',
        action='store_true', dest='mark_watched', default=False,
        help='Mark videos watched (even with --simulate)')
    general.add_option(
        '--no-mark-watched',
pukkandan's avatar
pukkandan committed
        action='store_false', dest='mark_watched',
        help='Do not mark videos watched (default)')
    general.add_option(
pukkandan's avatar
pukkandan committed
        '--no-colors',
pukkandan's avatar
pukkandan committed
        action='store_true', dest='no_color', default=False,
testbonn's avatar
testbonn committed
        help='Do not emit color codes in output')
    general.add_option(
        '--compat-options',
        metavar='OPTS', dest='compat_opts', default=set(), type='str',
        action='callback', callback=_set_from_options_callback,
        callback_kwargs={
            'allowed_values': {
                'filename', 'filename-sanitization', 'format-sort', 'abort-on-error', 'format-spec', 'no-playlist-metafiles',
                'multistreams', 'no-live-chat', 'playlist-index', 'list-formats', 'no-direct-merge',
                'no-youtube-channel-redirect', 'no-youtube-unavailable-videos', 'no-attach-info-json', 'embed-metadata',
                'embed-thumbnail-atomicparsley', 'seperate-video-versions', 'no-clean-infojson', 'no-keep-subs', 'no-certifi',
            }, 'aliases': {
                'youtube-dl': ['-multistreams', 'all'],
                'youtube-dlc': ['-no-youtube-channel-redirect', '-no-live-chat', 'all'],
            }
        }, help=(
            'Options that can help keep compatibility with youtube-dl or youtube-dlc '
            'configurations by reverting some of the changes made in yt-dlp. '
            'See "Differences in default behavior" for details'))
    general.add_option(
        '--check-mastodon-instance',
        action='store_true', dest='check_mastodon_instance',
        default=False,
        help='Always perform online checks for Mastodon-like URL')
    general.add_option(
        '--check-peertube-instance',
        action='store_true', dest='check_peertube_instance',
        default=False,
        help='Always perform online checks for PeerTube-like URL')
    general.add_option(
        '--check-misskey-instance',
        action='store_true', dest='check_misskey_instance',
        default=False,
        help='Always perform online checks for Misskey-like URL')
    general.add_option(
        '--test-filename',
        metavar='CMD', dest='test_filename',
        help='Like --exec option, but used for testing if downloading should be started. '
             'You can begin with "re:" to use regex instead of commands')
    general.add_option(
        '--print-infojson-types',
        action='store_true', dest='printjsontypes',
        default=False,
        help=optparse.SUPPRESS_HELP)
    # help='DO NOT USE. IT\'S MEANINGLESS FOR MOST PEOPLE. Prints types of object in info json. '
    #      'Use this for extractors that --print-json won\' work.')
    general.add_option(
        '--enable-lock',
        action='store_true', dest='lock_exclusive',
        default=False,
        help='Locks downloading exclusively. Blocks other ytdl-patched process downloading the same video.')
    general.add_option(
        '--no-lock',
        action='store_false', dest='lock_exclusive',
        default=False,
        help='Do not lock downloading exclusively. '
             'Download will start even if other process is working on it.')
    general.add_option(
        '--ffmpeg-native-progress', '--use-ffmpeg-native-progress', '--enable-ffmpeg-native-progress',
        action='store_true', dest='enable_ffmpeg_native_progress',
        default=False,
        help=('Show FFmpeg download and some postprocessing progress with built-in progress. '
              'This is an experimental feature, and disabled on live streams. (see yt-dlp/yt-dlp#1947)'))
    general.add_option(
        '--no-ffmpeg-native-progress', '--disable-ffmpeg-native-progress',
        action='store_false', dest='enable_ffmpeg_native_progress',
        default=False,
        help='Show direct output from FFmpeg for download')
    network = optparse.OptionGroup(parser, 'Network Options')
    network.add_option(
        '--proxy', dest='proxy',
        default=None, metavar='URL',
        help=(
            'Use the specified HTTP/HTTPS/SOCKS proxy. To enable '
            'SOCKS proxy, specify a proper scheme. For example '
            'socks5://user:pass@127.0.0.1:1080/. Pass in an empty string (--proxy "") '
            'for direct connection'))
    network.add_option(
        '--socket-timeout',
        dest='socket_timeout', type=float, default=None, metavar='SECONDS',
        help='Time to wait before giving up, in seconds')
    network.add_option(
        '--source-address',
        metavar='IP', dest='source_address', default=None,
        help='Client-side IP address to bind to',
    network.add_option(
        '-4', '--force-ipv4',
        action='store_const', const='0.0.0.0', dest='source_address',
        help='Make all connections via IPv4',
    )
    network.add_option(
        '-6', '--force-ipv6',
        action='store_const', const='::', dest='source_address',
        help='Make all connections via IPv6',
pukkandan's avatar
pukkandan committed
    geo = optparse.OptionGroup(parser, 'Geo-restriction')
        '--geo-verification-proxy',
        dest='geo_verification_proxy', default=None, metavar='URL',
        help=(
            'Use this proxy to verify the IP address for some geo-restricted sites. '
pukkandan's avatar
pukkandan committed
            'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading'))
        '--cn-verification-proxy',
        dest='cn_verification_proxy', default=None, metavar='URL',
        help=optparse.SUPPRESS_HELP)
    geo.add_option(
        '--geo-bypass',
        action='store_true', dest='geo_bypass', default=True,
pukkandan's avatar
pukkandan committed
        help='Bypass geographic restriction via faking X-Forwarded-For HTTP header (default)')
pukkandan's avatar
pukkandan committed
        action='store_false', dest='geo_bypass',
        help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')
    geo.add_option(
        '--geo-bypass-country', metavar='CODE',
        dest='geo_bypass_country', default=None,
        help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')
    geo.add_option(
        '--geo-bypass-ip-block', metavar='IP_BLOCK',
        dest='geo_bypass_ip_block', default=None,
        help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')
    selection = optparse.OptionGroup(parser, 'Video Selection')
    selection.add_option(
        '--playlist-start',
        dest='playliststart', metavar='NUMBER', default=1, type=int,
testbonn's avatar
testbonn committed
        help='Playlist video to start at (default is %default)')
    selection.add_option(
        '--playlist-end',
        dest='playlistend', metavar='NUMBER', default=None, type=int,
testbonn's avatar
testbonn committed
        help='Playlist video to end at (default is last)')
        '--playlist-items', '--playlist-index',
        dest='playlist_items', metavar='ITEM_SPEC', default=None,
pukkandan's avatar
pukkandan committed
        help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13')
    selection.add_option(
        '--match-title',
        dest='matchtitle', metavar='REGEX',
        help=optparse.SUPPRESS_HELP)
    selection.add_option(
        '--reject-title',
        dest='rejecttitle', metavar='REGEX',
        help=optparse.SUPPRESS_HELP)
    selection.add_option(
        '--min-filesize',
        metavar='SIZE', dest='min_filesize', default=None,
        help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
    selection.add_option(
        '--max-filesize',
        metavar='SIZE', dest='max_filesize', default=None,
        help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
    selection.add_option(
        '--date',
        metavar='DATE', dest='date', default=None,
pukkandan's avatar
pukkandan committed
        help=(
            'Download only videos uploaded on this date. '
pukkandan's avatar
pukkandan committed
            'The date can be "YYYYMMDD" or in the format '
pukkandan's avatar
pukkandan committed
            '"(now|today)[+-][0-9](day|week|month|year)(s)?"'))
    selection.add_option(
        '--datebefore',
        metavar='DATE', dest='datebefore', default=None,
pukkandan's avatar
pukkandan committed
        help=(
            'Download only videos uploaded on or before this date. '
            'The date formats accepted is the same as --date'))
    selection.add_option(
        '--dateafter',
        metavar='DATE', dest='dateafter', default=None,
pukkandan's avatar
pukkandan committed
        help=(
            'Download only videos uploaded on or after this date. '
            'The date formats accepted is the same as --date'))
    selection.add_option(
        '--min-views',
        metavar='COUNT', dest='min_views', default=None, type=int,
        help=optparse.SUPPRESS_HELP)
    selection.add_option(
        '--max-views',
        metavar='COUNT', dest='max_views', default=None, type=int,
        help=optparse.SUPPRESS_HELP)
        '--match-filters',
        metavar='FILTER', dest='match_filter', action='append',
            'Generic video filter. Any field (see "OUTPUT TEMPLATE") can be compared with a '
            'number or a string using the operators defined in "Filtering formats". '
            'You can also simply specify a field to match if the field is present, '
            'use "!field" to check if the field is not present, and "&" to check multiple conditions. '
            'Use a "\\" to escape "&" or quotes if needed. If used multiple times, '
            'the filter matches if atleast one of the conditions are met. Eg: --match-filter '
            '!is_live --match-filter "like_count>?100 & description~=\'(?i)\\bcats \\& dogs\\b\'" '
            'matches only videos that are not live OR those that have a like count more than 100 '
            '(or the like field is not available) and also has a description '
            'that contains the phrase "cats & dogs" (ignoring case). '
            'Use "--match-filter -" to interactively ask whether to download each video'))
    selection.add_option(
        '--no-match-filter',
        metavar='FILTER', dest='match_filter', action='store_const', const=None,
        help='Do not use generic video filter (default)')
    selection.add_option(
        '--no-playlist',
        action='store_true', dest='noplaylist', default=False,
pukkandan's avatar
pukkandan committed
        help='Download only the video, if the URL refers to a video and a playlist')
pukkandan's avatar
pukkandan committed
        action='store_false', dest='noplaylist',
pukkandan's avatar
pukkandan committed
        help='Download the playlist, if the URL refers to a video and a playlist')
    selection.add_option(
        '--age-limit',
        metavar='YEARS', dest='age_limit', default=None, type=int,
testbonn's avatar
testbonn committed
        help='Download only videos suitable for the given age')
    selection.add_option(
        '--download-archive', metavar='FILE',
        dest='download_archive',
pukkandan's avatar
pukkandan committed
        help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it')
pukkandan's avatar
pukkandan committed
    selection.add_option(
        '--no-download-archive',
        dest='download_archive', action="store_const", const=None,
        help='Do not use archive file (default)')
    selection.add_option(
        '--max-downloads',
        dest='max_downloads', metavar='NUMBER', type=int, default=None,
        help='Abort after downloading NUMBER files')
    selection.add_option(
        '--break-on-existing',
        action='store_true', dest='break_on_existing', default=False,
pukkandan's avatar
pukkandan committed
        help='Stop the download process when encountering a file that is in the archive')
    selection.add_option(
        '--break-on-reject',
        action='store_true', dest='break_on_reject', default=False,
pukkandan's avatar
pukkandan committed
        help='Stop the download process when encountering a file that has been filtered out')
    selection.add_option(
        '--break-per-input',
        action='store_true', dest='break_per_url', default=False,
        help='Make --break-on-existing and --break-on-reject act only on the current input URL')
    selection.add_option(
        '--no-break-per-input',
        action='store_false', dest='break_per_url',
        help='--break-on-existing and --break-on-reject terminates the entire download queue')
    selection.add_option(
        '--skip-playlist-after-errors', metavar='N',
        dest='skip_playlist_after_errors', default=None, type=int,
        help='Number of allowed failures until the rest of the playlist is skipped')
    selection.add_option(
        '--include-ads',
        dest='include_ads', action='store_true',
pukkandan's avatar
pukkandan committed
        help=optparse.SUPPRESS_HELP)
    selection.add_option(
        '--no-include-ads',
        dest='include_ads', action='store_false',
pukkandan's avatar
pukkandan committed
        help=optparse.SUPPRESS_HELP)
    authentication = optparse.OptionGroup(parser, 'Authentication Options')
    authentication.add_option(
        '-u', '--username',
        dest='username', metavar='USERNAME',
testbonn's avatar
testbonn committed
        help='Login with this account ID')
    authentication.add_option(
        '-p', '--password',
        dest='password', metavar='PASSWORD',
        help='Account password. If this option is left out, yt-dlp will ask interactively')
    authentication.add_option(
        '-2', '--twofactor',
        dest='twofactor', metavar='TWOFACTOR',
        help='Two-factor authentication code')
    authentication.add_option(
        '-n', '--netrc',
        action='store_true', dest='usenetrc', default=False,
testbonn's avatar
testbonn committed
        help='Use .netrc authentication data')
    authentication.add_option(
        '--netrc-location',
        dest='netrc_location', metavar='PATH',
        help='Location of .netrc authentication data; either the path or its containing directory. Defaults to ~/.netrc')
    authentication.add_option(
        '--video-password',
        dest='videopassword', metavar='PASSWORD',
pukkandan's avatar
pukkandan committed
        help='Video password (vimeo, youku)')
pukkandan's avatar
pukkandan committed
    authentication.add_option(
        '--ap-mso',
        dest='ap_mso', metavar='MSO',
        help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
pukkandan's avatar
pukkandan committed
    authentication.add_option(
        dest='ap_username', metavar='USERNAME',
        help='Multiple-system operator account login')
pukkandan's avatar
pukkandan committed
    authentication.add_option(
        dest='ap_password', metavar='PASSWORD',
        help='Multiple-system operator account password. If this option is left out, yt-dlp will ask interactively')
pukkandan's avatar
pukkandan committed
    authentication.add_option(
        '--ap-list-mso',
        action='store_true', dest='ap_list_mso', default=False,
        help='List all supported multiple-system operators')
    authentication.add_option(
        '--client-certificate',
        dest='client_certificate', metavar='CERTFILE',
        help='Path to client certificate file in PEM format. May include the private key')
    authentication.add_option(
        '--client-certificate-key',
        dest='client_certificate_key', metavar='KEYFILE',
        help='Path to private key file for client certificate')
    authentication.add_option(
        '--client-certificate-password',
        dest='client_certificate_password', metavar='PASSWORD',
        help='Password for client certificate private key, if encrypted. '
             'If not provided and the key is encrypted, yt-dlp will ask interactively')

    video_format = optparse.OptionGroup(parser, 'Video Format Options')
    video_format.add_option(
        '-f', '--format',
        action='store', dest='format', metavar='FORMAT', default=None,
        help='Video format code, see "FORMAT SELECTION" for more details')
    video_format.add_option(
pukkandan's avatar
pukkandan committed
        '-S', '--format-sort', metavar='SORTORDER',
pukkandan's avatar
pukkandan committed
        dest='format_sort', default=[], type='str', action='callback',
        callback=_list_from_options_callback, callback_kwargs={'append': -1},
        help='Sort the formats by the fields given, see "Sorting Formats" for more details')
    video_format.add_option(
        '--format-sort-force', '--S-force',
        action='store_true', dest='format_sort_force', metavar='FORMAT', default=False,
        help=(
            'Force user specified sort order to have precedence over all fields, '
            'see "Sorting Formats" for more details'))
    video_format.add_option(
        '--no-format-sort-force',
        action='store_false', dest='format_sort_force', metavar='FORMAT', default=False,
        help=(
            'Some fields have precedence over the user specified sort order (default), '
            'see "Sorting Formats" for more details'))
pukkandan's avatar
pukkandan committed
    video_format.add_option(
        '--video-multistreams',
        action='store_true', dest='allow_multiple_video_streams', default=None,
pukkandan's avatar
pukkandan committed
        help='Allow multiple video streams to be merged into a single file')
pukkandan's avatar
pukkandan committed
    video_format.add_option(
        '--no-video-multistreams',
        action='store_false', dest='allow_multiple_video_streams',
pukkandan's avatar
pukkandan committed
        help='Only one video stream is downloaded for each output file (default)')
pukkandan's avatar
pukkandan committed
    video_format.add_option(
        '--audio-multistreams',
        action='store_true', dest='allow_multiple_audio_streams', default=None,
pukkandan's avatar
pukkandan committed
        help='Allow multiple audio streams to be merged into a single file')
pukkandan's avatar
pukkandan committed
    video_format.add_option(
        '--no-audio-multistreams',
        action='store_false', dest='allow_multiple_audio_streams',
pukkandan's avatar
pukkandan committed
        help='Only one audio stream is downloaded for each output file (default)')
    video_format.add_option(
        '--all-formats',
        action='store_const', dest='format', const='all',
pukkandan's avatar
pukkandan committed
        help=optparse.SUPPRESS_HELP)
    video_format.add_option(
        '--prefer-free-formats',
        action='store_true', dest='prefer_free_formats', default=False,
        help=(
            'Prefer video formats with free containers over non-free ones of same quality. '
            'Use with "-S ext" to strictly prefer free containers irrespective of quality'))
    video_format.add_option(
        '--no-prefer-free-formats',
        action='store_false', dest='prefer_free_formats', default=False,
        help="Don't give any special preference to free containers (default)")
        action='store_const', const='selected', dest='check_formats', default=None,
        help='Make sure formats are selected only from those that are actually downloadable')
    video_format.add_option(
        '--check-all-formats',
        action='store_true', dest='check_formats',
        help='Check all formats for whether they are actually downloadable')
    video_format.add_option(
        '--no-check-formats',
        action='store_false', dest='check_formats',
        help='Do not check that the formats are actually downloadable')
    video_format.add_option(
        '-F', '--list-formats',
        action='store_true', dest='listformats',
        help='List available formats of each video. Simulate unless --no-simulate is used')
    video_format.add_option(
        '--list-formats-as-table',
pukkandan's avatar
pukkandan committed
        action='store_true', dest='listformats_table', default=True,
        help=optparse.SUPPRESS_HELP)
    video_format.add_option(
        '--list-formats-old', '--no-list-formats-as-table',
        action='store_false', dest='listformats_table',
        help=optparse.SUPPRESS_HELP)
        '--merge-output-format',
        action='store', dest='merge_output_format', metavar='FORMAT', default=None,
            'If a merge is required (e.g. bestvideo+bestaudio), '
            'output to given container format. One of mkv, mp4, ogg, webm, flv. '
    video_format.add_option(
        '--allow-unplayable-formats',
        action='store_true', dest='allow_unplayable_formats', default=False,
        help=optparse.SUPPRESS_HELP)
    video_format.add_option(
        '--no-allow-unplayable-formats',
        action='store_false', dest='allow_unplayable_formats',
        help=optparse.SUPPRESS_HELP)
    video_format.add_option(
        '--live-download-mkv',
        action='store_true', dest='live_download_mkv', default=False,
        help=(
            'Changes video file format to MKV when downloading a live. '
            'This is useful if the computer might shutdown while downloading.'))

    subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
    subtitles.add_option(
        '--write-subs', '--write-srt',
        action='store_true', dest='writesubtitles', default=False,
testbonn's avatar
testbonn committed
        help='Write subtitle file')
        '--no-write-subs', '--no-write-srt',
        action='store_false', dest='writesubtitles',
        help='Do not write subtitle file (default)')
    subtitles.add_option(
        '--write-auto-subs', '--write-automatic-subs',
        action='store_true', dest='writeautomaticsub', default=False,
        help='Write automatically generated subtitle file (Alias: --write-automatic-subs)')
    subtitles.add_option(
        '--no-write-auto-subs', '--no-write-automatic-subs',
        action='store_false', dest='writeautomaticsub', default=False,
        help='Do not write auto-generated subtitles (default) (Alias: --no-write-automatic-subs)')
    subtitles.add_option(
        '--all-subs',
        action='store_true', dest='allsubtitles', default=False,
        help=optparse.SUPPRESS_HELP)
        '--list-subs', '--list-subtitles',
        action='store_true', dest='listsubtitles', default=False,
        help='List available subtitles of each video. Simulate unless --no-simulate is used')
    subtitles.add_option(
        '--sub-format',
        action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
        help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
        '--sub-langs', '--srt-langs',
        action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
pukkandan's avatar
pukkandan committed
        default=[], callback=_list_from_options_callback,
        help=(
pukkandan's avatar
pukkandan committed
            'Languages of the subtitles to download (can be regex) or "all" separated by commas. (Eg: --sub-langs "en.*,ja") '
            'You can prefix the language code with a "-" to exempt it from the requested languages. (Eg: --sub-langs all,-live_chat) '
            'Use --list-subs for a list of available language tags'))

    downloader = optparse.OptionGroup(parser, 'Download Options')
    downloader.add_option(
        '-N', '--concurrent-fragments',
        dest='concurrent_fragment_downloads', metavar='N', default=1, type=int,
pukkandan's avatar
pukkandan committed
        help='Number of fragments of a dash/hlsnative video that should be downloaded concurrently (default is %default)')
        '-r', '--limit-rate', '--rate-limit',
        dest='ratelimit', metavar='RATE',
testbonn's avatar
testbonn committed
        help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
    downloader.add_option(
        '--throttled-rate',
        dest='throttledratelimit', metavar='RATE',
        help='Minimum download rate in bytes per second below which throttling is assumed and the video data is re-extracted (e.g. 100K)')
    downloader.add_option(
        '-R', '--retries',
        dest='retries', metavar='RETRIES', default=10,
pukkandan's avatar
pukkandan committed
        help='Number of retries (default is %default), or "infinite"')
    downloader.add_option(
        '--file-access-retries',
        dest='file_access_retries', metavar='RETRIES', default=3,
        help='Number of times to retry on file access error (default is %default), or "infinite"')
    downloader.add_option(
        '--fragment-retries',
        dest='fragment_retries', metavar='RETRIES', default=10,
        help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
    downloader.add_option(
pukkandan's avatar
pukkandan committed
        '--skip-unavailable-fragments', '--no-abort-on-unavailable-fragment',
        action='store_true', dest='skip_unavailable_fragments', default=True,
pukkandan's avatar
pukkandan committed
        help='Skip unavailable fragments for DASH, hlsnative and ISM (default) (Alias: --no-abort-on-unavailable-fragment)')
        '--abort-on-unavailable-fragment', '--no-skip-unavailable-fragments',
        action='store_false', dest='skip_unavailable_fragments',
pukkandan's avatar
pukkandan committed
        help='Abort downloading if a fragment is unavailable (Alias: --no-skip-unavailable-fragments)')
Sergey M․'s avatar
Sergey M․ committed
    downloader.add_option(
        '--keep-fragments',
        action='store_true', dest='keep_fragments', default=False,
        help='Keep downloaded fragments on disk after downloading is finished')
    downloader.add_option(
        '--no-keep-fragments',
        action='store_false', dest='keep_fragments',
        help='Delete downloaded fragments after downloading is finished (default)')
    downloader.add_option(
        '--buffer-size',
        dest='buffersize', metavar='SIZE', default='1024',
testbonn's avatar
testbonn committed
        help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
    downloader.add_option(
        '--resize-buffer',
        action='store_false', dest='noresizebuffer',
        help='The buffer size is automatically resized from an initial value of --buffer-size (default)')
    downloader.add_option(
        '--no-resize-buffer',
        action='store_true', dest='noresizebuffer', default=False,
        help='Do not automatically adjust the buffer size')
    downloader.add_option(
        '--http-chunk-size',
        dest='http_chunk_size', metavar='SIZE', default=None,
        help=(
            'Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
            'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)'))
    downloader.add_option(
        '--test',
        action='store_true', dest='test', default=False,
        help=optparse.SUPPRESS_HELP)
    downloader.add_option(
        '--playlist-reverse',
        action='store_true',
        help='Download playlist videos in reverse order')
    downloader.add_option(
        '--no-playlist-reverse',
pukkandan's avatar
pukkandan committed
        action='store_false', dest='playlist_reverse',
        help='Download playlist videos in default order (default)')
    downloader.add_option(
        '--playlist-random',
        action='store_true',
        help='Download playlist videos in random order')
    downloader.add_option(
        '--xattr-set-filesize',
        dest='xattr_set_filesize', action='store_true',
        help='Set file xattribute ytdl.filesize with expected file size')
Sergey M․'s avatar
Sergey M․ committed
        dest='hls_prefer_native', action='store_true', default=None,
        help=optparse.SUPPRESS_HELP)
Sergey M․'s avatar
Sergey M․ committed
    downloader.add_option(
        '--hls-prefer-ffmpeg',
        dest='hls_prefer_native', action='store_false', default=None,
        help=optparse.SUPPRESS_HELP)
    downloader.add_option(
        '--hls-use-mpegts',
        dest='hls_use_mpegts', action='store_true', default=None,
            'Use the mpegts container for HLS videos; '
            'allowing some players to play the video while downloading, '
            'and reducing the chance of file corruption if download is interrupted. '
            'This is enabled by default for live streams'))
    downloader.add_option(
        '--no-hls-use-mpegts',
        dest='hls_use_mpegts', action='store_false',
        help=(
            'Do not use the mpegts container for HLS videos. '
            'This is default when not downloading live streams'))
        '--downloader', '--external-downloader',
        dest='external_downloader', metavar='[PROTO:]NAME', default={}, type='str',
pukkandan's avatar
pukkandan committed
        action='callback', callback=_dict_from_options_callback,
        callback_kwargs={
            'allowed_keys': 'http|ftp|m3u8|dash|rtsp|rtmp|mms',
            'default_key': 'default',
pukkandan's avatar
pukkandan committed
            'process': str.strip
        }, help=(
            'Name or path of the external downloader to use (optionally) prefixed by '
            'the protocols (http, ftp, m3u8, dash, rstp, rtmp, mms) to use it for. '
pukkandan's avatar
pukkandan committed
            f'Currently supports native, {", ".join(list_external_downloaders())}. '
            'You can use this option multiple times to set different downloaders for different protocols. '
            'For example, --downloader aria2c --downloader "dash,m3u8:native" will use '
            'aria2c for http/ftp downloads, and the native downloader for dash/m3u8 downloads '
pukkandan's avatar
pukkandan committed
            '(Alias: --external-downloader)'))
        '--downloader-args', '--external-downloader-args',
        metavar='NAME:ARGS', dest='external_downloader_args', default={}, type='str',
pukkandan's avatar
pukkandan committed
        action='callback', callback=_dict_from_options_callback,
pukkandan's avatar
pukkandan committed
            'allowed_keys': r'ffmpeg_[io]\d*|%s' % '|'.join(map(re.escape, list_external_downloaders())),
            'default_key': 'default',
            'process': shlex.split
pukkandan's avatar
pukkandan committed
        }, help=(
            'Give these arguments to the external downloader. '
            'Specify the downloader name and the arguments separated by a colon ":". '
            'For ffmpeg, arguments can be passed to different positions using the same syntax as --postprocessor-args. '
            'You can use this option multiple times to give different arguments to different downloaders '
            '(Alias: --external-downloader-args)'))

    workarounds = optparse.OptionGroup(parser, 'Workarounds')
    workarounds.add_option(
        '--encoding',
        dest='encoding', metavar='ENCODING',
        help='Force the specified encoding (experimental)')
    workarounds.add_option(
        '--legacy-server-connect',
        action='store_true', dest='legacy_server_connect', default=False,
        help='Explicitly allow HTTPS connection to servers that do not support RFC 5746 secure renegotiation')
    workarounds.add_option(
        '--no-check-certificates',
        action='store_true', dest='no_check_certificate', default=False,
testbonn's avatar
testbonn committed
        help='Suppress HTTPS certificate validation')
    workarounds.add_option(
        '--prefer-insecure', '--prefer-unsecure',
        action='store_true', dest='prefer_insecure',
        help='Use an unencrypted connection to retrieve information about the video (Currently supported only for YouTube)')
    workarounds.add_option(
        '--user-agent',
        metavar='UA', dest='user_agent',
        help=optparse.SUPPRESS_HELP)
    workarounds.add_option(
        '--referer',
        metavar='URL', dest='referer', default=None,
        help=optparse.SUPPRESS_HELP)
    workarounds.add_option(
        '--add-header', '--header', '-H',
        metavar='FIELD:VALUE', dest='headers', default={}, type='str',
pukkandan's avatar
pukkandan committed
        action='callback', callback=_dict_from_options_callback,
        callback_kwargs={'multiple_keys': False},
        help='Specify a custom HTTP header and its value, separated by a colon ":". You can use this option multiple times',
    )
    workarounds.add_option(
        '--bidi-workaround',
        dest='bidi_workaround', action='store_true',
        help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
    workarounds.add_option(
        '--sleep-requests', metavar='SECONDS',
        dest='sleep_interval_requests', type=float,
        help='Number of seconds to sleep between requests during data extraction')
        '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
        dest='sleep_interval', type=float,
            'Number of seconds to sleep before each download. '
            'This is the minimum time to sleep when used along with --max-sleep-interval '
            '(Alias: --min-sleep-interval)'))
    workarounds.add_option(
        '--max-sleep-interval', metavar='SECONDS',
        dest='max_sleep_interval', type=float,
        help='Maximum number of seconds to sleep. Can only be used along with --min-sleep-interval')
    workarounds.add_option(
pukkandan's avatar
pukkandan committed
        '--sleep-subtitles', metavar='SECONDS',
Unknown's avatar
Unknown committed
        dest='sleep_interval_subtitles', default=0, type=int,
        help='Number of seconds to sleep before each subtitle download')
    workarounds.add_option(
        '--sleep-before-extract', '--min-sleep-before-extract', metavar='SECONDS',
        dest='sleep_before_extract', type=float,
        help=(
            'Number of seconds to sleep before each extraction when used alone '
            'or a lower bound of a range for randomized sleep before each extraction '
            '(minimum possible number of seconds to sleep) when used along with '
            '--max-sleep-before-extract.'))
    workarounds.add_option(
        '--max-sleep-before-extract', metavar='SECONDS',
        dest='max_sleep_before_extract', type=float,
        help=(
            'Upper bound of a range for randomized sleep before each extraction '
            '(maximum possible number of seconds to sleep). Must only be used '
            'along with --min-sleep-before-extract.'))
    workarounds.add_option(
        '--escape-long-names',
        action='store_true', dest='escape_long_names', default=False,
        help=(
            'Split filename longer than 255 bytes into few path segments. '
            'This may create dumb directories.'))
    workarounds.add_option(
        '--use-modern-tls-ciphers', '--enable-modern-tls-ciphers',
        action='store_true', dest='use_modern_tls_cipher', default=False,
        help=(
            'Report servers that client is only capable of modern cipher suites for TLS. '
            'See https://github.com/yt-dlp/yt-dlp/pull/1049 for details.'))
    workarounds.add_option(
        '--no-use-modern-tls-ciphers', '--disable-modern-tls-ciphers',
        action='store_false', dest='use_modern_tls_cipher', default=False,
        help=(
            'Report servers that client is capable of Python\'s default cipher suites for TLS.'))
    verbosity = optparse.OptionGroup(parser, 'Verbosity and Simulation Options')
    verbosity.add_option(
        '-q', '--quiet',
        action='store_true', dest='quiet', default=False,