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.

354 lines
13 KiB

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