Merge pull request #8898 from dstftw/fragment-retries
[youtube-dl] / youtube_dl / options.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import optparse
5 import sys
6
7 from .downloader.external import list_external_downloaders
8 from .compat import (
9     compat_expanduser,
10     compat_get_terminal_size,
11     compat_getenv,
12     compat_kwargs,
13     compat_shlex_split,
14 )
15 from .utils import (
16     preferredencoding,
17     write_string,
18 )
19 from .version import __version__
20
21
22 def parseOpts(overrideArguments=None):
23     def _readOptions(filename_bytes, default=[]):
24         try:
25             optionf = open(filename_bytes)
26         except IOError:
27             return default  # silently skip if file is not present
28         try:
29             res = []
30             for l in optionf:
31                 res += compat_shlex_split(l, comments=True)
32         finally:
33             optionf.close()
34         return res
35
36     def _readUserConf():
37         xdg_config_home = compat_getenv('XDG_CONFIG_HOME')
38         if xdg_config_home:
39             userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
40             if not os.path.isfile(userConfFile):
41                 userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
42         else:
43             userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config')
44             if not os.path.isfile(userConfFile):
45                 userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf')
46         userConf = _readOptions(userConfFile, None)
47
48         if userConf is None:
49             appdata_dir = compat_getenv('appdata')
50             if appdata_dir:
51                 userConf = _readOptions(
52                     os.path.join(appdata_dir, 'youtube-dl', 'config'),
53                     default=None)
54                 if userConf is None:
55                     userConf = _readOptions(
56                         os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
57                         default=None)
58
59         if userConf is None:
60             userConf = _readOptions(
61                 os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),
62                 default=None)
63         if userConf is None:
64             userConf = _readOptions(
65                 os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),
66                 default=None)
67
68         if userConf is None:
69             userConf = []
70
71         return userConf
72
73     def _format_option_string(option):
74         ''' ('-o', '--option') -> -o, --format METAVAR'''
75
76         opts = []
77
78         if option._short_opts:
79             opts.append(option._short_opts[0])
80         if option._long_opts:
81             opts.append(option._long_opts[0])
82         if len(opts) > 1:
83             opts.insert(1, ', ')
84
85         if option.takes_value():
86             opts.append(' %s' % option.metavar)
87
88         return ''.join(opts)
89
90     def _comma_separated_values_options_callback(option, opt_str, value, parser):
91         setattr(parser.values, option.dest, value.split(','))
92
93     def _hide_login_info(opts):
94         opts = list(opts)
95         for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
96             try:
97                 i = opts.index(private_opt)
98                 opts[i + 1] = 'PRIVATE'
99             except ValueError:
100                 pass
101         return opts
102
103     # No need to wrap help messages if we're on a wide console
104     columns = compat_get_terminal_size().columns
105     max_width = columns if columns else 80
106     max_help_position = 80
107
108     fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
109     fmt.format_option_strings = _format_option_string
110
111     kw = {
112         'version': __version__,
113         'formatter': fmt,
114         'usage': '%prog [OPTIONS] URL [URL...]',
115         'conflict_handler': 'resolve',
116     }
117
118     parser = optparse.OptionParser(**compat_kwargs(kw))
119
120     general = optparse.OptionGroup(parser, 'General Options')
121     general.add_option(
122         '-h', '--help',
123         action='help',
124         help='Print this help text and exit')
125     general.add_option(
126         '-v', '--version',
127         action='version',
128         help='Print program version and exit')
129     general.add_option(
130         '-U', '--update',
131         action='store_true', dest='update_self',
132         help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
133     general.add_option(
134         '-i', '--ignore-errors',
135         action='store_true', dest='ignoreerrors', default=False,
136         help='Continue on download errors, for example to skip unavailable videos in a playlist')
137     general.add_option(
138         '--abort-on-error',
139         action='store_false', dest='ignoreerrors',
140         help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
141     general.add_option(
142         '--dump-user-agent',
143         action='store_true', dest='dump_user_agent', default=False,
144         help='Display the current browser identification')
145     general.add_option(
146         '--list-extractors',
147         action='store_true', dest='list_extractors', default=False,
148         help='List all supported extractors')
149     general.add_option(
150         '--extractor-descriptions',
151         action='store_true', dest='list_extractor_descriptions', default=False,
152         help='Output descriptions of all supported extractors')
153     general.add_option(
154         '--force-generic-extractor',
155         action='store_true', dest='force_generic_extractor', default=False,
156         help='Force extraction to use the generic extractor')
157     general.add_option(
158         '--default-search',
159         dest='default_search', metavar='PREFIX',
160         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.')
161     general.add_option(
162         '--ignore-config',
163         action='store_true',
164         help='Do not read configuration files. '
165         'When given in the global configuration file /etc/youtube-dl.conf: '
166         'Do not read the user configuration in ~/.config/youtube-dl/config '
167         '(%APPDATA%/youtube-dl/config.txt on Windows)')
168     general.add_option(
169         '--flat-playlist',
170         action='store_const', dest='extract_flat', const='in_playlist',
171         default=False,
172         help='Do not extract the videos of a playlist, only list them.')
173     general.add_option(
174         '--mark-watched',
175         action='store_true', dest='mark_watched', default=False,
176         help='Mark videos watched (YouTube only)')
177     general.add_option(
178         '--no-mark-watched',
179         action='store_false', dest='mark_watched', default=False,
180         help='Do not mark videos watched (YouTube only)')
181     general.add_option(
182         '--no-color', '--no-colors',
183         action='store_true', dest='no_color',
184         default=False,
185         help='Do not emit color codes in output')
186
187     network = optparse.OptionGroup(parser, 'Network Options')
188     network.add_option(
189         '--proxy', dest='proxy',
190         default=None, metavar='URL',
191         help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
192     network.add_option(
193         '--socket-timeout',
194         dest='socket_timeout', type=float, default=None, metavar='SECONDS',
195         help='Time to wait before giving up, in seconds')
196     network.add_option(
197         '--source-address',
198         metavar='IP', dest='source_address', default=None,
199         help='Client-side IP address to bind to (experimental)',
200     )
201     network.add_option(
202         '-4', '--force-ipv4',
203         action='store_const', const='0.0.0.0', dest='source_address',
204         help='Make all connections via IPv4 (experimental)',
205     )
206     network.add_option(
207         '-6', '--force-ipv6',
208         action='store_const', const='::', dest='source_address',
209         help='Make all connections via IPv6 (experimental)',
210     )
211     network.add_option(
212         '--cn-verification-proxy',
213         dest='cn_verification_proxy', default=None, metavar='URL',
214         help='Use this proxy to verify the IP address for some Chinese sites. '
215         'The default proxy specified by --proxy (or none, if the options is not present) is used for the actual downloading. (experimental)'
216     )
217
218     selection = optparse.OptionGroup(parser, 'Video Selection')
219     selection.add_option(
220         '--playlist-start',
221         dest='playliststart', metavar='NUMBER', default=1, type=int,
222         help='Playlist video to start at (default is %default)')
223     selection.add_option(
224         '--playlist-end',
225         dest='playlistend', metavar='NUMBER', default=None, type=int,
226         help='Playlist video to end at (default is last)')
227     selection.add_option(
228         '--playlist-items',
229         dest='playlist_items', metavar='ITEM_SPEC', default=None,
230         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.')
231     selection.add_option(
232         '--match-title',
233         dest='matchtitle', metavar='REGEX',
234         help='Download only matching titles (regex or caseless sub-string)')
235     selection.add_option(
236         '--reject-title',
237         dest='rejecttitle', metavar='REGEX',
238         help='Skip download for matching titles (regex or caseless sub-string)')
239     selection.add_option(
240         '--max-downloads',
241         dest='max_downloads', metavar='NUMBER', type=int, default=None,
242         help='Abort after downloading NUMBER files')
243     selection.add_option(
244         '--min-filesize',
245         metavar='SIZE', dest='min_filesize', default=None,
246         help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
247     selection.add_option(
248         '--max-filesize',
249         metavar='SIZE', dest='max_filesize', default=None,
250         help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
251     selection.add_option(
252         '--date',
253         metavar='DATE', dest='date', default=None,
254         help='Download only videos uploaded in this date')
255     selection.add_option(
256         '--datebefore',
257         metavar='DATE', dest='datebefore', default=None,
258         help='Download only videos uploaded on or before this date (i.e. inclusive)')
259     selection.add_option(
260         '--dateafter',
261         metavar='DATE', dest='dateafter', default=None,
262         help='Download only videos uploaded on or after this date (i.e. inclusive)')
263     selection.add_option(
264         '--min-views',
265         metavar='COUNT', dest='min_views', default=None, type=int,
266         help='Do not download any videos with less than COUNT views')
267     selection.add_option(
268         '--max-views',
269         metavar='COUNT', dest='max_views', default=None, type=int,
270         help='Do not download any videos with more than COUNT views')
271     selection.add_option(
272         '--match-filter',
273         metavar='FILTER', dest='match_filter', default=None,
274         help=(
275             'Generic video filter (experimental). '
276             'Specify any key (see help for -o for a list of available keys) to'
277             ' match if the key is present, '
278             '!key to check if the key is not present,'
279             'key > NUMBER (like "comment_count > 12", also works with '
280             '>=, <, <=, !=, =) to compare against a number, and '
281             '& to require multiple matches. '
282             'Values which are not known are excluded unless you'
283             ' put a question mark (?) after the operator.'
284             'For example, to only match videos that have been liked more than '
285             '100 times and disliked less than 50 times (or the dislike '
286             'functionality is not available at the given service), but who '
287             'also have a description, use --match-filter '
288             '"like_count > 100 & dislike_count <? 50 & description" .'
289         ))
290     selection.add_option(
291         '--no-playlist',
292         action='store_true', dest='noplaylist', default=False,
293         help='Download only the video, if the URL refers to a video and a playlist.')
294     selection.add_option(
295         '--yes-playlist',
296         action='store_false', dest='noplaylist', default=False,
297         help='Download the playlist, if the URL refers to a video and a playlist.')
298     selection.add_option(
299         '--age-limit',
300         metavar='YEARS', dest='age_limit', default=None, type=int,
301         help='Download only videos suitable for the given age')
302     selection.add_option(
303         '--download-archive', metavar='FILE',
304         dest='download_archive',
305         help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
306     selection.add_option(
307         '--include-ads',
308         dest='include_ads', action='store_true',
309         help='Download advertisements as well (experimental)')
310
311     authentication = optparse.OptionGroup(parser, 'Authentication Options')
312     authentication.add_option(
313         '-u', '--username',
314         dest='username', metavar='USERNAME',
315         help='Login with this account ID')
316     authentication.add_option(
317         '-p', '--password',
318         dest='password', metavar='PASSWORD',
319         help='Account password. If this option is left out, youtube-dl will ask interactively.')
320     authentication.add_option(
321         '-2', '--twofactor',
322         dest='twofactor', metavar='TWOFACTOR',
323         help='Two-factor auth code')
324     authentication.add_option(
325         '-n', '--netrc',
326         action='store_true', dest='usenetrc', default=False,
327         help='Use .netrc authentication data')
328     authentication.add_option(
329         '--video-password',
330         dest='videopassword', metavar='PASSWORD',
331         help='Video password (vimeo, smotri, youku)')
332
333     video_format = optparse.OptionGroup(parser, 'Video Format Options')
334     video_format.add_option(
335         '-f', '--format',
336         action='store', dest='format', metavar='FORMAT', default=None,
337         help='Video format code, see the "FORMAT SELECTION" for all the info')
338     video_format.add_option(
339         '--all-formats',
340         action='store_const', dest='format', const='all',
341         help='Download all available video formats')
342     video_format.add_option(
343         '--prefer-free-formats',
344         action='store_true', dest='prefer_free_formats', default=False,
345         help='Prefer free video formats unless a specific one is requested')
346     video_format.add_option(
347         '-F', '--list-formats',
348         action='store_true', dest='listformats',
349         help='List all available formats of requested videos')
350     video_format.add_option(
351         '--youtube-include-dash-manifest',
352         action='store_true', dest='youtube_include_dash_manifest', default=True,
353         help=optparse.SUPPRESS_HELP)
354     video_format.add_option(
355         '--youtube-skip-dash-manifest',
356         action='store_false', dest='youtube_include_dash_manifest',
357         help='Do not download the DASH manifests and related data on YouTube videos')
358     video_format.add_option(
359         '--merge-output-format',
360         action='store', dest='merge_output_format', metavar='FORMAT', default=None,
361         help=(
362             'If a merge is required (e.g. bestvideo+bestaudio), '
363             'output to given container format. One of mkv, mp4, ogg, webm, flv. '
364             'Ignored if no merge is required'))
365
366     subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
367     subtitles.add_option(
368         '--write-sub', '--write-srt',
369         action='store_true', dest='writesubtitles', default=False,
370         help='Write subtitle file')
371     subtitles.add_option(
372         '--write-auto-sub', '--write-automatic-sub',
373         action='store_true', dest='writeautomaticsub', default=False,
374         help='Write automatically generated subtitle file (YouTube only)')
375     subtitles.add_option(
376         '--all-subs',
377         action='store_true', dest='allsubtitles', default=False,
378         help='Download all the available subtitles of the video')
379     subtitles.add_option(
380         '--list-subs',
381         action='store_true', dest='listsubtitles', default=False,
382         help='List all available subtitles for the video')
383     subtitles.add_option(
384         '--sub-format',
385         action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
386         help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
387     subtitles.add_option(
388         '--sub-lang', '--sub-langs', '--srt-lang',
389         action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
390         default=[], callback=_comma_separated_values_options_callback,
391         help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
392
393     downloader = optparse.OptionGroup(parser, 'Download Options')
394     downloader.add_option(
395         '-r', '--rate-limit',
396         dest='ratelimit', metavar='LIMIT',
397         help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
398     downloader.add_option(
399         '-R', '--retries',
400         dest='retries', metavar='RETRIES', default=10,
401         help='Number of retries (default is %default), or "infinite".')
402     downloader.add_option(
403         '--fragment-retries',
404         dest='fragment_retries', metavar='RETRIES', default=10,
405         help='Number of retries for a fragment (default is %default), or "infinite" (DASH only)')
406     downloader.add_option(
407         '--buffer-size',
408         dest='buffersize', metavar='SIZE', default='1024',
409         help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
410     downloader.add_option(
411         '--no-resize-buffer',
412         action='store_true', dest='noresizebuffer', default=False,
413         help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
414     downloader.add_option(
415         '--test',
416         action='store_true', dest='test', default=False,
417         help=optparse.SUPPRESS_HELP)
418     downloader.add_option(
419         '--playlist-reverse',
420         action='store_true',
421         help='Download playlist videos in reverse order')
422     downloader.add_option(
423         '--xattr-set-filesize',
424         dest='xattr_set_filesize', action='store_true',
425         help='Set file xattribute ytdl.filesize with expected filesize (experimental)')
426     downloader.add_option(
427         '--hls-prefer-native',
428         dest='hls_prefer_native', action='store_true',
429         help='Use the native HLS downloader instead of ffmpeg (experimental)')
430     downloader.add_option(
431         '--hls-use-mpegts',
432         dest='hls_use_mpegts', action='store_true',
433         help='Use the mpegts container for HLS videos, allowing to play the '
434              'video while downloading (some players may not be able to play it)')
435     downloader.add_option(
436         '--external-downloader',
437         dest='external_downloader', metavar='COMMAND',
438         help='Use the specified external downloader. '
439              'Currently supports %s' % ','.join(list_external_downloaders()))
440     downloader.add_option(
441         '--external-downloader-args',
442         dest='external_downloader_args', metavar='ARGS',
443         help='Give these arguments to the external downloader')
444
445     workarounds = optparse.OptionGroup(parser, 'Workarounds')
446     workarounds.add_option(
447         '--encoding',
448         dest='encoding', metavar='ENCODING',
449         help='Force the specified encoding (experimental)')
450     workarounds.add_option(
451         '--no-check-certificate',
452         action='store_true', dest='no_check_certificate', default=False,
453         help='Suppress HTTPS certificate validation')
454     workarounds.add_option(
455         '--prefer-insecure',
456         '--prefer-unsecure', action='store_true', dest='prefer_insecure',
457         help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
458     workarounds.add_option(
459         '--user-agent',
460         metavar='UA', dest='user_agent',
461         help='Specify a custom user agent')
462     workarounds.add_option(
463         '--referer',
464         metavar='URL', dest='referer', default=None,
465         help='Specify a custom referer, use if the video access is restricted to one domain',
466     )
467     workarounds.add_option(
468         '--add-header',
469         metavar='FIELD:VALUE', dest='headers', action='append',
470         help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
471     )
472     workarounds.add_option(
473         '--bidi-workaround',
474         dest='bidi_workaround', action='store_true',
475         help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
476     workarounds.add_option(
477         '--sleep-interval', metavar='SECONDS',
478         dest='sleep_interval', type=float,
479         help='Number of seconds to sleep before each download.')
480
481     verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
482     verbosity.add_option(
483         '-q', '--quiet',
484         action='store_true', dest='quiet', default=False,
485         help='Activate quiet mode')
486     verbosity.add_option(
487         '--no-warnings',
488         dest='no_warnings', action='store_true', default=False,
489         help='Ignore warnings')
490     verbosity.add_option(
491         '-s', '--simulate',
492         action='store_true', dest='simulate', default=False,
493         help='Do not download the video and do not write anything to disk')
494     verbosity.add_option(
495         '--skip-download',
496         action='store_true', dest='skip_download', default=False,
497         help='Do not download the video')
498     verbosity.add_option(
499         '-g', '--get-url',
500         action='store_true', dest='geturl', default=False,
501         help='Simulate, quiet but print URL')
502     verbosity.add_option(
503         '-e', '--get-title',
504         action='store_true', dest='gettitle', default=False,
505         help='Simulate, quiet but print title')
506     verbosity.add_option(
507         '--get-id',
508         action='store_true', dest='getid', default=False,
509         help='Simulate, quiet but print id')
510     verbosity.add_option(
511         '--get-thumbnail',
512         action='store_true', dest='getthumbnail', default=False,
513         help='Simulate, quiet but print thumbnail URL')
514     verbosity.add_option(
515         '--get-description',
516         action='store_true', dest='getdescription', default=False,
517         help='Simulate, quiet but print video description')
518     verbosity.add_option(
519         '--get-duration',
520         action='store_true', dest='getduration', default=False,
521         help='Simulate, quiet but print video length')
522     verbosity.add_option(
523         '--get-filename',
524         action='store_true', dest='getfilename', default=False,
525         help='Simulate, quiet but print output filename')
526     verbosity.add_option(
527         '--get-format',
528         action='store_true', dest='getformat', default=False,
529         help='Simulate, quiet but print output format')
530     verbosity.add_option(
531         '-j', '--dump-json',
532         action='store_true', dest='dumpjson', default=False,
533         help='Simulate, quiet but print JSON information. See --output for a description of available keys.')
534     verbosity.add_option(
535         '-J', '--dump-single-json',
536         action='store_true', dest='dump_single_json', default=False,
537         help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.')
538     verbosity.add_option(
539         '--print-json',
540         action='store_true', dest='print_json', default=False,
541         help='Be quiet and print the video information as JSON (video is still being downloaded).',
542     )
543     verbosity.add_option(
544         '--newline',
545         action='store_true', dest='progress_with_newline', default=False,
546         help='Output progress bar as new lines')
547     verbosity.add_option(
548         '--no-progress',
549         action='store_true', dest='noprogress', default=False,
550         help='Do not print progress bar')
551     verbosity.add_option(
552         '--console-title',
553         action='store_true', dest='consoletitle', default=False,
554         help='Display progress in console titlebar')
555     verbosity.add_option(
556         '-v', '--verbose',
557         action='store_true', dest='verbose', default=False,
558         help='Print various debugging information')
559     verbosity.add_option(
560         '--dump-pages', '--dump-intermediate-pages',
561         action='store_true', dest='dump_intermediate_pages', default=False,
562         help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
563     verbosity.add_option(
564         '--write-pages',
565         action='store_true', dest='write_pages', default=False,
566         help='Write downloaded intermediary pages to files in the current directory to debug problems')
567     verbosity.add_option(
568         '--youtube-print-sig-code',
569         action='store_true', dest='youtube_print_sig_code', default=False,
570         help=optparse.SUPPRESS_HELP)
571     verbosity.add_option(
572         '--print-traffic', '--dump-headers',
573         dest='debug_printtraffic', action='store_true', default=False,
574         help='Display sent and read HTTP traffic')
575     verbosity.add_option(
576         '-C', '--call-home',
577         dest='call_home', action='store_true', default=False,
578         help='Contact the youtube-dl server for debugging')
579     verbosity.add_option(
580         '--no-call-home',
581         dest='call_home', action='store_false', default=False,
582         help='Do NOT contact the youtube-dl server for debugging')
583
584     filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
585     filesystem.add_option(
586         '-a', '--batch-file',
587         dest='batchfile', metavar='FILE',
588         help='File containing URLs to download (\'-\' for stdin)')
589     filesystem.add_option(
590         '--id', default=False,
591         action='store_true', dest='useid', help='Use only video ID in file name')
592     filesystem.add_option(
593         '-o', '--output',
594         dest='outtmpl', metavar='TEMPLATE',
595         help=('Output filename template. Use %(title)s to get the title, '
596               '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
597               '%(autonumber)s to get an automatically incremented number, '
598               '%(ext)s for the filename extension, '
599               '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
600               '%(format_id)s for the unique id of the format (like YouTube\'s itags: "137"), '
601               '%(upload_date)s for the upload date (YYYYMMDD), '
602               '%(extractor)s for the provider (youtube, metacafe, etc), '
603               '%(id)s for the video id, '
604               '%(playlist_title)s, %(playlist_id)s, or %(playlist)s (=title if present, ID otherwise) for the playlist the video is in, '
605               '%(playlist_index)s for the position in the playlist. '
606               '%(height)s and %(width)s for the width and height of the video format. '
607               '%(resolution)s for a textual description of the resolution of the video format. '
608               '%% for a literal percent. '
609               'Use - to output to stdout. Can also be used to download to a different directory, '
610               'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
611     filesystem.add_option(
612         '--autonumber-size',
613         dest='autonumber_size', metavar='NUMBER',
614         help='Specify the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
615     filesystem.add_option(
616         '--restrict-filenames',
617         action='store_true', dest='restrictfilenames', default=False,
618         help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
619     filesystem.add_option(
620         '-A', '--auto-number',
621         action='store_true', dest='autonumber', default=False,
622         help='[deprecated; use -o "%(autonumber)s-%(title)s.%(ext)s" ] Number downloaded files starting from 00000')
623     filesystem.add_option(
624         '-t', '--title',
625         action='store_true', dest='usetitle', default=False,
626         help='[deprecated] Use title in file name (default)')
627     filesystem.add_option(
628         '-l', '--literal', default=False,
629         action='store_true', dest='usetitle',
630         help='[deprecated] Alias of --title')
631     filesystem.add_option(
632         '-w', '--no-overwrites',
633         action='store_true', dest='nooverwrites', default=False,
634         help='Do not overwrite files')
635     filesystem.add_option(
636         '-c', '--continue',
637         action='store_true', dest='continue_dl', default=True,
638         help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
639     filesystem.add_option(
640         '--no-continue',
641         action='store_false', dest='continue_dl',
642         help='Do not resume partially downloaded files (restart from beginning)')
643     filesystem.add_option(
644         '--no-part',
645         action='store_true', dest='nopart', default=False,
646         help='Do not use .part files - write directly into output file')
647     filesystem.add_option(
648         '--no-mtime',
649         action='store_false', dest='updatetime', default=True,
650         help='Do not use the Last-modified header to set the file modification time')
651     filesystem.add_option(
652         '--write-description',
653         action='store_true', dest='writedescription', default=False,
654         help='Write video description to a .description file')
655     filesystem.add_option(
656         '--write-info-json',
657         action='store_true', dest='writeinfojson', default=False,
658         help='Write video metadata to a .info.json file')
659     filesystem.add_option(
660         '--write-annotations',
661         action='store_true', dest='writeannotations', default=False,
662         help='Write video annotations to a .annotations.xml file')
663     filesystem.add_option(
664         '--load-info',
665         dest='load_info_filename', metavar='FILE',
666         help='JSON file containing the video information (created with the "--write-info-json" option)')
667     filesystem.add_option(
668         '--cookies',
669         dest='cookiefile', metavar='FILE',
670         help='File to read cookies from and dump cookie jar in')
671     filesystem.add_option(
672         '--cache-dir', dest='cachedir', default=None, metavar='DIR',
673         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.')
674     filesystem.add_option(
675         '--no-cache-dir', action='store_const', const=False, dest='cachedir',
676         help='Disable filesystem caching')
677     filesystem.add_option(
678         '--rm-cache-dir',
679         action='store_true', dest='rm_cachedir',
680         help='Delete all filesystem cache files')
681
682     thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
683     thumbnail.add_option(
684         '--write-thumbnail',
685         action='store_true', dest='writethumbnail', default=False,
686         help='Write thumbnail image to disk')
687     thumbnail.add_option(
688         '--write-all-thumbnails',
689         action='store_true', dest='write_all_thumbnails', default=False,
690         help='Write all thumbnail image formats to disk')
691     thumbnail.add_option(
692         '--list-thumbnails',
693         action='store_true', dest='list_thumbnails', default=False,
694         help='Simulate and list all available thumbnail formats')
695
696     postproc = optparse.OptionGroup(parser, 'Post-processing Options')
697     postproc.add_option(
698         '-x', '--extract-audio',
699         action='store_true', dest='extractaudio', default=False,
700         help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
701     postproc.add_option(
702         '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
703         help='Specify audio format: "best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; "%default" by default')
704     postproc.add_option(
705         '--audio-quality', metavar='QUALITY',
706         dest='audioquality', default='5',
707         help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')
708     postproc.add_option(
709         '--recode-video',
710         metavar='FORMAT', dest='recodevideo', default=None,
711         help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
712     postproc.add_option(
713         '--postprocessor-args',
714         dest='postprocessor_args', metavar='ARGS',
715         help='Give these arguments to the postprocessor')
716     postproc.add_option(
717         '-k', '--keep-video',
718         action='store_true', dest='keepvideo', default=False,
719         help='Keep the video file on disk after the post-processing; the video is erased by default')
720     postproc.add_option(
721         '--no-post-overwrites',
722         action='store_true', dest='nopostoverwrites', default=False,
723         help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
724     postproc.add_option(
725         '--embed-subs',
726         action='store_true', dest='embedsubtitles', default=False,
727         help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
728     postproc.add_option(
729         '--embed-thumbnail',
730         action='store_true', dest='embedthumbnail', default=False,
731         help='Embed thumbnail in the audio as cover art')
732     postproc.add_option(
733         '--add-metadata',
734         action='store_true', dest='addmetadata', default=False,
735         help='Write metadata to the video file')
736     postproc.add_option(
737         '--metadata-from-title',
738         metavar='FORMAT', dest='metafromtitle',
739         help='Parse additional metadata like song title / artist from the video title. '
740              'The format syntax is the same as --output, '
741              'the parsed parameters replace existing values. '
742              'Additional templates: %(album)s, %(artist)s. '
743              'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
744              '"Coldplay - Paradise"')
745     postproc.add_option(
746         '--xattrs',
747         action='store_true', dest='xattrs', default=False,
748         help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
749     postproc.add_option(
750         '--fixup',
751         metavar='POLICY', dest='fixup', default='detect_or_warn',
752         help='Automatically correct known faults of the file. '
753              'One of never (do nothing), warn (only emit a warning), '
754              'detect_or_warn (the default; fix file if we can, warn otherwise)')
755     postproc.add_option(
756         '--prefer-avconv',
757         action='store_false', dest='prefer_ffmpeg',
758         help='Prefer avconv over ffmpeg for running the postprocessors (default)')
759     postproc.add_option(
760         '--prefer-ffmpeg',
761         action='store_true', dest='prefer_ffmpeg',
762         help='Prefer ffmpeg over avconv for running the postprocessors')
763     postproc.add_option(
764         '--ffmpeg-location', '--avconv-location', metavar='PATH',
765         dest='ffmpeg_location',
766         help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
767     postproc.add_option(
768         '--exec',
769         metavar='CMD', dest='exec_cmd',
770         help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
771     postproc.add_option(
772         '--convert-subs', '--convert-subtitles',
773         metavar='FORMAT', dest='convertsubtitles', default=None,
774         help='Convert the subtitles to other format (currently supported: srt|ass|vtt)')
775
776     parser.add_option_group(general)
777     parser.add_option_group(network)
778     parser.add_option_group(selection)
779     parser.add_option_group(downloader)
780     parser.add_option_group(filesystem)
781     parser.add_option_group(thumbnail)
782     parser.add_option_group(verbosity)
783     parser.add_option_group(workarounds)
784     parser.add_option_group(video_format)
785     parser.add_option_group(subtitles)
786     parser.add_option_group(authentication)
787     parser.add_option_group(postproc)
788
789     if overrideArguments is not None:
790         opts, args = parser.parse_args(overrideArguments)
791         if opts.verbose:
792             write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
793     else:
794         def compat_conf(conf):
795             if sys.version_info < (3,):
796                 return [a.decode(preferredencoding(), 'replace') for a in conf]
797             return conf
798
799         command_line_conf = compat_conf(sys.argv[1:])
800
801         if '--ignore-config' in command_line_conf:
802             system_conf = []
803             user_conf = []
804         else:
805             system_conf = compat_conf(_readOptions('/etc/youtube-dl.conf'))
806             if '--ignore-config' in system_conf:
807                 user_conf = []
808             else:
809                 user_conf = compat_conf(_readUserConf())
810         argv = system_conf + user_conf + command_line_conf
811
812         opts, args = parser.parse_args(argv)
813         if opts.verbose:
814             write_string('[debug] System config: ' + repr(_hide_login_info(system_conf)) + '\n')
815             write_string('[debug] User config: ' + repr(_hide_login_info(user_conf)) + '\n')
816             write_string('[debug] Command-line args: ' + repr(_hide_login_info(command_line_conf)) + '\n')
817
818     return parser, opts, args