]> jfr.im git - yt-dlp.git/blob - yt_dlp/__init__.py
Add `--print playlist:` to print fields per playlist
[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, SUPPORTED_KEYRINGS
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.file_access_retries is not None:
226 opts.file_access_retries = parse_retries(opts.file_access_retries, 'file access ')
227 if opts.fragment_retries is not None:
228 opts.fragment_retries = parse_retries(opts.fragment_retries, 'fragment ')
229 if opts.extractor_retries is not None:
230 opts.extractor_retries = parse_retries(opts.extractor_retries, 'extractor ')
231 if opts.buffersize is not None:
232 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
233 if numeric_buffersize is None:
234 parser.error('invalid buffer size specified')
235 opts.buffersize = numeric_buffersize
236 if opts.http_chunk_size is not None:
237 numeric_chunksize = FileDownloader.parse_bytes(opts.http_chunk_size)
238 if not numeric_chunksize:
239 parser.error('invalid http chunk size specified')
240 opts.http_chunk_size = numeric_chunksize
241 if opts.playliststart <= 0:
242 raise parser.error('Playlist start must be positive')
243 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
244 raise parser.error('Playlist end must be greater than playlist start')
245 if opts.extractaudio:
246 opts.audioformat = opts.audioformat.lower()
247 if opts.audioformat not in ['best'] + list(FFmpegExtractAudioPP.SUPPORTED_EXTS):
248 parser.error('invalid audio format specified')
249 if opts.audioquality:
250 opts.audioquality = opts.audioquality.strip('k').strip('K')
251 audioquality = int_or_none(float_or_none(opts.audioquality)) # int_or_none prevents inf, nan
252 if audioquality is None or audioquality < 0:
253 parser.error('invalid audio quality specified')
254 if opts.recodevideo is not None:
255 opts.recodevideo = opts.recodevideo.replace(' ', '')
256 if not re.match(FFmpegVideoConvertorPP.FORMAT_RE, opts.recodevideo):
257 parser.error('invalid video remux format specified')
258 if opts.remuxvideo is not None:
259 opts.remuxvideo = opts.remuxvideo.replace(' ', '')
260 if not re.match(FFmpegVideoRemuxerPP.FORMAT_RE, opts.remuxvideo):
261 parser.error('invalid video remux format specified')
262 if opts.convertsubtitles is not None:
263 if opts.convertsubtitles not in FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS:
264 parser.error('invalid subtitle format specified')
265 if opts.convertthumbnails is not None:
266 if opts.convertthumbnails not in FFmpegThumbnailsConvertorPP.SUPPORTED_EXTS:
267 parser.error('invalid thumbnail format specified')
268 if opts.cookiesfrombrowser is not None:
269 mobj = re.match(r'(?P<name>[^+:]+)(\s*\+\s*(?P<keyring>[^:]+))?(\s*:(?P<profile>.+))?', opts.cookiesfrombrowser)
270 if mobj is None:
271 parser.error(f'invalid cookies from browser arguments: {opts.cookiesfrombrowser}')
272 browser_name, keyring, profile = mobj.group('name', 'keyring', 'profile')
273 browser_name = browser_name.lower()
274 if browser_name not in SUPPORTED_BROWSERS:
275 parser.error(f'unsupported browser specified for cookies: "{browser_name}". '
276 f'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}')
277 if keyring is not None:
278 keyring = keyring.upper()
279 if keyring not in SUPPORTED_KEYRINGS:
280 parser.error(f'unsupported keyring specified for cookies: "{keyring}". '
281 f'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}')
282 opts.cookiesfrombrowser = (browser_name, profile, keyring)
283 geo_bypass_code = opts.geo_bypass_ip_block or opts.geo_bypass_country
284 if geo_bypass_code is not None:
285 try:
286 GeoUtils.random_ipv4(geo_bypass_code)
287 except Exception:
288 parser.error('unsupported geo-bypass country or ip-block')
289
290 if opts.date is not None:
291 date = DateRange.day(opts.date)
292 else:
293 date = DateRange(opts.dateafter, opts.datebefore)
294
295 compat_opts = opts.compat_opts
296
297 def report_conflict(arg1, arg2):
298 warnings.append(f'{arg2} is ignored since {arg1} was given')
299
300 def _unused_compat_opt(name):
301 if name not in compat_opts:
302 return False
303 compat_opts.discard(name)
304 compat_opts.update(['*%s' % name])
305 return True
306
307 def set_default_compat(compat_name, opt_name, default=True, remove_compat=True):
308 attr = getattr(opts, opt_name)
309 if compat_name in compat_opts:
310 if attr is None:
311 setattr(opts, opt_name, not default)
312 return True
313 else:
314 if remove_compat:
315 _unused_compat_opt(compat_name)
316 return False
317 elif attr is None:
318 setattr(opts, opt_name, default)
319 return None
320
321 set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
322 set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
323 set_default_compat('no-clean-infojson', 'clean_infojson')
324 if 'no-attach-info-json' in compat_opts:
325 if opts.embed_infojson:
326 _unused_compat_opt('no-attach-info-json')
327 else:
328 opts.embed_infojson = False
329 if 'format-sort' in compat_opts:
330 opts.format_sort.extend(InfoExtractor.FormatSort.ytdl_default)
331 _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False)
332 _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False)
333 if _video_multistreams_set is False and _audio_multistreams_set is False:
334 _unused_compat_opt('multistreams')
335 outtmpl_default = opts.outtmpl.get('default')
336 if opts.useid:
337 if outtmpl_default is None:
338 outtmpl_default = opts.outtmpl['default'] = '%(id)s.%(ext)s'
339 else:
340 report_conflict('--output', '--id')
341 if 'filename' in compat_opts:
342 if outtmpl_default is None:
343 outtmpl_default = opts.outtmpl['default'] = '%(title)s-%(id)s.%(ext)s'
344 else:
345 _unused_compat_opt('filename')
346
347 def validate_outtmpl(tmpl, msg):
348 err = YoutubeDL.validate_outtmpl(tmpl)
349 if err:
350 parser.error('invalid %s %r: %s' % (msg, tmpl, error_to_compat_str(err)))
351
352 for k, tmpl in opts.outtmpl.items():
353 validate_outtmpl(tmpl, f'{k} output template')
354 for type_, tmpl_list in opts.forceprint.items():
355 for tmpl in tmpl_list:
356 validate_outtmpl(tmpl, f'{type_} print template')
357 validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
358 for k, tmpl in opts.progress_template.items():
359 k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
360 validate_outtmpl(tmpl, f'{k} template')
361
362 if opts.extractaudio and not opts.keepvideo and opts.format is None:
363 opts.format = 'bestaudio/best'
364
365 if outtmpl_default is not None and not os.path.splitext(outtmpl_default)[1] and opts.extractaudio:
366 parser.error('Cannot download a video and extract audio into the same'
367 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
368 ' template'.format(outtmpl_default))
369
370 for f in opts.format_sort:
371 if re.match(InfoExtractor.FormatSort.regex, f) is None:
372 parser.error('invalid format sort string "%s" specified' % f)
373
374 def metadataparser_actions(f):
375 if isinstance(f, str):
376 cmd = '--parse-metadata %s' % compat_shlex_quote(f)
377 try:
378 actions = [MetadataFromFieldPP.to_action(f)]
379 except Exception as err:
380 parser.error(f'{cmd} is invalid; {err}')
381 else:
382 cmd = '--replace-in-metadata %s' % ' '.join(map(compat_shlex_quote, f))
383 actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
384
385 for action in actions:
386 try:
387 MetadataParserPP.validate_action(*action)
388 except Exception as err:
389 parser.error(f'{cmd} is invalid; {err}')
390 yield action
391
392 if opts.parse_metadata is None:
393 opts.parse_metadata = []
394 if opts.metafromtitle is not None:
395 opts.parse_metadata.append('title:%s' % opts.metafromtitle)
396 opts.parse_metadata = list(itertools.chain(*map(metadataparser_actions, opts.parse_metadata)))
397
398 any_getting = (any(opts.forceprint.values()) or opts.dumpjson or opts.dump_single_json
399 or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail
400 or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration)
401
402 any_printing = opts.print_json
403 download_archive_fn = expand_path(opts.download_archive) if opts.download_archive is not None else opts.download_archive
404
405 # If JSON is not printed anywhere, but comments are requested, save it to file
406 printing_json = opts.dumpjson or opts.print_json or opts.dump_single_json
407 if opts.getcomments and not printing_json:
408 opts.writeinfojson = True
409
410 if opts.no_sponsorblock:
411 opts.sponsorblock_mark = set()
412 opts.sponsorblock_remove = set()
413 sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
414
415 opts.remove_chapters = opts.remove_chapters or []
416
417 if (opts.remove_chapters or sponsorblock_query) and opts.sponskrub is not False:
418 if opts.sponskrub:
419 if opts.remove_chapters:
420 report_conflict('--remove-chapters', '--sponskrub')
421 if opts.sponsorblock_mark:
422 report_conflict('--sponsorblock-mark', '--sponskrub')
423 if opts.sponsorblock_remove:
424 report_conflict('--sponsorblock-remove', '--sponskrub')
425 opts.sponskrub = False
426 if opts.sponskrub_cut and opts.split_chapters and opts.sponskrub is not False:
427 report_conflict('--split-chapter', '--sponskrub-cut')
428 opts.sponskrub_cut = False
429
430 if opts.remuxvideo and opts.recodevideo:
431 report_conflict('--recode-video', '--remux-video')
432 opts.remuxvideo = False
433
434 if opts.allow_unplayable_formats:
435 def report_unplayable_conflict(opt_name, arg, default=False, allowed=None):
436 val = getattr(opts, opt_name)
437 if (not allowed and val) or (allowed and not allowed(val)):
438 report_conflict('--allow-unplayable-formats', arg)
439 setattr(opts, opt_name, default)
440
441 report_unplayable_conflict('extractaudio', '--extract-audio')
442 report_unplayable_conflict('remuxvideo', '--remux-video')
443 report_unplayable_conflict('recodevideo', '--recode-video')
444 report_unplayable_conflict('addmetadata', '--embed-metadata')
445 report_unplayable_conflict('addchapters', '--embed-chapters')
446 report_unplayable_conflict('embed_infojson', '--embed-info-json')
447 opts.embed_infojson = False
448 report_unplayable_conflict('embedsubtitles', '--embed-subs')
449 report_unplayable_conflict('embedthumbnail', '--embed-thumbnail')
450 report_unplayable_conflict('xattrs', '--xattrs')
451 report_unplayable_conflict('fixup', '--fixup', default='never', allowed=lambda x: x in (None, 'never', 'ignore'))
452 opts.fixup = 'never'
453 report_unplayable_conflict('remove_chapters', '--remove-chapters', default=[])
454 report_unplayable_conflict('sponsorblock_remove', '--sponsorblock-remove', default=set())
455 report_unplayable_conflict('sponskrub', '--sponskrub', default=set())
456 opts.sponskrub = False
457
458 if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
459 opts.addchapters = True
460
461 # PostProcessors
462 postprocessors = list(opts.add_postprocessors)
463 if sponsorblock_query:
464 postprocessors.append({
465 'key': 'SponsorBlock',
466 'categories': sponsorblock_query,
467 'api': opts.sponsorblock_api,
468 # Run this immediately after extraction is complete
469 'when': 'pre_process'
470 })
471 if opts.parse_metadata:
472 postprocessors.append({
473 'key': 'MetadataParser',
474 'actions': opts.parse_metadata,
475 # Run this immediately after extraction is complete
476 'when': 'pre_process'
477 })
478 if opts.convertsubtitles:
479 postprocessors.append({
480 'key': 'FFmpegSubtitlesConvertor',
481 'format': opts.convertsubtitles,
482 # Run this before the actual video download
483 'when': 'before_dl'
484 })
485 if opts.convertthumbnails:
486 postprocessors.append({
487 'key': 'FFmpegThumbnailsConvertor',
488 'format': opts.convertthumbnails,
489 # Run this before the actual video download
490 'when': 'before_dl'
491 })
492 # Must be after all other before_dl
493 if opts.exec_before_dl_cmd:
494 postprocessors.append({
495 'key': 'Exec',
496 'exec_cmd': opts.exec_before_dl_cmd,
497 'when': 'before_dl'
498 })
499 if opts.extractaudio:
500 postprocessors.append({
501 'key': 'FFmpegExtractAudio',
502 'preferredcodec': opts.audioformat,
503 'preferredquality': opts.audioquality,
504 'nopostoverwrites': opts.nopostoverwrites,
505 })
506 if opts.remuxvideo:
507 postprocessors.append({
508 'key': 'FFmpegVideoRemuxer',
509 'preferedformat': opts.remuxvideo,
510 })
511 if opts.recodevideo:
512 postprocessors.append({
513 'key': 'FFmpegVideoConvertor',
514 'preferedformat': opts.recodevideo,
515 })
516 # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
517 if opts.embedsubtitles:
518 already_have_subtitle = opts.writesubtitles and 'no-keep-subs' not in compat_opts
519 postprocessors.append({
520 'key': 'FFmpegEmbedSubtitle',
521 # already_have_subtitle = True prevents the file from being deleted after embedding
522 'already_have_subtitle': already_have_subtitle
523 })
524 if not opts.writeautomaticsub and 'no-keep-subs' not in compat_opts:
525 opts.writesubtitles = True
526 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
527 # this was the old behaviour if only --all-sub was given.
528 if opts.allsubtitles and not opts.writeautomaticsub:
529 opts.writesubtitles = True
530 # ModifyChapters must run before FFmpegMetadataPP
531 remove_chapters_patterns, remove_ranges = [], []
532 for regex in opts.remove_chapters:
533 if regex.startswith('*'):
534 dur = list(map(parse_duration, regex[1:].split('-')))
535 if len(dur) == 2 and all(t is not None for t in dur):
536 remove_ranges.append(tuple(dur))
537 continue
538 parser.error(f'invalid --remove-chapters time range {regex!r}. Must be of the form *start-end')
539 try:
540 remove_chapters_patterns.append(re.compile(regex))
541 except re.error as err:
542 parser.error(f'invalid --remove-chapters regex {regex!r} - {err}')
543 if opts.remove_chapters or sponsorblock_query:
544 postprocessors.append({
545 'key': 'ModifyChapters',
546 'remove_chapters_patterns': remove_chapters_patterns,
547 'remove_sponsor_segments': opts.sponsorblock_remove,
548 'remove_ranges': remove_ranges,
549 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
550 'force_keyframes': opts.force_keyframes_at_cuts
551 })
552 # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
553 # FFmpegExtractAudioPP as containers before conversion may not support
554 # metadata (3gp, webm, etc.)
555 # By default ffmpeg preserves metadata applicable for both
556 # source and target containers. From this point the container won't change,
557 # so metadata can be added here.
558 if opts.addmetadata or opts.addchapters or opts.embed_infojson:
559 if opts.embed_infojson is None:
560 opts.embed_infojson = 'if_exists'
561 postprocessors.append({
562 'key': 'FFmpegMetadata',
563 'add_chapters': opts.addchapters,
564 'add_metadata': opts.addmetadata,
565 'add_infojson': opts.embed_infojson,
566 })
567 # Deprecated
568 # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
569 # but must be below EmbedSubtitle and FFmpegMetadata
570 # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
571 # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
572 if opts.sponskrub is not False:
573 postprocessors.append({
574 'key': 'SponSkrub',
575 'path': opts.sponskrub_path,
576 'args': opts.sponskrub_args,
577 'cut': opts.sponskrub_cut,
578 'force': opts.sponskrub_force,
579 'ignoreerror': opts.sponskrub is None,
580 '_from_cli': True,
581 })
582 if opts.embedthumbnail:
583 postprocessors.append({
584 'key': 'EmbedThumbnail',
585 # already_have_thumbnail = True prevents the file from being deleted after embedding
586 'already_have_thumbnail': opts.writethumbnail
587 })
588 if not opts.writethumbnail:
589 opts.writethumbnail = True
590 opts.outtmpl['pl_thumbnail'] = ''
591 if opts.split_chapters:
592 postprocessors.append({
593 'key': 'FFmpegSplitChapters',
594 'force_keyframes': opts.force_keyframes_at_cuts,
595 })
596 # XAttrMetadataPP should be run after post-processors that may change file contents
597 if opts.xattrs:
598 postprocessors.append({'key': 'XAttrMetadata'})
599 # Exec must be the last PP
600 if opts.exec_cmd:
601 postprocessors.append({
602 'key': 'Exec',
603 'exec_cmd': opts.exec_cmd,
604 # Run this only after the files have been moved to their final locations
605 'when': 'after_move'
606 })
607
608 def report_args_compat(arg, name):
609 warnings.append('%s given without specifying name. The arguments will be given to all %s' % (arg, name))
610
611 if 'default' in opts.external_downloader_args:
612 report_args_compat('--downloader-args', 'external downloaders')
613
614 if 'default-compat' in opts.postprocessor_args and 'default' not in opts.postprocessor_args:
615 report_args_compat('--post-processor-args', 'post-processors')
616 opts.postprocessor_args.setdefault('sponskrub', [])
617 opts.postprocessor_args['default'] = opts.postprocessor_args['default-compat']
618
619 def report_deprecation(val, old, new=None):
620 if not val:
621 return
622 deprecation_warnings.append(
623 f'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
624 else f'{old} is deprecated and may not work as expected')
625
626 report_deprecation(opts.sponskrub, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
627 report_deprecation(not opts.prefer_ffmpeg, '--prefer-avconv', 'ffmpeg')
628 report_deprecation(opts.include_ads, '--include-ads')
629 # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
630 # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
631
632 final_ext = (
633 opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
634 else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
635 else opts.audioformat if (opts.extractaudio and opts.audioformat != 'best')
636 else None)
637
638 match_filter = (
639 None if opts.match_filter is None
640 else match_filter_func(opts.match_filter))
641
642 ydl_opts = {
643 'usenetrc': opts.usenetrc,
644 'netrc_location': opts.netrc_location,
645 'username': opts.username,
646 'password': opts.password,
647 'twofactor': opts.twofactor,
648 'videopassword': opts.videopassword,
649 'ap_mso': opts.ap_mso,
650 'ap_username': opts.ap_username,
651 'ap_password': opts.ap_password,
652 'quiet': (opts.quiet or any_getting or any_printing),
653 'no_warnings': opts.no_warnings,
654 'forceurl': opts.geturl,
655 'forcetitle': opts.gettitle,
656 'forceid': opts.getid,
657 'forcethumbnail': opts.getthumbnail,
658 'forcedescription': opts.getdescription,
659 'forceduration': opts.getduration,
660 'forcefilename': opts.getfilename,
661 'forceformat': opts.getformat,
662 'forceprint': opts.forceprint,
663 'forcejson': opts.dumpjson or opts.print_json,
664 'dump_single_json': opts.dump_single_json,
665 'force_write_download_archive': opts.force_write_download_archive,
666 'simulate': (any_getting or None) if opts.simulate is None else opts.simulate,
667 'skip_download': opts.skip_download,
668 'format': opts.format,
669 'allow_unplayable_formats': opts.allow_unplayable_formats,
670 'ignore_no_formats_error': opts.ignore_no_formats_error,
671 'format_sort': opts.format_sort,
672 'format_sort_force': opts.format_sort_force,
673 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
674 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
675 'check_formats': opts.check_formats,
676 'listformats': opts.listformats,
677 'listformats_table': opts.listformats_table,
678 'outtmpl': opts.outtmpl,
679 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
680 'paths': opts.paths,
681 'autonumber_size': opts.autonumber_size,
682 'autonumber_start': opts.autonumber_start,
683 'restrictfilenames': opts.restrictfilenames,
684 'windowsfilenames': opts.windowsfilenames,
685 'ignoreerrors': opts.ignoreerrors,
686 'force_generic_extractor': opts.force_generic_extractor,
687 'ratelimit': opts.ratelimit,
688 'throttledratelimit': opts.throttledratelimit,
689 'overwrites': opts.overwrites,
690 'retries': opts.retries,
691 'file_access_retries': opts.file_access_retries,
692 'fragment_retries': opts.fragment_retries,
693 'extractor_retries': opts.extractor_retries,
694 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
695 'keep_fragments': opts.keep_fragments,
696 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
697 'buffersize': opts.buffersize,
698 'noresizebuffer': opts.noresizebuffer,
699 'http_chunk_size': opts.http_chunk_size,
700 'continuedl': opts.continue_dl,
701 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
702 'progress_with_newline': opts.progress_with_newline,
703 'progress_template': opts.progress_template,
704 'playliststart': opts.playliststart,
705 'playlistend': opts.playlistend,
706 'playlistreverse': opts.playlist_reverse,
707 'playlistrandom': opts.playlist_random,
708 'noplaylist': opts.noplaylist,
709 'logtostderr': outtmpl_default == '-',
710 'consoletitle': opts.consoletitle,
711 'nopart': opts.nopart,
712 'updatetime': opts.updatetime,
713 'writedescription': opts.writedescription,
714 'writeannotations': opts.writeannotations,
715 'writeinfojson': opts.writeinfojson,
716 'allow_playlist_files': opts.allow_playlist_files,
717 'clean_infojson': opts.clean_infojson,
718 'getcomments': opts.getcomments,
719 'writethumbnail': opts.writethumbnail is True,
720 'write_all_thumbnails': opts.writethumbnail == 'all',
721 'writelink': opts.writelink,
722 'writeurllink': opts.writeurllink,
723 'writewebloclink': opts.writewebloclink,
724 'writedesktoplink': opts.writedesktoplink,
725 'writesubtitles': opts.writesubtitles,
726 'writeautomaticsub': opts.writeautomaticsub,
727 'allsubtitles': opts.allsubtitles,
728 'listsubtitles': opts.listsubtitles,
729 'subtitlesformat': opts.subtitlesformat,
730 'subtitleslangs': opts.subtitleslangs,
731 'matchtitle': decodeOption(opts.matchtitle),
732 'rejecttitle': decodeOption(opts.rejecttitle),
733 'max_downloads': opts.max_downloads,
734 'prefer_free_formats': opts.prefer_free_formats,
735 'trim_file_name': opts.trim_file_name,
736 'verbose': opts.verbose,
737 'dump_intermediate_pages': opts.dump_intermediate_pages,
738 'write_pages': opts.write_pages,
739 'test': opts.test,
740 'keepvideo': opts.keepvideo,
741 'min_filesize': opts.min_filesize,
742 'max_filesize': opts.max_filesize,
743 'min_views': opts.min_views,
744 'max_views': opts.max_views,
745 'daterange': date,
746 'cachedir': opts.cachedir,
747 'youtube_print_sig_code': opts.youtube_print_sig_code,
748 'age_limit': opts.age_limit,
749 'download_archive': download_archive_fn,
750 'break_on_existing': opts.break_on_existing,
751 'break_on_reject': opts.break_on_reject,
752 'break_per_url': opts.break_per_url,
753 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
754 'cookiefile': opts.cookiefile,
755 'cookiesfrombrowser': opts.cookiesfrombrowser,
756 'nocheckcertificate': opts.no_check_certificate,
757 'prefer_insecure': opts.prefer_insecure,
758 'proxy': opts.proxy,
759 'socket_timeout': opts.socket_timeout,
760 'bidi_workaround': opts.bidi_workaround,
761 'debug_printtraffic': opts.debug_printtraffic,
762 'prefer_ffmpeg': opts.prefer_ffmpeg,
763 'include_ads': opts.include_ads,
764 'default_search': opts.default_search,
765 'dynamic_mpd': opts.dynamic_mpd,
766 'extractor_args': opts.extractor_args,
767 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
768 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
769 'encoding': opts.encoding,
770 'extract_flat': opts.extract_flat,
771 'live_from_start': opts.live_from_start,
772 'wait_for_video': opts.wait_for_video,
773 'mark_watched': opts.mark_watched,
774 'merge_output_format': opts.merge_output_format,
775 'final_ext': final_ext,
776 'postprocessors': postprocessors,
777 'fixup': opts.fixup,
778 'source_address': opts.source_address,
779 'call_home': opts.call_home,
780 'sleep_interval_requests': opts.sleep_interval_requests,
781 'sleep_interval': opts.sleep_interval,
782 'max_sleep_interval': opts.max_sleep_interval,
783 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
784 'external_downloader': opts.external_downloader,
785 'list_thumbnails': opts.list_thumbnails,
786 'playlist_items': opts.playlist_items,
787 'xattr_set_filesize': opts.xattr_set_filesize,
788 'match_filter': match_filter,
789 'no_color': opts.no_color,
790 'ffmpeg_location': opts.ffmpeg_location,
791 'hls_prefer_native': opts.hls_prefer_native,
792 'hls_use_mpegts': opts.hls_use_mpegts,
793 'hls_split_discontinuity': opts.hls_split_discontinuity,
794 'external_downloader_args': opts.external_downloader_args,
795 'postprocessor_args': opts.postprocessor_args,
796 'cn_verification_proxy': opts.cn_verification_proxy,
797 'geo_verification_proxy': opts.geo_verification_proxy,
798 'geo_bypass': opts.geo_bypass,
799 'geo_bypass_country': opts.geo_bypass_country,
800 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
801 '_warnings': warnings,
802 '_deprecation_warnings': deprecation_warnings,
803 'compat_opts': compat_opts,
804 }
805
806 with YoutubeDL(ydl_opts) as ydl:
807 actual_use = all_urls or opts.load_info_filename
808
809 # Remove cache dir
810 if opts.rm_cachedir:
811 ydl.cache.remove()
812
813 # Update version
814 if opts.update_self:
815 # If updater returns True, exit. Required for windows
816 if run_update(ydl):
817 if actual_use:
818 sys.exit('ERROR: The program must exit for the update to complete')
819 sys.exit()
820
821 # Maybe do nothing
822 if not actual_use:
823 if opts.update_self or opts.rm_cachedir:
824 sys.exit()
825
826 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
827 parser.error(
828 'You must provide at least one URL.\n'
829 'Type yt-dlp --help to see a list of all options.')
830
831 try:
832 if opts.load_info_filename is not None:
833 retcode = ydl.download_with_info_file(expand_path(opts.load_info_filename))
834 else:
835 retcode = ydl.download(all_urls)
836 except DownloadCancelled:
837 ydl.to_screen('Aborting remaining downloads')
838 retcode = 101
839
840 sys.exit(retcode)
841
842
843 def main(argv=None):
844 try:
845 _real_main(argv)
846 except DownloadError:
847 sys.exit(1)
848 except SameFileError as e:
849 sys.exit(f'ERROR: {e}')
850 except KeyboardInterrupt:
851 sys.exit('\nERROR: Interrupted by user')
852 except BrokenPipeError as e:
853 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
854 devnull = os.open(os.devnull, os.O_WRONLY)
855 os.dup2(devnull, sys.stdout.fileno())
856 sys.exit(f'\nERROR: {e}')
857
858
859 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']