studio / app.py
seawolf2357's picture
Update app.py
813b71a verified
"""
Simple Video Editor - Canvas 기반 렌더링
빈 프레임 문제 완전 해결 + 서버 사이드 MP4 내보내기
블러 배경 내보내기 수정: 더블 버퍼링
🎨 Comic Classic Theme 적용
"""
import gradio as gr
import base64
import os
import json
import subprocess
import tempfile
import shutil
import time
# Hugging Face Spaces GPU 요구사항 충족용 더미 함수
try:
import spaces
@spaces.GPU
def dummy_gpu_function():
"""Spaces GPU requirement를 충족하기 위한 더미 함수"""
return None
except ImportError:
pass
# 서버 사이드 MP4 내보내기용
UPLOAD_DIR = tempfile.mkdtemp()
uploaded_files = {} # {filename: filepath}
def get_editor_html(media_data="[]"):
return f'''<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<style>
*{{margin:0;padding:0;box-sizing:border-box}}
body{{font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#f5f5f7;font-size:13px}}
.editor{{display:flex;flex-direction:column;height:100vh}}
.toolbar{{height:44px;background:#fff;border-bottom:1px solid #ddd;display:flex;align-items:center;justify-content:space-between;padding:0 12px}}
.toolbar-title{{font-size:15px;font-weight:600}}
.btn{{padding:5px 10px;border:none;border-radius:5px;cursor:pointer;font-size:11px;font-weight:500}}
.btn-secondary{{background:#f0f0f0;color:#333}}
.btn-secondary:hover{{background:#e0e0e0}}
.btn-success{{background:#10b981;color:#fff}}
.btn-danger{{background:#ef4444;color:#fff}}
.main{{display:flex;flex:1;overflow:hidden}}
.library{{width:160px;background:#fff;border-right:1px solid #ddd;display:flex;flex-direction:column}}
.lib-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
.lib-content{{flex:1;overflow-y:auto;padding:6px}}
.lib-hint{{text-align:center;padding:15px;color:#999;font-size:10px}}
.media-grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:4px}}
.media-item{{aspect-ratio:16/9;background:#f0f0f0;border-radius:4px;overflow:hidden;cursor:grab;position:relative;border:1px solid #e0e0e0}}
.media-item:hover{{border-color:#6366f1}}
.media-item img{{width:100%;height:100%;object-fit:cover}}
.media-item-icon{{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:18px}}
.media-item-dur{{position:absolute;top:2px;right:2px;background:rgba(0,0,0,0.7);padding:1px 3px;border-radius:2px;font-size:8px;color:#fff}}
.preview-area{{flex:1;display:flex;flex-direction:column;background:#1a1a1a;margin:6px;border-radius:8px;overflow:hidden}}
.preview-box{{flex:1;display:flex;align-items:center;justify-content:center;background:#000;overflow:hidden}}
#previewCanvas{{background:#000;box-shadow:0 0 20px rgba(0,0,0,0.5);cursor:default}}
.controls{{height:45px;background:#222;display:flex;align-items:center;justify-content:center;gap:6px}}
.ctrl-btn{{width:28px;height:28px;border:none;border-radius:50%;background:rgba(255,255,255,0.1);color:#fff;cursor:pointer;font-size:12px}}
.ctrl-btn:hover{{background:rgba(255,255,255,0.2)}}
.ctrl-btn.play{{width:36px;height:36px;background:#6366f1}}
.time-display{{font-family:monospace;font-size:10px;color:#aaa;min-width:90px;text-align:center}}
.props{{width:140px;background:#fff;border-left:1px solid #ddd}}
.props-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
.props-content{{padding:8px}}
.no-sel{{color:#999;text-align:center;padding:15px;font-size:10px}}
.prop-group{{margin-bottom:10px}}
.prop-label{{font-size:9px;color:#666;margin-bottom:2px}}
.prop-input{{width:100%;padding:4px;border:1px solid #ddd;border-radius:3px;font-size:10px}}
.timeline{{height:180px;background:#fff;border-top:1px solid #ddd;display:flex;flex-direction:column}}
.tl-toolbar{{height:28px;background:#fafafa;border-bottom:1px solid #eee;display:flex;align-items:center;padding:0 6px;gap:4px}}
.tl-toolbar .btn{{padding:2px 6px;font-size:9px}}
.tl-zoom{{display:flex;align-items:center;gap:3px;margin-left:auto;font-size:9px;color:#666}}
.tl-zoom input{{width:50px}}
.tl-container{{flex:1;overflow-x:auto;position:relative}}
.tl-ruler{{height:18px;background:#fff;border-bottom:1px solid #eee}}
.tl-tracks{{position:relative}}
.tl-track{{height:45px;border-bottom:1px solid #eee;display:flex}}
.tl-track:nth-child(2){{background:#fffbeb}}
.tl-track:nth-child(3){{background:#fdf2f8}}
.track-label{{width:50px;padding:0 4px;font-size:8px;color:#666;background:#fafafa;display:flex;align-items:center;border-right:1px solid #eee}}
.track-content{{flex:1;position:relative;min-width:600px}}
.clip{{position:absolute;height:36px;top:4px;border-radius:4px;cursor:grab;display:flex;align-items:center;overflow:hidden}}
.clip:hover{{box-shadow:0 0 0 2px #6366f1}}
.clip.selected{{box-shadow:0 0 0 2px #6366f1}}
.clip.video{{background:linear-gradient(135deg,#818cf8,#6366f1)}}
.clip.image{{background:linear-gradient(135deg,#34d399,#10b981)}}
.clip.audio{{background:linear-gradient(135deg,#fbbf24,#f59e0b)}}
.clip.text{{background:linear-gradient(135deg,#f472b6,#ec4899)}}
.clip-thumb{{width:36px;height:100%;object-fit:cover}}
.clip-info{{padding:0 4px;flex:1;overflow:hidden}}
.clip-name{{font-size:8px;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
.clip-dur{{font-size:7px;color:rgba(255,255,255,0.7)}}
.clip-handle{{position:absolute;top:0;bottom:0;width:8px;background:rgba(255,255,255,0.5);cursor:ew-resize;opacity:0}}
.clip:hover .clip-handle{{opacity:1}}
.clip-handle-l{{left:0;border-radius:4px 0 0 4px}}
.clip-handle-r{{right:0;border-radius:0 4px 4px 0}}
.playhead{{position:absolute;top:0;bottom:0;width:2px;background:#ef4444;z-index:10;pointer-events:none}}
.playhead::before{{content:"";position:absolute;top:0;left:-4px;border-left:5px solid transparent;border-right:5px solid transparent;border-top:7px solid #ef4444}}
.drop-zone{{background:rgba(99,102,241,0.1)!important;outline:2px dashed #6366f1!important}}
.status{{height:20px;background:#f5f5f5;border-top:1px solid #ddd;display:flex;align-items:center;padding:0 8px;font-size:9px;color:#666}}
.ctx-menu{{position:fixed;background:#fff;border:1px solid #ddd;border-radius:5px;padding:3px 0;min-width:100px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);display:none}}
.ctx-item{{padding:5px 10px;cursor:pointer;font-size:10px}}
.ctx-item:hover{{background:#f5f5f5}}
.ctx-item.danger{{color:#ef4444}}
.modal{{position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:1000}}
.modal-box{{background:#fff;border-radius:8px;padding:16px;min-width:240px;text-align:center}}
.modal-box h3{{margin-bottom:8px;font-size:13px}}
.progress{{height:5px;background:#eee;border-radius:3px;overflow:hidden;margin:10px 0}}
.progress-bar{{height:100%;background:#6366f1;transition:width 0.2s}}
.hidden-media{{position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0;pointer-events:none}}
</style>
</head>
<body>
<div class="editor">
<div class="toolbar">
<div class="toolbar-title">🎬 Video Editor</div>
<div style="display:flex;gap:8px;align-items:center">
<select id="ratioSelect" onchange="setRatio(this.value)" style="padding:4px 8px;border-radius:4px;border:1px solid #ddd;font-size:11px">
<option value="16:9">16:9 (가로)</option>
<option value="9:16">9:16 (세로)</option>
<option value="1:1">1:1 (정사각)</option>
<option value="4:3">4:3</option>
<option value="4:5">4:5 (인스타)</option>
</select>
<select id="fillMode" onchange="setFillMode(this.value)" style="padding:4px 8px;border-radius:4px;border:1px solid #ddd;font-size:11px">
<option value="fit">맞춤 (여백)</option>
<option value="fill">채우기 (확대)</option>
<option value="blur">블러 배경</option>
</select>
<button class="btn btn-secondary" onclick="undo()">↩ 실행취소</button>
<button class="btn btn-success" onclick="exportVideo()">📥 내보내기</button>
</div>
</div>
<div class="main">
<div class="library">
<div class="lib-header">📁 미디어</div>
<div class="lib-content">
<div class="lib-hint" id="hint">파일을 업로드하세요</div>
<div class="media-grid" id="mediaGrid"></div>
</div>
</div>
<div class="preview-area">
<div class="preview-box">
<canvas id="previewCanvas" width="640" height="360"></canvas>
</div>
<div class="controls">
<button class="ctrl-btn" onclick="seek(0)">⏮</button>
<button class="ctrl-btn" onclick="seek(S.time-5)">⏪</button>
<button class="ctrl-btn play" onclick="togglePlay()" id="playBtn">▶</button>
<button class="ctrl-btn" onclick="seek(S.time+5)">⏩</button>
<button class="ctrl-btn" onclick="seek(S.dur)">⏭</button>
<div class="time-display"><span id="curT">00:00.00</span> / <span id="totT">00:00.00</span></div>
<button class="ctrl-btn" onclick="toggleMute()" id="muteBtn">🔊</button>
</div>
</div>
<div class="props">
<div class="props-header">⚙️ 속성</div>
<div class="props-content" id="propsBox"><div class="no-sel">클립 선택</div></div>
</div>
</div>
<div class="timeline">
<div class="tl-toolbar">
<button class="btn btn-secondary" onclick="addTextClip()">📝 텍스트</button>
<button class="btn btn-secondary" onclick="splitClip()">✂ 자르기</button>
<button class="btn btn-secondary" onclick="dupeClip()">📋 복제</button>
<button class="btn btn-danger" onclick="delClip()">🗑 삭제</button>
<div class="tl-zoom">🔍<input type="range" min="0.5" max="3" step="0.1" value="1" oninput="setZoom(this.value)"></div>
</div>
<div class="tl-container" id="tlBox" onclick="tlClick(event)">
<div class="tl-ruler" id="ruler"></div>
<div class="tl-tracks">
<div class="tl-track"><div class="track-label">🎬 영상</div><div class="track-content" id="t0"></div></div>
<div class="tl-track"><div class="track-label">🎵 오디오</div><div class="track-content" id="t1"></div></div>
<div class="tl-track"><div class="track-label">📝 텍스트</div><div class="track-content" id="t2"></div></div>
</div>
<div class="playhead" id="playhead" style="left:50px"></div>
</div>
</div>
<div class="status" id="status">준비됨</div>
</div>
<div class="ctx-menu" id="ctx">
<div class="ctx-item" onclick="splitClip()">✂ 자르기</div>
<div class="ctx-item" onclick="dupeClip()">📋 복제</div>
<div class="ctx-item danger" onclick="delClip()">🗑 삭제</div>
</div>
<div class="modal" id="exportModal" style="display:none">
<div class="modal-box">
<h3>🎬 영상 내보내기</h3>
<p id="exportMsg">준비중...</p>
<div class="progress"><div class="progress-bar" id="exportBar"></div></div>
<button class="btn btn-secondary" onclick="cancelExport()">취소</button>
</div>
</div>
<div class="modal" id="textModal" style="display:none">
<div class="modal-box" style="min-width:320px">
<h3>📝 텍스트 추가</h3>
<div style="margin:10px 0;text-align:left">
<div style="margin-bottom:8px">
<label style="font-size:11px;color:#666">텍스트 내용</label>
<input type="text" id="textInput" placeholder="텍스트 입력..." style="width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
</div>
<div style="display:flex;gap:8px;margin-bottom:8px">
<div style="flex:1">
<label style="font-size:11px;color:#666">글자 크기</label>
<select id="textSize" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
<option value="24">작게 (24px)</option>
<option value="36">보통 (36px)</option>
<option value="48" selected>크게 (48px)</option>
<option value="64">매우 크게 (64px)</option>
<option value="96">최대 (96px)</option>
</select>
</div>
<div style="flex:1">
<label style="font-size:11px;color:#666">글자 색상</label>
<input type="color" id="textColor" value="#ffffff" style="width:100%;height:32px;border:1px solid #ddd;border-radius:4px;margin-top:4px;cursor:pointer">
</div>
</div>
<div style="display:flex;gap:8px;margin-bottom:8px">
<div style="flex:1">
<label style="font-size:11px;color:#666">배경 스타일</label>
<select id="textBgStyle" onchange="toggleBgColor()" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
<option value="none">배경 없음</option>
<option value="solid" selected>단색 배경</option>
<option value="rounded">둥근 배경</option>
</select>
</div>
<div style="flex:1" id="bgColorBox">
<label style="font-size:11px;color:#666">배경 색상</label>
<input type="color" id="textBgColor" value="#000000" style="width:100%;height:32px;border:1px solid #ddd;border-radius:4px;margin-top:4px;cursor:pointer">
</div>
</div>
<div style="margin-bottom:8px">
<label style="font-size:11px;color:#666">표시 시간 (초)</label>
<input type="number" id="textDuration" value="5" min="1" max="60" step="0.5" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
</div>
</div>
<div style="display:flex;gap:8px;justify-content:center">
<button class="btn btn-secondary" onclick="closeTextModal()">취소</button>
<button class="btn btn-success" onclick="confirmAddText()">추가</button>
</div>
</div>
</div>
<div id="hiddenMedia" class="hidden-media"></div>
<script>
var S={{
media:[],
clips:[],
sel:null,
playing:false,
muted:false,
time:0,
dur:0,
zoom:1,
pps:80,
history:[],
animId:null,
cancelled:false,
els:{{}},
canvas:null,
ctx:null,
lastClipId:null,
ratio:'16:9',
fillMode:'fit',
ratioSizes:{{
'16:9':{{w:1280,h:720,pw:640,ph:360}},
'9:16':{{w:720,h:1280,pw:203,ph:360}},
'1:1':{{w:1080,h:1080,pw:360,ph:360}},
'4:3':{{w:1280,h:960,pw:480,ph:360}},
'4:5':{{w:1080,h:1350,pw:288,ph:360}}
}}
}};
function init(){{
S.canvas=document.getElementById('previewCanvas');
S.ctx=S.canvas.getContext('2d');
updateCanvasSize();
drawPlaceholder();
setupCanvasDrag();
}}
// 캔버스에서 텍스트 드래그 설정
function setupCanvasDrag(){{
var canvas=S.canvas;
var dragging=null;
var dragOffsetX=0,dragOffsetY=0;
canvas.addEventListener('mousedown',function(e){{
var rect=canvas.getBoundingClientRect();
var scaleX=canvas.width/rect.width;
var scaleY=canvas.height/rect.height;
var mx=(e.clientX-rect.left)*scaleX;
var my=(e.clientY-rect.top)*scaleY;
// 현재 시간의 텍스트 클립 중 클릭된 것 찾기
var textClips=getTextClipsAt(S.time);
for(var i=textClips.length-1;i>=0;i--){{
var tc=textClips[i];
if(tc._bounds){{
var b=tc._bounds;
if(mx>=b.x&&mx<=b.x+b.w&&my>=b.y&&my<=b.y+b.h){{
dragging=tc;
selClip(tc.id);
var size=S.ratioSizes[S.ratio];
dragOffsetX=mx-size.pw*tc.posX;
dragOffsetY=my-size.ph*tc.posY;
canvas.style.cursor='move';
e.preventDefault();
return;
}}
}}
}}
}});
canvas.addEventListener('mousemove',function(e){{
var rect=canvas.getBoundingClientRect();
var scaleX=canvas.width/rect.width;
var scaleY=canvas.height/rect.height;
var mx=(e.clientX-rect.left)*scaleX;
var my=(e.clientY-rect.top)*scaleY;
if(dragging){{
var size=S.ratioSizes[S.ratio];
dragging.posX=Math.max(0.1,Math.min(0.9,(mx-dragOffsetX)/size.pw));
dragging.posY=Math.max(0.1,Math.min(0.9,(my-dragOffsetY)/size.ph));
drawFrame();
}}else{{
// 호버 커서 변경
var textClips=getTextClipsAt(S.time);
var onText=false;
for(var i=0;i<textClips.length;i++){{
var tc=textClips[i];
if(tc._bounds){{
var b=tc._bounds;
if(mx>=b.x&&mx<=b.x+b.w&&my>=b.y&&my<=b.y+b.h){{
onText=true;
break;
}}
}}
}}
canvas.style.cursor=onText?'move':'default';
}}
}});
canvas.addEventListener('mouseup',function(){{
if(dragging){{
save();
dragging=null;
canvas.style.cursor='default';
renderProps();
}}
}});
canvas.addEventListener('mouseleave',function(){{
if(dragging){{
save();
dragging=null;
canvas.style.cursor='default';
}}
}});
}}
function updateCanvasSize(){{
var size=S.ratioSizes[S.ratio];
S.canvas.width=size.pw;
S.canvas.height=size.ph;
S.canvas.style.width=size.pw+'px';
S.canvas.style.height=size.ph+'px';
}}
function setRatio(r){{
S.ratio=r;
updateCanvasSize();
drawFrame();
stat('화면 비율: '+r);
}}
function setFillMode(m){{
S.fillMode=m;
drawFrame();
stat('채우기 모드: '+(m==='fit'?'맞춤 (여백)':m==='fill'?'채우기 (확대)':'블러 배경'));
}}
function id(){{return Math.random().toString(36).substr(2,9)}}
function fmt(t){{if(!t||isNaN(t))t=0;var m=Math.floor(t/60),s=Math.floor(t%60),ms=Math.floor((t%1)*100);return String(m).padStart(2,'0')+':'+String(s).padStart(2,'0')+'.'+String(ms).padStart(2,'0')}}
function r(n){{return Math.round(n*1000)/1000}}
function stat(m){{document.getElementById('status').textContent=m}}
function save(){{S.history.push(JSON.stringify(S.clips));if(S.history.length>30)S.history.shift()}}
function drawPlaceholder(){{
var size=S.ratioSizes[S.ratio];
var pw=size.pw,ph=size.ph;
S.ctx.fillStyle='#000';
S.ctx.fillRect(0,0,pw,ph);
S.ctx.fillStyle='#444';
S.ctx.font='14px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('타임라인에 미디어를 추가하세요',pw/2,ph/2);
}}
function addMedia(name,type,url,filePath){{
var m={{id:id(),name:name,type:type,url:url,filePath:filePath||name,dur:type==='image'?5:0,thumb:type==='image'?url:null}};
S.media.push(m);
var container=document.getElementById('hiddenMedia');
if(type==='video'){{
var v=document.createElement('video');
v.src=url;
v.muted=false;
v.playsInline=true;
v.preload='auto';
v.crossOrigin='anonymous';
v.setAttribute('playsinline','');
v.setAttribute('webkit-playsinline','');
container.appendChild(v);
S.els[m.id]=v;
// 버퍼링 강화: 전체 로드 대기
v.load();
v.onloadedmetadata=function(){{
m.dur=r(v.duration);
renderLib();
v.currentTime=0.5;
}};
v.onseeked=function(){{
if(!m.thumb){{
try{{
var c=document.createElement('canvas');
c.width=160;c.height=90;
c.getContext('2d').drawImage(v,0,0,160,90);
m.thumb=c.toDataURL();
renderLib();
}}catch(e){{}}
}}
}};
}}else if(type==='audio'){{
var a=document.createElement('audio');
a.src=url;
a.preload='auto';
container.appendChild(a);
S.els[m.id]=a;
a.onloadedmetadata=function(){{m.dur=r(a.duration);renderLib()}};
}}else if(type==='image'){{
var img=new Image();
img.src=url;
img.crossOrigin='anonymous';
S.els[m.id]=img;
}}
renderLib();
stat('미디어 추가: '+name);
setTimeout(function(){{addClip(m)}},400);
}}
function renderLib(){{
var g=document.getElementById('mediaGrid');
var h=document.getElementById('hint');
h.style.display=S.media.length?'none':'block';
g.innerHTML='';
S.media.forEach(function(m){{
var d=document.createElement('div');
d.className='media-item';
d.draggable=true;
d.ondblclick=function(){{addClip(m)}};
d.ondragstart=function(e){{e.dataTransfer.setData('mid',m.id)}};
var th=m.thumb?'<img src="'+m.thumb+'">':'<div class="media-item-icon">'+(m.type==='video'?'🎬':m.type==='audio'?'🎵':'🖼')+'</div>';
d.innerHTML=th+(m.dur?'<div class="media-item-dur">'+fmt(m.dur)+'</div>':'');
g.appendChild(d);
}});
}}
function trackEnd(tr){{
var end=0;
for(var i=0;i<S.clips.length;i++){{
var c=S.clips[i];
if(c.track===tr){{
var e=r(c.start+(c.te-c.ts));
if(e>end)end=e;
}}
}}
return end;
}}
function addClip(m,at){{
save();
var tr=m.type==='audio'?1:0;
var st=at!==undefined?r(at):trackEnd(tr);
S.clips.push({{
id:id(),
mid:m.id,
name:m.name,
type:m.type,
track:tr,
start:st,
dur:m.dur,
ts:0,
te:m.dur,
vol:1,
filePath:m.filePath
}});
renderTL();
updateDur();
stat('클립 추가: '+m.name);
drawFrame();
}}
function renderTL(){{
['t0','t1','t2'].forEach(function(tid){{document.getElementById(tid).innerHTML=''}});
S.clips.forEach(function(c){{
var tr=document.getElementById('t'+c.track);
var el=document.createElement('div');
el.className='clip '+c.type+(S.sel===c.id?' selected':'');
var len=r(c.te-c.ts);
el.style.left=r(c.start*S.pps*S.zoom)+'px';
el.style.width=Math.max(25,r(len*S.pps*S.zoom))+'px';
el.draggable=true;
el.onclick=function(e){{e.stopPropagation();selClip(c.id)}};
el.oncontextmenu=function(e){{e.preventDefault();selClip(c.id);showCtx(e.clientX,e.clientY)}};
el.ondragstart=function(e){{e.dataTransfer.setData('cid',c.id);e.dataTransfer.setData('ox',e.offsetX)}};
var m=S.media.find(function(x){{return x.id===c.mid}});
var th=m&&m.thumb?'<img class="clip-thumb" src="'+m.thumb+'">':'';
var clipName=c.type==='text'?('📝 '+c.text.substring(0,8)):c.name;
el.innerHTML=th+'<div class="clip-info"><div class="clip-name">'+clipName+'</div><div class="clip-dur">'+fmt(len)+'</div></div><div class="clip-handle clip-handle-l"></div><div class="clip-handle clip-handle-r"></div>';
el.querySelector('.clip-handle-l').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'l',e)}};
el.querySelector('.clip-handle-r').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'r',e)}};
tr.appendChild(el);
}});
renderRuler();
setupDrop();
}}
function renderRuler(){{
var ru=document.getElementById('ruler');
var w=Math.max(r(S.dur*S.pps*S.zoom)+150,600);
ru.style.width=w+'px';
var h='<svg width="100%" height="18" style="position:absolute;left:50px">';
var step=S.zoom<0.7?5:S.zoom<1.5?2:1;
for(var i=0;i<=S.dur+10;i+=step){{
var x=r(i*S.pps*S.zoom);
h+='<line x1="'+x+'" y1="13" x2="'+x+'" y2="18" stroke="#ccc"/>';
h+='<text x="'+x+'" y="10" fill="#999" font-size="8" text-anchor="middle">'+fmt(i)+'</text>';
}}
ru.innerHTML=h+'</svg>';
}}
function setupDrop(){{
['t0','t1','t2'].forEach(function(tid,idx){{
var tr=document.getElementById(tid);
tr.ondragover=function(e){{e.preventDefault();tr.classList.add('drop-zone')}};
tr.ondragleave=function(){{tr.classList.remove('drop-zone')}};
tr.ondrop=function(e){{
e.preventDefault();
tr.classList.remove('drop-zone');
var rect=tr.getBoundingClientRect();
var t=r(Math.max(0,(e.clientX-rect.left)/(S.pps*S.zoom)));
var mid=e.dataTransfer.getData('mid');
var cid=e.dataTransfer.getData('cid');
var ox=parseFloat(e.dataTransfer.getData('ox')||0);
if(mid){{
var m=S.media.find(function(x){{return x.id===mid}});
if(m)addClip(m,t);
}}else if(cid){{
save();
var c=S.clips.find(function(x){{return x.id===cid}});
if(c){{
c.start=r(Math.max(0,t-ox/(S.pps*S.zoom)));
// 텍스트는 텍스트 트랙으로만, 그 외는 영상/오디오 트랙으로
if(c.type==='text'){{
c.track=2;
}}else if(c.type==='audio'){{
c.track=1;
}}else{{
c.track=idx===2?0:idx;
}}
renderTL();
updateDur();
drawFrame();
}}
}}
}};
}});
}}
var trimData=null;
function startTrim(cid,side,e){{
e.preventDefault();
var c=S.clips.find(function(x){{return x.id===cid}});
if(!c)return;
save();
trimData={{cid:cid,side:side,sx:e.clientX,ots:c.ts,ote:c.te,ost:c.start}};
document.addEventListener('mousemove',doTrim);
document.addEventListener('mouseup',endTrim);
}}
function doTrim(e){{
if(!trimData)return;
var c=S.clips.find(function(x){{return x.id===trimData.cid}});
if(!c)return;
var dx=e.clientX-trimData.sx;
var dt=r(dx/(S.pps*S.zoom));
if(trimData.side==='l'){{
var newTs=Math.max(0,Math.min(c.te-0.1,trimData.ots+dt));
c.ts=r(newTs);
c.start=r(trimData.ost+(newTs-trimData.ots));
}}else{{
c.te=r(Math.max(c.ts+0.1,Math.min(c.dur,trimData.ote+dt)));
}}
renderTL();
updateDur();
}}
function endTrim(){{
trimData=null;
document.removeEventListener('mousemove',doTrim);
document.removeEventListener('mouseup',endTrim);
}}
function selClip(cid){{S.sel=cid;renderTL();renderProps()}}
function renderProps(){{
var box=document.getElementById('propsBox');
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(!c){{box.innerHTML='<div class="no-sel">클립 선택</div>';return}}
var len=r(c.te-c.ts);
if(c.type==='text'){{
// 텍스트 클립 속성
box.innerHTML='<div class="prop-group"><div class="prop-label">텍스트</div><input class="prop-input" value="'+c.text+'" onchange="setProp(\\'text\\',this.value)"></div>'+
'<div class="prop-group"><div class="prop-label">시작</div><input class="prop-input" type="number" step="0.1" value="'+c.start+'" onchange="setProp(\\'start\\',parseFloat(this.value))"></div>'+
'<div class="prop-group"><div class="prop-label">길이: '+fmt(len)+'</div></div>'+
'<div class="prop-group"><div class="prop-label">위치 X ('+Math.round((c.posX||0.5)*100)+'%)</div><input class="prop-input" type="range" min="0.05" max="0.95" step="0.01" value="'+(c.posX||0.5)+'" oninput="setProp(\\'posX\\',parseFloat(this.value))"></div>'+
'<div class="prop-group"><div class="prop-label">위치 Y ('+Math.round((c.posY||0.85)*100)+'%)</div><input class="prop-input" type="range" min="0.05" max="0.95" step="0.01" value="'+(c.posY||0.85)+'" oninput="setProp(\\'posY\\',parseFloat(this.value))"></div>'+
'<div class="prop-group"><div class="prop-label">글자 크기</div><select class="prop-input" onchange="setProp(\\'fontSize\\',parseInt(this.value))">'+
'<option value="24"'+(c.fontSize===24?' selected':'')+'>작게</option>'+
'<option value="36"'+(c.fontSize===36?' selected':'')+'>보통</option>'+
'<option value="48"'+(c.fontSize===48?' selected':'')+'>크게</option>'+
'<option value="64"'+(c.fontSize===64?' selected':'')+'>매우 크게</option>'+
'<option value="96"'+(c.fontSize===96?' selected':'')+'>최대</option>'+
'</select></div>'+
'<div class="prop-group"><div class="prop-label">글자 색상</div><input class="prop-input" type="color" value="'+c.fontColor+'" onchange="setProp(\\'fontColor\\',this.value)"></div>'+
'<div class="prop-group"><div class="prop-label">배경 스타일</div><select class="prop-input" onchange="setProp(\\'bgStyle\\',this.value)">'+
'<option value="none"'+(c.bgStyle==='none'?' selected':'')+'>없음</option>'+
'<option value="solid"'+(c.bgStyle==='solid'?' selected':'')+'>단색</option>'+
'<option value="rounded"'+(c.bgStyle==='rounded'?' selected':'')+'>둥근</option>'+
'</select></div>'+
'<div class="prop-group"><div class="prop-label">배경 색상</div><input class="prop-input" type="color" value="'+c.bgColor+'" onchange="setProp(\\'bgColor\\',this.value)"></div>';
}}else{{
// 기존 미디어 클립 속성
box.innerHTML='<div class="prop-group"><div class="prop-label">이름</div><input class="prop-input" value="'+c.name+'" onchange="setProp(\\'name\\',this.value)"></div>'+
'<div class="prop-group"><div class="prop-label">시작</div><input class="prop-input" type="number" step="0.1" value="'+c.start+'" onchange="setProp(\\'start\\',parseFloat(this.value))"></div>'+
'<div class="prop-group"><div class="prop-label">길이: '+fmt(len)+'</div></div>'+
(c.type!=='image'?'<div class="prop-group"><div class="prop-label">볼륨 '+Math.round(c.vol*100)+'%</div><input class="prop-input" type="range" min="0" max="1" step="0.05" value="'+c.vol+'" oninput="setProp(\\'vol\\',parseFloat(this.value))"></div>':'');
}}
}}
function setProp(p,v){{
save();
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(c){{c[p]=p==='start'?r(v):v;renderTL();updateDur();renderProps();drawFrame()}}
}}
function splitClip(){{
if(!S.sel){{alert('클립을 선택하세요');return}}
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(!c)return;
var cEnd=r(c.start+c.te-c.ts);
if(S.time<=c.start||S.time>=cEnd){{alert('플레이헤드가 클립 안에 있어야 합니다');return}}
save();
var splitAt=r(S.time-c.start);
var c2=JSON.parse(JSON.stringify(c));
c2.id=id();
c2.start=r(S.time);
c2.ts=r(c.ts+splitAt);
c.te=r(c.ts+splitAt);
S.clips.push(c2);
renderTL();updateDur();hideCtx();stat('클립 분할됨');
}}
function dupeClip(){{
if(!S.sel)return;
var c=S.clips.find(function(x){{return x.id===S.sel}});
if(!c)return;
save();
var len=r(c.te-c.ts);
var nc=JSON.parse(JSON.stringify(c));
nc.id=id();
nc.start=r(c.start+len);
S.clips.push(nc);
renderTL();updateDur();hideCtx();stat('클립 복제됨');
}}
function delClip(){{
if(!S.sel)return;
save();
S.clips=S.clips.filter(function(x){{return x.id!==S.sel}});
S.sel=null;
renderTL();renderProps();updateDur();hideCtx();stat('클립 삭제됨');
drawFrame();
}}
function undo(){{if(S.history.length){{S.clips=JSON.parse(S.history.pop());renderTL();updateDur();stat('실행취소');drawFrame()}}}}
function updateDur(){{
var mx=0;
for(var i=0;i<S.clips.length;i++){{
var c=S.clips[i];
var e=r(c.start+c.te-c.ts);
if(e>mx)mx=e;
}}
S.dur=mx;
document.getElementById('totT').textContent=fmt(mx);
}}
function togglePlay(){{
S.playing=!S.playing;
document.getElementById('playBtn').textContent=S.playing?'⏸':'▶';
if(S.playing)play();else stop();
}}
function play(){{
// 현재 비주얼 클립 찾기
var vc=getClipAt(S.time,'visual');
if(vc&&vc.type==='video'){{
var el=S.els[vc.mid];
if(el){{
el.currentTime=S.time-vc.start+vc.ts;
el.play().catch(function(){{}});
}}
}}
// 오디오 클립들 시작
S.clips.forEach(function(c){{
if(c.type==='audio'){{
var cEnd=c.start+(c.te-c.ts);
if(S.time>=c.start&&S.time<cEnd){{
var el=S.els[c.mid];
if(el){{
el.currentTime=S.time-c.start+c.ts;
el.volume=S.muted?0:c.vol;
el.play().catch(function(){{}});
}}
}}
}}
}});
function loop(){{
if(!S.playing)return;
var vc=getClipAt(S.time,'visual');
if(vc&&vc.type==='video'){{
var el=S.els[vc.mid];
if(el&&!el.paused){{
S.time=vc.start+(el.currentTime-vc.ts);
}}else{{
S.time+=1/60;
}}
}}else{{
S.time+=1/60;
}}
if(S.time>=S.dur){{
S.time=0;
if(S.dur===0){{S.playing=false;document.getElementById('playBtn').textContent='▶';return}}
}}
updateHead();
drawFrameSmooth();
S.animId=requestAnimationFrame(loop);
}}
S.animId=requestAnimationFrame(loop);
}}
function drawFrameSmooth(){{
var t=S.time;
var vc=getClipAt(t,'visual');
var size=S.ratioSizes[S.ratio];
var pw=size.pw,ph=size.ph;
S.ctx.fillStyle='#000';
S.ctx.fillRect(0,0,pw,ph);
if(vc){{
var el=S.els[vc.mid];
if(el){{
if(vc.type==='video'){{
el.volume=S.muted?0:vc.vol;
}}
try{{
var sw=el.videoWidth||el.naturalWidth||el.width||pw;
var sh=el.videoHeight||el.naturalHeight||el.height||ph;
drawWithMode(S.ctx,el,sw,sh,pw,ph,S.fillMode);
}}catch(e){{}}
}}
}}else if(S.clips.length===0){{
S.ctx.fillStyle='#444';
S.ctx.font='14px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('Add media to timeline',pw/2,ph/2);
}}
// 오디오 동기화 (가벼운 체크만)
S.clips.forEach(function(c){{
if(c.type!=='audio')return;
var cEnd=c.start+(c.te-c.ts);
var el=S.els[c.mid];
if(!el)return;
if(t>=c.start&&t<cEnd){{
el.volume=S.muted?0:c.vol;
if(el.paused)el.play().catch(function(){{}});
}}else{{
if(!el.paused)el.pause();
}}
}});
if(!vc&&S.clips.length>0){{
var hasText=getTextClipsAt(t).length>0;
if(!hasText){{
S.ctx.fillStyle='#333';
S.ctx.font='12px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('No media at playhead',pw/2,ph/2);
}}
}}
var textClips=getTextClipsAt(t);
textClips.forEach(function(tc){{
drawText(S.ctx,tc,pw,ph);
}});
}}
function stop(){{
if(S.animId){{cancelAnimationFrame(S.animId);S.animId=null}}
Object.keys(S.els).forEach(function(k){{
var el=S.els[k];
if(el&&el.pause){{
el.pause();
}}
}});
drawFrame();
}}
function seek(t){{
S.time=Math.max(0,Math.min(S.dur||0,t));
// 비디오/오디오 위치도 동기화
S.clips.forEach(function(c){{
var el=S.els[c.mid];
if(!el)return;
var cEnd=c.start+(c.te-c.ts);
if(t>=c.start&&t<cEnd){{
el.currentTime=t-c.start+c.ts;
}}
}});
updateHead();
drawFrame();
}}
function updateHead(){{
document.getElementById('playhead').style.left=(50+S.time*S.pps*S.zoom)+'px';
document.getElementById('curT').textContent=fmt(S.time);
}}
function getClipAt(t,type){{
var sorted=S.clips.filter(function(c){{
if(type==='visual')return c.type==='video'||c.type==='image';
if(type==='audio')return c.type==='audio';
return true;
}}).sort(function(a,b){{return a.start-b.start}});
for(var i=0;i<sorted.length;i++){{
var c=sorted[i];
var cEnd=c.start+(c.te-c.ts);
if(t>=c.start&&t<cEnd)return c;
}}
return null;
}}
function drawFrame(){{
var t=S.time;
var vc=getClipAt(t,'visual');
var size=S.ratioSizes[S.ratio];
var pw=size.pw,ph=size.ph;
S.ctx.fillStyle='#000';
S.ctx.fillRect(0,0,pw,ph);
if(vc){{
var el=S.els[vc.mid];
if(el){{
if(vc.type==='video'){{
var clipT=t-vc.start+vc.ts;
if(Math.abs(el.currentTime-clipT)>0.3){{
el.currentTime=clipT;
}}
if(S.playing&&el.paused)el.play().catch(function(){{}});
if(!S.playing&&!el.paused)el.pause();
el.volume=S.muted?0:vc.vol;
}}
try{{
var sw=el.videoWidth||el.naturalWidth||el.width||pw;
var sh=el.videoHeight||el.naturalHeight||el.height||ph;
drawWithMode(S.ctx,el,sw,sh,pw,ph,S.fillMode);
}}catch(e){{}}
}}
}}else if(S.clips.length===0){{
S.ctx.fillStyle='#444';
S.ctx.font='14px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('타임라인에 미디어를 추가하세요',pw/2,ph/2);
}}
var audioClips=S.clips.filter(function(c){{
if(c.type!=='audio')return false;
var cEnd=c.start+(c.te-c.ts);
return t>=c.start&&t<cEnd;
}});
audioClips.forEach(function(ac){{
var el=S.els[ac.mid];
if(el){{
var clipT=t-ac.start+ac.ts;
if(Math.abs(el.currentTime-clipT)>0.5)el.currentTime=clipT;
el.volume=S.muted?0:ac.vol;
if(S.playing&&el.paused)el.play().catch(function(){{}});
if(!S.playing&&!el.paused)el.pause();
}}
}});
S.clips.forEach(function(c){{
if(c.type!=='audio')return;
var cEnd=c.start+(c.te-c.ts);
if(t<c.start||t>=cEnd){{
var el=S.els[c.mid];
if(el&&!el.paused)el.pause();
}}
}});
if(!vc&&!audioClips.length&&S.clips.length>0){{
var hasText=getTextClipsAt(t).length>0;
if(!hasText){{
S.ctx.fillStyle='#333';
S.ctx.font='12px sans-serif';
S.ctx.textAlign='center';
S.ctx.fillText('재생 위치에 미디어가 없습니다',pw/2,ph/2);
}}
}}
// 텍스트 오버레이 렌더링
var textClips=getTextClipsAt(t);
textClips.forEach(function(tc){{
drawText(S.ctx,tc,pw,ph);
}});
}}
function drawWithMode(ctx,el,sw,sh,dw,dh,mode){{
if(mode==='fill'){{
// 채우기: 캔버스를 꽉 채우도록 확대, 넘치는 부분 잘림
var scale=Math.max(dw/sw,dh/sh);
var nw=sw*scale,nh=sh*scale;
var ox=(dw-nw)/2,oy=(dh-nh)/2;
ctx.drawImage(el,ox,oy,nw,nh);
}}else if(mode==='blur'){{
// 프레임 먼저 캡처
var frameCanvas=document.createElement('canvas');
frameCanvas.width=sw;frameCanvas.height=sh;
var frameCtx=frameCanvas.getContext('2d');
frameCtx.drawImage(el,0,0,sw,sh);
// 블러용 작은 캔버스
var blurCanvas=document.createElement('canvas');
blurCanvas.width=16;blurCanvas.height=16;
var blurCtx=blurCanvas.getContext('2d');
blurCtx.drawImage(frameCanvas,0,0,16,16);
// 배경
ctx.imageSmoothingEnabled=true;
ctx.imageSmoothingQuality='high';
var scale=Math.max(dw/sw,dh/sh)*1.1;
var nw=sw*scale,nh=sh*scale;
var ox=(dw-nw)/2,oy=(dh-nh)/2;
ctx.drawImage(blurCanvas,ox,oy,nw,nh);
// 어둡게
ctx.fillStyle='rgba(0,0,0,0.4)';
ctx.fillRect(0,0,dw,dh);
// 원본 (캡처된 프레임)
var fitScale=Math.min(dw/sw,dh/sh);
var fw=sw*fitScale,fh=sh*fitScale;
var fx=(dw-fw)/2,fy=(dh-fh)/2;
ctx.drawImage(frameCanvas,fx,fy,fw,fh);
}}else{{
// 맞춤 (fit): 원본 비율 유지, 여백
var scale=Math.min(dw/sw,dh/sh);
var nw=sw*scale,nh=sh*scale;
var ox=(dw-nw)/2,oy=(dh-nh)/2;
ctx.drawImage(el,ox,oy,nw,nh);
}}
}}
function toggleMute(){{S.muted=!S.muted;document.getElementById('muteBtn').textContent=S.muted?'🔇':'🔊'}}
// 텍스트 클립 관련 함수들
function addTextClip(){{
document.getElementById('textModal').style.display='flex';
document.getElementById('textInput').value='';
document.getElementById('textInput').focus();
}}
function closeTextModal(){{
document.getElementById('textModal').style.display='none';
}}
function toggleBgColor(){{
var style=document.getElementById('textBgStyle').value;
document.getElementById('bgColorBox').style.opacity=style==='none'?'0.5':'1';
}}
function confirmAddText(){{
var text=document.getElementById('textInput').value.trim();
if(!text){{alert('텍스트를 입력하세요');return}}
save();
var duration=parseFloat(document.getElementById('textDuration').value)||5;
S.clips.push({{
id:id(),
type:'text',
track:2,
start:S.time,
dur:duration,
ts:0,
te:duration,
text:text,
fontSize:parseInt(document.getElementById('textSize').value),
fontColor:document.getElementById('textColor').value,
bgStyle:document.getElementById('textBgStyle').value,
bgColor:document.getElementById('textBgColor').value,
posX:0.5, // 0~1 비율 (가운데)
posY:0.85 // 0~1 비율 (하단)
}});
closeTextModal();
renderTL();
updateDur();
drawFrame();
stat('텍스트 추가: '+text);
}}
function getTextClipsAt(t){{
return S.clips.filter(function(c){{
if(c.type!=='text')return false;
var cEnd=c.start+(c.te-c.ts);
return t>=c.start&&t<cEnd;
}});
}}
function drawText(ctx,clip,dw,dh){{
var text=clip.text;
var fontSize=clip.fontSize||48;
var fontColor=clip.fontColor||'#ffffff';
var bgStyle=clip.bgStyle||'none';
var bgColor=clip.bgColor||'#000000';
var posX=clip.posX!==undefined?clip.posX:0.5;
var posY=clip.posY!==undefined?clip.posY:0.85;
ctx.font='bold '+fontSize+'px -apple-system,BlinkMacSystemFont,sans-serif';
ctx.textAlign='center';
ctx.textBaseline='middle';
var metrics=ctx.measureText(text);
var textW=metrics.width;
var textH=fontSize;
var x=dw*posX;
var y=dh*posY;
// 텍스트 영역 저장 (클릭 감지용)
clip._bounds={{
x:x-textW/2-fontSize*0.3,
y:y-textH/2-fontSize*0.15,
w:textW+fontSize*0.6,
h:textH+fontSize*0.3
}};
if(bgStyle!=='none'){{
var padding=fontSize*0.3;
var bgX=x-textW/2-padding;
var bgY=y-textH/2-padding/2;
var bgW=textW+padding*2;
var bgH=textH+padding;
ctx.fillStyle=bgColor+'cc';
if(bgStyle==='rounded'){{
ctx.beginPath();
ctx.roundRect(bgX,bgY,bgW,bgH,10);
ctx.fill();
}}else{{
ctx.fillRect(bgX,bgY,bgW,bgH);
}}
}}
// 텍스트 그림자
ctx.fillStyle='rgba(0,0,0,0.5)';
ctx.fillText(text,x+2,y+2);
// 텍스트
ctx.fillStyle=fontColor;
ctx.fillText(text,x,y);
// 선택된 텍스트면 테두리 표시
if(S.sel===clip.id){{
ctx.strokeStyle='#6366f1';
ctx.lineWidth=2;
ctx.setLineDash([5,3]);
ctx.strokeRect(clip._bounds.x,clip._bounds.y,clip._bounds.w,clip._bounds.h);
ctx.setLineDash([]);
}}
}}
function setZoom(v){{S.zoom=parseFloat(v);renderTL();updateHead()}}
function tlClick(e){{
if(e.target.closest('.clip'))return;
var rect=document.getElementById('tlBox').getBoundingClientRect();
var scrollL=document.getElementById('tlBox').scrollLeft;
S.time=Math.max(0,Math.min(S.dur||0,(e.clientX-rect.left-50+scrollL)/(S.pps*S.zoom)));
updateHead();
drawFrame();
}}
function showCtx(x,y){{var m=document.getElementById('ctx');m.style.display='block';m.style.left=x+'px';m.style.top=y+'px'}}
function hideCtx(){{document.getElementById('ctx').style.display='none'}}
document.addEventListener('click',function(e){{if(!e.target.closest('.ctx-menu'))hideCtx()}});
function exportVideo(){{
if(!S.clips.length){{alert('클립을 추가하세요');return}}
S.cancelled=false;
document.getElementById('exportModal').style.display='flex';
document.getElementById('exportBar').style.width='0%';
document.getElementById('exportMsg').textContent='녹화 준비 중...';
doExport();
}}
// ============================================
// 핵심 수정: 더블 버퍼링으로 블러 번쩍임 방지
// ============================================
async function doExport(){{
var size=S.ratioSizes[S.ratio];
var exportW=size.w,exportH=size.h;
// ★ 메인 캔버스 (MediaRecorder 연결) - 완성된 프레임만 받음
var mainCanvas=document.createElement('canvas');
mainCanvas.width=exportW;mainCanvas.height=exportH;
var mainCtx=mainCanvas.getContext('2d');
// ★ 오프스크린 캔버스 (렌더링용) - 여기서 모든 작업 후 한번에 복사
var offCanvas=document.createElement('canvas');
offCanvas.width=exportW;offCanvas.height=exportH;
var offCtx=offCanvas.getContext('2d');
// 초기 검은 화면
mainCtx.fillStyle='#000';
mainCtx.fillRect(0,0,exportW,exportH);
var stream=mainCanvas.captureStream(30);
// 고화질 설정
var opts={{mimeType:'video/webm;codecs=vp9',videoBitsPerSecond:8000000}};
if(!MediaRecorder.isTypeSupported(opts.mimeType)){{
opts={{mimeType:'video/webm;codecs=vp8',videoBitsPerSecond:8000000}};
}}
if(!MediaRecorder.isTypeSupported(opts.mimeType)){{
opts={{mimeType:'video/webm',videoBitsPerSecond:5000000}};
}}
var rec=new MediaRecorder(stream,opts);
var chunks=[];
rec.ondataavailable=function(e){{if(e.data.size>0)chunks.push(e.data)}};
document.getElementById('exportMsg').textContent='녹화 중... ('+S.ratio+')';
rec.start(100);
var dur=S.dur;
var fillMode=S.fillMode;
// 블러용 캔버스 (재사용)
var frameCanvas=document.createElement('canvas');
var frameCtx=frameCanvas.getContext('2d');
var blurCanvas=document.createElement('canvas');
blurCanvas.width=16;blurCanvas.height=16;
var blurCtx=blurCanvas.getContext('2d');
// 모든 비디오를 처음으로 되돌리고 재생
videoClips.forEach(function(vc){{
var el=S.els[vc.mid];
if(el){{
el.currentTime=vc.ts;
el.muted=true; // 내보내기 중에만 음소거 (정상)
}}
}});
// 잠시 대기 후 재생 시작
await new Promise(function(r){{setTimeout(r,200)}});
videoClips.forEach(function(vc){{
var el=S.els[vc.mid];
if(el)el.play().catch(function(){{}});
}});
var startTime=performance.now();
// 실시간 렌더링 루프
await new Promise(function(resolve){{
function render(){{
if(S.cancelled){{rec.stop();resolve();return}}
var elapsed=(performance.now()-startTime)/1000;
if(elapsed>=dur){{
rec.stop();
setTimeout(resolve,200);
return;
}}
// 진행률 업데이트
document.getElementById('exportBar').style.width=(elapsed/dur*100)+'%';
document.getElementById('exportMsg').textContent='녹화 중... '+Math.round(elapsed/dur*100)+'%';
// ★ 오프스크린 캔버스에 완전히 렌더링 ★
offCtx.fillStyle='#000';
offCtx.fillRect(0,0,exportW,exportH);
var vc=getClipAt(elapsed,'visual');
if(vc){{
var el=S.els[vc.mid];
if(el){{
// 비디오 시간 동기화 (차이가 크면 보정)
if(vc.type==='video'){{
var targetT=elapsed-vc.start+vc.ts;
if(Math.abs(el.currentTime-targetT)>0.5){{
el.currentTime=targetT;
}}
}}
try{{
var sw=el.videoWidth||el.naturalWidth||el.width||exportW;
var sh=el.videoHeight||el.naturalHeight||el.height||exportH;
if(fillMode==='blur'){{
// ★ 블러: 오프스크린에서 완전히 처리 후 메인에 복사 ★
frameCanvas.width=sw;
frameCanvas.height=sh;
frameCtx.drawImage(el,0,0,sw,sh);
blurCtx.drawImage(frameCanvas,0,0,16,16);
offCtx.imageSmoothingEnabled=true;
offCtx.imageSmoothingQuality='high';
var scale=Math.max(exportW/sw,exportH/sh)*1.1;
var nw=sw*scale,nh=sh*scale;
offCtx.drawImage(blurCanvas,(exportW-nw)/2,(exportH-nh)/2,nw,nh);
offCtx.fillStyle='rgba(0,0,0,0.4)';
offCtx.fillRect(0,0,exportW,exportH);
var fitScale=Math.min(exportW/sw,exportH/sh);
var fw=sw*fitScale,fh=sh*fitScale;
offCtx.drawImage(frameCanvas,(exportW-fw)/2,(exportH-fh)/2,fw,fh);
}}else if(fillMode==='fill'){{
var scale=Math.max(exportW/sw,exportH/sh);
var nw=sw*scale,nh=sh*scale;
offCtx.drawImage(el,(exportW-nw)/2,(exportH-nh)/2,nw,nh);
}}else{{
// fit
var scale=Math.min(exportW/sw,exportH/sh);
var nw=sw*scale,nh=sh*scale;
offCtx.drawImage(el,(exportW-nw)/2,(exportH-nh)/2,nw,nh);
}}
}}catch(e){{console.error('Draw error:',e)}}
}}
}}
// 텍스트 오버레이 렌더링 (오프스크린에)
var textClips=getTextClipsAt(elapsed);
textClips.forEach(function(tc){{
drawTextExport(offCtx,tc,exportW,exportH);
}});
// ★ 오프스크린 → 메인 캔버스로 한번에 복사 (atomic) ★
mainCtx.drawImage(offCanvas,0,0);
requestAnimationFrame(render);
}}
requestAnimationFrame(render);
}});
// 정리
Object.keys(S.els).forEach(function(k){{
var el=S.els[k];
if(el&&el.pause)el.pause();
}});
if(S.cancelled)return;
var webmBlob=new Blob(chunks,{{type:'video/webm'}});
if(webmBlob.size<1000){{document.getElementById('exportMsg').textContent='녹화 실패';return}}
document.getElementById('exportBar').style.width='100%';
document.getElementById('exportMsg').textContent='완료! ('+Math.round(webmBlob.size/1024/1024*10)/10+'MB, '+S.ratio+') - 아래에서 다운로드';
var downloadDiv=document.createElement('div');
downloadDiv.style.marginTop='10px';
var webmLink=document.createElement('a');
webmLink.href=URL.createObjectURL(webmBlob);
webmLink.download='video_'+S.ratio.replace(':','x')+'_'+Date.now()+'.webm';
webmLink.className='btn btn-success';
webmLink.textContent='📥 WebM 다운로드';
webmLink.style.marginRight='5px';
downloadDiv.appendChild(webmLink);
var copyBtn=document.createElement('button');
copyBtn.className='btn btn-secondary';
copyBtn.textContent='📋 MP4변환용 복사';
copyBtn.onclick=async function(){{
document.getElementById('exportMsg').textContent='데이터 준비 중...';
var reader=new FileReader();
reader.onload=function(){{
var base64=reader.result.split(',')[1];
navigator.clipboard.writeText(base64).then(function(){{
document.getElementById('exportMsg').textContent='복사 완료! 위 입력란에 붙여넣기';
alert('복사 완료!\\n\\nGradio의 "WebM 데이터" 입력란에 붙여넣기(Ctrl+V) 후\\n"MP4 변환" 버튼을 클릭하세요.');
}}).catch(function(){{
prompt('아래 데이터를 복사하세요:', base64.substring(0,100)+'...');
}});
}};
reader.readAsDataURL(webmBlob);
}};
downloadDiv.appendChild(copyBtn);
document.querySelector('.modal-box').appendChild(downloadDiv);
}}
// 내보내기용 텍스트 렌더링
function drawTextExport(ctx,clip,dw,dh){{
var text=clip.text;
var fontSize=Math.round(clip.fontSize*(dw/640))||72;
var fontColor=clip.fontColor||'#ffffff';
var bgStyle=clip.bgStyle||'none';
var bgColor=clip.bgColor||'#000000';
var posX=clip.posX!==undefined?clip.posX:0.5;
var posY=clip.posY!==undefined?clip.posY:0.85;
ctx.font='bold '+fontSize+'px -apple-system,BlinkMacSystemFont,sans-serif';
ctx.textAlign='center';
ctx.textBaseline='middle';
var metrics=ctx.measureText(text);
var textW=metrics.width;
var textH=fontSize;
var x=dw*posX;
var y=dh*posY;
if(bgStyle!=='none'){{
var padding=fontSize*0.3;
var bgX=x-textW/2-padding;
var bgY=y-textH/2-padding/2;
var bgW=textW+padding*2;
var bgH=textH+padding;
ctx.fillStyle=bgColor+'cc';
if(bgStyle==='rounded'){{
ctx.beginPath();
ctx.roundRect(bgX,bgY,bgW,bgH,15);
ctx.fill();
}}else{{
ctx.fillRect(bgX,bgY,bgW,bgH);
}}
}}
ctx.fillStyle='rgba(0,0,0,0.5)';
ctx.fillText(text,x+3,y+3);
ctx.fillStyle=fontColor;
ctx.fillText(text,x,y);
}}
function cancelExport(){{S.cancelled=true;document.getElementById('exportModal').style.display='none'}}
document.addEventListener('keydown',function(e){{
if(e.target.tagName==='INPUT')return;
if(e.code==='Space'){{e.preventDefault();togglePlay()}}
else if(e.code==='Delete'){{e.preventDefault();delClip()}}
else if(e.code==='ArrowLeft'){{seek(S.time-0.1)}}
else if(e.code==='ArrowRight'){{seek(S.time+0.1)}}
}});
init();
renderTL();
stat('준비됨');
var initData={media_data};
if(initData&&initData.length)initData.forEach(function(m){{addMedia(m.name,m.type,m.dataUrl,m.filePath)}});
</script>
</body>
</html>'''
def process_file(files):
"""파일 처리 및 서버에 저장"""
global uploaded_files
if not files:
return []
results = []
file_list = files if isinstance(files, list) else [files]
for f in file_list:
if not f:
continue
path = f.name if hasattr(f, 'name') else f
name = os.path.basename(path)
ext = name.lower().split('.')[-1]
if ext in ['mp4', 'webm', 'mov', 'avi', 'mkv']:
t, m = 'video', f'video/{ext}'
elif ext in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
t, m = 'image', f'image/{ext}'
elif ext in ['mp3', 'wav', 'ogg', 'm4a', 'aac']:
t, m = 'audio', f'audio/{ext}'
else:
continue
# 서버에 파일 복사 (MP4 내보내기용)
dst_path = os.path.join(UPLOAD_DIR, f"{int(time.time()*1000)}_{name}")
shutil.copy(path, dst_path)
uploaded_files[name] = dst_path
with open(path, 'rb') as fp:
d = base64.b64encode(fp.read()).decode()
results.append({'name': name, 'type': t, 'dataUrl': f'data:{m};base64,{d}', 'filePath': name})
return results
def make_iframe(data):
j = json.dumps(data, ensure_ascii=False)
h = get_editor_html(j).replace("'", "&#39;")
return f"<iframe srcdoc='{h}' style='width:100%;height:750px;border:none;border-radius:10px'></iframe>"
def export_mp4(export_json):
"""서버 사이드 MP4 내보내기"""
global uploaded_files
if not export_json or len(export_json) < 10:
return None
try:
data = json.loads(export_json)
clips = data.get('clips', [])
if not clips:
return None
video_clips = [c for c in clips if c['type'] in ['video', 'image']]
if not video_clips:
return None
temp_dir = tempfile.mkdtemp()
output_path = os.path.join(temp_dir, f'output_{int(time.time())}.mp4')
# 단일 클립
if len(video_clips) == 1:
clip = video_clips[0]
file_path = uploaded_files.get(clip['filePath'])
if not file_path or not os.path.exists(file_path):
return None
duration = clip['te'] - clip['ts']
if clip['type'] == 'image':
cmd = ['ffmpeg', '-y', '-loop', '1', '-i', file_path, '-c:v', 'libx264', '-t', str(duration), '-pix_fmt', 'yuv420p', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', output_path]
else:
cmd = ['ffmpeg', '-y', '-i', file_path, '-ss', str(clip['ts']), '-t', str(duration), '-c:v', 'libx264', '-preset', 'fast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', '-movflags', '+faststart', output_path]
subprocess.run(cmd, capture_output=True, timeout=300)
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
return output_path
return None
# 여러 클립
temp_files = []
concat_file = os.path.join(temp_dir, 'concat.txt')
for i, clip in enumerate(sorted(video_clips, key=lambda x: x['start'])):
file_path = uploaded_files.get(clip['filePath'])
if not file_path or not os.path.exists(file_path):
continue
temp_out = os.path.join(temp_dir, f'temp_{i}.mp4')
duration = clip['te'] - clip['ts']
if clip['type'] == 'image':
cmd = ['ffmpeg', '-y', '-loop', '1', '-i', file_path, '-c:v', 'libx264', '-t', str(duration), '-pix_fmt', 'yuv420p', '-r', '30', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', temp_out]
else:
cmd = ['ffmpeg', '-y', '-i', file_path, '-ss', str(clip['ts']), '-t', str(duration), '-c:v', 'libx264', '-preset', 'fast', '-c:a', 'aac', '-r', '30', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', temp_out]
subprocess.run(cmd, capture_output=True, timeout=120)
if os.path.exists(temp_out):
temp_files.append(temp_out)
if not temp_files:
return None
with open(concat_file, 'w') as f:
for tf in temp_files:
f.write(f"file '{tf}'\n")
cmd = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_file, '-c:v', 'libx264', '-preset', 'fast', '-c:a', 'aac', '-movflags', '+faststart', output_path]
subprocess.run(cmd, capture_output=True, timeout=300)
for tf in temp_files:
try: os.remove(tf)
except: pass
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
return output_path
return None
except Exception as e:
print(f"[Export] Error: {e}")
return None
def convert_webm_to_mp4(webm_base64):
"""WebM base64 데이터를 MP4로 변환"""
if not webm_base64 or len(webm_base64) < 100:
return None
try:
# base64 디코딩
webm_data = base64.b64decode(webm_base64)
temp_dir = tempfile.mkdtemp()
webm_path = os.path.join(temp_dir, 'input.webm')
mp4_path = os.path.join(temp_dir, f'output_{int(time.time())}.mp4')
# WebM 파일 저장
with open(webm_path, 'wb') as f:
f.write(webm_data)
# FFmpeg로 MP4 변환
cmd = [
'ffmpeg', '-y',
'-i', webm_path,
'-c:v', 'libx264',
'-preset', 'fast',
'-crf', '23',
'-c:a', 'aac',
'-b:a', '128k',
'-movflags', '+faststart',
mp4_path
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
# WebM 파일 삭제
try:
os.remove(webm_path)
except:
pass
if os.path.exists(mp4_path) and os.path.getsize(mp4_path) > 0:
return mp4_path
return None
except Exception as e:
print(f"[Convert] Error: {e}")
return None
# ============================================
# 🎨 Comic Classic Theme CSS
# ============================================
css = """
/* ===== 🎨 Google Fonts Import ===== */
@import url('https://fonts.googleapis.com/css2?family=Bangers&family=Comic+Neue:wght@400;700&display=swap');
/* ===== 🎨 Comic Classic Background ===== */
.gradio-container {
background-color: #FEF9C3 !important;
background-image:
radial-gradient(#1F2937 1px, transparent 1px) !important;
background-size: 20px 20px !important;
min-height: 100vh !important;
font-family: 'Comic Neue', cursive, sans-serif !important;
}
/* ===== Hide HuggingFace Elements ===== */
.huggingface-space-header,
#space-header,
.space-header,
[class*="space-header"],
.svelte-1ed2p3z,
.space-header-badge,
.header-badge,
[data-testid="space-header"],
.svelte-kqij2n,
.svelte-1ax1toq,
.embed-container > div:first-child {
display: none !important;
visibility: hidden !important;
height: 0 !important;
width: 0 !important;
overflow: hidden !important;
opacity: 0 !important;
pointer-events: none !important;
}
/* ===== Hide Footer ===== */
footer,
.footer,
.gradio-container footer,
.built-with,
[class*="footer"],
.gradio-footer,
.main-footer,
div[class*="footer"],
.show-api,
.built-with-gradio,
a[href*="gradio.app"],
a[href*="huggingface.co/spaces"] {
display: none !important;
visibility: hidden !important;
height: 0 !important;
padding: 0 !important;
margin: 0 !important;
}
/* ===== Main Container ===== */
#col-container {
max-width: 1200px;
margin: 0 auto;
}
/* ===== 🎨 Header Title - Comic Style ===== */
.header-text h1 {
font-family: 'Bangers', cursive !important;
color: #1F2937 !important;
font-size: 3.5rem !important;
font-weight: 400 !important;
text-align: center !important;
margin-bottom: 0.5rem !important;
text-shadow:
4px 4px 0px #FACC15,
6px 6px 0px #1F2937 !important;
letter-spacing: 3px !important;
-webkit-text-stroke: 2px #1F2937 !important;
}
/* ===== 🎨 Subtitle ===== */
.subtitle {
text-align: center !important;
font-family: 'Comic Neue', cursive !important;
font-size: 1.2rem !important;
color: #1F2937 !important;
margin-bottom: 1.5rem !important;
font-weight: 700 !important;
}
/* ===== 🎨 Cards/Panels - Comic Frame Style ===== */
.gr-panel,
.gr-box,
.gr-form,
.block,
.gr-group {
background: #FFFFFF !important;
border: 3px solid #1F2937 !important;
border-radius: 8px !important;
box-shadow: 6px 6px 0px #1F2937 !important;
transition: all 0.2s ease !important;
}
.gr-panel:hover,
.block:hover {
transform: translate(-2px, -2px) !important;
box-shadow: 8px 8px 0px #1F2937 !important;
}
/* ===== 🎨 Input Fields ===== */
textarea,
input[type="text"],
input[type="number"] {
background: #FFFFFF !important;
border: 3px solid #1F2937 !important;
border-radius: 8px !important;
color: #1F2937 !important;
font-family: 'Comic Neue', cursive !important;
font-size: 1rem !important;
font-weight: 700 !important;
transition: all 0.2s ease !important;
}
textarea:focus,
input[type="text"]:focus,
input[type="number"]:focus {
border-color: #3B82F6 !important;
box-shadow: 4px 4px 0px #3B82F6 !important;
outline: none !important;
}
textarea::placeholder {
color: #9CA3AF !important;
font-weight: 400 !important;
}
/* ===== 🎨 Primary Button - Comic Blue ===== */
.gr-button-primary,
button.primary,
.gr-button.primary {
background: #3B82F6 !important;
border: 3px solid #1F2937 !important;
border-radius: 8px !important;
color: #FFFFFF !important;
font-family: 'Bangers', cursive !important;
font-weight: 400 !important;
font-size: 1.3rem !important;
letter-spacing: 2px !important;
padding: 14px 28px !important;
box-shadow: 5px 5px 0px #1F2937 !important;
transition: all 0.1s ease !important;
text-shadow: 1px 1px 0px #1F2937 !important;
}
.gr-button-primary:hover,
button.primary:hover,
.gr-button.primary:hover {
background: #2563EB !important;
transform: translate(-2px, -2px) !important;
box-shadow: 7px 7px 0px #1F2937 !important;
}
.gr-button-primary:active,
button.primary:active,
.gr-button.primary:active {
transform: translate(3px, 3px) !important;
box-shadow: 2px 2px 0px #1F2937 !important;
}
/* ===== 🎨 Secondary Button - Comic Red ===== */
.gr-button-secondary,
button.secondary {
background: #EF4444 !important;
border: 3px solid #1F2937 !important;
border-radius: 8px !important;
color: #FFFFFF !important;
font-family: 'Bangers', cursive !important;
font-weight: 400 !important;
font-size: 1.1rem !important;
letter-spacing: 1px !important;
box-shadow: 4px 4px 0px #1F2937 !important;
transition: all 0.1s ease !important;
text-shadow: 1px 1px 0px #1F2937 !important;
}
.gr-button-secondary:hover,
button.secondary:hover {
background: #DC2626 !important;
transform: translate(-2px, -2px) !important;
box-shadow: 6px 6px 0px #1F2937 !important;
}
.gr-button-secondary:active,
button.secondary:active {
transform: translate(2px, 2px) !important;
box-shadow: 2px 2px 0px #1F2937 !important;
}
/* ===== 🎨 Labels ===== */
label,
.gr-input-label,
.gr-block-label {
color: #1F2937 !important;
font-family: 'Comic Neue', cursive !important;
font-weight: 700 !important;
font-size: 1rem !important;
}
span.gr-label {
color: #1F2937 !important;
}
/* ===== 🎨 File Upload Area ===== */
.gr-file-upload {
border: 3px dashed #1F2937 !important;
border-radius: 8px !important;
background: #FEF9C3 !important;
}
.gr-file-upload:hover {
border-color: #3B82F6 !important;
background: #EFF6FF !important;
}
/* ===== 🎨 Scrollbar - Comic Style ===== */
::-webkit-scrollbar {
width: 12px;
height: 12px;
}
::-webkit-scrollbar-track {
background: #FEF9C3;
border: 2px solid #1F2937;
}
::-webkit-scrollbar-thumb {
background: #3B82F6;
border: 2px solid #1F2937;
border-radius: 0px;
}
::-webkit-scrollbar-thumb:hover {
background: #EF4444;
}
/* ===== 🎨 Selection Highlight ===== */
::selection {
background: #FACC15;
color: #1F2937;
}
/* ===== 🎨 Links ===== */
a {
color: #3B82F6 !important;
text-decoration: none !important;
font-weight: 700 !important;
}
a:hover {
color: #EF4444 !important;
}
/* ===== 🎨 Row/Column Spacing ===== */
.gr-row {
gap: 1.5rem !important;
}
.gr-column {
gap: 1rem !important;
}
/* ===== Responsive Adjustments ===== */
@media (max-width: 768px) {
.header-text h1 {
font-size: 2.2rem !important;
text-shadow:
3px 3px 0px #FACC15,
4px 4px 0px #1F2937 !important;
}
.gr-button-primary,
button.primary {
padding: 12px 20px !important;
font-size: 1.1rem !important;
}
.gr-panel,
.block {
box-shadow: 4px 4px 0px #1F2937 !important;
}
}
/* ===== 🎨 Disable Dark Mode ===== */
@media (prefers-color-scheme: dark) {
.gradio-container {
background-color: #FEF9C3 !important;
}
}
"""
# ============================================
# Gradio UI
# ============================================
with gr.Blocks(title="Video Editor") as demo:
# Inject CSS via HTML (Audio Extractor와 동일한 방식)
gr.HTML(f"<style>{css}</style>")
# HOME Badge (Audio Extractor와 동일한 방식)
gr.HTML("""
<div style="text-align: center; margin: 20px 0 10px 0;">
<a href="https://www.humangen.ai" target="_blank" style="text-decoration: none;">
<img src="https://img.shields.io/static/v1?label=🏠 HOME&message=HUMANGEN.AI&color=0000ff&labelColor=ffcc00&style=for-the-badge" alt="HOME">
</a>
</div>
""")
# Header Title
gr.Markdown(
"""
# 🎬 VIDEO EDITOR 🎬
""",
elem_classes="header-text"
)
gr.Markdown(
"""
<p class="subtitle">✂️ Edit your videos with timeline, effects & more! 🎥</p>
""",
)
f = gr.File(label="📁 Upload Files (Video, Image, Audio)", file_count="multiple", file_types=["video", "image", "audio"])
e = gr.HTML(value=make_iframe([]))
gr.Markdown("---")
gr.Markdown("### 📥 MP4 Conversion")
gr.Markdown("In editor: 'Export' → 'Copy for MP4' → Paste below")
with gr.Row():
webm_data = gr.Textbox(label="WebM Data (base64)", placeholder="Paste here (Ctrl+V)", lines=2, scale=4)
convert_btn = gr.Button("🎬 Convert to MP4", variant="primary", scale=1)
mp4_output = gr.File(label="📥 Download MP4 ")
f.change(fn=lambda x: make_iframe(process_file(x)), inputs=[f], outputs=[e])
convert_btn.click(fn=convert_webm_to_mp4, inputs=[webm_data], outputs=[mp4_output])
if __name__ == "__main__":
demo.launch()