]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/external.py
Improve `--clean-infojson`
[yt-dlp.git] / yt_dlp / downloader / external.py
1 import os.path
2 import re
3 import subprocess
4 import sys
5 import time
6
7 from .fragment import FragmentFD
8 from ..compat import compat_setenv, compat_str
9 from ..postprocessor.ffmpeg import EXT_TO_OUT_FORMATS, FFmpegPostProcessor
10 from ..utils import (
11 Popen,
12 _configuration_args,
13 check_executable,
14 classproperty,
15 cli_bool_option,
16 cli_option,
17 cli_valueless_option,
18 determine_ext,
19 encodeArgument,
20 encodeFilename,
21 handle_youtubedl_headers,
22 remove_end,
23 traverse_obj,
24 )
25
26
27 class ExternalFD(FragmentFD):
28 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps')
29 can_download_to_stdout = False
30
31 def real_download(self, filename, info_dict):
32 self.report_destination(filename)
33 tmpfilename = self.temp_name(filename)
34
35 try:
36 started = time.time()
37 retval = self._call_downloader(tmpfilename, info_dict)
38 except KeyboardInterrupt:
39 if not info_dict.get('is_live'):
40 raise
41 # Live stream downloading cancellation should be considered as
42 # correct and expected termination thus all postprocessing
43 # should take place
44 retval = 0
45 self.to_screen('[%s] Interrupted by user' % self.get_basename())
46
47 if retval == 0:
48 status = {
49 'filename': filename,
50 'status': 'finished',
51 'elapsed': time.time() - started,
52 }
53 if filename != '-':
54 fsize = os.path.getsize(encodeFilename(tmpfilename))
55 self.to_screen(f'\r[{self.get_basename()}] Downloaded {fsize} bytes')
56 self.try_rename(tmpfilename, filename)
57 status.update({
58 'downloaded_bytes': fsize,
59 'total_bytes': fsize,
60 })
61 self._hook_progress(status, info_dict)
62 return True
63 else:
64 self.to_stderr('\n')
65 self.report_error('%s exited with code %d' % (
66 self.get_basename(), retval))
67 return False
68
69 @classmethod
70 def get_basename(cls):
71 return cls.__name__[:-2].lower()
72
73 @classproperty
74 def EXE_NAME(cls):
75 return cls.get_basename()
76
77 @property
78 def exe(self):
79 return self.EXE_NAME
80
81 @classmethod
82 def available(cls, path=None):
83 path = check_executable(
84 cls.EXE_NAME if path in (None, cls.get_basename()) else path,
85 [cls.AVAILABLE_OPT])
86 if not path:
87 return False
88 cls.exe = path
89 return path
90
91 @classmethod
92 def supports(cls, info_dict):
93 return (
94 (cls.can_download_to_stdout or not info_dict.get('to_stdout'))
95 and info_dict['protocol'] in cls.SUPPORTED_PROTOCOLS)
96
97 @classmethod
98 def can_download(cls, info_dict, path=None):
99 return cls.available(path) and cls.supports(info_dict)
100
101 def _option(self, command_option, param):
102 return cli_option(self.params, command_option, param)
103
104 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
105 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
106
107 def _valueless_option(self, command_option, param, expected_value=True):
108 return cli_valueless_option(self.params, command_option, param, expected_value)
109
110 def _configuration_args(self, keys=None, *args, **kwargs):
111 return _configuration_args(
112 self.get_basename(), self.params.get('external_downloader_args'), self.EXE_NAME,
113 keys, *args, **kwargs)
114
115 def _call_downloader(self, tmpfilename, info_dict):
116 """ Either overwrite this or implement _make_cmd """
117 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
118
119 self._debug_cmd(cmd)
120
121 if 'fragments' not in info_dict:
122 p = Popen(cmd, stderr=subprocess.PIPE)
123 _, stderr = p.communicate_or_kill()
124 if p.returncode != 0:
125 self.to_stderr(stderr.decode('utf-8', 'replace'))
126 return p.returncode
127
128 fragment_retries = self.params.get('fragment_retries', 0)
129 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
130
131 count = 0
132 while count <= fragment_retries:
133 p = Popen(cmd, stderr=subprocess.PIPE)
134 _, stderr = p.communicate_or_kill()
135 if p.returncode == 0:
136 break
137 # TODO: Decide whether to retry based on error code
138 # https://aria2.github.io/manual/en/html/aria2c.html#exit-status
139 self.to_stderr(stderr.decode('utf-8', 'replace'))
140 count += 1
141 if count <= fragment_retries:
142 self.to_screen(
143 '[%s] Got error. Retrying fragments (attempt %d of %s)...'
144 % (self.get_basename(), count, self.format_retries(fragment_retries)))
145 if count > fragment_retries:
146 if not skip_unavailable_fragments:
147 self.report_error('Giving up after %s fragment retries' % fragment_retries)
148 return -1
149
150 decrypt_fragment = self.decrypter(info_dict)
151 dest, _ = self.sanitize_open(tmpfilename, 'wb')
152 for frag_index, fragment in enumerate(info_dict['fragments']):
153 fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index)
154 try:
155 src, _ = self.sanitize_open(fragment_filename, 'rb')
156 except OSError as err:
157 if skip_unavailable_fragments and frag_index > 1:
158 self.report_skip_fragment(frag_index, err)
159 continue
160 self.report_error(f'Unable to open fragment {frag_index}; {err}')
161 return -1
162 dest.write(decrypt_fragment(fragment, src.read()))
163 src.close()
164 if not self.params.get('keep_fragments', False):
165 self.try_remove(encodeFilename(fragment_filename))
166 dest.close()
167 self.try_remove(encodeFilename('%s.frag.urls' % tmpfilename))
168 return 0
169
170
171 class CurlFD(ExternalFD):
172 AVAILABLE_OPT = '-V'
173
174 def _make_cmd(self, tmpfilename, info_dict):
175 cmd = [self.exe, '--location', '-o', tmpfilename, '--compressed']
176 if info_dict.get('http_headers') is not None:
177 for key, val in info_dict['http_headers'].items():
178 cmd += ['--header', f'{key}: {val}']
179
180 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
181 cmd += self._valueless_option('--silent', 'noprogress')
182 cmd += self._valueless_option('--verbose', 'verbose')
183 cmd += self._option('--limit-rate', 'ratelimit')
184 retry = self._option('--retry', 'retries')
185 if len(retry) == 2:
186 if retry[1] in ('inf', 'infinite'):
187 retry[1] = '2147483647'
188 cmd += retry
189 cmd += self._option('--max-filesize', 'max_filesize')
190 cmd += self._option('--interface', 'source_address')
191 cmd += self._option('--proxy', 'proxy')
192 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
193 cmd += self._configuration_args()
194 cmd += ['--', info_dict['url']]
195 return cmd
196
197 def _call_downloader(self, tmpfilename, info_dict):
198 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
199
200 self._debug_cmd(cmd)
201
202 # curl writes the progress to stderr so don't capture it.
203 p = Popen(cmd)
204 p.communicate_or_kill()
205 return p.returncode
206
207
208 class AxelFD(ExternalFD):
209 AVAILABLE_OPT = '-V'
210
211 def _make_cmd(self, tmpfilename, info_dict):
212 cmd = [self.exe, '-o', tmpfilename]
213 if info_dict.get('http_headers') is not None:
214 for key, val in info_dict['http_headers'].items():
215 cmd += ['-H', f'{key}: {val}']
216 cmd += self._configuration_args()
217 cmd += ['--', info_dict['url']]
218 return cmd
219
220
221 class WgetFD(ExternalFD):
222 AVAILABLE_OPT = '--version'
223
224 def _make_cmd(self, tmpfilename, info_dict):
225 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto']
226 if info_dict.get('http_headers') is not None:
227 for key, val in info_dict['http_headers'].items():
228 cmd += ['--header', f'{key}: {val}']
229 cmd += self._option('--limit-rate', 'ratelimit')
230 retry = self._option('--tries', 'retries')
231 if len(retry) == 2:
232 if retry[1] in ('inf', 'infinite'):
233 retry[1] = '0'
234 cmd += retry
235 cmd += self._option('--bind-address', 'source_address')
236 proxy = self.params.get('proxy')
237 if proxy:
238 for var in ('http_proxy', 'https_proxy'):
239 cmd += ['--execute', f'{var}={proxy}']
240 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
241 cmd += self._configuration_args()
242 cmd += ['--', info_dict['url']]
243 return cmd
244
245
246 class Aria2cFD(ExternalFD):
247 AVAILABLE_OPT = '-v'
248 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
249
250 @staticmethod
251 def supports_manifest(manifest):
252 UNSUPPORTED_FEATURES = [
253 r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1]
254 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
255 ]
256 check_results = (not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES)
257 return all(check_results)
258
259 def _make_cmd(self, tmpfilename, info_dict):
260 cmd = [self.exe, '-c',
261 '--console-log-level=warn', '--summary-interval=0', '--download-result=hide',
262 '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16']
263 if 'fragments' in info_dict:
264 cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true']
265 else:
266 cmd += ['--min-split-size', '1M']
267
268 if info_dict.get('http_headers') is not None:
269 for key, val in info_dict['http_headers'].items():
270 cmd += ['--header', f'{key}: {val}']
271 cmd += self._option('--max-overall-download-limit', 'ratelimit')
272 cmd += self._option('--interface', 'source_address')
273 cmd += self._option('--all-proxy', 'proxy')
274 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
275 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
276 cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=')
277 cmd += self._configuration_args()
278
279 # aria2c strips out spaces from the beginning/end of filenames and paths.
280 # We work around this issue by adding a "./" to the beginning of the
281 # filename and relative path, and adding a "/" at the end of the path.
282 # See: https://github.com/yt-dlp/yt-dlp/issues/276
283 # https://github.com/ytdl-org/youtube-dl/issues/20312
284 # https://github.com/aria2/aria2/issues/1373
285 dn = os.path.dirname(tmpfilename)
286 if dn:
287 if not os.path.isabs(dn):
288 dn = f'.{os.path.sep}{dn}'
289 cmd += ['--dir', dn + os.path.sep]
290 if 'fragments' not in info_dict:
291 cmd += ['--out', f'.{os.path.sep}{os.path.basename(tmpfilename)}']
292 cmd += ['--auto-file-renaming=false']
293
294 if 'fragments' in info_dict:
295 cmd += ['--file-allocation=none', '--uri-selector=inorder']
296 url_list_file = '%s.frag.urls' % tmpfilename
297 url_list = []
298 for frag_index, fragment in enumerate(info_dict['fragments']):
299 fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index)
300 url_list.append('%s\n\tout=%s' % (fragment['url'], fragment_filename))
301 stream, _ = self.sanitize_open(url_list_file, 'wb')
302 stream.write('\n'.join(url_list).encode('utf-8'))
303 stream.close()
304 cmd += ['-i', url_list_file]
305 else:
306 cmd += ['--', info_dict['url']]
307 return cmd
308
309
310 class HttpieFD(ExternalFD):
311 AVAILABLE_OPT = '--version'
312 EXE_NAME = 'http'
313
314 def _make_cmd(self, tmpfilename, info_dict):
315 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
316
317 if info_dict.get('http_headers') is not None:
318 for key, val in info_dict['http_headers'].items():
319 cmd += [f'{key}:{val}']
320 return cmd
321
322
323 class FFmpegFD(ExternalFD):
324 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments')
325 can_download_to_stdout = True
326
327 @classmethod
328 def available(cls, path=None):
329 # TODO: Fix path for ffmpeg
330 # Fixme: This may be wrong when --ffmpeg-location is used
331 return FFmpegPostProcessor().available
332
333 @classmethod
334 def supports(cls, info_dict):
335 return all(proto in cls.SUPPORTED_PROTOCOLS for proto in info_dict['protocol'].split('+'))
336
337 def on_process_started(self, proc, stdin):
338 """ Override this in subclasses """
339 pass
340
341 @classmethod
342 def can_merge_formats(cls, info_dict, params):
343 return (
344 info_dict.get('requested_formats')
345 and info_dict.get('protocol')
346 and not params.get('allow_unplayable_formats')
347 and 'no-direct-merge' not in params.get('compat_opts', [])
348 and cls.can_download(info_dict))
349
350 def _call_downloader(self, tmpfilename, info_dict):
351 urls = [f['url'] for f in info_dict.get('requested_formats', [])] or [info_dict['url']]
352 ffpp = FFmpegPostProcessor(downloader=self)
353 if not ffpp.available:
354 self.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
355 return False
356 ffpp.check_version()
357
358 args = [ffpp.executable, '-y']
359
360 for log_level in ('quiet', 'verbose'):
361 if self.params.get(log_level, False):
362 args += ['-loglevel', log_level]
363 break
364 if not self.params.get('verbose'):
365 args += ['-hide_banner']
366
367 args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[])
368
369 # These exists only for compatibility. Extractors should use
370 # info_dict['downloader_options']['ffmpeg_args'] instead
371 args += info_dict.get('_ffmpeg_args')
372 seekable = info_dict.get('_seekable')
373 if seekable is not None:
374 # setting -seekable prevents ffmpeg from guessing if the server
375 # supports seeking(by adding the header `Range: bytes=0-`), which
376 # can cause problems in some cases
377 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
378 # http://trac.ffmpeg.org/ticket/6125#comment:10
379 args += ['-seekable', '1' if seekable else '0']
380
381 # start_time = info_dict.get('start_time') or 0
382 # if start_time:
383 # args += ['-ss', compat_str(start_time)]
384 # end_time = info_dict.get('end_time')
385 # if end_time:
386 # args += ['-t', compat_str(end_time - start_time)]
387
388 http_headers = None
389 if info_dict.get('http_headers'):
390 youtubedl_headers = handle_youtubedl_headers(info_dict['http_headers'])
391 http_headers = [
392 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
393 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
394 '-headers',
395 ''.join(f'{key}: {val}\r\n' for key, val in youtubedl_headers.items())
396 ]
397
398 env = None
399 proxy = self.params.get('proxy')
400 if proxy:
401 if not re.match(r'^[\da-zA-Z]+://', proxy):
402 proxy = 'http://%s' % proxy
403
404 if proxy.startswith('socks'):
405 self.report_warning(
406 '%s does not support SOCKS proxies. Downloading is likely to fail. '
407 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
408
409 # Since December 2015 ffmpeg supports -http_proxy option (see
410 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
411 # We could switch to the following code if we are able to detect version properly
412 # args += ['-http_proxy', proxy]
413 env = os.environ.copy()
414 compat_setenv('HTTP_PROXY', proxy, env=env)
415 compat_setenv('http_proxy', proxy, env=env)
416
417 protocol = info_dict.get('protocol')
418
419 if protocol == 'rtmp':
420 player_url = info_dict.get('player_url')
421 page_url = info_dict.get('page_url')
422 app = info_dict.get('app')
423 play_path = info_dict.get('play_path')
424 tc_url = info_dict.get('tc_url')
425 flash_version = info_dict.get('flash_version')
426 live = info_dict.get('rtmp_live', False)
427 conn = info_dict.get('rtmp_conn')
428 if player_url is not None:
429 args += ['-rtmp_swfverify', player_url]
430 if page_url is not None:
431 args += ['-rtmp_pageurl', page_url]
432 if app is not None:
433 args += ['-rtmp_app', app]
434 if play_path is not None:
435 args += ['-rtmp_playpath', play_path]
436 if tc_url is not None:
437 args += ['-rtmp_tcurl', tc_url]
438 if flash_version is not None:
439 args += ['-rtmp_flashver', flash_version]
440 if live:
441 args += ['-rtmp_live', 'live']
442 if isinstance(conn, list):
443 for entry in conn:
444 args += ['-rtmp_conn', entry]
445 elif isinstance(conn, compat_str):
446 args += ['-rtmp_conn', conn]
447
448 for i, url in enumerate(urls):
449 # We need to specify headers for each http input stream
450 # otherwise, it will only be applied to the first.
451 # https://github.com/yt-dlp/yt-dlp/issues/2696
452 if http_headers is not None and re.match(r'^https?://', url):
453 args += http_headers
454 args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', url]
455
456 args += ['-c', 'copy']
457 if info_dict.get('requested_formats') or protocol == 'http_dash_segments':
458 for (i, fmt) in enumerate(info_dict.get('requested_formats') or [info_dict]):
459 stream_number = fmt.get('manifest_stream_number', 0)
460 args.extend(['-map', f'{i}:{stream_number}'])
461
462 if self.params.get('test', False):
463 args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
464
465 ext = info_dict['ext']
466 if protocol in ('m3u8', 'm3u8_native'):
467 use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts')
468 if use_mpegts is None:
469 use_mpegts = info_dict.get('is_live')
470 if use_mpegts:
471 args += ['-f', 'mpegts']
472 else:
473 args += ['-f', 'mp4']
474 if (ffpp.basename == 'ffmpeg' and ffpp._features.get('needs_adtstoasc')) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')):
475 args += ['-bsf:a', 'aac_adtstoasc']
476 elif protocol == 'rtmp':
477 args += ['-f', 'flv']
478 elif ext == 'mp4' and tmpfilename == '-':
479 args += ['-f', 'mpegts']
480 elif ext == 'unknown_video':
481 ext = determine_ext(remove_end(tmpfilename, '.part'))
482 if ext == 'unknown_video':
483 self.report_warning(
484 'The video format is unknown and cannot be downloaded by ffmpeg. '
485 'Explicitly set the extension in the filename to attempt download in that format')
486 else:
487 self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename')
488 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
489 else:
490 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
491
492 args += self._configuration_args(('_o1', '_o', ''))
493
494 args = [encodeArgument(opt) for opt in args]
495 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
496 self._debug_cmd(args)
497
498 proc = Popen(args, stdin=subprocess.PIPE, env=env)
499 if url in ('-', 'pipe:'):
500 self.on_process_started(proc, proc.stdin)
501 try:
502 retval = proc.wait()
503 except BaseException as e:
504 # subprocces.run would send the SIGKILL signal to ffmpeg and the
505 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
506 # produces a file that is playable (this is mostly useful for live
507 # streams). Note that Windows is not affected and produces playable
508 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
509 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and url not in ('-', 'pipe:'):
510 proc.communicate_or_kill(b'q')
511 else:
512 proc.kill()
513 proc.wait()
514 raise
515 return retval
516
517
518 class AVconvFD(FFmpegFD):
519 pass
520
521
522 _BY_NAME = {
523 klass.get_basename(): klass
524 for name, klass in globals().items()
525 if name.endswith('FD') and name not in ('ExternalFD', 'FragmentFD')
526 }
527
528 _BY_EXE = {klass.EXE_NAME: klass for klass in _BY_NAME.values()}
529
530
531 def list_external_downloaders():
532 return sorted(_BY_NAME.keys())
533
534
535 def get_external_downloader(external_downloader):
536 """ Given the name of the executable, see whether we support the given
537 downloader . """
538 # Drop .exe extension on Windows
539 bn = os.path.splitext(os.path.basename(external_downloader))[0]
540 return _BY_NAME.get(bn, _BY_EXE.get(bn))