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.

342 lines
12 KiB

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