]> jfr.im git - yt-dlp.git/blob - yt_dlp/__init__.py
[cleanup] Misc cleanup
[yt-dlp.git] / yt_dlp / __init__.py
1 #!/usr/bin/env python3
2 # coding: utf-8
3
4 f'You are using an unsupported version of Python. Only Python versions 3.6 and above are supported by yt-dlp' # noqa: F541
5
6 __license__ = 'Public Domain'
7
8 import codecs
9 import io
10 import itertools
11 import os
12 import random
13 import re
14 import sys
15
16 from .options import (
17 parseOpts,
18 )
19 from .compat import (
20 compat_getpass,
21 compat_os_name,
22 compat_shlex_quote,
23 workaround_optparse_bug9161,
24 )
25 from .cookies import SUPPORTED_BROWSERS
26 from .utils import (
27 DateRange,
28 decodeOption,
29 DownloadCancelled,
30 DownloadError,
31 error_to_compat_str,
32 expand_path,
33 GeoUtils,
34 float_or_none,
35 int_or_none,
36 match_filter_func,
37 parse_duration,
38 preferredencoding,
39 read_batch_urls,
40 render_table,
41 SameFileError,
42 setproctitle,
43 std_headers,
44 write_string,
45 )
46 from .update import run_update
47 from .downloader import (
48 FileDownloader,
49 )
50 from .extractor import gen_extractors, list_extractors
51 from .extractor.common import InfoExtractor
52 from .extractor.adobepass import MSO_INFO
53 from .postprocessor import (
54 FFmpegExtractAudioPP,
55 FFmpegSubtitlesConvertorPP,
56 FFmpegThumbnailsConvertorPP,
57 FFmpegVideoConvertorPP,
58 FFmpegVideoRemuxerPP,
59 MetadataFromFieldPP,
60 MetadataParserPP,
61 )
62 from .YoutubeDL import YoutubeDL
63
64
65 def _real_main(argv=None):
66 # Compatibility fixes for Windows
67 if sys.platform == 'win32':
68 # https://github.com/ytdl-org/youtube-dl/issues/820
69 codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
70
71 workaround_optparse_bug9161()
72
73 setproctitle('yt-dlp')
74
75 parser, opts, args = parseOpts(argv)
76 warnings, deprecation_warnings = [], []
77
78 # Set user agent
79 if opts.user_agent is not None:
80 std_headers['User-Agent'] = opts.user_agent
81
82 # Set referer
83 if opts.referer is not None:
84 std_headers['Referer'] = opts.referer
85
86 # Custom HTTP headers
87 std_headers.update(opts.headers)
88
89 # Dump user agent
90 if opts.dump_user_agent:
91 write_string(std_headers['User-Agent'] + '\n', out=sys.stdout)
92 sys.exit(0)
93
94 # Batch file verification
95 batch_urls = []
96 if opts.batchfile is not None:
97 try:
98 if opts.batchfile == '-':
99 write_string('Reading URLs from stdin - EOF (%s) to end:\n' % (
100 'Ctrl+Z' if compat_os_name == 'nt' else 'Ctrl+D'))
101 batchfd = sys.stdin
102 else:
103 batchfd = io.open(
104 expand_path(opts.batchfile),
105 'r', encoding='utf-8', errors='ignore')
106 batch_urls = read_batch_urls(batchfd)
107 if opts.verbose:
108 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
109 except IOError:
110 sys.exit('ERROR: batch file %s could not be read' % opts.batchfile)
111 all_urls = batch_urls + [url.strip() for url in args] # batch_urls are already striped in read_batch_urls
112 _enc = preferredencoding()
113 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
114
115 if opts.list_extractors:
116 for ie in list_extractors(opts.age_limit):
117 write_string(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie.working() else '') + '\n', out=sys.stdout)
118 matchedUrls = [url for url in all_urls if ie.suitable(url)]
119 for mu in matchedUrls:
120 write_string(' ' + mu + '\n', out=sys.stdout)
121 sys.exit(0)
122 if opts.list_extractor_descriptions:
123 for ie in list_extractors(opts.age_limit):
124 if not ie.working():
125 continue
126 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
127 if desc is False:
128 continue
129 if getattr(ie, 'SEARCH_KEY', None) is not None:
130 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
131 _COUNTS = ('', '5', '10', 'all')
132 desc += f'; "{ie.SEARCH_KEY}:" prefix (Example: "{ie.SEARCH_KEY}{random.choice(_COUNTS)}:{random.choice(_SEARCHES)}")'
133 write_string(desc + '\n', out=sys.stdout)
134 sys.exit(0)
135 if opts.ap_list_mso:
136 table = [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()]
137 write_string('Supported TV Providers:\n' + render_table(['mso', 'mso name'], table) + '\n', out=sys.stdout)
138 sys.exit(0)
139
140 # Conflicting, missing and erroneous options
141 if opts.format == 'best':
142 warnings.append('.\n '.join(
143 '"-f best" selects the best pre-merged format which is often not the best option',
144 'To let yt-dlp download and merge the best available formats, simply do not pass any format selection',
145 'If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning'))
146 if opts.usenetrc and (opts.username is not None or opts.password is not None):
147 parser.error('using .netrc conflicts with giving username/password')
148 if opts.password is not None and opts.username is None:
149 parser.error('account username missing\n')
150 if opts.ap_password is not None and opts.ap_username is None:
151 parser.error('TV Provider account username missing\n')
152 if opts.autonumber_size is not None:
153 if opts.autonumber_size <= 0:
154 parser.error('auto number size must be positive')
155 if opts.autonumber_start is not None:
156 if opts.autonumber_start < 0:
157 parser.error('auto number start must be positive or 0')
158 if opts.username is not None and opts.password is None:
159 opts.password = compat_getpass('Type account password and press [Return]: ')
160 if opts.ap_username is not None and opts.ap_password is None:
161 opts.ap_password = compat_getpass('Type TV provider account password and press [Return]: ')
162 if opts.ratelimit is not None:
163 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
164 if numeric_limit is None:
165 parser.error('invalid rate limit specified')
166 opts.ratelimit = numeric_limit
167 if opts.throttledratelimit is not None:
168 numeric_limit = FileDownloader.parse_bytes(opts.throttledratelimit)
169 if numeric_limit is None:
170 parser.error('invalid rate limit specified')
171 opts.throttledratelimit = numeric_limit
172 if opts.min_filesize is not None:
173 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
174 if numeric_limit is None:
175 parser.error('invalid min_filesize specified')
176 opts.min_filesize = numeric_limit
177 if opts.max_filesize is not None:
178 numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
179 if numeric_limit is None:
180 parser.error('invalid max_filesize specified')
181 opts.max_filesize = numeric_limit
182 if opts.sleep_interval is not None:
183 if opts.sleep_interval < 0:
184 parser.error('sleep interval must be positive or 0')
185 if opts.max_sleep_interval is not None:
186 if opts.max_sleep_interval < 0:
187 parser.error('max sleep interval must be positive or 0')
188 if opts.sleep_interval is None:
189 parser.error('min sleep interval must be specified, use --min-sleep-interval')
190 if opts.max_sleep_interval < opts.sleep_interval:
191 parser.error('max sleep interval must be greater than or equal to min sleep interval')
192 else:
193 opts.max_sleep_interval = opts.sleep_interval
194 if opts.sleep_interval_subtitles is not None:
195 if opts.sleep_interval_subtitles < 0:
196 parser.error('subtitles sleep interval must be positive or 0')
197 if opts.sleep_interval_requests is not None:
198 if opts.sleep_interval_requests < 0:
199 parser.error('requests sleep interval must be positive or 0')
200 if opts.ap_mso and opts.ap_mso not in MSO_INFO:
201 parser.error('Unsupported TV Provider, use --ap-list-mso to get a list of supported TV Providers')
202 if opts.overwrites: # --yes-overwrites implies --no-continue
203 opts.continue_dl = False
204 if opts.concurrent_fragment_downloads <= 0:
205 parser.error('Concurrent fragments must be positive')
206 if opts.wait_for_video is not None:
207 min_wait, max_wait, *_ = map(parse_duration, opts.wait_for_video.split('-', 1) + [None])
208 if min_wait is None or (max_wait is None and '-' in opts.wait_for_video):
209 parser.error('Invalid time range to wait')
210 elif max_wait is not None and max_wait < min_wait:
211 parser.error('Minimum time range to wait must not be longer than the maximum')
212 opts.wait_for_video = (min_wait, max_wait)
213
214 def parse_retries(retries, name=''):
215 if retries in ('inf', 'infinite'):
216 parsed_retries = float('inf')
217 else:
218 try:
219 parsed_retries = int(retries)
220 except (TypeError, ValueError):
221 parser.error('invalid %sretry count specified' % name)
222 return parsed_retries
223 if opts.retries is not None:
224 opts.retries = parse_retries(opts.retries)
225 if opts.fragment_retries is not None:
226 opts.fragment_retries = parse_retries(opts.fragment_retries, 'fragment ')
227 if opts.extractor_retries is not None:
228 opts.extractor_retries = parse_retries(opts.extractor_retries, 'extractor ')
229 if opts.buffersize is not None:
230 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
231 if numeric_buffersize is None:
232 parser.error('invalid buffer size specified')
233 opts.buffersize = numeric_buffersize
234 if opts.http_chunk_size is not None:
235 numeric_chunksize = FileDownloader.parse_bytes(opts.http_chunk_size)
236 if not numeric_chunksize:
237 parser.error('invalid http chunk size specified')
238 opts.http_chunk_size = numeric_chunksize
239 if opts.playliststart <= 0:
240 raise parser.error('Playlist start must be positive')
241 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
242 raise parser.error('Playlist end must be greater than playlist start')
243 if opts.extractaudio:
244 opts.audioformat = opts.audioformat.lower()
245 if opts.audioformat not in ['best'] + list(FFmpegExtractAudioPP.SUPPORTED_EXTS):
246 parser.error('invalid audio format specified')
247 if opts.audioquality:
248 opts.audioquality = opts.audioquality.strip('k').strip('K')
249 audioquality = int_or_none(float_or_none(opts.audioquality)) # int_or_none prevents inf, nan
250 if audioquality is None or audioquality < 0:
251 parser.error('invalid audio quality specified')
252 if opts.recodevideo is not None:
253 opts.recodevideo = opts.recodevideo.replace(' ', '')
254 if not re.match(FFmpegVideoConvertorPP.FORMAT_RE, opts.recodevideo):
255 parser.error('invalid video remux format specified')
256 if opts.remuxvideo is not None:
257 opts.remuxvideo = opts.remuxvideo.replace(' ', '')
258 if not re.match(FFmpegVideoRemuxerPP.FORMAT_RE, opts.remuxvideo):
259 parser.error('invalid video remux format specified')
260 if opts.convertsubtitles is not None:
261 if opts.convertsubtitles not in FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS:
262 parser.error('invalid subtitle format specified')
263 if opts.convertthumbnails is not None:
264 if opts.convertthumbnails not in FFmpegThumbnailsConvertorPP.SUPPORTED_EXTS:
265 parser.error('invalid thumbnail format specified')
266 if opts.cookiesfrombrowser is not None:
267 opts.cookiesfrombrowser = [
268 part.strip() or None for part in opts.cookiesfrombrowser.split(':', 1)]
269 if opts.cookiesfrombrowser[0].lower() not in SUPPORTED_BROWSERS:
270 parser.error('unsupported browser specified for cookies')
271 geo_bypass_code = opts.geo_bypass_ip_block or opts.geo_bypass_country
272 if geo_bypass_code is not None:
273 try:
274 GeoUtils.random_ipv4(geo_bypass_code)
275 except Exception:
276 parser.error('unsupported geo-bypass country or ip-block')
277
278 if opts.date is not None:
279 date = DateRange.day(opts.date)
280 else:
281 date = DateRange(opts.dateafter, opts.datebefore)
282
283 compat_opts = opts.compat_opts
284
285 def report_conflict(arg1, arg2):
286 warnings.append(f'{arg2} is ignored since {arg1} was given')
287
288 def _unused_compat_opt(name):
289 if name not in compat_opts:
290 return False
291 compat_opts.discard(name)
292 compat_opts.update(['*%s' % name])
293 return True
294
295 def set_default_compat(compat_name, opt_name, default=True, remove_compat=True):
296 attr = getattr(opts, opt_name)
297 if compat_name in compat_opts:
298 if attr is None:
299 setattr(opts, opt_name, not default)
300 return True
301 else:
302 if remove_compat:
303 _unused_compat_opt(compat_name)
304 return False
305 elif attr is None:
306 setattr(opts, opt_name, default)
307 return None
308
309 set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
310 set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
311 set_default_compat('no-clean-infojson', 'clean_infojson')
312 if 'no-attach-info-json' in compat_opts:
313 if opts.embed_infojson:
314 _unused_compat_opt('no-attach-info-json')
315 else:
316 opts.embed_infojson = False
317 if 'format-sort' in compat_opts:
318 opts.format_sort.extend(InfoExtractor.FormatSort.ytdl_default)
319 _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False)
320 _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False)
321 if _video_multistreams_set is False and _audio_multistreams_set is False:
322 _unused_compat_opt('multistreams')
323 outtmpl_default = opts.outtmpl.get('default')
324 if opts.useid:
325 if outtmpl_default is None:
326 outtmpl_default = opts.outtmpl['default'] = '%(id)s.%(ext)s'
327 else:
328 report_conflict('--output', '--id')
329 if 'filename' in compat_opts:
330 if outtmpl_default is None:
331 outtmpl_default = opts.outtmpl['default'] = '%(title)s-%(id)s.%(ext)s'
332 else:
333 _unused_compat_opt('filename')
334
335 def validate_outtmpl(tmpl, msg):
336 err = YoutubeDL.validate_outtmpl(tmpl)
337 if err:
338 parser.error('invalid %s %r: %s' % (msg, tmpl, error_to_compat_str(err)))
339
340 for k, tmpl in opts.outtmpl.items():
341 validate_outtmpl(tmpl, f'{k} output template')
342 opts.forceprint = opts.forceprint or []
343 for tmpl in opts.forceprint or []:
344 validate_outtmpl(tmpl, 'print template')
345 validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
346 for k, tmpl in opts.progress_template.items():
347 k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
348 validate_outtmpl(tmpl, f'{k} template')
349
350 if opts.extractaudio and not opts.keepvideo and opts.format is None:
351 opts.format = 'bestaudio/best'
352
353 if outtmpl_default is not None and not os.path.splitext(outtmpl_default)[1] and opts.extractaudio:
354 parser.error('Cannot download a video and extract audio into the same'
355 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
356 ' template'.format(outtmpl_default))
357
358 for f in opts.format_sort:
359 if re.match(InfoExtractor.FormatSort.regex, f) is None:
360 parser.error('invalid format sort string "%s" specified' % f)
361
362 def metadataparser_actions(f):
363 if isinstance(f, str):
364 cmd = '--parse-metadata %s' % compat_shlex_quote(f)
365 try:
366 actions = [MetadataFromFieldPP.to_action(f)]
367 except Exception as err:
368 parser.error(f'{cmd} is invalid; {err}')
369 else:
370 cmd = '--replace-in-metadata %s' % ' '.join(map(compat_shlex_quote, f))
371 actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
372
373 for action in actions:
374 try:
375 MetadataParserPP.validate_action(*action)
376 except Exception as err:
377 parser.error(f'{cmd} is invalid; {err}')
378 yield action
379
380 if opts.parse_metadata is None:
381 opts.parse_metadata = []
382 if opts.metafromtitle is not None:
383 opts.parse_metadata.append('title:%s' % opts.metafromtitle)
384 opts.parse_metadata = list(itertools.chain(*map(metadataparser_actions, opts.parse_metadata)))
385
386 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
387 any_printing = opts.print_json
388 download_archive_fn = expand_path(opts.download_archive) if opts.download_archive is not None else opts.download_archive
389
390 # If JSON is not printed anywhere, but comments are requested, save it to file
391 printing_json = opts.dumpjson or opts.print_json or opts.dump_single_json
392 if opts.getcomments and not printing_json:
393 opts.writeinfojson = True
394
395 if opts.no_sponsorblock:
396 opts.sponsorblock_mark = set()
397 opts.sponsorblock_remove = set()
398 sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
399
400 opts.remove_chapters = opts.remove_chapters or []
401
402 if (opts.remove_chapters or sponsorblock_query) and opts.sponskrub is not False:
403 if opts.sponskrub:
404 if opts.remove_chapters:
405 report_conflict('--remove-chapters', '--sponskrub')
406 if opts.sponsorblock_mark:
407 report_conflict('--sponsorblock-mark', '--sponskrub')
408 if opts.sponsorblock_remove:
409 report_conflict('--sponsorblock-remove', '--sponskrub')
410 opts.sponskrub = False
411 if opts.sponskrub_cut and opts.split_chapters and opts.sponskrub is not False:
412 report_conflict('--split-chapter', '--sponskrub-cut')
413 opts.sponskrub_cut = False
414
415 if opts.remuxvideo and opts.recodevideo:
416 report_conflict('--recode-video', '--remux-video')
417 opts.remuxvideo = False
418
419 if opts.allow_unplayable_formats:
420 def report_unplayable_conflict(opt_name, arg, default=False, allowed=None):
421 val = getattr(opts, opt_name)
422 if (not allowed and val) or (allowed and not allowed(val)):
423 report_conflict('--allow-unplayable-formats', arg)
424 setattr(opts, opt_name, default)
425
426 report_unplayable_conflict('extractaudio', '--extract-audio')
427 report_unplayable_conflict('remuxvideo', '--remux-video')
428 report_unplayable_conflict('recodevideo', '--recode-video')
429 report_unplayable_conflict('addmetadata', '--embed-metadata')
430 report_unplayable_conflict('addchapters', '--embed-chapters')
431 report_unplayable_conflict('embed_infojson', '--embed-info-json')
432 opts.embed_infojson = False
433 report_unplayable_conflict('embedsubtitles', '--embed-subs')
434 report_unplayable_conflict('embedthumbnail', '--embed-thumbnail')
435 report_unplayable_conflict('xattrs', '--xattrs')
436 report_unplayable_conflict('fixup', '--fixup', default='never', allowed=lambda x: x in (None, 'never', 'ignore'))
437 opts.fixup = 'never'
438 report_unplayable_conflict('remove_chapters', '--remove-chapters', default=[])
439 report_unplayable_conflict('sponsorblock_remove', '--sponsorblock-remove', default=set())
440 report_unplayable_conflict('sponskrub', '--sponskrub', default=set())
441 opts.sponskrub = False
442
443 if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
444 opts.addchapters = True
445
446 # PostProcessors
447 postprocessors = list(opts.add_postprocessors)
448 if sponsorblock_query:
449 postprocessors.append({
450 'key': 'SponsorBlock',
451 'categories': sponsorblock_query,
452 'api': opts.sponsorblock_api,
453 # Run this immediately after extraction is complete
454 'when': 'pre_process'
455 })
456 if opts.parse_metadata:
457 postprocessors.append({
458 'key': 'MetadataParser',
459 'actions': opts.parse_metadata,
460 # Run this immediately after extraction is complete
461 'when': 'pre_process'
462 })
463 if opts.convertsubtitles:
464 postprocessors.append({
465 'key': 'FFmpegSubtitlesConvertor',
466 'format': opts.convertsubtitles,
467 # Run this before the actual video download
468 'when': 'before_dl'
469 })
470 if opts.convertthumbnails:
471 postprocessors.append({
472 'key': 'FFmpegThumbnailsConvertor',
473 'format': opts.convertthumbnails,
474 # Run this before the actual video download
475 'when': 'before_dl'
476 })
477 # Must be after all other before_dl
478 if opts.exec_before_dl_cmd:
479 postprocessors.append({
480 'key': 'Exec',
481 'exec_cmd': opts.exec_before_dl_cmd,
482 'when': 'before_dl'
483 })
484 if opts.extractaudio:
485 postprocessors.append({
486 'key': 'FFmpegExtractAudio',
487 'preferredcodec': opts.audioformat,
488 'preferredquality': opts.audioquality,
489 'nopostoverwrites': opts.nopostoverwrites,
490 })
491 if opts.remuxvideo:
492 postprocessors.append({
493 'key': 'FFmpegVideoRemuxer',
494 'preferedformat': opts.remuxvideo,
495 })
496 if opts.recodevideo:
497 postprocessors.append({
498 'key': 'FFmpegVideoConvertor',
499 'preferedformat': opts.recodevideo,
500 })
501 # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
502 if opts.embedsubtitles:
503 already_have_subtitle = opts.writesubtitles and 'no-keep-subs' not in compat_opts
504 postprocessors.append({
505 'key': 'FFmpegEmbedSubtitle',
506 # already_have_subtitle = True prevents the file from being deleted after embedding
507 'already_have_subtitle': already_have_subtitle
508 })
509 if not opts.writeautomaticsub and 'no-keep-subs' not in compat_opts:
510 opts.writesubtitles = True
511 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
512 # this was the old behaviour if only --all-sub was given.
513 if opts.allsubtitles and not opts.writeautomaticsub:
514 opts.writesubtitles = True
515 # ModifyChapters must run before FFmpegMetadataPP
516 remove_chapters_patterns, remove_ranges = [], []
517 for regex in opts.remove_chapters:
518 if regex.startswith('*'):
519 dur = list(map(parse_duration, regex[1:].split('-')))
520 if len(dur) == 2 and all(t is not None for t in dur):
521 remove_ranges.append(tuple(dur))
522 continue
523 parser.error(f'invalid --remove-chapters time range {regex!r}. Must be of the form *start-end')
524 try:
525 remove_chapters_patterns.append(re.compile(regex))
526 except re.error as err:
527 parser.error(f'invalid --remove-chapters regex {regex!r} - {err}')
528 if opts.remove_chapters or sponsorblock_query:
529 postprocessors.append({
530 'key': 'ModifyChapters',
531 'remove_chapters_patterns': remove_chapters_patterns,
532 'remove_sponsor_segments': opts.sponsorblock_remove,
533 'remove_ranges': remove_ranges,
534 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
535 'force_keyframes': opts.force_keyframes_at_cuts
536 })
537 # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
538 # FFmpegExtractAudioPP as containers before conversion may not support
539 # metadata (3gp, webm, etc.)
540 # By default ffmpeg preserves metadata applicable for both
541 # source and target containers. From this point the container won't change,
542 # so metadata can be added here.
543 if opts.addmetadata or opts.addchapters or opts.embed_infojson:
544 if opts.embed_infojson is None:
545 opts.embed_infojson = 'if_exists'
546 postprocessors.append({
547 'key': 'FFmpegMetadata',
548 'add_chapters': opts.addchapters,
549 'add_metadata': opts.addmetadata,
550 'add_infojson': opts.embed_infojson,
551 })
552 # Deprecated
553 # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
554 # but must be below EmbedSubtitle and FFmpegMetadata
555 # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
556 # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
557 if opts.sponskrub is not False:
558 postprocessors.append({
559 'key': 'SponSkrub',
560 'path': opts.sponskrub_path,
561 'args': opts.sponskrub_args,
562 'cut': opts.sponskrub_cut,
563 'force': opts.sponskrub_force,
564 'ignoreerror': opts.sponskrub is None,
565 '_from_cli': True,
566 })
567 if opts.embedthumbnail:
568 postprocessors.append({
569 'key': 'EmbedThumbnail',
570 # already_have_thumbnail = True prevents the file from being deleted after embedding
571 'already_have_thumbnail': opts.writethumbnail
572 })
573 if not opts.writethumbnail:
574 opts.writethumbnail = True
575 opts.outtmpl['pl_thumbnail'] = ''
576 if opts.split_chapters:
577 postprocessors.append({
578 'key': 'FFmpegSplitChapters',
579 'force_keyframes': opts.force_keyframes_at_cuts,
580 })
581 # XAttrMetadataPP should be run after post-processors that may change file contents
582 if opts.xattrs:
583 postprocessors.append({'key': 'XAttrMetadata'})
584 # Exec must be the last PP
585 if opts.exec_cmd:
586 postprocessors.append({
587 'key': 'Exec',
588 'exec_cmd': opts.exec_cmd,
589 # Run this only after the files have been moved to their final locations
590 'when': 'after_move'
591 })
592
593 def report_args_compat(arg, name):
594 warnings.append('%s given without specifying name. The arguments will be given to all %s' % (arg, name))
595
596 if 'default' in opts.external_downloader_args:
597 report_args_compat('--downloader-args', 'external downloaders')
598
599 if 'default-compat' in opts.postprocessor_args and 'default' not in opts.postprocessor_args:
600 report_args_compat('--post-processor-args', 'post-processors')
601 opts.postprocessor_args.setdefault('sponskrub', [])
602 opts.postprocessor_args['default'] = opts.postprocessor_args['default-compat']
603
604 def report_deprecation(val, old, new=None):
605 if not val:
606 return
607 deprecation_warnings.append(
608 f'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
609 else f'{old} is deprecated and may not work as expected')
610
611 report_deprecation(opts.sponskrub, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
612 report_deprecation(not opts.prefer_ffmpeg, '--prefer-avconv', 'ffmpeg')
613 report_deprecation(opts.include_ads, '--include-ads')
614 # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
615 # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
616
617 final_ext = (
618 opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
619 else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
620 else opts.audioformat if (opts.extractaudio and opts.audioformat != 'best')
621 else None)
622
623 match_filter = (
624 None if opts.match_filter is None
625 else match_filter_func(opts.match_filter))
626
627 ydl_opts = {
628 'usenetrc': opts.usenetrc,
629 'netrc_location': opts.netrc_location,
630 'username': opts.username,
631 'password': opts.password,
632 'twofactor': opts.twofactor,
633 'videopassword': opts.videopassword,
634 'ap_mso': opts.ap_mso,
635 'ap_username': opts.ap_username,
636 'ap_password': opts.ap_password,
637 'quiet': (opts.quiet or any_getting or any_printing),
638 'no_warnings': opts.no_warnings,
639 'forceurl': opts.geturl,
640 'forcetitle': opts.gettitle,
641 'forceid': opts.getid,
642 'forcethumbnail': opts.getthumbnail,
643 'forcedescription': opts.getdescription,
644 'forceduration': opts.getduration,
645 'forcefilename': opts.getfilename,
646 'forceformat': opts.getformat,
647 'forceprint': opts.forceprint,
648 'forcejson': opts.dumpjson or opts.print_json,
649 'dump_single_json': opts.dump_single_json,
650 'force_write_download_archive': opts.force_write_download_archive,
651 'simulate': (any_getting or None) if opts.simulate is None else opts.simulate,
652 'skip_download': opts.skip_download,
653 'format': opts.format,
654 'allow_unplayable_formats': opts.allow_unplayable_formats,
655 'ignore_no_formats_error': opts.ignore_no_formats_error,
656 'format_sort': opts.format_sort,
657 'format_sort_force': opts.format_sort_force,
658 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
659 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
660 'check_formats': opts.check_formats,
661 'listformats': opts.listformats,
662 'listformats_table': opts.listformats_table,
663 'outtmpl': opts.outtmpl,
664 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
665 'paths': opts.paths,
666 'autonumber_size': opts.autonumber_size,
667 'autonumber_start': opts.autonumber_start,
668 'restrictfilenames': opts.restrictfilenames,
669 'windowsfilenames': opts.windowsfilenames,
670 'ignoreerrors': opts.ignoreerrors,
671 'force_generic_extractor': opts.force_generic_extractor,
672 'ratelimit': opts.ratelimit,
673 'throttledratelimit': opts.throttledratelimit,
674 'overwrites': opts.overwrites,
675 'retries': opts.retries,
676 'fragment_retries': opts.fragment_retries,
677 'extractor_retries': opts.extractor_retries,
678 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
679 'keep_fragments': opts.keep_fragments,
680 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
681 'buffersize': opts.buffersize,
682 'noresizebuffer': opts.noresizebuffer,
683 'http_chunk_size': opts.http_chunk_size,
684 'continuedl': opts.continue_dl,
685 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
686 'progress_with_newline': opts.progress_with_newline,
687 'progress_template': opts.progress_template,
688 'playliststart': opts.playliststart,
689 'playlistend': opts.playlistend,
690 'playlistreverse': opts.playlist_reverse,
691 'playlistrandom': opts.playlist_random,
692 'noplaylist': opts.noplaylist,
693 'logtostderr': outtmpl_default == '-',
694 'consoletitle': opts.consoletitle,
695 'nopart': opts.nopart,
696 'updatetime': opts.updatetime,
697 'writedescription': opts.writedescription,
698 'writeannotations': opts.writeannotations,
699 'writeinfojson': opts.writeinfojson,
700 'allow_playlist_files': opts.allow_playlist_files,
701 'clean_infojson': opts.clean_infojson,
702 'getcomments': opts.getcomments,
703 'writethumbnail': opts.writethumbnail is True,
704 'write_all_thumbnails': opts.writethumbnail == 'all',
705 'writelink': opts.writelink,
706 'writeurllink': opts.writeurllink,
707 'writewebloclink': opts.writewebloclink,
708 'writedesktoplink': opts.writedesktoplink,
709 'writesubtitles': opts.writesubtitles,
710 'writeautomaticsub': opts.writeautomaticsub,
711 'allsubtitles': opts.allsubtitles,
712 'listsubtitles': opts.listsubtitles,
713 'subtitlesformat': opts.subtitlesformat,
714 'subtitleslangs': opts.subtitleslangs,
715 'matchtitle': decodeOption(opts.matchtitle),
716 'rejecttitle': decodeOption(opts.rejecttitle),
717 'max_downloads': opts.max_downloads,
718 'prefer_free_formats': opts.prefer_free_formats,
719 'trim_file_name': opts.trim_file_name,
720 'verbose': opts.verbose,
721 'dump_intermediate_pages': opts.dump_intermediate_pages,
722 'write_pages': opts.write_pages,
723 'test': opts.test,
724 'keepvideo': opts.keepvideo,
725 'min_filesize': opts.min_filesize,
726 'max_filesize': opts.max_filesize,
727 'min_views': opts.min_views,
728 'max_views': opts.max_views,
729 'daterange': date,
730 'cachedir': opts.cachedir,
731 'youtube_print_sig_code': opts.youtube_print_sig_code,
732 'age_limit': opts.age_limit,
733 'download_archive': download_archive_fn,
734 'break_on_existing': opts.break_on_existing,
735 'break_on_reject': opts.break_on_reject,
736 'break_per_url': opts.break_per_url,
737 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
738 'cookiefile': opts.cookiefile,
739 'cookiesfrombrowser': opts.cookiesfrombrowser,
740 'nocheckcertificate': opts.no_check_certificate,
741 'prefer_insecure': opts.prefer_insecure,
742 'proxy': opts.proxy,
743 'socket_timeout': opts.socket_timeout,
744 'bidi_workaround': opts.bidi_workaround,
745 'debug_printtraffic': opts.debug_printtraffic,
746 'prefer_ffmpeg': opts.prefer_ffmpeg,
747 'include_ads': opts.include_ads,
748 'default_search': opts.default_search,
749 'dynamic_mpd': opts.dynamic_mpd,
750 'extractor_args': opts.extractor_args,
751 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
752 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
753 'encoding': opts.encoding,
754 'extract_flat': opts.extract_flat,
755 'live_from_start': opts.live_from_start,
756 'wait_for_video': opts.wait_for_video,
757 'mark_watched': opts.mark_watched,
758 'merge_output_format': opts.merge_output_format,
759 'final_ext': final_ext,
760 'postprocessors': postprocessors,
761 'fixup': opts.fixup,
762 'source_address': opts.source_address,
763 'call_home': opts.call_home,
764 'sleep_interval_requests': opts.sleep_interval_requests,
765 'sleep_interval': opts.sleep_interval,
766 'max_sleep_interval': opts.max_sleep_interval,
767 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
768 'external_downloader': opts.external_downloader,
769 'list_thumbnails': opts.list_thumbnails,
770 'playlist_items': opts.playlist_items,
771 'xattr_set_filesize': opts.xattr_set_filesize,
772 'match_filter': match_filter,
773 'no_color': opts.no_color,
774 'ffmpeg_location': opts.ffmpeg_location,
775 'hls_prefer_native': opts.hls_prefer_native,
776 'hls_use_mpegts': opts.hls_use_mpegts,
777 'hls_split_discontinuity': opts.hls_split_discontinuity,
778 'external_downloader_args': opts.external_downloader_args,
779 'postprocessor_args': opts.postprocessor_args,
780 'cn_verification_proxy': opts.cn_verification_proxy,
781 'geo_verification_proxy': opts.geo_verification_proxy,
782 'geo_bypass': opts.geo_bypass,
783 'geo_bypass_country': opts.geo_bypass_country,
784 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
785 '_warnings': warnings,
786 '_deprecation_warnings': deprecation_warnings,
787 'compat_opts': compat_opts,
788 }
789
790 with YoutubeDL(ydl_opts) as ydl:
791 actual_use = all_urls or opts.load_info_filename
792
793 # Remove cache dir
794 if opts.rm_cachedir:
795 ydl.cache.remove()
796
797 # Update version
798 if opts.update_self:
799 # If updater returns True, exit. Required for windows
800 if run_update(ydl):
801 if actual_use:
802 sys.exit('ERROR: The program must exit for the update to complete')
803 sys.exit()
804
805 # Maybe do nothing
806 if not actual_use:
807 if opts.update_self or opts.rm_cachedir:
808 sys.exit()
809
810 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
811 parser.error(
812 'You must provide at least one URL.\n'
813 'Type yt-dlp --help to see a list of all options.')
814
815 try:
816 if opts.load_info_filename is not None:
817 retcode = ydl.download_with_info_file(expand_path(opts.load_info_filename))
818 else:
819 retcode = ydl.download(all_urls)
820 except DownloadCancelled:
821 ydl.to_screen('Aborting remaining downloads')
822 retcode = 101
823
824 sys.exit(retcode)
825
826
827 def main(argv=None):
828 try:
829 _real_main(argv)
830 except DownloadError:
831 sys.exit(1)
832 except SameFileError as e:
833 sys.exit(f'ERROR: {e}')
834 except KeyboardInterrupt:
835 sys.exit('\nERROR: Interrupted by user')
836 except BrokenPipeError as e:
837 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
838 devnull = os.open(os.devnull, os.O_WRONLY)
839 os.dup2(devnull, sys.stdout.fileno())
840 sys.exit(f'\nERROR: {e}')
841
842
843 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']