]> jfr.im git - yt-dlp.git/blame - yt_dlp/__init__.py
[cleanup] Minor cleanup
[yt-dlp.git] / yt_dlp / __init__.py
CommitLineData
cc52de43 1#!/usr/bin/env python3
dcdb292f 2# coding: utf-8
235b3ba4 3
347182a0 4f'You are using an unsupported version of Python. Only Python versions 3.6 and above are supported by yt-dlp' # noqa: F541
a4bc4336 5
235b3ba4 6__license__ = 'Public Domain'
235b3ba4 7
0d94f247 8import codecs
8f563f32 9import io
e9f4ccd1 10import itertools
235b3ba4 11import os
0f818663 12import random
43820c03 13import re
235b3ba4 14import sys
235b3ba4 15
2daabe49
PH
16from .options import (
17 parseOpts,
18)
8c25f81b 19from .compat import (
e68301af 20 compat_getpass,
e9f4ccd1 21 compat_shlex_quote,
e07e9313 22 workaround_optparse_bug9161,
8c25f81b 23)
982ee69a 24from .cookies import SUPPORTED_BROWSERS
8c25f81b 25from .utils import (
a4fd0415
PH
26 DateRange,
27 decodeOption,
a4fd0415 28 DownloadError,
76a264ac 29 error_to_compat_str,
8b0d7497 30 ExistingVideoReached,
590bc6f6 31 expand_path,
31c49255 32 float_or_none,
33 int_or_none,
347de493 34 match_filter_func,
a4fd0415 35 MaxDownloadsReached,
2d9ec704 36 parse_duration,
a4fd0415 37 preferredencoding,
62e609ab 38 read_batch_urls,
8b0d7497 39 RejectedVideoReached,
df692c5a 40 render_table,
a4fd0415 41 SameFileError,
e3946f98 42 setproctitle,
a4fd0415
PH
43 std_headers,
44 write_string,
a4fd0415 45)
c19bc311 46from .update import run_update
92a86f4c 47from .downloader import (
a4fd0415
PH
48 FileDownloader,
49)
2bad0e5d 50from .extractor import gen_extractors, list_extractors
eb8a4433 51from .extractor.common import InfoExtractor
1b6712ab 52from .extractor.adobepass import MSO_INFO
e9f4ccd1 53from .postprocessor import (
81a23040 54 FFmpegExtractAudioPP,
55 FFmpegSubtitlesConvertorPP,
56 FFmpegThumbnailsConvertorPP,
57 FFmpegVideoConvertorPP,
58 FFmpegVideoRemuxerPP,
e9f4ccd1 59 MetadataFromFieldPP,
60 MetadataParserPP,
81a23040 61)
8222d8de 62from .YoutubeDL import YoutubeDL
a4fd0415 63
235b3ba4 64
b8ad4f02 65def _real_main(argv=None):
0d94f247
PH
66 # Compatibility fixes for Windows
67 if sys.platform == 'win32':
067aa17e 68 # https://github.com/ytdl-org/youtube-dl/issues/820
0d94f247
PH
69 codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
70
e07e9313
PH
71 workaround_optparse_bug9161()
72
7a5c1cfe 73 setproctitle('yt-dlp')
e3946f98 74
b8ad4f02 75 parser, opts, args = parseOpts(argv)
0d1bb027 76 warnings = []
59ae15a5 77
59ae15a5
PH
78 # Set user agent
79 if opts.user_agent is not None:
80 std_headers['User-Agent'] = opts.user_agent
1865ed31 81
28535652
BH
82 # Set referer
83 if opts.referer is not None:
84 std_headers['Referer'] = opts.referer
59ae15a5 85
410afb20 86 # Custom HTTP headers
45016689 87 std_headers.update(opts.headers)
410afb20 88
59ae15a5
PH
89 # Dump user agent
90 if opts.dump_user_agent:
7b0d1c28 91 write_string(std_headers['User-Agent'] + '\n', out=sys.stdout)
59ae15a5
PH
92 sys.exit(0)
93
94 # Batch file verification
62e609ab 95 batch_urls = []
59ae15a5
PH
96 if opts.batchfile is not None:
97 try:
98 if opts.batchfile == '-':
99 batchfd = sys.stdin
100 else:
e2eca6f6 101 batchfd = io.open(
590bc6f6 102 expand_path(opts.batchfile),
e2eca6f6 103 'r', encoding='utf-8', errors='ignore')
62e609ab 104 batch_urls = read_batch_urls(batchfd)
05afc96b 105 if opts.verbose:
a4bc4336 106 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
59ae15a5 107 except IOError:
826dcff9 108 sys.exit('ERROR: batch file %s could not be read' % opts.batchfile)
b2fc1c4f 109 all_urls = batch_urls + [url.strip() for url in args] # batch_urls are already striped in read_batch_urls
c774b3c6 110 _enc = preferredencoding()
41292a38 111 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
59ae15a5 112
59ae15a5 113 if opts.list_extractors:
05900629 114 for ie in list_extractors(opts.age_limit):
251ae04e 115 write_string(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie.working() else '') + '\n', out=sys.stdout)
1a2c3c0f 116 matchedUrls = [url for url in all_urls if ie.suitable(url)]
59ae15a5 117 for mu in matchedUrls:
7b0d1c28 118 write_string(' ' + mu + '\n', out=sys.stdout)
59ae15a5 119 sys.exit(0)
0f818663 120 if opts.list_extractor_descriptions:
05900629 121 for ie in list_extractors(opts.age_limit):
251ae04e 122 if not ie.working():
0f818663
PH
123 continue
124 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
15870e90
PH
125 if desc is False:
126 continue
96565c7e 127 if getattr(ie, 'SEARCH_KEY', None) is not None:
50a0f6df 128 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
a4bc4336 129 _COUNTS = ('', '5', '10', 'all')
96565c7e 130 desc += f'; "{ie.SEARCH_KEY}:" prefix (Example: "{ie.SEARCH_KEY}{random.choice(_COUNTS)}:{random.choice(_SEARCHES)}")'
7b0d1c28 131 write_string(desc + '\n', out=sys.stdout)
0f818663 132 sys.exit(0)
87148bb7 133 if opts.ap_list_mso:
1b6712ab 134 table = [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()]
797c636b 135 write_string('Supported TV Providers:\n' + render_table(['mso', 'mso name'], table) + '\n', out=sys.stdout)
1b6712ab 136 sys.exit(0)
0f818663 137
59ae15a5
PH
138 # Conflicting, missing and erroneous options
139 if opts.usenetrc and (opts.username is not None or opts.password is not None):
a4bc4336 140 parser.error('using .netrc conflicts with giving username/password')
59ae15a5 141 if opts.password is not None and opts.username is None:
a4bc4336 142 parser.error('account username missing\n')
1b6712ab
RA
143 if opts.ap_password is not None and opts.ap_username is None:
144 parser.error('TV Provider account username missing\n')
1a241a2d
S
145 if opts.autonumber_size is not None:
146 if opts.autonumber_size <= 0:
147 parser.error('auto number size must be positive')
148 if opts.autonumber_start is not None:
149 if opts.autonumber_start < 0:
150 parser.error('auto number start must be positive or 0')
59ae15a5 151 if opts.username is not None and opts.password is None:
a4bc4336 152 opts.password = compat_getpass('Type account password and press [Return]: ')
1b6712ab
RA
153 if opts.ap_username is not None and opts.ap_password is None:
154 opts.ap_password = compat_getpass('Type TV provider account password and press [Return]: ')
59ae15a5
PH
155 if opts.ratelimit is not None:
156 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
157 if numeric_limit is None:
a4bc4336 158 parser.error('invalid rate limit specified')
59ae15a5 159 opts.ratelimit = numeric_limit
51d9739f 160 if opts.throttledratelimit is not None:
161 numeric_limit = FileDownloader.parse_bytes(opts.throttledratelimit)
162 if numeric_limit is None:
163 parser.error('invalid rate limit specified')
164 opts.throttledratelimit = numeric_limit
9e982f9e
JC
165 if opts.min_filesize is not None:
166 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
167 if numeric_limit is None:
a4bc4336 168 parser.error('invalid min_filesize specified')
9e982f9e
JC
169 opts.min_filesize = numeric_limit
170 if opts.max_filesize is not None:
171 numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
172 if numeric_limit is None:
a4bc4336 173 parser.error('invalid max_filesize specified')
9e982f9e 174 opts.max_filesize = numeric_limit
065bc354 175 if opts.sleep_interval is not None:
176 if opts.sleep_interval < 0:
1ad6b891
S
177 parser.error('sleep interval must be positive or 0')
178 if opts.max_sleep_interval is not None:
179 if opts.max_sleep_interval < 0:
180 parser.error('max sleep interval must be positive or 0')
050afa60
JZ
181 if opts.sleep_interval is None:
182 parser.error('min sleep interval must be specified, use --min-sleep-interval')
1ad6b891
S
183 if opts.max_sleep_interval < opts.sleep_interval:
184 parser.error('max sleep interval must be greater than or equal to min sleep interval')
185 else:
186 opts.max_sleep_interval = opts.sleep_interval
1cf376f5 187 if opts.sleep_interval_subtitles is not None:
188 if opts.sleep_interval_subtitles < 0:
189 parser.error('subtitles sleep interval must be positive or 0')
190 if opts.sleep_interval_requests is not None:
191 if opts.sleep_interval_requests < 0:
192 parser.error('requests sleep interval must be positive or 0')
797c636b 193 if opts.ap_mso and opts.ap_mso not in MSO_INFO:
87148bb7 194 parser.error('Unsupported TV Provider, use --ap-list-mso to get a list of supported TV Providers')
486fb179 195 if opts.overwrites: # --yes-overwrites implies --no-continue
0c3d0f51 196 opts.continue_dl = False
4cf1e5d2 197 if opts.concurrent_fragment_downloads <= 0:
198 raise ValueError('Concurrent fragments must be positive')
52bb437e 199
62bff2c1 200 def parse_retries(retries, name=''):
52bb437e
S
201 if retries in ('inf', 'infinite'):
202 parsed_retries = float('inf')
baeaeffc
PH
203 else:
204 try:
52bb437e 205 parsed_retries = int(retries)
baeaeffc 206 except (TypeError, ValueError):
62bff2c1 207 parser.error('invalid %sretry count specified' % name)
52bb437e
S
208 return parsed_retries
209 if opts.retries is not None:
210 opts.retries = parse_retries(opts.retries)
211 if opts.fragment_retries is not None:
62bff2c1 212 opts.fragment_retries = parse_retries(opts.fragment_retries, 'fragment ')
213 if opts.extractor_retries is not None:
214 opts.extractor_retries = parse_retries(opts.extractor_retries, 'extractor ')
59ae15a5
PH
215 if opts.buffersize is not None:
216 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
217 if numeric_buffersize is None:
a4bc4336 218 parser.error('invalid buffer size specified')
59ae15a5 219 opts.buffersize = numeric_buffersize
ba515388
S
220 if opts.http_chunk_size is not None:
221 numeric_chunksize = FileDownloader.parse_bytes(opts.http_chunk_size)
222 if not numeric_chunksize:
223 parser.error('invalid http chunk size specified')
224 opts.http_chunk_size = numeric_chunksize
a19fd00c 225 if opts.playliststart <= 0:
a4bc4336 226 raise ValueError('Playlist start must be positive')
a19fd00c 227 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
a4bc4336 228 raise ValueError('Playlist end must be greater than playlist start')
59ae15a5 229 if opts.extractaudio:
0930b11f 230 opts.audioformat = opts.audioformat.lower()
81a23040 231 if opts.audioformat not in ['best'] + list(FFmpegExtractAudioPP.SUPPORTED_EXTS):
a4bc4336 232 parser.error('invalid audio format specified')
59ae15a5
PH
233 if opts.audioquality:
234 opts.audioquality = opts.audioquality.strip('k').strip('K')
9af98e17 235 audioquality = int_or_none(float_or_none(opts.audioquality)) # int_or_none prevents inf, nan
236 if audioquality is None or audioquality < 0:
a4bc4336 237 parser.error('invalid audio quality specified')
7851b379 238 if opts.recodevideo is not None:
81a23040 239 opts.recodevideo = opts.recodevideo.replace(' ', '')
240 if not re.match(FFmpegVideoConvertorPP.FORMAT_RE, opts.recodevideo):
241 parser.error('invalid video remux format specified')
17912249 242 if opts.remuxvideo is not None:
df692c5a 243 opts.remuxvideo = opts.remuxvideo.replace(' ', '')
81a23040 244 if not re.match(FFmpegVideoRemuxerPP.FORMAT_RE, opts.remuxvideo):
17912249 245 parser.error('invalid video remux format specified')
e9fade72 246 if opts.convertsubtitles is not None:
81a23040 247 if opts.convertsubtitles not in FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS:
e9fade72 248 parser.error('invalid subtitle format specified')
8fa43c73 249 if opts.convertthumbnails is not None:
81a23040 250 if opts.convertthumbnails not in FFmpegThumbnailsConvertorPP.SUPPORTED_EXTS:
8fa43c73 251 parser.error('invalid thumbnail format specified')
bd1a281e 252
982ee69a
MB
253 if opts.cookiesfrombrowser is not None:
254 opts.cookiesfrombrowser = [
255 part.strip() or None for part in opts.cookiesfrombrowser.split(':', 1)]
ca46b941 256 if opts.cookiesfrombrowser[0].lower() not in SUPPORTED_BROWSERS:
982ee69a
MB
257 parser.error('unsupported browser specified for cookies')
258
bd558525
JMF
259 if opts.date is not None:
260 date = DateRange.day(opts.date)
261 else:
262 date = DateRange(opts.dateafter, opts.datebefore)
59ae15a5 263
31654882 264 compat_opts = opts.compat_opts
53ed7066 265
19b824f6 266 def report_conflict(arg1, arg2):
267 warnings.append(f'{arg2} is ignored since {arg1} was given')
268
53ed7066 269 def _unused_compat_opt(name):
270 if name not in compat_opts:
271 return False
272 compat_opts.discard(name)
273 compat_opts.update(['*%s' % name])
274 return True
275
e4f02757 276 def set_default_compat(compat_name, opt_name, default=True, remove_compat=True):
53ed7066 277 attr = getattr(opts, opt_name)
278 if compat_name in compat_opts:
279 if attr is None:
280 setattr(opts, opt_name, not default)
281 return True
282 else:
283 if remove_compat:
284 _unused_compat_opt(compat_name)
285 return False
286 elif attr is None:
287 setattr(opts, opt_name, default)
288 return None
289
b1940459 290 set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
53ed7066 291 set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
e4f02757 292 set_default_compat('no-clean-infojson', 'clean_infojson')
dac5df5a 293 if 'no-attach-info-json' in compat_opts:
294 if opts.embed_infojson:
295 _unused_compat_opt('no-attach-info-json')
296 else:
297 opts.embed_infojson = False
53ed7066 298 if 'format-sort' in compat_opts:
299 opts.format_sort.extend(InfoExtractor.FormatSort.ytdl_default)
300 _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False)
301 _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False)
302 if _video_multistreams_set is False and _audio_multistreams_set is False:
303 _unused_compat_opt('multistreams')
304 outtmpl_default = opts.outtmpl.get('default')
19b824f6 305 if opts.useid:
306 if outtmpl_default is None:
307 outtmpl_default = opts.outtmpl['default'] = '%(id)s.%(ext)s'
308 else:
309 report_conflict('--output', '--id')
53ed7066 310 if 'filename' in compat_opts:
311 if outtmpl_default is None:
19b824f6 312 outtmpl_default = opts.outtmpl['default'] = '%(title)s-%(id)s.%(ext)s'
53ed7066 313 else:
314 _unused_compat_opt('filename')
315
76a264ac 316 def validate_outtmpl(tmpl, msg):
317 err = YoutubeDL.validate_outtmpl(tmpl)
318 if err:
319 parser.error('invalid %s %r: %s' % (msg, tmpl, error_to_compat_str(err)))
320
321 for k, tmpl in opts.outtmpl.items():
819e0531 322 validate_outtmpl(tmpl, f'{k} output template')
ad3dc496 323 opts.forceprint = opts.forceprint or []
324 for tmpl in opts.forceprint or []:
76a264ac 325 validate_outtmpl(tmpl, 'print template')
7a340e0d 326 validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
819e0531 327 for k, tmpl in opts.progress_template.items():
328 k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
329 validate_outtmpl(tmpl, f'{k} template')
76a264ac 330
de3ef3ed
PH
331 if opts.extractaudio and not opts.keepvideo and opts.format is None:
332 opts.format = 'bestaudio/best'
333
de6000d9 334 if outtmpl_default is not None and not os.path.splitext(outtmpl_default)[1] and opts.extractaudio:
a4bc4336
PH
335 parser.error('Cannot download a video and extract audio into the same'
336 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
de6000d9 337 ' template'.format(outtmpl_default))
0202b52a 338
eb8a4433 339 for f in opts.format_sort:
340 if re.match(InfoExtractor.FormatSort.regex, f) is None:
341 parser.error('invalid format sort string "%s" specified' % f)
29c7a63d 342
e9f4ccd1 343 def metadataparser_actions(f):
344 if isinstance(f, str):
345 cmd = '--parse-metadata %s' % compat_shlex_quote(f)
346 try:
347 actions = [MetadataFromFieldPP.to_action(f)]
348 except Exception as err:
349 parser.error(f'{cmd} is invalid; {err}')
350 else:
351 cmd = '--replace-in-metadata %s' % ' '.join(map(compat_shlex_quote, f))
352 actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
353
354 for action in actions:
355 try:
356 MetadataParserPP.validate_action(*action)
357 except Exception as err:
358 parser.error(f'{cmd} is invalid; {err}')
359 yield action
360
361 if opts.parse_metadata is None:
362 opts.parse_metadata = []
5bfa4862 363 if opts.metafromtitle is not None:
e9f4ccd1 364 opts.parse_metadata.append('title:%s' % opts.metafromtitle)
365 opts.parse_metadata = list(itertools.chain(*map(metadataparser_actions, opts.parse_metadata)))
5bfa4862 366
d2a1fad9 367 any_getting = opts.forceprint or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson or opts.dump_single_json
c0bdf32a 368 any_printing = opts.print_json
590bc6f6 369 download_archive_fn = expand_path(opts.download_archive) if opts.download_archive is not None else opts.download_archive
525ef922 370
f0884c8b 371 # If JSON is not printed anywhere, but comments are requested, save it to file
372 printing_json = opts.dumpjson or opts.print_json or opts.dump_single_json
373 if opts.getcomments and not printing_json:
374 opts.writeinfojson = True
375
7a340e0d
NA
376 if opts.no_sponsorblock:
377 opts.sponsorblock_mark = set()
378 opts.sponsorblock_remove = set()
379 sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
380
7a340e0d
NA
381 opts.remove_chapters = opts.remove_chapters or []
382
7a340e0d
NA
383 if (opts.remove_chapters or sponsorblock_query) and opts.sponskrub is not False:
384 if opts.sponskrub:
385 if opts.remove_chapters:
386 report_conflict('--remove-chapters', '--sponskrub')
387 if opts.sponsorblock_mark:
388 report_conflict('--sponsorblock-mark', '--sponskrub')
389 if opts.sponsorblock_remove:
390 report_conflict('--sponsorblock-remove', '--sponskrub')
391 opts.sponskrub = False
72755351 392 if opts.sponskrub_cut and opts.split_chapters and opts.sponskrub is not False:
393 report_conflict('--split-chapter', '--sponskrub-cut')
394 opts.sponskrub_cut = False
395
7a340e0d
NA
396 if opts.remuxvideo and opts.recodevideo:
397 report_conflict('--recode-video', '--remux-video')
398 opts.remuxvideo = False
399
63ad4d43 400 if opts.allow_unplayable_formats:
9222c381 401 def report_unplayable_conflict(opt_name, arg, default=False, allowed=None):
402 val = getattr(opts, opt_name)
403 if (not allowed and val) or not allowed(val):
404 report_conflict('--allow-unplayable-formats', arg)
405 setattr(opts, opt_name, default)
406
407 report_unplayable_conflict('extractaudio', '--extract-audio')
408 report_unplayable_conflict('remuxvideo', '--remux-video')
409 report_unplayable_conflict('recodevideo', '--recode-video')
410 report_unplayable_conflict('addmetadata', '--embed-metadata')
411 report_unplayable_conflict('addchapters', '--embed-chapters')
412 report_unplayable_conflict('embed_infojson', '--embed-info-json')
413 opts.embed_infojson = False
414 report_unplayable_conflict('embedsubtitles', '--embed-subs')
415 report_unplayable_conflict('embedthumbnail', '--embed-thumbnail')
416 report_unplayable_conflict('xattrs', '--xattrs')
417 report_unplayable_conflict('fixup', '--fixup', default='never', allowed=lambda x: x in (None, 'never', 'ignore'))
63ad4d43 418 opts.fixup = 'never'
9222c381 419 report_unplayable_conflict('remove_chapters', '--remove-chapters', default=[])
420 report_unplayable_conflict('sponsorblock_remove', '--sponsorblock-remove', default=set())
421 report_unplayable_conflict('sponskrub', '--sponskrub', default=set())
63ad4d43 422 opts.sponskrub = False
423
9222c381 424 if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
425 opts.addchapters = True
426
4f026faf 427 # PostProcessors
3ae5e797 428 postprocessors = list(opts.add_postprocessors)
7a340e0d
NA
429 if sponsorblock_query:
430 postprocessors.append({
431 'key': 'SponsorBlock',
432 'categories': sponsorblock_query,
433 'api': opts.sponsorblock_api,
434 # Run this immediately after extraction is complete
435 'when': 'pre_process'
436 })
e9f4ccd1 437 if opts.parse_metadata:
e7db87f7 438 postprocessors.append({
e9f4ccd1 439 'key': 'MetadataParser',
440 'actions': opts.parse_metadata,
56d868db 441 # Run this immediately after extraction is complete
442 'when': 'pre_process'
443 })
444 if opts.convertsubtitles:
445 postprocessors.append({
446 'key': 'FFmpegSubtitlesConvertor',
447 'format': opts.convertsubtitles,
448 # Run this before the actual video download
449 'when': 'before_dl'
e7db87f7 450 })
8fa43c73 451 if opts.convertthumbnails:
452 postprocessors.append({
453 'key': 'FFmpegThumbnailsConvertor',
454 'format': opts.convertthumbnails,
455 # Run this before the actual video download
456 'when': 'before_dl'
457 })
5520aa2d 458 # Must be after all other before_dl
459 if opts.exec_before_dl_cmd:
460 postprocessors.append({
ad3dc496 461 'key': 'Exec',
5520aa2d 462 'exec_cmd': opts.exec_before_dl_cmd,
463 'when': 'before_dl'
464 })
4f026faf
PH
465 if opts.extractaudio:
466 postprocessors.append({
467 'key': 'FFmpegExtractAudio',
468 'preferredcodec': opts.audioformat,
469 'preferredquality': opts.audioquality,
470 'nopostoverwrites': opts.nopostoverwrites,
471 })
efe87a10
FS
472 if opts.remuxvideo:
473 postprocessors.append({
474 'key': 'FFmpegVideoRemuxer',
475 'preferedformat': opts.remuxvideo,
476 })
4f026faf
PH
477 if opts.recodevideo:
478 postprocessors.append({
479 'key': 'FFmpegVideoConvertor',
480 'preferedformat': opts.recodevideo,
481 })
7a340e0d 482 # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
4f026faf 483 if opts.embedsubtitles:
b51d2ae3 484 already_have_subtitle = opts.writesubtitles and 'no-keep-subs' not in compat_opts
4f026faf
PH
485 postprocessors.append({
486 'key': 'FFmpegEmbedSubtitle',
56d868db 487 # already_have_subtitle = True prevents the file from being deleted after embedding
cffab0ee 488 'already_have_subtitle': already_have_subtitle
4f026faf 489 })
b51d2ae3 490 if not opts.writeautomaticsub and 'no-keep-subs' not in compat_opts:
cffab0ee 491 opts.writesubtitles = True
492 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
493 # this was the old behaviour if only --all-sub was given.
494 if opts.allsubtitles and not opts.writeautomaticsub:
495 opts.writesubtitles = True
7a340e0d 496 # ModifyChapters must run before FFmpegMetadataPP
2d9ec704 497 remove_chapters_patterns, remove_ranges = [], []
7a340e0d 498 for regex in opts.remove_chapters:
2d9ec704 499 if regex.startswith('*'):
500 dur = list(map(parse_duration, regex[1:].split('-')))
501 if len(dur) == 2 and all(t is not None for t in dur):
502 remove_ranges.append(tuple(dur))
503 continue
504 parser.error(f'invalid --remove-chapters time range {regex!r}. Must be of the form ?start-end')
7a340e0d
NA
505 try:
506 remove_chapters_patterns.append(re.compile(regex))
507 except re.error as err:
508 parser.error(f'invalid --remove-chapters regex {regex!r} - {err}')
509 if opts.remove_chapters or sponsorblock_query:
510 postprocessors.append({
511 'key': 'ModifyChapters',
512 'remove_chapters_patterns': remove_chapters_patterns,
513 'remove_sponsor_segments': opts.sponsorblock_remove,
2d9ec704 514 'remove_ranges': remove_ranges,
7a340e0d
NA
515 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
516 'force_keyframes': opts.force_keyframes_at_cuts
517 })
518 # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
519 # FFmpegExtractAudioPP as containers before conversion may not support
520 # metadata (3gp, webm, etc.)
521 # By default ffmpeg preserves metadata applicable for both
522 # source and target containers. From this point the container won't change,
523 # so metadata can be added here.
dac5df5a 524 if opts.addmetadata or opts.addchapters or opts.embed_infojson:
525 if opts.embed_infojson is None:
526 opts.embed_infojson = 'if_exists'
7a340e0d
NA
527 postprocessors.append({
528 'key': 'FFmpegMetadata',
529 'add_chapters': opts.addchapters,
530 'add_metadata': opts.addmetadata,
dac5df5a 531 'add_infojson': opts.embed_infojson,
7a340e0d 532 })
e6f21b3d 533 # Note: Deprecated
f4e4be19 534 # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
535 # but must be below EmbedSubtitle and FFmpegMetadata
536 # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
a9e7f546 537 # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
538 if opts.sponskrub is not False:
539 postprocessors.append({
540 'key': 'SponSkrub',
541 'path': opts.sponskrub_path,
542 'args': opts.sponskrub_args,
543 'cut': opts.sponskrub_cut,
544 'force': opts.sponskrub_force,
545 'ignoreerror': opts.sponskrub is None,
546 })
f4e4be19 547 if opts.embedthumbnail:
548 already_have_thumbnail = opts.writethumbnail or opts.write_all_thumbnails
549 postprocessors.append({
550 'key': 'EmbedThumbnail',
56d868db 551 # already_have_thumbnail = True prevents the file from being deleted after embedding
f4e4be19 552 'already_have_thumbnail': already_have_thumbnail
553 })
554 if not already_have_thumbnail:
555 opts.writethumbnail = True
80c03fa9 556 opts.outtmpl['pl_thumbnail'] = ''
72755351 557 if opts.split_chapters:
7a340e0d
NA
558 postprocessors.append({
559 'key': 'FFmpegSplitChapters',
560 'force_keyframes': opts.force_keyframes_at_cuts,
561 })
72755351 562 # XAttrMetadataPP should be run after post-processors that may change file contents
563 if opts.xattrs:
564 postprocessors.append({'key': 'XAttrMetadata'})
ad3dc496 565 # Exec must be the last PP
4f026faf
PH
566 if opts.exec_cmd:
567 postprocessors.append({
ad3dc496 568 'key': 'Exec',
4f026faf 569 'exec_cmd': opts.exec_cmd,
56d868db 570 # Run this only after the files have been moved to their final locations
571 'when': 'after_move'
4f026faf 572 })
1b77b347 573
06869367 574 def report_args_compat(arg, name):
0d1bb027 575 warnings.append('%s given without specifying name. The arguments will be given to all %s' % (arg, name))
576
b8f6bbe6 577 if 'default' in opts.external_downloader_args:
0d1bb027 578 report_args_compat('--downloader-args', 'external downloaders')
b8f6bbe6 579
45016689 580 if 'default-compat' in opts.postprocessor_args and 'default' not in opts.postprocessor_args:
06869367 581 report_args_compat('--post-processor-args', 'post-processors')
45016689 582 opts.postprocessor_args.setdefault('sponskrub', [])
583 opts.postprocessor_args['default'] = opts.postprocessor_args['default-compat']
1b77b347 584
df692c5a 585 final_ext = (
81a23040 586 opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
587 else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
588 else opts.audioformat if (opts.extractaudio and opts.audioformat != 'best')
589 else None)
f6d7624f 590
347de493
PH
591 match_filter = (
592 None if opts.match_filter is None
593 else match_filter_func(opts.match_filter))
4f026faf 594
bdde425c 595 ydl_opts = {
59ae15a5 596 'usenetrc': opts.usenetrc,
0001fcb5 597 'netrc_location': opts.netrc_location,
59ae15a5
PH
598 'username': opts.username,
599 'password': opts.password,
83317f69 600 'twofactor': opts.twofactor,
c6c19746 601 'videopassword': opts.videopassword,
797c636b 602 'ap_mso': opts.ap_mso,
1b6712ab
RA
603 'ap_username': opts.ap_username,
604 'ap_password': opts.ap_password,
c0bdf32a 605 'quiet': (opts.quiet or any_getting or any_printing),
ad8915b7 606 'no_warnings': opts.no_warnings,
59ae15a5
PH
607 'forceurl': opts.geturl,
608 'forcetitle': opts.gettitle,
1a2adf3f 609 'forceid': opts.getid,
59ae15a5
PH
610 'forcethumbnail': opts.getthumbnail,
611 'forcedescription': opts.getdescription,
525ef922 612 'forceduration': opts.getduration,
59ae15a5
PH
613 'forcefilename': opts.getfilename,
614 'forceformat': opts.getformat,
d2a1fad9 615 'forceprint': opts.forceprint,
c0bdf32a 616 'forcejson': opts.dumpjson or opts.print_json,
63e0be34 617 'dump_single_json': opts.dump_single_json,
2d30509f 618 'force_write_download_archive': opts.force_write_download_archive,
b7b04c78 619 'simulate': (any_getting or None) if opts.simulate is None else opts.simulate,
1bdeb7be 620 'skip_download': opts.skip_download,
59ae15a5 621 'format': opts.format,
63ad4d43 622 'allow_unplayable_formats': opts.allow_unplayable_formats,
b7da73eb 623 'ignore_no_formats_error': opts.ignore_no_formats_error,
eb8a4433 624 'format_sort': opts.format_sort,
625 'format_sort_force': opts.format_sort_force,
909d24dd 626 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
627 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
e8e73840 628 'check_formats': opts.check_formats,
59ae15a5 629 'listformats': opts.listformats,
76d321f6 630 'listformats_table': opts.listformats_table,
486fb179 631 'outtmpl': opts.outtmpl,
a820dc72 632 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
0202b52a 633 'paths': opts.paths,
213c31ae 634 'autonumber_size': opts.autonumber_size,
acbb2374 635 'autonumber_start': opts.autonumber_start,
59ae15a5 636 'restrictfilenames': opts.restrictfilenames,
c2934512 637 'windowsfilenames': opts.windowsfilenames,
59ae15a5 638 'ignoreerrors': opts.ignoreerrors,
d22dec74 639 'force_generic_extractor': opts.force_generic_extractor,
59ae15a5 640 'ratelimit': opts.ratelimit,
51d9739f 641 'throttledratelimit': opts.throttledratelimit,
0c3d0f51 642 'overwrites': opts.overwrites,
52bb437e
S
643 'retries': opts.retries,
644 'fragment_retries': opts.fragment_retries,
62bff2c1 645 'extractor_retries': opts.extractor_retries,
9603b660 646 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
0eee52f3 647 'keep_fragments': opts.keep_fragments,
4cf1e5d2 648 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
59ae15a5
PH
649 'buffersize': opts.buffersize,
650 'noresizebuffer': opts.noresizebuffer,
ba515388 651 'http_chunk_size': opts.http_chunk_size,
59ae15a5 652 'continuedl': opts.continue_dl,
819e0531 653 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
5717d91a 654 'progress_with_newline': opts.progress_with_newline,
819e0531 655 'progress_template': opts.progress_template,
59ae15a5
PH
656 'playliststart': opts.playliststart,
657 'playlistend': opts.playlistend,
ff815fe6 658 'playlistreverse': opts.playlist_reverse,
75822ca7 659 'playlistrandom': opts.playlist_random,
47192f92 660 'noplaylist': opts.noplaylist,
de6000d9 661 'logtostderr': outtmpl_default == '-',
59ae15a5
PH
662 'consoletitle': opts.consoletitle,
663 'nopart': opts.nopart,
664 'updatetime': opts.updatetime,
665 'writedescription': opts.writedescription,
1fb07d10 666 'writeannotations': opts.writeannotations,
f0884c8b 667 'writeinfojson': opts.writeinfojson,
1ea24129 668 'allow_playlist_files': opts.allow_playlist_files,
75d43ca0 669 'clean_infojson': opts.clean_infojson,
06167fbb 670 'getcomments': opts.getcomments,
11d9224e 671 'writethumbnail': opts.writethumbnail,
ec82d85a 672 'write_all_thumbnails': opts.write_all_thumbnails,
732044af 673 'writelink': opts.writelink,
674 'writeurllink': opts.writeurllink,
675 'writewebloclink': opts.writewebloclink,
676 'writedesktoplink': opts.writedesktoplink,
59ae15a5 677 'writesubtitles': opts.writesubtitles,
b004821f 678 'writeautomaticsub': opts.writeautomaticsub,
ae608b80 679 'allsubtitles': opts.allsubtitles,
2a4093ea 680 'listsubtitles': opts.listsubtitles,
9e62bc44 681 'subtitlesformat': opts.subtitlesformat,
d6e203b3 682 'subtitleslangs': opts.subtitleslangs,
8271226a
PH
683 'matchtitle': decodeOption(opts.matchtitle),
684 'rejecttitle': decodeOption(opts.rejecttitle),
59ae15a5
PH
685 'max_downloads': opts.max_downloads,
686 'prefer_free_formats': opts.prefer_free_formats,
bdc3fd2f 687 'trim_file_name': opts.trim_file_name,
59ae15a5 688 'verbose': opts.verbose,
855703e5 689 'dump_intermediate_pages': opts.dump_intermediate_pages,
d41e6efc 690 'write_pages': opts.write_pages,
8d5d3a5d 691 'test': opts.test,
7851b379 692 'keepvideo': opts.keepvideo,
9e982f9e 693 'min_filesize': opts.min_filesize,
bd558525 694 'max_filesize': opts.max_filesize,
5fe18bdb
PH
695 'min_views': opts.min_views,
696 'max_views': opts.max_views,
11d9224e 697 'daterange': date,
7f747732 698 'cachedir': opts.cachedir,
f8061589 699 'youtube_print_sig_code': opts.youtube_print_sig_code,
8dbe9899 700 'age_limit': opts.age_limit,
17093b83 701 'download_archive': download_archive_fn,
ea6e0c2b 702 'break_on_existing': opts.break_on_existing,
8b0d7497 703 'break_on_reject': opts.break_on_reject,
26e2805c 704 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
dca08720 705 'cookiefile': opts.cookiefile,
982ee69a 706 'cookiesfrombrowser': opts.cookiesfrombrowser,
dca08720 707 'nocheckcertificate': opts.no_check_certificate,
7e8c0af0 708 'prefer_insecure': opts.prefer_insecure,
c2e52508 709 'proxy': opts.proxy,
6ad14cab 710 'socket_timeout': opts.socket_timeout,
0783b09b 711 'bidi_workaround': opts.bidi_workaround,
a0ddb8a2 712 'debug_printtraffic': opts.debug_printtraffic,
76b1bd67 713 'prefer_ffmpeg': opts.prefer_ffmpeg,
7b0817e8 714 'include_ads': opts.include_ads,
04b4d394 715 'default_search': opts.default_search,
78895bd3 716 'dynamic_mpd': opts.dynamic_mpd,
5d3a0e79 717 'extractor_args': opts.extractor_args,
4919603f 718 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
78895bd3 719 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
62fec3b2 720 'encoding': opts.encoding,
057a5206 721 'extract_flat': opts.extract_flat,
d77ab8e2 722 'mark_watched': opts.mark_watched,
34c781a2 723 'merge_output_format': opts.merge_output_format,
df692c5a 724 'final_ext': final_ext,
4f026faf 725 'postprocessors': postprocessors,
6271f1ca 726 'fixup': opts.fixup,
be4a824d 727 'source_address': opts.source_address,
58b1f00d 728 'call_home': opts.call_home,
1cf376f5 729 'sleep_interval_requests': opts.sleep_interval_requests,
5f0d813d 730 'sleep_interval': opts.sleep_interval,
065bc354 731 'max_sleep_interval': opts.max_sleep_interval,
0c9df79e 732 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
222516d9 733 'external_downloader': opts.external_downloader,
cfb56d1a 734 'list_thumbnails': opts.list_thumbnails,
c14e88f0 735 'playlist_items': opts.playlist_items,
881e6a1f 736 'xattr_set_filesize': opts.xattr_set_filesize,
347de493 737 'match_filter': match_filter,
7e5db8c9 738 'no_color': opts.no_color,
73fac4e9 739 'ffmpeg_location': opts.ffmpeg_location,
85729c51 740 'hls_prefer_native': opts.hls_prefer_native,
7d106a65 741 'hls_use_mpegts': opts.hls_use_mpegts,
310c2ed2 742 'hls_split_discontinuity': opts.hls_split_discontinuity,
46ee996e 743 'external_downloader_args': opts.external_downloader_args,
45016689 744 'postprocessor_args': opts.postprocessor_args,
91410c9b 745 'cn_verification_proxy': opts.cn_verification_proxy,
38cce791 746 'geo_verification_proxy': opts.geo_verification_proxy,
0a840f58
S
747 'geo_bypass': opts.geo_bypass,
748 'geo_bypass_country': opts.geo_bypass_country,
5f95927a 749 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
49a57e70 750 '_warnings': warnings,
53ed7066 751 'compat_opts': compat_opts,
bdde425c 752 }
59ae15a5 753
bdde425c 754 with YoutubeDL(ydl_opts) as ydl:
e5813e53 755 actual_use = len(all_urls) or opts.load_info_filename
bdde425c 756
052421ff
PH
757 # Remove cache dir
758 if opts.rm_cachedir:
a0e07d31 759 ydl.cache.remove()
052421ff 760
e5813e53 761 # Update version
762 if opts.update_self:
763 # If updater returns True, exit. Required for windows
c19bc311 764 if run_update(ydl):
e5813e53 765 if actual_use:
6b027907 766 sys.exit('ERROR: The program must exit for the update to complete')
e5813e53 767 sys.exit()
768
bdde425c 769 # Maybe do nothing
e5813e53 770 if not actual_use:
7d4111ed 771 if opts.update_self or opts.rm_cachedir:
bdde425c 772 sys.exit()
59ae15a5 773
7d4111ed 774 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
adc0ae3c
PH
775 parser.error(
776 'You must provide at least one URL.\n'
7a5c1cfe 777 'Type yt-dlp --help to see a list of all options.')
7d4111ed 778
bdde425c 779 try:
1dcc4c0c 780 if opts.load_info_filename is not None:
590bc6f6 781 retcode = ydl.download_with_info_file(expand_path(opts.load_info_filename))
1dcc4c0c
JMF
782 else:
783 retcode = ydl.download(all_urls)
8b0d7497 784 except (MaxDownloadsReached, ExistingVideoReached, RejectedVideoReached):
785 ydl.to_screen('Aborting remaining downloads')
bdde425c 786 retcode = 101
59ae15a5 787
59ae15a5 788 sys.exit(retcode)
235b3ba4 789
a27b9e8b 790
b8ad4f02 791def main(argv=None):
59ae15a5 792 try:
b8ad4f02 793 _real_main(argv)
59ae15a5
PH
794 except DownloadError:
795 sys.exit(1)
aa9369a2 796 except SameFileError as e:
797 sys.exit(f'ERROR: {e}')
59ae15a5 798 except KeyboardInterrupt:
a4bc4336 799 sys.exit('\nERROR: Interrupted by user')
aa9369a2 800 except BrokenPipeError as e:
cc3fa8d3 801 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
802 devnull = os.open(os.devnull, os.O_WRONLY)
803 os.dup2(devnull, sys.stdout.fileno())
aa9369a2 804 sys.exit(f'\nERROR: {e}')
2bad0e5d 805
582be358 806
2bad0e5d 807__all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']