ffmpeg.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. import collections
  2. import contextvars
  3. import itertools
  4. import json
  5. import os
  6. import re
  7. import subprocess
  8. import time
  9. from .common import PostProcessor
  10. from ..compat import functools, imghdr
  11. from ..utils import (
  12. ISO639Utils,
  13. Popen,
  14. PostProcessingError,
  15. _get_exe_version_output,
  16. detect_exe_version,
  17. determine_ext,
  18. dfxp2srt,
  19. encodeArgument,
  20. encodeFilename,
  21. filter_dict,
  22. float_or_none,
  23. is_outdated_version,
  24. orderedSet,
  25. prepend_extension,
  26. replace_extension,
  27. shell_quote,
  28. traverse_obj,
  29. variadic,
  30. write_json_file,
  31. write_string,
  32. )
  33. EXT_TO_OUT_FORMATS = {
  34. 'aac': 'adts',
  35. 'flac': 'flac',
  36. 'm4a': 'ipod',
  37. 'mka': 'matroska',
  38. 'mkv': 'matroska',
  39. 'mpg': 'mpeg',
  40. 'ogv': 'ogg',
  41. 'ts': 'mpegts',
  42. 'wma': 'asf',
  43. 'wmv': 'asf',
  44. 'vtt': 'webvtt',
  45. }
  46. ACODECS = {
  47. # name: (ext, encoder, opts)
  48. 'mp3': ('mp3', 'libmp3lame', ()),
  49. 'aac': ('m4a', 'aac', ('-f', 'adts')),
  50. 'm4a': ('m4a', 'aac', ('-bsf:a', 'aac_adtstoasc')),
  51. 'opus': ('opus', 'libopus', ()),
  52. 'vorbis': ('ogg', 'libvorbis', ()),
  53. 'flac': ('flac', 'flac', ()),
  54. 'alac': ('m4a', None, ('-acodec', 'alac')),
  55. 'wav': ('wav', None, ('-f', 'wav')),
  56. }
  57. def create_mapping_re(supported):
  58. return re.compile(r'{0}(?:/{0})*$'.format(r'(?:\s*\w+\s*>)?\s*(?:%s)\s*' % '|'.join(supported)))
  59. def resolve_mapping(source, mapping):
  60. """
  61. Get corresponding item from a mapping string like 'A>B/C>D/E'
  62. @returns (target, error_message)
  63. """
  64. for pair in mapping.lower().split('/'):
  65. kv = pair.split('>', 1)
  66. if len(kv) == 1 or kv[0].strip() == source:
  67. target = kv[-1].strip()
  68. if target == source:
  69. return target, f'already is in target format {source}'
  70. return target, None
  71. return None, f'could not find a mapping for {source}'
  72. class FFmpegPostProcessorError(PostProcessingError):
  73. pass
  74. class FFmpegPostProcessor(PostProcessor):
  75. _ffmpeg_location = contextvars.ContextVar('ffmpeg_location', default=None)
  76. def __init__(self, downloader=None):
  77. PostProcessor.__init__(self, downloader)
  78. self._prefer_ffmpeg = self.get_param('prefer_ffmpeg', True)
  79. self._paths = self._determine_executables()
  80. @staticmethod
  81. def get_versions_and_features(downloader=None):
  82. pp = FFmpegPostProcessor(downloader)
  83. return pp._versions, pp._features
  84. @staticmethod
  85. def get_versions(downloader=None):
  86. return FFmpegPostProcessor.get_versions_and_features(downloader)[0]
  87. _ffmpeg_to_avconv = {'ffmpeg': 'avconv', 'ffprobe': 'avprobe'}
  88. def _determine_executables(self):
  89. programs = [*self._ffmpeg_to_avconv.keys(), *self._ffmpeg_to_avconv.values()]
  90. location = self.get_param('ffmpeg_location', self._ffmpeg_location.get())
  91. if location is None:
  92. return {p: p for p in programs}
  93. if not os.path.exists(location):
  94. self.report_warning(f'ffmpeg-location {location} does not exist! Continuing without ffmpeg')
  95. return {}
  96. elif os.path.isdir(location):
  97. dirname, basename = location, None
  98. else:
  99. basename = os.path.splitext(os.path.basename(location))[0]
  100. basename = next((p for p in programs if basename.startswith(p)), 'ffmpeg')
  101. dirname = os.path.dirname(os.path.abspath(location))
  102. if basename in self._ffmpeg_to_avconv.keys():
  103. self._prefer_ffmpeg = True
  104. paths = {p: os.path.join(dirname, p) for p in programs}
  105. if basename:
  106. paths[basename] = location
  107. return paths
  108. _version_cache, _features_cache = {None: None}, {}
  109. def _get_ffmpeg_version(self, prog):
  110. path = self._paths.get(prog)
  111. if path in self._version_cache:
  112. return self._version_cache[path], self._features_cache.get(path, {})
  113. out = _get_exe_version_output(path, ['-bsfs'], to_screen=self.write_debug)
  114. ver = detect_exe_version(out) if out else False
  115. if ver:
  116. regexs = [
  117. r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
  118. r'n([0-9.]+)$', # Arch Linux
  119. # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
  120. ]
  121. for regex in regexs:
  122. mobj = re.match(regex, ver)
  123. if mobj:
  124. ver = mobj.group(1)
  125. self._version_cache[path] = ver
  126. if prog != 'ffmpeg' or not out:
  127. return ver, {}
  128. mobj = re.search(r'(?m)^\s+libavformat\s+(?:[0-9. ]+)\s+/\s+(?P<runtime>[0-9. ]+)', out)
  129. lavf_runtime_version = mobj.group('runtime').replace(' ', '') if mobj else None
  130. self._features_cache[path] = features = {
  131. 'fdk': '--enable-libfdk-aac' in out,
  132. 'setts': 'setts' in out.splitlines(),
  133. 'needs_adtstoasc': is_outdated_version(lavf_runtime_version, '57.56.100', False),
  134. }
  135. return ver, features
  136. @property
  137. def _versions(self):
  138. return filter_dict({self.basename: self._version, self.probe_basename: self._probe_version})
  139. @functools.cached_property
  140. def basename(self):
  141. self._version # run property
  142. return self.basename
  143. @functools.cached_property
  144. def probe_basename(self):
  145. self._probe_version # run property
  146. return self.probe_basename
  147. def _get_version(self, kind):
  148. executables = (kind, self._ffmpeg_to_avconv[kind])
  149. if not self._prefer_ffmpeg:
  150. executables = reversed(executables)
  151. basename, version, features = next(filter(
  152. lambda x: x[1], ((p, *self._get_ffmpeg_version(p)) for p in executables)), (None, None, {}))
  153. if kind == 'ffmpeg':
  154. self.basename, self._features = basename, features
  155. else:
  156. self.probe_basename = basename
  157. if basename == self._ffmpeg_to_avconv[kind]:
  158. self.deprecation_warning(
  159. f'Support for {self._ffmpeg_to_avconv[kind]} is deprecated and may be removed in a future version. Use {kind} instead')
  160. return version
  161. @functools.cached_property
  162. def _version(self):
  163. return self._get_version('ffmpeg')
  164. @functools.cached_property
  165. def _probe_version(self):
  166. return self._get_version('ffprobe')
  167. @property
  168. def available(self):
  169. return self.basename is not None
  170. @property
  171. def executable(self):
  172. return self._paths.get(self.basename)
  173. @property
  174. def probe_available(self):
  175. return self.probe_basename is not None
  176. @property
  177. def probe_executable(self):
  178. return self._paths.get(self.probe_basename)
  179. @staticmethod
  180. def stream_copy_opts(copy=True, *, ext=None):
  181. yield from ('-map', '0')
  182. # Don't copy Apple TV chapters track, bin_data
  183. # See https://github.com/yt-dlp/yt-dlp/issues/2, #19042, #19024, https://trac.ffmpeg.org/ticket/6016
  184. yield from ('-dn', '-ignore_unknown')
  185. if copy:
  186. yield from ('-c', 'copy')
  187. if ext in ('mp4', 'mov', 'm4a'):
  188. yield from ('-c:s', 'mov_text')
  189. def check_version(self):
  190. if not self.available:
  191. raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
  192. required_version = '10-0' if self.basename == 'avconv' else '1.0'
  193. if is_outdated_version(self._version, required_version):
  194. self.report_warning(f'Your copy of {self.basename} is outdated, update {self.basename} '
  195. f'to version {required_version} or newer if you encounter any errors')
  196. def get_audio_codec(self, path):
  197. if not self.probe_available and not self.available:
  198. raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
  199. try:
  200. if self.probe_available:
  201. cmd = [
  202. encodeFilename(self.probe_executable, True),
  203. encodeArgument('-show_streams')]
  204. else:
  205. cmd = [
  206. encodeFilename(self.executable, True),
  207. encodeArgument('-i')]
  208. cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
  209. self.write_debug(f'{self.basename} command line: {shell_quote(cmd)}')
  210. stdout, stderr, returncode = Popen.run(
  211. cmd, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  212. if returncode != (0 if self.probe_available else 1):
  213. return None
  214. except OSError:
  215. return None
  216. output = stdout if self.probe_available else stderr
  217. if self.probe_available:
  218. audio_codec = None
  219. for line in output.split('\n'):
  220. if line.startswith('codec_name='):
  221. audio_codec = line.split('=')[1].strip()
  222. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  223. return audio_codec
  224. else:
  225. # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
  226. mobj = re.search(
  227. r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
  228. output)
  229. if mobj:
  230. return mobj.group(1)
  231. return None
  232. def get_metadata_object(self, path, opts=[]):
  233. if self.probe_basename != 'ffprobe':
  234. if self.probe_available:
  235. self.report_warning('Only ffprobe is supported for metadata extraction')
  236. raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
  237. self.check_version()
  238. cmd = [
  239. encodeFilename(self.probe_executable, True),
  240. encodeArgument('-hide_banner'),
  241. encodeArgument('-show_format'),
  242. encodeArgument('-show_streams'),
  243. encodeArgument('-print_format'),
  244. encodeArgument('json'),
  245. ]
  246. cmd += opts
  247. cmd.append(self._ffmpeg_filename_argument(path))
  248. self.write_debug(f'ffprobe command line: {shell_quote(cmd)}')
  249. stdout, _, _ = Popen.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  250. return json.loads(stdout)
  251. def get_stream_number(self, path, keys, value):
  252. streams = self.get_metadata_object(path)['streams']
  253. num = next(
  254. (i for i, stream in enumerate(streams) if traverse_obj(stream, keys, casesense=False) == value),
  255. None)
  256. return num, len(streams)
  257. def _get_real_video_duration(self, filepath, fatal=True):
  258. try:
  259. duration = float_or_none(
  260. traverse_obj(self.get_metadata_object(filepath), ('format', 'duration')))
  261. if not duration:
  262. raise PostProcessingError('ffprobe returned empty duration')
  263. return duration
  264. except PostProcessingError as e:
  265. if fatal:
  266. raise PostProcessingError(f'Unable to determine video duration: {e.msg}')
  267. def _duration_mismatch(self, d1, d2, tolerance=2):
  268. if not d1 or not d2:
  269. return None
  270. # The duration is often only known to nearest second. So there can be <1sec disparity natually.
  271. # Further excuse an additional <1sec difference.
  272. return abs(d1 - d2) > tolerance
  273. def run_ffmpeg_multiple_files(self, input_paths, out_path, opts, **kwargs):
  274. return self.real_run_ffmpeg(
  275. [(path, []) for path in input_paths],
  276. [(out_path, opts)], **kwargs)
  277. def real_run_ffmpeg(self, input_path_opts, output_path_opts, *, expected_retcodes=(0,)):
  278. self.check_version()
  279. oldest_mtime = min(
  280. os.stat(encodeFilename(path)).st_mtime for path, _ in input_path_opts if path)
  281. cmd = [encodeFilename(self.executable, True), encodeArgument('-y')]
  282. # avconv does not have repeat option
  283. if self.basename == 'ffmpeg':
  284. cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
  285. def make_args(file, args, name, number):
  286. keys = ['_%s%d' % (name, number), '_%s' % name]
  287. if name == 'o':
  288. args += ['-movflags', '+faststart']
  289. if number == 1:
  290. keys.append('')
  291. args += self._configuration_args(self.basename, keys)
  292. if name == 'i':
  293. args.append('-i')
  294. return (
  295. [encodeArgument(arg) for arg in args]
  296. + [encodeFilename(self._ffmpeg_filename_argument(file), True)])
  297. for arg_type, path_opts in (('i', input_path_opts), ('o', output_path_opts)):
  298. cmd += itertools.chain.from_iterable(
  299. make_args(path, list(opts), arg_type, i + 1)
  300. for i, (path, opts) in enumerate(path_opts) if path)
  301. self.write_debug('ffmpeg command line: %s' % shell_quote(cmd))
  302. _, stderr, returncode = Popen.run(
  303. cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  304. if returncode not in variadic(expected_retcodes):
  305. self.write_debug(stderr)
  306. raise FFmpegPostProcessorError(stderr.strip().splitlines()[-1])
  307. for out_path, _ in output_path_opts:
  308. if out_path:
  309. self.try_utime(out_path, oldest_mtime, oldest_mtime)
  310. return stderr
  311. def run_ffmpeg(self, path, out_path, opts, **kwargs):
  312. return self.run_ffmpeg_multiple_files([path], out_path, opts, **kwargs)
  313. @staticmethod
  314. def _ffmpeg_filename_argument(fn):
  315. # Always use 'file:' because the filename may contain ':' (ffmpeg
  316. # interprets that as a protocol) or can start with '-' (-- is broken in
  317. # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
  318. # Also leave '-' intact in order not to break streaming to stdout.
  319. if fn.startswith(('http://', 'https://')):
  320. return fn
  321. return 'file:' + fn if fn != '-' else fn
  322. @staticmethod
  323. def _quote_for_ffmpeg(string):
  324. # See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
  325. # A sequence of '' produces '\'''\'';
  326. # final replace removes the empty '' between \' \'.
  327. string = string.replace("'", r"'\''").replace("'''", "'")
  328. # Handle potential ' at string boundaries.
  329. string = string[1:] if string[0] == "'" else "'" + string
  330. return string[:-1] if string[-1] == "'" else string + "'"
  331. def force_keyframes(self, filename, timestamps):
  332. timestamps = orderedSet(timestamps)
  333. if timestamps[0] == 0:
  334. timestamps = timestamps[1:]
  335. keyframe_file = prepend_extension(filename, 'keyframes.temp')
  336. self.to_screen(f'Re-encoding "{filename}" with appropriate keyframes')
  337. self.run_ffmpeg(filename, keyframe_file, [
  338. *self.stream_copy_opts(False, ext=determine_ext(filename)),
  339. '-force_key_frames', ','.join(f'{t:.6f}' for t in timestamps)])
  340. return keyframe_file
  341. def concat_files(self, in_files, out_file, concat_opts=None):
  342. """
  343. Use concat demuxer to concatenate multiple files having identical streams.
  344. Only inpoint, outpoint, and duration concat options are supported.
  345. See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
  346. """
  347. concat_file = f'{out_file}.concat'
  348. self.write_debug(f'Writing concat spec to {concat_file}')
  349. with open(concat_file, 'wt', encoding='utf-8') as f:
  350. f.writelines(self._concat_spec(in_files, concat_opts))
  351. out_flags = list(self.stream_copy_opts(ext=determine_ext(out_file)))
  352. self.real_run_ffmpeg(
  353. [(concat_file, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
  354. [(out_file, out_flags)])
  355. self._delete_downloaded_files(concat_file)
  356. @classmethod
  357. def _concat_spec(cls, in_files, concat_opts=None):
  358. if concat_opts is None:
  359. concat_opts = [{}] * len(in_files)
  360. yield 'ffconcat version 1.0\n'
  361. for file, opts in zip(in_files, concat_opts):
  362. yield f'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
  363. # Iterate explicitly to yield the following directives in order, ignoring the rest.
  364. for directive in 'inpoint', 'outpoint', 'duration':
  365. if directive in opts:
  366. yield f'{directive} {opts[directive]}\n'
  367. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  368. COMMON_AUDIO_EXTS = ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
  369. SUPPORTED_EXTS = tuple(ACODECS.keys())
  370. FORMAT_RE = create_mapping_re(('best', *SUPPORTED_EXTS))
  371. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  372. FFmpegPostProcessor.__init__(self, downloader)
  373. self.mapping = preferredcodec or 'best'
  374. self._preferredquality = float_or_none(preferredquality)
  375. self._nopostoverwrites = nopostoverwrites
  376. def _quality_args(self, codec):
  377. if self._preferredquality is None:
  378. return []
  379. elif self._preferredquality > 10:
  380. return ['-b:a', f'{self._preferredquality}k']
  381. limits = {
  382. 'libmp3lame': (10, 0),
  383. 'libvorbis': (0, 10),
  384. # FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
  385. # Experimentally, with values over 4, bitrate changes were minimal or non-existent
  386. 'aac': (0.1, 4),
  387. 'libfdk_aac': (1, 5),
  388. }.get(codec)
  389. if not limits:
  390. return []
  391. q = limits[1] + (limits[0] - limits[1]) * (self._preferredquality / 10)
  392. if codec == 'libfdk_aac':
  393. return ['-vbr', f'{int(q)}']
  394. return ['-q:a', f'{q}']
  395. def run_ffmpeg(self, path, out_path, codec, more_opts):
  396. if codec is None:
  397. acodec_opts = []
  398. else:
  399. acodec_opts = ['-acodec', codec]
  400. opts = ['-vn'] + acodec_opts + more_opts
  401. try:
  402. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  403. except FFmpegPostProcessorError as err:
  404. raise PostProcessingError(f'audio conversion failed: {err.msg}')
  405. @PostProcessor._restrict_to(images=False)
  406. def run(self, information):
  407. orig_path = path = information['filepath']
  408. target_format, _skip_msg = resolve_mapping(information['ext'], self.mapping)
  409. if target_format == 'best' and information['ext'] in self.COMMON_AUDIO_EXTS:
  410. target_format, _skip_msg = None, 'the file is already in a common audio format'
  411. if not target_format:
  412. self.to_screen(f'Not converting audio {orig_path}; {_skip_msg}')
  413. return [], information
  414. filecodec = self.get_audio_codec(path)
  415. if filecodec is None:
  416. raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
  417. if filecodec == 'aac' and target_format in ('m4a', 'best'):
  418. # Lossless, but in another container
  419. extension, _, more_opts, acodec = *ACODECS['m4a'], 'copy'
  420. elif target_format == 'best' or target_format == filecodec:
  421. # Lossless if possible
  422. try:
  423. extension, _, more_opts, acodec = *ACODECS[filecodec], 'copy'
  424. except KeyError:
  425. extension, acodec, more_opts = ACODECS['mp3']
  426. else:
  427. # We convert the audio (lossy if codec is lossy)
  428. extension, acodec, more_opts = ACODECS[target_format]
  429. if acodec == 'aac' and self._features.get('fdk'):
  430. acodec, more_opts = 'libfdk_aac', []
  431. more_opts = list(more_opts)
  432. if acodec != 'copy':
  433. more_opts = self._quality_args(acodec)
  434. # not os.path.splitext, since the latter does not work on unicode in all setups
  435. temp_path = new_path = f'{path.rpartition(".")[0]}.{extension}'
  436. if new_path == path:
  437. if acodec == 'copy':
  438. self.to_screen(f'Not converting audio {orig_path}; file is already in target format {target_format}')
  439. return [], information
  440. orig_path = prepend_extension(path, 'orig')
  441. temp_path = prepend_extension(path, 'temp')
  442. if (self._nopostoverwrites and os.path.exists(encodeFilename(new_path))
  443. and os.path.exists(encodeFilename(orig_path))):
  444. self.to_screen('Post-process file %s exists, skipping' % new_path)
  445. return [], information
  446. self.to_screen(f'Destination: {new_path}')
  447. self.run_ffmpeg(path, temp_path, acodec, more_opts)
  448. os.replace(path, orig_path)
  449. os.replace(temp_path, new_path)
  450. information['filepath'] = new_path
  451. information['ext'] = extension
  452. # Try to update the date time for extracted audio file.
  453. if information.get('filetime') is not None:
  454. self.try_utime(
  455. new_path, time.time(), information['filetime'], errnote='Cannot update utime of audio file')
  456. return [orig_path], information
  457. class FFmpegVideoConvertorPP(FFmpegPostProcessor):
  458. SUPPORTED_EXTS = ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mka', 'ogg', *FFmpegExtractAudioPP.SUPPORTED_EXTS)
  459. FORMAT_RE = create_mapping_re(SUPPORTED_EXTS)
  460. _ACTION = 'converting'
  461. def __init__(self, downloader=None, preferedformat=None):
  462. super().__init__(downloader)
  463. self.mapping = preferedformat
  464. @staticmethod
  465. def _options(target_ext):
  466. yield from FFmpegPostProcessor.stream_copy_opts(False)
  467. if target_ext == 'avi':
  468. yield from ('-c:v', 'libxvid', '-vtag', 'XVID')
  469. @PostProcessor._restrict_to(images=False)
  470. def run(self, info):
  471. filename, source_ext = info['filepath'], info['ext'].lower()
  472. target_ext, _skip_msg = resolve_mapping(source_ext, self.mapping)
  473. if _skip_msg:
  474. self.to_screen(f'Not {self._ACTION} media file "{filename}"; {_skip_msg}')
  475. return [], info
  476. outpath = replace_extension(filename, target_ext, source_ext)
  477. self.to_screen(f'{self._ACTION.title()} video from {source_ext} to {target_ext}; Destination: {outpath}')
  478. self.run_ffmpeg(filename, outpath, self._options(target_ext))
  479. info['filepath'] = outpath
  480. info['format'] = info['ext'] = target_ext
  481. return [filename], info
  482. class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP):
  483. _ACTION = 'remuxing'
  484. @staticmethod
  485. def _options(target_ext):
  486. return FFmpegPostProcessor.stream_copy_opts()
  487. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  488. SUPPORTED_EXTS = ('mp4', 'mov', 'm4a', 'webm', 'mkv', 'mka')
  489. def __init__(self, downloader=None, already_have_subtitle=False):
  490. super().__init__(downloader)
  491. self._already_have_subtitle = already_have_subtitle
  492. @PostProcessor._restrict_to(images=False)
  493. def run(self, info):
  494. if info['ext'] not in self.SUPPORTED_EXTS:
  495. self.to_screen(f'Subtitles can only be embedded in {", ".join(self.SUPPORTED_EXTS)} files')
  496. return [], info
  497. subtitles = info.get('requested_subtitles')
  498. if not subtitles:
  499. self.to_screen('There aren\'t any subtitles to embed')
  500. return [], info
  501. filename = info['filepath']
  502. # Disabled temporarily. There needs to be a way to override this
  503. # in case of duration actually mismatching in extractor
  504. # See: https://github.com/yt-dlp/yt-dlp/issues/1870, https://github.com/yt-dlp/yt-dlp/issues/1385
  505. '''
  506. if info.get('duration') and not info.get('__real_download') and self._duration_mismatch(
  507. self._get_real_video_duration(filename, False), info['duration']):
  508. self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
  509. return [], info
  510. '''
  511. ext = info['ext']
  512. sub_langs, sub_names, sub_filenames = [], [], []
  513. webm_vtt_warn = False
  514. mp4_ass_warn = False
  515. for lang, sub_info in subtitles.items():
  516. if not os.path.exists(sub_info.get('filepath', '')):
  517. self.report_warning(f'Skipping embedding {lang} subtitle because the file is missing')
  518. continue
  519. sub_ext = sub_info['ext']
  520. if sub_ext == 'json':
  521. self.report_warning('JSON subtitles cannot be embedded')
  522. elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
  523. sub_langs.append(lang)
  524. sub_names.append(sub_info.get('name'))
  525. sub_filenames.append(sub_info['filepath'])
  526. else:
  527. if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
  528. webm_vtt_warn = True
  529. self.report_warning('Only WebVTT subtitles can be embedded in webm files')
  530. if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass':
  531. mp4_ass_warn = True
  532. self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
  533. if not sub_langs:
  534. return [], info
  535. input_files = [filename] + sub_filenames
  536. opts = [
  537. *self.stream_copy_opts(ext=info['ext']),
  538. # Don't copy the existing subtitles, we may be running the
  539. # postprocessor a second time
  540. '-map', '-0:s',
  541. ]
  542. for i, (lang, name) in enumerate(zip(sub_langs, sub_names)):
  543. opts.extend(['-map', '%d:0' % (i + 1)])
  544. lang_code = ISO639Utils.short2long(lang) or lang
  545. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  546. if name:
  547. opts.extend(['-metadata:s:s:%d' % i, 'handler_name=%s' % name,
  548. '-metadata:s:s:%d' % i, 'title=%s' % name])
  549. temp_filename = prepend_extension(filename, 'temp')
  550. self.to_screen('Embedding subtitles in "%s"' % filename)
  551. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  552. os.replace(temp_filename, filename)
  553. files_to_delete = [] if self._already_have_subtitle else sub_filenames
  554. return files_to_delete, info
  555. class FFmpegMetadataPP(FFmpegPostProcessor):
  556. def __init__(self, downloader, add_metadata=True, add_chapters=True, add_infojson='if_exists'):
  557. FFmpegPostProcessor.__init__(self, downloader)
  558. self._add_metadata = add_metadata
  559. self._add_chapters = add_chapters
  560. self._add_infojson = add_infojson
  561. @staticmethod
  562. def _options(target_ext):
  563. audio_only = target_ext == 'm4a'
  564. yield from FFmpegPostProcessor.stream_copy_opts(not audio_only)
  565. if audio_only:
  566. yield from ('-vn', '-acodec', 'copy')
  567. @PostProcessor._restrict_to(images=False)
  568. def run(self, info):
  569. filename, metadata_filename = info['filepath'], None
  570. files_to_delete, options = [], []
  571. if self._add_chapters and info.get('chapters'):
  572. metadata_filename = replace_extension(filename, 'meta')
  573. options.extend(self._get_chapter_opts(info['chapters'], metadata_filename))
  574. files_to_delete.append(metadata_filename)
  575. if self._add_metadata:
  576. options.extend(self._get_metadata_opts(info))
  577. if self._add_infojson:
  578. if info['ext'] in ('mkv', 'mka'):
  579. infojson_filename = info.get('infojson_filename')
  580. options.extend(self._get_infojson_opts(info, infojson_filename))
  581. if not infojson_filename:
  582. files_to_delete.append(info.get('infojson_filename'))
  583. elif self._add_infojson is True:
  584. self.to_screen('The info-json can only be attached to mkv/mka files')
  585. if not options:
  586. self.to_screen('There isn\'t any metadata to add')
  587. return [], info
  588. temp_filename = prepend_extension(filename, 'temp')
  589. self.to_screen('Adding metadata to "%s"' % filename)
  590. self.run_ffmpeg_multiple_files(
  591. (filename, metadata_filename), temp_filename,
  592. itertools.chain(self._options(info['ext']), *options))
  593. self._delete_downloaded_files(*files_to_delete)
  594. os.replace(temp_filename, filename)
  595. return [], info
  596. @staticmethod
  597. def _get_chapter_opts(chapters, metadata_filename):
  598. with open(metadata_filename, 'wt', encoding='utf-8') as f:
  599. def ffmpeg_escape(text):
  600. return re.sub(r'([\\=;#\n])', r'\\\1', text)
  601. metadata_file_content = ';FFMETADATA1\n'
  602. for chapter in chapters:
  603. metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
  604. metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
  605. metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
  606. chapter_title = chapter.get('title')
  607. if chapter_title:
  608. metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title)
  609. f.write(metadata_file_content)
  610. yield ('-map_metadata', '1')
  611. def _get_metadata_opts(self, info):
  612. meta_prefix = 'meta'
  613. metadata = collections.defaultdict(dict)
  614. def add(meta_list, info_list=None):
  615. value = next((
  616. str(info[key]) for key in [f'{meta_prefix}_'] + list(variadic(info_list or meta_list))
  617. if info.get(key) is not None), None)
  618. if value not in ('', None):
  619. value = value.replace('\0', '') # nul character cannot be passed in command line
  620. metadata['common'].update({meta_f: value for meta_f in variadic(meta_list)})
  621. # Info on media metadata/metadata supported by ffmpeg:
  622. # https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
  623. # https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
  624. # https://kodi.wiki/view/Video_file_tagging
  625. add('title', ('track', 'title'))
  626. add('date', 'upload_date')
  627. add(('description', 'synopsis'), 'description')
  628. add(('purl', 'comment'), 'webpage_url')
  629. add('track', 'track_number')
  630. add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
  631. add('genre')
  632. add('album')
  633. add('album_artist')
  634. add('disc', 'disc_number')
  635. add('show', 'series')
  636. add('season_number')
  637. add('episode_id', ('episode', 'episode_id'))
  638. add('episode_sort', 'episode_number')
  639. if 'embed-metadata' in self.get_param('compat_opts', []):
  640. add('comment', 'description')
  641. metadata['common'].pop('synopsis', None)
  642. meta_regex = rf'{re.escape(meta_prefix)}(?P<i>\d+)?_(?P<key>.+)'
  643. for key, value in info.items():
  644. mobj = re.fullmatch(meta_regex, key)
  645. if value is not None and mobj:
  646. metadata[mobj.group('i') or 'common'][mobj.group('key')] = value.replace('\0', '')
  647. # Write id3v1 metadata also since Windows Explorer can't handle id3v2 tags
  648. yield ('-write_id3v1', '1')
  649. for name, value in metadata['common'].items():
  650. yield ('-metadata', f'{name}={value}')
  651. stream_idx = 0
  652. for fmt in info.get('requested_formats') or []:
  653. stream_count = 2 if 'none' not in (fmt.get('vcodec'), fmt.get('acodec')) else 1
  654. lang = ISO639Utils.short2long(fmt.get('language') or '') or fmt.get('language')
  655. for i in range(stream_idx, stream_idx + stream_count):
  656. if lang:
  657. metadata[str(i)].setdefault('language', lang)
  658. for name, value in metadata[str(i)].items():
  659. yield (f'-metadata:s:{i}', f'{name}={value}')
  660. stream_idx += stream_count
  661. def _get_infojson_opts(self, info, infofn):
  662. if not infofn or not os.path.exists(infofn):
  663. if self._add_infojson is not True:
  664. return
  665. infofn = infofn or '%s.temp' % (
  666. self._downloader.prepare_filename(info, 'infojson')
  667. or replace_extension(self._downloader.prepare_filename(info), 'info.json', info['ext']))
  668. if not self._downloader._ensure_dir_exists(infofn):
  669. return
  670. self.write_debug(f'Writing info-json to: {infofn}')
  671. write_json_file(self._downloader.sanitize_info(info, self.get_param('clean_infojson', True)), infofn)
  672. info['infojson_filename'] = infofn
  673. old_stream, new_stream = self.get_stream_number(info['filepath'], ('tags', 'mimetype'), 'application/json')
  674. if old_stream is not None:
  675. yield ('-map', '-0:%d' % old_stream)
  676. new_stream -= 1
  677. yield (
  678. '-attach', infofn,
  679. f'-metadata:s:{new_stream}', 'mimetype=application/json',
  680. f'-metadata:s:{new_stream}', 'filename=info.json',
  681. )
  682. class FFmpegMergerPP(FFmpegPostProcessor):
  683. @PostProcessor._restrict_to(images=False)
  684. def run(self, info):
  685. filename = info['filepath']
  686. temp_filename = prepend_extension(filename, 'temp')
  687. args = ['-c', 'copy']
  688. audio_streams = 0
  689. for (i, fmt) in enumerate(info['requested_formats']):
  690. if fmt.get('acodec') != 'none':
  691. args.extend(['-map', f'{i}:a:0'])
  692. aac_fixup = fmt['protocol'].startswith('m3u8') and self.get_audio_codec(fmt['filepath']) == 'aac'
  693. if aac_fixup:
  694. args.extend([f'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
  695. audio_streams += 1
  696. if fmt.get('vcodec') != 'none':
  697. args.extend(['-map', '%u:v:0' % (i)])
  698. self.to_screen('Merging formats into "%s"' % filename)
  699. self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
  700. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  701. return info['__files_to_merge'], info
  702. def can_merge(self):
  703. # TODO: figure out merge-capable ffmpeg version
  704. if self.basename != 'avconv':
  705. return True
  706. required_version = '10-0'
  707. if is_outdated_version(
  708. self._versions[self.basename], required_version):
  709. warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
  710. 'yt-dlp will download single file media. '
  711. 'Update %s to version %s or newer to fix this.') % (
  712. self.basename, self.basename, required_version)
  713. self.report_warning(warning)
  714. return False
  715. return True
  716. class FFmpegFixupPostProcessor(FFmpegPostProcessor):
  717. def _fixup(self, msg, filename, options):
  718. temp_filename = prepend_extension(filename, 'temp')
  719. self.to_screen(f'{msg} of "{filename}"')
  720. self.run_ffmpeg(filename, temp_filename, options)
  721. os.replace(temp_filename, filename)
  722. class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor):
  723. @PostProcessor._restrict_to(images=False, audio=False)
  724. def run(self, info):
  725. stretched_ratio = info.get('stretched_ratio')
  726. if stretched_ratio not in (None, 1):
  727. self._fixup('Fixing aspect ratio', info['filepath'], [
  728. *self.stream_copy_opts(), '-aspect', '%f' % stretched_ratio])
  729. return [], info
  730. class FFmpegFixupM4aPP(FFmpegFixupPostProcessor):
  731. @PostProcessor._restrict_to(images=False, video=False)
  732. def run(self, info):
  733. if info.get('container') == 'm4a_dash':
  734. self._fixup('Correcting container', info['filepath'], [*self.stream_copy_opts(), '-f', 'mp4'])
  735. return [], info
  736. class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor):
  737. def _needs_fixup(self, info):
  738. yield info['ext'] in ('mp4', 'm4a')
  739. yield info['protocol'].startswith('m3u8')
  740. try:
  741. metadata = self.get_metadata_object(info['filepath'])
  742. except PostProcessingError as e:
  743. self.report_warning(f'Unable to extract metadata: {e.msg}')
  744. yield True
  745. else:
  746. yield traverse_obj(metadata, ('format', 'format_name'), casesense=False) == 'mpegts'
  747. @PostProcessor._restrict_to(images=False)
  748. def run(self, info):
  749. if all(self._needs_fixup(info)):
  750. self._fixup('Fixing MPEG-TS in MP4 container', info['filepath'], [
  751. *self.stream_copy_opts(), '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'])
  752. return [], info
  753. class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor):
  754. def __init__(self, downloader=None, trim=0.001):
  755. # "trim" should be used when the video contains unintended packets
  756. super().__init__(downloader)
  757. assert isinstance(trim, (int, float))
  758. self.trim = str(trim)
  759. @PostProcessor._restrict_to(images=False)
  760. def run(self, info):
  761. if not self._features.get('setts'):
  762. self.report_warning(
  763. 'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
  764. 'Please install ffmpeg 4.4 or later to fixup without re-encoding')
  765. opts = ['-vf', 'setpts=PTS-STARTPTS']
  766. else:
  767. opts = ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
  768. self._fixup('Fixing frame timestamp', info['filepath'], opts + [*self.stream_copy_opts(False), '-ss', self.trim])
  769. return [], info
  770. class FFmpegCopyStreamPP(FFmpegFixupPostProcessor):
  771. MESSAGE = 'Copying stream'
  772. @PostProcessor._restrict_to(images=False)
  773. def run(self, info):
  774. self._fixup(self.MESSAGE, info['filepath'], self.stream_copy_opts())
  775. return [], info
  776. class FFmpegFixupDurationPP(FFmpegCopyStreamPP):
  777. MESSAGE = 'Fixing video duration'
  778. class FFmpegFixupDuplicateMoovPP(FFmpegCopyStreamPP):
  779. MESSAGE = 'Fixing duplicate MOOV atoms'
  780. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  781. SUPPORTED_EXTS = ('srt', 'vtt', 'ass', 'lrc')
  782. def __init__(self, downloader=None, format=None):
  783. super().__init__(downloader)
  784. self.format = format
  785. def run(self, info):
  786. subs = info.get('requested_subtitles')
  787. new_ext = self.format
  788. new_format = new_ext
  789. if new_format == 'vtt':
  790. new_format = 'webvtt'
  791. if subs is None:
  792. self.to_screen('There aren\'t any subtitles to convert')
  793. return [], info
  794. self.to_screen('Converting subtitles')
  795. sub_filenames = []
  796. for lang, sub in subs.items():
  797. if not os.path.exists(sub.get('filepath', '')):
  798. self.report_warning(f'Skipping embedding {lang} subtitle because the file is missing')
  799. continue
  800. ext = sub['ext']
  801. if ext == new_ext:
  802. self.to_screen('Subtitle file for %s is already in the requested format' % new_ext)
  803. continue
  804. elif ext == 'json':
  805. self.to_screen(
  806. 'You have requested to convert json subtitles into another format, '
  807. 'which is currently not possible')
  808. continue
  809. old_file = sub['filepath']
  810. sub_filenames.append(old_file)
  811. new_file = replace_extension(old_file, new_ext)
  812. if ext in ('dfxp', 'ttml', 'tt'):
  813. self.report_warning(
  814. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  815. 'which results in style information loss')
  816. dfxp_file = old_file
  817. srt_file = replace_extension(old_file, 'srt')
  818. with open(dfxp_file, 'rb') as f:
  819. srt_data = dfxp2srt(f.read())
  820. with open(srt_file, 'wt', encoding='utf-8') as f:
  821. f.write(srt_data)
  822. old_file = srt_file
  823. subs[lang] = {
  824. 'ext': 'srt',
  825. 'data': srt_data,
  826. 'filepath': srt_file,
  827. }
  828. if new_ext == 'srt':
  829. continue
  830. else:
  831. sub_filenames.append(srt_file)
  832. self.run_ffmpeg(old_file, new_file, ['-f', new_format])
  833. with open(new_file, encoding='utf-8') as f:
  834. subs[lang] = {
  835. 'ext': new_ext,
  836. 'data': f.read(),
  837. 'filepath': new_file,
  838. }
  839. info['__files_to_move'][new_file] = replace_extension(
  840. info['__files_to_move'][sub['filepath']], new_ext)
  841. return sub_filenames, info
  842. class FFmpegSplitChaptersPP(FFmpegPostProcessor):
  843. def __init__(self, downloader, force_keyframes=False):
  844. FFmpegPostProcessor.__init__(self, downloader)
  845. self._force_keyframes = force_keyframes
  846. def _prepare_filename(self, number, chapter, info):
  847. info = info.copy()
  848. info.update({
  849. 'section_number': number,
  850. 'section_title': chapter.get('title'),
  851. 'section_start': chapter.get('start_time'),
  852. 'section_end': chapter.get('end_time'),
  853. })
  854. return self._downloader.prepare_filename(info, 'chapter')
  855. def _ffmpeg_args_for_chapter(self, number, chapter, info):
  856. destination = self._prepare_filename(number, chapter, info)
  857. if not self._downloader._ensure_dir_exists(encodeFilename(destination)):
  858. return
  859. chapter['filepath'] = destination
  860. self.to_screen('Chapter %03d; Destination: %s' % (number, destination))
  861. return (
  862. destination,
  863. ['-ss', str(chapter['start_time']),
  864. '-t', str(chapter['end_time'] - chapter['start_time'])])
  865. @PostProcessor._restrict_to(images=False)
  866. def run(self, info):
  867. chapters = info.get('chapters') or []
  868. if not chapters:
  869. self.to_screen('Chapter information is unavailable')
  870. return [], info
  871. in_file = info['filepath']
  872. if self._force_keyframes and len(chapters) > 1:
  873. in_file = self.force_keyframes(in_file, (c['start_time'] for c in chapters))
  874. self.to_screen('Splitting video by chapters; %d chapters found' % len(chapters))
  875. for idx, chapter in enumerate(chapters):
  876. destination, opts = self._ffmpeg_args_for_chapter(idx + 1, chapter, info)
  877. self.real_run_ffmpeg([(in_file, opts)], [(destination, self.stream_copy_opts())])
  878. if in_file != info['filepath']:
  879. self._delete_downloaded_files(in_file, msg=None)
  880. return [], info
  881. class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor):
  882. SUPPORTED_EXTS = ('jpg', 'png', 'webp')
  883. FORMAT_RE = create_mapping_re(SUPPORTED_EXTS)
  884. def __init__(self, downloader=None, format=None):
  885. super().__init__(downloader)
  886. self.mapping = format
  887. @classmethod
  888. def is_webp(cls, path):
  889. write_string(f'DeprecationWarning: {cls.__module__}.{cls.__name__}.is_webp is deprecated')
  890. return imghdr.what(path) == 'webp'
  891. def fixup_webp(self, info, idx=-1):
  892. thumbnail_filename = info['thumbnails'][idx]['filepath']
  893. _, thumbnail_ext = os.path.splitext(thumbnail_filename)
  894. if thumbnail_ext:
  895. if thumbnail_ext.lower() != '.webp' and imghdr.what(thumbnail_filename) == 'webp':
  896. self.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename)
  897. webp_filename = replace_extension(thumbnail_filename, 'webp')
  898. os.replace(thumbnail_filename, webp_filename)
  899. info['thumbnails'][idx]['filepath'] = webp_filename
  900. info['__files_to_move'][webp_filename] = replace_extension(
  901. info['__files_to_move'].pop(thumbnail_filename), 'webp')
  902. @staticmethod
  903. def _options(target_ext):
  904. if target_ext == 'jpg':
  905. return ['-bsf:v', 'mjpeg2jpeg']
  906. return []
  907. def convert_thumbnail(self, thumbnail_filename, target_ext):
  908. thumbnail_conv_filename = replace_extension(thumbnail_filename, target_ext)
  909. self.to_screen(f'Converting thumbnail "{thumbnail_filename}" to {target_ext}')
  910. self.real_run_ffmpeg(
  911. [(thumbnail_filename, ['-f', 'image2', '-pattern_type', 'none'])],
  912. [(thumbnail_conv_filename.replace('%', '%%'), self._options(target_ext))])
  913. return thumbnail_conv_filename
  914. def run(self, info):
  915. files_to_delete = []
  916. has_thumbnail = False
  917. for idx, thumbnail_dict in enumerate(info.get('thumbnails') or []):
  918. original_thumbnail = thumbnail_dict.get('filepath')
  919. if not original_thumbnail:
  920. continue
  921. has_thumbnail = True
  922. self.fixup_webp(info, idx)
  923. thumbnail_ext = os.path.splitext(original_thumbnail)[1][1:].lower()
  924. if thumbnail_ext == 'jpeg':
  925. thumbnail_ext = 'jpg'
  926. target_ext, _skip_msg = resolve_mapping(thumbnail_ext, self.mapping)
  927. if _skip_msg:
  928. self.to_screen(f'Not converting thumbnail "{original_thumbnail}"; {_skip_msg}')
  929. continue
  930. thumbnail_dict['filepath'] = self.convert_thumbnail(original_thumbnail, target_ext)
  931. files_to_delete.append(original_thumbnail)
  932. info['__files_to_move'][thumbnail_dict['filepath']] = replace_extension(
  933. info['__files_to_move'][original_thumbnail], target_ext)
  934. if not has_thumbnail:
  935. self.to_screen('There aren\'t any thumbnails to convert')
  936. return files_to_delete, info
  937. class FFmpegConcatPP(FFmpegPostProcessor):
  938. def __init__(self, downloader, only_multi_video=False):
  939. self._only_multi_video = only_multi_video
  940. super().__init__(downloader)
  941. def _get_codecs(self, file):
  942. codecs = traverse_obj(self.get_metadata_object(file), ('streams', ..., 'codec_name'))
  943. self.write_debug(f'Codecs = {", ".join(codecs)}')
  944. return tuple(codecs)
  945. def concat_files(self, in_files, out_file):
  946. if not self._downloader._ensure_dir_exists(out_file):
  947. return
  948. if len(in_files) == 1:
  949. if os.path.realpath(in_files[0]) != os.path.realpath(out_file):
  950. self.to_screen(f'Moving "{in_files[0]}" to "{out_file}"')
  951. os.replace(in_files[0], out_file)
  952. return []
  953. if len(set(map(self._get_codecs, in_files))) > 1:
  954. raise PostProcessingError(
  955. 'The files have different streams/codecs and cannot be concatenated. '
  956. 'Either select different formats or --recode-video them to a common format')
  957. self.to_screen(f'Concatenating {len(in_files)} files; Destination: {out_file}')
  958. super().concat_files(in_files, out_file)
  959. return in_files
  960. @PostProcessor._restrict_to(images=False, simulated=False)
  961. def run(self, info):
  962. entries = info.get('entries') or []
  963. if not any(entries) or (self._only_multi_video and info['_type'] != 'multi_video'):
  964. return [], info
  965. elif traverse_obj(entries, (..., lambda k, v: k == 'requested_downloads' and len(v) > 1)):
  966. raise PostProcessingError('Concatenation is not supported when downloading multiple separate formats')
  967. in_files = traverse_obj(entries, (..., 'requested_downloads', 0, 'filepath')) or []
  968. if len(in_files) < len(entries):
  969. raise PostProcessingError('Aborting concatenation because some downloads failed')
  970. exts = traverse_obj(entries, (..., 'requested_downloads', 0, 'ext'), (..., 'ext'))
  971. ie_copy = collections.ChainMap({'ext': exts[0] if len(set(exts)) == 1 else 'mkv'},
  972. info, self._downloader._playlist_infodict(info))
  973. out_file = self._downloader.prepare_filename(ie_copy, 'pl_video')
  974. files_to_delete = self.concat_files(in_files, out_file)
  975. info['requested_downloads'] = [{
  976. 'filepath': out_file,
  977. 'ext': ie_copy['ext'],
  978. }]
  979. return files_to_delete, info