ffmpeg.py 48 KB

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