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.

276 lines
9.5 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 ..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. args += self._configuration_args()
  147. # start_time = info_dict.get('start_time') or 0
  148. # if start_time:
  149. # args += ['-ss', compat_str(start_time)]
  150. # end_time = info_dict.get('end_time')
  151. # if end_time:
  152. # args += ['-t', compat_str(end_time - start_time)]
  153. if info_dict['http_headers'] and re.match(r'^https?://', url):
  154. # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
  155. # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
  156. headers = handle_youtubedl_headers(info_dict['http_headers'])
  157. args += [
  158. '-headers',
  159. ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
  160. protocol = info_dict.get('protocol')
  161. if protocol == 'rtmp':
  162. player_url = info_dict.get('player_url')
  163. page_url = info_dict.get('page_url')
  164. app = info_dict.get('app')
  165. play_path = info_dict.get('play_path')
  166. tc_url = info_dict.get('tc_url')
  167. flash_version = info_dict.get('flash_version')
  168. live = info_dict.get('rtmp_live', False)
  169. if player_url is not None:
  170. args += ['-rtmp_swfverify', player_url]
  171. if page_url is not None:
  172. args += ['-rtmp_pageurl', page_url]
  173. if app is not None:
  174. args += ['-rtmp_app', app]
  175. if play_path is not None:
  176. args += ['-rtmp_playpath', play_path]
  177. if tc_url is not None:
  178. args += ['-rtmp_tcurl', tc_url]
  179. if flash_version is not None:
  180. args += ['-rtmp_flashver', flash_version]
  181. if live:
  182. args += ['-rtmp_live', 'live']
  183. args += ['-i', url, '-c', 'copy']
  184. if protocol == 'm3u8':
  185. if self.params.get('hls_use_mpegts', False):
  186. args += ['-f', 'mpegts']
  187. else:
  188. args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  189. elif protocol == 'rtmp':
  190. args += ['-f', 'flv']
  191. else:
  192. args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
  193. args = [encodeArgument(opt) for opt in args]
  194. args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
  195. self._debug_cmd(args)
  196. proc = subprocess.Popen(args, stdin=subprocess.PIPE)
  197. try:
  198. retval = proc.wait()
  199. except KeyboardInterrupt:
  200. # subprocces.run would send the SIGKILL signal to ffmpeg and the
  201. # mp4 file couldn't be played, but if we ask ffmpeg to quit it
  202. # produces a file that is playable (this is mostly useful for live
  203. # streams). Note that Windows is not affected and produces playable
  204. # files (see https://github.com/rg3/youtube-dl/issues/8300).
  205. if sys.platform != 'win32':
  206. proc.communicate(b'q')
  207. raise
  208. return retval
  209. class AVconvFD(FFmpegFD):
  210. pass
  211. _BY_NAME = dict(
  212. (klass.get_basename(), klass)
  213. for name, klass in globals().items()
  214. if name.endswith('FD') and name != 'ExternalFD'
  215. )
  216. def list_external_downloaders():
  217. return sorted(_BY_NAME.keys())
  218. def get_external_downloader(external_downloader):
  219. """ Given the name of the executable, see whether we support the given
  220. downloader . """
  221. # Drop .exe extension on Windows
  222. bn = os.path.splitext(os.path.basename(external_downloader))[0]
  223. return _BY_NAME[bn]