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