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