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