# Calling MoonJLS

## MoonBit

Install the module from an existing project with `moon add ZSY2221/moon_jpegls`. External consumers verified the public core API on Native, JS and Wasm GC. Build the browser SDK and Worker from the repository. [Exact versions and reproduction](MOONCAKES_RELEASE.md)

Import package `ZSY2221/moon_jpegls/core` as `@jls`. `Frame` holds `width`, `height`, `bits` and `near`. `Frame::maxval()` derives MAXVAL from a valid coded `bits`. For the current profile, coded precision is 2–16 and integer `near` runs through min(255, floor(effective MAXVAL/2)). Pass optional `preset~` to `Encoder::new` or `encode` for non-default MAXVAL, T1/T2/T3 or RESET. Accessors and `decode_with_preset` return the resolved preset. An out-of-range encode argument yields `InvalidArgument`; a coded NEAR beyond the legal MAXVAL bound yields `InvalidData`. `Limits::default()` allows up to 65535 on either axis, 100 million pixels and 1 MiB of APPn/COM marker segments. Applications may choose lower limits before accepting a stream.

```moonbit
let frame : @jls.Frame = { width: 3, height: 2, bits: 16, near: 0 }
let samples : FixedArray[Int] = [0, 32767, 32768, 65535, 1, 42]
let compressed = @jls.encode(frame, samples)
let (decoded_frame, reconstructed) = @jls.decode(compressed)
```

`encode(frame, pixels, limits?)` and `decode(bytes, limits?)` raise `CodecError` and allocate the entire result. The latter rejects input after EOI; single-component `decode` rejects multi-component streams with `UnsupportedFeature` for backward compatibility. For a row-bounded stream independent of height, call `Encoder::new(frame, limits)`, `Encoder::new_multicomponent(frame_info, scans, limits?)`, or `Decoder::new(limits)` and advance explicitly. Multi-component non-interleaved (`ILV=0`, `H=V=1`, `Pt=0`) callers use `FrameInfo`, `ComponentSpec`, `ScanSpec`, `encode_multicomponent`, `decode_multicomponent`, and `inspect(bytes, limits?)`, which expose `ScanInfo`, `StreamStructure`, and `ErrorLocation`.

For ILV=1 or ILV=2 with equal-sized components, use `Encoder::new_scans` or `encode_scans` with `MultiScanSpec`. ILV=1 takes each component's complete row in SOS order. ILV=2 takes one sample per SOS component at each pixel. `Decoder::step` delivers one planar row at a time with its component ID and row index.

For embedded single-byte mapping tables, `Decoder::row()` and whole-image decoding return the mapped unsigned samples. `Decoder::scan_mapping_selector(scan_index, slot)` reads the SOS selector in scan component order. `Decoder::current_row_mapping_selector()` reads the selector of the last delivered row. APPn, COM, LSE1, embedded mapping segments and supported DRI share the cumulative `max_metadata_bytes` wire budget. The preset segments emitted by the encoder also charge this limit. The SDK exposes `scan.mappingSelectors` and `rowMeta.mappingSelector` when a table is used. Native JSON inspection reports `mappingSelectors`. Native and workbench Netpbm exports use MAXVAL 255 for mapped rows; NEAR continues to describe reconstructed indices in the coding domain. [Embedded mapping scope](EMBEDDED_MAPPING_RESULTS.md)

Pass `mappings~ : Array[ScanMappings]` to `Encoder::new_scans` or `encode_scans`. Each config corresponds to a scan and holds `definitions : Array[MappingDefinition]` plus `selectors : Array[Int32]` in SOS component order. Provide immutable `Bytes` indexed from 0 to the active MAXVAL. An empty selector array selects identity, and a zero skips mapping for that component. Earlier tables can be reused or replaced. The encoder receives indices for selected components. It writes the tables incrementally under output backpressure. The default budget remains 1 MiB. A caller with a smaller budget should include the emitted full LSE1, LSE2 and LSE3 segment sizes.

