# ASMF in MP4, version 1.0

This document is part 2 of the ASMF specification. Part 1 ([`asmf-format.md`](asmf-format.md)) defines the Aroma Signal
Media File document: one JSON text that describes a scent signal for one piece of media. This part defines how one
such document is carried inside an MP4 file, so that a single video or audio file carries its scent. In the way a codec
specification is accompanied by a rule for carrying that codec in a container, part 1 is the content format and this
part is the rule for carrying it in MP4.

The carriage is one timed-metadata track holding one sample, and that sample is the document. A player that does not
know the track plays the video or audio as usual. A player that knows it can find the document by reading the head of
the file only, and a tool can put, replace or remove the document without re-encoding the media and without changing a
byte of its media data.

## 1. Scope

This part defines:

- which files it covers (section 3);
- the scent track: its boxes, how a reader recognises it and which one it uses (section 4);
- how the times of the document relate to the movie (section 5);
- where a writer places the document in the file (section 6);
- how a reader extracts the document from an untrusted file, with its limits and errors (section 7);
- how a writer puts, replaces and removes the scent track, and which files it refuses (section 8);
- how the track relates to a sidecar `.asmf` file (section 9);
- what is reserved for later versions (section 10);
- how to check an implementation (section 13).

It does not define fragmented files, live streaming, segments of HTTP streaming formats, containers other than MP4, more
than one scent track per file, or compression, encryption or signing of the document. Section 10 reserves room for some
of these.

Box definitions are those of ISO/IEC 14496-12 (ISO base media file format); this part refers to boxes by their
four-character codes and to their fields by the names used there, and does not repeat their definitions. All integers
in boxes are big-endian.

## 2. Terminology

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and
"OPTIONAL" in this document are to be interpreted as described in BCP 14 (RFC 2119 and RFC 8174) when, and only when,
they appear in all capitals, as shown here.

- **Document**: one ASMF document (part 1).
- **MP4 file**: a file in the ISO base media file format, normally with the extension `.mp4`.
- **Box**: a box as defined by ISO/IEC 14496-12: a size, a four-character type, and a body. A **top-level box** is a
  box that is not inside another box. A box's **level** counts a top-level box as level 1, its children as level 2,
  and so on.
- **Header**: the size and type of a box: 8 bytes, or 16 bytes when the 32-bit size is 1 and a 64-bit size follows.
- **Scent track**: a track whose first sample entry identifies it as carrying an ASMF document (section 4.2).
- **ASMF-typed track**: a track whose first sample entry is a `mett` entry with the ASMF media type, whatever its
  `content_encoding` or sample count (section 4.2). Every scent track is one; a writer removes all of them (section 8.1).
- **Scent candidate**: a `trak` that a reader examines as a possible scent track (section 7.4, step 6).
- **Chunk offset table**: the `stco` or `co64` box of a track: the absolute file offsets of its chunks.
- **Reader**: software that extracts the document from an MP4 file. A **player** is a reader that plays the file (video,
  or audio only) with its scent.
- **Movie**: the presentation that an MP4 file holds, as ISO/IEC 14496-12 names it (`mvhd`); an audio-only file has one
  too.
- **Writer**: software that puts the scent track into an MP4 file, replaces it, or removes it.
- **Error code**: one of `NOT_MP4`, `TRUNCATED`, `BAD_BOX`, `TOO_LARGE`, `BAD_TRACK` and `UNSUPPORTED` (section 7.3).

## 3. Files covered

1. The carriage applies to files in the ISO base media file format (ISO/IEC 14496-12), in practice MP4 files, with
   video or with audio only (for example AAC audio in an `.m4a` file). Carrying a scent track does not change the
   file's extension or media type (`.mp4` and `video/mp4`, `.m4a` and `audio/mp4`).
2. A writer MUST NOT add a brand to `ftyp` for the scent track, and a reader MUST NOT require one. The presence of the
   scent track is known from the track itself.
3. Version 1.0 covers **non-fragmented** files only. A file whose `moov` contains an `mvex` box is fragmented; a 1.0
   reader treats it as having no scent (section 7.4), and a 1.0 writer refuses it (section 8.2).
4. A file need not have an `ftyp` box.

## 4. The ASMF track

### 4.1 Requirements

The document is carried as one timed-metadata track. A writer MUST write the track as follows; these are the
properties that readers and other software rely on. (The SHOULD items of this table and the field values of
section 4.4 beyond them are recommendations.)

| Item | Requirement |
|---|---|
| Track header | `tkhd` with the `track_enabled` flag (`0x000001`) set. |
| Handler | `hdlr` with `handler_type` `meta` (timed metadata). |
| Media header | `nmhd`. |
| Media timescale | The `timescale` of `mdhd` is greater than 0. |
| Sample entry | The first and only entry of `stsd` is `mett` (text metadata sample entry), with `content_encoding` the empty string and `mime_format` the string `application/vnd.aromajoin.asmf+json`, each terminated by a NUL byte. |
| Data reference | One self-contained entry (`url ` with flags 1, no location). |
| Samples | Exactly one sample. Its bytes are one document: UTF-8 without a byte order mark, at most 4194304 bytes (the document limit of part 1). The document MUST be valid, that is, have no structural error (part 1, sections 3 and 5.1) and no rule violation (part 1, sections 4 and 5.2), and SHOULD be in canonical form (part 1, section 11). |
| Sample size table | `stsz` (not `stz2`) with `sample_count` 1, giving the size of the sample: either as `sample_size`, or with `sample_size` 0 and one entry. |
| Chunks | The track has exactly one chunk, holding the one sample. `stsc` has one entry (`first_chunk` 1, `samples_per_chunk` 1, `sample_description_index` 1). The chunk offset table (`stco`, or `co64`) has one entry: the file offset of the first byte of the sample. |
| Sample time | `stts` has one entry: one sample, which starts at time 0. Its `sample_delta` is the duration of the track in the media timescale, limited to `0xFFFFFFFF`, the largest value the field holds; it is 0 when the movie's timescale is 0, since the movie's duration is then unknown. A reader of this part does not use this value. The track's duration SHOULD equal the movie's duration. |
| Edit list | None: a writer MUST NOT write `edts` in the scent track. |
| Track reference | When a track with handler `vide` stays in the file, a writer SHOULD write `tref` with a `cdsc` reference to the lowest `vide` track that stays in the file, by `track_ID` ("this track describes that video"). |
| Number | A 1.0 writer writes at most one scent track per file. |
| Placement | The sample is alone in its own `mdat` box (section 6). |

