impak
impak – space-efficient image collection format based on pixel-diff patches.
Quick start
Pack a folder of PNG variants into a single file:
import impak
with impak.create("variants.impak", mode="vs_first") as w:
for path in sorted(Path("frames/").glob("*.png")):
w.add(path, name=path.stem)
Read them back:
with impak.open("variants.impak") as r:
print(r.info()) # human-readable summary
img = r[0] # PIL Image, by index
img = r["frame_01"] # by name
for img in r: # iterate all
img.show()
Diff modes
| Mode | Description |
|---|---|
lto (default) |
Each frame searches all prior frames and picks the best reference (smallest patch payload), forming a DAG of deltas. A keyframe is stored when it's smaller than the best delta. Params: lto_candidates (default 6), max_ref_depth (default 8). |
vs_first |
Every frame is a patch against frame 0. |
vs_prior |
Every frame is a patch against the immediately prior frame. |
keyframe |
Like vs_prior but stores a full image every K frames. Param: keyframe_interval (default 10). |
manual |
User-designated baselines are stored first and searched before each content frame. Params: baselines (required), fallback_mode (default vs_prior). |
Example:
with impak.create(
"out.impak",
mode="manual",
baselines=["day_bg.png", "night_bg.png"],
fallback_mode="vs_prior",
) as w:
for path in content_frames:
w.add(path)
1""" 2impak – space-efficient image collection format based on pixel-diff patches. 3 4Quick start 5----------- 6Pack a folder of PNG variants into a single file: 7 8 import impak 9 10 with impak.create("variants.impak", mode="vs_first") as w: 11 for path in sorted(Path("frames/").glob("*.png")): 12 w.add(path, name=path.stem) 13 14Read them back: 15 16 with impak.open("variants.impak") as r: 17 print(r.info()) # human-readable summary 18 img = r[0] # PIL Image, by index 19 img = r["frame_01"] # by name 20 for img in r: # iterate all 21 img.show() 22 23Diff modes 24---------- 25| Mode | Description | 26|------|-------------| 27| ``lto`` *(default)* | Each frame searches all prior frames and picks the best reference (smallest patch payload), forming a DAG of deltas. A keyframe is stored when it's smaller than the best delta. Params: ``lto_candidates`` (default 6), ``max_ref_depth`` (default 8). | 28| ``vs_first`` | Every frame is a patch against frame 0. | 29| ``vs_prior`` | Every frame is a patch against the immediately prior frame. | 30| ``keyframe`` | Like ``vs_prior`` but stores a full image every K frames. Param: ``keyframe_interval`` (default 10). | 31| ``manual`` | User-designated baselines are stored first and searched before each content frame. Params: ``baselines`` (required), ``fallback_mode`` (default ``vs_prior``). | 32 33 Example: 34 35 with impak.create( 36 "out.impak", 37 mode="manual", 38 baselines=["day_bg.png", "night_bg.png"], 39 fallback_mode="vs_prior", 40 ) as w: 41 for path in content_frames: 42 w.add(path) 43 44""" 45 46from .decoder import ImpakReader 47from .differ import reconstruct 48 49try: 50 from .encoder import ImpakWriter 51 from .differ import compute_patches, similarity_score 52except ImportError: 53 ImpakWriter = None # type: ignore 54 compute_patches = None # type: ignore 55 similarity_score = None # type: ignore 56 57 58def create(path, mode="lto", **kwargs) -> "ImpakWriter": 59 """ 60 Parameters 61 ---------- 62 path : file path (str or Path) 63 mode : "vs_first" | "vs_prior" | "keyframe" | "lto" | "manual" 64 codec : "png" or "webp" (default) 65 quality : 0-100. 100 = lossless for both codecs. 66 Values <100 enable lossy WebP (smaller, not pixel-perfect). 67 keyframe_interval : (keyframe mode) full image every N frames (default 10) 68 threshold : pixel delta threshold 0-255 (default 4) 69 tile_size : diff grid tile size in px (default 32) 70 merge_gap : merge adjacent changed tiles within N px (default 8) 71 auto_keyframe_sim : force keyframe when similarity drops below this (default 0.5) 72 lto_candidates : (lto / manual mode) how many top-similarity frames to 73 fully probe (default 6) 74 max_ref_depth : (lto mode) max decode-chain depth before forcing a keyframe 75 (default 8) 76 baselines : (manual mode, required) list of PIL Images or file paths 77 stored as pinned keyframes at the start of the file; 78 every content frame is diffed against these first. 79 fallback_mode : (manual mode) strategy used when no baseline wins; 80 one of "vs_first", "vs_prior", "keyframe", "lto" 81 (default "vs_prior") 82 """ 83 if ImpakWriter is None: 84 raise ImportError( 85 "Encoding requires the 'encoder' extra: pip install impak[encoder]" 86 ) 87 return ImpakWriter(path, mode=mode, **kwargs) 88 89 90def open(path, low_ram_mode=False, cache_size=None, **kwargs) -> ImpakReader: 91 return ImpakReader( 92 path, 93 low_ram_mode=low_ram_mode, 94 cache_size=cache_size, 95 **kwargs, 96 ) 97 98 99__all__ = [ 100 "open", 101 "ImpakReader", 102 "reconstruct", 103] 104if ImpakWriter is not None: 105 __all__ += ["create", "ImpakWriter", "compute_patches", "similarity_score"] 106 107__version__ = "1.0.0"
49class ImpakReader: 50 """ 51 Random-access reader for .impak collections. 52 53 The file index is read at open time (small); pixel data is lazy-loaded 54 per frame request. 55 56 In manual-mode files the leading baseline keyframes are automatically 57 detected (via their {"_baseline": true} metadata) and excluded from all 58 public-facing operations. They are still used internally when decoding 59 delta frames that reference them. 60 """ 61 62 def __init__( 63 self, 64 path: Union[str, Path], 65 low_ram_mode: bool = False, 66 cache_size: Optional[int] = None, 67 ): 68 self.path = Path(path) 69 self._fh = open(self.path, "rb") 70 self._header: dict = {} 71 self._index: list[dict] = [] 72 self._name_map: dict[str, int] = {} # name → content_id 73 self._meta_cache: dict[int, dict] = {} 74 75 self.low_ram_mode = low_ram_mode 76 if cache_size is None: 77 cache_size = 2 if low_ram_mode else 0 78 self.cache_size = max(0, cache_size) 79 80 # abs_id -> Image.Image 81 # normal mode: unlimited dict-like cache 82 # low_ram_mode: bounded LRU cache 83 self._decode_cache: "OrderedDict[int, Image.Image]" = OrderedDict() 84 85 self._read_header() 86 self._read_index() 87 88 self._baseline_count: int = self._detect_baseline_count() 89 90 def __enter__(self): 91 return self 92 93 def __exit__(self, *_): 94 self.close() 95 96 def close(self): 97 if self._fh and not self._fh.closed: 98 self._fh.close() 99 100 def __len__(self) -> int: 101 """Number of content frames (baseline frames are not counted).""" 102 return self._header["frame_count"] - self._baseline_count 103 104 def __getitem__(self, key: Union[int, str]) -> Image.Image: 105 """ 106 Retrieve a content frame by index or name. 107 108 Integer indices are relative to content frames only (0 = first content 109 frame, regardless of how many baselines precede it). 110 """ 111 if isinstance(key, str): 112 self._build_name_map() 113 if key not in self._name_map: 114 raise KeyError(f"Frame name '{key}' not found in collection") 115 abs_id = self._name_map[key] 116 return self._decode_frame(abs_id) 117 118 if key < 0: 119 key = len(self) + key 120 if not (0 <= key < len(self)): 121 raise IndexError(f"Frame index {key} out of range (0..{len(self)-1})") 122 return self._decode_frame(self._content_to_abs(key)) 123 124 def __iter__(self) -> Iterator[Image.Image]: 125 for i in range(len(self)): 126 yield self._decode_frame(self._content_to_abs(i)) 127 128 def _cache_get(self, abs_id: int) -> Optional[Image.Image]: 129 img = self._decode_cache.get(abs_id) 130 if img is None: 131 return None 132 # LRU touch 133 self._decode_cache.move_to_end(abs_id) 134 return img.copy() 135 136 def _cache_put(self, abs_id: int, img: Image.Image) -> None: 137 if self.cache_size == 0: 138 return 139 140 self._decode_cache[abs_id] = img.copy() 141 self._decode_cache.move_to_end(abs_id) 142 143 if self.low_ram_mode: 144 while len(self._decode_cache) > self.cache_size: 145 self._decode_cache.popitem(last=False) 146 147 def get_metadata(self, frame_id: int) -> dict: 148 """ 149 Return the metadata dict for a content frame by content index. 150 """ 151 return self._read_metadata(self._content_to_abs(frame_id)) 152 153 def info(self) -> str: 154 """Human-readable summary of the collection.""" 155 h = self._header 156 mode_name = MODE_NAMES.get(h["diff_mode"], "unknown") 157 codec_name = CODEC_NAMES.get(h.get("codec", 0), "png") 158 quality = h.get("quality", 100) 159 quality_str = "lossless" if quality == 100 else f"quality={quality}" 160 total_bytes = self.path.stat().st_size 161 n_content = len(self) 162 lines = [ 163 f"File : {self.path}", 164 f"Format : impak v{h['version']}", 165 f"Diff : {mode_name}", 166 f"Codec : {codec_name} ({quality_str})", 167 f"Canvas : {h['width']} × {h['height']} px", 168 f"Frames : {n_content}" 169 + (f" ({self._baseline_count} hidden baseline(s))" if self._baseline_count else ""), 170 f"Size : {total_bytes:,} bytes ({total_bytes/1024:.1f} KB)", 171 "", 172 ] 173 174 frame_sizes = {self._frame_size(self._content_to_abs(i)) for i in range(n_content)} 175 mixed_sizes = len(frame_sizes) > 1 176 177 if mixed_sizes: 178 lines += [ 179 f"{'ID':>4} {'Type':>9} {'Ref':>4} {'Patches':>7} {'Bytes':>9} {'Size':>11} Name", 180 "─" * 72, 181 ] 182 else: 183 lines += [ 184 f"{'ID':>4} {'Type':>9} {'Ref':>4} {'Patches':>7} {'Bytes':>9} Name", 185 "─" * 64, 186 ] 187 188 for content_id in range(n_content): 189 abs_id = self._content_to_abs(content_id) 190 entry = self._index[abs_id] 191 ftype = "keyframe" if entry["frame_type"] == FRAME_KEYFRAME else "delta" 192 ref_abs = entry["ref_frame_id"] 193 if entry["frame_type"] == FRAME_DELTA: 194 if ref_abs < self._baseline_count: 195 ref = f"B{ref_abs}" 196 else: 197 ref = str(ref_abs - self._baseline_count) 198 else: 199 ref = "self" 200 data_bytes = self._frame_data_size(abs_id) 201 meta = self._read_metadata(abs_id) 202 name = meta.get("name", "") 203 if mixed_sizes: 204 fw, fh = self._frame_size(abs_id) 205 size_str = f"{fw}×{fh}" 206 lines.append( 207 f"{content_id:>4} {ftype:>9} {ref:>4} " 208 f"{entry['patch_count']:>7} {data_bytes:>9,} {size_str:>11} {name}" 209 ) 210 else: 211 lines.append( 212 f"{content_id:>4} {ftype:>9} {ref:>4} " 213 f"{entry['patch_count']:>7} {data_bytes:>9,} {name}" 214 ) 215 return "\n".join(lines) 216 217 def diff_map(self, frame_id: int) -> list[tuple[int, int, int, int]]: 218 """ 219 Return the (x, y, w, h) patch rectangles for a content frame. 220 *frame_id* is a content-visible index. 221 """ 222 abs_id = self._content_to_abs(frame_id) 223 entry = self._index[abs_id] 224 if entry["frame_type"] == FRAME_KEYFRAME: 225 w, h = self._frame_size(abs_id) 226 return [(0, 0, w, h)] 227 patches = self._read_patches(abs_id) 228 return [(x, y, w, h) for (x, y, w, h, _) in patches] 229 230 @property 231 def canvas_size(self) -> tuple[int, int]: 232 return self._header["width"], self._header["height"] 233 234 @property 235 def mode(self) -> str: 236 return MODE_NAMES.get(self._header["diff_mode"], "unknown") 237 238 @property 239 def baseline_count(self) -> int: 240 """Number of hidden baseline frames (0 for non-manual files).""" 241 return self._baseline_count 242 243 def _frame_size(self, abs_id: int) -> tuple[int, int]: 244 """ 245 Return (width, height) for a frame. 246 247 For files written with multi-size support the per-frame size is stored 248 in JSON metadata under "_size". For older single-size files (or frames 249 that pre-date the feature) we fall back to the global canvas dimensions. 250 """ 251 meta = self._read_metadata(abs_id) 252 if "_size" in meta: 253 return tuple(meta["_size"]) 254 return self._header["width"], self._header["height"] 255 256 def _content_to_abs(self, content_id: int) -> int: 257 """Convert a public content index to an absolute frame index.""" 258 return content_id + self._baseline_count 259 260 def _decode_frame(self, abs_id: int, _memo: Optional[dict[int, Image.Image]] = None) -> Image.Image: 261 """Decode frame by absolute index (works for baselines too).""" 262 if _memo is None: 263 _memo = {} 264 265 if abs_id in _memo: 266 return _memo[abs_id].copy() 267 268 cached = self._cache_get(abs_id) 269 if cached is not None: 270 _memo[abs_id] = cached 271 return cached.copy() 272 273 entry = self._index[abs_id] 274 codec = self.codec 275 276 if entry["frame_type"] == FRAME_KEYFRAME: 277 patches = self._read_patches(abs_id) 278 assert len(patches) == 1 279 img = self._decompress_patch_to_image(patches[0][4], codec) 280 else: 281 ref_id = entry["ref_frame_id"] 282 ref_img = self._decode_frame(ref_id, _memo=_memo) 283 patches = self._read_patches(abs_id) 284 img = reconstruct(ref_img, patches, codec=codec) 285 286 img = img.convert("RGBA") 287 _memo[abs_id] = img 288 self._cache_put(abs_id, img) 289 return img.copy() 290 291 def _read_header(self): 292 self._fh.seek(0) 293 raw = self._fh.read(FILE_HEADER_SIZE) 294 if len(raw) < FILE_HEADER_SIZE: 295 raise ValueError("File too small to be a valid .impak archive") 296 h = unpack_file_header(raw) 297 if h["magic"] != MAGIC: 298 raise ValueError("Not a valid .impak file (bad magic bytes)") 299 self._header = h 300 301 def _read_index(self): 302 self._fh.seek(self._header["index_offset"]) 303 count = self._header["frame_count"] 304 self._index = [] 305 for _ in range(count): 306 raw = self._fh.read(FRAME_INDEX_ENTRY_SIZE) 307 self._index.append(unpack_index_entry(raw)) 308 309 def _read_patches(self, abs_id: int) -> list: 310 entry = self._index[abs_id] 311 self._fh.seek(entry["data_offset"]) 312 patches = [] 313 for _ in range(entry["patch_count"]): 314 hdr = self._fh.read(PATCH_HEADER_SIZE) 315 x, y, w, h, data_len = unpack_patch_header(hdr) 316 data = self._fh.read(data_len) 317 patches.append((x, y, w, h, data)) 318 return patches 319 320 def _read_metadata(self, abs_id: int) -> dict: 321 if abs_id in self._meta_cache: 322 return self._meta_cache[abs_id] 323 entry = self._index[abs_id] 324 meta_len = entry["metadata_len"] 325 if meta_len == 0: 326 self._meta_cache[abs_id] = {} 327 return {} 328 self._fh.seek(entry["data_offset"]) 329 for _ in range(entry["patch_count"]): 330 hdr = self._fh.read(PATCH_HEADER_SIZE) 331 _, _, _, _, data_len = unpack_patch_header(hdr) 332 self._fh.seek(data_len, 1) 333 raw = self._fh.read(meta_len) 334 try: 335 meta = json.loads(raw.decode()) 336 except Exception: 337 meta = {} 338 self._meta_cache[abs_id] = meta 339 return meta 340 341 def _frame_data_size(self, abs_id: int) -> int: 342 entry = self._index[abs_id] 343 total = self._header["frame_count"] 344 if abs_id + 1 < total: 345 next_off = self._index[abs_id + 1]["data_offset"] 346 else: 347 next_off = self.path.stat().st_size 348 return next_off - entry["data_offset"] 349 350 def _decompress_patch_to_image(self, compressed: bytes, codec: str = "png") -> Image.Image: 351 from .differ import _decode_patch 352 return _decode_patch(compressed, codec=codec) 353 354 def _detect_baseline_count(self) -> int: 355 """ 356 Scan leading frames for the {"_baseline": true} metadata tag. 357 Returns the count of consecutive baseline frames at the front. 358 This is how the reader discovers how many frames to hide, without 359 any binary format change. 360 """ 361 count = 0 362 total = self._header["frame_count"] 363 for abs_id in range(total): 364 meta = self._read_metadata(abs_id) 365 if meta.get("_baseline"): 366 count += 1 367 else: 368 break # baselines are always contiguous at the front 369 return count 370 371 @property 372 def codec(self) -> str: 373 return CODEC_NAMES.get(self._header.get("codec", 0), "png") 374 375 @property 376 def quality(self) -> int: 377 return self._header.get("quality", 100) 378 379 def _build_name_map(self): 380 if self._name_map: 381 return 382 for content_id in range(len(self)): 383 abs_id = self._content_to_abs(content_id) 384 meta = self._read_metadata(abs_id) 385 if "name" in meta: 386 self._name_map[meta["name"]] = abs_id 387 388 @classmethod 389 def load_all( 390 cls, 391 path: Union[str, Path], 392 low_ram_mode: bool = False, 393 cache_size: Optional[int] = None, 394 ) -> List[Image.Image]: 395 """Load every content frame and return as a list of PIL Images.""" 396 with cls(path, low_ram_mode=low_ram_mode, cache_size=cache_size) as r: 397 return list(r) 398 399 @classmethod 400 def load_frame( 401 cls, 402 path: Union[str, Path], 403 frame_id: int, 404 low_ram_mode: bool = False, 405 cache_size: Optional[int] = None, 406 ) -> Image.Image: 407 """Load a single content frame by content index.""" 408 with cls(path, low_ram_mode=low_ram_mode, cache_size=cache_size) as r: 409 return r[frame_id]
Random-access reader for .impak collections.
The file index is read at open time (small); pixel data is lazy-loaded per frame request.
In manual-mode files the leading baseline keyframes are automatically detected (via their {"_baseline": true} metadata) and excluded from all public-facing operations. They are still used internally when decoding delta frames that reference them.
62 def __init__( 63 self, 64 path: Union[str, Path], 65 low_ram_mode: bool = False, 66 cache_size: Optional[int] = None, 67 ): 68 self.path = Path(path) 69 self._fh = open(self.path, "rb") 70 self._header: dict = {} 71 self._index: list[dict] = [] 72 self._name_map: dict[str, int] = {} # name → content_id 73 self._meta_cache: dict[int, dict] = {} 74 75 self.low_ram_mode = low_ram_mode 76 if cache_size is None: 77 cache_size = 2 if low_ram_mode else 0 78 self.cache_size = max(0, cache_size) 79 80 # abs_id -> Image.Image 81 # normal mode: unlimited dict-like cache 82 # low_ram_mode: bounded LRU cache 83 self._decode_cache: "OrderedDict[int, Image.Image]" = OrderedDict() 84 85 self._read_header() 86 self._read_index() 87 88 self._baseline_count: int = self._detect_baseline_count()
147 def get_metadata(self, frame_id: int) -> dict: 148 """ 149 Return the metadata dict for a content frame by content index. 150 """ 151 return self._read_metadata(self._content_to_abs(frame_id))
Return the metadata dict for a content frame by content index.
153 def info(self) -> str: 154 """Human-readable summary of the collection.""" 155 h = self._header 156 mode_name = MODE_NAMES.get(h["diff_mode"], "unknown") 157 codec_name = CODEC_NAMES.get(h.get("codec", 0), "png") 158 quality = h.get("quality", 100) 159 quality_str = "lossless" if quality == 100 else f"quality={quality}" 160 total_bytes = self.path.stat().st_size 161 n_content = len(self) 162 lines = [ 163 f"File : {self.path}", 164 f"Format : impak v{h['version']}", 165 f"Diff : {mode_name}", 166 f"Codec : {codec_name} ({quality_str})", 167 f"Canvas : {h['width']} × {h['height']} px", 168 f"Frames : {n_content}" 169 + (f" ({self._baseline_count} hidden baseline(s))" if self._baseline_count else ""), 170 f"Size : {total_bytes:,} bytes ({total_bytes/1024:.1f} KB)", 171 "", 172 ] 173 174 frame_sizes = {self._frame_size(self._content_to_abs(i)) for i in range(n_content)} 175 mixed_sizes = len(frame_sizes) > 1 176 177 if mixed_sizes: 178 lines += [ 179 f"{'ID':>4} {'Type':>9} {'Ref':>4} {'Patches':>7} {'Bytes':>9} {'Size':>11} Name", 180 "─" * 72, 181 ] 182 else: 183 lines += [ 184 f"{'ID':>4} {'Type':>9} {'Ref':>4} {'Patches':>7} {'Bytes':>9} Name", 185 "─" * 64, 186 ] 187 188 for content_id in range(n_content): 189 abs_id = self._content_to_abs(content_id) 190 entry = self._index[abs_id] 191 ftype = "keyframe" if entry["frame_type"] == FRAME_KEYFRAME else "delta" 192 ref_abs = entry["ref_frame_id"] 193 if entry["frame_type"] == FRAME_DELTA: 194 if ref_abs < self._baseline_count: 195 ref = f"B{ref_abs}" 196 else: 197 ref = str(ref_abs - self._baseline_count) 198 else: 199 ref = "self" 200 data_bytes = self._frame_data_size(abs_id) 201 meta = self._read_metadata(abs_id) 202 name = meta.get("name", "") 203 if mixed_sizes: 204 fw, fh = self._frame_size(abs_id) 205 size_str = f"{fw}×{fh}" 206 lines.append( 207 f"{content_id:>4} {ftype:>9} {ref:>4} " 208 f"{entry['patch_count']:>7} {data_bytes:>9,} {size_str:>11} {name}" 209 ) 210 else: 211 lines.append( 212 f"{content_id:>4} {ftype:>9} {ref:>4} " 213 f"{entry['patch_count']:>7} {data_bytes:>9,} {name}" 214 ) 215 return "\n".join(lines)
Human-readable summary of the collection.
217 def diff_map(self, frame_id: int) -> list[tuple[int, int, int, int]]: 218 """ 219 Return the (x, y, w, h) patch rectangles for a content frame. 220 *frame_id* is a content-visible index. 221 """ 222 abs_id = self._content_to_abs(frame_id) 223 entry = self._index[abs_id] 224 if entry["frame_type"] == FRAME_KEYFRAME: 225 w, h = self._frame_size(abs_id) 226 return [(0, 0, w, h)] 227 patches = self._read_patches(abs_id) 228 return [(x, y, w, h) for (x, y, w, h, _) in patches]
Return the (x, y, w, h) patch rectangles for a content frame. frame_id is a content-visible index.
238 @property 239 def baseline_count(self) -> int: 240 """Number of hidden baseline frames (0 for non-manual files).""" 241 return self._baseline_count
Number of hidden baseline frames (0 for non-manual files).
388 @classmethod 389 def load_all( 390 cls, 391 path: Union[str, Path], 392 low_ram_mode: bool = False, 393 cache_size: Optional[int] = None, 394 ) -> List[Image.Image]: 395 """Load every content frame and return as a list of PIL Images.""" 396 with cls(path, low_ram_mode=low_ram_mode, cache_size=cache_size) as r: 397 return list(r)
Load every content frame and return as a list of PIL Images.
399 @classmethod 400 def load_frame( 401 cls, 402 path: Union[str, Path], 403 frame_id: int, 404 low_ram_mode: bool = False, 405 cache_size: Optional[int] = None, 406 ) -> Image.Image: 407 """Load a single content frame by content index.""" 408 with cls(path, low_ram_mode=low_ram_mode, cache_size=cache_size) as r: 409 return r[frame_id]
Load a single content frame by content index.
269def reconstruct(base_img: Image.Image, patches: List[Patch], codec: str = "png") -> Image.Image: 270 """ 271 Apply a list of patches onto *base_img* and return a new Image. 272 273 *base_img* is not modified in place. 274 *codec* must match the codec used when the patches were encoded. 275 """ 276 result = base_img.copy().convert("RGBA") 277 for (x, y, w, h, compressed) in patches: 278 patch_img = _decode_patch(compressed, codec=codec).convert("RGBA") 279 result.paste(patch_img, (x, y)) 280 return result
Apply a list of patches onto base_img and return a new Image.
base_img is not modified in place. codec must match the codec used when the patches were encoded.
59def create(path, mode="lto", **kwargs) -> "ImpakWriter": 60 """ 61 Parameters 62 ---------- 63 path : file path (str or Path) 64 mode : "vs_first" | "vs_prior" | "keyframe" | "lto" | "manual" 65 codec : "png" or "webp" (default) 66 quality : 0-100. 100 = lossless for both codecs. 67 Values <100 enable lossy WebP (smaller, not pixel-perfect). 68 keyframe_interval : (keyframe mode) full image every N frames (default 10) 69 threshold : pixel delta threshold 0-255 (default 4) 70 tile_size : diff grid tile size in px (default 32) 71 merge_gap : merge adjacent changed tiles within N px (default 8) 72 auto_keyframe_sim : force keyframe when similarity drops below this (default 0.5) 73 lto_candidates : (lto / manual mode) how many top-similarity frames to 74 fully probe (default 6) 75 max_ref_depth : (lto mode) max decode-chain depth before forcing a keyframe 76 (default 8) 77 baselines : (manual mode, required) list of PIL Images or file paths 78 stored as pinned keyframes at the start of the file; 79 every content frame is diffed against these first. 80 fallback_mode : (manual mode) strategy used when no baseline wins; 81 one of "vs_first", "vs_prior", "keyframe", "lto" 82 (default "vs_prior") 83 """ 84 if ImpakWriter is None: 85 raise ImportError( 86 "Encoding requires the 'encoder' extra: pip install impak[encoder]" 87 ) 88 return ImpakWriter(path, mode=mode, **kwargs)
Parameters
path (file path (str or Path)):
mode ("vs_first" | "vs_prior" | "keyframe" | "lto" | "manual"):
codec ("png" or "webp" (default)):
quality (0-100. 100 = lossless for both codecs.): Values <100 enable lossy WebP (smaller, not pixel-perfect).
keyframe_interval ((keyframe mode) full image every N frames (default 10)):
threshold (pixel delta threshold 0-255 (default 4)):
tile_size (diff grid tile size in px (default 32)):
merge_gap (merge adjacent changed tiles within N px (default 8)):
auto_keyframe_sim (force keyframe when similarity drops below this (default 0.5)):
lto_candidates ((lto / manual mode) how many top-similarity frames to): fully probe (default 6)
- max_ref_depth ((lto mode) max decode-chain depth before forcing a keyframe): (default 8)
- baselines ((manual mode, required) list of PIL Images or file paths): stored as pinned keyframes at the start of the file; every content frame is diffed against these first.
- fallback_mode ((manual mode) strategy used when no baseline wins;): one of "vs_first", "vs_prior", "keyframe", "lto" (default "vs_prior")
140class ImpakWriter: 141 """ 142 Sequential writer for .impak collections. 143 144 Parameters 145 ---------- 146 path : output file path 147 mode : "vs_first" | "vs_prior" | "keyframe" | "lto" | "manual" 148 keyframe_interval : (keyframe mode only) store a full image every N frames 149 threshold : pixel delta considered "changed" (0 = perfectly lossless) 150 tile_size : diff grid cell size in pixels 151 merge_gap : pixels gap between changed tiles before they are merged 152 auto_keyframe_sim : if similarity drops below this fraction a keyframe is 153 forced regardless of mode (0.0 = never force) 154 workers : thread-pool size used for parallel patch compression and 155 LTO candidate probing. None = os.cpu_count(). 156 Set to 1 to disable parallelism entirely. 157 baselines : (manual mode) list of PIL Images or file paths used as 158 pinned reference anchors. They are stored as hidden 159 leading keyframes so the delta chain is self-contained, 160 but ImpakReader hides them from callers — only content 161 frames are visible when iterating or indexing. 162 Baselines are automatically resized to match the canvas 163 size established by the first content frame (or the 164 first baseline if all are the same size). 165 fallback_mode : (manual mode) diff strategy applied when no baseline 166 yields a patch set smaller than this alternative. 167 Accepts "vs_first", "vs_prior", "keyframe", or "lto". 168 Defaults to "lto". 169 """ 170 171 def __init__( 172 self, 173 path: Union[str, Path], 174 mode: str = "vs_first", 175 keyframe_interval: int = 10, 176 threshold: int = 4, 177 tile_size: int = 64, 178 merge_gap: int = 8, 179 auto_keyframe_sim: float = 0.5, 180 codec: str = "webp", 181 quality: int = 100, 182 lto_candidates: int = 6, 183 max_ref_depth: int = 8, 184 workers: Optional[int] = None, 185 baselines: Optional[List[Union[Image.Image, str, Path]]] = None, 186 fallback_mode: str = "lto", 187 lto_fast_keyframe_probe: bool = True, 188 lto_fast_probe_sim: float = 0.5, 189 ): 190 if mode not in MODE_FROM_NAME: 191 raise ValueError(f"mode must be one of {list(MODE_FROM_NAME)}") 192 if codec not in ("png", "webp"): 193 raise ValueError("codec must be 'png' or 'webp'") 194 if not (0 <= quality <= 100): 195 raise ValueError("quality must be 0-100") 196 if lto_candidates < 1: 197 raise ValueError("lto_candidates must be >= 1") 198 if max_ref_depth < 1: 199 raise ValueError("max_ref_depth must be >= 1") 200 201 if mode == "manual": 202 _valid_fallbacks = [m for m in MODE_FROM_NAME if m != "manual"] 203 if fallback_mode not in _valid_fallbacks: 204 raise ValueError( 205 f"fallback_mode must be one of {_valid_fallbacks}" 206 ) 207 if not baselines: 208 raise ValueError( 209 "manual mode requires at least one entry in 'baselines'" 210 ) 211 212 self.path = Path(path) 213 self.mode = mode 214 self.mode_id = MODE_FROM_NAME[mode] 215 self.keyframe_interval = keyframe_interval 216 self.threshold = threshold 217 self.tile_size = tile_size 218 self.merge_gap = merge_gap 219 self.auto_keyframe_sim = auto_keyframe_sim 220 self.codec = codec 221 self.quality = quality 222 self.lto_candidates = lto_candidates 223 self.max_ref_depth = max_ref_depth 224 self.workers = workers 225 self.fallback_mode = fallback_mode 226 self.fallback_mode_id = MODE_FROM_NAME.get(fallback_mode, MODE_LTO) 227 self.lto_fast_keyframe_probe = lto_fast_keyframe_probe 228 self.lto_fast_probe_sim = lto_fast_probe_sim 229 230 self._frames: list[dict] = [] 231 self._frame_data: list[bytes] = [] 232 self._ref_images: list[Image.Image] = [] 233 self._ref_arrays: list[np.ndarray] = [] 234 self._depths: list[int] = [] 235 236 self._canvas: Optional[tuple[int, int]] = None 237 self._size_groups: dict[tuple[int, int], list[int]] = {} 238 self._closed = False 239 240 self._baseline_ids: list[int] = [] 241 self._baseline_count: int = 0 242 self._pending_baselines: list = list(baselines) if baselines else [] 243 244 _pool_size = workers if workers is not None else (os.cpu_count() or 4) 245 self._pool = ThreadPoolExecutor(max_workers=max(1, _pool_size)) 246 247 def add( 248 self, 249 image: Union[Image.Image, str, Path], 250 name: Optional[str] = None, 251 metadata: Optional[dict] = None, 252 ) -> int: 253 """ 254 Add one content image to the collection. Returns the 0-based frame 255 index as seen by readers (i.e. not counting hidden baseline frames). 256 257 *image* may be a Pillow Image or a file path. 258 *name* is stored in per-frame metadata (useful for later retrieval). 259 *metadata* is an arbitrary JSON-serialisable dict merged with name. 260 """ 261 if self._closed: 262 raise RuntimeError("Writer is already closed") 263 264 if isinstance(image, (str, Path)): 265 image = Image.open(image) 266 267 image = image.convert("RGBA") 268 new_arr = np.array(image, dtype=np.int16) 269 270 if self._canvas is None: 271 self._canvas = (image.width, image.height) 272 273 if self._pending_baselines: 274 self._inject_baselines(self._pending_baselines) 275 self._pending_baselines = [] 276 277 frame_id = len(self._frames) 278 279 frame_type, ref_id, patches = self._encode_frame(image, frame_id, new_arr) 280 281 meta: dict = {} 282 if name: 283 meta["name"] = name 284 if metadata: 285 meta.update(metadata) 286 287 meta["_size"] = [image.width, image.height] 288 meta_bytes = json.dumps(meta, separators=(",", ":")).encode() if meta else b"" 289 290 parts: list[bytes] = [] 291 for (x, y, w, h, data) in patches: 292 parts.append(pack_patch_header(x, y, w, h, len(data))) 293 parts.append(data) 294 parts.append(meta_bytes) 295 frame_bytes = b"".join(parts) 296 297 if frame_type == FRAME_KEYFRAME: 298 self._depths.append(0) 299 else: 300 self._depths.append(self._depths[ref_id] + 1) 301 302 self._frames.append({ 303 "patch_count": len(patches), 304 "ref_frame_id": ref_id, 305 "metadata_len": len(meta_bytes), 306 "frame_type": frame_type, 307 }) 308 self._frame_data.append(frame_bytes) 309 self._ref_images.append(image) 310 self._ref_arrays.append(new_arr) 311 size_key = (image.width, image.height) 312 self._size_groups.setdefault(size_key, []).append(frame_id) 313 314 return frame_id - self._baseline_count 315 316 def add_batch( 317 self, 318 images: Sequence[Union[Image.Image, str, Path]], 319 names: Optional[Sequence[Optional[str]]] = None, 320 metadatas: Optional[Sequence[Optional[dict]]] = None, 321 workers: Optional[int] = None, 322 ) -> list[int]: 323 """ 324 Add multiple images in parallel (vs_first mode only). 325 326 For ``vs_first`` mode all frames after the first are encoded against 327 frame 0 using a process pool — significantly faster on multi-core 328 hardware. Other modes fall back to serial :meth:`add`. 329 330 Parameters 331 ---------- 332 images : iterable of PIL Images or file paths 333 names : optional per-frame name (parallel to *images*) 334 metadatas : optional per-frame metadata dicts 335 workers : process pool size (default: *os.cpu_count()*) 336 337 Returns 338 ------- 339 list[int] – content frame indices (same order as *images*) 340 """ 341 if self._closed: 342 raise RuntimeError("Writer is already closed") 343 344 if self._pending_baselines: 345 self._inject_baselines(self._pending_baselines) 346 self._pending_baselines = [] 347 348 images = list(images) 349 if not images: 350 return [] 351 352 # ── vs_first with ref 0 → parallel ────────────────────────── 353 if self.mode_id == MODE_VS_FIRST and len(self._frames) > 0: 354 return self._add_batch_parallel( 355 images, names, metadatas, workers, 356 ) 357 358 # ── fallback: serial add() ─────────────────────────────────── 359 return [ 360 self.add( 361 images[i], 362 name=names[i] if names and i < len(names) else None, 363 metadata=metadatas[i] if metadatas and i < len(metadatas) else None, 364 ) 365 for i in range(len(images)) 366 ] 367 368 def _add_batch_parallel( 369 self, 370 images: list, 371 names: Optional[Sequence[Optional[str]]], 372 metadatas: Optional[Sequence[Optional[dict]]], 373 workers: Optional[int], 374 ) -> list[int]: 375 """Encode all images in parallel against ref 0. 376 """ 377 from concurrent.futures import ProcessPoolExecutor 378 379 # Preprocess: convert all to RGBA + arrays 380 preprocessed: list[tuple] = [] 381 for img in images: 382 if isinstance(img, (str, Path)): 383 img = Image.open(img) 384 img = img.convert("RGBA") 385 arr = np.array(img, dtype=np.int16) 386 preprocessed.append((img, arr)) 387 388 if self._canvas is None and preprocessed: 389 self._canvas = (preprocessed[0][0].width, preprocessed[0][0].height) 390 391 ref_arr = self._ref_arrays[0] 392 ref_shm, ref_meta = _store_in_shm(ref_arr) 393 394 params = { 395 k: getattr(self, k) 396 for k in ("threshold", "tile_size", "merge_gap", "codec", "quality", 397 "auto_keyframe_sim") 398 } 399 400 n_workers = workers if workers is not None else (os.cpu_count() or 4) 401 result_ids: list[int] = [] 402 403 new_shms: list = [] 404 try: 405 with ProcessPoolExecutor(max_workers=n_workers) as pool: 406 futures = [] 407 for img, arr in preprocessed: 408 new_shm, new_meta = _store_in_shm(arr) 409 new_shms.append(new_shm) 410 futures.append(pool.submit( 411 _encode_vs_first_worker, 412 ref_meta, new_meta, params, 413 )) 414 415 for i, future in enumerate(futures): 416 result = future.result() 417 img, arr = preprocessed[i] 418 frame_type = result["frame_type"] 419 ref_id = result["ref_frame_id"] 420 patches = result["patches"] 421 frame_id = len(self._frames) 422 423 meta: dict = {} 424 if names and i < len(names) and names[i]: 425 meta["name"] = names[i] 426 if metadatas and i < len(metadatas) and metadatas[i]: 427 meta.update(metadatas[i]) 428 meta["_size"] = [img.width, img.height] 429 meta_bytes = json.dumps(meta, separators=(",", ":")).encode() if meta else b"" 430 431 parts: list[bytes] = [] 432 for (x, y, w, h, data) in patches: 433 parts.append(pack_patch_header(x, y, w, h, len(data))) 434 parts.append(data) 435 parts.append(meta_bytes) 436 frame_bytes = b"".join(parts) 437 438 if frame_type == FRAME_KEYFRAME: 439 ref_id = frame_id 440 self._depths.append(0) 441 else: 442 self._depths.append(self._depths[ref_id] + 1) 443 444 self._frames.append({ 445 "patch_count": len(patches), 446 "ref_frame_id": ref_id, 447 "metadata_len": len(meta_bytes), 448 "frame_type": frame_type, 449 }) 450 self._frame_data.append(frame_bytes) 451 self._ref_images.append(img) 452 self._ref_arrays.append(arr) 453 size_key = (img.width, img.height) 454 self._size_groups.setdefault(size_key, []).append(frame_id) 455 456 result_ids.append(frame_id - self._baseline_count) 457 finally: 458 for shm in new_shms: 459 try: 460 shm.close() 461 shm.unlink() 462 except Exception: 463 pass 464 ref_shm.close() 465 ref_shm.unlink() 466 467 return result_ids 468 469 def close(self): 470 """Finalise and write the file. Called automatically by __exit__.""" 471 if self._closed: 472 return 473 if not self._frames: 474 raise RuntimeError("No frames added — nothing to write") 475 476 self._pool.shutdown(wait=False) 477 478 w, h = self._canvas 479 frame_count = len(self._frames) 480 481 index_offset = FILE_HEADER_SIZE 482 data_start = index_offset + frame_count * FRAME_INDEX_ENTRY_SIZE 483 offsets: list[int] = [] 484 cursor = data_start 485 for fd in self._frame_data: 486 offsets.append(cursor) 487 cursor += len(fd) 488 489 self.path.parent.mkdir(parents=True, exist_ok=True) 490 491 with open(self.path, "wb") as f: 492 f.write(pack_file_header( 493 self.mode_id, frame_count, index_offset, w, h, 494 codec=CODEC_FROM_NAME[self.codec], 495 quality=self.quality, 496 )) 497 for i, fm in enumerate(self._frames): 498 f.write(pack_index_entry( 499 data_offset=offsets[i], 500 patch_count=fm["patch_count"], 501 ref_frame_id=fm["ref_frame_id"], 502 metadata_len=fm["metadata_len"], 503 frame_type=fm["frame_type"], 504 )) 505 for fd in self._frame_data: 506 f.write(fd) 507 508 self._closed = True 509 510 def __enter__(self): 511 return self 512 513 def __exit__(self, exc_type, exc_val, exc_tb): 514 if exc_type is None: 515 self.close() 516 else: 517 self._pool.shutdown(wait=False) 518 self._closed = True 519 return False 520 521 @property 522 def frame_count(self) -> int: 523 """Total frames including hidden baselines.""" 524 return len(self._frames) 525 526 @property 527 def content_frame_count(self) -> int: 528 """Content frames only (what callers see).""" 529 return len(self._frames) - self._baseline_count 530 531 @property 532 def baseline_count(self) -> int: 533 return self._baseline_count 534 535 @property 536 def stats(self) -> list[dict]: 537 """Per-frame stats including hidden baseline frames.""" 538 result = [] 539 for i, (fm, fd) in enumerate(zip(self._frames, self._frame_data)): 540 is_baseline = i in self._baseline_ids 541 result.append({ 542 "frame_id": i, 543 "content_id": None if is_baseline else i - self._baseline_count, 544 "frame_type": "keyframe" if fm["frame_type"] == FRAME_KEYFRAME else "delta", 545 "ref_frame_id": fm["ref_frame_id"], 546 "patch_count": fm["patch_count"], 547 "data_bytes": len(fd), 548 "is_baseline": is_baseline, 549 }) 550 return result 551 552 def _inject_baselines(self, baselines: list): 553 """ 554 Store each baseline as a hidden leading FRAME_KEYFRAME. 555 556 Called from the first add() so self._canvas is already set. 557 Baselines are resized to the canvas if their native size differs. 558 """ 559 for idx, raw in enumerate(baselines): 560 if isinstance(raw, (str, Path)): 561 img = Image.open(raw).convert("RGBA") 562 else: 563 img = raw.convert("RGBA") 564 565 # LANCZOS? not sure.. 566 if img.size != self._canvas: 567 img = img.resize(self._canvas, Image.LANCZOS) 568 569 frame_id = len(self._frames) 570 cw, ch = self._canvas 571 compressed = _encode_crop(img, 0, 0, cw, ch, codec=self.codec, quality=self.quality) 572 573 meta_bytes = json.dumps( 574 {"_baseline": True, "baseline_index": idx}, 575 separators=(",", ":"), 576 ).encode() 577 578 parts: list[bytes] = [ 579 pack_patch_header(0, 0, cw, ch, len(compressed)), 580 compressed, 581 meta_bytes, 582 ] 583 frame_bytes = b"".join(parts) 584 585 self._depths.append(0) 586 self._frames.append({ 587 "patch_count": 1, 588 "ref_frame_id": frame_id, 589 "metadata_len": len(meta_bytes), 590 "frame_type": FRAME_KEYFRAME, 591 }) 592 self._frame_data.append(frame_bytes) 593 self._ref_images.append(img) 594 self._ref_arrays.append(np.array(img, dtype=np.int16)) 595 self._baseline_ids.append(frame_id) 596 597 self._baseline_count = len(self._baseline_ids) 598 599 def _encode_frame(self, image: Image.Image, frame_id: int, new_arr: np.ndarray): 600 """Route to the appropriate encoder. Returns (frame_type, ref_id, patches).""" 601 size_key = (image.width, image.height) 602 same_size_ids = [fid for fid in self._size_groups.get(size_key, []) 603 if fid < frame_id] 604 if not same_size_ids and frame_id > 0: 605 return self._make_keyframe(image, frame_id) 606 607 if self.mode_id == MODE_MANUAL: 608 return self._encode_frame_manual(image, frame_id, new_arr) 609 610 if frame_id == 0: 611 return self._make_keyframe(image, frame_id) 612 613 if self.mode_id == MODE_LTO: 614 return self._encode_frame_lto(image, frame_id, new_arr, same_size_ids) 615 616 if self.mode_id == MODE_KEYFRAME and (frame_id % self.keyframe_interval == 0): 617 return self._make_keyframe(image, frame_id) 618 619 if self.mode_id == MODE_VS_FIRST: 620 ref_id = same_size_ids[0] 621 elif self.mode_id == MODE_VS_PRIOR: 622 ref_id = same_size_ids[-1] 623 else: 624 ref_id = same_size_ids[-1] 625 626 return self._diff_against(image, frame_id, ref_id, new_arr) 627 628 def _ref_chain_depth(self, frame_id: int) -> int: 629 return self._depths[frame_id] 630 631 def _make_keyframe(self, image: Image.Image, frame_id: int): 632 w, h = image.size 633 compressed = _encode_crop(image, 0, 0, w, h, codec=self.codec, quality=self.quality) 634 return FRAME_KEYFRAME, frame_id, [(0, 0, w, h, compressed)] 635 636 def _diff_against( 637 self, 638 image: Image.Image, 639 frame_id: int, 640 ref_id: int, 641 new_arr: np.ndarray, 642 ): 643 ref_arr = self._ref_arrays[ref_id] 644 diff_arr = np.abs(new_arr - ref_arr).max(axis=2) 645 646 if self.auto_keyframe_sim > 0: 647 total = ref_arr.shape[0] * ref_arr.shape[1] 648 if (diff_arr <= self.threshold).sum() / total < self.auto_keyframe_sim: 649 return self._make_keyframe(image, frame_id) 650 651 patches = compute_patches( 652 self._ref_images[ref_id], 653 image, 654 threshold=self.threshold, 655 tile_size=self.tile_size, 656 merge_gap=self.merge_gap, 657 codec=self.codec, 658 quality=self.quality, 659 workers=self.workers, 660 ref_arr=ref_arr, 661 new_arr=new_arr, 662 diff_arr=diff_arr, 663 executor=self._pool, 664 ) 665 666 return FRAME_DELTA, ref_id, patches 667 668 def _encode_frame_lto(self, image: Image.Image, frame_id: int, 669 new_arr: np.ndarray, 670 same_size_ids: Optional[list] = None): 671 total_px = new_arr.shape[0] * new_arr.shape[1] 672 673 if same_size_ids is None: 674 size_key = (image.width, image.height) 675 same_size_ids = [fid for fid in self._size_groups.get(size_key, []) 676 if fid < frame_id] 677 678 eligible = [ 679 cid for cid in same_size_ids 680 if self._depths[cid] + 1 <= self.max_ref_depth 681 ] 682 if not eligible: 683 return self._make_keyframe(image, frame_id) 684 685 def _encode_keyframe(): 686 iw, ih = image.size 687 kf_data = _encode_crop(image, 0, 0, iw, ih, codec=self.codec, quality=self.quality) 688 return FRAME_KEYFRAME, frame_id, [(0, 0, iw, ih, kf_data)], len(kf_data) 689 690 kf_future = self._pool.submit(_encode_keyframe) 691 692 _diff_cache: dict[int, np.ndarray] = {} 693 694 def _score(cid: int): 695 diff = np.abs(new_arr - self._ref_arrays[cid]).max(axis=2) 696 _diff_cache[cid] = diff 697 sim = float((diff <= self.threshold).sum()) / total_px 698 return sim, cid 699 700 scored = list(self._pool.map(_score, eligible)) 701 702 scored.sort(key=lambda x: -x[0]) 703 704 if self.lto_fast_keyframe_probe and scored: 705 best_sim = scored[0][0] 706 if best_sim < self.lto_fast_probe_sim: 707 return kf_future.result()[:3] 708 709 candidates = [cid for (_, cid) in scored[: self.lto_candidates]] 710 711 def _probe(cid: int): 712 diff_arr = _diff_cache.pop(cid) 713 patches = compute_patches( 714 self._ref_images[cid], image, 715 threshold=self.threshold, 716 tile_size=self.tile_size, 717 merge_gap=self.merge_gap, 718 codec=self.codec, 719 quality=self.quality, 720 workers=1, 721 ref_arr=self._ref_arrays[cid], 722 new_arr=new_arr, 723 diff_arr=diff_arr, 724 ) 725 return FRAME_DELTA, cid, patches, sum(len(p[4]) for p in patches) 726 727 probe_futures = [self._pool.submit(_probe, cid) for cid in candidates] 728 kf_result = kf_future.result() 729 probe_results = [f.result() for f in probe_futures] 730 731 all_results = probe_results + [kf_result] 732 best_type, best_ref_id, best_patches, _ = min(all_results, key=lambda r: r[3]) 733 734 return best_type, best_ref_id, best_patches 735 736 def _encode_frame_manual(self, image: Image.Image, frame_id: int, new_arr: np.ndarray): 737 """ 738 Manual-mode encoder: probe designated baseline frames first, then fall 739 back to the configured fallback mode if no baseline wins. 740 """ 741 total_px = new_arr.shape[0] * new_arr.shape[1] 742 743 _diff_cache: dict[int, np.ndarray] = {} 744 745 def _score_baseline(bid: int): 746 diff = np.abs(new_arr - self._ref_arrays[bid]).max(axis=2) 747 _diff_cache[bid] = diff 748 sim = float((diff <= self.threshold).sum()) / total_px 749 return sim, bid 750 751 if len(self._baseline_ids) <= 2 or self.workers == 1: 752 scored = [_score_baseline(bid) for bid in self._baseline_ids] 753 else: 754 scored = list(self._pool.map(_score_baseline, self._baseline_ids)) 755 756 scored.sort(key=lambda x: -x[0]) 757 top_baselines = [bid for (_, bid) in scored[: self.lto_candidates]] 758 759 def _probe_baseline(bid: int): 760 diff_arr = _diff_cache.pop(bid) 761 patches = compute_patches( 762 self._ref_images[bid], image, 763 threshold=self.threshold, 764 tile_size=self.tile_size, 765 merge_gap=self.merge_gap, 766 codec=self.codec, 767 quality=self.quality, 768 workers=1, 769 ref_arr=self._ref_arrays[bid], 770 new_arr=new_arr, 771 diff_arr=diff_arr, 772 ) 773 return bid, patches, sum(len(p[4]) for p in patches) 774 775 if len(top_baselines) <= 1 or self.workers == 1: 776 baseline_results = [_probe_baseline(bid) for bid in top_baselines] 777 else: 778 baseline_results = list(self._pool.map(_probe_baseline, top_baselines)) 779 780 best_bl_ref, best_bl_patches, best_bl_size = min(baseline_results, key=lambda r: r[2]) 781 782 fb_type, fb_ref_id, fb_patches = self._encode_frame_fallback(image, frame_id, new_arr) 783 fb_size = sum(len(p[4]) for p in fb_patches) 784 785 iw, ih = image.size 786 kf_size = len(_encode_crop(image, 0, 0, iw, ih, codec=self.codec, quality=self.quality)) 787 788 if kf_size <= best_bl_size and kf_size <= fb_size: 789 return self._make_keyframe(image, frame_id) 790 if best_bl_size <= fb_size: 791 return FRAME_DELTA, best_bl_ref, best_bl_patches 792 return fb_type, fb_ref_id, fb_patches 793 794 def _encode_frame_fallback(self, image: Image.Image, frame_id: int, new_arr: np.ndarray): 795 """ 796 Run the configured fallback_mode for this frame. 797 """ 798 content_id = frame_id - self._baseline_count 799 800 if self.fallback_mode_id == MODE_VS_FIRST: 801 if content_id == 0: 802 return self._make_keyframe(image, frame_id) 803 ref_id = self._baseline_count 804 return self._diff_against(image, frame_id, ref_id, new_arr) 805 806 if self.fallback_mode_id == MODE_VS_PRIOR: 807 if content_id == 0: 808 return self._make_keyframe(image, frame_id) 809 return self._diff_against(image, frame_id, frame_id - 1, new_arr) 810 811 if self.fallback_mode_id == MODE_KEYFRAME: 812 if content_id == 0 or (content_id % self.keyframe_interval == 0): 813 return self._make_keyframe(image, frame_id) 814 return self._diff_against(image, frame_id, frame_id - 1, new_arr) 815 816 if self.fallback_mode_id == MODE_LTO: 817 if content_id == 0: 818 return self._make_keyframe(image, frame_id) 819 return self._encode_frame_lto(image, frame_id, new_arr) 820 821 return self._make_keyframe(image, frame_id)
Sequential writer for .impak collections.
Parameters
path (output file path):
mode ("vs_first" | "vs_prior" | "keyframe" | "lto" | "manual"):
keyframe_interval ((keyframe mode only) store a full image every N frames):
threshold (pixel delta considered "changed" (0 = perfectly lossless)):
tile_size (diff grid cell size in pixels):
merge_gap (pixels gap between changed tiles before they are merged):
auto_keyframe_sim (if similarity drops below this fraction a keyframe is): forced regardless of mode (0.0 = never force)
- workers (thread-pool size used for parallel patch compression and): LTO candidate probing. None = os.cpu_count(). Set to 1 to disable parallelism entirely.
- baselines ((manual mode) list of PIL Images or file paths used as): pinned reference anchors. They are stored as hidden leading keyframes so the delta chain is self-contained, but ImpakReader hides them from callers — only content frames are visible when iterating or indexing. Baselines are automatically resized to match the canvas size established by the first content frame (or the first baseline if all are the same size).
- fallback_mode ((manual mode) diff strategy applied when no baseline): yields a patch set smaller than this alternative. Accepts "vs_first", "vs_prior", "keyframe", or "lto". Defaults to "lto".
171 def __init__( 172 self, 173 path: Union[str, Path], 174 mode: str = "vs_first", 175 keyframe_interval: int = 10, 176 threshold: int = 4, 177 tile_size: int = 64, 178 merge_gap: int = 8, 179 auto_keyframe_sim: float = 0.5, 180 codec: str = "webp", 181 quality: int = 100, 182 lto_candidates: int = 6, 183 max_ref_depth: int = 8, 184 workers: Optional[int] = None, 185 baselines: Optional[List[Union[Image.Image, str, Path]]] = None, 186 fallback_mode: str = "lto", 187 lto_fast_keyframe_probe: bool = True, 188 lto_fast_probe_sim: float = 0.5, 189 ): 190 if mode not in MODE_FROM_NAME: 191 raise ValueError(f"mode must be one of {list(MODE_FROM_NAME)}") 192 if codec not in ("png", "webp"): 193 raise ValueError("codec must be 'png' or 'webp'") 194 if not (0 <= quality <= 100): 195 raise ValueError("quality must be 0-100") 196 if lto_candidates < 1: 197 raise ValueError("lto_candidates must be >= 1") 198 if max_ref_depth < 1: 199 raise ValueError("max_ref_depth must be >= 1") 200 201 if mode == "manual": 202 _valid_fallbacks = [m for m in MODE_FROM_NAME if m != "manual"] 203 if fallback_mode not in _valid_fallbacks: 204 raise ValueError( 205 f"fallback_mode must be one of {_valid_fallbacks}" 206 ) 207 if not baselines: 208 raise ValueError( 209 "manual mode requires at least one entry in 'baselines'" 210 ) 211 212 self.path = Path(path) 213 self.mode = mode 214 self.mode_id = MODE_FROM_NAME[mode] 215 self.keyframe_interval = keyframe_interval 216 self.threshold = threshold 217 self.tile_size = tile_size 218 self.merge_gap = merge_gap 219 self.auto_keyframe_sim = auto_keyframe_sim 220 self.codec = codec 221 self.quality = quality 222 self.lto_candidates = lto_candidates 223 self.max_ref_depth = max_ref_depth 224 self.workers = workers 225 self.fallback_mode = fallback_mode 226 self.fallback_mode_id = MODE_FROM_NAME.get(fallback_mode, MODE_LTO) 227 self.lto_fast_keyframe_probe = lto_fast_keyframe_probe 228 self.lto_fast_probe_sim = lto_fast_probe_sim 229 230 self._frames: list[dict] = [] 231 self._frame_data: list[bytes] = [] 232 self._ref_images: list[Image.Image] = [] 233 self._ref_arrays: list[np.ndarray] = [] 234 self._depths: list[int] = [] 235 236 self._canvas: Optional[tuple[int, int]] = None 237 self._size_groups: dict[tuple[int, int], list[int]] = {} 238 self._closed = False 239 240 self._baseline_ids: list[int] = [] 241 self._baseline_count: int = 0 242 self._pending_baselines: list = list(baselines) if baselines else [] 243 244 _pool_size = workers if workers is not None else (os.cpu_count() or 4) 245 self._pool = ThreadPoolExecutor(max_workers=max(1, _pool_size))
247 def add( 248 self, 249 image: Union[Image.Image, str, Path], 250 name: Optional[str] = None, 251 metadata: Optional[dict] = None, 252 ) -> int: 253 """ 254 Add one content image to the collection. Returns the 0-based frame 255 index as seen by readers (i.e. not counting hidden baseline frames). 256 257 *image* may be a Pillow Image or a file path. 258 *name* is stored in per-frame metadata (useful for later retrieval). 259 *metadata* is an arbitrary JSON-serialisable dict merged with name. 260 """ 261 if self._closed: 262 raise RuntimeError("Writer is already closed") 263 264 if isinstance(image, (str, Path)): 265 image = Image.open(image) 266 267 image = image.convert("RGBA") 268 new_arr = np.array(image, dtype=np.int16) 269 270 if self._canvas is None: 271 self._canvas = (image.width, image.height) 272 273 if self._pending_baselines: 274 self._inject_baselines(self._pending_baselines) 275 self._pending_baselines = [] 276 277 frame_id = len(self._frames) 278 279 frame_type, ref_id, patches = self._encode_frame(image, frame_id, new_arr) 280 281 meta: dict = {} 282 if name: 283 meta["name"] = name 284 if metadata: 285 meta.update(metadata) 286 287 meta["_size"] = [image.width, image.height] 288 meta_bytes = json.dumps(meta, separators=(",", ":")).encode() if meta else b"" 289 290 parts: list[bytes] = [] 291 for (x, y, w, h, data) in patches: 292 parts.append(pack_patch_header(x, y, w, h, len(data))) 293 parts.append(data) 294 parts.append(meta_bytes) 295 frame_bytes = b"".join(parts) 296 297 if frame_type == FRAME_KEYFRAME: 298 self._depths.append(0) 299 else: 300 self._depths.append(self._depths[ref_id] + 1) 301 302 self._frames.append({ 303 "patch_count": len(patches), 304 "ref_frame_id": ref_id, 305 "metadata_len": len(meta_bytes), 306 "frame_type": frame_type, 307 }) 308 self._frame_data.append(frame_bytes) 309 self._ref_images.append(image) 310 self._ref_arrays.append(new_arr) 311 size_key = (image.width, image.height) 312 self._size_groups.setdefault(size_key, []).append(frame_id) 313 314 return frame_id - self._baseline_count
Add one content image to the collection. Returns the 0-based frame index as seen by readers (i.e. not counting hidden baseline frames).
image may be a Pillow Image or a file path. name is stored in per-frame metadata (useful for later retrieval). metadata is an arbitrary JSON-serialisable dict merged with name.
316 def add_batch( 317 self, 318 images: Sequence[Union[Image.Image, str, Path]], 319 names: Optional[Sequence[Optional[str]]] = None, 320 metadatas: Optional[Sequence[Optional[dict]]] = None, 321 workers: Optional[int] = None, 322 ) -> list[int]: 323 """ 324 Add multiple images in parallel (vs_first mode only). 325 326 For ``vs_first`` mode all frames after the first are encoded against 327 frame 0 using a process pool — significantly faster on multi-core 328 hardware. Other modes fall back to serial :meth:`add`. 329 330 Parameters 331 ---------- 332 images : iterable of PIL Images or file paths 333 names : optional per-frame name (parallel to *images*) 334 metadatas : optional per-frame metadata dicts 335 workers : process pool size (default: *os.cpu_count()*) 336 337 Returns 338 ------- 339 list[int] – content frame indices (same order as *images*) 340 """ 341 if self._closed: 342 raise RuntimeError("Writer is already closed") 343 344 if self._pending_baselines: 345 self._inject_baselines(self._pending_baselines) 346 self._pending_baselines = [] 347 348 images = list(images) 349 if not images: 350 return [] 351 352 # ── vs_first with ref 0 → parallel ────────────────────────── 353 if self.mode_id == MODE_VS_FIRST and len(self._frames) > 0: 354 return self._add_batch_parallel( 355 images, names, metadatas, workers, 356 ) 357 358 # ── fallback: serial add() ─────────────────────────────────── 359 return [ 360 self.add( 361 images[i], 362 name=names[i] if names and i < len(names) else None, 363 metadata=metadatas[i] if metadatas and i < len(metadatas) else None, 364 ) 365 for i in range(len(images)) 366 ]
Add multiple images in parallel (vs_first mode only).
For vs_first mode all frames after the first are encoded against
frame 0 using a process pool — significantly faster on multi-core
hardware. Other modes fall back to serial add().
Parameters
images (iterable of PIL Images or file paths):
names (optional per-frame name (parallel to images)):
metadatas (optional per-frame metadata dicts):
workers : process pool size (default (os.cpu_count())):
Returns
- list[int] – content frame indices (same order as images)
469 def close(self): 470 """Finalise and write the file. Called automatically by __exit__.""" 471 if self._closed: 472 return 473 if not self._frames: 474 raise RuntimeError("No frames added — nothing to write") 475 476 self._pool.shutdown(wait=False) 477 478 w, h = self._canvas 479 frame_count = len(self._frames) 480 481 index_offset = FILE_HEADER_SIZE 482 data_start = index_offset + frame_count * FRAME_INDEX_ENTRY_SIZE 483 offsets: list[int] = [] 484 cursor = data_start 485 for fd in self._frame_data: 486 offsets.append(cursor) 487 cursor += len(fd) 488 489 self.path.parent.mkdir(parents=True, exist_ok=True) 490 491 with open(self.path, "wb") as f: 492 f.write(pack_file_header( 493 self.mode_id, frame_count, index_offset, w, h, 494 codec=CODEC_FROM_NAME[self.codec], 495 quality=self.quality, 496 )) 497 for i, fm in enumerate(self._frames): 498 f.write(pack_index_entry( 499 data_offset=offsets[i], 500 patch_count=fm["patch_count"], 501 ref_frame_id=fm["ref_frame_id"], 502 metadata_len=fm["metadata_len"], 503 frame_type=fm["frame_type"], 504 )) 505 for fd in self._frame_data: 506 f.write(fd) 507 508 self._closed = True
Finalise and write the file. Called automatically by __exit__.
521 @property 522 def frame_count(self) -> int: 523 """Total frames including hidden baselines.""" 524 return len(self._frames)
Total frames including hidden baselines.
526 @property 527 def content_frame_count(self) -> int: 528 """Content frames only (what callers see).""" 529 return len(self._frames) - self._baseline_count
Content frames only (what callers see).
535 @property 536 def stats(self) -> list[dict]: 537 """Per-frame stats including hidden baseline frames.""" 538 result = [] 539 for i, (fm, fd) in enumerate(zip(self._frames, self._frame_data)): 540 is_baseline = i in self._baseline_ids 541 result.append({ 542 "frame_id": i, 543 "content_id": None if is_baseline else i - self._baseline_count, 544 "frame_type": "keyframe" if fm["frame_type"] == FRAME_KEYFRAME else "delta", 545 "ref_frame_id": fm["ref_frame_id"], 546 "patch_count": fm["patch_count"], 547 "data_bytes": len(fd), 548 "is_baseline": is_baseline, 549 }) 550 return result
Per-frame stats including hidden baseline frames.
79def compute_patches( 80 ref_img: Image.Image, 81 new_img: Image.Image, 82 threshold: int = 4, 83 tile_size: int = 32, 84 merge_gap: int = 8, 85 codec: str = "png", 86 quality: int = 100, 87 workers: Optional[int] = None, 88 ref_arr: Optional[np.ndarray] = None, 89 new_arr: Optional[np.ndarray] = None, 90 diff_arr: Optional[np.ndarray] = None, 91 executor: Optional[Executor] = None, 92) -> List[Patch]: 93 """ 94 Compare *new_img* against *ref_img* using a tile grid. 95 Parameters 96 ---------- 97 threshold : per-channel absolute pixel delta that counts as "changed" 98 (use 0 for perfectly lossless; 3-6 absorbs JPEG noise) 99 tile_size : grid cell size in pixels (smaller = finer granularity but 100 more patch overhead; 16–64 is a good range) 101 merge_gap : changed tiles within this many pixels of each other on the 102 same row are merged into one patch (reduces patch count) 103 workers : thread-pool size for parallel patch compression. 104 None = use ThreadPoolExecutor default (cpu_count × 4 or so). 105 Set to 1 to disable parallelism entirely. 106 107 """ 108 import numpy as np 109 110 if ref_arr is None: 111 ref = np.array(ref_img.convert("RGBA"), dtype=np.int16) 112 else: 113 ref = ref_arr 114 if ref.dtype != np.int16: 115 ref = ref.astype(np.int16, copy=False) 116 117 if new_arr is None: 118 new = np.array(new_img.convert("RGBA"), dtype=np.int16) 119 else: 120 new = new_arr 121 if new.dtype != np.int16: 122 new = new.astype(np.int16, copy=False) 123 124 if ref.shape != new.shape: 125 raise ValueError( 126 f"Image dimensions differ: ref={ref.shape[:2]} new={new.shape[:2]}" 127 ) 128 129 h, w = ref.shape[:2] 130 131 if diff_arr is None: 132 diff = np.abs(new - ref).max(axis=2) 133 else: 134 diff = diff_arr 135 if diff.shape != (h, w): 136 raise ValueError( 137 f"diff_arr dimensions differ: diff={diff.shape} expected={(h, w)}" 138 ) 139 140 cols = (w + tile_size - 1) // tile_size 141 rows = (h + tile_size - 1) // tile_size 142 143 pad_h = rows * tile_size - h 144 pad_w = cols * tile_size - w 145 if pad_h or pad_w: 146 diff_padded = np.pad(diff, ((0, pad_h), (0, pad_w)), constant_values=0) 147 else: 148 diff_padded = diff 149 150 tile_max = ( 151 diff_padded 152 .reshape(rows, tile_size, cols, tile_size) 153 .max(axis=(1, 3)) 154 ) 155 changed_mask = tile_max > threshold 156 tile_rows, tile_cols = np.where(changed_mask) 157 changed_tiles = list(zip(tile_rows.tolist(), tile_cols.tolist())) 158 159 if not changed_tiles: 160 return [] 161 162 rects = _tiles_to_rects(changed_tiles, tile_size, w, h) 163 merged = _merge_rects(rects, merge_gap, tile_size, w, h) 164 165 if len(merged) <= 2 or workers == 1: 166 patches: List[Patch] = [ 167 ( 168 rx, 169 ry, 170 rw, 171 rh, 172 _encode_crop(new_img, rx, ry, rw, rh, codec=codec, quality=quality), 173 ) 174 for (rx, ry, rw, rh) in merged 175 ] 176 else: 177 def _compress_rect(rect: tuple) -> Patch: 178 rx, ry, rw, rh = rect 179 return rx, ry, rw, rh, _encode_crop( 180 new_img, 181 rx, 182 ry, 183 rw, 184 rh, 185 codec=codec, 186 quality=quality, 187 ) 188 189 if executor is not None: 190 patches = list(executor.map(_compress_rect, merged)) 191 else: 192 with ThreadPoolExecutor(max_workers=workers) as pool: 193 patches = list(pool.map(_compress_rect, merged)) 194 195 return patches
Compare new_img against ref_img using a tile grid.
Parameters
- threshold (per-channel absolute pixel delta that counts as "changed"): (use 0 for perfectly lossless; 3-6 absorbs JPEG noise)
- tile_size (grid cell size in pixels (smaller = finer granularity but): more patch overhead; 16–64 is a good range)
- merge_gap (changed tiles within this many pixels of each other on the): same row are merged into one patch (reduces patch count)
- workers (thread-pool size for parallel patch compression.): None = use ThreadPoolExecutor default (cpu_count × 4 or so). Set to 1 to disable parallelism entirely.
293def similarity_score(img_a: Image.Image, img_b: Image.Image) -> float: 294 """ 295 Return fraction of pixels that are identical (0.0 = completely different, 296 1.0 = identical). Useful for deciding whether to force a keyframe. 297 """ 298 import numpy as np 299 a = np.array(img_a.convert("RGBA"), dtype=np.int16) 300 b = np.array(img_b.convert("RGBA"), dtype=np.int16) 301 if a.shape != b.shape: 302 return 0.0 303 diff = np.abs(a - b).max(axis=2) 304 identical_pixels = int((diff == 0).sum()) 305 total = a.shape[0] * a.shape[1] 306 return identical_pixels / total
Return fraction of pixels that are identical (0.0 = completely different, 1.0 = identical). Useful for deciding whether to force a keyframe.