AvifImagePlugin.py 9.2 KB

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