external.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. from __future__ import unicode_literals
  2. import os
  3. import re
  4. import subprocess
  5. import sys
  6. import tempfile
  7. import time
  8. from .common import FileDownloader
  9. from ..compat import (
  10. compat_setenv,
  11. compat_str,
  12. )
  13. from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
  14. from ..utils import (
  15. cli_option,
  16. cli_valueless_option,
  17. cli_bool_option,
  18. cli_configuration_args,
  19. encodeFilename,
  20. encodeArgument,
  21. handle_youtubedl_headers,
  22. check_executable,
  23. is_outdated_version,
  24. process_communicate_or_kill,
  25. T,
  26. traverse_obj,
  27. )
  28. class ExternalFD(FileDownloader):
  29. def real_download(self, filename, info_dict):
  30. self.report_destination(filename)
  31. tmpfilename = self.temp_name(filename)
  32. self._cookies_tempfile = None
  33. try:
  34. started = time.time()
  35. retval = self._call_downloader(tmpfilename, info_dict)
  36. except KeyboardInterrupt:
  37. if not info_dict.get('is_live'):
  38. raise
  39. # Live stream downloading cancellation should be considered as
  40. # correct and expected termination thus all postprocessing
  41. # should take place
  42. retval = 0
  43. self.to_screen('[%s] Interrupted by user' % self.get_basename())
  44. finally:
  45. if self._cookies_tempfile and os.path.isfile(self._cookies_tempfile):
  46. try:
  47. os.remove(self._cookies_tempfile)
  48. except OSError:
  49. self.report_warning(
  50. 'Unable to delete temporary cookies file "{0}"'.format(self._cookies_tempfile))
  51. if retval == 0:
  52. status = {
  53. 'filename': filename,
  54. 'status': 'finished',
  55. 'elapsed': time.time() - started,
  56. }
  57. if filename != '-':
  58. fsize = os.path.getsize(encodeFilename(tmpfilename))
  59. self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
  60. self.try_rename(tmpfilename, filename)
  61. status.update({
  62. 'downloaded_bytes': fsize,
  63. 'total_bytes': fsize,
  64. })
  65. self._hook_progress(status)
  66. return True
  67. else:
  68. self.to_stderr('\n')
  69. self.report_error('%s exited with code %d' % (
  70. self.get_basename(), retval))
  71. return False
  72. @classmethod
  73. def get_basename(cls):
  74. return cls.__name__[:-2].lower()
  75. @property
  76. def exe(self):
  77. return self.params.get('external_downloader')
  78. @classmethod
  79. def available(cls):
  80. return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
  81. @classmethod
  82. def supports(cls, info_dict):
  83. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
  84. @classmethod
  85. def can_download(cls, info_dict):
  86. return cls.available() and cls.supports(info_dict)
  87. def _option(self, command_option, param):
  88. return cli_option(self.params, command_option, param)
  89. def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
  90. return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
  91. def _valueless_option(self, command_option, param, expected_value=True):
  92. return cli_valueless_option(self.params, command_option, param, expected_value)
  93. def _configuration_args(self, default=[]):
  94. return cli_configuration_args(self.params, 'external_downloader_args', default)
  95. def _write_cookies(self):
  96. if not self.ydl.cookiejar.filename:
  97. tmp_cookies = tempfile.NamedTemporaryFile(suffix='.cookies', delete=False)
  98. tmp_cookies.close()
  99. self._cookies_tempfile = tmp_cookies.name
  100. self.to_screen('[download] Writing temporary cookies file to "{0}"'.format(self._cookies_tempfile))
  101. # real_download resets _cookies_tempfile; if it's None, save() will write to cookiejar.filename
  102. self.ydl.cookiejar.save(self._cookies_tempfile, ignore_discard=True, ignore_expires=True)
  103. return self.ydl.cookiejar.filename or self._cookies_tempfile
  104. def _call_downloader(self, tmpfilename, info_dict):
  105. """ Either overwrite this or implement _make_cmd """
  106. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  107. self._debug_cmd(cmd)
  108. p = subprocess.Popen(
  109. cmd, stderr=subprocess.PIPE)
  110. _, stderr = process_communicate_or_kill(p)
  111. if p.returncode != 0:
  112. self.to_stderr(stderr.decode('utf-8', 'replace'))
  113. return p.returncode
  114. @staticmethod
  115. def _header_items(info_dict):
  116. return traverse_obj(
  117. info_dict, ('http_headers', T(dict.items), Ellipsis))
  118. class CurlFD(ExternalFD):
  119. AVAILABLE_OPT = '-V'
  120. def _make_cmd(self, tmpfilename, info_dict):
  121. cmd = [self.exe, '--location', '-o', tmpfilename, '--compressed']
  122. cookie_header = self.ydl.cookiejar.get_cookie_header(info_dict['url'])
  123. if cookie_header:
  124. cmd += ['--cookie', cookie_header]
  125. for key, val in self._header_items(info_dict):
  126. cmd += ['--header', '%s: %s' % (key, val)]
  127. cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
  128. cmd += self._valueless_option('--silent', 'noprogress')
  129. cmd += self._valueless_option('--verbose', 'verbose')
  130. cmd += self._option('--limit-rate', 'ratelimit')
  131. retry = self._option('--retry', 'retries')
  132. if len(retry) == 2:
  133. if retry[1] in ('inf', 'infinite'):
  134. retry[1] = '2147483647'
  135. cmd += retry
  136. cmd += self._option('--max-filesize', 'max_filesize')
  137. cmd += self._option('--interface', 'source_address')
  138. cmd += self._option('--proxy', 'proxy')
  139. cmd += self._valueless_option('--insecure', 'nocheckcertificate')
  140. cmd += self._configuration_args()
  141. cmd += ['--', info_dict['url']]
  142. return cmd
  143. def _call_downloader(self, tmpfilename, info_dict):
  144. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  145. self._debug_cmd(cmd)
  146. # curl writes the progress to stderr so don't capture it.
  147. p = subprocess.Popen(cmd)
  148. process_communicate_or_kill(p)
  149. return p.returncode
  150. class AxelFD(ExternalFD):
  151. AVAILABLE_OPT = '-V'
  152. def _make_cmd(self, tmpfilename, info_dict):
  153. cmd = [self.exe, '-o', tmpfilename]
  154. for key, val in self._header_items(info_dict):
  155. cmd += ['-H', '%s: %s' % (key, val)]
  156. cookie_header = self.ydl.cookiejar.get_cookie_header(info_dict['url'])
  157. if cookie_header:
  158. cmd += ['-H', 'Cookie: {0}'.format(cookie_header), '--max-redirect=0']
  159. cmd += self._configuration_args()
  160. cmd += ['--', info_dict['url']]
  161. return cmd
  162. class WgetFD(ExternalFD):
  163. AVAILABLE_OPT = '--version'
  164. def _make_cmd(self, tmpfilename, info_dict):
  165. cmd = [self.exe, '-O', tmpfilename, '-nv', '--compression=auto']
  166. if self.ydl.cookiejar.get_cookie_header(info_dict['url']):
  167. cmd += ['--load-cookies', self._write_cookies()]
  168. for key, val in self._header_items(info_dict):
  169. cmd += ['--header', '%s: %s' % (key, val)]
  170. cmd += self._option('--limit-rate', 'ratelimit')
  171. retry = self._option('--tries', 'retries')
  172. if len(retry) == 2:
  173. if retry[1] in ('inf', 'infinite'):
  174. retry[1] = '0'
  175. cmd += retry
  176. cmd += self._option('--bind-address', 'source_address')
  177. cmd += self._option('--proxy', 'proxy')
  178. cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
  179. cmd += self._configuration_args()
  180. cmd += ['--', info_dict['url']]
  181. return cmd
  182. class Aria2cFD(ExternalFD):
  183. AVAILABLE_OPT = '-v'
  184. @staticmethod
  185. def _aria2c_filename(fn):
  186. return fn if os.path.isabs(fn) else os.path.join('.', fn)
  187. def _make_cmd(self, tmpfilename, info_dict):
  188. cmd = [self.exe, '-c',
  189. '--console-log-level=warn', '--summary-interval=0', '--download-result=hide',
  190. '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16']
  191. if 'fragments' in info_dict:
  192. cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true']
  193. else:
  194. cmd += ['--min-split-size', '1M']
  195. if self.ydl.cookiejar.get_cookie_header(info_dict['url']):
  196. cmd += ['--load-cookies={0}'.format(self._write_cookies())]
  197. for key, val in self._header_items(info_dict):
  198. cmd += ['--header', '%s: %s' % (key, val)]
  199. cmd += self._configuration_args(['--max-connection-per-server', '4'])
  200. cmd += ['--out', os.path.basename(tmpfilename)]
  201. cmd += self._option('--max-overall-download-limit', 'ratelimit')
  202. cmd += self._option('--interface', 'source_address')
  203. cmd += self._option('--all-proxy', 'proxy')
  204. cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
  205. cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
  206. cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=')
  207. cmd += self._configuration_args()
  208. # aria2c strips out spaces from the beginning/end of filenames and paths.
  209. # We work around this issue by adding a "./" to the beginning of the
  210. # filename and relative path, and adding a "/" at the end of the path.
  211. # See: https://github.com/yt-dlp/yt-dlp/issues/276
  212. # https://github.com/ytdl-org/youtube-dl/issues/20312
  213. # https://github.com/aria2/aria2/issues/1373
  214. dn = os.path.dirname(tmpfilename)
  215. if dn:
  216. cmd += ['--dir', self._aria2c_filename(dn) + os.path.sep]
  217. if 'fragments' not in info_dict:
  218. cmd += ['--out', self._aria2c_filename(os.path.basename(tmpfilename))]
  219. cmd += ['--auto-file-renaming=false']
  220. if 'fragments' in info_dict:
  221. cmd += ['--file-allocation=none', '--uri-selector=inorder']
  222. url_list_file = '%s.frag.urls' % (tmpfilename, )
  223. url_list = []
  224. for frag_index, fragment in enumerate(info_dict['fragments']):
  225. fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index)
  226. url_list.append('%s\n\tout=%s' % (fragment['url'], self._aria2c_filename(fragment_filename)))
  227. stream, _ = self.sanitize_open(url_list_file, 'wb')
  228. stream.write('\n'.join(url_list).encode())
  229. stream.close()
  230. cmd += ['-i', self._aria2c_filename(url_list_file)]
  231. else:
  232. cmd += ['--', info_dict['url']]
  233. return cmd
  234. class Aria2pFD(ExternalFD):
  235. ''' Aria2pFD class
  236. This class support to use aria2p as downloader.
  237. (Aria2p, a command-line tool and Python library to interact with an aria2c daemon process
  238. through JSON-RPC.)
  239. It can help you to get download progress more easily.
  240. To use aria2p as downloader, you need to install aria2c and aria2p, aria2p can download with pip.
  241. Then run aria2c in the background and enable with the --enable-rpc option.
  242. '''
  243. try:
  244. import aria2p
  245. __avail = True
  246. except ImportError:
  247. __avail = False
  248. @classmethod
  249. def available(cls):
  250. return cls.__avail
  251. def _call_downloader(self, tmpfilename, info_dict):
  252. aria2 = self.aria2p.API(
  253. self.aria2p.Client(
  254. host='http://localhost',
  255. port=6800,
  256. secret=''
  257. )
  258. )
  259. options = {
  260. 'min-split-size': '1M',
  261. 'max-connection-per-server': 4,
  262. 'auto-file-renaming': 'false',
  263. }
  264. options['dir'] = os.path.dirname(tmpfilename) or os.path.abspath('.')
  265. options['out'] = os.path.basename(tmpfilename)
  266. if self.ydl.cookiejar.get_cookie_header(info_dict['url']):
  267. options['load-cookies'] = self._write_cookies()
  268. options['header'] = []
  269. for key, val in self._header_items(info_dict):
  270. options['header'].append('{0}: {1}'.format(key, val))
  271. download = aria2.add_uris([info_dict['url']], options)
  272. status = {
  273. 'status': 'downloading',
  274. 'tmpfilename': tmpfilename,
  275. }
  276. started = time.time()
  277. while download.status in ['active', 'waiting']:
  278. download = aria2.get_download(download.gid)
  279. status.update({
  280. 'downloaded_bytes': download.completed_length,
  281. 'total_bytes': download.total_length,
  282. 'elapsed': time.time() - started,
  283. 'eta': download.eta.total_seconds(),
  284. 'speed': download.download_speed,
  285. })
  286. self._hook_progress(status)
  287. time.sleep(.5)
  288. return download.status != 'complete'
  289. class HttpieFD(ExternalFD):
  290. @classmethod
  291. def available(cls):
  292. return check_executable('http', ['--version'])
  293. def _make_cmd(self, tmpfilename, info_dict):
  294. cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
  295. for key, val in self._header_items(info_dict):
  296. cmd += ['%s:%s' % (key, val)]
  297. # httpie 3.1.0+ removes the Cookie header on redirect, so this should be safe for now. [1]
  298. # If we ever need cookie handling for redirects, we can export the cookiejar into a session. [2]
  299. # 1: https://github.com/httpie/httpie/security/advisories/GHSA-9w4w-cpc8-h2fq
  300. # 2: https://httpie.io/docs/cli/sessions
  301. cookie_header = self.ydl.cookiejar.get_cookie_header(info_dict['url'])
  302. if cookie_header:
  303. cmd += ['Cookie:%s' % cookie_header]
  304. return cmd
  305. class FFmpegFD(ExternalFD):
  306. @classmethod
  307. def supports(cls, info_dict):
  308. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms', 'http_dash_segments')
  309. @classmethod
  310. def available(cls):
  311. return FFmpegPostProcessor().available
  312. def _call_downloader(self, tmpfilename, info_dict):
  313. url = info_dict['url']
  314. ffpp = FFmpegPostProcessor(downloader=self)
  315. if not ffpp.available:
  316. self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
  317. return False
  318. ffpp.check_version()
  319. args = [ffpp.executable, '-y']
  320. for log_level in ('quiet', 'verbose'):
  321. if self.params.get(log_level, False):
  322. args += ['-loglevel', log_level]
  323. break
  324. seekable = info_dict.get('_seekable')
  325. if seekable is not None:
  326. # setting -seekable prevents ffmpeg from guessing if the server
  327. # supports seeking(by adding the header `Range: bytes=0-`), which
  328. # can cause problems in some cases
  329. # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
  330. # http://trac.ffmpeg.org/ticket/6125#comment:10
  331. args += ['-seekable', '1' if seekable else '0']
  332. args += self._configuration_args()
  333. # start_time = info_dict.get('start_time') or 0
  334. # if start_time:
  335. # args += ['-ss', compat_str(start_time)]
  336. # end_time = info_dict.get('end_time')
  337. # if end_time:
  338. # args += ['-t', compat_str(end_time - start_time)]
  339. cookies = self.ydl.cookiejar.get_cookies_for_url(url)
  340. if cookies:
  341. args.extend(['-cookies', ''.join(
  342. '{0}={1}; path={2}; domain={3};\r\n'.format(
  343. cookie.name, cookie.value, cookie.path, cookie.domain)
  344. for cookie in cookies)])
  345. if info_dict.get('http_headers') and re.match(r'^https?://', url):
  346. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  347. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  348. headers = handle_youtubedl_headers(info_dict['http_headers'])
  349. args += [
  350. '-headers',
  351. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  352. env = None
  353. proxy = self.params.get('proxy')
  354. if proxy:
  355. if not re.match(r'^[\da-zA-Z]+://', proxy):
  356. proxy = 'http://%s' % proxy
  357. if proxy.startswith('socks'):
  358. self.report_warning(
  359. '%s does not support SOCKS proxies. Downloading is likely to fail. '
  360. 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
  361. # Since December 2015 ffmpeg supports -http_proxy option (see
  362. # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
  363. # We could switch to the following code if we are able to detect version properly
  364. # args += ['-http_proxy', proxy]
  365. env = os.environ.copy()
  366. compat_setenv('HTTP_PROXY', proxy, env=env)
  367. compat_setenv('http_proxy', proxy, env=env)
  368. protocol = info_dict.get('protocol')
  369. if protocol == 'rtmp':
  370. player_url = info_dict.get('player_url')
  371. page_url = info_dict.get('page_url')
  372. app = info_dict.get('app')
  373. play_path = info_dict.get('play_path')
  374. tc_url = info_dict.get('tc_url')
  375. flash_version = info_dict.get('flash_version')
  376. live = info_dict.get('rtmp_live', False)
  377. conn = info_dict.get('rtmp_conn')
  378. if player_url is not None:
  379. args += ['-rtmp_swfverify', player_url]
  380. if page_url is not None:
  381. args += ['-rtmp_pageurl', page_url]
  382. if app is not None:
  383. args += ['-rtmp_app', app]
  384. if play_path is not None:
  385. args += ['-rtmp_playpath', play_path]
  386. if tc_url is not None:
  387. args += ['-rtmp_tcurl', tc_url]
  388. if flash_version is not None:
  389. args += ['-rtmp_flashver', flash_version]
  390. if live:
  391. args += ['-rtmp_live', 'live']
  392. if isinstance(conn, list):
  393. for entry in conn:
  394. args += ['-rtmp_conn', entry]
  395. elif isinstance(conn, compat_str):
  396. args += ['-rtmp_conn', conn]
  397. args += ['-i', url, '-c', 'copy']
  398. if self.params.get('test', False):
  399. args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
  400. if protocol in ('m3u8', 'm3u8_native'):
  401. if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
  402. args += ['-f', 'mpegts']
  403. else:
  404. args += ['-f', 'mp4']
  405. if (ffpp.basename == 'ffmpeg' and is_outdated_version(ffpp._versions['ffmpeg'], '3.2', False)) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')):
  406. args += ['-bsf:a', 'aac_adtstoasc']
  407. elif protocol == 'rtmp':
  408. args += ['-f', 'flv']
  409. else:
  410. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  411. args = [encodeArgument(opt) for opt in args]
  412. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  413. self._debug_cmd(args)
  414. proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
  415. try:
  416. retval = proc.wait()
  417. except BaseException as e:
  418. # subprocess.run would send the SIGKILL signal to ffmpeg and the
  419. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  420. # produces a file that is playable (this is mostly useful for live
  421. # streams). Note that Windows is not affected and produces playable
  422. # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
  423. if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32':
  424. process_communicate_or_kill(proc, b'q')
  425. else:
  426. proc.kill()
  427. proc.wait()
  428. raise
  429. return retval
  430. class AVconvFD(FFmpegFD):
  431. pass
  432. _BY_NAME = dict(
  433. (klass.get_basename(), klass)
  434. for name, klass in globals().items()
  435. if name.endswith('FD') and name != 'ExternalFD'
  436. )
  437. def list_external_downloaders():
  438. return sorted(_BY_NAME.keys())
  439. def get_external_downloader(external_downloader):
  440. """ Given the name of the executable, see whether we support the given
  441. downloader . """
  442. # Drop .exe extension on Windows
  443. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  444. return _BY_NAME[bn]