# ========================================================================== # core/render/compositor.py — ترکیب‌گر GPU نرم‌افزاری (سمت سرور) # -------------------------------------------------------------------------- # این کلاس «برنامه‌ی رسم» هر فریم را (که node/plan.js با کد مشترک ساخته) # با همان شیدرهای پیش‌نمایش اجرا می‌کند. ترتیب مراحل دقیقاً با # static/js/engine/compositor.js یکی است؛ هر تغییری اینجا باید آنجا هم # اعمال شود (و برعکس) تا پیش‌نمایش و خروجی یکی بمانند. # ========================================================================== import math import numpy as np import moderngl from .glctx import to330 def blur_plan(radius, w, h): """کپی دقیق blurPlan در static/js/shared/shaders.js""" sigma = max(0.0, radius) * 0.5 if sigma < 0.35: return None n, d, k = 2, 1, 0.0 while True: k = (sigma / d) / (1.64 * math.sqrt(n)) if k <= 2.2 or d >= 32 or (w / (d * 2)) < 8 or (h / (d * 2)) < 8: break d *= 2 if k > 2.2: n = min(6, int(math.ceil(((sigma / d) / (1.64 * 2.2)) ** 2))) k = (sigma / d) / (1.64 * math.sqrt(n)) return {"d": d, "k": k, "n": n, "w": max(1, int(round(w / d))), "h": max(1, int(round(h / d)))} class Compositor: def __init__(self, ctx: moderngl.Context, out_w: int, out_h: int, proj_w: int, proj_h: int, shaders: dict, meta: dict): self.ctx = ctx self.OW, self.OH = int(out_w), int(out_h) self.W, self.H = proj_w, proj_h self.k = self.OW / float(self.W) self.sh = shaders self.meta = meta self.cols = meta.get("cols") or [] self.curves_data = meta.get("curves") or {} self.blend_modes = meta.get("blendModes") or [] self.vbo = ctx.buffer(np.array([0, 0, 1, 0, 0, 1, 1, 1], dtype="f4").tobytes()) self._progs = {} self._vaos = {} self._fbo_pool = {} # (w,h) -> [fbo...] self._in_use = set() self._curves_tex = {} self._lut_tex = {} self._white = ctx.texture((1, 1), 4, bytes([255, 255, 255, 255])) self.accum = [self._new_fbo(self.OW, self.OH), self._new_fbo(self.OW, self.OH)] self.ai = 0 self.p_layer = self._prog("layer", shaders["VS_QUAD"], shaders["FS_LAYER"]) self.p_blend = self._prog("blend", shaders["VS_FULL"], shaders["FS_BLEND"]) self.p_blur = self._prog("blur", shaders["VS_FULL"], shaders["FS_BLUR"]) self.p_copy = self._prog("copy", shaders["VS_FULL"], shaders["FS_COPY"]) self.p_bg = self._prog("bg", shaders["VS_FULL"], shaders["FS_BG"]) # ------------------------------------------------------------------ GL def _prog(self, key, vs, fs): p = self._progs.get(key) if p is None: p = self.ctx.program(vertex_shader=to330(vs, "vs"), fragment_shader=to330(fs, "fs")) self._progs[key] = p return p def _vao(self, prog): v = self._vaos.get(id(prog)) if v is None: v = self.ctx.vertex_array(prog, [(self.vbo, "2f", "a_pos")]) self._vaos[id(prog)] = v return v @staticmethod def _set(prog, name, value): try: u = prog[name] except KeyError: return if isinstance(value, (list, tuple)) and value and isinstance(value[0], (list, tuple)): u.write(np.array(value, dtype="f4").tobytes()) else: u.value = value def _new_fbo(self, w, h): tex = self.ctx.texture((int(w), int(h)), 4) tex.filter = (moderngl.LINEAR, moderngl.LINEAR) tex.repeat_x = False tex.repeat_y = False return self.ctx.framebuffer(color_attachments=[tex]) def _temp(self, w, h): w, h = max(1, int(w)), max(1, int(h)) pool = self._fbo_pool.setdefault((w, h), []) for f in pool: if id(f) not in self._in_use: self._in_use.add(id(f)) return f f = self._new_fbo(w, h) pool.append(f) self._in_use.add(id(f)) return f def _release(self, fbo): self._in_use.discard(id(fbo)) def _draw(self, prog): self._vao(prog).render(moderngl.TRIANGLE_STRIP) # ------------------------------------------------------------- منابع def curves_texture(self, key): if not key: return None t = self._curves_tex.get(key) if t is None: data = self.curves_data.get(key) if not data: return None t = self.ctx.texture((256, 1), 4, bytes(bytearray(int(v) & 255 for v in data))) t.filter = (moderngl.LINEAR, moderngl.LINEAR) t.repeat_x = False t.repeat_y = False self._curves_tex[key] = t return t def set_lut(self, key, size, rgba_bytes): t = self.ctx.texture((size * size, size), 4, rgba_bytes) t.filter = (moderngl.LINEAR, moderngl.LINEAR) t.repeat_x = False t.repeat_y = False self._lut_tex[key] = (t, size) # --------------------------------------------------------- شیدر لایه def _layer_uniforms(self, p, d, tex, tex_flip, premul, target_w, target_h, scale, full=False, use_color=True, use_mask=True, matte=None, opacity=None, sub=None, local_mode=False): """تنظیم یونیفرم‌های شیدر لایه — همان ترتیب compositor.js""" S = self._set if full: m = [target_w, 0.0, 0.0, 0.0, target_h, 0.0] else: mm = d["m"] m = [mm[0] * scale, mm[1] * scale, mm[2] * scale, mm[3] * scale, mm[4] * scale, mm[5] * scale] S(p, "u_canvas", (float(target_w), float(target_h))) S(p, "u_m0", (m[0], m[1], m[2])) S(p, "u_m1", (m[3], m[4], m[5])) sb = sub if sub is not None else (d.get("sub") if not full else None) S(p, "u_sub", tuple(sb) if sb else (0.0, 0.0, 1.0, 1.0)) tex.use(location=0) S(p, "u_tex", 0) S(p, "u_texFlip", float(tex_flip)) if local_mode: S(p, "u_crop", (0.0, 0.0, 1.0, 1.0)) S(p, "u_rot90", 0.0) S(p, "u_flip", (0.0, 0.0)) else: cr = d.get("crop") or [0, 0, 1, 1] S(p, "u_crop", tuple(float(v) for v in cr)) S(p, "u_rot90", float(d.get("rot90") or 0)) fl = d.get("flip") or [0, 0] S(p, "u_flip", (float(fl[0]), float(fl[1]))) S(p, "u_opacity", float(d.get("op", 1.0) if opacity is None else opacity)) S(p, "u_premul", float(premul)) S(p, "u_packed", 0.0) if matte is not None: matte.use(location=1) S(p, "u_matte", 1) S(p, "u_hasMatte", 1.0) S(p, "u_matteFlip", 0.0) else: self._white.use(location=1) S(p, "u_matte", 1) S(p, "u_hasMatte", 0.0) S(p, "u_matteFlip", 0.0) mk = d.get("mk") if use_mask else None if mk: S(p, "u_maskOn", 1.0) S(p, "u_mk0", (float(mk[0]), float(mk[1]), float(mk[2]), float(mk[3]))) S(p, "u_mk1", (float(mk[4]), float(mk[5]), float(mk[6]), float(mk[7]))) S(p, "u_mk2", (float(mk[8]), 0.0, 0.0, 0.0)) else: S(p, "u_maskOn", 0.0) S(p, "u_mk0", (0.0, 0.5, 0.5, 1.0)) S(p, "u_mk1", (1.0, 0.0, 0.0, 0.0)) S(p, "u_mk2", (0.0, 0.0, 0.0, 0.0)) ck = d.get("ck") if use_color else None if ck: S(p, "u_ck0", (float(ck[0]), float(ck[1]), float(ck[2]), 1.0)) S(p, "u_ck1", (float(ck[3]), float(ck[4]), float(ck[5]), 0.0)) else: S(p, "u_ck0", (0.0, 1.0, 0.0, 0.0)) S(p, "u_ck1", (0.0, 0.0, 0.0, 0.0)) col = None if use_color: ci = d.get("ci") if ci is not None and 0 <= ci < len(self.cols): col = self.cols[ci] if col: S(p, "u_colOn", 1.0) S(p, "u_col", [tuple(col[i:i + 4]) for i in range(0, 52, 4)]) else: S(p, "u_colOn", 0.0) ctex = self.curves_texture(d.get("cv")) if (use_color and col) else None if ctex is not None: ctex.use(location=2) S(p, "u_curves", 2) S(p, "u_curvesOn", 1.0) else: self._white.use(location=2) S(p, "u_curves", 2) S(p, "u_curvesOn", 0.0) lut = d.get("lut") if use_color else None lt = self._lut_tex.get(lut[0]) if lut else None if lt: lt[0].use(location=3) S(p, "u_lut", 3) S(p, "u_lutInfo", (float(lt[1]), float(lut[1]), 1.0)) else: self._white.use(location=3) S(p, "u_lut", 3) S(p, "u_lutInfo", (2.0, 0.0, 0.0)) tw, th = tex.size S(p, "u_texel", (1.0 / max(1, tw), 1.0 / max(1, th))) if full: S(p, "u_size", (float(target_w), float(target_h))) else: mm = d["m"] S(p, "u_size", (math.hypot(mm[0], mm[3]) * scale, math.hypot(mm[1], mm[4]) * scale)) S(p, "u_noise", (float(d.get("time", 0.0)), float(d.get("seed", 0.0)))) # --------------------------------------------------------- محو def blur(self, src_fbo, radius): sw, sh = src_fbo.size bp = blur_plan(radius, sw, sh) if not bp: return None # کوچک‌سازی تدریجی (هر بار نصف) برای جلوگیری از پله‌پله شدن cur = src_fbo cw, ch = sw, sh steps = [] d = 1 while d < bp["d"]: d *= 2 nw, nh = max(1, int(round(sw / d))), max(1, int(round(sh / d))) nxt = self._temp(nw, nh) self._copy(cur, nxt, flip_src=1.0) if cur is not src_fbo: self._release(cur) cur = nxt cw, ch = nw, nh if cur is src_fbo: nxt = self._temp(cw, ch) self._copy(cur, nxt, flip_src=1.0) cur = nxt a, b = cur, self._temp(cw, ch) kk = bp["k"] p = self.p_blur self.ctx.disable(moderngl.BLEND) for _ in range(bp["n"]): b.use() a.color_attachments[0].use(location=0) self._set(p, "u_tex", 0) self._set(p, "u_texFlip", 1.0) self._set(p, "u_dir", (kk / cw, 0.0)) self._draw(p) a.use() b.color_attachments[0].use(location=0) self._set(p, "u_dir", (0.0, kk / ch)) self._draw(p) self._release(b) return a def _copy(self, src_fbo, dst_fbo, flip_src=1.0, tone=(1.0, 1.0), blend=False): p = self.p_copy dst_fbo.use() if blend: self.ctx.enable(moderngl.BLEND) self.ctx.blend_func = moderngl.ONE, moderngl.ONE_MINUS_SRC_ALPHA else: self.ctx.disable(moderngl.BLEND) src_fbo.color_attachments[0].use(location=0) self._set(p, "u_tex", 0) self._set(p, "u_texFlip", float(flip_src)) self._set(p, "u_tone", (float(tone[0]), float(tone[1]))) self._draw(p) # --------------------------------------------------------- افکت def fx_program(self, fx_id): key = "fx:" + fx_id p = self._progs.get(key) if p is None: code = self.sh["fx"].get(fx_id) if not code: return None p = self._prog(key, self.sh["VS_FULL"], code) return p def run_effect(self, fx, src_fbo, dst_fbo, out_h_ref): p = self.fx_program(fx["id"]) if p is None: self._copy(src_fbo, dst_fbo) return blurred = None br = float(fx.get("br") or 0.0) if br > 0: blurred = self.blur(src_fbo, br * out_h_ref) w, h = dst_fbo.size dst_fbo.use() self.ctx.disable(moderngl.BLEND) src_fbo.color_attachments[0].use(location=0) self._set(p, "fx_src", 0) self._set(p, "fx_srcFlip", 1.0) if blurred is not None: blurred.color_attachments[0].use(location=1) else: src_fbo.color_attachments[0].use(location=1) self._set(p, "fx_blur", 1) self._set(p, "fx_blurFlip", 1.0) self._set(p, "fx_res", (float(w), float(h))) self._set(p, "fx_time", float(fx.get("tm", 0.0))) self._set(p, "fx_seed", float(fx.get("seed", 0.0))) self._set(p, "fx_dur", float(fx.get("dur", 0.0))) pv = list(fx.get("p") or [0, 0, 0, 0]) + [0, 0, 0, 0] self._set(p, "fx_p", (float(pv[0]), float(pv[1]), float(pv[2]), float(pv[3]))) self._draw(p) if blurred is not None: self._release(blurred) # --------------------------------------------------------- آیتم def draw_item(self, d, target_fbo, tex, tex_flip, premul, matte=None, scale=None, use_color=True): """رسم یک آیتم روی target با ترکیب معمولی (premultiplied over)""" scale = self.k if scale is None else scale tw, th = target_fbo.size p = self.p_layer fxl = d.get("fx") if fxl: mm = d["m"] pw = int(max(2, min(4096, round(math.hypot(mm[0], mm[3]) * scale)))) ph = int(max(2, min(4096, round(math.hypot(mm[1], mm[4]) * scale)))) P = self._temp(pw, ph) P.use() self.ctx.clear(0.0, 0.0, 0.0, 0.0) self.ctx.disable(moderngl.BLEND) self._layer_uniforms(p, d, tex, tex_flip, premul, pw, ph, scale, full=True, use_color=use_color, use_mask=False, matte=matte, opacity=1.0, sub=(0.0, 0.0, 1.0, 1.0)) self._draw(p) for fx in fxl: Q = self._temp(pw, ph) self.run_effect(fx, P, Q, self.OH) self._release(P) P = Q target_fbo.use() self.ctx.enable(moderngl.BLEND) self.ctx.blend_func = moderngl.ONE, moderngl.ONE_MINUS_SRC_ALPHA self._layer_uniforms(p, d, P.color_attachments[0], 1.0, 1.0, tw, th, scale, use_color=False, use_mask=True, matte=None, local_mode=True) self._draw(p) self._release(P) else: target_fbo.use() self.ctx.enable(moderngl.BLEND) self.ctx.blend_func = moderngl.ONE, moderngl.ONE_MINUS_SRC_ALPHA self._layer_uniforms(p, d, tex, tex_flip, premul, tw, th, scale, use_color=use_color, matte=matte) self._draw(p) # --------------------------------------------------------- پس‌زمینه def draw_scene(self, scn, target, get_tex): bg = scn.get("bg") or {"t": "color", "c": [0, 0, 0, 1]} target.use() self.ctx.disable(moderngl.BLEND) t = bg.get("t") if t == "grad": p = self.p_bg c1, c2 = bg["c1"], bg["c2"] self._set(p, "u_c1", tuple(float(v) for v in c1)) self._set(p, "u_c2", tuple(float(v) for v in c2)) self._set(p, "u_res", (float(self.OW), float(self.OH))) self._set(p, "u_ang", float(bg.get("ang", 0.0))) self._set(p, "u_kind", float(bg.get("kind", 1))) self._draw(p) elif t == "blur" and bg.get("d"): self.ctx.clear(0.0, 0.0, 0.0, 1.0) cd = bg["d"] tex, flip, premul, matte = get_tex(cd) radius = (0.01 + float(bg.get("amt", 0.5)) * 0.07) * self.OH if float(bg.get("amt", 0.5)) > 0 else 0.0 bp = blur_plan(radius, self.OW, self.OH) if radius > 0 else None if tex is None: pass elif not bp: self.draw_item(dict(cd, op=1.0, mk=None, fx=None), target, tex, flip, premul, matte) else: S1 = self._temp(bp["w"], bp["h"]) S1.use() self.ctx.clear(0.0, 0.0, 0.0, 1.0) self.draw_item(dict(cd, op=1.0, mk=None, fx=None), S1, tex, flip, premul, matte, scale=self.k * bp["w"] / self.OW) blurred = self.blur_small(S1, bp) self._copy(blurred, target, flip_src=1.0, tone=(float(bg.get("dim", 1.0)), 1.0)) self._release(blurred) if blurred is not S1: self._release(S1) else: c = bg.get("c") or [0, 0, 0, 1] self.ctx.clear(float(c[0]), float(c[1]), float(c[2]), 1.0) d = scn.get("d") if d: tex, flip, premul, matte = get_tex(d) if tex is not None: self.draw_item(d, target, tex, flip, premul, matte) def blur_small(self, S1, bp): """محو یک FBO که از قبل در اندازه‌ی کوچک رسم شده (همان گام‌های blur)""" cw, ch = S1.size b = self._temp(cw, ch) p = self.p_blur self.ctx.disable(moderngl.BLEND) kk = bp["k"] for _ in range(bp["n"]): b.use() S1.color_attachments[0].use(location=0) self._set(p, "u_tex", 0) self._set(p, "u_texFlip", 1.0) self._set(p, "u_dir", (kk / cw, 0.0)) self._draw(p) S1.use() b.color_attachments[0].use(location=0) self._set(p, "u_dir", (0.0, kk / ch)) self._draw(p) self._release(b) return S1 # --------------------------------------------------------- ترنزیشن def tr_program(self, tr_id): key = "tr:" + tr_id p = self._progs.get(key) if p is None: code = self.sh["tr"].get(tr_id) if not code: return None p = self._prog(key, self.sh["VS_FULL"], code) return p # --------------------------------------------------------- فریم def render(self, plan, get_tex): """get_tex(draw) → (texture, texFlip, premul, matteTexture)""" self.ai = 0 acc = self.accum[0] base = plan.get("base") or {} if base.get("tr"): tr = base["tr"] fa = self._temp(self.OW, self.OH) fb = self._temp(self.OW, self.OH) self.draw_scene(base["a"], fa, get_tex) self.draw_scene(base["b"], fb, get_tex) p = self.tr_program(tr["id"]) acc.use() self.ctx.disable(moderngl.BLEND) if p is None: self._copy(fb if tr.get("p", 0) >= 0.5 else fa, acc) else: fa.color_attachments[0].use(location=0) fb.color_attachments[0].use(location=1) self._set(p, "tr_from", 0) self._set(p, "tr_to", 1) self._set(p, "progress", float(tr.get("p", 0.0))) self._set(p, "ratio", self.OW / float(self.OH)) self._set(p, "tr_res", (float(self.OW), float(self.OH))) self._set(p, "tr_p", (0.0, 0.0, 0.0, 0.0)) self._draw(p) self._release(fa) self._release(fb) elif base.get("sc"): self.draw_scene(base["sc"], acc, get_tex) else: acc.use() self.ctx.clear(0.0, 0.0, 0.0, 1.0) for L in plan.get("layers") or []: k = L.get("k") cur = self.accum[self.ai] other = self.accum[1 - self.ai] if k == "fx": self.run_effect(L["fx"], cur, other, self.OH) self.ai = 1 - self.ai elif k == "col": other.use() self.ctx.disable(moderngl.BLEND) Ld = dict(L) Ld["time"] = float(plan.get("t", 0.0)) self._layer_uniforms(self.p_layer, Ld, cur.color_attachments[0], 1.0, 1.0, self.OW, self.OH, self.k, full=True, use_color=True, use_mask=False, opacity=1.0, sub=(0.0, 0.0, 1.0, 1.0), local_mode=True) self._draw(self.p_layer) self.ai = 1 - self.ai else: tex, flip, premul, matte = get_tex(L) if tex is None: continue bl = int(L.get("bl") or 0) if bl == 0: self.draw_item(L, cur, tex, flip, premul, matte) else: lay = self._temp(self.OW, self.OH) lay.use() self.ctx.clear(0.0, 0.0, 0.0, 0.0) self.draw_item(L, lay, tex, flip, premul, matte) other.use() self.ctx.disable(moderngl.BLEND) p = self.p_blend cur.color_attachments[0].use(location=0) lay.color_attachments[0].use(location=1) self._set(p, "u_dst", 0) self._set(p, "u_src", 1) self._set(p, "u_mode", float(bl)) self._set(p, "u_op", 1.0) self._draw(p) self._release(lay) self.ai = 1 - self.ai return self.accum[self.ai] def read_rgb(self, fbo): """خواندن فریم نهایی (ردیف‌ها از پایین به بالا؛ برعکس‌کردن با vflip در ffmpeg)""" return fbo.read(components=3, alignment=1)