// ── กล้อง: getUserMedia + ImageCapture + torch + zoom ──────── import { JPEG_QUALITY, THUMB_MAX, THUMB_QUALITY } from "./config.js"; export const cam = { stream: null, track: null, imageCapture: null, caps: {}, facing: "environment", torch: false, zoom: null, videoEl: null, }; function camError(code, cause) { const e = new Error(code); e.code = code; e.cause = cause; return e; } const mapError = (err) => { const name = err?.name || ""; if (name === "NotAllowedError" || name === "PermissionDeniedError") return camError("denied", err); if (name === "NotFoundError" || name === "DevicesNotFoundError") return camError("nocamera", err); if (name === "NotReadableError" || name === "TrackStartError") return camError("busy", err); if (name === "SecurityError") return camError("insecure", err); if (name === "OverconstrainedError") return camError("constraints", err); return camError("unknown", err); }; export async function permissionState() { try { if (!navigator.permissions?.query) return "unknown"; const s = await navigator.permissions.query({ name: "camera" }); return s.state; // granted | denied | prompt } catch { return "unknown"; } } export function stopCamera() { if (cam.stream) { cam.stream.getTracks().forEach((t) => t.stop()); } if (cam.videoEl) cam.videoEl.srcObject = null; cam.stream = null; cam.track = null; cam.imageCapture = null; cam.caps = {}; cam.torch = false; cam.zoom = null; } /** * เปิดกล้องหลัง (ค่าเริ่มต้น) / หน้า * ลำดับ constraint: 1080p → 720p → อะไรก็ได้ที่ใช้ได้ (S23 ผ่านหมด แต่กันกรณีรุ่นอื่น) */ export async function startCamera(videoEl, facing = "environment") { if (!window.isSecureContext) throw camError("insecure"); if (!navigator.mediaDevices?.getUserMedia) throw camError("unsupported"); stopCamera(); cam.videoEl = videoEl; cam.facing = facing; const attempts = [ { video: { facingMode: { ideal: facing }, width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 30 } }, audio: false }, { video: { facingMode: { ideal: facing }, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false }, { video: { facingMode: { ideal: facing } }, audio: false }, { video: true, audio: false }, ]; let lastErr = null; for (const constraints of attempts) { try { cam.stream = await navigator.mediaDevices.getUserMedia(constraints); break; } catch (err) { lastErr = err; if (["NotAllowedError", "PermissionDeniedError", "SecurityError"].includes(err?.name)) throw mapError(err); } } if (!cam.stream) throw mapError(lastErr || new Error("no stream")); cam.track = cam.stream.getVideoTracks()[0]; cam.caps = cam.track.getCapabilities ? cam.track.getCapabilities() : {}; try { cam.imageCapture = typeof window.ImageCapture !== "undefined" ? new window.ImageCapture(cam.track) : null; } catch { cam.imageCapture = null; } videoEl.srcObject = cam.stream; videoEl.muted = true; videoEl.setAttribute("playsinline", ""); try { await videoEl.play(); } catch { /* autoplay may need gesture; caller retries */ } return { settings: cam.track.getSettings?.() || {}, caps: cam.caps, torchAvailable: cam.caps.torch === true, zoomRange: cam.caps.zoom || null, }; } export async function setTorch(on) { if (!cam.track || cam.caps.torch !== true) return false; try { await cam.track.applyConstraints({ advanced: [{ torch: !!on }] }); cam.torch = !!on; return true; } catch { return false; } } export async function setZoom(value) { if (!cam.track || !cam.caps.zoom) return false; const z = Number(value); try { await cam.track.applyConstraints({ advanced: [{ zoom: z }] }); cam.zoom = z; return true; } catch { return false; } } /** * บังคับให้เป็น JPEG จริง — EXIF ฝังได้เฉพาะ JPEG * (ImageCapture บางเครื่อง/บางเวอร์ชันคืน PNG กลับมา) */ async function toJpegBlob(blob, quality = JPEG_QUALITY) { if (!blob) return blob; const head = new Uint8Array(await blob.slice(0, 3).arrayBuffer()); const isJpeg = head[0] === 0xff && head[1] === 0xd8; if (isJpeg) return blob.type === "image/jpeg" ? blob : new Blob([blob], { type: "image/jpeg" }); try { const bmp = await createImageBitmap(blob); const canvas = document.createElement("canvas"); canvas.width = bmp.width; canvas.height = bmp.height; canvas.getContext("2d").drawImage(bmp, 0, 0); bmp.close?.(); const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", quality)); return out || blob; } catch { return blob; } } async function makeThumb(blob) { try { const bmp = await createImageBitmap(blob); const scale = Math.min(1, THUMB_MAX / Math.max(bmp.width, bmp.height)); const w = Math.max(1, Math.round(bmp.width * scale)); const h = Math.max(1, Math.round(bmp.height * scale)); const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; canvas.getContext("2d").drawImage(bmp, 0, 0, w, h); bmp.close?.(); return await new Promise((res) => canvas.toBlob(res, "image/jpeg", THUMB_QUALITY)); } catch { return blob; } } /** /** ครอปกลางภาพให้ได้อัตราส่วนที่เลือก (4:3 = 1.333, 3:4 = 0.75) */ async function cropToRatio(blob, ratio) { try { const bmp = await createImageBitmap(blob); const w = bmp.width, h = bmp.height; const src = w / h; let sw = w, sh = h, sx = 0, sy = 0; if (src > ratio + 0.002) { sw = Math.round(h * ratio); sx = Math.round((w - sw) / 2); } else if (src < ratio - 0.002) { sh = Math.round(w / ratio); sy = Math.round((h - sh) / 2); } if (sw === w && sh === h) { bmp.close?.(); return { blob, width: w, height: h }; } const canvas = document.createElement("canvas"); canvas.width = sw; canvas.height = sh; canvas.getContext("2d").drawImage(bmp, sx, sy, sw, sh, 0, 0, sw, sh); bmp.close?.(); const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY)); return { blob: out || blob, width: sw, height: sh }; } catch { return { blob, width: 0, height: 0 }; } } function ratioValue(label) { const m = /^(\d+)\s*[:x/]\s*(\d+)$/.exec(String(label || "")); if (!m) return 4 / 3; const a = Number(m[1]), b = Number(m[2]); return b ? a / b : 4 / 3; } /** ถ่ายภาพนิ่ง * 1) ImageCapture.takePhoto() — ได้ JPEG ความละเอียดเต็มเซนเซอร์ + EXIF จากกล้อง (S23) * 2) fallback: วาดเฟรมวิดีโอลง canvas */ export async function captureStill({ ratio = "4:3" } = {}) { if (!cam.track) throw camError("notready"); let blob = null; let source = "canvas"; if (cam.imageCapture) { try { // บางเครื่อง takePhoto() ค้างไม่ resolve → กันด้วย timeout แล้วตกไปใช้ canvas blob = await Promise.race([ cam.imageCapture.takePhoto(), new Promise((_, rej) => setTimeout(() => rej(new Error("takePhoto timeout")), 4000)), ]); source = "imagecapture"; } catch { blob = null; } } let width = 0, height = 0; if (!blob) { const v = cam.videoEl; if (!v || !v.videoWidth) throw camError("notready"); const canvas = document.createElement("canvas"); canvas.width = v.videoWidth; canvas.height = v.videoHeight; canvas.getContext("2d").drawImage(v, 0, 0); blob = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY)); width = canvas.width; height = canvas.height; source = "canvas"; } // EXIF ฝังได้เฉพาะ JPEG → แปลงถ้าจำเป็น (ก่อนอ่านขนาด/ทำ thumb) blob = await toJpegBlob(blob); // ครอป/จัดทิศทางทำที่ main.js (หลัง auto-orient) — ที่นี่คืนภาพดิบ if (!width || !height) { try { const bmp = await createImageBitmap(blob); width = bmp.width; height = bmp.height; bmp.close?.(); } catch { width = cam.videoEl?.videoWidth || 0; height = cam.videoEl?.videoHeight || 0; } } const thumb = await makeThumb(blob); return { blob, thumb, width, height, source, facing: cam.facing }; }