__init__.py 41 KB

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