### 4.2 Identifying a scent track

A track is a scent track when the first entry of its sample description (`stsd`) is a `mett` entry whose
`content_encoding` is empty and whose `mime_format` equals `application/vnd.aromajoin.asmf+json`, compared ASCII
case-insensitively.

- A reader MUST NOT identify a scent track by its name, handler, position in `moov` or any other property. (A writer
  still writes the handler and media header of section 4.1, so that other software sees a timed-metadata track.)
- A `mett` track with a non-empty `content_encoding` is not a 1.0 scent track: a 1.0 reader ignores it. When it has the
  ASMF media type a 1.0 writer still removes it (section 8.1), so that no scent data stays behind after a put or a
  remove.

### 4.3 Choosing the track

1. Of the scent tracks whose sample count (from `stsz`) is exactly 1, a reader uses the one with the lowest `track_ID`
   (not the first in `moov` order). Of tracks with the same `track_ID`, it uses the first in `moov` order.
2. A scent track with a sample count other than 1 is ignored, as if it were absent. A scent track without `stsz` (for
   example one with `stz2`) has no usable sample count and is ignored.
3. A reader ignores an edit list (`edts`) of the scent track: the document's times are the movie's presentation times
   (section 5).
4. If no scent track qualifies, the file has no scent. This is not an error.

### 4.4 The track as written

The table gives the scent track that the reference writer adds, box by box and field by field. A writer SHOULD write
the track this way. Byte-identical output is required only to match the writer cases of section 13, which compare
output with files written this way; it is not a requirement of a conforming writer. All boxes have 8-byte
headers. The order of the boxes is the order of the table. Times are 0 because the format does not depend on a clock.

| Box | Field | Size | Value |
|---|---|---|---|
| `trak` | | | Contains `tkhd`, `tref` (when present), `mdia`. |
| `tkhd` | version, flags | 1, 3 | 0 when the movie duration fits 32 bits, else 1; flags `0x000003` (enabled, in movie). |
| | creation_time, modification_time | 4 + 4 (version 1: 8 + 8) | 0, 0. |
| | track_ID | 4 | The new track ID (section 8.3, step 4). |
| | reserved | 4 | 0. |
| | duration | 4 (version 1: 8) | The movie duration from `mvhd`, in the movie timescale. |
| | reserved, layer, alternate_group, volume, reserved | 8, 2, 2, 2, 2 | 0. |
| | matrix | 36 | `0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000` (unity). |
| | width, height | 4, 4 | 0, 0. The box is 92 bytes (version 1: 104). |
| `tref` | | | Only when a `vide` track stays in the file. 20 bytes. |
| `cdsc` | track_ID | 4 | The lowest `track_ID` of the `vide` tracks that stay in the file. 12 bytes. |
| `mdia` | | | Contains `mdhd`, `hdlr`, `minf`. |
| `mdhd` | version, flags | 1, 3 | 0, 0. |
| | creation_time, modification_time | 4, 4 | 0, 0. |
| | timescale | 4 | 1000 (milliseconds). |
| | duration | 4 | The movie duration in milliseconds, rounded down: `floor(duration × 1000 / timescale)` of `mvhd`, at most `0xFFFFFFFF`; 0 when the movie timescale is 0. |
| | language, pre_defined | 2, 2 | `0x55C4` (`und`), 0. The box is 32 bytes. |
| `hdlr` | version, flags | 1, 3 | 0, 0. |
| | pre_defined | 4 | 0. |
| | handler_type | 4 | `meta`. |
| | reserved | 12 | 0. |
| | name | 5 | `ASMF` and a NUL byte. The box is 37 bytes. |
| `minf` | | | Contains `nmhd`, `dinf`, `stbl`. |
| `nmhd` | version, flags | 1, 3 | 0, 0. The box is 12 bytes. |
| `dinf` | | | Contains `dref`. |
| `dref` | version, flags, entry_count | 1, 3, 4 | 0, 0, 1. |
| `url ` | version, flags | 1, 3 | 0, 1 (self-contained); no location. The box is 12 bytes. |
| `stbl` | | | Contains `stsd`, `stts`, `stsc`, `stsz`, then `stco` or `co64`. |
| `stsd` | version, flags, entry_count | 1, 3, 4 | 0, 0, 1. |
| `mett` | reserved, data_reference_index | 6, 2 | 0, 1. |
| | content_encoding | 1 | A NUL byte (the empty string). |
| | mime_format | 36 | `application/vnd.aromajoin.asmf+json` and a NUL byte. The box is 53 bytes. |
| `stts` | version, flags, entry_count | 1, 3, 4 | 0, 0, 1. |
| | sample_count, sample_delta | 4, 4 | 1, the `mdhd` duration. |
| `stsc` | version, flags, entry_count | 1, 3, 4 | 0, 0, 1. |
| | first_chunk, samples_per_chunk, sample_description_index | 4, 4, 4 | 1, 1, 1. |
| `stsz` | version, flags | 1, 3 | 0, 0. |
| | sample_size, sample_count | 4, 4 | 0, 1. |
| | entry_size | 4 | The length of the document in bytes. |
| `stco` | version, flags, entry_count | 1, 3, 4 | 0, 0, 1. |
| | chunk_offset | 4 | The file offset of the first byte of the document. |
| `co64` | (instead of `stco`) | 1, 3, 4, 8 | The same, with a 64-bit offset; written when the offset exceeds `0xFFFFFFFF`. |

