__init__.py 47 KB

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