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.

347 lines
13 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. for log_level in ('quiet', 'verbose'):
  174. if self.params.get(log_level, False):
  175. args += ['-loglevel', log_level]
  176. break
  177. seekable = info_dict.get('_seekable')
  178. if seekable is not None:
  179. # setting -seekable prevents ffmpeg from guessing if the server
  180. # supports seeking(by adding the header `Range: bytes=0-`), which
  181. # can cause problems in some cases
  182. # https://github.com/rg3/youtube-dl/issues/11800#issuecomment-275037127
  183. # http://trac.ffmpeg.org/ticket/6125#comment:10
  184. args += ['-seekable', '1' if seekable else '0']
  185. args += self._configuration_args()
  186. # start_time = info_dict.get('start_time') or 0
  187. # if start_time:
  188. # args += ['-ss', compat_str(start_time)]
  189. # end_time = info_dict.get('end_time')
  190. # if end_time:
  191. # args += ['-t', compat_str(end_time - start_time)]
  192. if info_dict['http_headers'] and re.match(r'^https?://', url):
  193. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  194. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  195. headers = handle_youtubedl_headers(info_dict['http_headers'])
  196. args += [
  197. '-headers',
  198. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  199. env = None
  200. proxy = self.params.get('proxy')
  201. if proxy:
  202. if not re.match(r'^[\da-zA-Z]+://', proxy):
  203. proxy = 'http://%s' % proxy
  204. if proxy.startswith('socks'):
  205. self.report_warning(
  206. '%s does not support SOCKS proxies. Downloading is likely to fail. '
  207. 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
  208. # Since December 2015 ffmpeg supports -http_proxy option (see
  209. # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
  210. # We could switch to the following code if we are able to detect version properly
  211. # args += ['-http_proxy', proxy]
  212. env = os.environ.copy()
  213. compat_setenv('HTTP_PROXY', proxy, env=env)
  214. compat_setenv('http_proxy', proxy, env=env)
  215. protocol = info_dict.get('protocol')
  216. if protocol == 'rtmp':
  217. player_url = info_dict.get('player_url')
  218. page_url = info_dict.get('page_url')
  219. app = info_dict.get('app')
  220. play_path = info_dict.get('play_path')
  221. tc_url = info_dict.get('tc_url')
  222. flash_version = info_dict.get('flash_version')
  223. live = info_dict.get('rtmp_live', False)
  224. if player_url is not None:
  225. args += ['-rtmp_swfverify', player_url]
  226. if page_url is not None:
  227. args += ['-rtmp_pageurl', page_url]
  228. if app is not None:
  229. args += ['-rtmp_app', app]
  230. if play_path is not None:
  231. args += ['-rtmp_playpath', play_path]
  232. if tc_url is not None:
  233. args += ['-rtmp_tcurl', tc_url]
  234. if flash_version is not None:
  235. args += ['-rtmp_flashver', flash_version]
  236. if live:
  237. args += ['-rtmp_live', 'live']
  238. args += ['-i', url, '-c', 'copy']
  239. if self.params.get('test', False):
  240. args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
  241. if protocol in ('m3u8', 'm3u8_native'):
  242. if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
  243. args += ['-f', 'mpegts']
  244. else:
  245. args += ['-f', 'mp4']
  246. 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')):
  247. args += ['-bsf:a', 'aac_adtstoasc']
  248. elif protocol == 'rtmp':
  249. args += ['-f', 'flv']
  250. else:
  251. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  252. args = [encodeArgument(opt) for opt in args]
  253. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  254. self._debug_cmd(args)
  255. proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
  256. try:
  257. retval = proc.wait()
  258. except KeyboardInterrupt:
  259. # subprocces.run would send the SIGKILL signal to ffmpeg and the
  260. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  261. # produces a file that is playable (this is mostly useful for live
  262. # streams). Note that Windows is not affected and produces playable
  263. # files (see https://github.com/rg3/youtube-dl/issues/8300).
  264. if sys.platform != 'win32':
  265. proc.communicate(b'q')
  266. raise
  267. return retval
  268. class AVconvFD(FFmpegFD):
  269. pass
  270. _BY_NAME = dict(
  271. (klass.get_basename(), klass)
  272. for name, klass in globals().items()
  273. if name.endswith('FD') and name != 'ExternalFD'
  274. )
  275. def list_external_downloaders():
  276. return sorted(_BY_NAME.keys())
  277. def get_external_downloader(external_downloader):
  278. """ Given the name of the executable, see whether we support the given
  279. downloader . """
  280. # Drop .exe extension on Windows
  281. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  282. return _BY_NAME[bn]