// public/publish.js if (window.__PUBLISH_JS_RUNNING__) { console.warn('publish.js ya estaba corriendo, ignorando segunda carga.'); } else { window.__PUBLISH_JS_RUNNING__ = true; const rawOwnerId = new URLSearchParams(location.search).get('ownerId'); const ownerId = decodeURIComponent(String(rawOwnerId || '')).trim(); if (!ownerId) throw new Error('ownerId requerido'); const MS = window.mediasoupClient; if (!MS?.Device) throw new Error('window.mediasoupClient.Device no existe. Revisa el bundle.'); const $ = (id) => document.getElementById(id); const overlay = $('overlay'); const previewVideo = $('localVideo'); const effectsBtn = $('effectsBtn'); const configBtn = $('configBtn'); const sheetOverlay = $('sheetOverlay'); const effectsPanel = $('effectsPanel'); const configPanel = $('configPanel'); const micBtn = $('micBtn'); const camBtn = $('camBtn'); const videoSelect = $('videoSelect'); const audioSelect = $('audioSelect'); const nickInput = $('nickInput'); const fxList = $('fxList'); const maskList = $('maskList'); let socket = null; let device = null; let sendTransport = null; let videoProducer = null; let audioProducer = null; let rawStream = null; let processedStream = null; let rawVideo = null; let renderCanvas = null; let renderCtx = null; let started = false; let starting = false; let renderTimer = null; let pingTimer = null; let reconnectTimer = null; let reconnectAttempts = 0; let pageHidden = false; let micEnabled = true; let camEnabled = true; let currentEffect = 'natural'; let currentMask = 'none'; let nickname = ownerId; let faceLandmarker = null; let faceTaskLoading = null; let lastFaceResults = null; let lastFaceAt = 0; let lastVideoTime = -1; const FX = [ { id: 'natural', icon: '✨', name: 'Natural', desc: 'Limpio' }, { id: 'cinema', icon: '🎬', name: 'Cinema', desc: 'Film look' }, { id: 'neon', icon: '🌈', name: 'Neon', desc: 'Glow pop' }, { id: 'noir', icon: '🖤', name: 'Noir', desc: 'B&N' }, { id: 'dream', icon: '☁️', name: 'Dream', desc: 'Soft glow' }, { id: 'retro', icon: '📼', name: 'Retro', desc: 'VHS lite' } ]; const MASKS = [ { id: 'none', icon: '🙂', name: 'Sin máscara', desc: 'natural' }, { id: 'bear', icon: '🐻', name: 'Osito real', desc: 'peluche premium' }, { id: 'bunny', icon: '🐰', name: 'Conejito', desc: 'cute plush' }, { id: 'cat', icon: '🐱', name: 'Gatito', desc: 'soft glam' }, { id: 'dog', icon: '🐶', name: 'Perrito', desc: 'sweet puppy' }, { id: 'fox', icon: '🦊', name: 'Zorro', desc: 'sharp look' }, { id: 'panda', icon: '🐼', name: 'Panda', desc: 'soft panda' }, { id: 'koala', icon: '🐨', name: 'Koala', desc: 'soft gray' }, { id: 'deer', icon: '🦌', name: 'Ciervo', desc: 'sweet deer' }, { id: 'glasses', icon: '🕶️', name: 'Gafas', desc: 'cool vibe' }, { id: 'crown', icon: '👑', name: 'Corona', desc: 'vip glow' }, { id: 'devil', icon: '😈', name: 'Diablito', desc: 'cute neon' } ]; function showOverlay(text) { if (!overlay) return; overlay.style.display = 'flex'; overlay.textContent = text; } function hideOverlay() { if (!overlay) return; overlay.style.display = 'none'; } function closeSilently(entity) { try { entity?.close?.(); } catch {} } // Flag para no disparar el recovery cuando somos nosotros los que paramos // los tracks (por ej al reabrir cámara). Antes esto causaba bucles porque // stopStream → onended → recoverVideoAfterTrackEnded → startMedia → stopStream → ... let stoppingIntentionally = false; function stopStream(stream) { stoppingIntentionally = true; try { stream?.getTracks?.().forEach((t) => t.stop()); } catch {} finally { // Pequeño delay para que onended del track viejo no nos pille con el flag bajo. setTimeout(() => { stoppingIntentionally = false; }, 50); } } function stopRenderLoop() { if (renderTimer) { clearTimeout(renderTimer); renderTimer = null; } } function stopPing() { if (pingTimer) { clearInterval(pingTimer); pingTimer = null; } } // Decide si necesitamos el pipeline de canvas. Solo cuando hay un efecto o máscara // activo gastamos CPU/GPU procesando frames. Esto reduce drásticamente la batería // y la RAM en el modo "natural" (que será el más usado). function needsCanvasPipeline() { return currentEffect !== 'natural' || currentMask !== 'none'; } function cleanupSocketAndTransport() { stopPing(); closeSilently(videoProducer); closeSilently(audioProducer); closeSilently(sendTransport); videoProducer = null; audioProducer = null; sendTransport = null; try { socket?.removeAllListeners?.(); socket?.disconnect?.(); } catch {} socket = null; device = null; } function send(type, data = {}) { return new Promise((resolve, reject) => { if (!socket) return reject(new Error('socket no inicializado')); socket.emit(type, data, (err, res) => (err ? reject(new Error(String(err))) : resolve(res))); }); } function waitWelcome() { return new Promise((resolve, reject) => { const t = setTimeout(() => reject(new Error('timeout esperando welcome')), 15000); socket.once('message', (m) => { if (m?.type === 'welcome') { clearTimeout(t); resolve(); } }); }); } function hasExpectedMediaCodecs(dev) { const codecs = dev?.rtpCapabilities?.codecs || []; const hasAudio = codecs.some((c) => (c.mimeType || '').toLowerCase() === 'audio/opus'); const hasVideo = codecs.some((c) => ['video/vp9', 'video/vp8', 'video/h264'].includes((c.mimeType || '').toLowerCase())); return hasAudio && hasVideo; } async function warmupCodecDetection() { let pc; try { pc = new RTCPeerConnection(); pc.addTransceiver('audio', { direction: 'recvonly' }); pc.addTransceiver('video', { direction: 'recvonly' }); await pc.createOffer(); } catch (e) { console.warn('Warmup codecs falló:', e); } finally { try { pc?.close?.(); } catch {} } } async function createLoadedDevice(routerRtpCapabilities) { let dev = new MS.Device(); await dev.load({ routerRtpCapabilities }); if (!hasExpectedMediaCodecs(dev)) { await warmupCodecDetection(); dev = new MS.Device(); await dev.load({ routerRtpCapabilities }); } return dev; } // Constraints más conservadoras: 1280x720 si la cámara lo permite, si no // que el navegador elija lo más cercano. frameRate 24 ideal: balance // calidad/batería sólido. Mucha gente publica desde celulares low-end. function defaultVideoConstraint() { return { width: { ideal: 1280, max: 1920 }, height: { ideal: 720, max: 1080 }, frameRate: { ideal: 24, max: 30 }, facingMode: 'user' }; } function defaultAudioConstraint() { return { echoCancellation: true, noiseSuppression: true, autoGainControl: true }; } function createChipHTML(item, activeId) { return ``; } function renderMenus() { if (fxList) fxList.innerHTML = FX.map((x) => createChipHTML(x, currentEffect)).join(''); if (maskList) maskList.innerHTML = MASKS.map((x) => createChipHTML(x, currentMask)).join(''); } function openPanel(which) { if (sheetOverlay) sheetOverlay.style.display = 'block'; if (effectsPanel) effectsPanel.style.display = which === 'effects' ? 'block' : 'none'; if (configPanel) configPanel.style.display = which === 'config' ? 'block' : 'none'; effectsBtn?.classList.toggle('active', which === 'effects'); configBtn?.classList.toggle('active', which === 'config'); } function closePanels() { if (sheetOverlay) sheetOverlay.style.display = 'none'; if (effectsPanel) effectsPanel.style.display = 'none'; if (configPanel) configPanel.style.display = 'none'; effectsBtn?.classList.remove('active'); configBtn?.classList.remove('active'); } function setToggleButtonState(btn, enabled, onLabel, offLabel) { if (!btn) return; btn.classList.toggle('on', enabled); btn.classList.toggle('off', !enabled); btn.textContent = enabled ? onLabel : offLabel; } function ensureRenderPipeline() { if (!rawVideo) { rawVideo = document.createElement('video'); rawVideo.autoplay = true; rawVideo.muted = true; rawVideo.playsInline = true; } if (!renderCanvas) { renderCanvas = document.createElement('canvas'); renderCtx = renderCanvas.getContext('2d', { alpha: false, desynchronized: true }); } } function isHeavyVisualMode() { return currentMask !== 'none'; } function pickCanvasSize() { if (!renderCanvas) return; const track = rawStream?.getVideoTracks?.()[0]; const settings = track?.getSettings?.() || {}; const srcW = Number(settings.width || 1280); const srcH = Number(settings.height || 720); // Si hay máscara reducimos un poco para que face tracking + draw vayan fluido. const maxW = currentMask !== 'none' ? 960 : 1280; const scale = Math.min(1, maxW / srcW); const w = Math.max(640, Math.round(srcW * scale)); const h = Math.max(360, Math.round(srcH * scale)); renderCanvas.width = w; renderCanvas.height = h; } async function startMedia({ videoConstraint, audioConstraint } = {}) { stopStream(rawStream); const desiredVideo = videoConstraint || defaultVideoConstraint(); const desiredAudio = audioConstraint || defaultAudioConstraint(); let stream = null; let lastError = null; const attempts = [ { label: 'video+audio', constraints: { video: desiredVideo, audio: desiredAudio } }, { label: 'video+audio-basico', constraints: { video: desiredVideo, audio: true } }, { label: 'solo-video', constraints: { video: desiredVideo, audio: false } } ]; for (const attempt of attempts) { try { stream = await navigator.mediaDevices.getUserMedia(attempt.constraints); break; } catch (e) { lastError = e; } } if (!stream) throw lastError || new Error('No se pudo abrir la cámara'); if (stream.getVideoTracks().length === 0) { stopStream(stream); throw new Error('No se obtuvo track de video'); } rawStream = stream; rawStream.getAudioTracks().forEach((t) => { t.enabled = micEnabled; }); rawStream.getVideoTracks().forEach((t) => { t.enabled = camEnabled; // BUG FIX: cuando la cam se corta de verdad (background, llamada, dispositivo // cambia), antes solo se reabría getUserMedia y el producer quedaba con un // track muerto. Ahora reabrimos Y reemplazamos el track del producer. // Pero solo si el end NO fue causado por nosotros parando el stream. t.onended = async () => { if (stoppingIntentionally) return; console.warn('⚠️ video track ended (real) → recuperando…'); try { await new Promise(r => setTimeout(r, 800)); await recoverVideoAfterTrackEnded(); } catch (e) { console.error('Recovery falló:', e); showOverlay('⚠️ La cámara se cortó.\nTocá para reintentar.'); started = false; } }; }); ensureRenderPipeline(); rawVideo.srcObject = rawStream; await rawVideo.play().catch(() => {}); pickCanvasSize(); // Solo creamos canvas captureStream si vamos a usar pipeline visual. // Esto es la mayor ganancia de batería del refactor. if (needsCanvasPipeline()) { try { const fps = isHeavyVisualMode() ? 20 : 24; if (!processedStream) processedStream = renderCanvas.captureStream(fps); startRenderLoop(); } catch (e) { console.warn('No se pudo crear canvas captureStream:', e); processedStream = null; } } else { // Modo natural: descartamos canvas para ahorrar CPU/GPU/RAM. stopRenderLoop(); stopStream(processedStream); processedStream = null; } // Preview siempre rápida y barata: mostramos el stream que esté activo. previewVideo.srcObject = needsCanvasPipeline() && processedStream ? processedStream : rawStream; await previewVideo.play().catch(() => {}); } // Reemplaza el track del videoProducer con la fuente actual (raw o canvas) // sin tirar la sesión. Se usa al cambiar de cámara, al cambiar FX/máscara, // o al recuperar de track.onended. async function applyCurrentVideoTrackToProducer() { if (!videoProducer) return; const track = needsCanvasPipeline() ? processedStream?.getVideoTracks?.()[0] || rawStream?.getVideoTracks?.()[0] : rawStream?.getVideoTracks?.()[0]; if (!track) return; try { await videoProducer.replaceTrack({ track }); } catch (e) { console.warn('replaceTrack video falló:', e); } } async function recoverVideoAfterTrackEnded() { // Reabrimos cámara con las constraints actuales y reemplazamos track. await startMedia(); await applyCurrentVideoTrackToProducer(); await replaceAudioTrack(); } // Cambio de modo visual en caliente: cuando el user activa un efecto/máscara // o vuelve a "natural", swap el track del producer entre raw y canvas sin // tirar la conexión. async function syncVisualPipeline() { ensureRenderPipeline(); pickCanvasSize(); if (needsCanvasPipeline()) { try { if (!processedStream) { const fps = isHeavyVisualMode() ? 20 : 24; processedStream = renderCanvas.captureStream(fps); } startRenderLoop(); } catch (e) { console.warn('No pude armar canvas pipeline:', e); } } else { stopRenderLoop(); stopStream(processedStream); processedStream = null; } previewVideo.srcObject = needsCanvasPipeline() && processedStream ? processedStream : rawStream; previewVideo.play().catch(() => {}); await applyCurrentVideoTrackToProducer(); } async function loadDevices() { const devices = await navigator.mediaDevices.enumerateDevices(); if (videoSelect) videoSelect.innerHTML = ''; if (audioSelect) audioSelect.innerHTML = ''; for (const d of devices) { const opt = document.createElement('option'); opt.value = d.deviceId; opt.textContent = d.label || d.kind; if (d.kind === 'videoinput' && videoSelect) videoSelect.appendChild(opt); if (d.kind === 'audioinput' && audioSelect) audioSelect.appendChild(opt); } const currentVideoId = rawStream?.getVideoTracks?.()[0]?.getSettings?.().deviceId; const currentAudioId = rawStream?.getAudioTracks?.()[0]?.getSettings?.().deviceId; if (currentVideoId && videoSelect) videoSelect.value = currentVideoId; if (currentAudioId && audioSelect) audioSelect.value = currentAudioId; } // Preferencia: VP8 > H264. VP8 tiene encoder hardware en casi todo, // se lleva bien con simulcast L1T3 en Chrome y es lo que el bundle ya usaba. // (VP9 con simulcast rompe en Chrome — solo aceptaría SVC puro, otra historia.) function pickPreferredVideoCodec(dev) { const codecs = dev?.rtpCapabilities?.codecs || []; const vp8 = codecs.find((c) => c.kind === 'video' && (c.mimeType || '').toLowerCase() === 'video/vp8'); if (vp8) return vp8; return codecs.find((c) => c.kind === 'video' && (c.mimeType || '').toLowerCase() === 'video/h264') || null; } function isMobileLikely() { const ua = navigator.userAgent || ''; return /Android|iPhone|iPad|iPod|Mobile/i.test(ua); } async function produceVideo() { const track = needsCanvasPipeline() ? processedStream?.getVideoTracks?.()[0] || rawStream?.getVideoTracks?.()[0] : rawStream?.getVideoTracks?.()[0]; if (!track) throw new Error('No hay track de video disponible.'); if (!device.canProduce('video')) throw new Error('Este dispositivo no puede publicar video.'); const preferredCodec = pickPreferredVideoCodec(device); const mobile = isMobileLikely(); // Simulcast con 3 capas (mismo que tenías) pero con bitrates ajustados: // - Mobile: techos más bajos para preservar batería sin perder mucha calidad. // - Desktop: techos altos para mejor calidad real cuando la red lo permite. // OJO: sin `rid` ni `maxFramerate` explícitos; mediasoup-client los maneja. const heavy = isHeavyVisualMode(); const encodings = mobile ? [ { maxBitrate: 180_000, scaleResolutionDownBy: 4, scalabilityMode: 'L1T3' }, { maxBitrate: 600_000, scaleResolutionDownBy: 2, scalabilityMode: 'L1T3' }, { maxBitrate: heavy ? 1_400_000 : 1_800_000, scaleResolutionDownBy: 1, scalabilityMode: 'L1T3' } ] : [ { maxBitrate: 250_000, scaleResolutionDownBy: 4, scalabilityMode: 'L1T3' }, { maxBitrate: 900_000, scaleResolutionDownBy: 2, scalabilityMode: 'L1T3' }, { maxBitrate: heavy ? 2_200_000 : 3_000_000, scaleResolutionDownBy: 1, scalabilityMode: 'L1T3' } ]; const options = { track, encodings, codecOptions: { videoGoogleStartBitrate: mobile ? 700 : 1200, videoGoogleMinBitrate: 150, videoGoogleMaxBitrate: mobile ? 1800 : 3000 } }; const producer = preferredCodec ? await sendTransport.produce({ ...options, codec: preferredCodec }).catch(() => sendTransport.produce(options)) : await sendTransport.produce(options); // Priorizar la capa baja: si la red empeora, mejor mantener algo viendose // que cortar. degradationPreference 'balanced' equilibra fps y resolución. try { const params = producer.rtpSender?.getParameters?.(); if (params?.encodings?.length) { params.degradationPreference = 'balanced'; params.encodings[0].priority = 'high'; params.encodings[0].networkPriority = 'high'; await producer.rtpSender.setParameters(params).catch(() => {}); } } catch {} return producer; } async function produceAudio() { const track = rawStream?.getAudioTracks?.()[0]; if (!track || !device.canProduce('audio')) return null; return await sendTransport.produce({ track, codecOptions: { opusStereo: false, opusDtx: true, opusFec: true, opusMaxAverageBitrate: 32_000 } }); } async function connectSocketAndTransport() { socket = io({ transports: ['polling', 'websocket'], upgrade: true, reconnection: true, reconnectionAttempts: Infinity, reconnectionDelay: 1000, reconnectionDelayMax: 5000, timeout: 20000 }); // Reconexión transparente: si el socket pierde conexión y vuelve, solo // rehacemos el transport si REALMENTE estaba caído. Si el WebRTC sigue // funcionando (que es lo común con un blip de WebSocket), no tocamos nada. socket.io.on('reconnect', async () => { const state = sendTransport?.connectionState; console.warn('🔁 socket.io reconnect. transport state:', state); if (state === 'connected' || state === 'connecting') { // El media plane sigue vivo. No rehacer nada. return; } try { await rebuildSession(); } catch (e) { console.error('rebuildSession falló:', e); scheduleSelfReconnect(); } }); socket.on('disconnect', (reason) => { console.warn('socket disconnect:', reason); }); await waitWelcome(); const routerRtpCapabilities = await send('getRouterRtpCapabilities'); device = await createLoadedDevice(routerRtpCapabilities); sendTransport = device.createSendTransport(await send('createProducerTransport', { ownerId })); sendTransport.on('connect', ({ dtlsParameters }, cb, eb) => { send('connectProducerTransport', { dtlsParameters }).then(cb).catch(eb); }); sendTransport.on('produce', async ({ kind, rtpParameters }, cb, eb) => { try { const { id } = await send('produce', { kind, rtpParameters }); cb({ id }); } catch (e) { eb(e); } }); sendTransport.on('connectionstatechange', (state) => { console.log('publisher transport state:', state); // Solo `failed` es terminal. `disconnected` es transitorio en WebRTC y // se recupera solo (sobre todo en mobile cambiando red). `closed` lo // maneja el handler de transport.close en el server. Reaccionar a // disconnected acá causaba re-handshakes innecesarios → flicker a negro. if (state === 'failed') { scheduleSelfReconnect(); } }); // Ping de aplicación cada 15s. El server lo usa para cancelar el // grace timer si todavía estamos vivos pese a fluctuaciones de socket. stopPing(); pingTimer = setInterval(() => { try { socket?.emit?.('publisherPing'); } catch {} }, 15_000); } // Construye transport + producers reusando la cámara ya abierta. async function rebuildSession() { closeSilently(videoProducer); closeSilently(audioProducer); closeSilently(sendTransport); videoProducer = null; audioProducer = null; sendTransport = null; if (!socket?.connected) { // Socket aún no listo; el evento reconnect llamará de nuevo. return; } const routerRtpCapabilities = await send('getRouterRtpCapabilities'); device = await createLoadedDevice(routerRtpCapabilities); sendTransport = device.createSendTransport(await send('createProducerTransport', { ownerId })); sendTransport.on('connect', ({ dtlsParameters }, cb, eb) => { send('connectProducerTransport', { dtlsParameters }).then(cb).catch(eb); }); sendTransport.on('produce', async ({ kind, rtpParameters }, cb, eb) => { try { const { id } = await send('produce', { kind, rtpParameters }); cb({ id }); } catch (e) { eb(e); } }); sendTransport.on('connectionstatechange', (state) => { if (state === 'failed') { scheduleSelfReconnect(); } }); videoProducer = await produceVideo(); audioProducer = await produceAudio(); started = true; reconnectAttempts = 0; hideOverlay(); console.log('✅ sesión reconstruida sin intervención'); } function scheduleSelfReconnect() { if (reconnectTimer) return; reconnectAttempts++; if (reconnectAttempts > 8) { // Después de varios intentos, sí pedimos intervención. showOverlay('⚠️ La conexión se perdió.\nTocá para reintentar.'); started = false; reconnectAttempts = 0; return; } const delay = Math.min(8000, 1000 * reconnectAttempts); console.log(`🕓 reconectando en ${delay}ms (intento ${reconnectAttempts})`); reconnectTimer = setTimeout(async () => { reconnectTimer = null; try { if (!socket?.connected) { // Si socket también está caído, hacer un restart full. cleanupSocketAndTransport(); await connectSocketAndTransport(); videoProducer = await produceVideo(); audioProducer = await produceAudio(); started = true; reconnectAttempts = 0; hideOverlay(); } else { await rebuildSession(); } } catch (e) { console.error('reconnect falló:', e); scheduleSelfReconnect(); } }, delay); } function nickSafeText(){ return ''; } function fitText(ctx, text, maxWidth, basePx) { let size = basePx; while (size > 13) { ctx.font = `800 ${size}px Inter, system-ui, sans-serif`; if (ctx.measureText(text).width <= maxWidth) return size; size -= 1; } return size; } function drawRoundedRect(ctx, x, y, w, h, r) { const rr = Math.min(r, w / 2, h / 2); ctx.beginPath(); ctx.moveTo(x + rr, y); ctx.arcTo(x + w, y, x + w, y + h, rr); ctx.arcTo(x + w, y + h, x, y + h, rr); ctx.arcTo(x, y + h, x, y, rr); ctx.arcTo(x, y, x + w, y, rr); ctx.closePath(); } function applyColorFX(ctx, w, h) { switch (currentEffect) { case 'cinema': ctx.filter = 'contrast(1.06) saturate(0.92) brightness(0.95)'; break; case 'neon': ctx.filter = 'saturate(1.28) contrast(1.1) brightness(1.05)'; break; case 'noir': ctx.filter = 'grayscale(1) contrast(1.14) brightness(1.02)'; break; case 'dream': ctx.filter = 'brightness(1.05) saturate(0.96) blur(0.6px)'; break; case 'retro': ctx.filter = 'sepia(0.32) saturate(0.86) contrast(1.04)'; break; default: ctx.filter = 'none'; } ctx.drawImage(rawVideo, 0, 0, w, h); ctx.filter = 'none'; if (currentEffect === 'cinema') { const band = Math.round(h * 0.048); ctx.fillStyle = 'rgba(0,0,0,.78)'; ctx.fillRect(0, 0, w, band); ctx.fillRect(0, h - band, w, band); } else if (currentEffect === 'neon') { const g = ctx.createLinearGradient(0, 0, w, h); g.addColorStop(0, 'rgba(115,92,255,.15)'); g.addColorStop(1, 'rgba(40,210,255,.12)'); ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); } else if (currentEffect === 'dream') { ctx.fillStyle = 'rgba(255,225,245,.08)'; ctx.fillRect(0, 0, w, h); } else if (currentEffect === 'retro') { ctx.fillStyle = 'rgba(255,170,110,.06)'; ctx.fillRect(0, 0, w, h); ctx.strokeStyle = 'rgba(255,255,255,.035)'; for (let y = 0; y < h; y += 4) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); } } } function lerpPoint(a, b, t) { return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; } function drawSoftGlow(ctx, drawFn, color, blur = 18, alpha = 0.55) { ctx.save(); ctx.globalAlpha = alpha; ctx.shadowColor = color; ctx.shadowBlur = blur; drawFn(); ctx.restore(); } function drawCircle(ctx, x, y, r, fill, alpha = 1) { ctx.save(); ctx.globalAlpha = alpha; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fillStyle = fill; ctx.fill(); ctx.restore(); } function drawEllipse(ctx, x, y, rx, ry, fill, alpha = 1, rot = 0) { ctx.save(); ctx.globalAlpha = alpha; ctx.beginPath(); ctx.ellipse(x, y, rx, ry, rot, 0, Math.PI * 2); ctx.fillStyle = fill; ctx.fill(); ctx.restore(); } function drawHeart(ctx, x, y, size, fill) { ctx.save(); ctx.translate(x, y); ctx.scale(size, size); ctx.beginPath(); ctx.moveTo(0, 0.35); ctx.bezierCurveTo(-0.55, -0.1, -1.0, 0.45, 0, 1.0); ctx.bezierCurveTo(1.0, 0.45, 0.55, -0.1, 0, 0.35); ctx.closePath(); ctx.fillStyle = fill; ctx.fill(); ctx.restore(); } function drawAntler(ctx, x, y, scale, side, color) { ctx.save(); ctx.translate(x, y); ctx.scale(side * scale, scale); ctx.strokeStyle = color; ctx.lineWidth = 6; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(0, 30); ctx.quadraticCurveTo(6, -20, 0, -76); ctx.moveTo(0, -52); ctx.lineTo(28, -72); ctx.moveTo(2, -22); ctx.lineTo(26, -38); ctx.moveTo(-1, -2); ctx.lineTo(22, -14); ctx.stroke(); ctx.restore(); } function makeRadial(ctx, x, y, r, inner, outer) { const g = ctx.createRadialGradient(x - r * 0.22, y - r * 0.28, r * 0.18, x, y, r); g.addColorStop(0, inner); g.addColorStop(1, outer); return g; } function drawFurRing(ctx, x, y, r, color, alpha = 0.18) { ctx.save(); ctx.strokeStyle = color; ctx.globalAlpha = alpha; ctx.lineCap = 'round'; ctx.lineWidth = Math.max(1, r * 0.1); for (let i = 0; i < 18; i++) { const a = (Math.PI * 2 * i) / 18; const inner = r * 0.88; const outer = r * 1.05; ctx.beginPath(); ctx.moveTo(x + Math.cos(a) * inner, y + Math.sin(a) * inner); ctx.lineTo(x + Math.cos(a) * outer, y + Math.sin(a) * outer); ctx.stroke(); } ctx.restore(); } function drawPlushEar(ctx, x, y, s, rot, outerA, outerB, innerA, innerB, innerScale = 0.56) { ctx.save(); ctx.translate(x, y); ctx.rotate(rot); const outer = ctx.createRadialGradient(-s * 0.16, -s * 0.28, s * 0.12, 0, 0, s); outer.addColorStop(0, outerA); outer.addColorStop(1, outerB); ctx.beginPath(); ctx.ellipse(0, 0, s * 0.68, s, 0, 0, Math.PI * 2); ctx.fillStyle = outer; ctx.shadowColor = 'rgba(0,0,0,.28)'; ctx.shadowBlur = s * 0.35; ctx.fill(); ctx.shadowBlur = 0; drawFurRing(ctx, 0, 0, s * 0.86, 'rgba(255,255,255,.55)', 0.12); const inner = ctx.createRadialGradient(0, -s * 0.1, s * 0.06, 0, 0, s * innerScale); inner.addColorStop(0, innerA); inner.addColorStop(1, innerB); ctx.beginPath(); ctx.ellipse(0, s * 0.02, s * 0.34, s * innerScale, 0, 0, Math.PI * 2); ctx.fillStyle = inner; ctx.fill(); ctx.restore(); } function drawPlushTriangleEar(ctx, x, y, s, rot, outerTop, outerBottom, innerTop, innerBottom) { ctx.save(); ctx.translate(x, y); ctx.rotate(rot); ctx.beginPath(); ctx.moveTo(0, -s); ctx.lineTo(-s * 0.82, s * 0.58); ctx.lineTo(s * 0.82, s * 0.58); ctx.closePath(); const grad = ctx.createLinearGradient(0, -s, 0, s * 0.58); grad.addColorStop(0, outerTop); grad.addColorStop(1, outerBottom); ctx.fillStyle = grad; ctx.shadowColor = 'rgba(0,0,0,.28)'; ctx.shadowBlur = s * 0.3; ctx.fill(); ctx.shadowBlur = 0; ctx.beginPath(); ctx.moveTo(0, -s * 0.62); ctx.lineTo(-s * 0.38, s * 0.18); ctx.lineTo(s * 0.38, s * 0.18); ctx.closePath(); const inner = ctx.createLinearGradient(0, -s * 0.62, 0, s * 0.18); inner.addColorStop(0, innerTop); inner.addColorStop(1, innerBottom); ctx.fillStyle = inner; ctx.fill(); ctx.restore(); } function drawMuzzle(ctx, x, y, w, h, skinA, skinB, noseColor, lineColor, opts = {}) { const { alpha = 1, noseLift = 0.22, shine = true, philtrum = true } = opts; ctx.save(); ctx.globalAlpha = alpha; const grad = ctx.createRadialGradient(x - w * 0.15, y - h * 0.22, w * 0.12, x, y, Math.max(w, h)); grad.addColorStop(0, skinA); grad.addColorStop(1, skinB); ctx.beginPath(); ctx.ellipse(x, y, w, h, 0, 0, Math.PI * 2); ctx.fillStyle = grad; ctx.shadowColor = 'rgba(0,0,0,.16)'; ctx.shadowBlur = Math.max(8, w * 0.18); ctx.fill(); ctx.shadowBlur = 0; ctx.beginPath(); ctx.ellipse(x, y + h * 0.04, w * 0.86, h * 0.82, 0, 0, Math.PI * 2); ctx.strokeStyle = 'rgba(255,255,255,.20)'; ctx.lineWidth = Math.max(1.2, w * 0.03); ctx.stroke(); ctx.beginPath(); ctx.ellipse(x, y - h * noseLift, w * 0.36, h * 0.24, 0, 0, Math.PI * 2); const nose = ctx.createRadialGradient(x - w * 0.05, y - h * (noseLift + 0.06), w * 0.02, x, y - h * noseLift, w * 0.34); nose.addColorStop(0, 'rgba(255,255,255,.45)'); nose.addColorStop(0.22, noseColor); nose.addColorStop(1, lineColor); ctx.fillStyle = nose; ctx.fill(); if (shine) drawCircle(ctx, x - w * 0.07, y - h * (noseLift + 0.05), Math.max(1.5, w * 0.06), 'rgba(255,255,255,.55)', 0.55); if (philtrum) { ctx.strokeStyle = lineColor; ctx.lineWidth = Math.max(1.2, w * 0.035); ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(x, y - h * 0.01); ctx.lineTo(x, y + h * 0.35); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x, y + h * 0.35); ctx.quadraticCurveTo(x - w * 0.16, y + h * 0.48, x - w * 0.24, y + h * 0.26); ctx.moveTo(x, y + h * 0.35); ctx.quadraticCurveTo(x + w * 0.16, y + h * 0.48, x + w * 0.24, y + h * 0.26); ctx.stroke(); } ctx.restore(); } function drawBlushPair(ctx, left, right, r, color='rgba(255,170,195,.24)') { drawCircle(ctx, left.x, left.y, r, color, 1); drawCircle(ctx, right.x, right.y, r, color, 1); } function drawEyeSparkles(ctx, leftEye, rightEye, eyeDist) { const r = Math.max(2, eyeDist * 0.045); drawCircle(ctx, leftEye.x + eyeDist * 0.04, leftEye.y - eyeDist * 0.06, r, 'rgba(255,255,255,.55)', 0.7); drawCircle(ctx, rightEye.x + eyeDist * 0.04, rightEye.y - eyeDist * 0.06, r, 'rgba(255,255,255,.55)', 0.7); } function drawWhiskers(ctx, nose, eyeDist, color='rgba(255,255,255,.92)') { ctx.save(); ctx.strokeStyle = color; ctx.lineWidth = Math.max(1.4, eyeDist * 0.012); ctx.lineCap = 'round'; [[-1, -0.03], [-1, 0.05], [-1, 0.13], [1, -0.03], [1, 0.05], [1, 0.13]].forEach(([dir, off]) => { ctx.beginPath(); ctx.moveTo(nose.x + dir * eyeDist * 0.12, nose.y + eyeDist * off); ctx.quadraticCurveTo( nose.x + dir * eyeDist * 0.26, nose.y + eyeDist * (off - 0.05), nose.x + dir * eyeDist * 0.50, nose.y + eyeDist * (off - 0.01) ); ctx.stroke(); }); ctx.restore(); } function drawSoftForeheadGlow(ctx, center, forehead, eyeDist, color='rgba(255,255,255,.14)') { const g = ctx.createRadialGradient(center.x, forehead.y - eyeDist * 0.2, 4, center.x, forehead.y - eyeDist * 0.2, eyeDist * 0.9); g.addColorStop(0, color); g.addColorStop(1, 'rgba(255,255,255,0)'); ctx.fillStyle = g; ctx.fillRect(center.x - eyeDist, forehead.y - eyeDist * 1.1, eyeDist * 2, eyeDist * 1.3); } function drawMaskAR(ctx, face, w, h) { const pts = face.map((p) => ({ x: p.x * w, y: p.y * h, z: p.z || 0 })); const leftEye = pts[33] || pts[130] || pts[159]; const rightEye = pts[263] || pts[359] || pts[386]; const nose = pts[1] || pts[4]; const forehead = pts[10] || pts[9] || nose; const leftCheek = pts[234] || pts[205] || leftEye; const rightCheek = pts[454] || pts[425] || rightEye; const leftMouth = pts[61] || nose; const rightMouth = pts[291] || nose; if (!leftEye || !rightEye || !nose || !forehead) return; const dx = rightEye.x - leftEye.x; const dy = rightEye.y - leftEye.y; const angle = Math.atan2(dy, dx); const eyeDist = Math.hypot(dx, dy); const center = lerpPoint(leftEye, rightEye, 0.5); const earLift = forehead.y - eyeDist * 0.58; const muzzleY = nose.y + eyeDist * 0.17; const blushLeft = { x: leftCheek.x + eyeDist * 0.08, y: leftCheek.y + eyeDist * 0.10 }; const blushRight = { x: rightCheek.x - eyeDist * 0.08, y: rightCheek.y + eyeDist * 0.10 }; drawSoftForeheadGlow(ctx, center, forehead, eyeDist, 'rgba(255,255,255,.10)'); drawEyeSparkles(ctx, leftEye, rightEye, eyeDist); if (currentMask === 'bear') { drawSoftGlow(ctx, () => { drawPlushEar(ctx, center.x - eyeDist * 0.44, earLift - eyeDist * 0.05, eyeDist * 0.33, angle - 0.08, '#d9a56a', '#8a5934', '#ffd9a7', '#c68658', 0.52); drawPlushEar(ctx, center.x + eyeDist * 0.44, earLift - eyeDist * 0.05, eyeDist * 0.33, angle + 0.08, '#d9a56a', '#8a5934', '#ffd9a7', '#c68658', 0.52); }, 'rgba(191,137,88,.38)', 18, 0.96); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.30, eyeDist * 0.21, '#ffe8c9', '#d9ab7f', '#2f1a10', '#24140e'); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.10, 'rgba(255,182,166,.18)'); drawCircle(ctx, nose.x - eyeDist * 0.08, muzzleY - eyeDist * 0.08, eyeDist * 0.025, 'rgba(255,255,255,.50)', 0.5); } else if (currentMask === 'bunny') { drawSoftGlow(ctx, () => { drawPlushEar(ctx, center.x - eyeDist * 0.38, earLift - eyeDist * 0.36, eyeDist * 0.56, angle - 0.18, '#fffaf8', '#d6d1d6', '#ffc9df', '#ff95bf', 0.56); drawPlushEar(ctx, center.x + eyeDist * 0.38, earLift - eyeDist * 0.36, eyeDist * 0.56, angle + 0.18, '#fffaf8', '#d6d1d6', '#ffc9df', '#ff95bf', 0.56); }, 'rgba(255,182,211,.34)', 18, 0.98); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.24, eyeDist * 0.17, '#fff5fb', '#ffcbe4', '#ff77b0', '#7d3a59', { noseLift: 0.18 }); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.12, 'rgba(255,165,205,.22)'); drawWhiskers(ctx, nose, eyeDist, 'rgba(255,247,252,.88)'); drawHeart(ctx, center.x, forehead.y - eyeDist * 0.98, eyeDist * 0.075, 'rgba(255,175,214,.92)'); } else if (currentMask === 'cat') { drawSoftGlow(ctx, () => { drawPlushTriangleEar(ctx, center.x - eyeDist * 0.39, earLift - eyeDist * 0.02, eyeDist * 0.38, angle - 0.14, '#4b383d', '#22181d', '#ffb0d1', '#ff83b9'); drawPlushTriangleEar(ctx, center.x + eyeDist * 0.39, earLift - eyeDist * 0.02, eyeDist * 0.38, angle + 0.14, '#4b383d', '#22181d', '#ffb0d1', '#ff83b9'); }, 'rgba(255,120,185,.24)', 16, 0.98); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.18, eyeDist * 0.14, '#fff5fb', '#ffd4e7', '#ff85ba', '#663044', { noseLift: 0.16, philtrum: true }); drawWhiskers(ctx, nose, eyeDist, 'rgba(255,248,252,.90)'); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.09, 'rgba(255,154,194,.18)'); } else if (currentMask === 'dog') { drawSoftGlow(ctx, () => { drawPlushEar(ctx, center.x - eyeDist * 0.46, earLift + eyeDist * 0.12, eyeDist * 0.38, angle - 0.62, '#b77a4c', '#6b3f22', '#f5c79d', '#c88556', 0.50); drawPlushEar(ctx, center.x + eyeDist * 0.46, earLift + eyeDist * 0.12, eyeDist * 0.38, angle + 0.62, '#b77a4c', '#6b3f22', '#f5c79d', '#c88556', 0.50); }, 'rgba(182,121,76,.30)', 16, 0.96); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.31, eyeDist * 0.22, '#fff2df', '#d3ab82', '#17110d', '#2a1a12', { noseLift: 0.25 }); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.085, 'rgba(255,186,163,.15)'); drawCircle(ctx, leftMouth.x + eyeDist * 0.04, leftMouth.y + eyeDist * 0.19, eyeDist * 0.018, 'rgba(255,255,255,.38)', 0.4); } else if (currentMask === 'fox') { drawSoftGlow(ctx, () => { drawPlushTriangleEar(ctx, center.x - eyeDist * 0.39, earLift, eyeDist * 0.40, angle - 0.2, '#f18a3a', '#b6481c', '#fff4e4', '#ffd4b3'); drawPlushTriangleEar(ctx, center.x + eyeDist * 0.39, earLift, eyeDist * 0.40, angle + 0.2, '#f18a3a', '#b6481c', '#fff4e4', '#ffd4b3'); }, 'rgba(255,144,74,.28)', 15, 0.95); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.24, eyeDist * 0.18, '#fff4e7', '#ffd2ad', '#272221', '#271b14'); drawWhiskers(ctx, nose, eyeDist, 'rgba(255,248,242,.85)'); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.07, 'rgba(255,180,132,.12)'); } else if (currentMask === 'panda') { drawCircle(ctx, center.x - eyeDist * 0.32, center.y + eyeDist * 0.02, eyeDist * 0.24, 'rgba(36,36,36,.82)'); drawCircle(ctx, center.x + eyeDist * 0.32, center.y + eyeDist * 0.02, eyeDist * 0.24, 'rgba(36,36,36,.82)'); drawPlushEar(ctx, center.x - eyeDist * 0.42, earLift - eyeDist * 0.04, eyeDist * 0.28, angle - 0.02, '#2e2e2e', '#111', '#434343', '#282828', 0.48); drawPlushEar(ctx, center.x + eyeDist * 0.42, earLift - eyeDist * 0.04, eyeDist * 0.28, angle + 0.02, '#2e2e2e', '#111', '#434343', '#282828', 0.48); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.24, eyeDist * 0.18, '#fffdf8', '#d9d5ce', '#171717', '#121212', { noseLift: 0.20 }); } else if (currentMask === 'koala') { drawPlushEar(ctx, center.x - eyeDist * 0.42, earLift - eyeDist * 0.02, eyeDist * 0.30, angle - 0.02, '#98a0aa', '#666f7a', '#eff3f6', '#d7dde3', 0.52); drawPlushEar(ctx, center.x + eyeDist * 0.42, earLift - eyeDist * 0.02, eyeDist * 0.30, angle + 0.02, '#98a0aa', '#666f7a', '#eff3f6', '#d7dde3', 0.52); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.18, eyeDist * 0.22, '#5c6772', '#2f3843', '#11171e', '#11171e', { noseLift: 0.08, philtrum: false }); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.08, 'rgba(255,196,206,.13)'); } else if (currentMask === 'deer') { drawSoftGlow(ctx, () => { drawAntler(ctx, center.x - eyeDist * 0.30, earLift + eyeDist * 0.02, eyeDist / 80, -1, '#b77b4c'); drawAntler(ctx, center.x + eyeDist * 0.30, earLift + eyeDist * 0.02, eyeDist / 80, 1, '#b77b4c'); }, 'rgba(244,192,120,.34)', 12, 0.95); drawPlushEar(ctx, center.x - eyeDist * 0.32, earLift + eyeDist * 0.14, eyeDist * 0.20, angle - 0.24, '#c79165', '#915b3c', '#f8e2d1', '#f0c5aa', 0.46); drawPlushEar(ctx, center.x + eyeDist * 0.32, earLift + eyeDist * 0.14, eyeDist * 0.20, angle + 0.24, '#c79165', '#915b3c', '#f8e2d1', '#f0c5aa', 0.46); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.18, eyeDist * 0.13, '#8f6146', '#6f4630', '#3f2417', '#3f2417', { noseLift: 0.16 }); drawHeart(ctx, center.x, forehead.y - eyeDist * 1.02, eyeDist * 0.07, 'rgba(255,226,185,.85)'); } else if (currentMask === 'glasses') { ctx.save(); ctx.translate(center.x, center.y); ctx.rotate(angle); ctx.strokeStyle = 'rgba(20,20,22,.95)'; ctx.lineWidth = Math.max(3, eyeDist * 0.05); const lensW = eyeDist * 0.42; const lensH = eyeDist * 0.26; ctx.strokeRect(-eyeDist * 0.58, -lensH * 0.5, lensW, lensH); ctx.strokeRect(eyeDist * 0.16, -lensH * 0.5, lensW, lensH); ctx.beginPath(); ctx.moveTo(-eyeDist * 0.16, 0); ctx.lineTo(eyeDist * 0.16, 0); ctx.stroke(); ctx.fillStyle = 'rgba(69,209,255,.10)'; ctx.fillRect(-eyeDist * 0.58, -lensH * 0.5, lensW, lensH); ctx.fillRect(eyeDist * 0.16, -lensH * 0.5, lensW, lensH); ctx.restore(); } else if (currentMask === 'crown') { const crownY = forehead.y - eyeDist * 0.82; const crownW = eyeDist * 1.05; const crownH = eyeDist * 0.42; const x = center.x - crownW / 2; const y = crownY; const grad = ctx.createLinearGradient(x, y, x, y + crownH); grad.addColorStop(0, '#fff5ac'); grad.addColorStop(0.55, '#ffcf54'); grad.addColorStop(1, '#d89816'); drawSoftGlow(ctx, () => { ctx.beginPath(); ctx.moveTo(x, y + crownH); ctx.lineTo(x + crownW * 0.14, y + crownH * 0.22); ctx.lineTo(x + crownW * 0.32, y + crownH * 0.72); ctx.lineTo(x + crownW * 0.5, y); ctx.lineTo(x + crownW * 0.68, y + crownH * 0.72); ctx.lineTo(x + crownW * 0.86, y + crownH * 0.22); ctx.lineTo(x + crownW, y + crownH); ctx.closePath(); ctx.fillStyle = grad; ctx.fill(); }, 'rgba(255,212,87,.55)', 18, 1); [0.14, 0.5, 0.86].forEach((p) => drawCircle(ctx, x + crownW * p, y + crownH * 0.18, eyeDist * 0.045, '#fff6da')); } else if (currentMask === 'devil') { drawSoftGlow(ctx, () => { drawPlushTriangleEar(ctx, center.x - eyeDist * 0.28, earLift + eyeDist * 0.08, eyeDist * 0.26, angle - 0.48, '#b80b2d', '#6f0218', '#ff9aaa', '#ff6c83'); drawPlushTriangleEar(ctx, center.x + eyeDist * 0.28, earLift + eyeDist * 0.08, eyeDist * 0.26, angle + 0.48, '#b80b2d', '#6f0218', '#ff9aaa', '#ff6c83'); }, 'rgba(255,37,84,.42)', 18, 1); drawMuzzle(ctx, nose.x, muzzleY, eyeDist * 0.13, eyeDist * 0.10, '#ffd3dd', '#ff9db2', '#ff5375', '#7b1732', { noseLift: 0.16 }); drawBlushPair(ctx, blushLeft, blushRight, eyeDist * 0.07, 'rgba(255,83,117,.10)'); } if (currentMask !== 'none') { ctx.strokeStyle = 'rgba(255,255,255,.10)'; ctx.lineWidth = Math.max(1, eyeDist * 0.006); ctx.beginPath(); ctx.arc(center.x, center.y + eyeDist * 0.04, eyeDist * 0.78, 0, Math.PI * 2); ctx.stroke(); } } function drawNickname(ctx, w, h) { const text = nickSafeText(); if (!text) return; const maxW = w - 36; const fontSize = fitText(ctx, text, maxW - 24, Math.max(16, Math.round(w * 0.045))); ctx.font = `800 ${fontSize}px Inter, system-ui, sans-serif`; const textW = Math.ceil(ctx.measureText(text).width); const boxH = Math.max(30, Math.round(fontSize * 1.75)); const boxW = Math.min(maxW, textW + 26); const x = 18; const y = Math.max(18, h - boxH - 18); drawRoundedRect(ctx, x, y, boxW, boxH, 14); ctx.fillStyle = 'rgba(0,0,0,.44)'; ctx.fill(); ctx.strokeStyle = 'rgba(255,255,255,.14)'; ctx.stroke(); } async function ensureFaceTask() { if (faceLandmarker) return faceLandmarker; if (faceTaskLoading) return faceTaskLoading; faceTaskLoading = (async () => { showOverlay('🧠 Cargando máscaras AR…'); const mod = await import('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/vision_bundle.mjs'); const vision = await mod.FilesetResolver.forVisionTasks('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm'); faceLandmarker = await mod.FaceLandmarker.createFromOptions(vision, { baseOptions: { modelAssetPath: 'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task', delegate: 'GPU' }, runningMode: 'VIDEO', numFaces: 1, minFaceDetectionConfidence: 0.55, minFacePresenceConfidence: 0.55, minTrackingConfidence: 0.55, outputFaceBlendshapes: false, outputFacialTransformationMatrixes: false }); hideOverlay(); return faceLandmarker; })().catch((e) => { faceTaskLoading = null; console.error('No se pudo cargar Face Landmarker', e); showOverlay('❌ No se pudo cargar AR facial.\nRevisá conexión/CDN y tocá para seguir.'); throw e; }); return faceTaskLoading; } async function maybeRunFaceTracking() { if (currentMask === 'none' || !faceLandmarker || !rawVideo || rawVideo.readyState < 2) return; const now = performance.now(); if (now - lastFaceAt < 110) return; if (rawVideo.currentTime === lastVideoTime) return; lastVideoTime = rawVideo.currentTime; lastFaceAt = now; try { lastFaceResults = faceLandmarker.detectForVideo(rawVideo, now); } catch (e) { console.warn('Face tracking falló en frame:', e); } } function drawFrame() { if (!renderCtx || !renderCanvas || !rawVideo) return; const w = renderCanvas.width; const h = renderCanvas.height; renderCtx.imageSmoothingEnabled = true; renderCtx.imageSmoothingQuality = 'high'; renderCtx.clearRect(0, 0, w, h); if (!camEnabled) { renderCtx.fillStyle = '#050505'; renderCtx.fillRect(0, 0, w, h); renderCtx.fillStyle = 'rgba(255,255,255,.88)'; renderCtx.font = `800 ${Math.max(24, Math.round(w * 0.06))}px Inter, system-ui, sans-serif`; renderCtx.textAlign = 'center'; renderCtx.textBaseline = 'middle'; drawNickname(renderCtx, w, h); return; } applyColorFX(renderCtx, w, h); const landmarks = lastFaceResults?.faceLandmarks?.[0]; if (currentMask !== 'none' && landmarks?.length) drawMaskAR(renderCtx, landmarks, w, h); drawNickname(renderCtx, w, h); } // Render loop solo corre cuando realmente hace falta. Si la página está // oculta (background), pausamos para no quemar batería. function startRenderLoop() { stopRenderLoop(); if (!needsCanvasPipeline()) return; if (pageHidden) return; const tick = async () => { try { if (currentMask !== 'none' && faceLandmarker) await maybeRunFaceTracking(); drawFrame(); } catch (e) { console.warn('render tick falló:', e); } // 50ms (20fps) con máscara, 33ms (~30fps) con solo color FX, 40ms (25) si solo nick. const interval = isHeavyVisualMode() ? 50 : 40; renderTimer = setTimeout(tick, interval); }; tick(); } async function replaceAudioTrack() { const newAudioTrack = rawStream?.getAudioTracks?.()[0] || null; if (audioProducer && newAudioTrack) await audioProducer.replaceTrack({ track: newAudioTrack }); } async function startAll() { if (started || starting) return; starting = true; try { showOverlay('🎥 Iniciando cámara…\nAceptá permisos.'); await startMedia(); await loadDevices(); cleanupSocketAndTransport(); await connectSocketAndTransport(); videoProducer = await produceVideo(); audioProducer = await produceAudio(); started = true; reconnectAttempts = 0; hideOverlay(); } catch (e) { console.error(e); started = false; cleanupSocketAndTransport(); const name = e?.name || ''; const msg = e?.message || String(e); if (name === 'NotAllowedError' || name === 'PermissionDeniedError') showOverlay('🔒 Permiso bloqueado.\nTocá para reintentar.'); else if (name === 'NotFoundError') showOverlay('❌ No se encontró cámara o micrófono.\nTocá para reintentar.'); else showOverlay('❌ No se pudo iniciar:\n' + msg + '\n\nTocá para reintentar.'); } finally { starting = false; } } // visibilitychange: cuando la página queda en background, pausamos el render // loop (canvas) para ahorrar batería. La cámara y los producers siguen vivos // así el viewer no pierde nada. document.addEventListener('visibilitychange', () => { pageHidden = document.hidden; if (pageHidden) { stopRenderLoop(); } else if (started && needsCanvasPipeline()) { startRenderLoop(); } }); overlay?.addEventListener('click', () => startAll(), { passive: true }); overlay?.addEventListener('touchstart', () => startAll(), { passive: true }); effectsBtn && (effectsBtn.onclick = () => openPanel('effects')); configBtn && (configBtn.onclick = () => openPanel('config')); sheetOverlay && (sheetOverlay.onclick = closePanels); document.querySelectorAll('[data-close]').forEach((btn) => btn.addEventListener('click', closePanels)); micBtn && (micBtn.onclick = () => { micEnabled = !micEnabled; rawStream?.getAudioTracks?.().forEach((t) => { t.enabled = micEnabled; }); setToggleButtonState(micBtn, micEnabled, '🎤 Mic ON', '🔇 Mic OFF'); }); camBtn && (camBtn.onclick = async () => { camEnabled = !camEnabled; rawStream?.getVideoTracks?.().forEach((t) => { t.enabled = camEnabled; }); try { camEnabled ? videoProducer?.resume?.() : videoProducer?.pause?.(); } catch {} setToggleButtonState(camBtn, camEnabled, '📷 Cam ON', '🚫 Cam OFF'); drawFrame(); }); if (nickInput) { nickInput.value = nickname; nickInput.addEventListener('input', () => { nickname = String(nickInput.value || '').trim() || ownerId; drawFrame(); }); } if (videoSelect) videoSelect.onchange = async () => { try { showOverlay('🎥 Cambiando cámara…'); await startMedia({ videoConstraint: { deviceId: { exact: videoSelect.value } }, audioConstraint: defaultAudioConstraint() }); await applyCurrentVideoTrackToProducer(); hideOverlay(); } catch (e) { console.error(e); showOverlay('❌ No se pudo cambiar la cámara.\nTocá para reintentar.'); } }; if (audioSelect) audioSelect.onchange = async () => { try { showOverlay('🎤 Cambiando micrófono…'); await startMedia({ audioConstraint: { deviceId: { exact: audioSelect.value } }, videoConstraint: defaultVideoConstraint() }); await replaceAudioTrack(); hideOverlay(); } catch (e) { console.error(e); showOverlay('❌ No se pudo cambiar el micrófono.\nTocá para reintentar.'); } }; // FX y máscaras: ahora hacen swap del pipeline en caliente sin tirar la // sesión. Si pasamos de "natural" a un FX/máscara, creamos canvas+stream y // hacemos replaceTrack en el producer. Si volvemos a natural, swap de vuelta // al rawStream y matamos el render loop. fxList && fxList.addEventListener('click', async (e) => { const btn = e.target.closest('[data-id]'); if (!btn) return; const prev = currentEffect; currentEffect = btn.dataset.id; renderMenus(); if (prev !== currentEffect) { try { await syncVisualPipeline(); } catch (err) { console.warn('syncVisualPipeline FX:', err); } } drawFrame(); }); maskList && maskList.addEventListener('click', async (e) => { const btn = e.target.closest('[data-id]'); if (!btn) return; const nextMask = btn.dataset.id; if (nextMask !== 'none' && !faceLandmarker) { try { await ensureFaceTask(); } catch { return; } } const prev = currentMask; currentMask = nextMask; lastFaceResults = null; renderMenus(); if (prev !== currentMask) { try { await syncVisualPipeline(); } catch (err) { console.warn('syncVisualPipeline mask:', err); } } drawFrame(); }); window.addEventListener('beforeunload', () => { stopRenderLoop(); cleanupSocketAndTransport(); stopStream(rawStream); stopStream(processedStream); }); renderMenus(); setToggleButtonState(micBtn, true, '🎤 Mic ON', '🔇 Mic OFF'); setToggleButtonState(camBtn, true, '📷 Cam ON', '🚫 Cam OFF'); showOverlay('🔄 Iniciando cámara y mic…'); startAll(); }