-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
265 lines (231 loc) · 10.5 KB
/
Copy pathscripts.js
File metadata and controls
265 lines (231 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// scripts.js — вспомогательные функции для рендеринга и анализа
let globalVideoElement = null;
let lastFrameTime = performance.now();
let fps = 0;
// Обновляет счётчики FPS и времени на обработку кадра
export function updatePerformanceMetrics(frameTimeMs = 0) {
const now = performance.now();
fps = 1000 / (now - lastFrameTime);
lastFrameTime = now;
const fpsEl = document.getElementById('fpsCounter');
if (fpsEl) {
fpsEl.textContent = `${fps.toFixed(1)} FPS`;
}
// Показываем реальное время обработки кадра
const frameTimeEl = document.getElementById('frameTime');
if (frameTimeEl) {
frameTimeEl.textContent = `${frameTimeMs.toFixed(1)} ms`;
}
}
// Сохраняем элемент видео, чтобы не дергать DOM каждый раз
export function setGlobalVideo(videoEl) {
globalVideoElement = videoEl;
}
// Возвращает canvas с текущим кадром видео
export function getOriginalVideoFrame(targetW, targetH) {
if (!globalVideoElement) return null;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = targetW;
canvas.height = targetH;
ctx.drawImage(globalVideoElement, 0, 0, targetW, targetH);
return canvas;
}
// Анализирует фон (где почти нет человека) и возвращает его средний цвет.
// Помогает для режима "авто-цвет".
export async function analyzeBackgroundColor(pha, originalFrame) {
const [h, w] = pha.shape.slice(1, 3);
const alphaData = await pha.data(); // маска прозрачности
const ctx = originalFrame.getContext('2d');
const frameData = ctx.getImageData(0, 0, w, h).data;
let r = 0, g = 0, b = 0, count = 0;
const step = 4; // Проверяем не каждый пиксель, а с шагом, для скорости
for (let i = 0; i < w * h; i += step) {
// если пиксель относится к фону (alpha < 0.1)
if (alphaData[i] < 0.1) {
const idx = i * 4;
r += frameData[idx];
g += frameData[idx + 1];
b += frameData[idx + 2];
count++;
}
}
if (count === 0) return '#000000'; // на всякий случай
const avgR = Math.round(r / count);
const avgG = Math.round(g / count);
const avgB = Math.round(b / count);
return `#${avgR.toString(16).padStart(2, '0')}${avgG.toString(16).padStart(2, '0')}${avgB.toString(16).padStart(2, '0')}`;
}
// Рисует медиа (картинку или видео), чтобы оно заполняло весь canvas, сохраняя пропорции.
// Аналог css-свойства object-fit: cover
function drawCover(ctx, media) {
const mWidth = media.videoWidth || media.width;
const mHeight = media.videoHeight || media.height;
const canvasWidth = ctx.canvas.width;
const canvasHeight = ctx.canvas.height;
const mediaAspect = mWidth / mHeight;
const canvasAspect = canvasWidth / canvasHeight;
let sx, sy, sWidth, sHeight;
if (mediaAspect > canvasAspect) {
sHeight = mHeight;
sWidth = mHeight * canvasAspect;
sx = (mWidth - sWidth) / 2;
sy = 0;
} else {
sWidth = mWidth;
sHeight = mWidth / canvasAspect;
sx = 0;
sy = (mHeight - sHeight) / 2;
}
ctx.drawImage(media, sx, sy, sWidth, sHeight, 0, 0, canvasWidth, canvasHeight);
}
// Применяет размытие через CSS-фильтр
function applyBlur(ctx, sourceCanvas, radius) {
if (radius <= 0) {
ctx.drawImage(sourceCanvas, 0, 0);
return;
}
ctx.filter = `blur(${radius}px)`;
ctx.drawImage(sourceCanvas, 0, 0);
ctx.filter = 'none'; // сбрасываем фильтр, чтобы не влиял на другие элементы
}
// Определяет, какой цвет текста (чёрный или белый) будет лучше читаться на определённом участке canvas
function getContrastColor(ctx, x, y, width, height) {
if (width <= 0 || height <= 0) return '#ffffff';
const step = Math.max(1, Math.floor(Math.min(width, height) / 5));
let r = 0, g = 0, b = 0, count = 0;
for (let dx = 0; dx < width; dx += step) {
for (let dy = 0; dy < height; dy += step) {
if (x + dx >= ctx.canvas.width || y + dy >= ctx.canvas.height) continue;
const data = ctx.getImageData(x + dx, y + dy, 1, 1).data;
r += data[0]; g += data[1]; b += data[2]; count++;
}
}
if (count === 0) return '#FFFFFF';
// Формула яркости
const brightness = (r / count * 0.299 + g / count * 0.587 + b / count * 0.114);
return brightness > 160 ? '#000000' : '#ffffff';
}
// Готовит строки для оверлея в зависимости от уровня приватности
function getPrivacyText(level, data) {
if (!data) return { left: '', right: '' };
const { full_name, position, company, department, office_location, contact, branding } = data;
switch (level) {
case 'low': return { left: position || '', right: '' };
case 'medium': return { left: `${full_name}\n${position}`, right: company || '' };
case 'high': return {
left: `${full_name}\n${position}\n${department}\n${office_location}`,
right: `${company}\n${contact?.email || ''}\n${contact?.telegram || ''}\n${branding?.slogan || ''}`
};
default: return { left: '', right: '' };
}
}
// Рисует красивую полупрозрачную подложку под текст (эффект "матового стекла")
function drawGlassRect(ctx, x, y, w, h) {
const radius = 10;
const glass = document.createElement('canvas');
glass.width = w;
glass.height = h;
const gctx = glass.getContext('2d');
gctx.filter = 'blur(10px)';
gctx.fillStyle = 'rgba(255, 255, 255, 0.15)';
gctx.fillRect(0, 0, w, h);
gctx.filter = 'none';
ctx.save();
ctx.globalAlpha = 0.8;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + w - radius, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
ctx.lineTo(x + w, y + h - radius);
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
ctx.lineTo(x + radius, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.clip();
ctx.drawImage(glass, x, y);
ctx.restore();
}
// Рисует оверлей с инфой о сотруднике
export function drawPrivacyOverlay(ctx, level, employeeData) {
if (!employeeData || !level || level === 'none') return;
const { left, right } = getPrivacyText(level, employeeData);
if (!left && !right) return;
const margin = 20, lineHeight = 20, maxWidth = 250;
ctx.font = '14px system-ui, sans-serif';
ctx.textBaseline = 'top';
// Левый блок текста
if (left) {
const lines = left.split('\n');
const textHeight = lines.length * lineHeight;
const x = margin;
const y = ctx.canvas.height - textHeight - margin;
drawGlassRect(ctx, x - 15, y - 15, maxWidth + 30, textHeight + 30 - 10);
const textColor = getContrastColor(ctx, x, y, maxWidth, textHeight);
ctx.fillStyle = textColor;
lines.forEach((line, i) => { if (line.trim()) ctx.fillText(line, x, y + i * lineHeight, maxWidth); });
}
// Правый блок текста
if (right) {
const lines = right.split('\n');
const textHeight = lines.length * lineHeight;
const measured = lines.map(l => ctx.measureText(l).width);
const textWidth = Math.max(...measured, 1);
const x = ctx.canvas.width - textWidth - margin;
const y = ctx.canvas.height - textHeight - margin;
drawGlassRect(ctx, x - 15, y - 15, textWidth + 30, textHeight + 30 - 10);
const textColor = getContrastColor(ctx, x, y, textWidth, textHeight);
ctx.fillStyle = textColor;
lines.forEach((line, i) => { if (line.trim()) ctx.fillText(line, x, y + i * lineHeight, maxWidth); });
}
}
// Главная функция рендеринга: собирает фон и вырезанного человека вместе
export async function drawMatte(fgr, pha, ctx, mode, options = {}) {
const { bgMedia, blurRadius = 0, bgColor = '#000000', autoColor = '#000000' } = options;
const [h, w] = pha.shape.slice(1, 3);
// Конвертируем тензоры от нейронки в обычное изображение (ImageData)
const fgrData = await fgr.data();
const alphaData = await pha.data();
const rgbaData = new Uint8ClampedArray(w * h * 4);
for (let i = 0; i < w * h; i++) {
const a = alphaData[i];
rgbaData[i * 4 + 0] = fgrData[i * 3 + 0] * 255;
rgbaData[i * 4 + 1] = fgrData[i * 3 + 1] * 255;
rgbaData[i * 4 + 2] = fgrData[i * 3 + 2] * 255;
rgbaData[i * 4 + 3] = a * 255;
}
const imageData = new ImageData(rgbaData, w, h);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const tempCanvas = document.createElement('canvas');
const tctx = tempCanvas.getContext('2d');
tempCanvas.width = ctx.canvas.width;
tempCanvas.height = ctx.canvas.height;
// Рисуем фон в зависимости от выбранного режима
if (mode === 'color') {
tctx.fillStyle = bgColor;
tctx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
} else if (mode === 'auto') {
tctx.fillStyle = autoColor;
tctx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
} else if (mode === 'blur') {
const frame = getOriginalVideoFrame(tempCanvas.width, tempCanvas.height);
if (frame) drawCover(tctx, frame);
} else if (mode === 'preset' && bgMedia) {
drawCover(tctx, bgMedia);
}
// Применяем размытие к нарисованому фону, если нужно
applyBlur(ctx, tempCanvas, blurRadius);
// Рисуем человека поверх фона
const fgrCanvas = document.createElement('canvas');
fgrCanvas.width = w;
fgrCanvas.height = h;
fgrCanvas.getContext('2d').putImageData(imageData, 0, 0);
const drawW = ctx.canvas.width;
const drawH = (drawW / w) * h;
const drawY = (ctx.canvas.height - drawH) / 2;
ctx.drawImage(fgrCanvas, 0, drawY, drawW, drawH);
// И в конце добавляем оверлей с информацией
drawPrivacyOverlay(ctx, window.privacyLevel, window.employeeData);
}