@su-engineering/heic 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/CONTRIBUTING.md +7 -1
- package/README.md +25 -5
- package/dist/heic.global.js +1 -1
- package/dist/heic.global.js.map +1 -1
- package/dist/index.d.ts +9 -3
- package/dist/index.js +32 -1
- package/dist/index.js.map +1 -1
- package/dist/{types-Bv9KPnri.d.ts → types-nCqKJJpp.d.ts} +11 -1
- package/dist/wasm.d.ts +2 -2
- package/dist/wasm.js +52 -44
- package/dist/wasm.js.map +1 -1
- package/docs/api.md +9 -1
- package/docs/benchmarks.md +66 -0
- package/docs/releasing.md +40 -25
- package/package.json +11 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- f71e02e: Add JPEG/PNG conversion with decode metadata and automatic bitmap cleanup. Require libheif-js 1.23.2 or newer for the optional fallback, release libheif contexts after decoding, and add a reproducible browser benchmark against heic-to.
|
|
8
|
+
|
|
9
|
+
## 0.1.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 395b783: Document the initial public release and the automated Changesets release process with npm trusted publishing.
|
|
14
|
+
|
|
3
15
|
## 0.1.0
|
|
4
16
|
|
|
5
17
|
Initial public release.
|
package/CONTRIBUTING.md
CHANGED
|
@@ -17,7 +17,7 @@ pnpm test:package
|
|
|
17
17
|
pnpm test:unit
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
A source checkout can be used by building it and importing `dist/index.js`, or by installing a tarball created with `pnpm pack --pack-destination /tmp/heic-pack`. The WASM entry point is `dist/wasm.js`; its optional peer dependency must be available in the consuming project.
|
|
21
21
|
|
|
22
22
|
## Repository map
|
|
23
23
|
|
|
@@ -81,3 +81,9 @@ Do not commit `dist/`, browser reports, `node_modules/`, or the private photo co
|
|
|
81
81
|
## Community expectations
|
|
82
82
|
|
|
83
83
|
Be respectful, explain disagreements with evidence, and focus reviews on the work. Do not harass contributors or disclose private information. Report conduct concerns privately to hello@su.engineering. Use the [security policy](SECURITY.md) for vulnerabilities.
|
|
84
|
+
|
|
85
|
+
## Releases
|
|
86
|
+
|
|
87
|
+
Package changes use Changesets. Once merged into `master`, the release workflow
|
|
88
|
+
creates a version/changelog PR. Merging that PR publishes its new version after
|
|
89
|
+
validation using npm trusted publishing. See [the release guide](docs/releasing.md).
|
package/README.md
CHANGED
|
@@ -15,17 +15,17 @@ HEIC uploads need not force every visitor to download a software codec. This Typ
|
|
|
15
15
|
|
|
16
16
|
The project is at **0.1.0**. Test it with representative files and target devices before production use. The repository is named `heic-web`; the npm package name is `@su-engineering/heic`.
|
|
17
17
|
|
|
18
|
-
[API reference](docs/api.md) · [Compatibility and limitations](docs/compatibility.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md)
|
|
18
|
+
[API reference](docs/api.md) · [Compatibility and limitations](docs/compatibility.md) · [Benchmarks](docs/benchmarks.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) · [Release process](docs/releasing.md)
|
|
19
19
|
|
|
20
20
|
## Installation
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
Install the package:
|
|
23
23
|
|
|
24
24
|
```sh
|
|
25
25
|
npm install @su-engineering/heic
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
For a checkout
|
|
28
|
+
For a source checkout, see [local development](CONTRIBUTING.md#local-development). Decoding runs in a browser or browser worker. Node.js can run the container parser, but this package does not provide a Node.js pixel decoder.
|
|
29
29
|
|
|
30
30
|
## Quick start
|
|
31
31
|
|
|
@@ -83,7 +83,26 @@ const decoded = await decodeHeic(file, {
|
|
|
83
83
|
|
|
84
84
|
The separate entry point loads `libheif-js/wasm-bundle.js` on its first decode. A bundler supporting dynamic imports can keep the adapter and codec out of the initial chunk. Check your bundler's output: asset splitting and download sizes depend on your toolchain and the libheif version.
|
|
85
85
|
|
|
86
|
-
For self-hosted assets, custom builds, or direct browser imports, use [`createWasmAdapter`](docs/api.md#wasm-adapters). The core library is MIT licensed; optional libheif distributions have [their own licenses](docs/compatibility.md#third-party-code).
|
|
86
|
+
The optional peer requires `libheif-js` 1.23.2 or newer within major version 1. For self-hosted assets, custom builds, or direct browser imports, use [`createWasmAdapter`](docs/api.md#wasm-adapters). The core library is MIT licensed; optional libheif distributions have [their own licenses](docs/compatibility.md#third-party-code).
|
|
87
|
+
|
|
88
|
+
## Convert to JPEG or PNG
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { convertHeic } from '@su-engineering/heic';
|
|
92
|
+
|
|
93
|
+
const converted = await convertHeic(file, {
|
|
94
|
+
type: 'image/jpeg', // Or 'image/png'; JPEG is the default.
|
|
95
|
+
quality: 0.92, // 0–1 for JPEG; ignored for PNG.
|
|
96
|
+
maxDimension: 2048,
|
|
97
|
+
wasmLoader: async () => (await import('@su-engineering/heic/wasm')).wasmDecoder,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const form = new FormData();
|
|
101
|
+
form.append('image', converted.blob, 'photo.jpg');
|
|
102
|
+
console.log(converted.width, converted.height, converted.strategy, converted.warnings);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Install `libheif-js` for the fallback in this example. Omit `wasmLoader` if you only want browser decoding. Conversion runs in browsers and workers, releases its own bitmap, and does not copy source EXIF into the output. Browser encoders determine the final color and compression behavior.
|
|
87
106
|
|
|
88
107
|
## Choose by capability
|
|
89
108
|
|
|
@@ -103,6 +122,7 @@ HEVC support depends on the browser, OS, installed codecs, hardware, and file pr
|
|
|
103
122
|
| Export | Purpose |
|
|
104
123
|
| --- | --- |
|
|
105
124
|
| `decodeHeic(input, options?)` | Decode a `Blob`, `File`, `ArrayBuffer`, or `Uint8Array` to an `ImageBitmap` plus metadata. |
|
|
125
|
+
| `convertHeic(input, options?)` | Encode the primary image to a JPEG/PNG `Blob` plus decode metadata; releases its bitmap automatically. |
|
|
106
126
|
| `isHeic(input)` | Inspect up to the first 64 KiB for HEIC identification and coding hints. |
|
|
107
127
|
| `probeSupport()` | Probe native HEIC decoding and accepted WebCodecs HEVC configurations. |
|
|
108
128
|
| `parseHeif(buffer)` | Inspect container items, properties, references, and locations without decoding pixels. |
|
|
@@ -113,7 +133,7 @@ Common decode options are `strategy`, `maxDimension`, `colorSpace`, `signal`, an
|
|
|
113
133
|
|
|
114
134
|
## Scope and limits
|
|
115
135
|
|
|
116
|
-
This library returns pixels
|
|
136
|
+
This library returns pixels or a JPEG/PNG conversion of the primary HEVC image. It does not encode HEIC, supply an upload UI, preserve EXIF in the output, or decode AVIF, animation, or Live Photo video. Recognized alpha, depth, and HDR gain-map auxiliary items produce warnings; warning coverage is not exhaustive.
|
|
117
137
|
|
|
118
138
|
`maxDimension` reduces the returned bitmap size. **It does not cap peak decode memory:** decoding and compositing may still allocate the full-resolution image. Apply file-size limits, bound concurrent decodes, and use workers for large or untrusted uploads.
|
|
119
139
|
|
package/dist/heic.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var HeicDecoder=(()=>{var re=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var Me=(t,e)=>{for(var r in e)re(t,r,{get:e[r],enumerable:!0})},Ne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Re(e))!Ue.call(t,o)&&o!==r&&re(t,o,{get:()=>e[o],enumerable:!(n=$e(e,o))||n.enumerable});return t};var ke=t=>Ne(re({},"__esModule",{value:!0}),t);var St={};Me(St,{HeicAbortError:()=>I,HeicDecodeError:()=>w,HeicError:()=>D,HeicParseError:()=>d,HeicUnsupportedError:()=>x,decodeHeic:()=>Pt,findProperty:()=>C,getRegisteredAdapter:()=>Bt,hvccToAnnexBPrologue:()=>j,hvccToCodecString:()=>U,isHeic:()=>Ct,lengthPrefixedToAnnexB:()=>q,parseGridPayload:()=>ne,parseHeif:()=>N,parseHvcC:()=>V,planDecode:()=>Z,probeSupport:()=>Te,propertiesForItem:()=>T,readGrid:()=>Y,readItemData:()=>k,registerDecoderAdapter:()=>Tt});function X(t){return new Blob([t],{type:"image/heic"})}var D=class extends Error{context;constructor(e,r={},n){let o=Fe(r);super(o?`${e} (${o})`:e,n),this.name="HeicError",this.context=r}},d=class extends D{constructor(e,r={},n){super(e,r,n),this.name="HeicParseError"}},x=class extends D{attempts;constructor(e,r=[],n={},o){let i=r.map(s=>`${s.strategy}: ${s.reason}`).join("; ");super(i?`${e} [${i}]`:e,n,o),this.name="HeicUnsupportedError",this.attempts=r}},w=class extends D{constructor(e,r={},n){super(e,r,n),this.name="HeicDecodeError"}},I=class extends D{constructor(e="Decode aborted",r={},n){super(e,r,n),this.name="HeicAbortError"}};function Fe(t){let e=[];for(let[r,n]of Object.entries(t))n!==void 0&&e.push(`${r}=${n}`);return e.join(" ")}function S(t,e){if(typeof OffscreenCanvas>"u")throw new w("OffscreenCanvas is not available; this environment cannot composite",{});return new OffscreenCanvas(t,e)}function A(t){if(t?.aborted)throw new I}var pe=!1;async function fe(t,e,r){if(typeof createImageBitmap>"u")return{status:"unsupported",reason:"createImageBitmap is not available"};if(pe)return{status:"unsupported",reason:"this browser has no HEIC image decoder"};A(r);let n;try{n=await createImageBitmap(t)}catch{return pe=!0,{status:"unsupported",reason:"createImageBitmap rejected the file"}}if(A(r),!Le(n,e)){let o=`${n.width}x${n.height}`;return n.close(),{status:"wrong-image",reason:`returned ${o}, expected ${e.displayWidth}x${e.displayHeight}`}}return{status:"ok",bitmap:n}}function Le(t,e){let{displayWidth:r,displayHeight:n}=e,o=t.width===r&&t.height===n,i=t.width===n&&t.height===r;return o||i}async function ue(){if(typeof createImageBitmap>"u")return!1;try{let t=_e(ze),e=await createImageBitmap(X(t)),r=e.width===Ge&&e.height===We;return e.close(),r}catch{return!1}}function _e(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Ge=2,We=2,ze="AAAAHGZ0eXBoZWljAAAAAG1pZjFoZWljbWlhZgAAAXxtZXRhAAAAAAAAACFoZGxyAAAAAAAAAABwaWN0AAAAAAAAAAAAAAAAAAAAACJpbG9jAAAAAERAAAEAAQAAAAABoAABAAAAAAAAADcAAAAjaWluZgAAAAAAAQAAABVpbmZlAgAAAAABAABodmMxAAAAAA5waXRtAAAAAAABAAAA/GlwcnAAAADcaXBjbwAAAHVodmNDAQNwAAAAAAAAAAAAHvAA/P34+AAADwNgAAEAGEABDAH//wNwAAADAJAAAAMAAAMAHroCQGEAAQApQgEBA3AAAAMAkAAAAwAAAwAeoCCBBZbqrprm4CGgwIAAAAyAAAADAIRiAAEABkQBwXPBiQAAABNjb2xybmNseAABAA0ABoAAAAAUaXNwZQAAAAAAAABAAAAAQAAAAChjbGFwAAAAAgAAAAEAAAACAAAAAf///8IAAAAC////wgAAAAIAAAAQcGl4aQAAAAADCAgIAAAAGGlwbWEAAAAAAAAAAQABBYECAwWEAAAAP21kYXQAAAAzKAGvBjIWhzSJIPC/cov//8tX9l+i9qzWyeuEfoBjx+S3kJGe9F97GFLlPHQg9JxTuc2A";var O=class t{bytes;view;base;pos=0;constructor(e,r=0,n){let o=e instanceof Uint8Array?e:new Uint8Array(e),i=o.byteOffset+r,s=n??o.byteLength-r;if(r<0||s<0||r+s>o.byteLength)throw new d("Reader window is outside the source buffer",{offset:r});this.bytes=new Uint8Array(o.buffer,i,s),this.view=new DataView(o.buffer,i,s),this.base=i}get length(){return this.bytes.byteLength}get offset(){return this.pos}get absoluteOffset(){return this.base+this.pos}get remaining(){return this.length-this.pos}get eof(){return this.pos>=this.length}seek(e){this.require(0,e),this.pos=e}skip(e){this.require(e),this.pos+=e}require(e,r=this.pos){if(!Number.isFinite(e)||e<0||!Number.isFinite(r)||r<0)throw new d("Malformed read request",{offset:this.base+this.pos});if(r+e>this.length)throw new d(`Read of ${e} bytes at ${r} exceeds the ${this.length}-byte window`,{offset:this.base+r})}u8(){return this.require(1),this.view.getUint8(this.pos++)}u16(){this.require(2);let e=this.view.getUint16(this.pos);return this.pos+=2,e}u24(){this.require(3);let e=this.view.getUint8(this.pos)<<16|this.view.getUint8(this.pos+1)<<8|this.view.getUint8(this.pos+2);return this.pos+=3,e>>>0}u32(){this.require(4);let e=this.view.getUint32(this.pos);return this.pos+=4,e>>>0}u64(){this.require(8);let e=this.view.getBigUint64(this.pos);if(this.pos+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new d("64-bit value exceeds the safe integer range",{offset:this.base+this.pos-8});return Number(e)}uint(e){switch(e){case 0:return 0;case 1:return this.u8();case 2:return this.u16();case 4:return this.u32();case 8:return this.u64();default:throw new d(`Unsupported integer width: ${e} bytes`,{offset:this.base+this.pos})}}fourCC(){this.require(4);let e="";for(let r=0;r<4;r++){let n=this.view.getUint8(this.pos+r);e+=n>=32&&n<=126?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`}return this.pos+=4,e}cString(){let e=this.pos;for(;this.pos<this.length&&this.bytes[this.pos]!==0;)this.pos++;let r=this.bytes.subarray(e,this.pos);return this.pos<this.length&&this.pos++,new TextDecoder().decode(r)}view_(e){this.require(e);let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}copy(e){return new Uint8Array(this.view_(e))}sub(e){this.require(e);let r=new t(this.bytes,this.pos,e);return this.pos+=e,r}peekRest(){return new t(this.bytes,this.pos,this.remaining)}};function v(t){let e=t.u8(),r=t.u24();return{version:e,flags:r}}var Xe=32,Ve=33,je=34,qe=32,Qe=256;function V(t){let e=t.peekRest().bytes,r=t.u8();if(r!==1)throw new d(`Unsupported HEVCDecoderConfigurationRecord version ${r}`,{box:"hvcC"});let n=t.u8(),o=n>>6&3,i=n>>5&1,s=n&31,a=t.u32(),c=t.copy(6),p=t.u8(),u=t.u16()&4095,m=t.u8()&3,f=t.u8()&3,l=t.u8()&7,g=t.u8()&7,y=t.u16(),h=t.u8(),B=h>>6&3,P=h>>3&7,H=h>>2&1,$=h&3,E=t.u8();if(E>qe)throw new d(`hvcC declares ${E} NAL arrays`,{box:"hvcC"});let W=[];for(let R=0;R<E;R++){let z=t.u8(),L=(z>>7&1)===1,_=z&63,te=t.u16();if(te>Qe)throw new d(`hvcC array declares ${te} NAL units`,{box:"hvcC"});let ae=[];for(let ce=0;ce<te;ce++){let Oe=t.u16();ae.push(t.view_(Oe))}W.push({arrayCompleteness:L,nalUnitType:_,nalus:ae})}return{configurationVersion:r,generalProfileSpace:o,generalTierFlag:i,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:c,generalLevelIdc:p,minSpatialSegmentationIdc:u,parallelismType:m,chromaFormat:f,bitDepthLumaMinus8:l,bitDepthChromaMinus8:g,avgFrameRate:y,constantFrameRate:B,numTemporalLayers:P,temporalIdNested:H,lengthSizeMinusOne:$,arrays:W,raw:e}}var Ye=["","A","B","C"];function U(t,e="hvc1"){let n=`${Ye[t.generalProfileSpace]??""}${t.generalProfileIdc}`,o=Ze(t.generalProfileCompatibilityFlags).toString(16),s=`${t.generalTierFlag===1?"H":"L"}${t.generalLevelIdc}`,a=[...t.generalConstraintIndicatorFlags];for(;a.length>0&&a[a.length-1]===0;)a.pop();let c=a.map(p=>p.toString(16).padStart(2,"0").toUpperCase());return[e,n,o,s,...c].join(".")}function Ze(t){let e=t>>>0;return e=(e&1431655765)<<1|e>>>1&1431655765,e=(e&858993459)<<2|e>>>2&858993459,e=(e&252645135)<<4|e>>>4&252645135,e=(e&16711935)<<8|e>>>8&16711935,e=e>>>16|e<<16,e>>>0}function de(t){return t.bitDepthLumaMinus8+8}function j(t){let r=[Xe,Ve,je].flatMap(s=>t.arrays.filter(a=>a.nalUnitType===s)).flatMap(s=>s.nalus),n=0;for(let s of r)n+=4+s.byteLength;let o=new Uint8Array(n),i=0;for(let s of r)o.set([0,0,0,1],i),i+=4,o.set(s,i),i+=s.byteLength;return o}function q(t,e){if(e<1||e>4)throw new d(`Invalid NAL length size ${e}`,{box:"hvcC"});let r=new Uint8Array(t.byteLength+Je(t,e)*(4-e)),n=0,o=0;for(;n+e<=t.byteLength;){let i=0;for(let s=0;s<e;s++)i=i<<8|t[n+s];if(n+=e,i<0||n+i>t.byteLength)throw new d("NAL unit length runs past the end of the item payload",{offset:n});r.set([0,0,0,1],o),o+=4,r.set(t.subarray(n,n+i),o),o+=i,n+=i}return r.subarray(0,o)}function Je(t,e){let r=0,n=0;for(;r+e<=t.byteLength;){let o=0;for(let i=0;i<e;i++)o=o<<8|t[r+i];if(r+=e+o,o<0||r>t.byteLength)break;n++}return n}var me=32,le=65536;function*G(t,e={}){let{depth:r=0,lenient:n=!1}=typeof e=="number"?{depth:e,lenient:!1}:e;if(r>me)throw new d(`Box nesting deeper than ${me}`,{offset:t.absoluteOffset});let o=0;for(;t.remaining>=8;){if(++o>le)throw new d(`More than ${le} sibling boxes at one level`,{offset:t.absoluteOffset});let i=t.absoluteOffset,s=t.offset,a=t.u32(),c=t.fourCC(),p=8;if(a===1?(a=t.u64(),p=16):a===0&&(a=t.length-s),a<p){if(n)return;throw new d(`Box size ${a} is smaller than its ${p}-byte header`,{offset:i,box:c})}if(s+a>t.length){if(n)return;throw new d(`Box extends ${s+a-t.length} bytes past its container`,{offset:i,box:c})}let u=a-p,m=t.sub(u);yield{type:c,offset:i,size:a,headerSize:p,body:m},t.seek(s+a)}}function M(t,e={}){return[...G(t,e)]}function b(t,e){return t.find(r=>r.type===e)}function he(t,e){return t.filter(r=>r.type===e)}var Q=65536,Ke=4096,ge=4096,et=256,tt=8192;function rt(t){let e=t.body,{version:r,flags:n}=v(e),o=(n&1)===1;if(r>=2){let p=r===2?e.u16():e.u32(),u=e.u16(),m=e.fourCC(),f=e.cString(),l={itemId:p,protectionIndex:u,itemType:m,itemName:f,hidden:o};return m==="mime"&&(l.contentType=e.cString()),l}let i=e.u16(),s=e.u16(),a=e.cString(),c=e.cString();return{itemId:i,protectionIndex:s,itemType:"",itemName:a,contentType:c,hidden:o}}function nt(t){let e=t.body,{version:r}=v(e),n=r===0?e.u16():e.u32();if(n>Q)throw new d(`iinf declares ${n} items`,{box:"iinf"});let o=new Map,i=0;for(let s of G(e.peekRest())){if(s.type!=="infe")continue;if(++i>Q)break;let a=rt(s);o.set(a.itemId,a)}return o}function ot(t){let e=t.body,{version:r}=v(e),n=e.u8(),o=n>>4&15,i=n&15,s=e.u8(),a=s>>4&15,c=r===1||r===2?s&15:0,p=r<2?e.u16():e.u32();if(p>Q)throw new d(`iloc declares ${p} items`,{box:"iloc"});let u=new Map;for(let m=0;m<p;m++){let f=r<2?e.u16():e.u32(),l=0;(r===1||r===2)&&(l=e.u16()&15),e.u16();let g=e.uint(a),y=e.u16();if(y>Ke)throw new d(`Item ${f} declares ${y} extents`,{box:"iloc",itemId:f});let h=[];for(let B=0;B<y;B++){(r===1||r===2)&&c>0&&e.uint(c);let P=e.uint(o),H=e.uint(i);h.push({offset:P,length:H})}u.set(f,{itemId:f,constructionMethod:l,baseOffset:g,extents:h})}return u}function it(t){let e=t.body;switch(t.type){case"ispe":return v(e),{type:"ispe",width:e.u32(),height:e.u32()};case"hvcC":return{type:"hvcC",hvcc:V(e)};case"irot":return{type:"irot",angle:(e.u8()&3)*90};case"imir":return{type:"imir",axis:e.u8()&1};case"colr":{let r=e.fourCC();if(r==="nclx"){let n=e.u16(),o=e.u16(),i=e.u16(),s=(e.u8()&128)!==0;return{type:"colr",colorType:"nclx",primaries:n,transfer:o,matrix:i,fullRange:s}}return r==="rICC"||r==="prof"?{type:"colr",colorType:"icc",profile:e.copy(e.remaining)}:{type:"unknown",boxType:`colr:${r}`}}case"pixi":{v(e);let r=e.u8(),n=[];for(let o=0;o<r;o++)n.push(e.u8());return{type:"pixi",bitsPerChannel:n}}case"clap":return{type:"clap",widthN:e.u32(),widthD:e.u32(),heightN:e.u32(),heightD:e.u32(),horizOffN:e.u32()|0,horizOffD:e.u32(),vertOffN:e.u32()|0,vertOffD:e.u32()};case"auxC":return v(e),{type:"auxC",auxType:e.cString()};default:return{type:"unknown",boxType:t.type}}}function st(t,e){let r=t.body,{version:n,flags:o}=v(r),i=(o&1)===1,s=r.u32();if(s>Q)throw new d(`ipma declares ${s} entries`,{box:"ipma"});for(let a=0;a<s;a++){let c=n===0?r.u16():r.u32(),p=r.u8();if(p>et)throw new d(`Item ${c} declares ${p} properties`,{box:"ipma",itemId:c});let u=[];for(let f=0;f<p;f++)if(i){let l=r.u16();u.push({essential:(l&32768)!==0,index:l&32767})}else{let l=r.u8();u.push({essential:(l&128)!==0,index:l&127})}let m=e.get(c);m?m.push(...u):e.set(c,u)}}function at(t){let e=M(t.body),r=b(e,"ipco"),n=[];if(r)for(let i of G(r.body)){if(n.length>=ge)throw new d(`ipco holds more than ${ge} properties`,{box:"ipco"});n.push(it(i))}let o=new Map;for(let i of he(e,"ipma"))st(i,o);return{properties:n,associations:o}}function ct(t){let e=t.body,{version:r}=v(e),n=new Map;for(let o of G(e.peekRest())){let i=o.body,s=r===0?i.u16():i.u32(),a=i.u16();if(a>tt)throw new d(`Item ${s} declares ${a} references`,{box:o.type,itemId:s});let c=[];for(let u=0;u<a;u++)c.push(r===0?i.u16():i.u32());let p=n.get(o.type);p||n.set(o.type,p=new Map),p.set(s,c)}return n}function N(t,e={}){let r=t instanceof Uint8Array?t:new Uint8Array(t),n=new O(r),o=M(n,{lenient:e.truncated===!0}),i=b(o,"ftyp");if(!i)throw new d("No 'ftyp' box: this is not an ISOBMFF file",{offset:0});let s=i.body.fourCC(),a=i.body.u32(),c=[];for(;i.body.remaining>=4;)c.push(i.body.fourCC());let p=b(o,"meta");if(!p)throw new d("No 'meta' box: not a HEIF image file",{brand:s});v(p.body);let u=M(p.body,1),m=b(u,"hdlr"),f="";if(m&&(v(m.body),m.body.u32(),f=m.body.fourCC()),f&&f!=="pict")throw new d(`meta handler is '${f}', expected 'pict'`,{brand:s});let l=0,g=b(u,"pitm");if(g){let{version:L}=v(g.body);l=L===0?g.body.u16():g.body.u32()}let y=b(u,"iinf"),h=y?nt(y):new Map,B=b(u,"iloc"),P=B?ot(B):new Map,H=b(u,"iprp"),$=H?at(H):{properties:[],associations:new Map},E=b(u,"iref"),W=E?ct(E):new Map,R=b(u,"idat"),z=R?R.body.copy(R.body.remaining):void 0;if(l===0){for(let[L,_]of h)if(_.itemType==="hvc1"||_.itemType==="hev1"||_.itemType==="grid"){l=L;break}}return{majorBrand:s,minorVersion:a,compatibleBrands:c,primaryItemId:l,handlerType:f,items:h,locations:P,itemProperties:$,references:W,itemData:z,source:r}}function T(t,e){let r=t.itemProperties.associations.get(e)??[],n=[];for(let o of r){if(o.index===0)continue;let i=t.itemProperties.properties[o.index-1];if(!i)throw new d(`Item ${e} references property ${o.index}, but ipco holds ${t.itemProperties.properties.length}`,{itemId:e,box:"ipma"});if(o.essential&&i.type==="unknown")throw new d(`Item ${e} requires unsupported essential property '${i.boxType}'`,{itemId:e,box:i.boxType});n.push(i)}return n}function C(t,e){return t.find(r=>r.type===e)}function k(t,e){let r=t.locations.get(e);if(!r)throw new d(`No iloc entry for item ${e}`,{itemId:e,box:"iloc"});let n=t.items.get(e),o={itemId:e,itemType:n?.itemType,box:"iloc"},i;switch(r.constructionMethod){case 0:i=t.source;break;case 1:if(!t.itemData)throw new d(`Item ${e} points into 'idat', but the file has no idat box`,o);i=t.itemData;break;case 2:throw new d(`Item ${e} uses construction_method 2 (item offset), which is not supported`,o);default:throw new d(`Item ${e} uses unknown construction_method ${r.constructionMethod}`,o)}let s=0;for(let p of r.extents){let u=r.baseOffset+p.offset,m=p.length===0?i.byteLength-u:p.length;if(u<0||m<0||u+m>i.byteLength)throw new d(`Item ${e} extent [${u}, ${u+m}) is outside its ${i.byteLength}-byte container`,o);s+=m}if(r.extents.length===1){let p=r.extents[0],u=r.baseOffset+p.offset;return i.subarray(u,u+s)}let a=new Uint8Array(s),c=0;for(let p of r.extents){let u=r.baseOffset+p.offset,m=p.length===0?i.byteLength-u:p.length;a.set(i.subarray(u,u+m),c),c+=m}return a}var ye=4096;function ne(t){let e=new O(t),r=e.u8();if(r!==0)throw new d(`Unsupported grid version ${r}`,{itemType:"grid"});let o=(e.u8()&1)===1,i=e.u8()+1,s=e.u8()+1,a=o?e.u32():e.u16(),c=o?e.u32():e.u16();return{rows:i,columns:s,outputWidth:a,outputHeight:c}}function Y(t,e,r=[]){let n=k(t,e),{rows:o,columns:i,outputWidth:s,outputHeight:a}=ne(n),c=t.references.get("dimg")?.get(e)??[];if(c.length===0)throw new d(`Grid item ${e} has no 'dimg' tile references`,{itemId:e,itemType:"grid"});let p=o*i;if(p!==c.length)throw new d(`Grid item ${e} declares ${o}x${i} = ${p} tiles but 'dimg' lists ${c.length}`,{itemId:e,itemType:"grid"});if(p>ye)throw new d(`Grid item ${e} declares ${p} tiles (max ${ye})`,{itemId:e,itemType:"grid"});let u=s,m=a,f=C(T(t,e),"ispe");return f&&(f.width!==s||f.height!==a)&&(r.push({code:"grid-dimension-mismatch",message:`Grid payload declares ${s}x${a} but ispe declares ${f.width}x${f.height}; using ispe`}),u=f.width,m=f.height),{rows:o,columns:i,outputWidth:u,outputHeight:m,tileItemIds:c}}var Ae=256e6;function Z(t){let e=N(t),r=[],n=e.primaryItemId,o=e.items.get(n);if(!o)throw new d(`Primary item ${n} is not described by iinf`,{brand:e.majorBrand,itemId:n});let i=o.itemType==="grid";if(!i&&o.itemType!=="hvc1"&&o.itemType!=="hev1")throw new x(`Primary item type '${o.itemType}' is not a supported image item`,[],{brand:e.majorBrand,itemType:o.itemType,itemId:n});let s=T(e,n),a=[],c,p;if(i){let h=Y(e,n,r);c=h.outputWidth,p=h.outputHeight;let B=T(e,h.tileItemIds[0]),P=C(B,"ispe");if(!P)throw new d(`Grid tile ${h.tileItemIds[0]} has no ispe`,{itemId:h.tileItemIds[0]});for(let[H,$]of h.tileItemIds.entries()){let E=C(T(e,$),"ispe")??P;a.push({itemId:$,x:H%h.columns*P.width,y:Math.floor(H/h.columns)*P.height,width:E.width,height:E.height})}}else{let h=C(s,"ispe");if(!h)throw new d(`Primary item ${n} has no ispe`,{itemId:n});c=h.width,p=h.height,a.push({itemId:n,x:0,y:0,width:h.width,height:h.height})}if(c<=0||p<=0)throw new d(`Implausible image dimensions ${c}x${p}`,{itemId:n});if(c*p>Ae)throw new x(`Image is ${c}x${p}, above the ${Ae}-pixel limit`,[],{itemId:n});let u=pt(e,a,r),m=ft(s,c,p),{displayWidth:f,displayHeight:l}=dt(c,p,m),y=C(s,"pixi")?.bitsPerChannel[0]??de(u[0].hvcc);return lt(e,n,r),{file:e,primaryItemId:n,isGrid:i,codedWidth:c,codedHeight:p,displayWidth:f,displayHeight:l,tiles:a,tileGroups:u,transforms:m,bitDepth:y,sourceColor:mt(s,T(e,a[0].itemId)),warnings:r}}function pt(t,e,r){let n=new Map;for(let[i,s]of e.entries()){let c=(t.itemProperties.associations.get(s.itemId)??[]).find(u=>t.itemProperties.properties[u.index-1]?.type==="hvcC");if(!c)throw new d(`Item ${s.itemId} has no hvcC property`,{itemId:s.itemId});let p=n.get(c.index);if(!p){let u=t.itemProperties.properties[c.index-1];if(u?.type!=="hvcC")throw new d(`Property ${c.index} is not an hvcC`,{itemId:s.itemId});p={configIndex:c.index,hvcc:u.hvcc,codec:U(u.hvcc),tileIndices:[]},n.set(c.index,p)}p.tileIndices.push(i)}let o=[...n.values()];if(o.length===0)throw new d("No decoder configuration found for any tile",{});return o.length>1&&r.push({code:"mixed-tile-configs",message:`Tiles use ${o.length} different decoder configurations; decoding in ${o.length} groups`}),o}function ft(t,e,r){let n=[],o=e,i=r;for(let s of t)switch(s.type){case"clap":{let a=ut(s,o,i);a&&(n.push(a),o=a.width,i=a.height);break}case"irot":s.angle!==0&&(n.push({kind:"rotate",angle:s.angle}),(s.angle===90||s.angle===270)&&([o,i]=[i,o]));break;case"imir":n.push({kind:"mirror",axis:s.axis});break;default:break}return n}function ut(t,e,r){if(t.widthD===0||t.heightD===0||t.horizOffD===0||t.vertOffD===0)return;let n=Math.round(t.widthN/t.widthD),o=Math.round(t.heightN/t.heightD),i=t.horizOffN/t.horizOffD,s=t.vertOffN/t.vertOffD,a=Math.round((e-n)/2+i),c=Math.round((r-o)/2+s);if(!(n<=0||o<=0)&&!(n===e&&o===r&&a===0&&c===0)&&!(a<0||c<0||a+n>e||c+o>r))return{kind:"crop",width:n,height:o,offsetX:a,offsetY:c}}function dt(t,e,r){let n=t,o=e;for(let i of r)i.kind==="crop"?(n=i.width,o=i.height):i.kind==="rotate"&&(i.angle===90||i.angle===270)&&([n,o]=[o,n]);return{displayWidth:n,displayHeight:o}}function mt(t,e){let r=C(t,"colr")??C(e,"colr");return r?r.colorType==="nclx"?{type:"nclx",primaries:r.primaries,transfer:r.transfer,matrix:r.matrix,fullRange:r.fullRange}:{type:"icc",profile:r.profile}:null}function lt(t,e,r){let n=new Set,o=s=>{n.has(s.code)||(n.add(s.code),r.push(s))},i=t.references.get("auxl");if(i)for(let[s,a]of i){if(!a.includes(e))continue;let c=C(T(t,s),"auxC")?.auxType??"";/alpha/i.test(c)?o({code:"alpha-ignored",message:`Alpha aux image ${s} ignored`}):/depth|disparity/i.test(c)?o({code:"depth-ignored",message:`Depth aux image ${s} ignored`}):/hdrgainmap|gainmap/i.test(c)&&o({code:"gain-map-ignored",message:`HDR gain map ${s} ignored; the image decodes as SDR`})}for(let s of t.items.values())if(s.itemType==="tmap"){o({code:"gain-map-ignored",message:`Tone-map item ${s.itemId} ignored; the image decodes as SDR`});break}}function be(t,e){return k(t.file,e.itemId)}function F(){return typeof VideoDecoder<"u"&&typeof EncodedVideoChunk<"u"}async function ht(t,e,r){let n=t.hvcc.lengthSizeMinusOne+1,o=[],i={codec:t.codec,description:new Uint8Array(t.hvcc.raw),codedWidth:e,codedHeight:r,optimizeForLatency:!0};try{let a=await VideoDecoder.isConfigSupported(i);if(a.supported)return{mode:"hvc1",config:a.config??i,lengthSize:n};o.push({strategy:"hvc1",reason:"isConfigSupported returned false"})}catch(a){o.push({strategy:"hvc1",reason:String(a)})}let s={codec:U(t.hvcc,"hev1"),codedWidth:e,codedHeight:r,optimizeForLatency:!0};try{let a=await VideoDecoder.isConfigSupported(s);if(a.supported)return{mode:"hev1",config:a.config??s,prologue:j(t.hvcc),lengthSize:n};o.push({strategy:"hev1",reason:"isConfigSupported returned false"})}catch(a){o.push({strategy:"hev1",reason:String(a)})}throw new x("No HEVC decoder configuration was accepted",o,{strategy:"webcodecs",codec:t.codec})}function gt(t,e){if(t.mode==="hvc1")return e;let r=q(e,t.lengthSize),n=t.prologue,o=new Uint8Array(n.byteLength+r.byteLength);return o.set(n,0),o.set(r,n.byteLength),o}async function xe(t,e,r){if(!F())throw new x("WebCodecs VideoDecoder is not available in this environment",[{strategy:"webcodecs",reason:"VideoDecoder is undefined"}],{strategy:"webcodecs"});A(r);let n=S(t.codedWidth,t.codedHeight),o=n.getContext("2d",{colorSpace:e,alpha:!1,willReadFrequently:!1});if(!o)throw new w("Could not get a 2d context for compositing",{strategy:"webcodecs"});for(let i of t.tileGroups)A(r),await yt(t,i,o,r);return n}async function yt(t,e,r,n){let o=t.tiles[e.tileIndices[0]],i=await ht(e,o.width,o.height);A(n);let s=0,a=0,c,p=new Promise((f,l)=>{c=l}),u=new VideoDecoder({output:f=>{try{let l=t.tiles[e.tileIndices[s++]];l&&(r.drawImage(f,l.x,l.y,l.width,l.height),a++)}finally{f.close()}},error:f=>{c?.(new w(`VideoDecoder failed: ${f.message}`,{strategy:"webcodecs",codec:i.config.codec}))}}),m=()=>c?.(new I);n?.addEventListener("abort",m,{once:!0});try{try{u.configure(i.config);for(let f of e.tileIndices){let l=t.tiles[f],g=gt(i,be(t,l));u.decode(new EncodedVideoChunk({type:"key",timestamp:f,duration:0,data:g}))}}catch(f){throw f instanceof I||f instanceof w?f:new w(`VideoDecoder rejected the stream: ${f instanceof Error?f.message:String(f)}`,{strategy:"webcodecs",codec:i.config.codec},{cause:f})}if(await Promise.race([u.flush(),p]),a!==e.tileIndices.length)throw new w(`Decoder emitted ${a} frames for ${e.tileIndices.length} tiles`,{strategy:"webcodecs",codec:i.config.codec})}finally{n?.removeEventListener("abort",m);try{u.close()}catch{}}}var At=["hvc1.3.e.L93.B0","hvc1.1.6.L93.B0","hvc1.2.4.L120.B0"];async function we(){if(!F())return[];let t=[];for(let e of At)try{(await VideoDecoder.isConfigSupported({codec:e,codedWidth:1920,codedHeight:1080})).supported&&t.push(e)}catch{}return t}var bt=new Set(["heic","heix","hevc","hevx","heim","heis","hevm","hevs","mif1","msf1"]),xt=new Set(["heic","heix","hevc","hevx","heim","heis","hevm","hevs"]),Ie=65536;function ve(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),r,n;try{let c=M(new O(e),{lenient:!0}),p=b(c,"ftyp");if(!p)return{isHeic:!1};for(n=p.body.fourCC(),r=new Set([n]),p.body.u32();p.body.remaining>=4;)r.add(p.body.fourCC())}catch{return{isHeic:!1}}if(![...r].some(c=>bt.has(c)))return{isHeic:!1,brand:n};let o;try{o=N(e,{truncated:!0})}catch{o=void 0}let i=o?.items.get(o.primaryItemId)?.itemType,s=o?Ce(o,i):"unknown";if(s==="av1")return{isHeic:!1,brand:n,primaryItemType:i,coding:s};if(s==="hevc")return{isHeic:!0,brand:n,primaryItemType:i,coding:s};let a={isHeic:[...r].some(c=>xt.has(c)),brand:n,coding:"unknown"};return i!==void 0&&(a.primaryItemType=i),a}function Ce(t,e,r=0){if(e==="hvc1"||e==="hev1")return"hevc";if(e==="av01")return"av1";if(r<4&&(e==="grid"||e==="iovl"||e==="iden")){let n=t.references.get("dimg")?.get(t.primaryItemId)?.[0];if(n!==void 0)return Ce(t,t.items.get(n)?.itemType,r+1)}return"unknown"}function J(t,e,r){let n=t;for(let o of e)switch(o.kind){case"crop":n=oe(n,wt(n,o,r),t);break;case"rotate":n=oe(n,It(n,o.angle,r),t);break;case"mirror":n=oe(n,vt(n,o.axis,r),t);break}return{canvas:n,applied:K(e)}}function K(t){let e={rotation:0,mirrored:"none",cropped:!1};for(let r of t)switch(r.kind){case"crop":e.cropped=!0;break;case"rotate":e.rotation=(e.rotation+r.angle)%360;break;case"mirror":{let n=Pe(r.axis);e.mirrored==="none"?e.mirrored=n:e.mirrored===n?e.mirrored="none":(e.mirrored="none",e.rotation=(e.rotation+180)%360);break}}return e}function Pe(t){return t===0?"vertical":"horizontal"}function wt(t,e,r){let n=S(e.width,e.height);return ie(n,r).drawImage(t,e.offsetX,e.offsetY,e.width,e.height,0,0,e.width,e.height),n}function It(t,e,r){let n=e===90||e===270,o=S(n?t.height:t.width,n?t.width:t.height),i=ie(o,r);return i.translate(o.width/2,o.height/2),i.rotate(-e*Math.PI/180),i.drawImage(t,-t.width/2,-t.height/2),o}function vt(t,e,r){let n=S(t.width,t.height),o=ie(n,r);return Pe(e)==="horizontal"?(o.translate(t.width,0),o.scale(-1,1)):(o.translate(0,t.height),o.scale(1,-1)),o.drawImage(t,0,0),n}function ie(t,e){let r=t.getContext("2d",{colorSpace:e,alpha:!1});if(!r)throw new Error("Could not get a 2d context");return r}function oe(t,e,r){return t!==r&&(t.width=0,t.height=0),e}async function Te(){let[t,e]=await Promise.all([ue(),we()]),r=F()&&e.length>0;return{native:t,webcodecs:r,hevcCodecStrings:e,recommended:t?"native":r?"webcodecs":"wasm"}}async function Ct(t){let e=await Et(t,Ie),r=ve(e),n={isHeic:r.isHeic};return r.brand!==void 0&&(n.brand=r.brand),r.primaryItemType!==void 0&&(n.primaryItemType=r.primaryItemType),r.coding!==void 0&&(n.coding=r.coding),n}async function Pt(t,e={}){let{strategy:r="auto",colorSpace:n="srgb",maxDimension:o,signal:i,wasmLoader:s}=e;A(i);let a=await De(t);A(i);let c=Z(a);A(i);let p=[],u=m=>r==="auto"||r===m;if(u("native")){let m=t instanceof Blob?t:X(a),f=await fe(m,c,i);if(f.status==="ok"){let l=await He(f.bitmap,o,i);return se(c,l,"native",K(c.transforms))}p.push({strategy:"native",reason:f.reason})}if(u("webcodecs"))if(!F())p.push({strategy:"webcodecs",reason:"VideoDecoder is not available"});else try{let m=await xe(c,n,i),{canvas:f,applied:l}=J(m,c.transforms,n),g=await Be(f,o,i);return se(c,g,"webcodecs",l)}catch(m){if(m instanceof I||r==="webcodecs")throw m;p.push({strategy:"webcodecs",reason:Ee(m)})}if(u("wasm")){let m=await Ht(s);if(!m)p.push({strategy:"wasm",reason:"no adapter: pass options.wasmLoader or call registerDecoderAdapter()"});else try{let f=await m.decode({data:a,colorSpace:n,signal:i}),l=K(c.transforms),g;if(f.image instanceof ImageBitmap){let y=m.appliesTransforms?f.image:await Dt(f.image,c,n);g=await He(y,o,i)}else{let y=m.appliesTransforms?f.image:J(f.image,c.transforms,n).canvas;g=await Be(y,o,i)}return se(c,g,"wasm",l)}catch(f){if(f instanceof I||r==="wasm")throw f;p.push({strategy:"wasm",reason:Ee(f)})}}throw new x("Could not decode this HEIC",p,{brand:c.file.majorBrand,itemType:c.file.items.get(c.primaryItemId)?.itemType,itemId:c.primaryItemId})}var ee;function Tt(t){ee=t}function Bt(){return ee}async function Ht(t){if(ee)return ee;if(t)return t()}async function De(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(await t.arrayBuffer())}async function Et(t,e){return t instanceof Blob?new Uint8Array(await t.slice(0,e).arrayBuffer()):(await De(t)).subarray(0,e)}function Se(t,e,r){if(!r||r<=0)return 1;let n=Math.max(t,e);return n<=r?1:r/n}async function Be(t,e,r){A(r);let n=Se(t.width,t.height,e);if(n===1)return t.transferToImageBitmap();let o=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n));try{return await createImageBitmap(t,{resizeWidth:o,resizeHeight:i,resizeQuality:"high"})}finally{t.width=0,t.height=0}}async function He(t,e,r){A(r);let n=Se(t.width,t.height,e);if(n===1)return t;let o=await createImageBitmap(t,{resizeWidth:Math.max(1,Math.round(t.width*n)),resizeHeight:Math.max(1,Math.round(t.height*n)),resizeQuality:"high"});return t.close(),o}async function Dt(t,e,r){if(e.transforms.length===0)return t;let n=S(t.width,t.height),o=n.getContext("2d",{colorSpace:r,alpha:!1});if(!o)return t;o.drawImage(t,0,0),t.close();let{canvas:i}=J(n,e.transforms,r);return i.transferToImageBitmap()}function se(t,e,r,n){return{image:e,width:e.width,height:e.height,sourceWidth:t.displayWidth,sourceHeight:t.displayHeight,strategy:r,bitDepth:t.bitDepth,isGrid:t.isGrid,tileCount:t.tiles.length,sourceColor:t.sourceColor,transformsApplied:n,warnings:t.warnings}}function Ee(t){return t instanceof Error?t.message:String(t)}return ke(St);})();
|
|
1
|
+
"use strict";var HeicDecoder=(()=>{var re=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var Ne=(t,e)=>{for(var r in e)re(t,r,{get:e[r],enumerable:!0})},ke=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ue(e))!Me.call(t,o)&&o!==r&&re(t,o,{get:()=>e[o],enumerable:!(n=Re(e,o))||n.enumerable});return t};var Fe=t=>ke(re({},"__esModule",{value:!0}),t);var Ot={};Ne(Ot,{HeicAbortError:()=>I,HeicDecodeError:()=>y,HeicError:()=>S,HeicParseError:()=>d,HeicUnsupportedError:()=>w,convertHeic:()=>Tt,decodeHeic:()=>De,findProperty:()=>C,getRegisteredAdapter:()=>Ht,hvccToAnnexBPrologue:()=>V,hvccToCodecString:()=>U,isHeic:()=>Pt,lengthPrefixedToAnnexB:()=>q,parseGridPayload:()=>ne,parseHeif:()=>N,parseHvcC:()=>j,planDecode:()=>Z,probeSupport:()=>Te,propertiesForItem:()=>T,readGrid:()=>Y,readItemData:()=>k,registerDecoderAdapter:()=>Bt});function X(t){return new Blob([t],{type:"image/heic"})}var S=class extends Error{context;constructor(e,r={},n){let o=Le(r);super(o?`${e} (${o})`:e,n),this.name="HeicError",this.context=r}},d=class extends S{constructor(e,r={},n){super(e,r,n),this.name="HeicParseError"}},w=class extends S{attempts;constructor(e,r=[],n={},o){let i=r.map(s=>`${s.strategy}: ${s.reason}`).join("; ");super(i?`${e} [${i}]`:e,n,o),this.name="HeicUnsupportedError",this.attempts=r}},y=class extends S{constructor(e,r={},n){super(e,r,n),this.name="HeicDecodeError"}},I=class extends S{constructor(e="Decode aborted",r={},n){super(e,r,n),this.name="HeicAbortError"}};function Le(t){let e=[];for(let[r,n]of Object.entries(t))n!==void 0&&e.push(`${r}=${n}`);return e.join(" ")}function D(t,e){if(typeof OffscreenCanvas>"u")throw new y("OffscreenCanvas is not available; this environment cannot composite",{});return new OffscreenCanvas(t,e)}function A(t){if(t?.aborted)throw new I}var pe=!1;async function fe(t,e,r){if(typeof createImageBitmap>"u")return{status:"unsupported",reason:"createImageBitmap is not available"};if(pe)return{status:"unsupported",reason:"this browser has no HEIC image decoder"};A(r);let n;try{n=await createImageBitmap(t)}catch{return pe=!0,{status:"unsupported",reason:"createImageBitmap rejected the file"}}if(A(r),!_e(n,e)){let o=`${n.width}x${n.height}`;return n.close(),{status:"wrong-image",reason:`returned ${o}, expected ${e.displayWidth}x${e.displayHeight}`}}return{status:"ok",bitmap:n}}function _e(t,e){let{displayWidth:r,displayHeight:n}=e,o=t.width===r&&t.height===n,i=t.width===n&&t.height===r;return o||i}async function ue(){if(typeof createImageBitmap>"u")return!1;try{let t=Ge(Xe),e=await createImageBitmap(X(t)),r=e.width===We&&e.height===ze;return e.close(),r}catch{return!1}}function Ge(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var We=2,ze=2,Xe="AAAAHGZ0eXBoZWljAAAAAG1pZjFoZWljbWlhZgAAAXxtZXRhAAAAAAAAACFoZGxyAAAAAAAAAABwaWN0AAAAAAAAAAAAAAAAAAAAACJpbG9jAAAAAERAAAEAAQAAAAABoAABAAAAAAAAADcAAAAjaWluZgAAAAAAAQAAABVpbmZlAgAAAAABAABodmMxAAAAAA5waXRtAAAAAAABAAAA/GlwcnAAAADcaXBjbwAAAHVodmNDAQNwAAAAAAAAAAAAHvAA/P34+AAADwNgAAEAGEABDAH//wNwAAADAJAAAAMAAAMAHroCQGEAAQApQgEBA3AAAAMAkAAAAwAAAwAeoCCBBZbqrprm4CGgwIAAAAyAAAADAIRiAAEABkQBwXPBiQAAABNjb2xybmNseAABAA0ABoAAAAAUaXNwZQAAAAAAAABAAAAAQAAAAChjbGFwAAAAAgAAAAEAAAACAAAAAf///8IAAAAC////wgAAAAIAAAAQcGl4aQAAAAADCAgIAAAAGGlwbWEAAAAAAAAAAQABBYECAwWEAAAAP21kYXQAAAAzKAGvBjIWhzSJIPC/cov//8tX9l+i9qzWyeuEfoBjx+S3kJGe9F97GFLlPHQg9JxTuc2A";var O=class t{bytes;view;base;pos=0;constructor(e,r=0,n){let o=e instanceof Uint8Array?e:new Uint8Array(e),i=o.byteOffset+r,s=n??o.byteLength-r;if(r<0||s<0||r+s>o.byteLength)throw new d("Reader window is outside the source buffer",{offset:r});this.bytes=new Uint8Array(o.buffer,i,s),this.view=new DataView(o.buffer,i,s),this.base=i}get length(){return this.bytes.byteLength}get offset(){return this.pos}get absoluteOffset(){return this.base+this.pos}get remaining(){return this.length-this.pos}get eof(){return this.pos>=this.length}seek(e){this.require(0,e),this.pos=e}skip(e){this.require(e),this.pos+=e}require(e,r=this.pos){if(!Number.isFinite(e)||e<0||!Number.isFinite(r)||r<0)throw new d("Malformed read request",{offset:this.base+this.pos});if(r+e>this.length)throw new d(`Read of ${e} bytes at ${r} exceeds the ${this.length}-byte window`,{offset:this.base+r})}u8(){return this.require(1),this.view.getUint8(this.pos++)}u16(){this.require(2);let e=this.view.getUint16(this.pos);return this.pos+=2,e}u24(){this.require(3);let e=this.view.getUint8(this.pos)<<16|this.view.getUint8(this.pos+1)<<8|this.view.getUint8(this.pos+2);return this.pos+=3,e>>>0}u32(){this.require(4);let e=this.view.getUint32(this.pos);return this.pos+=4,e>>>0}u64(){this.require(8);let e=this.view.getBigUint64(this.pos);if(this.pos+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new d("64-bit value exceeds the safe integer range",{offset:this.base+this.pos-8});return Number(e)}uint(e){switch(e){case 0:return 0;case 1:return this.u8();case 2:return this.u16();case 4:return this.u32();case 8:return this.u64();default:throw new d(`Unsupported integer width: ${e} bytes`,{offset:this.base+this.pos})}}fourCC(){this.require(4);let e="";for(let r=0;r<4;r++){let n=this.view.getUint8(this.pos+r);e+=n>=32&&n<=126?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`}return this.pos+=4,e}cString(){let e=this.pos;for(;this.pos<this.length&&this.bytes[this.pos]!==0;)this.pos++;let r=this.bytes.subarray(e,this.pos);return this.pos<this.length&&this.pos++,new TextDecoder().decode(r)}view_(e){this.require(e);let r=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,r}copy(e){return new Uint8Array(this.view_(e))}sub(e){this.require(e);let r=new t(this.bytes,this.pos,e);return this.pos+=e,r}peekRest(){return new t(this.bytes,this.pos,this.remaining)}};function v(t){let e=t.u8(),r=t.u24();return{version:e,flags:r}}var je=32,Ve=33,qe=34,Qe=32,Ye=256;function j(t){let e=t.peekRest().bytes,r=t.u8();if(r!==1)throw new d(`Unsupported HEVCDecoderConfigurationRecord version ${r}`,{box:"hvcC"});let n=t.u8(),o=n>>6&3,i=n>>5&1,s=n&31,a=t.u32(),c=t.copy(6),p=t.u8(),u=t.u16()&4095,m=t.u8()&3,f=t.u8()&3,l=t.u8()&7,g=t.u8()&7,b=t.u16(),h=t.u8(),B=h>>6&3,P=h>>3&7,H=h>>2&1,$=h&3,E=t.u8();if(E>Qe)throw new d(`hvcC declares ${E} NAL arrays`,{box:"hvcC"});let W=[];for(let R=0;R<E;R++){let z=t.u8(),L=(z>>7&1)===1,_=z&63,te=t.u16();if(te>Ye)throw new d(`hvcC array declares ${te} NAL units`,{box:"hvcC"});let ae=[];for(let ce=0;ce<te;ce++){let $e=t.u16();ae.push(t.view_($e))}W.push({arrayCompleteness:L,nalUnitType:_,nalus:ae})}return{configurationVersion:r,generalProfileSpace:o,generalTierFlag:i,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:c,generalLevelIdc:p,minSpatialSegmentationIdc:u,parallelismType:m,chromaFormat:f,bitDepthLumaMinus8:l,bitDepthChromaMinus8:g,avgFrameRate:b,constantFrameRate:B,numTemporalLayers:P,temporalIdNested:H,lengthSizeMinusOne:$,arrays:W,raw:e}}var Ze=["","A","B","C"];function U(t,e="hvc1"){let n=`${Ze[t.generalProfileSpace]??""}${t.generalProfileIdc}`,o=Je(t.generalProfileCompatibilityFlags).toString(16),s=`${t.generalTierFlag===1?"H":"L"}${t.generalLevelIdc}`,a=[...t.generalConstraintIndicatorFlags];for(;a.length>0&&a[a.length-1]===0;)a.pop();let c=a.map(p=>p.toString(16).padStart(2,"0").toUpperCase());return[e,n,o,s,...c].join(".")}function Je(t){let e=t>>>0;return e=(e&1431655765)<<1|e>>>1&1431655765,e=(e&858993459)<<2|e>>>2&858993459,e=(e&252645135)<<4|e>>>4&252645135,e=(e&16711935)<<8|e>>>8&16711935,e=e>>>16|e<<16,e>>>0}function de(t){return t.bitDepthLumaMinus8+8}function V(t){let r=[je,Ve,qe].flatMap(s=>t.arrays.filter(a=>a.nalUnitType===s)).flatMap(s=>s.nalus),n=0;for(let s of r)n+=4+s.byteLength;let o=new Uint8Array(n),i=0;for(let s of r)o.set([0,0,0,1],i),i+=4,o.set(s,i),i+=s.byteLength;return o}function q(t,e){if(e<1||e>4)throw new d(`Invalid NAL length size ${e}`,{box:"hvcC"});let r=new Uint8Array(t.byteLength+Ke(t,e)*(4-e)),n=0,o=0;for(;n+e<=t.byteLength;){let i=0;for(let s=0;s<e;s++)i=i<<8|t[n+s];if(n+=e,i<0||n+i>t.byteLength)throw new d("NAL unit length runs past the end of the item payload",{offset:n});r.set([0,0,0,1],o),o+=4,r.set(t.subarray(n,n+i),o),o+=i,n+=i}return r.subarray(0,o)}function Ke(t,e){let r=0,n=0;for(;r+e<=t.byteLength;){let o=0;for(let i=0;i<e;i++)o=o<<8|t[r+i];if(r+=e+o,o<0||r>t.byteLength)break;n++}return n}var me=32,le=65536;function*G(t,e={}){let{depth:r=0,lenient:n=!1}=typeof e=="number"?{depth:e,lenient:!1}:e;if(r>me)throw new d(`Box nesting deeper than ${me}`,{offset:t.absoluteOffset});let o=0;for(;t.remaining>=8;){if(++o>le)throw new d(`More than ${le} sibling boxes at one level`,{offset:t.absoluteOffset});let i=t.absoluteOffset,s=t.offset,a=t.u32(),c=t.fourCC(),p=8;if(a===1?(a=t.u64(),p=16):a===0&&(a=t.length-s),a<p){if(n)return;throw new d(`Box size ${a} is smaller than its ${p}-byte header`,{offset:i,box:c})}if(s+a>t.length){if(n)return;throw new d(`Box extends ${s+a-t.length} bytes past its container`,{offset:i,box:c})}let u=a-p,m=t.sub(u);yield{type:c,offset:i,size:a,headerSize:p,body:m},t.seek(s+a)}}function M(t,e={}){return[...G(t,e)]}function x(t,e){return t.find(r=>r.type===e)}function he(t,e){return t.filter(r=>r.type===e)}var Q=65536,et=4096,ge=4096,tt=256,rt=8192;function nt(t){let e=t.body,{version:r,flags:n}=v(e),o=(n&1)===1;if(r>=2){let p=r===2?e.u16():e.u32(),u=e.u16(),m=e.fourCC(),f=e.cString(),l={itemId:p,protectionIndex:u,itemType:m,itemName:f,hidden:o};return m==="mime"&&(l.contentType=e.cString()),l}let i=e.u16(),s=e.u16(),a=e.cString(),c=e.cString();return{itemId:i,protectionIndex:s,itemType:"",itemName:a,contentType:c,hidden:o}}function ot(t){let e=t.body,{version:r}=v(e),n=r===0?e.u16():e.u32();if(n>Q)throw new d(`iinf declares ${n} items`,{box:"iinf"});let o=new Map,i=0;for(let s of G(e.peekRest())){if(s.type!=="infe")continue;if(++i>Q)break;let a=nt(s);o.set(a.itemId,a)}return o}function it(t){let e=t.body,{version:r}=v(e),n=e.u8(),o=n>>4&15,i=n&15,s=e.u8(),a=s>>4&15,c=r===1||r===2?s&15:0,p=r<2?e.u16():e.u32();if(p>Q)throw new d(`iloc declares ${p} items`,{box:"iloc"});let u=new Map;for(let m=0;m<p;m++){let f=r<2?e.u16():e.u32(),l=0;(r===1||r===2)&&(l=e.u16()&15),e.u16();let g=e.uint(a),b=e.u16();if(b>et)throw new d(`Item ${f} declares ${b} extents`,{box:"iloc",itemId:f});let h=[];for(let B=0;B<b;B++){(r===1||r===2)&&c>0&&e.uint(c);let P=e.uint(o),H=e.uint(i);h.push({offset:P,length:H})}u.set(f,{itemId:f,constructionMethod:l,baseOffset:g,extents:h})}return u}function st(t){let e=t.body;switch(t.type){case"ispe":return v(e),{type:"ispe",width:e.u32(),height:e.u32()};case"hvcC":return{type:"hvcC",hvcc:j(e)};case"irot":return{type:"irot",angle:(e.u8()&3)*90};case"imir":return{type:"imir",axis:e.u8()&1};case"colr":{let r=e.fourCC();if(r==="nclx"){let n=e.u16(),o=e.u16(),i=e.u16(),s=(e.u8()&128)!==0;return{type:"colr",colorType:"nclx",primaries:n,transfer:o,matrix:i,fullRange:s}}return r==="rICC"||r==="prof"?{type:"colr",colorType:"icc",profile:e.copy(e.remaining)}:{type:"unknown",boxType:`colr:${r}`}}case"pixi":{v(e);let r=e.u8(),n=[];for(let o=0;o<r;o++)n.push(e.u8());return{type:"pixi",bitsPerChannel:n}}case"clap":return{type:"clap",widthN:e.u32(),widthD:e.u32(),heightN:e.u32(),heightD:e.u32(),horizOffN:e.u32()|0,horizOffD:e.u32(),vertOffN:e.u32()|0,vertOffD:e.u32()};case"auxC":return v(e),{type:"auxC",auxType:e.cString()};default:return{type:"unknown",boxType:t.type}}}function at(t,e){let r=t.body,{version:n,flags:o}=v(r),i=(o&1)===1,s=r.u32();if(s>Q)throw new d(`ipma declares ${s} entries`,{box:"ipma"});for(let a=0;a<s;a++){let c=n===0?r.u16():r.u32(),p=r.u8();if(p>tt)throw new d(`Item ${c} declares ${p} properties`,{box:"ipma",itemId:c});let u=[];for(let f=0;f<p;f++)if(i){let l=r.u16();u.push({essential:(l&32768)!==0,index:l&32767})}else{let l=r.u8();u.push({essential:(l&128)!==0,index:l&127})}let m=e.get(c);m?m.push(...u):e.set(c,u)}}function ct(t){let e=M(t.body),r=x(e,"ipco"),n=[];if(r)for(let i of G(r.body)){if(n.length>=ge)throw new d(`ipco holds more than ${ge} properties`,{box:"ipco"});n.push(st(i))}let o=new Map;for(let i of he(e,"ipma"))at(i,o);return{properties:n,associations:o}}function pt(t){let e=t.body,{version:r}=v(e),n=new Map;for(let o of G(e.peekRest())){let i=o.body,s=r===0?i.u16():i.u32(),a=i.u16();if(a>rt)throw new d(`Item ${s} declares ${a} references`,{box:o.type,itemId:s});let c=[];for(let u=0;u<a;u++)c.push(r===0?i.u16():i.u32());let p=n.get(o.type);p||n.set(o.type,p=new Map),p.set(s,c)}return n}function N(t,e={}){let r=t instanceof Uint8Array?t:new Uint8Array(t),n=new O(r),o=M(n,{lenient:e.truncated===!0}),i=x(o,"ftyp");if(!i)throw new d("No 'ftyp' box: this is not an ISOBMFF file",{offset:0});let s=i.body.fourCC(),a=i.body.u32(),c=[];for(;i.body.remaining>=4;)c.push(i.body.fourCC());let p=x(o,"meta");if(!p)throw new d("No 'meta' box: not a HEIF image file",{brand:s});v(p.body);let u=M(p.body,1),m=x(u,"hdlr"),f="";if(m&&(v(m.body),m.body.u32(),f=m.body.fourCC()),f&&f!=="pict")throw new d(`meta handler is '${f}', expected 'pict'`,{brand:s});let l=0,g=x(u,"pitm");if(g){let{version:L}=v(g.body);l=L===0?g.body.u16():g.body.u32()}let b=x(u,"iinf"),h=b?ot(b):new Map,B=x(u,"iloc"),P=B?it(B):new Map,H=x(u,"iprp"),$=H?ct(H):{properties:[],associations:new Map},E=x(u,"iref"),W=E?pt(E):new Map,R=x(u,"idat"),z=R?R.body.copy(R.body.remaining):void 0;if(l===0){for(let[L,_]of h)if(_.itemType==="hvc1"||_.itemType==="hev1"||_.itemType==="grid"){l=L;break}}return{majorBrand:s,minorVersion:a,compatibleBrands:c,primaryItemId:l,handlerType:f,items:h,locations:P,itemProperties:$,references:W,itemData:z,source:r}}function T(t,e){let r=t.itemProperties.associations.get(e)??[],n=[];for(let o of r){if(o.index===0)continue;let i=t.itemProperties.properties[o.index-1];if(!i)throw new d(`Item ${e} references property ${o.index}, but ipco holds ${t.itemProperties.properties.length}`,{itemId:e,box:"ipma"});if(o.essential&&i.type==="unknown")throw new d(`Item ${e} requires unsupported essential property '${i.boxType}'`,{itemId:e,box:i.boxType});n.push(i)}return n}function C(t,e){return t.find(r=>r.type===e)}function k(t,e){let r=t.locations.get(e);if(!r)throw new d(`No iloc entry for item ${e}`,{itemId:e,box:"iloc"});let n=t.items.get(e),o={itemId:e,itemType:n?.itemType,box:"iloc"},i;switch(r.constructionMethod){case 0:i=t.source;break;case 1:if(!t.itemData)throw new d(`Item ${e} points into 'idat', but the file has no idat box`,o);i=t.itemData;break;case 2:throw new d(`Item ${e} uses construction_method 2 (item offset), which is not supported`,o);default:throw new d(`Item ${e} uses unknown construction_method ${r.constructionMethod}`,o)}let s=0;for(let p of r.extents){let u=r.baseOffset+p.offset,m=p.length===0?i.byteLength-u:p.length;if(u<0||m<0||u+m>i.byteLength)throw new d(`Item ${e} extent [${u}, ${u+m}) is outside its ${i.byteLength}-byte container`,o);s+=m}if(r.extents.length===1){let p=r.extents[0],u=r.baseOffset+p.offset;return i.subarray(u,u+s)}let a=new Uint8Array(s),c=0;for(let p of r.extents){let u=r.baseOffset+p.offset,m=p.length===0?i.byteLength-u:p.length;a.set(i.subarray(u,u+m),c),c+=m}return a}var ye=4096;function ne(t){let e=new O(t),r=e.u8();if(r!==0)throw new d(`Unsupported grid version ${r}`,{itemType:"grid"});let o=(e.u8()&1)===1,i=e.u8()+1,s=e.u8()+1,a=o?e.u32():e.u16(),c=o?e.u32():e.u16();return{rows:i,columns:s,outputWidth:a,outputHeight:c}}function Y(t,e,r=[]){let n=k(t,e),{rows:o,columns:i,outputWidth:s,outputHeight:a}=ne(n),c=t.references.get("dimg")?.get(e)??[];if(c.length===0)throw new d(`Grid item ${e} has no 'dimg' tile references`,{itemId:e,itemType:"grid"});let p=o*i;if(p!==c.length)throw new d(`Grid item ${e} declares ${o}x${i} = ${p} tiles but 'dimg' lists ${c.length}`,{itemId:e,itemType:"grid"});if(p>ye)throw new d(`Grid item ${e} declares ${p} tiles (max ${ye})`,{itemId:e,itemType:"grid"});let u=s,m=a,f=C(T(t,e),"ispe");return f&&(f.width!==s||f.height!==a)&&(r.push({code:"grid-dimension-mismatch",message:`Grid payload declares ${s}x${a} but ispe declares ${f.width}x${f.height}; using ispe`}),u=f.width,m=f.height),{rows:o,columns:i,outputWidth:u,outputHeight:m,tileItemIds:c}}var Ae=256e6;function Z(t){let e=N(t),r=[],n=e.primaryItemId,o=e.items.get(n);if(!o)throw new d(`Primary item ${n} is not described by iinf`,{brand:e.majorBrand,itemId:n});let i=o.itemType==="grid";if(!i&&o.itemType!=="hvc1"&&o.itemType!=="hev1")throw new w(`Primary item type '${o.itemType}' is not a supported image item`,[],{brand:e.majorBrand,itemType:o.itemType,itemId:n});let s=T(e,n),a=[],c,p;if(i){let h=Y(e,n,r);c=h.outputWidth,p=h.outputHeight;let B=T(e,h.tileItemIds[0]),P=C(B,"ispe");if(!P)throw new d(`Grid tile ${h.tileItemIds[0]} has no ispe`,{itemId:h.tileItemIds[0]});for(let[H,$]of h.tileItemIds.entries()){let E=C(T(e,$),"ispe")??P;a.push({itemId:$,x:H%h.columns*P.width,y:Math.floor(H/h.columns)*P.height,width:E.width,height:E.height})}}else{let h=C(s,"ispe");if(!h)throw new d(`Primary item ${n} has no ispe`,{itemId:n});c=h.width,p=h.height,a.push({itemId:n,x:0,y:0,width:h.width,height:h.height})}if(c<=0||p<=0)throw new d(`Implausible image dimensions ${c}x${p}`,{itemId:n});if(c*p>Ae)throw new w(`Image is ${c}x${p}, above the ${Ae}-pixel limit`,[],{itemId:n});let u=ft(e,a,r),m=ut(s,c,p),{displayWidth:f,displayHeight:l}=mt(c,p,m),b=C(s,"pixi")?.bitsPerChannel[0]??de(u[0].hvcc);return ht(e,n,r),{file:e,primaryItemId:n,isGrid:i,codedWidth:c,codedHeight:p,displayWidth:f,displayHeight:l,tiles:a,tileGroups:u,transforms:m,bitDepth:b,sourceColor:lt(s,T(e,a[0].itemId)),warnings:r}}function ft(t,e,r){let n=new Map;for(let[i,s]of e.entries()){let c=(t.itemProperties.associations.get(s.itemId)??[]).find(u=>t.itemProperties.properties[u.index-1]?.type==="hvcC");if(!c)throw new d(`Item ${s.itemId} has no hvcC property`,{itemId:s.itemId});let p=n.get(c.index);if(!p){let u=t.itemProperties.properties[c.index-1];if(u?.type!=="hvcC")throw new d(`Property ${c.index} is not an hvcC`,{itemId:s.itemId});p={configIndex:c.index,hvcc:u.hvcc,codec:U(u.hvcc),tileIndices:[]},n.set(c.index,p)}p.tileIndices.push(i)}let o=[...n.values()];if(o.length===0)throw new d("No decoder configuration found for any tile",{});return o.length>1&&r.push({code:"mixed-tile-configs",message:`Tiles use ${o.length} different decoder configurations; decoding in ${o.length} groups`}),o}function ut(t,e,r){let n=[],o=e,i=r;for(let s of t)switch(s.type){case"clap":{let a=dt(s,o,i);a&&(n.push(a),o=a.width,i=a.height);break}case"irot":s.angle!==0&&(n.push({kind:"rotate",angle:s.angle}),(s.angle===90||s.angle===270)&&([o,i]=[i,o]));break;case"imir":n.push({kind:"mirror",axis:s.axis});break;default:break}return n}function dt(t,e,r){if(t.widthD===0||t.heightD===0||t.horizOffD===0||t.vertOffD===0)return;let n=Math.round(t.widthN/t.widthD),o=Math.round(t.heightN/t.heightD),i=t.horizOffN/t.horizOffD,s=t.vertOffN/t.vertOffD,a=Math.round((e-n)/2+i),c=Math.round((r-o)/2+s);if(!(n<=0||o<=0)&&!(n===e&&o===r&&a===0&&c===0)&&!(a<0||c<0||a+n>e||c+o>r))return{kind:"crop",width:n,height:o,offsetX:a,offsetY:c}}function mt(t,e,r){let n=t,o=e;for(let i of r)i.kind==="crop"?(n=i.width,o=i.height):i.kind==="rotate"&&(i.angle===90||i.angle===270)&&([n,o]=[o,n]);return{displayWidth:n,displayHeight:o}}function lt(t,e){let r=C(t,"colr")??C(e,"colr");return r?r.colorType==="nclx"?{type:"nclx",primaries:r.primaries,transfer:r.transfer,matrix:r.matrix,fullRange:r.fullRange}:{type:"icc",profile:r.profile}:null}function ht(t,e,r){let n=new Set,o=s=>{n.has(s.code)||(n.add(s.code),r.push(s))},i=t.references.get("auxl");if(i)for(let[s,a]of i){if(!a.includes(e))continue;let c=C(T(t,s),"auxC")?.auxType??"";/alpha/i.test(c)?o({code:"alpha-ignored",message:`Alpha aux image ${s} ignored`}):/depth|disparity/i.test(c)?o({code:"depth-ignored",message:`Depth aux image ${s} ignored`}):/hdrgainmap|gainmap/i.test(c)&&o({code:"gain-map-ignored",message:`HDR gain map ${s} ignored; the image decodes as SDR`})}for(let s of t.items.values())if(s.itemType==="tmap"){o({code:"gain-map-ignored",message:`Tone-map item ${s.itemId} ignored; the image decodes as SDR`});break}}function be(t,e){return k(t.file,e.itemId)}function F(){return typeof VideoDecoder<"u"&&typeof EncodedVideoChunk<"u"}async function gt(t,e,r){let n=t.hvcc.lengthSizeMinusOne+1,o=[],i={codec:t.codec,description:new Uint8Array(t.hvcc.raw),codedWidth:e,codedHeight:r,optimizeForLatency:!0};try{let a=await VideoDecoder.isConfigSupported(i);if(a.supported)return{mode:"hvc1",config:a.config??i,lengthSize:n};o.push({strategy:"hvc1",reason:"isConfigSupported returned false"})}catch(a){o.push({strategy:"hvc1",reason:String(a)})}let s={codec:U(t.hvcc,"hev1"),codedWidth:e,codedHeight:r,optimizeForLatency:!0};try{let a=await VideoDecoder.isConfigSupported(s);if(a.supported)return{mode:"hev1",config:a.config??s,prologue:V(t.hvcc),lengthSize:n};o.push({strategy:"hev1",reason:"isConfigSupported returned false"})}catch(a){o.push({strategy:"hev1",reason:String(a)})}throw new w("No HEVC decoder configuration was accepted",o,{strategy:"webcodecs",codec:t.codec})}function yt(t,e){if(t.mode==="hvc1")return e;let r=q(e,t.lengthSize),n=t.prologue,o=new Uint8Array(n.byteLength+r.byteLength);return o.set(n,0),o.set(r,n.byteLength),o}async function xe(t,e,r){if(!F())throw new w("WebCodecs VideoDecoder is not available in this environment",[{strategy:"webcodecs",reason:"VideoDecoder is undefined"}],{strategy:"webcodecs"});A(r);let n=D(t.codedWidth,t.codedHeight),o=n.getContext("2d",{colorSpace:e,alpha:!1,willReadFrequently:!1});if(!o)throw new y("Could not get a 2d context for compositing",{strategy:"webcodecs"});for(let i of t.tileGroups)A(r),await At(t,i,o,r);return n}async function At(t,e,r,n){let o=t.tiles[e.tileIndices[0]],i=await gt(e,o.width,o.height);A(n);let s=0,a=0,c,p=new Promise((f,l)=>{c=l}),u=new VideoDecoder({output:f=>{try{let l=t.tiles[e.tileIndices[s++]];l&&(r.drawImage(f,l.x,l.y,l.width,l.height),a++)}finally{f.close()}},error:f=>{c?.(new y(`VideoDecoder failed: ${f.message}`,{strategy:"webcodecs",codec:i.config.codec}))}}),m=()=>c?.(new I);n?.addEventListener("abort",m,{once:!0});try{try{u.configure(i.config);for(let f of e.tileIndices){let l=t.tiles[f],g=yt(i,be(t,l));u.decode(new EncodedVideoChunk({type:"key",timestamp:f,duration:0,data:g}))}}catch(f){throw f instanceof I||f instanceof y?f:new y(`VideoDecoder rejected the stream: ${f instanceof Error?f.message:String(f)}`,{strategy:"webcodecs",codec:i.config.codec},{cause:f})}if(await Promise.race([u.flush(),p]),a!==e.tileIndices.length)throw new y(`Decoder emitted ${a} frames for ${e.tileIndices.length} tiles`,{strategy:"webcodecs",codec:i.config.codec})}finally{n?.removeEventListener("abort",m);try{u.close()}catch{}}}var bt=["hvc1.3.e.L93.B0","hvc1.1.6.L93.B0","hvc1.2.4.L120.B0"];async function we(){if(!F())return[];let t=[];for(let e of bt)try{(await VideoDecoder.isConfigSupported({codec:e,codedWidth:1920,codedHeight:1080})).supported&&t.push(e)}catch{}return t}var xt=new Set(["heic","heix","hevc","hevx","heim","heis","hevm","hevs","mif1","msf1"]),wt=new Set(["heic","heix","hevc","hevx","heim","heis","hevm","hevs"]),Ie=65536;function ve(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),r,n;try{let c=M(new O(e),{lenient:!0}),p=x(c,"ftyp");if(!p)return{isHeic:!1};for(n=p.body.fourCC(),r=new Set([n]),p.body.u32();p.body.remaining>=4;)r.add(p.body.fourCC())}catch{return{isHeic:!1}}if(![...r].some(c=>xt.has(c)))return{isHeic:!1,brand:n};let o;try{o=N(e,{truncated:!0})}catch{o=void 0}let i=o?.items.get(o.primaryItemId)?.itemType,s=o?Ce(o,i):"unknown";if(s==="av1")return{isHeic:!1,brand:n,primaryItemType:i,coding:s};if(s==="hevc")return{isHeic:!0,brand:n,primaryItemType:i,coding:s};let a={isHeic:[...r].some(c=>wt.has(c)),brand:n,coding:"unknown"};return i!==void 0&&(a.primaryItemType=i),a}function Ce(t,e,r=0){if(e==="hvc1"||e==="hev1")return"hevc";if(e==="av01")return"av1";if(r<4&&(e==="grid"||e==="iovl"||e==="iden")){let n=t.references.get("dimg")?.get(t.primaryItemId)?.[0];if(n!==void 0)return Ce(t,t.items.get(n)?.itemType,r+1)}return"unknown"}function J(t,e,r){let n=t;for(let o of e)switch(o.kind){case"crop":n=oe(n,It(n,o,r),t);break;case"rotate":n=oe(n,vt(n,o.angle,r),t);break;case"mirror":n=oe(n,Ct(n,o.axis,r),t);break}return{canvas:n,applied:K(e)}}function K(t){let e={rotation:0,mirrored:"none",cropped:!1};for(let r of t)switch(r.kind){case"crop":e.cropped=!0;break;case"rotate":e.rotation=(e.rotation+r.angle)%360;break;case"mirror":{let n=Pe(r.axis);e.mirrored==="none"?e.mirrored=n:e.mirrored===n?e.mirrored="none":(e.mirrored="none",e.rotation=(e.rotation+180)%360);break}}return e}function Pe(t){return t===0?"vertical":"horizontal"}function It(t,e,r){let n=D(e.width,e.height);return ie(n,r).drawImage(t,e.offsetX,e.offsetY,e.width,e.height,0,0,e.width,e.height),n}function vt(t,e,r){let n=e===90||e===270,o=D(n?t.height:t.width,n?t.width:t.height),i=ie(o,r);return i.translate(o.width/2,o.height/2),i.rotate(-e*Math.PI/180),i.drawImage(t,-t.width/2,-t.height/2),o}function Ct(t,e,r){let n=D(t.width,t.height),o=ie(n,r);return Pe(e)==="horizontal"?(o.translate(t.width,0),o.scale(-1,1)):(o.translate(0,t.height),o.scale(1,-1)),o.drawImage(t,0,0),n}function ie(t,e){let r=t.getContext("2d",{colorSpace:e,alpha:!1});if(!r)throw new Error("Could not get a 2d context");return r}function oe(t,e,r){return t!==r&&(t.width=0,t.height=0),e}async function Te(){let[t,e]=await Promise.all([ue(),we()]),r=F()&&e.length>0;return{native:t,webcodecs:r,hevcCodecStrings:e,recommended:t?"native":r?"webcodecs":"wasm"}}async function Pt(t){let e=await Dt(t,Ie),r=ve(e),n={isHeic:r.isHeic};return r.brand!==void 0&&(n.brand=r.brand),r.primaryItemType!==void 0&&(n.primaryItemType=r.primaryItemType),r.coding!==void 0&&(n.coding=r.coding),n}async function De(t,e={}){let{strategy:r="auto",colorSpace:n="srgb",maxDimension:o,signal:i,wasmLoader:s}=e;A(i);let a=await Se(t);A(i);let c=Z(a);A(i);let p=[],u=m=>r==="auto"||r===m;if(u("native")){let m=t instanceof Blob?t:X(a),f=await fe(m,c,i);if(f.status==="ok"){let l=await He(f.bitmap,o,i);return se(c,l,"native",K(c.transforms))}p.push({strategy:"native",reason:f.reason})}if(u("webcodecs"))if(!F())p.push({strategy:"webcodecs",reason:"VideoDecoder is not available"});else try{let m=await xe(c,n,i),{canvas:f,applied:l}=J(m,c.transforms,n),g=await Be(f,o,i);return se(c,g,"webcodecs",l)}catch(m){if(m instanceof I||r==="webcodecs")throw m;p.push({strategy:"webcodecs",reason:Ee(m)})}if(u("wasm")){let m=await Et(s);if(!m)p.push({strategy:"wasm",reason:"no adapter: pass options.wasmLoader or call registerDecoderAdapter()"});else try{let f=await m.decode({data:a,colorSpace:n,signal:i}),l=K(c.transforms),g;if(f.image instanceof ImageBitmap){let b=m.appliesTransforms?f.image:await St(f.image,c,n);g=await He(b,o,i)}else{let b=m.appliesTransforms?f.image:J(f.image,c.transforms,n).canvas;g=await Be(b,o,i)}return se(c,g,"wasm",l)}catch(f){if(f instanceof I||r==="wasm")throw f;p.push({strategy:"wasm",reason:Ee(f)})}}throw new w("Could not decode this HEIC",p,{brand:c.file.majorBrand,itemType:c.file.items.get(c.primaryItemId)?.itemType,itemId:c.primaryItemId})}async function Tt(t,e={}){let{type:r="image/jpeg",quality:n=.92,...o}=e;if(r!=="image/jpeg"&&r!=="image/png")throw new TypeError("type must be image/jpeg or image/png");if(!Number.isFinite(n)||n<0||n>1)throw new RangeError("quality must be a finite number between 0 and 1");let i=await De(t,o),s;try{A(e.signal),s=D(i.width,i.height);let a=s.getContext("2d",{colorSpace:e.colorSpace??"srgb",alpha:!1});if(!a)throw new y("Could not get a 2d context for conversion",{});a.drawImage(i.image,0,0);let c=await s.convertToBlob({type:r,quality:n});if(A(e.signal),c.type!==r||c.size===0)throw new y(`Browser could not encode ${r}`,{});let{image:p,...u}=i;return{...u,blob:c}}finally{i.image.close(),s&&(s.width=0,s.height=0)}}var ee;function Bt(t){ee=t}function Ht(){return ee}async function Et(t){if(ee)return ee;if(t)return t()}async function Se(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(await t.arrayBuffer())}async function Dt(t,e){return t instanceof Blob?new Uint8Array(await t.slice(0,e).arrayBuffer()):(await Se(t)).subarray(0,e)}function Oe(t,e,r){if(!r||r<=0)return 1;let n=Math.max(t,e);return n<=r?1:r/n}async function Be(t,e,r){A(r);let n=Oe(t.width,t.height,e);if(n===1)return t.transferToImageBitmap();let o=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n));try{return await createImageBitmap(t,{resizeWidth:o,resizeHeight:i,resizeQuality:"high"})}finally{t.width=0,t.height=0}}async function He(t,e,r){A(r);let n=Oe(t.width,t.height,e);if(n===1)return t;let o=await createImageBitmap(t,{resizeWidth:Math.max(1,Math.round(t.width*n)),resizeHeight:Math.max(1,Math.round(t.height*n)),resizeQuality:"high"});return t.close(),o}async function St(t,e,r){if(e.transforms.length===0)return t;let n=D(t.width,t.height),o=n.getContext("2d",{colorSpace:r,alpha:!1});if(!o)return t;o.drawImage(t,0,0),t.close();let{canvas:i}=J(n,e.transforms,r);return i.transferToImageBitmap()}function se(t,e,r,n){return{image:e,width:e.width,height:e.height,sourceWidth:t.displayWidth,sourceHeight:t.displayHeight,strategy:r,bitDepth:t.bitDepth,isGrid:t.isGrid,tileCount:t.tiles.length,sourceColor:t.sourceColor,transformsApplied:n,warnings:t.warnings}}function Ee(t){return t instanceof Error?t.message:String(t)}return Fe(Ot);})();
|
|
2
2
|
//# sourceMappingURL=heic.global.js.map
|