```moonbit
let mappings : Array[@jls.ScanMappings] = [
  { selectors: [7], definitions: [{ id: 7, entries: b"\xc9\xd4\xdf\xea" }] },
]
// For a P2 4×1 frame and its one ILV=0 scan.
let coded = @jls.encode_scans(frame, scans, [0, 3, 1, 2], mappings~)
let (_, pixels) = @jls.decode(coded)
assert_eq(pixels, [201, 234, 212, 223])
```

For widths 1–255, pass `mapping_tables~ : Array[ScanMappingTables]` instead of the Wt=1 convenience configuration. A `MappingTableSpec` supplies `id`, `entry_bytes`, and immutable `entries` in index order. Each nonzero SOS selector requires exactly `MAXVAL + 1` entries and Pt=0. For the opt-in decoder use `Decoder::new(limits, opaque_mapping=true)`. On `RowReady`, a width above one from `current_row_mapping_entry_bytes()` selects `opaque_row()`. The row is a borrowed array of `current_row_width() × Wt` bytes in table order. `index_row()` borrows reconstructed coding-domain indices and `row()` remains the scalar access path. Copy borrowed rows before the next step. `scan_mapping_entry_bytes(scan, slot)` records the selected width at SOS, including across table replacement.

The Native raw CLI uses `--mapping-selectors` and repeatable `--scan-table`. For a one-scan P2 file containing the four indices as bytes, use `moonjls encode-planar 4 1 2 1 0 indices.raw mapped.jls --mapping-selectors 7 --scan-table 0,7,table.bin`. The table file contains four bytes in index order. Use `--scan-wide-table SCAN,TID,WT,FILE` for multi-byte entries. To decode, `mapped-bytes` writes rows in decoder delivery order, with Wt bytes per mapped sample for Wt>1 and uint32 little-endian for scalar rows. `inspect --json` exposes sample geometry and per-SOS `mappingEntryBytes`.

### Standalone C.4 table streams

`encode_tables(definitions, ...)` takes mapping definitions and accepts optional raw `preset=` and `limits=` arguments. `load_tables(bytes, base=..., limits=...)` returns an immutable `TableContext`. A newer LSE2 replaces that ID with its own aligned LSE3 chain. Unrelated tables are shared. `table_info(id)` returns width and count, `table_byte(id, offset)` reads one byte in table order, and `table(id)` returns an owned table. `TableContext::empty()` starts a fresh bank. Raw LSE1 fields describe only the current table stream.

`TableLoader::step` supports incremental input. It publishes a snapshot after EOI and EOF. Errors and cancellation release staged data and leave the base snapshot usable. The metadata limit bounds current segment bytes and the resulting installed table payload separately. Earlier snapshots can remain live while users retain references.

Native offers `inspect-tables`, `extract-table` and `encode-tables`. The SDK exposes `loadTableStream` and `core.createTableLoader`. SDK `getTable()` returns a fresh `Uint8Array`. Load steps accept a byte chunk or `null` to confirm EOF. A base snapshot comes from the same loaded codec. [Conformance and examples](TABLE_STREAM_RESULTS.md)

### C.3 images with external tables

Pass `external_tables=Some(context)` to `Encoder::new_scans`, `encode_scans`, `Decoder::new`, or the scalar whole-image decode functions. The encoder writes the SOS selectors and only the inline definitions explicitly listed in each scan. Both codecs check each selected table against the image's effective MAXVAL. The current image's inline LSE2 can shadow that ID from its definition onward. The original snapshot stays usable after success, failure, or cancellation. Image presets always come from the image. For Wt>1 use `opaque_mapping=true` with a streaming decoder or inspector.

Native supports `--table-stream FILE` on `encode-planar`, `decode`, `decode-pgms`, `inspect`, and `verify`. Use `--mapping-selectors LIST` when encoding. The SDK takes `tableContext` from its own loaded codec. A Worker takes the C.4 file bytes as `tableStream` and installs them for the current job. [C.3 examples and verification](ABBREVIATED_IMAGE_RESULTS.md)

