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