import type { PhotoRecord } from '../types'; import { getBitmap } from './images'; export type MergeKind = 'hdr' | 'panorama' | 'focus'; export interface MergeResult { blob: Blob; width: number; height: number; thumb: string; kind: MergeKind; sourceIds: string[]; } interface Layer { canvas: HTMLCanvasElement; pixels: Uint8ClampedArray; gray: Uint8Array; grayW: number; grayH: number; dx: number; dy: number; } const MAX_EDGE = 2600; function scaledCanvas(bitmap: ImageBitmap): HTMLCanvasElement { const scale = Math.min(1, MAX_EDGE / Math.max(bitmap.width, bitmap.height)); const canvas = document.createElement('canvas'); canvas.width = Math.max(1, Math.round(bitmap.width * scale)); canvas.height = Math.max(1, Math.round(bitmap.height * scale)); const ctx = canvas.getContext('2d', { willReadFrequently: true }); if (!ctx) throw new Error('Could not create a merge canvas'); ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height); return canvas; } function readPixels(canvas: HTMLCanvasElement) { const ctx = canvas.getContext('2d', { willReadFrequently: true }); if (!ctx) throw new Error('Could not read the merge pixels'); return ctx.getImageData(0, 0, canvas.width, canvas.height); } function grayFrom(pixels: Uint8ClampedArray, width: number, height: number, maxW = 360) { const scale = Math.min(1, maxW / width); const w = Math.max(1, Math.round(width * scale)); const h = Math.max(1, Math.round(height * scale)); const out = new Uint8Array(w * h); for (let y = 0; y < h; y++) { const sy = Math.min(height - 1, Math.round((y / h) * height)); for (let x = 0; x < w; x++) { const sx = Math.min(width - 1, Math.round((x / w) * width)); const o = (sy * width + sx) * 4; out[y * w + x] = Math.round(0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]); } } return { data: out, w, h }; } /** Translation-only alignment is enough for bracketed and focus-stacked frames. */ function align(ref: Layer, layer: Layer, maxShift = 36) { const { data: a, w, h } = { data: ref.gray, w: ref.grayW, h: ref.grayH }; let best = { dx: 0, dy: 0, score: Number.POSITIVE_INFINITY }; for (let dy = -maxShift; dy <= maxShift; dy += 2) { for (let dx = -maxShift; dx <= maxShift; dx += 2) { let score = 0; let n = 0; for (let y = maxShift; y < h - maxShift; y += 4) { for (let x = maxShift; x < w - maxShift; x += 4) { const bx = x + Math.round((dx / maxShift) * maxShift); const by = y + Math.round((dy / maxShift) * maxShift); if (bx < 0 || by < 0 || bx >= w || by >= h) continue; score += Math.abs(a[y * w + x] - layer.gray[by * w + bx]); n++; } } if (n && score / n < best.score) best = { dx, dy, score: score / n }; } } return best; } function luma(pixels: Uint8ClampedArray, o: number) { return (0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]) / 255; } /** * Exposure blending. Each frame contributes more where it is mid-toned, so a * blown highlight in the bright frame does not wash out the dark frame, and a * noisy shadow does not dominate the final image. */ function mergeHdr(layers: Layer[]) { const width = Math.min(...layers.map((l) => l.canvas.width)); const height = Math.min(...layers.map((l) => l.canvas.height)); const out = new Uint8ClampedArray(width * height * 4); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let r = 0; let g = 0; let b = 0; let total = 0; for (const layer of layers) { const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx)); const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy)); const o = (sy * layer.canvas.width + sx) * 4; const l = luma(layer.pixels, o); const weight = Math.max(0.03, 1 - Math.abs(l - 0.46) * 1.75); r += layer.pixels[o] * weight; g += layer.pixels[o + 1] * weight; b += layer.pixels[o + 2] * weight; total += weight; } const o = (y * width + x) * 4; out[o] = r / total; out[o + 1] = g / total; out[o + 2] = b / total; out[o + 3] = 255; } } return out; } function sharpness(pixels: Uint8ClampedArray, width: number, x: number, y: number) { if (x < 1 || y < 1 || x >= width - 1) return 0; const o = (y * width + x) * 4; const l = luma(pixels, o); const lx = luma(pixels, o - 4); const rx = luma(pixels, o + 4); const ty = luma(pixels, o - width * 4); const by = luma(pixels, o + width * 4); return Math.abs(l * 4 - lx - rx - ty - by); } /** Pick the locally sharpest source pixel, then feather the decision with a 3×3 vote. */ function mergeFocus(layers: Layer[]) { const width = Math.min(...layers.map((l) => l.canvas.width)); const height = Math.min(...layers.map((l) => l.canvas.height)); const out = new Uint8ClampedArray(width * height * 4); const picks = new Uint8Array(width * height); for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let best = 0; let bestScore = -1; for (let i = 0; i < layers.length; i++) { const layer = layers[i]; const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx)); const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy)); const score = sharpness(layer.pixels, layer.canvas.width, sx, sy); if (score > bestScore) { bestScore = score; best = i; } } picks[y * width + x] = best; } } for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const votes = new Map(); for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const px = Math.min(width - 1, Math.max(0, x + dx)); const py = Math.min(height - 1, Math.max(0, y + dy)); const pick = picks[py * width + px]; votes.set(pick, (votes.get(pick) ?? 0) + 1); } } let best = picks[y * width + x]; let bestVotes = 0; for (const [pick, count] of votes) { if (count > bestVotes) { best = pick; bestVotes = count; } } const layer = layers[best]; const sx = Math.min(layer.canvas.width - 1, Math.max(0, x + layer.dx)); const sy = Math.min(layer.canvas.height - 1, Math.max(0, y + layer.dy)); const so = (sy * layer.canvas.width + sx) * 4; const o = (y * width + x) * 4; out[o] = layer.pixels[so]; out[o + 1] = layer.pixels[so + 1]; out[o + 2] = layer.pixels[so + 2]; out[o + 3] = 255; } } return out; } function panoramaOffset(left: Layer, right: Layer) { const w = Math.min(left.grayW, right.grayW); const h = Math.min(left.grayH, right.grayH); const minOverlap = Math.round(w * 0.12); const maxOverlap = Math.round(w * 0.72); let best = { overlap: Math.round(w * 0.35), dy: 0, score: Number.POSITIVE_INFINITY }; for (let dy = -8; dy <= 8; dy += 2) { for (let overlap = minOverlap; overlap <= maxOverlap; overlap += 3) { let score = 0; let n = 0; for (let y = 6; y < h - 6; y += 5) { for (let x = w - overlap; x < w - 2; x += 4) { const ry = y + dy; if (ry < 0 || ry >= h) continue; score += Math.abs(left.gray[y * w + x] - right.gray[ry * w + (x - (w - overlap))]); n++; } } if (n && score / n < best.score) best = { overlap, dy, score: score / n }; } } return best; } function mergePanorama(layers: Layer[]) { const overlaps: number[] = []; const dys: number[] = []; for (let i = 1; i < layers.length; i++) { const match = panoramaOffset(layers[i - 1], layers[i]); overlaps.push(Math.round((match.overlap / Math.max(1, layers[i - 1].grayW)) * layers[i - 1].canvas.width)); dys.push(Math.round((match.dy / Math.max(1, layers[i - 1].grayH)) * layers[i - 1].canvas.height)); } const xs = [0]; for (let i = 1; i < layers.length; i++) xs.push(xs[i - 1] + layers[i - 1].canvas.width - overlaps[i - 1]); const width = Math.max(...xs.map((x, i) => x + layers[i].canvas.width)); const height = Math.max(...layers.map((l) => l.canvas.height)); const acc = new Float32Array(width * height * 3); const weight = new Float32Array(width * height); layers.forEach((layer, i) => { const x0 = xs[i]; const y0 = Math.round((height - layer.canvas.height) / 2 + (i ? dys[i - 1] : 0)); for (let y = 0; y < layer.canvas.height; y++) { const oy = y + y0; if (oy < 0 || oy >= height) continue; for (let x = 0; x < layer.canvas.width; x++) { const ox = x + x0; if (ox < 0 || ox >= width) continue; const o = (y * layer.canvas.width + x) * 4; const target = oy * width + ox; const edge = Math.min(1, Math.min(x, layer.canvas.width - 1 - x) / Math.max(1, layer.canvas.width * 0.08)); const w = 0.15 + edge * 0.85; acc[target * 3] += layer.pixels[o] * w; acc[target * 3 + 1] += layer.pixels[o + 1] * w; acc[target * 3 + 2] += layer.pixels[o + 2] * w; weight[target] += w; } } }); const out = new Uint8ClampedArray(width * height * 4); for (let i = 0; i < width * height; i++) { const w = weight[i] || 1; out[i * 4] = acc[i * 3] / w; out[i * 4 + 1] = acc[i * 3 + 1] / w; out[i * 4 + 2] = acc[i * 3 + 2] / w; out[i * 4 + 3] = 255; } return { pixels: out, width, height }; } function canvasFromPixels(pixels: Uint8ClampedArray, width: number, height: number) { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('Could not build the merged image'); const image = ctx.createImageData(width, height); image.data.set(pixels); ctx.putImageData(image, 0, 0); return canvas; } function thumbFrom(canvas: HTMLCanvasElement) { const thumb = document.createElement('canvas'); const scale = 480 / Math.max(canvas.width, canvas.height); thumb.width = Math.max(1, Math.round(canvas.width * scale)); thumb.height = Math.max(1, Math.round(canvas.height * scale)); thumb.getContext('2d')?.drawImage(canvas, 0, 0, thumb.width, thumb.height); return thumb.toDataURL('image/jpeg', 0.82); } export async function mergePhotos( photos: PhotoRecord[], kind: MergeKind, onProgress?: (done: number, total: number) => void, ): Promise { if (photos.length < 2) throw new Error('Select at least two photos to merge'); const layers: Layer[] = []; for (let i = 0; i < photos.length; i++) { onProgress?.(i, photos.length); const bitmap = await getBitmap(photos[i]); const canvas = scaledCanvas(bitmap); const image = readPixels(canvas); const gray = grayFrom(image.data, canvas.width, canvas.height); layers.push({ canvas, pixels: image.data, gray: gray.data, grayW: gray.w, grayH: gray.h, dx: 0, dy: 0, }); } onProgress?.(photos.length, photos.length); if (kind === 'panorama') { const merged = mergePanorama(layers); const canvas = canvasFromPixels(merged.pixels, merged.width, merged.height); const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.94)); if (!blob) throw new Error('Could not encode the panorama'); return { blob, width: merged.width, height: merged.height, thumb: thumbFrom(canvas), kind, sourceIds: photos.map((p) => p.id) }; } const progress = (n: number) => onProgress?.(Math.min(photos.length, photos.length - 1 + n / 10), photos.length); const ref = layers[0]; for (let i = 1; i < layers.length; i++) { const match = align(ref, layers[i]); layers[i].dx = Math.round((match.dx / Math.max(1, ref.grayW)) * ref.canvas.width); layers[i].dy = Math.round((match.dy / Math.max(1, ref.grayH)) * ref.canvas.height); progress(i); } const width = Math.min(...layers.map((l) => l.canvas.width)); const height = Math.min(...layers.map((l) => l.canvas.height)); const pixels = kind === 'hdr' ? mergeHdr(layers) : mergeFocus(layers); const canvas = canvasFromPixels(pixels, width, height); const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.94)); if (!blob) throw new Error('Could not encode the merged image'); return { blob, width, height, thumb: thumbFrom(canvas), kind, sourceIds: photos.map((p) => p.id) }; }