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