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