The `mdat` that holds the sample has an 8-byte header (size = document length + 8, type `mdat`) followed by the document
and nothing else; the chunk offset is the offset of that `mdat` plus 8.

With a `tref` and a 32-bit `stco`, the `trak` is 426 bytes; without a `tref`, 406 bytes. A `co64` adds 4 bytes and a
version 1 `tkhd` adds 12.

## 5. Time base

1. The times of the document (`startMs`, `endMs`, the fades of part 1) are presentation times of the movie in
   milliseconds, counted from 0 at the start of playback: the position that a player reports while it plays the file.
   They do not depend on the timescale of the scent track or on any edit list of the scent track.
2. Spans of the document that lie beyond the end of the movie are not emitted.
3. A document's `media.durationMs` that differs from the movie's duration is not an error. A writer SHOULD set
   `media.durationMs` to the movie's duration in milliseconds, rounded down.

## 6. Placement

A reader MUST find the sample wherever it is in the file (section 7). A writer places it so that a reader can get the
document from the head of the file with one or two range requests (first the head with `moov`, then the sample), and so
that a later replacement only rewrites `moov` and the sample's own box:

1. The sample MUST be alone in its own `mdat` box: that `mdat` holds no byte of any other track. Then replacing or
   removing the document leaves no byte of the old document in the file (section 8.5).
2. `moov` SHOULD come before the media data ("fast start").
3. A document of at most 262144 bytes (256 KiB) MUST be placed in an `mdat` immediately after `moov`, before any other
   media data that follows `moov`. A larger document MUST be placed in an `mdat` at the end of the file, so that a
   player that does not know the track does not have to receive a large document before playback can start. (Typical
   documents are a few kilobytes.)
4. A writer that rewrites a file whose `moov` is at the end MAY keep it there; the `mdat` of a small document then
   follows `moov` at the end of the file.

## 7. Reading

A reader treats every file as untrusted: the file may be damaged, or written to exhaust memory or time. It checks every
size, count and offset against the bytes that are there before it uses them, performs arithmetic on them without
overflow, and never allocates memory in proportion to a count that the file declares.

### 7.1 Results

Reading a file gives exactly one of three results:

- **No scent**: the file has no scent track the reader uses (none at all, a fragmented file, or only scent tracks that a
  1.0 reader ignores). This is not an error.
- **A document**: the bytes of the sample, which the reader then passes to part 1 (section 7.6).
- **A problem**: an error code and the file offset where the problem was found (section 7.3).

A problem with the file or with its document MUST NOT stop the video or audio from playing: a player reports it and
plays the file without scent.

### 7.2 Limits

| Limit | Value | When it is exceeded |
|---|---|---|
| Document (the sample) | `4194304` bytes (4 MiB) | `TOO_LARGE`, judged on the declared size before the sample is read. |
| `moov` | `134217728` bytes (128 MiB) | `TOO_LARGE`, judged on the declared size before `moov` is read. |
| Box nesting inside `moov` | `16` levels (`moov` is level 1) | `TOO_LARGE` at the first box below level 16. |
| Tracks | `256` `trak` boxes in `moov` | `TOO_LARGE` at the 257th `trak`. |
| Top-level boxes walked | `4096` | `TOO_LARGE` at the 4097th top-level box. |
| Placement of a document after `moov` (writers) | `262144` bytes (256 KiB) | Section 6. |
| First range request of an incremental reader | `65536` bytes (64 KiB) | Section 7.5. |

A reader MUST apply the first five limits with these values, so that all readers agree on which files they accept.

### 7.3 Errors

Every problem has one of these codes and the file offset of the box or field where it was found (0 for problems of the
whole file). Offsets help to locate a problem; the test vectors compare codes only.

| Code | Meaning |
|---|---|
| `NOT_MP4` | The input is not an MP4 file: the first top-level box is not a plausible box (step 1 of section 7.4), or the top-level boxes are valid but none is `moov`. An empty file is `NOT_MP4`. Offset 0. |
| `TRUNCATED` | `moov` ends beyond the end of the file (at `moov`), or reading the input (or, for a writer, writing the output) failed. |
| `BAD_BOX` | A box or a field in it is malformed: a top-level box after the first that is not plausible; a box inside `moov` whose size is 0, smaller than its header or larger than what remains of its parent; a table that declares more entries than its box holds; a field that runs past the end of its box; a required box that is missing (`mvhd`, or `tkhd` in a scent candidate); a `stsd` whose entry count differs from the entries it holds; a sample entry whose body is shorter than the 8 bytes of `reserved` and `data_reference_index`; a `mett` entry whose strings are not both NUL-terminated. (Inside tracks, these apply to the tracks a reader reads in full: scent candidates, step 7 of section 7.4, and every track for a writer.) |
| `TOO_LARGE` | A limit of section 7.2 is exceeded. |
| `BAD_TRACK` | The scent track the reader uses is broken: its sample has no chunk offset, lies (in part) outside the file, or overlaps `moov`. |
| `UNSUPPORTED` | A reader meets a version of `mvhd` or `tkhd` other than 0 or 1; a writer refuses the file (section 8.2). |

### 7.4 Steps

A reader extracts the document as follows. The result of a file with several problems is the first one met: problems
are reported in the order of these steps and, within a step, in file order. Within step 7 the box sizes of a candidate
come before its fields. So every reader gives the same error code for the same file.

1. **Walk the top-level boxes** from offset 0. For each box:
   1. If 4096 top-level boxes have been walked without finding `moov` and the end of the file is not reached, the
      result is `TOO_LARGE` at the offset of the next box. A `moov` that is the 4096th top-level box is accepted (the
      walk stops there, sub-step 4).
   2. Read its header. A 32-bit size of 1 means a 64-bit size follows (16-byte header); a size of 0 means the box
      extends to the end of the file, which makes it the last box.
   3. The box is plausible when its header is complete, its type is four printable ASCII bytes (`0x20` to `0x7E`), its
      size is at least its header length and the box ends within the file. A box typed `moov` is judged first on its
      declared size: more than 134217728 bytes is `TOO_LARGE`, and ending beyond the file is `TRUNCATED`, even when it
      is the first box (a plausible header typed `moov` is evidence enough that the file is an MP4 file). Any other
      box that is not plausible is `NOT_MP4` (offset 0) when it is the first top-level box and `BAD_BOX` at the box
      otherwise.
   4. Stop at the first `moov`. A reader does not examine what follows it.

   If the end of the file is reached without a `moov`, the result is `NOT_MP4`.
