external.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. from __future__ import unicode_literals
  2. import os.path
  3. import re
  4. import subprocess
  5. import sys
  6. import time
  7. from .common import FileDownloader
  8. from ..compat import (
  9. compat_setenv,
  10. compat_str,
  11. )
  12. from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
  13. from ..utils import (
  14. cli_option,
  15. cli_valueless_option,
  16. cli_bool_option,
  17. cli_configuration_args,
  18. encodeFilename,
  19. encodeArgument,
  20. handle_youtubedl_headers,
  21. check_executable,
  22. is_outdated_version,
  23. process_communicate_or_kill,
  24. )
  25. class ExternalFD(FileDownloader):
  26. def real_download(self, filename, info_dict):
  27. self.report_destination(filename)
  28. tmpfilename = self.temp_name(filename)
  29. try:
  30. started = time.time()
  31. retval = self._call_downloader(tmpfilename, info_dict)
  32. except KeyboardInterrupt:
  33. if not info_dict.get('is_live'):
  34. raise
  35. # Live stream downloading cancellation should be considered as
  36. # correct and expected termination thus all postprocessing
  37. # should take place
  38. retval = 0
  39. self.to_screen('[%s] Interrupted by user' % self.get_basename())
  40. if retval == 0:
  41. status = {
  42. 'filename': filename,
  43. 'status': 'finished',
  44. 'elapsed': time.time() - started,
  45. }
  46. if filename != '-':
  47. fsize = os.path.getsize(encodeFilename(tmpfilename))
  48. self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
  49. self.try_rename(tmpfilename, filename)
  50. status.update({
  51. 'downloaded_bytes': fsize,
  52. 'total_bytes': fsize,
  53. })
  54. self._hook_progress(status)
  55. return True
  56. else:
  57. self.to_stderr('\n')
  58. self.report_error('%s exited with code %d' % (
  59. self.get_basename(), retval))
  60. return False
  61. @classmethod
  62. def get_basename(cls):
  63. return cls.__name__[:-2].lower()
  64. @property
  65. def exe(self):
  66. return self.params.get('external_downloader')
  67. @classmethod
  68. def available(cls):
  69. return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
  70. @classmethod
  71. def supports(cls, info_dict):
  72. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
  73. @classmethod
  74. def can_download(cls, info_dict):
  75. return cls.available() and cls.supports(info_dict)
  76. def _option(self, command_option, param):
  77. return cli_option(self.params, command_option, param)
  78. def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
  79. return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
  80. def _valueless_option(self, command_option, param, expected_value=True):
  81. return cli_valueless_option(self.params, command_option, param, expected_value)
  82. def _configuration_args(self, default=[]):
  83. return cli_configuration_args(self.params, 'external_downloader_args', default)
  84. def _call_downloader(self, tmpfilename, info_dict):
  85. """ Either overwrite this or implement _make_cmd """
  86. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  87. self._debug_cmd(cmd)
  88. p = subprocess.Popen(
  89. cmd, stderr=subprocess.PIPE)
  90. _, stderr = process_communicate_or_kill(p)
  91. if p.returncode != 0:
  92. self.to_stderr(stderr.decode('utf-8', 'replace'))
  93. return p.returncode
  94. class CurlFD(ExternalFD):
  95. AVAILABLE_OPT = '-V'
  96. def _make_cmd(self, tmpfilename, info_dict):
  97. cmd = [self.exe, '--location', '-o', tmpfilename]
  98. for key, val in info_dict['http_headers'].items():
  99. cmd += ['--header', '%s: %s' % (key, val)]
  100. cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
  101. cmd += self._valueless_option('--silent', 'noprogress')
  102. cmd += self._valueless_option('--verbose', 'verbose')
  103. cmd += self._option('--limit-rate', 'ratelimit')
  104. retry = self._option('--retry', 'retries')
  105. if len(retry) == 2:
  106. if retry[1] in ('inf', 'infinite'):
  107. retry[1] = '2147483647'
  108. cmd += retry
  109. cmd += self._option('--max-filesize', 'max_filesize')
  110. cmd += self._option('--interface', 'source_address')
  111. cmd += self._option('--proxy', 'proxy')
  112. cmd += self._valueless_option('--insecure', 'nocheckcertificate')
  113. cmd += self._configuration_args()
  114. cmd += ['--', info_dict['url']]
  115. return cmd
  116. def _call_downloader(self, tmpfilename, info_dict):
  117. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  118. self._debug_cmd(cmd)
  119. # curl writes the progress to stderr so don't capture it.
  120. p = subprocess.Popen(cmd)
  121. process_communicate_or_kill(p)
  122. return p.returncode
  123. class AxelFD(ExternalFD):
  124. AVAILABLE_OPT = '-V'
  125. def _make_cmd(self, tmpfilename, info_dict):
  126. cmd = [self.exe, '-o', tmpfilename]
  127. for key, val in info_dict['http_headers'].items():
  128. cmd += ['-H', '%s: %s' % (key, val)]
  129. cmd += self._configuration_args()
  130. cmd += ['--', info_dict['url']]
  131. return cmd
  132. class WgetFD(ExternalFD):
  133. AVAILABLE_OPT = '--version'
  134. def _make_cmd(self, tmpfilename, info_dict):
  135. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  136. for key, val in info_dict['http_headers'].items():
  137. cmd += ['--header', '%s: %s' % (key, val)]
  138. cmd += self._option('--limit-rate', 'ratelimit')
  139. retry = self._option('--tries', 'retries')
  140. if len(retry) == 2:
  141. if retry[1] in ('inf', 'infinite'):
  142. retry[1] = '0'
  143. cmd += retry
  144. cmd += self._option('--bind-address', 'source_address')
  145. cmd += self._option('--proxy', 'proxy')
  146. cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
  147. cmd += self._configuration_args()
  148. cmd += ['--', info_dict['url']]
  149. return cmd
  150. class Aria2cFD(ExternalFD):
  151. AVAILABLE_OPT = '-v'
  152. def _make_cmd(self, tmpfilename, info_dict):
  153. cmd = [self.exe, '-c']
  154. cmd += self._configuration_args([
  155. '--min-split-size', '1M', '--max-connection-per-server', '4'])
  156. dn = os.path.dirname(tmpfilename)
  157. if dn:
  158. cmd += ['--dir', dn]
  159. cmd += ['--out', os.path.basename(tmpfilename)]
  160. for key, val in info_dict['http_headers'].items():
  161. cmd += ['--header', '%s: %s' % (key, val)]
  162. cmd += self._option('--interface', 'source_address')
  163. cmd += self._option('--all-proxy', 'proxy')
  164. cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
  165. cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
  166. cmd += ['--', info_dict['url']]
  167. return cmd
  168. class HttpieFD(ExternalFD):
  169. @classmethod
  170. def available(cls):
  171. return check_executable('http', ['--version'])
  172. def _make_cmd(self, tmpfilename, info_dict):
  173. cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
  174. for key, val in info_dict['http_headers'].items():
  175. cmd += ['%s:%s' % (key, val)]
  176. return cmd
  177. class FFmpegFD(ExternalFD):
  178. @classmethod
  179. def supports(cls, info_dict):
  180. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
  181. @classmethod
  182. def available(cls):
  183. return FFmpegPostProcessor().available
  184. def _call_downloader(self, tmpfilename, info_dict):
  185. url = info_dict['url']
  186. ffpp = FFmpegPostProcessor(downloader=self)
  187. if not ffpp.available:
  188. self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
  189. return False
  190. ffpp.check_version()
  191. args = [ffpp.executable, '-y']
  192. for log_level in ('quiet', 'verbose'):
  193. if self.params.get(log_level, False):
  194. args += ['-loglevel', log_level]
  195. break
  196. seekable = info_dict.get('_seekable')
  197. if seekable is not None:
  198. # setting -seekable prevents ffmpeg from guessing if the server
  199. # supports seeking(by adding the header `Range: bytes=0-`), which
  200. # can cause problems in some cases
  201. # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
  202. # http://trac.ffmpeg.org/ticket/6125#comment:10
  203. args += ['-seekable', '1' if seekable else '0']
  204. args += self._configuration_args()
  205. # start_time = info_dict.get('start_time') or 0
  206. # if start_time:
  207. # args += ['-ss', compat_str(start_time)]
  208. # end_time = info_dict.get('end_time')
  209. # if end_time:
  210. # args += ['-t', compat_str(end_time - start_time)]
  211. if info_dict['http_headers'] and re.match(r'^https?://', url):
  212. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  213. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  214. headers = handle_youtubedl_headers(info_dict['http_headers'])
  215. args += [
  216. '-headers',
  217. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  218. env = None
  219. proxy = self.params.get('proxy')
  220. if proxy:
  221. if not re.match(r'^[\da-zA-Z]+://', proxy):
  222. proxy = 'http://%s' % proxy
  223. if proxy.startswith('socks'):
  224. self.report_warning(
  225. '%s does not support SOCKS proxies. Downloading is likely to fail. '
  226. 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
  227. # Since December 2015 ffmpeg supports -http_proxy option (see
  228. # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
  229. # We could switch to the following code if we are able to detect version properly
  230. # args += ['-http_proxy', proxy]
  231. env = os.environ.copy()
  232. compat_setenv('HTTP_PROXY', proxy, env=env)
  233. compat_setenv('http_proxy', proxy, env=env)
  234. protocol = info_dict.get('protocol')
  235. if protocol == 'rtmp':
  236. player_url = info_dict.get('player_url')
  237. page_url = info_dict.get('page_url')
  238. app = info_dict.get('app')
  239. play_path = info_dict.get('play_path')
  240. tc_url = info_dict.get('tc_url')
  241. flash_version = info_dict.get('flash_version')
  242. live = info_dict.get('rtmp_live', False)
  243. conn = info_dict.get('rtmp_conn')
  244. if player_url is not None:
  245. args += ['-rtmp_swfverify', player_url]
  246. if page_url is not None:
  247. args += ['-rtmp_pageurl', page_url]
  248. if app is not None:
  249. args += ['-rtmp_app', app]
  250. if play_path is not None:
  251. args += ['-rtmp_playpath', play_path]
  252. if tc_url is not None:
  253. args += ['-rtmp_tcurl', tc_url]
  254. if flash_version is not None:
  255. args += ['-rtmp_flashver', flash_version]
  256. if live:
  257. args += ['-rtmp_live', 'live']
  258. if isinstance(conn, list):
  259. for entry in conn:
  260. args += ['-rtmp_conn', entry]
  261. elif isinstance(conn, compat_str):
  262. args += ['-rtmp_conn', conn]
  263. args += ['-i', url, '-c', 'copy']
  264. if self.params.get('test', False):
  265. args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
  266. if protocol in ('m3u8', 'm3u8_native'):
  267. if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
  268. args += ['-f', 'mpegts']
  269. else:
  270. args += ['-f', 'mp4']
  271. 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')):
  272. args += ['-bsf:a', 'aac_adtstoasc']
  273. elif protocol == 'rtmp':
  274. args += ['-f', 'flv']
  275. else:
  276. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  277. args = [encodeArgument(opt) for opt in args]
  278. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  279. self._debug_cmd(args)
  280. proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
  281. try:
  282. retval = proc.wait()
  283. except BaseException as e:
  284. # subprocess.run would send the SIGKILL signal to ffmpeg and the
  285. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  286. # produces a file that is playable (this is mostly useful for live
  287. # streams). Note that Windows is not affected and produces playable
  288. # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
  289. if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32':
  290. process_communicate_or_kill(proc, b'q')
  291. else:
  292. proc.kill()
  293. proc.wait()
  294. raise
  295. return retval
  296. class AVconvFD(FFmpegFD):
  297. pass
  298. _BY_NAME = dict(
  299. (klass.get_basename(), klass)
  300. for name, klass in globals().items()
  301. if name.endswith('FD') and name != 'ExternalFD'
  302. )
  303. def list_external_downloaders():
  304. return sorted(_BY_NAME.keys())
  305. def get_external_downloader(external_downloader):
  306. """ Given the name of the executable, see whether we support the given
  307. downloader . """
  308. # Drop .exe extension on Windows
  309. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  310. return _BY_NAME[bn]