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.

245 lines
8.3 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 ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
  8. from ..compat import compat_str
  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)
  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') and not info_dict.get('requested_formats')
  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. ffpp.check_version()
  143. args = [ffpp.executable, '-y']
  144. start_time = info_dict.get('start_time') or 0
  145. if start_time:
  146. args += ['-ss', compat_str(start_time)]
  147. end_time = info_dict.get('end_time')
  148. if end_time:
  149. args += ['-t', compat_str(end_time - start_time)]
  150. if info_dict['http_headers'] and re.match(r'^https?://', url):
  151. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  152. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  153. headers = handle_youtubedl_headers(info_dict['http_headers'])
  154. args += [
  155. '-headers',
  156. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  157. args += ['-i', url, '-c', 'copy']
  158. if info_dict.get('protocol') == 'm3u8':
  159. if self.params.get('hls_use_mpegts', False):
  160. args += ['-f', 'mpegts']
  161. else:
  162. args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  163. else:
  164. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  165. args = [encodeArgument(opt) for opt in args]
  166. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  167. self._debug_cmd(args)
  168. proc = subprocess.Popen(args, stdin=subprocess.PIPE)
  169. try:
  170. retval = proc.wait()
  171. except KeyboardInterrupt:
  172. # subprocces.run would send the SIGKILL signal to ffmpeg and the
  173. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  174. # produces a file that is playable (this is mostly useful for live
  175. # streams). Note that Windows is not affected and produces playable
  176. # files (see https://github.com/rg3/youtube-dl/issues/8300).
  177. if sys.platform != 'win32':
  178. proc.communicate(b'q')
  179. raise
  180. return retval
  181. class AVconvFD(FFmpegFD):
  182. pass
  183. _BY_NAME = dict(
  184. (klass.get_basename(), klass)
  185. for name, klass in globals().items()
  186. if name.endswith('FD') and name != 'ExternalFD'
  187. )
  188. def list_external_downloaders():
  189. return sorted(_BY_NAME.keys())
  190. def get_external_downloader(external_downloader):
  191. """ Given the name of the executable, see whether we support the given
  192. downloader . """
  193. # Drop .exe extension on Windows
  194. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  195. return _BY_NAME[bn]