seawolf2357 commited on
Commit
2695903
·
verified ·
1 Parent(s): 12a739c

Delete app-backup.py

Browse files
Files changed (1) hide show
  1. app-backup.py +0 -1365
app-backup.py DELETED
@@ -1,1365 +0,0 @@
1
- """
2
- Simple Video Editor - Canvas 기반 렌더링
3
- 빈 프레임 문제 완전 해결 + 서버 사이드 MP4 내보내기
4
- """
5
-
6
- import gradio as gr
7
- import base64
8
- import os
9
- import json
10
- import subprocess
11
- import tempfile
12
- import shutil
13
- import time
14
-
15
- # 서버 사이드 MP4 내보내기용
16
- UPLOAD_DIR = tempfile.mkdtemp()
17
- uploaded_files = {} # {filename: filepath}
18
-
19
- def get_editor_html(media_data="[]"):
20
- return f'''<!DOCTYPE html>
21
- <html lang="ko">
22
- <head>
23
- <meta charset="UTF-8">
24
- <style>
25
- *{{margin:0;padding:0;box-sizing:border-box}}
26
- body{{font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#f5f5f7;font-size:13px}}
27
- .editor{{display:flex;flex-direction:column;height:100vh}}
28
- .toolbar{{height:44px;background:#fff;border-bottom:1px solid #ddd;display:flex;align-items:center;justify-content:space-between;padding:0 12px}}
29
- .toolbar-title{{font-size:15px;font-weight:600}}
30
- .btn{{padding:5px 10px;border:none;border-radius:5px;cursor:pointer;font-size:11px;font-weight:500}}
31
- .btn-secondary{{background:#f0f0f0;color:#333}}
32
- .btn-secondary:hover{{background:#e0e0e0}}
33
- .btn-success{{background:#10b981;color:#fff}}
34
- .btn-danger{{background:#ef4444;color:#fff}}
35
- .main{{display:flex;flex:1;overflow:hidden}}
36
- .library{{width:160px;background:#fff;border-right:1px solid #ddd;display:flex;flex-direction:column}}
37
- .lib-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
38
- .lib-content{{flex:1;overflow-y:auto;padding:6px}}
39
- .lib-hint{{text-align:center;padding:15px;color:#999;font-size:10px}}
40
- .media-grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:4px}}
41
- .media-item{{aspect-ratio:16/9;background:#f0f0f0;border-radius:4px;overflow:hidden;cursor:grab;position:relative;border:1px solid #e0e0e0}}
42
- .media-item:hover{{border-color:#6366f1}}
43
- .media-item img{{width:100%;height:100%;object-fit:cover}}
44
- .media-item-icon{{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:18px}}
45
- .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}}
46
- .preview-area{{flex:1;display:flex;flex-direction:column;background:#1a1a1a;margin:6px;border-radius:8px;overflow:hidden}}
47
- .preview-box{{flex:1;display:flex;align-items:center;justify-content:center;background:#000;overflow:hidden}}
48
- #previewCanvas{{background:#000;box-shadow:0 0 20px rgba(0,0,0,0.5)}}
49
- .controls{{height:45px;background:#222;display:flex;align-items:center;justify-content:center;gap:6px}}
50
- .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}}
51
- .ctrl-btn:hover{{background:rgba(255,255,255,0.2)}}
52
- .ctrl-btn.play{{width:36px;height:36px;background:#6366f1}}
53
- .time-display{{font-family:monospace;font-size:10px;color:#aaa;min-width:90px;text-align:center}}
54
- .props{{width:140px;background:#fff;border-left:1px solid #ddd}}
55
- .props-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
56
- .props-content{{padding:8px}}
57
- .no-sel{{color:#999;text-align:center;padding:15px;font-size:10px}}
58
- .prop-group{{margin-bottom:10px}}
59
- .prop-label{{font-size:9px;color:#666;margin-bottom:2px}}
60
- .prop-input{{width:100%;padding:4px;border:1px solid #ddd;border-radius:3px;font-size:10px}}
61
- .timeline{{height:180px;background:#fff;border-top:1px solid #ddd;display:flex;flex-direction:column}}
62
- .tl-toolbar{{height:28px;background:#fafafa;border-bottom:1px solid #eee;display:flex;align-items:center;padding:0 6px;gap:4px}}
63
- .tl-toolbar .btn{{padding:2px 6px;font-size:9px}}
64
- .tl-zoom{{display:flex;align-items:center;gap:3px;margin-left:auto;font-size:9px;color:#666}}
65
- .tl-zoom input{{width:50px}}
66
- .tl-container{{flex:1;overflow-x:auto;position:relative}}
67
- .tl-ruler{{height:18px;background:#fff;border-bottom:1px solid #eee}}
68
- .tl-tracks{{position:relative}}
69
- .tl-track{{height:45px;border-bottom:1px solid #eee;display:flex}}
70
- .tl-track:nth-child(2){{background:#fffbeb}}
71
- .tl-track:nth-child(3){{background:#fdf2f8}}
72
- .track-label{{width:50px;padding:0 4px;font-size:8px;color:#666;background:#fafafa;display:flex;align-items:center;border-right:1px solid #eee}}
73
- .track-content{{flex:1;position:relative;min-width:600px}}
74
- .clip{{position:absolute;height:36px;top:4px;border-radius:4px;cursor:grab;display:flex;align-items:center;overflow:hidden}}
75
- .clip:hover{{box-shadow:0 0 0 2px #6366f1}}
76
- .clip.selected{{box-shadow:0 0 0 2px #6366f1}}
77
- .clip.video{{background:linear-gradient(135deg,#818cf8,#6366f1)}}
78
- .clip.image{{background:linear-gradient(135deg,#34d399,#10b981)}}
79
- .clip.audio{{background:linear-gradient(135deg,#fbbf24,#f59e0b)}}
80
- .clip.text{{background:linear-gradient(135deg,#f472b6,#ec4899)}}
81
- .clip-thumb{{width:36px;height:100%;object-fit:cover}}
82
- .clip-info{{padding:0 4px;flex:1;overflow:hidden}}
83
- .clip-name{{font-size:8px;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
84
- .clip-dur{{font-size:7px;color:rgba(255,255,255,0.7)}}
85
- .clip-handle{{position:absolute;top:0;bottom:0;width:8px;background:rgba(255,255,255,0.5);cursor:ew-resize;opacity:0}}
86
- .clip:hover .clip-handle{{opacity:1}}
87
- .clip-handle-l{{left:0;border-radius:4px 0 0 4px}}
88
- .clip-handle-r{{right:0;border-radius:0 4px 4px 0}}
89
- .playhead{{position:absolute;top:0;bottom:0;width:2px;background:#ef4444;z-index:10;pointer-events:none}}
90
- .playhead::before{{content:"";position:absolute;top:0;left:-4px;border-left:5px solid transparent;border-right:5px solid transparent;border-top:7px solid #ef4444}}
91
- .drop-zone{{background:rgba(99,102,241,0.1)!important;outline:2px dashed #6366f1!important}}
92
- .status{{height:20px;background:#f5f5f5;border-top:1px solid #ddd;display:flex;align-items:center;padding:0 8px;font-size:9px;color:#666}}
93
- .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}}
94
- .ctx-item{{padding:5px 10px;cursor:pointer;font-size:10px}}
95
- .ctx-item:hover{{background:#f5f5f5}}
96
- .ctx-item.danger{{color:#ef4444}}
97
- .modal{{position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:1000}}
98
- .modal-box{{background:#fff;border-radius:8px;padding:16px;min-width:240px;text-align:center}}
99
- .modal-box h3{{margin-bottom:8px;font-size:13px}}
100
- .progress{{height:5px;background:#eee;border-radius:3px;overflow:hidden;margin:10px 0}}
101
- .progress-bar{{height:100%;background:#6366f1;transition:width 0.2s}}
102
- .hidden-media{{position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0;pointer-events:none}}
103
- </style>
104
- </head>
105
- <body>
106
- <div class="editor">
107
- <div class="toolbar">
108
- <div class="toolbar-title">🎬 Video Editor</div>
109
- <div style="display:flex;gap:8px;align-items:center">
110
- <select id="ratioSelect" onchange="setRatio(this.value)" style="padding:4px 8px;border-radius:4px;border:1px solid #ddd;font-size:11px">
111
- <option value="16:9">16:9 (가로)</option>
112
- <option value="9:16">9:16 (세로)</option>
113
- <option value="1:1">1:1 (정사각)</option>
114
- <option value="4:3">4:3</option>
115
- <option value="4:5">4:5 (인스타)</option>
116
- </select>
117
- <select id="fillMode" onchange="setFillMode(this.value)" style="padding:4px 8px;border-radius:4px;border:1px solid #ddd;font-size:11px">
118
- <option value="fit">맞춤 (여백)</option>
119
- <option value="fill">채우기 (확대)</option>
120
- <option value="blur">블러 배경</option>
121
- </select>
122
- <button class="btn btn-secondary" onclick="undo()">↩ 실행취소</button>
123
- <button class="btn btn-success" onclick="exportVideo()">📥 내보내기</button>
124
- </div>
125
- </div>
126
- <div class="main">
127
- <div class="library">
128
- <div class="lib-header">📁 미디어</div>
129
- <div class="lib-content">
130
- <div class="lib-hint" id="hint">파일을 업로드하세요</div>
131
- <div class="media-grid" id="mediaGrid"></div>
132
- </div>
133
- </div>
134
- <div class="preview-area">
135
- <div class="preview-box">
136
- <canvas id="previewCanvas" width="640" height="360"></canvas>
137
- </div>
138
- <div class="controls">
139
- <button class="ctrl-btn" onclick="seek(0)">⏮</button>
140
- <button class="ctrl-btn" onclick="seek(S.time-5)">⏪</button>
141
- <button class="ctrl-btn play" onclick="togglePlay()" id="playBtn">▶</button>
142
- <button class="ctrl-btn" onclick="seek(S.time+5)">⏩</button>
143
- <button class="ctrl-btn" onclick="seek(S.dur)">⏭</button>
144
- <div class="time-display"><span id="curT">00:00.00</span> / <span id="totT">00:00.00</span></div>
145
- <button class="ctrl-btn" onclick="toggleMute()" id="muteBtn">🔊</button>
146
- </div>
147
- </div>
148
- <div class="props">
149
- <div class="props-header">⚙️ 속성</div>
150
- <div class="props-content" id="propsBox"><div class="no-sel">클립 선택</div></div>
151
- </div>
152
- </div>
153
- <div class="timeline">
154
- <div class="tl-toolbar">
155
- <button class="btn btn-secondary" onclick="addTextClip()">📝 텍스트</button>
156
- <button class="btn btn-secondary" onclick="splitClip()">✂ 자르기</button>
157
- <button class="btn btn-secondary" onclick="dupeClip()">📋 복제</button>
158
- <button class="btn btn-danger" onclick="delClip()">🗑 삭제</button>
159
- <div class="tl-zoom">🔍<input type="range" min="0.5" max="3" step="0.1" value="1" oninput="setZoom(this.value)"></div>
160
- </div>
161
- <div class="tl-container" id="tlBox" onclick="tlClick(event)">
162
- <div class="tl-ruler" id="ruler"></div>
163
- <div class="tl-tracks">
164
- <div class="tl-track"><div class="track-label">🎬 영상</div><div class="track-content" id="t0"></div></div>
165
- <div class="tl-track"><div class="track-label">🎵 오디오</div><div class="track-content" id="t1"></div></div>
166
- <div class="tl-track"><div class="track-label">📝 텍스트</div><div class="track-content" id="t2"></div></div>
167
- </div>
168
- <div class="playhead" id="playhead" style="left:50px"></div>
169
- </div>
170
- </div>
171
- <div class="status" id="status">준비됨</div>
172
- </div>
173
- <div class="ctx-menu" id="ctx">
174
- <div class="ctx-item" onclick="splitClip()">✂ 자르기</div>
175
- <div class="ctx-item" onclick="dupeClip()">📋 복제</div>
176
- <div class="ctx-item danger" onclick="delClip()">🗑 삭제</div>
177
- </div>
178
- <div class="modal" id="exportModal" style="display:none">
179
- <div class="modal-box">
180
- <h3>�� 영상 내보내기</h3>
181
- <p id="exportMsg">준비중...</p>
182
- <div class="progress"><div class="progress-bar" id="exportBar"></div></div>
183
- <button class="btn btn-secondary" onclick="cancelExport()">취소</button>
184
- </div>
185
- </div>
186
- <div class="modal" id="textModal" style="display:none">
187
- <div class="modal-box" style="min-width:320px">
188
- <h3>📝 텍스트 추가</h3>
189
- <div style="margin:10px 0;text-align:left">
190
- <div style="margin-bottom:8px">
191
- <label style="font-size:11px;color:#666">텍스트 내용</label>
192
- <input type="text" id="textInput" placeholder="텍스트 입력..." style="width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
193
- </div>
194
- <div style="display:flex;gap:8px;margin-bottom:8px">
195
- <div style="flex:1">
196
- <label style="font-size:11px;color:#666">글자 크기</label>
197
- <select id="textSize" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
198
- <option value="24">작게 (24px)</option>
199
- <option value="36">보통 (36px)</option>
200
- <option value="48" selected>크게 (48px)</option>
201
- <option value="64">매우 크게 (64px)</option>
202
- <option value="96">최대 (96px)</option>
203
- </select>
204
- </div>
205
- <div style="flex:1">
206
- <label style="font-size:11px;color:#666">글자 색상</label>
207
- <input type="color" id="textColor" value="#ffffff" style="width:100%;height:32px;border:1px solid #ddd;border-radius:4px;margin-top:4px;cursor:pointer">
208
- </div>
209
- </div>
210
- <div style="display:flex;gap:8px;margin-bottom:8px">
211
- <div style="flex:1">
212
- <label style="font-size:11px;color:#666">배경 스타일</label>
213
- <select id="textBgStyle" onchange="toggleBgColor()" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:4px;margin-top:4px">
214
- <option value="none">배경 없음</option>
215
- <option value="solid" selected>단색 배경</option>
216
- <option value="rounded">둥근 배경</option>
217
- </select>
218
- </div>
219
- <div style="flex:1" id="bgColorBox">
220
- <label style="font-size:11px;color:#666">배경 색상</label>
221
- <input type="color" id="textBgColor" value="#000000" style="width:100%;height:32px;border:1px solid #ddd;border-radius:4px;margin-top:4px;cursor:pointer">
222
- </div>
223
- </div>
224
- <div style="margin-bottom:8px">
225
- <label style="font-size:11px;color:#666">표시 시간 (초)</label>
226
- <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">
227
- </div>
228
- </div>
229
- <div style="display:flex;gap:8px;justify-content:center">
230
- <button class="btn btn-secondary" onclick="closeTextModal()">취소</button>
231
- <button class="btn btn-success" onclick="confirmAddText()">추가</button>
232
- </div>
233
- </div>
234
- </div>
235
- <div id="hiddenMedia" class="hidden-media"></div>
236
- <script>
237
- var S={{
238
- media:[],
239
- clips:[],
240
- sel:null,
241
- playing:false,
242
- muted:false,
243
- time:0,
244
- dur:0,
245
- zoom:1,
246
- pps:80,
247
- history:[],
248
- animId:null,
249
- cancelled:false,
250
- els:{{}},
251
- canvas:null,
252
- ctx:null,
253
- lastClipId:null,
254
- ratio:'16:9',
255
- fillMode:'fit',
256
- ratioSizes:{{
257
- '16:9':{{w:1280,h:720,pw:640,ph:360}},
258
- '9:16':{{w:720,h:1280,pw:203,ph:360}},
259
- '1:1':{{w:1080,h:1080,pw:360,ph:360}},
260
- '4:3':{{w:1280,h:960,pw:480,ph:360}},
261
- '4:5':{{w:1080,h:1350,pw:288,ph:360}}
262
- }}
263
- }};
264
-
265
- function init(){{
266
- S.canvas=document.getElementById('previewCanvas');
267
- S.ctx=S.canvas.getContext('2d');
268
- updateCanvasSize();
269
- drawPlaceholder();
270
- }}
271
-
272
- function updateCanvasSize(){{
273
- var size=S.ratioSizes[S.ratio];
274
- S.canvas.width=size.pw;
275
- S.canvas.height=size.ph;
276
- S.canvas.style.width=size.pw+'px';
277
- S.canvas.style.height=size.ph+'px';
278
- }}
279
-
280
- function setRatio(r){{
281
- S.ratio=r;
282
- updateCanvasSize();
283
- drawFrame();
284
- stat('화면 비율: '+r);
285
- }}
286
-
287
- function setFillMode(m){{
288
- S.fillMode=m;
289
- drawFrame();
290
- stat('채우기 모드: '+(m==='fit'?'맞춤 (여백)':m==='fill'?'채우기 (확대)':'블러 배경'));
291
- }}
292
-
293
- function id(){{return Math.random().toString(36).substr(2,9)}}
294
- 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')}}
295
- function r(n){{return Math.round(n*1000)/1000}}
296
- function stat(m){{document.getElementById('status').textContent=m}}
297
- function save(){{S.history.push(JSON.stringify(S.clips));if(S.history.length>30)S.history.shift()}}
298
-
299
- function drawPlaceholder(){{
300
- var size=S.ratioSizes[S.ratio];
301
- var pw=size.pw,ph=size.ph;
302
- S.ctx.fillStyle='#000';
303
- S.ctx.fillRect(0,0,pw,ph);
304
- S.ctx.fillStyle='#444';
305
- S.ctx.font='14px sans-serif';
306
- S.ctx.textAlign='center';
307
- S.ctx.fillText('타임라인에 미디어를 추가하세요',pw/2,ph/2);
308
- }}
309
-
310
- function addMedia(name,type,url,filePath){{
311
- var m={{id:id(),name:name,type:type,url:url,filePath:filePath||name,dur:type==='image'?5:0,thumb:type==='image'?url:null}};
312
- S.media.push(m);
313
- var container=document.getElementById('hiddenMedia');
314
- if(type==='video'){{
315
- var v=document.createElement('video');
316
- v.src=url;
317
- v.muted=true;
318
- v.playsInline=true;
319
- v.preload='auto';
320
- v.crossOrigin='anonymous';
321
- container.appendChild(v);
322
- S.els[m.id]=v;
323
- v.onloadedmetadata=function(){{
324
- m.dur=r(v.duration);
325
- renderLib();
326
- v.currentTime=0.5;
327
- }};
328
- v.onseeked=function(){{
329
- if(!m.thumb){{
330
- try{{
331
- var c=document.createElement('canvas');
332
- c.width=160;c.height=90;
333
- c.getContext('2d').drawImage(v,0,0,160,90);
334
- m.thumb=c.toDataURL();
335
- renderLib();
336
- }}catch(e){{}}
337
- }}
338
- }};
339
- }}else if(type==='audio'){{
340
- var a=document.createElement('audio');
341
- a.src=url;
342
- a.preload='auto';
343
- container.appendChild(a);
344
- S.els[m.id]=a;
345
- a.onloadedmetadata=function(){{m.dur=r(a.duration);renderLib()}};
346
- }}else if(type==='image'){{
347
- var img=new Image();
348
- img.src=url;
349
- img.crossOrigin='anonymous';
350
- S.els[m.id]=img;
351
- }}
352
- renderLib();
353
- stat('미디어 추가: '+name);
354
- setTimeout(function(){{addClip(m)}},400);
355
- }}
356
-
357
- function renderLib(){{
358
- var g=document.getElementById('mediaGrid');
359
- var h=document.getElementById('hint');
360
- h.style.display=S.media.length?'none':'block';
361
- g.innerHTML='';
362
- S.media.forEach(function(m){{
363
- var d=document.createElement('div');
364
- d.className='media-item';
365
- d.draggable=true;
366
- d.ondblclick=function(){{addClip(m)}};
367
- d.ondragstart=function(e){{e.dataTransfer.setData('mid',m.id)}};
368
- var th=m.thumb?'<img src="'+m.thumb+'">':'<div class="media-item-icon">'+(m.type==='video'?'🎬':m.type==='audio'?'🎵':'🖼')+'</div>';
369
- d.innerHTML=th+(m.dur?'<div class="media-item-dur">'+fmt(m.dur)+'</div>':'');
370
- g.appendChild(d);
371
- }});
372
- }}
373
-
374
- function trackEnd(tr){{
375
- var end=0;
376
- for(var i=0;i<S.clips.length;i++){{
377
- var c=S.clips[i];
378
- if(c.track===tr){{
379
- var e=r(c.start+(c.te-c.ts));
380
- if(e>end)end=e;
381
- }}
382
- }}
383
- return end;
384
- }}
385
-
386
- function addClip(m,at){{
387
- save();
388
- var tr=m.type==='audio'?1:0;
389
- var st=at!==undefined?r(at):trackEnd(tr);
390
- S.clips.push({{
391
- id:id(),
392
- mid:m.id,
393
- name:m.name,
394
- type:m.type,
395
- track:tr,
396
- start:st,
397
- dur:m.dur,
398
- ts:0,
399
- te:m.dur,
400
- vol:1,
401
- filePath:m.filePath
402
- }});
403
- renderTL();
404
- updateDur();
405
- stat('클립 추가: '+m.name);
406
- drawFrame();
407
- }}
408
-
409
- function renderTL(){{
410
- ['t0','t1','t2'].forEach(function(tid){{document.getElementById(tid).innerHTML=''}});
411
- S.clips.forEach(function(c){{
412
- var tr=document.getElementById('t'+c.track);
413
- var el=document.createElement('div');
414
- el.className='clip '+c.type+(S.sel===c.id?' selected':'');
415
- var len=r(c.te-c.ts);
416
- el.style.left=r(c.start*S.pps*S.zoom)+'px';
417
- el.style.width=Math.max(25,r(len*S.pps*S.zoom))+'px';
418
- el.draggable=true;
419
- el.onclick=function(e){{e.stopPropagation();selClip(c.id)}};
420
- el.oncontextmenu=function(e){{e.preventDefault();selClip(c.id);showCtx(e.clientX,e.clientY)}};
421
- el.ondragstart=function(e){{e.dataTransfer.setData('cid',c.id);e.dataTransfer.setData('ox',e.offsetX)}};
422
- var m=S.media.find(function(x){{return x.id===c.mid}});
423
- var th=m&&m.thumb?'<img class="clip-thumb" src="'+m.thumb+'">':'';
424
- var clipName=c.type==='text'?('📝 '+c.text.substring(0,8)):c.name;
425
- 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>';
426
- el.querySelector('.clip-handle-l').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'l',e)}};
427
- el.querySelector('.clip-handle-r').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'r',e)}};
428
- tr.appendChild(el);
429
- }});
430
- renderRuler();
431
- setupDrop();
432
- }}
433
-
434
- function renderRuler(){{
435
- var ru=document.getElementById('ruler');
436
- var w=Math.max(r(S.dur*S.pps*S.zoom)+150,600);
437
- ru.style.width=w+'px';
438
- var h='<svg width="100%" height="18" style="position:absolute;left:50px">';
439
- var step=S.zoom<0.7?5:S.zoom<1.5?2:1;
440
- for(var i=0;i<=S.dur+10;i+=step){{
441
- var x=r(i*S.pps*S.zoom);
442
- h+='<line x1="'+x+'" y1="13" x2="'+x+'" y2="18" stroke="#ccc"/>';
443
- h+='<text x="'+x+'" y="10" fill="#999" font-size="8" text-anchor="middle">'+fmt(i)+'</text>';
444
- }}
445
- ru.innerHTML=h+'</svg>';
446
- }}
447
-
448
- function setupDrop(){{
449
- ['t0','t1','t2'].forEach(function(tid,idx){{
450
- var tr=document.getElementById(tid);
451
- tr.ondragover=function(e){{e.preventDefault();tr.classList.add('drop-zone')}};
452
- tr.ondragleave=function(){{tr.classList.remove('drop-zone')}};
453
- tr.ondrop=function(e){{
454
- e.preventDefault();
455
- tr.classList.remove('drop-zone');
456
- var rect=tr.getBoundingClientRect();
457
- var t=r(Math.max(0,(e.clientX-rect.left)/(S.pps*S.zoom)));
458
- var mid=e.dataTransfer.getData('mid');
459
- var cid=e.dataTransfer.getData('cid');
460
- var ox=parseFloat(e.dataTransfer.getData('ox')||0);
461
- if(mid){{
462
- var m=S.media.find(function(x){{return x.id===mid}});
463
- if(m)addClip(m,t);
464
- }}else if(cid){{
465
- save();
466
- var c=S.clips.find(function(x){{return x.id===cid}});
467
- if(c){{
468
- c.start=r(Math.max(0,t-ox/(S.pps*S.zoom)));
469
- // 텍스트는 텍스트 트랙으로만, 그 외는 영상/오디오 트랙으로
470
- if(c.type==='text'){{
471
- c.track=2;
472
- }}else if(c.type==='audio'){{
473
- c.track=1;
474
- }}else{{
475
- c.track=idx===2?0:idx;
476
- }}
477
- renderTL();
478
- updateDur();
479
- drawFrame();
480
- }}
481
- }}
482
- }};
483
- }});
484
- }}
485
-
486
- var trimData=null;
487
- function startTrim(cid,side,e){{
488
- e.preventDefault();
489
- var c=S.clips.find(function(x){{return x.id===cid}});
490
- if(!c)return;
491
- save();
492
- trimData={{cid:cid,side:side,sx:e.clientX,ots:c.ts,ote:c.te,ost:c.start}};
493
- document.addEventListener('mousemove',doTrim);
494
- document.addEventListener('mouseup',endTrim);
495
- }}
496
- function doTrim(e){{
497
- if(!trimData)return;
498
- var c=S.clips.find(function(x){{return x.id===trimData.cid}});
499
- if(!c)return;
500
- var dx=e.clientX-trimData.sx;
501
- var dt=r(dx/(S.pps*S.zoom));
502
- if(trimData.side==='l'){{
503
- var newTs=Math.max(0,Math.min(c.te-0.1,trimData.ots+dt));
504
- c.ts=r(newTs);
505
- c.start=r(trimData.ost+(newTs-trimData.ots));
506
- }}else{{
507
- c.te=r(Math.max(c.ts+0.1,Math.min(c.dur,trimData.ote+dt)));
508
- }}
509
- renderTL();
510
- updateDur();
511
- }}
512
- function endTrim(){{
513
- trimData=null;
514
- document.removeEventListener('mousemove',doTrim);
515
- document.removeEventListener('mouseup',endTrim);
516
- }}
517
-
518
- function selClip(cid){{S.sel=cid;renderTL();renderProps()}}
519
-
520
- function renderProps(){{
521
- var box=document.getElementById('propsBox');
522
- var c=S.clips.find(function(x){{return x.id===S.sel}});
523
- if(!c){{box.innerHTML='<div class="no-sel">클립 선택</div>';return}}
524
- var len=r(c.te-c.ts);
525
-
526
- if(c.type==='text'){{
527
- // 텍스트 클립 속성
528
- box.innerHTML='<div class="prop-group"><div class="prop-label">텍스트</div><input class="prop-input" value="'+c.text+'" onchange="setProp(\\'text\\',this.value)"></div>'+
529
- '<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>'+
530
- '<div class="prop-group"><div class="prop-label">길이: '+fmt(len)+'</div></div>'+
531
- '<div class="prop-group"><div class="prop-label">글자 크기</div><select class="prop-input" onchange="setProp(\\'fontSize\\',parseInt(this.value))">'+
532
- '<option value="24"'+(c.fontSize===24?' selected':'')+'>작게</option>'+
533
- '<option value="36"'+(c.fontSize===36?' selected':'')+'>보통</option>'+
534
- '<option value="48"'+(c.fontSize===48?' selected':'')+'>크게</option>'+
535
- '<option value="64"'+(c.fontSize===64?' selected':'')+'>매우 크게</option>'+
536
- '<option value="96"'+(c.fontSize===96?' selected':'')+'>최대</option>'+
537
- '</select></div>'+
538
- '<div class="prop-group"><div class="prop-label">글자 색상</div><input class="prop-input" type="color" value="'+c.fontColor+'" onchange="setProp(\\'fontColor\\',this.value)"></div>'+
539
- '<div class="prop-group"><div class="prop-label">배경 스타일</div><select class="prop-input" onchange="setProp(\\'bgStyle\\',this.value)">'+
540
- '<option value="none"'+(c.bgStyle==='none'?' selected':'')+'>없음</option>'+
541
- '<option value="solid"'+(c.bgStyle==='solid'?' selected':'')+'>단색</option>'+
542
- '<option value="rounded"'+(c.bgStyle==='rounded'?' selected':'')+'>둥근</option>'+
543
- '</select></div>'+
544
- '<div class="prop-group"><div class="prop-label">배경 색상</div><input class="prop-input" type="color" value="'+c.bgColor+'" onchange="setProp(\\'bgColor\\',this.value)"></div>';
545
- }}else{{
546
- // 기존 미디어 클립 속성
547
- box.innerHTML='<div class="prop-group"><div class="prop-label">이름</div><input class="prop-input" value="'+c.name+'" onchange="setProp(\\'name\\',this.value)"></div>'+
548
- '<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>'+
549
- '<div class="prop-group"><div class="prop-label">길이: '+fmt(len)+'</div></div>'+
550
- (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>':'');
551
- }}
552
- }}
553
-
554
- function setProp(p,v){{
555
- save();
556
- var c=S.clips.find(function(x){{return x.id===S.sel}});
557
- if(c){{c[p]=p==='start'?r(v):v;renderTL();updateDur();renderProps();drawFrame()}}
558
- }}
559
-
560
- function splitClip(){{
561
- if(!S.sel){{alert('클립을 선택하세요');return}}
562
- var c=S.clips.find(function(x){{return x.id===S.sel}});
563
- if(!c)return;
564
- var cEnd=r(c.start+c.te-c.ts);
565
- if(S.time<=c.start||S.time>=cEnd){{alert('플레이헤드가 클립 안에 있어야 합니다');return}}
566
- save();
567
- var splitAt=r(S.time-c.start);
568
- var c2=JSON.parse(JSON.stringify(c));
569
- c2.id=id();
570
- c2.start=r(S.time);
571
- c2.ts=r(c.ts+splitAt);
572
- c.te=r(c.ts+splitAt);
573
- S.clips.push(c2);
574
- renderTL();updateDur();hideCtx();stat('클립 분할됨');
575
- }}
576
-
577
- function dupeClip(){{
578
- if(!S.sel)return;
579
- var c=S.clips.find(function(x){{return x.id===S.sel}});
580
- if(!c)return;
581
- save();
582
- var len=r(c.te-c.ts);
583
- var nc=JSON.parse(JSON.stringify(c));
584
- nc.id=id();
585
- nc.start=r(c.start+len);
586
- S.clips.push(nc);
587
- renderTL();updateDur();hideCtx();stat('클립 복제됨');
588
- }}
589
-
590
- function delClip(){{
591
- if(!S.sel)return;
592
- save();
593
- S.clips=S.clips.filter(function(x){{return x.id!==S.sel}});
594
- S.sel=null;
595
- renderTL();renderProps();updateDur();hideCtx();stat('클립 삭제됨');
596
- drawFrame();
597
- }}
598
-
599
- function undo(){{if(S.history.length){{S.clips=JSON.parse(S.history.pop());renderTL();updateDur();stat('실행취소');drawFrame()}}}}
600
-
601
- function updateDur(){{
602
- var mx=0;
603
- for(var i=0;i<S.clips.length;i++){{
604
- var c=S.clips[i];
605
- var e=r(c.start+c.te-c.ts);
606
- if(e>mx)mx=e;
607
- }}
608
- S.dur=mx;
609
- document.getElementById('totT').textContent=fmt(mx);
610
- }}
611
-
612
- function togglePlay(){{
613
- S.playing=!S.playing;
614
- document.getElementById('playBtn').textContent=S.playing?'⏸':'▶';
615
- if(S.playing)play();else stop();
616
- }}
617
-
618
- function play(){{
619
- var last=performance.now();
620
- function loop(now){{
621
- if(!S.playing)return;
622
- var dt=(now-last)/1000;
623
- last=now;
624
- S.time=S.time+dt;
625
- if(S.time>=S.dur){{
626
- S.time=0;
627
- if(S.dur===0){{S.playing=false;document.getElementById('playBtn').textContent='▶';return}}
628
- }}
629
- updateHead();
630
- drawFrame();
631
- S.animId=requestAnimationFrame(loop);
632
- }}
633
- S.animId=requestAnimationFrame(loop);
634
- }}
635
-
636
- function stop(){{
637
- if(S.animId){{cancelAnimationFrame(S.animId);S.animId=null}}
638
- Object.keys(S.els).forEach(function(k){{
639
- var el=S.els[k];
640
- if(el&&el.pause)el.pause();
641
- }});
642
- }}
643
-
644
- function seek(t){{
645
- S.time=Math.max(0,Math.min(S.dur||0,t));
646
- updateHead();
647
- drawFrame();
648
- }}
649
-
650
- function updateHead(){{
651
- document.getElementById('playhead').style.left=(50+S.time*S.pps*S.zoom)+'px';
652
- document.getElementById('curT').textContent=fmt(S.time);
653
- }}
654
-
655
- function getClipAt(t,type){{
656
- var sorted=S.clips.filter(function(c){{
657
- if(type==='visual')return c.type==='video'||c.type==='image';
658
- if(type==='audio')return c.type==='audio';
659
- return true;
660
- }}).sort(function(a,b){{return a.start-b.start}});
661
- for(var i=0;i<sorted.length;i++){{
662
- var c=sorted[i];
663
- var cEnd=c.start+(c.te-c.ts);
664
- if(t>=c.start&&t<cEnd)return c;
665
- }}
666
- return null;
667
- }}
668
-
669
- function drawFrame(){{
670
- var t=S.time;
671
- var vc=getClipAt(t,'visual');
672
- var size=S.ratioSizes[S.ratio];
673
- var pw=size.pw,ph=size.ph;
674
-
675
- S.ctx.fillStyle='#000';
676
- S.ctx.fillRect(0,0,pw,ph);
677
-
678
- if(vc){{
679
- var el=S.els[vc.mid];
680
- if(el){{
681
- if(vc.type==='video'){{
682
- var clipT=t-vc.start+vc.ts;
683
- if(Math.abs(el.currentTime-clipT)>0.05){{
684
- el.currentTime=clipT;
685
- }}
686
- if(S.playing&&el.paused)el.play().catch(function(){{}});
687
- if(!S.playing&&!el.paused)el.pause();
688
- el.volume=S.muted?0:vc.vol;
689
- }}
690
- try{{
691
- var sw=el.videoWidth||el.naturalWidth||el.width||pw;
692
- var sh=el.videoHeight||el.naturalHeight||el.height||ph;
693
- drawWithMode(S.ctx,el,sw,sh,pw,ph,S.fillMode);
694
- }}catch(e){{}}
695
- }}
696
- }}else if(S.clips.length===0){{
697
- S.ctx.fillStyle='#444';
698
- S.ctx.font='14px sans-serif';
699
- S.ctx.textAlign='center';
700
- S.ctx.fillText('타임라인에 미디어를 추가하세요',pw/2,ph/2);
701
- }}
702
- var audioClips=S.clips.filter(function(c){{
703
- if(c.type!=='audio')return false;
704
- var cEnd=c.start+(c.te-c.ts);
705
- return t>=c.start&&t<cEnd;
706
- }});
707
- audioClips.forEach(function(ac){{
708
- var el=S.els[ac.mid];
709
- if(el){{
710
- var clipT=t-ac.start+ac.ts;
711
- if(Math.abs(el.currentTime-clipT)>0.1)el.currentTime=clipT;
712
- el.volume=S.muted?0:ac.vol;
713
- if(S.playing&&el.paused)el.play().catch(function(){{}});
714
- if(!S.playing&&!el.paused)el.pause();
715
- }}
716
- }});
717
- S.clips.forEach(function(c){{
718
- if(c.type!=='audio')return;
719
- var cEnd=c.start+(c.te-c.ts);
720
- if(t<c.start||t>=cEnd){{
721
- var el=S.els[c.mid];
722
- if(el&&!el.paused)el.pause();
723
- }}
724
- }});
725
- if(!vc&&!audioClips.length&&S.clips.length>0){{
726
- var hasText=getTextClipsAt(t).length>0;
727
- if(!hasText){{
728
- S.ctx.fillStyle='#333';
729
- S.ctx.font='12px sans-serif';
730
- S.ctx.textAlign='center';
731
- S.ctx.fillText('재생 위치에 미디어가 없습니다',pw/2,ph/2);
732
- }}
733
- }}
734
-
735
- // 텍스트 오버레이 렌더링
736
- var textClips=getTextClipsAt(t);
737
- textClips.forEach(function(tc){{
738
- drawText(S.ctx,tc,pw,ph);
739
- }});
740
- }}
741
-
742
- function drawWithMode(ctx,el,sw,sh,dw,dh,mode){{
743
- if(mode==='fill'){{
744
- // 채우기: 캔버스를 꽉 채우도록 확대, 넘치는 부분 잘림
745
- var scale=Math.max(dw/sw,dh/sh);
746
- var nw=sw*scale,nh=sh*scale;
747
- var ox=(dw-nw)/2,oy=(dh-nh)/2;
748
- ctx.drawImage(el,ox,oy,nw,nh);
749
- }}else if(mode==='blur'){{
750
- // 프레임 먼저 캡처
751
- var frameCanvas=document.createElement('canvas');
752
- frameCanvas.width=sw;frameCanvas.height=sh;
753
- var frameCtx=frameCanvas.getContext('2d');
754
- frameCtx.drawImage(el,0,0,sw,sh);
755
-
756
- // 블러용 작은 캔버스
757
- var blurCanvas=document.createElement('canvas');
758
- blurCanvas.width=16;blurCanvas.height=16;
759
- var blurCtx=blurCanvas.getContext('2d');
760
- blurCtx.drawImage(frameCanvas,0,0,16,16);
761
-
762
- // 배경
763
- ctx.imageSmoothingEnabled=true;
764
- ctx.imageSmoothingQuality='high';
765
- var scale=Math.max(dw/sw,dh/sh)*1.1;
766
- var nw=sw*scale,nh=sh*scale;
767
- var ox=(dw-nw)/2,oy=(dh-nh)/2;
768
- ctx.drawImage(blurCanvas,ox,oy,nw,nh);
769
-
770
- // 어둡게
771
- ctx.fillStyle='rgba(0,0,0,0.4)';
772
- ctx.fillRect(0,0,dw,dh);
773
-
774
- // 원본 (캡처된 프레임)
775
- var fitScale=Math.min(dw/sw,dh/sh);
776
- var fw=sw*fitScale,fh=sh*fitScale;
777
- var fx=(dw-fw)/2,fy=(dh-fh)/2;
778
- ctx.drawImage(frameCanvas,fx,fy,fw,fh);
779
- }}else{{
780
- // 맞춤 (fit): 원본 비율 유지, 여백
781
- var scale=Math.min(dw/sw,dh/sh);
782
- var nw=sw*scale,nh=sh*scale;
783
- var ox=(dw-nw)/2,oy=(dh-nh)/2;
784
- ctx.drawImage(el,ox,oy,nw,nh);
785
- }}
786
- }}
787
-
788
- function toggleMute(){{S.muted=!S.muted;document.getElementById('muteBtn').textContent=S.muted?'🔇':'🔊'}}
789
-
790
- // 텍스트 클립 관련 함수들
791
- function addTextClip(){{
792
- document.getElementById('textModal').style.display='flex';
793
- document.getElementById('textInput').value='';
794
- document.getElementById('textInput').focus();
795
- }}
796
-
797
- function closeTextModal(){{
798
- document.getElementById('textModal').style.display='none';
799
- }}
800
-
801
- function toggleBgColor(){{
802
- var style=document.getElementById('textBgStyle').value;
803
- document.getElementById('bgColorBox').style.opacity=style==='none'?'0.5':'1';
804
- }}
805
-
806
- function confirmAddText(){{
807
- var text=document.getElementById('textInput').value.trim();
808
- if(!text){{alert('텍스트를 입력하세요');return}}
809
- save();
810
- var duration=parseFloat(document.getElementById('textDuration').value)||5;
811
- S.clips.push({{
812
- id:id(),
813
- type:'text',
814
- track:2,
815
- start:S.time,
816
- dur:duration,
817
- ts:0,
818
- te:duration,
819
- text:text,
820
- fontSize:parseInt(document.getElementById('textSize').value),
821
- fontColor:document.getElementById('textColor').value,
822
- bgStyle:document.getElementById('textBgStyle').value,
823
- bgColor:document.getElementById('textBgColor').value
824
- }});
825
- closeTextModal();
826
- renderTL();
827
- updateDur();
828
- drawFrame();
829
- stat('텍스트 추가: '+text);
830
- }}
831
-
832
- function getTextClipsAt(t){{
833
- return S.clips.filter(function(c){{
834
- if(c.type!=='text')return false;
835
- var cEnd=c.start+(c.te-c.ts);
836
- return t>=c.start&&t<cEnd;
837
- }});
838
- }}
839
-
840
- function drawText(ctx,clip,dw,dh){{
841
- var text=clip.text;
842
- var fontSize=clip.fontSize||48;
843
- var fontColor=clip.fontColor||'#ffffff';
844
- var bgStyle=clip.bgStyle||'none';
845
- var bgColor=clip.bgColor||'#000000';
846
-
847
- ctx.font='bold '+fontSize+'px -apple-system,BlinkMacSystemFont,sans-serif';
848
- ctx.textAlign='center';
849
- ctx.textBaseline='middle';
850
-
851
- var metrics=ctx.measureText(text);
852
- var textW=metrics.width;
853
- var textH=fontSize;
854
- var x=dw/2;
855
- var y=dh-fontSize-30; // 하단에 배치
856
-
857
- if(bgStyle!=='none'){{
858
- var padding=fontSize*0.3;
859
- var bgX=x-textW/2-padding;
860
- var bgY=y-textH/2-padding/2;
861
- var bgW=textW+padding*2;
862
- var bgH=textH+padding;
863
-
864
- ctx.fillStyle=bgColor+'cc'; // 약간 투명
865
- if(bgStyle==='rounded'){{
866
- ctx.beginPath();
867
- ctx.roundRect(bgX,bgY,bgW,bgH,10);
868
- ctx.fill();
869
- }}else{{
870
- ctx.fillRect(bgX,bgY,bgW,bgH);
871
- }}
872
- }}
873
-
874
- // 텍스트 그림자
875
- ctx.fillStyle='rgba(0,0,0,0.5)';
876
- ctx.fillText(text,x+2,y+2);
877
-
878
- // 텍스트
879
- ctx.fillStyle=fontColor;
880
- ctx.fillText(text,x,y);
881
- }}
882
- function setZoom(v){{S.zoom=parseFloat(v);renderTL();updateHead()}}
883
- function tlClick(e){{
884
- if(e.target.closest('.clip'))return;
885
- var rect=document.getElementById('tlBox').getBoundingClientRect();
886
- var scrollL=document.getElementById('tlBox').scrollLeft;
887
- S.time=Math.max(0,Math.min(S.dur||0,(e.clientX-rect.left-50+scrollL)/(S.pps*S.zoom)));
888
- updateHead();
889
- drawFrame();
890
- }}
891
-
892
- function showCtx(x,y){{var m=document.getElementById('ctx');m.style.display='block';m.style.left=x+'px';m.style.top=y+'px'}}
893
- function hideCtx(){{document.getElementById('ctx').style.display='none'}}
894
- document.addEventListener('click',function(e){{if(!e.target.closest('.ctx-menu'))hideCtx()}});
895
-
896
- function exportVideo(){{
897
- if(!S.clips.length){{alert('클립을 추가하세요');return}}
898
- S.cancelled=false;
899
- document.getElementById('exportModal').style.display='flex';
900
- document.getElementById('exportBar').style.width='0%';
901
- document.getElementById('exportMsg').textContent='녹화 준비 중...';
902
- doExport();
903
- }}
904
-
905
- async function doExport(){{
906
- var size=S.ratioSizes[S.ratio];
907
- var exportW=size.w,exportH=size.h;
908
-
909
- // 메인 캔버스 (MediaRecorder 연결용)
910
- var canvas=document.createElement('canvas');
911
- canvas.width=exportW;canvas.height=exportH;
912
- var ctx=canvas.getContext('2d');
913
-
914
- // 오프스크린 캔버스 (렌더링용 - 더블 버퍼링)
915
- var offCanvas=document.createElement('canvas');
916
- offCanvas.width=exportW;offCanvas.height=exportH;
917
- var offCtx=offCanvas.getContext('2d');
918
-
919
- // 초기 검은 화면
920
- ctx.fillStyle='#000';
921
- ctx.fillRect(0,0,exportW,exportH);
922
-
923
- var stream=canvas.captureStream(30);
924
-
925
- // 고화질 설정
926
- var opts={{mimeType:'video/webm;codecs=vp9',videoBitsPerSecond:8000000}};
927
- if(!MediaRecorder.isTypeSupported(opts.mimeType)){{
928
- opts={{mimeType:'video/webm;codecs=vp8',videoBitsPerSecond:8000000}};
929
- }}
930
- if(!MediaRecorder.isTypeSupported(opts.mimeType)){{
931
- opts={{mimeType:'video/webm',videoBitsPerSecond:5000000}};
932
- }}
933
-
934
- var rec=new MediaRecorder(stream,opts);
935
- var chunks=[];
936
- rec.ondataavailable=function(e){{if(e.data.size>0)chunks.push(e.data)}};
937
-
938
- document.getElementById('exportMsg').textContent='녹화 중... ('+S.ratio+')';
939
- rec.start(100);
940
-
941
- var dur=S.dur;
942
- var fps=30;
943
- var frameInterval=1000/fps;
944
- var totalFrames=Math.ceil(dur*fps);
945
- var startTime=performance.now();
946
- var fillMode=S.fillMode;
947
-
948
- // 실시간 기반 렌더링
949
- // 블러 모드용 프레임 캡처 캔버스 (재사용)
950
- var frameCanvas=document.createElement('canvas');
951
- frameCanvas.width=1920;frameCanvas.height=1080;
952
- var frameCtx=frameCanvas.getContext('2d');
953
-
954
- await new Promise(function(resolve){{
955
- var frameCount=0;
956
- var lastVideoEl=null;
957
- var lastClipId=null;
958
-
959
- function render(){{
960
- if(S.cancelled){{rec.stop();resolve();return}}
961
-
962
- var elapsed=performance.now()-startTime;
963
- var t=elapsed/1000;
964
-
965
- if(t>=dur){{
966
- rec.stop();
967
- setTimeout(resolve,100);
968
- return;
969
- }}
970
-
971
- document.getElementById('exportBar').style.width=(t/dur*100)+'%';
972
- document.getElementById('exportMsg').textContent='녹화 중... '+Math.round(t/dur*100)+'% ('+t.toFixed(1)+'/'+dur.toFixed(1)+'초)';
973
-
974
- offCtx.fillStyle='#000';
975
- offCtx.fillRect(0,0,exportW,exportH);
976
-
977
- var vc=getClipAt(t,'visual');
978
- if(vc){{
979
- var el=S.els[vc.mid];
980
- if(el){{
981
- if(vc.type==='video'){{
982
- var clipT=t-vc.start+vc.ts;
983
- if(lastClipId!==vc.id){{
984
- el.currentTime=clipT;
985
- el.play().catch(function(){{}});
986
- lastClipId=vc.id;
987
- lastVideoEl=el;
988
- }}
989
- if(lastVideoEl&&lastVideoEl!==el&&!lastVideoEl.paused){{
990
- lastVideoEl.pause();
991
- }}
992
- lastVideoEl=el;
993
- }}
994
-
995
- try{{
996
- var sw=el.videoWidth||el.naturalWidth||el.width||exportW;
997
- var sh=el.videoHeight||el.naturalHeight||el.height||exportH;
998
-
999
- // 블러 모드: 프레임을 먼저 캡처
1000
- if(fillMode==='blur'){{
1001
- frameCanvas.width=sw;frameCanvas.height=sh;
1002
- frameCtx.drawImage(el,0,0,sw,sh);
1003
- drawBlurFromFrame(offCtx,frameCanvas,sw,sh,exportW,exportH);
1004
- }}else{{
1005
- drawWithModeExport(offCtx,el,sw,sh,exportW,exportH,fillMode);
1006
- }}
1007
- }}catch(e){{}}
1008
- }}
1009
- }}else{{
1010
- if(lastVideoEl&&!lastVideoEl.paused){{
1011
- lastVideoEl.pause();
1012
- lastClipId=null;
1013
- }}
1014
- }}
1015
-
1016
- // 텍스트 오버레이 렌더링
1017
- var textClips=getTextClipsAt(t);
1018
- textClips.forEach(function(tc){{
1019
- drawTextExport(offCtx,tc,exportW,exportH);
1020
- }});
1021
-
1022
- ctx.drawImage(offCanvas,0,0);
1023
- requestAnimationFrame(render);
1024
- }}
1025
-
1026
- requestAnimationFrame(render);
1027
- }});
1028
-
1029
- Object.keys(S.els).forEach(function(k){{
1030
- var el=S.els[k];
1031
- if(el&&el.pause)el.pause();
1032
- }});
1033
-
1034
- if(S.cancelled)return;
1035
-
1036
- var webmBlob=new Blob(chunks,{{type:'video/webm'}});
1037
- if(webmBlob.size<1000){{document.getElementById('exportMsg').textContent='녹화 실패';return}}
1038
-
1039
- document.getElementById('exportBar').style.width='100%';
1040
- document.getElementById('exportMsg').textContent='완료! ('+Math.round(webmBlob.size/1024/1024*10)/10+'MB, '+S.ratio+') - 아래에서 다운로드';
1041
-
1042
- var downloadDiv=document.createElement('div');
1043
- downloadDiv.style.marginTop='10px';
1044
- var webmLink=document.createElement('a');
1045
- webmLink.href=URL.createObjectURL(webmBlob);
1046
- webmLink.download='video_'+S.ratio.replace(':','x')+'_'+Date.now()+'.webm';
1047
- webmLink.className='btn btn-success';
1048
- webmLink.textContent='📥 WebM 다운로드';
1049
- webmLink.style.marginRight='5px';
1050
- downloadDiv.appendChild(webmLink);
1051
-
1052
- var copyBtn=document.createElement('button');
1053
- copyBtn.className='btn btn-secondary';
1054
- copyBtn.textContent='📋 MP4변환용 복사';
1055
- copyBtn.onclick=async function(){{
1056
- document.getElementById('exportMsg').textContent='데이터 준비 중...';
1057
- var reader=new FileReader();
1058
- reader.onload=function(){{
1059
- var base64=reader.result.split(',')[1];
1060
- navigator.clipboard.writeText(base64).then(function(){{
1061
- document.getElementById('exportMsg').textContent='복사 완료! 위 입력란에 붙여넣기';
1062
- alert('복사 완료!\\n\\nGradio의 "WebM 데이터" 입력란에 붙여넣기(Ctrl+V) 후\\n"MP4 변환" 버튼을 클릭하세요.');
1063
- }}).catch(function(){{
1064
- prompt('아래 데이터를 복사하세요:', base64.substring(0,100)+'...');
1065
- }});
1066
- }};
1067
- reader.readAsDataURL(webmBlob);
1068
- }};
1069
- downloadDiv.appendChild(copyBtn);
1070
- document.querySelector('.modal-box').appendChild(downloadDiv);
1071
- }}
1072
-
1073
- // 내보내기용 그리기 함수 (블러 효과 포함)
1074
- function drawWithModeExport(ctx,el,sw,sh,dw,dh,mode){{
1075
- if(mode==='fill'){{
1076
- var scale=Math.max(dw/sw,dh/sh);
1077
- var nw=sw*scale,nh=sh*scale;
1078
- var ox=(dw-nw)/2,oy=(dh-nh)/2;
1079
- ctx.drawImage(el,ox,oy,nw,nh);
1080
- }}else{{
1081
- var scale=Math.min(dw/sw,dh/sh);
1082
- var nw=sw*scale,nh=sh*scale;
1083
- var ox=(dw-nw)/2,oy=(dh-nh)/2;
1084
- ctx.drawImage(el,ox,oy,nw,nh);
1085
- }}
1086
- }}
1087
-
1088
- // 블러 전용 - 캡처된 프레임으로 처리
1089
- function drawBlurFromFrame(ctx,frameCanvas,sw,sh,dw,dh){{
1090
- // 1. 작은 캔버스로 축소 (블러 효과)
1091
- var blurCanvas=document.createElement('canvas');
1092
- blurCanvas.width=16;blurCanvas.height=16;
1093
- var blurCtx=blurCanvas.getContext('2d');
1094
- blurCtx.drawImage(frameCanvas,0,0,16,16);
1095
-
1096
- // 2. 배경에 확대해서 그림
1097
- ctx.imageSmoothingEnabled=true;
1098
- ctx.imageSmoothingQuality='high';
1099
- var scale=Math.max(dw/sw,dh/sh)*1.1;
1100
- var nw=sw*scale,nh=sh*scale;
1101
- var ox=(dw-nw)/2,oy=(dh-nh)/2;
1102
- ctx.drawImage(blurCanvas,ox,oy,nw,nh);
1103
-
1104
- // 3. 어둡게
1105
- ctx.fillStyle='rgba(0,0,0,0.4)';
1106
- ctx.fillRect(0,0,dw,dh);
1107
-
1108
- // 4. 원본 (캡처된 프레임 사용)
1109
- var fitScale=Math.min(dw/sw,dh/sh);
1110
- var fw=sw*fitScale,fh=sh*fitScale;
1111
- var fx=(dw-fw)/2,fy=(dh-fh)/2;
1112
- ctx.drawImage(frameCanvas,fx,fy,fw,fh);
1113
- }}
1114
-
1115
- // 내보내기용 텍스트 렌더링
1116
- function drawTextExport(ctx,clip,dw,dh){{
1117
- var text=clip.text;
1118
- var fontSize=Math.round(clip.fontSize*(dw/640))||72; // 내보내기 해상도에 맞게 스케일
1119
- var fontColor=clip.fontColor||'#ffffff';
1120
- var bgStyle=clip.bgStyle||'none';
1121
- var bgColor=clip.bgColor||'#000000';
1122
-
1123
- ctx.font='bold '+fontSize+'px -apple-system,BlinkMacSystemFont,sans-serif';
1124
- ctx.textAlign='center';
1125
- ctx.textBaseline='middle';
1126
-
1127
- var metrics=ctx.measureText(text);
1128
- var textW=metrics.width;
1129
- var textH=fontSize;
1130
- var x=dw/2;
1131
- var y=dh-fontSize-50; // 하단에 배치
1132
-
1133
- if(bgStyle!=='none'){{
1134
- var padding=fontSize*0.3;
1135
- var bgX=x-textW/2-padding;
1136
- var bgY=y-textH/2-padding/2;
1137
- var bgW=textW+padding*2;
1138
- var bgH=textH+padding;
1139
-
1140
- ctx.fillStyle=bgColor+'cc';
1141
- if(bgStyle==='rounded'){{
1142
- ctx.beginPath();
1143
- ctx.roundRect(bgX,bgY,bgW,bgH,15);
1144
- ctx.fill();
1145
- }}else{{
1146
- ctx.fillRect(bgX,bgY,bgW,bgH);
1147
- }}
1148
- }}
1149
-
1150
- ctx.fillStyle='rgba(0,0,0,0.5)';
1151
- ctx.fillText(text,x+3,y+3);
1152
-
1153
- ctx.fillStyle=fontColor;
1154
- ctx.fillText(text,x,y);
1155
- }}
1156
-
1157
- function cancelExport(){{S.cancelled=true;document.getElementById('exportModal').style.display='none'}}
1158
-
1159
- document.addEventListener('keydown',function(e){{
1160
- if(e.target.tagName==='INPUT')return;
1161
- if(e.code==='Space'){{e.preventDefault();togglePlay()}}
1162
- else if(e.code==='Delete'){{e.preventDefault();delClip()}}
1163
- else if(e.code==='ArrowLeft'){{seek(S.time-0.1)}}
1164
- else if(e.code==='ArrowRight'){{seek(S.time+0.1)}}
1165
- }});
1166
-
1167
- init();
1168
- renderTL();
1169
- stat('준비됨');
1170
- var initData={media_data};
1171
- if(initData&&initData.length)initData.forEach(function(m){{addMedia(m.name,m.type,m.dataUrl,m.filePath)}});
1172
- </script>
1173
- </body>
1174
- </html>'''
1175
-
1176
- def process_file(files):
1177
- """파일 처리 및 서버에 저장"""
1178
- global uploaded_files
1179
- if not files:
1180
- return []
1181
- results = []
1182
- file_list = files if isinstance(files, list) else [files]
1183
- for f in file_list:
1184
- if not f:
1185
- continue
1186
- path = f.name if hasattr(f, 'name') else f
1187
- name = os.path.basename(path)
1188
- ext = name.lower().split('.')[-1]
1189
- if ext in ['mp4', 'webm', 'mov', 'avi', 'mkv']:
1190
- t, m = 'video', f'video/{ext}'
1191
- elif ext in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
1192
- t, m = 'image', f'image/{ext}'
1193
- elif ext in ['mp3', 'wav', 'ogg', 'm4a', 'aac']:
1194
- t, m = 'audio', f'audio/{ext}'
1195
- else:
1196
- continue
1197
-
1198
- # 서버에 파일 복사 (MP4 내보내기용)
1199
- dst_path = os.path.join(UPLOAD_DIR, f"{int(time.time()*1000)}_{name}")
1200
- shutil.copy(path, dst_path)
1201
- uploaded_files[name] = dst_path
1202
-
1203
- with open(path, 'rb') as fp:
1204
- d = base64.b64encode(fp.read()).decode()
1205
- results.append({'name': name, 'type': t, 'dataUrl': f'data:{m};base64,{d}', 'filePath': name})
1206
- return results
1207
-
1208
- def make_iframe(data):
1209
- j = json.dumps(data, ensure_ascii=False)
1210
- h = get_editor_html(j).replace("'", "&#39;")
1211
- return f"<iframe srcdoc='{h}' style='width:100%;height:750px;border:none;border-radius:10px'></iframe>"
1212
-
1213
- def export_mp4(export_json):
1214
- """서버 사이드 MP4 내보내기"""
1215
- global uploaded_files
1216
-
1217
- if not export_json or len(export_json) < 10:
1218
- return None
1219
-
1220
- try:
1221
- data = json.loads(export_json)
1222
- clips = data.get('clips', [])
1223
-
1224
- if not clips:
1225
- return None
1226
-
1227
- video_clips = [c for c in clips if c['type'] in ['video', 'image']]
1228
- if not video_clips:
1229
- return None
1230
-
1231
- temp_dir = tempfile.mkdtemp()
1232
- output_path = os.path.join(temp_dir, f'output_{int(time.time())}.mp4')
1233
-
1234
- # 단일 클립
1235
- if len(video_clips) == 1:
1236
- clip = video_clips[0]
1237
- file_path = uploaded_files.get(clip['filePath'])
1238
-
1239
- if not file_path or not os.path.exists(file_path):
1240
- return None
1241
-
1242
- duration = clip['te'] - clip['ts']
1243
-
1244
- if clip['type'] == 'image':
1245
- 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]
1246
- else:
1247
- 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]
1248
-
1249
- subprocess.run(cmd, capture_output=True, timeout=300)
1250
-
1251
- if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
1252
- return output_path
1253
- return None
1254
-
1255
- # 여러 클립
1256
- temp_files = []
1257
- concat_file = os.path.join(temp_dir, 'concat.txt')
1258
-
1259
- for i, clip in enumerate(sorted(video_clips, key=lambda x: x['start'])):
1260
- file_path = uploaded_files.get(clip['filePath'])
1261
- if not file_path or not os.path.exists(file_path):
1262
- continue
1263
-
1264
- temp_out = os.path.join(temp_dir, f'temp_{i}.mp4')
1265
- duration = clip['te'] - clip['ts']
1266
-
1267
- if clip['type'] == 'image':
1268
- 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]
1269
- else:
1270
- 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]
1271
-
1272
- subprocess.run(cmd, capture_output=True, timeout=120)
1273
- if os.path.exists(temp_out):
1274
- temp_files.append(temp_out)
1275
-
1276
- if not temp_files:
1277
- return None
1278
-
1279
- with open(concat_file, 'w') as f:
1280
- for tf in temp_files:
1281
- f.write(f"file '{tf}'\n")
1282
-
1283
- cmd = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_file, '-c:v', 'libx264', '-preset', 'fast', '-c:a', 'aac', '-movflags', '+faststart', output_path]
1284
- subprocess.run(cmd, capture_output=True, timeout=300)
1285
-
1286
- for tf in temp_files:
1287
- try: os.remove(tf)
1288
- except: pass
1289
-
1290
- if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
1291
- return output_path
1292
- return None
1293
-
1294
- except Exception as e:
1295
- print(f"[Export] Error: {e}")
1296
- return None
1297
-
1298
- def convert_webm_to_mp4(webm_base64):
1299
- """WebM base64 데이터를 MP4로 변환"""
1300
- if not webm_base64 or len(webm_base64) < 100:
1301
- return None
1302
-
1303
- try:
1304
- # base64 디코딩
1305
- webm_data = base64.b64decode(webm_base64)
1306
-
1307
- temp_dir = tempfile.mkdtemp()
1308
- webm_path = os.path.join(temp_dir, 'input.webm')
1309
- mp4_path = os.path.join(temp_dir, f'output_{int(time.time())}.mp4')
1310
-
1311
- # WebM 파일 저장
1312
- with open(webm_path, 'wb') as f:
1313
- f.write(webm_data)
1314
-
1315
- # FFmpeg로 MP4 변환
1316
- cmd = [
1317
- 'ffmpeg', '-y',
1318
- '-i', webm_path,
1319
- '-c:v', 'libx264',
1320
- '-preset', 'fast',
1321
- '-crf', '23',
1322
- '-c:a', 'aac',
1323
- '-b:a', '128k',
1324
- '-movflags', '+faststart',
1325
- mp4_path
1326
- ]
1327
-
1328
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
1329
-
1330
- # WebM 파일 삭제
1331
- try:
1332
- os.remove(webm_path)
1333
- except:
1334
- pass
1335
-
1336
- if os.path.exists(mp4_path) and os.path.getsize(mp4_path) > 0:
1337
- return mp4_path
1338
-
1339
- return None
1340
-
1341
- except Exception as e:
1342
- print(f"[Convert] Error: {e}")
1343
- return None
1344
-
1345
- with gr.Blocks() as demo:
1346
- gr.Markdown("## 🎬 Video Editor")
1347
-
1348
- f = gr.File(label="📁 파일 업로드", file_count="multiple", file_types=["video", "image", "audio"])
1349
- e = gr.HTML(value=make_iframe([]))
1350
-
1351
- gr.Markdown("---")
1352
- gr.Markdown("### 📥 MP4 변환")
1353
- gr.Markdown("에디터에서 '내보내기' → 'MP4변환용 복사' 클릭 후 아래에 붙여넣기")
1354
-
1355
- with gr.Row():
1356
- webm_data = gr.Textbox(label="WebM 데이터 (base64)", placeholder="여기에 붙여넣기 (Ctrl+V)", lines=2, scale=4)
1357
- convert_btn = gr.Button("🎬 MP4 변환", variant="primary", scale=1)
1358
-
1359
- mp4_output = gr.File(label="📥 MP4 다운로드")
1360
-
1361
- f.change(fn=lambda x: make_iframe(process_file(x)), inputs=[f], outputs=[e])
1362
- convert_btn.click(fn=convert_webm_to_mp4, inputs=[webm_data], outputs=[mp4_output])
1363
-
1364
- if __name__ == "__main__":
1365
- demo.launch()