2. **Read `moov`.** Check the sizes of the boxes inside it, descending into the boxes whose body is nothing but boxes
   (`moov`, `trak`, `mdia`, `minf`, `stbl`, `dinf`, `edts`, `mvex`): a size of 0 is `BAD_BOX` (size 0 is accepted only
   for the last top-level box), as is a size smaller than the header or larger than what remains of the parent. A
   reader MUST be able to read the children of `moov` (level 2) and of each `trak` (level 3); a box at a deeper level
   whose size is wrong ends the walk of its parent without an error, unless it is inside a scent candidate (step 6).
   Any box below level 16 is `TOO_LARGE`, in any track.
3. **Count the tracks.** More than 256 `trak` boxes is `TOO_LARGE`.
4. **Read `mvhd` and look for `mvex`**, wherever they are among the children of `moov` and before any track: the version
   of the first `mvhd` MUST be 0 or 1 (`UNSUPPORTED` otherwise), and a `moov` without `mvhd` is `BAD_BOX`.
5. **Fragmented files.** If `moov` contains `mvex`, the result is no scent. No track is read, so a problem in the fields
   of a track of a fragmented file is not reported; problems found at steps 2 to 4 still are.
6. **Find the scent candidates.** A `trak` is a scent candidate when, following the first `mdia`, its first `minf`, its
   first `stbl` and its first `stsd`, the first sample entry is `mett` with an empty `content_encoding` and the ASMF
   media type (section 4.2). A track that cannot be read that far, whose first sample entry is shorter than 8 bytes
   after its header, or whose `mett` strings cannot be read, is not a candidate. Problems inside tracks that are not
   candidates do not fail extraction: a player must not lose the scent because of an oddity in a video or sound track.
   The limits and the readability of levels 2 and 3 (steps 2 and 3) still apply to the whole file.
7. **Read each candidate in full**, in file order. Every box size in the candidate is checked without exception, and
   every problem in it is an error.
   1. For these kinds only the first box counts and later ones of the same kind are skipped: `tkhd` and `mdia` in
      `trak`; `hdlr` and `minf` in `mdia`; `stbl` in `minf`; `stsd`, `stsz` and the chunk offset table in `stbl`,
      where `stco` and `co64` count as one kind.
   2. `stsc` and `stts` are not used for extraction, but every `stsc` and every `stts` in that `stbl` is checked: its
      entry count MUST fit in its box (12-byte entries for `stsc`, 8-byte entries for `stts`), else `BAD_BOX`.
   3. A candidate MUST have a `tkhd` of version 0 or 1, from which the reader takes `track_ID`.
   4. The entry count of `stsd` MUST fit in its box (at least 16 bytes per entry) and MUST equal the number of entries
      it holds; every entry MUST have at least 8 bytes after its header. The entry counts of `stco` and `co64`, and
      of `stsz` when its `sample_size` is 0, MUST fit in their boxes. (With a non-zero `sample_size`, `stsz` has no
      per-sample table and its count is not compared with the box.) Each failure is `BAD_BOX`.
   5. The sample count is the `sample_count` of `stsz` (0 when the track has no `stsz`).
8. **Choose the track** by section 4.3. If none qualifies, the result is no scent.
9. **Locate the sample.** Its offset is the first entry of the chunk offset table; its size is the `sample_size` of
   `stsz` when that is not 0, otherwise the first entry of `stsz`. Check, in this order, on the declared values and
   before reading anything:
   1. no chunk offset table, or one with no entry: `BAD_TRACK`;
   2. a size larger than 4194304 bytes: `TOO_LARGE`;
   3. a sample that ends beyond the end of the file: `BAD_TRACK`;
   4. a sample (of non-zero size) that overlaps `moov`: `BAD_TRACK`.
10. **Read the sample.** Its bytes are the document.

### 7.5 Reading with range requests

The steps above need only the top-level box headers, `moov` and the sample. A reader that fetches the file in ranges
(for example HTTP range requests or reads from object storage) can therefore extract the document without receiving the
media data. The reference implementation first asks for the first 65536 bytes of the file (or the whole file when it
is shorter; an empty file needs no request and is `NOT_MP4`), then for any further top-level box headers it needs (16
bytes at a time), then for `moov` in one range if it was not in what it already holds, then for the sample. It never asks for a byte outside the file or for a byte it
already holds. With the placement of section 6, a file written by a conforming writer usually needs one or two
requests.

### 7.6 The document

A reader passes the bytes of the sample to part 1 unchanged: they MUST be UTF-8 without a byte order mark (a byte order
mark is reported as part 1 reports it, and is not stripped), and they are parsed and validated by the rules of part 1.
The outcome for the player is one of:

- **no scent**: the file has none; play it as usual;
- **a valid document**: the document parses and has no rule violation; play it as part 1, section 10 describes;
- **a problem**: the sample is not UTF-8, does not parse, or breaks rules, or the file itself has a problem
  (section 7.3); report it and play the file without scent.

A problem never blocks playback.

## 8. Writing

### 8.1 Operations

- **Put**: add a scent track carrying a document. If the file already has ASMF-typed tracks, put replaces them: every
  one is removed, including tracks a reader ignores (for example one with two samples, or with a non-empty
  `content_encoding`), and then exactly one scent track is added. **Replace** is a put on a file that has such a track.
- **Remove**: remove every ASMF-typed track. Removing from a file without one gives the input unchanged.

None of the operations re-encodes or changes media data: every chunk of every other track keeps its bytes. What changes
is `moov` (tracks removed and added, `mvhd.next_track_ID`, the chunk offset tables moved by the change) and the `mdat`
holding the scent sample.

