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