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.

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