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