import {
createPanoramaRenderer,
PANO_FOV_DEFAULT_DEG,
wrapDegrees,
} from './panorama.js';
import { imageSize } from './imageSize.js';
import { msg, t } from '../../i18n/index.js';
/**
* EXPAND puts the viewer's wrap full screen, or (iPhone) opens it as a
* popover. Each is tried on its own: a browser that cannot parse one
* (Safari before 16.4) throws on the selector.
*/
const EXPANDED_SELECTORS = [
'.sl-viewer-wrap:fullscreen',
'.sl-viewer-wrap:popover-open',
];
/** A photo download (tens of kilobytes to a few megabytes). */
const IMAGE_TIMEOUT_MS = 15_000;
/** A picture file or decoded side past these is refused (a photo is a few MB). */
export const MAX_IMAGE_BYTES = 48 * 1024 * 1024;
export const MAX_IMAGE_SIDE = 16_384;
/** 64 MP: 256 MB once decoded to RGBA. A 16,384 px square is four times that. */
const MAX_IMAGE_PIXELS = 8_192 * 8_192;
/** Where in a file to look for its dimensions (a JPEG's EXIF comes first). */
const HEADER_BYTES = 256 * 1024;
/** Whether a picture this size is past what the viewer decodes. */
function tooManyPixels(width, height) {
return (
width > MAX_IMAGE_SIDE ||
height > MAX_IMAGE_SIDE ||
width * height > MAX_IMAGE_PIXELS
);
}
/** Panorama texture widths: enough for a docked viewer, and for an expanded one. */
const PANO_MID_SIZE = Object.freeze([2048, 1024]);
export const PANO_FULL_SIZE = Object.freeze([4096, 2048]);
/**
* Load an image within the timeout. A CORS-clean one (for WebGL) is decoded
* off the main thread into an ImageBitmap where the browser can: uploading
* a decoded bitmap costs a fraction of uploading an (90 ms → 15 ms for
* 4096×2048 on a phone-class CPU). `resize` shrinks a bitmap while decoding
* it (a panorama larger than any texture the viewer uploads).
* @param {string} url
* @param {{crossOrigin?: boolean, timeoutMs?: number, resize?: [number, number]|null, failure?: string}} [options]
*/
export function loadImage(
url,
{
crossOrigin = true,
timeoutMs = IMAGE_TIMEOUT_MS,
resize = null,
failure = msg('The photo could not be loaded'),
signal = null,
} = {},
) {
if (
crossOrigin &&
url &&
typeof globalThis.createImageBitmap === 'function' &&
typeof globalThis.fetch === 'function'
)
return loadBitmap(url, timeoutMs, resize, failure, signal);
return new Promise((resolve, reject) => {
if (!url) return reject(new Error(failure));
if (signal?.aborted) return reject(new Error(failure));
const image = new Image();
if (crossOrigin) image.crossOrigin = 'anonymous';
image.decoding = 'async';
// Stop the download: another photo opened, or the time ran out.
const stop = () => {
clearTimeout(timer);
signal?.removeEventListener?.('abort', stop);
image.onload = image.onerror = null;
image.src = '';
reject(new Error(failure));
};
const timer = setTimeout(stop, timeoutMs);
signal?.addEventListener?.('abort', stop, { once: true });
const settle = () => {
clearTimeout(timer);
signal?.removeEventListener?.('abort', stop);
};
image.onload = () => {
settle();
// An reads no header first: refuse what it decoded too large.
if (tooManyPixels(image.naturalWidth || 0, image.naturalHeight || 0)) {
image.src = '';
reject(oversized(failure));
return;
}
resolve(image);
};
image.onerror = () => {
settle();
reject(new Error(failure));
};
image.src = url;
});
}
async function loadBitmap(url, timeoutMs, resize, failure, signal) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
// The caller's abort (the photo changed) stops a multi-megabyte download.
const onAbort = () => controller.abort();
if (signal?.aborted) controller.abort();
signal?.addEventListener?.('abort', onAbort, { once: true });
try {
const response = await fetch(url, {
mode: 'cors',
signal: controller.signal,
});
if (!response.ok) throw new Error(failure);
// Picture hosts are not ours: refuse a file or an image past any real
// photo's size before it is decoded.
const length = Number(response.headers?.get?.('content-length'));
if (length > MAX_IMAGE_BYTES) throw oversized(failure);
const blob = await boundedBlob(response, failure);
// Its declared size, before anything decodes it.
const size = imageSize(
new Uint8Array(await blob.slice(0, HEADER_BYTES).arrayBuffer()),
);
if (size && tooManyPixels(size.width, size.height))
throw oversized(failure);
const bitmap = await (resize
? createImageBitmap(blob, {
resizeWidth: resize[0],
resizeHeight: resize[1],
resizeQuality: 'high',
})
: createImageBitmap(blob));
// (A resized decode reports its new size: this guards unresized ones.)
if (tooManyPixels(bitmap.width, bitmap.height)) {
bitmap.close?.();
throw oversized(failure);
}
return bitmap;
} catch (error) {
// A size refusal stays one: the viewer must not fetch it another way.
if (error?.tooLarge) throw error;
throw new Error(failure);
} finally {
clearTimeout(timer);
signal?.removeEventListener?.('abort', onAbort);
}
}
/**
* A picture refused for its size (`tooLarge`): the viewer will not load
* that file another way, an having no size limit at all.
*/
function oversized(failure) {
return Object.assign(new Error(failure), { tooLarge: true });
}
/**
* The body as a Blob, read with a running count so a host that sends no
* length (or a false one) cannot fill memory before the cap is checked.
*/
async function boundedBlob(response, failure) {
const reader = response.body?.getReader?.();
if (!reader) {
const blob = await response.blob();
if (blob.size > MAX_IMAGE_BYTES) throw oversized(failure);
return blob;
}
const chunks = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > MAX_IMAGE_BYTES) {
reader.cancel().catch(() => {});
throw oversized(failure);
}
chunks.push(value);
}
return new Blob(chunks, {
type: response.headers?.get?.('content-type') || 'image/jpeg',
});
}
/** The panorama size a canvas this wide can show sharply at this field of view. */
export function panoSizeFor(canvasPixels, fovDeg) {
const needed = (Math.max(1, canvasPixels) * 360) / Math.max(1, fovDeg);
return needed > PANO_MID_SIZE[0] ? PANO_FULL_SIZE : PANO_MID_SIZE;
}
/**
* @typedef {object} PhotoSources Where a provider's photo comes from.
* @property {(photo: object) => boolean} hasPano A 360° photo with an equirectangular image.
* @property {(photo: object) => {url: string, width: number, resize?: [number, number]|null}|null} panoFirst
* The panorama shown first, its texture width (0 when it is only a preview), and a size to shrink it to.
* @property {(photo: object, size: [number, number], view: {expanded: boolean}) => {url: string, resize?: [number, number]|null, timeoutMs?: number}|null} panoSharp
* A sharper panorama for a canvas that needs `size`, or null; `expanded` while the viewer is.
* @property {(photo: object, view: {expanded: boolean}) => Array} flatFirst Flat versions to try in turn (`expanded` while the viewer is).
* @property {(photo: object, pixels: number) => string|null} flatSharp
* A sharper flat version for a picture this many device pixels wide, or null.
* @property {(photo: object) => {title?: string|null, creator?: string|null, license?: string|null, externalUrl: string, capturedAtPrecision?: 'day'|'month'}} describe
* @property {(photo: object) => number|null} [bearingOf] Where the camera looked (default `photo.heading`).
*/
/**
* Viewer adapter for providers whose photos are plain image files: a flat
* photo in an , a 360° photo on a WebGL panorama (drag to look, wheel
* or pinch to zoom), and ‹ › to step along the sequence (also ← →). Poses
* follow the view direction.
*
* Photos are normalized by the provider: `{id, sequenceId, lon, lat,
* heading, isPano, capturedAt}` plus whatever its `sources` read.
*
* @param {object} options
* @param {string} options.providerId
* @param {string} options.name Provider name for labels and messages, e.g. 'KartaView'.
* @param {PhotoSources} options.sources
* @param {(photoId: string) => Promise