seawolf2357 commited on
Commit
0ae822c
·
verified ·
1 Parent(s): 6c98fe0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +594 -557
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
- Simple Video Editor - 허깅페이스 스페이스용
3
- srcdoc 방식으로 iframe 사용 - 파일 업로드 시 UI 유지
4
  """
5
 
6
  import gradio as gr
@@ -9,678 +9,715 @@ import os
9
  import json
10
 
11
  def get_editor_html(media_data="[]"):
12
- """에디터 HTML 생성"""
13
  return f'''<!DOCTYPE html>
14
  <html lang="ko">
15
  <head>
16
  <meta charset="UTF-8">
17
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
18
  <style>
19
  *{{margin:0;padding:0;box-sizing:border-box}}
20
- body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Noto Sans KR',sans-serif;background:#f5f5f7;color:#1d1d1f;font-size:13px}}
21
- .editor-container{{display:flex;flex-direction:column;height:100vh;background:#f5f5f7;overflow:hidden}}
22
- .toolbar{{height:48px;background:#fff;border-bottom:1px solid #e0e0e0;display:flex;align-items:center;justify-content:space-between;padding:0 12px;box-shadow:0 1px 3px rgba(0,0,0,0.05)}}
23
- .toolbar-title{{font-size:15px;font-weight:600;color:#1d1d1f;display:flex;align-items:center;gap:6px}}
24
- .toolbar-title svg{{width:20px;height:20px;color:#6366f1}}
25
- .toolbar-actions{{display:flex;gap:8px}}
26
- .btn{{padding:6px 12px;border:none;border-radius:6px;cursor:pointer;font-size:12px;font-weight:500;display:flex;align-items:center;gap:4px;transition:all 0.15s}}
27
- .btn svg{{width:14px;height:14px}}
28
- .btn-primary{{background:#6366f1;color:#fff}}
29
- .btn-primary:hover{{background:#4f46e5}}
30
  .btn-success{{background:#10b981;color:#fff}}
31
- .btn-success:hover{{background:#059669}}
32
  .btn-danger{{background:#ef4444;color:#fff}}
33
- .btn-danger:hover{{background:#dc2626}}
34
- .btn-secondary{{background:#f3f4f6;color:#374151;border:1px solid #e5e7eb}}
35
- .btn-secondary:hover{{background:#e5e7eb}}
36
- .main-area{{display:flex;flex:1;overflow:hidden;background:#f5f5f7}}
37
- .media-library{{width:200px;background:#fff;border-right:1px solid #e0e0e0;display:flex;flex-direction:column}}
38
- .library-header{{padding:10px 12px;border-bottom:1px solid #e0e0e0;font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px}}
39
- .library-content{{flex:1;overflow-y:auto;padding:8px}}
40
- .library-hint{{text-align:center;padding:20px 10px;color:#9ca3af;font-size:11px;line-height:1.5}}
41
- .media-grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:6px}}
42
- .media-item{{aspect-ratio:16/9;background:#f3f4f6;border-radius:6px;overflow:hidden;cursor:grab;position:relative;transition:all 0.15s;border:1px solid #e5e7eb}}
43
- .media-item:hover{{transform:scale(1.02);box-shadow:0 2px 8px rgba(0,0,0,0.1);border-color:#6366f1}}
44
- .media-item img,.media-item video{{width:100%;height:100%;object-fit:cover}}
45
- .media-item-overlay{{position:absolute;inset:0;background:linear-gradient(transparent 40%,rgba(0,0,0,0.7));opacity:0;transition:opacity 0.15s;display:flex;align-items:flex-end;padding:4px}}
46
- .media-item:hover .media-item-overlay{{opacity:1}}
47
- .media-item-name{{font-size:9px;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}
48
- .media-item-duration{{position:absolute;top:3px;right:3px;background:rgba(0,0,0,0.6);padding:1px 4px;border-radius:3px;font-size:9px;color:#fff}}
49
- .media-item-type{{position:absolute;top:3px;left:3px;width:16px;height:16px;background:rgba(0,0,0,0.6);border-radius:50%;display:flex;align-items:center;justify-content:center}}
50
- .media-item-type svg{{width:10px;height:10px;color:#fff}}
51
- .media-item-icon{{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:24px;color:#9ca3af;background:#e5e7eb}}
52
- .preview-area{{flex:1;display:flex;flex-direction:column;background:#1a1a1a;margin:8px;border-radius:12px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,0.15)}}
53
- .preview-container{{flex:1;display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden;background:#000}}
54
- .preview-container video,.preview-container img{{max-width:100%;max-height:100%;object-fit:contain}}
55
- .preview-placeholder{{text-align:center;color:#666}}
56
- .preview-placeholder svg{{width:48px;height:48px;margin-bottom:12px;opacity:0.5}}
57
- .preview-placeholder p{{font-size:12px}}
58
- .playback-controls{{height:50px;background:linear-gradient(180deg,#2a2a2a,#1a1a1a);display:flex;align-items:center;justify-content:center;gap:8px;padding:0 16px}}
59
- .control-btn{{width:32px;height:32px;border:none;border-radius:50%;background:rgba(255,255,255,0.1);color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.15s}}
60
- .control-btn:hover{{background:rgba(255,255,255,0.2)}}
61
- .control-btn svg{{width:14px;height:14px}}
62
- .control-btn.play-btn{{width:40px;height:40px;background:#6366f1}}
63
- .control-btn.play-btn:hover{{background:#4f46e5;transform:scale(1.05)}}
64
- .control-btn.play-btn svg{{width:18px;height:18px}}
65
- .time-display{{font-family:'SF Mono',Monaco,monospace;font-size:11px;color:#aaa;min-width:110px;text-align:center}}
66
- .properties-panel{{width:180px;background:#fff;border-left:1px solid #e0e0e0;display:flex;flex-direction:column}}
67
- .properties-header{{padding:10px 12px;border-bottom:1px solid #e0e0e0;font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px}}
68
- .properties-content{{flex:1;padding:12px;overflow-y:auto}}
69
- .property-group{{margin-bottom:14px}}
70
- .property-label{{font-size:10px;color:#6b7280;margin-bottom:4px;text-transform:uppercase;letter-spacing:0.3px}}
71
- .property-input{{width:100%;padding:6px 8px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:5px;color:#1d1d1f;font-size:12px}}
72
- .property-input:focus{{outline:none;border-color:#6366f1;box-shadow:0 0 0 2px rgba(99,102,241,0.1)}}
73
- .property-row{{display:flex;gap:8px}}
74
- .property-row>div{{flex:1}}
75
- .no-selection{{color:#9ca3af;text-align:center;padding:30px 15px;font-size:12px;line-height:1.5}}
76
- .timeline-area{{height:180px;background:#fff;border-top:1px solid #e0e0e0;display:flex;flex-direction:column}}
77
- .timeline-toolbar{{height:32px;background:#fafafa;border-bottom:1px solid #e0e0e0;display:flex;align-items:center;padding:0 8px;gap:6px}}
78
- .timeline-toolbar .btn{{padding:4px 8px;font-size:11px}}
79
- .timeline-toolbar .btn svg{{width:12px;height:12px}}
80
- .timeline-zoom{{display:flex;align-items:center;gap:4px;margin-left:auto;font-size:11px;color:#6b7280}}
81
- .timeline-zoom input{{width:60px;height:4px}}
82
- .timeline-zoom svg{{width:12px;height:12px}}
83
- .timeline-container{{flex:1;overflow-x:auto;overflow-y:hidden;position:relative;background:#f9fafb}}
84
- .timeline-ruler{{height:22px;background:#fff;position:sticky;top:0;z-index:10;border-bottom:1px solid #e5e7eb}}
85
- .timeline-tracks{{position:relative;min-height:120px}}
86
- .timeline-track{{height:55px;border-bottom:1px solid #e5e7eb;position:relative;display:flex;align-items:center;background:#fff}}
87
- .timeline-track:nth-child(2){{background:#fffbeb}}
88
- .track-label{{width:70px;padding:0 8px;font-size:10px;color:#6b7280;background:#f9fafb;height:100%;display:flex;align-items:center;gap:4px;border-right:1px solid #e5e7eb;position:sticky;left:0;z-index:5}}
89
- .track-label svg{{width:12px;height:12px}}
90
- .track-content{{flex:1;height:100%;position:relative;min-width:800px}}
91
- .timeline-clip{{position:absolute;height:45px;top:5px;border-radius:6px;cursor:grab;display:flex;align-items:center;overflow:hidden;transition:box-shadow 0.15s;min-width:40px;box-shadow:0 1px 3px rgba(0,0,0,0.1)}}
92
- .timeline-clip:hover{{box-shadow:0 0 0 2px #6366f1}}
93
- .timeline-clip.selected{{box-shadow:0 0 0 2px #6366f1,0 4px 12px rgba(99,102,241,0.3)}}
94
- .timeline-clip.video{{background:linear-gradient(135deg,#818cf8,#6366f1)}}
95
- .timeline-clip.image{{background:linear-gradient(135deg,#34d399,#10b981)}}
96
- .timeline-clip.audio{{background:linear-gradient(135deg,#fbbf24,#f59e0b)}}
97
- .clip-thumbnail{{width:45px;height:100%;object-fit:cover;flex-shrink:0}}
98
- .clip-info{{padding:0 6px;flex:1;overflow:hidden}}
99
- .clip-name{{font-size:10px;font-weight:500;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}
100
- .clip-duration{{font-size:9px;color:rgba(255,255,255,0.7)}}
101
- .clip-handles{{position:absolute;top:0;bottom:0;width:10px;background:rgba(255,255,255,0.5);cursor:ew-resize;opacity:0;transition:opacity 0.15s;z-index:10}}
102
- .timeline-clip:hover .clip-handles{{opacity:1}}
103
- .clip-handle-left{{left:0;border-radius:6px 0 0 6px}}
104
- .clip-handle-right{{right:0;border-radius:0 6px 6px 0}}
105
- .playhead{{position:absolute;top:0;bottom:0;width:2px;background:#ef4444;z-index:20;pointer-events:none}}
106
- .playhead::before{{content:'';position:absolute;top:0;left:-5px;width:12px;height:12px;background:#ef4444;clip-path:polygon(50% 100%,0 0,100% 0)}}
107
- .drop-highlight{{background:rgba(99,102,241,0.1)!important;outline:2px dashed #6366f1!important;outline-offset:-2px}}
108
- .context-menu{{position:fixed;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:4px 0;min-width:140px;z-index:1000;box-shadow:0 10px 40px rgba(0,0,0,0.15)}}
109
- .context-menu-item{{padding:6px 12px;cursor:pointer;display:flex;align-items:center;gap:8px;font-size:12px}}
110
- .context-menu-item:hover{{background:#f3f4f6}}
111
- .context-menu-item svg{{width:12px;height:12px}}
112
- .context-menu-item.danger{{color:#ef4444}}
113
- .context-menu-divider{{height:1px;background:#e5e7eb;margin:4px 0}}
114
- .status-bar{{height:24px;background:#f0f0f0;border-top:1px solid #e0e0e0;display:flex;align-items:center;padding:0 12px;font-size:11px;color:#666}}
115
- .modal-overlay{{position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:1000}}
116
- .modal{{background:#fff;border-radius:12px;padding:24px;min-width:280px;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3)}}
117
- .modal h3{{margin-bottom:12px;font-size:16px}}
118
- .modal p{{font-size:13px;color:#6b7280}}
119
- .progress-bar{{height:6px;background:#e5e7eb;border-radius:3px;overflow:hidden;margin:16px 0}}
120
- .progress-fill{{height:100%;background:linear-gradient(90deg,#6366f1,#8b5cf6);transition:width 0.3s}}
121
- ::-webkit-scrollbar{{width:6px;height:6px}}
122
- ::-webkit-scrollbar-track{{background:#f1f1f1}}
123
- ::-webkit-scrollbar-thumb{{background:#c1c1c1;border-radius:3px}}
124
  </style>
125
  </head>
126
  <body>
127
- <div class="editor-container">
128
  <div class="toolbar">
129
- <div class="toolbar-title">
130
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="2" width="20" height="20" rx="2"/><line x1="7" y1="2" x2="7" y2="22"/><line x1="17" y1="2" x2="17" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/></svg>
131
- Simple Video Editor
 
132
  </div>
133
- <div class="toolbar-actions">
134
- <button class="btn btn-secondary" onclick="editorUndo()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v6h6M3 13a9 9 0 1 0 2.5-6.5"/></svg>실행취소</button>
135
- <button class="btn btn-success" onclick="editorExport()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>내보내기</button>
136
  </div>
137
- </div>
138
- <div class="main-area">
139
- <div class="media-library">
140
- <div class="library-header">📁 미디어</div>
141
- <div class="library-content">
142
- <div class="library-hint" id="libraryHint">⬆️ 위의 파일 업로드를<br>사용하세요</div>
143
  <div class="media-grid" id="mediaGrid"></div>
144
  </div>
145
  </div>
146
  <div class="preview-area">
147
- <div class="preview-container" id="previewContainer">
148
- <div class="preview-placeholder">
149
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1"><rect x="2" y="2" width="20" height="20" rx="2"/><polygon points="10 8 16 12 10 16 10 8"/></svg>
150
- <p>타임라인에 미디어를 추가하세요</p>
151
- </div>
152
- </div>
153
- <div class="playback-controls">
154
- <button class="control-btn" onclick="editorSkipStart()"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/></svg></button>
155
- <button class="control-btn" onclick="editorSkipBack()"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z"/></svg></button>
156
- <button class="control-btn play-btn" onclick="editorTogglePlay()"><svg viewBox="0 0 24 24" fill="currentColor" id="playIcon"><polygon points="5 3 19 12 5 21 5 3"/></svg></button>
157
- <button class="control-btn" onclick="editorSkipForward()"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z"/></svg></button>
158
- <button class="control-btn" onclick="editorSkipEnd()"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/></svg></button>
159
- <div class="time-display"><span id="currentTimeDisplay">00:00.00</span> / <span id="durationDisplay">00:00.00</span></div>
160
- <button class="control-btn" onclick="editorToggleMute()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" id="volumeIcon"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/></svg></button>
161
- </div>
162
  </div>
163
- <div class="properties-panel">
164
- <div class="properties-header">⚙️ 속성</div>
165
- <div class="properties-content" id="propertiesContent"><div class="no-selection">클립을 선택하면<br>속성을 편집할 수 있습니다</div></div>
 
 
 
 
 
166
  </div>
167
  </div>
168
- <div class="timeline-area">
169
- <div class="timeline-toolbar">
170
- <button class="btn btn-secondary" onclick="editorSplit()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/></svg>자르기</button>
171
- <button class="btn btn-secondary" onclick="editorDuplicate()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>복제</button>
172
- <button class="btn btn-danger" onclick="editorDelete()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>삭제</button>
173
- <div class="timeline-zoom">
174
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
175
- <input type="range" min="0.5" max="3" step="0.1" value="1" oninput="editorSetZoom(this.value)">
176
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
177
  </div>
178
  </div>
179
- <div class="timeline-container" id="timelineContainer" onclick="editorTimelineClick(event)">
180
- <div class="timeline-ruler" id="timelineRuler"></div>
181
- <div class="timeline-tracks">
182
- <div class="timeline-track" data-track="0">
183
- <div class="track-label"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>영상</div>
184
- <div class="track-content" id="track0"></div>
185
  </div>
186
- <div class="timeline-track" data-track="1">
187
- <div class="track-label"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>오디오</div>
188
- <div class="track-content" id="track1"></div>
 
 
189
  </div>
 
190
  </div>
191
- <div class="playhead" id="playhead" style="left:70px"></div>
192
  </div>
 
193
  </div>
194
- <div class="status-bar" id="statusBar">준비됨 | 미디어: 0개 | 클립: 0개</div>
 
 
 
195
  </div>
196
- <div class="context-menu" id="contextMenu" style="display:none">
197
- <div class="context-menu-item" onclick="editorSplit()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/></svg>자르기</div>
198
- <div class="context-menu-item" onclick="editorDuplicate()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>복제</div>
199
- <div class="context-menu-divider"></div>
200
- <div class="context-menu-item danger" onclick="editorDelete()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>삭제</div>
201
- </div>
202
- <div class="modal-overlay" id="exportModal" style="display:none">
203
- <div class="modal">
204
  <h3>🎬 영상 내보내기</h3>
205
- <p id="exportStatus">영상을 처리하고 있습니다...</p>
206
- <div class="progress-bar"><div class="progress-fill" id="exportProgress" style="width:0%"></div></div>
207
- <button class="btn btn-secondary" onclick="editorCancelExport()" id="cancelExportBtn">취소</button>
208
  </div>
209
  </div>
 
210
  <script>
211
- var S={{mediaLibrary:[],timelineClips:[],selectedClipId:null,isPlaying:false,isMuted:false,currentTime:0,totalDuration:0,zoom:1,pps:80,undoStack:[],animId:null,audioElements:{{}},trimData:null,exportCancelled:false}};
212
- function gid(){{return Date.now().toString(36)+Math.random().toString(36).substr(2)}}
213
- function fmt(s){{if(!s||isNaN(s))s=0;var m=Math.floor(s/60),sec=Math.floor(s%60),ms=Math.floor((s%1)*100);return(m<10?'0':'')+m+':'+(sec<10?'0':'')+sec+'.'+(ms<10?'0':'')+ms}}
214
- function upStat(msg){{var e=document.getElementById('statusBar');if(e)e.textContent=msg+' | 미디어: '+S.mediaLibrary.length+'개 | 클립: '+S.timelineClips.length+'개'}}
215
- function save(){{S.undoStack.push(JSON.stringify(S.timelineClips));if(S.undoStack.length>50)S.undoStack.shift()}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  function addMedia(name,type,url){{
217
- console.log('Adding:',name,type);
218
- var m={{id:gid(),name:name,type:type,url:url,duration:type==='image'?5:0,thumb:type==='image'?url:null}};
219
- S.mediaLibrary.push(m);
220
- if(type==='video'||type==='audio'){{
221
- var el=document.createElement(type);el.src=url;el.preload='metadata';
222
- el.onloadedmetadata=function(){{m.duration=Math.round(el.duration*1000)/1000;renderLib();if(type==='video')el.currentTime=Math.min(1,el.duration/2)}};
223
- el.onseeked=function(){{if(type==='video'){{try{{var c=document.createElement('canvas');c.width=160;c.height=90;c.getContext('2d').drawImage(el,0,0,160,90);m.thumb=c.toDataURL();renderLib()}}catch(e){{}}}}}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  }}
225
- renderLib();upStat('미디어 추가됨: '+name);
226
- setTimeout(function(){{addToTL(m)}},100);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  }}
 
228
  function renderLib(){{
229
- var g=document.getElementById('mediaGrid'),h=document.getElementById('libraryHint');
230
- if(!g)return;
231
- if(h)h.style.display=S.mediaLibrary.length===0?'block':'none';
232
  g.innerHTML='';
233
- var icons={{video:'<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21"/></svg>',image:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',audio:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>'}};
234
- S.mediaLibrary.forEach(function(m){{
235
- var d=document.createElement('div');d.className='media-item';d.draggable=true;
236
- d.ondblclick=function(){{addToTL(m)}};
237
- d.ondragstart=function(e){{e.dataTransfer.setData('mid',m.id);this.style.opacity='0.5'}};
238
- d.ondragend=function(){{this.style.opacity='1'}};
239
- var th=m.thumb?'<img src="'+m.thumb+'">':'<div class="media-item-icon">'+(m.type==='video'?'🎬':m.type==='audio'?'🎵':'🖼')+'</div>';
240
- d.innerHTML=th+'<div class="media-item-type">'+icons[m.type]+'</div>'+(m.duration>0?'<div class="media-item-duration">'+fmt(m.duration)+'</div>':'')+'<div class="media-item-overlay"><span class="media-item-name">'+m.name+'</span></div>';
241
  g.appendChild(d);
242
  }});
243
  }}
244
- function addToTL(m,st){{
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  save();
246
  var tr=m.type==='audio'?1:0;
247
- var start;
248
- if(st!==undefined){{
249
- start=Math.round(st*1000)/1000;
250
- }}else{{
251
- start=getTrEnd(tr);
252
- }}
253
- var c={{id:gid(),mid:m.id,name:m.name,type:m.type,url:m.url,thumb:m.thumb,track:tr,start:start,dur:m.duration,ts:0,te:m.duration,vol:1}};
254
- S.timelineClips.push(c);
255
- renderTL();upDur();upStat('클립 추가됨: '+c.name);
 
 
 
 
 
 
 
 
256
  }}
257
- function getTrEnd(tr){{var mx=0;S.timelineClips.forEach(function(c){{if(c.track===tr){{var e=c.start+(c.te-c.ts);if(e>mx)mx=e}}}});return Math.round(mx*1000)/1000}}
258
  function renderTL(){{
259
- var t0=document.getElementById('track0'),t1=document.getElementById('track1');
260
- if(t0)t0.innerHTML='';if(t1)t1.innerHTML='';
261
- S.timelineClips.forEach(function(c){{
262
- var tr=document.getElementById('track'+c.track);if(!tr)return;
263
- var d=document.createElement('div');
264
- d.className='timeline-clip '+c.type+(S.selectedClipId===c.id?' selected':'');
265
- var cd=c.te-c.ts,l=c.start*S.pps*S.zoom,w=Math.max(40,cd*S.pps*S.zoom);
266
- d.style.left=l+'px';d.style.width=w+'px';d.draggable=true;
267
- d.onclick=function(e){{e.stopPropagation();selClip(c.id)}};
268
- d.oncontextmenu=function(e){{e.preventDefault();selClip(c.id);showCtx(e.clientX,e.clientY)}};
269
- d.ondragstart=function(e){{e.dataTransfer.setData('cid',c.id);e.dataTransfer.setData('ox',e.offsetX.toString())}};
270
- var th=c.thumb?'<img class="clip-thumbnail" src="'+c.thumb+'">':'';
271
- d.innerHTML=th+'<div class="clip-info"><div class="clip-name">'+c.name+'</div><div class="clip-duration">'+fmt(cd)+'</div></div><div class="clip-handles clip-handle-left" data-cid="'+c.id+'" data-side="left"></div><div class="clip-handles clip-handle-right" data-cid="'+c.id+'" data-side="right"></div>';
272
- var hl=d.querySelector('.clip-handle-left');
273
- var hr=d.querySelector('.clip-handle-right');
274
- hl.onmousedown=function(e){{e.stopPropagation();startTrim(e,c.id,'left')}};
275
- hr.onmousedown=function(e){{e.stopPropagation();startTrim(e,c.id,'right')}};
276
- tr.appendChild(d);
277
  }});
278
- renderRuler();setupDrop();
 
279
  }}
280
- function startTrim(e,cid,side){{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  e.preventDefault();
282
- var c=S.timelineClips.find(function(x){{return x.id===cid}});if(!c)return;
 
283
  save();
284
- S.trimData={{cid:cid,side:side,startX:e.clientX,origTs:c.ts,origTe:c.te,origStart:c.start}};
285
  document.addEventListener('mousemove',doTrim);
286
  document.addEventListener('mouseup',endTrim);
287
  }}
288
  function doTrim(e){{
289
- if(!S.trimData)return;
290
- var c=S.timelineClips.find(function(x){{return x.id===S.trimData.cid}});if(!c)return;
291
- var dx=e.clientX-S.trimData.startX;
292
- var dt=dx/(S.pps*S.zoom);
293
- dt=Math.round(dt*1000)/1000;
294
- if(S.trimData.side==='left'){{
295
- var newTs=Math.max(0,Math.min(c.te-0.1,S.trimData.origTs+dt));
296
- newTs=Math.round(newTs*1000)/1000;
297
- var delta=newTs-S.trimData.origTs;
298
- c.ts=newTs;
299
- c.start=Math.round((S.trimData.origStart+delta)*1000)/1000;
300
  }}else{{
301
- var newTe=Math.max(c.ts+0.1,Math.min(c.dur,S.trimData.origTe+dt));
302
- c.te=Math.round(newTe*1000)/1000;
303
  }}
304
- renderTL();upDur();
 
305
  }}
306
  function endTrim(){{
307
- S.trimData=null;
308
  document.removeEventListener('mousemove',doTrim);
309
  document.removeEventListener('mouseup',endTrim);
310
  }}
311
- function renderRuler(){{
312
- var r=document.getElementById('timelineRuler');if(!r)return;
313
- var w=Math.max(S.totalDuration*S.pps*S.zoom+300,1000);r.style.width=w+'px';
314
- var h='<svg width="100%" height="22" style="position:absolute;left:70px">';
315
- var st=S.zoom<0.7?5:S.zoom<1.5?2:1;
316
- for(var i=0;i<=Math.ceil(S.totalDuration)+10;i+=st){{var x=i*S.pps*S.zoom;h+='<line x1="'+x+'" y1="17" x2="'+x+'" y2="22" stroke="#d1d5db"/><text x="'+x+'" y="12" fill="#9ca3af" font-size="9" text-anchor="middle">'+fmt(i)+'</text>'}}
317
- h+='</svg>';r.innerHTML=h;
 
 
 
 
 
318
  }}
319
- function setupDrop(){{
320
- ['track0','track1'].forEach(function(tid,idx){{
321
- var tr=document.getElementById(tid);if(!tr)return;
322
- tr.ondragover=function(e){{e.preventDefault();tr.classList.add('drop-highlight')}};
323
- tr.ondragleave=function(){{tr.classList.remove('drop-highlight')}};
324
- tr.ondrop=function(e){{
325
- e.preventDefault();tr.classList.remove('drop-highlight');
326
- var rect=tr.getBoundingClientRect(),x=e.clientX-rect.left,t=Math.max(0,x/(S.pps*S.zoom));
327
- t=Math.round(t*1000)/1000;
328
- var mid=e.dataTransfer.getData('mid'),cid=e.dataTransfer.getData('cid'),ox=parseFloat(e.dataTransfer.getData('ox')||0);
329
- if(mid){{var m=S.mediaLibrary.find(function(x){{return x.id===mid}});if(m){{addToTL(m,t);var tgt=m.type==='audio'?1:idx;if(tgt!==idx){{S.timelineClips[S.timelineClips.length-1].track=tgt;renderTL()}}}}}}
330
- else if(cid){{save();var c=S.timelineClips.find(function(x){{return x.id===cid}});if(c){{var newStart=Math.max(0,t-ox/(S.pps*S.zoom));c.start=Math.round(newStart*1000)/1000;c.track=c.type==='audio'?1:idx;renderTL();upDur()}}}}
331
- }};
332
- }});
333
  }}
334
- function selClip(id){{S.selectedClipId=id;renderTL();renderProps()}}
335
- function renderProps(){{
336
- var ct=document.getElementById('propertiesContent');if(!ct)return;
337
- var c=S.timelineClips.find(function(x){{return x.id===S.selectedClipId}});
338
- if(!c){{ct.innerHTML='<div class="no-selection">클립을 선택하면<br>속성을 편집할 수 있습니다</div>';return}}
339
- var cd=c.te-c.ts;
340
- var h='<div class="property-group"><div class="property-label">름</div><input type="text" class="property-input" value="'+c.name+'" onchange="upProp(\\'name\\',this.value)"></div>'+
341
- '<div class="property-group"><div class="property-label">시작</div><input type="number" class="property-input" value="'+c.start.toFixed(2)+'" step="0.1" min="0" onchange="upProp(\\'start\\',parseFloat(this.value))"></div>'+
342
- '<div class="property-group"><div class="property-row"><div><div class="property-label">트림시작</div><input type="number" class="property-input" value="'+c.ts.toFixed(2)+'" step="0.1" min="0" max="'+c.dur+'" onchange="upProp(\\'ts\\',parseFloat(this.value))"></div>'+
343
- '<div><div class="property-label">트림끝</div><input type="number" class="property-input" value="'+c.te.toFixed(2)+'" step="0.1" min="0" max="'+c.dur+'" onchange="upProp(\\'te\\',parseFloat(this.value))"></div></div></div>'+
344
- '<div class="property-group"><div class="property-label">길이</div><div style="padding:6px 0;font-size:12px;color:#374151">'+fmt(cd)+'</div></div>';
345
- if(c.type!=='image')h+='<div class="property-group"><div class="property-label">볼륨 ('+Math.round(c.vol*100)+'%)</div><input type="range" class="property-input" style="padding:0" min="0" max="1" step="0.05" value="'+c.vol+'" oninput="upProp(\\'vol\\',parseFloat(this.value))"></div>';
346
- ct.innerHTML=h;
347
- }}
348
- function upProp(p,v){{save();var c=S.timelineClips.find(function(x){{return x.id===S.selectedClipId}});if(c){{c[p]=v;renderTL();upDur();renderProps()}}}}
349
- function editorSplit(){{
350
- if(!S.selectedClipId){{alert('클립을 선택해주세요.');return}}
351
- var c=S.timelineClips.find(function(x){{return x.id===S.selectedClipId}});if(!c)return;
352
- var clipStart=Math.round(c.start*1000)/1000;
353
- var clipEnd=Math.round((c.start+(c.te-c.ts))*1000)/1000;
354
- var curTime=Math.round(S.currentTime*1000)/1000;
355
- if(curTime<=clipStart||curTime>=clipEnd){{alert('플레이헤드가 선택한 클립 범위 안에 있어야 합니다.');return}}
356
  save();
357
- var splitAt=Math.round((S.currentTime-c.start)*1000)/1000;
358
  var c2=JSON.parse(JSON.stringify(c));
359
- c2.id=gid();
360
- c2.start=Math.round(S.currentTime*1000)/1000;
361
- c2.ts=Math.round((c.ts+splitAt)*1000)/1000;
362
- c.te=Math.round((c.ts+splitAt)*1000)/1000;
363
- S.timelineClips.push(c2);
364
- renderTL();upDur();hideCtx();upStat('클립 현재 위치에서 분할됨');
365
- }}
366
- function editorDuplicate(){{
367
- if(!S.selectedClipId)return;
368
- var c=S.timelineClips.find(function(x){{return x.id===S.selectedClipId}});if(!c)return;
 
 
369
  save();
370
- var cd=Math.round((c.te-c.ts)*1000)/1000;
371
  var nc=JSON.parse(JSON.stringify(c));
372
- nc.id=gid();
373
- nc.start=Math.round((c.start+cd)*1000)/1000;
374
- S.timelineClips.push(nc);
375
- renderTL();upDur();hideCtx();upStat('클립 복제됨');
376
- }}
377
- function editorDelete(){{
378
- if(!S.selectedClipId)return;save();
379
- S.timelineClips=S.timelineClips.filter(function(x){{return x.id!==S.selectedClipId}});
380
- S.selectedClipId=null;renderTL();renderProps();upDur();hideCtx();upStat('클립 삭제됨');
381
- }}
382
- function editorUndo(){{if(S.undoStack.length>0){{S.timelineClips=JSON.parse(S.undoStack.pop());renderTL();upDur();upStat('실행취소')}}}}
383
- function upDur(){{var mx=0;S.timelineClips.forEach(function(c){{var e=c.start+(c.te-c.ts);e=Math.round(e*1000)/1000;if(e>mx)mx=e}});S.totalDuration=mx;document.getElementById('durationDisplay').textContent=fmt(mx)}}
384
- function editorTogglePlay(){{
385
- S.isPlaying=!S.isPlaying;var ic=document.getElementById('playIcon');
386
- if(S.isPlaying){{ic.innerHTML='<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>';startPB()}}
387
- else{{ic.innerHTML='<polygon points="5 3 19 12 5 21 5 3"/>';stopPB()}}
388
- }}
389
- function startPB(){{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  var last=performance.now();
391
- function anim(now){{
392
- if(!S.isPlaying)return;
393
- var d=(now-last)/1000;last=now;S.currentTime+=d;
394
- if(S.currentTime>=S.totalDuration){{S.currentTime=0;if(S.totalDuration===0){{S.isPlaying=false;document.getElementById('playIcon').innerHTML='<polygon points="5 3 19 12 5 21 5 3"/>';return}}}}
395
- upPH();upPrev();S.animId=requestAnimationFrame(anim);
396
- }}
397
- S.animId=requestAnimationFrame(anim);
398
- }}
399
- function stopPB(){{if(S.animId){{cancelAnimationFrame(S.animId);S.animId=null}}var v=document.querySelector('#previewContainer video');if(v&&!v.paused)v.pause();if(S.audioElements)Object.keys(S.audioElements).forEach(function(id){{var au=S.audioElements[id];if(au&&!au.paused)au.pause()}})}}
400
- function upPH(){{var p=document.getElementById('playhead');if(p)p.style.left=(70+S.currentTime*S.pps*S.zoom)+'px';document.getElementById('currentTimeDisplay').textContent=fmt(S.currentTime)}}
401
- function upPrev(){{
402
- var ct=document.getElementById('previewContainer');if(!ct)return;
403
- var t=Math.round(S.currentTime*1000)/1000;
404
- var cur=S.timelineClips.filter(function(c){{
405
- var cs=Math.round(c.start*1000)/1000;
406
- var ce=Math.round((c.start+(c.te-c.ts))*1000)/1000;
407
- return t>=cs&&t<ce;
 
 
 
 
408
  }});
409
- var vc=cur.find(function(c){{return c.type==='video'||c.type==='image'}});
410
- var ac=cur.filter(function(c){{return c.type==='audio'}});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  if(vc){{
412
- var ct2=S.currentTime-vc.start+vc.ts;
413
- if(vc.type==='image'){{if(!ct.querySelector('img[data-cid="'+vc.id+'"]'))ct.innerHTML='<img src="'+vc.url+'" data-cid="'+vc.id+'">'}}
414
- else if(vc.type==='video'){{
415
- var v=ct.querySelector('video[data-cid="'+vc.id+'"]');
416
- if(!v){{ct.innerHTML='<video src="'+vc.url+'" data-cid="'+vc.id+'"'+(S.isMuted?' muted':'')+'></video>';v=ct.querySelector('video')}}
417
- if(Math.abs(v.currentTime-ct2)>0.2)v.currentTime=ct2;
418
- if(S.isPlaying&&v.paused)v.play().catch(function(){{}});
419
- else if(!S.isPlaying&&!v.paused)v.pause();
420
- v.volume=S.isMuted?0:vc.vol;v.muted=S.isMuted;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  }}
422
- }}else{{
423
- var ha=ac.length>0;
424
- if(!ct.querySelector('.preview-placeholder'))ct.innerHTML='<div class="preview-placeholder"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1"><rect x="2" y="2" width="20" height="20" rx="2"/><polygon points="10 8 16 12 10 16 10 8"/></svg><p>'+(ha?'🎵 오디오 재생 중':'타임라인에 미디어를 추가하세요')+'</p></div>';
425
- }}
426
- handleAudio(ac);
427
- }}
428
- function handleAudio(audioClips){{
429
- if(!S.audioElements)S.audioElements={{}};
430
- var activeIds={{}};
431
- audioClips.forEach(function(c){{
432
- activeIds[c.id]=true;
433
- var at=S.currentTime-c.start+c.ts;
434
- var au=S.audioElements[c.id];
435
- if(!au){{
436
- au=document.createElement('audio');
437
- au.src=c.url;
438
- au.preload='auto';
439
- S.audioElements[c.id]=au;
440
- }}
441
- if(Math.abs(au.currentTime-at)>0.3)au.currentTime=at;
442
- au.volume=S.isMuted?0:c.vol;
443
- au.muted=S.isMuted;
444
- if(S.isPlaying&&au.paused)au.play().catch(function(){{}});
445
- else if(!S.isPlaying&&!au.paused)au.pause();
446
  }});
447
- Object.keys(S.audioElements).forEach(function(id){{
448
- if(!activeIds[id]){{
449
- var au=S.audioElements[id];
450
- if(au&&!au.paused)au.pause();
 
 
451
  }}
452
  }});
 
 
 
 
 
453
  }}
454
- function editorSkipStart(){{S.currentTime=0;upPH();upPrev()}}
455
- function editorSkipEnd(){{S.currentTime=S.totalDuration;upPH();upPrev()}}
456
- function editorSkipBack(){{S.currentTime=Math.max(0,S.currentTime-5);upPH();upPrev()}}
457
- function editorSkipForward(){{S.currentTime=Math.min(S.totalDuration,S.currentTime+5);upPH();upPrev()}}
458
- function editorToggleMute(){{
459
- S.isMuted=!S.isMuted;var ic=document.getElementById('volumeIcon');
460
- if(S.isMuted)ic.innerHTML='<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/>';
461
- else ic.innerHTML='<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/>';
462
- var v=document.querySelector('#previewContainer video');if(v)v.muted=S.isMuted;
463
- if(S.audioElements)Object.keys(S.audioElements).forEach(function(id){{var au=S.audioElements[id];if(au)au.muted=S.isMuted}});
464
- }}
465
- function editorSetZoom(v){{S.zoom=parseFloat(v);renderTL();upPH()}}
466
- function editorTimelineClick(e){{
467
- if(e.target.closest('.timeline-clip'))return;
468
- var ct=document.getElementById('timelineContainer'),rect=ct.getBoundingClientRect();
469
- var x=e.clientX-rect.left-70+ct.scrollLeft;
470
- S.currentTime=Math.max(0,Math.min(S.totalDuration,x/(S.pps*S.zoom)));
471
- upPH();upPrev();
472
- }}
473
- function showCtx(x,y){{var m=document.getElementById('contextMenu');m.style.display='block';m.style.left=x+'px';m.style.top=y+'px'}}
474
- function hideCtx(){{document.getElementById('contextMenu').style.display='none'}}
475
- document.addEventListener('click',function(e){{if(!e.target.closest('.context-menu'))hideCtx()}});
476
- function editorExport(){{
477
- if(S.timelineClips.length===0){{alert('타임라인에 클립을 추가해주세요.');return}}
478
  document.getElementById('exportModal').style.display='flex';
479
- document.getElementById('exportProgress').style.width='0%';
480
- document.getElementById('exportStatus').textContent='렌더링 준비 중...';
481
- document.getElementById('cancelExportBtn').textContent='취소';
482
- S.exportCancelled=false;
483
- prepareExport();
484
  }}
485
- function prepareExport(){{
 
486
  var canvas=document.createElement('canvas');
487
  canvas.width=1280;canvas.height=720;
488
  var ctx=canvas.getContext('2d');
489
- ctx.fillStyle='#000';ctx.fillRect(0,0,1280,720);
490
- var mediaElements={{}};
491
- var loadCount=0;
492
- var totalLoad=S.mediaLibrary.length;
493
- if(totalLoad===0){{startRecording(canvas,ctx,{{}});return}}
494
- S.mediaLibrary.forEach(function(m){{
495
- if(m.type==='video'){{
496
- var v=document.createElement('video');
497
- v.src=m.url;v.muted=true;v.playsInline=true;v.preload='auto';
498
- v.onloadeddata=function(){{
499
- loadCount++;
500
- document.getElementById('exportStatus').textContent='미디어 로딩 중... ('+loadCount+'/'+totalLoad+')';
501
- if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements);
502
- }};
503
- v.onerror=function(){{loadCount++;if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements)}};
504
- mediaElements[m.id]=v;
505
- }}else if(m.type==='image'){{
506
- var img=new Image();
507
- img.onload=function(){{
508
- loadCount++;
509
- document.getElementById('exportStatus').textContent='미디어 로딩 중... ('+loadCount+'/'+totalLoad+')';
510
- if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements);
511
- }};
512
- img.onerror=function(){{loadCount++;if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements)}};
513
- img.src=m.url;
514
- mediaElements[m.id]=img;
515
- }}else if(m.type==='audio'){{
516
- var a=document.createElement('audio');
517
- a.src=m.url;a.preload='auto';
518
- a.onloadeddata=function(){{loadCount++;if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements)}};
519
- a.onerror=function(){{loadCount++;if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements)}};
520
- mediaElements[m.id]=a;
521
- }}else{{
522
- loadCount++;
523
- if(loadCount>=totalLoad)startRecording(canvas,ctx,mediaElements);
524
- }}
525
- }});
526
- }}
527
- function startRecording(canvas,ctx,mediaElements){{
528
- if(S.exportCancelled)return;
529
- document.getElementById('exportStatus').textContent='녹화 시작...';
530
  var stream=canvas.captureStream(30);
531
- var options={{mimeType:'video/webm;codecs=vp8'}};
532
- if(!MediaRecorder.isTypeSupported(options.mimeType)){{
533
- options={{mimeType:'video/webm'}};
534
- if(!MediaRecorder.isTypeSupported(options.mimeType)){{
535
- options={{}};
536
- }}
537
- }}
538
- var recorder=new MediaRecorder(stream,options);
539
  var chunks=[];
540
- recorder.ondataavailable=function(e){{
541
- if(e.data&&e.data.size>0)chunks.push(e.data);
542
- }};
543
- recorder.onstop=function(){{
544
- if(S.exportCancelled||chunks.length===0){{
545
- document.getElementById('exportStatus').textContent='내보내기 취소됨';
546
- return;
547
- }}
548
  var blob=new Blob(chunks,{{type:'video/webm'}});
549
- if(blob.size<1000){{
550
- document.getElementById('exportStatus').textContent='❌ 렌더링 실패. 다시 시도해주세요.';
551
- return;
552
- }}
553
- var url=URL.createObjectURL(blob);
554
  var a=document.createElement('a');
555
- a.href=url;
556
  a.download='video_'+Date.now()+'.webm';
557
  a.click();
558
- URL.revokeObjectURL(url);
559
- document.getElementById('exportStatus').textContent='✅ 다운로드 완료! ('+Math.round(blob.size/1024)+'KB)';
560
- document.getElementById('cancelExportBtn').textContent='닫기';
561
  }};
562
- recorder.start(100);
563
- var duration=S.totalDuration;
564
- var startTime=performance.now();
565
- var fps=30;
566
- var frameInterval=1000/fps;
567
- var lastFrameTime=0;
568
- function renderLoop(timestamp){{
569
- if(S.exportCancelled){{recorder.stop();return}}
570
- var elapsed=(performance.now()-startTime)/1000;
571
- if(elapsed>=duration){{
572
- setTimeout(function(){{recorder.stop()}},200);
573
- return;
574
- }}
575
- if(timestamp-lastFrameTime>=frameInterval){{
576
- lastFrameTime=timestamp;
577
- var progress=Math.min(100,Math.round((elapsed/duration)*100));
578
- document.getElementById('exportProgress').style.width=progress+'%';
579
- document.getElementById('exportStatus').textContent='렌더링 중... '+progress+'%';
580
- ctx.fillStyle='#000';ctx.fillRect(0,0,1280,720);
581
- var curClips=S.timelineClips.filter(function(c){{
582
- var cs=c.start;
583
- var ce=c.start+(c.te-c.ts);
584
- return elapsed>=cs-0.001&&elapsed<ce+0.001;
585
- }});
586
- var vc=curClips.find(function(c){{return c.type==='video'||c.type==='image'}});
587
  if(vc){{
588
- var media=S.mediaLibrary.find(function(m){{return m.id===vc.mid}});
589
- if(media){{
590
- var el=mediaElements[media.id];
591
  if(el){{
592
- if(vc.type==='video'){{
593
- var clipTime=elapsed-vc.start+vc.ts;
594
- if(el.paused){{el.currentTime=clipTime;el.play().catch(function(){{}})}}
595
- if(Math.abs(el.currentTime-clipTime)>0.5)el.currentTime=clipTime;
596
- }}
597
  try{{
598
  var sw=el.videoWidth||el.naturalWidth||el.width||1280;
599
  var sh=el.videoHeight||el.naturalHeight||el.height||720;
600
  var scale=Math.min(1280/sw,720/sh);
601
  var dw=sw*scale,dh=sh*scale;
602
- var dx=(1280-dw)/2,dy=(720-dh)/2;
603
- ctx.drawImage(el,dx,dy,dw,dh);
604
  }}catch(e){{}}
605
  }}
606
  }}
 
607
  }}
 
608
  }}
609
- requestAnimationFrame(renderLoop);
610
- }}
611
- requestAnimationFrame(renderLoop);
612
- }}
613
- function editorCancelExport(){{S.exportCancelled=true;document.getElementById('exportModal').style.display='none';document.getElementById('cancelExportBtn').textContent='취소'}}
614
  document.addEventListener('keydown',function(e){{
615
  if(e.target.tagName==='INPUT')return;
616
- if(e.code==='Space'){{e.preventDefault();editorTogglePlay()}}
617
- else if(e.code==='Delete'||e.code==='Backspace'){{e.preventDefault();editorDelete()}}
618
- else if(e.code==='KeyD'&&(e.ctrlKey||e.metaKey)){{e.preventDefault();editorDuplicate()}}
619
- else if(e.code==='KeyZ'&&(e.ctrlKey||e.metaKey)){{e.preventDefault();editorUndo()}}
620
- else if(e.code==='ArrowLeft'){{e.preventDefault();S.currentTime=Math.max(0,S.currentTime-(e.shiftKey?1:0.1));upPH();upPrev()}}
621
- else if(e.code==='ArrowRight'){{e.preventDefault();S.currentTime=Math.min(S.totalDuration,S.currentTime+(e.shiftKey?1:0.1));upPH();upPrev()}}
622
  }});
623
- renderTL();upStat('준비됨');
624
- var initMedia={media_data};
625
- if(initMedia&&initMedia.length>0)initMedia.forEach(function(m){{addMedia(m.name,m.type,m.dataUrl)}});
626
- console.log('Editor ready');
 
 
627
  </script>
628
  </body>
629
  </html>'''
630
 
631
-
632
- def process_file(file):
633
- if file is None:
634
  return []
635
  results = []
636
- files = file if isinstance(file, list) else [file]
637
- for f in files:
638
- if f is None:
639
  continue
640
- file_path = f.name if hasattr(f, 'name') else f
641
- file_name = os.path.basename(file_path)
642
- ext = file_name.lower().split('.')[-1]
643
  if ext in ['mp4', 'webm', 'mov', 'avi', 'mkv']:
644
- file_type, mime = 'video', f'video/{ext}'
645
  elif ext in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
646
- file_type, mime = 'image', f'image/{ext}'
647
  elif ext in ['mp3', 'wav', 'ogg', 'm4a', 'aac']:
648
- file_type, mime = 'audio', f'audio/{ext}'
649
  else:
650
  continue
651
- with open(file_path, 'rb') as fp:
652
- data = base64.b64encode(fp.read()).decode('utf-8')
653
- results.append({'name': file_name, 'type': file_type, 'dataUrl': f'data:{mime};base64,{data}'})
654
  return results
655
 
656
-
657
- def create_editor_iframe(media_data):
658
- """srcdoc 방식으로 iframe 생성"""
659
- media_json = json.dumps(media_data, ensure_ascii=False)
660
- html_content = get_editor_html(media_json)
661
- # srcdoc를 작은따옴표로 감싸므로, 내부의 작은따옴표만 이스케이프
662
- escaped = html_content.replace("'", "&#39;")
663
- return f"<iframe srcdoc='{escaped}' style='width:100%;height:800px;border:none;border-radius:12px;'></iframe>"
664
-
665
 
666
  with gr.Blocks() as demo:
667
- gr.Markdown("## 🎬 Simple Video Editor")
668
- gr.Markdown("파일 업로드하면 자동으로 타임라인에 추가됩니다.")
669
-
670
- file_input = gr.File(
671
- label="📁 파일 업로드 (영상/이미지/오디오)",
672
- file_count="multiple",
673
- file_types=["video", "image", "audio"]
674
- )
675
-
676
- editor_html = gr.HTML(value=create_editor_iframe([]))
677
-
678
- def on_file_upload(files):
679
- if not files:
680
- return create_editor_iframe([])
681
- return create_editor_iframe(process_file(files))
682
-
683
- file_input.change(fn=on_file_upload, inputs=[file_input], outputs=[editor_html])
684
 
685
  if __name__ == "__main__":
686
  demo.launch()
 
1
  """
