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