external.py 8.4 KB

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