/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import e from"../../../core/Error.js";import{isAborted as t,createAbortError as n,isAbortError as a}from"../../../core/promiseUtils.js";import{F as r}from"../../../chunks/Zlib.js";async function i(r,i,h){if(!r||r.byteLength<10)throw new e("imagecanvasdecoder: decode","required a valid encoded data as input.");const{width:s,height:g,format:w}=i,{applyJpegMask:f}=i;if(f&&(!s||!g))throw new e("imagecanvasdecoder: decode","image width and height are needed to apply jpeg mask directly to canvas");let u=null;"jpg"===w&&f&&s&&g&&(u=l(r,{width:s,height:g}));try{const e=new Blob([new Uint8Array(r)],{type:d(w)}),a=await createImageBitmap(e);if(t(h))throw n();const{tileIndex:l,tileSize:s}=i;return null!=l&&null!=s?c(a,l,s):o(a,u)}catch(m){if(a(m))throw m;throw new e("imagecanvasdecoder: decode","cannot load image")}}function o(t,n){const{width:a,height:r}=t,i=new OffscreenCanvas(a,r),o=i.getContext("2d");if(!o)throw new e("imagecanvasdecoder: decode","cannot create canvas context");o.drawImage(t,0,0,a,r);const c=h(o.getImageData(0,0,a,r),a,r,n);return i.width=0,i.height=0,c}function c(t,n,a){const[r,i,o]=n,[c,d]=a,l=Math.ceil(t.width/2**r),s=Math.ceil(t.height/2**r),g=Math.ceil(s/d),w=Math.ceil(l/c);if(i>=g||o>=w)return null;const f=new OffscreenCanvas(l,s),u=f.getContext("2d");if(!u)throw new e("imagecanvasdecoder: decode","cannot create canvas context");u.drawImage(t,0,0,l,s);const m=o*c,p=i*d,y=Math.min(c,l-m),v=Math.min(d,s-p),x=h(u.getImageData(m,p,y,v),c,d);return f.width=0,f.height=0,x}function h(e,t,n,a){const r=t*n,i=new Uint8Array(r),o=new Uint8Array(r),c=new Uint8Array(r),h=null==a;a||(a=new Uint8Array(r));const d={width:t,height:n,pixels:[i,o,c],mask:a,pixelType:"u8"},{width:l,height:s,data:g}=e;if(l===t&&s===n){for(let e=0,t=0;e<r;e++,t+=4)i[e]=g[t],o[e]=g[t+1],c[e]=g[t+2],h&&(a[e]=g[t+3]);return d}for(let w=0;w<s;w++){const e=w*l*4;for(let n=0;n<l;n++){const r=w*t+n;i[r]=g[e+4*n],o[r]=g[e+4*n+1],c[r]=g[e+4*n+2],h&&(a[r]=g[e+4*n+3])}}return d}function d(e){return`image/${"jpg"===e?"jpeg":e}`}function l(e,t){try{const n=new Uint8Array(e);let a=Math.ceil(n.length/2);const i=n.length-2;for(;a<i&&(255!==n[a]||217!==n[a+1]);a++);a+=2;let o=null;if(a<n.length-1){const e=new r(n.subarray(a)).getBytes();o=new Uint8Array(t.width*t.height);let i=0;for(let t=0;t<e.length;t++)for(let n=7;n>=0;n--)o[i++]=e[t]>>n&1}return o}catch{return null}}export{i as decode};
