__init__.py 37 KB

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