diff --git a/AGENTS.md b/AGENTS.md index c92b746..029bc33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,12 +16,12 @@ Read this file before changing parser, API, fixtures, fuzzers, or counts. This f ## Current design invariants (not additional assessment requirements) -**Scope gate:** Only requirements called out in the [assessment-only checklist](docs/assessment-brief.md#appendix-project-interpretation-not-assignment-text) are mandated by the employer. The configurable 50 MiB default limit, raw uploads, metadata-exclusion option, extended free-format range, fuzzing and release tooling are established **project choices**, not extra conditions imposed by the brief. Keep them working but never broaden unrelated scope to satisfy a reference appendix. +**Scope gate:** Only requirements called out in the [assessment-only checklist](docs/assessment-brief.md#appendix-project-interpretation-not-assignment-text) are mandated by the employer. The configurable 50 MiB default limit, raw uploads, metadata-exclusion option, fuzzing and release tooling are established **project choices**, not extra conditions imposed by the brief. Free-format candidate eligibility uses the [documented per-sample-rate 320 kbps envelope](docs/specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero); LAME's higher-rate extensions must not compete with in-scope layouts. Keep the documented behavior working but never broaden unrelated scope to satisfy a reference appendix. - MPEG-1 is version bits `11`; Layer III is layer bits `01`. Support bitrate indices 1–14 **and free-format index 0** (bounded frame-spacing inference); reject forbidden index 15 and reserved sample rate 3. MPEG-2, MPEG-2.5, Layers I/II, ADTS/AAC and MP4 are out of assessment scope. - Compute indexed frame lengths independently for **every frame**, including VBR/ABR, rather than multiplying the first frame length by the count or trusting a Xing/VBRI count. - Successive in-file sample-rate configurations use the [bounded sequence policy](docs/specifications/successive-sequences.md). They are separate from multiple uploaded files; do not claim a universal ISO concatenation mandate. Same-rate mode switching remains separate. -- Free-format has no table bitrate; cache the **unpadded frame length**, then apply each frame's padding. Follow the documented EOF/metadata-anchored short inference policy; reject equally supported candidates and disclose unavoidable singleton ambiguity. Never allow unbounded lookahead, rescans or backtracking. +- Free-format has no table bitrate; cache the **unpadded frame length**, then apply each frame's padding. Bound both the base and every physical frame by its own sample rate during root/successor inference and locked traversal, independently of the fixed probe budget. At maximum base, padding exceeds the envelope at 32/48 kHz but fits at 44.1 kHz. Do not infer a minimum bitrate from the indexed table or claim full padding-schedule validation. Follow the documented EOF/metadata-anchored short inference policy; reject equally supported candidates and disclose unavoidable singleton ambiguity. Never allow unbounded lookahead, rescans or backtracking. - **Current owner-selected policy:** HTTP omitted/`false` excludes at most one recognized _initial_ Xing/Info/VBRI encoder frame; HTTP `true` and direct parser calls with no option count complete physical MPEG frames. **ID3 frames are metadata records, not MPEG audio frames.** Exclusion must recognize the initial encoder structure, never subtract one blindly, and does not prove that every counted frame decodes to audio. - Skip supported ID3 tags from their encoded, bounded lengths; do not interpret tag content, decompress, execute, download art, log uploaded bytes, or load entire uploads into memory. - Preserve `AsyncIterable` parsing, bounded memory, streaming backpressure, one configurable raw/multipart per-file byte limit (50 MiB by default), typed deterministic failures, and JSON response format. diff --git a/README.md b/README.md index 8499e4e..0e86636 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,8 @@ Complexity: **O(n)** time and **O(max upstream chunk size)** additional memory. The parser detects free-format frame spacing using multiple consecutive compatible MPEG headers instead of a bitrate-table lookup. The parser rejects invalid data at the next required frame boundary. It does not resynchronize after corrupt frames or arbitrarily skip noise before the first header: doing so can silently turn a malformed upload into a plausible but wrong count. It supports consecutive ID3v2 tags at each MPEG boundary, including embedded tags; every appended tag must be v2.4 with a matching footer, followed by an optional final ID3v1. **Free-format MPEG-1 Layer III** (bitrate index zero) is supported with bounded inference of fixed frame spacing and per-frame padding; one-/two-frame streams can use bounded EOF or metadata-boundary evidence, while tied or conservatively ambiguous candidates return 415. Successive sample-rate configurations inside one uploaded file follow the [bounded sequence policy](docs/specifications/successive-sequences.md); competing layouts produce an explicit ambiguity error. Multiple uploaded files remain rejected. This structural heuristic cannot distinguish every truncated or extended singleton from a complete frame; see the [precise inference contract](docs/specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero). Table-defined bitrates 32–320 kbps remain supported. Other unsupported scope includes MPEG-2/2.5, Layers I/II, APE/Lyrics3 trailers, audio decoding, and CRC validation. +Free-format candidates use a per-sample-rate envelope through 320 kbps: unpadded spans up to 1,044 / 960 / 1,440 bytes at 44.1 / 48 / 32 kHz, and physical spans including padding up to 1,045 / 960 / 1,440 bytes. Thus padding at the maximum base fits only at 44.1 kHz. Larger spans are excluded from inference, including competing ancillary patterns. No eligible candidate returns 415 `unsupported-format`; a later physical overrun after span acquisition returns 422 `invalid-mp3`. The [inclusive endpoint interpretation and structural limits](docs/specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero) remain explicit; this is not full bitstream or padding-schedule validation. + ## Verification ```bash diff --git a/docs/architecture.md b/docs/architecture.md index 5cb1bce..7a7882b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,6 +27,8 @@ Every frame is parsed individually. This supports constant and variable bitrate Free-format MPEG-1 Layer III uses bitrate index zero and a fixed unpadded span plus each frame's padding. One 8,647-byte search window evaluates bounded candidate spans, crossing validated tags only at each proposed boundary. One additional unsearched lookahead byte distinguishes its edge from actual EOF before a final ID3v1 tag can add boundary evidence. A validated tag header can anchor a body larger than the probe, which is subsequently streamed. Candidates are ranked by compatible MPEG headers and then metadata-boundary evidence; ties reject. The [sequence policy](specifications/successive-sequences.md) adds bounded changed-rate continuation and a conflicting-layout veto without giving successor headers votes for a prior span. Three-header chains remain supported; shorter chains require EOF, metadata or supported changed-rate anchoring and conservative compatible-header/plausible-metadata checks. This is structural inference, not proof of unique decoding: EOF cannot distinguish every complete singleton from a truncated or extended one. The [complete policy and source limitations](specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero) are part of the contract. Locked traversal remains strict and never rescans payload. +The probe budget is independent of candidate eligibility. Root and successor candidates require `baseLength <= floor(144 * 320000 / sampleRateHz)` and every physical span, including padding, must fit `ceil(144 * 320000 / sampleRateHz)`. Locked traversal retains the physical check. Maximum-base padding therefore fits at 44.1 kHz but exceeds the bound at 32/48 kHz. Extension-only spans cannot create ambiguity for an otherwise supported layout. The inclusive endpoint follows the [documented maximum-rate interpretation](specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero); inference does not recover an exact bitrate or validate the complete padding schedule. + This is a **structural parser**, not a full Layer III bitstream validator. New sequence evidence reads the backward offset, declared main-data lengths and spectral-pair counts for necessary side-information bounds. Full validation would additionally establish side-information semantics, actual reservoir availability, Huffman data and CRC integrity. Supporting additional tag families such as APEv2/Lyrics3, or other MPEG versions/layers, is a separate compatibility expansion—not part of those Layer III decoding checks and not added here. ## Resource model diff --git a/docs/assessment-brief.md b/docs/assessment-brief.md index e945b18..65ce8dd 100644 --- a/docs/assessment-brief.md +++ b/docs/assessment-brief.md @@ -207,8 +207,12 @@ the policy, its change from the earlier HTTP default and verification evidence. The brief does not prescribe a multipart field name, raw uploads, MIME aliases, query options, exact error statuses/schema, upload caps, libraries or deployment -infrastructure. LAME free-format 321-640 kbps interoperability, arbitrary embedded -ID3, APEv2/Lyrics3 and decoder-style recovery are optional compatibility choices. +infrastructure. LAME extensions beyond the [documented 320 kbps candidate envelope](specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero) +are outside the supported scope and must not compete with supported layouts. +The inclusive endpoint follows the detailed maximum-rate rule and fixed-rate +arithmetic; the definition's wording distinction remains documented. +Arbitrary embedded ID3, APEv2/Lyrics3 and decoder-style recovery +are optional compatibility choices. Fuzzing, mutation testing, 100% coverage, SBOMs, release automation, formal security audits and production auth/rate limiting are likewise not evaluator mandates. diff --git a/docs/specifications/README.md b/docs/specifications/README.md index 3df7437..2b9ed8a 100644 --- a/docs/specifications/README.md +++ b/docs/specifications/README.md @@ -4,6 +4,8 @@ This directory is the **AI-agent and reviewer source register for this TypeScrip ## Authority classes, in order +Free-format boundary review also uses [ITU-R BS.1115-1, Appendix 2](https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.1115-1-200504-W!!PDF-E.pdf), a public primary reference describing a 320 kbps Layer III free-format maximum and per-frame padding. The inclusive endpoint follows the detailed maximum-rate rule and fixed-rate arithmetic; the wording distinction between ISO/IEC 11172-3:1993 §§2.1.67 and 2.4.3.4.4 remains documented in the [precise base and physical-span envelopes](mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero). LAME's larger encoder range is evidence for rejection fixtures, not authority to admit extension-only candidates. + | ID | Source and scope | Authority | Applicable project decision | | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | M1 | [ISO/IEC 11172-3:1993, MPEG-1 Part 3: Audio](https://www.iso.org/standard/22412.html) | **Normative international MPEG-1 audio standard**; current edition confirmed by ISO | MPEG-1 Layer III header syntax, sampling/bitrate indices, padding, CRC protection and free-format | @@ -15,7 +17,7 @@ This directory is the **AI-agent and reviewer source register for this TypeScrip | I24 | [ID3v2.4.0 Main Structure](https://id3.org/id3v2.4.0-structure) | Informal format standard | Header/footer, synchsafe size, appended tag and placement | | I1 | [ID3v1 / ID3v1.1](https://id3.org/ID3v1) | Format-author documentation | Exactly 128 trailing bytes beginning `TAG` | | IFAQ | [ID3.org FAQ](https://id3.org/FAQ) | Maintainer guidance, subordinate to versioned specs | Rare in-stream tags and trailing ID3 placement | -| L1 | [LAME USAGE (`--freeformat`)](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE) | Original encoder documentation; **interoperability evidence, not an amendment to ISO** | Fixed free-format bitrate 8–640 kbps; ordinary MPEG-1 Layer III table still capped at 320 kbps | +| L1 | [LAME USAGE (`--freeformat`)](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE) | Original encoder documentation; **interoperability evidence, not an amendment to ISO** | Encoder range 8–640 kbps; extension output supplies rejection fixtures, not a wider parser limit | | L2 | [LAME VbrTag.h](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/libmp3lame/VbrTag.h), [VbrTag.c](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/libmp3lame/VbrTag.c) and [LAME API](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/API) | Original encoder source for de facto Xing/Info/LAME layout | Metadata header is inside a physical MPEG frame; count field is not a reliable file-traversal oracle | | V1 | [FFmpeg mp3 demuxer, Xing and VBRI readers](https://github.com/FFmpeg/FFmpeg/blob/c220739be57307ea821d1197ad89ff6e372180e8/libavformat/mp3dec.c) and [TagLib Xing/VBRI reader](https://github.com/taglib/taglib/blob/1ae164e382f567c463d14b7bd782b3fe10516685/taglib/mpeg/xingheader.cpp) | **Corroborating independent implementations**; no verified standalone normative VBRI specification | Conditional VBRI recognition and optional metadata-frame exclusion | | R3003 | [RFC 3003: `audio/mpeg`](https://www.rfc-editor.org/rfc/rfc3003.html) and [IANA media registry](https://www.iana.org/assignments/media-types/) | IETF media-type definition/registration | `audio/mpeg` is canonical; MIME type does **not** imply the contained MPEG version is Layer III | @@ -29,7 +31,7 @@ This directory is the **AI-agent and reviewer source register for this TypeScrip 1. **The assignment is narrower than generic `audio/mpeg`.** RFC 3003 can describe a stream with interspersed non-MPEG bytes; the endpoint intentionally accepts a stricter sequence: supported leading metadata, complete MPEG-1 Layer III frames and supported trailing metadata, without arbitrary junk resynchronization. That is an **application policy**, not a claim that RFC 3003 prohibits other layouts. 2. **Metadata tags are independent of the MPEG audio coding standard.** Implement only byte-boundary handling needed for accurate counts. ID3 text encodings, embedded artwork, replay gain, extended headers, ID3 frame content and CRC fields do **not** need full interpretation. 3. **Xing/Info/LAME and VBRI are de facto encoder headers, not additional MPEG layers.** They can inhabit MPEG frames. The owner selected HTTP exclusion of one recognized initial header for omitted/`false`; explicit `true` and direct parser calls with no option count physical frames. These are project policies, not ISO requirements. The evaluator confirmed audio-frame counting and sample result 6089 on 2026-10-26; implementation details beyond that clarification remain distinct. See the [count contract](../frame-count-contract.md). -4. **Free-format is not MPEG-2 or an invalid bitrate.** Index zero is a valid MPEG-1 Layer III encoding choice with no table-derived frame length. A decoder's size-search heuristic is evidence of interoperability, not the ISO text itself. +4. **Free-format is not MPEG-2 or an invalid bitrate.** Index zero is a valid MPEG-1 Layer III encoding choice with no table-derived frame length. Its per-sample-rate candidate limit is separate from the fixed observation budget. A decoder's size-search heuristic or minimum support requirement does not establish a normative upper limit; LAME extensions cannot compete with in-scope candidates. 5. **Full ISO Layer III bitstream conformance would require decoding-side checks** (side information, bit reservoir, Huffman, CRC, etc.). This assessment explicitly requests logical _frame counting_. Do not change the project into an audio decoder. The [successive-sequence policy](successive-sequences.md) separately records ISO sequence invariants, RFC 3003 elementary-stream terminology, the MSE-specific W3C frame-combination profile and bounded project inference decisions. These are not universal unique-framing rules. diff --git a/docs/specifications/conformance.md b/docs/specifications/conformance.md index b2478ea..b2f13ea 100644 --- a/docs/specifications/conformance.md +++ b/docs/specifications/conformance.md @@ -1,6 +1,6 @@ # Conformance, format coverage and evidence matrix -This is a **capability and test checklist**, not a claim of certified ISO conformance or a list of employer-imposed acceptance requirements. The [assessment-only checklist](../assessment-brief.md#appendix-project-interpretation-not-assignment-text) takes precedence: most metadata, the configurable 50 MiB default, raw upload and 321–640 kbps entries below are project choices. Applicable authority: [source register](README.md). Source-of-truth for what the assignment demands: [original brief](../assessment-brief.md). The [count contract](../frame-count-contract.md) records the owner-selected HTTP default and the dated audio-frame/sample clarification. Implementation statuses below describe the code inspected on **2026-10-27**, not proof from a fresh exhaustive CI run; the separately dated **Confirmed** row records the later evaluator clarification. +This is a **capability and test checklist**, not a claim of certified ISO conformance or a list of employer-imposed acceptance requirements. The [assessment-only checklist](../assessment-brief.md#appendix-project-interpretation-not-assignment-text) takes precedence: metadata policies, the configurable 50 MiB default and raw upload include project choices. Applicable authority: [source register](README.md). Source-of-truth for what the assignment demands: [original brief](../assessment-brief.md). The [count contract](../frame-count-contract.md) records the owner-selected HTTP default and the dated audio-frame/sample clarification. Entries describe implementation and its limits, not proof from an exhaustive conformance run. The inclusive 320 kbps free-format interpretation follows the detailed maximum-rate rule and arithmetic; the definition's wording distinction remains documented. Legend: **Required** = assessment's format; **Supported** = implemented structural handling; **Limited** = implemented with documented restriction; **Policy** = stricter or extended application choice; **Out of scope** = not required for assignment; **Open** = unresolved external interpretation; **Confirmed** = dated evaluator clarification of the stated requirement and sample expectation, not a full conformance result. @@ -10,9 +10,9 @@ Legend: **Required** = assessment's format; **Supported** = implemented structur | Indexed bitrate 1–14, 32–320 kbps | Required, Supported | Per-frame integer frame-length formula | [MPEG syntax](mpeg-1-layer-iii.md), `frame-header.test.ts` | | CBR / VBR / ABR using indexed bitrates | Required, Supported | Recompute each frame; do not assume fixed size | `count-frames.test.ts` and existing FFmpeg fixtures | | Free-format bitrate index 0 | Valid MPEG-1 Layer III subtype; Limited | Unique best header/metadata evidence score; not proof of unique framing | [LAME `--freeformat`](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE), `free-format.ts` | -| Arbitrary integer free-format bitrates up to 320 kbps | Interoperability, Limited | No bitrate stored; inferred bounded frame spacing | `free-format.test.ts`; real LAME output at 128, 192, 320 and 400 kbps, including padding-free spans | -| 321–640 kbps free-format | Extended interoperability, Limited | Project length limit 2881 bytes | [LAME USAGE](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE); real encoder tests cover selected configurations | -| Free-format 1–2 frame streams | Valid target subtype; inference Limited | EOF/metadata-anchored short inference; equal evidence rejects; not a full decoder | `short-free-format.test.ts`, 48 normally flushed encoder fixtures | +| Free-format candidate envelope through 320 kbps | Structural; endpoint interpretation documented | Base maxima 1044/960/1440; physical maxima 1045/960/1440 at 44.1/48/32 kHz; no table-derived minimum | [Candidate envelope](mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero); LAME 128/192/320 kbps | +| Free-format spans outside that envelope | Extension out of scope | Exclude from root/successor evidence; no eligible candidate gives `unsupported-format` / 415 | [LAME USAGE](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE); real encoder output verifies extension rejection | +| Free-format 1–2 frame streams | Valid target subtype; inference Limited | EOF/metadata-anchored short inference; equal evidence rejects; not a full decoder | `short-free-format.test.ts`: 24 genuine 128 kbps acceptance cases and 24 genuine 400 kbps rejection cases | | Successive changed-rate configurations in one file | Project compatibility policy, Limited | Resolve configurations; conflicting layouts fail | [Sequence policy](successive-sequences.md) | | Same-rate free/indexed switching | Separate decision, Open | Existing rejection retained; not asserted ISO-forbidden | [Sequence scope](successive-sequences.md#authority-and-scope) | | Necessary new-sequence side fields | Inference evidence, Supported | Check capacity, pairs, switched block type, used first codebook and minimum scale bits; not decode audio | sequence-capacity.test.ts, side-information.test.ts, sequence-side-information.test.ts | @@ -48,10 +48,14 @@ are malformed (422), not a genuinely identified unsupported format (415). The matrix distinguishes encoder-produced fixtures from header-only probes; rejection does not validate another codec's payload or frame geometry. +Free-format envelope regressions are in `tests/mp3/free-format-rate-bound.test.ts`; +`tests/free-format-rate-upload.test.ts` verifies the same count/error contract in +both upload modes and every count-option setting. + ## Rules for tests and claims 1. A **valid structural test** needs an independent frame-offset/count oracle (synthetic manifest) or an independently produced encoder corpus checked by another implementation. A single decoder's decoded frame count need not equal physical frames. Construction offsets do not establish uniqueness for competing free-format layouts; such tests must assert ambiguity. -2. For each supported bitrate/rate/mode/CRC/padding combination, test exact counts and chunk-boundary invariance. For free-format, include variable padding, competing sync candidates, unusual valid integer rates, 640 kbps at 32 kHz, very short streams, and truncation. +2. For each supported bitrate/rate/mode/CRC/padding combination, test exact counts and chunk-boundary invariance. For free-format, include variable padding, genuinely in-scope competing candidates, below-table rates that fit the mandatory prefix, both base and physical upper bounds, maximum-base padding rejection at 32/48 kHz, very short streams, and truncation. Extension-only ancillary candidates must not veto supported layouts. 3. The generic binary Jazzer target tests crash-freedom and consistent results across chunkings; it is **not** an oracle of positive counts. The independent construction target covers indexed and free-format streams, per-frame padding/CRC/channel variation, and optional initial encoder headers with known offsets and both count policies. Its known-count free-format payloads exclude accidental sync bytes to avoid ambiguous oracle labels; these structural fixtures do not establish full decoded-audio validity. 4. A test or lint score, even 100% coverage, does **not** demonstrate conformance to all MPEG bitstream/decoder requirements. The [full-parser mutation gate](../mutation-review.md) covers every module, including `free-format.ts`, `encoder-frame.ts` and traversal; keep it at 100% adjusted when changing them. 5. Document violations of _format_ rules separately from deliberate _application_ limitations. For example, ambiguity-driven free-format rejection or a deliberate metadata resource cap does not make such a stream non-MPEG-1 Layer III. diff --git a/docs/specifications/http-api.md b/docs/specifications/http-api.md index a843a4b..9a80623 100644 --- a/docs/specifications/http-api.md +++ b/docs/specifications/http-api.md @@ -84,6 +84,16 @@ fields and the implementation's eleven-bit sync/two-bit version view. The forbid `0xff` in either version byte; that rule is distinct from an unknown major version. Accepted MIME, filename or sync alone never establishes supported audio. +With no eligible free-format candidate within the per-sample-rate envelope, +the parser reports `unsupported-format` / HTTP 415 with "Cannot infer a unique +free-format MPEG frame size within the supported 320 kb/s bitrate envelope". +This reports failed inference within scope, not a diagnosed exact bitrate. +Competing eligible layouts retain "Ambiguous free-format MPEG frame layout" +with the same classification. +After a free-format span has been acquired, a later physical frame exceeding +its sample rate's upper envelope raises `invalid-mp3` / HTTP 422 with +"Free-format frame exceeds the supported 320 kb/s bitrate envelope". + ### First-observable-failure precedence and chunk invariance Classification follows validated boundaries and the failure observable at that diff --git a/docs/specifications/mpeg-1-layer-iii.md b/docs/specifications/mpeg-1-layer-iii.md index 55585dd..19f0348 100644 --- a/docs/specifications/mpeg-1-layer-iii.md +++ b/docs/specifications/mpeg-1-layer-iii.md @@ -55,7 +55,7 @@ MPEG-1 Layer III normally represents **1152 PCM samples per frame**, independent ## 4. Free-format Layer III (bitrate index zero) -**Index `0000` is valid, not reserved.** It encodes no table-defined bitrate, so the indexed length formula alone is insufficient. [LAME's original documentation](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE) calls this a fixed-bitrate free-format stream, encodable at arbitrary integer rates from 8 to 640 kbps, and notes that generally conforming decoders need support only up to 320 kbps. The project's **640 kbps** interoperability goal is broader than the minimum decoding requirement. +**Index `0000` is valid, not reserved.** It encodes no table-defined bitrate, so the indexed length formula alone is insufficient. ISO/IEC 11172-3:1993 §§2.1.67, 2.4.2.3 and 2.4.3.4.4 address free format, padding and bitrate limits. [ITU-R BS.1115-1, Appendix 2](https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.1115-1-200504-W!!PDF-E.pdf) describes fixed-rate free format with a Layer III maximum of 320 kbps. The parser uses an **inclusive 320 kbps candidate envelope**, supported by the detailed maximum-rate rule and fixed-rate arithmetic. The ISO definition and detailed endpoint wording differ; inclusion remains a documented interpretation, not a settled full-conformance claim. [LAME's documented 8–640 kbps encoder range](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/USAGE) and decoder minimum-support requirements do not expand that envelope. The minimum complete prefix is **21 bytes for mono without CRC**, 23 for protected mono, 36 for other modes without CRC, and 38 for protected other modes. ISO/IEC 11172-3:1993 §§2.4.1.3/.4/.7 and 2.4.3.4.3 establish these fields; there is no 24-byte or 8 kbps format floor. An original 21-byte mono fixture at 48 kHz is exactly 7 kbps (§2.4.3.1): all-zero side information gives no reservoir dependency, scale-factor bits or Huffman bits, and zero spectral values (§§2.4.2.7, 2.4.3.4.5/.6). A protected 23-byte control includes an independently checked CRC. These are original test fixtures, not standard-document bytes; runtime still does not decode or verify CRC. @@ -68,19 +68,23 @@ baseLength = secondFrameStart - firstFrameStart - firstFramePadding frameLength(i) = baseLength + paddingBit(i) ``` -This is a structural inference from frame starts, not a reconstructed bitrate table. With LAME's documented upper rate and 32 kHz sample rate, `floor(144000 * 640 / 32000) + 1 = 2881` bytes. **2881 is a project interoperability/DoS bound inferred from LAME's ceiling, not a universal ISO-defined maximum**. See [LAME VbrTag.c](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/libmp3lame/VbrTag.c) (the encoder has a 2880-byte free-frame constant), [mpg123 inference](https://github.com/libsdl-org/mpg123/blob/b6881556a0ee8f417ccc14ded553893b533ffe0c/src/libmpg123/parse.c), and [GStreamer free-rate inference](https://github.com/GStreamer/gstreamer/blob/0250ebe851c131429b86779d4de37e414759e9db/subprojects/gst-plugins-good/gst/audioparsers/gstmpegaudioparse.c). +This is structural inference from frame starts, not reconstruction of an exact bitrate. Each candidate must satisfy `baseLength <= floor(144 * 320000 / sampleRateHz)`: maximum unpadded spans are **1,044 / 960 / 1,440 bytes** at **44.1 / 48 / 32 kHz**, respectively. Every physical span, `baseLength + paddingBit`, must also fit `ceil(144 * 320000 / sampleRateHz)`: **1,045 / 960 / 1,440 bytes**. At 48 kHz, §2.4.3.4.4 explicitly gives the constant 960-byte maximum-rate length; the same fixed-rate arithmetic yields 1,440 bytes at 32 kHz. Padding at either integer maximum therefore exceeds the envelope. At 44.1 kHz the maximum-base padded span remains within it. Channel mode and CRC affect required prefix space, not these upper bounds. + +Apply both bounds to initial and later candidate frames, including changed-rate successor evidence, so extension-only spans cannot veto an otherwise supported layout. Locked traversal also checks each physical span. Acquisition with no eligible candidate reports `unsupported-format`; a later physical overrun of an acquired span reports `invalid-mp3`. The observation budget remains 8,647 bytes independently of these limits. + +Byte spacing quantizes the inferred rate, and a free-format header carries no exact bitrate. The counter does not validate the long-term padding schedule or distinguish every nominal rate that yields the same observed spans. Neither 32 kbps from the indexed table nor 8 kbps from LAME is a free-format minimum. Candidate eligibility and structural counting therefore do not certify a complete ISO bitstream. Successive in-file sample-rate configurations follow the [bounded sequence policy](successive-sequences.md), a project compatibility choice rather than an asserted universal ISO concatenation mandate. Current code: discovery in `src/mp3/free-format.ts`; the lock and mixing rules in `src/mp3/frame-spans.ts`: -- Searches one bounded **8,647-byte** probe, with one additional unsearched byte of lookahead to distinguish an exactly full probe at EOF from a longer stream. Candidate unpadded spans are 20–2,880 bytes; each current frame adds its own padding. Compatible headers have the same free-format mode and sample rate. +- Searches one bounded **8,647-byte** probe, with one additional unsearched byte of lookahead to distinguish an exactly full probe at EOF from a longer stream. Candidate unpadded spans start at 20 bytes and end at the sample-rate-specific base limit above; each current padded span must also fit the physical limit. Compatible headers have the same free-format mode and sample rate. The probe budget is a resource policy, not a bitrate limit. - At a **candidate's predicted frame boundary**, shared ID3 validation can skip a complete metadata tag. A complete validated ID3v2 header can also anchor a tag larger than the probe: normal traversal subsequently streams its body, checks its footer and validates the next MPEG header. This works before length acquisition, including tag ends on either side of the probe edge, without buffering album art. - Rank candidates by compatible MPEG-header count, then validated metadata-boundary evidence. Equal best evidence returns `unsupported-format`, rather than choosing an arbitrary span. A conflicting supported changed-rate layout also vetoes a numeric count; successor headers do not vote for the prior span. Three-header chains retain the previous inference behavior; this remains evidence, not proof of a unique decoding. - One-/two-header candidates require **EOF closure, a validated metadata anchor or supported changed-rate evidence**, room for each mandatory prefix, and no unexplained compatible header or plausible metadata prefix inside their proposed payloads. Any available `ID3` header bytes that already show an unsupported version, reserved flags or non-synchsafe size are not competing supported metadata; nor is any available footer byte that disagrees with its header-derived expected value; neither is `TAG` more than 128 bytes before the minimum possible stream end established by available bytes and the candidate frame end. A final ID3v1 boundary adds ranking evidence only when EOF is proved; the probe edge alone is not a tail boundary. An unproved tail does not erase preceding validated ID3v2 anchors; subsequent streaming traversal still validates the tail completely. Partial headers/footers remain conservative evidence only while every available byte is compatible with a supported envelope. Unknown fields are not used to infer a tag size or footer. Known-boundary readers still require the complete ten-byte header/footer and retain their strict truncation behavior. This short-stream rule is **project policy**, not an ISO minimum or a normative inference algorithm. -- Once chosen, cache the **unpadded** span and validate every later boundary without payload scanning. A valid sample-rate change at a resolved boundary resets the configuration and reacquires a free span when needed. Same-rate free/indexed switching retains its rejection policy, not a claimed ISO prohibition. The current frame must fit its 4-byte header, optional 2-byte CRC and 17/32-byte side information. Invalid/unsupported later headers keep their own typed errors. +- Once chosen, cache the **unpadded** span and validate every later boundary without payload scanning. A valid sample-rate change at a resolved boundary resets the configuration and reacquires a free span when needed. Same-rate free/indexed switching retains its rejection policy, not a claimed ISO prohibition. The current frame must fit its 4-byte header, optional 2-byte CRC and 17/32-byte side information, and must not exceed its sample rate's physical-span envelope. Invalid/unsupported later headers keep their own typed errors. - **Unavoidable limits:** a free-format header does not encode its length. A singleton's EOF can be consistent both with a complete frame and a truncated larger frame, or with a frame plus additional ancillary/trailing bytes. The counter cannot distinguish all such cases without deeper audio/side-information validation or external framing. Conservative plausible-prefix rejection can still reject real payload coincidences. Conversely, before a span is established, an invalid or unsupported metadata envelope after audio is indistinguishable from ancillary bytes; it need not produce the malformed-tag error that the same bytes produce at an established boundary. These are compatibility/inference limits, not declarations that short files are ISO-invalid. -- The assessment states no minimum duration. Committed fixtures include **48 normally flushed libLAME 3.100 streams**, with one or two frames, all three sample rates, mono/stereo, CRC on/off and 128/400 kbps. They were never trimmed from longer files. Encoder frame totals and a separate walk using the known encoder bitrate/padding agree exactly; independent HIP decoding corroborates PCM output but does not itself validate the complete ancillary span. +- The assessment states no minimum duration. Committed fixtures include **48 normally flushed libLAME 3.100 streams**, with one or two frames, all three sample rates, mono/stereo, CRC on/off and 128/400 kbps. The 128 kbps files exercise supported short inference; the 400 kbps files exercise rejection outside the candidate envelope. They were never trimmed from longer files. Encoder frame totals and a separate walk using the known encoder bitrate/padding agree exactly; independent HIP decoding corroborates PCM output but does not make an encoder extension in scope. - Ancillary-decoy tests alter only verified unused bytes of the genuine silent mono singleton: its reservoir pointer and both granule bit lengths are zero. [LAME's original side-information writer](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/libmp3lame/bitstream.c) corroborates the field order/widths; independent HIP decoding retains 1,152 silent samples after each replacement. New sequence evidence reads the backward offset, declared main-data lengths and spectral-pair counts for necessary side-information bounds; no audio decoding or reservoir-availability validation is added. - Mature-reader corroboration is narrower than our policy: [mpg123](https://github.com/libsdl-org/mpg123/blob/eb1138723913c3879f414b4918a79df3b355bbca/src/libmpg123/parse.c) and [libmad](https://github.com/sezero/libmad/blob/486f902c6c686eafced3450851849527e29bc7f6/frame.c) acquire from a next header; [minimp3](https://github.com/lieff/minimp3/blob/ea99364f61c14656440e8d77e9c233ccf3124633/minimp3.h) uses a third. No one-frame EOF fallback was established in those readers. [LAME's HIP implementation](https://github.com/lameproject/lame/blob/1f5cc9487284d5950343aa5d4f70de433468070a/mpglib/interface.c) can emit decoded samples before the full free-format span is known; a zero-input decode call drains buffers, not an EOF signal. - Candidate work is bounded independently of upload length, using fixed-window caching and cooperative scheduling rather than a total-work format rejection in the [sequence policy](successive-sequences.md#resource-bounds). Every candidate step advances by at least 20 bytes; every skipped tag consumes at least ten bytes; within the probe, the byte bound also bounds the number of tag iterations. Ordinary indexed traversal has no inference work. No unbounded resynchronization, recursion or backtracking is added. @@ -93,6 +97,6 @@ A test's expected value must be explicit about whether it means (1) physically p ## 6. Test obligations -Assert all table indices 1–14, all three rates, both padding settings, both CRC-protection bits and all four channel modes. Test mixed-bitrate indexed streams, free-format exact span with alternating padding, high-rate 640 kbps/32 kHz, 1-byte chunks, payload sync decoys, competing candidate alignments, short/ambiguous free-format, truncated frame/header, ID3 before/after, and first-frame metadata inclusion/exclusion. Derive independently known counts from generated frame offsets and encoder fixtures; FFprobe/MediaInfo alone are **not** physical-frame ground truth. +Assert all table indices 1–14, all three rates, both padding settings, both CRC-protection bits and all four channel modes. Test mixed-bitrate indexed streams, free-format exact span with alternating padding, each rate's base and physical boundaries, maximum-base padding rejection at 32/48 kHz, 1-byte chunks, payload sync decoys, genuinely in-scope competing alignments, short/ambiguous free-format, truncated frame/header, ID3 before/after, and first-frame metadata inclusion/exclusion. High-rate extension candidates must neither produce counts nor veto an otherwise supported parse. Derive independently known counts from generated frame offsets and encoder fixtures; FFprobe/MediaInfo alone are **not** physical-frame ground truth. Relevant files: [header](../../src/mp3/frame-header.ts), [frame spans](../../src/mp3/frame-spans.ts), [free format](../../src/mp3/free-format.ts), [frame traversal](../../src/mp3/count-frames.ts), [tests](../../tests/mp3/free-format.test.ts), [real LAME test](../../tests/mp3/free-format-real.test.ts), [conformance](conformance.md). diff --git a/docs/specifications/successive-sequences.md b/docs/specifications/successive-sequences.md index 1435386..1af4be4 100644 --- a/docs/specifications/successive-sequences.md +++ b/docs/specifications/successive-sequences.md @@ -32,7 +32,13 @@ decision. Metadata alone is not treated as an ISO reset marker. ## Admissibility, ranking and errors 1. Search remains one 8,647-byte probe plus one unsearched EOF-witness byte. - Candidate unpadded spans remain 20–2,880 bytes. + Every root and successor candidate uses its own sample rate's upper unpadded + span: 1,044 / 960 / 1,440 bytes at 44.1 / 48 / 32 kHz. Its physical span, + including padding, must fit 1,045 / 960 / 1,440 bytes. These follow the + [documented inclusive 320 kbps interpretation](mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero), + based on the detailed maximum-rate rule and fixed-rate arithmetic. Maximum-base + padding at 32/48 kHz exceeds that envelope; it fits at 44.1 kHz. Check every + candidate frame so extension-only spans cannot supply competing evidence. 2. Within a free configuration, compatible-header count ranks first, then validated metadata evidence. This existing strongest-chain preference remains a **heuristic**, not proof of universal mathematical uniqueness. @@ -47,13 +53,15 @@ decision. Metadata alone is not treated as an ISO reset marker. outvoted by a coarser same-rate chain hiding that configuration. It, or an equal best same-configuration score, returns unsupported-format / HTTP 415: **“Ambiguous free-format MPEG frame layout”**. No numeric count is guessed. -6. No qualifying candidate retains the separate **“Cannot infer a unique - free-format MPEG frame size from consecutive headers”** error. These inference - failures do not declare every such byte string ISO-invalid. +6. No qualifying candidate returns **"Cannot infer a unique free-format MPEG + frame size within the supported 320 kb/s bitrate envelope"**, with + unsupported-format / HTTP 415. This reports failed in-scope inference; it + does not diagnose an exact bitrate or declare every such byte string ISO-invalid. 7. Once established, a span is skipped without scanning payload. No new sequence causes another encoder-header subtraction: HTTP omitted/false excludes at most the upload's initial recognized Xing/Info/VBRI frame; true and the direct parser - default count physical frames. + default count physical frames. Every later free-format physical span still + must fit its rate's envelope; an overrun raises `invalid-mp3` / HTTP 422. ## Necessary side-information bounds, not decoding @@ -165,7 +173,7 @@ bounded lookahead, chunk independence, scheduling fairness, cancellation and iterator cleanup. A 2,700-byte three-frame control with dense ancillary patterns remains counted: proposed alternatives either lack their claimed history or contain impossible spectral-pair counts. No reservoir reset is assumed. All 48 normally -flushed short encoder fixtures remain mandatory controls. +flushed short encoder fixtures remain controls: 128 kbps acceptance and 400 kbps rejection. Sequence-aware property and coverage-guided fuzz targets generate changed-rate indexed/free combinations, padding/CRC/channel modes, ancillary patterns, diff --git a/docs/testing.md b/docs/testing.md index bce51eb..fc22871 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -374,7 +374,13 @@ invalid outcomes still fail the gate. The same `POST /file-upload` endpoint accepts raw `audio/mpeg` (also `audio/mp3` and `application/octet-stream`) or single-file multipart bodies. HTTP tests cover both modes, default/optional counting, 413 errors for known-length and chunked streams, and invalid query values. The owner-selected HTTP default and explicit `includeVbrHeaderFrame=false` exclude only a structurally recognized initial Xing/Info or VBRI encoder header; `true` requests physical counting. No arbitrary payload match or declared VBR count changes the answer. The supplied sample's HTTP expectations are 6089 for omitted/`false` and 6090 for `true`; the low-level parser's default remains 6090. -Independent frame constructors exercise free-format MPEG-1 Layer III across supported sample rates and padding variations, including constant spans without padding (48 kHz and 32 kHz at round bitrates), malformed alignment, decoy sync bytes and truncation. Five fixed genuine LAME encodings are always checked at 400 kbps, 320 kbps, 192 kbps and 128 kbps across all three sample rates, including parser mutation. The required Node 24 validation step regenerates and decodes those exact fixtures with `node scripts/encoder-fixtures.mjs`; a missing or different encoder fails rather than skipping coverage. Committed `short-free-format.json` adds 48 normally flushed libLAME 3.100 one-/two-frame files, with independent configured-span and encoder-count oracles. Regenerate with `python3 scripts/generate-short-free-format.py` when libmp3lame is installed; CI consumes the committed bytes and hashes without an encoder dependency. EOF/metadata-anchored acquisition and its ambiguity limits are tested separately from known-span truncation. Ancillary-only replacements in a verified zero-main-data silent frame prove that invalid or unsupported metadata envelopes and non-tail TAG strings are not automatically competing boundaries. Probe-edge regressions cover genuine ancillary TAG bytes, false ranking evidence from binary tag data, exact 8,647-byte EOF, longer inputs, fragmented reads, and the single EOF-witness byte with early iterator cleanup. A full tag-edge sweep combines one/two genuine frames with single/repeated validated tag runs, preserving earlier anchors while requiring strict final-tail truncation/error offsets. `partial-metadata-prefix.test.ts` systematically checks available header bytes (lengths 3–10, versions 2/3/4, every reserved flag bit and size-byte position), available footer prefixes, plausible controls, and unchanged strict known-boundary truncation offsets; no missing byte is treated as observed evidence. The bounded evidence ranking does not establish a unique full decoding. `metadata-layouts.test.ts` covers source-backed placement, flags, SEEK/update records, all rates/channels/CRC/padding, seeded insertion properties and chunk partitions; `encoder-layouts.test.ts` covers all Xing flags and current VBRI policy. Real free-format LAME fixtures may be reproduced with `lame --freeformat -b 400 input.wav output.mp3` and decoded with `lame --decode` for independent confirmation; FFprobe may not recognize above-table free-format bitrates. +Independent frame constructors exercise free-format MPEG-1 Layer III across supported sample rates and padding variations, including constant spans without padding, malformed alignment, decoy sync bytes and truncation. Boundary tests distinguish each rate's base and physical limits: maximum-base padding fits at 44.1 kHz but exceeds the physical envelope at 32/48 kHz, during acquisition and after lock. Extension-only ancillary candidates cannot veto supported counts. These tests implement the [documented inclusive 320 kbps interpretation](specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero), not a full bitstream-conformance or padding-schedule claim. + +`tests/mp3/free-format-rate-bound.test.ts` covers those boundaries, short streams, all channel modes and CRC settings, padding patterns, below-table spans and former high-rate extension cases. `tests/free-format-rate-upload.test.ts` checks counts and explicit envelope rejection over raw/multipart uploads with omitted/true/false count options. The independent positive-count fuzz generators stay within the envelope; fixed negative regressions retain the former high-rate cases. + +Five fixed genuine LAME encodings cover acceptance at 128, 192 and 320 kbps and rejection at 400 kbps across all three sample rates, including parser mutation. The required Node 24 validation step regenerates and decodes those exact fixtures with `node scripts/encoder-fixtures.mjs`; a missing or different encoder fails rather than skipping coverage. Committed `short-free-format.json` adds 48 normally flushed libLAME 3.100 one-/two-frame files: 24 acceptance cases at 128 kbps and 24 rejection cases at 400 kbps, with independent configured-span and encoder-count oracles. Regenerate with `python3 scripts/generate-short-free-format.py` when libmp3lame is installed; CI consumes the committed bytes and hashes without an encoder dependency. Encoder decoding establishes fixture provenance, not that an extension is within the parser's scope. + +EOF/metadata-anchored acquisition and its ambiguity limits are tested separately from known-span truncation. Ancillary-only replacements in a verified zero-main-data silent frame prove that invalid or unsupported metadata envelopes and non-tail TAG strings are not automatically competing boundaries. Probe-edge regressions retain the 8,647-byte resource budget and cover genuine ancillary TAG bytes, false ranking evidence from binary tag data, exact EOF, longer inputs, fragmented reads, and the single EOF-witness byte with early iterator cleanup. A full tag-edge sweep combines one/two genuine frames with single/repeated validated tag runs, preserving earlier anchors while requiring strict final-tail truncation/error offsets. `partial-metadata-prefix.test.ts` systematically checks available header bytes (lengths 3–10, versions 2/3/4, every reserved flag bit and size-byte position), available footer prefixes, plausible controls, and unchanged strict known-boundary truncation offsets; no missing byte is treated as observed evidence. The bounded evidence ranking does not establish a unique full decoding. `metadata-layouts.test.ts` covers source-backed placement, flags, SEEK/update records, all rates/channels/CRC/padding, seeded insertion properties and chunk partitions; `encoder-layouts.test.ts` covers all Xing flags and current VBRI policy. ## HTTP error taxonomy and adversarial framing diff --git a/fuzz/README.md b/fuzz/README.md index 0dbe340..e42528e 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -10,7 +10,11 @@ MPEG parser directly. There are three targets: - `structured.fuzz.mjs`: mutation bytes construct independently known frame boundaries for indexed and free-format MPEG-1 Layer III streams. Free-format uses one fixed bitrate and sample rate per stream, variable per-frame padding, - CRC/channel flags, and 7–640 kbps cases at all three MPEG-1 sample rates. + CRC/channel flags, and selected 7–320 kbps cases at all three MPEG-1 sample rates. + This positive-count domain follows the [documented candidate envelope](../docs/specifications/mpeg-1-layer-iii.md#4-free-format-layer-iii-bitrate-index-zero); + it does not impose a 7 kbps format minimum or certify the exact 320 kbps endpoint. + Padding stays within the physical envelope: maximum-base frames at 32/48 kHz + are unpadded; maximum-base padding remains possible at 44.1 kHz. Optional ID3 and initial Xing/Info/VBRI metadata never supply the expected count. The generator records frame offsets and lengths during construction; its known physical-frame count makes **incorrect positive counts** detectable. It also @@ -22,8 +26,9 @@ MPEG parser directly. There are three targets: - `sequences.fuzz.mjs`: two to four changed-rate configurations with independently generated indexed/free modes, CRC/channel/padding variations, boundary metadata - and ancillary patterns. The exact-count domain uses short metadata-anchored - runs and only provably impossible ancillary continuation headers. Arbitrary + and ancillary patterns. The exact-count domain uses free rates within the same + 320 kbps envelope, short metadata-anchored runs and only provably impossible + ancillary continuation headers. Arbitrary payload/layout cases assert chunk-invariant success or typed failure without assuming a construction count. Separate 864-byte and 3,780-byte seeds require explicit ambiguity; a dense 2,700-byte ancillary control must retain count 3. @@ -42,13 +47,26 @@ rejected successful counts on shorter free-format frames. The fuzzer-found `regressions/raw/free-format-three-short-frames.bin` contains three 55-byte frames; the independently constructed 72-byte `regressions/raw/free-format-minimum.bin` contains three 24-byte frames. Original prefix-only and protected regressions contain three 21-byte and three 23-byte silent frames respectively, including a checked CRC in the protected fixture. All are replayed through that oracle. Structured -seeds cover 21-byte, 24-byte and 2,880-byte base spans, including padding, and the +seeds cover 21-byte, 24-byte and 1,440-byte base spans with permitted padding, and the encoder-frame policy: an initial Xing frame, a lone VBRI frame (zero audio frames), Info shifted past a CRC, the same shift without a CRC (not metadata) and a valid Xing signature in a later frame (still counted). `scripts/structured-fuzz.test.mjs` independently checks the generated geometry and metadata policy as part of `npm run test:tooling`. The sequence generator has separate geometry/domain tooling tests and a fast-check property suite; known alternative layouts are recorded independently. +Rates formerly included in the positive domain, 384/400/500/640 kbps, now have +explicit rejection regressions in `tests/mp3/free-format-rate-bound.test.ts`, +alongside 882/960 kbps cases exposed by the former global byte limit. That suite +also tests each sample rate's maximum base, its first excluded base, physical +upper bounds before and after acquisition, maximum-base padding restrictions, +channel/CRC combinations, short streams and extension-only ancillary decoys. +`tests/mp3/free-format-real.test.ts` and `tests/mp3/short-free-format.test.ts` +retain genuine 400 kbps encoder bytes as rejection fixtures and keep their +in-scope acceptance controls. `tests/free-format-rate-upload.test.ts` verifies +the count and typed rejection over raw/multipart uploads and all three count +option settings. These fixed negative regressions are separate from the +generators' independent positive-count oracles. + ## Commands ```bash diff --git a/fuzz/create-sequences.mjs b/fuzz/create-sequences.mjs index 9ad7e60..1846cfe 100644 --- a/fuzz/create-sequences.mjs +++ b/fuzz/create-sequences.mjs @@ -1,6 +1,6 @@ /** Original bounded sequence constructions, independent of the parser under test. */ const RATES = [44_100, 48_000, 32_000]; -const FREE_KBPS = [7, 72, 128, 137, 320, 640]; +const FREE_KBPS = [7, 72, 128, 137, 320, 300]; function tag(body = Buffer.alloc(0), footer = false) { const header = Buffer.from([ @@ -30,9 +30,14 @@ function setBits(bytes, bit, width, value) { } } +function framePadding(requested, { rate, free, kbps }) { + // Preserve requested padding except at integral maximum-rate free spans. + return free && kbps === 320 && RATES[rate] !== 44100 ? 0 : requested; +} + function frame(at, serial, configuration, uncertain) { const { rate, free, kbps } = configuration; - const padding = at(20 + serial * 3) & 1; + const padding = framePadding(at(20 + serial * 3) & 1, configuration); const base = Math.floor((144_000 * (free ? kbps : 128)) / RATES[rate]); const length = base + padding; const crc = length >= 23 && Boolean(at(21 + serial * 3) & 1); @@ -148,7 +153,7 @@ function denseAncillary() { /** * Four explicit domains: metadata-anchored counts; arbitrary payload/layout * chunk invariance (no guessed count); proven ambiguity; dense ancillary control. - * At most 28 frames of 2881 bytes, plus bounded tags. No source/parser imports. + * At most 28 frames of 1440 bytes, plus bounded tags. No source/parser imports. */ export function createSequenceMp3(input) { const data = Buffer.from(input); diff --git a/fuzz/create-structured.mjs b/fuzz/create-structured.mjs index c52d9a4..ff10c23 100644 --- a/fuzz/create-structured.mjs +++ b/fuzz/create-structured.mjs @@ -9,7 +9,9 @@ */ const BITRATE_KBPS = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0]; const SAMPLE_RATE_HZ = [44_100, 48_000, 32_000]; -const FREE_BITRATE_KBPS = [8, 32, 128, 137, 256, 320, 384, 400, 500, 640, 7]; +// The positive-count domain stays inside the parser's 320 kb/s envelope. +// Preserve low, non-table rates: the indexed table does not set a free-format minimum. +const FREE_BITRATE_KBPS = [8, 32, 128, 137, 256, 320, 288, 300, 319, 72, 7]; function synchsafe(value) { return Buffer.from([ @@ -75,9 +77,9 @@ function constructionParameters(at, flags) { const minimumFrames = freeFormat && (at(2) & 64) === 0 ? 3 : 1; const frameCount = minimumFrames + (at(0) % 24); const freeSampleRateIndex = at(5) % 3; + const freeBitrateKbps = FREE_BITRATE_KBPS[at(4) % FREE_BITRATE_KBPS.length]; const freeBaseLength = Math.floor( - (144000 * FREE_BITRATE_KBPS[at(4) % FREE_BITRATE_KBPS.length]) / - SAMPLE_RATE_HZ[freeSampleRateIndex], + (144000 * freeBitrateKbps) / SAMPLE_RATE_HZ[freeSampleRateIndex], ); const metadataKind = flags & 16 ? at(6) % 3 : undefined; const metadataShifted = Boolean(at(6) & 4); @@ -87,6 +89,7 @@ function constructionParameters(at, flags) { freeFormat, frameCount, freeSampleRateIndex, + freeBitrateKbps, freeBaseLength, metadataKind, metadataShifted, @@ -109,13 +112,18 @@ function leadingTags(at, flags) { return intro; } -function createFrame(at, i, { freeFormat, freeSampleRateIndex, freeBaseLength }) { +function framePadding(requested, freeFormat, freeBitrateKbps, sampleRate) { + // At the maximum fixed rate, integral 32/48 kHz spans have no padding room. + return freeFormat && freeBitrateKbps === 320 && sampleRate !== 44100 ? 0 : requested; +} + +function createFrame(at, i, { freeFormat, freeSampleRateIndex, freeBitrateKbps, freeBaseLength }) { const bits = at(9 + 5 * i); const bitrateIndex = freeFormat ? 0 : 1 + (bits % 14); const sampleRateIndex = freeFormat ? freeSampleRateIndex : at(10 + 5 * i) % 3; - const padding = at(11 + 5 * i) & 1; const bitrate = BITRATE_KBPS[bitrateIndex]; const sampleRate = SAMPLE_RATE_HZ[sampleRateIndex]; + const padding = framePadding(at(11 + 5 * i) & 1, freeFormat, freeBitrateKbps, sampleRate); const length = (freeFormat ? freeBaseLength : Math.floor((144000 * bitrate) / sampleRate)) + padding; const hasCrc = length >= 23 && Boolean(at(12 + 5 * i) & 1); diff --git a/fuzz/seeds/structured/free-format-maximum.bin b/fuzz/seeds/structured/free-format-maximum.bin index 7e6284d..c824872 100644 Binary files a/fuzz/seeds/structured/free-format-maximum.bin and b/fuzz/seeds/structured/free-format-maximum.bin differ diff --git a/mutation-equivalents.json b/mutation-equivalents.json index aa1c2f8..74ce523 100644 --- a/mutation-equivalents.json +++ b/mutation-equivalents.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "strykerVersion": "10.1.1", "target": 100, - "contextSha256": "e5d1eff8f98dd02a72951ab77f1ef926d2d48ab9f53276ee5c60f8684d88afb0", + "contextSha256": "d927a83d257a37f8050a1372fa345e55fb416f0eab3336676638dca58dc03911", "equivalents": [ { "id": "EQ-COPY-OR", @@ -587,17 +587,17 @@ { "id": "EQ-FREE-KNOWN-SUFFIX-ACCESS", "file": "src/mp3/free-format.ts", - "sourceSha256": "6e01e42c1a1f83b0a12e1201be68977464405f53e50b569efe8eb4da3b88ac65", + "sourceSha256": "8b395a9aff1cf8b6b9ab91f11afbf27f8f978ae96c2388015fc43b14b9833684", "mutatorName": "OptionalChaining", "original": "probe.suffixes.get(offset)?.credible", "replacement": "probe.suffixes.get(offset).credible", "location": { "start": { - "line": 82, + "line": 88, "column": 5 }, "end": { - "line": 82, + "line": 88, "column": 41 } }, @@ -607,17 +607,17 @@ { "id": "EQ-FREE-UNOBSERVED-SUFFIX-TIE", "file": "src/mp3/free-format.ts", - "sourceSha256": "6e01e42c1a1f83b0a12e1201be68977464405f53e50b569efe8eb4da3b88ac65", + "sourceSha256": "8b395a9aff1cf8b6b9ab91f11afbf27f8f978ae96c2388015fc43b14b9833684", "mutatorName": "BooleanLiteral", "original": "false", "replacement": "true", "location": { "start": { - "line": 131, + "line": 145, "column": 70 }, "end": { - "line": 131, + "line": 145, "column": 75 } }, diff --git a/scripts/fuzz-tooling.characterization.test.mjs b/scripts/fuzz-tooling.characterization.test.mjs index 7457ffd..c65e96b 100644 --- a/scripts/fuzz-tooling.characterization.test.mjs +++ b/scripts/fuzz-tooling.characterization.test.mjs @@ -34,7 +34,7 @@ function constructionCorpus() { test('structured construction retains all bytes and count/geometry manifests for 2,817 inputs', () => { // Covers every placement flag with encoder variants and seeded byte inputs. // Independent geometry assertions remain in structured-fuzz.test.mjs; - // this digest locks the short-stream, metadata and seven-kbps construction corpus. + // This digest includes the 7-320 kb/s corpus and unpadded integer maximum spans. const digest = createHash('sha256'); const inputs = constructionCorpus(); assert.equal(inputs.length, 2817); @@ -47,7 +47,7 @@ test('structured construction retains all bytes and count/geometry manifests for } assert.equal( digest.digest('hex'), - '19b1463320f95ceb63050b5cff64bb0703e86aabc5ed8c3170f2f09e3ccb0252', + '7bfe59d5b85940e044b8f287453a5fc8f91c625237c5b3e507461e26af6f2f97', ); }); diff --git a/scripts/release-smoke-cases.mjs b/scripts/release-smoke-cases.mjs index 475d90e..fd825b7 100644 --- a/scripts/release-smoke-cases.mjs +++ b/scripts/release-smoke-cases.mjs @@ -49,7 +49,7 @@ function multipart(id, bytes, expected, path = '/file-upload', options = {}) { }; } -function successfulUploads(fixtures) { +function fixtureUploads(fixtures) { const cases = []; for (const fixture of fixtures) { for (const [form, create] of [ @@ -58,7 +58,11 @@ function successfulUploads(fixtures) { ]) { for (const policy of ['default', 'false', 'true']) { const query = policy === 'default' ? '' : `?includeVbrHeaderFrame=${policy}`; - const expected = success(policy === 'true' ? fixture.physicalFrames : fixture.audioFrames); + // Preserve the genuine higher-rate LAME bytes as explicit rejection controls. + const expected = + fixture.bitrate > 320 + ? failure(415, 'unsupported-format') + : success(policy === 'true' ? fixture.physicalFrames : fixture.audioFrames); cases.push( create( `${fixture.name}/${form}/${policy}`, @@ -232,7 +236,7 @@ function limitUploads() { export function buildScenarios(fixtures) { assert.ok(fixtures.length > 0, 'Known fixtures are required'); return [ - ...successfulUploads(fixtures), + ...fixtureUploads(fixtures), ...malformedUploads(fixtures[0]), ...mimeUploads(fixtures[0]), ...multipartFaults(fixtures[0]), diff --git a/scripts/release-smoke-fixtures.mjs b/scripts/release-smoke-fixtures.mjs index 7189f9b..0d5a2e7 100644 --- a/scripts/release-smoke-fixtures.mjs +++ b/scripts/release-smoke-fixtures.mjs @@ -9,6 +9,10 @@ export function decodeFixtureManifest(manifest) { assert.equal(manifest.encoder, 'LAME 3.100'); assert.ok(Array.isArray(manifest.records) && manifest.records.length > 0); return manifest.records.map((record) => { + assert.ok( + Number.isSafeInteger(record.bitrate) && record.bitrate > 0, + 'Known fixture bitrate is required', + ); const bytes = Buffer.from(record.base64, 'base64'); assert.ok(bytes.length > 0 && bytes.length <= 1024 * 1024, 'Fixture size must stay bounded'); assert.equal(bytes.length, record.bytes, 'Fixture byte length changed'); @@ -30,6 +34,7 @@ export function decodeFixtureManifest(manifest) { ); return { name: `free-format-${record.name}`, + bitrate: record.bitrate, bytes, audioFrames: record.audioFrames, physicalFrames: record.physicalFrames, diff --git a/scripts/release-smoke.test.mjs b/scripts/release-smoke.test.mjs index 2cb4eff..75108dd 100644 --- a/scripts/release-smoke.test.mjs +++ b/scripts/release-smoke.test.mjs @@ -8,7 +8,7 @@ import { uploadLimit, } from './release-smoke-cases.mjs'; import { sendRequest, verifyResponse } from './release-smoke-http.mjs'; -import { decodeFixtureManifest } from './release-smoke-fixtures.mjs'; +import { decodeFixtureManifest, loadSmokeFixtures } from './release-smoke-fixtures.mjs'; import { createHash } from 'node:crypto'; const fixture = { name: 'cbr', bytes: Buffer.from([1, 2, 3]), audioFrames: 32, physicalFrames: 33 }; @@ -75,6 +75,33 @@ test('upload-limit source stays bounded and counts frames without using producti assert.throws(() => frameStream(-1), /frame count/); }); +test('genuine free-format smoke retains in-scope counts and rejects higher-rate extensions', async () => { + const fixtures = await loadSmokeFixtures(); + assert.equal(fixtures.length, 8); + const scenarios = buildScenarios(fixtures); + const extensions = new Set(['free-format-44100-1-400-false', 'free-format-32000-1-400-true']); + for (const item of fixtures) { + for (const form of ['raw', 'multipart']) { + for (const policy of ['default', 'false', 'true']) { + const found = scenarios.find( + (scenario) => scenario.id === `${item.name}/${form}/${policy}`, + ); + assert.ok(found); + assert.deepEqual( + found.expected, + extensions.has(item.name) + ? { status: 415, error: 'unsupported-format' } + : { + status: 200, + frameCount: policy === 'true' ? item.physicalFrames : item.audioFrames, + }, + found.id, + ); + } + } + } +}); + test('multipart generator places body bytes between complete deterministic boundaries', async () => { const parts = []; for await (const part of multipartStream([Buffer.from('abc')])) parts.push(part); @@ -110,6 +137,7 @@ test('genuine fixture manifest requires exact bytes and bounded independent coun const bytes = Buffer.from('benign fixture'); const record = { name: 'reviewed', + bitrate: 128, bytes: bytes.length, audioFrames: 2, physicalFrames: 3, @@ -123,6 +151,8 @@ test('genuine fixture manifest requires exact bytes and bounded independent coun { bytes: 1 }, { audioFrames: 0 }, { physicalFrames: 99 }, + { bitrate: 0 }, + { bitrate: '400' }, ]) { assert.throws(() => decodeFixtureManifest({ ...manifest, records: [{ ...record, ...patch }] })); } diff --git a/scripts/sequence-fuzz.test.mjs b/scripts/sequence-fuzz.test.mjs index c99d1a3..d16d30b 100644 --- a/scripts/sequence-fuzz.test.mjs +++ b/scripts/sequence-fuzz.test.mjs @@ -22,13 +22,56 @@ test('sequence construction varies rates and modes while retaining independent g fixture.frameOffsets.forEach((offset, i) => { assert.equal(fixture.bytes[offset], 255); assert.equal(fixture.bytes[offset + 1] & 254, 250); - assert.ok(fixture.frameLengths[i] >= 21 && fixture.frameLengths[i] <= 2881); + assert.ok(fixture.frameLengths[i] >= 21 && fixture.frameLengths[i] <= 1440); assert.ok(offset + fixture.frameLengths[i] <= fixture.bytes.length); }); } assert.equal(covered.size, 12); }); +test('exact-count sequence rates stay within independently tabulated free-format spans', () => { + // Rows are 7, 72, 128, 137, 320 and 300 kb/s; columns are 44.1, 48 and 32 kHz. + const spans = [ + [22, 21, 31], + [235, 216, 324], + [417, 384, 576], + [447, 411, 616], + [1044, 960, 1440], + [979, 900, 1350], + ]; + for (const [bitrate, rates] of spans.entries()) { + for (const [rate, base] of rates.entries()) { + for (const padding of [0, 1]) { + const input = Buffer.alloc(160); + input[3] = rate; + input[5] = 1; + input[6] = bitrate; + input[20] = padding; + const fixture = createSequenceMp3(input); + assert.equal(fixture.expectation.kind, 'count'); + const physicalMaximum = [1045, 960, 1440][rate]; + const expectedLength = Math.min(base + padding, physicalMaximum); + assert.equal(fixture.frameLengths[0], expectedLength); + assert.equal((fixture.bytes[fixture.frameOffsets[0] + 2] >> 1) & 1, expectedLength - base); + } + } + } +}); + +test('indexed sequence frames retain requested padding at every sample rate', () => { + for (const [rate, base] of [417, 384, 576].entries()) { + for (const padding of [0, 1]) { + const input = Buffer.alloc(160); + input[3] = rate; + input[6] = 4; // Free-rate selection must not affect an indexed configuration. + input[20] = padding; + const fixture = createSequenceMp3(input); + assert.equal(fixture.frameLengths[0], base + padding); + assert.equal((fixture.bytes[fixture.frameOffsets[0] + 2] >> 1) & 1, padding); + } + } +}); + test('ambiguous constructions expose two complete independent boundary layouts', () => { for (const longer of [0, 1]) { const fixture = createSequenceMp3(Uint8Array.from([2, longer])); diff --git a/scripts/structured-fuzz.test.mjs b/scripts/structured-fuzz.test.mjs index 7bc3d74..6bdb79f 100644 --- a/scripts/structured-fuzz.test.mjs +++ b/scripts/structured-fuzz.test.mjs @@ -18,10 +18,10 @@ test('free-format manifests match independently tabulated bitrate/sample-rate sp [447, 411, 616], [835, 768, 1152], [1044, 960, 1440], - [1253, 1152, 1728], - [1306, 1200, 1800], - [1632, 1500, 2250], - [2089, 1920, 2880], + [940, 864, 1296], + [979, 900, 1350], + [1041, 957, 1435], + [235, 216, 324], [22, 21, 31], ]; for (const [bitrate, rates] of spans.entries()) { @@ -59,6 +59,57 @@ test('small free-format spans retain a fixed base with per-frame padding and CRC } }); +test('free-format upper padding stays within physical bounds without changing indexed padding', () => { + // Independent [unpadded, requested-padded] spans at 44.1, 48 and 32 kHz. + for (const { flags, bitrate, spans } of [ + { + flags: 8, + bitrate: 5, + spans: [ + [1044, 1045], + [960, 960], + [1440, 1440], + ], + }, // Free 320. + { + flags: 8, + bitrate: 8, + spans: [ + [1041, 1042], + [957, 958], + [1435, 1436], + ], + }, // Free 319. + { + flags: 0, + bitrate: 13, + spans: [ + [1044, 1045], + [960, 961], + [1440, 1441], + ], + }, // Indexed 320. + ]) { + for (const [rate, lengths] of spans.entries()) { + for (const padding of [0, 1]) { + const input = seed(flags); + input[4] = bitrate; + input[5] = rate; + for (let frame = 0; frame < 3; frame++) { + input[9 + 5 * frame] = bitrate; + input[10 + 5 * frame] = rate; + input[11 + 5 * frame] = padding; + } + const fixture = createStructuredMp3(input); + for (const [frame, offset] of fixture.frameOffsets.entries()) { + assert.equal(fixture.frameLengths[frame], lengths[padding]); + assert.equal((fixture.bytes[offset + 2] >> 1) & 1, lengths[padding] - lengths[0]); + } + } + } + } +}); + test('frame offsets exclude surrounding tags and never trust declared VBR counts', () => { for (const kind of [0, 1, 2]) { const input = seed(31); @@ -87,7 +138,7 @@ test('curated structured seeds exercise mandatory-prefix and upper free-format b for (const [name, count, base] of [ ['free-format-minimum.bin', 3, 24], ['free-format-seven-kbps.bin', 3, 21], - ['free-format-maximum.bin', 7, 2880], + ['free-format-maximum.bin', 7, 1440], ]) { const input = await readFile(new URL(`../fuzz/seeds/structured/${name}`, import.meta.url)); const fixture = createStructuredMp3(input); diff --git a/scripts/verify-encoder-discovery.mjs b/scripts/verify-encoder-discovery.mjs index 0d85bf2..95b927f 100644 --- a/scripts/verify-encoder-discovery.mjs +++ b/scripts/verify-encoder-discovery.mjs @@ -2,15 +2,13 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { isMain } from './release-utils.mjs'; -export const ENCODER_TEST_NAMES = Object.freeze( - [ - '44100-1-400-false', - '48000-2-320-false', - '32000-1-400-true', - '48000-2-128-false', - '32000-2-192-false', - ].map((name) => `counts fixed genuine LAME free-format ${name}`), -); +export const ENCODER_TEST_NAMES = Object.freeze([ + 'rejects fixed genuine LAME extension 44100-1-400-false', + 'counts fixed genuine LAME free-format 48000-2-320-false', + 'rejects fixed genuine LAME extension 32000-1-400-true', + 'counts fixed genuine LAME free-format 48000-2-128-false', + 'counts fixed genuine LAME free-format 32000-2-192-false', +]); export function assertEncoderDiscovery(report) { return assertEncoderShardDiscovery([report]); diff --git a/src/mp3/frame-spans.ts b/src/mp3/frame-spans.ts index a922042..108ca98 100644 --- a/src/mp3/frame-spans.ts +++ b/src/mp3/frame-spans.ts @@ -1,7 +1,7 @@ import type { AsyncByteReader } from './byte-reader.js'; import { Mp3ParseError } from './errors.js'; import { decodeFrameHeader, type FrameHeader, type FreeFormatFrameHeader } from './frame-header.js'; -import { inferFreeFormatBaseLength } from './free-format.js'; +import { inferFreeFormatBaseLength, MAX_FREE_FORMAT_PHYSICAL_BYTES } from './free-format.js'; /** A physical frame's decoded header and its span in bytes. */ export interface FrameSpan { @@ -53,6 +53,13 @@ export class FrameSpans { } const mode = this.mode?.kind === 'free-format' ? this.mode : await this.discover(header); const length = mode.baseLength + header.padding; + if (length > MAX_FREE_FORMAT_PHYSICAL_BYTES[header.sampleRateIndex]!) { + throw new Mp3ParseError( + 'invalid-mp3', + offset, + 'Free-format frame exceeds the supported 320 kb/s bitrate envelope', + ); + } validateFreeFormatPrefix(header, length, offset); return { header, length }; } diff --git a/src/mp3/free-format.ts b/src/mp3/free-format.ts index f54b99c..0a559dd 100644 --- a/src/mp3/free-format.ts +++ b/src/mp3/free-format.ts @@ -11,11 +11,17 @@ import { type Metadata, } from './free-format-probe.js'; -/** LAME's interoperability ceiling, not an ISO maximum or a decoded-audio guarantee. */ -export const MAX_FREE_FORMAT_FRAME_BYTES = 2_881; +// floor(144 * 320000 / sampleRate) for 44.1, 48 and 32 kHz, before padding. +// The inclusive endpoint interpretation is documented in the MPEG contract; +// extension-only rates must never contribute root or successor evidence. +const MAX_FREE_FORMAT_BASE_BYTES = [1_044, 960, 1_440] as const; +// ceil(144 * 320000 / sampleRate): at the integer 32/48 kHz endpoints +// another padding byte cannot belong to a fixed rate within the envelope. +export const MAX_FREE_FORMAT_PHYSICAL_BYTES = [1_045, 960, 1_440] as const; // The smallest physical prefix is 21 bytes; one padding byte can make base 20 fit. const MIN_FREE_FORMAT_FRAME_BYTES = 20; -const MAX_PROBE_BYTES = MAX_FREE_FORMAT_FRAME_BYTES * 3 + 4; +// Preserve the fixed observation budget independently of candidate eligibility. +const MAX_PROBE_BYTES = 8_647; interface Selection { readonly bestBase: number; @@ -88,6 +94,13 @@ function candidateIsEligible( candidate: Candidate, successorEvidenceOnly: boolean, ): boolean { + if ( + candidate.frames.some( + (frame) => + frame.end - frame.start > MAX_FREE_FORMAT_PHYSICAL_BYTES[frame.header.sampleRateIndex]!, + ) + ) + return false; if (candidate.matches < 3 && (!candidate.anchored || !probe.shortIsUnambiguous(candidate))) return false; if ( @@ -110,11 +123,12 @@ function* selectCandidate( successorEvidenceOnly = false, ): Generator { const selected = new RankedCandidates(); - // A suffix whose prefix cannot fit even the largest admitted span cannot + const maximumBase = MAX_FREE_FORMAT_BASE_BYTES[first.sampleRateIndex]!; + // A suffix whose prefix cannot fit even the largest candidate span cannot // contribute evidence. This also rejects impossible side fields once. if ( successorEvidenceOnly && - !probe.frameMayFit(start, start + MAX_FREE_FORMAT_FRAME_BYTES, first) + !probe.frameMayFit(start, start + maximumBase + first.padding, first) ) { return selected.result(); } @@ -122,7 +136,7 @@ function* selectCandidate( for (let index = begin; index < probe.landmarks.length; index++) { if (probe.shouldYield()) yield { ...probe.work }; const base = probe.landmarks[index]! - start - first.padding; - if (base >= MAX_FREE_FORMAT_FRAME_BYTES) break; + if (base > maximumBase) break; probe.visitCandidate(); const candidate = followCandidate(probe, start, first, base); if (!candidateIsEligible(probe, candidate, successorEvidenceOnly)) continue; @@ -305,7 +319,7 @@ export async function inferFreeFormatBaseLength( start, evidence.tied ? 'Ambiguous free-format MPEG frame layout' - : 'Cannot infer a unique free-format MPEG frame size from consecutive headers', + : 'Cannot infer a unique free-format MPEG frame size within the supported 320 kb/s bitrate envelope', ); } return evidence.bestBase; diff --git a/tests/free-format-rate-upload.test.ts b/tests/free-format-rate-upload.test.ts new file mode 100644 index 0000000..5cecbd5 --- /dev/null +++ b/tests/free-format-rate-upload.test.ts @@ -0,0 +1,82 @@ +import { expect, it } from 'vitest'; +import { buildApp } from '../src/app.js'; +import { multipartBody } from './helpers/mp3-fixtures.js'; + +it('counts in-scope ancillary decoys and rejects extension-only rates through both upload modes', async () => { + const valid = Buffer.alloc(7200); + for (let offset = 0; offset < valid.length; offset += 900) valid.set([255, 251, 4, 192], offset); + for (const offset of [1440, 2880]) valid.set([255, 251, 4, 192], offset); + for (let offset = 4320; offset < valid.length; offset += 576) + valid.set([255, 251, 0x98, 192], offset); + const extension = Buffer.alloc(3600); + for (let offset = 0; offset < extension.length; offset += 1200) + extension.set([255, 251, 4, 192], offset); + const app = await buildApp(); + try { + for (const bytes of [valid, extension]) { + for (const { contentType, payload } of [ + { contentType: 'audio/mpeg', payload: bytes }, + multipartBody(bytes), + ]) { + for (const query of ['', '?includeVbrHeaderFrame=true', '?includeVbrHeaderFrame=false']) { + const response = await app.inject({ + method: 'POST', + url: '/file-upload' + query, + headers: { 'content-type': contentType }, + payload, + }); + expect(response.headers['content-type']).toContain('application/json'); + expect(response.statusCode).toBe(bytes === valid ? 200 : 415); + expect(response.json()).toEqual( + bytes === valid + ? { frameCount: 8 } + : { + error: 'unsupported-format', + message: + 'Cannot infer a unique free-format MPEG frame size within the supported 320 kb/s bitrate envelope', + }, + ); + } + } + } + } finally { + await app.close(); + } +}); + +it.each([false, true])( + 'reports impossible upper-bound padding after locking=%s through both upload modes', + async (locked) => { + const bytes = Buffer.concat( + Array.from({ length: locked ? 13 : 4 }, (_, index) => { + const padding = !locked || index === 12; + const frame = Buffer.alloc(960 + Number(padding)); + frame.set([255, 251, padding ? 6 : 4, 192]); + return frame; + }), + ); + const app = await buildApp(); + try { + for (const { contentType, payload } of [ + { contentType: 'audio/mpeg', payload: bytes }, + multipartBody(bytes), + ]) { + const response = await app.inject({ + method: 'POST', + url: '/file-upload', + headers: { 'content-type': contentType }, + payload, + }); + expect(response.statusCode).toBe(locked ? 422 : 415); + expect(response.json()).toEqual({ + error: locked ? 'invalid-mp3' : 'unsupported-format', + message: locked + ? 'Free-format frame exceeds the supported 320 kb/s bitrate envelope' + : 'Cannot infer a unique free-format MPEG frame size within the supported 320 kb/s bitrate envelope', + }); + } + } finally { + await app.close(); + } + }, +); diff --git a/tests/mp3/count-frames.test.ts b/tests/mp3/count-frames.test.ts index 8cfe92e..eaf9761 100644 --- a/tests/mp3/count-frames.test.ts +++ b/tests/mp3/count-frames.test.ts @@ -271,7 +271,8 @@ describe('streaming MP3 frame counting', () => { await expect(count(freeFormatHeader, 1)).rejects.toMatchObject({ kind: 'unsupported-format', offset: 0, - message: 'Cannot infer a unique free-format MPEG frame size from consecutive headers', + message: + 'Cannot infer a unique free-format MPEG frame size within the supported 320 kb/s bitrate envelope', }); const first = frame(); await expect(count(Buffer.concat([first, freeFormatHeader]), 1)).rejects.toMatchObject({ diff --git a/tests/mp3/free-format-metadata.test.ts b/tests/mp3/free-format-metadata.test.ts index abed43f..dd3fc30 100644 --- a/tests/mp3/free-format-metadata.test.ts +++ b/tests/mp3/free-format-metadata.test.ts @@ -301,16 +301,20 @@ describe('bounded free-format metadata acquisition', () => { }); it('rejects equally supported candidates that imply different physical counts', async () => { - // Two complete structural partitions share EOF: 36×2800 and 35×2880. - // The bounded probe contains four headers from each, with equal evidence. + // Two complete structural partitions share EOF: 36×700 and 35×720. + // The bounded probe contains thirteen headers from each, with equal evidence. // These are alternative header partitions, not asserted decodable audio. - const bytes = Buffer.alloc(100800, 0x11); - for (const span of [2800, 2880]) { + const bytes = Buffer.alloc(25200, 0x11); + for (const span of [700, 720]) { for (let offset = 0; offset < bytes.length; offset += span) { bytes.set([255, 251, 0, 192], offset); } } - await expect(count([bytes])).rejects.toMatchObject({ kind: 'unsupported-format', offset: 0 }); + await expect(count([bytes])).rejects.toMatchObject({ + kind: 'unsupported-format', + offset: 0, + message: 'Ambiguous free-format MPEG frame layout', + }); }); it('preserves known final-frame truncation once at least three headers establish a span', async () => { diff --git a/tests/mp3/free-format-probe.test.ts b/tests/mp3/free-format-probe.test.ts index 42fb83e..a662d45 100644 --- a/tests/mp3/free-format-probe.test.ts +++ b/tests/mp3/free-format-probe.test.ts @@ -110,7 +110,7 @@ describe('probe work is driven by supported boundary evidence', () => { }); it('does not turn non-target ancillary sync markers into extra candidate walks or yields', async () => { - const clean = freeFrame(2_880); + const clean = freeFrame(1_044); const first = decodeFrameHeader(clean.subarray(0, 4)); if (first.kind !== 'free-format') throw new Error('Invalid fixture'); const baseline = analyzeFreeFormatProbeSteps(clean, first, true, clean.length).next(); diff --git a/tests/mp3/free-format-rate-bound.test.ts b/tests/mp3/free-format-rate-bound.test.ts new file mode 100644 index 0000000..178ecca --- /dev/null +++ b/tests/mp3/free-format-rate-bound.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from 'vitest'; +import { countMp3Frames } from '../../src/mp3/count-frames.js'; +import { chunks, id3v2 } from '../helpers/mp3-fixtures.js'; + +// Independent byte-spacing oracle. Zero side information declares no reservoir +// or audio bits, so bytes after each mandatory prefix are ancillary data. +function freeFrames( + base: number, + count: number, + rateIndex = 1, + mode = 3, + crc = false, + pads = [0], +): Buffer { + return Buffer.concat( + Array.from({ length: count }, (_, index) => { + const padding = pads[index % pads.length]!; + const bytes = Buffer.alloc(base + padding); + bytes.set([0xff, crc ? 0xfa : 0xfb, (rateIndex << 2) | (padding << 1), mode << 6]); + return bytes; + }), + ); +} + +function writeBits(bytes: Buffer, start: number, width: number, value: number): void { + for (let bit = 0; bit < width; bit++) { + const position = start + bit; + bytes[position >>> 3]! |= ((value >>> (width - bit - 1)) & 1) << (7 - (position & 7)); + } +} + +describe('free-format bitrate candidate eligibility', () => { + it('does not let impossible maximum-rate padding veto an in-scope ancillary layout', async () => { + const original = freeFrames(899, 9, 1, 3, false, [1]); + const altered = Buffer.from(original); + for (const offset of [961, 1922]) altered.set([255, 251, 6, 192], offset); + for (let offset = 2883; offset < 8067; offset += 576) + altered.set([255, 251, 0x98, 192], offset); + altered.set(id3v2(Buffer.alloc(13), 4, true), 8067); + for (let offset = 0; offset < altered.length; offset += 900) + expect(altered.subarray(offset, offset + 21)).toEqual(original.subarray(offset, offset + 21)); + for (const size of [1, 7, 4096, altered.length]) + await expect(countMp3Frames(chunks(altered, [size]))).resolves.toBe(9); + }); + + it.each([ + { rate: 1, base: 960 }, + { rate: 2, base: 1440 }, + ])( + 'rejects maximum-base padding at rate $rate during acquisition and after locking', + async ({ rate, base }) => { + for (const pads of [[1], [0, 1]]) { + await expect( + countMp3Frames(chunks(freeFrames(base, 4, rate, 3, false, pads), [7])), + ).rejects.toMatchObject({ kind: 'unsupported-format' }); + } + const prefix = freeFrames(base, 12, rate); + const bytes = Buffer.concat([prefix, freeFrames(base, 1, rate, 3, false, [1])]); + await expect(countMp3Frames(chunks(bytes, [1, 4096]))).rejects.toMatchObject({ + kind: 'invalid-mp3', + offset: prefix.length, + message: 'Free-format frame exceeds the supported 320 kb/s bitrate envelope', + }); + }, + ); + it.each([1, 7, 4096, 7200])( + 'does not let an extension-only ancillary layout veto 300 kb/s frames (chunks %i)', + async (chunkSize) => { + const original = freeFrames(900, 8); + const altered = Buffer.from(original); + // Three 1,440-byte free frames at 48 kHz would require 480 kb/s. + for (const offset of [1440, 2880]) altered.set([0xff, 0xfb, 4, 0xc0], offset); + // Its changed-rate indexed suffix closes EOF, but cannot make that prefix legal. + for (let offset = 4320; offset < altered.length; offset += 576) + altered.set([0xff, 0xfb, 0x98, 0xc0], offset); + for (let offset = 0; offset < altered.length; offset += 900) + expect(altered.subarray(offset, offset + 21)).toEqual( + original.subarray(offset, offset + 21), + ); + await expect(countMp3Frames(chunks(original, [chunkSize]))).resolves.toBe(8); + await expect(countMp3Frames(chunks(altered, [chunkSize]))).resolves.toBe(8); + }, + ); + + it.each([1, 2, 3, 8])('rejects %i free-format frames requiring 400 kb/s', async (count) => { + await expect(countMp3Frames(chunks(freeFrames(1200, count), [7]))).rejects.toMatchObject({ + kind: 'unsupported-format', + message: + 'Cannot infer a unique free-format MPEG frame size within the supported 320 kb/s bitrate envelope', + }); + }); + + it('rejects an extension-only changed-rate suffix after a legal prefix', async () => { + const bytes = Buffer.concat([freeFrames(900, 3, 2), freeFrames(1200, 3, 1)]); + for (const chunkSize of [1, 7, 4096]) + await expect(countMp3Frames(chunks(bytes, [chunkSize]))).rejects.toMatchObject({ + kind: 'unsupported-format', + offset: 2700, + }); + }); + + it.each([384, 400, 500, 640, 882, 960])( + 'rejects the former extension rate %i kb/s at every sample rate', + async (bitrate) => { + for (const [rateIndex, rate] of [44100, 48000, 32000].entries()) { + const bytes = freeFrames(Math.floor((144000 * bitrate) / rate), 4, rateIndex); + await expect(countMp3Frames(chunks(bytes, [7, 4096]))).rejects.toMatchObject({ + kind: 'unsupported-format', + }); + } + }, + ); + + it.each([1044, 960, 1440])( + 'retains a changed-rate successor filling the %i-byte base envelope', + async (maximum) => { + const rateIndex = [1044, 960, 1440].indexOf(maximum); + for (const crc of [false, true]) + for (const padding of [0, 1]) { + for (const extra of [0, 1]) { + const base = rateIndex === 0 ? maximum : maximum - padding; + const suffix = freeFrames(base, 1, rateIndex, 0, crc, [padding]); + const prefix = crc ? 38 : 36; + let remaining = (suffix.length - prefix + extra) * 8; + // Four independent stereo part2_3_length records; this tests necessary + // capacity, not the decoding of their zero-filled main data. + for (let record = 0; record < 4; record++) { + const bits = Math.min(4095, remaining); + writeBits(suffix, (crc ? 6 : 4) * 8 + 20 + record * 59, 12, bits); + remaining -= bits; + } + expect(remaining).toBe(0); + const bytes = Buffer.concat([freeFrames(100, 2, (rateIndex + 1) % 3), suffix]); + const result = countMp3Frames(chunks(bytes, [1, 7, 4096])); + if (extra === 0) await expect(result).resolves.toBe(3); + else await expect(result).rejects.toMatchObject({ kind: 'unsupported-format' }); + } + } + }, + ); + + it.each([ + { rateIndex: 0, maximum: 1044 }, + { rateIndex: 1, maximum: 960 }, + { rateIndex: 2, maximum: 1440 }, + ])( + 'uses the unpadded boundary for every prefix at sample rate $rateIndex', + async ({ rateIndex, maximum }) => { + // The endpoint is the documented inclusive project interpretation. At + // 44.1 kHz one inferred span represents a rate interval, not an exact rate. + for (const mode of [0, 1, 2, 3]) + for (const crc of [false, true]) { + for (const pads of [[0], [1], [1, 0, 1]]) + for (const count of [1, 2, 4]) { + for (const base of [maximum - 1, maximum]) { + const bytes = freeFrames(base, count, rateIndex, mode, crc, pads); + const result = countMp3Frames(chunks(bytes, [1, 7, 4096])); + if (rateIndex !== 0 && base === maximum && pads.includes(1)) + await expect(result).rejects.toMatchObject({ kind: 'unsupported-format' }); + else await expect(result).resolves.toBe(count); + } + const bytes = freeFrames(maximum + 1, count, rateIndex, mode, crc, pads); + await expect(countMp3Frames(chunks(bytes, [1, 7, 4096]))).rejects.toMatchObject({ + kind: 'unsupported-format', + offset: 0, + }); + } + } + }, + ); + + it.each([0, 1, 2])( + 'does not impose the indexed 32 kb/s minimum at rate %i', + async (rateIndex) => { + for (const chunkSize of [1, 4096]) + await expect( + countMp3Frames(chunks(freeFrames(40, 4, rateIndex, 0, true, [1, 0]), [chunkSize])), + ).resolves.toBe(4); + }, + ); +}); diff --git a/tests/mp3/free-format-real.test.ts b/tests/mp3/free-format-real.test.ts index 4751389..dc38ae7 100644 --- a/tests/mp3/free-format-real.test.ts +++ b/tests/mp3/free-format-real.test.ts @@ -6,6 +6,7 @@ import { chunks } from '../helpers/mp3-fixtures.js'; interface EncoderFixture { name: string; + bitrate: number; base64: string; sha256: string; bytes: number; @@ -28,15 +29,39 @@ expect(manifest.records.map((record) => record.name)).toEqual([ '32000-2-192-false', ]); -it.each(manifest.records)('counts fixed genuine LAME free-format $name', async (record) => { +function verifiedBytes(record: EncoderFixture): Buffer { const bytes = Buffer.from(record.base64, 'base64'); expect(bytes.length).toBe(record.bytes); expect(createHash('sha256').update(bytes).digest('hex')).toBe(record.sha256); expect(record.physicalFrames).toBe(record.audioFrames + 1); - for (const sizes of [[3, 47, 8192], [1]]) { - expect(await countMp3Frames(chunks(bytes, sizes))).toBe(record.physicalFrames); - expect(await countMp3Frames(chunks(bytes, sizes), { includeVbrHeaderFrame: false })).toBe( - record.audioFrames, - ); - } -}); + return bytes; +} + +it.each(manifest.records.filter((record) => record.bitrate <= 320))( + 'counts fixed genuine LAME free-format $name', + async (record) => { + const bytes = verifiedBytes(record); + for (const sizes of [[3, 47, 8192], [1]]) { + expect(await countMp3Frames(chunks(bytes, sizes))).toBe(record.physicalFrames); + expect(await countMp3Frames(chunks(bytes, sizes), { includeVbrHeaderFrame: false })).toBe( + record.audioFrames, + ); + } + }, +); + +// LAME can encode/decode its extensions; that does not make their rates part +// of the MPEG-1 Layer III candidate envelope used by this parser. +it.each(manifest.records.filter((record) => record.bitrate > 320))( + 'rejects fixed genuine LAME extension $name', + async (record) => { + const bytes = verifiedBytes(record); + for (const sizes of [[3, 47, 8192], [1]]) { + for (const includeVbrHeaderFrame of [true, false]) { + await expect( + countMp3Frames(chunks(bytes, sizes), { includeVbrHeaderFrame }), + ).rejects.toMatchObject({ kind: 'unsupported-format' }); + } + } + }, +); diff --git a/tests/mp3/free-format.test.ts b/tests/mp3/free-format.test.ts index dc24f00..95a9bd4 100644 --- a/tests/mp3/free-format.test.ts +++ b/tests/mp3/free-format.test.ts @@ -33,9 +33,9 @@ describe('free-format MPEG-1 Layer III', () => { } }); - it('recognizes a real-sized 400 kbps free-format frame sequence', async () => { + it('rejects a 400 kbps free-format extension sequence', async () => { const bytes = mp3(Array.from({ length: 7 }, (_, i) => freeFrame(1306, i % 3 === 0 ? 1 : 0))); - await expect(count(bytes, 127)).resolves.toBe(7); + await expect(count(bytes, 127)).rejects.toMatchObject({ kind: 'unsupported-format' }); }); it('includes an initial free-format Info frame by default and excludes it on request', async () => { @@ -133,23 +133,22 @@ describe('free-format MPEG-1 Layer III', () => { it('accepts the smallest and largest supported spans', async () => { await expect(count(mp3(Array.from({ length: 4 }, () => freeFrame(21))))).resolves.toBe(4); - // A padded 2,881-byte first frame puts the second header at the last candidate offset. - const largest = mp3(Array.from({ length: 4 }, () => freeFrame(2_880, 1))); + // At 32 kHz the inclusive endpoint has a constant 1,440-byte span. + const largest = mp3(Array.from({ length: 4 }, () => freeFrame(1_440, 0, 2))); await expect(count(largest, 4096)).resolves.toBe(4); }); it('rejects spans just outside the supported range despite consecutive headers', async () => { const belowMinimum = mp3([freeFrame(19, 1), freeFrame(19), freeFrame(19)]); await expect(count(belowMinimum)).rejects.toMatchObject({ kind: 'unsupported-format' }); - const aboveMaximum = mp3(Array.from({ length: 3 }, () => freeFrame(2_881))); + const aboveMaximum = mp3(Array.from({ length: 3 }, () => freeFrame(1_045))); await expect(count(aboveMaximum, 4096)).rejects.toMatchObject({ kind: 'unsupported-format' }); }); - it('sees the fourth maximum-size header at the probe edge over a shorter payload chain', async () => { - // The probe holds three maximum frames plus one header. The genuine chain - // then has four headers, outweighing a three-header decoy chain in frame 0. - const frames = Array.from({ length: 5 }, () => freeFrame(2_880, 1)); - for (const offset of [1_000, 2_000]) frames[0]!.set([0xff, 0xfb, 0x02, 0xc4], offset); + it('prefers a maximum-size frame chain over a shorter ancillary chain', async () => { + // The genuine chain has more evidence than the three-header ancillary chain. + const frames = Array.from({ length: 5 }, () => freeFrame(1_439, 1, 2)); + for (const offset of [500, 1_000]) frames[0]!.set([0xff, 0xfb, 0x0a, 0xc4], offset); await expect(count(mp3(frames), 4096)).resolves.toBe(5); }); @@ -159,14 +158,14 @@ describe('free-format MPEG-1 Layer III', () => { await expect(count(input)).rejects.toMatchObject({ kind: 'invalid-mp3' }); }); it('reports ambiguous one-frame rate changes after successful frame inference', async () => { - const blocks = Array.from({ length: 7 }, () => freeFrame(730)); + const blocks = Array.from({ length: 7 }, () => freeFrame(400)); // The changed-rate alternative must have possible side information; // the generic 0x11 filler transmits a reserved switched block type zero. for (const block of blocks) block.fill(0, 4, 21); blocks[5]![2] = 4; // Beyond the initial three-header acquisition chain. await expect(count(mp3(blocks), 1)).rejects.toMatchObject({ kind: 'unsupported-format', - offset: 5 * 730, + offset: 5 * 400, message: 'Ambiguous free-format MPEG frame layout', }); }); @@ -205,9 +204,9 @@ describe('free-format MPEG-1 Layer III', () => { tooShort.set([0xff, 0xfb, 0, 0xc4], 20); await expect(count(tooShort)).rejects.toMatchObject({ kind: 'unsupported-format' }); - const tooLong = Buffer.alloc(2_885, 0x11); + const tooLong = Buffer.alloc(1_049, 0x11); tooLong.set([0xff, 0xfb, 0, 0xc4], 0); - tooLong.set([0xff, 0xfb, 0, 0xc4], 2_881); // Base 2881 exceeds bound. + tooLong.set([0xff, 0xfb, 0, 0xc4], 1_045); // Base 1045 exceeds the 44.1 kHz bound. await expect(count(tooLong)).rejects.toMatchObject({ kind: 'unsupported-format' }); }); diff --git a/tests/mp3/runtime-characterization.test.ts b/tests/mp3/runtime-characterization.test.ts index 15d0e2b..ffc0b97 100644 --- a/tests/mp3/runtime-characterization.test.ts +++ b/tests/mp3/runtime-characterization.test.ts @@ -179,11 +179,11 @@ describe('free-format candidate characterization', () => { it.each([8648, 9000])( 'stops discovery after the bounded probe and EOF witness within a %i-byte input chunk', async (size) => { - const bytes = headerWindow(size, [0, 2881, 5762, 8643]); - for (const offset of [0, 2881, 5762, 8643]) bytes[offset + 2] = 2; + const bytes = headerWindow(size, [0, 1001, 2002, 3003]); + for (const offset of [0, 1001, 2002, 3003]) bytes[offset + 2] = 2; const { input, events } = trackedInput([bytes], new Error('must not request another chunk')); const reader = new AsyncByteReader(input); - await expect(infer(reader)).resolves.toBe(2880); + await expect(infer(reader)).resolves.toBe(1000); expect(reader.offset).toBe(0); expect(reader.bufferedLength).toBe(size); expect(reader.peek(size)).toEqual(bytes); @@ -194,11 +194,11 @@ describe('free-format candidate characterization', () => { ); it('requests EOF once when the input exactly fills the searched window', async () => { - const bytes = headerWindow(8647, [0, 2881, 5762, 8643]); - for (const offset of [0, 2881, 5762, 8643]) bytes[offset + 2] = 2; + const bytes = headerWindow(8647, [0, 1001, 2002, 3003]); + for (const offset of [0, 1001, 2002, 3003]) bytes[offset + 2] = 2; const { input, events } = trackedInput([bytes]); const reader = new AsyncByteReader(input); - await expect(infer(reader)).resolves.toBe(2880); + await expect(infer(reader)).resolves.toBe(1000); expect(reader.offset).toBe(0); expect(reader.bufferedLength).toBe(8647); expect(reader.peek(8647)).toEqual(bytes); diff --git a/tests/mp3/sequence-work.test.ts b/tests/mp3/sequence-work.test.ts index d263b63..21c553a 100644 --- a/tests/mp3/sequence-work.test.ts +++ b/tests/mp3/sequence-work.test.ts @@ -78,7 +78,8 @@ it('distinguishes absence of any candidate from an actual ambiguous candidate se await expect(countMp3Frames(chunks(headerOnly, [1]))).rejects.toMatchObject({ kind: 'unsupported-format', offset: 0, - message: 'Cannot infer a unique free-format MPEG frame size from consecutive headers', + message: + 'Cannot infer a unique free-format MPEG frame size within the supported 320 kb/s bitrate envelope', }); }); diff --git a/tests/mp3/short-free-format.test.ts b/tests/mp3/short-free-format.test.ts index 1d3c2e0..fb1cfcb 100644 --- a/tests/mp3/short-free-format.test.ts +++ b/tests/mp3/short-free-format.test.ts @@ -24,8 +24,13 @@ const count = (bytes: Uint8Array, sizes: number[] = [1, 3, 7, 128]) => // Committed fixtures are normal encoder output, not trimmed longer MP3 files. describe('genuine normally flushed short free-format files', () => { - it.each(manifest.fixtures)( - '$rate Hz, $channels channel(s), CRC=$crc, $kbps kbps, $pcmSamples PCM samples', + it.each( + manifest.fixtures.map((fixture) => ({ + ...fixture, + outcome: fixture.kbps > 320 ? 'rejects extension' : 'counts', + })), + )( + '$outcome $rate Hz, $channels channel(s), CRC=$crc, $kbps kbps, $pcmSamples PCM samples', async (fixture) => { const bytes = Buffer.from(fixture.base64, 'base64'); expect(createHash('sha256').update(bytes).digest('hex')).toBe(fixture.sha256); @@ -39,7 +44,9 @@ describe('genuine normally flushed short free-format files', () => { } expect(end).toBe(bytes.length); for (const sizes of [[1], [2, 3, 5, 11], [bytes.length]]) { - expect(await count(bytes, sizes)).toBe(fixture.frames); + if (fixture.kbps > 320) + await expect(count(bytes, sizes)).rejects.toMatchObject({ kind: 'unsupported-format' }); + else expect(await count(bytes, sizes)).toBe(fixture.frames); } const tagged = Buffer.concat([ metadataTag(4, { seek: bytes.length }), @@ -47,7 +54,9 @@ describe('genuine normally flushed short free-format files', () => { metadataTag(4, { footer: true }), metadataV1(1), ]); - expect(await count(tagged)).toBe(fixture.frames); + if (fixture.kbps > 320) + await expect(count(tagged)).rejects.toMatchObject({ kind: 'unsupported-format' }); + else expect(await count(tagged)).toBe(fixture.frames); }, );