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