1 from __future__ import unicode_literals
9 from .common import FileDownloader
10 from ..compat import (
14 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
19 cli_configuration_args,
22 handle_youtubedl_headers,
28 class ExternalFD(FileDownloader):
29 def real_download(self, filename, info_dict):
30 self.report_destination(filename)
31 tmpfilename = self.temp_name(filename)
35 retval = self._call_downloader(tmpfilename, info_dict)
36 except KeyboardInterrupt:
37 if not info_dict.get('is_live'):
39 # Live stream downloading cancellation should be considered as
40 # correct and expected termination thus all postprocessing
43 self.to_screen('[%s] Interrupted by user' % self.get_basename())
49 'elapsed': time.time() - started,
52 fsize = os.path.getsize(encodeFilename(tmpfilename))
53 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
54 self.try_rename(tmpfilename, filename)
56 'downloaded_bytes': fsize,
59 self._hook_progress(status)
63 self.report_error('%s exited with code %d' % (
64 self.get_basename(), retval))
68 def get_basename(cls):
69 return cls.__name__[:-2].lower()
73 return self.params.get('external_downloader')
77 return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
80 def supports(cls, info_dict):
81 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
84 def can_download(cls, info_dict):
85 return cls.available() and cls.supports(info_dict)
87 def _option(self, command_option, param):
88 return cli_option(self.params, command_option, param)
90 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
91 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
93 def _valueless_option(self, command_option, param, expected_value=True):
94 return cli_valueless_option(self.params, command_option, param, expected_value)
96 def _configuration_args(self, default=[]):
97 return cli_configuration_args(self.params, 'external_downloader_args', default)
99 def _call_downloader(self, tmpfilename, info_dict):
100 """ Either overwrite this or implement _make_cmd """
101 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
105 p = subprocess.Popen(
106 cmd, stderr=subprocess.PIPE)
107 _, stderr = p.communicate()
108 if p.returncode != 0:
109 self.to_stderr(stderr.decode('utf-8', 'replace'))
113 class CurlFD(ExternalFD):
116 def _make_cmd(self, tmpfilename, info_dict):
117 cmd = [self.exe, '--location', '-o', tmpfilename]
118 for key, val in info_dict['http_headers'].items():
119 cmd += ['--header', '%s: %s' % (key, val)]
120 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
121 cmd += self._valueless_option('--silent', 'noprogress')
122 cmd += self._valueless_option('--verbose', 'verbose')
123 cmd += self._option('--limit-rate', 'ratelimit')
124 retry = self._option('--retry', 'retries')
126 if retry[1] in ('inf', 'infinite'):
127 retry[1] = '2147483647'
129 cmd += self._option('--max-filesize', 'max_filesize')
130 cmd += self._option('--interface', 'source_address')
131 cmd += self._option('--proxy', 'proxy')
132 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
133 cmd += self._configuration_args()
134 cmd += ['--', info_dict['url']]
137 def _call_downloader(self, tmpfilename, info_dict):
138 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
142 # curl writes the progress to stderr so don't capture it.
143 p = subprocess.Popen(cmd)
148 class AxelFD(ExternalFD):
151 def _make_cmd(self, tmpfilename, info_dict):
152 cmd = [self.exe, '-o', tmpfilename]
153 for key, val in info_dict['http_headers'].items():
154 cmd += ['-H', '%s: %s' % (key, val)]
155 cmd += self._configuration_args()
156 cmd += ['--', info_dict['url']]
160 class WgetFD(ExternalFD):
161 AVAILABLE_OPT = '--version'
163 def _make_cmd(self, tmpfilename, info_dict):
164 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
165 for key, val in info_dict['http_headers'].items():
166 cmd += ['--header', '%s: %s' % (key, val)]
167 cmd += self._option('--limit-rate', 'ratelimit')
168 retry = self._option('--tries', 'retries')
170 if retry[1] in ('inf', 'infinite'):
173 cmd += self._option('--bind-address', 'source_address')
174 cmd += self._option('--proxy', 'proxy')
175 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
176 cmd += self._configuration_args()
177 cmd += ['--', info_dict['url']]
181 class Aria2cFD(ExternalFD):
184 def _make_cmd(self, tmpfilename, info_dict):
185 cmd = [self.exe, '-c']
186 cmd += self._configuration_args([
187 '--min-split-size', '1M', '--max-connection-per-server', '4'])
188 dn = os.path.dirname(tmpfilename)
191 cmd += ['--out', os.path.basename(tmpfilename)]
192 for key, val in info_dict['http_headers'].items():
193 cmd += ['--header', '%s: %s' % (key, val)]
194 cmd += self._option('--interface', 'source_address')
195 cmd += self._option('--all-proxy', 'proxy')
196 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
197 cmd += ['--', info_dict['url']]
201 class HttpieFD(ExternalFD):
204 return check_executable('http', ['--version'])
206 def _make_cmd(self, tmpfilename, info_dict):
207 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
208 for key, val in info_dict['http_headers'].items():
209 cmd += ['%s:%s' % (key, val)]
213 class FFmpegFD(ExternalFD):
215 def supports(cls, info_dict):
216 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
220 return FFmpegPostProcessor().available
222 def _call_downloader(self, tmpfilename, info_dict):
223 url = info_dict['url']
224 ffpp = FFmpegPostProcessor(downloader=self)
225 if not ffpp.available:
226 self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
230 args = [ffpp.executable, '-y']
232 for log_level in ('quiet', 'verbose'):
233 if self.params.get(log_level, False):
234 args += ['-loglevel', log_level]
237 seekable = info_dict.get('_seekable')
238 if seekable is not None:
239 # setting -seekable prevents ffmpeg from guessing if the server
240 # supports seeking(by adding the header `Range: bytes=0-`), which
241 # can cause problems in some cases
242 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
243 # http://trac.ffmpeg.org/ticket/6125#comment:10
244 args += ['-seekable', '1' if seekable else '0']
246 args += self._configuration_args()
248 # start_time = info_dict.get('start_time') or 0
250 # args += ['-ss', compat_str(start_time)]
251 # end_time = info_dict.get('end_time')
253 # args += ['-t', compat_str(end_time - start_time)]
255 if info_dict['http_headers'] and re.match(r'^https?://', url):
256 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
257 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
258 headers = handle_youtubedl_headers(info_dict['http_headers'])
261 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
264 proxy = self.params.get('proxy')
266 if not re.match(r'^[\da-zA-Z]+://', proxy):
267 proxy = 'http://%s' % proxy
269 if proxy.startswith('socks'):
271 '%s does not support SOCKS proxies. Downloading is likely to fail. '
272 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
274 # Since December 2015 ffmpeg supports -http_proxy option (see
275 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
276 # We could switch to the following code if we are able to detect version properly
277 # args += ['-http_proxy', proxy]
278 env = os.environ.copy()
279 compat_setenv('HTTP_PROXY', proxy, env=env)
280 compat_setenv('http_proxy', proxy, env=env)
282 protocol = info_dict.get('protocol')
284 if protocol == 'rtmp':
285 player_url = info_dict.get('player_url')
286 page_url = info_dict.get('page_url')
287 app = info_dict.get('app')
288 play_path = info_dict.get('play_path')
289 tc_url = info_dict.get('tc_url')
290 flash_version = info_dict.get('flash_version')
291 live = info_dict.get('rtmp_live', False)
292 if player_url is not None:
293 args += ['-rtmp_swfverify', player_url]
294 if page_url is not None:
295 args += ['-rtmp_pageurl', page_url]
297 args += ['-rtmp_app', app]
298 if play_path is not None:
299 args += ['-rtmp_playpath', play_path]
300 if tc_url is not None:
301 args += ['-rtmp_tcurl', tc_url]
302 if flash_version is not None:
303 args += ['-rtmp_flashver', flash_version]
305 args += ['-rtmp_live', 'live']
307 args += ['-i', url, '-c', 'copy']
309 if self.params.get('test', False):
310 args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
312 if protocol in ('m3u8', 'm3u8_native'):
313 if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
314 args += ['-f', 'mpegts']
316 args += ['-f', 'mp4']
317 if (ffpp.basename == 'ffmpeg' and is_outdated_version(ffpp._versions['ffmpeg'], '3.2', False)) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')):
318 args += ['-bsf:a', 'aac_adtstoasc']
319 elif protocol == 'rtmp':
320 args += ['-f', 'flv']
322 args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
324 args = [encodeArgument(opt) for opt in args]
325 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
327 self._debug_cmd(args)
329 proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
332 except KeyboardInterrupt:
333 # subprocces.run would send the SIGKILL signal to ffmpeg and the
334 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
335 # produces a file that is playable (this is mostly useful for live
336 # streams). Note that Windows is not affected and produces playable
337 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
338 if sys.platform != 'win32':
339 proc.communicate(b'q')
344 class AVconvFD(FFmpegFD):
349 (klass.get_basename(), klass)
350 for name, klass in globals().items()
351 if name.endswith('FD') and name != 'ExternalFD'
355 def list_external_downloaders():
356 return sorted(_BY_NAME.keys())
359 def get_external_downloader(external_downloader):
360 """ Given the name of the executable, see whether we support the given
362 # Drop .exe extension on Windows
363 bn = os.path.splitext(os.path.basename(external_downloader))[0]