io7m | single-page | multi-page | Calino 2.0

Calino 2.0

Calino 2.0
CREATOR Mark Raynsford
DATE 2026-05-01T11:32:59+00:00
DESCRIPTION Specification for the Calino texture file format.
IDENTIFIER ba8fa621-69a4-486d-b5d7-1c31f76eba32
LANGUAGE en
RIGHTS Public Domain
TITLE Calino 2.0
This specification defines version 2.0 of the calino file format. The calino format is a carefully designed file format intended for the storage and delivery of texture data for realtime 3D rendering applications.
This specification is divided into an abstract model and a separate binary encoding. The purpose of the model is to describe the semantics of calino files; the actual meaning of the data within, and to describe properties and invariants that must be true for all valid calino files. The purpose of the binary encoding is to describe how the model is transformed to a sequence of bytes/octets; it describes the low-level on-disk format of calino files. This layered approach is intended to allow for specifying the format with a level of precision that will allow data in the calino format to remain readable for decades into the future, and in a manner that ensures that the format is not dependent on any present-day rendering APIs.
Developers wishing to write their own code to read and write calino files might find it easiest to view the binary encoding section first. The calino format is designed to be straightforward to parse, requiring only a few minimal primitives to express the entirety of the format, and requires no references to external specifications (unlike many other image/texture file formats) [1]. Once a developer is able to read data from an existing calino file, they should consult the model to understand what the data they're receiving actually means. The model chapters are arranged in dependency order starting with the most fundamental concepts, and ending with the top level definitions of the various texture types.

Footnotes

1
It would be more accurate to say that the calino specification does not depend on any other specifications that are at the same level of abstraction. For example, the calino specification makes references to Unicode, IEEE 754, and so on. It does not, however, require understanding any other existing texture formats, or depend on any definitions given in the specifications for any rendering APIs.
References to this footnote: 1
This section of the specification provides a simple, informal description of the calino format. It is intended as the recommended starting point for readers who want to understand the purpose and structure of the format before consulting the formal model or the binary encoding.
The following subsections walk through the main concepts: the purpose of the format, the kinds of textures that a calino file can store, the image information and channels that describe how pixel data is laid out and interpreted, the mipmaps that make up a texture, and the section-based file layout. An annotated hex dump is provided as a concrete illustration of a calino file.
The following subsections are informative; if any part of the following text disagrees with the rest of the specification, the rest of the specification should be considered the source of truth and this informative text mistaken.
This specification assumes that readers are familiar with the following:

2.2.2. Familiar Concepts

  • Basic graphics concepts including GPUs, textures, and mipmaps.
  • Byte ordering / endianness.
  • The DEFLATE and LZ4 compression algorithms DEFLATE LZ4.
  • Unicode text and its UTF-8 byte encoding UTF-8.
To read the full formal specification, the reader must be familiar with the Rocq language Rocq.
The calino format provides a simple and strongly-specified file format for storing textures that will be processed on the GPU. It is intended for storing two-dimensional, array, and cube textures, including mipmapped variants. It is not intended for storing polygon mesh data. For polygon mesh data, see the zeniro format zeniro.
General-purpose image interchange formats such as PNG cannot represent premultiplied alpha. Container formats such as KTX are complex and coupled to the OpenGL and Vulkan standards, and their texture types are not self-describing. A calino file fully describes the layout and interpretation of its image data, and can be parsed without consulting any external graphics standard. A consumer can therefore always recover the raw and compressed bytes of each mipmap, even when it does not understand the specific image format or compression method in use.
The file format is designed to be simple to read and write, and is defined in an extremely strict manner with a full formal specification that describes both the meaning of the data stored in files and the required structure of that data. The format is versioned, and is designed to facilitate forwards and backwards compatibility. The meaning of the data in calino files is described by the model, whilst the actual on-disk structure is described by the binary encoding.
A calino file describes a texture of one of three kinds: two-dimensional, array, or cube. All three are represented in the same way on disk, as a description of the image data followed by a run of mipmap data. The kind does not change how the bytes are stored, only how a reader groups them.
At each mipmap level, a two-dimensional texture holds a single image, an array texture holds one image per array layer, and a cube texture holds six images, one for each face of the cube. The declared kind tells the reader which of these groupings to apply, so that the underlying data is interpreted correctly without the reader having to make assumptions about it.
Every calino file begins by describing its own image data. The image information records the dimensions of the image and everything else a reader needs to interpret the pixels: the channels that make up each pixel, the color space, the compression method, the coordinate system, and the byte ordering of multi-octet channels.
The central idea is the channel: the set of intensity values for one color component (red, green, blue, alpha, and so on) across all the pixels in the image. Rather than naming an opaque format, calino describes each channel explicitly, including what it represents and what numeric type it uses, and then describes how the channels are laid out in memory. The channels of a pixel are written out in order with no padding between them. A set of channels is either packed, where the bits of several channels share a single integer value (so a single octet may hold bits from more than one channel), or unpacked, where each channel occupies a whole number of octets:
The precise set of channel types and layouts is defined in the model.
The image data of a texture is a sequence of mipmaps, a stack of progressively smaller copies of a base image. The base image is level 0, and each successive level is half the width and height of the one before it. A texture without mipmaps simply has a single level.
The levels are stored in the file with the smallest (highest-numbered) level first and the base image last. This is deliberate: it matches the way a GPU typically loads a texture, which is to display the small, cheap level immediately and progressively replace it with higher-detail levels as they arrive. The exact per-level metadata (sizes and checksums, and per-face offsets for cube textures) is defined in the mipmaps section of the model.
A calino file is a short fixed header followed by a sequence of explicitly-sized sections. The header contains a magic identifier and a major and minor version number. Each section carries a 64-bit identifier, a 64-bit size, that many octets of data, and then padding so that the next section begins on a 16-octet boundary.
Because every section carries its own size, a reader can skip any section it does not recognize simply by seeking forward past its data. This is what makes the format extensible: new section types can be introduced without breaking readers that do not know about them. A file must begin with a Calino section, contain one image data section per mipmap level (or per level and layer pair, for array images), and end with an end section.
An annotated hexdump of an example file is as follows:

2.8.2. Hex Dump

The fixed-size file header indicating the type and version of the file:

                             Format major version 2, minor version 0
          |- Calino identifier -|  |---------| |---------|
00000000  89 43 4c 4e 0d 0a 1a 0a  00 00 00 02 00 00 00 00  |.CLN............|

The calino section containing information about the contents of the file:

          |-Identifier CLNIINFO-|  |-Section size (1368) |
00000010  43 4c 4e 5f 43 4c 4e 4f  00 00 00 00 00 00 05 58  |CLN_CLNO.......X|
          Length(1364)|- JSON text ... ------------------|
00000020  00 00 05 54 7b 22 40 54  79 70 65 22 3a 22 32 44  |...T{"@Type":"2D|
00000030  22 2c 22 49 6d 61 67 65  49 6e 66 6f 22 3a 7b 22  |","ImageInfo":{"|
00000040  49 6d 61 67 65 53 69 7a  65 22 3a 7b 22 53 69 7a  |ImageSize":{"Siz|
00000050  65 58 22 3a 33 32 2c 22  53 69 7a 65 59 22 3a 33  |eX":32,"SizeY":3|
00000060  32 2c 22 53 69 7a 65 5a  22 3a 31 7d 2c 22 43 68  |2,"SizeZ":1},"Ch|
00000070  61 6e 6e 65 6c 73 4c 61  79 6f 75 74 22 3a 7b 22  |annelsLayout":{"|
...
...
000004d0  35 7d 5d 2c 22 4d 65 74  61 64 61 74 61 22 3a 5b  |5}],"Metadata":[|
000004e0  7b 22 4b 65 79 22 3a 22  64 63 2e 72 69 67 68 74  |{"Key":"dc.right|
000004f0  73 22 2c 22 56 61 6c 75  65 22 3a 22 50 75 62 6c  |s","Value":"Publ|
00000500  69 63 20 44 6f 6d 61 69  6e 22 7d 2c 7b 22 4b 65  |ic Domain"},{"Ke|
00000510  79 22 3a 22 64 63 2e 69  64 65 6e 74 69 66 69 65  |y":"dc.identifie|
00000520  72 22 2c 22 56 61 6c 75  65 22 3a 22 66 39 63 32  |r","Value":"f9c2|
00000530  63 66 31 33 2d 38 39 31  39 2d 34 63 66 64 2d 62  |cf13-8919-4cfd-b|
00000540  38 38 66 2d 30 61 36 63  39 65 35 35 32 64 35 39  |88f-0a6c9e552d59|
00000550  22 7d 2c 7b 22 4b 65 79  22 3a 22 64 63 2e 74 69  |"},{"Key":"dc.ti|
00000560  74 6c 65 22 2c 22 56 61  6c 75 65 22 3a 22 46 61  |tle","Value":"Fa|
                                   |- Padding -----------|
00000570  64 65 33 32 22 7d 5d 7d  ff ff ff ff ff ff ff ff  |de32"}]}........|

A section for a mipmap of a 2D image:

          |-Identifier CLN_MI2D-|  |-Section size (20)  -|
00000580  43 4c 4e 5f 4d 49 32 44  00 00 00 00 00 00 00 14  |CLN_MI2D........|
          |Level (5)| |- Padding ------------------------|
00000590  00 00 00 05 ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
                      |- Padding ------------------------|
000005a0  00 00 80 ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|

          |-Identifier CLN_MI2D-|  |-Section size (32)  -|
000005b0  43 4c 4e 5f 4d 49 32 44  00 00 00 00 00 00 00 20  |CLN_MI2D....... |
          |Level (4)| |- Padding ------------------------|
000005c0  00 00 00 04 ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
000005d0  00 00 80 ff ff 00 80 ff  00 ff 80 ff ff ff 80 ff  |................|

          |-Identifier CLN_MI2D-|  |-Section size (80)  -|
000005e0  43 4c 4e 5f 4d 49 32 44  00 00 00 00 00 00 00 50  |CLN_MI2D.......P|
          |Level (3)| |- Padding ------------------------|
000005f0  00 00 00 03 ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
00000600  00 00 80 ff 55 00 80 ff  aa 00 80 ff ff 00 80 ff  |....U...........|
00000610  00 55 80 ff 55 55 80 ff  aa 55 80 ff ff 55 80 ff  |.U..UU...U...U..|
00000620  00 aa 80 ff 55 aa 80 ff  aa aa 80 ff ff aa 80 ff  |....U...........|
00000630  00 ff 80 ff 55 ff 80 ff  aa ff 80 ff ff ff 80 ff  |....U...........|

          |-Identifier CLN_MI2D-|  |-Section size (272) -|
00000640  43 4c 4e 5f 4d 49 32 44  00 00 00 00 00 00 01 10  |CLN_MI2D........|
          |Level (2)| |- Padding ------------------------|
00000650  00 00 00 02 ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
00000660  00 00 80 ff 24 00 80 ff  48 00 80 ff 6d 00 80 ff  |....$...H...m...|
00000670  91 00 80 ff b6 00 80 ff  da 00 80 ff ff 00 80 ff  |................|
00000680  00 24 80 ff 24 24 80 ff  48 24 80 ff 6d 24 80 ff  |.$..$$..H$..m$..|
00000690  91 24 80 ff b6 24 80 ff  da 24 80 ff ff 24 80 ff  |.$...$...$...$..|
...
00000730  91 da 80 ff b6 da 80 ff  da da 80 ff ff da 80 ff  |................|
00000740  00 ff 80 ff 24 ff 80 ff  48 ff 80 ff 6d ff 80 ff  |....$...H...m...|
00000750  91 ff 80 ff b6 ff 80 ff  da ff 80 ff ff ff 80 ff  |................|

          |-Identifier CLN_MI2D-|  |-Section size (1040)-|
00000760  43 4c 4e 5f 4d 49 32 44  00 00 00 00 00 00 04 10  |CLN_MI2D........|
          |Level (1)| |- Padding ------------------------|
00000770  00 00 00 01 ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
00000780  00 00 80 ff 11 00 80 ff  22 00 80 ff 33 00 80 ff  |........"...3...|
00000790  44 00 80 ff 55 00 80 ff  66 00 80 ff 77 00 80 ff  |D...U...f...w...|
000007a0  88 00 80 ff 99 00 80 ff  aa 00 80 ff bb 00 80 ff  |................|
000007b0  cc 00 80 ff dd 00 80 ff  ee 00 80 ff ff 00 80 ff  |................|
000007c0  00 11 80 ff 11 11 80 ff  22 11 80 ff 33 11 80 ff  |........"...3...|
...
00000b60  88 ff 80 ff 99 ff 80 ff  aa ff 80 ff bb ff 80 ff  |................|
00000b70  cc ff 80 ff dd ff 80 ff  ee ff 80 ff ff ff 80 ff  |................|

          |-Identifier CLN_MI2D-|  |-Section size (4112)-|
00000b80  43 4c 4e 5f 4d 49 32 44  00 00 00 00 00 00 10 10  |CLN_MI2D........|
          |Level (0)| |- Padding ------------------------|
00000b90  00 00 00 00 ff ff ff ff  ff ff ff ff ff ff ff ff  |................|
00000ba0  00 00 80 ff 08 00 80 ff  10 00 80 ff 18 00 80 ff  |................|
00000bb0  20 00 80 ff 29 00 80 ff  31 00 80 ff 39 00 80 ff  | ...)...1...9...|
00000bc0  41 00 80 ff 4a 00 80 ff  52 00 80 ff 5a 00 80 ff  |A...J...R...Z...|
00000bd0  62 00 80 ff 6a 00 80 ff  73 00 80 ff 7b 00 80 ff  |b...j...s...{...|
...
00001b50  62 ff 80 ff 6a ff 80 ff  73 ff 80 ff 7b ff 80 ff  |b...j...s...{...|
00001b60  83 ff 80 ff 8b ff 80 ff  94 ff 80 ff 9c ff 80 ff  |................|
00001b70  a4 ff 80 ff ac ff 80 ff  b4 ff 80 ff bd ff 80 ff  |................|
00001b80  c5 ff 80 ff cd ff 80 ff  d5 ff 80 ff de ff 80 ff  |................|
00001b90  e6 ff 80 ff ee ff 80 ff  f6 ff 80 ff ff ff 80 ff  |................|

          |-Identifier CLN_END!-|  |-Section size (0) ---|
00001ba0  43 4c 4e 5f 45 4e 44 21  00 00 00 00 00 00 00 00  |CLN_END!........|
The formal specification described here is written in the specification language of the Rocq theorem prover . The language is a total, pure-functional, dependently-typed language allowing for describing systems in rigorous detail including machine-checked proofs of various chosen properties.
Readers are not expected to be able to understand the bodies of the proof texts, and doing so is not in any case required. As long as one can understand the meaning of the propositions being expressed, it suffices to trust that the proofs are correct as they are all machine-checked whenever the specification is published.
The full sources of the entire specification are published at the end of this book.
The specification makes reference to the Unicode character set which, at the time of writing, is at version 13.0.0. The specification often references specific Unicode characters, and does so using the standard notation U+NNNN, where N represents a hexadecimal digit. For example, U+03BB corresponds to the lowercase lambda symbol λ.
Where the specification refers to sets, it is referring to sets as defined in Zermelo-Fraenkel set theory .

3.3.2. ZFC

Notation Description
e ∈ A e is an element of the set A
e ∉ A e is not an element of the set A
{ x₀, x₁, ... xₙ } A set consisting of values from x₀ to xₙ
{ e ∈ A | p(e) } A set consisting of the elements of A for which the proposition p holds
|A| The cardinality of the set A; a measure of the number of elements in A
∅ The empty set
𝔹 The booleans
ℕ The natural numbers
ℝ The real numbers
ℤ The integers
[a, b] A closed interval in a set (given separately or implicit from the types of a and b), from a to b, including a and b
(a, b] A closed interval in a set (given separately or implicit from the types of a and b), from a to b, excluding a but including b
[a, b) A closed interval in a set (given separately or implicit from the types of a and b), from a to b, including a but excluding b
(a, b) A closed interval in a set (given separately or implicit from the types of a and b), from a to b, excluding a and b
A ⊂ B A is a subset of, and is not equal to, B
A ⊆ B A is a subset of, or is equal to, B
A ∩ B The smallest set of elements that appear in both A and B (intersection).
The calino texture file format is optimized for the storage of textures used for real-time 3D rendering. The format provides the following features:

4.1.2. Features

  • Detailed information about the format and layout of image data is included in all files. Image data, in the common case, can be introspected without requiring consulting any kind of external specification. The information provided about image data includes dimensions, full channel layout and type information, compression and supercompression methods, color space, coordinate system, alpha premultiplication, and byte ordering for formats that use components larger than a single octet.
  • Mipmaps are natively supported and are not treated differently to textures that do not have mipmaps; a texture without mipmaps is considered to comprise a single mip level 0. Mipmaps are exposed in a manner that facilitates efficient texture streaming.
  • Rendering system independence. The format specification does not require implementers to read the Vulkan, OpenGL, DirectX specifications in order to parse files.
  • Ease of parsing. The binary format is designed to facilitate easy and secure parsing without requiring backtracking or unbounded storage use. A competent developer should be able to implement a full parser within a week or two of work.
  • Carefully layered metadata. Consumers are not required to understand everything about the underlying image data in order to make use of it. For example, if image data is encoded using an unusual and/or proprietary texture format (such as A5B3G3R3), consumers can still trivially extract the raw data of each mipmap even if they cannot necessarily perform rendering with image data of that format. Likewise, the compressed bytes of each mipmap can always be obtained even if the compression method is unknown to the consumer.
  • Extensibility. The format consists of explicitly-sized sections with a well-defined ordering. Consumers can trivially skip sections that they do not understand. Sections carry unique 64-bit identifiers; if a section has an identifier not recognized by a consumer, the consumer may skip the section. The raw bytes that comprise a section can be extracted regardless of whether or not the consumer understands them. This specification defines a number of "standard" image data types that consumers are expected to understand, but the format also allows for declaring new self-describing image data types.
  • Practical metadata. The format provides a standard section that contains UTF-8 encoded keys and values intended to hold arbitrary metadata. Metadata that cannot be expressed as a UTF-8 string can be included as a custom section that can be skipped by consumers that do not recognize it.
This section of the specification documents the abstract model that the calino format uses to express all of the above.
This specification makes frequent use of values that must be evenly divisible by 8. Formally, a number n is evenly divisible by 8 if n mod 8 = 0.

4.2.2. Divisible8

Definition divisible8 (x : Z) : Prop :=
  Z.modulo x 8 = 0.
Values of certain types defined in this specification are identified by Lanark strings, a string format specified normatively by the Lanark reference; for example, the values of the enumerated types defined in this specification are identified by Lanark strings. A Lanark string is a value of lanarkT, and a Lanark string is valid when it satisfies lanarkValidT.
For each type identified by a Lanark string, this specification defines a function that maps each value of the type to its identifying Lanark string (for example, channelTypeDescribe).
The calino specification reserves the use of all Lanark strings that start with com.io7m.calino.

4.3.4. Calino Reserved Descriptor

Definition calinoReservedDescriptor (s : string) : lanarkT :=
  Lanark "com" ["io7m"; "calino"; s].

4.3.5. Calino Reserved Descriptor Predicate

Definition isCalinoReservedDescriptor (x : lanarkT) : Prop :=
  match x with
  | Lanark a (b :: c :: _) => a = "com" /\ b = "io7m" /\ c = "calino"
  | _                      => False
  end.
Types that admit custom values (for example CTCustom, CSCustom, and FlagCustom) require the custom value to be a Lanark string that is valid and that is not reserved by calino.
Decidability of isCalinoReservedDescriptor is established by isCalinoReservedDescriptorDecidable. The proposition isCalinoReservedDescriptorValid states that, provided s satisfies isLanarkSecondarySegment, the value calinoReservedDescriptor s is a valid Lanark string.

4.3.8. Calino Reserved Descriptor Decidable

Theorem isCalinoReservedDescriptorDecidable : forall x,
  {isCalinoReservedDescriptor x}+{~isCalinoReservedDescriptor x}.
Proof.
  (* Proof omitted for brevity; see Descriptor.v for proofs. *)
Qed.

4.3.9. Calino Reserved Descriptor Valid

Theorem isCalinoReservedDescriptorValid : forall x,
  isLanarkSecondarySegment x
  -> lanarkValidT (calinoReservedDescriptor x).
Proof.
  (* Proof omitted for brevity; see Descriptor.v for proofs. *)
Qed.
A bit is a single digit in the base-2 numbering system. A bit may either be 0 or 1:

4.4.2. Bit

Inductive bit : Set :=
  | B0
  | B1.
A sequence of bits may be divided into groups of eight bits known as octets. We avoid the use of the term byte because a byte hasn't consistently been equivalent to eight bits throughout all of computing history. An octet may either be exact or a remainder. An octet may be a remainder if the length of the sequence of bits used to produce it was not evenly divisible by 8. The first n groups of 8 bits consumed from a sequence of bits s will produce octets that are exact, with the remaining k bits (where k < 8) will produce at most one remainder octet. The remainder octet, if any, has its least significant 8 - k bits set to 0.

4.4.4. Octet

Inductive octet : Set :=
  | OctExact  : bit -> bit -> bit -> bit -> bit -> bit -> bit -> bit -> octet
  | OctRemain : bit -> bit -> bit -> bit -> bit -> bit -> bit -> bit -> octet.
The sequence of bits s will be consumed in order such that octets are filled from most significant to least significant bit order.
If the sequence of octets o produced is arranged such that the first bit of s appears as the most significant bit of the first octet in o, then o is said to be in big-endian order.

4.4.7. Big Endian Octets (Aux)

Fixpoint octetsBigEndianAux
  (bits   : list bit)
  (octets : list octet)
: list octet :=
  match bits with
  | (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: b0 :: rest) =>
    octets ++ [OctExact b7 b6 b5 b4 b3 b2 b1 b0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 b3 b2 b1 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 b3 b2 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: b3 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 b3 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 B0 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: rest) =>
    octets ++ [OctRemain b7 b6 B0 B0 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: rest) =>
    octets ++ [OctRemain b7 B0 B0 B0 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | [] =>
    octets
  end.

4.4.8. Big Endian Octets

Definition octetsBigEndian (bits : list bit) : list octet :=
  octetsBigEndianAux bits [].
If the sequence of octets o produced is arranged such that the first bit of s appears as the most significant bit of the last octet in o, then o is said to be in little-endian order.

4.4.10. Little Endian Octets

Definition octetsLittleEndian (bits : list bit) : list octet :=
  rev (octetsBigEndianAux bits []).
A sequence of bits s such that divisible8 (length s) will produce a sequence consisting of entirely exact octets.

4.4.12. Divisible8 Exact Octets (Big endian)

Theorem octetsBigEndianLengthDivisibleAllExact : forall (b : list bit),
  divisible8 (length b) -> Forall octetIsExact (octetsBigEndian b).
Proof.
  (* Proof omitted for brevity; see OctetOrder.v for proofs. *)
Qed.

4.4.13. Divisible8 Exact Octets (Little endian)

Theorem octetsLittleEndianLengthDivisibleAllExact : forall (b : list bit),
  divisible8 (length b) -> Forall octetIsExact (octetsLittleEndian b).
Proof.
  (* Proof omitted for brevity; see OctetOrder.v for proofs. *)
Qed.
A sequence of bits s such that ¬ divisible8 (length s) will produce a remainder octet.

4.4.15. Indivisible8 Remainder Octets (Big endian)

Theorem octetsBigEndianLengthIndivisibleRemainder : forall (b : list bit),
  0 < length b mod 8 -> exists o, In o (octetsBigEndian b) /\ octetIsRemainder o.
Proof.
  (* Proof omitted for brevity; see OctetOrder.v for proofs. *)
Qed.

4.4.16. Indivisible8 Remainder Octets (Little endian)

Theorem octetsLittleEndianLengthIndivisibleRemainder : forall (b : list bit),
  0 < length b mod 8 -> exists o, In o (octetsLittleEndian b) /\ octetIsRemainder o.
Proof.
  (* Proof omitted for brevity; see OctetOrder.v for proofs. *)
Qed.
The endianness of a sequence of octets is a value of octetOrder. A value of octetOrder is identified by the following Lanark string:

4.4.18. Byte Order

Inductive octetOrder : Set :=
  | OctetOrderBig
  | OctetOrderLittle.

4.4.19. Byte Order Description

Definition byteOrderDescribe (b : octetOrder) : lanarkT :=
  match b with
  | OctetOrderBig    => calinoReservedDescriptor "big_endian"
  | OctetOrderLittle => calinoReservedDescriptor "little_endian"
  end.
The identifying Lanark string of every value of octetOrder is valid (byteOrderDescribeValid).

4.4.21. Byte Order Description Valid

Theorem byteOrderDescribeValid : forall (b : octetOrder),
  lanarkValidT (byteOrderDescribe b).
Proof.
  (* Proof omitted for brevity; see ByteOrder.v for proofs. *)
Qed.
A channel in calino corresponds to the traditional definition of a channel in computer graphics: A channel consists of a set of intensity values for one of the color components that make up an image. For example, a typical RGB image has a red channel, a green channel, and a blue channel that store the intensity values of each component for each pixel in the image. The following image shows the separate red, green, and blue channels used for the pixels of an RGB image:
As the calino package is intended for use in real-time 3D graphics, it makes the assumption that for an image consisting of channels [c₁, cₙ], each pixel Pᵢ in the image stores channel values [c₁(ᵢ), cₙ (ᵢ)] sequentially in memory:
A set of channels may be packed or unpacked. In an unpacked set of channels, each channel is of a size in bits that is a multiple of 8. This means that when the set of channels is stored in memory for each pixel, each channel occupies at least one octet in memory, and no two channels in a given pixel occupy the same octet. For channels that are larger than a single octet, the byte ordering of the underlying host computer dictates the exact order of the octets that make up a single channel. Otherwise, the groups of octets that comprise the data for a set of channels are ordered according to the channel declaration order. For example, a common unpacked image format in computer graphics, at the time of writing, is R8G8B8. In the R8G8B8 format, each channel occupies 8 bits, and the channels are stored such that R comes first in memory, followed by G, and then B:
Note that, because all of the channels are 8 bits, the mapping from the channels to the underlying host octets does not depend on the byte ordering of the underlying host computer. Another common unpacked image format where the underlying byte ordering of the host computer does affect the mapping from channels to octets is the R16G16B16 format. In the R16G16B16 format, each channel requires 16 bits and so each channel must be mapped to two octets in memory. If the underlying host byte ordering is little-endian, then the most significant bits of each channel are stored in the higher of the two octets used for the channel. If the underlying host byte ordering is big-endian, then the most significant bits of each channel are stored in the lower of the two octets used for the channel. For example, channels in the R16G16B16 format are stored as follows on a computer with little-endian byte ordering:
As shown in the diagram, the 8 most significant bits of the R channel of pixel 0 are stored in octet 1. The 8 least significant bits of the R channel of pixel 0 are stored in octet 0. This pattern continues for each subsequent channel of each subsequent pixel. Note that regardless of the byte ordering, the octets that make up the R channel are stored first, followed by the G channel, and finally the B channel. The same format on a computer with big-endian byte ordering is stored as follows:
As shown in the diagram, the 8 most significant bits of the R channel of pixel 0 are stored in octet 0. The 8 least significant bits of the R channel of pixel 0 are stored in octet 1. This pattern continues for each subsequent channel of each subsequent pixel. Note that regardless of the byte ordering, the octets that make up the R channel are stored first, followed by the G channel, and finally the B channel.
In a packed set of channels, each channel may be of any size in bits (excluding zero) but the sum of the sizes of all of the channels in the set typically must be a multiple of 8. The calino package restricts this definition further by stating that the sum of the sizes of the channels must be in the set {8, 16, 32, 64}. Conceptually, the bits of all channels are packed into a single integer value, and then this integer value is stored in memory according to the host computer byte ordering. For example, a common packed image format in computer graphics, at the time of writing, is R5G6B5. In the R5G6B5 format, the bits of all of the channels are packed into a single 16-bit integer k such that the 5 bits of the R channel are packed into the 5 most significant bits of k, followed by the 6 bits of the G channel, followed by the 5 bits of the B channel. The value of k is then stored into memory according to the host computer byte ordering:
In the above diagram, it's clear that the 5 bits that make up the R channel of pixel 0 are mapped to bits [11,15] in k. The 6 bits that make up the G channel are mapped to bits [5,10] in k, and the remaining 5 bits that make up the B channel are mapped to bits [0,4] in k. On a big-endian computer, the two octets that make up k are arranged such that the most significant bits of k end up in octet 0 in memory, whilst the least significant bits of k end up in octet 1 in memory. On a little-endian computer, the two octets that make up k are arranged such that the most significant bits of k end up in octet 1 in memory, whilst the least significant bits of k end up in octet 0 in memory. Note that this means that the G channel ends up divided into two pieces with the R and B channels sandwiched between it. It's also important to note that the ordering of bits does not change between big-endian and little-endian systems. This demonstrates the critical difference between packed and unpacked formats: In a packed format, any given octet may contain bits from more than one channel, whilst in an unpacked format, a given octet will contain bits from exactly one channel. At the time of writing, no rendering API appears to have defined any packed image formats that pack channels into an integer value larger than 32 bits.
The information provided about a set of channels largely attempts to answer two main questions: "How do I get image data to and from storage?" and "How do I interpret the image data once I have it?". Channel semantic and channel type information answers the latter question, whilst channel descriptions answer the former. The aggregates of these values, channel layouts, answer a little of both questions.
A channel semantic specifies how a particular channel should be interpreted within the context of an image. A channel semantic may be one of the following values:

4.5.2.2. Channel Semantic Values

Inductive channelSemanticT : Set :=
  | CSRed
  | CSGreen
  | CSBlue
  | CSAlpha
  | CSDepth
  | CSStencil
  | CSExponent
  | CSUnused
  | CSCustom : lanarkT -> channelSemanticT.
A channel semantic is identified by the following Lanark string:

4.5.2.4. Channel Semantic Description

Definition channelSemanticDescribe (c : channelSemanticT) : lanarkT :=
  match c with
  | CSRed      => calinoReservedDescriptor "red"
  | CSGreen    => calinoReservedDescriptor "green"
  | CSBlue     => calinoReservedDescriptor "blue"
  | CSAlpha    => calinoReservedDescriptor "alpha"
  | CSDepth    => calinoReservedDescriptor "depth"
  | CSStencil  => calinoReservedDescriptor "stencil"
  | CSExponent => calinoReservedDescriptor "exponent"
  | CSUnused   => calinoReservedDescriptor "unused"
  | CSCustom s => s
  end.
The conditions under which a channel semantic is valid are declared by channelSemanticValid (decidable: channelSemanticValidDecidable). For a valid value, its identifying Lanark string is itself valid ( channelSemanticDescribeValid).

4.5.2.6. Channel Semantic Validity

Definition channelSemanticValid (c : channelSemanticT) : Prop :=
  match c with
  | CSRed      => True
  | CSGreen    => True
  | CSBlue     => True
  | CSAlpha    => True
  | CSDepth    => True
  | CSStencil  => True
  | CSExponent => True
  | CSUnused   => True
  | CSCustom s => (~isCalinoReservedDescriptor s) /\ lanarkValidT s
  end.

4.5.2.7. Channel Semantic Validity Decidable

Theorem channelSemanticValidDecidable : forall c,
  {channelSemanticValid c}+{~channelSemanticValid c}.
Proof.
  (* Proof omitted for brevity; see ChannelSemantic.v for proofs. *)
Qed.

4.5.2.8. Channel Semantic Description Valid

Theorem channelSemanticDescribeValid : forall (c : channelSemanticT),
  channelSemanticValid c ->
  match c with
  | CSCustom s => lanarkValidT s
  | _          => lanarkValidT (channelSemanticDescribe c)
  end.
Proof.
  (* Proof omitted for brevity; see ChannelSemantic.v for proofs. *)
Qed.
A channel description combines a channel semantic and a non-zero size value expressed in bits. The size value specifies the number of bits of storage required for a single value in the channel.

4.5.3.2. Channel Description

Inductive channelDescriptionT : Set := ChannelDescription {
  cdSemantic : channelSemanticT;
  cdBits     : Z
}.
The conditions under which a channel description is valid are declared by channelDescriptionValid (decidable: channelDescriptionValidDecidable): the size is non-zero, does not exceed 64 bits, and the channel semantic is valid.

4.5.3.4. Channel Description Validity

Definition channelDescriptionValid (c : channelDescriptionT) : Prop :=
     0 < (cdBits c) <= 64
  /\ channelSemanticValid (cdSemantic c).

4.5.3.5. Channel Description Validity Decidable

Theorem channelDescriptionValidDecidable : forall c,
  {channelDescriptionValid c}+{~channelDescriptionValid c}.
Proof.
  (* Proof omitted for brevity; see ChannelDescription.v for proofs. *)
Qed.
A channel layout describes how a set of channels are ordered. A channel layout may either be packed or unpacked.

4.5.4.1.2. Channel Layout

Inductive channelLayoutDescriptionT : Set :=
  | CLDUnpacked : channelLayoutDescriptionUnpackedT -> channelLayoutDescriptionT
  | CLDPacked   : channelLayoutDescriptionPackedT   -> channelLayoutDescriptionT.
The total number of bits required by a set of channels is the sum of the sizes of each channel, as given by channelDescriptionsBitsTotal:

4.5.4.1.4. Channels Required Bits

Fixpoint channelDescriptionsBitsTotal (c : list channelDescriptionT) : Z :=
  match c with
  | nil         => 0
  | (x :: rest) => (cdBits x) + (channelDescriptionsBitsTotal rest)
  end.
The size in bits of each channel in an unpacked layout must be divisible by 8, as declared by channelDescriptionBitsDivisible8. The size in bits of a packed layout is equal to the size in bits of its layout packing, which is always divisible by 8. It follows that the total size in bits of any layout is always divisible by 8.

4.5.4.1.6. Channel Bits Divisible 8

Definition channelDescriptionBitsDivisible8 (c : channelDescriptionT) : Prop :=
  divisible8 (cdBits c).
The proposition channelDescriptionBitsDivisible8 is decidable ( channelDescriptionBitsDivisible8Decidable). The conditions under which a channel layout is valid are declared by channelLayoutDescriptionValidT (decidable: channelLayoutDescriptionValidDecidable).

4.5.4.1.8. Channel Description Bits Divisible 8 Decidable

Theorem channelDescriptionBitsDivisible8Decidable : forall c,
  {channelDescriptionBitsDivisible8 c}+{~channelDescriptionBitsDivisible8 c}.
Proof.
  (* Proof omitted for brevity; see ChannelDescription.v for proofs. *)
Qed.

4.5.4.1.9. Channel Layout Description Validity Decidable

Theorem channelLayoutDescriptionValidDecidable : forall c,
  {channelLayoutDescriptionValidT c}+{~channelLayoutDescriptionValidT c}.
Proof.
  (* Proof omitted for brevity; see ChannelDescription.v for proofs. *)
Qed.
An unpacked layout consists of a non-empty sequence of channels where the size of each channel must be divisible by 8.

4.5.4.2.2. Unpacked Layout

Inductive channelLayoutDescriptionUnpackedT : Set := ChannelLayoutDescriptionUnpacked {
  uChannels : list channelDescriptionT;
}.
The constraints on an unpacked layout are declared by channelLayoutDescriptionUnpackedValidT (decidable: channelLayoutDescriptionUnpackedValidDecidable):

4.5.4.2.4. Unpacked Layout Validity

Definition channelLayoutDescriptionUnpackedValidT (c : channelLayoutDescriptionUnpackedT) : Prop :=
     [] <> uChannels c
  /\ Forall channelDescriptionValid (uChannels c)
  /\ Forall channelDescriptionBitsDivisible8 (uChannels c).

4.5.4.2.5. Unpacked Layout Validity Decidable

Theorem channelLayoutDescriptionUnpackedValidDecidable : forall c,
  {channelLayoutDescriptionUnpackedValidT c}+{~channelLayoutDescriptionUnpackedValidT c}.
Proof.
  (* Proof omitted for brevity; see ChannelDescription.v for proofs. *)
Qed.
A packed layout consists of a non-empty sequence of channels and a layout packing value.

4.5.4.3.2. Packed Layout

Inductive channelLayoutDescriptionPackedT : Set := ChannelLayoutDescriptionPacked {
  pChannels : list channelDescriptionT;
  pPacking  : channelLayoutPackingT;
}.
The total size in bits of the channels of a packed layout must equal the size in bits of its layout packing, as declared by channelLayoutDescriptionPackedValidT (decidable: channelLayoutDescriptionPackedValidDecidable):

4.5.4.3.4. Packed Layout Validity

Definition channelLayoutDescriptionPackedValidT (c : channelLayoutDescriptionPackedT) : Prop :=
     [] <> pChannels c
  /\ Forall channelDescriptionValid (pChannels c)
  /\ channelDescriptionsBitsTotal (pChannels c) = channelLayoutPackingBits (pPacking c).

4.5.4.3.5. Packed Layout Validity Decidable

Theorem channelLayoutDescriptionPackedValidDecidable : forall c,
  {channelLayoutDescriptionPackedValidT c}+{~channelLayoutDescriptionPackedValidT c}.
Proof.
  (* Proof omitted for brevity; see ChannelDescription.v for proofs. *)
Qed.
The layout packing value must be one of the following values:

4.5.4.3.7. Layout Packing

Inductive channelLayoutPackingT : Set :=
  | CLPack8
  | CLPack16
  | CLPack32
  | CLPack64.
The number of bits associated with a layout packing value is given by channelLayoutPackingBits:

4.5.4.3.9. Layout Packing Bits

Definition channelLayoutPackingBits (c : channelLayoutPackingT) : Z :=
  match c with
  | CLPack8  => 8
  | CLPack16 => 16
  | CLPack32 => 32
  | CLPack64 => 64
  end.
The number of bits associated with a layout packing value is always divisible by 8:

4.5.4.3.11. Layout Packing Bits Divisible 8

Theorem channelLayoutPackingBitsDiv8 : forall c, divisible8 (channelLayoutPackingBits (c)).
For a packed layout, the number of bits required for the channels must equal the number of bits associated with the given packed layout.
A layout packing value is identified by the following Lanark string:

4.5.4.3.14. Layout Packing Description

Definition channelLayoutPackingDescribe (c : channelLayoutPackingT) : lanarkT :=
  match c with
  | CLPack8  => calinoReservedDescriptor "pack8"
  | CLPack16 => calinoReservedDescriptor "pack16"
  | CLPack32 => calinoReservedDescriptor "pack32"
  | CLPack64 => calinoReservedDescriptor "pack64"
  end.
The identifying Lanark string of every layout packing value is valid (channelLayoutPackingDescribeValid).

4.5.4.3.16. Layout Packing Description Valid

Theorem channelLayoutPackingDescribeValid : forall c,
  lanarkValidT (channelLayoutPackingDescribe c).
Proof.
  (* Proof omitted for brevity; see ChannelDescription.v for proofs. *)
Qed.
A channel type defines how the sequence of bits that make up a value in a channel should be interpreted numerically. A channel type must be one of the following values:

4.5.5.2. Channel Types

Inductive channelTypeT : Set :=
  | CTFixedPointNormalizedUnsigned
  | CTFixedPointNormalizedSigned
  | CTScaledUnsigned
  | CTScaledSigned
  | CTIntegerUnsigned
  | CTIntegerSigned
  | CTFloatIEEE754
  | CTCustom : lanarkT -> channelTypeT.
A value of CTFixedPointNormalizedUnsigned indicates the values in a channel should be interpreted as unsigned fixed-point values. Given a floating point value f in the range [0, 1], the corresponding n-bit unsigned fixed point value h is given by the relation f = h / (2ⁿ - 1).
A value of CTFixedPointNormalizedSigned indicates that the values in a channel should be interpreted as signed fixed-point values. Given a floating point value f in the range [-1, 1], the corresponding n-bit signed fixed point value h is given by the relation f = max (h / (2ⁿ⁻¹ - 1), -1).
A value of CTScaledUnsigned indicates that the values in a channel should be interpreted as unsigned integers, and then converted to similar floating-point values on use. For example, a channel containing the value 23 would be ideally converted to 23.0 when sampled.
A value of CTScaledSigned indicates that the values in a channel should be interpreted as signed integers, and then converted to similar floating-point values on use. For example, a channel containing the value -23 would be ideally converted to -23.0 when sampled.
A value of CTIntegerUnsigned indicates that the values in a channel should be interpreted as unsigned integers.
A value of CTIntegerSigned indicates that the values in a channel should be interpreted as signed integers.
A value of CTFloatIEEE754 indicates that the values in a channel should be interpreted as IEEE 754 binary floating point values of a size appropriate for the channel (such as binary16, binary32, and binary64).
A value of CTCustom indicates that values in a channel should be interpreted in a manner not defined by this specification. CTCustom values may be used, for example, to specify exotic platform-specific floating point formats for textures that are intended to be used on a limited range of hardware.
A channel type is identified by the following Lanark string:

4.5.5.12. Channel Type Description

Definition channelTypeDescribe (c : channelTypeT) : lanarkT :=
  match c with
  | CTFixedPointNormalizedUnsigned => calinoReservedDescriptor "fixed_point_normalized_unsigned"
  | CTFixedPointNormalizedSigned   => calinoReservedDescriptor "fixed_point_normalized_signed"
  | CTScaledUnsigned               => calinoReservedDescriptor "scaled_unsigned"
  | CTScaledSigned                 => calinoReservedDescriptor "scaled_signed"
  | CTIntegerUnsigned              => calinoReservedDescriptor "integer_unsigned"
  | CTIntegerSigned                => calinoReservedDescriptor "integer_signed"
  | CTFloatIEEE754                 => calinoReservedDescriptor "float_ieee754"
  | CTCustom d                     => d
  end.
The conditions under which a channel type is valid are declared by channelTypeValid (decidable: channelTypeValidDecidable). For a valid value, its identifying Lanark string is itself valid (channelTypeDescribeValid ).

4.5.5.14. Channel Type Validity

Definition channelTypeValid (c : channelTypeT) : Prop :=
  match c with
  | CTFixedPointNormalizedUnsigned => True
  | CTFixedPointNormalizedSigned   => True
  | CTScaledUnsigned               => True
  | CTScaledSigned                 => True
  | CTIntegerUnsigned              => True
  | CTIntegerSigned                => True
  | CTFloatIEEE754                 => True
  | CTCustom d                     => (~isCalinoReservedDescriptor d) /\ lanarkValidT d
  end.

4.5.5.15. Channel Type Validity Decidable

Theorem channelTypeValidDecidable : forall c,
  {channelTypeValid c}+{~channelTypeValid c}.
Proof.
  (* Proof omitted for brevity; see ChannelType.v for proofs. *)
Qed.

4.5.5.16. Channel Type Description Valid

Theorem channelTypeDescribeValid : forall (c : channelTypeT),
  channelTypeValid c ->
  match c with
  | CTCustom s => lanarkValidT s
  | _          => lanarkValidT (channelTypeDescribe c)
  end.
Proof.
  (* Proof omitted for brevity; see ChannelType.v for proofs. *)
Qed.
The calino package considers a number of formats to be standard at the time of writing due to their widespread use. In most cases, support for the formats is guaranteed to be present on modern GPUs due to their status of being required formats by specifications such as Vulkan.
Implementations must provide some degree of support for these formats. For example, implementations that provide tools to manipulate images must be able to, at a minimum, manipulate images in all of the standard formats. Packages that provide the ability to read calino texture files and upload the contents to a GPU must expect to encounter textures in all of the standard formats.
For each standard format, the validity of its channel constants is established by theorems of the form XValid (for example, R8Valid), and the validity of its layout is established by theorems of the form Layout_XValid (for example, Layout_R8_G8_B8_A8Valid).

4.5.6.1.4. R8 Valid

Theorem R8Valid : channelDescriptionValid R8.

4.5.6.1.5. R8 G8 B8 A8 Layout Valid

Theorem Layout_R8_G8_B8_A8Valid : channelLayoutDescriptionValidT Layout_R8_G8_B8_A8.
An RGBA layout with 4 bits of precision in each channel, packed into a 16-bit integer.

4.5.6.2.2. R4 G4 B4 A4 Definition

Definition Layout_R4_G4_B4_A4 : channelLayoutDescriptionT :=
  CLDPacked (ChannelLayoutDescriptionPacked R4_G4_B4_A4_Channels CLPack16).
An RGBA layout with 1 bit of precision in the alpha channel, and 5 bits of precision in each of the other channels, packed into a 16-bit integer.

4.5.6.3.2. A1 R5 G5 B5 Definition

Definition Layout_A1_R5_G5_B5 : channelLayoutDescriptionT :=
  CLDPacked (ChannelLayoutDescriptionPacked A1_R5_G5_B5_Channels CLPack16).
An RGB layout with 5 bits of precision in the red and blue channels, and 6 bits of precision in the green channel, packed into a 16-bit integer.

4.5.6.4.2. R5 G6 B5 Definition

Definition Layout_R5_G6_B5 : channelLayoutDescriptionT :=
  CLDPacked (ChannelLayoutDescriptionPacked R5_G6_B5_Channels CLPack16).
An unpacked RGBA layout with 8 bits of precision in each channel.

4.5.6.5.2. R8 G8 B8 A8 Definition

Definition Layout_R8_G8_B8_A8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_G8_B8_A8_Channels).
An unpacked RGB layout with 8 bits of precision in each channel.

4.5.6.6.2. R8 G8 B8 Definition

Definition Layout_R8_G8_B8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_G8_B8_Channels).
An unpacked RG layout with 8 bits of precision in each channel.

4.5.6.7.2. R8 G8 Definition

Definition Layout_R8_G8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_G8_Channels).
An unpacked R layout with 8 bits of precision in each channel.

4.5.6.8.2. R8 Definition

Definition Layout_R8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_Channels).
An unpacked RGBA layout with 16 bits of precision in each channel.

4.5.6.9.2. R16 G16 B16 A16 Definition

Definition Layout_R16_G16_B16_A16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_G16_B16_A16_Channels).
An unpacked RGB layout with 16 bits of precision in each channel.

4.5.6.10.2. R16 G16 B16 Definition

Definition Layout_R16_G16_B16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_G16_B16_Channels).
An unpacked RG layout with 16 bits of precision in each channel.

4.5.6.11.2. R16 G16 Definition

Definition Layout_R16_G16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_G16_Channels).
An unpacked R layout with 16 bits of precision in each channel.

4.5.6.12.2. R16 Definition

Definition Layout_R16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_Channels).
An unpacked RGBA layout with 32 bits of precision in each channel.

4.5.6.13.2. R32 G32 B32 A32 Definition

Definition Layout_R32_G32_B32_A32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_G32_B32_A32_Channels).
An unpacked RGB layout with 32 bits of precision in each channel.

4.5.6.14.2. R32 G32 B32 Definition

Definition Layout_R32_G32_B32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_G32_B32_Channels).
An unpacked RG layout with 32 bits of precision in each channel.

4.5.6.15.2. R32 G32 Definition

Definition Layout_R32_G32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_G32_Channels).
An unpacked R layout with 32 bits of precision in each channel.

4.5.6.16.2. R32 Definition

Definition Layout_R32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_Channels).
An unpacked RGBA layout with 64 bits of precision in each channel.

4.5.6.17.2. R64 G64 B64 A64 Definition

Definition Layout_R64_G64_B64_A64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_G64_B64_A64_Channels).
An unpacked RGB layout with 64 bits of precision in each channel.

4.5.6.18.2. R64 G64 B64 Definition

Definition Layout_R64_G64_B64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_G64_B64_Channels).
An unpacked RG layout with 64 bits of precision in each channel.

4.5.6.19.2. R64 G64 Definition

Definition Layout_R64_G64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_G64_Channels).
An unpacked R layout with 64 bits of precision in each channel.

4.5.6.20.2. R64 Definition

Definition Layout_R64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_Channels).
The values in the n color channels of an image are interpreted as coordinates in an n-dimensional color space. A color space declaration indicates which color space is intended to be used.

4.6.2. Color Space

Inductive colorSpaceT : Set :=
  | CSLinear
  | CSsRGB
  | CSCustom : lanarkT -> colorSpaceT.
A value of CSLinear indicates that the color values should be interpreted as coordinates in a pure, conceptually linear color space.
A value of CSsRGB indicates that the color values should be interpreted as coordinates in the sRGB color space.
A value of CSCustom indicates that the color values should be interpreted as coordinates in a custom color space. Implementations are permitted to reject files containing unrecognized color spaces.
A color space is identified by the following Lanark string:

4.6.7. Color Space Description

Definition colorSpaceDescribe (c : colorSpaceT) : lanarkT :=
  match c with
  | CSLinear   => calinoReservedDescriptor "linear"
  | CSsRGB     => calinoReservedDescriptor "srgb"
  | CSCustom d => d
  end.
The conditions under which a color space is valid are declared by colorSpaceValid (decidable: colorSpaceValidDecidable ). For a valid value, its identifying Lanark string is itself valid ( colorSpaceDescribeValid).

4.6.9. Color Space Validity

Definition colorSpaceValid (c : colorSpaceT) : Prop :=
  match c with
  | CSLinear   => True
  | CSsRGB     => True
  | CSCustom t => (~isCalinoReservedDescriptor t) /\ lanarkValidT t
  end.

4.6.10. Color Space Validity Decidable

Theorem colorSpaceValidDecidable : forall c,
  {colorSpaceValid c}+{~colorSpaceValid c}.
Proof.
  (* Proof omitted for brevity; see ColorSpace.v for proofs. *)
Qed.

4.6.11. Color Space Description Valid

Theorem colorSpaceDescribeValid : forall (c : colorSpaceT),
  colorSpaceValid c ->
  match c with
  | CSCustom t => lanarkValidT t
  | _          => lanarkValidT (colorSpaceDescribe c)
  end.
Proof.
  (* Proof omitted for brevity; see ColorSpace.v for proofs. *)
Qed.
A compression declaration indicates that image data is compressed in a manner that is expected to be interpreted directly by a consuming GPU. This is in contrast to super compression, where image data must be manually decompressed before it can be consumed by a GPU.

4.7.1.2. Compression Methods

Inductive compressionMethodT : Set :=
  | CUncompressed : compressionUncompressedT -> compressionMethodT
  | CBC1          : compressionBC1T -> compressionMethodT
  | CBC2          : compressionBC2T -> compressionMethodT
  | CBC3          : compressionBC3T -> compressionMethodT
  | CBC4          : compressionBC4T -> compressionMethodT
  | CBC5          : compressionBC5T -> compressionMethodT
  | CBC6          : compressionBC6T -> compressionMethodT
  | CBC7          : compressionBC7T -> compressionMethodT
  | CETC1         : compressionETC1T -> compressionMethodT
  | CETC2         : compressionETC2T -> compressionMethodT
  | CEAC          : compressionEACT -> compressionMethodT
  | CASTC         : compressionASTCT -> compressionMethodT
  | CCustom       : compressionCustomT -> compressionMethodT.
A value of CompressionUncompressed indicates that image data is not compressed.
A value of CompressionBC1 indicates that image data is compressed using BC1 compression (also known as DXT1 compression).
A value of CompressionBC2 indicates that image data is compressed using BC2 compression (also known as DXT3 compression).
A value of CompressionBC3 indicates that image data is compressed using BC3 compression (also known as DXT5 compression).
A value of CompressionBC4 indicates that image data is compressed using BC4 compression.
A value of CompressionBC5 indicates that image data is compressed using BC5 compression.
A value of CompressionBC6 indicates that image data is compressed using BC6 compression.
A value of CompressionBC7 indicates that image data is compressed using BC7 compression.
A value of CompressionETC1 indicates that image data is compressed using ETC1 compression.
A value of CompressionETC2 indicates that image data is compressed using ETC2 compression.
A value of CompressionEAC indicates that image data is compressed using EAC compression.
A value of CompressionASTC indicates that image data is compressed using ASTC compression.
A value of CompressionCustom indicates that image data is compressed using a method not known to this specification.
A compression method is identified by the following Lanark string:

4.7.1.17. Compression Description

Definition compressionMethodDescribe (c : compressionMethodT) : lanarkT :=
  match c with
  | CUncompressed _ => calinoReservedDescriptor "uncompressed"
  | CBC1 _          => calinoReservedDescriptor "bc1"
  | CBC2 _          => calinoReservedDescriptor "bc2"
  | CBC3 _          => calinoReservedDescriptor "bc3"
  | CBC4 _          => calinoReservedDescriptor "bc4"
  | CBC5 _          => calinoReservedDescriptor "bc5"
  | CBC6 _          => calinoReservedDescriptor "bc6"
  | CBC7 _          => calinoReservedDescriptor "bc7"
  | CETC1 _         => calinoReservedDescriptor "etc1"
  | CETC2 _         => calinoReservedDescriptor "etc2"
  | CEAC _          => calinoReservedDescriptor "eac"
  | CASTC _         => calinoReservedDescriptor "astc"
  | CCustom t       => (customId t)
  end.
The conditions under which a compression method is valid are declared by compressionMethodValid (decidable: compressionMethodValidDecidable). For a valid value, its identifying Lanark string is itself valid ( compressionMethodDescribeValid).

4.7.1.19. Compression Method Validity

Definition compressionMethodValid (c : compressionMethodT) : Prop :=
  match c with
  | CUncompressed _ => True
  | CBC1 _          => True
  | CBC2 _          => True
  | CBC3 _          => True
  | CBC4 _          => True
  | CBC5 _          => True
  | CBC6 _          => True
  | CBC7 _          => True
  | CETC1 _         => True
  | CETC2 _         => True
  | CEAC _          => True
  | CASTC t         => compressionMethodASTCValid t
  | CCustom t       => compressionMethodCustomValid t
  end.

4.7.1.20. Compression Method Validity Decidable

Theorem compressionMethodValidDecidable : forall c,
  {compressionMethodValid c}+{~compressionMethodValid c}.
Proof.
  (* Proof omitted for brevity; see Compression.v for proofs. *)
Qed.

4.7.1.21. Compression Method Description Valid

Theorem compressionMethodDescribeValid : forall (c : compressionMethodT),
  compressionMethodValid c ->
  match c with
  | CCustom t => lanarkValidT (customId t)
  | _         => lanarkValidT (compressionMethodDescribe c)
  end.
Proof.
  (* Proof omitted for brevity; see Compression.v for proofs. *)
Qed.
The conditions under which an ASTC compression method is valid are declared by compressionMethodASTCValid (decidable: compressionMethodASTCValidDecidable): the block size in each dimension lies in the range [3,12].

4.7.1.23. ASTC Compression Method Validity

Definition compressionMethodASTCValid (c : compressionASTCT) : Prop :=
     (3 <= Z.to_nat (astcBlockSizeX c) <= 12)
  /\ (3 <= Z.to_nat (astcBlockSizeY c) <= 12).

4.7.1.24. ASTC Compression Method Validity Decidable

Theorem compressionMethodASTCValidDecidable : forall c,
  {compressionMethodASTCValid c}+{~compressionMethodASTCValid c}.
Proof.
  (* Proof omitted for brevity; see Compression.v for proofs. *)
Qed.
The conditions under which a custom compression method is valid are declared by compressionMethodCustomValid (decidable: compressionMethodCustomValidDecidable): the section identifier fits in 64 bits, the block sizes and the alignment are positive, and the identifier is a valid Lanark string that is not reserved by calino.

4.7.1.26. Custom Compression Method Validity

Definition compressionMethodCustomValid (c : compressionCustomT) : Prop :=
     (0 <= Z.to_nat (customSectionIdentifier c) <= 0xffffffffffffffff)
  /\ (1 <= Z.to_nat (customBlockSizeX c) <= 0xffffffff)
  /\ (1 <= Z.to_nat (customBlockSizeY c) <= 0xffffffff)
  /\ (1 <= Z.to_nat (customAlign c) <= 0xffffffff)
  /\ (~isCalinoReservedDescriptor (customId c))
  /\ lanarkValidT (customId c).

4.7.1.27. Custom Compression Method Validity Decidable

Theorem compressionMethodCustomValidDecidable : forall c,
  {compressionMethodCustomValid c}+{~compressionMethodCustomValid c}.
Proof.
  (* Proof omitted for brevity; see Compression.v for proofs. *)
Qed.
Compression methods have inherent block sizes that typically influence the required alignment in memory of compressed data.

4.7.2.2. Compression Block Size X

Definition compressionBlockSizeX (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 4
  | CBC2 _          => 4
  | CBC3 _          => 4
  | CBC4 _          => 4
  | CBC5 _          => 4
  | CBC6 _          => 4
  | CBC7 _          => 4
  | CETC1 _         => 4
  | CETC2 _         => 4
  | CEAC _          => 4
  | CASTC t         => astcBlockSizeX t
  | CCustom t       => customBlockSizeX t
  end.

4.7.2.3. Compression Block Size Y

Definition compressionBlockSizeY (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 4
  | CBC2 _          => 4
  | CBC3 _          => 4
  | CBC4 _          => 4
  | CBC5 _          => 4
  | CBC6 _          => 4
  | CBC7 _          => 4
  | CETC1 _         => 4
  | CETC2 _         => 4
  | CEAC _          => 4
  | CASTC t         => astcBlockSizeY t
  | CCustom t       => customBlockSizeY t
  end.

4.7.2.4. Compression Block Alignment

Definition compressionBlockAlignment (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 8
  | CBC2 _          => 16
  | CBC3 _          => 16
  | CBC4 _          => 8
  | CBC5 _          => 16
  | CBC6 _          => 16
  | CBC7 _          => 16
  | CETC1 _         => 16
  | CETC2 _         => 16
  | CEAC _          => 16
  | CASTC _         => 16
  | CCustom t       => customAlign t
  end.
Custom compression methods may require including extra metadata in order to allow the data to be decompressed. Compression methods may include a section identifier value indicating that consumers should look for a section with the given identifier to locate the metadata.

4.7.3.2. Compression Section Identifier

Definition compressionSectionIdentifier (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 0
  | CBC2 _          => 0
  | CBC3 _          => 0
  | CBC4 _          => 0
  | CBC5 _          => 0
  | CBC6 _          => 0
  | CBC7 _          => 0
  | CETC1 _         => 0
  | CETC2 _         => 0
  | CEAC _          => 0
  | CASTC _         => 0
  | CCustom t       => customSectionIdentifier t
  end.
A super compression declaration indicates that image data is compressed in a manner that requires it to be decompressed before it can be consumed by a GPU for use. This is in contrast to compression, where GPUs are expected to consume compressed data directly.

4.8.1.2. Supercompression Methods

Inductive superCompressionMethodT : Set :=
  | SCUncompressed : superCompressionUncompressedT -> superCompressionMethodT
  | SCLZ4          : superCompressionLZ4T -> superCompressionMethodT
  | SCDEFLATE      : superCompressionDEFLATET -> superCompressionMethodT
  | SCCustom       : superCompressionCustomT -> superCompressionMethodT.
A value of SuperCompressionUncompressed indicates that image data is not compressed.
A value of SuperCompressionLZ4 indicates that image data is compressed using LZ4 compression.
A value of SuperCompressionDEFLATE indicates that image data is compressed with the DEFLATE algorithm (RFC 1951) and stored in a zlib container (RFC 1950).
A value of SuperCompressionCustom indicates that image data is compressed using a method not known to this specification.
A super compression method is identified by the following Lanark string:

4.8.1.8. Super Compression Description

Definition superCompressionMethodDescribe (c : superCompressionMethodT) :=
  match c with
  | SCUncompressed _ => calinoReservedDescriptor "uncompressed"
  | SCLZ4 _          => calinoReservedDescriptor "lz4"
  | SCDEFLATE _      => calinoReservedDescriptor "deflate"
  | SCCustom t       => superCustomId t
  end.
The conditions under which a super compression method is valid are declared by superCompressionMethodValid (decidable: superCompressionMethodValidDecidable). For a valid value, its identifying Lanark string is itself valid ( superCompressionMethodDescribeValid).

4.8.1.10. Super Compression Method Validity

Definition superCompressionMethodValid (c : superCompressionMethodT) : Prop :=
  match c with
  | SCUncompressed _ => True
  | SCLZ4 _          => True
  | SCDEFLATE _      => True
  | SCCustom t       => (~isCalinoReservedDescriptor (superCustomId t)) /\ lanarkValidT (superCustomId t)
  end.

4.8.1.11. Super Compression Method Validity Decidable

Theorem superCompressionMethodValidDecidable : forall c,
  {superCompressionMethodValid c}+{~superCompressionMethodValid c}.
Proof.
  (* Proof omitted for brevity; see SuperCompression.v for proofs. *)
Qed.

4.8.1.12. Super Compression Method Description Valid

Theorem superCompressionMethodDescribeValid : forall (c : superCompressionMethodT),
  superCompressionMethodValid c ->
  match c with
  | SCCustom t => lanarkValidT (superCustomId t)
  | _          => lanarkValidT (superCompressionMethodDescribe c)
  end.
Proof.
  (* Proof omitted for brevity; see SuperCompression.v for proofs. *)
Qed.
Custom super compression methods may require including extra metadata in order to allow the data to be decompressed. Super compression methods may include a section identifier value indicating that consumers should look for a section with the given identifier to locate the metadata.

4.8.2.2. Super Compression Section Identifier

Definition superCompressionSectionIdentifier (c : superCompressionMethodT) : Z :=
  match c with
  | SCUncompressed _ => 0
  | SCLZ4 _          => 0
  | SCDEFLATE _      => 0
  | SCCustom t       => superCustomSectionIdentifier t
  end.
All images implicitly have a coordinate system such that the locations of pixels are specified relative to some origin point. For example, OpenGL's screen space is a coordinate system with the origin at the bottom left such that X coordinates increase rightwards and Y coordinates increase upwards. In contrast, Java2D's coordinate system has the origin at the top left such that X coordinates increase rightwards and Y coordinates increase downwards. Texture coordinates are typically expressed as a 3-tuple (R, S, T), where S is analogous to the X axis, T is analogous to the Y axis, and R is analogous to the Z axis. The R coordinate value is only present for 3D textures.
The coordinate system of an image must match the coordinate system of the intended rendering system in order for the image to be rendered correctly. For example, taking an image that was intended for Java2D's system and rendering it directly in OpenGL will result in an image displaying upside down.
Textures in the calino package include descriptions of their coordinate systems. A coordinate system declaration comprises three values that describe the orientations of the R, S, and T axes.

4.9.5. Coordinates R

Inductive coordinateAxisR : Set :=
  | AxisRIncreasingToward
  | AxisRIncreasingAway.
A value of AxisRIncreasingToward indicates that the R axis increases towards the viewer.
A value of AxisRIncreasingAway indicates that the R axis increases away from the viewer.

4.9.8. Coordinates S

Inductive coordinateAxisS : Set :=
  | AxisSIncreasingRight
  | AxisSIncreasingLeft.
A value of AxisSIncreasingRight indicates that the S axis increases rightwards.
A value of AxisSIncreasingLeft indicates that the S axis increases leftwards.

4.9.11. Coordinates T

Inductive coordinateAxisT : Set :=
  | AxisTIncreasingDown
  | AxisTIncreasingUp.
A value of AxisTIncreasingDown indicates that the T axis increases downwards.
A value of AxisTIncreasingUp indicates that the T axis increases upwards.

4.9.14. Coordinate System Values

Inductive coordinateSystemT : Set :=
  CoordinateSystem : coordinateAxisR -> coordinateAxisS -> coordinateAxisT -> coordinateSystemT.
Values of coordinate axis are identified by the following Lanark strings:

4.9.16. Coordinates R Description

Definition coordinateAxisRDescribe (c : coordinateAxisR) : lanarkT :=
  match c with
  | AxisRIncreasingToward => calinoReservedDescriptor "r_increasing_toward"
  | AxisRIncreasingAway   => calinoReservedDescriptor "r_increasing_away"
  end.

4.9.17. Coordinates S Description

Definition coordinateAxisSDescribe (c : coordinateAxisS) : lanarkT :=
  match c with
  | AxisSIncreasingRight => calinoReservedDescriptor "s_increasing_right"
  | AxisSIncreasingLeft  => calinoReservedDescriptor "s_increasing_left"
  end.

4.9.18. Coordinates T Description

Definition coordinateAxisTDescribe (c : coordinateAxisT) : lanarkT :=
  match c with
  | AxisTIncreasingDown => calinoReservedDescriptor "t_increasing_down"
  | AxisTIncreasingUp   => calinoReservedDescriptor "t_increasing_up"
  end.
The identifying Lanark string of every coordinate axis value is valid ( coordinateAxisRDescribeValid, coordinateAxisSDescribeValid, and coordinateAxisTDescribeValid).

4.9.20. Coordinate Axis R Description Valid

Theorem coordinateAxisRDescribeValid : forall (c : coordinateAxisR),
  lanarkValidT (coordinateAxisRDescribe c).
Proof.
  (* Proof omitted for brevity; see CoordinateSystem.v for proofs. *)
Qed.

4.9.21. Coordinate Axis S Description Valid

Theorem coordinateAxisSDescribeValid : forall (c : coordinateAxisS),
  lanarkValidT (coordinateAxisSDescribe c).
Proof.
  (* Proof omitted for brevity; see CoordinateSystem.v for proofs. *)
Qed.

4.9.22. Coordinate Axis T Description Valid

Theorem coordinateAxisTDescribeValid : forall (c : coordinateAxisT),
  lanarkValidT (coordinateAxisTDescribe c).
Proof.
  (* Proof omitted for brevity; see CoordinateSystem.v for proofs. *)
Qed.
A texture may have one or more boolean flags describing metadata that does not fit into any of the other categories of metadata included in calino texture files. A given flag may appear at most once in any given texture file.

4.10.2. Flag

Inductive flagT : Set :=
  | FlagAlphaPremultiplied
  | FlagCustom : lanarkT -> flagT.
A value of FlagAlphaPremultiplied indicates that the color channels of the image data have been multiplied by the value in the alpha channel of the image.
A value of FlagCustom indicates that the texture has flags not known to this specification.
A flag is identified by the following Lanark string:

4.10.6. Flag Description

Definition flagDescribe (f : flagT) : lanarkT :=
  match f with
  | FlagAlphaPremultiplied => calinoReservedDescriptor "alpha_premultiplied"
  | FlagCustom d           => d
  end.
The conditions under which a flag is valid are declared by flagValid (decidable: flagValidDecidable). For a valid value, its identifying Lanark string is itself valid ( flagDescribeValid).

4.10.8. Flag Validity

Definition flagValid (f : flagT) : Prop :=
  match f with
  | FlagAlphaPremultiplied => True
  | FlagCustom t           => (~isCalinoReservedDescriptor t) /\ lanarkValidT t
  end.

4.10.9. Flag Validity Decidable

Theorem flagValidDecidable : forall f,
  {flagValid f}+{~flagValid f}.
Proof.
  (* Proof omitted for brevity; see Flag.v for proofs. *)
Qed.

4.10.10. Flag Description Valid

Theorem flagDescribeValid : forall (c : flagT),
  flagValid c ->
  match c with
  | FlagCustom t => lanarkValidT t
  | _            => lanarkValidT (flagDescribe c)
  end.
Proof.
  (* Proof omitted for brevity; see Flag.v for proofs. *)
Qed.
The conditions under which a set of flags is valid are declared by flagSetValid (decidable: flagSetValidDecidable): the flags are distinct, and each flag is valid.

4.10.12. Flag Set Validity

Definition flagSetValid (f : flagSetT) : Prop :=
     NoDup (flags f)
  /\ Forall flagValid (flags f).

4.10.13. Flag Set Validity Decidable

Theorem flagSetValidDecidable : forall f,
  {flagSetValid f}+{~flagSetValid f}.
Proof.
  (* Proof omitted for brevity; see Flag.v for proofs. *)
Qed.
An image information value aggregates all of the image metadata described in this specification.

4.11.2. Image Information

Record imageInfoT : Set := ImageInfo {
  imageSize                   : imageSize3DT;
  imageChannelsLayout         : channelLayoutDescriptionT;
  imageChannelsType           : channelTypeT;
  imageCompressionMethod      : compressionMethodT;
  imageSuperCompressionMethod : superCompressionMethodT;
  imageCoordinateSystem       : coordinateSystemT;
  imageColorSpace             : colorSpaceT;
  imageFlags                  : flagSetT;
  imageByteOrder              : octetOrder
}.
The conditions under which an image information value is valid are declared by imageInfoValid (decidable: imageInfoValidDecidable): the image size, channel layout, channel type, compression method, super compression method, color space, and flags are all valid.

4.11.4. Image Information Validity

Definition imageInfoValid (i : imageInfoT) : Prop :=
     imageSize3DValid (imageSize i)
  /\ channelLayoutDescriptionValidT (imageChannelsLayout i)
  /\ channelTypeValid (imageChannelsType i)
  /\ compressionMethodValid (imageCompressionMethod i)
  /\ superCompressionMethodValid (imageSuperCompressionMethod i)
  /\ colorSpaceValid (imageColorSpace i)
  /\ flagSetValid (imageFlags i)
  .

4.11.5. Image Information Validity Decidable

Theorem imageInfoValidDecidable : forall i,
  {imageInfoValid i}+{~imageInfoValid i}.
Proof.
  (* Proof omitted for brevity; see ImageInfo.v for proofs. *)
Qed.

4.11.6. Image Size

Record imageSize3DT : Set := ImageSize3D {
  sizeX : nat;
  sizeY : nat;
  sizeZ : nat;
}.
The conditions under which an image size is valid are declared by imageSize3DValid (decidable: imageSize3DValidDecidable): all size values are non-zero.

4.11.8. Image Size Validity

Definition imageSize3DValid (i : imageSize3DT) : Prop :=
     0 <> (sizeX i)
  /\ 0 <> (sizeY i)
  /\ 0 <> (sizeZ i).

4.11.9. Image Size Validity Decidable

Theorem imageSize3DValidDecidable : forall i,
  {imageSize3DValid i}+{~imageSize3DValid i}.
Proof.
  (* Proof omitted for brevity; see ImageSize.v for proofs. *)
Qed.
The sizeX, sizeY, and sizeZ values declare the size of the image on the X, Y, and Z axes, respectively. All size values must be non-zero, and further restrictions may be placed on the size values by specific image types.
The block alignment of the compression method in use is a value in octets to which image data is expected to be aligned, as declared by compressionBlockAlignment in the block sizes subsection. For uncompressed images, this value is 0.

4.11.12. Compression Block Alignment

Definition compressionBlockAlignment (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 8
  | CBC2 _          => 16
  | CBC3 _          => 16
  | CBC4 _          => 8
  | CBC5 _          => 16
  | CBC6 _          => 16
  | CBC7 _          => 16
  | CETC1 _         => 16
  | CETC2 _         => 16
  | CEAC _          => 16
  | CASTC _         => 16
  | CCustom t       => customAlign t
  end.
A 2D texture consists of a non-empty sequence of mipmaps. A sequence of mipmaps is a sequence of progressively scaled-down copies of a base image. Each mipmap level is numbered with the base image being at level 0 and the number of each subsequent level is the successor of the number of the previous level. The mipmap image at each level is half the width and height of the previous level.
A mipmap stores the compressed size and uncompressed size of the image data, along with a CRC32 checksum of the uncompressed data. A CRC32 value of 0 indicates that no checksum is available. For uncompressed data, the compressed size must equal the uncompressed size.

4.12.4. MipMap

Inductive mipMapT : Set := MipMap {
  mipMapLevel            : nat;
  mipMapSizeCompressed   : nat;
  mipMapSizeUncompressed : nat;
  mipMapCRC32            : nat
}.
The sequence of mipmaps is ordered from the highest level to level 0. The proposition mipMapListIsSorted declares that the levels of the sequence are consecutive: the level of each mipmap is exactly one greater than the level of the mipmap following it.

4.12.6. MipMap Sequence Sorting

Inductive mipMapListIsSorted : list mipMapT -> Prop :=
  | MipsOne   : forall m, mipMapListIsSorted [m]
  | MipsCons  : forall mm0 mm1 mxs,
    mipMapLevel mm1 = S (mipMapLevel mm0) ->
      mipMapListIsSorted (mm0 :: mxs) ->
        mipMapListIsSorted (mm1 :: mm0 :: mxs).

4.12.7. MipMap Sequence

Inductive mipMapListT : Set := MipMapList {
  mipMaps : list mipMapT;
}.

4.12.8. MipMap Sequence Validity

Definition mipMapListValid (m : mipMapListT) (sizeX sizeY : nat) : Prop :=
     mipMapListIsSorted (mipMaps m) 
  /\ mipMapListIsNonEmpty (mipMaps m)
  /\ mipMapListLevelZero (mipMaps m)
  /\ mipMapListMaxLevelBounded (mipMaps m) sizeX sizeY.
The conditions under which a mipmap sequence is valid are declared by mipMapListValid (decidable: mipMapListValidDecidable ). Each constituent proposition is decidable: mipMapListIsSorted ( mipMapListIsSortedDecidable), mipMapListIsNonEmpty ( mipMapListIsNonEmptyDecidable), mipMapListLevelZero (mipMapListLevelZeroDecidable), and mipMapListMaxLevelBounded ( mipMapListMaxLevelBoundedDecidable).

4.12.10. MipMap List Is Non-Empty

Definition mipMapListIsNonEmpty (m : list mipMapT) : Prop :=
  nil <> m.

4.12.11. MipMap List Level Zero

Fixpoint mipMapListLevelZero (m : list mipMapT) : Prop :=
  match m with
  | nil      => False
  | x :: nil => mipMapLevel x = 0
  | _ :: xs  => mipMapListLevelZero xs
  end.

4.12.12. MipMap List Max Level Bounded

Definition mipMapListMaxLevelBounded
  (m           : list mipMapT)
  (sizeX sizeY : nat)
: Prop :=
  match m with
  | nil    => True
  | x :: _ => (2 ^ mipMapLevel x) <= sizeX /\ (2 ^ mipMapLevel x) <= sizeY
  end.

4.12.13. MipMap List Validity Decidable

Theorem mipMapListValidDecidable : forall m sizeX sizeY,
  {mipMapListValid m sizeX sizeY}+{~mipMapListValid m sizeX sizeY}.
Proof.
  (* Proof omitted for brevity; see MipMap.v for proofs. *)
Qed.

4.12.14. MipMap List Is Sorted Decidable

Theorem mipMapListIsSortedDecidable : forall m,
  {mipMapListIsSorted m}+{~mipMapListIsSorted m}.
Proof.
  (* Proof omitted for brevity; see MipMap.v for proofs. *)
Qed.

4.12.15. MipMap List Is Non-Empty Decidable

Theorem mipMapListIsNonEmptyDecidable : forall m,
  {mipMapListIsNonEmpty m}+{~mipMapListIsNonEmpty m}.
Proof.
  (* Proof omitted for brevity; see MipMap.v for proofs. *)
Qed.

4.12.16. MipMap List Level Zero Decidable

Theorem mipMapListLevelZeroDecidable : forall m,
  {mipMapListLevelZero m}+{~mipMapListLevelZero m}.
Proof.
  (* Proof omitted for brevity; see MipMap.v for proofs. *)
Qed.

4.12.17. MipMap List Max Level Bounded Decidable

Theorem mipMapListMaxLevelBoundedDecidable : forall m sizeX sizeY,
  {mipMapListMaxLevelBounded m sizeX sizeY}+{~mipMapListMaxLevelBounded m sizeX sizeY}.
Proof.
  (* Proof omitted for brevity; see MipMap.v for proofs. *)
Qed.
Given a base image of size (sizeX, sizeY), the size of the mipmap at level n is given by (sizeX / 2ⁿ, sizeY / 2ⁿ). A mipmap at level n may appear in a valid mipmap list only if 2ⁿ <= sizeX and 2ⁿ <= sizeY. The highest permitted level is the level at which the smaller of the two dimensions reaches 1, so mipmap images of size 1 on one or both axes are permitted.
The uncompressed size of a mipmap should be non-zero. This property is implicit in the definitions above; images must be of a non-zero width and height, and there are no channel layouts where the sizes of the channels sum to zero.
The compressed size of a mipmap should be non-zero. This property is implicit in the definitions above; images must be of a non-zero width and height, and there are no channel layouts where the sizes of the channels sum to zero.
A 2D array texture consists of a non-empty sequence of array mipmaps. Array mipmaps are very similar to mipmaps with the primary difference that, for a texture with n array layers, each array mipmap level stores a sequence of n images of the same size. This facilitates a common implementation pattern where textures are progressively streamed onto the GPU starting with the array layers in the highest mipmap levels first.
An array mipmap is uniquely identified with a level and a layer.

4.13.4. ArrayMipMap Index

Inductive arrayMipMapIndexT : Set := ArrayMipMapIndex {
  arrayMipMapLevel : nat;
  arrayMipMapLayer : nat;
}.
An array mipmap stores the compressed size and uncompressed size of the image data, along with a CRC32 checksum of the uncompressed data. A CRC32 value of 0 indicates that no checksum is available. For uncompressed data, the compressed size must equal the uncompressed size.

4.13.6. ArrayMipMap

Inductive arrayMipMapT : Set := ArrayMipMap {
  arrayMipMapIndex            : arrayMipMapIndexT;
  arrayMipMapSizeCompressed   : nat;
  arrayMipMapSizeUncompressed : nat;
  arrayMipMapCRC32            : nat
}.
The number of layers present in an array mipmap must equal the sizeZ value defined in the image info, and it follows that all array mipmaps must contain the same number of layers.

4.13.8. ArrayMipMap Layer Count For Level

Fixpoint arrayMipMapLayerCountForLevel
  (level : nat)
  (m     : list arrayMipMapT)
: nat :=
  match m with
  | []        => 0
  | (x :: xs) =>
    match Nat.eq_dec (arrayMipMapLevel (arrayMipMapIndex x)) level with
    | left _  => 1 + (arrayMipMapLayerCountForLevel level xs)
    | right _ => (arrayMipMapLayerCountForLevel level xs)
    end
  end.

4.13.9. ArrayMipMap Levels

Definition arrayMipMapLevels (m : list arrayMipMapT) : list nat :=
  nodup Nat.eq_dec (map (fun k => arrayMipMapLevel (arrayMipMapIndex k)) m).

4.13.10. ArrayMipMap Levels Count Equality

Definition arrayMipMapListSameLayers (m : list arrayMipMapT) : Prop :=
  match arrayMipMapLevels m with
  | nil     => True
  | l1 :: _ => Forall (fun l0 => arrayMipMapLayerCountForLevel l0 m = arrayMipMapLayerCountForLevel l1 m) (arrayMipMapLevels m)
  end.
The sequence of array mipmaps is ordered from the highest level to level 0, and, within each level, from layer 0 to the last layer. The proposition arrayMipMapIndexNextLayer declares that two indices are at the same level, and that the layer of the second is one greater than the layer of the first. The proposition arrayMipMapIndexNextLevel declares that the level of the first index is one greater than the level of the second, and that the layer of the second is 0. The proposition arrayMipMapIndicesSorted declares that each consecutive pair of indices in the sequence is related by one of the two preceding propositions.

4.13.12. ArrayMipMap Index Next Layer

Definition arrayMipMapIndexNextLayer (x y : arrayMipMapIndexT) : Prop :=
     arrayMipMapLevel x = arrayMipMapLevel y
  /\ arrayMipMapLayer y = S (arrayMipMapLayer x).

4.13.13. ArrayMipMap Index Next Level

Definition arrayMipMapIndexNextLevel (x y : arrayMipMapIndexT) : Prop :=
     arrayMipMapLevel x = S (arrayMipMapLevel y)
  /\ arrayMipMapLayer y = 0.

4.13.14. ArrayMipMap Index List Sorted

Inductive arrayMipMapIndicesSorted : list arrayMipMapIndexT -> Prop :=
  | AMMIOne  : forall m, arrayMipMapIndicesSorted [m]
  | AMMICons : forall mmx mmy mxs,
    (arrayMipMapIndexNextLayer mmx mmy \/ arrayMipMapIndexNextLevel mmx mmy) ->
      arrayMipMapIndicesSorted (mmy :: mxs) ->
        arrayMipMapIndicesSorted (mmx :: mmy :: mxs).

4.13.15. ArrayMipMap Sequence

Inductive arrayMipMapListT : Set := ArrayMipMapList {
  arrayMipMaps : list arrayMipMapT;
}.

4.13.16. Array MipMap Sequence Validity

Definition arrayMipMapListValid (a : arrayMipMapListT) (sizeX sizeY : nat) : Prop :=
     arrayMipMapIndicesSorted (map arrayMipMapIndex (arrayMipMaps a))
  /\ arrayMipMapListSameLayers (arrayMipMaps a)
  /\ arrayMipMapListLevelZero (arrayMipMaps a)
  /\ arrayMipMapListFirstLayerZero (arrayMipMaps a)
  /\ arrayMipMapListMaxLevelBounded (arrayMipMaps a) sizeX sizeY
  /\ arrayMipMapListIsNonEmpty (arrayMipMaps a).
The conditions under which a sequence of array mipmaps is valid are declared by arrayMipMapListValid (decidable: arrayMipMapListValidDecidable). Each constituent proposition is decidable: arrayMipMapIndicesSorted ( arrayMipMapIndicesSortedDecidable), arrayMipMapListSameLayers ( arrayMipMapListSameLayersDecidable), arrayMipMapListLevelZero ( arrayMipMapListLevelZeroDecidable), arrayMipMapListFirstLayerZero ( arrayMipMapListFirstLayerZeroDecidable), arrayMipMapListMaxLevelBounded ( arrayMipMapListMaxLevelBoundedDecidable), and arrayMipMapListIsNonEmpty ( arrayMipMapListIsNonEmptyDecidable). The propositions arrayMipMapIndexNextLayer and arrayMipMapIndexNextLevel are decidable ( arrayMipMapIndexNextLayerDecidable and arrayMipMapIndexNextLevelDecidable).

4.13.18. Array MipMap List Level Zero

Fixpoint arrayMipMapListLevelZero (m : list arrayMipMapT) : Prop :=
  match m with
  | nil      => False
  | x :: nil => arrayMipMapLevel (arrayMipMapIndex x) = 0
  | _ :: xs  => arrayMipMapListLevelZero xs
  end.

4.13.19. Array MipMap List First Layer Zero

Definition arrayMipMapListFirstLayerZero (m : list arrayMipMapT) : Prop :=
  match m with
  | nil    => True
  | x :: _ => arrayMipMapLayer (arrayMipMapIndex x) = 0
  end.

4.13.20. Array MipMap List Max Level Bounded

Definition arrayMipMapListMaxLevelBounded (m : list arrayMipMapT) (sizeX sizeY : nat) : Prop :=
  match m with
  | nil    => True
  | x :: _ => (2 ^ arrayMipMapLevel (arrayMipMapIndex x)) <= sizeX
           /\ (2 ^ arrayMipMapLevel (arrayMipMapIndex x)) <= sizeY
  end.

4.13.21. Array MipMap List Is Non-Empty

Definition arrayMipMapListIsNonEmpty (m : list arrayMipMapT) : Prop :=
  nil <> m.

4.13.22. Array MipMap List Validity Decidable

Theorem arrayMipMapListValidDecidable : forall m sizeX sizeY,
  {arrayMipMapListValid m sizeX sizeY}+{~arrayMipMapListValid m sizeX sizeY}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.23. Array MipMap Indices Sorted Decidable

Theorem arrayMipMapIndicesSortedDecidable : forall m,
  {arrayMipMapIndicesSorted m}+{~arrayMipMapIndicesSorted m}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.24. Array MipMap List Same Layers Decidable

Theorem arrayMipMapListSameLayersDecidable : forall m,
  {arrayMipMapListSameLayers m}+{~arrayMipMapListSameLayers m}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.25. Array MipMap List Level Zero Decidable

Theorem arrayMipMapListLevelZeroDecidable : forall m,
  {arrayMipMapListLevelZero m}+{~arrayMipMapListLevelZero m}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.26. Array MipMap List First Layer Zero Decidable

Theorem arrayMipMapListFirstLayerZeroDecidable : forall m,
  {arrayMipMapListFirstLayerZero m}+{~arrayMipMapListFirstLayerZero m}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.27. Array MipMap List Max Level Bounded Decidable

Theorem arrayMipMapListMaxLevelBoundedDecidable : forall m sizeX sizeY,
  {arrayMipMapListMaxLevelBounded m sizeX sizeY}+{~arrayMipMapListMaxLevelBounded m sizeX sizeY}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.28. Array MipMap List Is Non-Empty Decidable

Theorem arrayMipMapListIsNonEmptyDecidable : forall m,
  {arrayMipMapListIsNonEmpty m}+{~arrayMipMapListIsNonEmpty m}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.29. Array MipMap Index Next Layer Decidable

Theorem arrayMipMapIndexNextLayerDecidable : forall i0 i1,
  {arrayMipMapIndexNextLayer i0 i1}+{~arrayMipMapIndexNextLayer i0 i1}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.

4.13.30. Array MipMap Index Next Level Decidable

Theorem arrayMipMapIndexNextLevelDecidable : forall i0 i1,
  {arrayMipMapIndexNextLevel i0 i1}+{~arrayMipMapIndexNextLevel i0 i1}.
Proof.
  (* Proof omitted for brevity; see ArrayMipMap.v for proofs. *)
Qed.
Given a base image of size (sizeX, sizeY), the size of the mipmap at level n is given by (sizeX / 2ⁿ, sizeY / 2ⁿ). A mipmap at level n may appear in a valid mipmap list only if 2ⁿ <= sizeX and 2ⁿ <= sizeY. The highest permitted level is the level at which the smaller of the two dimensions reaches 1, so mipmap images of size 1 on one or both axes are permitted.
The uncompressed size of a mipmap should be non-zero. This property is implicit in the definitions above; images must be of a non-zero width and height, and there are no channel layouts where the sizes of the channels sum to zero.
The compressed size of a mipmap should be non-zero. This property is implicit in the definitions above; images must be of a non-zero width and height, and there are no channel layouts where the sizes of the channels sum to zero.
A cube texture consists of a non-empty sequence of cube mipmaps. Cube mipmaps are very similar to mipmaps with the primary difference that each cube mipmap level stores a sequence of 6 images of the same size representing the faces of the cube.
A cube map face is one of the 6 two-dimensional images that make up a cube texture at a given mipmap level; the six faces are labeled X positive, X negative, Y positive, Y negative, Z positive, and Z negative. A face is accessed and interpreted in exactly the same way as any other two-dimensional image in a calino file: its size, channel layout, channel type, coordinate system, color space, and byte order are all given by the texture's shared image information. The face record stores, for that face's image, its offset (relative to the start of the level's face data, as described in the CLN_MCUB section), its compressed size, its uncompressed size, and its CRC32 — the same per-image metadata used for a two-dimensional mipmap image, with the level supplied by the enclosing cube mipmap and an offset added to locate the face within the face data.

4.14.4. CubeMap Face

Inductive cubeMapFaceT : Set := CubeMapFace {
  cubeFaceOffset           : nat;
  cubeFaceSizeCompressed   : nat;
  cubeFaceSizeUncompressed : nat;
  cubeFaceCRC32            : nat
}.
The sequence of cube mipmaps is ordered from the highest level to level 0. The proposition cubeMipMapListIsSorted declares that the levels of the sequence are consecutive: the level of each mipmap is exactly one greater than the level of the mipmap following it.

4.14.6. CubeMap Level

Inductive cubeMipMapT : Set := CubeMipMap {
  cubeMipMapLevel  : nat;
  cubeMapFaceXPos  : cubeMapFaceT;
  cubeMapFaceXNeg  : cubeMapFaceT;
  cubeMapFaceYPos  : cubeMapFaceT;
  cubeMapFaceYNeg  : cubeMapFaceT;
  cubeMapFaceZPos  : cubeMapFaceT;
  cubeMapFaceZNeg  : cubeMapFaceT
}.

4.14.7. CubeMap Ordering

Inductive cubeMipMapListIsSorted : list cubeMipMapT -> Prop :=
  | CubeOne   : forall m, cubeMipMapListIsSorted [m]
  | CubeCons  : forall mm0 mm1 mxs,
    cubeMipMapLevel mm1 = S (cubeMipMapLevel mm0) ->
      cubeMipMapListIsSorted (mm0 :: mxs) ->
        cubeMipMapListIsSorted (mm1 :: mm0 :: mxs).

4.14.8. CubeMap Sequence

Inductive cubeMipMapListT : Set := CubeList {
  cubeMipMaps : list cubeMipMapT;
}.

4.14.9. Cube MipMap Sequence Validity

Definition cubeMipMapListValid (c : cubeMipMapListT) (sizeX sizeY : nat) : Prop :=
     cubeMipMapListIsSorted (cubeMipMaps c)
  /\ cubeMipMapListIsNonEmpty (cubeMipMaps c)
  /\ cubeMipMapListLevelZero (cubeMipMaps c)
  /\ cubeMipMapListMaxLevelBounded (cubeMipMaps c) sizeX sizeY
  /\ cubeMipMapFaceOffsetsCorrect (cubeMipMaps c).
The conditions under which a sequence of cube mipmaps is valid are declared by cubeMipMapListValid (decidable: cubeMipMapListValidDecidable). Each constituent proposition is decidable: cubeMipMapListIsSorted ( cubeMipMapListIsSortedDecidable), cubeMipMapListIsNonEmpty ( cubeMipMapListIsNonEmptyDecidable), cubeMipMapListLevelZero ( cubeMipMapListLevelZeroDecidable), cubeMipMapListMaxLevelBounded ( cubeMipMapListMaxLevelBoundedDecidable), and cubeMipMapFaceOffsetsCorrect ( cubeMipMapFaceOffsetsCorrectDecidable). The proposition cubeFaceOffsetsCorrect, which cubeMipMapFaceOffsetsCorrect requires of each level, is decidable ( cubeFaceOffsetsCorrectDecidable).

4.14.11. Cube MipMap List Is Non-Empty

Definition cubeMipMapListIsNonEmpty (m : list cubeMipMapT) : Prop :=
  nil <> m.

4.14.12. Cube MipMap List Level Zero

Fixpoint cubeMipMapListLevelZero (m : list cubeMipMapT) : Prop :=
  match m with
  | nil      => False
  | x :: nil => cubeMipMapLevel x = 0
  | _ :: xs  => cubeMipMapListLevelZero xs
  end.

4.14.13. Cube MipMap List Max Level Bounded

Definition cubeMipMapListMaxLevelBounded
  (m           : list cubeMipMapT)
  (sizeX sizeY : nat)
: Prop :=
  match m with
  | nil    => True
  | x :: _ => (2 ^ cubeMipMapLevel x) <= sizeX /\ (2 ^ cubeMipMapLevel x) <= sizeY
  end.

4.14.14. Cube MipMap Face Offsets Correct

Definition cubeMipMapFaceOffsetsCorrect (m : list cubeMipMapT) : Prop :=
  Forall cubeFaceOffsetsCorrect m.

4.14.15. Cube MipMap List Validity Decidable

Theorem cubeMipMapListValidDecidable : forall c sizeX sizeY,
  {cubeMipMapListValid c sizeX sizeY}+{~cubeMipMapListValid c sizeX sizeY}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.

4.14.16. Cube MipMap List Is Sorted Decidable

Theorem cubeMipMapListIsSortedDecidable : forall m,
  {cubeMipMapListIsSorted m}+{~cubeMipMapListIsSorted m}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.

4.14.17. Cube MipMap List Is Non-Empty Decidable

Theorem cubeMipMapListIsNonEmptyDecidable : forall m,
  {cubeMipMapListIsNonEmpty m}+{~cubeMipMapListIsNonEmpty m}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.

4.14.18. Cube MipMap List Level Zero Decidable

Theorem cubeMipMapListLevelZeroDecidable : forall m,
  {cubeMipMapListLevelZero m}+{~cubeMipMapListLevelZero m}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.

4.14.19. Cube MipMap List Max Level Bounded Decidable

Theorem cubeMipMapListMaxLevelBoundedDecidable : forall m sizeX sizeY,
  {cubeMipMapListMaxLevelBounded m sizeX sizeY}+{~cubeMipMapListMaxLevelBounded m sizeX sizeY}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.

4.14.20. Cube MipMap Face Offsets Correct Decidable

Theorem cubeMipMapFaceOffsetsCorrectDecidable : forall m,
  {cubeMipMapFaceOffsetsCorrect m}+{~cubeMipMapFaceOffsetsCorrect m}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.

4.14.21. Cube Face Offsets Correct Decidable

Theorem cubeFaceOffsetsCorrectDecidable : forall c,
  {cubeFaceOffsetsCorrect c}+{~cubeFaceOffsetsCorrect c}.
Proof.
  (* Proof omitted for brevity; see CubeMipMap.v for proofs. *)
Qed.
The extent of a cube face is the sum of its offset and its compressed size: it is the position immediately after the last octet of the face data, measured from the start of the containing block. The proposition cubeFaceOffsetsCorrect declares that the 6 faces of a cube mipmap are arranged, without overlap, in the order X positive, X negative, Y positive, Y negative, Z positive, Z negative: the extent of each face does not exceed the offset of the next face in that order. Gaps between faces are permitted.

4.14.23. CubeMap Extent

Definition cubeFaceExtent (f : cubeMapFaceT) : nat :=
  cubeFaceOffset f + cubeFaceSizeCompressed f.

4.14.24. CubeMap Face Offset Ordering

Definition cubeFaceOffsetsCorrect (c : cubeMipMapT) : Prop :=
     (cubeFaceExtent (cubeMapFaceXPos c) <= cubeFaceOffset (cubeMapFaceXNeg c))
  /\ (cubeFaceExtent (cubeMapFaceXNeg c) <= cubeFaceOffset (cubeMapFaceYPos c))
  /\ (cubeFaceExtent (cubeMapFaceYPos c) <= cubeFaceOffset (cubeMapFaceYNeg c))
  /\ (cubeFaceExtent (cubeMapFaceYNeg c) <= cubeFaceOffset (cubeMapFaceZPos c))
  /\ (cubeFaceExtent (cubeMapFaceZPos c) <= cubeFaceOffset (cubeMapFaceZNeg c)).
Given a base image of size (sizeX, sizeY), the size of the mipmap at level n is given by (sizeX / 2ⁿ, sizeY / 2ⁿ). A mipmap at level n may appear in a valid mipmap list only if 2ⁿ <= sizeX and 2ⁿ <= sizeY. The highest permitted level is the level at which the smaller of the two dimensions reaches 1, so mipmap images of size 1 on one or both axes are permitted.
The uncompressed size of a mipmap should be non-zero. This property is implicit in the definitions above; images must be of a non-zero width and height, and there are no channel layouts where the sizes of the channels sum to zero.
The compressed size of a mipmap should be non-zero. This property is implicit in the definitions above; images must be of a non-zero width and height, and there are no channel layouts where the sizes of the channels sum to zero.
A texture file can have associated free-form metadata. This is often used to, for example, express authorship information and indicate which tools were used to produce a given file. The metadata supported directly by calino is in the form of UTF-8 encoded keys and values. Metadata that requires more structure than this can be provided by custom sections that will be ignored by software that does not know how to interpret them.

4.15.2. Metadata Value

Inductive metadataValueT : Set := MetadataValue {
  mKey   : lanarkT;
  mValue : string
}.

4.15.3. Metadata

Inductive metadataT : Set := Metadata {
  mValues : list metadataValueT
}.
Conceptually, metadata is structured as a function from keys to non-empty lists of values; the values associated with multiple occurrences of a given key are expected to be combined into a list of values for the given key by consumers.
The conditions under which a metadata value is valid are declared by metadataValid (decidable: metadataValidDecidable): each key is a valid Lanark string.

4.15.6. Metadata Validity

Definition metadataValid (m : metadataT) : Prop :=
  Forall (fun v => lanarkValidT (mKey v)) (mValues m).

4.15.7. Metadata Validity Decidable

Theorem metadataValidDecidable : forall m,
  {metadataValid m}+{~metadataValid m}.
Proof.
  (* Proof omitted for brevity; see Metadata.v for proofs. *)
Qed.
An texture is a 2D texture, an array texture, or a cube texture.

4.16.1.2. Texture

Inductive calinoT : Set :=
  | C2D    : calino2DT -> calinoT
  | CCube  : calinoCubeT -> calinoT
  | CArray : calinoArrayT -> calinoT.
The conditions under which a texture is valid are declared by calinoValid (decidable: calinoValidDecidable), which reduces to the validity of the underlying 2D, array, or cube texture.

4.16.1.4. Texture Validity

Definition calinoValid (t : calinoT) : Prop :=
  match t with
  | C2D c    => calino2dValid c
  | CCube c  => calinoCubeValid c
  | CArray c => calinoArrayValid c
  end.

4.16.1.5. Texture Validity Decidable

Theorem calinoValidDecidable : forall c,
  {calinoValid c}+{~calinoValid c}.
Proof.
  (* Proof omitted for brevity; see Calino.v for proofs. *)
Qed.
A 2D texture aggregates image information and a sequence of mipmaps for a single two-dimensional texture.
2D textures must have sizeZ values equal to 1, as declared by calino2dValid.

4.16.2.3. 2D Texture

Inductive calino2DT : Set := Calino2D {
  c2dImageInfo : imageInfoT;
  c2dMipMaps   : mipMapListT;
  c2dMetadata  : metadataT
}.
The constraints on a 2D texture are declared by calino2dValid (decidable: calino2dValidDecidable):

4.16.2.5. 2D Texture Validity

Definition calino2dValid (c : calino2DT) : Prop :=
  let info       := c2dImageInfo c in
  let imageSizeX := ImageSize.sizeX (imageSize info) in
  let imageSizeY := ImageSize.sizeY (imageSize info) in
  let imageSizeZ := ImageSize.sizeZ (imageSize info) in
     imageInfoValid info
  /\ metadataValid (c2dMetadata c)
  /\ mipMapListValid (c2dMipMaps c) imageSizeX imageSizeY
  /\ 1 = imageSizeZ.

4.16.2.6. 2D Texture Validity Decidable

Theorem calino2dValidDecidable : forall c,
  {calino2dValid c}+{~calino2dValid c}.
Proof.
  (* Proof omitted for brevity; see Calino.v for proofs. *)
Qed.
An array texture aggregates image information and a sequence of array mipmaps for a single two-dimensional array texture.
Array textures must have sizeZ values equal to the number of array layers in the texture, as declared by calinoArrayValid.

4.16.3.3. Array Texture

Inductive calinoArrayT : Set := CalinoArray {
  cArrayImageInfo : imageInfoT;
  cArrayMipMaps   : arrayMipMapListT;
  cArrayMetadata  : metadataT
}.
The constraints on an array texture are declared by calinoArrayValid (decidable: calinoArrayValidDecidable):

4.16.3.5. Array Texture Validity

Definition calinoArrayValid (c : calinoArrayT) : Prop :=
  let info       := cArrayImageInfo c in
  let imageSizeX := ImageSize.sizeX (imageSize info) in
  let imageSizeY := ImageSize.sizeY (imageSize info) in
  let imageSizeZ := ImageSize.sizeZ (imageSize info) in
     imageInfoValid info
  /\ metadataValid (cArrayMetadata c)
  /\ arrayMipMapListValid (cArrayMipMaps c) imageSizeX imageSizeY
  /\ 1 <= imageSizeZ
  /\ arrayMipMapListLayerCountIs (cArrayMipMaps c) imageSizeZ.

4.16.3.6. Array Texture Validity Decidable

Theorem calinoArrayValidDecidable : forall c,
  {calinoArrayValid c}+{~calinoArrayValid c}.
Proof.
  (* Proof omitted for brevity; see Calino.v for proofs. *)
Qed.
The proposition arrayMipMapListLayerCountIs (decidable: arrayMipMapListLayerCountIsDecidable) states that the number of layers present at each level of a sequence of array mipmaps equals a given value.

4.16.3.8. Array MipMap List Layer Count

Definition arrayMipMapListLayerCountIs (m : arrayMipMapListT) (n : nat) : Prop :=
  Forall (fun l => arrayMipMapLayerCountForLevel l (arrayMipMaps m) = n) (arrayMipMapLevels (arrayMipMaps m)).

4.16.3.9. Array MipMap List Layer Count Decidable

Theorem arrayMipMapListLayerCountIsDecidable : forall (m : arrayMipMapListT) (n : nat),
  {arrayMipMapListLayerCountIs m n}+{~arrayMipMapListLayerCountIs m n}.
Proof.
  (* Proof omitted for brevity; see Calino.v for proofs. *)
Qed.
3D textures are not yet specified.
A cube texture aggregates image information and a sequence of cube mipmaps for a single cube texture.
Cube textures must have sizeZ values equal to 1, and sizeX values equal to sizeY, as declared by calinoCubeValid.

4.16.5.3. Cube Texture

Inductive calinoCubeT : Set := CalinoCube {
  cCubeImageInfo : imageInfoT;
  cCubeMipMaps   : cubeMipMapListT;
  cCubeMetadata  : metadataT
}.
The constraints on a cube texture are declared by calinoCubeValid (decidable: calinoCubeValidDecidable):

4.16.5.5. Cube Texture Validity

Definition calinoCubeValid (c : calinoCubeT) : Prop :=
  let info       := cCubeImageInfo c in
  let imageSizeX := ImageSize.sizeX (imageSize info) in
  let imageSizeY := ImageSize.sizeY (imageSize info) in
  let imageSizeZ := ImageSize.sizeZ (imageSize info) in
     imageInfoValid info
  /\ metadataValid (cCubeMetadata c)
  /\ cubeMipMapListValid (cCubeMipMaps c) imageSizeX imageSizeY
  /\ imageSizeX = imageSizeY
  /\ 1 = imageSizeZ.

4.16.5.6. Cube Texture Validity Decidable

Theorem calinoCubeValidDecidable : forall c,
  {calinoCubeValid c}+{~calinoCubeValid c}.
Proof.
  (* Proof omitted for brevity; see Calino.v for proofs. *)
Qed.
This section of the specification describes the calino binary encoding. The binary encoding explains how values defined in the model are mapped to streams of octets. Definitions may reference types defined later in the same section; use the cross-references to navigate.
The encoding is written in terms of a simple binary expression language. A file consists of a fixed header followed by a sequence of sized sections. The complete model value is encoded as a JSON document and stored in a single Calino section; image data is stored in a sequence of image data sections, one section per mipmap level, or per level and layer pair.
All properties defined in this section are decidable. See Appendix B for the sources.
The calino texture file format has a strict and easy-to-parse binary encoding, defined in terms of a small binary expression language. Terms in this binary expression language, when evaluated, produce streams of octets that are concatenated together to produce the final output file. This section of the specification defines the expression language, whilst subsequent sections describe how the semantic structures given in the model are mapped to binary expressions.
A term in the binary expression language is described by the following inductive type:

5.2.2.2. Binary Expression

Inductive binaryExp : Set :=
    (** A 32-bit unsigned integer. *)
    | BiU32     : nat -> binaryExp
    (** A 64-bit unsigned integer. *)
    | BiU64     : nat -> binaryExp
    (** A 64-bit IEEE754 binary64 value. *)
    | BiF64     : R -> binaryExp
    (** A sequence of bytes. *)
    | BiBytes   : list byte -> binaryExp
    (** A sequence of bytes describing UTF-8 encoded text. *)
    | BiUTF8    : list byte -> binaryExp
    (** An array of binary expressions. *)
    | BiArray   : list binaryExp -> binaryExp
    (** A section of reserved space. *)
    | BiReserve : nat -> binaryExp
    (** A record with named binary expression members. *)
    | BiRecord  : list (string * binaryExp) -> binaryExp.
An expression BiU32 n represents an unsigned 32-bit integer n.
An expression BiU64 n represents an unsigned 64-bit integer n.
An expression BiF64 f represents a 64-bit IEEE 754 binary floating point value f.
An expression BiBytes xs represents an octet array. Octet arrays are prefixed with an unsigned 32-bit integer value denoting their size in octets, not including any padding. Octet arrays are unconditionally padded with unsigned 8-bit values (which SHOULD be 0xff) such that the total size of the array including padding is evenly divisible by 4.
An expression BiUTF8 xs represents a UTF-8 encoded string. Strings are prefixed with an unsigned 32-bit integer value denoting their encoded size in octets, not including any padding. Strings are unconditionally padded with unsigned 8-bit values (which SHOULD be 0xff) such that the total size of the string including padding is evenly divisible by 4.
An expression BiArray xs represents an array of binary expressions xs. Arrays are prefixed with an unsigned 32-bit integer value denoting the number of array elements present.
An expression BiReserve n represents a block of reserved data of n octets in length. Data is unconditionally padded with unsigned 8-bit values (which SHOULD be 0xff) such that the total size of the block including padding is evenly divisible by 4.
As a defensive measure, padding octets SHOULD have the value 0xff; 0xff octets are typically slightly harder to confuse with valid values than 0x00 octets.
An expression BiRecord fs represents a sequence of named expression values. Intuitively, they can be considered to be fields of a record type. The number of fields is not present in the resulting encoded octet stream, and the names of fields are not included either. Consumers are expected to know, from reading this specification, when to expect a record type in a stream.
All of the possible forms of binary expression have an encoded size that is a multiple of 4. The sizes of each encoded expression form are given by binarySize:

5.2.2.13. Binary Expression Sizes

Fixpoint binarySize (b : binaryExp) : nat :=
  match b with
  | BiU32 _     => 4
  | BiU64 _     => 8
  | BiF64 _     => 8
  | BiBytes s   => 4 + asMultipleOf4 (length s)
  | BiUTF8 s    => 4 + asMultipleOf4 (length s)
  | BiArray f   => 4 + fold_right plus 0 (map binarySize f)
  | BiReserve s => asMultipleOf4 s
  | BiRecord f  => fold_right plus 0 (map (compose binarySize snd) f)
  end.

5.2.2.14. Binary Expression Sizes (multiple of)

Definition asMultipleOf (size q : nat) (Hnz : 0 <> q) : nat :=
  let r := size / q in
    match Nat.ltb_spec0 r q with
    | ReflectT _ _ => (r + 1) * q
    | ReflectF _ _ => r * q
    end.

5.2.2.15. Binary Expression Size Theorem

Theorem binarySizeMultiple4 : forall b, binarySize (b) mod 4 = 0.
This specification text makes use of a convenient abbreviation function, binarySizePadded16, to concisely denote the size of binary expressions padded to a size that is a multiple of 16, as well as a partial application of asMultipleOf fixed to a multiple of 4:

5.2.2.17. Binary Expression Size Padded 16

Definition binarySizePadded16 (b : binaryExp) : nat :=
  asMultipleOf16 (binarySize b).

5.2.2.18. asMultipleOf4

Definition asMultipleOf4 (size : nat) : nat :=
  asMultipleOf size 4 p0not4.
Binary expressions are encoded as streams of streamE values:

5.2.2.20. Stream Elements

Inductive streamE : Set :=
  (** A 64-bit IEEE754 binary64 value. *)
  | Vf64 : R -> streamE
  (** A 64-bit unsigned integer. *)
  | Vu64 : nat -> streamE
  (** A 32-bit unsigned integer. *)
  | Vu32 : nat -> streamE
  (** An 8-bit unsigned integer. *)
  | Vu8  : nat -> streamE.
An expression Vf64 f represents a 64-bit IEEE 754 binary floating point value in big-endian order.
An expression Vu64 n represents an unsigned 64-bit integer in big-endian order.
An expression Vu32 n represents an unsigned 32-bit integer in big-endian order.
An expression Vu8 n represents an unsigned 8-bit integer.
A given binary expression is transformed to a stream of octets using the following encoding rules:

5.2.2.26. Binary Expression Encoding

Fixpoint binaryEval (b : binaryExp) (pad: byte) : list streamE :=
  match b with
  | BiU32 k     => [Vu32 k]
  | BiU64 k     => [Vu64 k] 
  | BiF64 k     => [Vf64 k]
  | BiBytes s   => (Vu32 (length s)) :: (binaryEvalPaddedBytes s 4 pad Alignment.p0not4)
  | BiUTF8 s    => (Vu32 (length s)) :: (binaryEvalPaddedBytes s 4 pad Alignment.p0not4)
  | BiArray f   => (Vu32 (length f)) :: concat (map (fun e => binaryEval e pad) f)
  | BiReserve s => repeat (u8byte pad) (asMultipleOf4 s)
  | BiRecord f  => concat (map (compose (fun e => binaryEval e pad) snd) f)
  end.

5.2.2.27. Binary Expression Encoding (Padding)

Definition binaryEvalPaddedBytes
  (b     : list byte)
  (align : nat)
  (pad   : byte)
  (Hneq  : 0 <> align)
: list streamE :=
  let vremaining := length b mod align in
    match vremaining with
    | 0 => map u8byte b
    | _ => map u8byte (b ++ repeat pad (align - vremaining))
    end.
Informally, a stream s is well-formed if exactly one of the following conditions holds:

5.2.2.29. Well-Formed Stream (Informal rules)

  • s is empty.
  • s consists of a single 64-bit float.
  • s consists of a single 64-bit integer.
  • s consists of a single 32-bit integer.
  • s consists of a sequence of n 8-bit integers, where n is evenly divisible by 4.
  • s is the concatenation of a well-formed stream t and a well-formed stream u.
The rules for well-formedness correspond to the following proposition:

5.2.2.31. Well-Formed Stream

Inductive streamWellFormed : list streamE -> Prop :=
  (** An empty stream is well-formed. *)
  | BEPEmpty  : streamWellFormed []
  (** A stream consisting of a single 64-bit float is well-formed. *)
  | BEPVf64   : forall k, streamWellFormed [Vf64 k]
  (** A stream consisting of a single 64-bit integer is well-formed. *)
  | BEPVu64   : forall k, streamWellFormed [Vu64 k]
  (** A stream consisting of a single 32-bit integer is well-formed. *)
  | BEPVu32   : forall k, streamWellFormed [Vu32 k]
  (** A stream consisting of a number of 8-bit values of a length divisible by 4 is well-formed. *)
  | BEPVu8s   : forall es, Forall streamEIsU8 es -> length (es) mod 4 = 0 -> streamWellFormed es
  (** The concatenation of two well-formed streams is well-formed. *)
  | BEPAppend : forall xs ys, streamWellFormed xs -> streamWellFormed ys -> streamWellFormed (xs ++ ys).
The binary expression encoding rules produce well-formed streams. It follows that any well-formed stream has a size that is evenly divisible by 4.

5.2.2.33. Binary Expression Encoding Well-Formed

Theorem binaryEvalStreamsWellFormed : forall b p,
  streamWellFormed (binaryEval b p).
Proof.
  (* Proof omitted for brevity; see Binary.v for proofs. *)
Qed.

5.2.2.34. Binary Expression Encoding Size Divisible

Theorem streamsWellFormedDivisible4 : forall es,
  streamWellFormed es -> streamSize es mod 4 = 0.
Proof.
  (* Proof omitted for brevity; see Binary.v for proofs. *)
Qed.
The calino binary encoding uses JSON to store complex nested data in the Calino section.
This section of the specification describes how JSON expressions are represented and how they are serialized, and explains how various values from the model are encoded as JSON expressions.
Implementations, upon encountering JSON object properties that they do not recognize, must ignore those properties. This is to facilitate producing new revisions of the specification in a manner that is forwards compatible.
A JSON expression is a value of the following inductive type:

5.3.2.2. JSON Expression

Inductive json : Set :=
  (** A boolean constant. *)
  | JsonBoolean : bool -> json
  (** An integer constant. *)
  | JsonInteger : Z -> json
  (** A floating point constant. *)
  | JsonFloat   : float -> json
  (** A string constant. *)
  | JsonString  : string -> json
  (** An object. *)
  | JsonObject  : list (string * json) -> json
  (** An array. *)
  | JsonArray   : list json -> json
  .
A JSON expression is serialized to a string by first converting it to a sequence of tokens. A JSON token is a value of the following inductive type:

5.3.2.4. JSON Token

Inductive jsonToken : Set :=
  | JTTrue        : jsonToken
  | JTFalse       : jsonToken
  | JTInteger     : Z -> jsonToken
  | JTFloat       : float -> jsonToken
  | JTString      : string -> jsonToken
  | JTObjectStart : jsonToken
  | JTObjectEnd   : jsonToken
  | JTColon       : jsonToken
  | JTComma       : jsonToken
  | JTArrayStart  : jsonToken
  | JTArrayEnd    : jsonToken
  .
Converting an integer to a string is defined by the following function:

5.3.2.6. JSON Serialize Integer

Definition string_of_Z (n : Z) : string :=
  NilZero.string_of_int (Z.to_int n).
Serializing a JSON expression can involve inserting commas between two or more successive tokens:

5.3.2.8. JSON Serialize Comma

Fixpoint jsonComma (ss : list (list jsonToken)) : list jsonToken :=
  match ss with
  | []        => []
  | (x :: []) => x
  | (x :: xs) => x ++ JTComma :: (jsonComma xs)
  end.
Serializing a JSON expression to a sequence of tokens is defined by the following function:

5.3.2.10. JSON Serialize Expression

Fixpoint jsonSerialize (j : json) : list jsonToken :=
  match j with
  | JsonBoolean true  => [JTTrue]
  | JsonBoolean false => [JTFalse] 
  | JsonInteger n     => [JTInteger n]
  | JsonFloat r       => [JTFloat r]
  | JsonString s      => [JTString s]
  | JsonObject o      =>
    let props := map (fun p => JTString (fst p) :: JTColon :: jsonSerialize (snd p)) o in
      JTObjectStart :: (jsonComma props) ++ [JTObjectEnd]
  | JsonArray a       =>
    let values := map jsonSerialize a in
      JTArrayStart :: (jsonComma values) ++ [JTArrayEnd]
  end.
Strings are serialized with the characters 0x22 (double quote), 0x5c (backslash), and control characters 0x00 through 0x1f escaped:

5.3.2.12. JSON Escape Character

Inductive escapedT : Set :=
  | EscapedUnicode : nat -> escapedT
  | EscapedNot     : ascii -> escapedT
  .

5.3.2.13. JSON Escape Character Of

Definition escapeCharacter (c : ascii) : escapedT :=
  let n := Ascii.nat_of_ascii c in
    match Nat.leb n 0x1F with
    | true  => EscapedUnicode n
    | false =>
      if Nat.eqb n 0x5C
      then EscapedUnicode n
      else if Nat.eqb n 0x22
           then EscapedUnicode n
           else EscapedNot c
    end.

5.3.2.14. JSON Escape Characters

Fixpoint escapeCharacters (s : string) : list escapedT :=
  match s with
  | EmptyString => nil
  | String c ss => cons (escapeCharacter c) (escapeCharacters ss)
  end.

5.3.2.15. JSON Escape Character Serialize

Definition escapeCharacterSerialize (c : escapedT) : string :=
  match c with
  | EscapedUnicode n => escapedUnicode n
  | EscapedNot c     => String c ""
  end.

5.3.2.16. JSON Escape Characters Serialize Parts

Fixpoint escapeCharactersSerializeParts (xs : list escapedT) : list string :=
  match xs with
  | nil     => nil
  | y :: ys => cons (escapeCharacterSerialize y) (escapeCharactersSerializeParts ys)
  end.

5.3.2.17. JSON Escape String

Definition escapeString (s : string) : string :=
  let escaped := escapeCharacters s in
  let parts   := escapeCharactersSerializeParts escaped in
    fold_left String.append parts "".
The process to serialize a JSON token is defined by the following function:

5.3.2.19. JSON Serialize Token

Definition jsonStringOne (t : jsonToken) : string :=
  match t with
  | JTTrue        => "true"
  | JTFalse       => "false"
  | JTInteger n   => string_of_Z n
  | JTFloat r     => FloatString.formatFloat r 15
  | JTString s    => """" ++ (escapeString s) ++ """"
  | JTObjectStart => "{"
  | JTObjectEnd   => "}"
  | JTColon       => ":"
  | JTComma       => ","
  | JTArrayStart  => "["
  | JTArrayEnd    => "]"
  end.
Finally, serializing a sequence of JSON tokens to a string is defined by the following function:

5.3.2.21. JSON Serialize

Definition jsonSerializeString (j : json) : string :=
  let tokens := jsonSerialize j in
  let texts  := map jsonStringOne tokens in
    fold_left String.append texts "".
Values of the calinoT type are encoded to JSON using the following functions:

5.3.3.2. Calino JSON

Definition jsonCalino (c : calinoT) : json :=
  match c with
  | C2D x    => jsonCalino2D x
  | CCube x  => jsonCalinoCube x
  | CArray x => jsonCalinoArray x
  end.

5.3.3.3. Calino 2D JSON

Definition jsonCalino2D (c : calino2DT) : json :=
  JsonObject [
    ("@Type",     JsonString "2D");
    ("ImageInfo", jsonImageInfo (c2dImageInfo c));
    ("MipMaps",   jsonMipMapList (c2dMipMaps c));
    ("Metadata",  jsonMetadata (c2dMetadata c))
  ].

5.3.3.4. Calino Cube JSON

Definition jsonCalinoCube (c : calinoCubeT) : json :=
  JsonObject [
    ("@Type",     JsonString "Cube");
    ("ImageInfo", jsonImageInfo (cCubeImageInfo c));
    ("MipMaps",   jsonCubeMipMapList (cCubeMipMaps c));
    ("Metadata",  jsonMetadata (cCubeMetadata c))
  ].

5.3.3.5. Calino Array JSON

Definition jsonCalinoArray (c : calinoArrayT) : json :=
  JsonObject [
    ("@Type",     JsonString "Array");
    ("ImageInfo", jsonImageInfo (cArrayImageInfo c));
    ("MipMaps",   jsonArrayMipMapList (cArrayMipMaps c));
    ("Metadata",  jsonMetadata (cArrayMetadata c))
  ].
Values of the image information type are encoded to JSON using the following functions:

5.3.3.7. Image Info JSON

Definition jsonImageInfo (i : imageInfoT) : json :=
  JsonObject [
    ("ImageSize",              jsonImageSize3D (imageSize i));
    ("ChannelsLayout",         jsonChannelLayoutDescription (imageChannelsLayout i));
    ("ChannelsType",           jsonChannelType (imageChannelsType i));
    ("CompressionMethod",      jsonCompressionMethod (imageCompressionMethod i));
    ("SuperCompressionMethod", jsonSuperCompressionMethod (imageSuperCompressionMethod i));
    ("CoordinateSystem",       jsonCoordinateSystem (imageCoordinateSystem i));
    ("ColorSpace",             jsonColorSpace (imageColorSpace i));
    ("Flags",                  jsonFlagSet (imageFlags i));
    ("OctetOrder",             jsonOctetOrder (imageByteOrder i))
  ].

5.3.3.8. Image Size JSON

Definition jsonImageSize3D (s : imageSize3DT) : json :=
  JsonObject [
    ("SizeX", JsonInteger (Z.of_nat (sizeX s)));
    ("SizeY", JsonInteger (Z.of_nat (sizeY s)));
    ("SizeZ", JsonInteger (Z.of_nat (sizeZ s)))
  ].
Values of the channel types are encoded to JSON using the following functions:

5.3.3.10. Channel Semantic JSON

Definition jsonChannelSemantic (c : channelSemanticT) : json :=
  JsonString (lanarkText (channelSemanticDescribe c)).

5.3.3.11. Channel Description JSON

Definition jsonChannelDescription (c : channelDescriptionT) : json :=
  JsonObject [
    ("Semantic", jsonChannelSemantic (cdSemantic c));
    ("Bits",     JsonInteger (cdBits c))
  ].

5.3.3.12. Channel Packing JSON

Definition jsonPacking (c : channelLayoutPackingT) : json :=
  JsonString (lanarkText (channelLayoutPackingDescribe c)).

5.3.3.13. Channel Layout Description (Unpacked) JSON

Definition jsonChannelLayoutDescriptionUnpacked (s : channelLayoutDescriptionUnpackedT) : json :=
  JsonObject [
    ("@Type",    JsonString "Unpacked");
    ("Channels", JsonArray (map jsonChannelDescription (uChannels s)))
  ].

5.3.3.14. Channel Layout Description (Packed) JSON

Definition jsonChannelLayoutDescriptionPacked (s : channelLayoutDescriptionPackedT) : json :=
  JsonObject [
    ("@Type",    JsonString "Packed");
    ("Channels", JsonArray (map jsonChannelDescription (pChannels s)));
    ("Packing",  jsonPacking (pPacking s))
  ].

5.3.3.15. Channel Layout Description JSON

Definition jsonChannelLayoutDescription (s : channelLayoutDescriptionT) : json :=
  match s with
  | CLDUnpacked u => jsonChannelLayoutDescriptionUnpacked u
  | CLDPacked   p => jsonChannelLayoutDescriptionPacked p
  end.

5.3.3.16. Channel Type JSON

Definition jsonChannelType (c : channelTypeT) : json :=
  JsonString (lanarkText (channelTypeDescribe c)).
Values of the compression type are encoded to JSON using the following function:

5.3.3.18. Compression Method JSON

Definition jsonCompressionMethod (c : compressionMethodT) : json :=
  JsonObject (
    [("@Type", JsonString (lanarkText (compressionMethodDescribe c)))]
    ++
    match c with
    | CUncompressed x => jsonCompressionMethodUncompressed x
    | CBC1 x          => jsonCompressionMethodBC1 x
    | CBC2 x          => jsonCompressionMethodBC2 x
    | CBC3 x          => jsonCompressionMethodBC3 x
    | CBC4 x          => jsonCompressionMethodBC4 x
    | CBC5 x          => jsonCompressionMethodBC5 x
    | CBC6 x          => jsonCompressionMethodBC6 x
    | CBC7 x          => jsonCompressionMethodBC7 x
    | CETC1 x         => jsonCompressionMethodETC1 x
    | CETC2 x         => jsonCompressionMethodETC2 x
    | CEAC x          => jsonCompressionMethodEAC x
    | CASTC x         => jsonCompressionMethodASTC x
    | CCustom x       => jsonCompressionMethodCustom x
    end
  ).
Values of the super compression type are encoded to JSON using the following function:

5.3.3.20. Super Compression Method JSON

Definition jsonSuperCompressionMethod (c : superCompressionMethodT) : json :=
  JsonObject (
    [("@Type", JsonString (lanarkText (superCompressionMethodDescribe c)))]
    ++
    match c with
    | SCUncompressed x => jsonSuperCompressionMethodUncompressed x
    | SCLZ4 x          => jsonSuperCompressionMethodLZ4 x
    | SCDEFLATE x      => jsonSuperCompressionMethodDEFLATE x
    | SCCustom x       => jsonSuperCompressionMethodCustom x
    end
  ).
Values of the coordinate system, color space, flag, and octet order types are encoded to JSON using the following functions:

5.3.3.22. Coordinate System JSON

Definition jsonCoordinateSystem (c : coordinateSystemT) : json :=
  match c with
  | CoordinateSystem r s t =>
    JsonObject [
      ("AxisR", JsonString (lanarkText (coordinateAxisRDescribe r)));
      ("AxisS", JsonString (lanarkText (coordinateAxisSDescribe s)));
      ("AxisT", JsonString (lanarkText (coordinateAxisTDescribe t)))
    ]
  end.

5.3.3.23. Color Space JSON

Definition jsonColorSpace (c : colorSpaceT) : json :=
  JsonString (lanarkText (colorSpaceDescribe c)).

5.3.3.24. Flag JSON

Definition jsonFlag (f : flagT) : json :=
  JsonString (lanarkText (flagDescribe f)).

5.3.3.25. Octet Order JSON

Definition jsonOctetOrder (o : octetOrder) : json :=
  JsonString (lanarkText (byteOrderDescribe o)).

5.3.3.26. Flag Set JSON

Definition jsonFlagSet (f : flagSetT) : json :=
  JsonArray (map jsonFlag (flags f)).
Values of the metadata type are encoded to JSON using the following functions:

5.3.3.28. Metadata Value JSON

Definition jsonMetadataValue (m : metadataValueT) : json :=
  JsonObject [
    ("Key",   JsonString (lanarkText (mKey m)));
    ("Value", JsonString (mValue m))
  ].

5.3.3.29. Metadata JSON

Definition jsonMetadata (m : metadataT) : json :=
  JsonArray (map jsonMetadataValue (mValues m)).
Values of the mipmap types are encoded to JSON using the following functions:

5.3.3.31. MipMap JSON

Definition jsonMipMap (m : mipMapT) : json :=
  JsonObject [
    ("Level",            JsonInteger (Z.of_nat (mipMapLevel m)));
    ("SizeCompressed",   JsonInteger (Z.of_nat (mipMapSizeCompressed m)));
    ("SizeUncompressed", JsonInteger (Z.of_nat (mipMapSizeUncompressed m)));
    ("CRC32",            JsonInteger (Z.of_nat (mipMapCRC32 m)))
  ].

5.3.3.32. MipMap List JSON

Definition jsonMipMapList (m : mipMapListT) : json :=
  JsonArray (map jsonMipMap (mipMaps m)).

5.3.3.33. Array MipMap Index JSON

Definition jsonArrayMipMapIndex (i : arrayMipMapIndexT) : json :=
  JsonObject [
    ("Level", JsonInteger (Z.of_nat (arrayMipMapLevel i)));
    ("Layer", JsonInteger (Z.of_nat (arrayMipMapLayer i)))
  ].

5.3.3.34. Array MipMap JSON

Definition jsonArrayMipMap (m : arrayMipMapT) : json :=
  JsonObject [
    ("Index",            jsonArrayMipMapIndex (arrayMipMapIndex m));
    ("SizeCompressed",   JsonInteger (Z.of_nat (arrayMipMapSizeCompressed m)));
    ("SizeUncompressed", JsonInteger (Z.of_nat (arrayMipMapSizeUncompressed m)));
    ("CRC32",            JsonInteger (Z.of_nat (arrayMipMapCRC32 m)))
  ].

5.3.3.35. Array MipMap List JSON

Definition jsonArrayMipMapList (m : arrayMipMapListT) : json :=
  JsonArray (map jsonArrayMipMap (arrayMipMaps m)).

5.3.3.36. Cube Map Face JSON

Definition jsonCubeMapFace (f : cubeMapFaceT) : json :=
  JsonObject [
    ("Offset",           JsonInteger (Z.of_nat (cubeFaceOffset f)));
    ("SizeCompressed",   JsonInteger (Z.of_nat (cubeFaceSizeCompressed f)));
    ("SizeUncompressed", JsonInteger (Z.of_nat (cubeFaceSizeUncompressed f)));
    ("CRC32",            JsonInteger (Z.of_nat (cubeFaceCRC32 f)))
  ].

5.3.3.37. Cube MipMap JSON

Definition jsonCubeMipMap (m : cubeMipMapT) : json :=
  JsonObject [
    ("Level",         JsonInteger (Z.of_nat (cubeMipMapLevel m)));
    ("FaceXPositive", jsonCubeMapFace (cubeMapFaceXPos m));
    ("FaceXNegative", jsonCubeMapFace (cubeMapFaceXNeg m));
    ("FaceYPositive", jsonCubeMapFace (cubeMapFaceYPos m));
    ("FaceYNegative", jsonCubeMapFace (cubeMapFaceYNeg m));
    ("FaceZPositive", jsonCubeMapFace (cubeMapFaceZPos m));
    ("FaceZNegative", jsonCubeMapFace (cubeMapFaceZNeg m))
  ].

5.3.3.38. Cube MipMap List JSON

Definition jsonCubeMipMapList (m : cubeMipMapListT) : json :=
  JsonArray (map jsonCubeMipMap (cubeMipMaps m)).
All of the above JSON encodings are injective; the corresponding theorems are given in Appendix B.
The sections of a file begin with a 64-bit value called the section identifier. The identifier is followed by a 64-bit value, called the section size. The size value is the number of octets of valid data present in the section, not including any padding octets that follow the valid data. The section size is followed by the section data, and then by 0 to 15 octets of padding (which SHOULD have the value 0xff; see the note on padding octets), such that the next section, if there is one, begins on a 16-octet boundary. All sections of a file therefore begin at a file offset that is a multiple of 16 octets.
The first section in a file must be a Calino section, which contains the JSON encoding of the complete model value.
Image data is stored in a sequence of image data sections. For two-dimensional and cube map images, there is one image data section per mipmap level. For array images, there is one image data section per level and layer pair. The number of image data sections present in a file is determined by the contents of the Calino section.
A file must end with exactly one end section.
The standard sections are as follows:

5.4.1.6. Standard Sections

Section identifier Section
0x434c4e5f434c4e4f CLN_CLNO
0x434c4e5f4d493234 CLN_MI2D
0x434c4e5f4d49435542 CLN_MCUB
0x434c4e5f4d49415252 CLN_MARR
0x434c4e5f454e4421 CLN_END!
Sections with identifiers other than the ones listed above are permitted, and their contents are not interpreted by consumers of this revision of the specification.
The identifier of a calino file is given by the following definition:

5.4.2.2. File Identifier

Definition fileIdentifier : TagT :=
  Tag x89 x43 x4c x4e x0d x0a x1a x0a.
A calino file is identified by the following magic number:

5.4.2.4. File Magic Number

89 43 4c 4e 0d 0a 1a 0a
The magic number is followed by a 32-bit unsigned integer value representing the major version number of the calino file format. This revision of the specification requires that the major version number is 2.
The major version number is followed by a 32-bit unsigned integer value representing the minor version number of the calino file format. This revision of the specification requires that the minor version number is 0.

5.4.2.7. Binary Expression (File Header)

Definition binaryExpFileHeader : binaryExp := BiRecord [
  ("id",           u64 (tagNat fileIdentifier));
  ("versionMajor", u32 fileVersionMajor);
  ("versionMinor", u32 fileVersionMinor)
].
The identifier of the Calino section is given by the following definition:

5.4.3.2. Calino Section Identifier

Definition sectionCalinoIdentifier : TagT :=
  Tag x43 x4c x4e x5f x43 x4c x4e x4f.
The Calino section contains the JSON encoding of the complete model value. It must be the first section in the file, and there must be exactly one of them.

5.4.3.4. Calino Section Encoding

Definition binaryExpCalinoSection (c : calinoT) : binaryExp :=
  let jsonE        := jsonCalino c in
  let jsonText     := jsonSerializeString jsonE in
  let jsonTextSize := 4 + (String.length jsonText) in
    BiRecord [
      ("id",   u64 (tagNat sectionCalinoIdentifier));
      ("size", u64 jsonTextSize);
      ("data", utf8 jsonText)
    ].
The section data is a BiUTF8 encoding of the string produced by serializing the value jsonCalino c, where c is the model value. The section size field is the number of octets of valid data in the section: 4 octets for the BiUTF8 length prefix, plus the encoded length of the serialized JSON text, not including padding.
The identifier of a 2D image data section is given by the following definition:

5.4.4.2. 2D Section Identifier

Definition sectionImage2DIdentifier : TagT :=
  Tag x43 x4c x4e x5f x4d x49 x32 x44.
Two-dimensional image data is stored in a sequence of 2D image data sections, one per mipmap level of the 2D texture. The number of 2D image data sections is the number of mipmap levels. The sections appear in the file in the order of the sequence of mipmaps, from the highest level to level 0.

5.4.4.4. 2D Image Section Encoding

Definition binaryExpImageSection2D (c : mipMapT) : binaryExp :=
  let imageSize := mipMapSizeCompressed c in
  let dataSize  := 4 + 4 + 4 + 4 + imageSize in
    BiRecord [
      ("id",    u64 (tagNat sectionImage2DIdentifier));
      ("size",  u64 dataSize);
      ("level", u32 (mipMapLevel c));
      ("pad0",  u32 0xffffffff);
      ("pad1",  u32 0xffffffff);
      ("pad2",  u32 0xffffffff);
      ("data",  BiReserve imageSize)
    ].
The section data consists of a 32-bit unsigned integer mipmap level value, three 32-bit reserved values, and a BiReserve block of mipMapSizeCompressed octets holding the mipmap level's image data. The section size field is 16 plus mipMapSizeCompressed.

5.4.4.6. 2D Image Sections

Definition binaryExpImageSections2D (c : mipMapListT) : list binaryExp :=
  map binaryExpImageSection2D (mipMaps c).
The identifier of a cube image data section is given by the following definition:

5.4.5.2. Cube Section Identifier

Definition sectionImageCubeIdentifier : TagT :=
  Tag x43 x4c x4e x5f x4d x43 x55 x42.
Cube map image data is stored in a sequence of cube image data sections, one per mipmap level of the cube texture. The number of cube image data sections is the number of mipmap levels. The sections appear in the file in the order of the sequence of cube mipmaps, from the highest level to level 0.

5.4.5.4. Cube Image Section Encoding

Definition binaryExpImageSectionCube (c : cubeMipMapT) : binaryExp :=
  let imageSize := cubeFaceExtent (cubeMapFaceZNeg c) in
  let dataSize  := 4 + 4 + 4 + 4 + imageSize in
    BiRecord [
      ("id",    u64 (tagNat sectionImageCubeIdentifier));
      ("size",  u64 dataSize);
      ("level", u32 (cubeMipMapLevel c));
      ("pad0",  u32 0xffffffff);
      ("pad1",  u32 0xffffffff);
      ("pad2",  u32 0xffffffff);
      ("data",  BiReserve imageSize)
    ].
The section data consists of a 32-bit unsigned integer mipmap level value, three 32-bit reserved values, and a BiReserve block holding the six cube map face data blocks. The per-face offsets, given by the JSON encoding of the mipmap list, in the Calino section, are relative to the start of the BiReserve block, and give the position of each face data block within it. In the canonical serialization, the face data blocks are concatenated in the order X positive, X negative, Y positive, Y negative, Z positive, Z negative. The section size field is 16 plus the extent of the Z negative face. Octets of the BiReserve block that are not covered by a face data block are undefined.

5.4.5.6. Cube Image Sections

Definition binaryExpImageSectionsCube (c : cubeMipMapListT) : list binaryExp :=
  map binaryExpImageSectionCube (cubeMipMaps c).
The identifier of an array image data section is given by the following definition:

5.4.6.2. Array Section Identifier

Definition sectionImageArrayIdentifier : TagT :=
  Tag x43 x4c x4e x5f x4d x41 x52 x52.
Array image data is stored in a sequence of array image data sections, one per level and layer pair of the array texture. The number of array image data sections is the product of the number of mipmap levels and the number of layers. The sections appear in the file in the order of the sequence of array mipmaps: from the highest level to level 0, and, within each level, from layer 0 to the last layer.

5.4.6.4. Array Image Section Encoding

Definition binaryExpImageSectionArray (c : arrayMipMapT) : binaryExp :=
  let imageSize := arrayMipMapSizeCompressed c in
  let dataSize  := 4 + 4 + 4 + 4 + imageSize in
    BiRecord [
      ("id",    u64 (tagNat sectionImageArrayIdentifier));
      ("size",  u64 dataSize);
      ("level", u32 (arrayMipMapLevel (arrayMipMapIndex c)));
      ("layer", u32 (arrayMipMapLayer (arrayMipMapIndex c)));
      ("pad0",  u32 0xffffffff);
      ("pad1",  u32 0xffffffff);
      ("data",  BiReserve imageSize)
    ].
The section data consists of a 32-bit unsigned integer mipmap level value, a 32-bit unsigned integer layer value, two 32-bit reserved values, and a BiReserve block of arrayMipMapSizeCompressed octets holding the layer's mipmap level image data. The section size field is 16 plus arrayMipMapSizeCompressed.

5.4.6.6. Array Image Sections

Definition binaryExpImageSectionsArray (c : arrayMipMapListT) : list binaryExp :=
  map binaryExpImageSectionArray (arrayMipMaps c).
The identifier of the end section is given by the following definition:

5.4.7.2. End Section Identifier

Definition sectionEndIdentifier : TagT :=
  Tag x43 x4c x4e x5f x45 x4e x44 x21.
A calino file must end with an end section.

5.4.7.4. End Section Encoding

Definition binaryEndSection : binaryExp := BiRecord [
  ("id",   u64 (tagNat sectionEndIdentifier));
  ("size", u64 0)
].
The end section must have a size value of 0. There must be exactly one end section in a file, and it must be the last section in the file.
The end section must not have any trailing data.
Sections with identifiers other than the standard sections are permitted in a file. Consumers of this revision of the specification must not interpret the contents of such sections.
The complete file, as a list binaryExp value, is given by the following definition:

5.4.9.2. File

Definition binaryFile (c : calinoT) : list binaryExp :=
  (binaryExpCalinoSection c) :: (binaryExpImageSections c ++ [binaryEndSection]).
The complete file format, as a FileDescriptionT value, is given by the following definition:

5.4.9.4. File Description

Definition fileDescription : FileDescriptionT :=
  FileDescription
  fileIdentifier
  fileVersionMajor
  fileVersionMinor
  [sectionCalino; sectionImage2D; sectionImageCube; sectionImageArray]
  sectionEndIdentifier
  UnknownSectionsPermitted
  .
The per-section descriptions are given by the following definitions:

5.4.9.6. Calino Section Description

Definition sectionCalino :=
  FileSectionDescription sectionCalinoIdentifier FSO_MustBeFirst FSC_One.

5.4.9.7. 2D Image Section Description

Definition sectionImage2D :=
  FileSectionDescription sectionImage2DIdentifier FSO_AnyOrder FSC_ZeroToN.

5.4.9.8. Cube Image Section Description

Definition sectionImageCube :=
  FileSectionDescription sectionImageCubeIdentifier FSO_AnyOrder FSC_ZeroToN.

5.4.9.9. Array Image Section Description

Definition sectionImageArray :=
  FileSectionDescription sectionImageArrayIdentifier FSO_AnyOrder FSC_ZeroToN.
The file description satisfies the format invariants:

5.4.9.11. File Description Invariants Example

Theorem fileDescriptionInvariantsExample : fileDescriptionInvariants fileDescription.
The filename suffix .ctf is recommended for calino files.
The use of a particular filename suffix is advisory only, and consumers must determine the file type by inspecting the magic number in the file header, not by the filename.
The MIME type application/vnd.io7m.calino is registered for calino files.
The following references are normative. A well-formed implementation of the calino format must conform to the specifications cited below.

6.1.2. Normative References

Reference Description URI
IEEE754 IEEE Standard for Floating-Point Arithmetic, IEEE 754-2019 (July 2019). Also published as ISO/IEC/IEEE 60559:2020. Retrieval URI
sRGB Default RGB colour space - sRGB, IEC 61966-2-1:1999. Retrieval URI
zlib ZLIB Compressed Data Format Specification, RFC 1950 (May 1996). The container format emitted by the DEFLATE supercompression method. Retrieval URI
DEFLATE DEFLATE Compressed Data Format Specification, RFC 1951 (May 1996). The compression algorithm used within the zlib container. Retrieval URI
LZ4 The LZ4 compression algorithm. No published RFC or IEC standard exists; the project page is the primary source. Retrieval URI
Unicode The Unicode Standard. String values in the format are Unicode text. Retrieval URI
UTF-8 UTF-8, a transformation format of ISO 10646, RFC 3629 (STD 63, November 2003). The byte encoding of Unicode string values. Retrieval URI
Rocq The Rocq Theorem Prover - Reference Manual, Version 9.0.0. The formal model of the format is expressed in Rocq. Retrieval URI
Zeniro The Zeniro file format. Retrieval URI
Lanark Lanark dotted name strings. The string format used to identify values of the enumerated types defined in this specification; the Rocq specification is normative. Retrieval URI
The following references are informative. They provide context, comparison, or supplementary material but are not requirements for a conformant calino implementation.

6.2.2. Informative References

Reference Description URI
BCn / DXT S3TC block-compression texture formats (BC1, BC2, and BC3, also known as DXT1, DXT3, and DXT5), and the related BC7 format. Proprietary (Microsoft); no public standard. Retrieval URI
ETC Ericsson Texture Compression, including ETC1, ETC2, and EAC. Retrieval URI
ASTC Adaptive Scalable Texture Compression. Retrieval URI
Version 2.0 of the specification is a major reworking of the 1.0 format.
The changes made in version 2.0 are as follows:

7.1.3. Changes in Version 2.0

  • The file layout and the set of standard sections have been reworked. The image information and metadata sections, and the monolithic per-texture-type image data sections, have been removed. They are replaced by a single Calino section holding the complete model as a JSON document, and by a sequence of per-mipmap image data sections. See File layout and sections.
  • The section size field no longer includes the 16-octet alignment padding that follows the section data. See Section sizes.
  • The complete model value is now encoded as a single JSON document in the Calino section, instead of as separate binary sections. See Model encoding.
  • Alignment padding octets now SHOULD have the value 0xff. See Padding octets.
  • All descriptor values have been redefined as lowercase Lanark strings, and several model values that were previously single concatenated descriptor strings are now structured values. See Descriptors.
In version 1.0, a file consisted of the file header, an optional image information section (identifier 0x434C4E49494E464F), exactly one of the three texture data sections (identifiers 0x434C4E5F49324421, 0x434C4E5F41525221, or 0x434C4E5F43554245), an optional metadata section (identifier 0x434C4E5F4D455441), and a single end section (identifier 0x434C4E5F454E4421). All of the image data for the texture was stored in the single texture data section: a serialized array of mipmap descriptions, each carrying an explicit data offset, followed by padding, followed by the concatenated image data for every mipmap, padded to a multiple of 16 octets. The texture type was implicit in which of the three texture data sections was present.
In version 2.0, a file consists of the file header, exactly one Calino section (identifier 0x434C4E5F434C4E4F), which must be the first section in the file and which holds the complete model as a JSON document; a sequence of image data sections, one per mipmap (for two-dimensional and cube map textures, one section per mipmap level; for array textures, one section per level and layer pair); and exactly one end section (identifier 0x434C4E5F454E4421), which must be the last section in the file. Each image data section holds the (super-)compressed data of exactly one mipmap, immediately after an 8-octet header carrying the mipmap level (and, for array sections, the layer), and no explicit data offsets are present. The texture type is given explicitly by the Calino section. The image data sections appear in the file in mipmap order, from the highest level down to level 0 (and, for array sections, from layer 0 to the last layer within each level). Sections with other identifiers are permitted, and consumers must not interpret the contents of such sections.
The standard sections of version 2.0, and the version 1.0 sections they replace, are as follows:

7.2.4. Section Identifiers

1.0 identifier 1.0 section 2.0 identifier 2.0 section
0x434C4E49494E464F Image information. 0x434C4E5F434C4E4F Calino (image information and metadata, as JSON).
0x434C4E5F49324421 Image data for 2D textures. 0x434C4E5F4D493234 2D image data, one section per mipmap level.
0x434C4E5F41525221 Image data for array textures. 0x434C4E5F4D415252 Array image data, one section per level and layer pair.
0x434C4E5F43554245 Image data for cube textures. 0x434C4E5F4D435542 Cube image data, one section per mipmap level.
0x434C4E5F4D455441 Key/value metadata. — Metadata is a member of the Calino section.
0x434C4E5F454E4421 File terminator. 0x434C4E5F454E4421 End (unchanged).
In version 1.0, the section size field of every section was specified to include the padding octets used to align the next section to a 16-octet boundary. For example, the 2D texture data section was specified as follows:

7.3.2. Section Padding (1.0)

Definition binaryExpImage2DSection
  (i : imageInfo)
  (m : mipMapList)
: binaryExp := BiRecord [
  ("id",   u64 0x434C4E5F49324421);
  ("size", u64 (binarySizePadded16 (binaryExpImage2D i m)));
  ("data", binaryExpImage2D i m)
].
The actual intention was for the size to count only the valid data octets of the section, not the padding octets. As specified, however, the value of the size field was ambiguous: a consumer interpreting the field as a count of valid data octets would compute a different offset for the next section than a consumer interpreting it as the formal definition above. Version 2.0 resolves this by specifying explicitly that the section size field is the number of octets of valid data present in the section, not including any padding octets. See the sections of the binary encoding for the normative definition.
In version 1.0, the model value was split across separate binary sections: the image information section encoded the image information value as a binary record with UTF-8 descriptor strings, and the metadata section encoded the metadata value as an array of key/value pairs. In version 2.0, the complete model value — image information, the mipmap list, the metadata, and an explicit texture type discriminator — is encoded as a single JSON document and stored in the Calino section. The JSON text is not byte-for-byte normative: any valid JSON text denoting the model value is conforming, and consumers must ignore properties they do not recognize. See JSON and CLN_CLNO.
Version 1.0 did not specify the value of padding octets. In version 2.0, all alignment padding octets — both the 4-octet alignment padding within BiBytes, BiUTF8, and BiReserve payloads, and the 16-octet section padding — SHOULD have the value 0xff, as a defensive measure: 0xff octets are typically slightly harder to confuse with valid values than 0x00 octets. Consumers must accept any octet values in padding positions and must not validate them. See the note on padding octets.
Version 1.0 used uppercase, and in some cases concatenated, descriptor strings. For example, channel types were given values such as FIXED_POINT_NORMALIZED_UNSIGNED, octet orders BIG_ENDIAN and LITTLE_ENDIAN, color spaces LINEAR and SRGB, and the flag ALPHA_PREMULTIPLIED. Channel semantics were single characters ( R, G, B, A, D, S, E, X), a channel layout was a single concatenated string such as R8:G8:B8:A8 (optionally prefixed with the packing, for example p8|R8:G8:B8:A8), and a coordinate system was a single concatenated string such as RT:SR:TD.
In version 2.0, every descriptor value is a lowercase Lanark string. The standard values given in this specification are reserved, and any non-standard value must be a valid Lanark string that is not reserved by calino. For example, the channel types above are now given as fixed_point_normalized_unsigned, the octet orders as big_endian and little_endian, the color spaces as linear and srgb, and the flag as alpha_premultiplied.
In addition, two model values that were single concatenated descriptor strings in version 1.0 are now structured values: a channel layout is now a list of channel descriptions (each a channel semantic and a bit count), optionally with a packing, and a coordinate system is now three separate axis values. See Channels and Coordinate Systems in the model.
The full sources for the Rocq model underlying this specification are included here.

8.2. Calino/ArrayMipMap.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Bool.Bool.

Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.NatFacts.

Import ListNotations.

Inductive arrayMipMapIndexT : Set := ArrayMipMapIndex {
  arrayMipMapLevel : nat;
  arrayMipMapLayer : nat;
}.

Definition arrayMipMapIndexEqDecidable : forall (a b : arrayMipMapIndexT),
  {a = b}+{~a = b}.
Proof.
  destruct a as [a0 a1];
  destruct b as [b0 b1];
  destruct (Nat.eq_dec a0 b0);
  destruct (Nat.eq_dec a1 b1).
  * subst; left; auto.
  * right.
    unfold not; intro H; inversion H.
    contradiction.
  * right.
    unfold not; intro H; inversion H.
    contradiction.
  * right.
    unfold not; intro H; inversion H.
    contradiction.
Qed.

Definition arrayMipMapIndexNextLayer (x y : arrayMipMapIndexT) : Prop :=
     arrayMipMapLevel x = arrayMipMapLevel y
  /\ arrayMipMapLayer y = S (arrayMipMapLayer x).

Definition arrayMipMapIndexNextLevel (x y : arrayMipMapIndexT) : Prop :=
     arrayMipMapLevel x = S (arrayMipMapLevel y)
  /\ arrayMipMapLayer y = 0.

(** @annospec 40902752-59a6-4222-aa76-8d41ab075a10 *)
Inductive arrayMipMapIndicesSorted : list arrayMipMapIndexT -> Prop :=
  | AMMIOne  : forall m, arrayMipMapIndicesSorted [m]
  | AMMICons : forall mmx mmy mxs,
    (arrayMipMapIndexNextLayer mmx mmy \/ arrayMipMapIndexNextLevel mmx mmy) ->
      arrayMipMapIndicesSorted (mmy :: mxs) ->
        arrayMipMapIndicesSorted (mmx :: mmy :: mxs).

Inductive arrayMipMapT : Set := ArrayMipMap {
  arrayMipMapIndex            : arrayMipMapIndexT;
  arrayMipMapSizeCompressed   : nat;
  arrayMipMapSizeUncompressed : nat;
  arrayMipMapCRC32            : nat
}.

Fixpoint arrayMipMapLayerCountForLevel
  (level : nat)
  (m     : list arrayMipMapT)
: nat :=
  match m with
  | []        => 0
  | (x :: xs) =>
    match Nat.eq_dec (arrayMipMapLevel (arrayMipMapIndex x)) level with
    | left _  => 1 + (arrayMipMapLayerCountForLevel level xs)
    | right _ => (arrayMipMapLayerCountForLevel level xs)
    end
  end.

Definition arrayMipMapLevels (m : list arrayMipMapT) : list nat :=
  nodup Nat.eq_dec (map (fun k => arrayMipMapLevel (arrayMipMapIndex k)) m).

(** @annospec 67b2279c-c6a7-47d7-9dc7-060a6ed678cc *)
Definition arrayMipMapListSameLayers (m : list arrayMipMapT) : Prop :=
  match arrayMipMapLevels m with
  | nil     => True
  | l1 :: _ => Forall (fun l0 => arrayMipMapLayerCountForLevel l0 m = arrayMipMapLayerCountForLevel l1 m) (arrayMipMapLevels m)
  end.

(** @annospec 22621879-febe-4d9e-950e-23ebbb6e1c4a *)
Fixpoint arrayMipMapListLevelZero (m : list arrayMipMapT) : Prop :=
  match m with
  | nil      => False
  | x :: nil => arrayMipMapLevel (arrayMipMapIndex x) = 0
  | _ :: xs  => arrayMipMapListLevelZero xs
  end.

(** @annospec a3113778-f91e-4411-aebe-2b3bd95ea616 *)
Definition arrayMipMapListMaxLevelBounded (m : list arrayMipMapT) (sizeX sizeY : nat) : Prop :=
  match m with
  | nil    => True
  | x :: _ => (2 ^ arrayMipMapLevel (arrayMipMapIndex x)) <= sizeX
           /\ (2 ^ arrayMipMapLevel (arrayMipMapIndex x)) <= sizeY
  end.

(** @annospec d5a2c9db-e09d-42b5-b2c8-571ec3e5feeb *)
Definition arrayMipMapListIsNonEmpty (m : list arrayMipMapT) : Prop :=
  nil <> m.

(** @annospec 76df2966-08ea-4d27-ae26-0c9d8215e4fa *)
Definition arrayMipMapListFirstLayerZero (m : list arrayMipMapT) : Prop :=
  match m with
  | nil    => True
  | x :: _ => arrayMipMapLayer (arrayMipMapIndex x) = 0
  end.

(** @annospec fd41c4a4-c38c-49ff-8db9-09993b08c988 *)
Inductive arrayMipMapListT : Set := ArrayMipMapList {
  arrayMipMaps : list arrayMipMapT;
}.

(** @annospec fd41c4a4-c38c-49ff-8db9-09993b08c988 *)
Definition arrayMipMapListValid (a : arrayMipMapListT) (sizeX sizeY : nat) : Prop :=
     arrayMipMapIndicesSorted (map arrayMipMapIndex (arrayMipMaps a))
  /\ arrayMipMapListSameLayers (arrayMipMaps a)
  /\ arrayMipMapListLevelZero (arrayMipMaps a)
  /\ arrayMipMapListFirstLayerZero (arrayMipMaps a)
  /\ arrayMipMapListMaxLevelBounded (arrayMipMaps a) sizeX sizeY
  /\ arrayMipMapListIsNonEmpty (arrayMipMaps a).

Theorem arrayMipMapIndexNextLayerDecidable : forall i0 i1,
  {arrayMipMapIndexNextLayer i0 i1}+{~arrayMipMapIndexNextLayer i0 i1}.
Proof.
  intros i0 i1.
  unfold arrayMipMapIndexNextLayer.
  destruct (Nat.eq_dec (arrayMipMapLevel i0) (arrayMipMapLevel i1)) as [H0L|H0R].
  destruct (Nat.eq_dec (arrayMipMapLayer i1) (S (arrayMipMapLayer i0))) as [H1L|H1R].
  - left; intuition.
  - right; intuition.
  - right; intuition.
Qed.

Theorem arrayMipMapIndexNextLevelDecidable : forall i0 i1,
  {arrayMipMapIndexNextLevel i0 i1}+{~arrayMipMapIndexNextLevel i0 i1}.
Proof.
  intros i0 i1.
  unfold arrayMipMapIndexNextLevel.
  destruct (Nat.eq_dec (arrayMipMapLevel i0) (S (arrayMipMapLevel i1))) as [H0L|H0R].
  destruct (Nat.eq_dec (arrayMipMapLayer i1) 0) as [H1L|H1R].
  - left; intuition.
  - right; intuition.
  - right; intuition.
Qed.

Theorem arrayMipMapIndicesSortedDecidable : forall m,
  {arrayMipMapIndicesSorted m}+{~arrayMipMapIndicesSorted m}.
Proof.
  induction m as [|q0 qs IHqs].
  - right; unfold not; intro H; inversion H.
  - destruct qs as [|q1 qs].
    * left; constructor.
    * destruct IHqs as [HQL|HQR].
      -- destruct (arrayMipMapIndexNextLayerDecidable q0 q1) as [H0L|H0R].
         ** left; constructor; auto.
         ** destruct (arrayMipMapIndexNextLevelDecidable q0 q1) as [H1L|H1R].
            --- left; constructor; auto.
            --- right.
                unfold not; intro H; inversion H.
                destruct H2; contradiction.
      -- right.
         unfold not; intro H; inversion H.
         contradiction.
Qed.

Theorem arrayMipMapListMaxLevelBoundedDecidable : forall m sizeX sizeY,
  {arrayMipMapListMaxLevelBounded m sizeX sizeY}+{~arrayMipMapListMaxLevelBounded m sizeX sizeY}.
Proof.
  unfold arrayMipMapListMaxLevelBounded.
  destruct m as [|x xs].
  - intros.
    left; constructor.
  - intros.
    destruct (le_dec (2 ^ arrayMipMapLevel (arrayMipMapIndex x)) sizeX).
    destruct (le_dec (2 ^ arrayMipMapLevel (arrayMipMapIndex x)) sizeY).
    * left; auto.
    * right; intuition.
    * right; intuition.
Qed.

Theorem arrayMipMapListIsNonEmptyDecidable : forall m,
  {arrayMipMapListIsNonEmpty m}+{~arrayMipMapListIsNonEmpty m}.
Proof.
  unfold arrayMipMapListIsNonEmpty.
  destruct m.
  * right; intuition.
  * left; discriminate.
Qed.

Theorem arrayMipMapListLevelZeroDecidable : forall m,
  {arrayMipMapListLevelZero m}+{~arrayMipMapListLevelZero m}.
Proof.
  induction m as [|q qs IHqs].
  * right; intuition.
  * destruct qs.
    - destruct (Nat.eq_dec (arrayMipMapLevel (arrayMipMapIndex q)) 0) as [HL|HR].
      ** left; auto.
      ** right; intuition.
    - destruct IHqs as [HL|HR].
      ** left; auto.
      ** right; intuition.
Qed.

Theorem arrayMipMapListFirstLayerZeroDecidable : forall m,
  {arrayMipMapListFirstLayerZero m}+{~arrayMipMapListFirstLayerZero m}.
Proof.
  destruct m.
  - left; constructor.
  - apply Nat.eq_dec.
Qed.

Theorem arrayMipMapListSameLayersDecidable : forall m,
  {arrayMipMapListSameLayers m}+{~arrayMipMapListSameLayers m}.
Proof.
  unfold arrayMipMapListSameLayers.
  intros m.
  destruct (arrayMipMapLevels m) as [|r rs].
  - left; constructor.
  - induction rs as [|q qs IHqs].
    * left; constructor; auto.
    * destruct (Nat.eq_dec (arrayMipMapLayerCountForLevel r m)
                           (arrayMipMapLayerCountForLevel q m)) as [HL|HR].
      -- destruct IHqs as [H0L|H0R].
         ** left.
            constructor.
            reflexivity.
            constructor.
            symmetry.
            exact HL.
            apply (Forall_inv_tail H0L).
         ** right.
            unfold not; intro Hfalse; inversion Hfalse.
            subst.
            pose proof (Forall_inv_tail H2) as Hqs.
            apply H0R.
            apply Forall_cons.
            reflexivity.
            exact Hqs.
      -- right.
         unfold not; intro Hfalse; inversion Hfalse.
         subst.
         inversion H2.
         subst.
         symmetry in H3.
         contradiction.
Qed.

Theorem arrayMipMapListValidDecidable : forall m sizeX sizeY,
  {arrayMipMapListValid m sizeX sizeY}+{~arrayMipMapListValid m sizeX sizeY}.
Proof.
  unfold arrayMipMapListValid.
  intros m sizeX sizeY.
  destruct (arrayMipMapIndicesSortedDecidable (map arrayMipMapIndex (arrayMipMaps m)));
  destruct (arrayMipMapListSameLayersDecidable (arrayMipMaps m));
  destruct (arrayMipMapListLevelZeroDecidable (arrayMipMaps m));
  destruct (arrayMipMapListFirstLayerZeroDecidable (arrayMipMaps m));
  destruct (arrayMipMapListMaxLevelBoundedDecidable (arrayMipMaps m) sizeX sizeY);
  destruct (arrayMipMapListIsNonEmptyDecidable (arrayMipMaps m));
  intuition.
Qed.

8.3. Calino/Binary.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Byte.

Require Import com.io7m.calino.Calino.
Require Import com.io7m.calino.MipMap.
Require Import com.io7m.calino.CubeMipMap.
Require Import com.io7m.calino.ArrayMipMap.
Require Import com.io7m.calino.JsonData.

Require Import com.io7m.rentomos.Tags.
Require Import com.io7m.rentomos.Binary.
Require Import com.io7m.rentomos.FileFormat.

Require Import com.io7m.rocson.Json.

Import ListNotations.

Open Scope string_scope.
Open Scope nat_scope.

(** @annospec 0f7f0dca-9ada-4a6a-b738-dc4e7dda98ba *)
Definition fileIdentifier : TagT :=
  Tag x89 x43 x4c x4e x0d x0a x1a x0a.

Definition fileVersionMajor :=
  2.

Definition fileVersionMinor :=
  0.

(** @annospec 4896529a-0b76-4f03-bb08-366d9d15d4ec *)
Definition sectionCalinoIdentifier : TagT :=
  Tag x43 x4c x4e x5f x43 x4c x4e x4f.

(** @annospec 163896f8-24bb-41e8-886c-748f6907253d *)
Definition sectionImage2DIdentifier : TagT :=
  Tag x43 x4c x4e x5f x4d x49 x32 x44.

(** @annospec 861eafe6-e731-43d0-9535-a34c657f7c07 *)
Definition sectionImageCubeIdentifier : TagT :=
  Tag x43 x4c x4e x5f x4d x43 x55 x42.

(** @annospec efe09811-46a7-421a-9948-0d0a7adc6884 *)
Definition sectionImageArrayIdentifier : TagT :=
  Tag x43 x4c x4e x5f x4d x41 x52 x52.

(** @annospec 5963b0e2-09db-4b88-96a0-f654161b18ed *)
Definition sectionEndIdentifier : TagT :=
  Tag x43 x4c x4e x5f x45 x4e x44 x21.

Definition tagNat (t : TagT) : nat :=
  Z.to_nat (tagToZ t).

Definition binaryExpFileHeader : binaryExp := BiRecord [
  ("id",           u64 (tagNat fileIdentifier));
  ("versionMajor", u32 fileVersionMajor);
  ("versionMinor", u32 fileVersionMinor)
].

(** The [CLN_CLNO] section holds the model as a JSON text. The JSON
    text is not byte-for-byte normative (see the note in [JsonData]):
    a conforming implementation may write any valid JSON text denoting
    [jsonCalino c], including standard JSON string escaping. This
    definition uses the conservative reference encoding
    [jsonSerializeString]. *)
Definition binaryExpCalinoSection (c : calinoT) : binaryExp :=
  let jsonE        := jsonCalino c in
  let jsonText     := jsonSerializeString jsonE in
  let jsonTextSize := 4 + (String.length jsonText) in
    BiRecord [
      ("id",   u64 (tagNat sectionCalinoIdentifier));
      ("size", u64 jsonTextSize);
      ("data", utf8 jsonText)
    ].

Definition binaryExpImageSection2D (c : mipMapT) : binaryExp :=
  let imageSize := mipMapSizeCompressed c in
  let dataSize  := 4 + 4 + 4 + 4 + imageSize in
    BiRecord [
      ("id",    u64 (tagNat sectionImage2DIdentifier));
      ("size",  u64 dataSize);
      ("level", u32 (mipMapLevel c));
      ("pad0",  u32 0xffffffff);
      ("pad1",  u32 0xffffffff);
      ("pad2",  u32 0xffffffff);
      ("data",  BiReserve imageSize)
    ].

Definition binaryExpImageSectionCube (c : cubeMipMapT) : binaryExp :=
  let imageSize := cubeFaceExtent (cubeMapFaceZNeg c) in
  let dataSize  := 4 + 4 + 4 + 4 + imageSize in
    BiRecord [
      ("id",    u64 (tagNat sectionImageCubeIdentifier));
      ("size",  u64 dataSize);
      ("level", u32 (cubeMipMapLevel c));
      ("pad0",  u32 0xffffffff);
      ("pad1",  u32 0xffffffff);
      ("pad2",  u32 0xffffffff);
      ("data",  BiReserve imageSize)
    ].

Definition binaryExpImageSectionArray (c : arrayMipMapT) : binaryExp :=
  let imageSize := arrayMipMapSizeCompressed c in
  let dataSize  := 4 + 4 + 4 + 4 + imageSize in
    BiRecord [
      ("id",    u64 (tagNat sectionImageArrayIdentifier));
      ("size",  u64 dataSize);
      ("level", u32 (arrayMipMapLevel (arrayMipMapIndex c)));
      ("layer", u32 (arrayMipMapLayer (arrayMipMapIndex c)));
      ("pad0",  u32 0xffffffff);
      ("pad1",  u32 0xffffffff);
      ("data",  BiReserve imageSize)
    ].

Definition binaryExpImageSections2D (c : mipMapListT) : list binaryExp :=
  map binaryExpImageSection2D (mipMaps c).

Definition binaryExpImageSectionsCube (c : cubeMipMapListT) : list binaryExp :=
  map binaryExpImageSectionCube (cubeMipMaps c).

Definition binaryExpImageSectionsArray (c : arrayMipMapListT) : list binaryExp :=
  map binaryExpImageSectionArray (arrayMipMaps c).

Definition binaryExpImageSections (c : calinoT) : list binaryExp :=
  match c with
  | C2D x    => binaryExpImageSections2D (c2dMipMaps x)
  | CCube x  => binaryExpImageSectionsCube (cCubeMipMaps x)
  | CArray x => binaryExpImageSectionsArray (cArrayMipMaps x)
  end.

Definition binaryEndSection : binaryExp := BiRecord [
  ("id",   u64 (tagNat sectionEndIdentifier));
  ("size", u64 0)
].

(** @annospec 17562a57-5189-4346-b271-d7ad4f0fdf6e *)
Definition binaryFile (c : calinoT) : list binaryExp :=
  (binaryExpCalinoSection c) :: (binaryExpImageSections c ++ [binaryEndSection]).

Definition sectionCalino :=
  FileSectionDescription sectionCalinoIdentifier FSO_MustBeFirst FSC_One.

Definition sectionImage2D :=
  FileSectionDescription sectionImage2DIdentifier FSO_AnyOrder FSC_ZeroToN.

Definition sectionImageCube :=
  FileSectionDescription sectionImageCubeIdentifier FSO_AnyOrder FSC_ZeroToN.

Definition sectionImageArray :=
  FileSectionDescription sectionImageArrayIdentifier FSO_AnyOrder FSC_ZeroToN.

(** @annospec d68d11d0-ca78-4fc5-b86d-5f292731e2fc *)
Definition fileDescription : FileDescriptionT :=
  FileDescription
  fileIdentifier
  fileVersionMajor
  fileVersionMinor
  [sectionCalino; sectionImage2D; sectionImageCube; sectionImageArray]
  sectionEndIdentifier
  UnknownSectionsPermitted
  .

Lemma fileSectionAtMostOneFirstExample : fileSectionAtMostOneFirst (fileSections fileDescription).
Proof.
  unfold fileSectionAtMostOneFirst.
  simpl; auto.
Qed.

Lemma fileSectionAtMostOneLastExample : fileSectionAtMostOneLast (fileSections fileDescription).
Proof.
  unfold fileSectionAtMostOneLast.
  simpl; auto.
Qed.

Lemma fileSectionTagsUniqueExample : fileSectionTagsUnique (fileSections fileDescription).
Proof.
  unfold fileSectionTagsUnique.
  simpl; auto.
  constructor.
  - unfold not; intro H; inversion H.
    contradict H0; discriminate.
    inversion H0.
    contradict H1; discriminate.
    inversion H1.
    contradict H2; discriminate.
    contradiction.
  - constructor.
    * unfold not; intro H; inversion H.
      contradict H0; discriminate.
      inversion H0.
      contradict H1; discriminate.
      inversion H1.
    * constructor.
      -- unfold not; intro H; inversion H.
         contradict H0; discriminate.
         contradiction.
      -- constructor.
         unfold not; intro H; inversion H.
         constructor.
Qed.

Lemma fileSectionFileNotSectionExample : fileSectionFileNotSection fileDescription.
Proof.
  unfold fileSectionFileNotSection.
  simpl.
  unfold not; intro H; destruct H.
  - contradict H; discriminate.
  - destruct H.
    * contradict H; discriminate.
    * destruct H.
      -- contradict H; discriminate.
      -- destruct H.
         ** contradict H; discriminate.
         ** auto.
Qed.

Lemma endSectionFileNotSectionExample : endSectionFileNotSection fileDescription.
Proof.
  unfold endSectionFileNotSection.
  simpl.
  unfold not; intro H; destruct H.
  - contradict H; discriminate.
  - destruct H.
    * contradict H; discriminate.
    * destruct H.
      -- contradict H; discriminate.
      -- destruct H.
         ** contradict H; discriminate.
         ** auto.
Qed.

Theorem fileDescriptionInvariantsExample : fileDescriptionInvariants fileDescription.
Proof.
  constructor.
  apply fileSectionAtMostOneFirstExample.
  constructor.
  apply fileSectionAtMostOneLastExample.
  constructor.
  apply fileSectionTagsUniqueExample.
  constructor.
  apply fileSectionFileNotSectionExample.
  apply endSectionFileNotSectionExample.
Qed.

8.4. Calino/ByteOrder.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.octetorder.OctetOrder.

Require Import com.io7m.rlanark.Lanark.

Definition byteOrderDescribe (b : octetOrder) : lanarkT :=
  match b with
  | OctetOrderBig    => calinoReservedDescriptor "big_endian"
  | OctetOrderLittle => calinoReservedDescriptor "little_endian"
  end.

Theorem byteOrderDescribeValid : forall (b : octetOrder),
  lanarkValidT (byteOrderDescribe b).
Proof.
  intros b.
  destruct b; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
Qed.

8.5. Calino/Calino.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Lists.List.

Require Import com.io7m.calino.ArrayMipMap.
Require Import com.io7m.calino.MipMap.
Require Import com.io7m.calino.CubeMipMap.
Require Import com.io7m.calino.ImageInfo.
Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.Metadata.
Require Import com.io7m.calino.NatFacts.

Inductive calino2DT : Set := Calino2D {
  c2dImageInfo : imageInfoT;
  c2dMipMaps   : mipMapListT;
  c2dMetadata  : metadataT
}.

Inductive calinoCubeT : Set := CalinoCube {
  cCubeImageInfo : imageInfoT;
  cCubeMipMaps   : cubeMipMapListT;
  cCubeMetadata  : metadataT
}.

Inductive calinoArrayT : Set := CalinoArray {
  cArrayImageInfo : imageInfoT;
  cArrayMipMaps   : arrayMipMapListT;
  cArrayMetadata  : metadataT
}.

(** @annospec 688236fd-f586-4edf-a3a4-78eaac2f9e7b *)
Inductive calinoT : Set :=
  | C2D    : calino2DT -> calinoT
  | CCube  : calinoCubeT -> calinoT
  | CArray : calinoArrayT -> calinoT.

(** @annospec 91e75571-ae83-4d54-b01a-318fbf6b16b4 *)
Definition calino2dValid (c : calino2DT) : Prop :=
  let info       := c2dImageInfo c in
  let imageSizeX := ImageSize.sizeX (imageSize info) in
  let imageSizeY := ImageSize.sizeY (imageSize info) in
  let imageSizeZ := ImageSize.sizeZ (imageSize info) in
     imageInfoValid info
  /\ metadataValid (c2dMetadata c)
  /\ mipMapListValid (c2dMipMaps c) imageSizeX imageSizeY
  /\ 1 = imageSizeZ.

(** @annospec 181b47bc-a6e0-4630-991a-199b97abfd23 *)
Definition calinoCubeValid (c : calinoCubeT) : Prop :=
  let info       := cCubeImageInfo c in
  let imageSizeX := ImageSize.sizeX (imageSize info) in
  let imageSizeY := ImageSize.sizeY (imageSize info) in
  let imageSizeZ := ImageSize.sizeZ (imageSize info) in
     imageInfoValid info
  /\ metadataValid (cCubeMetadata c)
  /\ cubeMipMapListValid (cCubeMipMaps c) imageSizeX imageSizeY
  /\ imageSizeX = imageSizeY
  /\ 1 = imageSizeZ.

Definition arrayMipMapListLayerCountIs (m : arrayMipMapListT) (n : nat) : Prop :=
  Forall (fun l => arrayMipMapLayerCountForLevel l (arrayMipMaps m) = n) (arrayMipMapLevels (arrayMipMaps m)).

Theorem arrayMipMapListLayerCountIsDecidable : forall (m : arrayMipMapListT) (n : nat),
  {arrayMipMapListLayerCountIs m n}+{~arrayMipMapListLayerCountIs m n}.
Proof.
  intros m n.
  unfold arrayMipMapListLayerCountIs.
  destruct (@Forall_dec nat
            (fun l => arrayMipMapLayerCountForLevel l (arrayMipMaps m) = n)
            (fun l => Nat.eq_dec (arrayMipMapLayerCountForLevel l (arrayMipMaps m)) n)
            (arrayMipMapLevels (arrayMipMaps m))).
   - left;  assumption.
   - right; assumption.
Qed.

(** @annospec 2fc03c82-a43b-412b-b1df-9de1d4c7649a *)
Definition calinoArrayValid (c : calinoArrayT) : Prop :=
  let info       := cArrayImageInfo c in
  let imageSizeX := ImageSize.sizeX (imageSize info) in
  let imageSizeY := ImageSize.sizeY (imageSize info) in
  let imageSizeZ := ImageSize.sizeZ (imageSize info) in
     imageInfoValid info
  /\ metadataValid (cArrayMetadata c)
  /\ arrayMipMapListValid (cArrayMipMaps c) imageSizeX imageSizeY
  /\ 1 <= imageSizeZ
  /\ arrayMipMapListLayerCountIs (cArrayMipMaps c) imageSizeZ.

Theorem calino2dValidDecidable : forall c,
  {calino2dValid c}+{~calino2dValid c}.
Proof.
  unfold calino2dValid.
  intros c.
  remember (sizeX (imageSize (c2dImageInfo c))) as sx;
  remember (sizeY (imageSize (c2dImageInfo c))) as sy;
  remember (sizeZ (imageSize (c2dImageInfo c))) as sz;
  destruct (imageInfoValidDecidable (c2dImageInfo c));
  destruct (metadataValidDecidable (c2dMetadata c));
  destruct (mipMapListValidDecidable (c2dMipMaps c) sx sy);
  destruct (Nat.eq_dec 1 sz);
  intuition.
Qed.

Theorem calinoCubeValidDecidable : forall c,
  {calinoCubeValid c}+{~calinoCubeValid c}.
Proof.
  unfold calinoCubeValid.
  intros c.
  remember (sizeX (imageSize (cCubeImageInfo c))) as sx;
  remember (sizeY (imageSize (cCubeImageInfo c))) as sy;
  remember (sizeZ (imageSize (cCubeImageInfo c))) as sz;
  destruct (imageInfoValidDecidable (cCubeImageInfo c));
  destruct (metadataValidDecidable (cCubeMetadata c));
  destruct (cubeMipMapListValidDecidable (cCubeMipMaps c) sx sy);
  destruct (Nat.eq_dec sx sy);
  destruct (Nat.eq_dec 1 sz);
  intuition.
Qed.

Theorem calinoArrayValidDecidable : forall c,
  {calinoArrayValid c}+{~calinoArrayValid c}.
Proof.
  unfold calinoArrayValid.
  intros c.
  remember (sizeX (imageSize (cArrayImageInfo c))) as sx;
  remember (sizeY (imageSize (cArrayImageInfo c))) as sy;
  remember (sizeZ (imageSize (cArrayImageInfo c))) as sz;
  destruct (imageInfoValidDecidable (cArrayImageInfo c));
  destruct (metadataValidDecidable (cArrayMetadata c));
  destruct (arrayMipMapListValidDecidable (cArrayMipMaps c) sx sy);
  destruct (le_dec 1 sz);
  destruct (arrayMipMapListLayerCountIsDecidable (cArrayMipMaps c) sz);
  intuition.
Qed.

(** @annospec 0e94fbae-3d48-43f3-af28-8201b10bad22 *)
Definition calinoValid (t : calinoT) : Prop :=
  match t with
  | C2D c    => calino2dValid c
  | CCube c  => calinoCubeValid c
  | CArray c => calinoArrayValid c
  end.

Theorem calinoValidDecidable : forall c,
  {calinoValid c}+{~calinoValid c}.
Proof.
  destruct c.
  - apply calino2dValidDecidable.
  - apply calinoCubeValidDecidable.
  - apply calinoArrayValidDecidable.
Qed.

8.6. Calino/ChannelDescription.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.ChannelSemantic.
Require Import com.io7m.calino.Descriptor.

Require Import com.io7m.rlanark.Lanark.

Import ListNotations.

Open Scope Z_scope.

Definition divisible8 (x : Z) : Prop :=
  Z.modulo x 8 = 0.

(** @annospec 6eef3210-6afb-49f6-abae-22bd1c849bca *)
Inductive channelDescriptionT : Set := ChannelDescription {
  cdSemantic : channelSemanticT;
  cdBits     : Z
}.

(** @annospec 87af76a2-deb2-493b-a98c-762c2b86173d *)
Inductive channelLayoutPackingT : Set :=
  | CLPack8
  | CLPack16
  | CLPack32
  | CLPack64.

Definition channelLayoutPackingDescribe (c : channelLayoutPackingT) : lanarkT :=
  match c with
  | CLPack8  => calinoReservedDescriptor "pack8"
  | CLPack16 => calinoReservedDescriptor "pack16"
  | CLPack32 => calinoReservedDescriptor "pack32"
  | CLPack64 => calinoReservedDescriptor "pack64"
  end.

Lemma pack8Secondary : isLanarkSecondarySegment "pack8".
Proof. repeat lanarkSegmentSolve. Qed.
Lemma pack16Secondary : isLanarkSecondarySegment "pack16".
Proof. repeat lanarkSegmentSolve. Qed.
Lemma pack32Secondary : isLanarkSecondarySegment "pack32".
Proof. repeat lanarkSegmentSolve. Qed.
Lemma pack64Secondary : isLanarkSecondarySegment "pack64".
Proof. repeat lanarkSegmentSolve. Qed.

Theorem channelLayoutPackingDescribeValid : forall c,
  lanarkValidT (channelLayoutPackingDescribe c).
Proof.
  destruct c.
  - apply (isCalinoReservedDescriptorValid _ pack8Secondary).
  - apply (isCalinoReservedDescriptorValid _ pack16Secondary).
  - apply (isCalinoReservedDescriptorValid _ pack32Secondary).
  - apply (isCalinoReservedDescriptorValid _ pack64Secondary).
Qed.

Definition channelLayoutPackingBits (c : channelLayoutPackingT) : Z :=
  match c with
  | CLPack8  => 8
  | CLPack16 => 16
  | CLPack32 => 32
  | CLPack64 => 64
  end.

Theorem channelLayoutPackingBitsDiv8 : forall c, divisible8 (channelLayoutPackingBits (c)).
Proof.
  intros c.
  destruct c; reflexivity.
Qed.

Definition channelDescriptionBitsDivisible8 (c : channelDescriptionT) : Prop :=
  divisible8 (cdBits c).

(** @annospec 60daf48d-9dc6-413f-973a-5514f204c976 *)
Definition channelDescriptionValid (c : channelDescriptionT) : Prop :=
     0 < (cdBits c) <= 64
  /\ channelSemanticValid (cdSemantic c).

Fixpoint channelDescriptionsBitsTotal (c : list channelDescriptionT) : Z :=
  match c with
  | nil         => 0
  | (x :: rest) => (cdBits x) + (channelDescriptionsBitsTotal rest)
  end.

Lemma channelDescriptionsBitsNonEmptyNonZero : forall (cs : list channelDescriptionT),
  nil <> cs
  -> Forall (fun c => 0 < cdBits c) cs
  -> 0 < channelDescriptionsBitsTotal cs.
Proof.
  intros cs HnotNil Hfa.
  induction cs as [|y ys IHys]. {
    contradiction.
  } {
    pose proof (Forall_inv Hfa) as HbitsLt.
    simpl in *.
    destruct ys as [|q qs].
    - simpl. lia.
    - pose proof (Forall_inv_tail Hfa) as H0.
      assert ([] <> q :: qs) as H1 by discriminate.
      pose proof (IHys H1 H0) as H2.
      simpl in *.
      lia.
  }
Qed.

Inductive channelLayoutDescriptionUnpackedT : Set := ChannelLayoutDescriptionUnpacked {
  uChannels : list channelDescriptionT;
}.

Definition channelLayoutDescriptionUnpackedValidT (c : channelLayoutDescriptionUnpackedT) : Prop :=
     [] <> uChannels c
  /\ Forall channelDescriptionValid (uChannels c)
  /\ Forall channelDescriptionBitsDivisible8 (uChannels c).

Inductive channelLayoutDescriptionPackedT : Set := ChannelLayoutDescriptionPacked {
  pChannels : list channelDescriptionT;
  pPacking  : channelLayoutPackingT;
}.

Definition channelLayoutDescriptionPackedValidT (c : channelLayoutDescriptionPackedT) : Prop :=
     [] <> pChannels c
  /\ Forall channelDescriptionValid (pChannels c)
  /\ channelDescriptionsBitsTotal (pChannels c) = channelLayoutPackingBits (pPacking c).

(** @annospec dbb9f758-635b-4ad5-8b50-10a04bc68d79 *)
Inductive channelLayoutDescriptionT : Set :=
  | CLDUnpacked : channelLayoutDescriptionUnpackedT -> channelLayoutDescriptionT
  | CLDPacked   : channelLayoutDescriptionPackedT   -> channelLayoutDescriptionT.

Definition channelLayoutDescriptionValidT (c : channelLayoutDescriptionT) : Prop :=
  match c with
  | CLDUnpacked u => channelLayoutDescriptionUnpackedValidT u
  | CLDPacked   p => channelLayoutDescriptionPackedValidT p
  end.

Definition channelLayoutDescriptionBits (c : channelLayoutDescriptionT) : Z :=
  match c with
  | CLDUnpacked u => channelDescriptionsBitsTotal (uChannels u)
  | CLDPacked p   => channelDescriptionsBitsTotal (pChannels p)
  end.


Theorem channelDescriptionValidDecidable : forall c,
  {channelDescriptionValid c}+{~channelDescriptionValid c}.
Proof.
  unfold channelDescriptionValid.
  intros c.
  destruct (Z_lt_dec 0 (cdBits c));
  destruct (Z_le_dec (cdBits c) 64);
  destruct (channelSemanticValidDecidable (cdSemantic c));
  intuition.
Qed.

Theorem channelDescriptionBitsDivisible8Decidable : forall c,
  {channelDescriptionBitsDivisible8 c}+{~channelDescriptionBitsDivisible8 c}.
Proof.
  unfold channelDescriptionBitsDivisible8.
  intros c.
  apply Z.eq_dec.
Qed.

Theorem channelLayoutDescriptionUnpackedValidDecidable : forall c,
  {channelLayoutDescriptionUnpackedValidT c}+{~channelLayoutDescriptionUnpackedValidT c}.
Proof.
  unfold channelLayoutDescriptionUnpackedValidT.
  intros c.
  destruct (uChannels c).
  * right; intuition.
  * destruct (@Forall_dec _ _ channelDescriptionValidDecidable (c0 :: l)).
    ** destruct (@Forall_dec _ _ channelDescriptionBitsDivisible8Decidable (c0 :: l)).
       *** left; constructor.
           discriminate.
           constructor; auto.
       *** right; intuition.
    ** right; intuition.
Qed.

Theorem channelLayoutDescriptionPackedValidDecidable : forall c,
  {channelLayoutDescriptionPackedValidT c}+{~channelLayoutDescriptionPackedValidT c}.
Proof.
  unfold channelLayoutDescriptionPackedValidT.
  intros c.
  destruct (pChannels c).
  * right; intuition.
  * destruct (@Forall_dec _ _ channelDescriptionValidDecidable (c0 :: l)).
    ** destruct (Z.eq_dec (channelDescriptionsBitsTotal (c0 :: l)) (channelLayoutPackingBits (pPacking c))).
       *** left; constructor.
           discriminate.
           auto.
       *** right; intuition.
    ** right; intuition.
Qed.

Theorem channelLayoutDescriptionValidDecidable : forall c,
  {channelLayoutDescriptionValidT c}+{~channelLayoutDescriptionValidT c}.
Proof.
  unfold channelLayoutDescriptionValidT.
  destruct c.
  * apply channelLayoutDescriptionUnpackedValidDecidable.
  * apply channelLayoutDescriptionPackedValidDecidable.
Qed.

8.7. Calino/ChannelSemantic.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

(** @annospec 0c1471cb-6336-4c1c-b924-952f2ae87d6b *)
Inductive channelSemanticT : Set :=
  | CSRed
  | CSGreen
  | CSBlue
  | CSAlpha
  | CSDepth
  | CSStencil
  | CSExponent
  | CSUnused
  | CSCustom : lanarkT -> channelSemanticT.

Definition channelSemanticDescribe (c : channelSemanticT) : lanarkT :=
  match c with
  | CSRed      => calinoReservedDescriptor "red"
  | CSGreen    => calinoReservedDescriptor "green"
  | CSBlue     => calinoReservedDescriptor "blue"
  | CSAlpha    => calinoReservedDescriptor "alpha"
  | CSDepth    => calinoReservedDescriptor "depth"
  | CSStencil  => calinoReservedDescriptor "stencil"
  | CSExponent => calinoReservedDescriptor "exponent"
  | CSUnused   => calinoReservedDescriptor "unused"
  | CSCustom s => s
  end.

(** @annospec 93061b71-fb69-4080-8579-c2f2f686d7a8 *)
Definition channelSemanticValid (c : channelSemanticT) : Prop :=
  match c with
  | CSRed      => True
  | CSGreen    => True
  | CSBlue     => True
  | CSAlpha    => True
  | CSDepth    => True
  | CSStencil  => True
  | CSExponent => True
  | CSUnused   => True
  | CSCustom s => (~isCalinoReservedDescriptor s) /\ lanarkValidT s
  end.

Theorem channelSemanticDescribeValid : forall (c : channelSemanticT),
  channelSemanticValid c ->
  match c with
  | CSCustom s => lanarkValidT s
  | _          => lanarkValidT (channelSemanticDescribe c)
  end.
Proof.
  intros c Hc.
  destruct c.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - apply isCalinoReservedDescriptorValid.
    constructor.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
    repeat lanarkSegmentSolve.
  - destruct Hc; auto.
Qed.

Theorem channelSemanticValidDecidable : forall c,
  {channelSemanticValid c}+{~channelSemanticValid c}.
Proof.
  unfold channelSemanticValid.
  destruct c;
    try (left; auto || fail).

  destruct (lanarkValidDecidable l);
    destruct (isCalinoReservedDescriptorDecidable l);
      intuition.
Qed.

8.8. Calino/ChannelType.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

(** @annospec 5740b7f3-5547-4d27-abcb-8187151b7e3c *)
Inductive channelTypeT : Set :=
  | CTFixedPointNormalizedUnsigned
  | CTFixedPointNormalizedSigned
  | CTScaledUnsigned
  | CTScaledSigned
  | CTIntegerUnsigned
  | CTIntegerSigned
  | CTFloatIEEE754
  | CTCustom : lanarkT -> channelTypeT.

Definition channelTypeDescribe (c : channelTypeT) : lanarkT :=
  match c with
  | CTFixedPointNormalizedUnsigned => calinoReservedDescriptor "fixed_point_normalized_unsigned"
  | CTFixedPointNormalizedSigned   => calinoReservedDescriptor "fixed_point_normalized_signed"
  | CTScaledUnsigned               => calinoReservedDescriptor "scaled_unsigned"
  | CTScaledSigned                 => calinoReservedDescriptor "scaled_signed"
  | CTIntegerUnsigned              => calinoReservedDescriptor "integer_unsigned"
  | CTIntegerSigned                => calinoReservedDescriptor "integer_signed"
  | CTFloatIEEE754                 => calinoReservedDescriptor "float_ieee754"
  | CTCustom d                     => d
  end.

(** @annospec 28d4191b-d280-42eb-aeb4-5496a26ddecd *)
Definition channelTypeValid (c : channelTypeT) : Prop :=
  match c with
  | CTFixedPointNormalizedUnsigned => True
  | CTFixedPointNormalizedSigned   => True
  | CTScaledUnsigned               => True
  | CTScaledSigned                 => True
  | CTIntegerUnsigned              => True
  | CTIntegerSigned                => True
  | CTFloatIEEE754                 => True
  | CTCustom d                     => (~isCalinoReservedDescriptor d) /\ lanarkValidT d
  end.

Theorem channelTypeDescribeValid : forall (c : channelTypeT),
  channelTypeValid c ->
  match c with
  | CTCustom s => lanarkValidT s
  | _          => lanarkValidT (channelTypeDescribe c)
  end.
Proof.
  intros c Hc.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
  destruct Hc; auto.
Qed.

Theorem channelTypeValidDecidable : forall c,
  {channelTypeValid c}+{~channelTypeValid c}.
Proof.
  unfold channelTypeValid.
  destruct c;
    try (left; auto || fail).

  destruct (lanarkValidDecidable l);
    destruct (isCalinoReservedDescriptorDecidable l);
      intuition.
Qed.

8.9. Calino/ColorSpace.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

(** @annospec 9e5bcc04-24c8-49ec-ba80-1593f20506cd *)
Inductive colorSpaceT : Set :=
  | CSLinear
  | CSsRGB
  | CSCustom : lanarkT -> colorSpaceT.

Definition colorSpaceDescribe (c : colorSpaceT) : lanarkT :=
  match c with
  | CSLinear   => calinoReservedDescriptor "linear"
  | CSsRGB     => calinoReservedDescriptor "srgb"
  | CSCustom d => d
  end.

(** @annospec 8fe3249e-ffca-443e-ac54-77c1c4b2a603 *)
Definition colorSpaceValid (c : colorSpaceT) : Prop :=
  match c with
  | CSLinear   => True
  | CSsRGB     => True
  | CSCustom t => (~isCalinoReservedDescriptor t) /\ lanarkValidT t
  end.

Theorem colorSpaceDescribeValid : forall (c : colorSpaceT),
  colorSpaceValid c ->
  match c with
  | CSCustom t => lanarkValidT t
  | _          => lanarkValidT (colorSpaceDescribe c)
  end.
Proof.
  intros c Hc.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
  destruct Hc; auto.
Qed.

Theorem colorSpaceValidDecidable : forall c,
  {colorSpaceValid c}+{~colorSpaceValid c}.
Proof.
  unfold colorSpaceValid.
  destruct c;
    try (left; auto || fail).

  destruct (lanarkValidDecidable l);
    destruct (isCalinoReservedDescriptorDecidable l);
      intuition.
Qed.

8.10. Calino/Compression.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

Set Warnings "-abstract-large-number".

Inductive compressionUncompressedT : Set :=
  CompressionUncompressed.

Inductive compressionBC1T : Set :=
  CompressionBC1.

Inductive compressionBC2T : Set :=
  CompressionBC2.

Inductive compressionBC3T : Set :=
  CompressionBC3.

Inductive compressionBC4T : Set :=
  CompressionBC4.

Inductive compressionBC5T : Set :=
  CompressionBC5.

Inductive compressionBC6T : Set :=
  CompressionBC6.

Inductive compressionBC7T : Set :=
  CompressionBC7.

Inductive compressionETC1T : Set :=
  CompressionETC1.

Inductive compressionETC2T : Set :=
  CompressionETC2.

Inductive compressionEACT : Set :=
  CompressionEAC.

Inductive compressionASTCT : Set :=
  CompressionASTC {
    astcBlockSizeX : Z;
    astcBlockSizeY : Z
  }.

Inductive compressionCustomT : Set :=
  CompressionCustom {
    customId                : lanarkT;
    customBlockSizeX        : Z;
    customBlockSizeY        : Z;
    customSectionIdentifier : Z;
    customAlign             : Z
  }.

(** @annospec ce94241f-f6e7-431f-aabc-fd534b5ce004 *)
Inductive compressionMethodT : Set :=
  | CUncompressed : compressionUncompressedT -> compressionMethodT
  | CBC1          : compressionBC1T -> compressionMethodT
  | CBC2          : compressionBC2T -> compressionMethodT
  | CBC3          : compressionBC3T -> compressionMethodT
  | CBC4          : compressionBC4T -> compressionMethodT
  | CBC5          : compressionBC5T -> compressionMethodT
  | CBC6          : compressionBC6T -> compressionMethodT
  | CBC7          : compressionBC7T -> compressionMethodT
  | CETC1         : compressionETC1T -> compressionMethodT
  | CETC2         : compressionETC2T -> compressionMethodT
  | CEAC          : compressionEACT -> compressionMethodT
  | CASTC         : compressionASTCT -> compressionMethodT
  | CCustom       : compressionCustomT -> compressionMethodT.

Definition compressionMethodDescribe (c : compressionMethodT) : lanarkT :=
  match c with
  | CUncompressed _ => calinoReservedDescriptor "uncompressed"
  | CBC1 _          => calinoReservedDescriptor "bc1"
  | CBC2 _          => calinoReservedDescriptor "bc2"
  | CBC3 _          => calinoReservedDescriptor "bc3"
  | CBC4 _          => calinoReservedDescriptor "bc4"
  | CBC5 _          => calinoReservedDescriptor "bc5"
  | CBC6 _          => calinoReservedDescriptor "bc6"
  | CBC7 _          => calinoReservedDescriptor "bc7"
  | CETC1 _         => calinoReservedDescriptor "etc1"
  | CETC2 _         => calinoReservedDescriptor "etc2"
  | CEAC _          => calinoReservedDescriptor "eac"
  | CASTC _         => calinoReservedDescriptor "astc"
  | CCustom t       => (customId t)
  end.

(** @annospec 4606b59f-a8cb-4207-83a8-8fb0fa21cc1b *)
Definition compressionMethodASTCValid (c : compressionASTCT) : Prop :=
     (3 <= Z.to_nat (astcBlockSizeX c) <= 12)
  /\ (3 <= Z.to_nat (astcBlockSizeY c) <= 12).

(** @annospec 73854fab-7a25-4aa2-a973-1639dd842e06 *)
Definition compressionMethodCustomValid (c : compressionCustomT) : Prop :=
     (0 <= Z.to_nat (customSectionIdentifier c) <= 0xffffffffffffffff)
  /\ (1 <= Z.to_nat (customBlockSizeX c) <= 0xffffffff)
  /\ (1 <= Z.to_nat (customBlockSizeY c) <= 0xffffffff)
  /\ (1 <= Z.to_nat (customAlign c) <= 0xffffffff)
  /\ (~isCalinoReservedDescriptor (customId c))
  /\ lanarkValidT (customId c).

(** @annospec bd2607b4-9b19-4958-99be-7f9be3dfb01c *)
Definition compressionMethodValid (c : compressionMethodT) : Prop :=
  match c with
  | CUncompressed _ => True
  | CBC1 _          => True
  | CBC2 _          => True
  | CBC3 _          => True
  | CBC4 _          => True
  | CBC5 _          => True
  | CBC6 _          => True
  | CBC7 _          => True
  | CETC1 _         => True
  | CETC2 _         => True
  | CEAC _          => True
  | CASTC t         => compressionMethodASTCValid t
  | CCustom t       => compressionMethodCustomValid t
  end.

Definition compressionBlockSizeX (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 4
  | CBC2 _          => 4
  | CBC3 _          => 4
  | CBC4 _          => 4
  | CBC5 _          => 4
  | CBC6 _          => 4
  | CBC7 _          => 4
  | CETC1 _         => 4
  | CETC2 _         => 4
  | CEAC _          => 4
  | CASTC t         => astcBlockSizeX t
  | CCustom t       => customBlockSizeX t
  end.

Definition compressionBlockSizeY (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 4
  | CBC2 _          => 4
  | CBC3 _          => 4
  | CBC4 _          => 4
  | CBC5 _          => 4
  | CBC6 _          => 4
  | CBC7 _          => 4
  | CETC1 _         => 4
  | CETC2 _         => 4
  | CEAC _          => 4
  | CASTC t         => astcBlockSizeY t
  | CCustom t       => customBlockSizeY t
  end.

Definition compressionSectionIdentifier (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 0
  | CBC2 _          => 0
  | CBC3 _          => 0
  | CBC4 _          => 0
  | CBC5 _          => 0
  | CBC6 _          => 0
  | CBC7 _          => 0
  | CETC1 _         => 0
  | CETC2 _         => 0
  | CEAC _          => 0
  | CASTC _         => 0
  | CCustom t       => customSectionIdentifier t
  end.

Definition compressionBlockAlignment (c : compressionMethodT) : Z :=
  match c with
  | CUncompressed _ => 0
  | CBC1 _          => 8
  | CBC2 _          => 16
  | CBC3 _          => 16
  | CBC4 _          => 8
  | CBC5 _          => 16
  | CBC6 _          => 16
  | CBC7 _          => 16
  | CETC1 _         => 16
  | CETC2 _         => 16
  | CEAC _          => 16
  | CASTC _         => 16
  | CCustom t       => customAlign t
  end.


Theorem compressionMethodASTCValidDecidable : forall c,
  {compressionMethodASTCValid c}+{~compressionMethodASTCValid c}.
Proof.
  unfold compressionMethodASTCValid.
  intros c.
  destruct (le_dec 3 (Z.to_nat (astcBlockSizeX c)));
  destruct (le_dec (Z.to_nat (astcBlockSizeX c)) 12);
  destruct (le_dec 3 (Z.to_nat (astcBlockSizeY c)));
  destruct (le_dec (Z.to_nat (astcBlockSizeY c)) 12);
  intuition.
Qed.

Theorem le_dec_2 : forall x y z,
  {x <= y <= z}+{~(x <= y <= z)}.
Proof.
  intros x y z.
  destruct (le_dec x y);
  destruct (le_dec y z);
  intuition.
Qed.

Theorem compressionMethodCustomValidDecidable : forall c,
  {compressionMethodCustomValid c}+{~compressionMethodCustomValid c}.
Proof.
  intros c.
  destruct (le_dec_2 0 (Z.to_nat (customSectionIdentifier c)) 0xffffffffffffffff) as [H0L|H0R];
  destruct (le_dec_2 1 (Z.to_nat (customBlockSizeX c)) 0xffffffff) as [H1L|H1R];
  destruct (le_dec_2 1 (Z.to_nat (customBlockSizeY c)) 0xffffffff) as [H2L|H2R];
  destruct (le_dec_2 1 (Z.to_nat (customAlign c)) 0xffffffff) as [H3L|H3R];
  destruct (lanarkValidDecidable (customId c)) as [H4L|H4R];
  destruct (isCalinoReservedDescriptorDecidable (customId c)) as [H5L|H5R].
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf4.
    auto.
  - left.
    split; [exact H0L | split; [exact H1L | split; [exact H2L | split; [exact H3L | split; [exact H5R | exact H4L]]]]].
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf5.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf5.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf3.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf3.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf3.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf3.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf2.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf1.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
  - right.
    unfold not; intro Hfalse; inversion Hfalse as [Hf0 [Hf1 [Hf2 [Hf3 [Hf4 Hf5]]]]].
    contradict Hf0.
    auto.
Qed.


Theorem compressionMethodDescribeValid : forall (c : compressionMethodT),
  compressionMethodValid c ->
  match c with
  | CCustom t => lanarkValidT (customId t)
  | _         => lanarkValidT (compressionMethodDescribe c)
  end.
Proof.
  intros c Hc.
  unfold compressionMethodValid in Hc.
  destruct c;
    try (apply isCalinoReservedDescriptorValid; repeat lanarkSegmentSolve).
  - destruct Hc as [H0 [H1 [H2 [H3 [H4 H5]]]]].
    exact H5.
Qed.


Theorem compressionMethodValidDecidable : forall c,
  {compressionMethodValid c}+{~compressionMethodValid c}.
Proof.
  unfold compressionMethodValid.
  intros c.
  destruct c;
    try (left; auto || fail).
  - exact (compressionMethodASTCValidDecidable _).
  - exact (compressionMethodCustomValidDecidable _).
Qed.

8.11. Calino/CoordinateSystem.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

(** @annospec 3f35940c-0e92-4193-9838-fb14e8324f55 *)
Inductive coordinateAxisR : Set :=
  | AxisRIncreasingToward
  | AxisRIncreasingAway.

(** @annospec 4fc27183-e498-4fd1-a58a-029040e8384a *)
Inductive coordinateAxisS : Set :=
  | AxisSIncreasingRight
  | AxisSIncreasingLeft.

(** @annospec fe811351-5c2e-4a0c-9044-f1fcc42fbce6 *)
Inductive coordinateAxisT : Set :=
  | AxisTIncreasingDown
  | AxisTIncreasingUp.

Definition coordinateAxisRDescribe (c : coordinateAxisR) : lanarkT :=
  match c with
  | AxisRIncreasingToward => calinoReservedDescriptor "r_increasing_toward"
  | AxisRIncreasingAway   => calinoReservedDescriptor "r_increasing_away"
  end.

Definition coordinateAxisSDescribe (c : coordinateAxisS) : lanarkT :=
  match c with
  | AxisSIncreasingRight => calinoReservedDescriptor "s_increasing_right"
  | AxisSIncreasingLeft  => calinoReservedDescriptor "s_increasing_left"
  end.

Definition coordinateAxisTDescribe (c : coordinateAxisT) : lanarkT :=
  match c with
  | AxisTIncreasingDown => calinoReservedDescriptor "t_increasing_down"
  | AxisTIncreasingUp   => calinoReservedDescriptor "t_increasing_up"
  end.

(** @annospec 54cf99fe-209c-41ee-b40e-a6f01f7ffd0e *)
Inductive coordinateSystemT : Set :=
  CoordinateSystem : coordinateAxisR -> coordinateAxisS -> coordinateAxisT -> coordinateSystemT.

Theorem coordinateAxisRDescribeValid : forall (c : coordinateAxisR),
  lanarkValidT (coordinateAxisRDescribe c).
Proof.
  intros c.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
Qed.

Theorem coordinateAxisSDescribeValid : forall (c : coordinateAxisS),
  lanarkValidT (coordinateAxisSDescribe c).
Proof.
  intros c.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
Qed.

Theorem coordinateAxisTDescribeValid : forall (c : coordinateAxisT),
  lanarkValidT (coordinateAxisTDescribe c).
Proof.
  intros c.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
Qed.

8.12. Calino/CubeMipMap.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Bool.Bool.

Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.NatFacts.

Import ListNotations.

(** @annospec cf648138-c02a-4b55-b5a7-78ce8e6fee9e *)
Inductive cubeMapFaceT : Set := CubeMapFace {
  cubeFaceOffset           : nat;
  cubeFaceSizeCompressed   : nat;
  cubeFaceSizeUncompressed : nat;
  cubeFaceCRC32            : nat
}.

Inductive cubeMipMapT : Set := CubeMipMap {
  cubeMipMapLevel  : nat;
  cubeMapFaceXPos  : cubeMapFaceT;
  cubeMapFaceXNeg  : cubeMapFaceT;
  cubeMapFaceYPos  : cubeMapFaceT;
  cubeMapFaceYNeg  : cubeMapFaceT;
  cubeMapFaceZPos  : cubeMapFaceT;
  cubeMapFaceZNeg  : cubeMapFaceT
}.

Definition cubeFaceExtent (f : cubeMapFaceT) : nat :=
  cubeFaceOffset f + cubeFaceSizeCompressed f.

Definition cubeFaceOffsetsCorrect (c : cubeMipMapT) : Prop :=
     (cubeFaceExtent (cubeMapFaceXPos c) <= cubeFaceOffset (cubeMapFaceXNeg c))
  /\ (cubeFaceExtent (cubeMapFaceXNeg c) <= cubeFaceOffset (cubeMapFaceYPos c))
  /\ (cubeFaceExtent (cubeMapFaceYPos c) <= cubeFaceOffset (cubeMapFaceYNeg c))
  /\ (cubeFaceExtent (cubeMapFaceYNeg c) <= cubeFaceOffset (cubeMapFaceZPos c))
  /\ (cubeFaceExtent (cubeMapFaceZPos c) <= cubeFaceOffset (cubeMapFaceZNeg c)).

(** @annospec 65d49f1c-a520-4173-9099-b9d2d3d204b5 *)
Inductive cubeMipMapListIsSorted : list cubeMipMapT -> Prop :=
  | CubeOne   : forall m, cubeMipMapListIsSorted [m]
  | CubeCons  : forall mm0 mm1 mxs,
    cubeMipMapLevel mm1 = S (cubeMipMapLevel mm0) ->
      cubeMipMapListIsSorted (mm0 :: mxs) ->
        cubeMipMapListIsSorted (mm1 :: mm0 :: mxs).

(** @annospec 5fe31eb7-4e30-4edc-997c-19e2cdac6da6 *)
Inductive cubeMipMapListT : Set := CubeList {
  cubeMipMaps : list cubeMipMapT;
}.

(** @annospec 0fa0f9a2-ce58-4bd7-bb89-e8f0bc9306dc *)
Definition cubeMipMapFaceOffsetsCorrect (m : list cubeMipMapT) : Prop :=
  Forall cubeFaceOffsetsCorrect m.

(** @annospec 8364eb11-e9ec-4fb5-b266-fa0c2a09c868 *)
Definition cubeMipMapListIsNonEmpty (m : list cubeMipMapT) : Prop :=
  nil <> m.

(** @annospec 538f67c1-e106-440c-aa41-2917d3bb70d9 *)
Fixpoint cubeMipMapListLevelZero (m : list cubeMipMapT) : Prop :=
  match m with
  | nil      => False
  | x :: nil => cubeMipMapLevel x = 0
  | _ :: xs  => cubeMipMapListLevelZero xs
  end.

(** @annospec 68e08c64-7185-4e95-9b12-fa90cacdab62 *)
Definition cubeMipMapListMaxLevelBounded
  (m           : list cubeMipMapT)
  (sizeX sizeY : nat)
: Prop :=
  match m with
  | nil    => True
  | x :: _ => (2 ^ cubeMipMapLevel x) <= sizeX /\ (2 ^ cubeMipMapLevel x) <= sizeY
  end.

(** @annospec 0e3d6528-142b-417e-83ad-8210903b0ede *)
Definition cubeMipMapListValid (c : cubeMipMapListT) (sizeX sizeY : nat) : Prop :=
     cubeMipMapListIsSorted (cubeMipMaps c)
  /\ cubeMipMapListIsNonEmpty (cubeMipMaps c)
  /\ cubeMipMapListLevelZero (cubeMipMaps c)
  /\ cubeMipMapListMaxLevelBounded (cubeMipMaps c) sizeX sizeY
  /\ cubeMipMapFaceOffsetsCorrect (cubeMipMaps c).

Theorem cubeMipMapListIsSortedDecidable : forall m,
  {cubeMipMapListIsSorted m}+{~cubeMipMapListIsSorted m}.
Proof.
  induction m as [|q qs IHqs].
  - right; unfold not; intro H; inversion H.
  - destruct IHqs as [HL|HR].
    * destruct qs.
      -- left; constructor.
      -- destruct (Nat.eq_dec (cubeMipMapLevel q) (S (cubeMipMapLevel c))) as [H0L|H0R].
         ** left; constructor; auto.
         ** right; unfold not; intro H; inversion H.
            contradiction.
    * destruct qs.
      -- left; constructor.
      -- right.
         intro Hc.
         inversion Hc.
         contradiction.
Qed.

Theorem cubeMipMapListIsNonEmptyDecidable : forall m,
  {cubeMipMapListIsNonEmpty m}+{~cubeMipMapListIsNonEmpty m}.
Proof.
  destruct m.
  - right; auto.
  - left; discriminate.
Qed.

Theorem cubeMipMapListLevelZeroDecidable : forall m,
  {cubeMipMapListLevelZero m}+{~cubeMipMapListLevelZero m}.
Proof.
  induction m as [|q qs IHqs].
  - right; auto.
  - destruct qs as [|r rs].
    * destruct (Nat.eq_dec (cubeMipMapLevel q) 0) as [HL|HR].
      -- left; exact HL.
      -- right; intuition.
    * destruct IHqs as [HL|HR].
      -- left; exact HL.
      -- right; intuition.
Qed.

Theorem cubeMipMapListMaxLevelBoundedDecidable : forall m sizeX sizeY,
  {cubeMipMapListMaxLevelBounded m sizeX sizeY}+{~cubeMipMapListMaxLevelBounded m sizeX sizeY}.
Proof.
  destruct m as [|q qs].
  - intros sizeX sizeY.
    left; constructor.
  - intros sizeX sizeY.
    simpl.
    destruct (le_dec (2 ^ cubeMipMapLevel q) sizeX).
    destruct (le_dec (2 ^ cubeMipMapLevel q) sizeY).
    * left; intuition.
    * right; intuition.
    * right; intuition.
Qed.

Theorem cubeFaceOffsetsCorrectDecidable : forall c,
  {cubeFaceOffsetsCorrect c}+{~cubeFaceOffsetsCorrect c}.
Proof.
  intros c.
  unfold cubeFaceOffsetsCorrect.
  destruct (le_dec (cubeFaceExtent (cubeMapFaceXPos c)) (cubeFaceOffset (cubeMapFaceXNeg c)));
  destruct (le_dec (cubeFaceExtent (cubeMapFaceXNeg c)) (cubeFaceOffset (cubeMapFaceYPos c)));
  destruct (le_dec (cubeFaceExtent (cubeMapFaceYPos c)) (cubeFaceOffset (cubeMapFaceYNeg c)));
  destruct (le_dec (cubeFaceExtent (cubeMapFaceYNeg c)) (cubeFaceOffset (cubeMapFaceZPos c)));
  destruct (le_dec (cubeFaceExtent (cubeMapFaceZPos c)) (cubeFaceOffset (cubeMapFaceZNeg c)));
  intuition.
Qed.

Theorem cubeMipMapFaceOffsetsCorrectDecidable : forall m,
  {cubeMipMapFaceOffsetsCorrect m}+{~cubeMipMapFaceOffsetsCorrect m}.
Proof.
  induction m as [|q qs].
  - left; constructor.
  - destruct (cubeFaceOffsetsCorrectDecidable q) as [HL|HR].
    * destruct IHqs.
      -- left; constructor; auto.
      -- right.
         intro H.
         apply Forall_inv_tail in H.
         contradiction.
    * right.
      intro H.
      apply Forall_inv in H.
      contradiction.
Qed.

Theorem cubeMipMapListValidDecidable : forall c sizeX sizeY,
  {cubeMipMapListValid c sizeX sizeY}+{~cubeMipMapListValid c sizeX sizeY}.
Proof.
  intros c sizeX sizeY.
  unfold cubeMipMapListValid.
  destruct (cubeMipMapListIsSortedDecidable (cubeMipMaps c));
  destruct (cubeMipMapListIsNonEmptyDecidable (cubeMipMaps c));
  destruct (cubeMipMapListLevelZeroDecidable (cubeMipMaps c));
  destruct (cubeMipMapListMaxLevelBoundedDecidable (cubeMipMaps c) sizeX sizeY);
  destruct (cubeMipMapFaceOffsetsCorrectDecidable (cubeMipMaps c));
  intuition.
Qed.

8.13. Calino/CubeMipMapExample.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Bool.Bool.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.NatFacts.
Require Import com.io7m.calino.CubeMipMap.

Import ListNotations.

Example cubeFaceXP0 := CubeMapFace 0 8 8 0.
Example cubeFaceXN0 := CubeMapFace 16 8 8 0.
Example cubeFaceYP0 := CubeMapFace 32 8 8 0.
Example cubeFaceYN0 := CubeMapFace 48 8 8 0.
Example cubeFaceZP0 := CubeMapFace 64 8 8 0.
Example cubeFaceZN0 := CubeMapFace 80 8 8 0.

Example cubeMipMap0 := CubeMipMap 2 cubeFaceXP0 cubeFaceXN0 cubeFaceYP0 cubeFaceYN0 cubeFaceZP0 cubeFaceZN0.

Example cubeFaceXP1 := CubeMapFace 96 8 8 0.
Example cubeFaceXN1 := CubeMapFace 112 8 8 0.
Example cubeFaceYP1 := CubeMapFace 128 8 8 0.
Example cubeFaceYN1 := CubeMapFace 144 8 8 0.
Example cubeFaceZP1 := CubeMapFace 160 8 8 0.
Example cubeFaceZN1 := CubeMapFace 176 8 8 0.

Example cubeMipMap1 := CubeMipMap 1 cubeFaceXP1 cubeFaceXN1 cubeFaceYP1 cubeFaceYN1 cubeFaceZP1 cubeFaceZN1.

Example cubeFaceXP2 := CubeMapFace 192 8 8 0.
Example cubeFaceXN2 := CubeMapFace 208 8 8 0.
Example cubeFaceYP2 := CubeMapFace 224 8 8 0.
Example cubeFaceYN2 := CubeMapFace 240 8 8 0.
Example cubeFaceZP2 := CubeMapFace 256 8 8 0.
Example cubeFaceZN2 := CubeMapFace 272 8 8 0.

Example cubeMipMap2 := CubeMipMap 0 cubeFaceXP2 cubeFaceXN2 cubeFaceYP2 cubeFaceYN2 cubeFaceZP2 cubeFaceZN2.

Example exampleCubeMipMaps :=
  CubeList [cubeMipMap0; cubeMipMap1; cubeMipMap2].

Theorem exampleCubeMipMapListIsSorted : cubeMipMapListIsSorted (cubeMipMaps exampleCubeMipMaps).
Proof.
  apply CubeCons. { compute; reflexivity. }
  apply CubeCons. { compute; reflexivity. }
  apply CubeOne.
Qed.

Theorem exampleCubeMipMapListIsNonEmpty : cubeMipMapListIsNonEmpty (cubeMipMaps exampleCubeMipMaps).
Proof. discriminate. Qed.

Theorem exampleCubeMipMapListLevelZero : cubeMipMapListLevelZero (cubeMipMaps exampleCubeMipMaps).
Proof. reflexivity. Qed.

Theorem exampleCubeMipMapListMaxLevelBounded : cubeMipMapListMaxLevelBounded (cubeMipMaps exampleCubeMipMaps) 4 4.
Proof. simpl. lia. Qed.

Theorem exampleCubeMipMapFaceOffsetsCorrect : cubeMipMapFaceOffsetsCorrect (cubeMipMaps exampleCubeMipMaps).
Proof.
  simpl.
  assert (cubeFaceOffsetsCorrect cubeMipMap0) as H0 by (cbv; lia).
  assert (cubeFaceOffsetsCorrect cubeMipMap1) as H1 by (cbv; lia).
  assert (cubeFaceOffsetsCorrect cubeMipMap2) as H2 by (cbv; lia).
  constructor; auto.
Qed.

Theorem exampleCubeMipMapListValid : cubeMipMapListValid exampleCubeMipMaps 4 4.
Proof.
  constructor.
  apply exampleCubeMipMapListIsSorted.
  constructor.
  apply exampleCubeMipMapListIsNonEmpty.
  constructor.
  apply exampleCubeMipMapListLevelZero.
  constructor.
  apply exampleCubeMipMapListMaxLevelBounded.
  apply exampleCubeMipMapFaceOffsetsCorrect.
Qed.

8.14. Calino/Descriptor.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.
From Stdlib Require Import Strings.Ascii.
From Stdlib Require Import List.
From Stdlib Require Import Lia.

Require Import com.io7m.rlanark.Lanark.

Import ListNotations.

Definition calinoReservedDescriptor (s : string) : lanarkT :=
  Lanark "com" ["io7m"; "calino"; s].

(** @annospec cae2e9b7-01ef-460a-9496-40eacacb48e1 *)
Definition isCalinoReservedDescriptor (x : lanarkT) : Prop :=
  match x with
  | Lanark a (b :: c :: _) => a = "com" /\ b = "io7m" /\ c = "calino"
  | _                      => False
  end.

Theorem isCalinoReservedDescriptorDecidable : forall x,
  {isCalinoReservedDescriptor x}+{~isCalinoReservedDescriptor x}.
Proof.
  destruct x as [a rs].
  destruct rs as [|b rs0].
  - right; intuition.
  - destruct rs0 as [|c rs1].
    -- right; intuition.
    -- destruct (string_dec a "com").
       destruct (string_dec b "io7m").
       destruct (string_dec c "calino").
       subst.
       unfold isCalinoReservedDescriptor.
       left; auto.
       * right.
         intuition.
         inversion H.
         destruct H1.
         contradiction.
       * right.
         intuition.
         inversion H.
         destruct H1.
         contradiction.
       * right.
         intuition.
         inversion H.
         contradiction.
Qed.

Theorem isCalinoReservedDescriptorNotEqual : forall x y,
  isCalinoReservedDescriptor x
  -> ~isCalinoReservedDescriptor y
  -> x <> y.
Proof.
  intros x y Hx Hy.
  destruct (lanarkEqDecidable x y) as [HL|HR].
  - subst y. contradiction.
  - auto.
Qed.

Ltac lanarkSegmentSolve :=
  match goal with
  | |- isLanarkPrimarySegment ?x   => constructor
  | |- isLanarkSecondarySegment ?x => constructor

  | |- isLanarkCharRest ?y  =>
    match y with
    | "0"%char => (assert (isDecimal "0") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "1"%char => (assert (isDecimal "1") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "2"%char => (assert (isDecimal "2") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "3"%char => (assert (isDecimal "3") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "4"%char => (assert (isDecimal "4") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "5"%char => (assert (isDecimal "5") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "6"%char => (assert (isDecimal "6") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "7"%char => (assert (isDecimal "7") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "8"%char => (assert (isDecimal "8") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "9"%char => (assert (isDecimal "9") by (constructor; compute; lia); unfold isLanarkCharRest; auto)
    | "_"%char => (assert (nat_of_ascii "_" = nat_of_ascii underscore) by (reflexivity); unfold isLanarkCharRest; auto)
    | "-"%char => (assert (nat_of_ascii "-" = nat_of_ascii hyphen) by (reflexivity); unfold isLanarkCharRest; auto)
    | _        => constructor
    end

  | |- isLanarkCharStart ?y => constructor
  | |- ListDef.Forall ?f ?g => constructor

  | |- Ascii.nat_of_ascii ?a <= Ascii.nat_of_ascii ?b => compute; lia
  | |- String.length ?q <= ?r                         => compute; lia
  | _                                                 => fail 1 "lanarkSegmentSolve: unexpected goal"
  end.

Goal isLanarkCharRest "_".
Proof. lanarkSegmentSolve. Qed.

Goal isLanarkCharRest "-".
Proof. lanarkSegmentSolve. Qed.

Goal isLanarkCharRest "a".
Proof. repeat lanarkSegmentSolve. Qed.

Lemma primaryCom : isLanarkPrimarySegment "com".
Proof. repeat lanarkSegmentSolve. Qed.

Lemma secondaryIo7m : isLanarkSecondarySegment "io7m".
Proof. repeat lanarkSegmentSolve. Qed.

Lemma secondaryCalino : isLanarkSecondarySegment "calino".
Proof. repeat lanarkSegmentSolve. Qed.

Theorem isCalinoReservedDescriptorValid : forall x,
  isLanarkSecondarySegment x
  -> lanarkValidT (calinoReservedDescriptor x).
Proof.
  intros x Hx.
  constructor.
  exact primaryCom.
  constructor.
  * constructor.
    exact secondaryIo7m.
    constructor.
    exact secondaryCalino.
    constructor.
    exact Hx.
    constructor.
  * compute; lia.
Qed.

Theorem isCalinoReservedDescriptorCorrect : forall x,
  isLanarkSecondarySegment x
  -> isCalinoReservedDescriptor (calinoReservedDescriptor x).
Proof.
  intros x Hx.
  simpl.
  intuition.
Qed.

8.15. Calino/Flag.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.
From Stdlib Require Import List.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

(** @annospec 1980a36b-8366-440b-b1a0-121be7af7f6a *)
Inductive flagT : Set :=
  | FlagAlphaPremultiplied
  | FlagCustom : lanarkT -> flagT.

(** @annospec 736afcff-df83-40cc-bcb5-9c273e47ec7c *)
Definition flagValid (f : flagT) : Prop :=
  match f with
  | FlagAlphaPremultiplied => True
  | FlagCustom t           => (~isCalinoReservedDescriptor t) /\ lanarkValidT t
  end.

Definition flagDescribe (f : flagT) : lanarkT :=
  match f with
  | FlagAlphaPremultiplied => calinoReservedDescriptor "alpha_premultiplied"
  | FlagCustom d           => d
  end.

Inductive flagSetT : Set := FlagSet {
  flags : list flagT
}.

(** @annospec dc4132bf-c086-4f56-b23a-8e814b552e7a *)
Definition flagSetValid (f : flagSetT) : Prop :=
     NoDup (flags f)
  /\ Forall flagValid (flags f).

Theorem flagDescribeValid : forall (c : flagT),
  flagValid c ->
  match c with
  | FlagCustom t => lanarkValidT t
  | _            => lanarkValidT (flagDescribe c)
  end.
Proof.
  intros c Hc.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
  destruct Hc; auto.
Qed.

Theorem flagValidDecidable : forall f,
  {flagValid f}+{~flagValid f}.
Proof.
  unfold flagValid.
  destruct f;
    try (left; auto || fail).

  destruct (lanarkValidDecidable l);
    destruct (isCalinoReservedDescriptorDecidable l);
      intuition.
Qed.

Lemma flagEqDecidable : forall (a b : flagT),
  {a = b}+{~a = b}.
Proof.
  destruct a;
    destruct b;
      try (left; reflexivity);
      try (right; discriminate);
      try (intuition).
  destruct (lanarkEqDecidable l l0).
  * subst; left; f_equal.
  * right; congruence.
Qed.

Lemma flagSetNoDupDecidable : forall (f : list flagT),
  {NoDup f}+{~NoDup f}.
Proof.
  induction f as [|y ys].
  * left; constructor.
  * destruct IHys as [HL|HR].
    ** destruct (in_dec flagEqDecidable y ys) as [HinL|HinR].
       *** right.
           rewrite NoDup_cons_iff.
           intuition.
       *** left; constructor; auto.
    ** right.
       rewrite NoDup_cons_iff.
       intuition.
Qed.

Lemma flagSetForallValidDecidable : forall (f : list flagT),
  {Forall flagValid f}+{~Forall flagValid f}.
Proof.
  induction f as [|y ys].
  * left; constructor.
  * destruct IHys as [HL|HR].
    ** destruct (flagValidDecidable y) as [HfL|HfR].
       *** left; constructor; auto.
       *** right.
           unfold not; intro Hfalse.
           pose proof (Forall_inv Hfalse) as H0.
           contradiction.
    ** destruct (flagValidDecidable y) as [HfL|HfR].
       *** right.
           unfold not; intro Hfalse.
           pose proof (Forall_inv_tail Hfalse) as H0.
           contradiction.
       *** right.
           unfold not; intro Hfalse.
           pose proof (Forall_inv Hfalse) as H0.
           contradiction.
Qed.

Theorem flagSetValidDecidable : forall f,
  {flagSetValid f}+{~flagSetValid f}.
Proof.
  unfold flagSetValid.
  intros f.
  destruct (flagSetNoDupDecidable (flags f));
  destruct (flagSetForallValidDecidable (flags f));
  intuition.
Qed.

8.16. Calino/ImageInfo.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import PArith.PArith.
From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Strings.Ascii.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Nat.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.calino.ChannelDescription.
Require Import com.io7m.calino.ChannelSemantic.
Require Import com.io7m.calino.ChannelType.
Require Import com.io7m.calino.CoordinateSystem.
Require Import com.io7m.calino.Compression.
Require Import com.io7m.calino.SuperCompression.
Require Import com.io7m.calino.ColorSpace.
Require Import com.io7m.calino.Flag.
Require Import com.io7m.calino.ImageSize.

Require Import com.io7m.octetorder.OctetOrder.

(** @annospec e7729ae8-27ae-47e6-a98c-7cd83530b6e8 *)
Record imageInfoT : Set := ImageInfo {
  imageSize                   : imageSize3DT;
  imageChannelsLayout         : channelLayoutDescriptionT;
  imageChannelsType           : channelTypeT;
  imageCompressionMethod      : compressionMethodT;
  imageSuperCompressionMethod : superCompressionMethodT;
  imageCoordinateSystem       : coordinateSystemT;
  imageColorSpace             : colorSpaceT;
  imageFlags                  : flagSetT;
  imageByteOrder              : octetOrder
}.

(** @annospec 2178f721-c5d3-4810-8eef-56dea04bb54d *)
Definition imageInfoValid (i : imageInfoT) : Prop :=
     imageSize3DValid (imageSize i)
  /\ channelLayoutDescriptionValidT (imageChannelsLayout i)
  /\ channelTypeValid (imageChannelsType i)
  /\ compressionMethodValid (imageCompressionMethod i)
  /\ superCompressionMethodValid (imageSuperCompressionMethod i)
  /\ colorSpaceValid (imageColorSpace i)
  /\ flagSetValid (imageFlags i)
  .

Theorem imageInfoValidDecidable : forall i,
  {imageInfoValid i}+{~imageInfoValid i}.
Proof.
  unfold imageInfoValid.
  intros i.
  destruct (imageSize3DValidDecidable (imageSize i));
  destruct (channelLayoutDescriptionValidDecidable (imageChannelsLayout i));
  destruct (channelTypeValidDecidable (imageChannelsType i));
  destruct (compressionMethodValidDecidable (imageCompressionMethod i));
  destruct (superCompressionMethodValidDecidable (imageSuperCompressionMethod i));
  destruct (colorSpaceValidDecidable (imageColorSpace i));
  destruct (flagSetValidDecidable (imageFlags i));
  intuition.
Qed.

8.17. Calino/ImageSize.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import NArith.

(** @annospec a79b434c-165e-4dd7-a6c5-f8d25683cf22 *)
Record imageSize3DT : Set := ImageSize3D {
  sizeX : nat;
  sizeY : nat;
  sizeZ : nat;
}.

(** @annospec bbe2bbcc-3891-43cc-96eb-b679299900d8 *)
Definition imageSize3DValid (i : imageSize3DT) : Prop :=
     0 <> (sizeX i)
  /\ 0 <> (sizeY i)
  /\ 0 <> (sizeZ i).

Theorem imageSize3DValidDecidable : forall i,
  {imageSize3DValid i}+{~imageSize3DValid i}.
Proof.
  unfold imageSize3DValid.
  destruct i.
  destruct (PeanoNat.Nat.eq_dec 0 sizeX0);
  destruct (PeanoNat.Nat.eq_dec 0 sizeY0);
  destruct (PeanoNat.Nat.eq_dec 0 sizeZ0).
  * right; intuition.
  * right; intuition.
  * right; intuition.
  * right; intuition.
  * right; intuition.
  * right; intuition.
  * right; intuition.
  * left; intuition.
Qed.

8.18. Calino/JsonData.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Strings.Ascii.

Require Import com.io7m.calino.ByteOrder.
Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.ChannelDescription.
Require Import com.io7m.calino.ChannelSemantic.
Require Import com.io7m.calino.ChannelType.
Require Import com.io7m.calino.ColorSpace.
Require Import com.io7m.calino.Flag.
Require Import com.io7m.calino.Compression.
Require Import com.io7m.calino.CoordinateSystem.
Require Import com.io7m.calino.SuperCompression.
Require Import com.io7m.calino.Descriptor.

Require Import com.io7m.calino.ImageInfo.
Require Import com.io7m.calino.Metadata.
Require Import com.io7m.calino.MipMap.
Require Import com.io7m.calino.ArrayMipMap.
Require Import com.io7m.calino.CubeMipMap.
Require Import com.io7m.calino.Calino.

Require Import com.io7m.rocson.Json.
Require Import com.io7m.rlanark.Lanark.

Require Import com.io7m.octetorder.OctetOrder.

Import ListNotations.

Open Scope string_scope.

(** The [json*] definitions in this file define a canonical *reference*
    encoding of the model as a JSON value.

    The JSON text stored in the [CLN_CLNO] section is not byte-for-byte
    normative. [rocson]'s [jsonSerializeString] escapes strings in a
    conservative way (the characters [0x00]-[0x1f], [0x22] and [0x5c]
    are escaped as [\u00XX] with lower-case hexadecimal digits) for ease
    of verification. Standard JSON string escaping (RFC 8259) is
    perfectly acceptable: a conforming implementation may write any
    valid JSON text denoting the model value [jsonCalino c], and a
    conforming reader must accept any valid JSON text denoting it,
    ignoring unknown properties. *)

Definition jsonImageSize3D (s : imageSize3DT) : json :=
  JsonObject [
    ("SizeX", JsonInteger (Z.of_nat (sizeX s)));
    ("SizeY", JsonInteger (Z.of_nat (sizeY s)));
    ("SizeZ", JsonInteger (Z.of_nat (sizeZ s)))
  ].

Definition jsonChannelSemantic (c : channelSemanticT) : json :=
  JsonString (lanarkText (channelSemanticDescribe c)).

Definition jsonChannelDescription (c : channelDescriptionT) : json :=
  JsonObject [
    ("Semantic", jsonChannelSemantic (cdSemantic c));
    ("Bits",     JsonInteger (cdBits c))
  ].

Definition jsonPacking (c : channelLayoutPackingT) : json :=
  JsonString (lanarkText (channelLayoutPackingDescribe c)).

Definition jsonChannelLayoutDescriptionUnpacked (s : channelLayoutDescriptionUnpackedT) : json :=
  JsonObject [
    ("@Type",    JsonString "Unpacked");
    ("Channels", JsonArray (map jsonChannelDescription (uChannels s)))
  ].

Definition jsonChannelLayoutDescriptionPacked (s : channelLayoutDescriptionPackedT) : json :=
  JsonObject [
    ("@Type",    JsonString "Packed");
    ("Channels", JsonArray (map jsonChannelDescription (pChannels s)));
    ("Packing",  jsonPacking (pPacking s))
  ].

Definition jsonChannelLayoutDescription (s : channelLayoutDescriptionT) : json :=
  match s with
  | CLDUnpacked u => jsonChannelLayoutDescriptionUnpacked u
  | CLDPacked   p => jsonChannelLayoutDescriptionPacked p
  end.

Definition jsonChannelType (c : channelTypeT) : json :=
  JsonString (lanarkText (channelTypeDescribe c)).

Definition jsonCompressionMethodUncompressed (c : compressionUncompressedT) : list (string * json) := [].
Definition jsonCompressionMethodBC1 (c : compressionBC1T) : list (string * json) := [].
Definition jsonCompressionMethodBC2 (c : compressionBC2T) : list (string * json) := [].
Definition jsonCompressionMethodBC3 (c : compressionBC3T) : list (string * json) := [].
Definition jsonCompressionMethodBC4 (c : compressionBC4T) : list (string * json) := [].
Definition jsonCompressionMethodBC5 (c : compressionBC5T) : list (string * json) := [].
Definition jsonCompressionMethodBC6 (c : compressionBC6T) : list (string * json) := [].
Definition jsonCompressionMethodBC7 (c : compressionBC7T) : list (string * json) := [].
Definition jsonCompressionMethodETC1 (c : compressionETC1T) : list (string * json) := [].
Definition jsonCompressionMethodETC2 (c : compressionETC2T) : list (string * json) := [].
Definition jsonCompressionMethodEAC (c : compressionEACT) : list (string * json) := [].

Definition jsonCompressionMethodASTC (c : compressionASTCT) : list (string * json) := [
  ("BlockSizeX", JsonInteger (astcBlockSizeX c));
  ("BlockSizeY", JsonInteger (astcBlockSizeY c))
].

Definition jsonCompressionMethodCustom (c : compressionCustomT) : list (string * json) := [
  ("Identifier",        JsonString (lanarkText (customId c)));
  ("BlockSizeX",        JsonInteger (customBlockSizeX c));
  ("BlockSizeY",        JsonInteger (customBlockSizeY c));
  ("SectionIdentifier", JsonInteger (customSectionIdentifier c));
  ("Alignment",         JsonInteger (customAlign c))
].

Definition jsonCompressionMethod (c : compressionMethodT) : json :=
  JsonObject (
    [("@Type", JsonString (lanarkText (compressionMethodDescribe c)))]
    ++
    match c with
    | CUncompressed x => jsonCompressionMethodUncompressed x
    | CBC1 x          => jsonCompressionMethodBC1 x
    | CBC2 x          => jsonCompressionMethodBC2 x
    | CBC3 x          => jsonCompressionMethodBC3 x
    | CBC4 x          => jsonCompressionMethodBC4 x
    | CBC5 x          => jsonCompressionMethodBC5 x
    | CBC6 x          => jsonCompressionMethodBC6 x
    | CBC7 x          => jsonCompressionMethodBC7 x
    | CETC1 x         => jsonCompressionMethodETC1 x
    | CETC2 x         => jsonCompressionMethodETC2 x
    | CEAC x          => jsonCompressionMethodEAC x
    | CASTC x         => jsonCompressionMethodASTC x
    | CCustom x       => jsonCompressionMethodCustom x
    end
  ).

Definition jsonSuperCompressionMethodUncompressed (c : superCompressionUncompressedT) : list (string * json) := [].
Definition jsonSuperCompressionMethodLZ4 (c : superCompressionLZ4T) : list (string * json) := [].
Definition jsonSuperCompressionMethodDEFLATE (c : superCompressionDEFLATET) : list (string * json) := [].

Definition jsonSuperCompressionMethodCustom (c : superCompressionCustomT) : list (string * json) := [
  ("Identifier",        JsonString (lanarkText (superCustomId c)));
  ("SectionIdentifier", JsonInteger (superCustomSectionIdentifier c))
].

Definition jsonSuperCompressionMethod (c : superCompressionMethodT) : json :=
  JsonObject (
    [("@Type", JsonString (lanarkText (superCompressionMethodDescribe c)))]
    ++
    match c with
    | SCUncompressed x => jsonSuperCompressionMethodUncompressed x
    | SCLZ4 x          => jsonSuperCompressionMethodLZ4 x
    | SCDEFLATE x      => jsonSuperCompressionMethodDEFLATE x
    | SCCustom x       => jsonSuperCompressionMethodCustom x
    end
  ).

Definition jsonCoordinateSystem (c : coordinateSystemT) : json :=
  match c with
  | CoordinateSystem r s t =>
    JsonObject [
      ("AxisR", JsonString (lanarkText (coordinateAxisRDescribe r)));
      ("AxisS", JsonString (lanarkText (coordinateAxisSDescribe s)));
      ("AxisT", JsonString (lanarkText (coordinateAxisTDescribe t)))
    ]
  end.

Definition jsonColorSpace (c : colorSpaceT) : json :=
  JsonString (lanarkText (colorSpaceDescribe c)).

Definition jsonFlag (f : flagT) : json :=
  JsonString (lanarkText (flagDescribe f)).

Definition jsonOctetOrder (o : octetOrder) : json :=
  JsonString (lanarkText (byteOrderDescribe o)).

Definition jsonFlagSet (f : flagSetT) : json :=
  JsonArray (map jsonFlag (flags f)).

Definition jsonImageInfo (i : imageInfoT) : json :=
  JsonObject [
    ("ImageSize",              jsonImageSize3D (imageSize i));
    ("ChannelsLayout",         jsonChannelLayoutDescription (imageChannelsLayout i));
    ("ChannelsType",           jsonChannelType (imageChannelsType i));
    ("CompressionMethod",      jsonCompressionMethod (imageCompressionMethod i));
    ("SuperCompressionMethod", jsonSuperCompressionMethod (imageSuperCompressionMethod i));
    ("CoordinateSystem",       jsonCoordinateSystem (imageCoordinateSystem i));
    ("ColorSpace",             jsonColorSpace (imageColorSpace i));
    ("Flags",                  jsonFlagSet (imageFlags i));
    ("OctetOrder",             jsonOctetOrder (imageByteOrder i))
  ].

Definition jsonMetadataValue (m : metadataValueT) : json :=
  JsonObject [
    ("Key",   JsonString (lanarkText (mKey m)));
    ("Value", JsonString (mValue m))
  ].

Definition jsonMetadata (m : metadataT) : json :=
  JsonArray (map jsonMetadataValue (mValues m)).

Definition jsonMipMap (m : mipMapT) : json :=
  JsonObject [
    ("Level",            JsonInteger (Z.of_nat (mipMapLevel m)));
    ("SizeCompressed",   JsonInteger (Z.of_nat (mipMapSizeCompressed m)));
    ("SizeUncompressed", JsonInteger (Z.of_nat (mipMapSizeUncompressed m)));
    ("CRC32",            JsonInteger (Z.of_nat (mipMapCRC32 m)))
  ].

Definition jsonMipMapList (m : mipMapListT) : json :=
  JsonArray (map jsonMipMap (mipMaps m)).

Definition jsonArrayMipMapIndex (i : arrayMipMapIndexT) : json :=
  JsonObject [
    ("Level", JsonInteger (Z.of_nat (arrayMipMapLevel i)));
    ("Layer", JsonInteger (Z.of_nat (arrayMipMapLayer i)))
  ].

Definition jsonArrayMipMap (m : arrayMipMapT) : json :=
  JsonObject [
    ("Index",            jsonArrayMipMapIndex (arrayMipMapIndex m));
    ("SizeCompressed",   JsonInteger (Z.of_nat (arrayMipMapSizeCompressed m)));
    ("SizeUncompressed", JsonInteger (Z.of_nat (arrayMipMapSizeUncompressed m)));
    ("CRC32",            JsonInteger (Z.of_nat (arrayMipMapCRC32 m)))
  ].

Definition jsonArrayMipMapList (m : arrayMipMapListT) : json :=
  JsonArray (map jsonArrayMipMap (arrayMipMaps m)).

Definition jsonCubeMapFace (f : cubeMapFaceT) : json :=
  JsonObject [
    ("Offset",           JsonInteger (Z.of_nat (cubeFaceOffset f)));
    ("SizeCompressed",   JsonInteger (Z.of_nat (cubeFaceSizeCompressed f)));
    ("SizeUncompressed", JsonInteger (Z.of_nat (cubeFaceSizeUncompressed f)));
    ("CRC32",            JsonInteger (Z.of_nat (cubeFaceCRC32 f)))
  ].

Definition jsonCubeMipMap (m : cubeMipMapT) : json :=
  JsonObject [
    ("Level",         JsonInteger (Z.of_nat (cubeMipMapLevel m)));
    ("FaceXPositive", jsonCubeMapFace (cubeMapFaceXPos m));
    ("FaceXNegative", jsonCubeMapFace (cubeMapFaceXNeg m));
    ("FaceYPositive", jsonCubeMapFace (cubeMapFaceYPos m));
    ("FaceYNegative", jsonCubeMapFace (cubeMapFaceYNeg m));
    ("FaceZPositive", jsonCubeMapFace (cubeMapFaceZPos m));
    ("FaceZNegative", jsonCubeMapFace (cubeMapFaceZNeg m))
  ].

Definition jsonCubeMipMapList (m : cubeMipMapListT) : json :=
  JsonArray (map jsonCubeMipMap (cubeMipMaps m)).

Definition jsonCalino2D (c : calino2DT) : json :=
  JsonObject [
    ("@Type",     JsonString "2D");
    ("ImageInfo", jsonImageInfo (c2dImageInfo c));
    ("MipMaps",   jsonMipMapList (c2dMipMaps c));
    ("Metadata",  jsonMetadata (c2dMetadata c))
  ].

Definition jsonCalinoCube (c : calinoCubeT) : json :=
  JsonObject [
    ("@Type",     JsonString "Cube");
    ("ImageInfo", jsonImageInfo (cCubeImageInfo c));
    ("MipMaps",   jsonCubeMipMapList (cCubeMipMaps c));
    ("Metadata",  jsonMetadata (cCubeMetadata c))
  ].

Definition jsonCalinoArray (c : calinoArrayT) : json :=
  JsonObject [
    ("@Type",     JsonString "Array");
    ("ImageInfo", jsonImageInfo (cArrayImageInfo c));
    ("MipMaps",   jsonArrayMipMapList (cArrayMipMaps c));
    ("Metadata",  jsonMetadata (cArrayMetadata c))
  ].

(** @annospec 903a1404-2b54-48cc-93fa-fa04fe52af21 *)
Definition jsonCalino (c : calinoT) : json :=
  match c with
  | C2D x    => jsonCalino2D x
  | CCube x  => jsonCalinoCube x
  | CArray x => jsonCalinoArray x
  end.

8.19. Calino/JsonFacts.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Strings.Ascii.

Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.ChannelDescription.
Require Import com.io7m.calino.ChannelSemantic.
Require Import com.io7m.calino.ChannelType.
Require Import com.io7m.calino.Compression.
Require Import com.io7m.calino.ColorSpace.
Require Import com.io7m.calino.CoordinateSystem.
Require Import com.io7m.calino.SuperCompression.
Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.calino.Flag.
Require Import com.io7m.calino.ImageInfo.
Require Import com.io7m.calino.Metadata.
Require Import com.io7m.calino.MipMap.
Require Import com.io7m.calino.ArrayMipMap.
Require Import com.io7m.calino.CubeMipMap.
Require Import com.io7m.calino.Calino.
Require Import com.io7m.calino.JsonData.

Require Import com.io7m.rocson.Json.
Require Import com.io7m.rlanark.Lanark.

Import ListNotations.

Open Scope string_scope.

Theorem jsonImageSize3DInjective : forall a b,
  jsonImageSize3D a = jsonImageSize3D b
  -> a = b.
Proof.
  intros a b Heq.
  destruct a as [a0 a1 a2].
  destruct b as [b0 b1 b2].
  inversion Heq as [[H0 H1 H2]].
  rewrite Nat2Z.inj_iff in H0.
  rewrite Nat2Z.inj_iff in H1.
  rewrite Nat2Z.inj_iff in H2.
  subst.
  reflexivity.
Qed.

Theorem jsonChannelSemanticInjective : forall a b,
  channelSemanticValid a
  -> channelSemanticValid b
  -> jsonChannelSemantic a = jsonChannelSemantic b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct a;
  destruct b;
  try (reflexivity);
  try (inversion Heq).
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hvb.
    destruct Hvb as [Hv0 Hv1].
    pose proof (channelSemanticDescribeValid _ Hva) as H1.
    simpl in H1.
    pose proof (lanarkTextInjective _ _ H1 Hv1 H0) as H2.
    rewrite <- H2 in Hv0.
    contradict Hv0.
    simpl; intuition.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "red")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSRed Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "green")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSGreen Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "blue")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSBlue Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "alpha")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSAlpha Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "depth")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSDepth Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "stencil")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSStencil Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "exponent")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSExponent Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    destruct Hva as [Hva0 Hva1].
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "unused")) as Hvc. {
      simpl; intuition.
    }
    pose proof (channelSemanticDescribeValid CSUnused Hvb) as Hve.
    pose proof (lanarkTextInjective l _ Hva1 Hve H0) as Hvf.
    subst l.
    contradiction.
  * unfold channelSemanticValid in Hva.
    unfold channelSemanticValid in Hvb.
    destruct Hva as [Hva0 Hva1].
    destruct Hvb as [Hvb0 Hvb1].
    pose proof (lanarkTextInjective l l0 Hva1 Hvb1 H0) as H1.
    subst l.
    reflexivity.
Qed.

Theorem jsonPackingInjective : forall a b,
  jsonPacking a = jsonPacking b
  -> a = b.
Proof.
  intros a b Heq.
  pose proof (channelLayoutPackingDescribeValid a) as H0.
  pose proof (channelLayoutPackingDescribeValid b) as H1.
  inversion Heq.
  destruct a;
  destruct b.
  * reflexivity.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * reflexivity.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * reflexivity.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * pose proof (lanarkTextInjective  _ _ H0 H1 H2) as H3.
    contradict H3.
    discriminate.
  * reflexivity.
Qed.

Theorem jsonChannelDescriptionInjective : forall a b,
  channelDescriptionValid a 
  -> channelDescriptionValid b
  -> jsonChannelDescription a = jsonChannelDescription b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [_ Hva1].
  destruct Hvb as [_ Hvb1].
  unfold jsonChannelDescription in Heq.
  pose proof (channelSemanticDescribeValid _ Hva1) as H0.
  pose proof (channelSemanticDescribeValid _ Hvb1) as H1.
  assert (jsonChannelSemantic (cdSemantic a) = jsonChannelSemantic (cdSemantic b)) as H2
    by congruence.
  pose proof (jsonChannelSemanticInjective _ _ Hva1 Hvb1 H2) as H3.
  assert (cdBits a = cdBits b) as H4 by congruence.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonChannelDescriptionMapInjective : forall a b,
  Forall channelDescriptionValid a
  -> Forall channelDescriptionValid b
  -> map jsonChannelDescription a = map jsonChannelDescription b
  -> a = b.
Proof.
  induction a as [|y ys].
  - intros b H0 H1 H2.
    simpl in H2.
    pose proof (map_eq_nil jsonChannelDescription b (eq_sym H2)) as H3.
    auto.
  - intros b H0 H1 H2.
    destruct b as [|z zs].
    * contradict H2; discriminate.
    * assert (y = z) as H3. {
        simpl in H2.
        assert (jsonChannelDescription y = jsonChannelDescription z) as H4
          by congruence.
        apply jsonChannelDescriptionInjective.
        apply (Forall_inv H0).
        apply (Forall_inv H1).
        exact H4.
      }
      assert (ys = zs) as H4. {
        simpl in H2.
        assert (map jsonChannelDescription ys = map jsonChannelDescription zs) as H5
          by congruence.
        apply IHys.
        apply (Forall_inv_tail H0).
        apply (Forall_inv_tail H1).
        exact H5.
      }
      subst.
      reflexivity.
Qed.

Theorem jsonChannelLayoutDescriptionUnpackedInjective : forall a b,
  channelLayoutDescriptionUnpackedValidT a
  -> channelLayoutDescriptionUnpackedValidT b
  -> jsonChannelLayoutDescriptionUnpacked a = jsonChannelLayoutDescriptionUnpacked b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [_ [Hva1 _]].
  destruct Hvb as [_ [Hvb1 _]].
  unfold jsonChannelLayoutDescriptionUnpacked in Heq.
  assert (map jsonChannelDescription (uChannels a)
        = map jsonChannelDescription (uChannels b)) as H0. {
    congruence.
  }
  assert (uChannels a = uChannels b) as H1. {
    apply (jsonChannelDescriptionMapInjective (uChannels a) (uChannels b) Hva1 Hvb1 H0).
  }
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonChannelLayoutDescriptionPackedInjective : forall a b,
  channelLayoutDescriptionPackedValidT a
  -> channelLayoutDescriptionPackedValidT b
  -> jsonChannelLayoutDescriptionPacked a = jsonChannelLayoutDescriptionPacked b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [_ [Hva1 _]].
  destruct Hvb as [_ [Hvb1 _]].
  unfold jsonChannelLayoutDescriptionPacked in Heq.
  assert (map jsonChannelDescription (pChannels a)
        = map jsonChannelDescription (pChannels b)) as H0. {
    congruence.
  }
  assert (pChannels a = pChannels b) as H1. {
    apply (jsonChannelDescriptionMapInjective (pChannels a) (pChannels b) Hva1 Hvb1 H0).
  }
  assert (pPacking a = pPacking b) as H2. {
    apply jsonPackingInjective.
    congruence.
  }
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonChannelLayoutDescriptionInjective : forall a b,
  channelLayoutDescriptionValidT a
  -> channelLayoutDescriptionValidT b
  -> jsonChannelLayoutDescription a = jsonChannelLayoutDescription b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct a;
  destruct b.
  * pose proof (jsonChannelLayoutDescriptionUnpackedInjective _ _ Hva Hvb Heq) as H0.
    subst; reflexivity.
  * simpl in Heq.
    unfold jsonChannelLayoutDescriptionUnpacked in Heq.
    unfold jsonChannelLayoutDescriptionPacked in Heq.
    contradict Heq.
    discriminate.
  * simpl in Heq.
    unfold jsonChannelLayoutDescriptionUnpacked in Heq.
    unfold jsonChannelLayoutDescriptionPacked in Heq.
    contradict Heq.
    discriminate.
  * pose proof (jsonChannelLayoutDescriptionPackedInjective _ _ Hva Hvb Heq) as H0.
    subst; reflexivity.
Qed.

Theorem jsonChannelTypeInjective : forall a b,
  channelTypeValid a
  -> channelTypeValid b
  -> jsonChannelType a = jsonChannelType b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  pose proof (channelTypeDescribeValid a Hva) as Ha.
  pose proof (channelTypeDescribeValid b Hvb) as Hb.
  inversion Heq.

  destruct a; destruct b;
  try discriminate;
  try reflexivity.

  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (lanarkTextInjective _ _ Ha Hb H0) as H1.
    destruct Hvb as [Hvb1 _].
    subst l.
    simpl in *.
    contradict Hvb1.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    simpl in *.
    contradict Hva.
    intuition.
  * pose proof (eq_sym (lanarkTextInjective _ _ Ha Hb H0)) as H1.
    subst l.
    reflexivity.
Qed.

Theorem jsonCompressionMethodInjective : forall a b,
  compressionMethodValid a
  -> compressionMethodValid b
  -> jsonCompressionMethod a = jsonCompressionMethod b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.

  destruct a; destruct b;
  try discriminate;
  try reflexivity.

  all: try (destruct c; destruct c0; reflexivity).

  * destruct c; destruct c0.
    unfold jsonCompressionMethod in Heq.
    simpl in Heq.
    unfold jsonCompressionMethodASTC in Heq.
    assert (astcBlockSizeX = astcBlockSizeX0)
      by (simpl in *; congruence).
    assert (astcBlockSizeY = astcBlockSizeY0)
      by (simpl in *; congruence).
    subst astcBlockSizeX0.
    subst astcBlockSizeY0.
    reflexivity.
  * destruct c; destruct c0.
    unfold jsonCompressionMethod in Heq.
    simpl in Heq.
    unfold jsonCompressionMethodCustom in Heq.
    simpl in *.
    assert (customBlockSizeX = customBlockSizeX0)
      by (simpl in *; congruence).
    assert (customBlockSizeY = customBlockSizeY0)
      by (simpl in *; congruence).
    assert (customAlign = customAlign0)
      by (simpl in *; congruence).
    assert (customSectionIdentifier = customSectionIdentifier0)
      by (simpl in *; congruence).
    assert (lanarkText customId = lanarkText customId0)
      by congruence.

    subst customBlockSizeX0.
    subst customBlockSizeY0.
    subst customAlign0.
    subst customSectionIdentifier0.
    destruct Hva as [_ Hc1].
    destruct Hc1 as [_ Hc2].
    destruct Hc2 as [_ Hc3].
    destruct Hc3 as [_ Hc4].
    destruct Hc4 as [_ Hva1].
    destruct Hvb as [_ Hb1].
    destruct Hb1 as [_ Hb2].
    destruct Hb2 as [_ Hb3].
    destruct Hb3 as [_ Hb4].
    destruct Hb4 as [_ Hvb1].
    pose proof (lanarkTextInjective _ _ Hva1 Hvb1 H3) as H4.
    simpl in H4.
    subst customId0.
    reflexivity.
Qed.

Theorem jsonSuperCompressionMethodInjective : forall a b,
  superCompressionMethodValid a
  -> superCompressionMethodValid b
  -> jsonSuperCompressionMethod a = jsonSuperCompressionMethod b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.

  destruct a; destruct b;
  try discriminate;
  try reflexivity.

  * destruct s; destruct s0; reflexivity.
  * destruct s; destruct s0; reflexivity.
  * destruct s; destruct s0; reflexivity.

  * unfold jsonSuperCompressionMethod in Heq.
    unfold jsonSuperCompressionMethodCustom in Heq.
    simpl in Heq.
    destruct s; destruct s0.
    simpl in *.
    destruct Hva as [_ Hva1].
    destruct Hvb as [_ Hvb1].
    assert (lanarkText superCustomId = lanarkText superCustomId0) as H0
      by congruence.
    assert (superCustomSectionIdentifier = superCustomSectionIdentifier0) as H1
      by congruence.
    pose proof (lanarkTextInjective _ _ Hva1 Hvb1 H0) as H2.
    subst.
    reflexivity.
Qed.

Theorem jsonCoordinateSystemInjective : forall a b,
  jsonCoordinateSystem a = jsonCoordinateSystem b
  -> a = b.
Proof.
  intros a b Heq.
  destruct a as [a0 a1 a2].
  destruct b as [b0 b1 b2].

  destruct a0;
  destruct a1;
  destruct a2;
  destruct b0;
  destruct b1;
  destruct b2;
  try discriminate;
  try reflexivity.
Qed.

Theorem jsonColorSpaceInjective : forall a b,
  colorSpaceValid a
  -> colorSpaceValid b
  -> jsonColorSpace a = jsonColorSpace b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.

  pose proof (colorSpaceDescribeValid a Hva) as Ha.
  pose proof (colorSpaceDescribeValid b Hvb) as Hb.

  destruct a; destruct b;
  try discriminate;
  try reflexivity.

  * unfold jsonColorSpace in Heq.
    simpl in *.
    assert (lanarkText (calinoReservedDescriptor "linear") = lanarkText l)
      as H0 by congruence.
    pose proof (lanarkTextInjective _ _ Ha Hb H0)
      as H1.
    subst.
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "linear"))
      as H1 by (simpl; intuition).
    destruct Hvb.
    contradiction.
  * unfold jsonColorSpace in Heq.
    simpl in *.
    assert (lanarkText (calinoReservedDescriptor "srgb") = lanarkText l)
      as H0 by congruence.
    pose proof (lanarkTextInjective _ _ Ha Hb H0)
      as H1.
    subst.
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "srgb")) 
      as H1 by (simpl; intuition).
    destruct Hvb.
    contradiction.
  * unfold jsonColorSpace in Heq.
    simpl in *.
    assert (lanarkText (calinoReservedDescriptor "linear") = lanarkText l)
      as H0 by congruence.
    pose proof (lanarkTextInjective _ _ Hb Ha H0)
      as H1.
    subst.
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "linear"))
      as H1 by (simpl; intuition).
    destruct Hva.
    contradiction.
  * unfold jsonColorSpace in Heq.
    simpl in *.
    assert (lanarkText (calinoReservedDescriptor "srgb") = lanarkText l)
      as H0 by congruence.
    pose proof (lanarkTextInjective _ _ Hb Ha H0)
      as H1.
    subst.
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "srgb"))
      as H1 by (simpl; intuition).
    destruct Hva.
    contradiction.
  * unfold jsonColorSpace in Heq.
    simpl in *.
    assert (lanarkText l = lanarkText l0) by congruence.
    pose proof (lanarkTextInjective _ _ Ha Hb H).
    subst.
    reflexivity.
Qed.

Theorem jsonFlagInjective : forall a b,
  flagValid a
  -> flagValid b
  -> jsonFlag a = jsonFlag b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.

  pose proof (flagDescribeValid a Hva) as Ha.
  pose proof (flagDescribeValid b Hvb) as Hb.

  destruct a; destruct b;
  try discriminate;
  try reflexivity.

  * unfold jsonFlag in Heq.
    simpl in *.
    assert (lanarkText (calinoReservedDescriptor "alpha_premultiplied") = lanarkText l)
      as H0 by congruence.
    pose proof (lanarkTextInjective _ _ Ha Hb H0)
      as H1.
    subst l.
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "alpha_premultiplied"))
      as H1 by (simpl; intuition).
    destruct Hvb.
    contradiction.
  * unfold jsonFlag in Heq.
    simpl in *.
    assert (lanarkText l = lanarkText (calinoReservedDescriptor "alpha_premultiplied"))
      as H0 by congruence.
    pose proof (lanarkTextInjective _ _ Ha Hb H0)
      as H1.
    subst l.
    assert (isCalinoReservedDescriptor (calinoReservedDescriptor "alpha_premultiplied"))
      as H1 by (simpl; intuition).
    destruct Hva.
    contradiction.
  * unfold jsonFlag in Heq.
    simpl in *.
    assert (lanarkText l = lanarkText l0) by congruence.
    pose proof (lanarkTextInjective _ _ Ha Hb H).
    subst.
    reflexivity.
Qed.

Theorem jsonOctetOrderInjective : forall a b,
  jsonOctetOrder a = jsonOctetOrder b
  -> a = b.
Proof.
  intros a b Heq.

  destruct a; destruct b;
  try discriminate;
  try reflexivity.
Qed.

Theorem jsonFlagSetInjective : forall a b,
  flagSetValid a
  -> flagSetValid b
  -> jsonFlagSet a = jsonFlagSet b
  -> a = b.
Proof.
  destruct a as [av].
  induction av as [|y ys].
  - destruct b as [bv].
    * intros Hva Hvb Heq.
      destruct bv as [|z zs].
      -- reflexivity.
      -- inversion Heq.
  - destruct b as [bv].
    * intros Hva Hvb Heq.
      destruct bv as [|z zs].
      -- inversion Heq.
      -- unfold jsonFlagSet in Heq.
         unfold jsonFlagSet in IHys.
         simpl in Heq.
         assert (flagSetValid {| flags := ys |}) as H2. {
           unfold flagSetValid.
           inversion Hva as [Hva0 Hva1].
           constructor.
           simpl in Hva0.
           simpl.
           rewrite NoDup_cons_iff in Hva0.
           intuition.
           simpl in Hva1.
           apply Forall_inv_tail in Hva1.
           auto.
         }
         assert (flagSetValid {| flags := zs |}) as H3. {
           unfold flagSetValid.
           inversion Hvb as [Hvb0 Hvb1].
           constructor.
           simpl in Hvb0.
           simpl.
           rewrite NoDup_cons_iff in Hvb0.
           intuition.
           simpl in Hvb1.
           apply Forall_inv_tail in Hvb1.
           auto.
         }
         assert (
             JsonArray (map jsonFlag (flags {| flags := ys |})) 
           = JsonArray (map jsonFlag (flags {| flags := zs |}))
         ) as H4. {
           simpl.
           congruence.
         }
         pose proof (IHys _ H2 H3 H4) as H5.
         assert (y = z) as H6. {
           apply (jsonFlagInjective y z).
           inversion Hva as [_ Hva1].
           apply (Forall_inv Hva1).
           inversion Hvb as [_ Hvb1].
           apply (Forall_inv Hvb1).
           congruence.
         }
         congruence.
Qed.

Theorem jsonImageInfoInjective : forall a b,
  imageInfoValid a
  -> imageInfoValid b
  -> jsonImageInfo a = jsonImageInfo b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [_ [Hlayout [Htype [Hcomp [Hsuper [Hcolor Hflags]]]]]].
  destruct Hvb as [_ [Hlayout0 [Htype0 [Hcomp0 [Hsuper0 [Hcolor0 Hflags0]]]]]].
  unfold jsonImageInfo in Heq.
  assert (jsonImageSize3D (imageSize a) = jsonImageSize3D (imageSize b))
    as H0 by congruence.
  pose proof (jsonImageSize3DInjective _ _ H0) as H1.
  assert (jsonChannelLayoutDescription (imageChannelsLayout a)
        = jsonChannelLayoutDescription (imageChannelsLayout b))
    as H2 by congruence.
  pose proof (jsonChannelLayoutDescriptionInjective _ _ Hlayout Hlayout0 H2) as H3.
  assert (jsonChannelType (imageChannelsType a)
        = jsonChannelType (imageChannelsType b))
    as H4 by congruence.
  pose proof (jsonChannelTypeInjective _ _ Htype Htype0 H4) as H5.
  assert (jsonCompressionMethod (imageCompressionMethod a)
        = jsonCompressionMethod (imageCompressionMethod b))
    as H6 by congruence.
  pose proof (jsonCompressionMethodInjective _ _ Hcomp Hcomp0 H6) as H7.
  assert (jsonSuperCompressionMethod (imageSuperCompressionMethod a)
        = jsonSuperCompressionMethod (imageSuperCompressionMethod b))
    as H8 by congruence.
  pose proof (jsonSuperCompressionMethodInjective _ _ Hsuper Hsuper0 H8) as H9.
  assert (jsonCoordinateSystem (imageCoordinateSystem a)
        = jsonCoordinateSystem (imageCoordinateSystem b))
    as H10 by congruence.
  pose proof (jsonCoordinateSystemInjective _ _ H10) as H11.
  assert (jsonColorSpace (imageColorSpace a)
        = jsonColorSpace (imageColorSpace b))
    as H12 by congruence.
  pose proof (jsonColorSpaceInjective _ _ Hcolor Hcolor0 H12) as H13.
  assert (jsonFlagSet (imageFlags a) = jsonFlagSet (imageFlags b))
    as H14 by congruence.
  pose proof (jsonFlagSetInjective _ _ Hflags Hflags0 H14) as H15.
  assert (jsonOctetOrder (imageByteOrder a)
        = jsonOctetOrder (imageByteOrder b))
    as H16 by congruence.
  pose proof (jsonOctetOrderInjective _ _ H16) as H17.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonMetadataValueInjective : forall a b,
  lanarkValidT (mKey a)
  -> lanarkValidT (mKey b)
  -> jsonMetadataValue a = jsonMetadataValue b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  inversion Heq as [[H0 H1]].
  pose proof (lanarkTextInjective _ _ Hva Hvb H0) as H2.
  destruct a; destruct b.
  simpl in *.
  subst.
  reflexivity.
Qed.

#[local]
Theorem jsonMetadataValueMapInjective : forall a b,
  Forall (fun v => lanarkValidT (mKey v)) a
  -> Forall (fun v => lanarkValidT (mKey v)) b
  -> map jsonMetadataValue a = map jsonMetadataValue b
  -> a = b.
Proof.
  induction a as [|y ys].
  - intros b H0 H1 H2.
    simpl in H2.
    pose proof (map_eq_nil jsonMetadataValue b (eq_sym H2)) as H3.
    auto.
  - intros b H0 H1 H2.
    destruct b as [|z zs].
    * contradict H2; discriminate.
    * assert (y = z) as H3. {
        simpl in H2.
        assert (jsonMetadataValue y = jsonMetadataValue z) as H4
          by congruence.
        apply jsonMetadataValueInjective.
        apply (Forall_inv H0).
        apply (Forall_inv H1).
        exact H4.
      }
      assert (ys = zs) as H4. {
        simpl in H2.
        assert (map jsonMetadataValue ys = map jsonMetadataValue zs) as H5
          by congruence.
        apply IHys.
        apply (Forall_inv_tail H0).
        apply (Forall_inv_tail H1).
        exact H5.
      }
      subst.
      reflexivity.
Qed.

Theorem jsonMetadataInjective : forall a b,
  metadataValid a
  -> metadataValid b
  -> jsonMetadata a = jsonMetadata b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  unfold metadataValid in Hva.
  unfold metadataValid in Hvb.
  unfold jsonMetadata in Heq.
  assert (map jsonMetadataValue (mValues a)
        = map jsonMetadataValue (mValues b)) as H0 by congruence.
  pose proof (jsonMetadataValueMapInjective (mValues a) (mValues b) Hva Hvb H0) as H1.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonMipMapInjective : forall a b,
  jsonMipMap a = jsonMipMap b
  -> a = b.
Proof.
  intros a b Heq.
  destruct a as [a0 a1 a2 a3].
  destruct b as [b0 b1 b2 b3].
  inversion Heq.
  pose proof (Nat2Z.inj _ _ H0).
  pose proof (Nat2Z.inj _ _ H1).
  pose proof (Nat2Z.inj _ _ H2).
  pose proof (Nat2Z.inj _ _ H3).
  subst.
  reflexivity.
Qed.

Theorem jsonMipMapMapInjective : forall a b,
  map jsonMipMap a = map jsonMipMap b
  -> a = b.
Proof.
  induction a as [|y ys].
  - intros b H2.
    simpl in H2.
    pose proof (map_eq_nil jsonMipMap b (eq_sym H2)) as H3.
    auto.
  - intros b H2.
    destruct b as [|z zs].
    * contradict H2; discriminate.
    * assert (y = z) as H3. {
        simpl in H2.
        assert (jsonMipMap y = jsonMipMap z) as H4 by congruence.
        apply jsonMipMapInjective.
        exact H4.
      }
      assert (ys = zs) as H4. {
        simpl in H2.
        assert (map jsonMipMap ys = map jsonMipMap zs) as H5
          by congruence.
        apply IHys.
        exact H5.
      }
      subst.
      reflexivity.
Qed.

Theorem jsonMipMapListInjective : forall a b,
  jsonMipMapList a = jsonMipMapList b
  -> a = b.
Proof.
  intros a b Heq.
  unfold jsonMipMapList in Heq.
  assert (map jsonMipMap (mipMaps a) = map jsonMipMap (mipMaps b)) as H0.
  {
    congruence.
  }
  pose proof (jsonMipMapMapInjective (mipMaps a) (mipMaps b) H0) as H1.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonArrayMipMapIndexInjective : forall a b,
  jsonArrayMipMapIndex a = jsonArrayMipMapIndex b
  -> a = b.
Proof.
  intros a b Heq.
  destruct a as [a0 a1].
  destruct b as [b0 b1].
  inversion Heq.
  pose proof (Nat2Z.inj _ _ H0).
  pose proof (Nat2Z.inj _ _ H1).
  subst.
  reflexivity.
Qed.

Theorem jsonArrayMipMapInjective : forall a b,
  jsonArrayMipMap a = jsonArrayMipMap b
  -> a = b.
Proof.
  intros a b Heq.
  destruct a as [a0 a1 a2 a3].
  destruct b as [b0 b1 b2 b3].
  assert (jsonArrayMipMapIndex a0 = jsonArrayMipMapIndex b0) as Hk1. {
    destruct a0 as [a0x a0y].
    destruct b0 as [b0x b0y].
    inversion Heq.
    pose proof (Nat2Z.inj _ _ H0).
    pose proof (Nat2Z.inj _ _ H1).
    subst.
    reflexivity.
  }
  inversion Heq.
  pose proof (Nat2Z.inj _ _ H0).
  pose proof (Nat2Z.inj _ _ H1).
  pose proof (Nat2Z.inj _ _ H2).
  pose proof (Nat2Z.inj _ _ H3).
  pose proof (Nat2Z.inj _ _ H4).
  pose proof (jsonArrayMipMapIndexInjective a0 b0 Hk1) as Hk3.
  subst.
  reflexivity.
Qed.

Theorem jsonArrayMipMapMapInjective : forall a b,
  map jsonArrayMipMap a = map jsonArrayMipMap b
  -> a = b.
Proof.
  induction a as [|y ys].
  - intros b H2.
    simpl in H2.
    pose proof (map_eq_nil jsonArrayMipMap b (eq_sym H2)) as H3.
    auto.
  - intros b H2.
    destruct b as [|z zs].
    * contradict H2; discriminate.
    * assert (y = z) as H3. {
        simpl in H2.
        assert (jsonArrayMipMap y = jsonArrayMipMap z) as H4
          by congruence.
        apply jsonArrayMipMapInjective.
        exact H4.
      }
      assert (ys = zs) as H4. {
        simpl in H2.
        assert (map jsonArrayMipMap ys = map jsonArrayMipMap zs) as H5
          by congruence.
        apply IHys.
        exact H5.
      }
      subst.
      reflexivity.
Qed.

Theorem jsonArrayMipMapListInjective : forall a b,
  jsonArrayMipMapList a = jsonArrayMipMapList b
  -> a = b.
Proof.
  intros a b Heq.
  unfold jsonArrayMipMapList in Heq.
  assert (map jsonArrayMipMap (arrayMipMaps a)
        = map jsonArrayMipMap (arrayMipMaps b)) as H0 by congruence.
  pose proof (jsonArrayMipMapMapInjective (arrayMipMaps a) (arrayMipMaps b) H0) as H1.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonCubeMapFaceInjective : forall a b,
  jsonCubeMapFace a = jsonCubeMapFace b
  -> a = b.
Proof.
  intros a b Heq.
  destruct a as [a0 a1 a2 a3].
  destruct b as [b0 b1 b2 b3].
  inversion Heq.
  pose proof (Nat2Z.inj _ _ H0).
  pose proof (Nat2Z.inj _ _ H1).
  pose proof (Nat2Z.inj _ _ H2).
  pose proof (Nat2Z.inj _ _ H3).
  subst.
  reflexivity.
Qed.

Theorem jsonCubeMipMapInjective : forall a b,
  jsonCubeMipMap a = jsonCubeMipMap b
  -> a = b.
Proof.
  intros a b Heq.
  unfold jsonCubeMipMap in Heq.
  assert (Z.of_nat (cubeMipMapLevel a) = Z.of_nat (cubeMipMapLevel b))
    as H0 by congruence.
  pose proof (Nat2Z.inj _ _ H0) as H1.
  assert (jsonCubeMapFace (cubeMapFaceXPos a)
        = jsonCubeMapFace (cubeMapFaceXPos b)) as H2 by congruence.
  pose proof (jsonCubeMapFaceInjective _ _ H2) as H3.
  assert (jsonCubeMapFace (cubeMapFaceXNeg a)
        = jsonCubeMapFace (cubeMapFaceXNeg b)) as H4 by congruence.
  pose proof (jsonCubeMapFaceInjective _ _ H4) as H5.
  assert (jsonCubeMapFace (cubeMapFaceYPos a)
        = jsonCubeMapFace (cubeMapFaceYPos b)) as H6 by congruence.
  pose proof (jsonCubeMapFaceInjective _ _ H6) as H7.
  assert (jsonCubeMapFace (cubeMapFaceYNeg a)
        = jsonCubeMapFace (cubeMapFaceYNeg b)) as H8 by congruence.
  pose proof (jsonCubeMapFaceInjective _ _ H8) as H9.
  assert (jsonCubeMapFace (cubeMapFaceZPos a)
        = jsonCubeMapFace (cubeMapFaceZPos b)) as H10 by congruence.
  pose proof (jsonCubeMapFaceInjective _ _ H10) as H11.
  assert (jsonCubeMapFace (cubeMapFaceZNeg a)
        = jsonCubeMapFace (cubeMapFaceZNeg b)) as H12 by congruence.
  pose proof (jsonCubeMapFaceInjective _ _ H12) as H13.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonCubeMipMapMapInjective : forall a b,
  map jsonCubeMipMap a = map jsonCubeMipMap b
  -> a = b.
Proof.
  induction a as [|y ys].
  - intros b H2.
    simpl in H2.
    pose proof (map_eq_nil jsonCubeMipMap b (eq_sym H2)) as H3.
    auto.
  - intros b H2.
    destruct b as [|z zs].
    * contradict H2; discriminate.
    * assert (y = z) as H3. {
        simpl in H2.
        assert (jsonCubeMipMap y = jsonCubeMipMap z) as H4
          by congruence.
        apply jsonCubeMipMapInjective.
        exact H4.
      }
      assert (ys = zs) as H4. {
        simpl in H2.
        assert (map jsonCubeMipMap ys = map jsonCubeMipMap zs) as H5
          by congruence.
        apply IHys.
        exact H5.
      }
      subst.
      reflexivity.
Qed.

Theorem jsonCubeMipMapListInjective : forall a b,
  jsonCubeMipMapList a = jsonCubeMipMapList b
  -> a = b.
Proof.
  intros a b Heq.
  unfold jsonCubeMipMapList in Heq.
  assert (map jsonCubeMipMap (cubeMipMaps a)
        = map jsonCubeMipMap (cubeMipMaps b)) as H0 by congruence.
  pose proof (jsonCubeMipMapMapInjective (cubeMipMaps a) (cubeMipMaps b) H0) as H1.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonCalino2DInjective : forall a b,
  calino2dValid a
  -> calino2dValid b
  -> jsonCalino2D a = jsonCalino2D b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [Hinfo [Hmeta [Hmip _]]].
  destruct Hvb as [Hinfo0 [Hmeta0 [Hmip0 _]]].
  unfold jsonCalino2D in Heq.
  assert (jsonImageInfo (c2dImageInfo a)
        = jsonImageInfo (c2dImageInfo b)) as H0 by congruence.
  pose proof (jsonImageInfoInjective _ _ Hinfo Hinfo0 H0) as H1.
  assert (jsonMipMapList (c2dMipMaps a)
        = jsonMipMapList (c2dMipMaps b)) as H2 by congruence.
  pose proof (jsonMipMapListInjective _ _ H2) as H3.
  assert (jsonMetadata (c2dMetadata a)
        = jsonMetadata (c2dMetadata b)) as H4 by congruence.
  pose proof (jsonMetadataInjective _ _ Hmeta Hmeta0 H4) as H5.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonCalinoCubeInjective : forall a b,
  calinoCubeValid a
  -> calinoCubeValid b
  -> jsonCalinoCube a = jsonCalinoCube b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [Hinfo [Hmeta [Hcube _]]].
  destruct Hvb as [Hinfo0 [Hmeta0 [Hcube0 _]]].
  unfold jsonCalinoCube in Heq.
  assert (jsonImageInfo (cCubeImageInfo a)
        = jsonImageInfo (cCubeImageInfo b)) as H0 by congruence.
  pose proof (jsonImageInfoInjective _ _ Hinfo Hinfo0 H0) as H1.
  assert (jsonCubeMipMapList (cCubeMipMaps a)
        = jsonCubeMipMapList (cCubeMipMaps b)) as H2 by congruence.
  pose proof (jsonCubeMipMapListInjective _ _ H2) as H3.
  assert (jsonMetadata (cCubeMetadata a)
        = jsonMetadata (cCubeMetadata b)) as H4 by congruence.
  pose proof (jsonMetadataInjective _ _ Hmeta Hmeta0 H4) as H5.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonCalinoArrayInjective : forall a b,
  calinoArrayValid a
  -> calinoArrayValid b
  -> jsonCalinoArray a = jsonCalinoArray b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct Hva as [Hinfo [Hmeta [Harray _]]].
  destruct Hvb as [Hinfo0 [Hmeta0 [Harray0 _]]].
  unfold jsonCalinoArray in Heq.
  assert (jsonImageInfo (cArrayImageInfo a)
        = jsonImageInfo (cArrayImageInfo b)) as H0 by congruence.
  pose proof (jsonImageInfoInjective _ _ Hinfo Hinfo0 H0) as H1.
  assert (jsonArrayMipMapList (cArrayMipMaps a)
        = jsonArrayMipMapList (cArrayMipMaps b)) as H2 by congruence.
  pose proof (jsonArrayMipMapListInjective _ _ H2) as H3.
  assert (jsonMetadata (cArrayMetadata a)
        = jsonMetadata (cArrayMetadata b)) as H4 by congruence.
  pose proof (jsonMetadataInjective _ _ Hmeta Hmeta0 H4) as H5.
  destruct a;
  destruct b.
  simpl in *; subst; reflexivity.
Qed.

Theorem jsonCalinoInjective : forall a b,
  calinoValid a
  -> calinoValid b
  -> jsonCalino a = jsonCalino b
  -> a = b.
Proof.
  intros a b Hva Hvb Heq.
  destruct a;
  destruct b.
  * pose proof (jsonCalino2DInjective _ _ Hva Hvb Heq) as H0.
    subst; reflexivity.
  * simpl in Heq.
    unfold jsonCalino2D in Heq.
    unfold jsonCalinoCube in Heq.
    contradict Heq.
    discriminate.
  * simpl in Heq.
    unfold jsonCalino2D in Heq.
    unfold jsonCalinoArray in Heq.
    contradict Heq.
    discriminate.
  * simpl in Heq.
    unfold jsonCalinoCube in Heq.
    unfold jsonCalino2D in Heq.
    contradict Heq.
    discriminate.
  * pose proof (jsonCalinoCubeInjective _ _ Hva Hvb Heq) as H0.
    subst; reflexivity.
  * simpl in Heq.
    unfold jsonCalinoCube in Heq.
    unfold jsonCalinoArray in Heq.
    contradict Heq.
    discriminate.
  * simpl in Heq.
    unfold jsonCalinoArray in Heq.
    unfold jsonCalino2D in Heq.
    contradict Heq.
    discriminate.
  * simpl in Heq.
    unfold jsonCalinoArray in Heq.
    unfold jsonCalinoCube in Heq.
    contradict Heq.
    discriminate.
  * pose proof (jsonCalinoArrayInjective _ _ Hva Hvb Heq) as H0.
    subst; reflexivity.
Qed.

8.20. Calino/Metadata.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.String.
From Stdlib Require Import Strings.Ascii.
From Stdlib Require Import Lists.List.

Require Import com.io7m.rlanark.Lanark.

Open Scope string_scope.

Import ListNotations.

Inductive metadataValueT : Set := MetadataValue {
  mKey   : lanarkT;
  mValue : string
}.

(** @annospec 26b591d2-24b6-4519-bcbe-f2602e090372 *)
Inductive metadataT : Set := Metadata {
  mValues : list metadataValueT
}.

(** @annospec ae704d3b-2047-41d7-807b-388f5f83a6fb *)
Definition metadataValid (m : metadataT) : Prop :=
  Forall (fun v => lanarkValidT (mKey v)) (mValues m).

Theorem metadataValidDecidable : forall m,
  {metadataValid m}+{~metadataValid m}.
Proof.
  intros m.
  unfold metadataValid.
  destruct m as [mv].
  induction mv as [|x xs].
  - left; constructor.
  - destruct (lanarkValidDecidable (mKey x)) as [H0L|H0R].
    * destruct (IHxs) as [H1L|H1R].
      -- left; constructor; auto.
      -- right; unfold not; intro H; inversion H.
         subst.
         contradiction.
    * right; unfold not; intro H; inversion H.
      subst.
      contradiction.
Qed.

8.21. Calino/MipMap.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Bool.Bool.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.ImageSize.
Require Import com.io7m.calino.NatFacts.

Import ListNotations.

Inductive mipMapT : Set := MipMap {
  mipMapLevel            : nat;
  mipMapSizeCompressed   : nat;
  mipMapSizeUncompressed : nat;
  mipMapCRC32            : nat
}.

(** @annospec 1407d7b3-e6ea-4d5c-a197-0395549924a0 *)
Inductive mipMapListIsSorted : list mipMapT -> Prop :=
  | MipsOne   : forall m, mipMapListIsSorted [m]
  | MipsCons  : forall mm0 mm1 mxs,
    mipMapLevel mm1 = S (mipMapLevel mm0) ->
      mipMapListIsSorted (mm0 :: mxs) ->
        mipMapListIsSorted (mm1 :: mm0 :: mxs).

(** @annospec 1405d68c-3c8b-4f4e-b0dd-ceac807ce92b *)
Definition mipMapListIsNonEmpty (m : list mipMapT) : Prop :=
  nil <> m.

(** @annospec 736fd3e2-7304-4bcb-bd05-fb71ea2aec57 *)
Fixpoint mipMapListLevelZero (m : list mipMapT) : Prop :=
  match m with
  | nil      => False
  | x :: nil => mipMapLevel x = 0
  | _ :: xs  => mipMapListLevelZero xs
  end.

(** @annospec b9cb87ba-4bcb-4f3b-8331-947bd939ccca *)
Definition mipMapListMaxLevelBounded
  (m           : list mipMapT)
  (sizeX sizeY : nat)
: Prop :=
  match m with
  | nil    => True
  | x :: _ => (2 ^ mipMapLevel x) <= sizeX /\ (2 ^ mipMapLevel x) <= sizeY
  end.

(** @annospec 4ec61686-9065-490c-9028-d628c63ba26b *)
Inductive mipMapListT : Set := MipMapList {
  mipMaps : list mipMapT;
}.

(** @annospec 8dd86cb6-14c4-482b-874f-41d5c8a565dd *)
Definition mipMapListValid (m : mipMapListT) (sizeX sizeY : nat) : Prop :=
     mipMapListIsSorted (mipMaps m) 
  /\ mipMapListIsNonEmpty (mipMaps m)
  /\ mipMapListLevelZero (mipMaps m)
  /\ mipMapListMaxLevelBounded (mipMaps m) sizeX sizeY.

Theorem mipMapListIsSortedDecidable : forall m,
  {mipMapListIsSorted m}+{~mipMapListIsSorted m}.
Proof.
  induction m as [|y ys IHys].
  * right.
    unfold not; intro H; inversion H.
  * destruct IHys as [HL|HR].
    ** destruct ys as [|x xs].
       *** left; constructor.
       *** destruct (Nat.eq_dec (mipMapLevel y) (S (mipMapLevel x))) as [HnL|HnR].
           **** left; constructor; auto.
           **** right.
                unfold not; intro H; inversion H.
                contradiction.
    ** destruct ys as [|x xs].
       *** left; constructor.
       *** right;
           unfold not; intro H; inversion H.
           contradiction.
Qed.

Theorem mipMapListIsNonEmptyDecidable : forall m,
  {mipMapListIsNonEmpty m}+{~mipMapListIsNonEmpty m}.
Proof.
  unfold mipMapListIsNonEmpty.
  destruct m.
  * right; intuition.
  * left; discriminate.
Qed.

Theorem mipMapListLevelZeroDecidable : forall m,
  {mipMapListLevelZero m}+{~mipMapListLevelZero m}.
Proof.
  induction m as [|y ys].
  - right; intuition.
  - destruct ys as [|x xs].
    * unfold mipMapListLevelZero.
      apply Nat.eq_dec.
    * destruct IHys as [HL|HR].
      ** left; exact HL.
      ** right; intuition.
Qed.

Theorem mipMapListMaxLevelBoundedDecidable : forall m sizeX sizeY,
  {mipMapListMaxLevelBounded m sizeX sizeY}+{~mipMapListMaxLevelBounded m sizeX sizeY}.
Proof.
  destruct m as [|mm mms].
  - left; constructor.
  - intros sizeX sizeY.
    simpl.
    destruct (le_dec (2 ^ mipMapLevel mm) sizeX).
    destruct (le_dec (2 ^ mipMapLevel mm) sizeY).
    * left; intuition.
    * right; intuition.
    * right; intuition.
Qed.

Theorem mipMapListValidDecidable : forall m sizeX sizeY,
  {mipMapListValid m sizeX sizeY}+{~mipMapListValid m sizeX sizeY}.
Proof.
  unfold mipMapListValid.
  intros m sizeX sizeY.
  destruct (mipMapListIsSortedDecidable (mipMaps m));
  destruct (mipMapListIsNonEmptyDecidable (mipMaps m));
  destruct (mipMapListLevelZeroDecidable (mipMaps m));
  destruct (mipMapListMaxLevelBoundedDecidable (mipMaps m) sizeX sizeY);
  intuition.
Qed.

8.22. Calino/NatFacts.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Lia.

Lemma lt_neq : forall n, 0 <> n <-> 0 < n.
Proof.
  intros n.
  constructor.
  - intro Hneq.
    induction n as [|k].
    -- unfold not in Hneq.
       assert (0 = 0) as Heq by reflexivity.
       contradiction.
    -- apply (Nat.lt_0_succ k).
  - intro Hneq.
    induction n as [|k].
    -- inversion Hneq.
    -- discriminate.
Qed.

Lemma lt_neq_0 : forall n, 0 <> n -> 0 < n.
Proof.
  intros n Hneq.
  rewrite <- lt_neq; trivial.
Qed.

Lemma lt_neq_1 : forall n, 0 < n -> 0 <> n.
Proof.
  intros n Hneq.
  rewrite lt_neq; trivial.
Qed.

Lemma lt_dec : forall n m,
  {n < m}+{~n < m}.
Proof.
  induction n as [|p].
  * destruct m as [|r].
    ** right; lia.
    ** left; lia.
  * destruct m as [|r].
    ** right; lia.
    ** destruct (IHp r) as [HL|HR].
       *** left; lia.
       *** right; lia.
Qed.

Lemma le_dec : forall n m,
  {n <= m}+{~n <= m}.
Proof.
  induction n as [|p].
  * destruct m as [|r].
    ** left; lia.
    ** left; lia.
  * destruct m as [|r].
    ** right; lia.
    ** destruct (IHp r) as [HL|HR].
       *** left; lia.
       *** right; lia.
Qed.

8.23. Calino/StandardFormatFacts.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Lists.List.
From Stdlib Require Import Lia.

Require Import com.io7m.calino.ChannelDescription.
Require Import com.io7m.calino.StandardFormats.

Import ListNotations.

Theorem A1Valid : channelDescriptionValid A1.
Proof. constructor; simpl; lia. Qed.

Theorem R5Valid : channelDescriptionValid R5.
Proof. constructor; simpl; lia. Qed.
Theorem G6Valid : channelDescriptionValid G6.
Proof. constructor; simpl; lia. Qed.
Theorem B5Valid : channelDescriptionValid B5.
Proof. constructor; simpl; lia. Qed.

Theorem G5Valid : channelDescriptionValid G5.
Proof. constructor; simpl; lia. Qed.

Theorem R4Valid : channelDescriptionValid R4.
Proof. constructor; simpl; lia. Qed.
Theorem G4Valid : channelDescriptionValid G4.
Proof. constructor; simpl; lia. Qed.
Theorem B4Valid : channelDescriptionValid B4.
Proof. constructor; simpl; lia. Qed.
Theorem A4Valid : channelDescriptionValid A4.
Proof. constructor; simpl; lia. Qed.

Theorem R8Valid : channelDescriptionValid R8.
Proof. constructor; simpl; lia. Qed.
Theorem G8Valid : channelDescriptionValid G8.
Proof. constructor; simpl; lia. Qed.
Theorem B8Valid : channelDescriptionValid B8.
Proof. constructor; simpl; lia. Qed.
Theorem A8Valid : channelDescriptionValid A8.
Proof. constructor; simpl; lia. Qed.

Definition R8_Div8 : channelDescriptionBitsDivisible8 R8 := eq_refl.
Definition G8_Div8 : channelDescriptionBitsDivisible8 G8 := eq_refl.
Definition B8_Div8 : channelDescriptionBitsDivisible8 B8 := eq_refl.
Definition A8_Div8 : channelDescriptionBitsDivisible8 A8 := eq_refl.

Theorem R16Valid : channelDescriptionValid R16.
Proof. constructor; simpl; lia. Qed.
Theorem G16Valid : channelDescriptionValid G16.
Proof. constructor; simpl; lia. Qed.
Theorem B16Valid : channelDescriptionValid B16.
Proof. constructor; simpl; lia. Qed.
Theorem A16Valid : channelDescriptionValid A16.
Proof. constructor; simpl; lia. Qed.

Definition R16_Div8 : channelDescriptionBitsDivisible8 R16 := eq_refl.
Definition G16_Div8 : channelDescriptionBitsDivisible8 G16 := eq_refl.
Definition B16_Div8 : channelDescriptionBitsDivisible8 B16 := eq_refl.
Definition A16_Div8 : channelDescriptionBitsDivisible8 A16 := eq_refl.

Theorem R32Valid : channelDescriptionValid R32.
Proof. constructor; simpl; lia. Qed.
Theorem G32Valid : channelDescriptionValid G32.
Proof. constructor; simpl; lia. Qed.
Theorem B32Valid : channelDescriptionValid B32.
Proof. constructor; simpl; lia. Qed.
Theorem A32Valid : channelDescriptionValid A32.
Proof. constructor; simpl; lia. Qed.

Definition R32_Div8 : channelDescriptionBitsDivisible8 R32 := eq_refl.
Definition G32_Div8 : channelDescriptionBitsDivisible8 G32 := eq_refl.
Definition B32_Div8 : channelDescriptionBitsDivisible8 B32 := eq_refl.
Definition A32_Div8 : channelDescriptionBitsDivisible8 A32 := eq_refl.

Theorem R64Valid : channelDescriptionValid R64.
Proof. constructor; simpl; lia. Qed.
Theorem G64Valid : channelDescriptionValid G64.
Proof. constructor; simpl; lia. Qed.
Theorem B64Valid : channelDescriptionValid B64.
Proof. constructor; simpl; lia. Qed.
Theorem A64Valid : channelDescriptionValid A64.
Proof. constructor; simpl; lia. Qed.

Definition R64_Div8 : channelDescriptionBitsDivisible8 R64 := eq_refl.
Definition G64_Div8 : channelDescriptionBitsDivisible8 G64 := eq_refl.
Definition B64_Div8 : channelDescriptionBitsDivisible8 B64 := eq_refl.
Definition A64_Div8 : channelDescriptionBitsDivisible8 A64 := eq_refl.

(* Packed channels *)

Definition A1_R5_G5_B5_NonEmpty := nil_cons (x := A1) (l := [R5; G5; B5]).

Definition R4_G4_B4_A4_NonEmpty := nil_cons (x := R4) (l := [G4; B4; A4]).

Definition R5_G6_B5_NonEmpty := nil_cons (x := R5) (l := [G6; B5]).

(* 8-bit channels *)

Definition R8_G8_B8_A8_NonEmpty := nil_cons (x := R8) (l := [G8; B8; A8]).
Definition R8_G8_B8_A8_FDiv8 : Forall channelDescriptionBitsDivisible8 R8_G8_B8_A8_Channels :=
  Forall_cons R8 R8_Div8
 (Forall_cons G8 G8_Div8
 (Forall_cons B8 B8_Div8
 (Forall_cons A8 A8_Div8
 (Forall_nil _)))).

Definition R8_G8_B8_NonEmpty := nil_cons (x := R8) (l := [G8;B8]).
Definition R8_G8_B8_FDiv8 : Forall channelDescriptionBitsDivisible8 R8_G8_B8_Channels :=
  Forall_cons R8 R8_Div8
 (Forall_cons G8 G8_Div8
 (Forall_cons B8 B8_Div8
 (Forall_nil _))).

Definition R8_G8_NonEmpty := nil_cons (x := R8) (l := [G8]).
Definition R8_G8_FDiv8 : Forall channelDescriptionBitsDivisible8 R8_G8_Channels :=
  Forall_cons R8 R8_Div8
 (Forall_cons G8 G8_Div8
 (Forall_nil _)).

Definition R8_NonEmpty := nil_cons (x := R8) (l := []).
Definition R8_FDiv8 : Forall channelDescriptionBitsDivisible8 R8_Channels :=
  Forall_cons R8 R8_Div8 (Forall_nil _).

(* 16-bit channels *)

Definition R16_G16_B16_A16_NonEmpty := nil_cons (x := R16) (l := [G16; B16; A16]).
Definition R16_G16_B16_A16_FDiv8 : Forall channelDescriptionBitsDivisible8 R16_G16_B16_A16_Channels :=
  Forall_cons R16 R16_Div8
 (Forall_cons G16 G16_Div8
 (Forall_cons B16 B16_Div8
 (Forall_cons A16 A16_Div8
 (Forall_nil _)))).

Definition R16_G16_B16_NonEmpty := nil_cons (x := R16) (l := [G16;B16]).
Definition R16_G16_B16_FDiv8 : Forall channelDescriptionBitsDivisible8 R16_G16_B16_Channels :=
  Forall_cons R16 R16_Div8
 (Forall_cons G16 G16_Div8
 (Forall_cons B16 B16_Div8
 (Forall_nil _))).

Definition R16_G16_NonEmpty := nil_cons (x := R16) (l := [G16]).
Definition R16_G16_FDiv8 : Forall channelDescriptionBitsDivisible8 R16_G16_Channels :=
  Forall_cons R16 R16_Div8
 (Forall_cons G16 G16_Div8
 (Forall_nil _)).

Definition R16_NonEmpty := nil_cons (x := R16) (l := []).
Definition R16_FDiv8 : Forall channelDescriptionBitsDivisible8 R16_Channels :=
  Forall_cons R16 R16_Div8 (Forall_nil _).

(* 32-bit channels *)

Definition R32_G32_B32_A32_NonEmpty := nil_cons (x := R32) (l := [G32; B32; A32]).
Definition R32_G32_B32_A32_FDiv8 : Forall channelDescriptionBitsDivisible8 R32_G32_B32_A32_Channels :=
  Forall_cons R32 R32_Div8
 (Forall_cons G32 G32_Div8
 (Forall_cons B32 B32_Div8
 (Forall_cons A32 A32_Div8
 (Forall_nil _)))).

Definition R32_G32_B32_NonEmpty := nil_cons (x := R32) (l := [G32;B32]).
Definition R32_G32_B32_FDiv8 : Forall channelDescriptionBitsDivisible8 R32_G32_B32_Channels :=
  Forall_cons R32 R32_Div8
 (Forall_cons G32 G32_Div8
 (Forall_cons B32 B32_Div8
 (Forall_nil _))).

Definition R32_G32_NonEmpty := nil_cons (x := R32) (l := [G32]).
Definition R32_G32_FDiv8 : Forall channelDescriptionBitsDivisible8 R32_G32_Channels :=
  Forall_cons R32 R32_Div8
 (Forall_cons G32 G32_Div8
 (Forall_nil _)).

Definition R32_NonEmpty := nil_cons (x := R32) (l := []).
Definition R32_FDiv8 : Forall channelDescriptionBitsDivisible8 R32_Channels :=
  Forall_cons R32 R32_Div8 (Forall_nil _).

(* 64-bit channels *)

Definition R64_G64_B64_A64_NonEmpty := nil_cons (x := R64) (l := [G64; B64; A64]).
Definition R64_G64_B64_A64_FDiv8 : Forall channelDescriptionBitsDivisible8 R64_G64_B64_A64_Channels :=
  Forall_cons R64 R64_Div8
 (Forall_cons G64 G64_Div8
 (Forall_cons B64 B64_Div8
 (Forall_cons A64 A64_Div8
 (Forall_nil _)))).

Definition R64_G64_B64_NonEmpty := nil_cons (x := R64) (l := [G64;B64]).
Definition R64_G64_B64_FDiv8 : Forall channelDescriptionBitsDivisible8 R64_G64_B64_Channels :=
  Forall_cons R64 R64_Div8
 (Forall_cons G64 G64_Div8
 (Forall_cons B64 B64_Div8
 (Forall_nil _))).

Definition R64_G64_NonEmpty := nil_cons (x := R64) (l := [G64]).
Definition R64_G64_FDiv8 : Forall channelDescriptionBitsDivisible8 R64_G64_Channels :=
  Forall_cons R64 R64_Div8
 (Forall_cons G64 G64_Div8
 (Forall_nil _)).

Definition R64_NonEmpty := nil_cons (x := R64) (l := []).
Definition R64_FDiv8 : Forall channelDescriptionBitsDivisible8 R64_Channels :=
  Forall_cons R64 R64_Div8 (Forall_nil _).





(* Layouts *)

Theorem Layout_A1_R5_G5_B5Valid : channelLayoutDescriptionValidT Layout_A1_R5_G5_B5.
Proof.
  simpl.
  repeat constructor.
  - exact A1_R5_G5_B5_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R4_G4_B4_A4Valid : channelLayoutDescriptionValidT Layout_R4_G4_B4_A4.
Proof.
  simpl.
  repeat constructor.
  - exact R4_G4_B4_A4_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R5_G6_B5Valid : channelLayoutDescriptionValidT Layout_R5_G6_B5.
Proof.
  simpl.
  repeat constructor.
  - exact R5_G6_B5_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R8_G8_B8_A8Valid : channelLayoutDescriptionValidT Layout_R8_G8_B8_A8.
Proof.
  simpl.
  repeat constructor.
  - exact R8_G8_B8_A8_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R8_G8_B8Valid : channelLayoutDescriptionValidT Layout_R8_G8_B8.
Proof.
  simpl.
  repeat constructor.
  - exact R8_G8_B8_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R8_G8Valid : channelLayoutDescriptionValidT Layout_R8_G8.
Proof.
  simpl.
  repeat constructor.
  - exact R8_G8_NonEmpty.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R8Valid : channelLayoutDescriptionValidT Layout_R8.
Proof.
  simpl.
  repeat constructor.
  - exact R8_NonEmpty.
  - cbn; lia.
Qed.

Theorem Layout_R16_G16_B16_A16Valid : channelLayoutDescriptionValidT Layout_R16_G16_B16_A16.
Proof.
  simpl.
  repeat constructor.
  - exact R16_G16_B16_A16_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R16_G16_B16Valid : channelLayoutDescriptionValidT Layout_R16_G16_B16.
Proof.
  simpl.
  repeat constructor.
  - exact R16_G16_B16_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R16_G16Valid : channelLayoutDescriptionValidT Layout_R16_G16.
Proof.
  simpl.
  repeat constructor.
  - exact R16_G16_NonEmpty.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R16Valid : channelLayoutDescriptionValidT Layout_R16.
Proof.
  simpl.
  repeat constructor.
  - exact R16_NonEmpty.
  - cbn; lia.
Qed.

Theorem Layout_R32_G32_B32_A32Valid : channelLayoutDescriptionValidT Layout_R32_G32_B32_A32.
Proof.
  simpl.
  repeat constructor.
  - exact R32_G32_B32_A32_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R32_G32_B32Valid : channelLayoutDescriptionValidT Layout_R32_G32_B32.
Proof.
  simpl.
  repeat constructor.
  - exact R32_G32_B32_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R32_G32Valid : channelLayoutDescriptionValidT Layout_R32_G32.
Proof.
  simpl.
  repeat constructor.
  - exact R32_G32_NonEmpty.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R32Valid : channelLayoutDescriptionValidT Layout_R32.
Proof.
  simpl.
  repeat constructor.
  - exact R32_NonEmpty.
  - cbn; lia.
Qed.

Theorem Layout_R64_G64_B64_A64Valid : channelLayoutDescriptionValidT Layout_R64_G64_B64_A64.
Proof.
  simpl.
  repeat constructor.
  - exact R64_G64_B64_A64_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R64_G64_B64Valid : channelLayoutDescriptionValidT Layout_R64_G64_B64.
Proof.
  simpl.
  repeat constructor.
  - exact R64_G64_B64_NonEmpty.
  - cbn; lia.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R64_G64Valid : channelLayoutDescriptionValidT Layout_R64_G64.
Proof.
  simpl.
  repeat constructor.
  - exact R64_G64_NonEmpty.
  - cbn; lia.
  - cbn; lia.
Qed.

Theorem Layout_R64Valid : channelLayoutDescriptionValidT Layout_R64.
Proof.
  simpl.
  repeat constructor.
  - exact R64_NonEmpty.
  - cbn; lia.
Qed.

8.24. Calino/StandardFormats.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Lists.List.

Require Import com.io7m.calino.ChannelDescription.
Require Import com.io7m.calino.ChannelSemantic.
Require Import com.io7m.calino.ChannelType.

Import ListNotations.

Open Scope Z_scope.

Definition A1 : channelDescriptionT := ChannelDescription CSAlpha 1.

Definition R5 : channelDescriptionT := ChannelDescription CSRed   5.
Definition G6 : channelDescriptionT := ChannelDescription CSGreen 6.
Definition B5 : channelDescriptionT := ChannelDescription CSBlue  5.

Definition G5 : channelDescriptionT := ChannelDescription CSGreen 5.

Definition R4 : channelDescriptionT := ChannelDescription CSRed   4.
Definition G4 : channelDescriptionT := ChannelDescription CSGreen 4.
Definition B4 : channelDescriptionT := ChannelDescription CSBlue  4.
Definition A4 : channelDescriptionT := ChannelDescription CSAlpha 4.

Definition R8 : channelDescriptionT := ChannelDescription CSRed   8.
Definition G8 : channelDescriptionT := ChannelDescription CSGreen 8.
Definition B8 : channelDescriptionT := ChannelDescription CSBlue  8.
Definition A8 : channelDescriptionT := ChannelDescription CSAlpha 8.

Definition R16 : channelDescriptionT := ChannelDescription CSRed   16.
Definition G16 : channelDescriptionT := ChannelDescription CSGreen 16.
Definition B16 : channelDescriptionT := ChannelDescription CSBlue  16.
Definition A16 : channelDescriptionT := ChannelDescription CSAlpha 16.

Definition R32 : channelDescriptionT := ChannelDescription CSRed   32.
Definition G32 : channelDescriptionT := ChannelDescription CSGreen 32.
Definition B32 : channelDescriptionT := ChannelDescription CSBlue  32.
Definition A32 : channelDescriptionT := ChannelDescription CSAlpha 32.

Definition R64 : channelDescriptionT := ChannelDescription CSRed   64.
Definition G64 : channelDescriptionT := ChannelDescription CSGreen 64.
Definition B64 : channelDescriptionT := ChannelDescription CSBlue  64.
Definition A64 : channelDescriptionT := ChannelDescription CSAlpha 64.

(* Packed channels *)

Definition A1_R5_G5_B5_Channels : list channelDescriptionT := [A1; R5; G5; B5].

Definition R4_G4_B4_A4_Channels : list channelDescriptionT := [R4; G4; B4; A4].

Definition R5_G6_B5_Channels : list channelDescriptionT := [R5; G6; B5].

(* 8-bit channels *)

Definition R8_G8_B8_A8_Channels : list channelDescriptionT := [R8; G8; B8; A8].

Definition R8_G8_B8_Channels : list channelDescriptionT := [R8; G8; B8].

Definition R8_G8_Channels : list channelDescriptionT := [R8; G8].

Definition R8_Channels : list channelDescriptionT := [R8].

(* 16-bit channels *)

Definition R16_G16_B16_A16_Channels : list channelDescriptionT := [R16; G16; B16; A16].

Definition R16_G16_B16_Channels : list channelDescriptionT := [R16; G16; B16].

Definition R16_G16_Channels : list channelDescriptionT := [R16; G16].

Definition R16_Channels : list channelDescriptionT := [R16].

(* 32-bit channels *)

Definition R32_G32_B32_A32_Channels : list channelDescriptionT := [R32; G32; B32; A32].

Definition R32_G32_B32_Channels : list channelDescriptionT := [R32; G32; B32].

Definition R32_G32_Channels : list channelDescriptionT := [R32; G32].

Definition R32_Channels : list channelDescriptionT := [R32].

(* 64-bit channels *)

Definition R64_G64_B64_A64_Channels : list channelDescriptionT := [R64; G64; B64; A64].

Definition R64_G64_B64_Channels : list channelDescriptionT := [R64; G64; B64].

Definition R64_G64_Channels : list channelDescriptionT := [R64; G64].

Definition R64_Channels : list channelDescriptionT := [R64].

(* Layouts *)

Definition Layout_A1_R5_G5_B5 : channelLayoutDescriptionT :=
  CLDPacked (ChannelLayoutDescriptionPacked A1_R5_G5_B5_Channels CLPack16).

Definition Layout_R4_G4_B4_A4 : channelLayoutDescriptionT :=
  CLDPacked (ChannelLayoutDescriptionPacked R4_G4_B4_A4_Channels CLPack16).

Definition Layout_R5_G6_B5 : channelLayoutDescriptionT :=
  CLDPacked (ChannelLayoutDescriptionPacked R5_G6_B5_Channels CLPack16).

Definition Layout_R8_G8_B8_A8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_G8_B8_A8_Channels).

Definition Layout_R8_G8_B8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_G8_B8_Channels).

Definition Layout_R8_G8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_G8_Channels).

Definition Layout_R8 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R8_Channels).

Definition Layout_R16_G16_B16_A16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_G16_B16_A16_Channels).

Definition Layout_R16_G16_B16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_G16_B16_Channels).

Definition Layout_R16_G16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_G16_Channels).

Definition Layout_R16 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R16_Channels).

Definition Layout_R32_G32_B32_A32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_G32_B32_A32_Channels).

Definition Layout_R32_G32_B32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_G32_B32_Channels).

Definition Layout_R32_G32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_G32_Channels).

Definition Layout_R32 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R32_Channels).

Definition Layout_R64_G64_B64_A64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_G64_B64_A64_Channels).

Definition Layout_R64_G64_B64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_G64_B64_Channels).

Definition Layout_R64_G64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_G64_Channels).

Definition Layout_R64 : channelLayoutDescriptionT :=
  CLDUnpacked (ChannelLayoutDescriptionUnpacked R64_Channels).

8.25. Calino/SuperCompression.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import ZArith.
From Stdlib Require Import Strings.String.

Require Import com.io7m.calino.Descriptor.
Require Import com.io7m.rlanark.Lanark.

Inductive superCompressionUncompressedT : Set :=
  SuperCompressionUncompressed.

Inductive superCompressionLZ4T : Set :=
  SuperCompressionLZ4.

Inductive superCompressionDEFLATET : Set :=
  SuperCompressionDEFLATE.

Inductive superCompressionCustomT : Set :=
  SuperCompressionCustom {
    superCustomId                : lanarkT;
    superCustomSectionIdentifier : Z
  }.

(** @annospec c0e7a860-3ab8-44cb-b478-b3ebf97b55aa *)
Inductive superCompressionMethodT : Set :=
  | SCUncompressed : superCompressionUncompressedT -> superCompressionMethodT
  | SCLZ4          : superCompressionLZ4T -> superCompressionMethodT
  | SCDEFLATE      : superCompressionDEFLATET -> superCompressionMethodT
  | SCCustom       : superCompressionCustomT -> superCompressionMethodT.

Definition superCompressionMethodDescribe (c : superCompressionMethodT) :=
  match c with
  | SCUncompressed _ => calinoReservedDescriptor "uncompressed"
  | SCLZ4 _          => calinoReservedDescriptor "lz4"
  | SCDEFLATE _      => calinoReservedDescriptor "deflate"
  | SCCustom t       => superCustomId t
  end.

(** @annospec fbc562f7-264a-4d6d-b2fb-1ff12931ffb7 *)
Definition superCompressionMethodValid (c : superCompressionMethodT) : Prop :=
  match c with
  | SCUncompressed _ => True
  | SCLZ4 _          => True
  | SCDEFLATE _      => True
  | SCCustom t       => (~isCalinoReservedDescriptor (superCustomId t)) /\ lanarkValidT (superCustomId t)
  end.


Definition superCompressionSectionIdentifier (c : superCompressionMethodT) : Z :=
  match c with
  | SCUncompressed _ => 0
  | SCLZ4 _          => 0
  | SCDEFLATE _      => 0
  | SCCustom t       => superCustomSectionIdentifier t
  end.

Theorem superCompressionMethodDescribeValid : forall (c : superCompressionMethodT),
  superCompressionMethodValid c ->
  match c with
  | SCCustom t => lanarkValidT (superCustomId t)
  | _          => lanarkValidT (superCompressionMethodDescribe c)
  end.
Proof.
  intros c Hc.
  destruct c; (try (apply isCalinoReservedDescriptorValid; constructor; repeat lanarkSegmentSolve)).
  destruct Hc; auto.
Qed.

Theorem superCompressionMethodValidDecidable : forall c,
  {superCompressionMethodValid c}+{~superCompressionMethodValid c}.
Proof.
  unfold superCompressionMethodValid.
  destruct c;
    try (left; auto || fail).

  destruct (lanarkValidDecidable (superCustomId s));
    destruct (isCalinoReservedDescriptorDecidable (superCustomId s));
      intuition.
Qed.

8.26. rentomos/src/main/rocq/Alignment.v

(*
 * Copyright © 2025 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

Require Import Stdlib.Arith.PeanoNat.

(** * Alignment *)

(** Return _size_ scaled such that it is a multiple of _q_. *)
Definition asMultipleOf (size q : nat) (Hnz : 0 <> q) : nat :=
  let r := size / q in
    match Nat.ltb_spec0 r q with
    | ReflectT _ _ => (r + 1) * q
    | ReflectF _ _ => r * q
    end.

#[local]
Lemma p0not4 : 0 <> 4.
Proof. discriminate. Qed.

#[local]
Lemma p0not16 : 0 <> 16.
Proof. discriminate. Qed.

(** Return _size_ scaled such that it is a multiple of 4. *)
Definition asMultipleOf4 (size : nat) : nat :=
  asMultipleOf size 4 p0not4.

(** Return _size_ scaled such that it is a multiple of 6. *)
Definition asMultipleOf16 (size : nat) : nat :=
  asMultipleOf size 16 p0not16.

(** If _n_ is a multiple of _m_, then _n mod m = 0_. *)
Lemma asMultipleOfMod : forall s q (Hneq : 0 <> q), (asMultipleOf s q Hneq) mod q = 0.
Proof.
  intros s q Hneq.
  unfold asMultipleOf.
  destruct (Nat.ltb_spec0 (s / q) q) as [Hlt|H1].
  - apply (Nat.Div0.mod_mul (s / q + 1) q).
  - apply (Nat.Div0.mod_mul (s / q) q).
Qed.

8.27. rentomos/src/main/rocq/Binary.v

(*
 * Copyright © 2025 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Reals.
From Stdlib Require Import Strings.String.
From Stdlib Require Import Strings.Byte.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Program.Basics.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Psatz.

Import ListNotations.

Local Open Scope string_scope.

Require Import com.io7m.rentomos.Alignment.
Require Import com.io7m.rentomos.Divisible.

(** The type of stream elements. *)
Inductive streamE : Set :=
  (** A 64-bit IEEE754 binary64 value. *)
  | Vf64 : R -> streamE
  (** A 64-bit unsigned integer. *)
  | Vu64 : nat -> streamE
  (** A 32-bit unsigned integer. *)
  | Vu32 : nat -> streamE
  (** An 8-bit unsigned integer. *)
  | Vu8  : nat -> streamE.

Definition u8byte (b : byte) : streamE :=
  Vu8 (Byte.to_nat b).

Definition streamEIsU8 (e : streamE) : Prop :=
  match e with
  | Vf64 _ => False
  | Vu64 _ => False
  | Vu32 _ => False
  | Vu8  _ => True
  end.

(** A proposition that describes a well-formed stream. *)
Inductive streamWellFormed : list streamE -> Prop :=
  (** An empty stream is well-formed. *)
  | BEPEmpty  : streamWellFormed []
  (** A stream consisting of a single 64-bit float is well-formed. *)
  | BEPVf64   : forall k, streamWellFormed [Vf64 k]
  (** A stream consisting of a single 64-bit integer is well-formed. *)
  | BEPVu64   : forall k, streamWellFormed [Vu64 k]
  (** A stream consisting of a single 32-bit integer is well-formed. *)
  | BEPVu32   : forall k, streamWellFormed [Vu32 k]
  (** A stream consisting of a number of 8-bit values of a length divisible by 4 is well-formed. *)
  | BEPVu8s   : forall es, Forall streamEIsU8 es -> length (es) mod 4 = 0 -> streamWellFormed es
  (** The concatenation of two well-formed streams is well-formed. *)
  | BEPAppend : forall xs ys, streamWellFormed xs -> streamWellFormed ys -> streamWellFormed (xs ++ ys).

(** The size in octets of a stream element. *)
Definition streamElementSize (s : streamE) : nat :=
  match s with
  | Vf64 _ => 8
  | Vu64 _ => 8
  | Vu32 _ => 4
  | Vu8  _ => 1
  end.

(** The size of a stream is the sum of the size of its elements. *)
Definition streamSize (s : list streamE) : nat :=
  fold_right plus 0 (map streamElementSize s).

Section binaryExpressions.
  Local Unset Elimination Schemes.

  (** The binary expression type. *)
  Inductive binaryExp : Set :=
    (** A 32-bit unsigned integer. *)
    | BiU32     : nat -> binaryExp
    (** A 64-bit unsigned integer. *)
    | BiU64     : nat -> binaryExp
    (** A 64-bit IEEE754 binary64 value. *)
    | BiF64     : R -> binaryExp
    (** A sequence of bytes. *)
    | BiBytes   : list byte -> binaryExp
    (** A sequence of bytes describing UTF-8 encoded text. *)
    | BiUTF8    : list byte -> binaryExp
    (** An array of binary expressions. *)
    | BiArray   : list binaryExp -> binaryExp
    (** A section of reserved space. *)
    | BiReserve : nat -> binaryExp
    (** A record with named binary expression members. *)
    | BiRecord  : list (string * binaryExp) -> binaryExp.

  Section binaryExp_rect.
    Variable P             : binaryExp -> Type.
    Variable P_list        : list binaryExp -> Type.
    Hypothesis P_nil       : P_list [].
    Hypothesis P_cons      : forall x xs, P x -> P_list xs -> P_list (x :: xs).
    Hypothesis P_BiU32     : forall x, P (BiU32 x).
    Hypothesis P_BiU64     : forall x, P (BiU64 x).
    Hypothesis P_BiF64     : forall x, P (BiF64 x).
    Hypothesis P_BiBytes   : forall bs, P (BiBytes bs).
    Hypothesis P_BiUTF8    : forall bs, P (BiUTF8 bs).
    Hypothesis P_BiArray   : forall bs, P_list bs -> P (BiArray bs).
    Hypothesis P_BiReserve : forall x, P (BiReserve x).
    Hypothesis P_BiRecord  : forall fs, P_list (map snd fs) -> P (BiRecord fs).

    Fixpoint binaryExp_rect (b : binaryExp) : P b :=
      let
        fix expForAll (xs : list binaryExp) : P_list xs :=
          match xs as rxs return (P_list rxs) with
          | []        => @P_nil
          | (y :: ys) => @P_cons y ys (binaryExp_rect y) (expForAll ys)
          end
      in let
        fix forAllSnd (fs : list (string * binaryExp)) : P_list (map snd fs) :=
          match fs as rf return P_list (map snd rf) with
          | []             => @P_nil
          | ((_, y) :: ys) => @P_cons y (map snd ys) (binaryExp_rect y) (forAllSnd ys)
          end
      in
        match b with
        | BiU32 c     => P_BiU32 c
        | BiU64 c     => P_BiU64 c
        | BiF64 c     => P_BiF64 c
        | BiBytes bs  => P_BiBytes bs
        | BiUTF8 bs   => P_BiUTF8 bs
        | BiArray es  => P_BiArray es (expForAll es)
        | BiReserve c => P_BiReserve c
        | BiRecord fs => P_BiRecord fs (forAllSnd fs)
        end.
  End binaryExp_rect.

  Section binaryExp_ind.
    Variable P             : binaryExp -> Prop.
    Hypothesis P_BiU32     : forall x, P (BiU32 x).
    Hypothesis P_BiU64     : forall x, P (BiU64 x).
    Hypothesis P_BiF64     : forall x, P (BiF64 x).
    Hypothesis P_BiBytes   : forall bs, P (BiBytes bs).
    Hypothesis P_BiUTF8    : forall bs, P (BiUTF8 bs).
    Hypothesis P_BiArray   : forall bs, Forall P bs -> P (BiArray bs).
    Hypothesis P_BiReserve : forall x, P (BiReserve x).
    Hypothesis P_BiRecord  : forall fs, Forall P (map snd fs) -> P (BiRecord fs).

    Definition binaryExp_ind (b : binaryExp) : P b :=
      binaryExp_rect
        P
        (Forall P)
        (Forall_nil P)
        (Forall_cons (P:=P)) 
        P_BiU32
        P_BiU64
        P_BiF64
        P_BiBytes
        P_BiUTF8
        P_BiArray
        P_BiReserve
        P_BiRecord
        b.
  End binaryExp_ind.
End binaryExpressions.

(** The size of a binary expression in octets. *)
Fixpoint binarySize (b : binaryExp) : nat :=
  match b with
  | BiU32 _     => 4
  | BiU64 _     => 8
  | BiF64 _     => 8
  | BiBytes s   => 4 + asMultipleOf4 (length s)
  | BiUTF8 s    => 4 + asMultipleOf4 (length s)
  | BiArray f   => 4 + fold_right plus 0 (map binarySize f)
  | BiReserve s => asMultipleOf4 s
  | BiRecord f  => fold_right plus 0 (map (compose binarySize snd) f)
  end.

Definition binaryEvalPaddedBytes
  (b     : list byte)
  (align : nat)
  (pad   : byte)
  (Hneq  : 0 <> align)
: list streamE :=
  let vremaining := length b mod align in
    match vremaining with
    | 0 => map u8byte b
    | _ => map u8byte (b ++ repeat pad (align - vremaining))
    end.

(** The binary evaluation function; produces a stream from an expression. *)
Fixpoint binaryEval (b : binaryExp) (pad: byte) : list streamE :=
  match b with
  | BiU32 k     => [Vu32 k]
  | BiU64 k     => [Vu64 k] 
  | BiF64 k     => [Vf64 k]
  | BiBytes s   => (Vu32 (length s)) :: (binaryEvalPaddedBytes s 4 pad Alignment.p0not4)
  | BiUTF8 s    => (Vu32 (length s)) :: (binaryEvalPaddedBytes s 4 pad Alignment.p0not4)
  | BiArray f   => (Vu32 (length f)) :: concat (map (fun e => binaryEval e pad) f)
  | BiReserve s => repeat (u8byte pad) (asMultipleOf4 s)
  | BiRecord f  => concat (map (compose (fun e => binaryEval e pad) snd) f)
  end.

(** The size of a binary expression padded to 16 octet alignment. *)
Definition binarySizePadded16 (b : binaryExp) : nat :=
  asMultipleOf16 (binarySize b).

(** Shorthand for UTF-8 strings. *)
Definition utf8 (s : string) : binaryExp :=
  BiUTF8 (list_byte_of_string s).

(** Shorthand for integer types. *)
Definition u32 := BiU32.
(** Shorthand for integer types. *)
Definition u64 := BiU64.
(** Shorthand for real types. *)
Definition f64 := BiF64.

Lemma fold_right_add_cons : forall x xs,
  x + fold_right plus 0 xs = fold_right plus 0 (x :: xs).
Proof. reflexivity. Qed.

Lemma forall_map_binarySize : forall es,
  Forall (fun b : binaryExp => binarySize b mod 4 = 0) es
    <-> Forall (fun n => n mod 4 = 0) (map binarySize es).
Proof.
  intros es.
  induction es.
  constructor.
  - rewrite Forall_map.
    intros H. trivial.
  - rewrite Forall_map.
    intros H. trivial.
  - rewrite Forall_map.
    constructor.
    intros H; trivial.
    intros H; trivial.
Qed.

(** The size of a binary expression is always divisible by 4. *)
Theorem binarySizeMultiple4 : forall b, binarySize (b) mod 4 = 0.
Proof.
  intros b.
  induction b as [Hbu32|Hbu64|Hbf64|Hbbyte|Hbutf|xs HFA|Hbuns|xs HFF] using binaryExp_ind.
  (* U32 values are of size 4 *)
  - reflexivity.
  (* U64 values are of size 8 *)
  - reflexivity.
  (* F64 values are of size 8 *)
  - reflexivity.

  (* Byte array values are rounded up to a multiple of 4 and prefixed with 4 *)
  - unfold binarySize.
    unfold asMultipleOf4.
    remember (asMultipleOf (Datatypes.length Hbbyte) 4 Alignment.p0not4) as size eqn:Heqsize.
    rewrite Nat.add_comm.
    rewrite <- (Nat.Div0.add_mod_idemp_l size 4 4).
    assert (size mod 4 = 0) as Hm0. {
      rewrite Heqsize.
      apply (asMultipleOfMod (Datatypes.length Hbbyte) 4 (Alignment.p0not4)).
    }
    rewrite Hm0.
    reflexivity.

  (* UTF-8 values are rounded up to a multiple of 4 and prefixed with 4 *)
  - unfold binarySize.
    unfold asMultipleOf4.
    remember (asMultipleOf (Datatypes.length Hbutf) 4 Alignment.p0not4) as size eqn:Heqsize.
    rewrite Nat.add_comm.
    rewrite <- (Nat.Div0.add_mod_idemp_l size 4 4).
    assert (size mod 4 = 0) as Hm0. {
      rewrite Heqsize.
      apply (asMultipleOfMod (Datatypes.length Hbutf) 4 (Alignment.p0not4)).
    }
    rewrite Hm0.
    reflexivity.

  (* Each element of an array is a multiple of 4, so the entire array is too. *)
  - unfold binarySize.
    fold binarySize.
    induction xs as [|y ys HforAllInd].
    -- reflexivity.
    -- assert (fold_right Init.Nat.add 0 (map binarySize (y :: ys)) mod 4 = 0) as HfoldEq. {
         apply (@divisibilityNFoldPlus 4 (map binarySize (y :: ys))).
         discriminate.
         rewrite <- forall_map_binarySize.
         exact HFA.
       }
       rewrite map_cons.
       rewrite map_cons in HfoldEq.
       assert (4 mod 4 = 0) as H4mod40 by (reflexivity).
       assert (0 <> 4) as H0n4 by (discriminate).
       apply (divisiblityNAdd 4 (fold_right add 0 (binarySize y :: map binarySize ys)) 4 H0n4 H4mod40 HfoldEq).

  (* Unspecified values are rounded up. *)
  - unfold binarySize.
    unfold asMultipleOf4.
    rewrite asMultipleOfMod.
    reflexivity.

  (* Each element of an record is a multiple of 4, so the entire record is too. *)
  - unfold binarySize.
    fold binarySize.
    induction xs as [|y ys HforAllInd].
    -- reflexivity.
    -- rewrite map_cons.
       rewrite map_cons in HFF.
       rewrite <- fold_right_add_cons.
       apply divisiblityNAdd.
       discriminate.
       apply (Forall_inv HFF).
       apply HforAllInd.
       apply (Forall_inv_tail HFF).
Qed.

Lemma sub_0_lt_ymx : forall x y,
  0 <= x -> x < y -> 0 < y - x.
Proof.
  intros x y Hle Hlt.
  destruct x as [|a].
  - rewrite Nat.sub_0_r.
    exact Hlt.
  - rewrite <- Nat.lt_add_lt_sub_l.
    rewrite Nat.add_0_r.
    exact Hlt.
Qed.

Lemma mod_sub : forall x m,
  0 < m -> 0 < m - (x mod m) <= m.
Proof.
  intros x m Hlt.
  constructor.
  - assert (0 <= x mod m < m) as HmRange. {
      apply Nat.mod_bound_pos.
      apply Nat.le_0_l.
      exact Hlt.
    }
    destruct HmRange as [HA HB].
    remember (x mod m) as y.
    apply (sub_0_lt_ymx y m HA HB).
  - assert (x mod m < m) as HmRange. {
      apply Nat.mod_upper_bound.
      apply Nat.neq_sym.
      apply Nat.lt_neq.
      exact Hlt.
    }
    apply Nat.le_sub_l.
Qed.

Lemma mod_opposition : forall x a,
  0 <> a -> x mod a + (a - x mod a) = a.
Proof.
  intros x a Hnz.
  assert (x mod a < a) as Hxma. {
    apply (Nat.mod_upper_bound).
    apply Nat.neq_sym.
    exact Hnz.
  }
  remember (x mod a) as y eqn:Heqy.
  lia.
Qed.

(** The length of an evaluated binary expression padded to _a_ is always divisible by _a_. *)
Theorem binaryEvalPaddedBytesAligned : forall bs a p (Hnz : 0 <> a),
  length (binaryEvalPaddedBytes bs a p Hnz) mod a = 0.
Proof.
  intros bs a p Hnz.
  unfold binaryEvalPaddedBytes.
  destruct (Datatypes.length bs mod a) eqn:Hlen.
  - rewrite length_map.
    exact Hlen.
  - rewrite length_map.
    rewrite length_app.
    rewrite repeat_length.
    rewrite <- Hlen.
    remember (Datatypes.length bs) as x.
    rewrite <- (Nat.Div0.add_mod_idemp_l x (a - x mod a) a).
    assert ((x mod a + (a - x mod a)) = a) as Heqa. {
      rewrite (mod_opposition x a Hnz).
      reflexivity.
    }
    rewrite Heqa.
    apply Nat.Div0.mod_same.
Qed.

Lemma repeat_eq : forall (A : Type) (P : A -> Prop) (n : nat) (x : A),
  Forall (eq x) (repeat x n).
Proof.
  intros A P n x.
  induction n as [|m Hm].
  - constructor.
  - simpl.
    constructor.
    reflexivity.
    exact Hm.
Qed.

Lemma Forall_implies : forall (A : Type) (P : A -> Prop) (Q : A -> Prop) (xs : list A) (H : forall x, P x -> Q x),
  Forall P xs -> Forall Q xs.
Proof.
  intros A P Q xs Ht HforAll.
  induction HforAll as [|y ys Hpy HfaP HfaQ].
  - constructor.
  - constructor.
    apply (Ht y Hpy).
    exact HfaQ.
Qed.

(** Evaluating a binary expression results in a series of u8 values. *)
Theorem binaryEvalPaddedBytesU8 : forall bs a p (Hnz : 0 <> a),
  Forall streamEIsU8 (binaryEvalPaddedBytes bs a p Hnz).
Proof.
  intros bs a p Hnz.
  unfold binaryEvalPaddedBytes.
  destruct (Datatypes.length bs mod a) as [|HB].
  - rewrite Forall_map.
    induction bs as [|r rs Hrs].
    -- constructor.
    -- constructor.
       reflexivity.
       exact Hrs.
  - rewrite map_app.
    assert (Forall streamEIsU8 (map u8byte bs)) as Hmap. {
      rewrite Forall_map.
      induction bs as [|r rs Hrs].
      - constructor.
      - constructor.
        reflexivity.
        exact Hrs.
    }
    assert (Forall streamEIsU8 (map u8byte (repeat p (a - S HB)))) as HmapR. {
      rewrite Forall_map.
      assert (Forall (eq p) (repeat p (a - S HB))) as Hfeq
        by (apply (repeat_eq byte (fun _ : byte => True) (a - S HB) p)).
      simpl.
      apply (@Forall_implies byte (eq p) (fun _ : byte => True) (repeat p (a - S HB))). {
        intros. exact I.
      }
      exact Hfeq.
    }
    apply Forall_app.
    constructor.
    exact Hmap.
    exact HmapR.
Qed.

Lemma app_cons : forall (A : Type) (x : A) (xs : list A),
  x :: xs = app (cons x nil) xs.
Proof.
  intros A x xs.
  reflexivity.
Qed.

(** Streams produced by the _binaryEval_ function are well-formed. *)
Theorem binaryEvalStreamsWellFormed : forall b p,
  streamWellFormed (binaryEval b p).
Proof.
  intros b p.
  induction b as [a0|a1|a2|a3|a4|a5 Hfa|a6|a7 Hfa].
  (* U32 *)
  - apply BEPVu32.
  (* U64 *)
  - apply BEPVu64.
  (* F64 *)
  - apply BEPVf64.
  (* Bytes *)
  - unfold binaryEval.
    rewrite app_cons.
    apply BEPAppend.
    apply BEPVu32.
    assert (length (binaryEvalPaddedBytes a3 4 p Alignment.p0not4) mod 4 = 0) as Hlm
      by (apply (binaryEvalPaddedBytesAligned)).
    apply BEPVu8s.
    apply binaryEvalPaddedBytesU8.
    exact Hlm.
  (* UTF-8 *)
  - unfold binaryEval.
    rewrite app_cons.
    apply BEPAppend.
    apply BEPVu32.
    assert (length (binaryEvalPaddedBytes a4 4 p Alignment.p0not4) mod 4 = 0) as Hlm
      by (apply (binaryEvalPaddedBytesAligned)).
    assert (Forall streamEIsU8 (binaryEvalPaddedBytes a4 4 p Alignment.p0not4)) as Hu8
      by (apply (binaryEvalPaddedBytesU8)).
    apply (BEPVu8s _ Hu8 Hlm).
  (* Array *)
  - simpl.
    rewrite app_cons.
    apply BEPAppend.
    apply BEPVu32.
    induction a5 as [|q qs IHqs].
    -- constructor.
    -- assert (streamWellFormed (concat (map (fun e => binaryEval e p) qs))) as HqsWF
         by (apply (IHqs (Forall_inv_tail Hfa))).
       assert (streamWellFormed (binaryEval q p)) as HqWF
         by (apply (Forall_inv Hfa)).
       simpl.
       apply BEPAppend.
       exact HqWF.
       exact HqsWF.
  (* Reserve *)
  - simpl.
    unfold asMultipleOf4.
    remember (asMultipleOf a6 4 Alignment.p0not4) as size eqn:Heqsize.
    assert (size mod 4 = 0) as Heqm. {
      rewrite Heqsize.
      apply (asMultipleOfMod).
    }
    apply BEPVu8s.
    assert (Forall (eq (u8byte p)) (repeat (u8byte p) size)) as Hfeq
      by (apply (@repeat_eq streamE streamEIsU8 size (u8byte p))).
    apply (@Forall_implies streamE (eq (u8byte p)) streamEIsU8 (repeat (u8byte p) size)). {
      intros x Hxeq.
      unfold streamEIsU8.
      rewrite <- Hxeq.
      exact I.
    }
    exact Hfeq.
    rewrite repeat_length.
    exact Heqm.
  (* Record *)
  - simpl.
    induction a7 as [|q qs IHqs].
    -- constructor.
    -- assert (Forall (fun b : binaryExp => streamWellFormed (binaryEval b p)) (map snd qs)) as Hfqs. {
         apply (@Forall_inv_tail binaryExp (fun b : binaryExp => streamWellFormed (binaryEval b p)) (snd q) (map snd qs)). {
           assert ((map snd (q :: qs)) = (snd q :: map snd qs)) as Hmc by reflexivity.
           rewrite <- Hmc.
           exact Hfa.
         }
       }
       assert (streamWellFormed (concat (map (compose (fun e => binaryEval e p) snd) qs))) as Hconqs by (apply (IHqs Hfqs)).
       rewrite map_cons.
       rewrite concat_cons.
       apply BEPAppend.
       rewrite map_cons in Hfa.
       apply (Forall_inv Hfa).
       exact Hconqs.
Qed.

Lemma fold_right_1_length : forall xs,
  Forall (eq 1) xs -> fold_right add 0 xs = length xs.
Proof.
  intros xs Hfa.
  induction xs as [|y ys IHxs].
  - reflexivity.
  - rewrite <- fold_right_add_cons.
    assert (length (y :: ys) = 1 + length (ys)) as HlenYs by reflexivity.
    rewrite HlenYs.
    assert (1 = y) as Hy1 by (apply (Forall_inv Hfa)).
    rewrite <- Hy1.
    f_equal.
    apply IHxs.
    apply (Forall_inv_tail Hfa).
Qed.

Theorem fold_right_add_app : forall xs ys,
  fold_right add 0 xs + fold_right add 0 ys = fold_right add 0 (xs ++ ys).
Proof.
  intros xs ys.
  rewrite fold_right_app.
  generalize dependent ys.
  induction xs as [|q qs IHqs].
  - reflexivity.
  - intros ys.
    simpl.
    rewrite <- (IHqs ys).
    rewrite Nat.add_assoc.
    reflexivity.
Qed.

Theorem streamSizeApp : forall xs ys,
  streamSize xs + streamSize ys = streamSize (xs ++ ys).
Proof.
  intros xs ys.
  unfold streamSize.
  rewrite map_app.
  rewrite fold_right_add_app.
  reflexivity.
Qed.

(** All well-formed streams have a size divisible by 4. *)
Theorem streamsWellFormedDivisible4 : forall es,
  streamWellFormed es -> streamSize es mod 4 = 0.
Proof.
  intros es Hwf.
  induction Hwf as [|H1|H2|H3|es Hfa Hsize|xs ys Hxswf Hxsize Hyswf Hysize].
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - unfold streamSize.
    assert (Forall (fun e => 1 = streamElementSize e) es) as HFaSize. {
      apply (@Forall_implies streamE streamEIsU8 (fun e : streamE => 1 = streamElementSize e) es). {
        intros x His.
        destruct x as [f64|u64|u32|u8].
        - contradiction.
        - contradiction.
        - contradiction.
        - reflexivity.
      }
      exact Hfa.
    }
    assert (Forall (eq 1) (map streamElementSize es)) as Hall1. {
      apply (@Forall_map _ _ _ _ es).
      exact HFaSize.
    }
    assert (fold_right add 0 (map streamElementSize es) = length es) as HlenEq. {
      assert (length es = length (map streamElementSize es)) as HmapLen. {
        rewrite length_map.
        reflexivity.
      }
      rewrite HmapLen.
      apply (fold_right_1_length (map streamElementSize es) Hall1).
    }
    rewrite HlenEq.
    exact Hsize.
  - rewrite <- streamSizeApp.
    apply divisiblityNAdd.
    discriminate.
    exact Hxsize.
    exact Hysize.
Qed.

8.28. rentomos/src/main/rocq/Divisible.v

(*
 * Copyright © 2025 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Arith.PeanoNat.
From Stdlib Require Import Lists.List.
From Stdlib Require Import Init.Nat.

(** If _x_ and _y_ are divisible by _z_, then _x + y_ is also divisible by _z_. *)
Theorem divisiblityNAdd : forall (x y z : nat),
  0 <> z -> x mod z = 0 -> y mod z = 0 -> (x + y) mod z = 0.
Proof.
  intros x y z Hz Hx Hy.
  destruct y as [|y].
    (* If y = 0, then this matches one of our assumptions already. *)
    rewrite Nat.add_0_r; exact Hx.
    (* Otherwise, the following property always holds given that the divisor is ≠ 0. *)
    assert ((x mod z + S y) mod z = (x + S y) mod z) as Heq.
      apply (Nat.Div0.add_mod_idemp_l x (S y) z).
    (* x mod z = 0 *)
    rewrite Hx in Heq.
    (* 0 + S y = S y *)
    rewrite Nat.add_0_l in Heq.
    rewrite <- Heq.
    exact Hy.
Qed.

(** Divisibility is preserved over addition. *)
Theorem divisibilityNFoldPlus : forall z xs,
  0 <> z ->
    Forall (fun n => n mod z = 0) xs ->
      (fold_right plus 0 xs) mod z = 0.
Proof.
  intros z xs Hnz HforAll.
  induction xs as [|y ys].
  - apply (Nat.Div0.mod_0_l z).
  - assert (fold_right add 0 (y :: ys) = y + fold_right add 0 ys) as Hfoldeq by reflexivity.
    rewrite Hfoldeq.
    assert (fold_right add 0 ys mod z = 0) as Hfoldeq2. {
      apply IHys.
      apply (@Forall_inv_tail nat (fun n : nat => n mod z = 0) y ys HforAll).
    }
    rewrite divisiblityNAdd.
    reflexivity.
    exact Hnz.
    apply (@Forall_inv nat (fun n : nat => n mod z = 0) y ys HforAll).
    exact Hfoldeq2.
Qed.

8.29. rentomos/src/main/rocq/ExampleFileFormat.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Strings.Byte.
From Stdlib Require Import Lists.List.

Require Import com.io7m.rentomos.Tags.
Require Import com.io7m.rentomos.FileFormat.

Import ListNotations.

Example fileIdentifier : TagT :=
  Tag x89 x4d x54 x50 x0d x0a x1a x0a.

Example sectionEndIdentifier : TagT :=
  Tag x4d x54 x50 x5f x45 x4e x44 x21.

Example sectionManifestIdentifier : TagT :=
  Tag x4d x54 x50 x5f x4d x41 x4e x49.

Example sectionFileIdentifier : TagT :=
  Tag x4d x54 x50 x5f x46 x49 x4c x45.

Example sectionManifest : FileSectionDescriptionT :=
  FileSectionDescription sectionManifestIdentifier FSO_MustBeFirst FSC_One.

Example sectionFile : FileSectionDescriptionT :=
  FileSectionDescription sectionFileIdentifier FSO_AnyOrder FSC_ZeroToN.

Example fileDescriptionExample : FileDescriptionT :=
  FileDescription 
  fileIdentifier
  1 
  0 
  [sectionManifest; sectionFile] 
  sectionEndIdentifier
  UnknownSectionsPermitted
  .

Lemma fileSectionAtMostOneFirstExample : fileSectionAtMostOneFirst (fileSections fileDescriptionExample).
Proof.
  unfold fileSectionAtMostOneFirst.
  simpl; auto.
Qed.

Lemma fileSectionAtMostOneLastExample : fileSectionAtMostOneLast (fileSections fileDescriptionExample).
Proof.
  unfold fileSectionAtMostOneLast.
  simpl; auto.
Qed.

Lemma fileSectionTagsUniqueExample : fileSectionTagsUnique (fileSections fileDescriptionExample).
Proof.
  unfold fileSectionTagsUnique.
  simpl; auto.
  constructor.
  - unfold not.
    intro H.
    inversion H.
    contradict H0.
    discriminate.
    inversion H0.
  - constructor.
    unfold not.
    intro H.
    inversion H.
    constructor.
Qed.

Lemma fileSectionFileNotSectionExample : fileSectionFileNotSection fileDescriptionExample.
Proof.
  unfold fileSectionFileNotSection.
  simpl.
  unfold not.
  intro H.
  destruct H.
  - contradict H.
    discriminate.
  - destruct H.
    contradict H.
    discriminate.
    auto.
Qed.

Lemma endSectionFileNotSectionExample : endSectionFileNotSection fileDescriptionExample.
Proof.
  unfold endSectionFileNotSection.
  simpl.
  unfold not.
  intro H.
  destruct H.
  - contradict H.
    discriminate.
  - destruct H.
    contradict H.
    discriminate.
    auto.
Qed.

Theorem fileDescriptionInvariantsExample : fileDescriptionInvariants fileDescriptionExample.
Proof.
  constructor.
  apply fileSectionAtMostOneFirstExample.
  constructor.
  apply fileSectionAtMostOneLastExample.
  constructor.
  apply fileSectionTagsUniqueExample.
  constructor.
  apply fileSectionFileNotSectionExample.
  apply endSectionFileNotSectionExample.
Qed.

8.30. rentomos/src/main/rocq/FileFormat.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Lists.List.

Require Import com.io7m.rentomos.Tags.

Import ListNotations.

(** The ordering constraints on a file section. *)
Inductive FileSectionOrderingT :=
    (** The section must be the first in the file. *)
    FSO_MustBeFirst
  | (** The section must be the last in the file. *)
    FSO_MustBeLast
  | (** The section can appear anywhere in the file. *)
    FSO_AnyOrder
  .

(** The cardinality of a file section. *)
Inductive FileSectionCardinalityT :=
    (** The section must appear exactly once. *)
    FSC_One
  | (** The section can appear at most once. *)
    FSC_ZeroToOne
  | (** The section can appear any number of times, including not at all. *)
    FSC_ZeroToN
  | (** The section must appear at least once. *)
    FSC_OneToN
  .

(** The constraints on unknown sections. *)
Inductive FileSectionsUnknownT :=
  | (** Unknown sections are permitted. *)
    UnknownSectionsPermitted
  | (** Unknown sections are not permitted. *)
    UnknownSectionsNotPermitted
  .

(** A description of a file section. *)
Inductive FileSectionDescriptionT := FileSectionDescription {
  (** The file section tag. *)
  fileSectionTag         : TagT;
  (** The file section ordering constraint. *)
  fileSectionOrdering    : FileSectionOrderingT;
  (** The file section cardinality constraint. *)
  fileSectionCardinality : FileSectionCardinalityT
}.

(** The description of a file format version. *)
Inductive FileDescriptionT := FileDescription {
  (** The file tag. *)
  fileTag             : TagT;
  (** The major file format version. *)
  fileVersionMajor    : nat;
  (** The minor file format version. *)
  fileVersionMinor    : nat;
  (** The file sections. *)
  fileSections        : list FileSectionDescriptionT;
  (** The file end tag. *)
  fileEndTag          : TagT;
  (** The constraints on unknown file sections. *)
  fileSectionsUnknown : FileSectionsUnknownT
}.

(** The number of sections with _FSO_MustBeFirst_. *)
Fixpoint fileSectionOrderingCountFirst
  (xs : list FileSectionDescriptionT)
  (n  : nat)
: nat :=
  match xs with
  | nil       => 0
  | cons y ys =>
    match (fileSectionOrdering y) with
    | FSO_MustBeFirst => fileSectionOrderingCountFirst ys (S n)
    | _               => fileSectionOrderingCountFirst ys n
    end
  end.

(** The number of sections with _FSO_MustBeLast_. *)
Fixpoint fileSectionOrderingCountLast
  (xs : list FileSectionDescriptionT)
  (n  : nat)
: nat :=
  match xs with
  | nil       => 0
  | cons y ys =>
    match (fileSectionOrdering y) with
    | FSO_MustBeLast => fileSectionOrderingCountLast ys (S n)
    | _              => fileSectionOrderingCountLast ys n
    end
  end.

(** At most one section can be _FSO_MustBeFirst_. *)
Definition fileSectionAtMostOneFirst (xs : list FileSectionDescriptionT) : Prop :=
  fileSectionOrderingCountFirst xs 0 <= 1.

(** At most one section can be _FSO_MustBeLast_. *)
Definition fileSectionAtMostOneLast (xs : list FileSectionDescriptionT) : Prop :=
  fileSectionOrderingCountLast xs 0 <= 1.

(** The file sections must have unique tags. *)
Definition fileSectionTagsUnique (xs : list FileSectionDescriptionT) : Prop :=
  NoDup (map (fun s => fileSectionTag s) xs).

(** The file sections cannot contain the file tag. *)
Definition fileSectionFileNotSection (f : FileDescriptionT) : Prop :=
  ~In (fileTag f) (map (fun s => fileSectionTag s) (fileSections f)).

(** The file sections cannot contain the end tag. *)
Definition endSectionFileNotSection (f : FileDescriptionT) : Prop :=
  ~In (fileEndTag f) (map (fun s => fileSectionTag s) (fileSections f)).

(** The file format description invariants. *)
Definition fileDescriptionInvariants (f : FileDescriptionT) : Prop :=
     fileSectionAtMostOneFirst (fileSections f)
  /\ fileSectionAtMostOneLast (fileSections f)
  /\ fileSectionTagsUnique (fileSections f)
  /\ fileSectionFileNotSection f
  /\ endSectionFileNotSection  f.

8.31. rentomos/src/main/rocq/Tags.v

(*
 * Copyright © 2026 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

From Stdlib Require Import Lia.
From Stdlib Require Import ZArith.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Strings.Byte.
From Stdlib Require Import ZArith.Zbitwise.

(** A 64-bit section identifier. *)
Inductive TagT : Set := Tag {
  tag_byte0 : byte;
  tag_byte1 : byte;
  tag_byte2 : byte;
  tag_byte3 : byte;
  tag_byte4 : byte;
  tag_byte5 : byte;
  tag_byte6 : byte;
  tag_byte7 : byte
}.

(** The example PNG file format identifier. *)
Example tagPNG :=
  Tag x89 x50 x4e x47 x0d x0a x1a x0a.

Open Scope Z_scope.

Definition byteOfZ (z : Z) : byte :=
  match of_N (Z.to_N z) with
  | None   => x00
  | Some b => b
  end.

Definition byteToZ (b : byte) : Z :=
  Z.of_N (to_N b).

Theorem byteZIdentity0 : forall b,
  byteOfZ (byteToZ b) = b.
Proof.
  unfold byteToZ.
  unfold byteOfZ.
  intros b.
  rewrite N2Z.id.
  rewrite of_to_N.
  reflexivity.
Qed.

Theorem byteZIdentity1 : forall z,
  0 <= z < 256 -> byteToZ (byteOfZ z) = z.
Proof.
  unfold byteToZ.
  unfold byteOfZ.
  intros z [Hrange0 Hrange1].
  remember (of_N (Z.to_N z)) as b.
  destruct b.
  - symmetry in Heqb.
    rewrite (to_of_N _ Heqb).
    rewrite Z2N.id.
    reflexivity.
    auto.
  - symmetry in Heqb.
    rewrite (of_N_None_iff (Z.to_N z)) in Heqb.
    contradict Heqb.
    lia.
Qed.

(** Define a file tag from a single 64-bit integer. *)
Definition tagOfZ (z : Z) : TagT :=
  let t0 := Z.shiftr (Z.land z 0xff00000000000000) 56 in
  let t1 := Z.shiftr (Z.land z 0x00ff000000000000) 48 in
  let t2 := Z.shiftr (Z.land z 0x0000ff0000000000) 40 in
  let t3 := Z.shiftr (Z.land z 0x000000ff00000000) 32 in
  let t4 := Z.shiftr (Z.land z 0x00000000ff000000) 24 in
  let t5 := Z.shiftr (Z.land z 0x0000000000ff0000) 16 in
  let t6 := Z.shiftr (Z.land z 0x000000000000ff00) 8  in
  let t7 := Z.shiftr (Z.land z 0x00000000000000ff) 0  in
  let b0 := byteOfZ t0                                in
  let b1 := byteOfZ t1                                in
  let b2 := byteOfZ t2                                in
  let b3 := byteOfZ t3                                in
  let b4 := byteOfZ t4                                in
  let b5 := byteOfZ t5                                in
  let b6 := byteOfZ t6                                in
  let b7 := byteOfZ t7                                in
    Tag b0 b1 b2 b3 b4 b5 b6 b7.

(** Convert a file tag to a single 64-bit integer. *)
Definition tagToZ (t : TagT) : Z :=
  let z0 := Z.shiftl (byteToZ (tag_byte0 t)) 56 in
  let z1 := Z.shiftl (byteToZ (tag_byte1 t)) 48 in
  let z2 := Z.shiftl (byteToZ (tag_byte2 t)) 40 in
  let z3 := Z.shiftl (byteToZ (tag_byte3 t)) 32 in
  let z4 := Z.shiftl (byteToZ (tag_byte4 t)) 24 in
  let z5 := Z.shiftl (byteToZ (tag_byte5 t)) 16 in
  let z6 := Z.shiftl (byteToZ (tag_byte6 t)) 8  in
  let z7 := Z.shiftl (byteToZ (tag_byte7 t)) 0  in
    Z.lor z0 (Z.lor z1 (Z.lor z2 (Z.lor z3 (Z.lor z4 (Z.lor z5 (Z.lor z6 z7)))))).

Lemma byteInRange : forall z shift, 
  0 <= z < 2^64 ->
    0 <= shift ->
      0 <= Z.shiftr (Z.land z (Z.shiftl 0xff shift)) shift < 256.
Proof.
  intros z shift [Hrange0 Hrange1] HshiftRange.
  split.
  - rewrite Z.shiftr_nonneg.
    rewrite (Z.land_nonneg z (Z.shiftl 255 shift)).
    lia.
  - rewrite Z.shiftr_land.
    rewrite Z.shiftr_shiftl_r.
    assert (Hs: shift - shift = 0) by (lia).
    rewrite Hs.
    rewrite Z.shiftr_0_r.
    set (m := Z.shiftr z shift).
    assert (Hone: 255 = Z.ones 8) by (reflexivity).
    rewrite Hone.
    rewrite Z.land_ones.
    apply (Z.mod_pos_bound m (2 ^ 8)).
    lia. lia. lia.
Qed.

Lemma byteShiftZeros : forall shift,
  0 <= shift ->
    Z.land (Z.shiftl 255 shift) (Z.ones shift) = 0.
Proof.
  intros shift Hrange.
  rewrite (Z.land_ones (Z.shiftl 255 shift) shift).
  rewrite Z.shiftl_mul_pow2.
  rewrite Z.mod_mul.
  reflexivity.
  apply Z.pow_nonzero.
  discriminate.
  auto.
  auto.
  auto.
Qed.

Lemma byteShiftId : forall z shift,
  0 <= shift ->
    (Z.shiftl (Z.shiftr (Z.land z (Z.shiftl 255 shift)) shift) shift) = Z.land z (Z.shiftl 255 shift).
Proof.
  intros z shift Hrange.
  apply Z.bits_inj'.
  intros n Hn.
  set (mask := Z.shiftl 255 shift).
  set (masked := Z.land z mask).

  assert (HmaskLow : forall k, 0 <= k < shift -> Z.testbit mask k = false). {
    intros k [Hrange0 Hrange1].
    unfold mask.
    apply Z.shiftl_spec_low; auto.
  }

  assert (HmaskedLow : forall k, 0 <= k < shift -> Z.testbit masked k = false). {
    intros k [Hrange0 Hrange1].
    unfold masked.
    rewrite Z.land_spec.
    destruct (Z.testbit z k).
    - rewrite HmaskLow.
      reflexivity.
      auto.
    - reflexivity.
  }

  destruct (Z_ge_lt_dec n shift) as [Hge|Hlt].
  - set (k := n - shift).
    assert (Hk : 0 <= k) by (unfold k; lia).
    rewrite Z.shiftl_spec_high.
    rewrite Z.shiftr_spec by exact Hk.
    replace (n - shift + shift) with n by lia.
    reflexivity.
    auto.
    lia.
  - rewrite HmaskedLow.
    rewrite Z.shiftl_spec_low.
    auto.
    auto.
    auto.
Qed.

Lemma byteExtract : forall z shift,
  0 <= shift ->
    Z.shiftr (Z.land z (Z.shiftl 255 shift)) shift = (z / 2 ^ shift) mod 2 ^ 8.
Proof.
  intros z shift Hshift.
  rewrite Z.shiftr_land.
  rewrite (Z.shiftr_shiftl_r 255 shift shift Hshift).
  assert (Hss: shift - shift = 0) by (lia).
  rewrite Hss.
  rewrite Z.shiftr_0_r.
  assert (H255: 255 = Z.pred (2 ^ 8)) by (reflexivity).
  rewrite H255.
  rewrite <- Z.ones_equiv.
  rewrite Z.land_ones.
  rewrite Z.shiftr_div_pow2.
  reflexivity.
  auto.
  lia.
Qed.

Lemma byteReconstruct : forall z shift,
  0 <= shift ->
    Z.lor (Z.shiftl (Z.shiftr z shift) shift) (Z.land z (Z.ones shift)) = z.
Proof.
  intros z shift Hshift.
  rewrite <- Z.ldiff_ones_r.
  apply Z.lor_ldiff_and.
  auto.
Qed.

Lemma bitRangeMask : forall z n mask,
  0 <= z < (2 ^ mask) ->
    0 <= n < mask ->
      Z.testbit z n = Z.testbit (Z.land z (Z.ones mask)) n.
Proof.
  intros z n mask [Hzr0 Hzr1] [Hnr0 Hnr1].
  rewrite Z.land_ones_low.
  reflexivity.
  auto.
  destruct (Z.eq_dec z 0) as [Heq|Hneq].
  - subst z.
    simpl.
    lia.
  - apply Z.log2_lt_pow2; lia.
Qed.

Lemma bitMaskDisjoint
  (mask  : Z)
  (Hmask : 0 <= mask)
: Z.land (Z.ones mask) (Z.shiftl (Z.ones mask) mask) = 0.
Proof.
  apply Z.bits_inj'.
  intros n Hnr.
  rewrite Z.land_comm.
  rewrite Z.land_spec.
  destruct (Z_lt_ge_dec n mask) as [Hnlt|Hnge].
  - rewrite Z.ones_spec_low.
    rewrite Bool.andb_true_r.
    rewrite Z.shiftl_spec_low.
    rewrite Z.bits_0.
    reflexivity.
    auto.
    auto.
  - rewrite Z.ones_spec_high.
    rewrite Bool.andb_false_r.
    rewrite Z.bits_0.
    reflexivity.
    lia.
Qed.

Lemma bitMaskCombine
  (mask  : Z)
  (Hmask : 0 <= mask)
: Z.lor (Z.ones mask) (Z.shiftl (Z.ones mask) mask) = Z.ones (mask + mask).
Proof.
  apply Z.bits_inj'.
  intros n Hnr.
  rewrite Z.lor_spec.
  destruct (Z_lt_ge_dec n (mask + mask)) as [Hnltmm|Hngemm].
  - rewrite (Z.ones_spec_low (mask + mask) n) by lia.
    rewrite (Z.shiftl_spec (Z.ones mask) mask n) by lia.
    destruct (Z_lt_ge_dec n mask) as [Hnltm|Hngem].
    -- rewrite Z.ones_spec_low by lia.
       reflexivity.
    -- rewrite Z.ones_spec_high by lia.
       simpl.
       rewrite (Z.testbit_ones mask (n - mask) Hmask).
       lia.
  - rewrite (Z.ones_spec_high (mask + mask) n).
    destruct (Z_lt_ge_dec n mask) as [Hnltm|Hngem].
    -- contradict Hnltm; lia.
    -- rewrite (Z.ones_spec_high mask n) by lia.
       simpl.
       rewrite (Z.shiftl_spec_high (Z.ones mask) mask n) by lia.
       apply Z.ones_spec_high.
       lia.
    -- lia.
Qed.

Lemma bitRangeMaskOr
  (z mask : Z)
  (Hmask  : 0 <= mask)
  (Hz     : 0 <= z)
  (Hzb    : z < 2 ^ (mask + mask))
: Z.lor (Z.land z (Z.ones mask))
        (Z.land z (Z.shiftl (Z.ones mask) mask)) = z.
Proof.
  apply Z.bits_inj'.
  intros n Hn.
  pose proof (bitMaskCombine _ Hmask) as Hmcomb.
  rewrite <- Z.land_lor_distr_r.
  rewrite Hmcomb.
  assert (Z.land z (Z.ones (mask + mask)) = z) as Hzeq. {
    rewrite (Z.land_ones z (mask + mask)) by lia.
    apply Z.mod_small.
    lia.
  }
  rewrite Hzeq.
  reflexivity.
Qed.

(** Tag conversion is an identity for all unsigned 64-bit integers. *)
Theorem tagIdentity : forall z,
  0 <= z < 2^64 -> tagToZ (tagOfZ z) = z.
Proof.
  intros z [Hrange0 Hrange1].
  unfold tagToZ.
  unfold tagOfZ.

  assert (HS56: 0xff00000000000000 = Z.shiftl 0xff 56) by (reflexivity).
  rewrite HS56.
  assert (HS48: 0x00ff000000000000 = Z.shiftl 0xff 48) by (reflexivity).
  rewrite HS48.
  assert (HS40: 0x0000ff0000000000 = Z.shiftl 0xff 40) by (reflexivity).
  rewrite HS40.
  assert (HS32: 0x000000ff00000000 = Z.shiftl 0xff 32) by (reflexivity).
  rewrite HS32.
  assert (HS24: 0x00000000ff000000 = Z.shiftl 0xff 24) by (reflexivity).
  rewrite HS24.
  assert (HS16: 0x0000000000ff0000 = Z.shiftl 0xff 16) by (reflexivity).
  rewrite HS16.
  assert (HS8: 0x000000000000ff00 = Z.shiftl 0xff 8) by (reflexivity).
  rewrite HS8.
  assert (HS0: 0x00000000000000ff = Z.shiftl 0xff 0) by (reflexivity).
  rewrite HS0.

  rewrite Z.shiftl_0_r.

  assert (Hzle56: 0 <= 56) by (lia).
  assert (Hzle48: 0 <= 48) by (lia).
  assert (Hzle40: 0 <= 40) by (lia).
  assert (Hzle32: 0 <= 32) by (lia).
  assert (Hzle24: 0 <= 24) by (lia).
  assert (Hzle16: 0 <= 16) by (lia).
  assert (Hzle8: 0 <= 8) by (lia).
  pose proof (byteInRange z 56 (conj Hrange0 Hrange1) Hzle56) as Hr56.
  pose proof (byteInRange z 48 (conj Hrange0 Hrange1) Hzle48) as Hr48.
  pose proof (byteInRange z 40 (conj Hrange0 Hrange1) Hzle40) as Hr40.
  pose proof (byteInRange z 32 (conj Hrange0 Hrange1) Hzle32) as Hr32.
  pose proof (byteInRange z 24 (conj Hrange0 Hrange1) Hzle24) as Hr24.
  pose proof (byteInRange z 16 (conj Hrange0 Hrange1) Hzle16) as Hr16.
  pose proof (byteInRange z 8 (conj Hrange0 Hrange1) Hzle8) as Hr8.

  set (z0 := Z.shiftr (Z.land z (Z.shiftl 255 56)) 56).
  set (z1 := Z.shiftr (Z.land z (Z.shiftl 255 48)) 48).
  set (z2 := Z.shiftr (Z.land z (Z.shiftl 255 40)) 40).
  set (z3 := Z.shiftr (Z.land z (Z.shiftl 255 32)) 32).
  set (z4 := Z.shiftr (Z.land z (Z.shiftl 255 24)) 24).
  set (z5 := Z.shiftr (Z.land z (Z.shiftl 255 16)) 16).
  set (z6 := Z.shiftr (Z.land z (Z.shiftl 255 8)) 8).
  set (z7 := Z.shiftr (Z.land z 255) 0).

  set (r := {|
   tag_byte0 := byteOfZ z0;
   tag_byte1 := byteOfZ z1;
   tag_byte2 := byteOfZ z2;
   tag_byte3 := byteOfZ z3;
   tag_byte4 := byteOfZ z4;
   tag_byte5 := byteOfZ z5;
   tag_byte6 := byteOfZ z6;
   tag_byte7 := byteOfZ z7
  |}).

  assert (Htb0: tag_byte0 r = byteOfZ z0) by (reflexivity).
  rewrite Htb0.
  assert (Htb1: tag_byte1 r = byteOfZ z1) by (reflexivity).
  rewrite Htb1.
  assert (Htb2: tag_byte2 r = byteOfZ z2) by (reflexivity).
  rewrite Htb2.
  assert (Htb3: tag_byte3 r = byteOfZ z3) by (reflexivity).
  rewrite Htb3.
  assert (Htb4: tag_byte4 r = byteOfZ z4) by (reflexivity).
  rewrite Htb4.
  assert (Htb5: tag_byte5 r = byteOfZ z5) by (reflexivity).
  rewrite Htb5.
  assert (Htb6: tag_byte6 r = byteOfZ z6) by (reflexivity).
  rewrite Htb6.
  assert (Htb7: tag_byte7 r = byteOfZ z7) by (reflexivity).
  rewrite Htb7.

  rewrite byteZIdentity1.
  rewrite byteZIdentity1.
  rewrite byteZIdentity1.
  rewrite byteZIdentity1.
  rewrite byteZIdentity1.
  rewrite byteZIdentity1.
  rewrite byteZIdentity1.
  rewrite byteZIdentity1.

  subst z0.
  rewrite (byteShiftId z 56).
  subst z1.
  rewrite (byteShiftId z 48).
  subst z2.
  rewrite (byteShiftId z 40).
  subst z3.
  rewrite (byteShiftId z 32).
  subst z4.
  rewrite (byteShiftId z 24).
  subst z5.
  rewrite (byteShiftId z 16).
  subst z6.
  rewrite (byteShiftId z 8).
  subst z7.

  clear Htb0 Htb1 Htb2 Htb3 Htb4 Htb5 Htb6 Htb7.
  clear r.
  clear Hr56 Hr48 Hr40 Hr32 Hr24 Hr16 Hr8.
  clear HS56 HS48 HS40 HS32 HS24 HS16 HS8 HS0.

  assert (H255: 255 = Z.pred (2 ^ 8)) by (reflexivity).
  rewrite H255. clear H255.
  rewrite <- Z.ones_equiv.
  rewrite Z.shiftr_0_r.
  rewrite Z.shiftl_0_r.
  rewrite <- Z.land_lor_distr_r.
  rewrite <- Z.land_lor_distr_r.
  rewrite <- Z.land_lor_distr_r.
  rewrite <- Z.land_lor_distr_r.
  rewrite <- Z.land_lor_distr_r.
  rewrite <- Z.land_lor_distr_r.
  rewrite <- Z.land_lor_distr_r.

  assert (Hm0: Z.lor (Z.shiftl (Z.ones 8) 8) (Z.ones 8) = Z.ones 16). {
    apply (bitMaskCombine 8).
    lia.
  }
  rewrite Hm0. clear Hm0.
  assert (Hm1: Z.lor (Z.shiftl (Z.ones 8) 16) (Z.ones 16) = Z.ones 24). {
    simpl.
    rewrite Z.ones_equiv.
    lia.
  }
  rewrite Hm1. clear Hm1.
  assert (Hm2: Z.lor (Z.shiftl (Z.ones 8) 24) (Z.ones 24) = Z.ones 32). {
    simpl.
    rewrite Z.ones_equiv.
    lia.
  }
  rewrite Hm2. clear Hm2.
  assert (Hm3: Z.lor (Z.shiftl (Z.ones 8) 32) (Z.ones 32) = Z.ones 40). {
    simpl.
    rewrite Z.ones_equiv.
    lia.
  }
  rewrite Hm3. clear Hm3.
  assert (Hm4: Z.lor (Z.shiftl (Z.ones 8) 40) (Z.ones 40) = Z.ones 48). {
    simpl.
    rewrite Z.ones_equiv.
    lia.
  }
  rewrite Hm4. clear Hm4.
  assert (Hm5: Z.lor (Z.shiftl (Z.ones 8) 48) (Z.ones 48) = Z.ones 56). {
    simpl.
    rewrite Z.ones_equiv.
    lia.
  }
  rewrite Hm5. clear Hm5.
  assert (Hm6: Z.lor (Z.shiftl (Z.ones 8) 56) (Z.ones 56) = Z.ones 64). {
    simpl.
    rewrite Z.ones_equiv.
    lia.
  }
  rewrite Hm6. clear Hm6.

  apply Z.bits_inj'.
  intros n Hn.
  rewrite Z.land_spec.

  destruct (Z_lt_ge_dec n 64) as [Hnlt|Hnge]. {
    rewrite Z.ones_spec_low by lia.
    rewrite Bool.andb_true_r.
    reflexivity.
  } {
    rewrite Z.ones_spec_high by lia.
    rewrite Bool.andb_false_r.
    assert (z < 2 ^ n) as Hzn. {
      rewrite Z.ge_le_iff in Hnge.
      apply Z.lt_le_trans with (2 ^ 64).
      auto.
      apply (Z.pow_le_mono 2 64 2 n).
      lia.
      auto.
    }
    symmetry.
    apply (Z.testbit_unique z n false z 0).
    lia.
    simpl.
    lia.
  }

  - auto.
  - auto.
  - auto.
  - auto.
  - auto.
  - auto.
  - auto.
  - subst z7.
    apply (byteInRange z 0 (conj Hrange0 Hrange1)).
    lia.
  - subst z6; auto.
  - subst z5; auto.
  - subst z4; auto.
  - subst z3; auto.
  - subst z2; auto.
  - subst z1; auto.
  - subst z0; auto.
Qed.

8.32. roctetorder/src/main/rocq/OctetOrder.v

(*
 * Copyright © 2025 Mark Raynsford <code@io7m.com> https://www.io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *)

Require Import Stdlib.PArith.PArith.
Require Import Stdlib.Init.Nat.
Require Import Stdlib.Arith.PeanoNat.
Require Import Stdlib.Lists.List.

Import ListNotations.

(** The property of _x_ being divisible by 8. *)
Definition divisible8 (x : nat) : Prop :=
  modulo x 8 = 0.

(** An octet is either in big or little endian order. *)
Inductive octetOrder : Set :=
  | OctetOrderBig
  | OctetOrderLittle.

(** A single bit. *)
Inductive bit : Set :=
  | B0
  | B1.

(** A sequence of bits may be divided into groups of eight bits known as octets.
    We avoid the use of the term byte because a byte hasn't consistently been
    equivalent to eight bits throughout all of computing history. An octet may
    either be exact or a remainder. An octet may be a remainder if the length
    of the sequence of bits used to produce it was not evenly divisible by 8.
    The first n groups of 8 bits consumed from a sequence of bits s will produce
    octets that are exact, with the remaining k bits (where k < 8) will produce
    at most one remainder octet. The remainder octet, if any, has its least
    significant 8 - k bits set to 0. *)
Inductive octet : Set :=
  | OctExact  : bit -> bit -> bit -> bit -> bit -> bit -> bit -> bit -> octet
  | OctRemain : bit -> bit -> bit -> bit -> bit -> bit -> bit -> bit -> octet.

#[local]
Definition listInduction8 :
  forall (A : Type),
  forall (P : list A -> Prop),
  P [] ->
  (forall (b0                      : A), P (b0 :: [])) ->
  (forall (b1 b0                   : A), P (b1 :: b0 :: [])) ->
  (forall (b2 b1 b0                : A), P (b2 :: b1 :: b0 :: [])) ->
  (forall (b3 b2 b1 b0             : A), P (b3 :: b2 :: b1 :: b0 :: [])) ->
  (forall (b4 b3 b2 b1 b0          : A), P (b4 :: b3 :: b2 :: b1 :: b0 :: [])) ->
  (forall (b5 b4 b3 b2 b1 b0       : A), P (b5 :: b4 :: b3 :: b2 :: b1 :: b0 :: [])) ->
  (forall (b6 b5 b4 b3 b2 b1 b0    : A), P (b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: b0 :: [])) ->
  (forall (b7 b6 b5 b4 b3 b2 b1 b0 : A) (rest : list A), P rest -> P (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: b0 :: rest)) ->
  forall (L : list A), P L :=
  (fun A P P0 P1 P2 P3 P4 P5 P6 P7 P8 =>
  fix f (l : list A) :=
    match l with
    | []                                                     => P0
    | x0 :: []                                               => P1 x0
    | (x0 :: x1 :: [])                                       => P2 x0 x1
    | (x0 :: x1 :: x2 :: [])                                 => P3 x0 x1 x2
    | (x0 :: x1 :: x2 :: x3 :: [])                           => P4 x0 x1 x2 x3
    | (x0 :: x1 :: x2 :: x3 :: x4 :: [])                     => P5 x0 x1 x2 x3 x4
    | (x0 :: x1 :: x2 :: x3 :: x4 :: x5 :: [])               => P6 x0 x1 x2 x3 x4 x5
    | (x0 :: x1 :: x2 :: x3 :: x4 :: x5 :: x6 :: [])         => P7 x0 x1 x2 x3 x4 x5 x6
    | (x0 :: x1 :: x2 :: x3 :: x4 :: x5 :: x6 :: x7 :: rest) => P8 x0 x1 x2 x3 x4 x5 x6 x7 rest (f rest)
    end).

#[local]
Lemma app_non_empty : forall (A : Type) (xs : list A) (y : A),
  xs ++ [y] <> [].
Proof.
  intros A xs y.
  unfold not.
  destruct xs as [|z zs].
    intros Hfalse; inversion Hfalse.
    intros Hfalse; inversion Hfalse.
Qed.

#[local]
Lemma app_list_implies_eq : forall (A : Type) (x y : A) (xs : list A),
  xs ++ [x] = [y] -> xs = [] /\ x = y.
Proof.
  intros A x y xs Happ.
  induction xs as [|z zs] eqn:Hxe.
  - constructor. reflexivity.
    rewrite (app_nil_l [x]) in Happ.
    injection Happ as Heq; exact Heq.
  - inversion Happ.
    assert (zs ++ [x] <> []) by (apply app_non_empty).
    contradiction.
Qed.

#[local]
Lemma p8notZ : 8 <> 0.
Proof. discriminate. Qed.

#[local]
Lemma list_mod8_0 : forall (A : Type) (xs : list A) (n7 n6 n5 n4 n3 n2 n1 n0 : A),
  divisible8 (length xs) -> divisible8 (length (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: xs)).
Proof.
  intros A xs n7 n6 n5 n4 n3 n2 n1 n0 Hlen8.
  unfold divisible8 in *.
  assert (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: xs
       = (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: []) ++ xs) as HlistEq
          by reflexivity.
  rewrite HlistEq.
  rewrite length_app.
  assert (length [n7; n6; n5; n4; n3; n2; n1; n0] = 8) as Hprefix8 by reflexivity.
  rewrite Hprefix8.
  rewrite <- (Nat.Div0.add_mod_idemp_l 8 (length xs) 8).
  rewrite (Nat.Div0.mod_same 8).
  rewrite (Nat.add_0_l).
  exact Hlen8.
Qed.

#[local]
Lemma list_mod8_1 : forall (A : Type) (xs : list A) (n7 n6 n5 n4 n3 n2 n1 n0 : A),
  divisible8 (length (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: xs)) -> divisible8 (length xs).
Proof.
  intros A xs n7 n6 n5 n4 n3 n2 n1 n0 Hlen8.
  unfold divisible8 in *.
  assert (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: xs
       = (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: []) ++ xs) as HlistEq
          by reflexivity.
  rewrite HlistEq in Hlen8.
  rewrite length_app in Hlen8.
  assert (length [n7; n6; n5; n4; n3; n2; n1; n0] = 8) as Hprefix8 by reflexivity.
  rewrite Hprefix8 in Hlen8.
  rewrite <- (Nat.Div0.add_mod_idemp_l 8 (length xs) 8) in Hlen8.
  rewrite (Nat.Div0.mod_same 8) in Hlen8.
  rewrite (Nat.add_0_l) in Hlen8.
  exact Hlen8.
Qed.

#[local]
Theorem list_mod8 : forall (A : Type) (xs : list A) (n7 n6 n5 n4 n3 n2 n1 n0 : A),
  divisible8 (length xs) <-> divisible8 (length (n7 :: n6 :: n5 :: n4 :: n3 :: n2 :: n1 :: n0 :: xs)).
Proof.
  intros A xs n7 n6 n5 n4 n3 n2 n1 n0.
  constructor.
  - apply list_mod8_0.
  - apply list_mod8_1.
Qed.

#[local]
Lemma mod_8_lt_0 : forall (m : nat),
  0 < m mod 8 -> 0 < (m + 8) mod 8.
Proof.
  intros m Hlt.
  rewrite (Nat.Div0.add_mod m 8 8).
  rewrite (Nat.Div0.mod_same).
  rewrite (Nat.add_0_r).
  rewrite (Nat.Div0.mod_mod).
  exact Hlt.
Qed.

#[local]
Lemma mod_8_lt_1 : forall (m : nat),
  0 < (m + 8) mod 8 -> 0 < m mod 8.
Proof.
  intros m Hlt.
  rewrite (Nat.Div0.add_mod m 8 8) in Hlt.
  rewrite (Nat.Div0.mod_same)      in Hlt.
  rewrite (Nat.add_0_r)            in Hlt.
  rewrite (Nat.Div0.mod_mod)       in Hlt.
  exact Hlt.
Qed.

#[local]
Lemma mod_8_lt : forall (m : nat),
  0 < (m + 8) mod 8 <-> 0 < m mod 8.
Proof.
  constructor.
  apply mod_8_lt_1.
  apply mod_8_lt_0.
Qed.

Definition octetIsRemainder (o : octet): Prop :=
  match o with
  | OctExact  _ _ _ _ _ _ _ _ => False
  | OctRemain _ _ _ _ _ _ _ _ => True
  end.

Definition octetIsExact (o : octet): Prop :=
  match o with
  | OctExact  _ _ _ _ _ _ _ _ => True
  | OctRemain _ _ _ _ _ _ _ _ => False
  end.

Lemma octetIsRemainderNotExact : forall (o : octet), octetIsRemainder o -> ~octetIsExact o.
Proof.
  intros o Hrem Hfalse.
  destruct o; contradiction.
Qed.

Lemma octetIsExactNotRemainder : forall (o : octet), octetIsExact o -> ~octetIsRemainder o.
Proof.
  intros o Hrem Hfalse.
  destruct o; contradiction.
Qed.

Inductive bitsOctetsHasRemainder : list octet -> Prop :=
  | BOHasRemainder : forall (prefix : list octet) (o : octet),
    Forall octetIsExact prefix ->
      octetIsRemainder o ->
        bitsOctetsHasRemainder (prefix ++ o :: []).

(** If the sequence of octets o produced is arranged such that the first bit of s
    appears as the most significant bit of the first octet in o, then o is said to
    be in big-endian order. *)
Fixpoint octetsBigEndianAux
  (bits   : list bit)
  (octets : list octet)
: list octet :=
  match bits with
  | (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: b0 :: rest) =>
    octets ++ [OctExact b7 b6 b5 b4 b3 b2 b1 b0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 b3 b2 b1 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 b3 b2 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: b3 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 b3 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: b4 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 b4 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: b5 :: rest) =>
    octets ++ [OctRemain b7 b6 b5 B0 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: b6 :: rest) =>
    octets ++ [OctRemain b7 b6 B0 B0 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | (b7 :: rest) =>
    octets ++ [OctRemain b7 B0 B0 B0 B0 B0 B0 B0] ++ octetsBigEndianAux rest []
  | [] =>
    octets
  end.

Definition octetsBigEndian (bits : list bit) : list octet :=
  octetsBigEndianAux bits [].

(** If the sequence of octets o produced is arranged such that the first bit of
    s appears as the most significant bit of the last octet in o, then o is said
    to be in little-endian order. *)
Definition octetsLittleEndian (bits : list bit) : list octet :=
  rev (octetsBigEndianAux bits []).


(** A sequence of bits s such that divisible8 (length s) will produce a sequence
    consisting of entirely exact octets. *)
Theorem octetsBigEndianLengthDivisibleAllExact : forall (b : list bit),
  divisible8 (length b) -> Forall octetIsExact (octetsBigEndian b).
Proof.
  intros b Hlen8.
  unfold octetsBigEndian.
  induction b using listInduction8.
  - constructor.
  - inversion Hlen8.
  - inversion Hlen8.
  - inversion Hlen8.
  - inversion Hlen8.
  - inversion Hlen8.
  - inversion Hlen8.
  - inversion Hlen8.
  - simpl.
    rewrite <- list_mod8 in Hlen8.
    assert (Forall octetIsExact (octetsBigEndianAux b []))   as HallExact by (apply (IHb Hlen8)).
    assert (octetIsExact (OctExact b7 b6 b5 b4 b3 b2 b1 b0)) as Hexact    by constructor.
    apply (@Forall_cons octet octetIsExact (OctExact b7 b6 b5 b4 b3 b2 b1 b0) (octetsBigEndianAux b []) Hexact HallExact).
Qed.

(** A sequence of bits s such that divisible8 (length s) will produce a sequence
    consisting of entirely exact octets. *)
Theorem octetsLittleEndianLengthDivisibleAllExact : forall (b : list bit),
  divisible8 (length b) -> Forall octetIsExact (octetsLittleEndian b).
Proof.
  intros b Hlen8.
  apply (Forall_rev (octetsBigEndianLengthDivisibleAllExact b Hlen8)).
Qed.

Theorem octetsBigEndianLengthDivisibleNoRemainder : forall (b : list bit),
  Forall octetIsExact (octetsBigEndian b) -> ~bitsOctetsHasRemainder (octetsBigEndian b).
Proof.
  intros b HallExact.
  unfold octetsBigEndian.
  intro Hfalse.
  inversion Hfalse as [prefix o HprefixAllExact HoIsRemainder HprefixEq].
  unfold octetsBigEndian in HallExact.
  (* We know that everything in the list is exact. *)
  (* We can show that o must be in this list according to HprefixEq. *)
  assert (In o (octetsBigEndianAux b [])) as HoInB. {
    assert (In o (prefix ++ [o])) as HoInPrefix by (apply (in_elt o prefix [])).
    rewrite HprefixEq in HoInPrefix.
    exact HoInPrefix.
  }
  (* And because o is in the list, it must be exact. *)
  assert (octetIsExact o) as HoIsExact. {
    rewrite Forall_forall in HallExact.
    apply (HallExact o HoInB).
  }
  (* There is a contradiction; o cannot be both exact and a remainder. *)
  apply (octetIsExactNotRemainder o HoIsExact HoIsRemainder).
Qed.

(** A sequence of bits s such that ¬ divisible8 (length s) will produce a remainder octet. *)
Theorem octetsBigEndianLengthIndivisibleRemainder : forall (b : list bit),
  0 < length b mod 8 -> exists o, In o (octetsBigEndian b) /\ octetIsRemainder o.
Proof.
  intros b Hlength.
  induction b using listInduction8.
  - inversion Hlength.
  - exists (OctRemain b0 B0 B0 B0 B0 B0 B0 B0).
    constructor.
    left. reflexivity.
    constructor.
  - exists (OctRemain b1 b0 B0 B0 B0 B0 B0 B0).
    constructor.
    left.
    constructor.
    constructor.
  - exists (OctRemain b2 b1 b0 B0 B0 B0 B0 B0).
    constructor.
    left.
    constructor.
    constructor.
  - exists (OctRemain b3 b2 b1 b0 B0 B0 B0 B0).
    constructor.
    left.
    constructor.
    constructor.
  - exists (OctRemain b4 b3 b2 b1 b0 B0 B0 B0).
    constructor.
    left.
    constructor.
    constructor.
  - exists (OctRemain b5 b4 b3 b2 b1 b0 B0 B0).
    constructor.
    left.
    constructor.
    constructor.
  - exists (OctRemain b6 b5 b4 b3 b2 b1 b0 B0).
    constructor.
    left.
    constructor.
    constructor.
  - assert (0 < length b mod 8) as Hlt. {
      assert (length (b7 :: b6 :: b5 :: b4 :: b3 :: b2 :: b1 :: b0 :: b) = length b + 8) as Heq
        by (rewrite Nat.add_comm; reflexivity).
      rewrite Heq in Hlength.
      rewrite <- (mod_8_lt (length b)).
      exact Hlength.
    }
    assert (exists o : octet, In o (octetsBigEndian b) /\ octetIsRemainder o) as HEx
      by (apply (IHb Hlt)).
    destruct HEx as [ox [HoxIn HoxRem]].
    simpl.
    exists ox.
    constructor.
    right.
    exact HoxIn.
    exact HoxRem.
Qed.

(** A sequence of bits s such that ¬ divisible8 (length s) will produce a remainder octet. *)
Theorem octetsLittleEndianLengthIndivisibleRemainder : forall (b : list bit),
  0 < length b mod 8 -> exists o, In o (octetsLittleEndian b) /\ octetIsRemainder o.
Proof.
  unfold octetsLittleEndian.
  intros b Hlen.
  assert (exists o, In o (octetsBigEndian b) /\ octetIsRemainder o) as Hexists
    by (apply (octetsBigEndianLengthIndivisibleRemainder b Hlen)).
  destruct Hexists as [ox [HoxIn HoxRem]].
  exists ox.
  rewrite <- (in_rev (octetsBigEndianAux b [])).
  constructor.
  exact HoxIn.
  exact HoxRem.
Qed.
io7m | single-page | multi-page | Calino 2.0