### 8.2 Files a writer accepts

A writer changes the position of top-level boxes, so it accepts only files in which every absolute file offset it must
adjust is in a chunk offset table: self-contained, non-fragmented, unencrypted files. A writer MUST refuse, with
`UNSUPPORTED` at the offending box and without producing any output, a file that has:

1. `mvex` in `moov` (refused at the offset of `moov`), or a top-level `moof`, `mfra`, `sidx` or `ssix` box (a fragmented
   file);
2. a `dref` (in `trak` > `mdia` > `minf` > `dinf`) with an entry that is not self-contained (flags bit 0 clear), or a
   `dref` that cannot be read (its entry count differs from its entries);
3. an `sinf`, `saio` or `senc` box anywhere in `moov` (encryption);
4. an `iloc` box anywhere in `moov`, or any top-level `meta` box (item locations hold absolute offsets that the writer
   does not adjust).

A writer reads the layout of the file strictly: unlike a reader, it reads every track in full, and any problem in any
track is an error for writing (for example `BAD_BOX` for a second `stsd` in one `stbl`). The one exception is a file
with `mvex` in `moov`: its tracks are not read (section 7.4, step 5), so that it is refused as `UNSUPPORTED` whatever
the fields of its tracks hold; box sizes and nesting, the number of tracks and `mvhd` (steps 2 to 4 of that section) are
still checked first, at every level. A writer walks every top-level box, not only those up to `moov`, and a second
`moov` is `BAD_BOX`. The limits of section 7.2 apply. A writer refuses rather than guesses: a file it cannot rewrite
safely is left as it is. Reading (section 7) still works on files a writer refuses.

The reference implementation finds the boxes of items 3 and 4 by scanning the bytes of `moov` for the type code
preceded by a plausible size. An unlucky run of bytes can make it refuse a file that has no such box; it can never
make it write one.

### 8.3 Steps

A writer puts or removes the scent track as follows. Every check comes before any output is produced.

1. **Read the layout** strictly (section 8.2): the top-level boxes in file order, and `moov`.
2. **Refuse** the files of section 8.2 (`UNSUPPORTED`).
3. **Put**: a document larger than 4194304 bytes is `TOO_LARGE`.
4. **Put**: the new track takes `track_ID` = max(`next_track_ID`, highest `track_ID` + 1), where the highest is taken
   over every track of the input, including the tracks being removed, and a `next_track_ID` of `0xFFFFFFFF`
   ("search for a free ID") counts as 0. Track IDs are never reused. If the highest `track_ID` is already `0xFFFFFFFF`,
   the file is refused (`UNSUPPORTED`). `mvhd.next_track_ID` becomes the new `track_ID` + 1 (it stays `0xFFFFFFFF`
   when the new `track_ID` is `0xFFFFFFFF`). A remove leaves `next_track_ID` unchanged. Because of this rule, putting
   the same document twice gives a file that differs from the first result only in `mvhd.next_track_ID` and the new
   track's `track_ID`.
5. **Decide the top-level boxes of the output**, keeping the input order:
   1. a top-level `mdat` that holds (in its body) a chunk of a track being removed and no chunk of any other track is
      dropped;
   2. `moov` is replaced by the rewritten `moov`;
   3. for a put, the scent `mdat` is inserted immediately after `moov` when the document is at most 262144 bytes, and
      at the end of the file otherwise;
   4. every other top-level box is copied unchanged.
6. **Check the output against the limits**: more than 256 tracks is `TOO_LARGE` (at `moov`), more than 4096 top-level
   boxes is `TOO_LARGE` (offset 0). A writer MUST NOT produce a file that a reader would refuse for its limits.
7. **A size-0 last box.** When the input's last top-level box has size 0 ("to the end of the file") and a box now
   follows it, its header is rewritten with its explicit 32-bit size. If its size does not fit 32 bits, the file is
   refused (`UNSUPPORTED`). A size-0 box that stays last and is copied keeps size 0. A `moov` is never copied: a
   `moov` written with size 0 is always replaced by the rewritten `moov`, which has an explicit size (step 8).
8. **Rewrite `moov`**:
   1. remove every `trak` that is an ASMF-typed track;
   2. for a put, set `mvhd.next_track_ID` (step 4) and append the new `trak` (section 4.4) at the end of `moov`;
   3. move every chunk offset of every kept track (section 8.4);
   4. copy every other box byte for byte, in its own header form; the containers on the path from `moov` to a chunk
      offset table get sizes computed from their new content and keep a 64-bit header when they had one.

   The rewritten `moov` always has an explicit size, in the header form (8 or 16 bytes) of the input `moov`. A
   rewritten `moov` larger than 134217728 bytes is `TOO_LARGE`.
9. **Produce the output**: the new bytes (the rewritten `moov`, the scent `mdat`, a rewritten size-0 header) and the
   ranges copied unchanged from the input, in order. The reference implementation answers with this list instead of a
   whole file, so that a large file need not be held in memory, and so that a storage service can copy the large
   ranges itself. The list records the length of the input, and the reference implementation refuses to carry it out
   over an input of another length (`BAD_BOX`, offset 0).

### 8.4 Chunk offsets

1. Every chunk offset of every kept track is moved with the top-level box that contains it: if the input box starts at
   offset `a`, its body starts at `b` and it ends at `e`, and the box starts at `a'` in the output, an offset `o` with
   `b ≤ o < e` becomes `a' + (o − a)`.
2. An offset that lies in no kept top-level box's body (for example inside `moov`, in a box header, in a dropped box or
   beyond the file) is `BAD_BOX` at its table. A writer MUST NOT guess.
3. A `stco` table whose moved offsets do not all fit 32 bits becomes a `co64` table (version, flags and any bytes after
   the entries are kept). A `co64` table stays `co64`. Since a larger table makes `moov` larger and moves the boxes
   after it again, the writer repeats the computation until no table changes. A value that does not fit is never
   written truncated.
4. The scent track's own table is `co64` when the document's offset does not fit 32 bits.

