Release 2024.07.09
[yt-dlp.git] / yt_dlp / __init__.py
blob0e48569e33785091fabc4d6da509d6c3b372987b
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 validate_regex('merge output format', opts.merge_output_format,
239 r'({0})(/({0}))*'.format('|'.join(map(re.escape, FFmpegMergerPP.SUPPORTED_EXTS))))
240 validate_regex('audio format', opts.audioformat, FFmpegExtractAudioPP.FORMAT_RE)
241 validate_in('subtitle format', opts.convertsubtitles, FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS)
242 validate_regex('thumbnail format', opts.convertthumbnails, FFmpegThumbnailsConvertorPP.FORMAT_RE)
243 validate_regex('recode video format', opts.recodevideo, FFmpegVideoConvertorPP.FORMAT_RE)
244 validate_regex('remux video format', opts.remuxvideo, FFmpegVideoRemuxerPP.FORMAT_RE)
245 if opts.audioquality:
246 opts.audioquality = opts.audioquality.strip('k').strip('K')
247 # int_or_none prevents inf, nan
248 validate_positive('audio quality', int_or_none(float_or_none(opts.audioquality), default=0))
250 # Retries
251 def parse_retries(name, value):
252 if value is None:
253 return None
254 elif value in ('inf', 'infinite'):
255 return float('inf')
256 try:
257 return int(value)
258 except (TypeError, ValueError):
259 validate(False, f'{name} retry count', value)
261 opts.retries = parse_retries('download', opts.retries)
262 opts.fragment_retries = parse_retries('fragment', opts.fragment_retries)
263 opts.extractor_retries = parse_retries('extractor', opts.extractor_retries)
264 opts.file_access_retries = parse_retries('file access', opts.file_access_retries)
266 # Retry sleep function
267 def parse_sleep_func(expr):
268 NUMBER_RE = r'\d+(?:\.\d+)?'
269 op, start, limit, step, *_ = (*tuple(re.fullmatch(
270 rf'(?:(linear|exp)=)?({NUMBER_RE})(?::({NUMBER_RE})?)?(?::({NUMBER_RE}))?',
271 expr.strip()).groups()), None, None)
273 if op == 'exp':
274 return lambda n: min(float(start) * (float(step or 2) ** n), float(limit or 'inf'))
275 else:
276 default_step = start if op or limit else 0
277 return lambda n: min(float(start) + float(step or default_step) * n, float(limit or 'inf'))
279 for key, expr in opts.retry_sleep.items():
280 if not expr:
281 del opts.retry_sleep[key]
282 continue
283 try:
284 opts.retry_sleep[key] = parse_sleep_func(expr)
285 except AttributeError:
286 raise ValueError(f'invalid {key} retry sleep expression {expr!r}')
288 # Bytes
289 def validate_bytes(name, value):
290 if value is None:
291 return None
292 numeric_limit = parse_bytes(value)
293 validate(numeric_limit is not None, 'rate limit', value)
294 return numeric_limit
296 opts.ratelimit = validate_bytes('rate limit', opts.ratelimit)
297 opts.throttledratelimit = validate_bytes('throttled rate limit', opts.throttledratelimit)
298 opts.min_filesize = validate_bytes('min filesize', opts.min_filesize)
299 opts.max_filesize = validate_bytes('max filesize', opts.max_filesize)
300 opts.buffersize = validate_bytes('buffer size', opts.buffersize)
301 opts.http_chunk_size = validate_bytes('http chunk size', opts.http_chunk_size)
303 # Output templates
304 def validate_outtmpl(tmpl, msg):
305 err = YoutubeDL.validate_outtmpl(tmpl)
306 if err:
307 raise ValueError(f'invalid {msg} "{tmpl}": {err}')
309 for k, tmpl in opts.outtmpl.items():
310 validate_outtmpl(tmpl, f'{k} output template')
311 for type_, tmpl_list in opts.forceprint.items():
312 for tmpl in tmpl_list:
313 validate_outtmpl(tmpl, f'{type_} print template')
314 for type_, tmpl_list in opts.print_to_file.items():
315 for tmpl, file in tmpl_list:
316 validate_outtmpl(tmpl, f'{type_} print to file template')
317 validate_outtmpl(file, f'{type_} print to file filename')
318 validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
319 for k, tmpl in opts.progress_template.items():
320 k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
321 validate_outtmpl(tmpl, f'{k} template')
323 outtmpl_default = opts.outtmpl.get('default')
324 if outtmpl_default == '':
325 opts.skip_download = None
326 del opts.outtmpl['default']
328 def parse_chapters(name, value, advanced=False):
329 parse_timestamp = lambda x: float('inf') if x in ('inf', 'infinite') else parse_duration(x)
330 TIMESTAMP_RE = r'''(?x)(?:
331 (?P<start_sign>-?)(?P<start>[^-]+)
332 )?\s*-\s*(?:
333 (?P<end_sign>-?)(?P<end>[^-]+)
334 )?'''
336 chapters, ranges, from_url = [], [], False
337 for regex in value or []:
338 if advanced and regex == '*from-url':
339 from_url = True
340 continue
341 elif not regex.startswith('*'):
342 try:
343 chapters.append(re.compile(regex))
344 except re.error as err:
345 raise ValueError(f'invalid {name} regex "{regex}" - {err}')
346 continue
348 for range_ in map(str.strip, regex[1:].split(',')):
349 mobj = range_ != '-' and re.fullmatch(TIMESTAMP_RE, range_)
350 dur = mobj and [parse_timestamp(mobj.group('start') or '0'), parse_timestamp(mobj.group('end') or 'inf')]
351 signs = mobj and (mobj.group('start_sign'), mobj.group('end_sign'))
353 err = None
354 if None in (dur or [None]):
355 err = 'Must be of the form "*start-end"'
356 elif not advanced and any(signs):
357 err = 'Negative timestamps are not allowed'
358 else:
359 dur[0] *= -1 if signs[0] else 1
360 dur[1] *= -1 if signs[1] else 1
361 if dur[1] == float('-inf'):
362 err = '"-inf" is not a valid end'
363 if err:
364 raise ValueError(f'invalid {name} time range "{regex}". {err}')
365 ranges.append(dur)
367 return chapters, ranges, from_url
369 opts.remove_chapters, opts.remove_ranges, _ = parse_chapters('--remove-chapters', opts.remove_chapters)
370 opts.download_ranges = download_range_func(*parse_chapters('--download-sections', opts.download_ranges, True))
372 # Cookies from browser
373 if opts.cookiesfrombrowser:
374 container = None
375 mobj = re.fullmatch(r'''(?x)
376 (?P<name>[^+:]+)
377 (?:\s*\+\s*(?P<keyring>[^:]+))?
378 (?:\s*:\s*(?!:)(?P<profile>.+?))?
379 (?:\s*::\s*(?P<container>.+))?
380 ''', opts.cookiesfrombrowser)
381 if mobj is None:
382 raise ValueError(f'invalid cookies from browser arguments: {opts.cookiesfrombrowser}')
383 browser_name, keyring, profile, container = mobj.group('name', 'keyring', 'profile', 'container')
384 browser_name = browser_name.lower()
385 if browser_name not in SUPPORTED_BROWSERS:
386 raise ValueError(f'unsupported browser specified for cookies: "{browser_name}". '
387 f'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}')
388 if keyring is not None:
389 keyring = keyring.upper()
390 if keyring not in SUPPORTED_KEYRINGS:
391 raise ValueError(f'unsupported keyring specified for cookies: "{keyring}". '
392 f'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}')
393 opts.cookiesfrombrowser = (browser_name, profile, keyring, container)
395 if opts.impersonate is not None:
396 opts.impersonate = ImpersonateTarget.from_str(opts.impersonate.lower())
398 # MetadataParser
399 def metadataparser_actions(f):
400 if isinstance(f, str):
401 cmd = f'--parse-metadata {shell_quote(f)}'
402 try:
403 actions = [MetadataFromFieldPP.to_action(f)]
404 except Exception as err:
405 raise ValueError(f'{cmd} is invalid; {err}')
406 else:
407 cmd = f'--replace-in-metadata {shell_quote(f)}'
408 actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
410 for action in actions:
411 try:
412 MetadataParserPP.validate_action(*action)
413 except Exception as err:
414 raise ValueError(f'{cmd} is invalid; {err}')
415 yield action
417 if opts.metafromtitle is not None:
418 opts.parse_metadata.setdefault('pre_process', []).append(f'title:{opts.metafromtitle}')
419 opts.parse_metadata = {
420 k: list(itertools.chain(*map(metadataparser_actions, v)))
421 for k, v in opts.parse_metadata.items()
424 # Other options
425 if opts.playlist_items is not None:
426 try:
427 tuple(PlaylistEntries.parse_playlist_items(opts.playlist_items))
428 except Exception as err:
429 raise ValueError(f'Invalid playlist-items {opts.playlist_items!r}: {err}')
431 opts.geo_bypass_country, opts.geo_bypass_ip_block = None, None
432 if opts.geo_bypass.lower() not in ('default', 'never'):
433 try:
434 GeoUtils.random_ipv4(opts.geo_bypass)
435 except Exception:
436 raise ValueError(f'Unsupported --xff "{opts.geo_bypass}"')
437 if len(opts.geo_bypass) == 2:
438 opts.geo_bypass_country = opts.geo_bypass
439 else:
440 opts.geo_bypass_ip_block = opts.geo_bypass
441 opts.geo_bypass = opts.geo_bypass.lower() != 'never'
443 opts.match_filter = match_filter_func(opts.match_filter, opts.breaking_match_filter)
445 if opts.download_archive is not None:
446 opts.download_archive = expand_path(opts.download_archive)
448 if opts.ffmpeg_location is not None:
449 opts.ffmpeg_location = expand_path(opts.ffmpeg_location)
451 if opts.user_agent is not None:
452 opts.headers.setdefault('User-Agent', opts.user_agent)
453 if opts.referer is not None:
454 opts.headers.setdefault('Referer', opts.referer)
456 if opts.no_sponsorblock:
457 opts.sponsorblock_mark = opts.sponsorblock_remove = set()
459 default_downloader = None
460 for proto, path in opts.external_downloader.items():
461 if path == 'native':
462 continue
463 ed = get_external_downloader(path)
464 if ed is None:
465 raise ValueError(
466 f'No such {format_field(proto, None, "%s ", ignore="default")}external downloader "{path}"')
467 elif ed and proto == 'default':
468 default_downloader = ed.get_basename()
470 for policy in opts.color.values():
471 if policy not in ('always', 'auto', 'no_color', 'never'):
472 raise ValueError(f'"{policy}" is not a valid color policy')
474 warnings, deprecation_warnings = [], []
476 # Common mistake: -f best
477 if opts.format == 'best':
478 warnings.append('.\n '.join((
479 '"-f best" selects the best pre-merged format which is often not the best option',
480 'To let yt-dlp download and merge the best available formats, simply do not pass any format selection',
481 'If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning')))
483 # --(postprocessor/downloader)-args without name
484 def report_args_compat(name, value, key1, key2=None, where=None):
485 if key1 in value and key2 not in value:
486 warnings.append(f'{name.title()} arguments given without specifying name. '
487 f'The arguments will be given to {where or f"all {name}s"}')
488 return True
489 return False
491 if report_args_compat('external downloader', opts.external_downloader_args,
492 'default', where=default_downloader) and default_downloader:
493 # Compat with youtube-dl's behavior. See https://github.com/ytdl-org/youtube-dl/commit/49c5293014bc11ec8c009856cd63cffa6296c1e1
494 opts.external_downloader_args.setdefault(default_downloader, opts.external_downloader_args.pop('default'))
496 if report_args_compat('post-processor', opts.postprocessor_args, 'default-compat', 'default'):
497 opts.postprocessor_args['default'] = opts.postprocessor_args.pop('default-compat')
498 opts.postprocessor_args.setdefault('sponskrub', [])
500 def report_conflict(arg1, opt1, arg2='--allow-unplayable-formats', opt2='allow_unplayable_formats',
501 val1=NO_DEFAULT, val2=NO_DEFAULT, default=False):
502 if val2 is NO_DEFAULT:
503 val2 = getattr(opts, opt2)
504 if not val2:
505 return
507 if val1 is NO_DEFAULT:
508 val1 = getattr(opts, opt1)
509 if val1:
510 warnings.append(f'{arg1} is ignored since {arg2} was given')
511 setattr(opts, opt1, default)
513 # Conflicting options
514 report_conflict('--playlist-reverse', 'playlist_reverse', '--playlist-random', 'playlist_random')
515 report_conflict('--playlist-reverse', 'playlist_reverse', '--lazy-playlist', 'lazy_playlist')
516 report_conflict('--playlist-random', 'playlist_random', '--lazy-playlist', 'lazy_playlist')
517 report_conflict('--dateafter', 'dateafter', '--date', 'date', default=None)
518 report_conflict('--datebefore', 'datebefore', '--date', 'date', default=None)
519 report_conflict('--exec-before-download', 'exec_before_dl_cmd',
520 '"--exec before_dl:"', 'exec_cmd', val2=opts.exec_cmd.get('before_dl'))
521 report_conflict('--id', 'useid', '--output', 'outtmpl', val2=opts.outtmpl.get('default'))
522 report_conflict('--remux-video', 'remuxvideo', '--recode-video', 'recodevideo')
523 report_conflict('--sponskrub', 'sponskrub', '--remove-chapters', 'remove_chapters')
524 report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-mark', 'sponsorblock_mark')
525 report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-remove', 'sponsorblock_remove')
526 report_conflict('--sponskrub-cut', 'sponskrub_cut', '--split-chapter', 'split_chapters',
527 val1=opts.sponskrub and opts.sponskrub_cut)
529 # Conflicts with --allow-unplayable-formats
530 report_conflict('--embed-metadata', 'addmetadata')
531 report_conflict('--embed-chapters', 'addchapters')
532 report_conflict('--embed-info-json', 'embed_infojson')
533 report_conflict('--embed-subs', 'embedsubtitles')
534 report_conflict('--embed-thumbnail', 'embedthumbnail')
535 report_conflict('--extract-audio', 'extractaudio')
536 report_conflict('--fixup', 'fixup', val1=opts.fixup not in (None, 'never', 'ignore'), default='never')
537 report_conflict('--recode-video', 'recodevideo')
538 report_conflict('--remove-chapters', 'remove_chapters', default=[])
539 report_conflict('--remux-video', 'remuxvideo')
540 report_conflict('--sponskrub', 'sponskrub')
541 report_conflict('--sponsorblock-remove', 'sponsorblock_remove', default=set())
542 report_conflict('--xattrs', 'xattrs')
544 # Fully deprecated options
545 def report_deprecation(val, old, new=None):
546 if not val:
547 return
548 deprecation_warnings.append(
549 f'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
550 else f'{old} is deprecated and may not work as expected')
552 report_deprecation(opts.sponskrub, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
553 report_deprecation(not opts.prefer_ffmpeg, '--prefer-avconv', 'ffmpeg')
554 # report_deprecation(opts.include_ads, '--include-ads') # We may re-implement this in future
555 # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
556 # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
558 # Dependent options
559 opts.date = DateRange.day(opts.date) if opts.date else DateRange(opts.dateafter, opts.datebefore)
561 if opts.exec_before_dl_cmd:
562 opts.exec_cmd['before_dl'] = opts.exec_before_dl_cmd
564 if opts.useid: # --id is not deprecated in youtube-dl
565 opts.outtmpl['default'] = '%(id)s.%(ext)s'
567 if opts.overwrites: # --force-overwrites implies --no-continue
568 opts.continue_dl = False
570 if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
571 # Add chapters when adding metadata or marking sponsors
572 opts.addchapters = True
574 if opts.extractaudio and not opts.keepvideo and opts.format is None:
575 # Do not unnecessarily download audio
576 opts.format = 'bestaudio/best'
578 if opts.getcomments and opts.writeinfojson is None and not opts.embed_infojson:
579 # If JSON is not printed anywhere, but comments are requested, save it to file
580 if not opts.dumpjson or opts.print_json or opts.dump_single_json:
581 opts.writeinfojson = True
583 if opts.allsubtitles and not (opts.embedsubtitles or opts.writeautomaticsub):
584 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
585 opts.writesubtitles = True
587 if opts.addmetadata and opts.embed_infojson is None:
588 # If embedding metadata and infojson is present, embed it
589 opts.embed_infojson = 'if_exists'
591 # Ask for passwords
592 if opts.username is not None and opts.password is None:
593 opts.password = getpass.getpass('Type account password and press [Return]: ')
594 if opts.ap_username is not None and opts.ap_password is None:
595 opts.ap_password = getpass.getpass('Type TV provider account password and press [Return]: ')
597 # compat option changes global state destructively; only allow from cli
598 if 'allow-unsafe-ext' in opts.compat_opts:
599 warnings.append(
600 'Using allow-unsafe-ext opens you up to potential attacks. '
601 'Use with great care!')
602 _UnsafeExtensionError.sanitize_extension = lambda x, prepend=False: x
604 return warnings, deprecation_warnings
607 def get_postprocessors(opts):
608 yield from opts.add_postprocessors
610 for when, actions in opts.parse_metadata.items():
611 yield {
612 'key': 'MetadataParser',
613 'actions': actions,
614 'when': when,
616 sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
617 if sponsorblock_query:
618 yield {
619 'key': 'SponsorBlock',
620 'categories': sponsorblock_query,
621 'api': opts.sponsorblock_api,
622 'when': 'after_filter',
624 if opts.convertsubtitles:
625 yield {
626 'key': 'FFmpegSubtitlesConvertor',
627 'format': opts.convertsubtitles,
628 'when': 'before_dl',
630 if opts.convertthumbnails:
631 yield {
632 'key': 'FFmpegThumbnailsConvertor',
633 'format': opts.convertthumbnails,
634 'when': 'before_dl',
636 if opts.extractaudio:
637 yield {
638 'key': 'FFmpegExtractAudio',
639 'preferredcodec': opts.audioformat,
640 'preferredquality': opts.audioquality,
641 'nopostoverwrites': opts.nopostoverwrites,
643 if opts.remuxvideo:
644 yield {
645 'key': 'FFmpegVideoRemuxer',
646 'preferedformat': opts.remuxvideo,
648 if opts.recodevideo:
649 yield {
650 'key': 'FFmpegVideoConvertor',
651 'preferedformat': opts.recodevideo,
653 # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
654 if opts.embedsubtitles:
655 keep_subs = 'no-keep-subs' not in opts.compat_opts
656 yield {
657 'key': 'FFmpegEmbedSubtitle',
658 # already_have_subtitle = True prevents the file from being deleted after embedding
659 'already_have_subtitle': opts.writesubtitles and keep_subs,
661 if not opts.writeautomaticsub and keep_subs:
662 opts.writesubtitles = True
664 # ModifyChapters must run before FFmpegMetadataPP
665 if opts.remove_chapters or sponsorblock_query:
666 yield {
667 'key': 'ModifyChapters',
668 'remove_chapters_patterns': opts.remove_chapters,
669 'remove_sponsor_segments': opts.sponsorblock_remove,
670 'remove_ranges': opts.remove_ranges,
671 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
672 'force_keyframes': opts.force_keyframes_at_cuts,
674 # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
675 # FFmpegExtractAudioPP as containers before conversion may not support
676 # metadata (3gp, webm, etc.)
677 # By default ffmpeg preserves metadata applicable for both
678 # source and target containers. From this point the container won't change,
679 # so metadata can be added here.
680 if opts.addmetadata or opts.addchapters or opts.embed_infojson:
681 yield {
682 'key': 'FFmpegMetadata',
683 'add_chapters': opts.addchapters,
684 'add_metadata': opts.addmetadata,
685 'add_infojson': opts.embed_infojson,
687 # Deprecated
688 # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
689 # but must be below EmbedSubtitle and FFmpegMetadata
690 # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
691 # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
692 if opts.sponskrub is not False:
693 yield {
694 'key': 'SponSkrub',
695 'path': opts.sponskrub_path,
696 'args': opts.sponskrub_args,
697 'cut': opts.sponskrub_cut,
698 'force': opts.sponskrub_force,
699 'ignoreerror': opts.sponskrub is None,
700 '_from_cli': True,
702 if opts.embedthumbnail:
703 yield {
704 'key': 'EmbedThumbnail',
705 # already_have_thumbnail = True prevents the file from being deleted after embedding
706 'already_have_thumbnail': opts.writethumbnail,
708 if not opts.writethumbnail:
709 opts.writethumbnail = True
710 opts.outtmpl['pl_thumbnail'] = ''
711 if opts.split_chapters:
712 yield {
713 'key': 'FFmpegSplitChapters',
714 'force_keyframes': opts.force_keyframes_at_cuts,
716 # XAttrMetadataPP should be run after post-processors that may change file contents
717 if opts.xattrs:
718 yield {'key': 'XAttrMetadata'}
719 if opts.concat_playlist != 'never':
720 yield {
721 'key': 'FFmpegConcat',
722 'only_multi_video': opts.concat_playlist != 'always',
723 'when': 'playlist',
725 # Exec must be the last PP of each category
726 for when, exec_cmd in opts.exec_cmd.items():
727 yield {
728 'key': 'Exec',
729 'exec_cmd': exec_cmd,
730 'when': when,
734 ParsedOptions = collections.namedtuple('ParsedOptions', ('parser', 'options', 'urls', 'ydl_opts'))
737 def parse_options(argv=None):
738 """@returns ParsedOptions(parser, opts, urls, ydl_opts)"""
739 parser, opts, urls = parseOpts(argv)
740 urls = get_urls(urls, opts.batchfile, -1 if opts.quiet and not opts.verbose else opts.verbose)
742 set_compat_opts(opts)
743 try:
744 warnings, deprecation_warnings = validate_options(opts)
745 except ValueError as err:
746 parser.error(f'{err}\n')
748 postprocessors = list(get_postprocessors(opts))
750 print_only = bool(opts.forceprint) and all(k not in opts.forceprint for k in POSTPROCESS_WHEN[3:])
751 any_getting = any(getattr(opts, k) for k in (
752 'dumpjson', 'dump_single_json', 'getdescription', 'getduration', 'getfilename',
753 'getformat', 'getid', 'getthumbnail', 'gettitle', 'geturl',
755 if opts.quiet is None:
756 opts.quiet = any_getting or opts.print_json or bool(opts.forceprint)
758 playlist_pps = [pp for pp in postprocessors if pp.get('when') == 'playlist']
759 write_playlist_infojson = (opts.writeinfojson and not opts.clean_infojson
760 and opts.allow_playlist_files and opts.outtmpl.get('pl_infojson') != '')
761 if not any((
762 opts.extract_flat,
763 opts.dump_single_json,
764 opts.forceprint.get('playlist'),
765 opts.print_to_file.get('playlist'),
766 write_playlist_infojson,
768 if not playlist_pps:
769 opts.extract_flat = 'discard'
770 elif playlist_pps == [{'key': 'FFmpegConcat', 'only_multi_video': True, 'when': 'playlist'}]:
771 opts.extract_flat = 'discard_in_playlist'
773 final_ext = (
774 opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
775 else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
776 else opts.audioformat if (opts.extractaudio and opts.audioformat in FFmpegExtractAudioPP.SUPPORTED_EXTS)
777 else None)
779 return ParsedOptions(parser, opts, urls, {
780 'usenetrc': opts.usenetrc,
781 'netrc_location': opts.netrc_location,
782 'netrc_cmd': opts.netrc_cmd,
783 'username': opts.username,
784 'password': opts.password,
785 'twofactor': opts.twofactor,
786 'videopassword': opts.videopassword,
787 'ap_mso': opts.ap_mso,
788 'ap_username': opts.ap_username,
789 'ap_password': opts.ap_password,
790 'client_certificate': opts.client_certificate,
791 'client_certificate_key': opts.client_certificate_key,
792 'client_certificate_password': opts.client_certificate_password,
793 'quiet': opts.quiet,
794 'no_warnings': opts.no_warnings,
795 'forceurl': opts.geturl,
796 'forcetitle': opts.gettitle,
797 'forceid': opts.getid,
798 'forcethumbnail': opts.getthumbnail,
799 'forcedescription': opts.getdescription,
800 'forceduration': opts.getduration,
801 'forcefilename': opts.getfilename,
802 'forceformat': opts.getformat,
803 'forceprint': opts.forceprint,
804 'print_to_file': opts.print_to_file,
805 'forcejson': opts.dumpjson or opts.print_json,
806 'dump_single_json': opts.dump_single_json,
807 'force_write_download_archive': opts.force_write_download_archive,
808 'simulate': (print_only or any_getting or None) if opts.simulate is None else opts.simulate,
809 'skip_download': opts.skip_download,
810 'format': opts.format,
811 'allow_unplayable_formats': opts.allow_unplayable_formats,
812 'ignore_no_formats_error': opts.ignore_no_formats_error,
813 'format_sort': opts.format_sort,
814 'format_sort_force': opts.format_sort_force,
815 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
816 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
817 'check_formats': opts.check_formats,
818 'listformats': opts.listformats,
819 'listformats_table': opts.listformats_table,
820 'outtmpl': opts.outtmpl,
821 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
822 'paths': opts.paths,
823 'autonumber_size': opts.autonumber_size,
824 'autonumber_start': opts.autonumber_start,
825 'restrictfilenames': opts.restrictfilenames,
826 'windowsfilenames': opts.windowsfilenames,
827 'ignoreerrors': opts.ignoreerrors,
828 'force_generic_extractor': opts.force_generic_extractor,
829 'allowed_extractors': opts.allowed_extractors or ['default'],
830 'ratelimit': opts.ratelimit,
831 'throttledratelimit': opts.throttledratelimit,
832 'overwrites': opts.overwrites,
833 'retries': opts.retries,
834 'file_access_retries': opts.file_access_retries,
835 'fragment_retries': opts.fragment_retries,
836 'extractor_retries': opts.extractor_retries,
837 'retry_sleep_functions': opts.retry_sleep,
838 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
839 'keep_fragments': opts.keep_fragments,
840 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
841 'buffersize': opts.buffersize,
842 'noresizebuffer': opts.noresizebuffer,
843 'http_chunk_size': opts.http_chunk_size,
844 'continuedl': opts.continue_dl,
845 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
846 'progress_with_newline': opts.progress_with_newline,
847 'progress_template': opts.progress_template,
848 'progress_delta': opts.progress_delta,
849 'playliststart': opts.playliststart,
850 'playlistend': opts.playlistend,
851 'playlistreverse': opts.playlist_reverse,
852 'playlistrandom': opts.playlist_random,
853 'lazy_playlist': opts.lazy_playlist,
854 'noplaylist': opts.noplaylist,
855 'logtostderr': opts.outtmpl.get('default') == '-',
856 'consoletitle': opts.consoletitle,
857 'nopart': opts.nopart,
858 'updatetime': opts.updatetime,
859 'writedescription': opts.writedescription,
860 'writeannotations': opts.writeannotations,
861 'writeinfojson': opts.writeinfojson,
862 'allow_playlist_files': opts.allow_playlist_files,
863 'clean_infojson': opts.clean_infojson,
864 'getcomments': opts.getcomments,
865 'writethumbnail': opts.writethumbnail is True,
866 'write_all_thumbnails': opts.writethumbnail == 'all',
867 'writelink': opts.writelink,
868 'writeurllink': opts.writeurllink,
869 'writewebloclink': opts.writewebloclink,
870 'writedesktoplink': opts.writedesktoplink,
871 'writesubtitles': opts.writesubtitles,
872 'writeautomaticsub': opts.writeautomaticsub,
873 'allsubtitles': opts.allsubtitles,
874 'listsubtitles': opts.listsubtitles,
875 'subtitlesformat': opts.subtitlesformat,
876 'subtitleslangs': opts.subtitleslangs,
877 'matchtitle': decodeOption(opts.matchtitle),
878 'rejecttitle': decodeOption(opts.rejecttitle),
879 'max_downloads': opts.max_downloads,
880 'prefer_free_formats': opts.prefer_free_formats,
881 'trim_file_name': opts.trim_file_name,
882 'verbose': opts.verbose,
883 'dump_intermediate_pages': opts.dump_intermediate_pages,
884 'write_pages': opts.write_pages,
885 'load_pages': opts.load_pages,
886 'test': opts.test,
887 'keepvideo': opts.keepvideo,
888 'min_filesize': opts.min_filesize,
889 'max_filesize': opts.max_filesize,
890 'min_views': opts.min_views,
891 'max_views': opts.max_views,
892 'daterange': opts.date,
893 'cachedir': opts.cachedir,
894 'youtube_print_sig_code': opts.youtube_print_sig_code,
895 'age_limit': opts.age_limit,
896 'download_archive': opts.download_archive,
897 'break_on_existing': opts.break_on_existing,
898 'break_on_reject': opts.break_on_reject,
899 'break_per_url': opts.break_per_url,
900 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
901 'cookiefile': opts.cookiefile,
902 'cookiesfrombrowser': opts.cookiesfrombrowser,
903 'legacyserverconnect': opts.legacy_server_connect,
904 'nocheckcertificate': opts.no_check_certificate,
905 'prefer_insecure': opts.prefer_insecure,
906 'enable_file_urls': opts.enable_file_urls,
907 'http_headers': opts.headers,
908 'proxy': opts.proxy,
909 'socket_timeout': opts.socket_timeout,
910 'bidi_workaround': opts.bidi_workaround,
911 'debug_printtraffic': opts.debug_printtraffic,
912 'prefer_ffmpeg': opts.prefer_ffmpeg,
913 'include_ads': opts.include_ads,
914 'default_search': opts.default_search,
915 'dynamic_mpd': opts.dynamic_mpd,
916 'extractor_args': opts.extractor_args,
917 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
918 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
919 'encoding': opts.encoding,
920 'extract_flat': opts.extract_flat,
921 'live_from_start': opts.live_from_start,
922 'wait_for_video': opts.wait_for_video,
923 'mark_watched': opts.mark_watched,
924 'merge_output_format': opts.merge_output_format,
925 'final_ext': final_ext,
926 'postprocessors': postprocessors,
927 'fixup': opts.fixup,
928 'source_address': opts.source_address,
929 'impersonate': opts.impersonate,
930 'call_home': opts.call_home,
931 'sleep_interval_requests': opts.sleep_interval_requests,
932 'sleep_interval': opts.sleep_interval,
933 'max_sleep_interval': opts.max_sleep_interval,
934 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
935 'external_downloader': opts.external_downloader,
936 'download_ranges': opts.download_ranges,
937 'force_keyframes_at_cuts': opts.force_keyframes_at_cuts,
938 'list_thumbnails': opts.list_thumbnails,
939 'playlist_items': opts.playlist_items,
940 'xattr_set_filesize': opts.xattr_set_filesize,
941 'match_filter': opts.match_filter,
942 'color': opts.color,
943 'ffmpeg_location': opts.ffmpeg_location,
944 'hls_prefer_native': opts.hls_prefer_native,
945 'hls_use_mpegts': opts.hls_use_mpegts,
946 'hls_split_discontinuity': opts.hls_split_discontinuity,
947 'external_downloader_args': opts.external_downloader_args,
948 'postprocessor_args': opts.postprocessor_args,
949 'cn_verification_proxy': opts.cn_verification_proxy,
950 'geo_verification_proxy': opts.geo_verification_proxy,
951 'geo_bypass': opts.geo_bypass,
952 'geo_bypass_country': opts.geo_bypass_country,
953 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
954 '_warnings': warnings,
955 '_deprecation_warnings': deprecation_warnings,
956 'compat_opts': opts.compat_opts,
960 def _real_main(argv=None):
961 setproctitle('yt-dlp')
963 parser, opts, all_urls, ydl_opts = parse_options(argv)
965 # Dump user agent
966 if opts.dump_user_agent:
967 ua = traverse_obj(opts.headers, 'User-Agent', casesense=False, default=std_headers['User-Agent'])
968 write_string(f'{ua}\n', out=sys.stdout)
969 return
971 if print_extractor_information(opts, all_urls):
972 return
974 # We may need ffmpeg_location without having access to the YoutubeDL instance
975 # See https://github.com/yt-dlp/yt-dlp/issues/2191
976 if opts.ffmpeg_location:
977 FFmpegPostProcessor._ffmpeg_location.set(opts.ffmpeg_location)
979 with YoutubeDL(ydl_opts) as ydl:
980 pre_process = opts.update_self or opts.rm_cachedir
981 actual_use = all_urls or opts.load_info_filename
983 if opts.rm_cachedir:
984 ydl.cache.remove()
986 try:
987 updater = Updater(ydl, opts.update_self)
988 if opts.update_self and updater.update() and actual_use:
989 if updater.cmd:
990 return updater.restart()
991 # This code is reachable only for zip variant in py < 3.10
992 # It makes sense to exit here, but the old behavior is to continue
993 ydl.report_warning('Restart yt-dlp to use the updated version')
994 # return 100, 'ERROR: The program must exit for the update to complete'
995 except Exception:
996 traceback.print_exc()
997 ydl._download_retcode = 100
999 if opts.list_impersonate_targets:
1001 known_targets = [
1002 # List of simplified targets we know are supported,
1003 # to help users know what dependencies may be required.
1004 (ImpersonateTarget('chrome'), 'curl_cffi'),
1005 (ImpersonateTarget('edge'), 'curl_cffi'),
1006 (ImpersonateTarget('safari'), 'curl_cffi'),
1009 available_targets = ydl._get_available_impersonate_targets()
1011 def make_row(target, handler):
1012 return [
1013 join_nonempty(target.client.title(), target.version, delim='-') or '-',
1014 join_nonempty((target.os or '').title(), target.os_version, delim='-') or '-',
1015 handler,
1018 rows = [make_row(target, handler) for target, handler in available_targets]
1020 for known_target, known_handler in known_targets:
1021 if not any(
1022 known_target in target and handler == known_handler
1023 for target, handler in available_targets
1025 rows.append([
1026 ydl._format_out(text, ydl.Styles.SUPPRESS)
1027 for text in make_row(known_target, f'{known_handler} (not available)')
1030 ydl.to_screen('[info] Available impersonate targets')
1031 ydl.to_stdout(render_table(['Client', 'OS', 'Source'], rows, extra_gap=2, delim='-'))
1032 return
1034 if not actual_use:
1035 if pre_process:
1036 return ydl._download_retcode
1038 args = sys.argv[1:] if argv is None else argv
1039 ydl.warn_if_short_id(args)
1041 # Show a useful error message and wait for keypress if not launched from shell on Windows
1042 if not args and compat_os_name == 'nt' and getattr(sys, 'frozen', False):
1043 import ctypes.wintypes
1044 import msvcrt
1046 kernel32 = ctypes.WinDLL('Kernel32')
1048 buffer = (1 * ctypes.wintypes.DWORD)()
1049 attached_processes = kernel32.GetConsoleProcessList(buffer, 1)
1050 # If we only have a single process attached, then the executable was double clicked
1051 # When using `pyinstaller` with `--onefile`, two processes get attached
1052 is_onefile = hasattr(sys, '_MEIPASS') and os.path.basename(sys._MEIPASS).startswith('_MEI')
1053 if attached_processes == 1 or is_onefile and attached_processes == 2:
1054 print(parser._generate_error_message(
1055 'Do not double-click the executable, instead call it from a command line.\n'
1056 'Please read the README for further information on how to use yt-dlp: '
1057 'https://github.com/yt-dlp/yt-dlp#readme'))
1058 msvcrt.getch()
1059 _exit(2)
1060 parser.error(
1061 'You must provide at least one URL.\n'
1062 'Type yt-dlp --help to see a list of all options.')
1064 parser.destroy()
1065 try:
1066 if opts.load_info_filename is not None:
1067 if all_urls:
1068 ydl.report_warning('URLs are ignored due to --load-info-json')
1069 return ydl.download_with_info_file(expand_path(opts.load_info_filename))
1070 else:
1071 return ydl.download(all_urls)
1072 except DownloadCancelled:
1073 ydl.to_screen('Aborting remaining downloads')
1074 return 101
1077 def main(argv=None):
1078 global _IN_CLI
1079 _IN_CLI = True
1080 try:
1081 _exit(*variadic(_real_main(argv)))
1082 except DownloadError:
1083 _exit(1)
1084 except SameFileError as e:
1085 _exit(f'ERROR: {e}')
1086 except KeyboardInterrupt:
1087 _exit('\nERROR: Interrupted by user')
1088 except BrokenPipeError as e:
1089 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
1090 devnull = os.open(os.devnull, os.O_WRONLY)
1091 os.dup2(devnull, sys.stdout.fileno())
1092 _exit(f'\nERROR: {e}')
1093 except optparse.OptParseError as e:
1094 _exit(2, f'\n{e}')
1097 from .extractor import gen_extractors, list_extractors
1099 __all__ = [
1100 'main',
1101 'YoutubeDL',
1102 'parse_options',
1103 'gen_extractors',
1104 'list_extractors',