### Restart intervals

For a grayscale encoder pass `restart_interval=2L`. For an explicit scan sequence pass `restart_intervals=[2L, 0L]` to `Encoder::new_scans` or `encode_scans`, with one interval per scan. Each value counts MCUs. Use zero to disable restarts. A decoder exposes the active value with `scan_restart_interval(index)` and the validated marker count with `scan_restart_count(index)`. Native and Node encode CLIs accept `--restart N` for the common value. SDK and Worker encoders accept `frame.restartInterval` and `scan.restartInterval`. [Restart examples and verification](RESTART_INTERVAL_RESULTS.md)
### Deferred frame height

Native `encode-planar --dnl` and SDK encoder option `deferHeight: true` write SOF55 with Y=0 and place DNL immediately after the first scan. Supply the actual input height when constructing the encoder. The decoder accepts 16-, 24- and 32-bit DNL values within its configured dimension limits. It also accepts a matching DNL after the first scan when SOF55 already supplies a positive Y.

With Y=0 or explicit redefinition enabled, the decoder stages the first coded scan until it can resolve the height, then replays that scan with the resolved component geometry. The first row is delivered after resolution. The prefix limit is 32 MiB plus one 4 KiB staging block. Exceeding the prefix or dimension limit returns `ResourceLimit`. Native `inspect --json` reports the retained-byte peak as `deferredScanPeakBytes`. The default known-height decode remains row-bounded.

Native image commands accept `--max-width N` and `--max-height N` for extended geometry. The SDK uses `limits: { maxWidth, maxHeight }`. The default axis limit remains 65,535. [Geometry examples and evidence](FRAME_GEOMETRY_RESULTS.md)

To allow DNL to revise a positive SOF55 height, use `allowHeightRedefinition: true` in SDK decoding or `--allow-height-redefinition` in Native decode and inspection. This option stages the first scan under the same 32 MiB bound. The decoder uses the provisional SOF55 value if the first scan ends without DNL.

### Native CLI (`cmd/moonjls`)

- Single-component: `encode WIDTH HEIGHT BITS NEAR INPUT OUTPUT ...`, `encode-pgm NEAR INPUT OUTPUT [CHUNK] [preset flags]`
- Multi-component non-interleaved (`ILV=0`): `encode-planar WIDTH HEIGHT BITS COMPONENTS NEAR INPUT OUTPUT [raw-le|raw-be] [CHUNK] [--comp-ids LIST] [--scan-order LIST] [--scan-near LIST] [--maxval N] [preset flags]` (streams with `host_conversion_buffer_bytes=0`), `encode-pgms NEAR OUTPUT [--chunk N] [preset flags] IN1 [IN2 ...]`, `encode-ppm NEAR INPUT OUTPUT` (P6 RGB with explicit host planar conversion), `decode INPUT OUTPUT [raw-le|raw-be|pgm|ppm] [CHUNK]`, `decode-pgms [--chunk N] INPUT OUT1 [OUT2 ...]`, `inspect|verify INPUT [CHUNK] [--json]` (emits full `components`, `scans`, `markers`, and `eoiOffset`).

