]> jfr.im git - yt-dlp.git/blame - youtube_dl/downloader/external.py
[ChangeLog] Actualize
[yt-dlp.git] / youtube_dl / downloader / external.py
CommitLineData
222516d9
PH
1from __future__ import unicode_literals
2
3import os.path
4import subprocess
12b84ac8 5import sys
6import re
222516d9
PH
7
8from .common import FileDownloader
e62d9c5c 9from ..compat import compat_setenv
a755f825 10from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
222516d9 11from ..utils import (
1195a38f
S
12 cli_option,
13 cli_valueless_option,
14 cli_bool_option,
15 cli_configuration_args,
222516d9 16 encodeFilename,
74f8654a 17 encodeArgument,
12b84ac8 18 handle_youtubedl_headers,
99cbe98c 19 check_executable,
222516d9
PH
20)
21
22
23class ExternalFD(FileDownloader):
24 def real_download(self, filename, info_dict):
25 self.report_destination(filename)
26 tmpfilename = self.temp_name(filename)
27
28 retval = self._call_downloader(tmpfilename, info_dict)
29 if retval == 0:
30 fsize = os.path.getsize(encodeFilename(tmpfilename))
31 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
32 self.try_rename(tmpfilename, filename)
33 self._hook_progress({
34 'downloaded_bytes': fsize,
35 'total_bytes': fsize,
36 'filename': filename,
37 'status': 'finished',
38 })
39 return True
40 else:
41 self.to_stderr('\n')
42 self.report_error('%s exited with code %d' % (
43 self.get_basename(), retval))
44 return False
45
46 @classmethod
47 def get_basename(cls):
48 return cls.__name__[:-2].lower()
49
50 @property
51 def exe(self):
52 return self.params.get('external_downloader')
53
99cbe98c 54 @classmethod
55 def available(cls):
91ee320b 56 return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
99cbe98c 57
222516d9
PH
58 @classmethod
59 def supports(cls, info_dict):
60 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
61
2cb99ebb 62 @classmethod
63 def can_download(cls, info_dict):
64 return cls.available() and cls.supports(info_dict)
65
bf812ef7 66 def _option(self, command_option, param):
1195a38f 67 return cli_option(self.params, command_option, param)
bf812ef7 68
266b0ad6 69 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
1195a38f 70 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
266b0ad6 71
dc534b67 72 def _valueless_option(self, command_option, param, expected_value=True):
1195a38f 73 return cli_valueless_option(self.params, command_option, param, expected_value)
f30c2e8e 74
c75f0b36 75 def _configuration_args(self, default=[]):
1195a38f 76 return cli_configuration_args(self.params, 'external_downloader_args', default)
c75f0b36 77
222516d9
PH
78 def _call_downloader(self, tmpfilename, info_dict):
79 """ Either overwrite this or implement _make_cmd """
74f8654a 80 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
222516d9 81
74f8654a 82 self._debug_cmd(cmd)
222516d9
PH
83
84 p = subprocess.Popen(
384b6202
PH
85 cmd, stderr=subprocess.PIPE)
86 _, stderr = p.communicate()
222516d9 87 if p.returncode != 0:
e69f9f5d 88 self.to_stderr(stderr.decode('utf-8', 'replace'))
222516d9
PH
89 return p.returncode
90
91
384b6202 92class CurlFD(ExternalFD):
91ee320b 93 AVAILABLE_OPT = '-V'
99cbe98c 94
384b6202 95 def _make_cmd(self, tmpfilename, info_dict):
163d9667 96 cmd = [self.exe, '--location', '-o', tmpfilename]
e5660ee6 97 for key, val in info_dict['http_headers'].items():
384b6202 98 cmd += ['--header', '%s: %s' % (key, val)]
98e698f1
RA
99 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
100 cmd += self._valueless_option('--silent', 'noprogress')
101 cmd += self._valueless_option('--verbose', 'verbose')
102 cmd += self._option('--limit-rate', 'ratelimit')
103 cmd += self._option('--retry', 'retries')
104 cmd += self._option('--max-filesize', 'max_filesize')
9f3da138 105 cmd += self._option('--interface', 'source_address')
e7a8c303 106 cmd += self._option('--proxy', 'proxy')
dc534b67 107 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
c75f0b36 108 cmd += self._configuration_args()
384b6202
PH
109 cmd += ['--', info_dict['url']]
110 return cmd
111
98e698f1
RA
112 def _call_downloader(self, tmpfilename, info_dict):
113 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
114
115 self._debug_cmd(cmd)
116
acfccaca 117 # curl writes the progress to stderr so don't capture it.
98e698f1
RA
118 p = subprocess.Popen(cmd)
119 p.communicate()
120 return p.returncode
121
384b6202 122
e0ac5214 123class AxelFD(ExternalFD):
91ee320b 124 AVAILABLE_OPT = '-V'
99cbe98c 125
e0ac5214 126 def _make_cmd(self, tmpfilename, info_dict):
127 cmd = [self.exe, '-o', tmpfilename]
128 for key, val in info_dict['http_headers'].items():
129 cmd += ['-H', '%s: %s' % (key, val)]
130 cmd += self._configuration_args()
131 cmd += ['--', info_dict['url']]
132 return cmd
133
134
222516d9 135class WgetFD(ExternalFD):
91ee320b 136 AVAILABLE_OPT = '--version'
99cbe98c 137
222516d9
PH
138 def _make_cmd(self, tmpfilename, info_dict):
139 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
e5660ee6 140 for key, val in info_dict['http_headers'].items():
222516d9 141 cmd += ['--header', '%s: %s' % (key, val)]
9f3da138 142 cmd += self._option('--bind-address', 'source_address')
bf812ef7 143 cmd += self._option('--proxy', 'proxy')
dc534b67 144 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
c75f0b36 145 cmd += self._configuration_args()
222516d9
PH
146 cmd += ['--', info_dict['url']]
147 return cmd
148
149
384b6202 150class Aria2cFD(ExternalFD):
91ee320b 151 AVAILABLE_OPT = '-v'
99cbe98c 152
384b6202 153 def _make_cmd(self, tmpfilename, info_dict):
c75f0b36
PH
154 cmd = [self.exe, '-c']
155 cmd += self._configuration_args([
156 '--min-split-size', '1M', '--max-connection-per-server', '4'])
384b6202
PH
157 dn = os.path.dirname(tmpfilename)
158 if dn:
159 cmd += ['--dir', dn]
160 cmd += ['--out', os.path.basename(tmpfilename)]
e5660ee6 161 for key, val in info_dict['http_headers'].items():
384b6202 162 cmd += ['--header', '%s: %s' % (key, val)]
9f3da138 163 cmd += self._option('--interface', 'source_address')
bf812ef7 164 cmd += self._option('--all-proxy', 'proxy')
266b0ad6 165 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
384b6202
PH
166 cmd += ['--', info_dict['url']]
167 return cmd
168
906e2f0e
JMF
169
170class HttpieFD(ExternalFD):
99cbe98c 171 @classmethod
172 def available(cls):
173 return check_executable('http', ['--version'])
174
906e2f0e
JMF
175 def _make_cmd(self, tmpfilename, info_dict):
176 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
177 for key, val in info_dict['http_headers'].items():
178 cmd += ['%s:%s' % (key, val)]
179 return cmd
180
12b84ac8 181
182class FFmpegFD(ExternalFD):
183 @classmethod
184 def supports(cls, info_dict):
6ae27bed 185 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
12b84ac8 186
99cbe98c 187 @classmethod
188 def available(cls):
189 return FFmpegPostProcessor().available
190
12b84ac8 191 def _call_downloader(self, tmpfilename, info_dict):
192 url = info_dict['url']
193 ffpp = FFmpegPostProcessor(downloader=self)
77dea16a 194 if not ffpp.available:
195 self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
196 return False
12b84ac8 197 ffpp.check_version()
198
199 args = [ffpp.executable, '-y']
200
d8515fd4 201 args += self._configuration_args()
202
694c47b2 203 # start_time = info_dict.get('start_time') or 0
204 # if start_time:
205 # args += ['-ss', compat_str(start_time)]
206 # end_time = info_dict.get('end_time')
207 # if end_time:
208 # args += ['-t', compat_str(end_time - start_time)]
12b84ac8 209
210 if info_dict['http_headers'] and re.match(r'^https?://', url):
211 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
212 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
213 headers = handle_youtubedl_headers(info_dict['http_headers'])
214 args += [
215 '-headers',
216 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
217
e62d9c5c
S
218 env = None
219 proxy = self.params.get('proxy')
220 if proxy:
221 if not re.match(r'^[\da-zA-Z]+://', proxy):
222 proxy = 'http://%s' % proxy
223 # Since December 2015 ffmpeg supports -http_proxy option (see
224 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
225 # We could switch to the following code if we are able to detect version properly
226 # args += ['-http_proxy', proxy]
227 env = os.environ.copy()
228 compat_setenv('HTTP_PROXY', proxy, env=env)
50ce1c33 229 compat_setenv('http_proxy', proxy, env=env)
e62d9c5c 230
4230c489 231 protocol = info_dict.get('protocol')
232
233 if protocol == 'rtmp':
234 player_url = info_dict.get('player_url')
235 page_url = info_dict.get('page_url')
236 app = info_dict.get('app')
237 play_path = info_dict.get('play_path')
238 tc_url = info_dict.get('tc_url')
239 flash_version = info_dict.get('flash_version')
240 live = info_dict.get('rtmp_live', False)
241 if player_url is not None:
242 args += ['-rtmp_swfverify', player_url]
243 if page_url is not None:
244 args += ['-rtmp_pageurl', page_url]
245 if app is not None:
246 args += ['-rtmp_app', app]
247 if play_path is not None:
248 args += ['-rtmp_playpath', play_path]
249 if tc_url is not None:
250 args += ['-rtmp_tcurl', tc_url]
251 if flash_version is not None:
252 args += ['-rtmp_flashver', flash_version]
253 if live:
254 args += ['-rtmp_live', 'live']
255
12b84ac8 256 args += ['-i', url, '-c', 'copy']
f5436c5d 257 if protocol in ('m3u8', 'm3u8_native'):
ce599d5a 258 if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
12b84ac8 259 args += ['-f', 'mpegts']
260 else:
261 args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
4230c489 262 elif protocol == 'rtmp':
263 args += ['-f', 'flv']
12b84ac8 264 else:
a755f825 265 args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
12b84ac8 266
267 args = [encodeArgument(opt) for opt in args]
d868f43c 268 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
12b84ac8 269
270 self._debug_cmd(args)
271
e62d9c5c 272 proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
12b84ac8 273 try:
274 retval = proc.wait()
275 except KeyboardInterrupt:
276 # subprocces.run would send the SIGKILL signal to ffmpeg and the
277 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
278 # produces a file that is playable (this is mostly useful for live
279 # streams). Note that Windows is not affected and produces playable
280 # files (see https://github.com/rg3/youtube-dl/issues/8300).
281 if sys.platform != 'win32':
282 proc.communicate(b'q')
283 raise
284 return retval
285
286
287class AVconvFD(FFmpegFD):
288 pass
289
222516d9
PH
290_BY_NAME = dict(
291 (klass.get_basename(), klass)
292 for name, klass in globals().items()
293 if name.endswith('FD') and name != 'ExternalFD'
294)
295
296
297def list_external_downloaders():
298 return sorted(_BY_NAME.keys())
299
300
301def get_external_downloader(external_downloader):
302 """ Given the name of the executable, see whether we support the given
303 downloader . """
6c4d20cd
S
304 # Drop .exe extension on Windows
305 bn = os.path.splitext(os.path.basename(external_downloader))[0]
222516d9 306 return _BY_NAME[bn]