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