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.

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