2
+ Simple Video Editor - Canvas 기반 렌더링
3
+ 프레임 문제 완전 해결
4
  """
5
 
6
  import gradio as gr
 
9
  import json
10
 
11
  def get_editor_html(media_data="[]"):
 
12
  return f'''<!DOCTYPE html>
13
  <html lang="ko">
14
  <head>
15
  <meta charset="UTF-8">
 
16
  <style>
17
  *{{margin:0;padding:0;box-sizing:border-box}}
18
+ body{{font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#f5f5f7;font-size:13px}}
19
+ .editor{{display:flex;flex-direction:column;height:100vh}}
20
+ .toolbar{{height:44px;background:#fff;border-bottom:1px solid #ddd;display:flex;align-items:center;justify-content:space-between;padding:0 12px}}
21
+ .toolbar-title{{font-size:15px;font-weight:600}}
22
+ .btn{{padding:5px 10px;border:none;border-radius:5px;cursor:pointer;font-size:11px;font-weight:500}}
23
+ .btn-secondary{{background:#f0f0f0;color:#333}}
24
+ .btn-secondary:hover{{background:#e0e0e0}}
 
 
 
25
  .btn-success{{background:#10b981;color:#fff}}
 
26
  .btn-danger{{background:#ef4444;color:#fff}}
27
+ .main{{display:flex;flex:1;overflow:hidden}}
28
+ .library{{width:160px;background:#fff;border-right:1px solid #ddd;display:flex;flex-direction:column}}
29
+ .lib-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
30
+ .lib-content{{flex:1;overflow-y:auto;padding:6px}}
31
+ .lib-hint{{text-align:center;padding:15px;color:#999;font-size:10px}}
32
+ .media-grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:4px}}
33
+ .media-item{{aspect-ratio:16/9;background:#f0f0f0;border-radius:4px;overflow:hidden;cursor:grab;position:relative;border:1px solid #e0e0e0}}
34
+ .media-item:hover{{border-color:#6366f1}}
35
+ .media-item img{{width:100%;height:100%;object-fit:cover}}
36
+ .media-item-icon{{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:18px}}
37
+ .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}}
38
+ .preview-area{{flex:1;display:flex;flex-direction:column;background:#1a1a1a;margin:6px;border-radius:8px;overflow:hidden}}
39
+ .preview-box{{flex:1;display:flex;align-items:center;justify-content:center;background:#000}}
40
+ #previewCanvas{{max-width:100%;max-height:100%;background:#000}}
41
+ .controls{{height:45px;background:#222;display:flex;align-items:center;justify-content:center;gap:6px}}
42
+ .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}}
43
+ .ctrl-btn:hover{{background:rgba(255,255,255,0.2)}}
44
+ .ctrl-btn.play{{width:36px;height:36px;background:#6366f1}}
45
+ .time-display{{font-family:monospace;font-size:10px;color:#aaa;min-width:90px;text-align:center}}
46
+ .props{{width:140px;background:#fff;border-left:1px solid #ddd}}
47
+ .props-header{{padding:8px;border-bottom:1px solid #eee;font-size:10px;font-weight:600;color:#666}}
48
+ .props-content{{padding:8px}}
49
+ .no-sel{{color:#999;text-align:center;padding:15px;font-size:10px}}
50
+ .prop-group{{margin-bottom:10px}}
51
+ .prop-label{{font-size:9px;color:#666;margin-bottom:2px}}
52
+ .prop-input{{width:100%;padding:4px;border:1px solid #ddd;border-radius:3px;font-size:10px}}
53
+ .timeline{{height:140px;background:#fff;border-top:1px solid #ddd;display:flex;flex-direction:column}}
54
+ .tl-toolbar{{height:28px;background:#fafafa;border-bottom:1px solid #eee;display:flex;align-items:center;padding:0 6px;gap:4px}}
55
+ .tl-toolbar .btn{{padding:2px 6px;font-size:9px}}
56
+ .tl-zoom{{display:flex;align-items:center;gap:3px;margin-left:auto;font-size:9px;color:#666}}
57
+ .tl-zoom input{{width:50px}}
58
+ .tl-container{{flex:1;overflow-x:auto;position:relative}}
59
+ .tl-ruler{{height:18px;background:#fff;border-bottom:1px solid #eee}}
60
+ .tl-tracks{{position:relative}}
61
+ .tl-track{{height:45px;border-bottom:1px solid #eee;display:flex}}
62
+ .tl-track:nth-child(2){{background:#fffbeb}}
63
+ .track-label{{width:50px;padding:0 4px;font-size:8px;color:#666;background:#fafafa;display:flex;align-items:center;border-right:1px solid #eee}}
64
+ .track-content{{flex:1;position:relative;min-width:600px}}
65
+ .clip{{position:absolute;height:36px;top:4px;border-radius:4px;cursor:grab;display:flex;align-items:center;overflow:hidden}}
66
+ .clip:hover{{box-shadow:0 0 0 2px #6366f1}}
67
+ .clip.selected{{box-shadow:0 0 0 2px #6366f1}}
68
+ .clip.video{{background:linear-gradient(135deg,#818cf8,#6366f1)}}
69
+ .clip.image{{background:linear-gradient(135deg,#34d399,#10b981)}}
70
+ .clip.audio{{background:linear-gradient(135deg,#fbbf24,#f59e0b)}}
71
+ .clip-thumb{{width:36px;height:100%;object-fit:cover}}
72
+ .clip-info{{padding:0 4px;flex:1;overflow:hidden}}
73
+ .clip-name{{font-size:8px;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
74
+ .clip-dur{{font-size:7px;color:rgba(255,255,255,0.7)}}
75
+ .clip-handle{{position:absolute;top:0;bottom:0;width:8px;background:rgba(255,255,255,0.5);cursor:ew-resize;opacity:0}}
76
+ .clip:hover .clip-handle{{opacity:1}}
77
+ .clip-handle-l{{left:0;border-radius:4px 0 0 4px}}
78
+ .clip-handle-r{{right:0;border-radius:0 4px 4px 0}}
79
+ .playhead{{position:absolute;top:0;bottom:0;width:2px;background:#ef4444;z-index:10;pointer-events:none}}
80
+ .playhead::before{{content:"";position:absolute;top:0;left:-4px;border-left:5px solid transparent;border-right:5px solid transparent;border-top:7px solid #ef4444}}
81
+ .drop-zone{{background:rgba(99,102,241,0.1)!important;outline:2px dashed #6366f1!important}}
82
+ .status{{height:20px;background:#f5f5f5;border-top:1px solid #ddd;display:flex;align-items:center;padding:0 8px;font-size:9px;color:#666}}
83
+ .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}}
84
+ .ctx-item{{padding:5px 10px;cursor:pointer;font-size:10px}}
85
+ .ctx-item:hover{{background:#f5f5f5}}
86
+ .ctx-item.danger{{color:#ef4444}}
87
+ .modal{{position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:1000}}
88
+ .modal-box{{background:#fff;border-radius:8px;padding:16px;min-width:240px;text-align:center}}
89
+ .modal-box h3{{margin-bottom:8px;font-size:13px}}
90
+ .progress{{height:5px;background:#eee;border-radius:3px;overflow:hidden;margin:10px 0}}
91
+ .progress-bar{{height:100%;background:#6366f1;transition:width 0.2s}}
92
+ .hidden-media{{position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0;pointer-events:none}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  </style>
94
  </head>
95
  <body>
96
+ <div class="editor">
97
  <div class="toolbar">
98
+ <div class="toolbar-title">🎬 Video Editor</div>
99
+ <div style="display:flex;gap:4px">
100
+ <button class="btn btn-secondary" onclick="undo()">↩ 실행취소</button>
101
+ <button class="btn btn-success" onclick="exportVideo()">📥 내보내기</button>
102
  </div>
 
 
 
103
  </div>
104
+ <div class="main">
105
+ <div class="library">
106
+ <div class="lib-header">📁 미디어</div>
107
+ <div class="lib-content">
108
+ <div class="lib-hint" id="hint">파일을 업로드하세요</div>
 
109
  <div class="media-grid" id="mediaGrid"></div>
110
  </div>
111
  </div>
112
  <div class="preview-area">
113
+ <div class="preview-box">
114
+ <canvas id="previewCanvas" width="640" height="360"></canvas>
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  </div>
116
+ <div class="controls">
117
+ <button class="ctrl-btn" onclick="seek(0)">⏮</button>
118
+ <button class="ctrl-btn" onclick="seek(S.time-5)"></button>
119
+ <button class="ctrl-btn play" onclick="togglePlay()" id="playBtn">▶</button>
120
+ <button class="ctrl-btn" onclick="seek(S.time+5)">⏩</button>
121
+ <button class="ctrl-btn" onclick="seek(S.dur)">⏭</button>
122
+ <div class="time-display"><span id="curT">00:00.00</span> / <span id="totT">00:00.00</span></div>
123
+ <button class="ctrl-btn" onclick="toggleMute()" id="muteBtn">🔊</button>
124
  </div>
125
  </div>
126
+ <div class="props">
127
+ <div class="props-header">⚙️ 속성</div>
128
+ <div class="props-content" id="propsBox"><div class="no-sel">클립 선택</div></div>
 
 
 
 
 
 
129
  </div>
130
  </div>
131
+ <div class="timeline">
132
+ <div class="tl-toolbar">
133
+ <button class="btn btn-secondary" onclick="splitClip()">✂ 자르기</button>
134
+ <button class="btn btn-secondary" onclick="dupeClip()">📋 복제</button>
135
+ <button class="btn btn-danger" onclick="delClip()">🗑 삭제</button>
136
+ <div class="tl-zoom">🔍<input type="range" min="0.5" max="3" step="0.1" value="1" oninput="setZoom(this.value)"></div>
137
  </div>
138
+ <div class="tl-container" id="tlBox" onclick="tlClick(event)">
139
+ <div class="tl-ruler" id="ruler"></div>
140
+ <div class="tl-tracks">
141
+ <div class="tl-track"><div class="track-label">🎬 영상</div><div class="track-content" id="t0"></div></div>
142
+ <div class="tl-track"><div class="track-label">🎵 오디오</div><div class="track-content" id="t1"></div></div>
143
  </div>
144
+ <div class="playhead" id="playhead" style="left:50px"></div>
145
  </div>
 
146
  </div>
147
+ <div class="status" id="status">준비됨</div>
148
  </div>
149
+ <div class="ctx-menu" id="ctx">
150
+ <div class="ctx-item" onclick="splitClip()">✂ 자르기</div>
151
+ <div class="ctx-item" onclick="dupeClip()">📋 복제</div>
152
+ <div class="ctx-item danger" onclick="delClip()">🗑 삭제</div>
153
  </div>
154
+ <div class="modal" id="exportModal" style="display:none">
155
+ <div class="modal-box">
 
 
 
 
 
 
156
  <h3>🎬 영상 내보내기</h3>
157
+ <p id="exportMsg">준비중...</p>
158
+ <div class="progress"><div class="progress-bar" id="exportBar"></div></div>
159
+ <button class="btn btn-secondary" onclick="cancelExport()">취소</button>
160
  </div>
161
  </div>
162
+ <div id="hiddenMedia" class="hidden-media"></div>
163
  <script>
164
+ var S={{
165
+ media:[],
166
+ clips:[],
167
+ sel:null,
168
+ playing:false,
169
+ muted:false,
170
+ time:0,
171
+ dur:0,
172
+ zoom:1,
173
+ pps:80,
174
+ history:[],
175
+ animId:null,
176
+ cancelled:false,
177
+ els:{{}},
178
+ canvas:null,
179
+ ctx:null,
180
+ lastClipId:null
181
+ }};
182
+
183
+ function init(){{
184
+ S.canvas=document.getElementById('previewCanvas');
185
+ S.ctx=S.canvas.getContext('2d');
186
+ drawPlaceholder();
187
+ }}
188
+
189
+ function id(){{return Math.random().toString(36).substr(2,9)}}
190
+ 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')}}
191
+ function r(n){{return Math.round(n*1000)/1000}}
192
+ function stat(m){{document.getElementById('status').textContent=m}}
193
+ function save(){{S.history.push(JSON.stringify(S.clips));if(S.history.length>30)S.history.shift()}}
194
+
195
+ function drawPlaceholder(){{
196
+ S.ctx.fillStyle='#000';
197
+ S.ctx.fillRect(0,0,640,360);
198
+ S.ctx.fillStyle='#444';
199
+ S.ctx.font='14px sans-serif';
200
+ S.ctx.textAlign='center';
201
+ S.ctx.fillText('타임라인에 미디어를 추가하세요',320,180);
202
+ }}
203
+
204
  function addMedia(name,type,url){{
205
+ var m={{id:id(),name:name,type:type,url:url,dur:type==='image'?5:0,thumb:type==='image'?url:null}};
206
+ S.media.push(m);
207
+ var container=document.getElementById('hiddenMedia');
208
+ if(type==='video'){{
209
+ var v=document.createElement('video');
210
+ v.src=url;
211
+ v.muted=true;
212
+ v.playsInline=true;
213
+ v.preload='auto';
214
+ v.crossOrigin='anonymous';
215
+ container.appendChild(v);
216
+ S.els[m.id]=v;
217
+ v.onloadedmetadata=function(){{
218
+ m.dur=r(v.duration);
219
+ renderLib();
220
+ v.currentTime=0.5;
221
+ }};
222
+ v.onseeked=function(){{
223
+ if(!m.thumb){{
224
+ try{{
225
+ var c=document.createElement('canvas');
226
+ c.width=160;c.height=90;
227
+ c.getContext('2d').drawImage(v,0,0,160,90);
228
+ m.thumb=c.toDataURL();
229
+ renderLib();
230
+ }}catch(e){{}}
231
  }}
232
+ }};
233
+ }}else if(type==='audio'){{
234
+ var a=document.createElement('audio');
235
+ a.src=url;
236
+ a.preload='auto';
237
+ container.appendChild(a);
238
+ S.els[m.id]=a;
239
+ a.onloadedmetadata=function(){{m.dur=r(a.duration);renderLib()}};
240
+ }}else if(type==='image'){{
241
+ var img=new Image();
242
+ img.src=url;
243
+ img.crossOrigin='anonymous';
244
+ S.els[m.id]=img;
245
+ }}
246
+ renderLib();
247
+ stat('미디어 추가: '+name);
248
+ setTimeout(function(){{addClip(m)}},400);
249
  }}
250
+
251
  function renderLib(){{
252
+ var g=document.getElementById('mediaGrid');
253
+ var h=document.getElementById('hint');
254
+ h.style.display=S.media.length?'none':'block';
255
  g.innerHTML='';
256
+ S.media.forEach(function(m){{
257
+ var d=document.createElement('div');
258
+ d.className='media-item';
259
+ d.draggable=true;
260
+ d.ondblclick=function(){{addClip(m)}};
261
+ d.ondragstart=function(e){{e.dataTransfer.setData('mid',m.id)}};
262
+ var th=m.thumb?'<img src="'+m.thumb+'">':'<div class="media-item-icon">'+(m.type==='video'?'🎬':m.type==='audio'?'🎵':'🖼')+'</div>';
263
+ d.innerHTML=th+(m.dur?'<div class="media-item-dur">'+fmt(m.dur)+'</div>':'');
264
  g.appendChild(d);
265
  }});
266
  }}
267
+
268
+ function trackEnd(tr){{
269
+ var end=0;
270
+ for(var i=0;i<S.clips.length;i++){{
271
+ var c=S.clips[i];
272
+ if(c.track===tr){{
273
+ var e=r(c.start+(c.te-c.ts));
274
+ if(e>end)end=e;
275
+ }}
276
+ }}
277
+ return end;
278
+ }}
279
+
280
+ function addClip(m,at){{
281
  save();
282
  var tr=m.type==='audio'?1:0;
283
+ var st=at!==undefined?r(at):trackEnd(tr);
284
+ S.clips.push({{
285
+ id:id(),
286
+ mid:m.id,
287
+ name:m.name,
288
+ type:m.type,
289
+ track:tr,
290
+ start:st,
291
+ dur:m.dur,
292
+ ts:0,
293
+ te:m.dur,
294
+ vol:1
295
+ }});
296
+ renderTL();
297
+ updateDur();
298
+ stat('클립 추가: '+m.name);
299
+ drawFrame();
300
  }}
301
+
302
  function renderTL(){{
303
+ ['t0','t1'].forEach(function(tid){{document.getElementById(tid).innerHTML=''}});
304
+ S.clips.forEach(function(c){{
305
+ var tr=document.getElementById('t'+c.track);
306
+ var el=document.createElement('div');
307
+ el.className='clip '+c.type+(S.sel===c.id?' selected':'');
308
+ var len=r(c.te-c.ts);
309
+ el.style.left=r(c.start*S.pps*S.zoom)+'px';
310
+ el.style.width=Math.max(25,r(len*S.pps*S.zoom))+'px';
311
+ el.draggable=true;
312
+ el.onclick=function(e){{e.stopPropagation();selClip(c.id)}};
313
+ el.oncontextmenu=function(e){{e.preventDefault();selClip(c.id);showCtx(e.clientX,e.clientY)}};
314
+ el.ondragstart=function(e){{e.dataTransfer.setData('cid',c.id);e.dataTransfer.setData('ox',e.offsetX)}};
315
+ var m=S.media.find(function(x){{return x.id===c.mid}});
316
+ var th=m&&m.thumb?'<img class="clip-thumb" src="'+m.thumb+'">':'';
317
+ el.innerHTML=th+'<div class="clip-info"><div class="clip-name">'+c.name+'</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>';
318
+ el.querySelector('.clip-handle-l').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'l',e)}};
319
+ el.querySelector('.clip-handle-r').onmousedown=function(e){{e.stopPropagation();startTrim(c.id,'r',e)}};
320
+ tr.appendChild(el);
321
  }});
322
+ renderRuler();
323
+ setupDrop();
324
  }}
325
+
326
+ function renderRuler(){{
327
+ var ru=document.getElementById('ruler');
328
+ var w=Math.max(r(S.dur*S.pps*S.zoom)+150,600);
329
+ ru.style.width=w+'px';
330
+ var h='<svg width="100%" height="18" style="position:absolute;left:50px">';
331
+ var step=S.zoom<0.7?5:S.zoom<1.5?2:1;
332
+ for(var i=0;i<=S.dur+10;i+=step){{
333
+ var x=r(i*S.pps*S.zoom);
334
+ h+='<line x1="'+x+'" y1="13" x2="'+x+'" y2="18" stroke="#ccc"/>';
335
+ h+='<text x="'+x+'" y="10" fill="#999" font-size="8" text-anchor="middle">'+fmt(i)+'</text>';
336
+ }}
337
+ ru.innerHTML=h+'</svg>';
338
+ }}
339
+
340
+ function setupDrop(){{
341
+ ['t0','t1'].forEach(function(tid,idx){{
342
+ var tr=document.getElementById(tid);
343
+ tr.ondragover=function(e){{e.preventDefault();tr.classList.add('drop-zone')}};
344
+ tr.ondragleave=function(){{tr.classList.remove('drop-zone')}};
345
+ tr.ondrop=function(e){{
346
+ e.preventDefault();
347
+ tr.classList.remove('drop-zone');
348
+ var rect=tr.getBoundingClientRect();
349
+ var t=r(Math.max(0,(e.clientX-rect.left)/(S.pps*S.zoom)));
350
+ var mid=e.dataTransfer.getData('mid');
351
+ var cid=e.dataTransfer.getData('cid');
352
+ var ox=parseFloat(e.dataTransfer.getData('ox')||0);
353
+ if(mid){{
354
+ var m=S.media.find(function(x){{return x.id===mid}});
355
+ if(m)addClip(m,t);
356
+ }}else if(cid){{
357
+ save();
358
+ var c=S.clips.find(function(x){{return x.id===cid}});
359
+ if(c){{
360
+ c.start=r(Math.max(0,t-ox/(S.pps*S.zoom)));
361
+ c.track=c.type==='audio'?1:idx;
362
+ renderTL();
363
+ updateDur();
364
+ drawFrame();
365
+ }}
366
+ }}
367
+ }};
368
+ }});
369
+ }}
370
+
371
+ var trimData=null;
372
+ function startTrim(cid,side,e){{
373
  e.preventDefault();
374
+ var c=S.clips.find(function(x){{return x.id===cid}});
375
+ if(!c)return;
376
  save();
377
+ trimData={{cid:cid,side:side,sx:e.clientX,ots:c.ts,ote:c.te,ost:c.start}};
378
  document.addEventListener('mousemove',doTrim);
379
  document.addEventListener('mouseup',endTrim);
380
  }}
381
  function doTrim(e){{
382
+ if(!trimData)return;
383
+ var c=S.clips.find(function(x){{return x.id===trimData.cid}});
384
+ if(!c)return;
385
+ var dx=e.clientX-trimData.sx;
386
+ var dt=r(dx/(S.pps*S.zoom));
387
+ if(trimData.side==='l'){{
388
+ var newTs=Math.max(0,Math.min(c.te-0.1,trimData.ots+dt));
389
+ c.ts=r(newTs);
390
+ c.start=r(trimData.ost+(newTs-trimData.ots));
 
 
391
  }}else{{
392
+ c.te=r(Math.max(c.ts+0.1,Math.min(c.dur,trimData.ote+dt)));
 
393
  }}
394
+ renderTL();
395
+ updateDur();
396
  }}
397
  function endTrim(){{
398
+ trimData=null;
399
  document.removeEventListener('mousemove',doTrim);
400
  document.removeEventListener('mouseup',endTrim);
401
  }}
402
+
403
+ function selClip(cid){{S.sel=cid;renderTL();renderProps()}}
404
+
405
+ function renderProps(){{
406
+ var box=document.getElementById('propsBox');
407
+ var c=S.clips.find(function(x){{return x.id===S.sel}});
408
+ if(!c){{box.innerHTML='<div class="no-sel">클립 선택</div>';return}}
409
+ var len=r(c.te-c.ts);
410
+ box.innerHTML='<div class="prop-group"><div class="prop-label">이름</div><input class="prop-input" value="'+c.name+'" onchange="setProp(\\'name\\',this.value)"></div>'+
411
+ '<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>'+
412
+ '<div class="prop-group"><div class="prop-label">길이: '+fmt(len)+'</div></div>'+
413
+ (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>':'');
414
  }}
415
+
416
+ function setProp(p,v){{
417
+ save();
418
+ var c=S.clips.find(function(x){{return x.id===S.sel}});
419
+ if(c){{c[p]=p==='start'?r(v):v;renderTL();updateDur();renderProps();drawFrame()}}
 
 
 
 
 
 
 
 
 
420
  }}
421
+
422
+ function splitClip(){{
423
+ if(!S.sel){{alert('클립을 선택하세요');return}}
424
+ var c=S.clips.find(function(x){{return x.id===S.sel}});
425
+ if(!c)return;
426
+ var cEnd=r(c.start+c.te-c.ts);
427
+ if(S.time<=c.start||S.time>=cEnd){{alert('플레헤드가 클립 안에 있어야 합니다');return}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  save();
429
+ var splitAt=r(S.time-c.start);
430
  var c2=JSON.parse(JSON.stringify(c));
431
+ c2.id=id();
432
+ c2.start=r(S.time);
433
+ c2.ts=r(c.ts+splitAt);
434
+ c.te=r(c.ts+splitAt);
435
+ S.clips.push(c2);
436
+ renderTL();updateDur();hideCtx();stat('클립 분할됨');
437
+ }}
438
+
439
+ function dupeClip(){{
440
+ if(!S.sel)return;
441
+ var c=S.clips.find(function(x){{return x.id===S.sel}});
442
+ if(!c)return;
443
  save();
444
+ var len=r(c.te-c.ts);
445
  var nc=JSON.parse(JSON.stringify(c));
446
+ nc.id=id();
447
+ nc.start=r(c.start+len);
448
+ S.clips.push(nc);
449
+ renderTL();updateDur();hideCtx();stat('클립 복제됨');
450
+ }}
451
+
452
+ function delClip(){{
453
+ if(!S.sel)return;
454
+ save();
455
+ S.clips=S.clips.filter(function(x){{return x.id!==S.sel}});
456
+ S.sel=null;
457
+ renderTL();renderProps();updateDur();hideCtx();stat('클립 삭제됨');
458
+ drawFrame();
459
+ }}
460
+
461
+ function undo(){{if(S.history.length){{S.clips=JSON.parse(S.history.pop());renderTL();updateDur();stat('실행취소');drawFrame()}}}}
462
+
463
+ function updateDur(){{
464
+ var mx=0;
465
+ for(var i=0;i<S.clips.length;i++){{
466
+ var c=S.clips[i];
467
+ var e=r(c.start+c.te-c.ts);
468
+ if(e>mx)mx=e;
469
+ }}
470
+ S.dur=mx;
471
+ document.getElementById('totT').textContent=fmt(mx);
472
+ }}
473
+
474
+ function togglePlay(){{
475
+ S.playing=!S.playing;
476
+ document.getElementById('playBtn').textContent=S.playing?'⏸':'▶';
477
+ if(S.playing)play();else stop();
478
+ }}
479
+
480
+ function play(){{
481
  var last=performance.now();
482
+ function loop(now){{
483
+ if(!S.playing)return;
484
+ var dt=(now-last)/1000;
485
+ last=now;
486
+ S.time=S.time+dt;
487
+ if(S.time>=S.dur){{
488
+ S.time=0;
489
+ if(S.dur===0){{S.playing=false;document.getElementById('playBtn').textContent='▶';return}}
490
+ }}
491
+ updateHead();
492
+ drawFrame();
493
+ S.animId=requestAnimationFrame(loop);
494
+ }}
495
+ S.animId=requestAnimationFrame(loop);
496
+ }}
497
+
498
+ function stop(){{
499
+ if(S.animId){{cancelAnimationFrame(S.animId);S.animId=null}}
500
+ Object.keys(S.els).forEach(function(k){{
501
+ var el=S.els[k];
502
+ if(el&&el.pause)el.pause();
503
  }});
504
+ }}
505
+
506
+ function seek(t){{
507
+ S.time=Math.max(0,Math.min(S.dur||0,t));
508
+ updateHead();
509
+ drawFrame();
510
+ }}
511
+
512
+ function updateHead(){{
513
+ document.getElementById('playhead').style.left=(50+S.time*S.pps*S.zoom)+'px';
514
+ document.getElementById('curT').textContent=fmt(S.time);
515
+ }}
516
+
517
+ function getClipAt(t,type){{
518
+ var sorted=S.clips.filter(function(c){{
519
+ if(type==='visual')return c.type==='video'||c.type==='image';
520
+ if(type==='audio')return c.type==='audio';
521
+ return true;
522
+ }}).sort(function(a,b){{return a.start-b.start}});
523
+ for(var i=0;i<sorted.length;i++){{
524
+ var c=sorted[i];
525
+ var cEnd=c.start+(c.te-c.ts);
526
+ if(t>=c.start&&t<cEnd)return c;
527
+ }}
528
+ return null;
529
+ }}
530
+
531
+ function drawFrame(){{
532
+ var t=S.time;
533
+ var vc=getClipAt(t,'visual');
534
+ S.ctx.fillStyle='#000';
535
+ S.ctx.fillRect(0,0,640,360);
536
  if(vc){{
537
+ var el=S.els[vc.mid];
538
+ if(el){{
539
+ if(vc.type==='video'){{
540
+ var clipT=t-vc.start+vc.ts;
541
+ if(Math.abs(el.currentTime-clipT)>0.05){{
542
+ el.currentTime=clipT;
543
+ }}
544
+ if(S.playing&&el.paused)el.play().catch(function(){{}});
545
+ if(!S.playing&&!el.paused)el.pause();
546
+ el.volume=S.muted?0:vc.vol;
547
+ }}
548
+ try{{
549
+ var sw=el.videoWidth||el.naturalWidth||el.width||640;
550
+ var sh=el.videoHeight||el.naturalHeight||el.height||360;
551
+ var scale=Math.min(640/sw,360/sh);
552
+ var dw=sw*scale,dh=sh*scale;
553
+ var dx=(640-dw)/2,dy=(360-dh)/2;
554
+ S.ctx.drawImage(el,dx,dy,dw,dh);
555
+ }}catch(e){{}}
556
+ }}
557
+ }}else if(S.clips.length===0){{
558
+ S.ctx.fillStyle='#444';
559
+ S.ctx.font='14px sans-serif';
560
+ S.ctx.textAlign='center';
561
+ S.ctx.fillText('타임라인에 미디어를 추가하세요',320,180);
562
+ }}
563
+ var audioClips=S.clips.filter(function(c){{
564
+ if(c.type!=='audio')return false;
565
+ var cEnd=c.start+(c.te-c.ts);
566
+ return t>=c.start&&t<cEnd;
567
+ }});
568
+ audioClips.forEach(function(ac){{
569
+ var el=S.els[ac.mid];
570
+ if(el){{
571
+ var clipT=t-ac.start+ac.ts;
572
+ if(Math.abs(el.currentTime-clipT)>0.1)el.currentTime=clipT;
573
+ el.volume=S.muted?0:ac.vol;
574
+ if(S.playing&&el.paused)el.play().catch(function(){{}});
575
+ if(!S.playing&&!el.paused)el.pause();
576
  }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
  }});
578
+ S.clips.forEach(function(c){{
579
+ if(c.type!=='audio')return;
580
+ var cEnd=c.start+(c.te-c.ts);
581
+ if(t<c.start||t>=cEnd){{
582
+ var el=S.els[c.mid];
583
+ if(el&&!el.paused)el.pause();
584
  }}
585
  }});
586
+ if(!vc&&!audioClips.length&&S.clips.length>0){{
587
+ S.ctx.fillStyle='#333';
588
+ S.ctx.font='12px sans-serif';
589
+ S.ctx.textAlign='center';
590
+ S.ctx.fillText('재생 위치에 미디어가 없습니다',320,180);
591
  }}
592
+ }}
593
+
594
+ function toggleMute(){{S.muted=!S.muted;document.getElementById('muteBtn').textContent=S.muted?'🔇':'🔊'}}
595
+ function setZoom(v){{S.zoom=parseFloat(v);renderTL();updateHead()}}
596
+ function tlClick(e){{
597
+ if(e.target.closest('.clip'))return;
598
+ var rect=document.getElementById('tlBox').getBoundingClientRect();
599
+ var scrollL=document.getElementById('tlBox').scrollLeft;
600
+ S.time=Math.max(0,Math.min(S.dur||0,(e.clientX-rect.left-50+scrollL)/(S.pps*S.zoom)));
601
+ updateHead();
602
+ drawFrame();
603
+ }}
604
+
605
+ function showCtx(x,y){{var m=document.getElementById('ctx');m.style.display='block';m.style.left=x+'px';m.style.top=y+'px'}}
606
+ function hideCtx(){{document.getElementById('ctx').style.display='none'}}
607
+ document.addEventListener('click',function(e){{if(!e.target.closest('.ctx-menu'))hideCtx()}});
608
+
609
+ function exportVideo(){{
610
+ if(!S.clips.length){{alert('클립을 추가하세요');return}}
611
+ S.cancelled=false;
 
 
 
 
612
  document.getElementById('exportModal').style.display='flex';
613
+ document.getElementById('exportBar').style.width='0%';
614
+ document.getElementById('exportMsg').textContent='준비중...';
615
+ setTimeout(doExport,100);
 
 
616
  }}
617
+
618
+ function doExport(){{
619
  var canvas=document.createElement('canvas');
620
  canvas.width=1280;canvas.height=720;
621
  var ctx=canvas.getContext('2d');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
  var stream=canvas.captureStream(30);
623
+ var opts={{mimeType:'video/webm;codecs=vp8'}};
624
+ if(!MediaRecorder.isTypeSupported(opts.mimeType))opts={{mimeType:'video/webm'}};
625
+ var rec=new MediaRecorder(stream,opts);
 
 
 
 
 
626
  var chunks=[];
627
+ rec.ondataavailable=function(e){{if(e.data.size>0)chunks.push(e.data)}};
628
+ rec.onstop=function(){{
629
+ if(S.cancelled)return;
 
 
 
 
 
630
  var blob=new Blob(chunks,{{type:'video/webm'}});
631
+ if(blob.size<1000){{document.getElementById('exportMsg').textContent='실패';return}}
 
 
 
 
632
  var a=document.createElement('a');
633
+ a.href=URL.createObjectURL(blob);
634
  a.download='video_'+Date.now()+'.webm';
635
  a.click();
636
+ document.getElementById('exportMsg').textContent='완료! ('+Math.round(blob.size/1024)+'KB)';
 
 
637
  }};
638
+ rec.start(100);
639
+ var dur=S.dur;
640
+ var start=performance.now();
641
+ function render(){{
642
+ if(S.cancelled){{rec.stop();return}}
643
+ var t=(performance.now()-start)/1000;
644
+ if(t>=dur){{setTimeout(function(){{rec.stop()}},200);return}}
645
+ document.getElementById('exportBar').style.width=(t/dur*100)+'%';
646
+ document.getElementById('exportMsg').textContent='렌더링 '+Math.round(t/dur*100)+'%';
647
+ ctx.fillStyle='#000';
648
+ ctx.fillRect(0,0,1280,720);
649
+ var vc=getClipAt(t,'visual');
 
 
 
 
 
 
 
 
 
 
 
 
 
650
  if(vc){{
651
+ var el=S.els[vc.mid];
 
 
652
  if(el){{
653
+ if(vc.type==='video')el.currentTime=t-vc.start+vc.ts;
 
 
 
 
654
  try{{
655
  var sw=el.videoWidth||el.naturalWidth||el.width||1280;
656
  var sh=el.videoHeight||el.naturalHeight||el.height||720;
657
  var scale=Math.min(1280/sw,720/sh);
658
  var dw=sw*scale,dh=sh*scale;
659
+ ctx.drawImage(el,(1280-dw)/2,(720-dh)/2,dw,dh);
 
660
  }}catch(e){{}}
661
  }}
662
  }}
663
+ requestAnimationFrame(render);
664
  }}
665
+ requestAnimationFrame(render);
666
  }}
667
+
668
+ function cancelExport(){{S.cancelled=true;document.getElementById('exportModal').style.display='none'}}
669
+
 
 
670
  document.addEventListener('keydown',function(e){{
671
  if(e.target.tagName==='INPUT')return;
672
+ if(e.code==='Space'){{e.preventDefault();togglePlay()}}
673
+ else if(e.code==='Delete'){{e.preventDefault();delClip()}}
674
+ else if(e.code==='ArrowLeft'){{seek(S.time-0.1)}}
675
+ else if(e.code==='ArrowRight'){{seek(S.time+0.1)}}
 
 
676
  }});
677
+
678
+ init();
679
+ renderTL();
680
+ stat('준비됨');
681
+ var initData={media_data};
682
+ if(initData&&initData.length)initData.forEach(function(m){{addMedia(m.name,m.type,m.dataUrl)}});
683
  </script>
684
  </body>
685
  </html>'''
686
 
687
+ def process_file(files):
688
+ if not files:
 
689
  return []
690
  results = []
691
+ file_list = files if isinstance(files, list) else [files]
692
+ for f in file_list:
693
+ if not f:
694
  continue
695
+ path = f.name if hasattr(f, 'name') else f
696
+ name = os.path.basename(path)
697
+ ext = name.lower().split('.')[-1]
698
  if ext in ['mp4', 'webm', 'mov', 'avi', 'mkv']:
699
+ t, m = 'video', f'video/{ext}'
700
  elif ext in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
701
+ t, m = 'image', f'image/{ext}'
702
  elif ext in ['mp3', 'wav', 'ogg', 'm4a', 'aac']:
703
+ t, m = 'audio', f'audio/{ext}'
704
  else:
705
  continue
706
+ with open(path, 'rb') as fp:
707
+ d = base64.b64encode(fp.read()).decode()
708
+ results.append({'name': name, 'type': t, 'dataUrl': f'data:{m};base64,{d}'})
709
  return results
710
 
711
+ def make_iframe(data):
712
+ j = json.dumps(data, ensure_ascii=False)
713
+ h = get_editor_html(j).replace("'", "&#39;")
714
+ return f"<iframe srcdoc='{h}' style='width:100%;height:750px;border:none;border-radius:10px'></iframe>"
 
 
 
 
 
715
 
716
  with gr.Blocks() as demo:
717
+ gr.Markdown("## 🎬 Video Editor")
718
+ f = gr.File(label="📁 파일 업로드", file_count="multiple", file_types=["video", "image", "audio"])
719
+ e = gr.HTML(value=make_iframe([]))
720
+ f.change(fn=lambda x: make_iframe(process_file(x)), inputs=[f], outputs=[e])
 
 
 
 
 
 
 
 
 
 
 
 
 
721
 
722
  if __name__ == "__main__":
723
  demo.launch()