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