### 8.5 What stays and what goes

- A scent sample that was alone in its own `mdat` (as section 6 requires) goes with that `mdat`: after a replace or a
  remove, no byte of the old document remains in the file.
- A scent sample written by other software into an `mdat` that also holds other media cannot be cut out without moving
  that media. A replace or remove then removes the track, and the old document's bytes stay in that `mdat`,
  referenced by no track. To erase them, the file has to be written again from its media (for example by re-muxing).

### 8.6 The document

A writer MUST put only a document that is valid (no structural error and no rule violation, part 1, sections 3 to 5),
and SHOULD put it in canonical form (part 1, section 11). The reference implementation validates the document as given,
writes its canonical form, and refuses a document whose canonical text a reader would not accept (it parses and
validates that text again before writing it). The carriage itself does not alter the bytes it is given: the writer
cases of section 13 put each document text byte for byte.

### 8.7 Known limitation

A writer moves chunk offsets; it does not check the length of each chunk. In a valid file every chunk lies inside the
top-level box that holds its offset. In a malformed file whose chunk runs past the end of its top-level box, the bytes
beyond that box are not guaranteed to be preserved, because the box that follows may be dropped or moved.

## 9. Relation to sidecar files

Part 1 allows a document to sit next to its media as a sidecar file with the same base name (`video.mp4` and
`video.asmf`, `song.mp3` and `song.asmf`).

1. Media that is not an MP4 file (for example an MP3 file, or a video embedded from a web service) uses a sidecar
   file only.
2. When a player opens a local MP4 file and a `.asmf` file with the same base name is next to it, the sidecar file wins
   over the embedded track: it is more likely to be the newer edit, and the user placed it there on purpose.

## 10. Reserved for later

Version 1.0 leaves room for the following. What a 1.0 implementation does differs per item:

- **Fragmented files and live streaming**: a later version will carry the scent track's samples in time order across
  fragments. The intended principle: the list of aromas with their identifiers is carried once at the start, and the
  samples that follow refer to aromas by short numbers, so that identifiers are not compared during playback. A 1.0
  reader gives no scent for a fragmented file (`mvex`) and ignores a scent track with more than one sample.
- **Several scent tracks** (for example per language, or per device position): a 1.0 writer writes one. A 1.0 reader
  still gets a document from such a file: it uses the track with the lowest `track_ID` and ignores the others, which may
  not be the track a later rule would choose.
- **Document versions** follow part 1 (`asmf`, `requires`): the carriage does not change with the document version. A
  1.0 reader passes the sample to part 1, which can report a version or a required feature it does not support as a
  problem (section 7.6); the player then reports it and plays the file without scent.

## 11. Compatibility notes

This section is not normative.

- A service that delivers a scent signal separately from the media is outside this specification.
- The scent track is meant to be ignored by players that do not know it: it is an ordinary timed-metadata track with a
  sample entry defined by ISO/IEC 14496-12.
- Tools that re-mux or re-encode a file usually drop tracks they do not know, with their default settings, and so do
  many services that receive uploaded video or audio. Software that keeps the scent of an uploaded file should extract
  the document before such processing.
- Some players expect timed metadata in a different sample entry (for example `mebx`). Implementations are encouraged
  to test that the file still plays normally with the scent track on the players that matter to them.
- Data located relative to the end of a file (for example a vendor trailer) is kept but does not stay at the end when a
  document is placed at the end of the file (section 6).

## 12. Security considerations

- **Untrusted files.** Readers and writers accept files from anyone. Every size, count and offset MUST be checked
  against the bytes that are there before it is used; arithmetic on them MUST NOT overflow; memory MUST NOT be
  allocated in proportion to a declared count before the bytes that the count implies are known to exist (the
  reference implementation reports a table that declares more entries than its box holds as `BAD_BOX` before it reads
  any entry).
- **Bounded work.** The limits of section 7.2 bound memory (`moov`, the document), recursion (nesting) and time (tracks,
  top-level boxes). The size of `moov` and of the sample is judged on the declared size, before any of it is read.
  Every box walk advances by at least 8 bytes per box.
- **Sample location.** The sample MUST lie inside the file and outside `moov`; otherwise the track is `BAD_TRACK`. A
  reader never reads bytes that the file does not contain.
- **No blocking.** A problem with the scent never blocks playback (section 7.1).
- **The document is untrusted** like any other document; the security considerations of part 1 (section 16) apply to
  it, including those on error reports that embed text taken from the document.
- **Rewriting.** A writer refuses files it cannot rewrite exactly (section 8.2) and produces nothing for them, so a
  refusal cannot leave a damaged file. A writer that produces its output piece by piece can still fail part way
  through (for example when the destination is full); its output is then incomplete and MUST NOT be used.
- **Old documents.** After a replace or a remove, the old document is gone from a file written by the rules of this
  part, but stays in the file as unreferenced bytes when another tool had put it in a shared `mdat` (section 8.5).
  Anyone who must be sure that an old document is gone has to rewrite such a file.

## 13. Conformance

- A **conforming reader** follows section 7: it gives the same result as this specification for every input (no scent,
  the same document bytes, or the same error code).
- A **conforming writer** produces output that satisfies section 4.1 (the track) and section 6 (placement), from
  which a conforming reader extracts exactly the document that was put (or no scent after a remove), and in which the
  sample bytes of every other track are unchanged (section 8.1); it refuses the files of section 8.2. Byte-identical
  output is not required. A writer that also follows every SHOULD of section 4.4, the track ID rule of section 8.3
  (step 4), the box order of section 8.3 (steps 5 and 8) and the placement rules produces the committed outputs of the
  `write` cases byte for byte.

The shared test vectors in [`vectors/asmf-mp4-cases.json`](../vectors/asmf-mp4-cases.json), with the MP4 files under
[`vectors/mp4/`](../vectors/mp4/), check an implementation. The files use fake media data: nothing in them is meant to
be decoded. The cases file is one JSON object with a `description` and two sections, each an array of named cases:

