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.

241 lines
8.2 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. def _option(self, command_option, param):
  53. return cli_option(self.params, command_option, param)
  54. def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
  55. return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
  56. def _valueless_option(self, command_option, param, expected_value=True):
  57. return cli_valueless_option(self.params, command_option, param, expected_value)
  58. def _configuration_args(self, default=[]):
  59. return cli_configuration_args(self.params, 'external_downloader_args', default)
  60. def _call_downloader(self, tmpfilename, info_dict):
  61. """ Either overwrite this or implement _make_cmd """
  62. cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
  63. self._debug_cmd(cmd)
  64. p = subprocess.Popen(
  65. cmd, stderr=subprocess.PIPE)
  66. _, stderr = p.communicate()
  67. if p.returncode != 0:
  68. self.to_stderr(stderr)
  69. return p.returncode
  70. class CurlFD(ExternalFD):
  71. AVAILABLE_OPT = '-V'
  72. def _make_cmd(self, tmpfilename, info_dict):
  73. cmd = [self.exe, '--location', '-o', tmpfilename]
  74. for key, val in info_dict['http_headers'].items():
  75. cmd += ['--header', '%s: %s' % (key, val)]
  76. cmd += self._option('--interface', 'source_address')
  77. cmd += self._option('--proxy', 'proxy')
  78. cmd += self._valueless_option('--insecure', 'nocheckcertificate')
  79. cmd += self._configuration_args()
  80. cmd += ['--', info_dict['url']]
  81. return cmd
  82. class AxelFD(ExternalFD):
  83. AVAILABLE_OPT = '-V'
  84. def _make_cmd(self, tmpfilename, info_dict):
  85. cmd = [self.exe, '-o', tmpfilename]
  86. for key, val in info_dict['http_headers'].items():
  87. cmd += ['-H', '%s: %s' % (key, val)]
  88. cmd += self._configuration_args()
  89. cmd += ['--', info_dict['url']]
  90. return cmd
  91. class WgetFD(ExternalFD):
  92. AVAILABLE_OPT = '--version'
  93. def _make_cmd(self, tmpfilename, info_dict):
  94. cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
  95. for key, val in info_dict['http_headers'].items():
  96. cmd += ['--header', '%s: %s' % (key, val)]
  97. cmd += self._option('--bind-address', 'source_address')
  98. cmd += self._option('--proxy', 'proxy')
  99. cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
  100. cmd += self._configuration_args()
  101. cmd += ['--', info_dict['url']]
  102. return cmd
  103. class Aria2cFD(ExternalFD):
  104. AVAILABLE_OPT = '-v'
  105. def _make_cmd(self, tmpfilename, info_dict):
  106. cmd = [self.exe, '-c']
  107. cmd += self._configuration_args([
  108. '--min-split-size', '1M', '--max-connection-per-server', '4'])
  109. dn = os.path.dirname(tmpfilename)
  110. if dn:
  111. cmd += ['--dir', dn]
  112. cmd += ['--out', os.path.basename(tmpfilename)]
  113. for key, val in info_dict['http_headers'].items():
  114. cmd += ['--header', '%s: %s' % (key, val)]
  115. cmd += self._option('--interface', 'source_address')
  116. cmd += self._option('--all-proxy', 'proxy')
  117. cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
  118. cmd += ['--', info_dict['url']]
  119. return cmd
  120. class HttpieFD(ExternalFD):
  121. @classmethod
  122. def available(cls):
  123. return check_executable('http', ['--version'])
  124. def _make_cmd(self, tmpfilename, info_dict):
  125. cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
  126. for key, val in info_dict['http_headers'].items():
  127. cmd += ['%s:%s' % (key, val)]
  128. return cmd
  129. class FFmpegFD(ExternalFD):
  130. @classmethod
  131. def supports(cls, info_dict):
  132. return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms') and not info_dict.get('requested_formats')
  133. @classmethod
  134. def available(cls):
  135. return FFmpegPostProcessor().available
  136. def _call_downloader(self, tmpfilename, info_dict):
  137. url = info_dict['url']
  138. ffpp = FFmpegPostProcessor(downloader=self)
  139. ffpp.check_version()
  140. args = [ffpp.executable, '-y']
  141. start_time = info_dict.get('start_time') or 0
  142. if start_time:
  143. args += ['-ss', compat_str(start_time)]
  144. end_time = info_dict.get('end_time')
  145. if end_time:
  146. args += ['-t', compat_str(end_time - start_time)]
  147. if info_dict['http_headers'] and re.match(r'^https?://', url):
  148. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  149. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  150. headers = handle_youtubedl_headers(info_dict['http_headers'])
  151. args += [
  152. '-headers',
  153. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  154. args += ['-i', url, '-c', 'copy']
  155. if info_dict.get('protocol') == 'm3u8':
  156. if self.params.get('hls_use_mpegts', False):
  157. args += ['-f', 'mpegts']
  158. else:
  159. args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  160. else:
  161. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  162. args = [encodeArgument(opt) for opt in args]
  163. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  164. self._debug_cmd(args)
  165. proc = subprocess.Popen(args, stdin=subprocess.PIPE)
  166. try:
  167. retval = proc.wait()
  168. except KeyboardInterrupt:
  169. # subprocces.run would send the SIGKILL signal to ffmpeg and the
  170. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  171. # produces a file that is playable (this is mostly useful for live
  172. # streams). Note that Windows is not affected and produces playable
  173. # files (see https://github.com/rg3/youtube-dl/issues/8300).
  174. if sys.platform != 'win32':
  175. proc.communicate(b'q')
  176. raise
  177. return retval
  178. class AVconvFD(FFmpegFD):
  179. pass
  180. _BY_NAME = dict(
  181. (klass.get_basename(), klass)
  182. for name, klass in globals().items()
  183. if name.endswith('FD') and name != 'ExternalFD'
  184. )
  185. def list_external_downloaders():
  186. return sorted(_BY_NAME.keys())
  187. def get_external_downloader(external_downloader):
  188. """ Given the name of the executable, see whether we support the given
  189. downloader . """
  190. # Drop .exe extension on Windows
  191. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  192. return _BY_NAME[bn]