[extractor/lbry] Extract original quality formats (#7257)
[yt-dlp3.git] / yt_dlp / downloader / external.py
blob007689a8c90eadc6ab3eb277601512987c5d52cf
1 import enum
2 import json
3 import os.path
4 import re
5 import subprocess
6 import sys
7 import time
8 import uuid
10 from .fragment import FragmentFD
11 from ..compat import functools
12 from ..postprocessor.ffmpeg import EXT_TO_OUT_FORMATS, FFmpegPostProcessor
13 from ..utils import (
14 Popen,
15 RetryManager,
16 _configuration_args,
17 check_executable,
18 classproperty,
19 cli_bool_option,
20 cli_option,
21 cli_valueless_option,
22 determine_ext,
23 encodeArgument,
24 encodeFilename,
25 find_available_port,
26 remove_end,
27 sanitized_Request,
28 traverse_obj,
32 class Features(enum.Enum):
33 TO_STDOUT = enum.auto()
34 MULTIPLE_FORMATS = enum.auto()
37 class ExternalFD(FragmentFD):
38 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps')
39 SUPPORTED_FEATURES = ()
40 _CAPTURE_STDERR = True
42 def real_download(self, filename, info_dict):
43 self.report_destination(filename)
44 tmpfilename = self.temp_name(filename)
46 try:
47 started = time.time()
48 retval = self._call_downloader(tmpfilename, info_dict)
49 except KeyboardInterrupt:
50 if not info_dict.get('is_live'):
51 raise
52 # Live stream downloading cancellation should be considered as
53 # correct and expected termination thus all postprocessing
54 # should take place
55 retval = 0
56 self.to_screen('[%s] Interrupted by user' % self.get_basename())
58 if retval == 0:
59 status = {
60 'filename': filename,
61 'status': 'finished',
62 'elapsed': time.time() - started,
64 if filename != '-':
65 fsize = os.path.getsize(encodeFilename(tmpfilename))
66 self.try_rename(tmpfilename, filename)
67 status.update({
68 'downloaded_bytes': fsize,
69 'total_bytes': fsize,
71 self._hook_progress(status, info_dict)
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
79 @classmethod
80 def get_basename(cls):
81 return cls.__name__[:-2].lower()
83 @classproperty
84 def EXE_NAME(cls):
85 return cls.get_basename()
87 @functools.cached_property
88 def exe(self):
89 return self.EXE_NAME
91 @classmethod
92 def available(cls, path=None):
93 path = check_executable(
94 cls.EXE_NAME if path in (None, cls.get_basename()) else path,
95 [cls.AVAILABLE_OPT])
96 if not path:
97 return False
98 cls.exe = path
99 return path
101 @classmethod
102 def supports(cls, info_dict):
103 return all((
104 not info_dict.get('to_stdout') or Features.TO_STDOUT in cls.SUPPORTED_FEATURES,
105 '+' not in info_dict['protocol'] or Features.MULTIPLE_FORMATS in cls.SUPPORTED_FEATURES,
106 not traverse_obj(info_dict, ('hls_aes', ...), 'extra_param_to_segment_url'),
107 all(proto in cls.SUPPORTED_PROTOCOLS for proto in info_dict['protocol'].split('+')),
110 @classmethod
111 def can_download(cls, info_dict, path=None):
112 return cls.available(path) and cls.supports(info_dict)
114 def _option(self, command_option, param):
115 return cli_option(self.params, command_option, param)
117 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
118 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
120 def _valueless_option(self, command_option, param, expected_value=True):
121 return cli_valueless_option(self.params, command_option, param, expected_value)
123 def _configuration_args(self, keys=None, *args, **kwargs):
124 return _configuration_args(
125 self.get_basename(), self.params.get('external_downloader_args'), self.EXE_NAME,
126 keys, *args, **kwargs)
128 def _call_downloader(self, tmpfilename, info_dict):
129 """ Either overwrite this or implement _make_cmd """
130 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
132 self._debug_cmd(cmd)
134 if 'fragments' not in info_dict:
135 _, stderr, returncode = self._call_process(cmd, info_dict)
136 if returncode and stderr:
137 self.to_stderr(stderr)
138 return returncode
140 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
142 retry_manager = RetryManager(self.params.get('fragment_retries'), self.report_retry,
143 frag_index=None, fatal=not skip_unavailable_fragments)
144 for retry in retry_manager:
145 _, stderr, returncode = self._call_process(cmd, info_dict)
146 if not returncode:
147 break
148 # TODO: Decide whether to retry based on error code
149 # https://aria2.github.io/manual/en/html/aria2c.html#exit-status
150 if stderr:
151 self.to_stderr(stderr)
152 retry.error = Exception()
153 continue
154 if not skip_unavailable_fragments and retry_manager.error:
155 return -1
157 decrypt_fragment = self.decrypter(info_dict)
158 dest, _ = self.sanitize_open(tmpfilename, 'wb')
159 for frag_index, fragment in enumerate(info_dict['fragments']):
160 fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index)
161 try:
162 src, _ = self.sanitize_open(fragment_filename, 'rb')
163 except OSError as err:
164 if skip_unavailable_fragments and frag_index > 1:
165 self.report_skip_fragment(frag_index, err)
166 continue
167 self.report_error(f'Unable to open fragment {frag_index}; {err}')
168 return -1
169 dest.write(decrypt_fragment(fragment, src.read()))
170 src.close()
171 if not self.params.get('keep_fragments', False):
172 self.try_remove(encodeFilename(fragment_filename))
173 dest.close()
174 self.try_remove(encodeFilename('%s.frag.urls' % tmpfilename))
175 return 0
177 def _call_process(self, cmd, info_dict):
178 return Popen.run(cmd, text=True, stderr=subprocess.PIPE if self._CAPTURE_STDERR else None)
181 class CurlFD(ExternalFD):
182 AVAILABLE_OPT = '-V'
183 _CAPTURE_STDERR = False # curl writes the progress to stderr
185 def _make_cmd(self, tmpfilename, info_dict):
186 cmd = [self.exe, '--location', '-o', tmpfilename, '--compressed']
187 if info_dict.get('http_headers') is not None:
188 for key, val in info_dict['http_headers'].items():
189 cmd += ['--header', f'{key}: {val}']
191 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
192 cmd += self._valueless_option('--silent', 'noprogress')
193 cmd += self._valueless_option('--verbose', 'verbose')
194 cmd += self._option('--limit-rate', 'ratelimit')
195 retry = self._option('--retry', 'retries')
196 if len(retry) == 2:
197 if retry[1] in ('inf', 'infinite'):
198 retry[1] = '2147483647'
199 cmd += retry
200 cmd += self._option('--max-filesize', 'max_filesize')
201 cmd += self._option('--interface', 'source_address')
202 cmd += self._option('--proxy', 'proxy')
203 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
204 cmd += self._configuration_args()
205 cmd += ['--', info_dict['url']]
206 return cmd
209 class AxelFD(ExternalFD):
210 AVAILABLE_OPT = '-V'
212 def _make_cmd(self, tmpfilename, info_dict):
213 cmd = [self.exe, '-o', tmpfilename]
214 if info_dict.get('http_headers') is not None:
215 for key, val in info_dict['http_headers'].items():
216 cmd += ['-H', f'{key}: {val}']
217 cmd += self._configuration_args()
218 cmd += ['--', info_dict['url']]
219 return cmd
222 class WgetFD(ExternalFD):
223 AVAILABLE_OPT = '--version'
225 def _make_cmd(self, tmpfilename, info_dict):
226 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto']
227 if info_dict.get('http_headers') is not None:
228 for key, val in info_dict['http_headers'].items():
229 cmd += ['--header', f'{key}: {val}']
230 cmd += self._option('--limit-rate', 'ratelimit')
231 retry = self._option('--tries', 'retries')
232 if len(retry) == 2:
233 if retry[1] in ('inf', 'infinite'):
234 retry[1] = '0'
235 cmd += retry
236 cmd += self._option('--bind-address', 'source_address')
237 proxy = self.params.get('proxy')
238 if proxy:
239 for var in ('http_proxy', 'https_proxy'):
240 cmd += ['--execute', f'{var}={proxy}']
241 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
242 cmd += self._configuration_args()
243 cmd += ['--', info_dict['url']]
244 return cmd
247 class Aria2cFD(ExternalFD):
248 AVAILABLE_OPT = '-v'
249 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
251 @staticmethod
252 def supports_manifest(manifest):
253 UNSUPPORTED_FEATURES = [
254 r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1]
255 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
257 check_results = (not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES)
258 return all(check_results)
260 @staticmethod
261 def _aria2c_filename(fn):
262 return fn if os.path.isabs(fn) else f'.{os.path.sep}{fn}'
264 def _call_downloader(self, tmpfilename, info_dict):
265 # FIXME: Disabled due to https://github.com/yt-dlp/yt-dlp/issues/5931
266 if False and 'no-external-downloader-progress' not in self.params.get('compat_opts', []):
267 info_dict['__rpc'] = {
268 'port': find_available_port() or 19190,
269 'secret': str(uuid.uuid4()),
271 return super()._call_downloader(tmpfilename, info_dict)
273 def _make_cmd(self, tmpfilename, info_dict):
274 cmd = [self.exe, '-c',
275 '--console-log-level=warn', '--summary-interval=0', '--download-result=hide',
276 '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16']
277 if 'fragments' in info_dict:
278 cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true']
279 else:
280 cmd += ['--min-split-size', '1M']
282 if info_dict.get('http_headers') is not None:
283 for key, val in info_dict['http_headers'].items():
284 cmd += ['--header', f'{key}: {val}']
285 cmd += self._option('--max-overall-download-limit', 'ratelimit')
286 cmd += self._option('--interface', 'source_address')
287 cmd += self._option('--all-proxy', 'proxy')
288 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
289 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
290 cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=')
291 cmd += self._configuration_args()
293 if '__rpc' in info_dict:
294 cmd += [
295 '--enable-rpc',
296 f'--rpc-listen-port={info_dict["__rpc"]["port"]}',
297 f'--rpc-secret={info_dict["__rpc"]["secret"]}']
299 # aria2c strips out spaces from the beginning/end of filenames and paths.
300 # We work around this issue by adding a "./" to the beginning of the
301 # filename and relative path, and adding a "/" at the end of the path.
302 # See: https://github.com/yt-dlp/yt-dlp/issues/276
303 # https://github.com/ytdl-org/youtube-dl/issues/20312
304 # https://github.com/aria2/aria2/issues/1373
305 dn = os.path.dirname(tmpfilename)
306 if dn:
307 cmd += ['--dir', self._aria2c_filename(dn) + os.path.sep]
308 if 'fragments' not in info_dict:
309 cmd += ['--out', self._aria2c_filename(os.path.basename(tmpfilename))]
310 cmd += ['--auto-file-renaming=false']
312 if 'fragments' in info_dict:
313 cmd += ['--file-allocation=none', '--uri-selector=inorder']
314 url_list_file = '%s.frag.urls' % tmpfilename
315 url_list = []
316 for frag_index, fragment in enumerate(info_dict['fragments']):
317 fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index)
318 url_list.append('%s\n\tout=%s' % (fragment['url'], self._aria2c_filename(fragment_filename)))
319 stream, _ = self.sanitize_open(url_list_file, 'wb')
320 stream.write('\n'.join(url_list).encode())
321 stream.close()
322 cmd += ['-i', self._aria2c_filename(url_list_file)]
323 else:
324 cmd += ['--', info_dict['url']]
325 return cmd
327 def aria2c_rpc(self, rpc_port, rpc_secret, method, params=()):
328 # Does not actually need to be UUID, just unique
329 sanitycheck = str(uuid.uuid4())
330 d = json.dumps({
331 'jsonrpc': '2.0',
332 'id': sanitycheck,
333 'method': method,
334 'params': [f'token:{rpc_secret}', *params],
335 }).encode('utf-8')
336 request = sanitized_Request(
337 f'http://localhost:{rpc_port}/jsonrpc',
338 data=d, headers={
339 'Content-Type': 'application/json',
340 'Content-Length': f'{len(d)}',
341 'Ytdl-request-proxy': '__noproxy__',
343 with self.ydl.urlopen(request) as r:
344 resp = json.load(r)
345 assert resp.get('id') == sanitycheck, 'Something went wrong with RPC server'
346 return resp['result']
348 def _call_process(self, cmd, info_dict):
349 if '__rpc' not in info_dict:
350 return super()._call_process(cmd, info_dict)
352 send_rpc = functools.partial(self.aria2c_rpc, info_dict['__rpc']['port'], info_dict['__rpc']['secret'])
353 started = time.time()
355 fragmented = 'fragments' in info_dict
356 frag_count = len(info_dict['fragments']) if fragmented else 1
357 status = {
358 'filename': info_dict.get('_filename'),
359 'status': 'downloading',
360 'elapsed': 0,
361 'downloaded_bytes': 0,
362 'fragment_count': frag_count if fragmented else None,
363 'fragment_index': 0 if fragmented else None,
365 self._hook_progress(status, info_dict)
367 def get_stat(key, *obj, average=False):
368 val = tuple(filter(None, map(float, traverse_obj(obj, (..., ..., key))))) or [0]
369 return sum(val) / (len(val) if average else 1)
371 with Popen(cmd, text=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) as p:
372 # Add a small sleep so that RPC client can receive response,
373 # or the connection stalls infinitely
374 time.sleep(0.2)
375 retval = p.poll()
376 while retval is None:
377 # We don't use tellStatus as we won't know the GID without reading stdout
378 # Ref: https://aria2.github.io/manual/en/html/aria2c.html#aria2.tellActive
379 active = send_rpc('aria2.tellActive')
380 completed = send_rpc('aria2.tellStopped', [0, frag_count])
382 downloaded = get_stat('totalLength', completed) + get_stat('completedLength', active)
383 speed = get_stat('downloadSpeed', active)
384 total = frag_count * get_stat('totalLength', active, completed, average=True)
385 if total < downloaded:
386 total = None
388 status.update({
389 'downloaded_bytes': int(downloaded),
390 'speed': speed,
391 'total_bytes': None if fragmented else total,
392 'total_bytes_estimate': total,
393 'eta': (total - downloaded) / (speed or 1),
394 'fragment_index': min(frag_count, len(completed) + 1) if fragmented else None,
395 'elapsed': time.time() - started
397 self._hook_progress(status, info_dict)
399 if not active and len(completed) >= frag_count:
400 send_rpc('aria2.shutdown')
401 retval = p.wait()
402 break
404 time.sleep(0.1)
405 retval = p.poll()
407 return '', p.stderr.read(), retval
410 class HttpieFD(ExternalFD):
411 AVAILABLE_OPT = '--version'
412 EXE_NAME = 'http'
414 def _make_cmd(self, tmpfilename, info_dict):
415 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
417 if info_dict.get('http_headers') is not None:
418 for key, val in info_dict['http_headers'].items():
419 cmd += [f'{key}:{val}']
420 return cmd
423 class FFmpegFD(ExternalFD):
424 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments')
425 SUPPORTED_FEATURES = (Features.TO_STDOUT, Features.MULTIPLE_FORMATS)
427 @classmethod
428 def available(cls, path=None):
429 # TODO: Fix path for ffmpeg
430 # Fixme: This may be wrong when --ffmpeg-location is used
431 return FFmpegPostProcessor().available
433 def on_process_started(self, proc, stdin):
434 """ Override this in subclasses """
435 pass
437 @classmethod
438 def can_merge_formats(cls, info_dict, params):
439 return (
440 info_dict.get('requested_formats')
441 and info_dict.get('protocol')
442 and not params.get('allow_unplayable_formats')
443 and 'no-direct-merge' not in params.get('compat_opts', [])
444 and cls.can_download(info_dict))
446 def _call_downloader(self, tmpfilename, info_dict):
447 ffpp = FFmpegPostProcessor(downloader=self)
448 if not ffpp.available:
449 self.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
450 return False
451 ffpp.check_version()
453 args = [ffpp.executable, '-y']
455 for log_level in ('quiet', 'verbose'):
456 if self.params.get(log_level, False):
457 args += ['-loglevel', log_level]
458 break
459 if not self.params.get('verbose'):
460 args += ['-hide_banner']
462 args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[])
464 # These exists only for compatibility. Extractors should use
465 # info_dict['downloader_options']['ffmpeg_args'] instead
466 args += info_dict.get('_ffmpeg_args') or []
467 seekable = info_dict.get('_seekable')
468 if seekable is not None:
469 # setting -seekable prevents ffmpeg from guessing if the server
470 # supports seeking(by adding the header `Range: bytes=0-`), which
471 # can cause problems in some cases
472 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
473 # http://trac.ffmpeg.org/ticket/6125#comment:10
474 args += ['-seekable', '1' if seekable else '0']
476 env = None
477 proxy = self.params.get('proxy')
478 if proxy:
479 if not re.match(r'^[\da-zA-Z]+://', proxy):
480 proxy = 'http://%s' % proxy
482 if proxy.startswith('socks'):
483 self.report_warning(
484 '%s does not support SOCKS proxies. Downloading is likely to fail. '
485 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
487 # Since December 2015 ffmpeg supports -http_proxy option (see
488 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
489 # We could switch to the following code if we are able to detect version properly
490 # args += ['-http_proxy', proxy]
491 env = os.environ.copy()
492 env['HTTP_PROXY'] = proxy
493 env['http_proxy'] = proxy
495 protocol = info_dict.get('protocol')
497 if protocol == 'rtmp':
498 player_url = info_dict.get('player_url')
499 page_url = info_dict.get('page_url')
500 app = info_dict.get('app')
501 play_path = info_dict.get('play_path')
502 tc_url = info_dict.get('tc_url')
503 flash_version = info_dict.get('flash_version')
504 live = info_dict.get('rtmp_live', False)
505 conn = info_dict.get('rtmp_conn')
506 if player_url is not None:
507 args += ['-rtmp_swfverify', player_url]
508 if page_url is not None:
509 args += ['-rtmp_pageurl', page_url]
510 if app is not None:
511 args += ['-rtmp_app', app]
512 if play_path is not None:
513 args += ['-rtmp_playpath', play_path]
514 if tc_url is not None:
515 args += ['-rtmp_tcurl', tc_url]
516 if flash_version is not None:
517 args += ['-rtmp_flashver', flash_version]
518 if live:
519 args += ['-rtmp_live', 'live']
520 if isinstance(conn, list):
521 for entry in conn:
522 args += ['-rtmp_conn', entry]
523 elif isinstance(conn, str):
524 args += ['-rtmp_conn', conn]
526 start_time, end_time = info_dict.get('section_start') or 0, info_dict.get('section_end')
528 selected_formats = info_dict.get('requested_formats') or [info_dict]
529 for i, fmt in enumerate(selected_formats):
530 if fmt.get('http_headers') and re.match(r'^https?://', fmt['url']):
531 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
532 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
533 args.extend(['-headers', ''.join(f'{key}: {val}\r\n' for key, val in fmt['http_headers'].items())])
535 if start_time:
536 args += ['-ss', str(start_time)]
537 if end_time:
538 args += ['-t', str(end_time - start_time)]
540 args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', fmt['url']]
542 if not (start_time or end_time) or not self.params.get('force_keyframes_at_cuts'):
543 args += ['-c', 'copy']
545 if info_dict.get('requested_formats') or protocol == 'http_dash_segments':
546 for i, fmt in enumerate(selected_formats):
547 stream_number = fmt.get('manifest_stream_number', 0)
548 args.extend(['-map', f'{i}:{stream_number}'])
550 if self.params.get('test', False):
551 args += ['-fs', str(self._TEST_FILE_SIZE)]
553 ext = info_dict['ext']
554 if protocol in ('m3u8', 'm3u8_native'):
555 use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts')
556 if use_mpegts is None:
557 use_mpegts = info_dict.get('is_live')
558 if use_mpegts:
559 args += ['-f', 'mpegts']
560 else:
561 args += ['-f', 'mp4']
562 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')):
563 args += ['-bsf:a', 'aac_adtstoasc']
564 elif protocol == 'rtmp':
565 args += ['-f', 'flv']
566 elif ext == 'mp4' and tmpfilename == '-':
567 args += ['-f', 'mpegts']
568 elif ext == 'unknown_video':
569 ext = determine_ext(remove_end(tmpfilename, '.part'))
570 if ext == 'unknown_video':
571 self.report_warning(
572 'The video format is unknown and cannot be downloaded by ffmpeg. '
573 'Explicitly set the extension in the filename to attempt download in that format')
574 else:
575 self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename')
576 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
577 else:
578 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
580 args += self._configuration_args(('_o1', '_o', ''))
582 args = [encodeArgument(opt) for opt in args]
583 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
584 self._debug_cmd(args)
586 piped = any(fmt['url'] in ('-', 'pipe:') for fmt in selected_formats)
587 with Popen(args, stdin=subprocess.PIPE, env=env) as proc:
588 if piped:
589 self.on_process_started(proc, proc.stdin)
590 try:
591 retval = proc.wait()
592 except BaseException as e:
593 # subprocces.run would send the SIGKILL signal to ffmpeg and the
594 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
595 # produces a file that is playable (this is mostly useful for live
596 # streams). Note that Windows is not affected and produces playable
597 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
598 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and not piped:
599 proc.communicate_or_kill(b'q')
600 else:
601 proc.kill(timeout=None)
602 raise
603 return retval
606 class AVconvFD(FFmpegFD):
607 pass
610 _BY_NAME = {
611 klass.get_basename(): klass
612 for name, klass in globals().items()
613 if name.endswith('FD') and name not in ('ExternalFD', 'FragmentFD')
617 def list_external_downloaders():
618 return sorted(_BY_NAME.keys())
621 def get_external_downloader(external_downloader):
622 """ Given the name of the executable, see whether we support the given downloader """
623 bn = os.path.splitext(os.path.basename(external_downloader))[0]
624 return _BY_NAME.get(bn) or next((
625 klass for klass in _BY_NAME.values() if klass.EXE_NAME in bn
626 ), None)