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