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