4 f
'You are using an unsupported version of Python. Only Python versions 3.6 and above are supported by yt-dlp' # noqa: F541
6 __license__
= 'Public Domain'
16 from .options
import (
23 workaround_optparse_bug9161
,
25 from .cookies
import SUPPORTED_BROWSERS
, SUPPORTED_KEYRINGS
46 from .update
import run_update
47 from .downloader
import (
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 (
55 FFmpegSubtitlesConvertorPP
,
56 FFmpegThumbnailsConvertorPP
,
57 FFmpegVideoConvertorPP
,
62 from .YoutubeDL
import YoutubeDL
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)
71 workaround_optparse_bug9161()
73 setproctitle('yt-dlp')
75 parser
, opts
, args
= parseOpts(argv
)
76 warnings
, deprecation_warnings
= [], []
79 if opts
.user_agent
is not None:
80 std_headers
['User-Agent'] = opts
.user_agent
83 if opts
.referer
is not None:
84 std_headers
['Referer'] = opts
.referer
87 std_headers
.update(opts
.headers
)
90 if opts
.dump_user_agent
:
91 write_string(std_headers
['User-Agent'] + '\n', out
=sys
.stdout
)
94 # Batch file verification
96 if opts
.batchfile
is not None:
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'))
104 expand_path(opts
.batchfile
),
105 'r', encoding
='utf-8', errors
='ignore')
106 batch_urls
= read_batch_urls(batchfd
)
108 write_string('[debug] Batch file urls: ' + repr(batch_urls
) + '\n')
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
]
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
)
122 if opts
.list_extractor_descriptions
:
123 for ie
in list_extractors(opts
.age_limit
):
126 desc
= getattr(ie
, 'IE_DESC', ie
.IE_NAME
)
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
)
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
)
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
.exec_cmd
.get('before_dl') and opts
.exec_before_dl_cmd
:
147 parser
.error('using "--exec-before-download" conflicts with "--exec before_dl:"')
148 if opts
.usenetrc
and (opts
.username
is not None or opts
.password
is not None):
149 parser
.error('using .netrc conflicts with giving username/password')
150 if opts
.password
is not None and opts
.username
is None:
151 parser
.error('account username missing\n')
152 if opts
.ap_password
is not None and opts
.ap_username
is None:
153 parser
.error('TV Provider account username missing\n')
154 if opts
.autonumber_size
is not None:
155 if opts
.autonumber_size
<= 0:
156 parser
.error('auto number size must be positive')
157 if opts
.autonumber_start
is not None:
158 if opts
.autonumber_start
< 0:
159 parser
.error('auto number start must be positive or 0')
160 if opts
.username
is not None and opts
.password
is None:
161 opts
.password
= compat_getpass('Type account password and press [Return]: ')
162 if opts
.ap_username
is not None and opts
.ap_password
is None:
163 opts
.ap_password
= compat_getpass('Type TV provider account password and press [Return]: ')
164 if opts
.ratelimit
is not None:
165 numeric_limit
= FileDownloader
.parse_bytes(opts
.ratelimit
)
166 if numeric_limit
is None:
167 parser
.error('invalid rate limit specified')
168 opts
.ratelimit
= numeric_limit
169 if opts
.throttledratelimit
is not None:
170 numeric_limit
= FileDownloader
.parse_bytes(opts
.throttledratelimit
)
171 if numeric_limit
is None:
172 parser
.error('invalid rate limit specified')
173 opts
.throttledratelimit
= numeric_limit
174 if opts
.min_filesize
is not None:
175 numeric_limit
= FileDownloader
.parse_bytes(opts
.min_filesize
)
176 if numeric_limit
is None:
177 parser
.error('invalid min_filesize specified')
178 opts
.min_filesize
= numeric_limit
179 if opts
.max_filesize
is not None:
180 numeric_limit
= FileDownloader
.parse_bytes(opts
.max_filesize
)
181 if numeric_limit
is None:
182 parser
.error('invalid max_filesize specified')
183 opts
.max_filesize
= numeric_limit
184 if opts
.sleep_interval
is not None:
185 if opts
.sleep_interval
< 0:
186 parser
.error('sleep interval must be positive or 0')
187 if opts
.max_sleep_interval
is not None:
188 if opts
.max_sleep_interval
< 0:
189 parser
.error('max sleep interval must be positive or 0')
190 if opts
.sleep_interval
is None:
191 parser
.error('min sleep interval must be specified, use --min-sleep-interval')
192 if opts
.max_sleep_interval
< opts
.sleep_interval
:
193 parser
.error('max sleep interval must be greater than or equal to min sleep interval')
195 opts
.max_sleep_interval
= opts
.sleep_interval
196 if opts
.sleep_interval_subtitles
is not None:
197 if opts
.sleep_interval_subtitles
< 0:
198 parser
.error('subtitles sleep interval must be positive or 0')
199 if opts
.sleep_interval_requests
is not None:
200 if opts
.sleep_interval_requests
< 0:
201 parser
.error('requests sleep interval must be positive or 0')
202 if opts
.ap_mso
and opts
.ap_mso
not in MSO_INFO
:
203 parser
.error('Unsupported TV Provider, use --ap-list-mso to get a list of supported TV Providers')
204 if opts
.overwrites
: # --yes-overwrites implies --no-continue
205 opts
.continue_dl
= False
206 if opts
.concurrent_fragment_downloads
<= 0:
207 parser
.error('Concurrent fragments must be positive')
208 if opts
.wait_for_video
is not None:
209 min_wait
, max_wait
, *_
= map(parse_duration
, opts
.wait_for_video
.split('-', 1) + [None])
210 if min_wait
is None or (max_wait
is None and '-' in opts
.wait_for_video
):
211 parser
.error('Invalid time range to wait')
212 elif max_wait
is not None and max_wait
< min_wait
:
213 parser
.error('Minimum time range to wait must not be longer than the maximum')
214 opts
.wait_for_video
= (min_wait
, max_wait
)
216 def parse_retries(retries
, name
=''):
217 if retries
in ('inf', 'infinite'):
218 parsed_retries
= float('inf')
221 parsed_retries
= int(retries
)
222 except (TypeError, ValueError):
223 parser
.error('invalid %sretry count specified' % name
)
224 return parsed_retries
225 if opts
.retries
is not None:
226 opts
.retries
= parse_retries(opts
.retries
)
227 if opts
.file_access_retries
is not None:
228 opts
.file_access_retries
= parse_retries(opts
.file_access_retries
, 'file access ')
229 if opts
.fragment_retries
is not None:
230 opts
.fragment_retries
= parse_retries(opts
.fragment_retries
, 'fragment ')
231 if opts
.extractor_retries
is not None:
232 opts
.extractor_retries
= parse_retries(opts
.extractor_retries
, 'extractor ')
233 if opts
.buffersize
is not None:
234 numeric_buffersize
= FileDownloader
.parse_bytes(opts
.buffersize
)
235 if numeric_buffersize
is None:
236 parser
.error('invalid buffer size specified')
237 opts
.buffersize
= numeric_buffersize
238 if opts
.http_chunk_size
is not None:
239 numeric_chunksize
= FileDownloader
.parse_bytes(opts
.http_chunk_size
)
240 if not numeric_chunksize
:
241 parser
.error('invalid http chunk size specified')
242 opts
.http_chunk_size
= numeric_chunksize
243 if opts
.playliststart
<= 0:
244 raise parser
.error('Playlist start must be positive')
245 if opts
.playlistend
not in (-1, None) and opts
.playlistend
< opts
.playliststart
:
246 raise parser
.error('Playlist end must be greater than playlist start')
247 if opts
.extractaudio
:
248 opts
.audioformat
= opts
.audioformat
.lower()
249 if opts
.audioformat
not in ['best'] + list(FFmpegExtractAudioPP
.SUPPORTED_EXTS
):
250 parser
.error('invalid audio format specified')
251 if opts
.audioquality
:
252 opts
.audioquality
= opts
.audioquality
.strip('k').strip('K')
253 audioquality
= int_or_none(float_or_none(opts
.audioquality
)) # int_or_none prevents inf, nan
254 if audioquality
is None or audioquality
< 0:
255 parser
.error('invalid audio quality specified')
256 if opts
.recodevideo
is not None:
257 opts
.recodevideo
= opts
.recodevideo
.replace(' ', '')
258 if not re
.match(FFmpegVideoConvertorPP
.FORMAT_RE
, opts
.recodevideo
):
259 parser
.error('invalid video remux format specified')
260 if opts
.remuxvideo
is not None:
261 opts
.remuxvideo
= opts
.remuxvideo
.replace(' ', '')
262 if not re
.match(FFmpegVideoRemuxerPP
.FORMAT_RE
, opts
.remuxvideo
):
263 parser
.error('invalid video remux format specified')
264 if opts
.convertsubtitles
is not None:
265 if opts
.convertsubtitles
not in FFmpegSubtitlesConvertorPP
.SUPPORTED_EXTS
:
266 parser
.error('invalid subtitle format specified')
267 if opts
.convertthumbnails
is not None:
268 if opts
.convertthumbnails
not in FFmpegThumbnailsConvertorPP
.SUPPORTED_EXTS
:
269 parser
.error('invalid thumbnail format specified')
270 if opts
.cookiesfrombrowser
is not None:
271 mobj
= re
.match(r
'(?P<name>[^+:]+)(\s*\+\s*(?P<keyring>[^:]+))?(\s*:(?P<profile>.+))?', opts
.cookiesfrombrowser
)
273 parser
.error(f
'invalid cookies from browser arguments: {opts.cookiesfrombrowser}')
274 browser_name
, keyring
, profile
= mobj
.group('name', 'keyring', 'profile')
275 browser_name
= browser_name
.lower()
276 if browser_name
not in SUPPORTED_BROWSERS
:
277 parser
.error(f
'unsupported browser specified for cookies: "{browser_name}". '
278 f
'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}')
279 if keyring
is not None:
280 keyring
= keyring
.upper()
281 if keyring
not in SUPPORTED_KEYRINGS
:
282 parser
.error(f
'unsupported keyring specified for cookies: "{keyring}". '
283 f
'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}')
284 opts
.cookiesfrombrowser
= (browser_name
, profile
, keyring
)
285 geo_bypass_code
= opts
.geo_bypass_ip_block
or opts
.geo_bypass_country
286 if geo_bypass_code
is not None:
288 GeoUtils
.random_ipv4(geo_bypass_code
)
290 parser
.error('unsupported geo-bypass country or ip-block')
292 if opts
.date
is not None:
293 date
= DateRange
.day(opts
.date
)
295 date
= DateRange(opts
.dateafter
, opts
.datebefore
)
297 compat_opts
= opts
.compat_opts
299 def report_conflict(arg1
, arg2
):
300 warnings
.append(f
'{arg2} is ignored since {arg1} was given')
302 def _unused_compat_opt(name
):
303 if name
not in compat_opts
:
305 compat_opts
.discard(name
)
306 compat_opts
.update(['*%s' % name
])
309 def set_default_compat(compat_name
, opt_name
, default
=True, remove_compat
=True):
310 attr
= getattr(opts
, opt_name
)
311 if compat_name
in compat_opts
:
313 setattr(opts
, opt_name
, not default
)
317 _unused_compat_opt(compat_name
)
320 setattr(opts
, opt_name
, default
)
323 set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
324 set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
325 set_default_compat('no-clean-infojson', 'clean_infojson')
326 if 'no-attach-info-json' in compat_opts
:
327 if opts
.embed_infojson
:
328 _unused_compat_opt('no-attach-info-json')
330 opts
.embed_infojson
= False
331 if 'format-sort' in compat_opts
:
332 opts
.format_sort
.extend(InfoExtractor
.FormatSort
.ytdl_default
)
333 _video_multistreams_set
= set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat
=False)
334 _audio_multistreams_set
= set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat
=False)
335 if _video_multistreams_set
is False and _audio_multistreams_set
is False:
336 _unused_compat_opt('multistreams')
337 outtmpl_default
= opts
.outtmpl
.get('default')
338 if outtmpl_default
== '':
339 outtmpl_default
, opts
.skip_download
= None, True
340 del opts
.outtmpl
['default']
342 if outtmpl_default
is None:
343 outtmpl_default
= opts
.outtmpl
['default'] = '%(id)s.%(ext)s'
345 report_conflict('--output', '--id')
346 if 'filename' in compat_opts
:
347 if outtmpl_default
is None:
348 outtmpl_default
= opts
.outtmpl
['default'] = '%(title)s-%(id)s.%(ext)s'
350 _unused_compat_opt('filename')
352 def validate_outtmpl(tmpl
, msg
):
353 err
= YoutubeDL
.validate_outtmpl(tmpl
)
355 parser
.error('invalid %s %r: %s' % (msg
, tmpl
, error_to_compat_str(err
)))
357 for k
, tmpl
in opts
.outtmpl
.items():
358 validate_outtmpl(tmpl
, f
'{k} output template')
359 for type_
, tmpl_list
in opts
.forceprint
.items():
360 for tmpl
in tmpl_list
:
361 validate_outtmpl(tmpl
, f
'{type_} print template')
362 for type_
, tmpl_list
in opts
.print_to_file
.items():
363 for tmpl
, file in tmpl_list
:
364 validate_outtmpl(tmpl
, f
'{type_} print-to-file template')
365 validate_outtmpl(file, f
'{type_} print-to-file filename')
366 validate_outtmpl(opts
.sponsorblock_chapter_title
, 'SponsorBlock chapter title')
367 for k
, tmpl
in opts
.progress_template
.items():
368 k
= f
'{k[:-6]} console title' if '-title' in k
else f
'{k} progress'
369 validate_outtmpl(tmpl
, f
'{k} template')
371 if opts
.extractaudio
and not opts
.keepvideo
and opts
.format
is None:
372 opts
.format
= 'bestaudio/best'
374 if outtmpl_default
is not None and not os
.path
.splitext(outtmpl_default
)[1] and opts
.extractaudio
:
375 parser
.error('Cannot download a video and extract audio into the same'
376 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
377 ' template'.format(outtmpl_default
))
379 for f
in opts
.format_sort
:
380 if re
.match(InfoExtractor
.FormatSort
.regex
, f
) is None:
381 parser
.error('invalid format sort string "%s" specified' % f
)
383 def metadataparser_actions(f
):
384 if isinstance(f
, str):
385 cmd
= '--parse-metadata %s' % compat_shlex_quote(f
)
387 actions
= [MetadataFromFieldPP
.to_action(f
)]
388 except Exception as err
:
389 parser
.error(f
'{cmd} is invalid; {err}')
391 cmd
= '--replace-in-metadata %s' % ' '.join(map(compat_shlex_quote
, f
))
392 actions
= ((MetadataParserPP
.Actions
.REPLACE
, x
, *f
[1:]) for x
in f
[0].split(','))
394 for action
in actions
:
396 MetadataParserPP
.validate_action(*action
)
397 except Exception as err
:
398 parser
.error(f
'{cmd} is invalid; {err}')
401 if opts
.parse_metadata
is None:
402 opts
.parse_metadata
= []
403 if opts
.metafromtitle
is not None:
404 opts
.parse_metadata
.append('title:%s' % opts
.metafromtitle
)
405 opts
.parse_metadata
= list(itertools
.chain(*map(metadataparser_actions
, opts
.parse_metadata
)))
407 any_getting
= (any(opts
.forceprint
.values()) or opts
.dumpjson
or opts
.dump_single_json
408 or opts
.geturl
or opts
.gettitle
or opts
.getid
or opts
.getthumbnail
409 or opts
.getdescription
or opts
.getfilename
or opts
.getformat
or opts
.getduration
)
411 any_printing
= opts
.print_json
412 download_archive_fn
= expand_path(opts
.download_archive
) if opts
.download_archive
is not None else opts
.download_archive
414 # If JSON is not printed anywhere, but comments are requested, save it to file
415 printing_json
= opts
.dumpjson
or opts
.print_json
or opts
.dump_single_json
416 if opts
.getcomments
and not printing_json
:
417 opts
.writeinfojson
= True
419 if opts
.no_sponsorblock
:
420 opts
.sponsorblock_mark
= set()
421 opts
.sponsorblock_remove
= set()
422 sponsorblock_query
= opts
.sponsorblock_mark | opts
.sponsorblock_remove
424 opts
.remove_chapters
= opts
.remove_chapters
or []
426 if (opts
.remove_chapters
or sponsorblock_query
) and opts
.sponskrub
is not False:
428 if opts
.remove_chapters
:
429 report_conflict('--remove-chapters', '--sponskrub')
430 if opts
.sponsorblock_mark
:
431 report_conflict('--sponsorblock-mark', '--sponskrub')
432 if opts
.sponsorblock_remove
:
433 report_conflict('--sponsorblock-remove', '--sponskrub')
434 opts
.sponskrub
= False
435 if opts
.sponskrub_cut
and opts
.split_chapters
and opts
.sponskrub
is not False:
436 report_conflict('--split-chapter', '--sponskrub-cut')
437 opts
.sponskrub_cut
= False
439 if opts
.remuxvideo
and opts
.recodevideo
:
440 report_conflict('--recode-video', '--remux-video')
441 opts
.remuxvideo
= False
443 if opts
.allow_unplayable_formats
:
444 def report_unplayable_conflict(opt_name
, arg
, default
=False, allowed
=None):
445 val
= getattr(opts
, opt_name
)
446 if (not allowed
and val
) or (allowed
and not allowed(val
)):
447 report_conflict('--allow-unplayable-formats', arg
)
448 setattr(opts
, opt_name
, default
)
450 report_unplayable_conflict('extractaudio', '--extract-audio')
451 report_unplayable_conflict('remuxvideo', '--remux-video')
452 report_unplayable_conflict('recodevideo', '--recode-video')
453 report_unplayable_conflict('addmetadata', '--embed-metadata')
454 report_unplayable_conflict('addchapters', '--embed-chapters')
455 report_unplayable_conflict('embed_infojson', '--embed-info-json')
456 opts
.embed_infojson
= False
457 report_unplayable_conflict('embedsubtitles', '--embed-subs')
458 report_unplayable_conflict('embedthumbnail', '--embed-thumbnail')
459 report_unplayable_conflict('xattrs', '--xattrs')
460 report_unplayable_conflict('fixup', '--fixup', default
='never', allowed
=lambda x
: x
in (None, 'never', 'ignore'))
462 report_unplayable_conflict('remove_chapters', '--remove-chapters', default
=[])
463 report_unplayable_conflict('sponsorblock_remove', '--sponsorblock-remove', default
=set())
464 report_unplayable_conflict('sponskrub', '--sponskrub', default
=set())
465 opts
.sponskrub
= False
467 if (opts
.addmetadata
or opts
.sponsorblock_mark
) and opts
.addchapters
is None:
468 opts
.addchapters
= True
471 postprocessors
= list(opts
.add_postprocessors
)
472 if sponsorblock_query
:
473 postprocessors
.append({
474 'key': 'SponsorBlock',
475 'categories': sponsorblock_query
,
476 'api': opts
.sponsorblock_api
,
477 # Run this immediately after extraction is complete
478 'when': 'pre_process'
480 if opts
.parse_metadata
:
481 postprocessors
.append({
482 'key': 'MetadataParser',
483 'actions': opts
.parse_metadata
,
484 # Run this immediately after extraction is complete
485 'when': 'pre_process'
487 if opts
.convertsubtitles
:
488 postprocessors
.append({
489 'key': 'FFmpegSubtitlesConvertor',
490 'format': opts
.convertsubtitles
,
491 # Run this before the actual video download
494 if opts
.convertthumbnails
:
495 postprocessors
.append({
496 'key': 'FFmpegThumbnailsConvertor',
497 'format': opts
.convertthumbnails
,
498 # Run this before the actual video download
501 if opts
.extractaudio
:
502 postprocessors
.append({
503 'key': 'FFmpegExtractAudio',
504 'preferredcodec': opts
.audioformat
,
505 'preferredquality': opts
.audioquality
,
506 'nopostoverwrites': opts
.nopostoverwrites
,
509 postprocessors
.append({
510 'key': 'FFmpegVideoRemuxer',
511 'preferedformat': opts
.remuxvideo
,
514 postprocessors
.append({
515 'key': 'FFmpegVideoConvertor',
516 'preferedformat': opts
.recodevideo
,
518 # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
519 if opts
.embedsubtitles
:
520 already_have_subtitle
= opts
.writesubtitles
and 'no-keep-subs' not in compat_opts
521 postprocessors
.append({
522 'key': 'FFmpegEmbedSubtitle',
523 # already_have_subtitle = True prevents the file from being deleted after embedding
524 'already_have_subtitle': already_have_subtitle
526 if not opts
.writeautomaticsub
and 'no-keep-subs' not in compat_opts
:
527 opts
.writesubtitles
= True
528 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
529 # this was the old behaviour if only --all-sub was given.
530 if opts
.allsubtitles
and not opts
.writeautomaticsub
:
531 opts
.writesubtitles
= True
532 # ModifyChapters must run before FFmpegMetadataPP
533 remove_chapters_patterns
, remove_ranges
= [], []
534 for regex
in opts
.remove_chapters
:
535 if regex
.startswith('*'):
536 dur
= list(map(parse_duration
, regex
[1:].split('-')))
537 if len(dur
) == 2 and all(t
is not None for t
in dur
):
538 remove_ranges
.append(tuple(dur
))
540 parser
.error(f
'invalid --remove-chapters time range {regex!r}. Must be of the form *start-end')
542 remove_chapters_patterns
.append(re
.compile(regex
))
543 except re
.error
as err
:
544 parser
.error(f
'invalid --remove-chapters regex {regex!r} - {err}')
545 if opts
.remove_chapters
or sponsorblock_query
:
546 postprocessors
.append({
547 'key': 'ModifyChapters',
548 'remove_chapters_patterns': remove_chapters_patterns
,
549 'remove_sponsor_segments': opts
.sponsorblock_remove
,
550 'remove_ranges': remove_ranges
,
551 'sponsorblock_chapter_title': opts
.sponsorblock_chapter_title
,
552 'force_keyframes': opts
.force_keyframes_at_cuts
554 # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
555 # FFmpegExtractAudioPP as containers before conversion may not support
556 # metadata (3gp, webm, etc.)
557 # By default ffmpeg preserves metadata applicable for both
558 # source and target containers. From this point the container won't change,
559 # so metadata can be added here.
560 if opts
.addmetadata
or opts
.addchapters
or opts
.embed_infojson
:
561 if opts
.embed_infojson
is None:
562 opts
.embed_infojson
= 'if_exists'
563 postprocessors
.append({
564 'key': 'FFmpegMetadata',
565 'add_chapters': opts
.addchapters
,
566 'add_metadata': opts
.addmetadata
,
567 'add_infojson': opts
.embed_infojson
,
570 # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
571 # but must be below EmbedSubtitle and FFmpegMetadata
572 # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
573 # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
574 if opts
.sponskrub
is not False:
575 postprocessors
.append({
577 'path': opts
.sponskrub_path
,
578 'args': opts
.sponskrub_args
,
579 'cut': opts
.sponskrub_cut
,
580 'force': opts
.sponskrub_force
,
581 'ignoreerror': opts
.sponskrub
is None,
584 if opts
.embedthumbnail
:
585 postprocessors
.append({
586 'key': 'EmbedThumbnail',
587 # already_have_thumbnail = True prevents the file from being deleted after embedding
588 'already_have_thumbnail': opts
.writethumbnail
590 if not opts
.writethumbnail
:
591 opts
.writethumbnail
= True
592 opts
.outtmpl
['pl_thumbnail'] = ''
593 if opts
.split_chapters
:
594 postprocessors
.append({
595 'key': 'FFmpegSplitChapters',
596 'force_keyframes': opts
.force_keyframes_at_cuts
,
598 # XAttrMetadataPP should be run after post-processors that may change file contents
600 postprocessors
.append({'key': 'XAttrMetadata'}
)
601 if opts
.concat_playlist
!= 'never':
602 postprocessors
.append({
603 'key': 'FFmpegConcat',
604 'only_multi_video': opts
.concat_playlist
!= 'always',
607 # Exec must be the last PP of each category
608 if opts
.exec_before_dl_cmd
:
609 opts
.exec_cmd
.setdefault('before_dl', opts
.exec_before_dl_cmd
)
610 for when
, exec_cmd
in opts
.exec_cmd
.items():
611 postprocessors
.append({
613 'exec_cmd': exec_cmd
,
614 # Run this only after the files have been moved to their final locations
618 def report_args_compat(arg
, name
):
619 warnings
.append('%s given without specifying name. The arguments will be given to all %s' % (arg
, name
))
621 if 'default' in opts
.external_downloader_args
:
622 report_args_compat('--downloader-args', 'external downloaders')
624 if 'default-compat' in opts
.postprocessor_args
and 'default' not in opts
.postprocessor_args
:
625 report_args_compat('--post-processor-args', 'post-processors')
626 opts
.postprocessor_args
.setdefault('sponskrub', [])
627 opts
.postprocessor_args
['default'] = opts
.postprocessor_args
['default-compat']
629 def report_deprecation(val
, old
, new
=None):
632 deprecation_warnings
.append(
633 f
'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
634 else f
'{old} is deprecated and may not work as expected')
636 report_deprecation(opts
.sponskrub
, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
637 report_deprecation(not opts
.prefer_ffmpeg
, '--prefer-avconv', 'ffmpeg')
638 report_deprecation(opts
.include_ads
, '--include-ads')
639 # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
640 # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
643 opts
.recodevideo
if opts
.recodevideo
in FFmpegVideoConvertorPP
.SUPPORTED_EXTS
644 else opts
.remuxvideo
if opts
.remuxvideo
in FFmpegVideoRemuxerPP
.SUPPORTED_EXTS
645 else opts
.audioformat
if (opts
.extractaudio
and opts
.audioformat
!= 'best')
649 None if opts
.match_filter
is None
650 else match_filter_func(opts
.match_filter
))
653 'usenetrc': opts
.usenetrc
,
654 'netrc_location': opts
.netrc_location
,
655 'username': opts
.username
,
656 'password': opts
.password
,
657 'twofactor': opts
.twofactor
,
658 'videopassword': opts
.videopassword
,
659 'ap_mso': opts
.ap_mso
,
660 'ap_username': opts
.ap_username
,
661 'ap_password': opts
.ap_password
,
662 'quiet': (opts
.quiet
or any_getting
or any_printing
),
663 'no_warnings': opts
.no_warnings
,
664 'forceurl': opts
.geturl
,
665 'forcetitle': opts
.gettitle
,
666 'forceid': opts
.getid
,
667 'forcethumbnail': opts
.getthumbnail
,
668 'forcedescription': opts
.getdescription
,
669 'forceduration': opts
.getduration
,
670 'forcefilename': opts
.getfilename
,
671 'forceformat': opts
.getformat
,
672 'forceprint': opts
.forceprint
,
673 'print_to_file': opts
.print_to_file
,
674 'forcejson': opts
.dumpjson
or opts
.print_json
,
675 'dump_single_json': opts
.dump_single_json
,
676 'force_write_download_archive': opts
.force_write_download_archive
,
677 'simulate': (any_getting
or None) if opts
.simulate
is None else opts
.simulate
,
678 'skip_download': opts
.skip_download
,
679 'format': opts
.format
,
680 'allow_unplayable_formats': opts
.allow_unplayable_formats
,
681 'ignore_no_formats_error': opts
.ignore_no_formats_error
,
682 'format_sort': opts
.format_sort
,
683 'format_sort_force': opts
.format_sort_force
,
684 'allow_multiple_video_streams': opts
.allow_multiple_video_streams
,
685 'allow_multiple_audio_streams': opts
.allow_multiple_audio_streams
,
686 'check_formats': opts
.check_formats
,
687 'listformats': opts
.listformats
,
688 'listformats_table': opts
.listformats_table
,
689 'outtmpl': opts
.outtmpl
,
690 'outtmpl_na_placeholder': opts
.outtmpl_na_placeholder
,
692 'autonumber_size': opts
.autonumber_size
,
693 'autonumber_start': opts
.autonumber_start
,
694 'restrictfilenames': opts
.restrictfilenames
,
695 'windowsfilenames': opts
.windowsfilenames
,
696 'ignoreerrors': opts
.ignoreerrors
,
697 'force_generic_extractor': opts
.force_generic_extractor
,
698 'ratelimit': opts
.ratelimit
,
699 'throttledratelimit': opts
.throttledratelimit
,
700 'overwrites': opts
.overwrites
,
701 'retries': opts
.retries
,
702 'file_access_retries': opts
.file_access_retries
,
703 'fragment_retries': opts
.fragment_retries
,
704 'extractor_retries': opts
.extractor_retries
,
705 'skip_unavailable_fragments': opts
.skip_unavailable_fragments
,
706 'keep_fragments': opts
.keep_fragments
,
707 'concurrent_fragment_downloads': opts
.concurrent_fragment_downloads
,
708 'buffersize': opts
.buffersize
,
709 'noresizebuffer': opts
.noresizebuffer
,
710 'http_chunk_size': opts
.http_chunk_size
,
711 'continuedl': opts
.continue_dl
,
712 'noprogress': opts
.quiet
if opts
.noprogress
is None else opts
.noprogress
,
713 'progress_with_newline': opts
.progress_with_newline
,
714 'progress_template': opts
.progress_template
,
715 'playliststart': opts
.playliststart
,
716 'playlistend': opts
.playlistend
,
717 'playlistreverse': opts
.playlist_reverse
,
718 'playlistrandom': opts
.playlist_random
,
719 'noplaylist': opts
.noplaylist
,
720 'logtostderr': outtmpl_default
== '-',
721 'consoletitle': opts
.consoletitle
,
722 'nopart': opts
.nopart
,
723 'updatetime': opts
.updatetime
,
724 'writedescription': opts
.writedescription
,
725 'writeannotations': opts
.writeannotations
,
726 'writeinfojson': opts
.writeinfojson
,
727 'allow_playlist_files': opts
.allow_playlist_files
,
728 'clean_infojson': opts
.clean_infojson
,
729 'getcomments': opts
.getcomments
,
730 'writethumbnail': opts
.writethumbnail
is True,
731 'write_all_thumbnails': opts
.writethumbnail
== 'all',
732 'writelink': opts
.writelink
,
733 'writeurllink': opts
.writeurllink
,
734 'writewebloclink': opts
.writewebloclink
,
735 'writedesktoplink': opts
.writedesktoplink
,
736 'writesubtitles': opts
.writesubtitles
,
737 'writeautomaticsub': opts
.writeautomaticsub
,
738 'allsubtitles': opts
.allsubtitles
,
739 'listsubtitles': opts
.listsubtitles
,
740 'subtitlesformat': opts
.subtitlesformat
,
741 'subtitleslangs': opts
.subtitleslangs
,
742 'matchtitle': decodeOption(opts
.matchtitle
),
743 'rejecttitle': decodeOption(opts
.rejecttitle
),
744 'max_downloads': opts
.max_downloads
,
745 'prefer_free_formats': opts
.prefer_free_formats
,
746 'trim_file_name': opts
.trim_file_name
,
747 'verbose': opts
.verbose
,
748 'dump_intermediate_pages': opts
.dump_intermediate_pages
,
749 'write_pages': opts
.write_pages
,
751 'keepvideo': opts
.keepvideo
,
752 'min_filesize': opts
.min_filesize
,
753 'max_filesize': opts
.max_filesize
,
754 'min_views': opts
.min_views
,
755 'max_views': opts
.max_views
,
757 'cachedir': opts
.cachedir
,
758 'youtube_print_sig_code': opts
.youtube_print_sig_code
,
759 'age_limit': opts
.age_limit
,
760 'download_archive': download_archive_fn
,
761 'break_on_existing': opts
.break_on_existing
,
762 'break_on_reject': opts
.break_on_reject
,
763 'break_per_url': opts
.break_per_url
,
764 'skip_playlist_after_errors': opts
.skip_playlist_after_errors
,
765 'cookiefile': opts
.cookiefile
,
766 'cookiesfrombrowser': opts
.cookiesfrombrowser
,
767 'legacyserverconnect': opts
.legacy_server_connect
,
768 'nocheckcertificate': opts
.no_check_certificate
,
769 'prefer_insecure': opts
.prefer_insecure
,
771 'socket_timeout': opts
.socket_timeout
,
772 'bidi_workaround': opts
.bidi_workaround
,
773 'debug_printtraffic': opts
.debug_printtraffic
,
774 'prefer_ffmpeg': opts
.prefer_ffmpeg
,
775 'include_ads': opts
.include_ads
,
776 'default_search': opts
.default_search
,
777 'dynamic_mpd': opts
.dynamic_mpd
,
778 'extractor_args': opts
.extractor_args
,
779 'youtube_include_dash_manifest': opts
.youtube_include_dash_manifest
,
780 'youtube_include_hls_manifest': opts
.youtube_include_hls_manifest
,
781 'encoding': opts
.encoding
,
782 'extract_flat': opts
.extract_flat
,
783 'live_from_start': opts
.live_from_start
,
784 'wait_for_video': opts
.wait_for_video
,
785 'mark_watched': opts
.mark_watched
,
786 'merge_output_format': opts
.merge_output_format
,
787 'final_ext': final_ext
,
788 'postprocessors': postprocessors
,
790 'source_address': opts
.source_address
,
791 'call_home': opts
.call_home
,
792 'sleep_interval_requests': opts
.sleep_interval_requests
,
793 'sleep_interval': opts
.sleep_interval
,
794 'max_sleep_interval': opts
.max_sleep_interval
,
795 'sleep_interval_subtitles': opts
.sleep_interval_subtitles
,
796 'external_downloader': opts
.external_downloader
,
797 'list_thumbnails': opts
.list_thumbnails
,
798 'playlist_items': opts
.playlist_items
,
799 'xattr_set_filesize': opts
.xattr_set_filesize
,
800 'match_filter': match_filter
,
801 'no_color': opts
.no_color
,
802 'ffmpeg_location': opts
.ffmpeg_location
,
803 'hls_prefer_native': opts
.hls_prefer_native
,
804 'hls_use_mpegts': opts
.hls_use_mpegts
,
805 'hls_split_discontinuity': opts
.hls_split_discontinuity
,
806 'external_downloader_args': opts
.external_downloader_args
,
807 'postprocessor_args': opts
.postprocessor_args
,
808 'cn_verification_proxy': opts
.cn_verification_proxy
,
809 'geo_verification_proxy': opts
.geo_verification_proxy
,
810 'geo_bypass': opts
.geo_bypass
,
811 'geo_bypass_country': opts
.geo_bypass_country
,
812 'geo_bypass_ip_block': opts
.geo_bypass_ip_block
,
813 '_warnings': warnings
,
814 '_deprecation_warnings': deprecation_warnings
,
815 'compat_opts': compat_opts
,
818 with YoutubeDL(ydl_opts
) as ydl
:
819 actual_use
= all_urls
or opts
.load_info_filename
827 # If updater returns True, exit. Required for windows
830 sys
.exit('ERROR: The program must exit for the update to complete')
835 if opts
.update_self
or opts
.rm_cachedir
:
838 ydl
.warn_if_short_id(sys
.argv
[1:] if argv
is None else argv
)
840 'You must provide at least one URL.\n'
841 'Type yt-dlp --help to see a list of all options.')
844 if opts
.load_info_filename
is not None:
845 retcode
= ydl
.download_with_info_file(expand_path(opts
.load_info_filename
))
847 retcode
= ydl
.download(all_urls
)
848 except DownloadCancelled
:
849 ydl
.to_screen('Aborting remaining downloads')
858 except DownloadError
:
860 except SameFileError
as e
:
861 sys
.exit(f
'ERROR: {e}')
862 except KeyboardInterrupt:
863 sys
.exit('\nERROR: Interrupted by user')
864 except BrokenPipeError
as e
:
865 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
866 devnull
= os
.open(os
.devnull
, os
.O_WRONLY
)
867 os
.dup2(devnull
, sys
.stdout
.fileno())
868 sys
.exit(f
'\nERROR: {e}')
871 __all__
= ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']