[cleanup] Misc (#10807)
[yt-dlp.git] / yt_dlp / __init__.py
blobc2d19f94a087e2ac8186907631b0a46b287f8437
1 import sys
3 if sys.version_info < (3, 8):
4 raise ImportError(
5 f'You are using an unsupported version of Python. Only Python versions 3.8 and above are supported by yt-dlp') # noqa: F541
7 __license__ = 'The Unlicense'
9 import collections
10 import getpass
11 import itertools
12 import optparse
13 import os
14 import re
15 import traceback
17 from .compat import compat_os_name
18 from .cookies import SUPPORTED_BROWSERS, SUPPORTED_KEYRINGS
19 from .downloader.external import get_external_downloader
20 from .extractor import list_extractor_classes
21 from .extractor.adobepass import MSO_INFO
22 from .networking.impersonate import ImpersonateTarget
23 from .options import parseOpts
24 from .postprocessor import (
25 FFmpegExtractAudioPP,
26 FFmpegMergerPP,
27 FFmpegPostProcessor,
28 FFmpegSubtitlesConvertorPP,
29 FFmpegThumbnailsConvertorPP,
30 FFmpegVideoConvertorPP,
31 FFmpegVideoRemuxerPP,
32 MetadataFromFieldPP,
33 MetadataParserPP,
35 from .update import Updater
36 from .utils import (
37 NO_DEFAULT,
38 POSTPROCESS_WHEN,
39 DateRange,
40 DownloadCancelled,
41 DownloadError,
42 FormatSorter,
43 GeoUtils,
44 PlaylistEntries,
45 SameFileError,
46 decodeOption,
47 download_range_func,
48 expand_path,
49 float_or_none,
50 format_field,
51 int_or_none,
52 join_nonempty,
53 match_filter_func,
54 parse_bytes,
55 parse_duration,
56 preferredencoding,
57 read_batch_urls,
58 read_stdin,
59 render_table,
60 setproctitle,
61 shell_quote,
62 traverse_obj,
63 variadic,
64 write_string,
66 from .utils.networking import std_headers
67 from .utils._utils import _UnsafeExtensionError
68 from .YoutubeDL import YoutubeDL
70 _IN_CLI = False
73 def _exit(status=0, *args):
74 for msg in args:
75 sys.stderr.write(msg)
76 raise SystemExit(status)
79 def get_urls(urls, batchfile, verbose):
80 """
81 @param verbose -1: quiet, 0: normal, 1: verbose
82 """
83 batch_urls = []
84 if batchfile is not None:
85 try:
86 batch_urls = read_batch_urls(
87 read_stdin(None if verbose == -1 else 'URLs') if batchfile == '-'
88 else open(expand_path(batchfile), encoding='utf-8', errors='ignore'))
89 if verbose == 1:
90 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
91 except OSError:
92 _exit(f'ERROR: batch file {batchfile} could not be read')
93 _enc = preferredencoding()
94 return [
95 url.strip().decode(_enc, 'ignore') if isinstance(url, bytes) else url.strip()
96 for url in batch_urls + urls]
99 def print_extractor_information(opts, urls):
100 out = ''
101 if opts.list_extractors:
102 # Importing GenericIE is currently slow since it imports YoutubeIE
103 from .extractor.generic import GenericIE
105 urls = dict.fromkeys(urls, False)
106 for ie in list_extractor_classes(opts.age_limit):
107 out += ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie.working() else '') + '\n'
108 if ie == GenericIE:
109 matched_urls = [url for url, matched in urls.items() if not matched]
110 else:
111 matched_urls = tuple(filter(ie.suitable, urls.keys()))
112 urls.update(dict.fromkeys(matched_urls, True))
113 out += ''.join(f' {url}\n' for url in matched_urls)
114 elif opts.list_extractor_descriptions:
115 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
116 out = '\n'.join(
117 ie.description(markdown=False, search_examples=_SEARCHES)
118 for ie in list_extractor_classes(opts.age_limit) if ie.working() and ie.IE_DESC is not False)
119 elif opts.ap_list_mso:
120 out = 'Supported TV Providers:\n{}\n'.format(render_table(
121 ['mso', 'mso name'],
122 [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()]))
123 else:
124 return False
125 write_string(out, out=sys.stdout)
126 return True
129 def set_compat_opts(opts):
130 def _unused_compat_opt(name):
131 if name not in opts.compat_opts:
132 return False
133 opts.compat_opts.discard(name)
134 opts.compat_opts.update([f'*{name}'])
135 return True
137 def set_default_compat(compat_name, opt_name, default=True, remove_compat=True):
138 attr = getattr(opts, opt_name)
139 if compat_name in opts.compat_opts:
140 if attr is None:
141 setattr(opts, opt_name, not default)
142 return True
143 else:
144 if remove_compat:
145 _unused_compat_opt(compat_name)
146 return False
147 elif attr is None:
148 setattr(opts, opt_name, default)
149 return None
151 set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
152 set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
153 set_default_compat('no-clean-infojson', 'clean_infojson')
154 if 'no-attach-info-json' in opts.compat_opts:
155 if opts.embed_infojson:
156 _unused_compat_opt('no-attach-info-json')
157 else:
158 opts.embed_infojson = False
159 if 'format-sort' in opts.compat_opts:
160 opts.format_sort.extend(FormatSorter.ytdl_default)
161 _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False)
162 _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False)
163 if _video_multistreams_set is False and _audio_multistreams_set is False:
164 _unused_compat_opt('multistreams')
165 if 'filename' in opts.compat_opts:
166 if opts.outtmpl.get('default') is None:
167 opts.outtmpl.update({'default': '%(title)s-%(id)s.%(ext)s'})
168 else:
169 _unused_compat_opt('filename')
172 def validate_options(opts):
173 def validate(cndn, name, value=None, msg=None):
174 if cndn:
175 return True
176 raise ValueError((msg or 'invalid {name} "{value}" given').format(name=name, value=value))
178 def validate_in(name, value, items, msg=None):
179 return validate(value is None or value in items, name, value, msg)
181 def validate_regex(name, value, regex):
182 return validate(value is None or re.match(regex, value), name, value)
184 def validate_positive(name, value, strict=False):
185 return validate(value is None or value > 0 or (not strict and value == 0),
186 name, value, '{name} "{value}" must be positive' + ('' if strict else ' or 0'))
188 def validate_minmax(min_val, max_val, min_name, max_name=None):
189 if max_val is None or min_val is None or max_val >= min_val:
190 return
191 if not max_name:
192 min_name, max_name = f'min {min_name}', f'max {min_name}'
193 raise ValueError(f'{max_name} "{max_val}" must be must be greater than or equal to {min_name} "{min_val}"')
195 # Usernames and passwords
196 validate(sum(map(bool, (opts.usenetrc, opts.netrc_cmd, opts.username))) <= 1, '.netrc',
197 msg='{name}, netrc command and username/password are mutually exclusive options')
198 validate(opts.password is None or opts.username is not None, 'account username', msg='{name} missing')
199 validate(opts.ap_password is None or opts.ap_username is not None,
200 'TV Provider account username', msg='{name} missing')
201 validate_in('TV Provider', opts.ap_mso, MSO_INFO,
202 'Unsupported {name} "{value}", use --ap-list-mso to get a list of supported TV Providers')
204 # Numbers
205 validate_positive('autonumber start', opts.autonumber_start)
206 validate_positive('autonumber size', opts.autonumber_size, True)
207 validate_positive('concurrent fragments', opts.concurrent_fragment_downloads, True)
208 validate_positive('playlist start', opts.playliststart, True)
209 if opts.playlistend != -1:
210 validate_minmax(opts.playliststart, opts.playlistend, 'playlist start', 'playlist end')
212 # Time ranges
213 validate_positive('subtitles sleep interval', opts.sleep_interval_subtitles)
214 validate_positive('requests sleep interval', opts.sleep_interval_requests)
215 validate_positive('sleep interval', opts.sleep_interval)
216 validate_positive('max sleep interval', opts.max_sleep_interval)
217 if opts.sleep_interval is None:
218 validate(
219 opts.max_sleep_interval is None, 'min sleep interval',
220 msg='{name} must be specified; use --min-sleep-interval')
221 elif opts.max_sleep_interval is None:
222 opts.max_sleep_interval = opts.sleep_interval
223 else:
224 validate_minmax(opts.sleep_interval, opts.max_sleep_interval, 'sleep interval')
226 if opts.wait_for_video is not None:
227 min_wait, max_wait, *_ = map(parse_duration, [*opts.wait_for_video.split('-', 1), None])
228 validate(min_wait is not None and not (max_wait is None and '-' in opts.wait_for_video),
229 'time range to wait for video', opts.wait_for_video)
230 validate_minmax(min_wait, max_wait, 'time range to wait for video')
231 opts.wait_for_video = (min_wait, max_wait)
233 # Format sort
234 for f in opts.format_sort:
235 validate_regex('format sorting', f, FormatSorter.regex)
237 # Postprocessor formats
238 if opts.convertsubtitles == 'none':
239 opts.convertsubtitles = None
240 if opts.convertthumbnails == 'none':
241 opts.convertthumbnails = None
243 validate_regex('merge output format', opts.merge_output_format,
244 r'({0})(/({0}))*'.format('|'.join(map(re.escape, FFmpegMergerPP.SUPPORTED_EXTS))))
245 validate_regex('audio format', opts.audioformat, FFmpegExtractAudioPP.FORMAT_RE)
246 validate_in('subtitle format', opts.convertsubtitles, FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS)
247 validate_regex('thumbnail format', opts.convertthumbnails, FFmpegThumbnailsConvertorPP.FORMAT_RE)
248 validate_regex('recode video format', opts.recodevideo, FFmpegVideoConvertorPP.FORMAT_RE)
249 validate_regex('remux video format', opts.remuxvideo, FFmpegVideoRemuxerPP.FORMAT_RE)
250 if opts.audioquality:
251 opts.audioquality = opts.audioquality.strip('k').strip('K')
252 # int_or_none prevents inf, nan
253 validate_positive('audio quality', int_or_none(float_or_none(opts.audioquality), default=0))
255 # Retries
256 def parse_retries(name, value):
257 if value is None:
258 return None
259 elif value in ('inf', 'infinite'):
260 return float('inf')
261 try:
262 return int(value)
263 except (TypeError, ValueError):
264 validate(False, f'{name} retry count', value)
266 opts.retries = parse_retries('download', opts.retries)
267 opts.fragment_retries = parse_retries('fragment', opts.fragment_retries)
268 opts.extractor_retries = parse_retries('extractor', opts.extractor_retries)
269 opts.file_access_retries = parse_retries('file access', opts.file_access_retries)
271 # Retry sleep function
272 def parse_sleep_func(expr):
273 NUMBER_RE = r'\d+(?:\.\d+)?'
274 op, start, limit, step, *_ = (*tuple(re.fullmatch(
275 rf'(?:(linear|exp)=)?({NUMBER_RE})(?::({NUMBER_RE})?)?(?::({NUMBER_RE}))?',
276 expr.strip()).groups()), None, None)
278 if op == 'exp':
279 return lambda n: min(float(start) * (float(step or 2) ** n), float(limit or 'inf'))
280 else:
281 default_step = start if op or limit else 0
282 return lambda n: min(float(start) + float(step or default_step) * n, float(limit or 'inf'))
284 for key, expr in opts.retry_sleep.items():
285 if not expr:
286 del opts.retry_sleep[key]
287 continue
288 try:
289 opts.retry_sleep[key] = parse_sleep_func(expr)
290 except AttributeError:
291 raise ValueError(f'invalid {key} retry sleep expression {expr!r}')
293 # Bytes
294 def validate_bytes(name, value):
295 if value is None:
296 return None
297 numeric_limit = parse_bytes(value)
298 validate(numeric_limit is not None, 'rate limit', value)
299 return numeric_limit
301 opts.ratelimit = validate_bytes('rate limit', opts.ratelimit)
302 opts.throttledratelimit = validate_bytes('throttled rate limit', opts.throttledratelimit)
303 opts.min_filesize = validate_bytes('min filesize', opts.min_filesize)
304 opts.max_filesize = validate_bytes('max filesize', opts.max_filesize)
305 opts.buffersize = validate_bytes('buffer size', opts.buffersize)
306 opts.http_chunk_size = validate_bytes('http chunk size', opts.http_chunk_size)
308 # Output templates
309 def validate_outtmpl(tmpl, msg):
310 err = YoutubeDL.validate_outtmpl(tmpl)
311 if err:
312 raise ValueError(f'invalid {msg} "{tmpl}": {err}')
314 for k, tmpl in opts.outtmpl.items():
315 validate_outtmpl(tmpl, f'{k} output template')
316 for type_, tmpl_list in opts.forceprint.items():
317 for tmpl in tmpl_list:
318 validate_outtmpl(tmpl, f'{type_} print template')
319 for type_, tmpl_list in opts.print_to_file.items():
320 for tmpl, file in tmpl_list:
321 validate_outtmpl(tmpl, f'{type_} print to file template')
322 validate_outtmpl(file, f'{type_} print to file filename')
323 validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
324 for k, tmpl in opts.progress_template.items():
325 k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
326 validate_outtmpl(tmpl, f'{k} template')
328 outtmpl_default = opts.outtmpl.get('default')
329 if outtmpl_default == '':
330 opts.skip_download = None
331 del opts.outtmpl['default']
333 def parse_chapters(name, value, advanced=False):
334 parse_timestamp = lambda x: float('inf') if x in ('inf', 'infinite') else parse_duration(x)
335 TIMESTAMP_RE = r'''(?x)(?:
336 (?P<start_sign>-?)(?P<start>[^-]+)
337 )?\s*-\s*(?:
338 (?P<end_sign>-?)(?P<end>[^-]+)
339 )?'''
341 chapters, ranges, from_url = [], [], False
342 for regex in value or []:
343 if advanced and regex == '*from-url':
344 from_url = True
345 continue
346 elif not regex.startswith('*'):
347 try:
348 chapters.append(re.compile(regex))
349 except re.error as err:
350 raise ValueError(f'invalid {name} regex "{regex}" - {err}')
351 continue
353 for range_ in map(str.strip, regex[1:].split(',')):
354 mobj = range_ != '-' and re.fullmatch(TIMESTAMP_RE, range_)
355 dur = mobj and [parse_timestamp(mobj.group('start') or '0'), parse_timestamp(mobj.group('end') or 'inf')]
356 signs = mobj and (mobj.group('start_sign'), mobj.group('end_sign'))
358 err = None
359 if None in (dur or [None]):
360 err = 'Must be of the form "*start-end"'
361 elif not advanced and any(signs):
362 err = 'Negative timestamps are not allowed'
363 else:
364 dur[0] *= -1 if signs[0] else 1
365 dur[1] *= -1 if signs[1] else 1
366 if dur[1] == float('-inf'):
367 err = '"-inf" is not a valid end'
368 if err:
369 raise ValueError(f'invalid {name} time range "{regex}". {err}')
370 ranges.append(dur)
372 return chapters, ranges, from_url
374 opts.remove_chapters, opts.remove_ranges, _ = parse_chapters('--remove-chapters', opts.remove_chapters)
375 opts.download_ranges = download_range_func(*parse_chapters('--download-sections', opts.download_ranges, True))
377 # Cookies from browser
378 if opts.cookiesfrombrowser:
379 container = None
380 mobj = re.fullmatch(r'''(?x)
381 (?P<name>[^+:]+)
382 (?:\s*\+\s*(?P<keyring>[^:]+))?
383 (?:\s*:\s*(?!:)(?P<profile>.+?))?
384 (?:\s*::\s*(?P<container>.+))?
385 ''', opts.cookiesfrombrowser)
386 if mobj is None:
387 raise ValueError(f'invalid cookies from browser arguments: {opts.cookiesfrombrowser}')
388 browser_name, keyring, profile, container = mobj.group('name', 'keyring', 'profile', 'container')
389 browser_name = browser_name.lower()
390 if browser_name not in SUPPORTED_BROWSERS:
391 raise ValueError(f'unsupported browser specified for cookies: "{browser_name}". '
392 f'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}')
393 if keyring is not None:
394 keyring = keyring.upper()
395 if keyring not in SUPPORTED_KEYRINGS:
396 raise ValueError(f'unsupported keyring specified for cookies: "{keyring}". '
397 f'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}')
398 opts.cookiesfrombrowser = (browser_name, profile, keyring, container)
400 if opts.impersonate is not None:
401 opts.impersonate = ImpersonateTarget.from_str(opts.impersonate.lower())
403 # MetadataParser
404 def metadataparser_actions(f):
405 if isinstance(f, str):
406 cmd = f'--parse-metadata {shell_quote(f)}'
407 try:
408 actions = [MetadataFromFieldPP.to_action(f)]
409 except Exception as err:
410 raise ValueError(f'{cmd} is invalid; {err}')
411 else:
412 cmd = f'--replace-in-metadata {shell_quote(f)}'
413 actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
415 for action in actions:
416 try:
417 MetadataParserPP.validate_action(*action)
418 except Exception as err:
419 raise ValueError(f'{cmd} is invalid; {err}')
420 yield action
422 if opts.metafromtitle is not None:
423 opts.parse_metadata.setdefault('pre_process', []).append(f'title:{opts.metafromtitle}')
424 opts.parse_metadata = {
425 k: list(itertools.chain(*map(metadataparser_actions, v)))
426 for k, v in opts.parse_metadata.items()
429 # Other options
430 if opts.playlist_items is not None:
431 try:
432 tuple(PlaylistEntries.parse_playlist_items(opts.playlist_items))
433 except Exception as err:
434 raise ValueError(f'Invalid playlist-items {opts.playlist_items!r}: {err}')
436 opts.geo_bypass_country, opts.geo_bypass_ip_block = None, None
437 if opts.geo_bypass.lower() not in ('default', 'never'):
438 try:
439 GeoUtils.random_ipv4(opts.geo_bypass)
440 except Exception:
441 raise ValueError(f'Unsupported --xff "{opts.geo_bypass}"')
442 if len(opts.geo_bypass) == 2:
443 opts.geo_bypass_country = opts.geo_bypass
444 else:
445 opts.geo_bypass_ip_block = opts.geo_bypass
446 opts.geo_bypass = opts.geo_bypass.lower() != 'never'
448 opts.match_filter = match_filter_func(opts.match_filter, opts.breaking_match_filter)
450 if opts.download_archive is not None:
451 opts.download_archive = expand_path(opts.download_archive)
453 if opts.ffmpeg_location is not None:
454 opts.ffmpeg_location = expand_path(opts.ffmpeg_location)
456 if opts.user_agent is not None:
457 opts.headers.setdefault('User-Agent', opts.user_agent)
458 if opts.referer is not None:
459 opts.headers.setdefault('Referer', opts.referer)
461 if opts.no_sponsorblock:
462 opts.sponsorblock_mark = opts.sponsorblock_remove = set()
464 default_downloader = None
465 for proto, path in opts.external_downloader.items():
466 if path == 'native':
467 continue
468 ed = get_external_downloader(path)
469 if ed is None:
470 raise ValueError(
471 f'No such {format_field(proto, None, "%s ", ignore="default")}external downloader "{path}"')
472 elif ed and proto == 'default':
473 default_downloader = ed.get_basename()
475 for policy in opts.color.values():
476 if policy not in ('always', 'auto', 'auto-tty', 'no_color', 'no_color-tty', 'never'):
477 raise ValueError(f'"{policy}" is not a valid color policy')
479 warnings, deprecation_warnings = [], []
481 # Common mistake: -f best
482 if opts.format == 'best':
483 warnings.append('.\n '.join((
484 '"-f best" selects the best pre-merged format which is often not the best option',
485 'To let yt-dlp download and merge the best available formats, simply do not pass any format selection',
486 'If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning')))
488 # --(postprocessor/downloader)-args without name
489 def report_args_compat(name, value, key1, key2=None, where=None):
490 if key1 in value and key2 not in value:
491 warnings.append(f'{name.title()} arguments given without specifying name. '
492 f'The arguments will be given to {where or f"all {name}s"}')
493 return True
494 return False
496 if report_args_compat('external downloader', opts.external_downloader_args,
497 'default', where=default_downloader) and default_downloader:
498 # Compat with youtube-dl's behavior. See https://github.com/ytdl-org/youtube-dl/commit/49c5293014bc11ec8c009856cd63cffa6296c1e1
499 opts.external_downloader_args.setdefault(default_downloader, opts.external_downloader_args.pop('default'))
501 if report_args_compat('post-processor', opts.postprocessor_args, 'default-compat', 'default'):
502 opts.postprocessor_args['default'] = opts.postprocessor_args.pop('default-compat')
503 opts.postprocessor_args.setdefault('sponskrub', [])
505 def report_conflict(arg1, opt1, arg2='--allow-unplayable-formats', opt2='allow_unplayable_formats',
506 val1=NO_DEFAULT, val2=NO_DEFAULT, default=False):
507 if val2 is NO_DEFAULT:
508 val2 = getattr(opts, opt2)
509 if not val2:
510 return
512 if val1 is NO_DEFAULT:
513 val1 = getattr(opts, opt1)
514 if val1:
515 warnings.append(f'{arg1} is ignored since {arg2} was given')
516 setattr(opts, opt1, default)
518 # Conflicting options
519 report_conflict('--playlist-reverse', 'playlist_reverse', '--playlist-random', 'playlist_random')
520 report_conflict('--playlist-reverse', 'playlist_reverse', '--lazy-playlist', 'lazy_playlist')
521 report_conflict('--playlist-random', 'playlist_random', '--lazy-playlist', 'lazy_playlist')
522 report_conflict('--dateafter', 'dateafter', '--date', 'date', default=None)
523 report_conflict('--datebefore', 'datebefore', '--date', 'date', default=None)
524 report_conflict('--exec-before-download', 'exec_before_dl_cmd',
525 '"--exec before_dl:"', 'exec_cmd', val2=opts.exec_cmd.get('before_dl'))
526 report_conflict('--id', 'useid', '--output', 'outtmpl', val2=opts.outtmpl.get('default'))
527 report_conflict('--remux-video', 'remuxvideo', '--recode-video', 'recodevideo')
528 report_conflict('--sponskrub', 'sponskrub', '--remove-chapters', 'remove_chapters')
529 report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-mark', 'sponsorblock_mark')
530 report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-remove', 'sponsorblock_remove')
531 report_conflict('--sponskrub-cut', 'sponskrub_cut', '--split-chapter', 'split_chapters',
532 val1=opts.sponskrub and opts.sponskrub_cut)
534 # Conflicts with --allow-unplayable-formats
535 report_conflict('--embed-metadata', 'addmetadata')
536 report_conflict('--embed-chapters', 'addchapters')
537 report_conflict('--embed-info-json', 'embed_infojson')
538 report_conflict('--embed-subs', 'embedsubtitles')
539 report_conflict('--embed-thumbnail', 'embedthumbnail')
540 report_conflict('--extract-audio', 'extractaudio')
541 report_conflict('--fixup', 'fixup', val1=opts.fixup not in (None, 'never', 'ignore'), default='never')
542 report_conflict('--recode-video', 'recodevideo')
543 report_conflict('--remove-chapters', 'remove_chapters', default=[])
544 report_conflict('--remux-video', 'remuxvideo')
545 report_conflict('--sponskrub', 'sponskrub')
546 report_conflict('--sponsorblock-remove', 'sponsorblock_remove', default=set())
547 report_conflict('--xattrs', 'xattrs')
549 # Fully deprecated options
550 def report_deprecation(val, old, new=None):
551 if not val:
552 return
553 deprecation_warnings.append(
554 f'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
555 else f'{old} is deprecated and may not work as expected')
557 report_deprecation(opts.sponskrub, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
558 report_deprecation(not opts.prefer_ffmpeg, '--prefer-avconv', 'ffmpeg')
559 # report_deprecation(opts.include_ads, '--include-ads') # We may re-implement this in future
560 # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
561 # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
563 # Dependent options
564 opts.date = DateRange.day(opts.date) if opts.date else DateRange(opts.dateafter, opts.datebefore)
566 if opts.exec_before_dl_cmd:
567 opts.exec_cmd['before_dl'] = opts.exec_before_dl_cmd
569 if opts.useid: # --id is not deprecated in youtube-dl
570 opts.outtmpl['default'] = '%(id)s.%(ext)s'
572 if opts.overwrites: # --force-overwrites implies --no-continue
573 opts.continue_dl = False
575 if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
576 # Add chapters when adding metadata or marking sponsors
577 opts.addchapters = True
579 if opts.extractaudio and not opts.keepvideo and opts.format is None:
580 # Do not unnecessarily download audio
581 opts.format = 'bestaudio/best'
583 if opts.getcomments and opts.writeinfojson is None and not opts.embed_infojson:
584 # If JSON is not printed anywhere, but comments are requested, save it to file
585 if not opts.dumpjson or opts.print_json or opts.dump_single_json:
586 opts.writeinfojson = True
588 if opts.allsubtitles and not (opts.embedsubtitles or opts.writeautomaticsub):
589 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
590 opts.writesubtitles = True
592 if opts.addmetadata and opts.embed_infojson is None:
593 # If embedding metadata and infojson is present, embed it
594 opts.embed_infojson = 'if_exists'
596 # Ask for passwords
597 if opts.username is not None and opts.password is None:
598 opts.password = getpass.getpass('Type account password and press [Return]: ')
599 if opts.ap_username is not None and opts.ap_password is None:
600 opts.ap_password = getpass.getpass('Type TV provider account password and press [Return]: ')
602 # compat option changes global state destructively; only allow from cli
603 if 'allow-unsafe-ext' in opts.compat_opts:
604 warnings.append(
605 'Using allow-unsafe-ext opens you up to potential attacks. '
606 'Use with great care!')
607 _UnsafeExtensionError.sanitize_extension = lambda x, prepend=False: x
609 return warnings, deprecation_warnings
612 def get_postprocessors(opts):
613 yield from opts.add_postprocessors
615 for when, actions in opts.parse_metadata.items():
616 yield {
617 'key': 'MetadataParser',
618 'actions': actions,
619 'when': when,
621 sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
622 if sponsorblock_query:
623 yield {
624 'key': 'SponsorBlock',
625 'categories': sponsorblock_query,
626 'api': opts.sponsorblock_api,
627 'when': 'after_filter',
629 if opts.convertsubtitles:
630 yield {
631 'key': 'FFmpegSubtitlesConvertor',
632 'format': opts.convertsubtitles,
633 'when': 'before_dl',
635 if opts.convertthumbnails:
636 yield {
637 'key': 'FFmpegThumbnailsConvertor',
638 'format': opts.convertthumbnails,
639 'when': 'before_dl',
641 if opts.extractaudio:
642 yield {
643 'key': 'FFmpegExtractAudio',
644 'preferredcodec': opts.audioformat,
645 'preferredquality': opts.audioquality,
646 'nopostoverwrites': opts.nopostoverwrites,
648 if opts.remuxvideo:
649 yield {
650 'key': 'FFmpegVideoRemuxer',
651 'preferedformat': opts.remuxvideo,
653 if opts.recodevideo:
654 yield {
655 'key': 'FFmpegVideoConvertor',
656 'preferedformat': opts.recodevideo,
658 # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
659 if opts.embedsubtitles:
660 keep_subs = 'no-keep-subs' not in opts.compat_opts
661 yield {
662 'key': 'FFmpegEmbedSubtitle',
663 # already_have_subtitle = True prevents the file from being deleted after embedding
664 'already_have_subtitle': opts.writesubtitles and keep_subs,
666 if not opts.writeautomaticsub and keep_subs:
667 opts.writesubtitles = True
669 # ModifyChapters must run before FFmpegMetadataPP
670 if opts.remove_chapters or sponsorblock_query:
671 yield {
672 'key': 'ModifyChapters',
673 'remove_chapters_patterns': opts.remove_chapters,
674 'remove_sponsor_segments': opts.sponsorblock_remove,
675 'remove_ranges': opts.remove_ranges,
676 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
677 'force_keyframes': opts.force_keyframes_at_cuts,
679 # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
680 # FFmpegExtractAudioPP as containers before conversion may not support
681 # metadata (3gp, webm, etc.)
682 # By default ffmpeg preserves metadata applicable for both
683 # source and target containers. From this point the container won't change,
684 # so metadata can be added here.
685 if opts.addmetadata or opts.addchapters or opts.embed_infojson:
686 yield {
687 'key': 'FFmpegMetadata',
688 'add_chapters': opts.addchapters,
689 'add_metadata': opts.addmetadata,
690 'add_infojson': opts.embed_infojson,
692 # Deprecated
693 # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
694 # but must be below EmbedSubtitle and FFmpegMetadata
695 # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
696 # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
697 if opts.sponskrub is not False:
698 yield {
699 'key': 'SponSkrub',
700 'path': opts.sponskrub_path,
701 'args': opts.sponskrub_args,
702 'cut': opts.sponskrub_cut,
703 'force': opts.sponskrub_force,
704 'ignoreerror': opts.sponskrub is None,
705 '_from_cli': True,
707 if opts.embedthumbnail:
708 yield {
709 'key': 'EmbedThumbnail',
710 # already_have_thumbnail = True prevents the file from being deleted after embedding
711 'already_have_thumbnail': opts.writethumbnail,
713 if not opts.writethumbnail:
714 opts.writethumbnail = True
715 opts.outtmpl['pl_thumbnail'] = ''
716 if opts.split_chapters:
717 yield {
718 'key': 'FFmpegSplitChapters',
719 'force_keyframes': opts.force_keyframes_at_cuts,
721 # XAttrMetadataPP should be run after post-processors that may change file contents
722 if opts.xattrs:
723 yield {'key': 'XAttrMetadata'}
724 if opts.concat_playlist != 'never':
725 yield {
726 'key': 'FFmpegConcat',
727 'only_multi_video': opts.concat_playlist != 'always',
728 'when': 'playlist',
730 # Exec must be the last PP of each category
731 for when, exec_cmd in opts.exec_cmd.items():
732 yield {
733 'key': 'Exec',
734 'exec_cmd': exec_cmd,
735 'when': when,
739 ParsedOptions = collections.namedtuple('ParsedOptions', ('parser', 'options', 'urls', 'ydl_opts'))
742 def parse_options(argv=None):
743 """@returns ParsedOptions(parser, opts, urls, ydl_opts)"""
744 parser, opts, urls = parseOpts(argv)
745 urls = get_urls(urls, opts.batchfile, -1 if opts.quiet and not opts.verbose else opts.verbose)
747 set_compat_opts(opts)
748 try:
749 warnings, deprecation_warnings = validate_options(opts)
750 except ValueError as err:
751 parser.error(f'{err}\n')
753 postprocessors = list(get_postprocessors(opts))
755 print_only = bool(opts.forceprint) and all(k not in opts.forceprint for k in POSTPROCESS_WHEN[3:])
756 any_getting = any(getattr(opts, k) for k in (
757 'dumpjson', 'dump_single_json', 'getdescription', 'getduration', 'getfilename',
758 'getformat', 'getid', 'getthumbnail', 'gettitle', 'geturl',
760 if opts.quiet is None:
761 opts.quiet = any_getting or opts.print_json or bool(opts.forceprint)
763 playlist_pps = [pp for pp in postprocessors if pp.get('when') == 'playlist']
764 write_playlist_infojson = (opts.writeinfojson and not opts.clean_infojson
765 and opts.allow_playlist_files and opts.outtmpl.get('pl_infojson') != '')
766 if not any((
767 opts.extract_flat,
768 opts.dump_single_json,
769 opts.forceprint.get('playlist'),
770 opts.print_to_file.get('playlist'),
771 write_playlist_infojson,
773 if not playlist_pps:
774 opts.extract_flat = 'discard'
775 elif playlist_pps == [{'key': 'FFmpegConcat', 'only_multi_video': True, 'when': 'playlist'}]:
776 opts.extract_flat = 'discard_in_playlist'
778 final_ext = (
779 opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
780 else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
781 else opts.audioformat if (opts.extractaudio and opts.audioformat in FFmpegExtractAudioPP.SUPPORTED_EXTS)
782 else None)
784 return ParsedOptions(parser, opts, urls, {
785 'usenetrc': opts.usenetrc,
786 'netrc_location': opts.netrc_location,
787 'netrc_cmd': opts.netrc_cmd,
788 'username': opts.username,
789 'password': opts.password,
790 'twofactor': opts.twofactor,
791 'videopassword': opts.videopassword,
792 'ap_mso': opts.ap_mso,
793 'ap_username': opts.ap_username,
794 'ap_password': opts.ap_password,
795 'client_certificate': opts.client_certificate,
796 'client_certificate_key': opts.client_certificate_key,
797 'client_certificate_password': opts.client_certificate_password,
798 'quiet': opts.quiet,
799 'no_warnings': opts.no_warnings,
800 'forceurl': opts.geturl,
801 'forcetitle': opts.gettitle,
802 'forceid': opts.getid,
803 'forcethumbnail': opts.getthumbnail,
804 'forcedescription': opts.getdescription,
805 'forceduration': opts.getduration,
806 'forcefilename': opts.getfilename,
807 'forceformat': opts.getformat,
808 'forceprint': opts.forceprint,
809 'print_to_file': opts.print_to_file,
810 'forcejson': opts.dumpjson or opts.print_json,
811 'dump_single_json': opts.dump_single_json,
812 'force_write_download_archive': opts.force_write_download_archive,
813 'simulate': (print_only or any_getting or None) if opts.simulate is None else opts.simulate,
814 'skip_download': opts.skip_download,
815 'format': opts.format,
816 'allow_unplayable_formats': opts.allow_unplayable_formats,
817 'ignore_no_formats_error': opts.ignore_no_formats_error,
818 'format_sort': opts.format_sort,
819 'format_sort_force': opts.format_sort_force,
820 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
821 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
822 'check_formats': opts.check_formats,
823 'listformats': opts.listformats,
824 'listformats_table': opts.listformats_table,
825 'outtmpl': opts.outtmpl,
826 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
827 'paths': opts.paths,
828 'autonumber_size': opts.autonumber_size,
829 'autonumber_start': opts.autonumber_start,
830 'restrictfilenames': opts.restrictfilenames,
831 'windowsfilenames': opts.windowsfilenames,
832 'ignoreerrors': opts.ignoreerrors,
833 'force_generic_extractor': opts.force_generic_extractor,
834 'allowed_extractors': opts.allowed_extractors or ['default'],
835 'ratelimit': opts.ratelimit,
836 'throttledratelimit': opts.throttledratelimit,
837 'overwrites': opts.overwrites,
838 'retries': opts.retries,
839 'file_access_retries': opts.file_access_retries,
840 'fragment_retries': opts.fragment_retries,
841 'extractor_retries': opts.extractor_retries,
842 'retry_sleep_functions': opts.retry_sleep,
843 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
844 'keep_fragments': opts.keep_fragments,
845 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
846 'buffersize': opts.buffersize,
847 'noresizebuffer': opts.noresizebuffer,
848 'http_chunk_size': opts.http_chunk_size,
849 'continuedl': opts.continue_dl,
850 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
851 'progress_with_newline': opts.progress_with_newline,
852 'progress_template': opts.progress_template,
853 'progress_delta': opts.progress_delta,
854 'playliststart': opts.playliststart,
855 'playlistend': opts.playlistend,
856 'playlistreverse': opts.playlist_reverse,
857 'playlistrandom': opts.playlist_random,
858 'lazy_playlist': opts.lazy_playlist,
859 'noplaylist': opts.noplaylist,
860 'logtostderr': opts.outtmpl.get('default') == '-',
861 'consoletitle': opts.consoletitle,
862 'nopart': opts.nopart,
863 'updatetime': opts.updatetime,
864 'writedescription': opts.writedescription,
865 'writeannotations': opts.writeannotations,
866 'writeinfojson': opts.writeinfojson,
867 'allow_playlist_files': opts.allow_playlist_files,
868 'clean_infojson': opts.clean_infojson,
869 'getcomments': opts.getcomments,
870 'writethumbnail': opts.writethumbnail is True,
871 'write_all_thumbnails': opts.writethumbnail == 'all',
872 'writelink': opts.writelink,
873 'writeurllink': opts.writeurllink,
874 'writewebloclink': opts.writewebloclink,
875 'writedesktoplink': opts.writedesktoplink,
876 'writesubtitles': opts.writesubtitles,
877 'writeautomaticsub': opts.writeautomaticsub,
878 'allsubtitles': opts.allsubtitles,
879 'listsubtitles': opts.listsubtitles,
880 'subtitlesformat': opts.subtitlesformat,
881 'subtitleslangs': opts.subtitleslangs,
882 'matchtitle': decodeOption(opts.matchtitle),
883 'rejecttitle': decodeOption(opts.rejecttitle),
884 'max_downloads': opts.max_downloads,
885 'prefer_free_formats': opts.prefer_free_formats,
886 'trim_file_name': opts.trim_file_name,
887 'verbose': opts.verbose,
888 'dump_intermediate_pages': opts.dump_intermediate_pages,
889 'write_pages': opts.write_pages,
890 'load_pages': opts.load_pages,
891 'test': opts.test,
892 'keepvideo': opts.keepvideo,
893 'min_filesize': opts.min_filesize,
894 'max_filesize': opts.max_filesize,
895 'min_views': opts.min_views,
896 'max_views': opts.max_views,
897 'daterange': opts.date,
898 'cachedir': opts.cachedir,
899 'youtube_print_sig_code': opts.youtube_print_sig_code,
900 'age_limit': opts.age_limit,
901 'download_archive': opts.download_archive,
902 'break_on_existing': opts.break_on_existing,
903 'break_on_reject': opts.break_on_reject,
904 'break_per_url': opts.break_per_url,
905 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
906 'cookiefile': opts.cookiefile,
907 'cookiesfrombrowser': opts.cookiesfrombrowser,
908 'legacyserverconnect': opts.legacy_server_connect,
909 'nocheckcertificate': opts.no_check_certificate,
910 'prefer_insecure': opts.prefer_insecure,
911 'enable_file_urls': opts.enable_file_urls,
912 'http_headers': opts.headers,
913 'proxy': opts.proxy,
914 'socket_timeout': opts.socket_timeout,
915 'bidi_workaround': opts.bidi_workaround,
916 'debug_printtraffic': opts.debug_printtraffic,
917 'prefer_ffmpeg': opts.prefer_ffmpeg,
918 'include_ads': opts.include_ads,
919 'default_search': opts.default_search,
920 'dynamic_mpd': opts.dynamic_mpd,
921 'extractor_args': opts.extractor_args,
922 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
923 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
924 'encoding': opts.encoding,
925 'extract_flat': opts.extract_flat,
926 'live_from_start': opts.live_from_start,
927 'wait_for_video': opts.wait_for_video,
928 'mark_watched': opts.mark_watched,
929 'merge_output_format': opts.merge_output_format,
930 'final_ext': final_ext,
931 'postprocessors': postprocessors,
932 'fixup': opts.fixup,
933 'source_address': opts.source_address,
934 'impersonate': opts.impersonate,
935 'call_home': opts.call_home,
936 'sleep_interval_requests': opts.sleep_interval_requests,
937 'sleep_interval': opts.sleep_interval,
938 'max_sleep_interval': opts.max_sleep_interval,
939 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
940 'external_downloader': opts.external_downloader,
941 'download_ranges': opts.download_ranges,
942 'force_keyframes_at_cuts': opts.force_keyframes_at_cuts,
943 'list_thumbnails': opts.list_thumbnails,
944 'playlist_items': opts.playlist_items,
945 'xattr_set_filesize': opts.xattr_set_filesize,
946 'match_filter': opts.match_filter,
947 'color': opts.color,
948 'ffmpeg_location': opts.ffmpeg_location,
949 'hls_prefer_native': opts.hls_prefer_native,
950 'hls_use_mpegts': opts.hls_use_mpegts,
951 'hls_split_discontinuity': opts.hls_split_discontinuity,
952 'external_downloader_args': opts.external_downloader_args,
953 'postprocessor_args': opts.postprocessor_args,
954 'cn_verification_proxy': opts.cn_verification_proxy,
955 'geo_verification_proxy': opts.geo_verification_proxy,
956 'geo_bypass': opts.geo_bypass,
957 'geo_bypass_country': opts.geo_bypass_country,
958 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
959 '_warnings': warnings,
960 '_deprecation_warnings': deprecation_warnings,
961 'compat_opts': opts.compat_opts,
965 def _real_main(argv=None):
966 setproctitle('yt-dlp')
968 parser, opts, all_urls, ydl_opts = parse_options(argv)
970 # Dump user agent
971 if opts.dump_user_agent:
972 ua = traverse_obj(opts.headers, 'User-Agent', casesense=False, default=std_headers['User-Agent'])
973 write_string(f'{ua}\n', out=sys.stdout)
974 return
976 if print_extractor_information(opts, all_urls):
977 return
979 # We may need ffmpeg_location without having access to the YoutubeDL instance
980 # See https://github.com/yt-dlp/yt-dlp/issues/2191
981 if opts.ffmpeg_location:
982 FFmpegPostProcessor._ffmpeg_location.set(opts.ffmpeg_location)
984 with YoutubeDL(ydl_opts) as ydl:
985 pre_process = opts.update_self or opts.rm_cachedir
986 actual_use = all_urls or opts.load_info_filename
988 if opts.rm_cachedir:
989 ydl.cache.remove()
991 try:
992 updater = Updater(ydl, opts.update_self)
993 if opts.update_self and updater.update() and actual_use:
994 if updater.cmd:
995 return updater.restart()
996 # This code is reachable only for zip variant in py < 3.10
997 # It makes sense to exit here, but the old behavior is to continue
998 ydl.report_warning('Restart yt-dlp to use the updated version')
999 # return 100, 'ERROR: The program must exit for the update to complete'
1000 except Exception:
1001 traceback.print_exc()
1002 ydl._download_retcode = 100
1004 if opts.list_impersonate_targets:
1006 known_targets = [
1007 # List of simplified targets we know are supported,
1008 # to help users know what dependencies may be required.
1009 (ImpersonateTarget('chrome'), 'curl_cffi'),
1010 (ImpersonateTarget('edge'), 'curl_cffi'),
1011 (ImpersonateTarget('safari'), 'curl_cffi'),
1014 available_targets = ydl._get_available_impersonate_targets()
1016 def make_row(target, handler):
1017 return [
1018 join_nonempty(target.client.title(), target.version, delim='-') or '-',
1019 join_nonempty((target.os or '').title(), target.os_version, delim='-') or '-',
1020 handler,
1023 rows = [make_row(target, handler) for target, handler in available_targets]
1025 for known_target, known_handler in known_targets:
1026 if not any(
1027 known_target in target and handler == known_handler
1028 for target, handler in available_targets
1030 rows.append([
1031 ydl._format_out(text, ydl.Styles.SUPPRESS)
1032 for text in make_row(known_target, f'{known_handler} (not available)')
1035 ydl.to_screen('[info] Available impersonate targets')
1036 ydl.to_stdout(render_table(['Client', 'OS', 'Source'], rows, extra_gap=2, delim='-'))
1037 return
1039 if not actual_use:
1040 if pre_process:
1041 return ydl._download_retcode
1043 args = sys.argv[1:] if argv is None else argv
1044 ydl.warn_if_short_id(args)
1046 # Show a useful error message and wait for keypress if not launched from shell on Windows
1047 if not args and compat_os_name == 'nt' and getattr(sys, 'frozen', False):
1048 import ctypes.wintypes
1049 import msvcrt
1051 kernel32 = ctypes.WinDLL('Kernel32')
1053 buffer = (1 * ctypes.wintypes.DWORD)()
1054 attached_processes = kernel32.GetConsoleProcessList(buffer, 1)
1055 # If we only have a single process attached, then the executable was double clicked
1056 # When using `pyinstaller` with `--onefile`, two processes get attached
1057 is_onefile = hasattr(sys, '_MEIPASS') and os.path.basename(sys._MEIPASS).startswith('_MEI')
1058 if attached_processes == 1 or is_onefile and attached_processes == 2:
1059 print(parser._generate_error_message(
1060 'Do not double-click the executable, instead call it from a command line.\n'
1061 'Please read the README for further information on how to use yt-dlp: '
1062 'https://github.com/yt-dlp/yt-dlp#readme'))
1063 msvcrt.getch()
1064 _exit(2)
1065 parser.error(
1066 'You must provide at least one URL.\n'
1067 'Type yt-dlp --help to see a list of all options.')
1069 parser.destroy()
1070 try:
1071 if opts.load_info_filename is not None:
1072 if all_urls:
1073 ydl.report_warning('URLs are ignored due to --load-info-json')
1074 return ydl.download_with_info_file(expand_path(opts.load_info_filename))
1075 else:
1076 return ydl.download(all_urls)
1077 except DownloadCancelled:
1078 ydl.to_screen('Aborting remaining downloads')
1079 return 101
1082 def main(argv=None):
1083 global _IN_CLI
1084 _IN_CLI = True
1085 try:
1086 _exit(*variadic(_real_main(argv)))
1087 except DownloadError:
1088 _exit(1)
1089 except SameFileError as e:
1090 _exit(f'ERROR: {e}')
1091 except KeyboardInterrupt:
1092 _exit('\nERROR: Interrupted by user')
1093 except BrokenPipeError as e:
1094 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
1095 devnull = os.open(os.devnull, os.O_WRONLY)
1096 os.dup2(devnull, sys.stdout.fileno())
1097 _exit(f'\nERROR: {e}')
1098 except optparse.OptParseError as e:
1099 _exit(2, f'\n{e}')
1102 from .extractor import gen_extractors, list_extractors
1104 __all__ = [
1105 'main',
1106 'YoutubeDL',
1107 'parse_options',
1108 'gen_extractors',
1109 'list_extractors',