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