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