You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

842 lines
41 KiB

13 years ago
12 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __authors__ = (
  4. 'Ricardo Garcia Gonzalez',
  5. 'Danny Colligan',
  6. 'Benjamin Johnson',
  7. 'Vasyl\' Vavrychuk',
  8. 'Witold Baryluk',
  9. 'Paweł Paprota',
  10. 'Gergely Imreh',
  11. 'Rogério Brito',
  12. 'Philipp Hagemeister',
  13. 'Sören Schulze',
  14. 'Kevin Ngo',
  15. 'Ori Avtalion',
  16. 'shizeeg',
  17. 'Filippo Valsorda',
  18. 'Christian Albrecht',
  19. 'Dave Vasilevsky',
  20. 'Jaime Marquínez Ferrándiz',
  21. 'Jeff Crouse',
  22. 'Osama Khalid',
  23. 'Michael Walter',
  24. 'M. Yasoob Ullah Khalid',
  25. 'Julien Fraichard',
  26. 'Johny Mo Swag',
  27. 'Axel Noack',
  28. 'Albert Kim',
  29. 'Pierre Rudloff',
  30. 'Huarong Huo',
  31. 'Ismael Mejía',
  32. 'Steffan \'Ruirize\' James',
  33. 'Andras Elso',
  34. 'Jelle van der Waa',
  35. 'Marcin Cieślak',
  36. 'Anton Larionov',
  37. 'Takuya Tsuchida',
  38. 'Sergey M.',
  39. 'Michael Orlitzky',
  40. 'Chris Gahan',
  41. 'Saimadhav Heblikar',
  42. 'Mike Col',
  43. 'Oleg Prutz',
  44. 'pulpe',
  45. 'Andreas Schmitz',
  46. 'Michael Kaiser',
  47. 'Niklas Laxström',
  48. 'David Triendl',
  49. 'Anthony Weems',
  50. 'David Wagner',
  51. 'Juan C. Olivares',
  52. 'Mattias Harrysson',
  53. 'phaer',
  54. )
  55. __license__ = 'Public Domain'
  56. import codecs
  57. import io
  58. import locale
  59. import optparse
  60. import os
  61. import random
  62. import re
  63. import shlex
  64. import sys
  65. from .utils import (
  66. compat_getpass,
  67. compat_print,
  68. DateRange,
  69. decodeOption,
  70. get_term_width,
  71. DownloadError,
  72. get_cachedir,
  73. MaxDownloadsReached,
  74. preferredencoding,
  75. read_batch_urls,
  76. SameFileError,
  77. setproctitle,
  78. std_headers,
  79. write_string,
  80. )
  81. from .update import update_self
  82. from .FileDownloader import (
  83. FileDownloader,
  84. )
  85. from .extractor import gen_extractors
  86. from .version import __version__
  87. from .YoutubeDL import YoutubeDL
  88. from .postprocessor import (
  89. FFmpegMetadataPP,
  90. FFmpegVideoConvertor,
  91. FFmpegExtractAudioPP,
  92. FFmpegEmbedSubtitlePP,
  93. XAttrMetadataPP,
  94. )
  95. def parseOpts(overrideArguments=None):
  96. def _readOptions(filename_bytes, default=[]):
  97. try:
  98. optionf = open(filename_bytes)
  99. except IOError:
  100. return default # silently skip if file is not present
  101. try:
  102. res = []
  103. for l in optionf:
  104. res += shlex.split(l, comments=True)
  105. finally:
  106. optionf.close()
  107. return res
  108. def _readUserConf():
  109. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  110. if xdg_config_home:
  111. userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
  112. if not os.path.isfile(userConfFile):
  113. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  114. else:
  115. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
  116. if not os.path.isfile(userConfFile):
  117. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  118. userConf = _readOptions(userConfFile, None)
  119. if userConf is None:
  120. appdata_dir = os.environ.get('appdata')
  121. if appdata_dir:
  122. userConf = _readOptions(
  123. os.path.join(appdata_dir, 'youtube-dl', 'config'),
  124. default=None)
  125. if userConf is None:
  126. userConf = _readOptions(
  127. os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
  128. default=None)
  129. if userConf is None:
  130. userConf = _readOptions(
  131. os.path.join(os.path.expanduser('~'), 'youtube-dl.conf'),
  132. default=None)
  133. if userConf is None:
  134. userConf = _readOptions(
  135. os.path.join(os.path.expanduser('~'), 'youtube-dl.conf.txt'),
  136. default=None)
  137. if userConf is None:
  138. userConf = []
  139. return userConf
  140. def _format_option_string(option):
  141. ''' ('-o', '--option') -> -o, --format METAVAR'''
  142. opts = []
  143. if option._short_opts:
  144. opts.append(option._short_opts[0])
  145. if option._long_opts:
  146. opts.append(option._long_opts[0])
  147. if len(opts) > 1:
  148. opts.insert(1, ', ')
  149. if option.takes_value(): opts.append(' %s' % option.metavar)
  150. return "".join(opts)
  151. def _comma_separated_values_options_callback(option, opt_str, value, parser):
  152. setattr(parser.values, option.dest, value.split(','))
  153. def _hide_login_info(opts):
  154. opts = list(opts)
  155. for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
  156. try:
  157. i = opts.index(private_opt)
  158. opts[i+1] = '<PRIVATE>'
  159. except ValueError:
  160. pass
  161. return opts
  162. max_width = 80
  163. max_help_position = 80
  164. # No need to wrap help messages if we're on a wide console
  165. columns = get_term_width()
  166. if columns: max_width = columns
  167. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  168. fmt.format_option_strings = _format_option_string
  169. kw = {
  170. 'version' : __version__,
  171. 'formatter' : fmt,
  172. 'usage' : '%prog [options] url [url...]',
  173. 'conflict_handler' : 'resolve',
  174. }
  175. parser = optparse.OptionParser(**kw)
  176. # option groups
  177. general = optparse.OptionGroup(parser, 'General Options')
  178. selection = optparse.OptionGroup(parser, 'Video Selection')
  179. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  180. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  181. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  182. downloader = optparse.OptionGroup(parser, 'Download Options')
  183. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  184. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  185. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  186. general.add_option('-h', '--help',
  187. action='help', help='print this help text and exit')
  188. general.add_option('-v', '--version',
  189. action='version', help='print program version and exit')
  190. general.add_option('-U', '--update',
  191. action='store_true', dest='update_self', help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
  192. general.add_option('-i', '--ignore-errors',
  193. action='store_true', dest='ignoreerrors', help='continue on download errors, for example to skip unavailable videos in a playlist', default=False)
  194. general.add_option('--abort-on-error',
  195. action='store_false', dest='ignoreerrors',
  196. help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
  197. general.add_option('--dump-user-agent',
  198. action='store_true', dest='dump_user_agent',
  199. help='display the current browser identification', default=False)
  200. general.add_option('--user-agent',
  201. dest='user_agent', help='specify a custom user agent', metavar='UA')
  202. general.add_option('--referer',
  203. dest='referer', help='specify a custom referer, use if the video access is restricted to one domain',
  204. metavar='REF', default=None)
  205. general.add_option('--add-header',
  206. dest='headers', help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times', action="append",
  207. metavar='FIELD:VALUE')
  208. general.add_option('--list-extractors',
  209. action='store_true', dest='list_extractors',
  210. help='List all supported extractors and the URLs they would handle', default=False)
  211. general.add_option('--extractor-descriptions',
  212. action='store_true', dest='list_extractor_descriptions',
  213. help='Output descriptions of all supported extractors', default=False)
  214. general.add_option(
  215. '--proxy', dest='proxy', default=None, metavar='URL',
  216. help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
  217. general.add_option('--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation.')
  218. general.add_option(
  219. '--prefer-insecure', '--prefer-unsecure', action='store_true', dest='prefer_insecure',
  220. help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
  221. general.add_option(
  222. '--cache-dir', dest='cachedir', default=get_cachedir(), metavar='DIR',
  223. 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.')
  224. general.add_option(
  225. '--no-cache-dir', action='store_const', const=None, dest='cachedir',
  226. help='Disable filesystem caching')
  227. general.add_option(
  228. '--socket-timeout', dest='socket_timeout',
  229. type=float, default=None, help=u'Time to wait before giving up, in seconds')
  230. general.add_option(
  231. '--bidi-workaround', dest='bidi_workaround', action='store_true',
  232. help=u'Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
  233. general.add_option(
  234. '--default-search',
  235. dest='default_search', metavar='PREFIX',
  236. help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". By default (with value "auto") youtube-dl guesses.')
  237. general.add_option(
  238. '--ignore-config',
  239. action='store_true',
  240. help='Do not read configuration files. When given in the global configuration file /etc/youtube-dl.conf: do not read the user configuration in ~/.config/youtube-dl.conf (%APPDATA%/youtube-dl/config.txt on Windows)')
  241. general.add_option(
  242. '--encoding', dest='encoding', metavar='ENCODING',
  243. help='Force the specified encoding (experimental)')
  244. selection.add_option(
  245. '--playlist-start',
  246. dest='playliststart', metavar='NUMBER', default=1, type=int,
  247. help='playlist video to start at (default is %default)')
  248. selection.add_option(
  249. '--playlist-end',
  250. dest='playlistend', metavar='NUMBER', default=None, type=int,
  251. help='playlist video to end at (default is last)')
  252. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  253. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  254. selection.add_option('--max-downloads', metavar='NUMBER',
  255. dest='max_downloads', type=int, default=None,
  256. help='Abort after downloading NUMBER files')
  257. selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
  258. selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
  259. selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
  260. selection.add_option(
  261. '--datebefore', metavar='DATE', dest='datebefore', default=None,
  262. help='download only videos uploaded on or before this date (i.e. inclusive)')
  263. selection.add_option(
  264. '--dateafter', metavar='DATE', dest='dateafter', default=None,
  265. help='download only videos uploaded on or after this date (i.e. inclusive)')
  266. selection.add_option(
  267. '--min-views', metavar='COUNT', dest='min_views',
  268. default=None, type=int,
  269. help="Do not download any videos with less than COUNT views",)
  270. selection.add_option(
  271. '--max-views', metavar='COUNT', dest='max_views',
  272. default=None, type=int,
  273. help="Do not download any videos with more than COUNT views",)
  274. selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
  275. selection.add_option('--age-limit', metavar='YEARS', dest='age_limit',
  276. help='download only videos suitable for the given age',
  277. default=None, type=int)
  278. selection.add_option('--download-archive', metavar='FILE',
  279. dest='download_archive',
  280. help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
  281. selection.add_option(
  282. '--include-ads', dest='include_ads',
  283. action='store_true',
  284. help='Download advertisements as well (experimental)')
  285. selection.add_option(
  286. '--youtube-include-dash-manifest', action='store_true',
  287. dest='youtube_include_dash_manifest', default=False,
  288. help='Try to download the DASH manifest on YouTube videos (experimental)')
  289. authentication.add_option('-u', '--username',
  290. dest='username', metavar='USERNAME', help='account username')
  291. authentication.add_option('-p', '--password',
  292. dest='password', metavar='PASSWORD', help='account password')
  293. authentication.add_option('-n', '--netrc',
  294. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  295. authentication.add_option('--video-password',
  296. dest='videopassword', metavar='PASSWORD', help='video password (vimeo, smotri)')
  297. video_format.add_option('-f', '--format',
  298. action='store', dest='format', metavar='FORMAT', default=None,
  299. help='video format code, specify the order of preference using slashes: "-f 22/17/18". "-f mp4" and "-f flv" are also supported. You can also use the special names "best", "bestvideo", "bestaudio", "worst", "worstvideo" and "worstaudio". By default, youtube-dl will pick the best quality.')
  300. video_format.add_option('--all-formats',
  301. action='store_const', dest='format', help='download all available video formats', const='all')
  302. video_format.add_option('--prefer-free-formats',
  303. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  304. video_format.add_option('--max-quality',
  305. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  306. video_format.add_option('-F', '--list-formats',
  307. action='store_true', dest='listformats', help='list all available formats')
  308. subtitles.add_option('--write-sub', '--write-srt',
  309. action='store_true', dest='writesubtitles',
  310. help='write subtitle file', default=False)
  311. subtitles.add_option('--write-auto-sub', '--write-automatic-sub',
  312. action='store_true', dest='writeautomaticsub',
  313. help='write automatic subtitle file (youtube only)', default=False)
  314. subtitles.add_option('--all-subs',
  315. action='store_true', dest='allsubtitles',
  316. help='downloads all the available subtitles of the video', default=False)
  317. subtitles.add_option('--list-subs',
  318. action='store_true', dest='listsubtitles',
  319. help='lists all available subtitles for the video', default=False)
  320. subtitles.add_option('--sub-format',
  321. action='store', dest='subtitlesformat', metavar='FORMAT',
  322. help='subtitle format (default=srt) ([sbv/vtt] youtube only)', default='srt')
  323. subtitles.add_option('--sub-lang', '--sub-langs', '--srt-lang',
  324. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  325. default=[], callback=_comma_separated_values_options_callback,
  326. help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
  327. downloader.add_option('-r', '--rate-limit',
  328. dest='ratelimit', metavar='LIMIT', help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
  329. downloader.add_option('-R', '--retries',
  330. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  331. downloader.add_option('--buffer-size',
  332. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16K) (default is %default)', default="1024")
  333. downloader.add_option('--no-resize-buffer',
  334. action='store_true', dest='noresizebuffer',
  335. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  336. downloader.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
  337. verbosity.add_option('-q', '--quiet',
  338. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  339. verbosity.add_option(
  340. '--no-warnings',
  341. dest='no_warnings', action='store_true', default=False,
  342. help='Ignore warnings')
  343. verbosity.add_option('-s', '--simulate',
  344. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  345. verbosity.add_option('--skip-download',
  346. action='store_true', dest='skip_download', help='do not download the video', default=False)
  347. verbosity.add_option('-g', '--get-url',
  348. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  349. verbosity.add_option('-e', '--get-title',
  350. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  351. verbosity.add_option('--get-id',
  352. action='store_true', dest='getid', help='simulate, quiet but print id', default=False)
  353. verbosity.add_option('--get-thumbnail',
  354. action='store_true', dest='getthumbnail',
  355. help='simulate, quiet but print thumbnail URL', default=False)
  356. verbosity.add_option('--get-description',
  357. action='store_true', dest='getdescription',
  358. help='simulate, quiet but print video description', default=False)
  359. verbosity.add_option('--get-duration',
  360. action='store_true', dest='getduration',
  361. help='simulate, quiet but print video length', default=False)
  362. verbosity.add_option('--get-filename',
  363. action='store_true', dest='getfilename',
  364. help='simulate, quiet but print output filename', default=False)
  365. verbosity.add_option('--get-format',
  366. action='store_true', dest='getformat',
  367. help='simulate, quiet but print output format', default=False)
  368. verbosity.add_option('-j', '--dump-json',
  369. action='store_true', dest='dumpjson',
  370. help='simulate, quiet but print JSON information. See --output for a description of available keys.', default=False)
  371. verbosity.add_option('--newline',
  372. action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
  373. verbosity.add_option('--no-progress',
  374. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  375. verbosity.add_option('--console-title',
  376. action='store_true', dest='consoletitle',
  377. help='display progress in console titlebar', default=False)
  378. verbosity.add_option('-v', '--verbose',
  379. action='store_true', dest='verbose', help='print various debugging information', default=False)
  380. verbosity.add_option('--dump-intermediate-pages',
  381. action='store_true', dest='dump_intermediate_pages', default=False,
  382. help='print downloaded pages to debug problems (very verbose)')
  383. verbosity.add_option('--write-pages',
  384. action='store_true', dest='write_pages', default=False,
  385. help='Write downloaded intermediary pages to files in the current directory to debug problems')
  386. verbosity.add_option('--youtube-print-sig-code',
  387. action='store_true', dest='youtube_print_sig_code', default=False,
  388. help=optparse.SUPPRESS_HELP)
  389. verbosity.add_option('--print-traffic',
  390. dest='debug_printtraffic', action='store_true', default=False,
  391. help='Display sent and read HTTP traffic')
  392. filesystem.add_option('-t', '--title',
  393. action='store_true', dest='usetitle', help='use title in file name (default)', default=False)
  394. filesystem.add_option('--id',
  395. action='store_true', dest='useid', help='use only video ID in file name', default=False)
  396. filesystem.add_option('-l', '--literal',
  397. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  398. filesystem.add_option('-A', '--auto-number',
  399. action='store_true', dest='autonumber',
  400. help='number downloaded files starting from 00000', default=False)
  401. filesystem.add_option('-o', '--output',
  402. dest='outtmpl', metavar='TEMPLATE',
  403. help=('output filename template. Use %(title)s to get the title, '
  404. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  405. '%(autonumber)s to get an automatically incremented number, '
  406. '%(ext)s for the filename extension, '
  407. '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
  408. '%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
  409. '%(upload_date)s for the upload date (YYYYMMDD), '
  410. '%(extractor)s for the provider (youtube, metacafe, etc), '
  411. '%(id)s for the video id, %(playlist)s for the playlist the video is in, '
  412. '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
  413. '%(height)s and %(width)s for the width and height of the video format. '
  414. '%(resolution)s for a textual description of the resolution of the video format. '
  415. 'Use - to output to stdout. Can also be used to download to a different directory, '
  416. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  417. filesystem.add_option('--autonumber-size',
  418. dest='autonumber_size', metavar='NUMBER',
  419. help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
  420. filesystem.add_option('--restrict-filenames',
  421. action='store_true', dest='restrictfilenames',
  422. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  423. filesystem.add_option('-a', '--batch-file',
  424. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  425. filesystem.add_option('--load-info',
  426. dest='load_info_filename', metavar='FILE',
  427. help='json file containing the video information (created with the "--write-json" option)')
  428. filesystem.add_option('-w', '--no-overwrites',
  429. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  430. filesystem.add_option('-c', '--continue',
  431. action='store_true', dest='continue_dl', help='force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.', default=True)
  432. filesystem.add_option('--no-continue',
  433. action='store_false', dest='continue_dl',
  434. help='do not resume partially downloaded files (restart from beginning)')
  435. filesystem.add_option('--cookies',
  436. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  437. filesystem.add_option('--no-part',
  438. action='store_true', dest='nopart', help='do not use .part files', default=False)
  439. filesystem.add_option('--no-mtime',
  440. action='store_false', dest='updatetime',
  441. help='do not use the Last-modified header to set the file modification time', default=True)
  442. filesystem.add_option('--write-description',
  443. action='store_true', dest='writedescription',
  444. help='write video description to a .description file', default=False)
  445. filesystem.add_option('--write-info-json',
  446. action='store_true', dest='writeinfojson',
  447. help='write video metadata to a .info.json file', default=False)
  448. filesystem.add_option('--write-annotations',
  449. action='store_true', dest='writeannotations',
  450. help='write video annotations to a .annotation file', default=False)
  451. filesystem.add_option('--write-thumbnail',
  452. action='store_true', dest='writethumbnail',
  453. help='write thumbnail image to disk', default=False)
  454. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  455. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  456. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  457. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  458. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  459. help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)')
  460. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  461. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm)')
  462. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  463. help='keeps the video file on disk after the post-processing; the video is erased by default')
  464. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  465. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  466. postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
  467. help='embed subtitles in the video (only for mp4 videos)')
  468. postproc.add_option('--add-metadata', action='store_true', dest='addmetadata', default=False,
  469. help='write metadata to the video file')
  470. postproc.add_option('--xattrs', action='store_true', dest='xattrs', default=False,
  471. help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  472. postproc.add_option('--prefer-avconv', action='store_false', dest='prefer_ffmpeg',
  473. help='Prefer avconv over ffmpeg for running the postprocessors (default)')
  474. postproc.add_option('--prefer-ffmpeg', action='store_true', dest='prefer_ffmpeg',
  475. help='Prefer ffmpeg over avconv for running the postprocessors')
  476. parser.add_option_group(general)
  477. parser.add_option_group(selection)
  478. parser.add_option_group(downloader)
  479. parser.add_option_group(filesystem)
  480. parser.add_option_group(verbosity)
  481. parser.add_option_group(video_format)
  482. parser.add_option_group(subtitles)
  483. parser.add_option_group(authentication)
  484. parser.add_option_group(postproc)
  485. if overrideArguments is not None:
  486. opts, args = parser.parse_args(overrideArguments)
  487. if opts.verbose:
  488. write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
  489. else:
  490. commandLineConf = sys.argv[1:]
  491. if '--ignore-config' in commandLineConf:
  492. systemConf = []
  493. userConf = []
  494. else:
  495. systemConf = _readOptions('/etc/youtube-dl.conf')
  496. if '--ignore-config' in systemConf:
  497. userConf = []
  498. else:
  499. userConf = _readUserConf()
  500. argv = systemConf + userConf + commandLineConf
  501. opts, args = parser.parse_args(argv)
  502. if opts.verbose:
  503. write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
  504. write_string(u'[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
  505. write_string(u'[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
  506. return parser, opts, args
  507. def _real_main(argv=None):
  508. # Compatibility fixes for Windows
  509. if sys.platform == 'win32':
  510. # https://github.com/rg3/youtube-dl/issues/820
  511. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  512. setproctitle(u'youtube-dl')
  513. parser, opts, args = parseOpts(argv)
  514. # Set user agent
  515. if opts.user_agent is not None:
  516. std_headers['User-Agent'] = opts.user_agent
  517. # Set referer
  518. if opts.referer is not None:
  519. std_headers['Referer'] = opts.referer
  520. # Custom HTTP headers
  521. if opts.headers is not None:
  522. for h in opts.headers:
  523. if h.find(':', 1) < 0:
  524. parser.error(u'wrong header formatting, it should be key:value, not "%s"'%h)
  525. key, value = h.split(':', 2)
  526. if opts.verbose:
  527. write_string(u'[debug] Adding header from command line option %s:%s\n'%(key, value))
  528. std_headers[key] = value
  529. # Dump user agent
  530. if opts.dump_user_agent:
  531. compat_print(std_headers['User-Agent'])
  532. sys.exit(0)
  533. # Batch file verification
  534. batch_urls = []
  535. if opts.batchfile is not None:
  536. try:
  537. if opts.batchfile == '-':
  538. batchfd = sys.stdin
  539. else:
  540. batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
  541. batch_urls = read_batch_urls(batchfd)
  542. if opts.verbose:
  543. write_string(u'[debug] Batch file urls: ' + repr(batch_urls) + u'\n')
  544. except IOError:
  545. sys.exit(u'ERROR: batch file could not be read')
  546. all_urls = batch_urls + args
  547. all_urls = [url.strip() for url in all_urls]
  548. _enc = preferredencoding()
  549. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  550. extractors = gen_extractors()
  551. if opts.list_extractors:
  552. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  553. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  554. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  555. for mu in matchedUrls:
  556. compat_print(u' ' + mu)
  557. sys.exit(0)
  558. if opts.list_extractor_descriptions:
  559. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  560. if not ie._WORKING:
  561. continue
  562. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  563. if desc is False:
  564. continue
  565. if hasattr(ie, 'SEARCH_KEY'):
  566. _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise')
  567. _COUNTS = (u'', u'5', u'10', u'all')
  568. desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  569. compat_print(desc)
  570. sys.exit(0)
  571. # Conflicting, missing and erroneous options
  572. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  573. parser.error(u'using .netrc conflicts with giving username/password')
  574. if opts.password is not None and opts.username is None:
  575. parser.error(u'account username missing\n')
  576. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  577. parser.error(u'using output template conflicts with using title, video ID or auto number')
  578. if opts.usetitle and opts.useid:
  579. parser.error(u'using title conflicts with using video ID')
  580. if opts.username is not None and opts.password is None:
  581. opts.password = compat_getpass(u'Type account password and press [Return]: ')
  582. if opts.ratelimit is not None:
  583. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  584. if numeric_limit is None:
  585. parser.error(u'invalid rate limit specified')
  586. opts.ratelimit = numeric_limit
  587. if opts.min_filesize is not None:
  588. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  589. if numeric_limit is None:
  590. parser.error(u'invalid min_filesize specified')
  591. opts.min_filesize = numeric_limit
  592. if opts.max_filesize is not None:
  593. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  594. if numeric_limit is None:
  595. parser.error(u'invalid max_filesize specified')
  596. opts.max_filesize = numeric_limit
  597. if opts.retries is not None:
  598. try:
  599. opts.retries = int(opts.retries)
  600. except (TypeError, ValueError):
  601. parser.error(u'invalid retry count specified')
  602. if opts.buffersize is not None:
  603. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  604. if numeric_buffersize is None:
  605. parser.error(u'invalid buffer size specified')
  606. opts.buffersize = numeric_buffersize
  607. if opts.playliststart <= 0:
  608. raise ValueError(u'Playlist start must be positive')
  609. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  610. raise ValueError(u'Playlist end must be greater than playlist start')
  611. if opts.extractaudio:
  612. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  613. parser.error(u'invalid audio format specified')
  614. if opts.audioquality:
  615. opts.audioquality = opts.audioquality.strip('k').strip('K')
  616. if not opts.audioquality.isdigit():
  617. parser.error(u'invalid audio quality specified')
  618. if opts.recodevideo is not None:
  619. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  620. parser.error(u'invalid video recode format specified')
  621. if opts.date is not None:
  622. date = DateRange.day(opts.date)
  623. else:
  624. date = DateRange(opts.dateafter, opts.datebefore)
  625. if opts.default_search not in ('auto', 'auto_warning', None) and ':' not in opts.default_search:
  626. parser.error(u'--default-search invalid; did you forget a colon (:) at the end?')
  627. # Do not download videos when there are audio-only formats
  628. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  629. opts.format = 'bestaudio/best'
  630. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  631. # this was the old behaviour if only --all-sub was given.
  632. if opts.allsubtitles and (opts.writeautomaticsub == False):
  633. opts.writesubtitles = True
  634. if sys.version_info < (3,):
  635. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  636. if opts.outtmpl is not None:
  637. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  638. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  639. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  640. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  641. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  642. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  643. or (opts.useid and u'%(id)s.%(ext)s')
  644. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  645. or u'%(title)s-%(id)s.%(ext)s')
  646. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  647. parser.error(u'Cannot download a video and extract audio into the same'
  648. u' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  649. u' template'.format(outtmpl))
  650. any_printing = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson
  651. download_archive_fn = os.path.expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  652. ydl_opts = {
  653. 'usenetrc': opts.usenetrc,
  654. 'username': opts.username,
  655. 'password': opts.password,
  656. 'videopassword': opts.videopassword,
  657. 'quiet': (opts.quiet or any_printing),
  658. 'no_warnings': opts.no_warnings,
  659. 'forceurl': opts.geturl,
  660. 'forcetitle': opts.gettitle,
  661. 'forceid': opts.getid,
  662. 'forcethumbnail': opts.getthumbnail,
  663. 'forcedescription': opts.getdescription,
  664. 'forceduration': opts.getduration,
  665. 'forcefilename': opts.getfilename,
  666. 'forceformat': opts.getformat,
  667. 'forcejson': opts.dumpjson,
  668. 'simulate': opts.simulate,
  669. 'skip_download': (opts.skip_download or opts.simulate or any_printing),
  670. 'format': opts.format,
  671. 'format_limit': opts.format_limit,
  672. 'listformats': opts.listformats,
  673. 'outtmpl': outtmpl,
  674. 'autonumber_size': opts.autonumber_size,
  675. 'restrictfilenames': opts.restrictfilenames,
  676. 'ignoreerrors': opts.ignoreerrors,
  677. 'ratelimit': opts.ratelimit,
  678. 'nooverwrites': opts.nooverwrites,
  679. 'retries': opts.retries,
  680. 'buffersize': opts.buffersize,
  681. 'noresizebuffer': opts.noresizebuffer,
  682. 'continuedl': opts.continue_dl,
  683. 'noprogress': opts.noprogress,
  684. 'progress_with_newline': opts.progress_with_newline,
  685. 'playliststart': opts.playliststart,
  686. 'playlistend': opts.playlistend,
  687. 'noplaylist': opts.noplaylist,
  688. 'logtostderr': opts.outtmpl == '-',
  689. 'consoletitle': opts.consoletitle,
  690. 'nopart': opts.nopart,
  691. 'updatetime': opts.updatetime,
  692. 'writedescription': opts.writedescription,
  693. 'writeannotations': opts.writeannotations,
  694. 'writeinfojson': opts.writeinfojson,
  695. 'writethumbnail': opts.writethumbnail,
  696. 'writesubtitles': opts.writesubtitles,
  697. 'writeautomaticsub': opts.writeautomaticsub,
  698. 'allsubtitles': opts.allsubtitles,
  699. 'listsubtitles': opts.listsubtitles,
  700. 'subtitlesformat': opts.subtitlesformat,
  701. 'subtitleslangs': opts.subtitleslangs,
  702. 'matchtitle': decodeOption(opts.matchtitle),
  703. 'rejecttitle': decodeOption(opts.rejecttitle),
  704. 'max_downloads': opts.max_downloads,
  705. 'prefer_free_formats': opts.prefer_free_formats,
  706. 'verbose': opts.verbose,
  707. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  708. 'write_pages': opts.write_pages,
  709. 'test': opts.test,
  710. 'keepvideo': opts.keepvideo,
  711. 'min_filesize': opts.min_filesize,
  712. 'max_filesize': opts.max_filesize,
  713. 'min_views': opts.min_views,
  714. 'max_views': opts.max_views,
  715. 'daterange': date,
  716. 'cachedir': opts.cachedir,
  717. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  718. 'age_limit': opts.age_limit,
  719. 'download_archive': download_archive_fn,
  720. 'cookiefile': opts.cookiefile,
  721. 'nocheckcertificate': opts.no_check_certificate,
  722. 'prefer_insecure': opts.prefer_insecure,
  723. 'proxy': opts.proxy,
  724. 'socket_timeout': opts.socket_timeout,
  725. 'bidi_workaround': opts.bidi_workaround,
  726. 'debug_printtraffic': opts.debug_printtraffic,
  727. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  728. 'include_ads': opts.include_ads,
  729. 'default_search': opts.default_search,
  730. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  731. 'encoding': opts.encoding,
  732. }
  733. with YoutubeDL(ydl_opts) as ydl:
  734. ydl.print_debug_header()
  735. ydl.add_default_info_extractors()
  736. # PostProcessors
  737. # Add the metadata pp first, the other pps will copy it
  738. if opts.addmetadata:
  739. ydl.add_post_processor(FFmpegMetadataPP())
  740. if opts.extractaudio:
  741. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  742. if opts.recodevideo:
  743. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  744. if opts.embedsubtitles:
  745. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  746. if opts.xattrs:
  747. ydl.add_post_processor(XAttrMetadataPP())
  748. # Update version
  749. if opts.update_self:
  750. update_self(ydl.to_screen, opts.verbose)
  751. # Maybe do nothing
  752. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  753. if not opts.update_self:
  754. parser.error(u'you must provide at least one URL')
  755. else:
  756. sys.exit()
  757. try:
  758. if opts.load_info_filename is not None:
  759. retcode = ydl.download_with_info_file(opts.load_info_filename)
  760. else:
  761. retcode = ydl.download(all_urls)
  762. except MaxDownloadsReached:
  763. ydl.to_screen(u'--max-download limit reached, aborting.')
  764. retcode = 101
  765. sys.exit(retcode)
  766. def main(argv=None):
  767. try:
  768. _real_main(argv)
  769. except DownloadError:
  770. sys.exit(1)
  771. except SameFileError:
  772. sys.exit(u'ERROR: fixed output name but more than one file to download')
  773. except KeyboardInterrupt:
  774. sys.exit(u'\nERROR: Interrupted by user')