AvifImagePlugin.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. from __future__ import annotations
  2. import os
  3. from io import BytesIO
  4. from typing import IO
  5. from . import ExifTags, Image, ImageFile
  6. try:
  7. from . import _avif
  8. SUPPORTED = True
  9. except ImportError:
  10. SUPPORTED = False
  11. # Decoder options as module globals, until there is a way to pass parameters
  12. # to Image.open (see https://github.com/python-pillow/Pillow/issues/569)
  13. DECODE_CODEC_CHOICE = "auto"
  14. DEFAULT_MAX_THREADS = 0
  15. def get_codec_version(codec_name: str) -> str | None:
  16. versions = _avif.codec_versions()
  17. for version in versions.split(", "):
  18. if version.split(" [")[0] == codec_name:
  19. return version.split(":")[-1].split(" ")[0]
  20. return None
  21. def _accept(prefix: bytes) -> bool | str:
  22. if prefix[4:8] != b"ftyp":
  23. return False
  24. major_brand = prefix[8:12]
  25. if major_brand in (
  26. # coding brands
  27. b"avif",
  28. b"avis",
  29. # We accept files with AVIF container brands; we can't yet know if
  30. # the ftyp box has the correct compatible brands, but if it doesn't
  31. # then the plugin will raise a SyntaxError which Pillow will catch
  32. # before moving on to the next plugin that accepts the file.
  33. #
  34. # Also, because this file might not actually be an AVIF file, we
  35. # don't raise an error if AVIF support isn't properly compiled.
  36. b"mif1",
  37. b"msf1",
  38. ):
  39. if not SUPPORTED:
  40. return (
  41. "image file could not be identified because AVIF support not installed"
  42. )
  43. return True
  44. return False
  45. def _get_default_max_threads() -> int:
  46. if DEFAULT_MAX_THREADS:
  47. return DEFAULT_MAX_THREADS
  48. if hasattr(os, "sched_getaffinity"):
  49. return len(os.sched_getaffinity(0))
  50. else:
  51. return os.cpu_count() or 1
  52. class AvifImageFile(ImageFile.ImageFile):
  53. format = "AVIF"
  54. format_description = "AVIF image"
  55. __frame = -1
  56. def _open(self) -> None:
  57. if not SUPPORTED:
  58. msg = "image file could not be opened because AVIF support not installed"
  59. raise SyntaxError(msg)
  60. if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available(
  61. DECODE_CODEC_CHOICE
  62. ):
  63. msg = "Invalid opening codec"
  64. raise ValueError(msg)
  65. self._decoder = _avif.AvifDecoder(
  66. self.fp.read(),
  67. DECODE_CODEC_CHOICE,
  68. _get_default_max_threads(),
  69. )
  70. # Get info from decoder
  71. self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = (
  72. self._decoder.get_info()
  73. )
  74. self.is_animated = self.n_frames > 1
  75. if icc:
  76. self.info["icc_profile"] = icc
  77. if xmp:
  78. self.info["xmp"] = xmp
  79. if exif_orientation != 1 or exif:
  80. exif_data = Image.Exif()
  81. if exif:
  82. exif_data.load(exif)
  83. original_orientation = exif_data.get(ExifTags.Base.Orientation, 1)
  84. else:
  85. original_orientation = 1
  86. if exif_orientation != original_orientation:
  87. exif_data[ExifTags.Base.Orientation] = exif_orientation
  88. exif = exif_data.tobytes()
  89. if exif:
  90. self.info["exif"] = exif
  91. self.seek(0)
  92. def seek(self, frame: int) -> None:
  93. if not self._seek_check(frame):
  94. return
  95. # Set tile
  96. self.__frame = frame
  97. self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)]
  98. def load(self) -> Image.core.PixelAccess | None:
  99. if self.tile:
  100. # We need to load the image data for this frame
  101. data, timescale, pts_in_timescales, duration_in_timescales = (
  102. self._decoder.get_frame(self.__frame)
  103. )
  104. self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale))
  105. self.info["duration"] = round(1000 * (duration_in_timescales / timescale))
  106. if self.fp and self._exclusive_fp:
  107. self.fp.close()
  108. self.fp = BytesIO(data)
  109. return super().load()
  110. def load_seek(self, pos: int) -> None:
  111. pass
  112. def tell(self) -> int:
  113. return self.__frame
  114. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  115. _save(im, fp, filename, save_all=True)
  116. def _save(
  117. im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
  118. ) -> None:
  119. info = im.encoderinfo.copy()
  120. if save_all:
  121. append_images = list(info.get("append_images", []))
  122. else:
  123. append_images = []
  124. total = 0
  125. for ims in [im] + append_images:
  126. total += getattr(ims, "n_frames", 1)
  127. quality = info.get("quality", 75)
  128. if not isinstance(quality, int) or quality < 0 or quality > 100:
  129. msg = "Invalid quality setting"
  130. raise ValueError(msg)
  131. duration = info.get("duration", 0)
  132. subsampling = info.get("subsampling", "4:2:0")
  133. speed = info.get("speed", 6)
  134. max_threads = info.get("max_threads", _get_default_max_threads())
  135. codec = info.get("codec", "auto")
  136. if codec != "auto" and not _avif.encoder_codec_available(codec):
  137. msg = "Invalid saving codec"
  138. raise ValueError(msg)
  139. range_ = info.get("range", "full")
  140. tile_rows_log2 = info.get("tile_rows", 0)
  141. tile_cols_log2 = info.get("tile_cols", 0)
  142. alpha_premultiplied = bool(info.get("alpha_premultiplied", False))
  143. autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0))
  144. icc_profile = info.get("icc_profile", im.info.get("icc_profile"))
  145. exif_orientation = 1
  146. if exif := info.get("exif"):
  147. if isinstance(exif, Image.Exif):
  148. exif_data = exif
  149. else:
  150. exif_data = Image.Exif()
  151. exif_data.load(exif)
  152. if ExifTags.Base.Orientation in exif_data:
  153. exif_orientation = exif_data.pop(ExifTags.Base.Orientation)
  154. exif = exif_data.tobytes() if exif_data else b""
  155. elif isinstance(exif, Image.Exif):
  156. exif = exif_data.tobytes()
  157. xmp = info.get("xmp")
  158. if isinstance(xmp, str):
  159. xmp = xmp.encode("utf-8")
  160. advanced = info.get("advanced")
  161. if advanced is not None:
  162. if isinstance(advanced, dict):
  163. advanced = advanced.items()
  164. try:
  165. advanced = tuple(advanced)
  166. except TypeError:
  167. invalid = True
  168. else:
  169. invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced)
  170. if invalid:
  171. msg = (
  172. "advanced codec options must be a dict of key-value string "
  173. "pairs or a series of key-value two-tuples"
  174. )
  175. raise ValueError(msg)
  176. # Setup the AVIF encoder
  177. enc = _avif.AvifEncoder(
  178. im.size,
  179. subsampling,
  180. quality,
  181. speed,
  182. max_threads,
  183. codec,
  184. range_,
  185. tile_rows_log2,
  186. tile_cols_log2,
  187. alpha_premultiplied,
  188. autotiling,
  189. icc_profile or b"",
  190. exif or b"",
  191. exif_orientation,
  192. xmp or b"",
  193. advanced,
  194. )
  195. # Add each frame
  196. frame_idx = 0
  197. frame_duration = 0
  198. cur_idx = im.tell()
  199. is_single_frame = total == 1
  200. try:
  201. for ims in [im] + append_images:
  202. # Get number of frames in this image
  203. nfr = getattr(ims, "n_frames", 1)
  204. for idx in range(nfr):
  205. ims.seek(idx)
  206. # Make sure image mode is supported
  207. frame = ims
  208. rawmode = ims.mode
  209. if ims.mode not in {"RGB", "RGBA"}:
  210. rawmode = "RGBA" if ims.has_transparency_data else "RGB"
  211. frame = ims.convert(rawmode)
  212. # Update frame duration
  213. if isinstance(duration, (list, tuple)):
  214. frame_duration = duration[frame_idx]
  215. else:
  216. frame_duration = duration
  217. # Append the frame to the animation encoder
  218. enc.add(
  219. frame.tobytes("raw", rawmode),
  220. frame_duration,
  221. frame.size,
  222. rawmode,
  223. is_single_frame,
  224. )
  225. # Update frame index
  226. frame_idx += 1
  227. if not save_all:
  228. break
  229. finally:
  230. im.seek(cur_idx)
  231. # Get the final output from the encoder
  232. data = enc.finish()
  233. if data is None:
  234. msg = "cannot write file as AVIF (encoder returned None)"
  235. raise OSError(msg)
  236. fp.write(data)
  237. Image.register_open(AvifImageFile.format, AvifImageFile, _accept)
  238. if SUPPORTED:
  239. Image.register_save(AvifImageFile.format, _save)
  240. Image.register_save_all(AvifImageFile.format, _save_all)
  241. Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"])
  242. Image.register_mime(AvifImageFile.format, "image/avif")