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