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.

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