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