| Section | Each case | An implementation passes when |
|---|---|---|
| `cases` | `name`; `file`, the path of an MP4 file relative to `vectors/`; `expected`; and optionally `layout` | Extracting the scent document from `file` gives `expected`: `{"found": "none"}` for no scent; `{"found": "document", "bytes": N, "text": T}` when the sample is exactly the N bytes of the (ASCII) text T; `{"error": CODE}` for a problem with that error code. When `layout` is present (`{"error": CODE}`), a writer that reads the whole file to rewrite it (section 8.2) gives that error; a case without `layout` makes no claim about writers. |
| `write` | `name`; `input`, an MP4 file relative to `vectors/`; `op`, `"put"` or `"remove"`; `document`, the exact document text (put only); `expected` | For `{"file": F}`: carrying out `op` on `input` (a put writes the `document` text byte for byte as the sample) gives output that is byte for byte the file F (relative to `vectors/`). For `{"error": CODE}`: the writer refuses `input` with that error code and produces nothing. |

Error offsets are not compared. The `write` cases with an expected file pin the choices of the reference writer
(section 4.4, the order of section 8.3); a conforming writer that makes other choices permitted by this specification
cannot match them byte for byte, and checks instead that a reader gives back the document from its output, that every
chunk of every other track points to the same bytes as in the input, and that it refuses the same inputs.

### 13.1 Reader cases

| Reader case | Expected | What it pins |
|---|---|---|
| `no_scent_track` | none | A file with a video track and no scent track has no scent. |
| `scent_front` | document | The usual layout: the scent `mdat` immediately after `moov`. |
| `scent_end` | document | The scent `mdat` at the end of the file. |
| `moov_at_end` | document | `moov` after the media data. |
| `largesize_boxes` | document | Top-level boxes with 16-byte headers (64-bit sizes). |
| `size_zero_last_box` | document | A last top-level box of size 0 ("to the end of the file"). |
| `two_scent_tracks_lowest_id_wins` | document | Two usable scent tracks: the lowest `track_ID` wins, not the first in `moov`. |
| `mime_case_insensitive` | document | `mime_format` is compared ASCII case-insensitively. |
| `non_empty_content_encoding_ignored` | none | A `mett` track with a non-empty `content_encoding` is not a scent track. |
| `mett_with_other_mime_ignored` | none | A `mett` track with another media type is not a scent track. |
| `two_samples_ignored` | none | A scent track with two samples is ignored. |
| `fragmented_is_none` | none | A fragmented file (`mvex`) has no scent in 1.0. |
| `scent_track_with_edts_ignored_edts` | document | An edit list on the scent track is ignored. |
| `sample_shared_mdat` | document | A sample inside an `mdat` shared with video is still read. |
| `co64_chunk_offsets` | document | The scent track's offset is in a `co64` table. |
| `no_ftyp` | document | `ftyp` is not required. |
| `deep_within_limit` | document | Nesting of exactly 16 levels is accepted. |
| `not_mp4` | `NOT_MP4` | A first top-level box that is not plausible (a text file). |
| `empty_file` | `NOT_MP4` | An empty file. |
| `no_moov` | `NOT_MP4` | Valid top-level boxes without `moov`. |
| `truncated_moov` | `TRUNCATED` | `moov` ends beyond the end of the file. |
| `lying_box_sizes` | `BAD_BOX` | A top-level box after the first whose 64-bit size runs beyond the file. |
| `top_level_box_smaller_than_header` | `BAD_BOX` | A top-level box after the first whose size is smaller than its header. |
| `child_exceeds_parent` | `BAD_BOX` | A box inside `moov` larger than what remains of its parent. |
| `child_smaller_than_header` | `BAD_BOX` | A box inside `moov` whose size is smaller than its header. |
| `size_zero_inside_moov` | `BAD_BOX` | Size 0 is not allowed inside `moov`. |
| `huge_table_counts_do_not_allocate` | `BAD_BOX` | A `stsz` declaring `0xFFFFFFFF` entries; nothing is allocated for them. |
| `huge_chunk_offset_count` | `BAD_BOX` | A `stco` declaring `0xFFFFFFFF` entries. |
| `sample_outside_file` | `BAD_TRACK` | A sample that starts beyond the end of the file. |
| `sample_ends_outside_file` | `BAD_TRACK` | A sample that starts inside the file and ends beyond it. |
| `sample_overlaps_moov` | `BAD_TRACK` | A sample that overlaps `moov`. |
| `sample_too_large` | `TOO_LARGE` | A sample declared one byte over the document limit, judged before reading. |
| `moov_too_large` | `TOO_LARGE` | A `moov` declared one byte over the `moov` limit. |
| `too_deep` | `TOO_LARGE` | Nesting of 17 levels. |
| `too_many_tracks` | `TOO_LARGE` | 257 `trak` boxes. |
| `too_many_top_level_boxes` | `TOO_LARGE` | More than 4096 top-level boxes before `moov`. |
| `broken_video_track_no_scent` | none | A damaged video track does not fail extraction; a writer refuses the file (`layout`: `BAD_BOX`). |
| `broken_video_track_with_scent` | document | A damaged video track next to a valid scent track; a writer refuses the file (`layout`: `BAD_BOX`). |
| `duplicate_stsd_first_wins` | document | A second `stsd` in the scent track is skipped; a writer refuses it (`layout`: `BAD_BOX`). |
| `truncated_moov_first` | `TRUNCATED` | A first box typed `moov` that is cut short is `TRUNCATED`, not `NOT_MP4`. |
| `moov_too_large_first` | `TOO_LARGE` | A first box typed `moov` declared over the limit is `TOO_LARGE`, not `NOT_MP4`. |
| `two_video_tracks` | none | Two video tracks and no scent track (input of a writer case). |
| `sound_track_only` | none | A sound track only (input of a writer case). |
| `scent_tracks_one_ignored` | document | A one-sample scent track wins over a two-sample one. |
| `encrypted_track` | document | A reader reads a file with an encrypted track that a writer refuses. |
| `external_dref` | document | A reader reads a file with an external data reference that a writer refuses. |
| `meta_iloc_in_moov` | document | A reader reads a file with `iloc` in `moov` that a writer refuses. |
| `meta_iloc_at_file_level` | document | A reader reads a file with a top-level `meta` that a writer refuses. |
| `co64_video_chunks_in_two_mdats` | document | A video track with a `co64` table whose chunks lie in two `mdat` boxes. |
| `video_mdats_around_scent_mdat` | document | The scent `mdat` between two `mdat` boxes of a video track (input of writer cases). |
| `moov_between_video_mdats` | none | `moov` between two `mdat` boxes of a video track (input of a writer case). |
| `fragmented_with_broken_candidate_is_none` | none | `mvex` before a broken candidate: a fragmented file has no scent, and its tracks are not read. |
| `fragmented_after_broken_candidate_is_none` | none | The same with `mvex` after the broken candidate: `mvex` is looked for before any track, not in file order. |
| `broken_candidate_before_bad_mvhd` | `UNSUPPORTED` | A broken candidate before an `mvhd` of version 2: `mvhd` is read first (`layout`: `UNSUPPORTED`). |
| `candidate_without_mvhd` | `BAD_BOX` | A candidate with a `tkhd` of version 2 and no `mvhd`: the missing `mvhd` comes first (`layout`: `BAD_BOX`). |

