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