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