- Encoders accept `--pt N` for a common SOS point transform. `encode-planar` also accepts `--scan-pt LIST` in scan order, or one shared value for an interleaved scan. Netpbm input MAXVAL describes original sample storage. For nonzero Pt the coding MAXVAL defaults to the full SOF precision. Native decode accepts `raw32-le` and `raw32-be` for four-byte unsigned samples in codec row delivery order. Inspect with `moonjls inspect INPUT --json` to obtain the scan sequence and plane geometry. The existing one- or two-byte raw formats reject unrepresentable values. Netpbm output selects a header MAXVAL within the format limit.
- Interleaved encoding accepts `--ilv 1` or `--ilv 2` on `encode-planar`, `encode-pgms`, and `encode-ppm`. For regular `encode-planar` files, Native reads by byte offset with up to `min(CHUNK, 16384)` raw bytes of read-ahead per active plane. When that amount cannot hold two rows, the input scratch holds one component row and can use multiple reads. ILV=1 retains one integer component row and ILV=2 retains one interleaved integer row. The regular-file path verifies the input length and reports `input_mode=positional_regular`, zero `host_planar_buffer_bytes`, `host_raw_window_rows` and `input_read_calls`. Stdin and other nonregular inputs use the existing sequential path with one complete planar input. Interleaved PGM and PPM paths also use row buffers. [Capacity and timing](../reports/native-read-ahead-20261201/README.md)
- For that regular-file path, multirow input windows and `CHUNK` of at least 1 KiB enable output batching. `host_output_buffer_bytes` records up to `min(CHUNK, 65536)` additional bytes. `output_high_water` records the largest codec-produced fragment. The first image row and input-window boundaries flush to the writer. Successful completion follows input validation, EOI and the final awaited flush. A failed sink can retain a provisional prefix. [Write counts and failure tests](../reports/native-output-batch-20261201/README.md)
- `encode-planar ... --ilv 1|2 --input-policy spool` accepts stdin or a named FIFO. It stages the exact validated RAW bytes before producing JLS. `--max-input-bytes` and `--max-staging-bytes` default to 512 MiB each. `--staging-directory` chooses an existing parent directory, and `--input-timeout-ms` defaults to 300,000 ms per stalled connection or read. The default input policy retains the previous behavior. `input_mode=spooled_planar` reports disk bytes, the ingest buffer peak, read calls, and separate ingest/encode milliseconds. [Spool example and evidence](../reports/overnight-20261201/G1.md)

### Native mixed-scan configuration

`moonjls encode-scans CONFIG.json OUTPUT [CHUNK]` takes the `moonjls.encode-scans/1` schema. For example, prepare three files containing six 8-bit samples each and run the command with this `scans.json` from the same directory. The frame has one sample-interleaved scan followed by an independent point-transformed scan.

```json
{
  "schema": "moonjls.encode-scans/1",
  "width": 3,
  "height": 2,
  "bits": 8,
  "components": [
    { "id": 3, "path": "c3.raw" },
    { "id": 7, "path": "c7.raw" },
    { "id": 11, "path": "c11.raw" }
  ],
  "scans": [
    { "componentIds": [3, 7], "interleave": 2, "restartInterval": 1 },
    { "componentIds": [11], "interleave": 0, "pointTransform": 2 }
  ]
}
```

```sh
moonjls encode-scans scans.json mixed.jls 4096
moonjls inspect mixed.jls --json
moonjls decode mixed.jls mixed.u32le raw32-le 4096
```

`components` gives SOF order. Each input is a separate regular file with tight rows and exactly the sample count for its component geometry. Optional `hSampling` and `vSampling` default to `1`. `format` defaults to `raw-le` and also accepts `raw-be`. Precision determines the sample storage width. Paths resolve against the working directory.

`scans` gives SOS order. Each component appears once, and `componentIds` gives the active scan order. `near`, `pointTransform` and `restartInterval` default to zero. `preset` accepts `maxval`, `t1`, `t2`, `t3`, and `reset` using the core's zero-field defaults. `mappings.selectors` lists the table ID for each SOS component and `mappings.definitions` can install per-scan entries using `{ "id": 7, "entryBytes": 1, "path": "table.bin" }`. Top-level `deferHeight: true` emits DNL, and `tableStream` names an external C.4 table stream. Core validation applies to sampling, scan order, preset and mapping combinations. Unknown or duplicate JSON fields are rejected. Configuration size is capped at 1 MiB. An output file must be new. A later I/O failure can leave a partial file or stdout prefix and returns a nonzero exit.

### Streaming core calls

