2
0

external.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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._bool_option('--continue-at', 'continuedl', '-', '0')
  80. cmd += self._valueless_option('--silent', 'noprogress')
  81. cmd += self._valueless_option('--verbose', 'verbose')
  82. cmd += self._option('--limit-rate', 'ratelimit')
  83. cmd += self._option('--retry', 'retries')
  84. cmd += self._option('--max-filesize', 'max_filesize')
  85. cmd += self._option('--interface', 'source_address')
  86. cmd += self._option('--proxy', 'proxy')
  87. cmd += self._valueless_option('--insecure', 'nocheckcertificate')
  88. cmd += self._configuration_args()
  89. cmd += ['--', info_dict['url']]
  90. return cmd
  91. def _call_downloader(self, tmpfilename, info_dict):
  92. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  93. self._debug_cmd(cmd)
  94. p = subprocess.Popen(cmd)
  95. p.communicate()
  96. return p.returncode
  97. class AxelFD(ExternalFD):
  98. AVAILABLE_OPT = '-V'
  99. def _make_cmd(self, tmpfilename, info_dict):
  100. cmd = [self.exe, '-o', tmpfilename]
  101. for key, val in info_dict['http_headers'].items():
  102. cmd += ['-H', '%s: %s' % (key, val)]
  103. cmd += self._configuration_args()
  104. cmd += ['--', info_dict['url']]
  105. return cmd
  106. class WgetFD(ExternalFD):
  107. AVAILABLE_OPT = '--version'
  108. def _make_cmd(self, tmpfilename, info_dict):
  109. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  110. for key, val in info_dict['http_headers'].items():
  111. cmd += ['--header', '%s: %s' % (key, val)]
  112. cmd += self._option('--bind-address', 'source_address')
  113. cmd += self._option('--proxy', 'proxy')
  114. cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
  115. cmd += self._configuration_args()
  116. cmd += ['--', info_dict['url']]
  117. return cmd
  118. class Aria2cFD(ExternalFD):
  119. AVAILABLE_OPT = '-v'
  120. def _make_cmd(self, tmpfilename, info_dict):
  121. cmd = [self.exe, '-c']
  122. cmd += self._configuration_args([
  123. '--min-split-size', '1M', '--max-connection-per-server', '4'])
  124. dn = os.path.dirname(tmpfilename)
  125. if dn:
  126. cmd += ['--dir', dn]
  127. cmd += ['--out', os.path.basename(tmpfilename)]
  128. for key, val in info_dict['http_headers'].items():
  129. cmd += ['--header', '%s: %s' % (key, val)]
  130. cmd += self._option('--interface', 'source_address')
  131. cmd += self._option('--all-proxy', 'proxy')
  132. cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
  133. cmd += ['--', info_dict['url']]
  134. return cmd
  135. class HttpieFD(ExternalFD):
  136. @classmethod
  137. def available(cls):
  138. return check_executable('http', ['--version'])
  139. def _make_cmd(self, tmpfilename, info_dict):
  140. cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
  141. for key, val in info_dict['http_headers'].items():
  142. cmd += ['%s:%s' % (key, val)]
  143. return cmd
  144. class FFmpegFD(ExternalFD):
  145. @classmethod
  146. def supports(cls, info_dict):
  147. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
  148. @classmethod
  149. def available(cls):
  150. return FFmpegPostProcessor().available
  151. def _call_downloader(self, tmpfilename, info_dict):
  152. url = info_dict['url']
  153. ffpp = FFmpegPostProcessor(downloader=self)
  154. if not ffpp.available:
  155. self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
  156. return False
  157. ffpp.check_version()
  158. args = [ffpp.executable, '-y']
  159. args += self._configuration_args()
  160. # start_time = info_dict.get('start_time') or 0
  161. # if start_time:
  162. # args += ['-ss', compat_str(start_time)]
  163. # end_time = info_dict.get('end_time')
  164. # if end_time:
  165. # args += ['-t', compat_str(end_time - start_time)]
  166. if info_dict['http_headers'] and re.match(r'^https?://', url):
  167. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  168. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  169. headers = handle_youtubedl_headers(info_dict['http_headers'])
  170. args += [
  171. '-headers',
  172. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  173. env = None
  174. proxy = self.params.get('proxy')
  175. if proxy:
  176. if not re.match(r'^[\da-zA-Z]+://', proxy):
  177. proxy = 'http://%s' % proxy
  178. # Since December 2015 ffmpeg supports -http_proxy option (see
  179. # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
  180. # We could switch to the following code if we are able to detect version properly
  181. # args += ['-http_proxy', proxy]
  182. env = os.environ.copy()
  183. compat_setenv('HTTP_PROXY', proxy, env=env)
  184. compat_setenv('http_proxy', proxy, env=env)
  185. protocol = info_dict.get('protocol')
  186. if protocol == 'rtmp':
  187. player_url = info_dict.get('player_url')
  188. page_url = info_dict.get('page_url')
  189. app = info_dict.get('app')
  190. play_path = info_dict.get('play_path')
  191. tc_url = info_dict.get('tc_url')
  192. flash_version = info_dict.get('flash_version')
  193. live = info_dict.get('rtmp_live', False)
  194. if player_url is not None:
  195. args += ['-rtmp_swfverify', player_url]
  196. if page_url is not None:
  197. args += ['-rtmp_pageurl', page_url]
  198. if app is not None:
  199. args += ['-rtmp_app', app]
  200. if play_path is not None:
  201. args += ['-rtmp_playpath', play_path]
  202. if tc_url is not None:
  203. args += ['-rtmp_tcurl', tc_url]
  204. if flash_version is not None:
  205. args += ['-rtmp_flashver', flash_version]
  206. if live:
  207. args += ['-rtmp_live', 'live']
  208. args += ['-i', url, '-c', 'copy']
  209. if protocol in ('m3u8', 'm3u8_native'):
  210. if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
  211. args += ['-f', 'mpegts']
  212. else:
  213. args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  214. elif protocol == 'rtmp':
  215. args += ['-f', 'flv']
  216. else:
  217. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  218. args = [encodeArgument(opt) for opt in args]
  219. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  220. self._debug_cmd(args)
  221. proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
  222. try:
  223. retval = proc.wait()
  224. except KeyboardInterrupt:
  225. # subprocces.run would send the SIGKILL signal to ffmpeg and the
  226. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  227. # produces a file that is playable (this is mostly useful for live
  228. # streams). Note that Windows is not affected and produces playable
  229. # files (see https://github.com/rg3/youtube-dl/issues/8300).
  230. if sys.platform != 'win32':
  231. proc.communicate(b'q')
  232. raise
  233. return retval
  234. class AVconvFD(FFmpegFD):
  235. pass
  236. _BY_NAME = dict(
  237. (klass.get_basename(), klass)
  238. for name, klass in globals().items()
  239. if name.endswith('FD') and name != 'ExternalFD'
  240. )
  241. def list_external_downloaders():
  242. return sorted(_BY_NAME.keys())
  243. def get_external_downloader(external_downloader):
  244. """ Given the name of the executable, see whether we support the given
  245. downloader . """
  246. # Drop .exe extension on Windows
  247. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  248. return _BY_NAME[bn]