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