| Operation | Input and results |
| --- | --- |
| `encoder.step(input, offset, length, output, eof)` | Sample slice in `FixedArray[Int]`, writable `FixedArray[Byte]`. Returns `{ consumed, produced, status }`. Output begins at zero. |
| `decoder.step(bytes, offset, length, eof)` | Slice in `Bytes`. Returns `{ consumed, status }`. Query `frame()` and `row()` on `RowReady`. |
| `cancel()` | A subsequent step on an active stream returns `Failed(Cancelled)` with zero counts. |
| `workspace_bytes()` | Formula in [ARCHITECTURE.md](ARCHITECTURE.md). `pending_bytes()` on the encoder and `pending_bits()` on the decoder report occupied core buffers. |

| Status | Host action |
| --- | --- |
| `NeedInput` | Keep any suffix and obtain another block. Set `eof=true` on the last block or in a separate empty call. |
| `NeedOutput` | Take the produced bytes and supply space. With zero capacity this may have zero counts and a pending output queue. |
| `RowReady` | Handle the row. Encoder uses this as a progress event. Decoder returns a borrowed line that callers must treat as read-only and copy to retain. The next step acknowledges the event. |
| `Done` | Consume the returned counts. On decode, they end at EOI and leave any trailing bytes to the host. Repeated calls return `Done` with zero counts. |
| `Failed(error)` | Stop advancing. Output from earlier calls and any counts on this call describe provisional work. |

`eof=true` identifies the boundary at the end of the currently supplied slice. Retrying an unconsumed suffix preserves that flag. If no output room is available, wait for the sink instead of polling. The errors distinguish `InvalidData`, `UnsupportedFeature`, `ResourceLimit`, `Truncated`, `InvalidArgument`, and `Cancelled`.

## JS and Wasm GC

Run `node sdk/build.mjs` from the repository root. The ESM exports and adjacent `.d.mts` files are in `sdk/`. Loading is asynchronous. A `Core` creates synchronous, stateful sessions with `stage(chunk | null)` and `step()`. `null` is EOF. Each result reports counts and an owned output chunk, when present. Encode stages `Uint16Array` samples for all precisions and returns `Uint8Array` bytes. Decode stages `Uint8Array` bytes and returns `Uint16Array` rows by default. Use `sampleFormat: 'u32'` on a decoder session, `decodeStream`, `decodeImage` or `decodePlanarImage` to retain wide reconstruction in `Uint32Array`. Samples retain their original integer scale. The Node CLI accepts `decode --sample-format u32` and writes little-endian samples in delivery order.

```js
import { loadCore, decodeStream } from './sdk/index.mjs';

const core = await loadCore({ backend: 'wasm-gc' });
const result = await decodeStream(core, {
  inputChunkSize: 4096,
  read: async (maxBytes) => source.readAtMost(maxBytes), // Uint8Array or null
  onRow: async (row, y) => sink.write(y, row),
  trailing: 'reject',
});
console.log(result.frame, result.stats);
```

`encodeStream` pulls a source and awaits `onBytes`. `decodeStream` awaits `onRow` and optional `onScanComplete(scan, stats, structure)`; `row` events carry `rowMeta` (`scanIndex`, `componentIndex`, `componentId`, `rowIndex`, `near`, `preset`, `layout`, `stride`, `sampleBytes`, `endianness`). Whole-image multi-component helpers `encodePlanarImage`, `decodePlanarImage`, and `inspectStream` are documented in [index.d.mts](../sdk/index.d.mts). Decode's `trailing: 'allow'` reports consumption at EOI, while `'reject'` checks for a suffix and probes the source for EOF. Host and codec errors are surfaced as rejected promises with optional `error.location` (`scanIndex`, `componentId`, `marker`, `offset`). The marker field reports the observed code and uses 0 when the code is unknown. The byte offset is zero-based and identifies the last prefix after any FF fill, the offending byte when the prefix is missing, or the end-of-input position when the stream ends before a prefix.

## Worker protocol

`startWorker` in `sdk/worker-client.mjs` accepts the same options, a pull source, and `onEvent`. It returns `{ result, pause, resume, cancel }`. Options and events are typed in [worker-client.d.mts](../sdk/worker-client.d.mts). Worker decode flushes any pending row batch at scan boundaries and emits `scanComplete` with updated `structure`.

