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.

370 lines
14 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. retry = self._option('--retry', 'retries')
  104. if len(retry) == 2:
  105. if retry[1] in ('inf', 'infinite'):
  106. retry[1] = '2147483647'
  107. cmd += retry
  108. cmd += self._option('--max-filesize', 'max_filesize')
  109. cmd += self._option('--interface', 'source_address')
  110. cmd += self._option('--proxy', 'proxy')
  111. cmd += self._valueless_option('--insecure', 'nocheckcertificate')
  112. cmd += self._configuration_args()
  113. cmd += ['--', info_dict['url']]
  114. return cmd
  115. def _call_downloader(self, tmpfilename, info_dict):
  116. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  117. self._debug_cmd(cmd)
  118. # curl writes the progress to stderr so don't capture it.
  119. p = subprocess.Popen(cmd)
  120. p.communicate()
  121. return p.returncode
  122. class AxelFD(ExternalFD):
  123. AVAILABLE_OPT = '-V'
  124. def _make_cmd(self, tmpfilename, info_dict):
  125. cmd = [self.exe, '-o', tmpfilename]
  126. for key, val in info_dict['http_headers'].items():
  127. cmd += ['-H', '%s: %s' % (key, val)]
  128. cmd += self._configuration_args()
  129. cmd += ['--', info_dict['url']]
  130. return cmd
  131. class WgetFD(ExternalFD):
  132. AVAILABLE_OPT = '--version'
  133. def _make_cmd(self, tmpfilename, info_dict):
  134. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  135. for key, val in info_dict['http_headers'].items():
  136. cmd += ['--header', '%s: %s' % (key, val)]
  137. cmd += self._option('--limit-rate', 'ratelimit')
  138. retry = self._option('--tries', 'retries')
  139. if len(retry) == 2:
  140. if retry[1] in ('inf', 'infinite'):
  141. retry[1] = '0'
  142. cmd += retry
  143. cmd += self._option('--bind-address', 'source_address')
  144. cmd += self._option('--proxy', 'proxy')
  145. cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
  146. cmd += self._configuration_args()
  147. cmd += ['--', info_dict['url']]
  148. return cmd
  149. class Aria2cFD(ExternalFD):
  150. AVAILABLE_OPT = '-v'
  151. def _make_cmd(self, tmpfilename, info_dict):
  152. cmd = [self.exe, '-c']
  153. cmd += self._configuration_args([
  154. '--min-split-size', '1M', '--max-connection-per-server', '4'])
  155. dn = os.path.dirname(tmpfilename)
  156. if dn:
  157. cmd += ['--dir', dn]
  158. cmd += ['--out', os.path.basename(tmpfilename)]
  159. for key, val in info_dict['http_headers'].items():
  160. cmd += ['--header', '%s: %s' % (key, val)]
  161. cmd += self._option('--interface', 'source_address')
  162. cmd += self._option('--all-proxy', 'proxy')
  163. cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
  164. cmd += ['--', info_dict['url']]
  165. return cmd
  166. class HttpieFD(ExternalFD):
  167. @classmethod
  168. def available(cls):
  169. return check_executable('http', ['--version'])
  170. def _make_cmd(self, tmpfilename, info_dict):
  171. cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
  172. for key, val in info_dict['http_headers'].items():
  173. cmd += ['%s:%s' % (key, val)]
  174. return cmd
  175. class FFmpegFD(ExternalFD):
  176. @classmethod
  177. def supports(cls, info_dict):
  178. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
  179. @classmethod
  180. def available(cls):
  181. return FFmpegPostProcessor().available
  182. def _call_downloader(self, tmpfilename, info_dict):
  183. url = info_dict['url']
  184. ffpp = FFmpegPostProcessor(downloader=self)
  185. if not ffpp.available:
  186. self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
  187. return False
  188. ffpp.check_version()
  189. args = [ffpp.executable, '-y']
  190. for log_level in ('quiet', 'verbose'):
  191. if self.params.get(log_level, False):
  192. args += ['-loglevel', log_level]
  193. break
  194. seekable = info_dict.get('_seekable')
  195. if seekable is not None:
  196. # setting -seekable prevents ffmpeg from guessing if the server
  197. # supports seeking(by adding the header `Range: bytes=0-`), which
  198. # can cause problems in some cases
  199. # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
  200. # http://trac.ffmpeg.org/ticket/6125#comment:10
  201. args += ['-seekable', '1' if seekable else '0']
  202. args += self._configuration_args()
  203. # start_time = info_dict.get('start_time') or 0
  204. # if start_time:
  205. # args += ['-ss', compat_str(start_time)]
  206. # end_time = info_dict.get('end_time')
  207. # if end_time:
  208. # args += ['-t', compat_str(end_time - start_time)]
  209. if info_dict['http_headers'] and re.match(r'^https?://', url):
  210. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  211. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  212. headers = handle_youtubedl_headers(info_dict['http_headers'])
  213. args += [
  214. '-headers',
  215. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  216. env = None
  217. proxy = self.params.get('proxy')
  218. if proxy:
  219. if not re.match(r'^[\da-zA-Z]+://', proxy):
  220. proxy = 'http://%s' % proxy
  221. if proxy.startswith('socks'):
  222. self.report_warning(
  223. '%s does not support SOCKS proxies. Downloading is likely to fail. '
  224. 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
  225. # Since December 2015 ffmpeg supports -http_proxy option (see
  226. # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
  227. # We could switch to the following code if we are able to detect version properly
  228. # args += ['-http_proxy', proxy]
  229. env = os.environ.copy()
  230. compat_setenv('HTTP_PROXY', proxy, env=env)
  231. compat_setenv('http_proxy', proxy, env=env)
  232. protocol = info_dict.get('protocol')
  233. if protocol == 'rtmp':
  234. player_url = info_dict.get('player_url')
  235. page_url = info_dict.get('page_url')
  236. app = info_dict.get('app')
  237. play_path = info_dict.get('play_path')
  238. tc_url = info_dict.get('tc_url')
  239. flash_version = info_dict.get('flash_version')
  240. live = info_dict.get('rtmp_live', False)
  241. conn = info_dict.get('rtmp_conn')
  242. if player_url is not None:
  243. args += ['-rtmp_swfverify', player_url]
  244. if page_url is not None:
  245. args += ['-rtmp_pageurl', page_url]
  246. if app is not None:
  247. args += ['-rtmp_app', app]
  248. if play_path is not None:
  249. args += ['-rtmp_playpath', play_path]
  250. if tc_url is not None:
  251. args += ['-rtmp_tcurl', tc_url]
  252. if flash_version is not None:
  253. args += ['-rtmp_flashver', flash_version]
  254. if live:
  255. args += ['-rtmp_live', 'live']
  256. if isinstance(conn, list):
  257. for entry in conn:
  258. args += ['-rtmp_conn', entry]
  259. elif isinstance(conn, compat_str):
  260. args += ['-rtmp_conn', conn]
  261. args += ['-i', url, '-c', 'copy']
  262. if self.params.get('test', False):
  263. args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
  264. if protocol in ('m3u8', 'm3u8_native'):
  265. if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
  266. args += ['-f', 'mpegts']
  267. else:
  268. args += ['-f', 'mp4']
  269. 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')):
  270. args += ['-bsf:a', 'aac_adtstoasc']
  271. elif protocol == 'rtmp':
  272. args += ['-f', 'flv']
  273. else:
  274. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  275. args = [encodeArgument(opt) for opt in args]
  276. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  277. self._debug_cmd(args)
  278. proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
  279. try:
  280. retval = proc.wait()
  281. except KeyboardInterrupt:
  282. # subprocces.run would send the SIGKILL signal to ffmpeg and the
  283. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  284. # produces a file that is playable (this is mostly useful for live
  285. # streams). Note that Windows is not affected and produces playable
  286. # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
  287. if sys.platform != 'win32':
  288. proc.communicate(b'q')
  289. raise
  290. return retval
  291. class AVconvFD(FFmpegFD):
  292. pass
  293. _BY_NAME = dict(
  294. (klass.get_basename(), klass)
  295. for name, klass in globals().items()
  296. if name.endswith('FD') and name != 'ExternalFD'
  297. )
  298. def list_external_downloaders():
  299. return sorted(_BY_NAME.keys())
  300. def get_external_downloader(external_downloader):
  301. """ Given the name of the executable, see whether we support the given
  302. downloader . """
  303. # Drop .exe extension on Windows
  304. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  305. return _BY_NAME[bn]