ffmpeg.py 48 KB

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