__init__.py 40 KB

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