|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright Contributors to the OpenImageIO project. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# https://github.com/AcademySoftwareFoundation/OpenImageIO |
| 6 | + |
| 7 | +import struct |
| 8 | + |
| 9 | + |
| 10 | +BASE = "base-short-exif.webp" |
| 11 | +EXIF_FLAG = 0x08 |
| 12 | + |
| 13 | +CASES = [ |
| 14 | + ("short-exif-len0.webp", b""), |
| 15 | + ("short-exif-len4.webp", b"Exif"), |
| 16 | + ("short-exif-len5.webp", b"Exif\x00"), |
| 17 | + ("short-exif-len6.webp", b"Exif\x00\x00"), |
| 18 | + ("short-exif-len13.webp", b"Exif\x00\x00II*\x00\x08\x00\x00"), |
| 19 | +] |
| 20 | + |
| 21 | + |
| 22 | +def read_chunks(data): |
| 23 | + if len(data) < 12 or data[:4] != b"RIFF" or data[8:12] != b"WEBP": |
| 24 | + raise RuntimeError("%s is not a RIFF WebP file" % BASE) |
| 25 | + |
| 26 | + chunks = [] |
| 27 | + offset = 12 |
| 28 | + while offset < len(data): |
| 29 | + if offset + 8 > len(data): |
| 30 | + raise RuntimeError("truncated WebP chunk header") |
| 31 | + fourcc = data[offset : offset + 4] |
| 32 | + size = struct.unpack_from("<I", data, offset + 4)[0] |
| 33 | + begin = offset + 8 |
| 34 | + end = begin + size |
| 35 | + if end > len(data): |
| 36 | + raise RuntimeError("truncated WebP chunk payload") |
| 37 | + chunks.append((fourcc, data[begin:end])) |
| 38 | + offset = end + (size & 1) |
| 39 | + return chunks |
| 40 | + |
| 41 | + |
| 42 | +def write_chunk(fourcc, payload): |
| 43 | + chunk = fourcc + struct.pack("<I", len(payload)) + payload |
| 44 | + if len(payload) & 1: |
| 45 | + chunk += b"\x00" |
| 46 | + return chunk |
| 47 | + |
| 48 | + |
| 49 | +def make_webp(exif_payload, image_chunks): |
| 50 | + vp8x_payload = bytes((EXIF_FLAG, 0, 0, 0, 0, 0, 0, 0, 0, 0)) |
| 51 | + chunks = write_chunk(b"VP8X", vp8x_payload) |
| 52 | + chunks += write_chunk(b"EXIF", exif_payload) |
| 53 | + for fourcc, payload in image_chunks: |
| 54 | + if fourcc not in (b"VP8X", b"EXIF"): |
| 55 | + chunks += write_chunk(fourcc, payload) |
| 56 | + body = b"WEBP" + chunks |
| 57 | + return b"RIFF" + struct.pack("<I", len(body)) + body |
| 58 | + |
| 59 | + |
| 60 | +with open(BASE, "rb") as input_file: |
| 61 | + base_data = input_file.read() |
| 62 | + |
| 63 | +image_chunks = read_chunks(base_data) |
| 64 | + |
| 65 | +for filename, exif_payload in CASES: |
| 66 | + with open(filename, "wb") as output_file: |
| 67 | + output_file.write(make_webp(exif_payload, image_chunks)) |
0 commit comments