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.

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