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.

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