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