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.

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