external.py 13 KB

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