### 13.2 Writer cases

| Writer case | Expected | What it pins |
|---|---|---|
| `put_into_plain_file` | file | A put into a file without scent: the new track, `tref`, the `mdat` immediately after `moov`, moved offsets. |
| `replace_drops_the_old_own_mdat` | file | A replace drops the old document's own `mdat`. |
| `replace_in_shared_mdat_leaves_bytes_unreferenced` | file | A replace keeps a shared `mdat` whole; the old bytes stay, referenced by no track. |
| `remove_restores_no_scent` | file | A remove drops the scent track and its `mdat`; `next_track_ID` is unchanged. |
| `put_keeps_moov_at_end_files_valid` | file | A file with `moov` at the end: the scent `mdat` follows `moov` at the end. |
| `put_removes_every_scent_track_and_adds_one` | file | A put removes every scent track, including one a reader ignores, and adds one. |
| `tref_cdsc_points_to_lowest_video_track` | file | `cdsc` names the video track with the lowest `track_ID`, not the first in `moov`. |
| `no_video_track_no_tref` | file | No `vide` track: no `tref`. |
| `put_into_largesize_boxes` | file | 64-bit headers of the input are kept. |
| `put_into_size_zero_last_box` | file | A size-0 last box that stays last keeps size 0. |
| `replace_scent_track_with_co64_table` | file | A replace removes a scent track whose table is `co64`. |
| `put_keeps_co64_table_of_kept_track` | file | A kept `co64` table stays `co64`; chunks in two `mdat` boxes are moved with their own box. |
| `remove_keeps_co64_table_of_kept_track` | file | The same for a remove. |
| `replace_two_scent_tracks` | file | A put on a file with two scent tracks leaves one. |
| `remove_from_shared_mdat` | file | A remove from a shared `mdat` keeps the `mdat` whole. |
| `remove_with_moov_at_end` | file | A remove from a file with `moov` at the end. |
| `remove_two_scent_tracks` | file | A remove takes out both scent tracks and their `mdat` boxes. |
| `remove_without_scent_is_identity` | file | A remove from a file without scent gives the input unchanged. |
| `put_replaces_encoded_scent_track` | file | A put removes a track with the ASMF media type and a non-empty `content_encoding`, with its own `mdat`. |
| `remove_takes_encoded_scent_track` | file | A remove takes out such a track, with its own `mdat`, though a reader ignores it. |
| `remove_between_video_mdats` | file | Two shifts in one file: a chunk after the dropped `mdat` moves back further than a chunk before it. One delta for every offset fails this case. |
| `replace_between_video_mdats` | file | The same for a replace: the chunks move by different amounts. |
| `put_with_moov_between_video_mdats` | file | Two shifts in one file: a chunk before `moov` does not move, a chunk after it moves by what `moov` and the scent `mdat` add. |
| `fragmented_refused` | `UNSUPPORTED` | A put into a fragmented file is refused. |
| `fragmented_remove_refused` | `UNSUPPORTED` | A remove from a fragmented file is refused. |
| `fragmented_with_broken_track_refused` | `UNSUPPORTED` | A fragmented file is refused whatever the fields of its tracks hold. |
| `encrypted_refused` | `UNSUPPORTED` | A file with encryption boxes is refused. |
| `external_dref_refused` | `UNSUPPORTED` | A put into a file with a data reference that is not self-contained is refused. |
| `external_dref_remove_refused` | `UNSUPPORTED` | The same for a remove. |
| `meta_iloc_refused` | `UNSUPPORTED` | A file with `iloc` in `moov` is refused. |
| `meta_iloc_at_file_level_refused` | `UNSUPPORTED` | A file with a top-level `meta` is refused. |

Cases that need very large inputs (a document of 262144 or 262145 bytes, offsets beyond 4 GiB) are not in the file; the
reference implementation tests them in its own test suite. The rewritten header of a size-0 box (section 8.3, step 7)
has no case in the file for the same reason: a box follows a size-0 last box only when the document goes to the end of
the file, which takes a document over 262144 bytes (256 KiB).

The reference implementation is the Rust crate in `crates/asmf-mp4`. It runs both sections of the cases file in its
tests and checks this document against its constants and the cases file in `tests/spec_consistency.rs`.

## 14. Change log

| Version | Date | Changes |
|---|---|---|
| 1.0 | 2026-11-05 | First version. |
| 1.0 (draft revision) | 2026-11-20 | Wording: a file may hold video or audio only (`.m4a`, `audio/mp4`); rules that named the video name the file or its playback, so they cover an audio-only file too; "movie" defined (sections 1, 2, 3, 5, 6, 7.1, 7.6, 9, 10, 11, 12). No rule changed for a file with video. |
