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.

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