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.

1606 lines
70 KiB

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
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import datetime
  6. import errno
  7. import io
  8. import itertools
  9. import json
  10. import locale
  11. import operator
  12. import os
  13. import platform
  14. import re
  15. import shutil
  16. import subprocess
  17. import socket
  18. import sys
  19. import time
  20. import traceback
  21. if os.name == 'nt':
  22. import ctypes
  23. from .compat import (
  24. compat_cookiejar,
  25. compat_expanduser,
  26. compat_http_client,
  27. compat_kwargs,
  28. compat_str,
  29. compat_urllib_error,
  30. compat_urllib_request,
  31. )
  32. from .utils import (
  33. escape_url,
  34. ContentTooShortError,
  35. date_from_str,
  36. DateRange,
  37. DEFAULT_OUTTMPL,
  38. determine_ext,
  39. DownloadError,
  40. encodeFilename,
  41. ExtractorError,
  42. format_bytes,
  43. formatSeconds,
  44. get_term_width,
  45. locked_file,
  46. make_HTTPS_handler,
  47. MaxDownloadsReached,
  48. PagedList,
  49. parse_filesize,
  50. PostProcessingError,
  51. platform_name,
  52. preferredencoding,
  53. SameFileError,
  54. sanitize_filename,
  55. subtitles_filename,
  56. takewhile_inclusive,
  57. UnavailableVideoError,
  58. url_basename,
  59. version_tuple,
  60. write_json_file,
  61. write_string,
  62. YoutubeDLHandler,
  63. prepend_extension,
  64. args_to_str,
  65. age_restricted,
  66. )
  67. from .cache import Cache
  68. from .extractor import get_info_extractor, gen_extractors
  69. from .downloader import get_suitable_downloader
  70. from .downloader.rtmp import rtmpdump_version
  71. from .postprocessor import (
  72. FFmpegFixupM4aPP,
  73. FFmpegFixupStretchedPP,
  74. FFmpegMergerPP,
  75. FFmpegPostProcessor,
  76. get_postprocessor,
  77. )
  78. from .version import __version__
  79. class YoutubeDL(object):
  80. """YoutubeDL class.
  81. YoutubeDL objects are the ones responsible of downloading the
  82. actual video file and writing it to disk if the user has requested
  83. it, among some other tasks. In most cases there should be one per
  84. program. As, given a video URL, the downloader doesn't know how to
  85. extract all the needed information, task that InfoExtractors do, it
  86. has to pass the URL to one of them.
  87. For this, YoutubeDL objects have a method that allows
  88. InfoExtractors to be registered in a given order. When it is passed
  89. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  90. finds that reports being able to handle it. The InfoExtractor extracts
  91. all the information about the video or videos the URL refers to, and
  92. YoutubeDL process the extracted information, possibly using a File
  93. Downloader to download the video.
  94. YoutubeDL objects accept a lot of parameters. In order not to saturate
  95. the object constructor with arguments, it receives a dictionary of
  96. options instead. These options are available through the params
  97. attribute for the InfoExtractors to use. The YoutubeDL also
  98. registers itself as the downloader in charge for the InfoExtractors
  99. that are added to it, so this is a "mutual registration".
  100. Available options:
  101. username: Username for authentication purposes.
  102. password: Password for authentication purposes.
  103. videopassword: Password for acces a video.
  104. usenetrc: Use netrc for authentication instead.
  105. verbose: Print additional info to stdout.
  106. quiet: Do not print messages to stdout.
  107. no_warnings: Do not print out anything for warnings.
  108. forceurl: Force printing final URL.
  109. forcetitle: Force printing title.
  110. forceid: Force printing ID.
  111. forcethumbnail: Force printing thumbnail URL.
  112. forcedescription: Force printing description.
  113. forcefilename: Force printing final filename.
  114. forceduration: Force printing duration.
  115. forcejson: Force printing info_dict as JSON.
  116. dump_single_json: Force printing the info_dict of the whole playlist
  117. (or video) as a single JSON line.
  118. simulate: Do not download the video files.
  119. format: Video format code. See options.py for more information.
  120. format_limit: Highest quality format to try.
  121. outtmpl: Template for output names.
  122. restrictfilenames: Do not allow "&" and spaces in file names
  123. ignoreerrors: Do not stop on download errors.
  124. nooverwrites: Prevent overwriting files.
  125. playliststart: Playlist item to start at.
  126. playlistend: Playlist item to end at.
  127. playlistreverse: Download playlist items in reverse order.
  128. matchtitle: Download only matching titles.
  129. rejecttitle: Reject downloads for matching titles.
  130. logger: Log messages to a logging.Logger instance.
  131. logtostderr: Log messages to stderr instead of stdout.
  132. writedescription: Write the video description to a .description file
  133. writeinfojson: Write the video description to a .info.json file
  134. writeannotations: Write the video annotations to a .annotations.xml file
  135. writethumbnail: Write the thumbnail image to a file
  136. writesubtitles: Write the video subtitles to a file
  137. writeautomaticsub: Write the automatic subtitles to a file
  138. allsubtitles: Downloads all the subtitles of the video
  139. (requires writesubtitles or writeautomaticsub)
  140. listsubtitles: Lists all available subtitles for the video
  141. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  142. subtitleslangs: List of languages of the subtitles to download
  143. keepvideo: Keep the video file after post-processing
  144. daterange: A DateRange object, download only if the upload_date is in the range.
  145. skip_download: Skip the actual download of the video file
  146. cachedir: Location of the cache files in the filesystem.
  147. False to disable filesystem cache.
  148. noplaylist: Download single video instead of a playlist if in doubt.
  149. age_limit: An integer representing the user's age in years.
  150. Unsuitable videos for the given age are skipped.
  151. min_views: An integer representing the minimum view count the video
  152. must have in order to not be skipped.
  153. Videos without view count information are always
  154. downloaded. None for no limit.
  155. max_views: An integer representing the maximum view count.
  156. Videos that are more popular than that are not
  157. downloaded.
  158. Videos without view count information are always
  159. downloaded. None for no limit.
  160. download_archive: File name of a file where all downloads are recorded.
  161. Videos already present in the file are not downloaded
  162. again.
  163. cookiefile: File name where cookies should be read from and dumped to.
  164. nocheckcertificate:Do not verify SSL certificates
  165. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  166. At the moment, this is only supported by YouTube.
  167. proxy: URL of the proxy server to use
  168. socket_timeout: Time to wait for unresponsive hosts, in seconds
  169. bidi_workaround: Work around buggy terminals without bidirectional text
  170. support, using fridibi
  171. debug_printtraffic:Print out sent and received HTTP traffic
  172. include_ads: Download ads as well
  173. default_search: Prepend this string if an input url is not valid.
  174. 'auto' for elaborate guessing
  175. encoding: Use this encoding instead of the system-specified.
  176. extract_flat: Do not resolve URLs, return the immediate result.
  177. Pass in 'in_playlist' to only show this behavior for
  178. playlist items.
  179. postprocessors: A list of dictionaries, each with an entry
  180. * key: The name of the postprocessor. See
  181. youtube_dl/postprocessor/__init__.py for a list.
  182. as well as any further keyword arguments for the
  183. postprocessor.
  184. progress_hooks: A list of functions that get called on download
  185. progress, with a dictionary with the entries
  186. * filename: The final filename
  187. * status: One of "downloading" and "finished"
  188. The dict may also have some of the following entries:
  189. * downloaded_bytes: Bytes on disk
  190. * total_bytes: Size of the whole file, None if unknown
  191. * tmpfilename: The filename we're currently writing to
  192. * eta: The estimated time in seconds, None if unknown
  193. * speed: The download speed in bytes/second, None if
  194. unknown
  195. Progress hooks are guaranteed to be called at least once
  196. (with status "finished") if the download is successful.
  197. merge_output_format: Extension to use when merging formats.
  198. fixup: Automatically correct known faults of the file.
  199. One of:
  200. - "never": do nothing
  201. - "warn": only emit a warning
  202. - "detect_or_warn": check whether we can do anything
  203. about it, warn otherwise (default)
  204. source_address: (Experimental) Client-side IP address to bind to.
  205. call_home: Boolean, true iff we are allowed to contact the
  206. youtube-dl servers for debugging.
  207. sleep_interval: Number of seconds to sleep before each download.
  208. The following parameters are not used by YoutubeDL itself, they are used by
  209. the FileDownloader:
  210. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  211. noresizebuffer, retries, continuedl, noprogress, consoletitle
  212. The following options are used by the post processors:
  213. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  214. otherwise prefer avconv.
  215. exec_cmd: Arbitrary command to run after downloading
  216. """
  217. params = None
  218. _ies = []
  219. _pps = []
  220. _download_retcode = None
  221. _num_downloads = None
  222. _screen_file = None
  223. def __init__(self, params=None, auto_init=True):
  224. """Create a FileDownloader object with the given options."""
  225. if params is None:
  226. params = {}
  227. self._ies = []
  228. self._ies_instances = {}
  229. self._pps = []
  230. self._progress_hooks = []
  231. self._download_retcode = 0
  232. self._num_downloads = 0
  233. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  234. self._err_file = sys.stderr
  235. self.params = params
  236. self.cache = Cache(self)
  237. if params.get('bidi_workaround', False):
  238. try:
  239. import pty
  240. master, slave = pty.openpty()
  241. width = get_term_width()
  242. if width is None:
  243. width_args = []
  244. else:
  245. width_args = ['-w', str(width)]
  246. sp_kwargs = dict(
  247. stdin=subprocess.PIPE,
  248. stdout=slave,
  249. stderr=self._err_file)
  250. try:
  251. self._output_process = subprocess.Popen(
  252. ['bidiv'] + width_args, **sp_kwargs
  253. )
  254. except OSError:
  255. self._output_process = subprocess.Popen(
  256. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  257. self._output_channel = os.fdopen(master, 'rb')
  258. except OSError as ose:
  259. if ose.errno == 2:
  260. self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  261. else:
  262. raise
  263. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  264. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  265. and not params.get('restrictfilenames', False)):
  266. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  267. self.report_warning(
  268. 'Assuming --restrict-filenames since file system encoding '
  269. 'cannot encode all characters. '
  270. 'Set the LC_ALL environment variable to fix this.')
  271. self.params['restrictfilenames'] = True
  272. if '%(stitle)s' in self.params.get('outtmpl', ''):
  273. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  274. self._setup_opener()
  275. if auto_init:
  276. self.print_debug_header()
  277. self.add_default_info_extractors()
  278. for pp_def_raw in self.params.get('postprocessors', []):
  279. pp_class = get_postprocessor(pp_def_raw['key'])
  280. pp_def = dict(pp_def_raw)
  281. del pp_def['key']
  282. pp = pp_class(self, **compat_kwargs(pp_def))
  283. self.add_post_processor(pp)
  284. for ph in self.params.get('progress_hooks', []):
  285. self.add_progress_hook(ph)
  286. def warn_if_short_id(self, argv):
  287. # short YouTube ID starting with dash?
  288. idxs = [
  289. i for i, a in enumerate(argv)
  290. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  291. if idxs:
  292. correct_argv = (
  293. ['youtube-dl'] +
  294. [a for i, a in enumerate(argv) if i not in idxs] +
  295. ['--'] + [argv[i] for i in idxs]
  296. )
  297. self.report_warning(
  298. 'Long argument string detected. '
  299. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  300. args_to_str(correct_argv))
  301. def add_info_extractor(self, ie):
  302. """Add an InfoExtractor object to the end of the list."""
  303. self._ies.append(ie)
  304. self._ies_instances[ie.ie_key()] = ie
  305. ie.set_downloader(self)
  306. def get_info_extractor(self, ie_key):
  307. """
  308. Get an instance of an IE with name ie_key, it will try to get one from
  309. the _ies list, if there's no instance it will create a new one and add
  310. it to the extractor list.
  311. """
  312. ie = self._ies_instances.get(ie_key)
  313. if ie is None:
  314. ie = get_info_extractor(ie_key)()
  315. self.add_info_extractor(ie)
  316. return ie
  317. def add_default_info_extractors(self):
  318. """
  319. Add the InfoExtractors returned by gen_extractors to the end of the list
  320. """
  321. for ie in gen_extractors():
  322. self.add_info_extractor(ie)
  323. def add_post_processor(self, pp):
  324. """Add a PostProcessor object to the end of the chain."""
  325. self._pps.append(pp)
  326. pp.set_downloader(self)
  327. def add_progress_hook(self, ph):
  328. """Add the progress hook (currently only for the file downloader)"""
  329. self._progress_hooks.append(ph)
  330. def _bidi_workaround(self, message):
  331. if not hasattr(self, '_output_channel'):
  332. return message
  333. assert hasattr(self, '_output_process')
  334. assert isinstance(message, compat_str)
  335. line_count = message.count('\n') + 1
  336. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  337. self._output_process.stdin.flush()
  338. res = ''.join(self._output_channel.readline().decode('utf-8')
  339. for _ in range(line_count))
  340. return res[:-len('\n')]
  341. def to_screen(self, message, skip_eol=False):
  342. """Print message to stdout if not in quiet mode."""
  343. return self.to_stdout(message, skip_eol, check_quiet=True)
  344. def _write_string(self, s, out=None):
  345. write_string(s, out=out, encoding=self.params.get('encoding'))
  346. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  347. """Print message to stdout if not in quiet mode."""
  348. if self.params.get('logger'):
  349. self.params['logger'].debug(message)
  350. elif not check_quiet or not self.params.get('quiet', False):
  351. message = self._bidi_workaround(message)
  352. terminator = ['\n', ''][skip_eol]
  353. output = message + terminator
  354. self._write_string(output, self._screen_file)
  355. def to_stderr(self, message):
  356. """Print message to stderr."""
  357. assert isinstance(message, compat_str)
  358. if self.params.get('logger'):
  359. self.params['logger'].error(message)
  360. else:
  361. message = self._bidi_workaround(message)
  362. output = message + '\n'
  363. self._write_string(output, self._err_file)
  364. def to_console_title(self, message):
  365. if not self.params.get('consoletitle', False):
  366. return
  367. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  368. # c_wchar_p() might not be necessary if `message` is
  369. # already of type unicode()
  370. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  371. elif 'TERM' in os.environ:
  372. self._write_string('\033]0;%s\007' % message, self._screen_file)
  373. def save_console_title(self):
  374. if not self.params.get('consoletitle', False):
  375. return
  376. if 'TERM' in os.environ:
  377. # Save the title on stack
  378. self._write_string('\033[22;0t', self._screen_file)
  379. def restore_console_title(self):
  380. if not self.params.get('consoletitle', False):
  381. return
  382. if 'TERM' in os.environ:
  383. # Restore the title from stack
  384. self._write_string('\033[23;0t', self._screen_file)
  385. def __enter__(self):
  386. self.save_console_title()
  387. return self
  388. def __exit__(self, *args):
  389. self.restore_console_title()
  390. if self.params.get('cookiefile') is not None:
  391. self.cookiejar.save()
  392. def trouble(self, message=None, tb=None):
  393. """Determine action to take when a download problem appears.
  394. Depending on if the downloader has been configured to ignore
  395. download errors or not, this method may throw an exception or
  396. not when errors are found, after printing the message.
  397. tb, if given, is additional traceback information.
  398. """
  399. if message is not None:
  400. self.to_stderr(message)
  401. if self.params.get('verbose'):
  402. if tb is None:
  403. if sys.exc_info()[0]: # if .trouble has been called from an except block
  404. tb = ''
  405. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  406. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  407. tb += compat_str(traceback.format_exc())
  408. else:
  409. tb_data = traceback.format_list(traceback.extract_stack())
  410. tb = ''.join(tb_data)
  411. self.to_stderr(tb)
  412. if not self.params.get('ignoreerrors', False):
  413. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  414. exc_info = sys.exc_info()[1].exc_info
  415. else:
  416. exc_info = sys.exc_info()
  417. raise DownloadError(message, exc_info)
  418. self._download_retcode = 1
  419. def report_warning(self, message):
  420. '''
  421. Print the message to stderr, it will be prefixed with 'WARNING:'
  422. If stderr is a tty file the 'WARNING:' will be colored
  423. '''
  424. if self.params.get('logger') is not None:
  425. self.params['logger'].warning(message)
  426. else:
  427. if self.params.get('no_warnings'):
  428. return
  429. if self._err_file.isatty() and os.name != 'nt':
  430. _msg_header = '\033[0;33mWARNING:\033[0m'
  431. else:
  432. _msg_header = 'WARNING:'
  433. warning_message = '%s %s' % (_msg_header, message)
  434. self.to_stderr(warning_message)
  435. def report_error(self, message, tb=None):
  436. '''
  437. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  438. in red if stderr is a tty file.
  439. '''
  440. if self._err_file.isatty() and os.name != 'nt':
  441. _msg_header = '\033[0;31mERROR:\033[0m'
  442. else:
  443. _msg_header = 'ERROR:'
  444. error_message = '%s %s' % (_msg_header, message)
  445. self.trouble(error_message, tb)
  446. def report_file_already_downloaded(self, file_name):
  447. """Report file has already been fully downloaded."""
  448. try:
  449. self.to_screen('[download] %s has already been downloaded' % file_name)
  450. except UnicodeEncodeError:
  451. self.to_screen('[download] The file has already been downloaded')
  452. def prepare_filename(self, info_dict):
  453. """Generate the output filename."""
  454. try:
  455. template_dict = dict(info_dict)
  456. template_dict['epoch'] = int(time.time())
  457. autonumber_size = self.params.get('autonumber_size')
  458. if autonumber_size is None:
  459. autonumber_size = 5
  460. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  461. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  462. if template_dict.get('playlist_index') is not None:
  463. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  464. if template_dict.get('resolution') is None:
  465. if template_dict.get('width') and template_dict.get('height'):
  466. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  467. elif template_dict.get('height'):
  468. template_dict['resolution'] = '%sp' % template_dict['height']
  469. elif template_dict.get('width'):
  470. template_dict['resolution'] = '?x%d' % template_dict['width']
  471. sanitize = lambda k, v: sanitize_filename(
  472. compat_str(v),
  473. restricted=self.params.get('restrictfilenames'),
  474. is_id=(k == 'id'))
  475. template_dict = dict((k, sanitize(k, v))
  476. for k, v in template_dict.items()
  477. if v is not None)
  478. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  479. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  480. tmpl = compat_expanduser(outtmpl)
  481. filename = tmpl % template_dict
  482. return filename
  483. except ValueError as err:
  484. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  485. return None
  486. def _match_entry(self, info_dict):
  487. """ Returns None iff the file should be downloaded """
  488. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  489. if 'title' in info_dict:
  490. # This can happen when we're just evaluating the playlist
  491. title = info_dict['title']
  492. matchtitle = self.params.get('matchtitle', False)
  493. if matchtitle:
  494. if not re.search(matchtitle, title, re.IGNORECASE):
  495. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  496. rejecttitle = self.params.get('rejecttitle', False)
  497. if rejecttitle:
  498. if re.search(rejecttitle, title, re.IGNORECASE):
  499. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  500. date = info_dict.get('upload_date', None)
  501. if date is not None:
  502. dateRange = self.params.get('daterange', DateRange())
  503. if date not in dateRange:
  504. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  505. view_count = info_dict.get('view_count', None)
  506. if view_count is not None:
  507. min_views = self.params.get('min_views')
  508. if min_views is not None and view_count < min_views:
  509. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  510. max_views = self.params.get('max_views')
  511. if max_views is not None and view_count > max_views:
  512. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  513. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  514. return 'Skipping "%s" because it is age restricted' % title
  515. if self.in_download_archive(info_dict):
  516. return '%s has already been recorded in archive' % video_title
  517. return None
  518. @staticmethod
  519. def add_extra_info(info_dict, extra_info):
  520. '''Set the keys from extra_info in info dict if they are missing'''
  521. for key, value in extra_info.items():
  522. info_dict.setdefault(key, value)
  523. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  524. process=True):
  525. '''
  526. Returns a list with a dictionary for each video we find.
  527. If 'download', also downloads the videos.
  528. extra_info is a dict containing the extra values to add to each result
  529. '''
  530. if ie_key:
  531. ies = [self.get_info_extractor(ie_key)]
  532. else:
  533. ies = self._ies
  534. for ie in ies:
  535. if not ie.suitable(url):
  536. continue
  537. if not ie.working():
  538. self.report_warning('The program functionality for this site has been marked as broken, '
  539. 'and will probably not work.')
  540. try:
  541. ie_result = ie.extract(url)
  542. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  543. break
  544. if isinstance(ie_result, list):
  545. # Backwards compatibility: old IE result format
  546. ie_result = {
  547. '_type': 'compat_list',
  548. 'entries': ie_result,
  549. }
  550. self.add_default_extra_info(ie_result, ie, url)
  551. if process:
  552. return self.process_ie_result(ie_result, download, extra_info)
  553. else:
  554. return ie_result
  555. except ExtractorError as de: # An error we somewhat expected
  556. self.report_error(compat_str(de), de.format_traceback())
  557. break
  558. except MaxDownloadsReached:
  559. raise
  560. except Exception as e:
  561. if self.params.get('ignoreerrors', False):
  562. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  563. break
  564. else:
  565. raise
  566. else:
  567. self.report_error('no suitable InfoExtractor for URL %s' % url)
  568. def add_default_extra_info(self, ie_result, ie, url):
  569. self.add_extra_info(ie_result, {
  570. 'extractor': ie.IE_NAME,
  571. 'webpage_url': url,
  572. 'webpage_url_basename': url_basename(url),
  573. 'extractor_key': ie.ie_key(),
  574. })
  575. def process_ie_result(self, ie_result, download=True, extra_info={}):
  576. """
  577. Take the result of the ie(may be modified) and resolve all unresolved
  578. references (URLs, playlist items).
  579. It will also download the videos if 'download'.
  580. Returns the resolved ie_result.
  581. """
  582. result_type = ie_result.get('_type', 'video')
  583. if result_type in ('url', 'url_transparent'):
  584. extract_flat = self.params.get('extract_flat', False)
  585. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  586. extract_flat is True):
  587. if self.params.get('forcejson', False):
  588. self.to_stdout(json.dumps(ie_result))
  589. return ie_result
  590. if result_type == 'video':
  591. self.add_extra_info(ie_result, extra_info)
  592. return self.process_video_result(ie_result, download=download)
  593. elif result_type == 'url':
  594. # We have to add extra_info to the results because it may be
  595. # contained in a playlist
  596. return self.extract_info(ie_result['url'],
  597. download,
  598. ie_key=ie_result.get('ie_key'),
  599. extra_info=extra_info)
  600. elif result_type == 'url_transparent':
  601. # Use the information from the embedding page
  602. info = self.extract_info(
  603. ie_result['url'], ie_key=ie_result.get('ie_key'),
  604. extra_info=extra_info, download=False, process=False)
  605. force_properties = dict(
  606. (k, v) for k, v in ie_result.items() if v is not None)
  607. for f in ('_type', 'url'):
  608. if f in force_properties:
  609. del force_properties[f]
  610. new_result = info.copy()
  611. new_result.update(force_properties)
  612. assert new_result.get('_type') != 'url_transparent'
  613. return self.process_ie_result(
  614. new_result, download=download, extra_info=extra_info)
  615. elif result_type == 'playlist' or result_type == 'multi_video':
  616. # We process each entry in the playlist
  617. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  618. self.to_screen('[download] Downloading playlist: %s' % playlist)
  619. playlist_results = []
  620. playliststart = self.params.get('playliststart', 1) - 1
  621. playlistend = self.params.get('playlistend', None)
  622. # For backwards compatibility, interpret -1 as whole list
  623. if playlistend == -1:
  624. playlistend = None
  625. ie_entries = ie_result['entries']
  626. if isinstance(ie_entries, list):
  627. n_all_entries = len(ie_entries)
  628. entries = ie_entries[playliststart:playlistend]
  629. n_entries = len(entries)
  630. self.to_screen(
  631. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  632. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  633. elif isinstance(ie_entries, PagedList):
  634. entries = ie_entries.getslice(
  635. playliststart, playlistend)
  636. n_entries = len(entries)
  637. self.to_screen(
  638. "[%s] playlist %s: Downloading %d videos" %
  639. (ie_result['extractor'], playlist, n_entries))
  640. else: # iterable
  641. entries = list(itertools.islice(
  642. ie_entries, playliststart, playlistend))
  643. n_entries = len(entries)
  644. self.to_screen(
  645. "[%s] playlist %s: Downloading %d videos" %
  646. (ie_result['extractor'], playlist, n_entries))
  647. if self.params.get('playlistreverse', False):
  648. entries = entries[::-1]
  649. for i, entry in enumerate(entries, 1):
  650. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  651. extra = {
  652. 'n_entries': n_entries,
  653. 'playlist': playlist,
  654. 'playlist_id': ie_result.get('id'),
  655. 'playlist_title': ie_result.get('title'),
  656. 'playlist_index': i + playliststart,
  657. 'extractor': ie_result['extractor'],
  658. 'webpage_url': ie_result['webpage_url'],
  659. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  660. 'extractor_key': ie_result['extractor_key'],
  661. }
  662. reason = self._match_entry(entry)
  663. if reason is not None:
  664. self.to_screen('[download] ' + reason)
  665. continue
  666. entry_result = self.process_ie_result(entry,
  667. download=download,
  668. extra_info=extra)
  669. playlist_results.append(entry_result)
  670. ie_result['entries'] = playlist_results
  671. return ie_result
  672. elif result_type == 'compat_list':
  673. self.report_warning(
  674. 'Extractor %s returned a compat_list result. '
  675. 'It needs to be updated.' % ie_result.get('extractor'))
  676. def _fixup(r):
  677. self.add_extra_info(
  678. r,
  679. {
  680. 'extractor': ie_result['extractor'],
  681. 'webpage_url': ie_result['webpage_url'],
  682. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  683. 'extractor_key': ie_result['extractor_key'],
  684. }
  685. )
  686. return r
  687. ie_result['entries'] = [
  688. self.process_ie_result(_fixup(r), download, extra_info)
  689. for r in ie_result['entries']
  690. ]
  691. return ie_result
  692. else:
  693. raise Exception('Invalid result type: %s' % result_type)
  694. def _apply_format_filter(self, format_spec, available_formats):
  695. " Returns a tuple of the remaining format_spec and filtered formats "
  696. OPERATORS = {
  697. '<': operator.lt,
  698. '<=': operator.le,
  699. '>': operator.gt,
  700. '>=': operator.ge,
  701. '=': operator.eq,
  702. '!=': operator.ne,
  703. }
  704. operator_rex = re.compile(r'''(?x)\s*\[
  705. (?P<key>width|height|tbr|abr|vbr|filesize)
  706. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  707. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  708. \]$
  709. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  710. m = operator_rex.search(format_spec)
  711. if not m:
  712. raise ValueError('Invalid format specification %r' % format_spec)
  713. try:
  714. comparison_value = int(m.group('value'))
  715. except ValueError:
  716. comparison_value = parse_filesize(m.group('value'))
  717. if comparison_value is None:
  718. comparison_value = parse_filesize(m.group('value') + 'B')
  719. if comparison_value is None:
  720. raise ValueError(
  721. 'Invalid value %r in format specification %r' % (
  722. m.group('value'), format_spec))
  723. op = OPERATORS[m.group('op')]
  724. def _filter(f):
  725. actual_value = f.get(m.group('key'))
  726. if actual_value is None:
  727. return m.group('none_inclusive')
  728. return op(actual_value, comparison_value)
  729. new_formats = [f for f in available_formats if _filter(f)]
  730. new_format_spec = format_spec[:-len(m.group(0))]
  731. if not new_format_spec:
  732. new_format_spec = 'best'
  733. return (new_format_spec, new_formats)
  734. def select_format(self, format_spec, available_formats):
  735. while format_spec.endswith(']'):
  736. format_spec, available_formats = self._apply_format_filter(
  737. format_spec, available_formats)
  738. if not available_formats:
  739. return None
  740. if format_spec == 'best' or format_spec is None:
  741. return available_formats[-1]
  742. elif format_spec == 'worst':
  743. return available_formats[0]
  744. elif format_spec == 'bestaudio':
  745. audio_formats = [
  746. f for f in available_formats
  747. if f.get('vcodec') == 'none']
  748. if audio_formats:
  749. return audio_formats[-1]
  750. elif format_spec == 'worstaudio':
  751. audio_formats = [
  752. f for f in available_formats
  753. if f.get('vcodec') == 'none']
  754. if audio_formats:
  755. return audio_formats[0]
  756. elif format_spec == 'bestvideo':
  757. video_formats = [
  758. f for f in available_formats
  759. if f.get('acodec') == 'none']
  760. if video_formats:
  761. return video_formats[-1]
  762. elif format_spec == 'worstvideo':
  763. video_formats = [
  764. f for f in available_formats
  765. if f.get('acodec') == 'none']
  766. if video_formats:
  767. return video_formats[0]
  768. else:
  769. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  770. if format_spec in extensions:
  771. filter_f = lambda f: f['ext'] == format_spec
  772. else:
  773. filter_f = lambda f: f['format_id'] == format_spec
  774. matches = list(filter(filter_f, available_formats))
  775. if matches:
  776. return matches[-1]
  777. return None
  778. def process_video_result(self, info_dict, download=True):
  779. assert info_dict.get('_type', 'video') == 'video'
  780. if 'id' not in info_dict:
  781. raise ExtractorError('Missing "id" field in extractor result')
  782. if 'title' not in info_dict:
  783. raise ExtractorError('Missing "title" field in extractor result')
  784. if 'playlist' not in info_dict:
  785. # It isn't part of a playlist
  786. info_dict['playlist'] = None
  787. info_dict['playlist_index'] = None
  788. thumbnails = info_dict.get('thumbnails')
  789. if thumbnails:
  790. thumbnails.sort(key=lambda t: (
  791. t.get('width'), t.get('height'), t.get('url')))
  792. for t in thumbnails:
  793. if 'width' in t and 'height' in t:
  794. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  795. if thumbnails and 'thumbnail' not in info_dict:
  796. info_dict['thumbnail'] = thumbnails[-1]['url']
  797. if 'display_id' not in info_dict and 'id' in info_dict:
  798. info_dict['display_id'] = info_dict['id']
  799. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  800. # Working around negative timestamps in Windows
  801. # (see http://bugs.python.org/issue1646728)
  802. if info_dict['timestamp'] < 0 and os.name == 'nt':
  803. info_dict['timestamp'] = 0
  804. upload_date = datetime.datetime.utcfromtimestamp(
  805. info_dict['timestamp'])
  806. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  807. # This extractors handle format selection themselves
  808. if info_dict['extractor'] in ['Youku']:
  809. if download:
  810. self.process_info(info_dict)
  811. return info_dict
  812. # We now pick which formats have to be downloaded
  813. if info_dict.get('formats') is None:
  814. # There's only one format available
  815. formats = [info_dict]
  816. else:
  817. formats = info_dict['formats']
  818. if not formats:
  819. raise ExtractorError('No video formats found!')
  820. # We check that all the formats have the format and format_id fields
  821. for i, format in enumerate(formats):
  822. if 'url' not in format:
  823. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  824. if format.get('format_id') is None:
  825. format['format_id'] = compat_str(i)
  826. if format.get('format') is None:
  827. format['format'] = '{id} - {res}{note}'.format(
  828. id=format['format_id'],
  829. res=self.format_resolution(format),
  830. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  831. )
  832. # Automatically determine file extension if missing
  833. if 'ext' not in format:
  834. format['ext'] = determine_ext(format['url']).lower()
  835. format_limit = self.params.get('format_limit', None)
  836. if format_limit:
  837. formats = list(takewhile_inclusive(
  838. lambda f: f['format_id'] != format_limit, formats
  839. ))
  840. # TODO Central sorting goes here
  841. if formats[0] is not info_dict:
  842. # only set the 'formats' fields if the original info_dict list them
  843. # otherwise we end up with a circular reference, the first (and unique)
  844. # element in the 'formats' field in info_dict is info_dict itself,
  845. # wich can't be exported to json
  846. info_dict['formats'] = formats
  847. if self.params.get('listformats', None):
  848. self.list_formats(info_dict)
  849. return
  850. req_format = self.params.get('format')
  851. if req_format is None:
  852. req_format = 'best'
  853. formats_to_download = []
  854. # The -1 is for supporting YoutubeIE
  855. if req_format in ('-1', 'all'):
  856. formats_to_download = formats
  857. else:
  858. for rfstr in req_format.split(','):
  859. # We can accept formats requested in the format: 34/5/best, we pick
  860. # the first that is available, starting from left
  861. req_formats = rfstr.split('/')
  862. for rf in req_formats:
  863. if re.match(r'.+?\+.+?', rf) is not None:
  864. # Two formats have been requested like '137+139'
  865. format_1, format_2 = rf.split('+')
  866. formats_info = (self.select_format(format_1, formats),
  867. self.select_format(format_2, formats))
  868. if all(formats_info):
  869. # The first format must contain the video and the
  870. # second the audio
  871. if formats_info[0].get('vcodec') == 'none':
  872. self.report_error('The first format must '
  873. 'contain the video, try using '
  874. '"-f %s+%s"' % (format_2, format_1))
  875. return
  876. output_ext = (
  877. formats_info[0]['ext']
  878. if self.params.get('merge_output_format') is None
  879. else self.params['merge_output_format'])
  880. selected_format = {
  881. 'requested_formats': formats_info,
  882. 'format': rf,
  883. 'ext': formats_info[0]['ext'],
  884. 'width': formats_info[0].get('width'),
  885. 'height': formats_info[0].get('height'),
  886. 'resolution': formats_info[0].get('resolution'),
  887. 'fps': formats_info[0].get('fps'),
  888. 'vcodec': formats_info[0].get('vcodec'),
  889. 'vbr': formats_info[0].get('vbr'),
  890. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  891. 'acodec': formats_info[1].get('acodec'),
  892. 'abr': formats_info[1].get('abr'),
  893. 'ext': output_ext,
  894. }
  895. else:
  896. selected_format = None
  897. else:
  898. selected_format = self.select_format(rf, formats)
  899. if selected_format is not None:
  900. formats_to_download.append(selected_format)
  901. break
  902. if not formats_to_download:
  903. raise ExtractorError('requested format not available',
  904. expected=True)
  905. if download:
  906. if len(formats_to_download) > 1:
  907. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  908. for format in formats_to_download:
  909. new_info = dict(info_dict)
  910. new_info.update(format)
  911. self.process_info(new_info)
  912. # We update the info dict with the best quality format (backwards compatibility)
  913. info_dict.update(formats_to_download[-1])
  914. return info_dict
  915. def process_info(self, info_dict):
  916. """Process a single resolved IE result."""
  917. assert info_dict.get('_type', 'video') == 'video'
  918. max_downloads = self.params.get('max_downloads')
  919. if max_downloads is not None:
  920. if self._num_downloads >= int(max_downloads):
  921. raise MaxDownloadsReached()
  922. info_dict['fulltitle'] = info_dict['title']
  923. if len(info_dict['title']) > 200:
  924. info_dict['title'] = info_dict['title'][:197] + '...'
  925. # Keep for backwards compatibility
  926. info_dict['stitle'] = info_dict['title']
  927. if 'format' not in info_dict:
  928. info_dict['format'] = info_dict['ext']
  929. reason = self._match_entry(info_dict)
  930. if reason is not None:
  931. self.to_screen('[download] ' + reason)
  932. return
  933. self._num_downloads += 1
  934. filename = self.prepare_filename(info_dict)
  935. # Forced printings
  936. if self.params.get('forcetitle', False):
  937. self.to_stdout(info_dict['fulltitle'])
  938. if self.params.get('forceid', False):
  939. self.to_stdout(info_dict['id'])
  940. if self.params.get('forceurl', False):
  941. if info_dict.get('requested_formats') is not None:
  942. for f in info_dict['requested_formats']:
  943. self.to_stdout(f['url'] + f.get('play_path', ''))
  944. else:
  945. # For RTMP URLs, also include the playpath
  946. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  947. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  948. self.to_stdout(info_dict['thumbnail'])
  949. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  950. self.to_stdout(info_dict['description'])
  951. if self.params.get('forcefilename', False) and filename is not None:
  952. self.to_stdout(filename)
  953. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  954. self.to_stdout(formatSeconds(info_dict['duration']))
  955. if self.params.get('forceformat', False):
  956. self.to_stdout(info_dict['format'])
  957. if self.params.get('forcejson', False):
  958. info_dict['_filename'] = filename
  959. self.to_stdout(json.dumps(info_dict))
  960. if self.params.get('dump_single_json', False):
  961. info_dict['_filename'] = filename
  962. # Do nothing else if in simulate mode
  963. if self.params.get('simulate', False):
  964. return
  965. if filename is None:
  966. return
  967. try:
  968. dn = os.path.dirname(encodeFilename(filename))
  969. if dn and not os.path.exists(dn):
  970. os.makedirs(dn)
  971. except (OSError, IOError) as err:
  972. self.report_error('unable to create directory ' + compat_str(err))
  973. return
  974. if self.params.get('writedescription', False):
  975. descfn = filename + '.description'
  976. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  977. self.to_screen('[info] Video description is already present')
  978. elif info_dict.get('description') is None:
  979. self.report_warning('There\'s no description to write.')
  980. else:
  981. try:
  982. self.to_screen('[info] Writing video description to: ' + descfn)
  983. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  984. descfile.write(info_dict['description'])
  985. except (OSError, IOError):
  986. self.report_error('Cannot write description file ' + descfn)
  987. return
  988. if self.params.get('writeannotations', False):
  989. annofn = filename + '.annotations.xml'
  990. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  991. self.to_screen('[info] Video annotations are already present')
  992. else:
  993. try:
  994. self.to_screen('[info] Writing video annotations to: ' + annofn)
  995. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  996. annofile.write(info_dict['annotations'])
  997. except (KeyError, TypeError):
  998. self.report_warning('There are no annotations to write.')
  999. except (OSError, IOError):
  1000. self.report_error('Cannot write annotations file: ' + annofn)
  1001. return
  1002. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1003. self.params.get('writeautomaticsub')])
  1004. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  1005. # subtitles download errors are already managed as troubles in relevant IE
  1006. # that way it will silently go on when used with unsupporting IE
  1007. subtitles = info_dict['subtitles']
  1008. sub_format = self.params.get('subtitlesformat', 'srt')
  1009. for sub_lang in subtitles.keys():
  1010. sub = subtitles[sub_lang]
  1011. if sub is None:
  1012. continue
  1013. try:
  1014. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1015. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1016. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1017. else:
  1018. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1019. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1020. subfile.write(sub)
  1021. except (OSError, IOError):
  1022. self.report_error('Cannot write subtitles file ' + sub_filename)
  1023. return
  1024. if self.params.get('writeinfojson', False):
  1025. infofn = os.path.splitext(filename)[0] + '.info.json'
  1026. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1027. self.to_screen('[info] Video description metadata is already present')
  1028. else:
  1029. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1030. try:
  1031. write_json_file(info_dict, infofn)
  1032. except (OSError, IOError):
  1033. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1034. return
  1035. if self.params.get('writethumbnail', False):
  1036. if info_dict.get('thumbnail') is not None:
  1037. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  1038. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  1039. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1040. self.to_screen('[%s] %s: Thumbnail is already present' %
  1041. (info_dict['extractor'], info_dict['id']))
  1042. else:
  1043. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  1044. (info_dict['extractor'], info_dict['id']))
  1045. try:
  1046. uf = self.urlopen(info_dict['thumbnail'])
  1047. with open(thumb_filename, 'wb') as thumbf:
  1048. shutil.copyfileobj(uf, thumbf)
  1049. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  1050. (info_dict['extractor'], info_dict['id'], thumb_filename))
  1051. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1052. self.report_warning('Unable to download thumbnail "%s": %s' %
  1053. (info_dict['thumbnail'], compat_str(err)))
  1054. if not self.params.get('skip_download', False):
  1055. try:
  1056. def dl(name, info):
  1057. fd = get_suitable_downloader(info)(self, self.params)
  1058. for ph in self._progress_hooks:
  1059. fd.add_progress_hook(ph)
  1060. if self.params.get('verbose'):
  1061. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1062. return fd.download(name, info)
  1063. if info_dict.get('requested_formats') is not None:
  1064. downloaded = []
  1065. success = True
  1066. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1067. if not merger._executable:
  1068. postprocessors = []
  1069. self.report_warning('You have requested multiple '
  1070. 'formats but ffmpeg or avconv are not installed.'
  1071. ' The formats won\'t be merged')
  1072. else:
  1073. postprocessors = [merger]
  1074. for f in info_dict['requested_formats']:
  1075. new_info = dict(info_dict)
  1076. new_info.update(f)
  1077. fname = self.prepare_filename(new_info)
  1078. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1079. downloaded.append(fname)
  1080. partial_success = dl(fname, new_info)
  1081. success = success and partial_success
  1082. info_dict['__postprocessors'] = postprocessors
  1083. info_dict['__files_to_merge'] = downloaded
  1084. else:
  1085. # Just a single file
  1086. success = dl(filename, info_dict)
  1087. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1088. self.report_error('unable to download video data: %s' % str(err))
  1089. return
  1090. except (OSError, IOError) as err:
  1091. raise UnavailableVideoError(err)
  1092. except (ContentTooShortError, ) as err:
  1093. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1094. return
  1095. if success:
  1096. # Fixup content
  1097. fixup_policy = self.params.get('fixup')
  1098. if fixup_policy is None:
  1099. fixup_policy = 'detect_or_warn'
  1100. stretched_ratio = info_dict.get('stretched_ratio')
  1101. if stretched_ratio is not None and stretched_ratio != 1:
  1102. if fixup_policy == 'warn':
  1103. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1104. info_dict['id'], stretched_ratio))
  1105. elif fixup_policy == 'detect_or_warn':
  1106. stretched_pp = FFmpegFixupStretchedPP(self)
  1107. if stretched_pp.available:
  1108. info_dict.setdefault('__postprocessors', [])
  1109. info_dict['__postprocessors'].append(stretched_pp)
  1110. else:
  1111. self.report_warning(
  1112. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1113. info_dict['id'], stretched_ratio))
  1114. else:
  1115. assert fixup_policy in ('ignore', 'never')
  1116. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1117. if fixup_policy == 'warn':
  1118. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1119. info_dict['id']))
  1120. elif fixup_policy == 'detect_or_warn':
  1121. fixup_pp = FFmpegFixupM4aPP(self)
  1122. if fixup_pp.available:
  1123. info_dict.setdefault('__postprocessors', [])
  1124. info_dict['__postprocessors'].append(fixup_pp)
  1125. else:
  1126. self.report_warning(
  1127. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1128. info_dict['id']))
  1129. else:
  1130. assert fixup_policy in ('ignore', 'never')
  1131. try:
  1132. self.post_process(filename, info_dict)
  1133. except (PostProcessingError) as err:
  1134. self.report_error('postprocessing: %s' % str(err))
  1135. return
  1136. self.record_download_archive(info_dict)
  1137. def download(self, url_list):
  1138. """Download a given list of URLs."""
  1139. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1140. if (len(url_list) > 1 and
  1141. '%' not in outtmpl
  1142. and self.params.get('max_downloads') != 1):
  1143. raise SameFileError(outtmpl)
  1144. for url in url_list:
  1145. try:
  1146. # It also downloads the videos
  1147. res = self.extract_info(url)
  1148. except UnavailableVideoError:
  1149. self.report_error('unable to download video')
  1150. except MaxDownloadsReached:
  1151. self.to_screen('[info] Maximum number of downloaded files reached.')
  1152. raise
  1153. else:
  1154. if self.params.get('dump_single_json', False):
  1155. self.to_stdout(json.dumps(res))
  1156. return self._download_retcode
  1157. def download_with_info_file(self, info_filename):
  1158. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1159. info = json.load(f)
  1160. try:
  1161. self.process_ie_result(info, download=True)
  1162. except DownloadError:
  1163. webpage_url = info.get('webpage_url')
  1164. if webpage_url is not None:
  1165. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1166. return self.download([webpage_url])
  1167. else:
  1168. raise
  1169. return self._download_retcode
  1170. def post_process(self, filename, ie_info):
  1171. """Run all the postprocessors on the given file."""
  1172. info = dict(ie_info)
  1173. info['filepath'] = filename
  1174. pps_chain = []
  1175. if ie_info.get('__postprocessors') is not None:
  1176. pps_chain.extend(ie_info['__postprocessors'])
  1177. pps_chain.extend(self._pps)
  1178. for pp in pps_chain:
  1179. keep_video = None
  1180. old_filename = info['filepath']
  1181. try:
  1182. keep_video_wish, info = pp.run(info)
  1183. if keep_video_wish is not None:
  1184. if keep_video_wish:
  1185. keep_video = keep_video_wish
  1186. elif keep_video is None:
  1187. # No clear decision yet, let IE decide
  1188. keep_video = keep_video_wish
  1189. except PostProcessingError as e:
  1190. self.report_error(e.msg)
  1191. if keep_video is False and not self.params.get('keepvideo', False):
  1192. try:
  1193. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1194. os.remove(encodeFilename(old_filename))
  1195. except (IOError, OSError):
  1196. self.report_warning('Unable to remove downloaded video file')
  1197. def _make_archive_id(self, info_dict):
  1198. # Future-proof against any change in case
  1199. # and backwards compatibility with prior versions
  1200. extractor = info_dict.get('extractor_key')
  1201. if extractor is None:
  1202. if 'id' in info_dict:
  1203. extractor = info_dict.get('ie_key') # key in a playlist
  1204. if extractor is None:
  1205. return None # Incomplete video information
  1206. return extractor.lower() + ' ' + info_dict['id']
  1207. def in_download_archive(self, info_dict):
  1208. fn = self.params.get('download_archive')
  1209. if fn is None:
  1210. return False
  1211. vid_id = self._make_archive_id(info_dict)
  1212. if vid_id is None:
  1213. return False # Incomplete video information
  1214. try:
  1215. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1216. for line in archive_file:
  1217. if line.strip() == vid_id:
  1218. return True
  1219. except IOError as ioe:
  1220. if ioe.errno != errno.ENOENT:
  1221. raise
  1222. return False
  1223. def record_download_archive(self, info_dict):
  1224. fn = self.params.get('download_archive')
  1225. if fn is None:
  1226. return
  1227. vid_id = self._make_archive_id(info_dict)
  1228. assert vid_id
  1229. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1230. archive_file.write(vid_id + '\n')
  1231. @staticmethod
  1232. def format_resolution(format, default='unknown'):
  1233. if format.get('vcodec') == 'none':
  1234. return 'audio only'
  1235. if format.get('resolution') is not None:
  1236. return format['resolution']
  1237. if format.get('height') is not None:
  1238. if format.get('width') is not None:
  1239. res = '%sx%s' % (format['width'], format['height'])
  1240. else:
  1241. res = '%sp' % format['height']
  1242. elif format.get('width') is not None:
  1243. res = '?x%d' % format['width']
  1244. else:
  1245. res = default
  1246. return res
  1247. def _format_note(self, fdict):
  1248. res = ''
  1249. if fdict.get('ext') in ['f4f', 'f4m']:
  1250. res += '(unsupported) '
  1251. if fdict.get('format_note') is not None:
  1252. res += fdict['format_note'] + ' '
  1253. if fdict.get('tbr') is not None:
  1254. res += '%4dk ' % fdict['tbr']
  1255. if fdict.get('container') is not None:
  1256. if res:
  1257. res += ', '
  1258. res += '%s container' % fdict['container']
  1259. if (fdict.get('vcodec') is not None and
  1260. fdict.get('vcodec') != 'none'):
  1261. if res:
  1262. res += ', '
  1263. res += fdict['vcodec']
  1264. if fdict.get('vbr') is not None:
  1265. res += '@'
  1266. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1267. res += 'video@'
  1268. if fdict.get('vbr') is not None:
  1269. res += '%4dk' % fdict['vbr']
  1270. if fdict.get('fps') is not None:
  1271. res += ', %sfps' % fdict['fps']
  1272. if fdict.get('acodec') is not None:
  1273. if res:
  1274. res += ', '
  1275. if fdict['acodec'] == 'none':
  1276. res += 'video only'
  1277. else:
  1278. res += '%-5s' % fdict['acodec']
  1279. elif fdict.get('abr') is not None:
  1280. if res:
  1281. res += ', '
  1282. res += 'audio'
  1283. if fdict.get('abr') is not None:
  1284. res += '@%3dk' % fdict['abr']
  1285. if fdict.get('asr') is not None:
  1286. res += ' (%5dHz)' % fdict['asr']
  1287. if fdict.get('filesize') is not None:
  1288. if res:
  1289. res += ', '
  1290. res += format_bytes(fdict['filesize'])
  1291. elif fdict.get('filesize_approx') is not None:
  1292. if res:
  1293. res += ', '
  1294. res += '~' + format_bytes(fdict['filesize_approx'])
  1295. return res
  1296. def list_formats(self, info_dict):
  1297. def line(format, idlen=20):
  1298. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1299. format['format_id'],
  1300. format['ext'],
  1301. self.format_resolution(format),
  1302. self._format_note(format),
  1303. ))
  1304. formats = info_dict.get('formats', [info_dict])
  1305. idlen = max(len('format code'),
  1306. max(len(f['format_id']) for f in formats))
  1307. formats_s = [
  1308. line(f, idlen) for f in formats
  1309. if f.get('preference') is None or f['preference'] >= -1000]
  1310. if len(formats) > 1:
  1311. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1312. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1313. header_line = line({
  1314. 'format_id': 'format code', 'ext': 'extension',
  1315. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1316. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1317. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1318. def urlopen(self, req):
  1319. """ Start an HTTP download """
  1320. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1321. # always respected by websites, some tend to give out URLs with non percent-encoded
  1322. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1323. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1324. # To work around aforementioned issue we will replace request's original URL with
  1325. # percent-encoded one
  1326. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1327. url = req if req_is_string else req.get_full_url()
  1328. url_escaped = escape_url(url)
  1329. # Substitute URL if any change after escaping
  1330. if url != url_escaped:
  1331. if req_is_string:
  1332. req = url_escaped
  1333. else:
  1334. req = compat_urllib_request.Request(
  1335. url_escaped, data=req.data, headers=req.headers,
  1336. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1337. return self._opener.open(req, timeout=self._socket_timeout)
  1338. def print_debug_header(self):
  1339. if not self.params.get('verbose'):
  1340. return
  1341. if type('') is not compat_str:
  1342. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1343. self.report_warning(
  1344. 'Your Python is broken! Update to a newer and supported version')
  1345. stdout_encoding = getattr(
  1346. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1347. encoding_str = (
  1348. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1349. locale.getpreferredencoding(),
  1350. sys.getfilesystemencoding(),
  1351. stdout_encoding,
  1352. self.get_encoding()))
  1353. write_string(encoding_str, encoding=None)
  1354. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1355. try:
  1356. sp = subprocess.Popen(
  1357. ['git', 'rev-parse', '--short', 'HEAD'],
  1358. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1359. cwd=os.path.dirname(os.path.abspath(__file__)))
  1360. out, err = sp.communicate()
  1361. out = out.decode().strip()
  1362. if re.match('[0-9a-f]+', out):
  1363. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1364. except:
  1365. try:
  1366. sys.exc_clear()
  1367. except:
  1368. pass
  1369. self._write_string('[debug] Python version %s - %s\n' % (
  1370. platform.python_version(), platform_name()))
  1371. exe_versions = FFmpegPostProcessor.get_versions()
  1372. exe_versions['rtmpdump'] = rtmpdump_version()
  1373. exe_str = ', '.join(
  1374. '%s %s' % (exe, v)
  1375. for exe, v in sorted(exe_versions.items())
  1376. if v
  1377. )
  1378. if not exe_str:
  1379. exe_str = 'none'
  1380. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1381. proxy_map = {}
  1382. for handler in self._opener.handlers:
  1383. if hasattr(handler, 'proxies'):
  1384. proxy_map.update(handler.proxies)
  1385. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1386. if self.params.get('call_home', False):
  1387. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1388. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1389. latest_version = self.urlopen(
  1390. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1391. if version_tuple(latest_version) > version_tuple(__version__):
  1392. self.report_warning(
  1393. 'You are using an outdated version (newest version: %s)! '
  1394. 'See https://yt-dl.org/update if you need help updating.' %
  1395. latest_version)
  1396. def _setup_opener(self):
  1397. timeout_val = self.params.get('socket_timeout')
  1398. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1399. opts_cookiefile = self.params.get('cookiefile')
  1400. opts_proxy = self.params.get('proxy')
  1401. if opts_cookiefile is None:
  1402. self.cookiejar = compat_cookiejar.CookieJar()
  1403. else:
  1404. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1405. opts_cookiefile)
  1406. if os.access(opts_cookiefile, os.R_OK):
  1407. self.cookiejar.load()
  1408. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1409. self.cookiejar)
  1410. if opts_proxy is not None:
  1411. if opts_proxy == '':
  1412. proxies = {}
  1413. else:
  1414. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1415. else:
  1416. proxies = compat_urllib_request.getproxies()
  1417. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1418. if 'http' in proxies and 'https' not in proxies:
  1419. proxies['https'] = proxies['http']
  1420. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1421. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1422. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1423. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1424. opener = compat_urllib_request.build_opener(
  1425. https_handler, proxy_handler, cookie_processor, ydlh)
  1426. # Delete the default user-agent header, which would otherwise apply in
  1427. # cases where our custom HTTP handler doesn't come into play
  1428. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1429. opener.addheaders = []
  1430. self._opener = opener
  1431. def encode(self, s):
  1432. if isinstance(s, bytes):
  1433. return s # Already encoded
  1434. try:
  1435. return s.encode(self.get_encoding())
  1436. except UnicodeEncodeError as err:
  1437. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1438. raise
  1439. def get_encoding(self):
  1440. encoding = self.params.get('encoding')
  1441. if encoding is None:
  1442. encoding = preferredencoding()
  1443. return encoding