| Message | Ownership and sequencing |
| --- | --- |
| `start` | Main thread sends mode, limits, backend, chunk ceilings and encoder frame. One job per Worker. |
| `needInput(seq, maxElements)` → `input(seq, chunk)` | Worker asks for one block. Host supplies `Uint8Array`, `Uint16Array`, or `null` for EOF. A subview is copied before transfer to prevent retaining or detaching a larger buffer. Full, owned input buffers are transferred and detached from the sender. |
| `bytes`, `row`, `rows`, `progress` → `ack(seq)` | Worker waits for the sink promise before proceeding. Byte and row buffers transfer ownership to the host. Rows are `Uint16Array` by default or `Uint32Array` with `sampleFormat: 'u32'`. Events include frame fields, the zero-based component row index, and the storage width. A `rows` event carries `startIndex`, `count` and a `samples` view with exactly `count * stride` elements. |
| `pause`, `resume`, `cancel` | Pause stops new source reads and Worker requests at the next boundary. At most one already requested pull or event can be in flight. Cancel rejects the session. |
| `done`, `error` | Terminal frame/metrics or error code and message. The client terminates its Worker. |

Metrics expose rows, input and output units, consumed/produced totals, live and peak queue bytes, core and bridge payload, elapsed time, and first-row timing. A sink can block acknowledgements to impose backpressure. The demo's fixed preview and file download choices are host policy.

Worker decode batching is optional: `maxBatchBytes` is an integer in `0..1048576`, with `0` disabling batching. The first row is immediate; wider-than-budget rows remain atomic. This is a batch-buffer budget, not a total memory ceiling. `outputQueueBytes` reports the allocated batch or the full backing buffer of an unacknowledged output; short views can therefore have a smaller `byteLength`. `outputPeakBytes` additionally counts the source row while copying into a batch or when the previous component batch is held for ACK, remains monotonic across progress/data/terminal records, and is retained after `done` clears the live queue. These are explicit output payloads, not JavaScript heap or browser RSS. See [SDK ownership and metrics](../sdk/README.md).

## Physical raster exchange

The public MoonBit package ZSY2221/moon_jpegls/raster exposes Budget::new, physical_error, physical_value and recover_u16le. Give the budget decimal text to preserve exact boundary decisions across Native, JS and Wasm GC. The SDK's loaded core has createPhysicalBudget(maxval, scale, offset, epsilon), which returns near and exact physical values as strings. The dedicated CLI entry is moonjls physical-budget MAXVAL SCALE OFFSET EPSILON. It prints JSON with maxval, near and the exact physical error bound. For a larger known-height raster, the [independent streaming producer and recovery commands](../examples/raster-stream/README.md) use the public Budget and codec APIs with configurable file, pixel and temporary-disk limits.

Decoder stream statistics can include deferredHeightStage when a first scan requires height resolution. It reports only phases observed by the current driver. It becomes null after the last observed stage finishes. Known-height decoding keeps its ordinary row behavior. See [Raster exchange](RASTER_EXCHANGE.md) for the bounded sidecar format and the independent restore example.
## Native raster scan planning

`moonjls plan-raster-scans REQUEST.json` accepts an existing `moonjls.raster-exchange-request/v2` descriptor. It reads up to 16 KiB of regular metadata and emits `moonjls.raster-scan-plans/v1` JSON. The request's declared scans supply the optional manual alternative. The command reads metadata even when the plane paths are still unavailable.

Plans contain the shared geometry and SOF order, canonical IDs, selectors, interleave, exact NEAR, every limiting component, and physical bounds. Native and the SDK serialize the same MoonBit plans. The command supports the existing v2 profile of 2–4 unsigned components, H=V=1, Pt=0, and a common geometry, precision and MAXVAL. The separate comparison command measures actual sizes. [Usage and verification](../examples/raster-stream/README.md#compare-scan-candidates)
