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