diff --git a/README.md b/README.md index 0d30c62..ad0ac0d 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,10 @@ npm run dev ``` Open http://localhost:5173. Initial model preparation downloads pinned reference -checkpoints at build time (~300 MiB), validates their LFS SHA-256 hashes, and packs -**encoder and decoder tensors**. No Python/PyTorch is needed. The resulting four -bundles total ~104 MiB. Raw checkpoints remain in `.cache/`; model bundles and -WASM are generated, not committed. The manifest and dependency lockfiles are committed. +checkpoints at build time (~430 MiB), validates their LFS SHA-256 hashes, and packs +**encoder and decoder tensors**. No Python/PyTorch is needed. The resulting eight +bundles total ~322 MiB (four BOP at ~26 MiB each, four HOP at ~54 MiB each). Raw checkpoints remain in `.cache/`; model bundles and +WASM are generated, not committed. The manifests and dependency lockfiles are committed. `npm run models` is required for JPEG AI, not JPEG/AVIF/JPEG XL. Missing assets produce a visible error rather than simulated compression. `npm run build` refuses @@ -67,8 +67,13 @@ modifying or redistributing it. External library and model terms also apply. original file again, rather than repeatedly resizing an already reduced image. Size changes retain each codec's latest result and encode-time reference metadata. Only selecting a new source clears results. Rows show each result's dimensions so mixed sizes are clear. -- JPEG AI: all four BOP models, adjustable quantisation, actual target-bpp search. -- Four compact JPEG AI model cards. Selecting a model downloads it into Cache Storage; +- JPEG AI: BOP/HOP Operating point selector with a hover/focus/tap explanation. + BOP is the faster default; HOP uses higher-complexity transforms, aiming for better + compression at the cost of slower decoding and more memory. Both offer four models, + adjustable quantisation and actual target-bpp search within the selected operating point. + Changing point retains the last output until the next encode; its table row and + download filename identify the point actually encoded. There is still one result per codec. +- Four compact JPEG AI model cards for the selected operating point. Selecting a model downloads it into Cache Storage; each card has a Download/Remove action and cached-state color. Verification remains internal; there is no model file export/import or checksum display. - JPEG: quality, progressive mode and chroma subsampling (MozJPEG). @@ -130,7 +135,7 @@ src/codec.worker.ts orchestration; no UI-thread codec work crates/codec/src/lib.rs Rust JPEG AI WASM adapter + metrics and unit tests crates/codec/src/bin/ native encoder+decoder model packer scripts/ WASM/model preparation and source archive -public/models/manifest.json pinned weights and integrity metadata +public/models/manifest*.json pinned BOP/HOP weights and integrity metadata ``` The JPEG AI implementation is pinned to zenjpegai commit @@ -171,9 +176,11 @@ against `dist/` using Vite preview. It does not certify JPEG AI conformance. not silently resize it. Downscale selection is explicit. Browser decoding can allocate before the source-size check; not hardened against hostile decompression bombs. Use a smaller source on memory-constrained devices. -- JPEG AI is CPU-only BOP, advanced optional coding tools off. No WebGPU or hidden +- JPEG AI is CPU-only BOP/HOP, advanced optional coding tools off. No WebGPU or hidden server fallback. Modern browsers with WASM SIMD are required for this build. - JPEG AI's encode working-set cap is 3072 MiB (3 GiB), with the same decoder cap. + HOP preflight also covers a conservative synthesis bound plus retained models, and + pads the target-search model allowance rather than using BOP's smaller estimate. Jobs estimated above 1536 MiB pause for explicit Continue encoding / Cancel confirmation before loading model weights or encoding. The estimate is not a measured whole-tab peak and excludes browser copies, model cache storage and other tabs; even a confirmed job @@ -182,10 +189,10 @@ against `dist/` using Vite preview. It does not certify JPEG AI conformance. not held in another full-resolution canvas. - JPEG AI target-bpp search can take minutes and uses all four model bundles. Requested bpp is a target, not a guarantee; header overhead dominates tiny images. -- File-size reduction is `(1 - encodedBytes / uploadedBytes) * 100`, excluding model - downloads. A negative reduction is displayed as a percentage larger. If the input - is resized, this measures the full workflow, not codec-only savings. Quality - metrics always compare normalized working pixels against decoded output pixels. +- File-size reduction is `(1 - encodedBytes / referenceBytes) * 100`, excluding model + downloads. The reference is the uploaded file at full resolution, or an actual PNG + of the downscaled input. A negative reduction is displayed as a percentage larger. + Quality metrics always compare normalized encode-time input pixels against decoded output pixels. Settings are snapshotted per result; quality scales differ across formats. - SSIM: Rec.709 luma, non-overlapping 8x8 windows (including smaller edges), population variance, K1=.01/K2=.03/L=255. Not MS-SSIM. PSNR uses RGB MSE, with `null` in JSON diff --git a/crates/codec/src/bin/pack-models.rs b/crates/codec/src/bin/pack-models.rs index 6c21e5f..e234967 100644 --- a/crates/codec/src/bin/pack-models.rs +++ b/crates/codec/src/bin/pack-models.rs @@ -8,19 +8,25 @@ use zenjpegai::{ }; fn main() -> Result<(), Box> { let args: Vec<_> = env::args().collect(); - if args.len() != 5 { + if args.len() != 6 { return Err( - "usage: pack-models ".into(), + "usage: pack-models " + .into(), ); } let dir = PathBuf::from(&args[1]); let id: usize = args[2].parse()?; + let op = match args[5].as_str() { + "bop" => OperatingPoint::Bop, + "hop" => OperatingPoint::Hop, + _ => return Err("operating point must be bop or hop".into()), + }; let mut source = ModelBundle::new(); for ccs in 0..2 { for path in [ model::common_path(id, ccs)?, - model::analysis_path(id, ccs, OperatingPoint::Bop)?, - model::synthesis_path(id, ccs, OperatingPoint::Bop)?, + model::analysis_path(id, ccs, op)?, + model::synthesis_path(id, ccs, op)?, ] { source.insert(path.clone(), fs::read(dir.join(path))?); } @@ -42,12 +48,12 @@ fn main() -> Result<(), Box> { Ok(()) })?; } - model::load_analysis_primary(&recorder, id, OperatingPoint::Bop, &eng)?; - model::load_analysis_secondary(&recorder, id, OperatingPoint::Bop, &eng)?; - model::load_synthesis_primary(&recorder, id, OperatingPoint::Bop, &eng)?; - model::load_synthesis_secondary(&recorder, id, OperatingPoint::Bop, &eng)?; + model::load_analysis_primary(&recorder, id, op, &eng)?; + model::load_analysis_secondary(&recorder, id, op, &eng)?; + model::load_synthesis_primary(&recorder, id, op, &eng)?; + model::load_synthesis_secondary(&recorder, id, op, &eng)?; let bytes = recorder.pack(&fs::read_to_string(&args[3])?)?; fs::write(&args[4], &bytes)?; - println!("model {id}: {} bytes", bytes.len()); + println!("{op:?} model {id}: {} bytes", bytes.len()); Ok(()) } diff --git a/crates/codec/src/lib.rs b/crates/codec/src/lib.rs index a077d29..68b635e 100644 --- a/crates/codec/src/lib.rs +++ b/crates/codec/src/lib.rs @@ -35,6 +35,7 @@ fn error(e: impl std::fmt::Debug) -> JsError { #[wasm_bindgen] pub struct JpegAi { + op: OperatingPoint, models: Models, encoder: Encoder, decoder: Decoder, @@ -43,24 +44,28 @@ pub struct JpegAi { #[wasm_bindgen] impl JpegAi { #[wasm_bindgen(constructor)] - pub fn new() -> Self { + pub fn new(operating_point: &str) -> Result { + let op = parse_operating_point(operating_point).map_err(JsError::new)?; let models = Models::default(); // One CPU worker, SIMD when compiled with +simd128. No WebGPU or server fallback. let engine = Engine::with(Tier::detect(), false); zenjpegai::nn::fast::set_pool_limit(32 << 20); - Self { + Ok(Self { + op, encoder: Encoder::with_source(Box::new(models.clone()), engine).limits( EncodeLimits::default() .with_max_pixels(MAX_PIXELS as u64) .with_max_memory(MEMORY_LIMIT), ), - decoder: Decoder::with_source(Box::new(models.clone()), engine).limits( - zenjpegai::Limits::default() - .with_max_pixels(MAX_PIXELS as u64) - .with_max_memory(MEMORY_LIMIT), - ), + decoder: Decoder::with_source(Box::new(models.clone()), engine) + .operating_point(Some(op)) + .limits( + zenjpegai::Limits::default() + .with_max_pixels(MAX_PIXELS as u64) + .with_max_memory(MEMORY_LIMIT), + ), models, - } + }) } #[wasm_bindgen(js_name = addModels)] pub fn add_models(&self, bundle: Vec) -> Result { @@ -68,7 +73,7 @@ impl JpegAi { store.add(bundle).map_err(error)?; Ok(store.notice().to_owned()) } - /// Fixed BOP model with adjustable quantisation, or true target-bpp search across models. + /// Selected BOP/HOP model with quantisation, or target-bpp search within that point. pub fn encode( &self, rgba: &[u8], @@ -97,7 +102,7 @@ impl JpegAi { }; let params = EncodeParams { model_id: model, - op: OperatingPoint::Bop, + op: self.op, beta_displacement_log: [displacement; 2], ..Default::default() }; @@ -109,7 +114,14 @@ impl JpegAi { self.encoder.encode(src, params) }; self.encoder.release_buffers(); - result.map_err(error) + let bytes = result.map_err(error)?; + let headers = self.decoder.read_headers(&bytes).map_err(error)?; + if headers.picture.synthesis_transforms.first() != Some(&self.op) { + return Err(JsError::new( + "encoded JPEG AI operating point does not match", + )); + } + Ok(bytes) } pub fn decode(&self, stream: &[u8]) -> Result, JsError> { let image = self.decoder.decode(stream).map_err(error)?; @@ -123,22 +135,43 @@ impl JpegAi { } #[wasm_bindgen(js_name = estimateMemory)] pub fn estimate_memory(&self, width: u32, height: u32, rate_matched: bool) -> f64 { - self.encoder - .estimate_memory( - width.into(), - height.into(), - OperatingPoint::Bop, - rate_matched, - ) - .live_bytes as f64 + estimate_job_memory(width.into(), height.into(), self.op, rate_matched) as f64 } } impl Default for JpegAi { fn default() -> Self { - Self::new() + Self::new("bop").expect("BOP is a supported operating point") } } +fn parse_operating_point(value: &str) -> Result { + match value { + "bop" => Ok(OperatingPoint::Bop), + "hop" => Ok(OperatingPoint::Hop), + _ => Err("JPEG AI operating point must be bop or hop"), + } +} + +fn estimate_job_memory(width: u64, height: u64, op: OperatingPoint, rate_matched: bool) -> u64 { + let encode = + zenjpegai::encoder::estimate_encode_memory(width, height, op, rate_matched).live_bytes; + if op != OperatingPoint::Hop { + return encode; + } + // HOP synthesis can peak above analysis. The pinned encoder uses <=1024² synthesis + // tiles, decoded sequentially. Match the upstream decoder's 970 B/tile-pixel and + // 20 B/picture-pixel bound, with 128 MiB/model for retained bundles/encoder networks. + let retained = (if rate_matched { 4 } else { 1 }) * (128 << 20); + let decode = (44u64 << 20) + .saturating_add(20u64.saturating_mul(width.saturating_mul(height))) + .saturating_add(970 * width.min(1024) * height.min(1024)) + .saturating_add(retained); + // Upstream's target-search model allowance is calibrated for BOP. Pad HOP's + // three extra model sets from 28 to 64 MiB each. + let encode = encode.saturating_add(if rate_matched { 3 * (36 << 20) } else { 0 }); + encode.max(decode) +} + fn validate(rgba: &[u8], width: usize, height: usize, limit: usize) -> Result<(), &'static str> { let pixels = width.checked_mul(height).ok_or("dimension overflow")?; if pixels == 0 || pixels > limit || pixels.checked_mul(4) != Some(rgba.len()) { @@ -261,6 +294,20 @@ mod tests { assert_eq!(MEMORY_LIMIT, 3072 << 20); } #[test] + fn operating_points_and_hop_memory_are_explicit() { + assert_eq!(parse_operating_point("bop"), Ok(OperatingPoint::Bop)); + assert_eq!(parse_operating_point("hop"), Ok(OperatingPoint::Hop)); + assert!(parse_operating_point("sop").is_err()); + let bop = estimate_job_memory(1024, 1024, OperatingPoint::Bop, false); + let hop = estimate_job_memory(1024, 1024, OperatingPoint::Hop, false); + let analysis = + zenjpegai::encoder::estimate_encode_memory(1024, 1024, OperatingPoint::Hop, false); + assert!(hop > bop && hop > analysis.live_bytes); + assert!(estimate_job_memory(2048, 2048, OperatingPoint::Hop, true) > 1536 << 20); + assert!(estimate_job_memory(2048, 2048, OperatingPoint::Hop, true) <= MEMORY_LIMIT); + assert!(estimate_job_memory(6000, 4000, OperatingPoint::Hop, false) > MEMORY_LIMIT); + } + #[test] fn known_error() { let a = vec![0; 8 * 8 * 4]; let b = vec![10; 8 * 8 * 4]; diff --git a/public/legal/index.html b/public/legal/index.html index 14f657f..592a8c6 100644 --- a/public/legal/index.html +++ b/public/legal/index.html @@ -13,8 +13,8 @@

Image compression demo is a static, client-side compression demonstration. Your image is read locally; no upload endpoint, external analytics, remote inference, or third-party fonts are used. Encoding, output decoding and quality metrics run in WebAssembly on your CPU. The browser imports images and prepares 8-bit sRGB pixels using its canvas APIs.

JPEG AI is experimental

JPEG AI is the learned image compression standard ISO/IEC 6048-1. This application uses zenjpegai, pinned to commit 1192fca6b6c2fdc4dcf29a6c8064c53a987caf59. This is not a certification of conformance. The .jai extension is a project convention, not a claim of a registered media type or native browser support.

-

All four trained BOP models are available as compact selectable cards in the JPEG AI tab. Weights are separate from the compressed image. One encoder/decoder bundle is about 26 MiB; target-bitrate search needs about 104 MiB. Downloads are verified with SHA-256 before use and may be cached in your browser. Selecting a model downloads its weights into the browser cache; each card supports downloading or removal. There is no model file export or import. Browser storage may be evicted.

-

The initial version uses only the BOP profile with advanced coding tools off. It supports fixed-model quantisation and target-bpp search. It does not provide HDR, animation, alpha preservation, arbitrary model files, WebGPU or a server fallback.

+

All four trained models for each of BOP and HOP are available as compact selectable cards in the JPEG AI tab. The Operating point selector switches between BOP (faster, the default) and HOP (higher complexity), with an explanatory tooltip. Weights are separate from the compressed image. One encoder/decoder bundle is about 26 MiB for BOP or 54 MiB for HOP; target-bitrate search downloads all four models for the selected point, about 104 MiB or 218 MiB respectively. BOP and HOP use separate verified cache entries. Downloads are verified with SHA-256 before use and may be cached in your browser. Selecting a model downloads its weights into the browser cache; each card supports downloading or removal. There is no model file export or import. Browser storage may be evicted.

+

Both BOP and HOP are supported with advanced optional coding tools off. HOP aims for better compression with slower decoding and higher memory use; it is not guaranteed to produce smaller output for every image or setting. Both points support fixed-model quantisation and target-bpp search. HOP preflight includes a conservative synthesis-memory bound and retained model storage, not just the encoder estimate. It does not provide HDR, animation, alpha preservation, arbitrary model files, WebGPU or a server fallback.

Software and model licenses

This application's corresponding source is provided under AGPL-3.0. zenjpegai is AGPL-3.0 or commercially licensed by its author. This build uses the AGPL option. Download this build's source and build scripts. Dependency sources are pinned in the included lockfiles; build instructions are in README.md.

The JPEG AI reference weights derive from the ITU/ISO/IEC reference software, pinned to commit b9e573fef1dd90408270da23aae678c823f15525. The upstream BSD license and notices are embedded in every packed model bundle and reproduced here.

diff --git a/public/models/manifest-hop.json b/public/models/manifest-hop.json new file mode 100644 index 0000000..e12014a --- /dev/null +++ b/public/models/manifest-hop.json @@ -0,0 +1,30 @@ +{ + "revision": "b9e573fef1dd90408270da23aae678c823f15525", + "operatingPoint": "hop", + "models": [ + { + "id": 0, + "file": "hop-m0.zjb", + "bytes": 57069952, + "sha256": "097a7f3529627238e86bc2c5fb7e779c785c928415fc9f82fde72d750a758b40" + }, + { + "id": 1, + "file": "hop-m1.zjb", + "bytes": 57069952, + "sha256": "a81991b5b3142c4c63da236493c544c6792bb10767c37c4ca549e5e9622df57c" + }, + { + "id": 2, + "file": "hop-m2.zjb", + "bytes": 57069952, + "sha256": "7308ba00cd9f8a573cc8a5ace51a164fa448feae4089ba6ab75928a01de6a9af" + }, + { + "id": 3, + "file": "hop-m3.zjb", + "bytes": 57069952, + "sha256": "06862fa719f1a5ce7494674368c6cafa9a9b0f61f73888e951ce91a896c2b6c6" + } + ] +} diff --git a/scripts/package-source.mjs b/scripts/package-source.mjs index 395c228..a4d6b16 100644 --- a/scripts/package-source.mjs +++ b/scripts/package-source.mjs @@ -3,12 +3,17 @@ import { readFile } from 'node:fs/promises'; import { createHash } from 'node:crypto'; // A production build must not silently omit the main codec's weights. -const manifest = JSON.parse(await readFile('public/models/manifest.json', 'utf8')); -if (manifest.models?.length !== 4) throw new Error('Run npm run models before building.'); -for (const model of manifest.models) { - const bytes = await readFile(`public/models/${model.file}`); - if (bytes.length !== model.bytes || createHash('sha256').update(bytes).digest('hex') !== model.sha256) { - throw new Error(`Model ${model.file} missing or corrupt. Run npm run models.`); +for (const [op, file] of [['bop', 'manifest.json'], ['hop', 'manifest-hop.json']]) { + const manifest = JSON.parse(await readFile(`public/models/${file}`, 'utf8')); + if (manifest.operatingPoint !== op || !Array.isArray(manifest.models) || manifest.models.length !== 4 || + manifest.models.some((model, id) => model.id !== id || model.file !== `${op}-m${id}.zjb`)) { + throw new Error(`Invalid or incomplete ${op.toUpperCase()} manifest. Run npm run models before building.`); + } + for (const model of manifest.models) { + const bytes = await readFile(`public/models/${model.file}`); + if (bytes.length !== model.bytes || createHash('sha256').update(bytes).digest('hex') !== model.sha256) { + throw new Error(`Model ${model.file} missing or corrupt. Run npm run models.`); + } } } const args = [ @@ -16,7 +21,7 @@ const args = [ '--exclude=crates/codec/target', '--exclude=src/wasm', 'src', 'crates', 'scripts', 'tests', 'deploy', 'public/legal', - 'public/models/manifest.json', 'index.html', 'package.json', 'package-lock.json', + 'public/models/manifest.json', 'public/models/manifest-hop.json', 'index.html', 'package.json', 'package-lock.json', 'tsconfig.json', 'vite.config.ts', 'playwright.config.ts', 'Dockerfile', '.dockerignore', '.gitignore', 'LICENSE', 'README.md', ]; diff --git a/scripts/prepare-models.mjs b/scripts/prepare-models.mjs index 099626e..a1727ea 100644 --- a/scripts/prepare-models.mjs +++ b/scripts/prepare-models.mjs @@ -21,33 +21,35 @@ if (run('git', ['-C', cache, 'rev-parse', 'HEAD'], true).trim() !== revision) { } run('cargo', ['build', '--release', '--manifest-path', 'crates/codec/Cargo.toml', '--features', 'model-packer', '--bin', 'pack-models']); const betas = ['0.002', '0.012', '0.075', '0.5']; -const models = []; -for (let id = 0; id < 4; id++) { - const beta = betas[id]; - const paths = ['Y', 'UV'].flatMap(c => [`VM_common_int/${c}_${beta}.pth`, `VM_bop/encoder_${c}_${beta}.pth`, `VM_bop/decoder_${c}_${beta}.pth`]); - await Promise.all(paths.map(async path => { - const pointer = run('git', ['-C', cache, 'show', `${revision}:models/${path}`], true); - const sha = /oid sha256:([a-f0-9]{64})/.exec(pointer)?.[1]; - const size = Number(/size (\d+)/.exec(pointer)?.[1]); - if (!sha || !size) throw new Error(`Not a pinned LFS pointer: ${path}`); - const dest = `${cache}/models/${path}`; - if (existsSync(dest)) { const b = await readFile(dest); if (b.length === size && hash(b) === sha) return; } - console.log(`Downloading verified weights: ${path} (${(size/1048576).toFixed(1)} MiB)`); - const url = `https://gitlab.com/wg1/jpeg-ai/jpeg-ai-reference-software/-/raw/${revision}/models/${path}`; - let bytes; - for (let attempt = 0; attempt < 3; attempt++) { - const response = await fetch(url, { signal: AbortSignal.timeout(180_000) }); - if (response.ok) { bytes = Buffer.from(await response.arrayBuffer()); if (bytes.length === size && hash(bytes) === sha) break; } - bytes = undefined; - } - if (!bytes) throw new Error(`Download or SHA-256 verification failed: ${path}`); - await mkdir(dest.slice(0, dest.lastIndexOf('/')), { recursive: true }); - await writeFile(`${dest}.tmp`, bytes); await rename(`${dest}.tmp`, dest); - })); - const file = `bop-m${id}.zjb`; - run('crates/codec/target/release/pack-models', [`${cache}/models`, String(id), 'public/legal/jpeg-ai-reference-LICENSE.txt', `${output}/${file}`]); - const bytes = await readFile(`${output}/${file}`); - models.push({ id, file, bytes: bytes.length, sha256: hash(bytes) }); +for (const op of ['bop', 'hop']) { + const models = []; + for (let id = 0; id < 4; id++) { + const beta = betas[id]; + const paths = ['Y', 'UV'].flatMap(c => [`VM_common_int/${c}_${beta}.pth`, `VM_${op}/encoder_${c}_${beta}.pth`, `VM_${op}/decoder_${c}_${beta}.pth`]); + await Promise.all(paths.map(async path => { + const pointer = run('git', ['-C', cache, 'show', `${revision}:models/${path}`], true); + const sha = /oid sha256:([a-f0-9]{64})/.exec(pointer)?.[1]; + const size = Number(/size (\d+)/.exec(pointer)?.[1]); + if (!sha || !size) throw new Error(`Not a pinned LFS pointer: ${path}`); + const dest = `${cache}/models/${path}`; + if (existsSync(dest)) { const b = await readFile(dest); if (b.length === size && hash(b) === sha) return; } + console.log(`Downloading verified weights: ${path} (${(size/1048576).toFixed(1)} MiB)`); + const url = `https://gitlab.com/wg1/jpeg-ai/jpeg-ai-reference-software/-/raw/${revision}/models/${path}`; + let bytes; + for (let attempt = 0; attempt < 3; attempt++) { + const response = await fetch(url, { signal: AbortSignal.timeout(180_000) }); + if (response.ok) { bytes = Buffer.from(await response.arrayBuffer()); if (bytes.length === size && hash(bytes) === sha) break; } + bytes = undefined; + } + if (!bytes) throw new Error(`Download or SHA-256 verification failed: ${path}`); + await mkdir(dest.slice(0, dest.lastIndexOf('/')), { recursive: true }); + await writeFile(`${dest}.tmp`, bytes); await rename(`${dest}.tmp`, dest); + })); + const file = `${op}-m${id}.zjb`; + run('crates/codec/target/release/pack-models', [`${cache}/models`, String(id), 'public/legal/jpeg-ai-reference-LICENSE.txt', `${output}/${file}`, op]); + const bytes = await readFile(`${output}/${file}`); + models.push({ id, file, bytes: bytes.length, sha256: hash(bytes) }); + } + await writeFile(`${output}/${op === 'bop' ? 'manifest' : 'manifest-hop'}.json`, JSON.stringify({ revision, operatingPoint: op, models }, null, 2) + '\n'); } -await writeFile(`${output}/manifest.json`, JSON.stringify({ revision, operatingPoint: 'bop', models }, null, 2) + '\n'); console.log('All encoder + decoder bundles ready. Serve public/models with the site.'); diff --git a/src/codec.worker.ts b/src/codec.worker.ts index 62f792b..18bc0fc 100644 --- a/src/codec.worker.ts +++ b/src/codec.worker.ts @@ -29,7 +29,8 @@ self.onmessage = async ({ data }: MessageEvent) => { let encodeMs: number, decodeMs: number, startupMs: number; let confirmationWaitMs = 0; if (s.format === 'jpegai') { - const ai = new JpegAi(); + const ai = new JpegAi(s.operatingPoint); + const point = s.operatingPoint.toUpperCase(); estimatedMemory = ai.estimateMemory(width, height, s.rateMode === 'target'); if (estimatedMemory > JPEG_AI_MEMORY_LIMIT) throw new Error('Estimated JPEG AI working memory exceeds the 3 GiB cap. Choose a smaller size under Downscale image.'); if (estimatedMemory > JPEG_AI_CONFIRM_THRESHOLD) { @@ -41,22 +42,22 @@ self.onmessage = async ({ data }: MessageEvent) => { }); confirmationWaitMs = performance.now() - waiting; } - const manifest = await loadManifest(); + const manifest = await loadManifest(s.operatingPoint); const entries = s.rateMode === 'target' ? manifest.models : manifest.models.filter(m => m.id === s.model); if (entries.length !== (s.rateMode === 'target' ? 4 : 1)) throw new Error('Incomplete JPEG AI model manifest'); for (const entry of entries) { - progress(`Loading JPEG AI model ${entry.id + 1} · ${(entry.bytes / 1048576).toFixed(1)} MiB (cached after first use)…`); + progress(`Loading JPEG AI ${point} model ${entry.id + 1} · ${(entry.bytes / 1048576).toFixed(1)} MiB (cached after first use)…`); const { bytes } = await getModel(entry, (received, total) => { progress(`Loading model ${entry.id + 1} · ${Math.round(received / total * 100)}% (download or local cache)…`); }); notices.push(ai.addModels(bytes)); modelSize += bytes.length; } startupMs = performance.now() - start - confirmationWaitMs; - progress(s.rateMode === 'target' ? 'Searching all four models for the target bitrate. This may take several minutes…' : 'Encoding JPEG AI on your CPU…'); + progress(s.rateMode === 'target' ? `Searching all four ${point} models for the target bitrate. This may take several minutes…` : `Encoding JPEG AI ${point} on your CPU…`); let tick = performance.now(); encoded = new Uint8Array(ai.encode(new Uint8Array(pixels.buffer), width, height, s.model, s.displacement, s.rateMode === 'target' ? s.targetBpp : 0)); encodeMs = performance.now() - tick; - progress('Decoding the actual JPEG AI bitstream…'); + progress(`Decoding the actual JPEG AI ${point} bitstream…`); tick = performance.now(); decoded = new Uint8ClampedArray(ai.decode(encoded)); decodeMs = performance.now() - tick; diff --git a/src/components/CodecControls.vue b/src/components/CodecControls.vue index a15f3a2..64dedfb 100644 --- a/src/components/CodecControls.vue +++ b/src/components/CodecControls.vue @@ -1,5 +1,6 @@