PoopMan333 commited on
Commit
9fcd033
·
verified ·
1 Parent(s): 9f950a7

Upload Nugget Video Trimmer v1.6.html

Browse files

Nugget Video Trimmer v1.6

-Adding option for cropping video
-Fixed multiclip export
-Improved output video quality
-Added Gif export options

Files changed (1) hide show
  1. Nugget Video Trimmer v1.6.html +1643 -0
Nugget Video Trimmer v1.6.html ADDED
@@ -0,0 +1,1643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Nugget Video Trimmer</title>
7
+ <style>
8
+ :root{
9
+ --bg:#0e1116; --panel:#161b22; --panel2:#1c232d; --line:#2a323d;
10
+ --txt:#e6edf3; --dim:#8b98a5; --accent:#4cc2ff; --accent2:#2a9fd6;
11
+ --ok:#3fb950; --warn:#d29922; --danger:#f85149;
12
+ --r:10px;
13
+ }
14
+ *{box-sizing:border-box}
15
+ html,body{margin:0;height:100%}
16
+ body{
17
+ background:var(--bg); color:var(--txt);
18
+ font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
19
+ -webkit-font-smoothing:antialiased;
20
+ }
21
+ .wrap{max-width:1180px;margin:0 auto;padding:20px 20px 60px}
22
+ header{display:flex;align-items:center;gap:12px;margin-bottom:18px}
23
+ header h1{font-size:17px;margin:0;font-weight:600;letter-spacing:.2px}
24
+ header .sub{color:var(--dim);font-size:12.5px}
25
+ header .ver{color:var(--dim);font-size:12px;font-variant-numeric:tabular-nums;
26
+ border:1px solid var(--line);border-radius:99px;padding:3px 10px;background:var(--panel)}
27
+ .spacer{flex:1}
28
+
29
+ button{
30
+ font:inherit;color:var(--txt);background:var(--panel2);border:1px solid var(--line);
31
+ padding:7px 13px;border-radius:8px;cursor:pointer;transition:.12s;
32
+ }
33
+ button:hover:not(:disabled){background:#242d39;border-color:#3a4553}
34
+ button:disabled{opacity:.4;cursor:not-allowed}
35
+ button.primary{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
36
+ button.primary:hover:not(:disabled){background:#6bcfff}
37
+ button.ghost{background:transparent}
38
+ button.danger{color:#ffb4ae;border-color:#5a2b2b}
39
+ button.danger:hover:not(:disabled){background:#341c1c;border-color:#7a3a3a}
40
+ .icobtn{padding:7px 11px;font-variant-numeric:tabular-nums}
41
+ .small{padding:5px 10px;font-size:12.5px}
42
+
43
+ /* ---------- drop zone ---------- */
44
+ #drop{
45
+ border:2px dashed var(--line);border-radius:14px;padding:64px 24px;text-align:center;
46
+ background:var(--panel);cursor:pointer;transition:.15s;
47
+ }
48
+ #drop:hover,#drop.over{border-color:var(--accent);background:#12212b}
49
+ #drop h2{margin:0 0 6px;font-size:18px;font-weight:600}
50
+ #drop p{margin:0;color:var(--dim);font-size:13px}
51
+ #drop .big{font-size:38px;line-height:1;margin-bottom:14px;opacity:.65}
52
+
53
+ /* ---------- layout ---------- */
54
+ #app{display:none}
55
+ .grid{display:grid;grid-template-columns:1fr 316px;gap:18px;align-items:start}
56
+ @media(max-width:900px){.grid{grid-template-columns:1fr}}
57
+
58
+ .card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:14px}
59
+ .card h3{margin:0 0 12px;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim);font-weight:600}
60
+
61
+ .stage{background:#000;border-radius:var(--r);overflow:hidden;display:flex;align-items:center;justify-content:center;position:relative;border:1px solid var(--line)}
62
+ .stage video,.stage canvas{max-width:100%;max-height:56vh;display:block}
63
+ #exportCanvas{display:none}
64
+ .badge{position:absolute;top:10px;left:10px;z-index:3;background:rgba(0,0,0,.66);backdrop-filter:blur(4px);
65
+ padding:4px 9px;border-radius:6px;font-size:11.5px;color:#cfe;letter-spacing:.3px}
66
+
67
+ /* ---------- crop overlay ---------- */
68
+ #cropLayer{position:absolute;display:none;touch-action:none;z-index:2}
69
+ #cropBox{position:absolute;box-shadow:0 0 0 9999px rgba(4,7,11,.62);
70
+ border:1px solid rgba(255,255,255,.92);cursor:move;box-sizing:border-box}
71
+ #cropBox::after{content:"";position:absolute;inset:0;pointer-events:none;
72
+ background:
73
+ linear-gradient(to right,transparent calc(33.33% - 0.5px),rgba(255,255,255,.3) calc(33.33% - 0.5px),rgba(255,255,255,.3) calc(33.33% + 0.5px),transparent calc(33.33% + 0.5px),transparent calc(66.66% - 0.5px),rgba(255,255,255,.3) calc(66.66% - 0.5px),rgba(255,255,255,.3) calc(66.66% + 0.5px),transparent calc(66.66% + 0.5px)),
74
+ linear-gradient(to bottom,transparent calc(33.33% - 0.5px),rgba(255,255,255,.3) calc(33.33% - 0.5px),rgba(255,255,255,.3) calc(33.33% + 0.5px),transparent calc(33.33% + 0.5px),transparent calc(66.66% - 0.5px),rgba(255,255,255,.3) calc(66.66% - 0.5px),rgba(255,255,255,.3) calc(66.66% + 0.5px),transparent calc(66.66% + 0.5px));}
75
+ .ch{position:absolute;width:16px;height:16px;background:#fff;border:1px solid rgba(0,0,0,.65);border-radius:3px;z-index:2}
76
+ .ch:hover{background:var(--accent)}
77
+ .ch[data-h=nw]{left:-8px;top:-8px;cursor:nwse-resize}
78
+ .ch[data-h=ne]{right:-8px;top:-8px;cursor:nesw-resize}
79
+ .ch[data-h=sw]{left:-8px;bottom:-8px;cursor:nesw-resize}
80
+ .ch[data-h=se]{right:-8px;bottom:-8px;cursor:nwse-resize}
81
+ .ch[data-h=n]{left:calc(50% - 8px);top:-8px;cursor:ns-resize}
82
+ .ch[data-h=s]{left:calc(50% - 8px);bottom:-8px;cursor:ns-resize}
83
+ .ch[data-h=w]{left:-8px;top:calc(50% - 8px);cursor:ew-resize}
84
+ .ch[data-h=e]{right:-8px;top:calc(50% - 8px);cursor:ew-resize}
85
+ .cropdims{position:absolute;left:50%;transform:translateX(-50%);bottom:5px;
86
+ background:rgba(0,0,0,.75);color:#dff;padding:2px 8px;border-radius:5px;
87
+ font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none}
88
+
89
+ #cropBtn.on{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
90
+ #cropBtn.on .kbd{background:rgba(0,0,0,.15);border-color:rgba(0,0,0,.25);color:#04121c}
91
+ .arlab{color:var(--dim);font-size:11px;text-transform:uppercase;letter-spacing:.6px;margin:2px 0 5px}
92
+ .arRow{margin-bottom:8px}
93
+ .arcustom{display:flex;align-items:center;gap:6px;margin-bottom:4px}
94
+ .arcustom input{width:100%;min-width:0;text-align:center}
95
+ .arcustom span{color:var(--dim)}
96
+ .arcustom.on input{border-color:var(--accent)}
97
+
98
+ /* ---------- transport ---------- */
99
+ .transport{display:flex;align-items:center;gap:8px;margin-top:12px;flex-wrap:wrap}
100
+ .tc{font-variant-numeric:tabular-nums;font-size:13px;color:var(--dim)}
101
+ .tc b{color:var(--txt);font-weight:600}
102
+
103
+ /* ---------- timeline ---------- */
104
+ .tl-wrap{margin-top:14px;user-select:none}
105
+ .tl{position:relative;height:70px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;overflow:hidden;touch-action:none;cursor:pointer}
106
+ #strip{position:absolute;inset:0;display:flex;opacity:.9}
107
+ #strip canvas{height:100%;flex:1 1 0;min-width:0;object-fit:cover}
108
+ .mask{position:absolute;top:0;bottom:0;background:rgba(6,9,13,.72);pointer-events:none}
109
+ .sel{position:absolute;top:0;bottom:0;border-left:2px solid var(--accent);border-right:2px solid var(--accent);
110
+ box-shadow:inset 0 0 0 1px rgba(76,194,255,.25);pointer-events:none}
111
+ .handle{position:absolute;top:0;bottom:0;width:16px;margin-left:-8px;cursor:ew-resize;touch-action:none;z-index:5}
112
+ .handle::after{content:"";position:absolute;left:5px;top:50%;transform:translateY(-50%);
113
+ width:6px;height:26px;border-radius:3px;background:var(--accent);box-shadow:0 0 0 1px rgba(0,0,0,.4)}
114
+ .handle:hover::after{background:#8bd8ff}
115
+ .playhead{position:absolute;top:0;bottom:0;width:2px;margin-left:-1px;background:#fff;pointer-events:none;z-index:6;box-shadow:0 0 6px rgba(255,255,255,.7)}
116
+ .ruler{display:flex;justify-content:space-between;margin-top:5px;color:var(--dim);font-size:11px;font-variant-numeric:tabular-nums}
117
+
118
+ /* saved clips drawn along the bottom of the timeline */
119
+ #segBand{position:absolute;left:0;right:0;bottom:0;height:16px;pointer-events:none;z-index:4}
120
+ .segbar{position:absolute;bottom:0;height:16px;min-width:3px;background:rgba(63,185,80,.42);
121
+ border:1px solid rgba(63,185,80,.95);border-radius:3px;overflow:hidden;
122
+ font-size:9.5px;line-height:14px;text-align:center;color:#dfffe6;font-weight:600}
123
+ .segbar.on{background:rgba(76,194,255,.5);border-color:#8bd8ff;color:#eaf7ff}
124
+
125
+ .marks{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;align-items:center}
126
+ .pill{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:12.5px;font-variant-numeric:tabular-nums}
127
+ .pill span{color:var(--dim)}
128
+ .pill b{font-weight:600}
129
+ .pill.dur b{color:var(--accent)}
130
+ .edit{cursor:text;border-bottom:1px dotted #4a5663;padding-bottom:1px}
131
+ .edit:hover{border-bottom-color:var(--accent);color:var(--accent)}
132
+ .edit input{width:88px;padding:0 3px;border:1px solid var(--accent);border-radius:4px;
133
+ background:#0b0f14;color:var(--txt);font:inherit;font-weight:600;text-align:center}
134
+
135
+ /* ---------- clip list ---------- */
136
+ #clipsWrap{display:none;margin-top:18px}
137
+ .clips-head{display:flex;align-items:center;gap:10px;margin-bottom:8px}
138
+ .clips-head h3{margin:0;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim);font-weight:600}
139
+ #clipList{border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel)}
140
+ .crow{display:flex;align-items:center;gap:10px;padding:7px 10px;border-top:1px solid var(--line);font-size:12.5px}
141
+ .crow:first-child{border-top:none}
142
+ .crow:hover{background:var(--panel2)}
143
+ .crow.on{background:#12212b;box-shadow:inset 2px 0 0 var(--accent)}
144
+ .cnum{width:20px;color:var(--dim);font-variant-numeric:tabular-nums;flex:none}
145
+ .cname{flex:1 1 90px;min-width:60px;max-width:230px}
146
+ .cname input{width:100%;background:transparent;border:1px solid transparent;border-radius:6px;
147
+ padding:2px 6px;color:var(--txt);font:inherit}
148
+ .cname input:hover{border-color:var(--line)}
149
+ .cname input:focus{outline:none;border-color:var(--accent);background:#0b0f14}
150
+ .cname input::placeholder{color:#5a6572}
151
+ .ctimes{font-variant-numeric:tabular-nums;color:var(--dim);flex:none}
152
+ .ctimes b{color:var(--txt);font-weight:600}
153
+ .cdur{font-variant-numeric:tabular-nums;color:var(--accent);font-weight:600;width:64px;text-align:right;flex:none}
154
+ .cbtns{display:flex;gap:4px;flex:none}
155
+ .cbtns button{padding:3px 8px;font-size:11.5px;border-radius:6px}
156
+ @media(max-width:760px){ .ctimes{display:none} }
157
+
158
+ /* ---------- settings ---------- */
159
+ .row{display:flex;align-items:center;gap:8px;margin-bottom:10px}
160
+ .row label{flex:0 0 78px;color:var(--dim);font-size:12.5px}
161
+ input[type=text],input[type=number],select{
162
+ font:inherit;background:var(--panel2);color:var(--txt);border:1px solid var(--line);
163
+ border-radius:7px;padding:6px 8px;width:100%;min-width:0;
164
+ }
165
+ input:focus,select:focus{outline:none;border-color:var(--accent)}
166
+ input[type=range]{width:100%;accent-color:var(--accent)}
167
+ .seg{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px}
168
+ .seg button{padding:5px 9px;font-size:12.5px;border-radius:7px}
169
+ .seg button.on{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
170
+ .hint{color:var(--dim);font-size:11.5px;margin:-4px 0 12px}
171
+ .chk{display:flex;align-items:center;gap:7px;color:var(--dim);font-size:12.5px;margin-bottom:10px;cursor:pointer}
172
+ hr{border:none;border-top:1px solid var(--line);margin:14px 0}
173
+
174
+ .est{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:9px 11px;font-size:12.5px;margin-bottom:12px}
175
+ .est div{display:flex;justify-content:space-between;margin:2px 0}
176
+ .est span{color:var(--dim)}
177
+ .est b{font-variant-numeric:tabular-nums;font-weight:600}
178
+
179
+ #exportBtn{width:100%;padding:11px}
180
+ #gifBtn{width:100%;padding:9px;margin-top:8px}
181
+ #stopBtn{width:100%;padding:9px;margin-top:8px;display:none}
182
+ .bar{height:6px;background:var(--panel2);border-radius:99px;overflow:hidden;margin-top:10px;display:none}
183
+ .bar i{display:block;height:100%;width:0;background:var(--accent);transition:width .2s}
184
+ #status{font-size:12px;color:var(--dim);margin-top:8px;text-align:center;min-height:16px}
185
+
186
+ #result{display:none;margin-top:14px}
187
+ #result video{width:100%;border-radius:8px;background:#000;border:1px solid var(--line)}
188
+ #saved{display:none;margin-top:14px;border:1px solid var(--line);border-radius:8px;background:var(--panel2);padding:10px 12px}
189
+ #saved h4{margin:0 0 6px;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim)}
190
+ #savedList{margin:0;padding-left:16px;font-size:12px;color:var(--txt);line-height:1.7;max-height:190px;overflow:auto}
191
+ .note{font-size:11.5px;color:var(--warn);margin-top:8px;line-height:1.4}
192
+ .kbd{display:inline-block;background:var(--panel2);border:1px solid var(--line);border-bottom-width:2px;
193
+ border-radius:5px;padding:0 5px;font-size:11px;font-family:ui-monospace,Menlo,Consolas,monospace}
194
+ .keys{color:var(--dim);font-size:11.5px;margin-top:12px;line-height:1.9}
195
+ </style>
196
+ </head>
197
+ <body>
198
+ <div class="wrap">
199
+
200
+ <header>
201
+ <h1>Nugget Video Trimmer</h1>
202
+ <span class="sub">trim &middot; resize &middot; fps &middot; quality</span>
203
+ <span class="spacer"></span>
204
+ <button id="newBtn" class="ghost" style="display:none">Load another video</button>
205
+ <span class="ver">v1.6</span>
206
+ </header>
207
+
208
+ <div id="drop">
209
+ <div class="big">&#9634;</div>
210
+ <h2>Drop a video here</h2>
211
+ <p>or click to choose a file &nbsp;&middot;&nbsp; MP4, MOV, WebM, MKV &nbsp;&middot;&nbsp; nothing is uploaded, it all stays on this computer</p>
212
+ <input type="file" id="file" accept="video/*" hidden>
213
+ </div>
214
+
215
+ <div id="app">
216
+ <div class="grid">
217
+
218
+ <!-- LEFT -->
219
+ <div>
220
+ <div class="stage" id="stage">
221
+ <video id="video" playsinline></video>
222
+ <canvas id="exportCanvas"></canvas>
223
+ <div id="cropLayer">
224
+ <div id="cropBox" data-h="move">
225
+ <span class="ch" data-h="nw"></span><span class="ch" data-h="n"></span><span class="ch" data-h="ne"></span>
226
+ <span class="ch" data-h="w"></span><span class="ch" data-h="e"></span>
227
+ <span class="ch" data-h="sw"></span><span class="ch" data-h="s"></span><span class="ch" data-h="se"></span>
228
+ <span class="cropdims" id="cropDims"></span>
229
+ </div>
230
+ </div>
231
+ <div class="badge" id="srcBadge"></div>
232
+ </div>
233
+
234
+ <div class="transport">
235
+ <button id="playBtn" class="icobtn" title="Play / pause (Space)">&#9654;</button>
236
+ <button id="prevF" class="icobtn" title="Previous frame (&larr;)">&#8676;</button>
237
+ <button id="nextF" class="icobtn" title="Next frame (&rarr;)">&#8677;</button>
238
+ <span class="tc"><b id="curTime">0:00.00</b> / <span id="totTime">0:00.00</span></span>
239
+ <span class="spacer"></span>
240
+ <button id="cropBtn" title="Show or hide the crop box (C)">Crop &nbsp;<span class="kbd">C</span></button>
241
+ <button id="setIn">Set start &nbsp;<span class="kbd">I</span></button>
242
+ <button id="setOut">Set end &nbsp;<span class="kbd">O</span></button>
243
+ <button id="loopBtn" class="ghost" title="Loop the selection">Loop: off</button>
244
+ </div>
245
+
246
+ <div class="tl-wrap">
247
+ <div class="tl" id="tl">
248
+ <div id="strip"></div>
249
+ <div class="mask" id="maskL"></div>
250
+ <div class="mask" id="maskR"></div>
251
+ <div class="sel" id="sel"></div>
252
+ <div id="segBand"></div>
253
+ <div class="playhead" id="ph"></div>
254
+ <div class="handle" id="hIn"></div>
255
+ <div class="handle" id="hOut"></div>
256
+ </div>
257
+ <div class="ruler"><span>0:00</span><span id="rulMid"></span><span id="rulEnd"></span></div>
258
+
259
+ <div class="marks">
260
+ <span class="pill"><span>Start</span> <b id="pIn" class="edit" title="Click to type an exact time">0:00.00</b></span>
261
+ <span class="pill"><span>End</span> <b id="pOut" class="edit" title="Click to type an exact time">0:00.00</b></span>
262
+ <span class="pill dur"><span>Duration</span> <b id="pDur" class="edit" title="Click to type an exact length, e.g. 30 or 1:30">0:00.00</b></span>
263
+ <button id="addClip" class="primary small" title="Save this selection to the clip list (A)">+ Add clip &nbsp;<span class="kbd" style="background:rgba(0,0,0,.15);border-color:rgba(0,0,0,.25)">A</span></button>
264
+ <button id="resetSel" class="ghost small">Reset to full clip</button>
265
+ </div>
266
+
267
+ <div class="keys">
268
+ <span class="kbd">Space</span> play/pause &nbsp; <span class="kbd">&larr;</span><span class="kbd">&rarr;</span> step 1 frame &nbsp;
269
+ <span class="kbd">Shift</span>+<span class="kbd">&larr;</span><span class="kbd">&rarr;</span> step 1 sec &nbsp;
270
+ <span class="kbd">I</span> set start &nbsp; <span class="kbd">O</span> set end &nbsp; <span class="kbd">A</span> add clip &nbsp; <span class="kbd">C</span> crop &nbsp; <span class="kbd">Home</span>/<span class="kbd">End</span> jump
271
+ <br>Click <b style="color:var(--txt)">Start</b>, <b style="color:var(--txt)">End</b> or <b style="color:var(--txt)">Duration</b> above to type an exact value — seconds (<code>90</code>) or minutes:seconds (<code>1:30</code>).
272
+ </div>
273
+
274
+ <!-- clip list: only appears once you add something -->
275
+ <div id="clipsWrap">
276
+ <div class="clips-head">
277
+ <h3 id="clipsTitle">Clip list</h3>
278
+ <span class="spacer"></span>
279
+ <button id="clearClips" class="ghost small">Clear all</button>
280
+ </div>
281
+ <div id="clipList"></div>
282
+ <div class="hint" style="margin-top:8px">
283
+ Export uses this list — the timeline selection is only used for adding new clips.
284
+ Use ▶ to preview a clip, Set to overwrite it with the current timeline selection, ✕ to remove it. Click its times to type exact values.
285
+ Names are optional and become the file name.
286
+ </div>
287
+ </div>
288
+ </div>
289
+ </div>
290
+
291
+ <!-- RIGHT -->
292
+ <div>
293
+ <div class="card">
294
+ <div id="cropSection" style="display:none">
295
+ <h3>Crop &amp; aspect ratio</h3>
296
+ <div class="seg arRow">
297
+ <button data-ar="0" data-lbl="free">Free</button>
298
+ <button data-ar="src" data-lbl="original">Original</button>
299
+ <button data-ar="1" data-lbl="1:1">1:1 square</button>
300
+ </div>
301
+ <div class="arlab">Landscape</div>
302
+ <div class="seg arRow">
303
+ <button data-ar="2.33333" data-lbl="21:9">21:9</button>
304
+ <button data-ar="1.77778" data-lbl="16:9">16:9</button>
305
+ <button data-ar="1.5" data-lbl="3:2">3:2</button>
306
+ <button data-ar="1.33333" data-lbl="4:3">4:3</button>
307
+ </div>
308
+ <div class="arlab">Portrait</div>
309
+ <div class="seg arRow">
310
+ <button data-ar="0.5625" data-lbl="9:16">9:16</button>
311
+ <button data-ar="0.5" data-lbl="1:2">1:2</button>
312
+ <button data-ar="0.66667" data-lbl="2:3">2:3</button>
313
+ <button data-ar="0.75" data-lbl="3:4">3:4</button>
314
+ <button data-ar="0.8" data-lbl="4:5">4:5</button>
315
+ </div>
316
+ <div class="arlab">Custom</div>
317
+ <div class="arcustom" id="arCustom">
318
+ <input type="number" id="arW" min="1" max="9999" step="1" placeholder="9">
319
+ <span>:</span>
320
+ <input type="number" id="arH" min="1" max="9999" step="1" placeholder="16">
321
+ <button id="arApply" class="small">Use</button>
322
+ </div>
323
+ <div class="hint" id="cropInfo" style="margin:8px 0"></div>
324
+ <button id="cropMax" class="small" style="width:100%">Biggest box that fits</button>
325
+ <hr>
326
+ </div>
327
+
328
+ <h3>Size</h3>
329
+ <div class="seg" id="scaleSeg">
330
+ <button data-s="1">100%</button>
331
+ <button data-s="0.75">75%</button>
332
+ <button data-s="0.5">50%</button>
333
+ <button data-s="0.25">25%</button>
334
+ </div>
335
+ <div class="row">
336
+ <label>Width</label><input type="number" id="w" min="16" step="2">
337
+ </div>
338
+ <div class="row">
339
+ <label>Height</label><input type="number" id="h" min="16" step="2">
340
+ </div>
341
+ <label class="chk"><input type="checkbox" id="lockAr" checked> Lock aspect ratio</label>
342
+ <div class="hint" id="sizeHint"></div>
343
+
344
+ <hr>
345
+ <h3>Frame rate</h3>
346
+ <div class="seg" id="fpsSeg"></div>
347
+ <div class="row">
348
+ <label>Custom</label><input type="number" id="fps" min="1" max="120" step="1">
349
+ </div>
350
+ <div class="hint">Higher than the source frame rate won't add detail.</div>
351
+
352
+ <hr>
353
+ <h3>Quality</h3>
354
+ <input type="range" id="q" min="0" max="100" value="78">
355
+ <div class="hint" id="qHint"></div>
356
+ <label class="chk"><input type="checkbox" id="keepAudio" checked> Include audio</label>
357
+
358
+ <div class="est">
359
+ <div><span>Output</span><b id="eSize">—</b></div>
360
+ <div><span>Bitrate</span><b id="eRate">—</b></div>
361
+ <div><span>Encoder</span><b id="eCodec">—</b></div>
362
+ <div><span id="eBytesLbl">Est. file size</span><b id="eBytes">—</b></div>
363
+ <div><span>Export takes about</span><b id="eTime">—</b></div>
364
+ </div>
365
+
366
+ <button id="exportBtn" class="primary">Export clip</button>
367
+ <button id="gifBtn">Export as GIF</button>
368
+ <div class="hint" id="gifHint" style="margin:6px 0 0">GIF has only 256 colours and no sound, and files get large fast. A smaller width and 10–15 fps work best.</div>
369
+ <button id="stopBtn" class="danger">Stop</button>
370
+ <div class="bar" id="bar"><i id="barI"></i></div>
371
+ <div id="status"></div>
372
+ <div class="hint" id="expNote" style="display:none;margin:8px 0 0;text-align:center">
373
+ Leave this tab on screen — if you switch away, the export pauses and picks up when you come back.
374
+ </div>
375
+
376
+ <div id="result">
377
+ <video id="outVid" controls></video>
378
+ <img id="outImg" alt="" style="display:none;width:100%;border-radius:8px;background:#000;border:1px solid var(--line)">
379
+ <div style="display:flex;gap:8px;margin-top:10px">
380
+ <button id="dlBtn" class="primary" style="flex:1">Download again</button>
381
+ <button id="clearRes" class="ghost">Clear</button>
382
+ </div>
383
+ <div class="note" id="outNote"></div>
384
+ </div>
385
+
386
+ <div id="saved">
387
+ <h4 id="savedWhere">Saved</h4>
388
+ <ol id="savedList"></ol>
389
+ <div class="note" id="savedNote"></div>
390
+ </div>
391
+ </div>
392
+ </div>
393
+
394
+ </div>
395
+ </div>
396
+ </div>
397
+
398
+ <script>
399
+ "use strict";
400
+ (function(){
401
+
402
+ /* ---------------- helpers ---------------- */
403
+ const $ = id => document.getElementById(id);
404
+ const clamp = (v,a,b) => Math.min(b, Math.max(a, v));
405
+ function tc(t, frac){ // 1:23.45 / 1:05:03.20
406
+ if(!isFinite(t)||t<0) t=0;
407
+ const h = Math.floor(t/3600);
408
+ const m = Math.floor((t-h*3600)/60), s = t - h*3600 - m*60;
409
+ const mm = h ? String(m).padStart(2,"0") : String(m);
410
+ const hh = h ? h+":" : "";
411
+ return frac===false ? hh+mm+":"+String(Math.floor(s)).padStart(2,"0")
412
+ : hh+mm+":"+(s<10?"0":"")+s.toFixed(2);
413
+ }
414
+ function stamp(t){ t=Math.max(0,t||0); return Math.floor(t/60)+"m"+String(Math.floor(t%60)).padStart(2,"0")+"s"; }
415
+ function bytes(n){
416
+ if(!isFinite(n)) return "—";
417
+ if(n < 1024*1024) return (n/1024).toFixed(0)+" KB";
418
+ if(n < 1024*1024*1024) return (n/1048576).toFixed(1)+" MB";
419
+ return (n/1073741824).toFixed(2)+" GB";
420
+ }
421
+ function even(n){ n = Math.round(n); return n%2 ? n+1 : n; }
422
+ function safeName(s, n){ return String(s||"").replace(/[\\/:*?"<>|\x00-\x1f]+/g,"-").replace(/^\.+/,"").trim().slice(0,n||60); }
423
+ function once(el,ev){ return new Promise(r=>el.addEventListener(ev,r,{once:true})); }
424
+
425
+ /* ---------------- state ---------------- */
426
+ const V = $("video");
427
+ let srcUrl=null, srcName="clip", dur=0, natW=0, natH=0, srcFps=30;
428
+ let inT=0, outT=0, looping=false, dragging=null, exporting=false, cancelExport=false;
429
+ let audioCtx=null, mediaSrc=null, monitorGain=null, streamDest=null;
430
+ let lastBlob=null, lastExt="webm", lastMeta=null;
431
+ let segments=[], activeSeg=-1, segId=0;
432
+
433
+ /* ---------------- file loading ---------------- */
434
+ const drop=$("drop"), fileInput=$("file");
435
+ fileInput.addEventListener("click", e=>e.stopPropagation());
436
+ drop.addEventListener("click", ()=>fileInput.click());
437
+ fileInput.addEventListener("change", e=>{ if(e.target.files[0]) load(e.target.files[0]); e.target.value=""; });
438
+ ["dragenter","dragover"].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.add("over")}));
439
+ ["dragleave","drop"].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.remove("over")}));
440
+ // ONE drop handler only, on the window — two handlers meant a drop started the load twice
441
+ window.addEventListener("dragover", e=>e.preventDefault());
442
+ window.addEventListener("drop", e=>{
443
+ e.preventDefault(); drop.classList.remove("over");
444
+ const f = e.dataTransfer && e.dataTransfer.files[0];
445
+ if(f) load(f);
446
+ });
447
+ $("newBtn").addEventListener("click", ()=>fileInput.click());
448
+
449
+ const DROP_HTML = drop.innerHTML;
450
+ let loadSeq = 0; // only the newest load() is allowed to touch the UI
451
+ let loadedOnce = false;
452
+
453
+ async function load(file){
454
+ if(exporting){ alert("Hang on until the export finishes, then load the next video."); return; }
455
+ if(segments.length && loadedOnce &&
456
+ !confirm("Loading a new video clears the clip list ("+segments.length+" clips). Continue?")) return;
457
+
458
+ const myId = ++loadSeq;
459
+ const newUrl = URL.createObjectURL(file);
460
+ const prevUrl = srcUrl;
461
+
462
+ const bail = (msg)=>{
463
+ URL.revokeObjectURL(newUrl);
464
+ if(myId !== loadSeq) return; // a newer load took over — stay quiet
465
+ srcUrl = prevUrl;
466
+ if(loadedOnce){ // don't destroy a session that's already open
467
+ if(V.src !== prevUrl && prevUrl){ V.src = prevUrl; }
468
+ alert(msg+"\n\nYour current video is still open.");
469
+ }else{
470
+ drop.innerHTML = DROP_HTML; drop.style.display="block"; $("app").style.display="none";
471
+ alert(msg);
472
+ }
473
+ };
474
+
475
+ srcName = (file.name||"clip").replace(/\.[^.]+$/,"") || "clip";
476
+ srcUrl = newUrl;
477
+ clearResult(); clearSaved();
478
+ V.src = newUrl;
479
+ V.muted = false;
480
+
481
+ const how = await new Promise(res=>{
482
+ let settled=false, timer=0;
483
+ const done = v => { if(settled) return; settled=true; clearTimeout(timer);
484
+ V.onloadedmetadata=null; V.onerror=null; res(v); };
485
+ V.onloadedmetadata = ()=>done("ok");
486
+ V.onerror = ()=>done("err");
487
+ timer = setTimeout(()=>done("slow"), 120000);
488
+ });
489
+ if(myId !== loadSeq){ URL.revokeObjectURL(newUrl); return; }
490
+
491
+ if(how==="err") return bail("This browser can't open “"+file.name+"”.\n\nTry an MP4, MOV or WebM file — Chrome can't read every format (AVI and some MKVs won't work).");
492
+ if(how==="slow") return bail("“"+file.name+"” is taking too long to open. If it's on a network or cloud drive, copy it to this computer first.");
493
+
494
+ dur = V.duration;
495
+ if(!isFinite(dur) || dur<=0){ // some WebM/MKV files report no duration until you seek past the end
496
+ try{
497
+ V.currentTime = 1e7;
498
+ await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,2500))]);
499
+ dur = isFinite(V.duration) ? V.duration : V.currentTime;
500
+ V.currentTime = 0;
501
+ await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,1500))]);
502
+ }catch(e){}
503
+ }
504
+ if(myId !== loadSeq){ URL.revokeObjectURL(newUrl); return; }
505
+ if(!isFinite(dur) || dur<=0) return bail("Couldn't work out how long that video is, so it can't be trimmed. Try converting it to MP4 first.");
506
+
507
+ if(prevUrl) URL.revokeObjectURL(prevUrl); // safe now: the new file is definitely in
508
+ natW = V.videoWidth || 640; natH = V.videoHeight || 360;
509
+ inT = 0; outT = dur;
510
+ segments = []; activeSeg = -1;
511
+ removeCrop();
512
+
513
+ if(!loadedOnce) drop.innerHTML = '<div class="big">&#9634;</div><h2>Reading video…</h2><p>one moment</p>';
514
+ srcFps = 30;
515
+ await detectFps();
516
+ if(myId !== loadSeq) return;
517
+
518
+ loadedOnce = true;
519
+ drop.style.display="none"; $("app").style.display="block"; $("newBtn").style.display="inline-block";
520
+
521
+ $("w").value = natW; $("h").value = natH;
522
+ $("totTime").textContent = tc(dur);
523
+ $("rulEnd").textContent = tc(dur,false);
524
+ $("rulMid").textContent = tc(dur/2,false);
525
+
526
+ buildFpsSeg();
527
+ $("fps").value = Math.round(srcFps);
528
+ $("srcBadge").textContent = natW+"×"+natH+" · "+Math.round(srcFps)+" fps · "+tc(dur,false);
529
+ document.title = srcName+" — Nugget Video Trimmer";
530
+ markScale(1);
531
+ refresh(); update();
532
+ buildStrip(newUrl, myId);
533
+ }
534
+
535
+ /* estimate source fps by counting presented frames over a short muted sample */
536
+ async function detectFps(){
537
+ if(!("requestVideoFrameCallback" in HTMLVideoElement.prototype)) return;
538
+ const prevMuted = V.muted;
539
+ V.muted = true;
540
+ let stop = false;
541
+ try{
542
+ V.currentTime = Math.min(0.2, dur/4);
543
+ await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,1500))]);
544
+ let first=null, last=null, n=0;
545
+ const done = new Promise(res=>{
546
+ const finish = ()=>{ stop=true; res(); };
547
+ const cb=(now,md)=>{
548
+ if(stop) return;
549
+ if(first===null) first=md.mediaTime; else { last=md.mediaTime; n++; }
550
+ if(n>=12 || (last!==null && last-first>0.5)) return finish();
551
+ V.requestVideoFrameCallback(cb);
552
+ };
553
+ V.requestVideoFrameCallback(cb);
554
+ setTimeout(finish, 1400); // rVFC never fired (or is throttled) — give up
555
+ });
556
+ await V.play().catch(()=>{});
557
+ await done;
558
+ if(n>2 && last>first){
559
+ const f = n/(last-first);
560
+ if(f>4 && f<125) srcFps = Math.round(f*100)/100;
561
+ }
562
+ }catch(e){}
563
+ stop = true;
564
+ try{ V.pause(); }catch(e){}
565
+ V.muted = prevMuted;
566
+ V.currentTime = 0;
567
+ await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,800))]);
568
+ }
569
+
570
+ /* ---------------- filmstrip ---------------- */
571
+ async function buildStrip(url, id){
572
+ const strip=$("strip"); strip.innerHTML="";
573
+ const N=12, tw=160, th=90, total=dur;
574
+ const v=document.createElement("video");
575
+ v.src=url; v.muted=true; v.playsInline=true;
576
+ try{
577
+ await Promise.race([once(v,"loadeddata"), once(v,"error"), new Promise(r=>setTimeout(r,15000))]);
578
+ }catch(e){ return; }
579
+ for(let i=0;i<N;i++){
580
+ if(id !== loadSeq){ v.removeAttribute("src"); return; }
581
+ const c=document.createElement("canvas"); c.width=tw; c.height=th;
582
+ strip.appendChild(c);
583
+ try{
584
+ v.currentTime = Math.min(total-0.03, (i+0.5)*total/N);
585
+ await Promise.race([once(v,"seeked"), new Promise(r=>setTimeout(r,1500))]);
586
+ c.getContext("2d").drawImage(v,0,0,tw,th);
587
+ }catch(e){}
588
+ }
589
+ v.removeAttribute("src");
590
+ }
591
+
592
+ /* ---------------- transport ---------------- */
593
+ $("playBtn").addEventListener("click", togglePlay);
594
+ function togglePlay(){
595
+ if(exporting) return;
596
+ if(V.paused){ if(V.currentTime<inT-0.01||V.currentTime>=outT-0.01) V.currentTime=inT; V.play(); }
597
+ else V.pause();
598
+ }
599
+ V.addEventListener("play", ()=>$("playBtn").innerHTML="&#10073;&#10073;");
600
+ V.addEventListener("pause",()=>$("playBtn").innerHTML="&#9654;");
601
+ V.addEventListener("timeupdate", update);
602
+ V.addEventListener("seeked", update);
603
+
604
+ function rafLoop(){
605
+ if(!V.paused && !exporting){
606
+ if(V.currentTime>=outT-0.02){ if(looping){ V.currentTime=inT; } else { V.pause(); V.currentTime=outT; } }
607
+ update();
608
+ }
609
+ requestAnimationFrame(rafLoop);
610
+ }
611
+ requestAnimationFrame(rafLoop);
612
+
613
+ $("prevF").addEventListener("click", ()=>step(-1));
614
+ $("nextF").addEventListener("click", ()=>step(1));
615
+ function step(dir, big){
616
+ V.pause();
617
+ const d = big ? 1 : 1/(srcFps||30);
618
+ V.currentTime = clamp(V.currentTime + dir*d, 0, dur);
619
+ }
620
+ /* Setting a start later than the current end used to clamp the start back onto
621
+ the end. Marking a new clip after the previous one is the normal way to work,
622
+ so the other mark gets out of the way instead. */
623
+ function setIn(t){
624
+ inT = clamp(t, 0, Math.max(0, dur-0.02));
625
+ if(outT <= inT + 0.02) outT = dur; // start moved past the end — open the end up
626
+ refresh();
627
+ }
628
+ function setOut(t){
629
+ outT = clamp(t, 0.02, dur);
630
+ if(inT >= outT - 0.02) inT = 0; // end moved before the start — open the start up
631
+ refresh();
632
+ }
633
+ $("setIn").addEventListener("click", ()=>setIn(V.currentTime));
634
+ $("setOut").addEventListener("click", ()=>setOut(V.currentTime));
635
+ $("resetSel").addEventListener("click", ()=>{ inT=0; outT=dur; refresh(); });
636
+ $("loopBtn").addEventListener("click", e=>{ looping=!looping; e.target.textContent="Loop: "+(looping?"on":"off"); e.target.classList.toggle("ghost",!looping); });
637
+
638
+ /* ---------------- click-to-type time fields ---------------- */
639
+ function parseTime(s){ // "1:23.4", "0:05", "83.4", "1:02:03"
640
+ s = String(s).trim(); if(!s) return null;
641
+ const parts = s.split(":").map(x=>parseFloat(x));
642
+ if(parts.some(x=>isNaN(x))) return null;
643
+ return parts.reduce((a,x)=>a*60+x, 0);
644
+ }
645
+ function makeTimeEditor(el, get, set){
646
+ el.addEventListener("click", function(e){
647
+ e.stopPropagation();
648
+ if(exporting || el.querySelector("input")) return;
649
+ const inp = document.createElement("input");
650
+ inp.value = tc(get()); el.textContent=""; el.appendChild(inp);
651
+ inp.focus(); inp.select();
652
+ let done=false;
653
+ const commit = ok => {
654
+ if(done) return; done=true;
655
+ const v = ok ? parseTime(inp.value) : null;
656
+ inp.remove();
657
+ if(v !== null && isFinite(v)) set(v);
658
+ refresh();
659
+ };
660
+ inp.addEventListener("blur", ()=>commit(true));
661
+ inp.addEventListener("click", ev=>ev.stopPropagation());
662
+ inp.addEventListener("keydown", ev=>{
663
+ ev.stopPropagation();
664
+ if(ev.key==="Enter"){ ev.preventDefault(); commit(true); }
665
+ if(ev.key==="Escape"){ ev.preventDefault(); commit(false); }
666
+ });
667
+ });
668
+ }
669
+ makeTimeEditor($("pIn"), ()=>inT, v=>{ setIn(v); V.currentTime=inT; });
670
+ makeTimeEditor($("pOut"), ()=>outT, v=>{ setOut(v); V.currentTime=outT; });
671
+ makeTimeEditor($("pDur"), ()=>outT-inT, v=>{
672
+ const len = clamp(v, 0.02, dur);
673
+ if(inT + len <= dur){ outT = inT + len; }
674
+ else { outT = dur; inT = Math.max(0, dur - len); }
675
+ V.currentTime = inT;
676
+ });
677
+
678
+ document.addEventListener("keydown", e=>{
679
+ if(exporting) return;
680
+ const t=e.target.tagName;
681
+ if(t==="INPUT"||t==="SELECT"||t==="TEXTAREA") return;
682
+ const k=e.key;
683
+ if(k===" "){ e.preventDefault(); togglePlay(); }
684
+ else if(k==="ArrowLeft"){ e.preventDefault(); step(-1, e.shiftKey); }
685
+ else if(k==="ArrowRight"){ e.preventDefault(); step(1, e.shiftKey); }
686
+ else if(k==="i"||k==="I"){ setIn(V.currentTime); }
687
+ else if(k==="o"||k==="O"){ setOut(V.currentTime); }
688
+ else if(k==="a"||k==="A"){ e.preventDefault(); addClip(); }
689
+ else if(k==="c"||k==="C"){ e.preventDefault(); toggleCrop(); }
690
+ else if(k==="Home"){ V.currentTime=inT; }
691
+ else if(k==="End"){ V.currentTime=outT; }
692
+ });
693
+
694
+ /* ---------------- timeline drag ---------------- */
695
+ const tl=$("tl");
696
+ function posToTime(clientX){
697
+ const r=tl.getBoundingClientRect();
698
+ return clamp((clientX-r.left)/r.width,0,1)*dur;
699
+ }
700
+ tl.addEventListener("pointerdown", e=>{
701
+ if(exporting||!dur) return;
702
+ if(e.target===$("hIn")) dragging="in";
703
+ else if(e.target===$("hOut")) dragging="out";
704
+ else { dragging="seek"; V.pause(); V.currentTime=posToTime(e.clientX); }
705
+ tl.setPointerCapture(e.pointerId);
706
+ });
707
+ tl.addEventListener("pointermove", e=>{
708
+ if(!dragging) return;
709
+ const t=posToTime(e.clientX);
710
+ if(dragging==="in"){ inT=clamp(t,0,outT-0.02); V.currentTime=inT; }
711
+ else if(dragging==="out"){ outT=clamp(t,inT+0.02,dur); V.currentTime=outT; }
712
+ else V.currentTime=t;
713
+ refresh();
714
+ });
715
+ ["pointerup","pointercancel"].forEach(ev=>tl.addEventListener(ev,()=>dragging=null));
716
+
717
+ function refresh(){
718
+ const a = dur? inT/dur*100 : 0, b = dur? outT/dur*100 : 100;
719
+ $("maskL").style.left="0"; $("maskL").style.width=a+"%";
720
+ $("maskR").style.left=b+"%"; $("maskR").style.width=(100-b)+"%";
721
+ $("sel").style.left=a+"%"; $("sel").style.width=(b-a)+"%";
722
+ $("hIn").style.left=a+"%"; $("hOut").style.left=b+"%";
723
+ if(activeSeg>=0){ // highlight only while the selection still matches
724
+ const sg=segments[activeSeg];
725
+ if(!sg || Math.abs(sg.start-inT)>0.001 || Math.abs(sg.end-outT)>0.001) activeSeg=-1;
726
+ }
727
+ if(!$("pIn").querySelector("input")) $("pIn").textContent=tc(inT);
728
+ if(!$("pOut").querySelector("input")) $("pOut").textContent=tc(outT);
729
+ if(!$("pDur").querySelector("input")) $("pDur").textContent=tc(outT-inT);
730
+ renderClips(); renderBand(); estimate();
731
+ }
732
+ function update(){
733
+ $("curTime").textContent=tc(V.currentTime);
734
+ $("ph").style.left=(dur? V.currentTime/dur*100 : 0)+"%";
735
+ }
736
+
737
+ /* ---------------- clip list ---------------- */
738
+ $("addClip").addEventListener("click", addClip);
739
+ function addClip(){
740
+ if(exporting || !dur) return;
741
+ if(outT - inT < 0.05){ setStatus("Selection is too short to add."); return; }
742
+ segments.push({id:++segId, start:inT, end:outT, name:""});
743
+ activeSeg = segments.length-1;
744
+ setStatus("");
745
+ refresh();
746
+ }
747
+ $("clearClips").addEventListener("click", ()=>{
748
+ if(exporting || !segments.length) return;
749
+ if(segments.length>1 && !confirm("Remove all "+segments.length+" clips from the list?")) return;
750
+ segments=[]; activeSeg=-1; refresh();
751
+ });
752
+
753
+ function renderClips(){
754
+ const wrap=$("clipsWrap"), list=$("clipList");
755
+ wrap.style.display = segments.length ? "block" : "none";
756
+ $("clipsTitle").textContent = "Clip list ("+segments.length+")";
757
+ if(!segments.length){ list.innerHTML=""; return; }
758
+ if(list.querySelector("input:focus")) return; // don't yank a field being typed in
759
+
760
+ list.innerHTML="";
761
+ segments.forEach((s,i)=>{
762
+ const row=document.createElement("div");
763
+ row.className="crow"+(i===activeSeg?" on":"");
764
+
765
+ const num=document.createElement("span"); num.className="cnum"; num.textContent=(i+1);
766
+
767
+ const nameWrap=document.createElement("span"); nameWrap.className="cname";
768
+ const name=document.createElement("input");
769
+ name.type="text"; name.value=s.name||""; name.placeholder="name (optional)"; name.maxLength=40;
770
+ name.addEventListener("input", ()=>{ s.name=name.value; });
771
+ name.addEventListener("keydown", ev=>{ ev.stopPropagation(); if(ev.key==="Enter") name.blur(); });
772
+ name.addEventListener("click", ev=>ev.stopPropagation());
773
+ nameWrap.appendChild(name);
774
+
775
+ const times=document.createElement("span"); times.className="ctimes";
776
+ const bS=document.createElement("b"); bS.className="edit"; bS.textContent=tc(s.start);
777
+ const bE=document.createElement("b"); bE.className="edit"; bE.textContent=tc(s.end);
778
+ times.appendChild(bS); times.appendChild(document.createTextNode(" → ")); times.appendChild(bE);
779
+ makeTimeEditor(bS, ()=>s.start, v=>{ s.start = clamp(v, 0, s.end-0.02); });
780
+ makeTimeEditor(bE, ()=>s.end, v=>{ s.end = clamp(v, s.start+0.02, dur); });
781
+
782
+ const d=document.createElement("span"); d.className="cdur"; d.textContent=tc(s.end-s.start);
783
+
784
+ const btns=document.createElement("span"); btns.className="cbtns";
785
+ const prev=document.createElement("button");
786
+ prev.textContent="▶"; prev.title="Load this clip onto the timeline and play it";
787
+ prev.addEventListener("click", ev=>{ ev.stopPropagation();
788
+ if(exporting) return;
789
+ activeSeg=i; inT=s.start; outT=s.end; V.currentTime=s.start; refresh();
790
+ V.play().catch(()=>{}); });
791
+ const use=document.createElement("button");
792
+ use.textContent="Set"; use.title="Replace this clip's start and end with the current timeline selection";
793
+ use.addEventListener("click", ev=>{ ev.stopPropagation();
794
+ if(exporting) return;
795
+ s.start=inT; s.end=outT; activeSeg=i; refresh(); });
796
+ const del=document.createElement("button");
797
+ del.textContent="✕"; del.title="Remove this clip"; del.className="danger";
798
+ del.addEventListener("click", ev=>{ ev.stopPropagation();
799
+ if(exporting) return;
800
+ segments.splice(i,1);
801
+ if(activeSeg>=segments.length) activeSeg=segments.length-1;
802
+ refresh(); });
803
+ btns.appendChild(prev); btns.appendChild(use); btns.appendChild(del);
804
+
805
+ row.appendChild(num); row.appendChild(nameWrap); row.appendChild(times);
806
+ row.appendChild(d); row.appendChild(btns);
807
+ row.addEventListener("click", ()=>{ // preview this clip on the timeline
808
+ if(exporting) return;
809
+ activeSeg=i; inT=s.start; outT=s.end; V.currentTime=s.start; refresh();
810
+ });
811
+ list.appendChild(row);
812
+ });
813
+ }
814
+
815
+ function renderBand(){
816
+ const band=$("segBand"); band.innerHTML="";
817
+ if(!dur) return;
818
+ segments.forEach((s,i)=>{
819
+ const el=document.createElement("div");
820
+ el.className="segbar"+(i===activeSeg?" on":"");
821
+ el.style.left=(s.start/dur*100)+"%";
822
+ el.style.width=Math.max(0.4,(s.end-s.start)/dur*100)+"%";
823
+ el.textContent=(i+1);
824
+ band.appendChild(el);
825
+ });
826
+ }
827
+
828
+ /* the list is what gets exported; with an empty list it's just the selection */
829
+ function exportList(){
830
+ return segments.length ? segments.map(s=>({start:s.start,end:s.end,name:s.name}))
831
+ : [{start:inT,end:outT,name:""}];
832
+ }
833
+ function totalLen(){ return exportList().reduce((a,s)=>a+Math.max(0,s.end-s.start),0); }
834
+
835
+ /* ---------------- crop ----------------
836
+ Held in source pixels so it survives any output size change. Everything that
837
+ sizes the output asks srcW()/srcH() rather than the video's own dimensions. */
838
+ let crop=null, cropAR=0, cropARLabel="free", curScale=1;
839
+ function srcW(){ return crop ? crop.w : natW; }
840
+ function srcH(){ return crop ? crop.h : natH; }
841
+ function drawSource(dctx, dw, dh){
842
+ dctx.imageSmoothingEnabled=true; dctx.imageSmoothingQuality="high";
843
+ if(crop) dctx.drawImage(V, crop.x, crop.y, crop.w, crop.h, 0, 0, dw, dh);
844
+ else dctx.drawImage(V, 0, 0, dw, dh);
845
+ }
846
+
847
+ function videoBox(){
848
+ const st=$("stage").getBoundingClientRect(), v=V.getBoundingClientRect();
849
+ return {left:v.left-st.left, top:v.top-st.top, w:v.width, h:v.height};
850
+ }
851
+ function layoutCrop(){
852
+ if(!crop || !natW) return;
853
+ const L=$("cropLayer"), b=videoBox();
854
+ if(!b.w || !b.h) return;
855
+ L.style.left=b.left+"px"; L.style.top=b.top+"px";
856
+ L.style.width=b.w+"px"; L.style.height=b.h+"px";
857
+ const sx=b.w/natW, sy=b.h/natH, B=$("cropBox");
858
+ B.style.left=(crop.x*sx)+"px"; B.style.top=(crop.y*sy)+"px";
859
+ B.style.width=(crop.w*sx)+"px"; B.style.height=(crop.h*sy)+"px";
860
+ $("cropDims").textContent = Math.round(crop.w)+" × "+Math.round(crop.h);
861
+ }
862
+ function cropChanged(finalise){
863
+ if(crop){
864
+ crop.x=Math.max(0,Math.round(crop.x)); crop.y=Math.max(0,Math.round(crop.y));
865
+ crop.w=Math.min(Math.round(crop.w), natW-crop.x);
866
+ crop.h=Math.min(Math.round(crop.h), natH-crop.y);
867
+ }
868
+ layoutCrop();
869
+ $("cropInfo").textContent = crop
870
+ ? "Keeping "+crop.w+" × "+crop.h+" ("+cropARLabel+") out of "+natW+" × "+natH+" · drag the box or its handles"
871
+ : "";
872
+ if(finalise){ // only resize the output once the drag ends
873
+ if(curScale){ W.value=even(srcW()*curScale); H.value=even(srcH()*curScale); markScale(curScale); }
874
+ else if(lock.checked){ H.value=even((+W.value||srcW())*srcH()/srcW()); }
875
+ }
876
+ estimate();
877
+ }
878
+ function setCrop(x,y,w,h){
879
+ w=Math.max(16,Math.min(w,natW)); h=Math.max(16,Math.min(h,natH));
880
+ crop={x:clamp(x,0,natW-w), y:clamp(y,0,natH-h), w, h};
881
+ }
882
+ function snapToAR(ar){
883
+ if(!ar || !crop) return;
884
+ const cx=crop.x+crop.w/2, cy=crop.y+crop.h/2;
885
+ let w=Math.min(natW, Math.max(crop.w, crop.h*ar)), h=w/ar;
886
+ if(h>natH){ h=natH; w=h*ar; }
887
+ setCrop(cx-w/2, cy-h/2, w, h);
888
+ }
889
+ function biggestFit(ar){
890
+ let w=natW, h=natW/(ar||natW/natH);
891
+ if(h>natH){ h=natH; w=h*(ar||natW/natH); }
892
+ setCrop((natW-w)/2, (natH-h)/2, w, h);
893
+ }
894
+
895
+ function showCrop(on){
896
+ $("cropLayer").style.display = on ? "block" : "none";
897
+ $("cropSection").style.display = on ? "block" : "none";
898
+ $("cropBtn").classList.toggle("on", on);
899
+ }
900
+ $("cropBtn").addEventListener("click", toggleCrop);
901
+ function toggleCrop(){
902
+ if(exporting || !dur) return;
903
+ if(crop){ removeCrop(); return; }
904
+ if(cropAR) biggestFit(cropAR);
905
+ else setCrop(natW*0.1, natH*0.1, natW*0.8, natH*0.8);
906
+ showCrop(true); markAR(); cropChanged(true);
907
+ }
908
+ function removeCrop(){
909
+ crop=null; cropAR=0; cropARLabel="free";
910
+ showCrop(false);
911
+ if(curScale){ W.value=even(natW*curScale); H.value=even(natH*curScale); markScale(curScale); }
912
+ $("cropInfo").textContent="";
913
+ estimate();
914
+ }
915
+ $("cropMax").addEventListener("click", ()=>{ if(!crop) return; biggestFit(cropAR||natW/natH); cropChanged(true); });
916
+
917
+ function applyAR(ar, label){
918
+ cropAR = ar; cropARLabel = label;
919
+ markAR();
920
+ if(cropAR) snapToAR(cropAR);
921
+ cropChanged(true);
922
+ }
923
+ document.querySelectorAll(".arRow").forEach(row=>{
924
+ row.addEventListener("click", e=>{
925
+ const b=e.target.closest("button"); if(!b || !crop) return;
926
+ const v=b.dataset.ar;
927
+ applyAR(v==="src" ? natW/natH : parseFloat(v), v==="src" ? "original" : b.dataset.lbl);
928
+ });
929
+ });
930
+ function useCustomAR(){
931
+ if(!crop) return;
932
+ const a=+$("arW").value, b=+$("arH").value;
933
+ if(!(a>0) || !(b>0)){ $("arW").focus(); return; }
934
+ applyAR(a/b, a+":"+b);
935
+ }
936
+ $("arApply").addEventListener("click", useCustomAR);
937
+ ["arW","arH"].forEach(id=>$(id).addEventListener("keydown", e=>{
938
+ e.stopPropagation();
939
+ if(e.key==="Enter"){ e.preventDefault(); useCustomAR(); }
940
+ }));
941
+ function markAR(){
942
+ let matched=false;
943
+ document.querySelectorAll(".arRow button").forEach(b=>{
944
+ const v=b.dataset.ar, val = v==="src" ? (natW/natH) : parseFloat(v);
945
+ const on = (!cropAR && v==="0") || (cropAR>0 && Math.abs(val-cropAR) < 0.004);
946
+ b.classList.toggle("on", on);
947
+ if(on) matched=true;
948
+ });
949
+ $("arCustom").classList.toggle("on", !matched && cropAR>0);
950
+ }
951
+
952
+ let cropDrag=null;
953
+ $("cropLayer").addEventListener("pointerdown", e=>{
954
+ const h=e.target.dataset.h;
955
+ if(!h || exporting || !crop) return;
956
+ e.preventDefault();
957
+ const b=videoBox();
958
+ cropDrag={h, s:{...crop}, px:e.clientX, py:e.clientY, sx:b.w/natW, sy:b.h/natH};
959
+ $("cropLayer").setPointerCapture(e.pointerId);
960
+ });
961
+ $("cropLayer").addEventListener("pointermove", e=>{
962
+ if(!cropDrag) return;
963
+ const dx=(e.clientX-cropDrag.px)/cropDrag.sx, dy=(e.clientY-cropDrag.py)/cropDrag.sy;
964
+ const s=cropDrag.s, H=cropDrag.h, ar=cropAR;
965
+ if(H==="move"){
966
+ setCrop(s.x+dx, s.y+dy, s.w, s.h);
967
+ }else if(ar){
968
+ if(H==="n"||H==="s"){
969
+ let hh = H==="n" ? s.h-dy : s.h+dy;
970
+ hh=Math.max(16,Math.min(hh,natH)); let ww=hh*ar;
971
+ if(ww>natW){ ww=natW; hh=ww/ar; }
972
+ const cx=s.x+s.w/2, y = H==="n" ? (s.y+s.h)-hh : s.y;
973
+ setCrop(cx-ww/2, y, ww, hh);
974
+ }else if(H==="e"||H==="w"){
975
+ let ww = H==="w" ? s.w-dx : s.w+dx;
976
+ ww=Math.max(16,Math.min(ww,natW)); let hh=ww/ar;
977
+ if(hh>natH){ hh=natH; ww=hh*ar; }
978
+ const cy=s.y+s.h/2, x = H==="w" ? (s.x+s.w)-ww : s.x;
979
+ setCrop(x, cy-hh/2, ww, hh);
980
+ }else{ // corner: opposite corner stays put
981
+ const west=H.indexOf("w")>=0, north=H.indexOf("n")>=0;
982
+ const ax = west ? s.x+s.w : s.x, ay = north ? s.y+s.h : s.y;
983
+ const availW = west ? ax : natW-ax, availH = north ? ay : natH-ay;
984
+ let ww = Math.max(west ? s.w-dx : s.w+dx, (north ? s.h-dy : s.h+dy)*ar);
985
+ ww = Math.max(16, Math.min(ww, availW, availH*ar));
986
+ const hh = ww/ar;
987
+ setCrop(west ? ax-ww : ax, north ? ay-hh : ay, ww, hh);
988
+ }
989
+ }else{
990
+ let l=s.x, tp=s.y, r=s.x+s.w, bt=s.y+s.h;
991
+ if(H.indexOf("w")>=0) l=clamp(s.x+dx, 0, r-16);
992
+ if(H.indexOf("e")>=0) r=clamp(s.x+s.w+dx, l+16, natW);
993
+ if(H.indexOf("n")>=0) tp=clamp(s.y+dy, 0, bt-16);
994
+ if(H.indexOf("s")>=0) bt=clamp(s.y+s.h+dy, tp+16, natH);
995
+ setCrop(l, tp, r-l, bt-tp);
996
+ }
997
+ cropChanged(false);
998
+ });
999
+ ["pointerup","pointercancel"].forEach(ev=>$("cropLayer").addEventListener(ev, ()=>{
1000
+ if(cropDrag){ cropDrag=null; cropChanged(true); }
1001
+ }));
1002
+ window.addEventListener("resize", layoutCrop);
1003
+ if(window.ResizeObserver) new ResizeObserver(layoutCrop).observe($("stage"));
1004
+ V.addEventListener("loadeddata", layoutCrop);
1005
+
1006
+ /* ---------------- size ---------------- */
1007
+ const W=$("w"), H=$("h"), lock=$("lockAr");
1008
+ $("scaleSeg").addEventListener("click", e=>{
1009
+ const b=e.target.closest("button"); if(!b) return;
1010
+ const s=parseFloat(b.dataset.s);
1011
+ W.value=even(srcW()*s); H.value=even(srcH()*s); markScale(s); estimate();
1012
+ });
1013
+ function markScale(s){
1014
+ curScale = s;
1015
+ [...$("scaleSeg").children].forEach(b=>b.classList.toggle("on", parseFloat(b.dataset.s)===s));
1016
+ }
1017
+ W.addEventListener("input", ()=>{ if(lock.checked && srcW()) H.value=even(W.value*srcH()/srcW()); markScale(null); estimate(); });
1018
+ H.addEventListener("input", ()=>{ if(lock.checked && srcH()) W.value=even(H.value*srcW()/srcH()); markScale(null); estimate(); });
1019
+
1020
+ /* ---------------- fps ---------------- */
1021
+ function buildFpsSeg(){
1022
+ const seg=$("fpsSeg"); seg.innerHTML="";
1023
+ const opts=[Math.round(srcFps),60,30,24,15,12].filter((v,i,a)=>v<=Math.max(60,Math.round(srcFps))&&a.indexOf(v)===i);
1024
+ opts.forEach(f=>{
1025
+ const b=document.createElement("button");
1026
+ b.textContent = (f===Math.round(srcFps)? "Same ("+f+")" : f);
1027
+ b.dataset.f=f;
1028
+ b.addEventListener("click",()=>{ $("fps").value=f; markFps(); estimate(); });
1029
+ seg.appendChild(b);
1030
+ });
1031
+ markFps();
1032
+ }
1033
+ function markFps(){
1034
+ const f=+$("fps").value;
1035
+ [...$("fpsSeg").children].forEach(b=>b.classList.toggle("on", +b.dataset.f===f));
1036
+ }
1037
+ $("fps").addEventListener("input", ()=>{ markFps(); estimate(); });
1038
+
1039
+ /* ---------------- quality / estimate ---------------- */
1040
+ $("q").addEventListener("input", estimate);
1041
+ $("keepAudio").addEventListener("change", estimate);
1042
+ /* bits per pixel per frame. The browser's recorder is a realtime encoder, so it
1043
+ needs noticeably more bitrate than an offline one to look the same. At the
1044
+ 78 default this is ~7 Mbps for 720p30 and ~16 Mbps for 1080p30. */
1045
+ function qualityBpp(){
1046
+ const q=+$("q").value/100;
1047
+ return 0.035 * Math.pow(0.55/0.035, q); // 0.035 → 0.55
1048
+ }
1049
+ function targets(){
1050
+ const w=even(clamp(+W.value||srcW(),16,7680)), h=even(clamp(+H.value||srcH(),16,4320));
1051
+ const f=clamp(+$("fps").value||Math.round(srcFps),1,120);
1052
+ const bitrate=Math.round(clamp(w*h*f*qualityBpp(), 250000, 120000000));
1053
+ return {w,h,f,bitrate};
1054
+ }
1055
+ function estimate(){
1056
+ const t=targets(), n=exportList().length, len=totalLen();
1057
+ $("eSize").textContent = t.w+"×"+t.h;
1058
+ $("eRate").textContent = (t.bitrate/1e6).toFixed(2)+" Mbps";
1059
+ $("eBytesLbl").textContent = n>1 ? "Est. size, all "+n : "Est. file size";
1060
+ $("eCodec").textContent = codecLabel();
1061
+ $("eBytes").textContent = bytes(t.bitrate*len/8 + (wantAudio()?192000:0)*len/8);
1062
+ $("eTime").textContent = len<1 ? "—" : (len<60? Math.ceil(len)+" s" : Math.ceil(len/60)+" min");
1063
+ const q=+$("q").value;
1064
+ $("qHint").textContent = (q<25?"Small file — fine for quick previews"
1065
+ : q<50?"Balanced — good for email and chat"
1066
+ : q<72?"High — good for web and presentations"
1067
+ : q<90?"Very high — hard to tell from the original"
1068
+ : "Maximum — biggest file, best detail");
1069
+ $("sizeHint").textContent = (crop ? "Cropped to "+crop.w+"×"+crop.h+" (from "+natW+"×"+natH+")."
1070
+ : "Source "+natW+"×"+natH+".")+" Width and height are rounded to even numbers.";
1071
+ $("exportBtn").textContent = n>1 ? "Export "+n+" clips" : (segments.length===1 ? "Export 1 clip" : "Export clip");
1072
+ $("gifBtn").textContent = n>1 ? "Export "+n+" GIFs" : "Export as GIF";
1073
+ }
1074
+
1075
+ /* ---------------- recording engine ---------------- */
1076
+ /* H.264 High profile first — Baseline (the old default) has no CABAC and no
1077
+ B-frames, which is a big quality loss at the same bitrate. Level 5.2 so 4K
1078
+ is inside the profile limits. */
1079
+ const MIMES = [
1080
+ "video/mp4;codecs=avc1.640034,mp4a.40.2", // High 5.2
1081
+ "video/mp4;codecs=avc1.64002A,mp4a.40.2", // High 4.2
1082
+ "video/mp4;codecs=avc1.4D402A,mp4a.40.2", // Main 4.2
1083
+ "video/mp4;codecs=avc1.640034",
1084
+ "video/mp4",
1085
+ "video/webm;codecs=vp9,opus",
1086
+ "video/webm;codecs=vp9",
1087
+ "video/webm;codecs=vp8,opus",
1088
+ "video/webm"
1089
+ ];
1090
+ function pickMime(){
1091
+ for(const m of MIMES) if(window.MediaRecorder && MediaRecorder.isTypeSupported(m)) return m;
1092
+ return "";
1093
+ }
1094
+ function codecLabel(){
1095
+ const m = pickMime();
1096
+ if(!m) return "none";
1097
+ if(/avc1\.64/.test(m)) return "H.264 High";
1098
+ if(/avc1\.4D/.test(m)) return "H.264 Main";
1099
+ if(/avc1/.test(m)) return "H.264";
1100
+ if(/mp4/.test(m)) return "MP4";
1101
+ if(/vp9/.test(m)) return "VP9";
1102
+ if(/vp8/.test(m)) return "VP8";
1103
+ return m;
1104
+ }
1105
+ function wantAudio(){ const c=$("keepAudio"); return !c || c.checked; }
1106
+ function setupAudio(){
1107
+ if(audioCtx) return;
1108
+ try{
1109
+ audioCtx = new (window.AudioContext||window.webkitAudioContext)();
1110
+ mediaSrc = audioCtx.createMediaElementSource(V);
1111
+ monitorGain = audioCtx.createGain(); monitorGain.gain.value = 1;
1112
+ mediaSrc.connect(monitorGain); monitorGain.connect(audioCtx.destination);
1113
+ streamDest = audioCtx.createMediaStreamDestination();
1114
+ mediaSrc.connect(streamDest);
1115
+ }catch(e){ audioCtx=null; }
1116
+ }
1117
+
1118
+ /* records V from `a` to `z` onto the export canvas; resolves with {blob,ext,stalled,speed} */
1119
+ /* A clock that keeps ticking when the tab is in the background.
1120
+
1121
+ The bug this fixes: the whole export used to run inside requestAnimationFrame.
1122
+ Chrome stops firing rAF when a tab is hidden (or the window is fully covered),
1123
+ so the canvas was never repainted and the "we've reached the end, stop now"
1124
+ check never ran. Result: one frozen video frame plus audio, recording on until
1125
+ the source video ended. Web Audio runs on a realtime thread the browser does
1126
+ not throttle, so it drives things now; rAF and a timer are extra safety. */
1127
+ function makeClock(fn){
1128
+ const stops=[];
1129
+ try{
1130
+ if(audioCtx && audioCtx.createScriptProcessor){
1131
+ const node = audioCtx.createScriptProcessor(1024, 1, 1); // ~21 ms, ~47 Hz
1132
+ const mute = audioCtx.createGain(); mute.gain.value = 0;
1133
+ node.onaudioprocess = ()=>fn();
1134
+ node.connect(mute); mute.connect(audioCtx.destination);
1135
+ stops.push(()=>{ node.onaudioprocess=null; try{ node.disconnect(); mute.disconnect(); }catch(e){} });
1136
+ }
1137
+ }catch(e){}
1138
+ if(typeof requestAnimationFrame === "function"){
1139
+ let alive=true, raf=0;
1140
+ const loop=()=>{ if(!alive) return; fn(); raf=requestAnimationFrame(loop); };
1141
+ raf=requestAnimationFrame(loop);
1142
+ stops.push(()=>{ alive=false; try{ cancelAnimationFrame(raf); }catch(e){} });
1143
+ }
1144
+ const id=setInterval(fn, 60);
1145
+ stops.push(()=>clearInterval(id));
1146
+ return ()=>stops.forEach(f=>{ try{ f(); }catch(e){} });
1147
+ }
1148
+
1149
+ let wakeLock=null;
1150
+ async function keepAwake(on){
1151
+ try{
1152
+ if(on && navigator.wakeLock && !wakeLock){ wakeLock = await navigator.wakeLock.request("screen"); }
1153
+ else if(!on && wakeLock){ await wakeLock.release(); wakeLock=null; }
1154
+ }catch(e){ wakeLock=null; }
1155
+ }
1156
+
1157
+ async function recordRange(a, z, t, mime, ctx, cv, onProg){
1158
+ const len = Math.max(0.02, z-a);
1159
+
1160
+ // Let the canvas sample on its own clock. Driving frames by hand with
1161
+ // requestFrame() was tried and measured worse: roughly one run in three came
1162
+ // out badly short (0.85 s for a 2.00 s clip), whereas this is consistent.
1163
+ const cStream = cv.captureStream(t.f);
1164
+
1165
+ const tracks = [...cStream.getVideoTracks()];
1166
+ if(streamDest && wantAudio()) tracks.push(...streamDest.stream.getAudioTracks());
1167
+ const stream = new MediaStream(tracks);
1168
+
1169
+ let rec;
1170
+ try{ rec = new MediaRecorder(stream, {mimeType:mime, videoBitsPerSecond:t.bitrate, audioBitsPerSecond:192000}); }
1171
+ catch(e){ rec = new MediaRecorder(stream, {mimeType:mime}); }
1172
+
1173
+ const chunks=[];
1174
+ rec.ondataavailable = e => { if(e.data && e.data.size) chunks.push(e.data); };
1175
+ const stopped = new Promise(r => rec.onstop = r);
1176
+
1177
+ const paintFrame = ()=> drawSource(ctx, t.w, t.h);
1178
+
1179
+ V.currentTime = a;
1180
+ await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,5000))]);
1181
+ drawSource(ctx, t.w, t.h);
1182
+
1183
+ let stopClock=null, stopping=false, stalled=false, aborted=false;
1184
+ let wall0=0, media0=a, speed=1, pausedTotal=0, pausedAt=0, hiddenPaused=false;
1185
+ let lastT=V.currentTime, stallMs=0, prevNow=performance.now();
1186
+ const frameMs = 1000/Math.max(1,t.f);
1187
+ let nextFrameAt = 0;
1188
+ const maxMs = len*1000*3 + 8000; // a clip can never run away, whatever else breaks
1189
+
1190
+ const stop = ()=>{
1191
+ if(stopClock){ stopClock(); stopClock=null; }
1192
+ const el=(performance.now()-wall0-pausedTotal)/1000;
1193
+ if(el>0.2) speed=(V.currentTime-media0)/el;
1194
+ V.pause();
1195
+ try{ rec.stop(); }catch(e){}
1196
+ };
1197
+
1198
+ // Chrome may stop decoding video for a hidden tab, so recording while hidden
1199
+ // can't be trusted. Pause instead and pick up where we left off.
1200
+ const onVis = ()=>{
1201
+ if(stopping) return;
1202
+ if(document.hidden && !hiddenPaused){
1203
+ hiddenPaused=true; pausedAt=performance.now();
1204
+ try{ V.pause(); }catch(e){}
1205
+ try{ if(rec.state==="recording") rec.pause(); }catch(e){}
1206
+ setStatus("Paused — come back to this tab to carry on exporting");
1207
+ }else if(!document.hidden && hiddenPaused){
1208
+ hiddenPaused=false; pausedTotal += performance.now()-pausedAt;
1209
+ prevNow=performance.now(); nextFrameAt=0;
1210
+ try{ if(rec.state==="paused") rec.resume(); }catch(e){}
1211
+ V.play().catch(()=>{});
1212
+ keepAwake(true);
1213
+ }
1214
+ };
1215
+ document.addEventListener("visibilitychange", onVis);
1216
+
1217
+ const tick = ()=>{
1218
+ if(stopping || hiddenPaused) return;
1219
+ const now=performance.now();
1220
+ if(now >= nextFrameAt){
1221
+ paintFrame();
1222
+ nextFrameAt = (nextFrameAt && now - nextFrameAt < frameMs) ? nextFrameAt + frameMs : now + frameMs;
1223
+ }
1224
+ if(Math.abs(V.currentTime-lastT)>0.001){ lastT=V.currentTime; stallMs=0; } else { stallMs += now-prevNow; }
1225
+ prevNow=now;
1226
+ if(onProg) onProg(clamp((V.currentTime-a)/len,0,1), Math.max(0,len-(V.currentTime-a)));
1227
+ if(cancelExport || V.currentTime >= z-0.005 || V.ended ||
1228
+ stallMs > 10000 || (now-wall0-pausedTotal) > maxMs){
1229
+ stopping=true;
1230
+ if(cancelExport) aborted=true; // half a clip is worse than none
1231
+ if(stallMs>10000 || (now-wall0-pausedTotal)>maxMs) stalled=true;
1232
+ stop();
1233
+ }
1234
+ };
1235
+ const onEnded = ()=>{ if(!stopping){ stopping=true; stop(); } };
1236
+ V.addEventListener("ended", onEnded);
1237
+
1238
+ // start playback FIRST, then the recorder — otherwise the frozen first frame
1239
+ // gets baked into the front of the clip and the output runs long
1240
+ V.playbackRate = 1;
1241
+ try{ await V.play(); }
1242
+ catch(e){
1243
+ document.removeEventListener("visibilitychange", onVis);
1244
+ V.removeEventListener("ended",onEnded);
1245
+ try{ cStream.getTracks().forEach(x=>x.stop()); }catch(e2){}
1246
+ throw new Error("Couldn't start playback: "+e.message);
1247
+ }
1248
+ wall0 = performance.now(); media0 = V.currentTime; prevNow = wall0; nextFrameAt = 0;
1249
+ rec.start(200);
1250
+ stopClock = makeClock(tick);
1251
+
1252
+ await stopped;
1253
+ if(stopClock){ stopClock(); stopClock=null; }
1254
+ document.removeEventListener("visibilitychange", onVis);
1255
+ V.removeEventListener("ended", onEnded);
1256
+ try{ cStream.getTracks().forEach(x=>x.stop()); }catch(e){}
1257
+
1258
+ const type = mime.split(";")[0];
1259
+ return { blob:new Blob(chunks,{type}), ext:(type.indexOf("mp4")>=0?"mp4":"webm"), stalled, speed, aborted };
1260
+ }
1261
+
1262
+ /* ---------------- GIF encoder ----------------
1263
+ Written out longhand so the file stays self-contained and works offline.
1264
+ GIF is limited to 256 colours per frame, so each frame gets its own palette
1265
+ (median cut) and Floyd-Steinberg dithering to stop gradients banding. */
1266
+ const _hist=new Int32Array(32768), _rs=new Int32Array(32768), _gs=new Int32Array(32768), _bs=new Int32Array(32768);
1267
+ const _bins=new Int32Array(32768), _cache=new Int16Array(32768);
1268
+
1269
+ function gifBytes(){
1270
+ let b=new Uint8Array(1<<18), n=0;
1271
+ const grow=k=>{ if(n+k<=b.length) return; let L=b.length; while(L<n+k) L*=2;
1272
+ const t=new Uint8Array(L); t.set(b.subarray(0,n)); b=t; };
1273
+ return {
1274
+ u8(v){ grow(1); b[n++]=v&255; },
1275
+ u16(v){ grow(2); b[n++]=v&255; b[n++]=(v>>8)&255; },
1276
+ str(s){ grow(s.length); for(let i=0;i<s.length;i++) b[n++]=s.charCodeAt(i); },
1277
+ raw(a){ grow(a.length); b.set(a,n); n+=a.length; },
1278
+ size(){ return n; },
1279
+ out(){ return b.slice(0,n); }
1280
+ };
1281
+ }
1282
+
1283
+ function buildPalette(data, maxColors){
1284
+ _hist.fill(0); _rs.fill(0); _gs.fill(0); _bs.fill(0);
1285
+ for(let i=0;i<data.length;i+=4){
1286
+ const r=data[i], g=data[i+1], b=data[i+2];
1287
+ const k=((r>>3)<<10)|((g>>3)<<5)|(b>>3);
1288
+ _hist[k]++; _rs[k]+=r; _gs[k]+=g; _bs[k]+=b;
1289
+ }
1290
+ let m=0; for(let k=0;k<32768;k++) if(_hist[k]) _bins[m++]=k;
1291
+ const stat=(s,e)=>{
1292
+ let rmin=31,rmax=0,gmin=31,gmax=0,bmin=31,bmax=0;
1293
+ for(let i=s;i<e;i++){ const k=_bins[i], r=(k>>10)&31, g=(k>>5)&31, b=k&31;
1294
+ if(r<rmin)rmin=r; if(r>rmax)rmax=r;
1295
+ if(g<gmin)gmin=g; if(g>gmax)gmax=g;
1296
+ if(b<bmin)bmin=b; if(b>bmax)bmax=b; }
1297
+ const dr=rmax-rmin, dg=gmax-gmin, db=bmax-bmin;
1298
+ let chan=0, ext=dr;
1299
+ if(dg>ext){ chan=1; ext=dg; }
1300
+ if(db>ext){ chan=2; ext=db; }
1301
+ return {s,e,chan,ext};
1302
+ };
1303
+ let boxes=[stat(0,m)];
1304
+ while(boxes.length<maxColors){
1305
+ let bi=-1, best=0;
1306
+ for(let i=0;i<boxes.length;i++){ const B=boxes[i];
1307
+ if(B.e-B.s<2) continue;
1308
+ if(B.ext>best){ best=B.ext; bi=i; } }
1309
+ if(bi<0) break;
1310
+ const B=boxes[bi], shift=B.chan===0?10:B.chan===1?5:0;
1311
+ const sub=Array.from(_bins.subarray(B.s,B.e));
1312
+ sub.sort((x,y)=>(((x>>shift)&31)-((y>>shift)&31)));
1313
+ _bins.set(sub,B.s);
1314
+ let total=0; for(let i=B.s;i<B.e;i++) total+=_hist[_bins[i]];
1315
+ let acc=0, mid=B.s+1;
1316
+ for(let i=B.s;i<B.e;i++){ acc+=_hist[_bins[i]]; if(acc*2>=total){ mid=i+1; break; } }
1317
+ if(mid<=B.s) mid=B.s+1;
1318
+ if(mid>=B.e) mid=B.e-1;
1319
+ boxes.splice(bi,1,stat(B.s,mid),stat(mid,B.e));
1320
+ }
1321
+ const pal=new Uint8Array(768);
1322
+ for(let i=0;i<boxes.length;i++){
1323
+ const B=boxes[i]; let c=0,R=0,G=0,Bl=0;
1324
+ for(let x=B.s;x<B.e;x++){ const k=_bins[x]; c+=_hist[k]; R+=_rs[k]; G+=_gs[k]; Bl+=_bs[k]; }
1325
+ if(c){ pal[i*3]=Math.round(R/c); pal[i*3+1]=Math.round(G/c); pal[i*3+2]=Math.round(Bl/c); }
1326
+ }
1327
+ return {pal, count:Math.max(1,boxes.length)};
1328
+ }
1329
+
1330
+ function mapToPalette(data, w, h, pal, palCount, dither){
1331
+ const idx=new Uint8Array(w*h);
1332
+ _cache.fill(-1);
1333
+ const nearest=(r,g,b)=>{
1334
+ const key=((r>>3)<<10)|((g>>3)<<5)|(b>>3);
1335
+ const hit=_cache[key]; if(hit>=0) return hit;
1336
+ let bd=Infinity, bi=0;
1337
+ for(let i=0;i<palCount;i++){
1338
+ const dr=r-pal[i*3], dg=g-pal[i*3+1], db=b-pal[i*3+2];
1339
+ const d=dr*dr*3+dg*dg*6+db*db; // roughly luma-weighted
1340
+ if(d<bd){ bd=d; bi=i; }
1341
+ }
1342
+ _cache[key]=bi; return bi;
1343
+ };
1344
+ if(!dither){
1345
+ for(let p=0,q=0;q<idx.length;q++,p+=4) idx[q]=nearest(data[p],data[p+1],data[p+2]);
1346
+ return idx;
1347
+ }
1348
+ const buf=new Float32Array(w*h*3);
1349
+ for(let p=0,q=0;q<w*h;q++,p+=4){ buf[q*3]=data[p]; buf[q*3+1]=data[p+1]; buf[q*3+2]=data[p+2]; }
1350
+ const cl=v=>v<0?0:(v>255?255:v);
1351
+ for(let y=0;y<h;y++){
1352
+ for(let x=0;x<w;x++){
1353
+ const q=y*w+x, o=q*3;
1354
+ const r=cl(buf[o]), g=cl(buf[o+1]), b=cl(buf[o+2]);
1355
+ const i=nearest(r|0,g|0,b|0); idx[q]=i;
1356
+ const er=(r-pal[i*3])*0.75, eg=(g-pal[i*3+1])*0.75, eb=(b-pal[i*3+2])*0.75;
1357
+ if(x+1<w){ const oo=(q+1)*3; buf[oo]+=er*0.4375; buf[oo+1]+=eg*0.4375; buf[oo+2]+=eb*0.4375; }
1358
+ if(y+1<h){
1359
+ if(x>0){ const oo=(q+w-1)*3; buf[oo]+=er*0.1875; buf[oo+1]+=eg*0.1875; buf[oo+2]+=eb*0.1875; }
1360
+ { const oo=(q+w)*3; buf[oo]+=er*0.3125; buf[oo+1]+=eg*0.3125; buf[oo+2]+=eb*0.3125; }
1361
+ if(x+1<w){ const oo=(q+w+1)*3; buf[oo]+=er*0.0625; buf[oo+1]+=eg*0.0625; buf[oo+2]+=eb*0.0625; }
1362
+ }
1363
+ }
1364
+ }
1365
+ return idx;
1366
+ }
1367
+
1368
+ function lzwWrite(minCodeSize, indices, g){
1369
+ const CLEAR=1<<minCodeSize, EOI=CLEAR+1;
1370
+ let codeSize=minCodeSize+1, next=EOI+1;
1371
+ let dict=new Map(), cur=0, curBits=0;
1372
+ const block=[];
1373
+ const flush=()=>{ if(block.length){ g.u8(block.length); for(let i=0;i<block.length;i++) g.u8(block[i]); block.length=0; } };
1374
+ const emit=code=>{
1375
+ cur |= code<<curBits; curBits += codeSize;
1376
+ while(curBits>=8){ block.push(cur&255); cur>>>=8; curBits-=8; if(block.length===255) flush(); }
1377
+ };
1378
+ g.u8(minCodeSize);
1379
+ emit(CLEAR);
1380
+ let prefix=indices[0];
1381
+ for(let i=1;i<indices.length;i++){
1382
+ const k=indices[i], key=prefix*256+k, found=dict.get(key);
1383
+ if(found!==undefined){ prefix=found; continue; }
1384
+ emit(prefix);
1385
+ if(next===4096){
1386
+ emit(CLEAR); dict=new Map(); next=EOI+1; codeSize=minCodeSize+1;
1387
+ }else{
1388
+ // grow the code width BEFORE claiming the code, so the decoder — which
1389
+ // builds its table one code behind — switches width at the same place
1390
+ if(next >= (1<<codeSize) && codeSize<12) codeSize++;
1391
+ dict.set(key,next); next++;
1392
+ }
1393
+ prefix=k;
1394
+ }
1395
+ emit(prefix); emit(EOI);
1396
+ if(curBits>0){ block.push(cur&255); if(block.length===255) flush(); }
1397
+ flush();
1398
+ g.u8(0);
1399
+ }
1400
+
1401
+ function whileVisible(){
1402
+ if(!document.hidden) return Promise.resolve();
1403
+ setStatus("Paused — come back to this tab to carry on");
1404
+ return new Promise(res=>{
1405
+ const h=()=>{ if(!document.hidden){ document.removeEventListener("visibilitychange",h); res(); } };
1406
+ document.addEventListener("visibilitychange",h);
1407
+ });
1408
+ }
1409
+
1410
+ /* Renders by seeking frame by frame rather than playing in real time, so it is
1411
+ exact and doesn't care how fast the machine is. */
1412
+ async function renderGif(a, z, t, ctx, cv, onProg){
1413
+ const len=Math.max(0.02, z-a);
1414
+ const delay=Math.max(2, Math.round(100/Math.min(20, t.f))); // GIF delays are in 1/100 s
1415
+ const w=t.w, h=t.h;
1416
+ const n=Math.max(1, Math.min(900, Math.round(len*100/delay)));
1417
+ const g=gifBytes();
1418
+ g.str("GIF89a"); g.u16(w); g.u16(h); g.u8(0x70); g.u8(0); g.u8(0);
1419
+ g.u8(0x21); g.u8(0xFF); g.u8(11); g.str("NETSCAPE2.0"); g.u8(3); g.u8(1); g.u16(0); g.u8(0); // loop forever
1420
+
1421
+ let aborted=false, t0=performance.now();
1422
+ for(let i=0;i<n;i++){
1423
+ if(cancelExport){ aborted=true; break; }
1424
+ await whileVisible();
1425
+ V.currentTime = Math.min(z-0.001, a + i*delay/100);
1426
+ await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,3000))]);
1427
+ drawSource(ctx, w, h);
1428
+ const img=ctx.getImageData(0,0,w,h);
1429
+ const {pal,count}=buildPalette(img.data, 256);
1430
+ const idx=mapToPalette(img.data, w, h, pal, count, true);
1431
+ g.u8(0x21); g.u8(0xF9); g.u8(4); g.u8(0x04); g.u16(delay); g.u8(0); g.u8(0);
1432
+ g.u8(0x2C); g.u16(0); g.u16(0); g.u16(w); g.u16(h); g.u8(0x87);
1433
+ g.raw(pal);
1434
+ lzwWrite(8, idx, g);
1435
+ if(onProg){
1436
+ const per=(performance.now()-t0)/(i+1)/1000;
1437
+ onProg((i+1)/n, Math.max(0,(n-i-1)*per));
1438
+ }
1439
+ if((i&1)===0) await new Promise(r=>setTimeout(r,0)); // keep the page responsive
1440
+ }
1441
+ g.u8(0x3B);
1442
+ return { blob:new Blob([g.out()],{type:"image/gif"}), ext:"gif", stalled:false, speed:1, aborted,
1443
+ frames:n, fps:Math.round(1000/delay)/10 };
1444
+ }
1445
+
1446
+ /* ---------------- export ---------------- */
1447
+ $("exportBtn").addEventListener("click", ()=>doExport("video"));
1448
+ $("gifBtn").addEventListener("click", ()=>doExport("gif"));
1449
+ $("stopBtn").addEventListener("click", ()=>{ cancelExport=true; setStatus("Stopping…"); });
1450
+
1451
+ async function doExport(mode){
1452
+ if(exporting || !dur) return;
1453
+ const isGif = mode === "gif";
1454
+ const t = targets();
1455
+ const list = exportList().filter(s => s.end - s.start >= 0.05);
1456
+ if(!list.length){ setStatus("Selection is too short."); return; }
1457
+ const multi = list.length > 1;
1458
+ const mime = isGif ? "image/gif" : pickMime();
1459
+ if(!mime){ setStatus("This browser can't record video. Try Chrome or Edge."); return; }
1460
+
1461
+ if(isGif){ // GIFs balloon quickly — say so before spending the time
1462
+ const gfps = Math.min(20, t.f);
1463
+ const frames = Math.round(list.reduce((x,sg)=>x+(sg.end-sg.start),0) * gfps);
1464
+ if(t.w*t.h*frames > 90e6 &&
1465
+ !confirm("That's "+frames+" frames at "+t.w+"×"+t.h+", which will make a very large GIF and take a while.\n\nA smaller width or fewer frames per second would help.\n\nCarry on anyway?")) return;
1466
+ }
1467
+
1468
+ // several files → put them in a folder of your choosing (must happen on the click)
1469
+ let dirHandle = null;
1470
+ if(multi && window.showDirectoryPicker){
1471
+ try{
1472
+ dirHandle = await window.showDirectoryPicker({id:"nugget-clips", mode:"readwrite", startIn:"videos"});
1473
+ }catch(e){
1474
+ if(e && e.name === "AbortError"){ setStatus("Export cancelled — no folder chosen."); return; }
1475
+ dirHandle = null; // not supported here; fall back to downloads
1476
+ }
1477
+ }
1478
+
1479
+ exporting=true; cancelExport=false;
1480
+ clearResult(); clearSaved();
1481
+ $("exportBtn").disabled=true; $("gifBtn").disabled=true;
1482
+ $("exportBtn").textContent = isGif ? "Building GIF…" : "Exporting…";
1483
+ $("stopBtn").style.display="block";
1484
+ $("expNote").style.display="block";
1485
+ $("bar").style.display="block"; $("barI").style.width="0%";
1486
+ V.pause();
1487
+
1488
+ const cv=$("exportCanvas"); cv.width=t.w; cv.height=t.h;
1489
+ const ctx=cv.getContext("2d",{alpha:false});
1490
+ ctx.imageSmoothingEnabled=true; ctx.imageSmoothingQuality="high";
1491
+ ctx.fillStyle="#000"; ctx.fillRect(0,0,t.w,t.h);
1492
+ V.style.display="none"; cv.style.display="block"; $("cropLayer").style.display="none";
1493
+
1494
+ setupAudio();
1495
+ if(audioCtx && audioCtx.state==="suspended"){ try{ await audioCtx.resume(); }catch(e){} }
1496
+ if(monitorGain) monitorGain.gain.value = 0;
1497
+ keepAwake(true);
1498
+
1499
+ const total = list.reduce((a,s)=>a+(s.end-s.start),0);
1500
+ let doneLen = 0, saved = [], slow = false, cut = false, failed = 0;
1501
+
1502
+ try{
1503
+ for(let i=0;i<list.length;i++){
1504
+ if(cancelExport) break;
1505
+ const s = list[i];
1506
+ const len = s.end - s.start;
1507
+ const label = multi ? "Clip "+(i+1)+" of "+list.length+" · " : "";
1508
+
1509
+ const onProg = (p, left)=>{
1510
+ const overall = (doneLen + p*len)/total;
1511
+ $("barI").style.width=(overall*100).toFixed(1)+"%";
1512
+ setStatus(label+(isGif?"building GIF ":"recording ")+Math.round(p*100)+"% · about "+Math.ceil(left)+"s left");
1513
+ };
1514
+ const r = isGif ? await renderGif(s.start, s.end, t, ctx, cv, onProg)
1515
+ : await recordRange(s.start, s.end, t, mime, ctx, cv, onProg);
1516
+ doneLen += len;
1517
+ lastExt = r.ext;
1518
+ if(r.stalled) cut = true;
1519
+ if(!r.stalled && r.speed < 0.9) slow = true;
1520
+
1521
+ if(r.aborted) break; // stopped part-way through this clip — discard it
1522
+ if(!r.blob.size){ failed++; continue; }
1523
+
1524
+ const fname = clipFileName(i, s, t, multi);
1525
+ if(dirHandle){
1526
+ setStatus(label+"saving…");
1527
+ try{
1528
+ const fh = await dirHandle.getFileHandle(fname, {create:true});
1529
+ const ws = await fh.createWritable();
1530
+ await ws.write(r.blob); await ws.close();
1531
+ saved.push(fname+" ("+bytes(r.blob.size)+")");
1532
+ }catch(e){ failed++; saved.push(fname+" — could not be written: "+e.message); }
1533
+ }else if(multi){
1534
+ pushDownload(r.blob, fname);
1535
+ saved.push(fname+" ("+bytes(r.blob.size)+")");
1536
+ await new Promise(r2=>setTimeout(r2,400)); // let the browser keep up
1537
+ }else{
1538
+ lastBlob = r.blob;
1539
+ lastMeta = {w:t.w, h:t.h, f:t.f, at:s.start, name:s.name};
1540
+ const url = URL.createObjectURL(lastBlob);
1541
+ if(isGif){ $("outImg").src=url; $("outImg").style.display="block"; $("outVid").style.display="none"; }
1542
+ else { $("outVid").src=url; $("outVid").style.display="block"; $("outImg").style.display="none"; }
1543
+ $("result").style.display="block";
1544
+ const n = download();
1545
+ saved.push((n||fname)+" ("+bytes(r.blob.size)+")");
1546
+ }
1547
+ }
1548
+ }catch(err){
1549
+ setStatus(err.message);
1550
+ }finally{
1551
+ exporting=false;
1552
+ if(monitorGain) monitorGain.gain.value=1;
1553
+ cv.style.display="none"; V.style.display="block";
1554
+ if(crop){ showCrop(true); layoutCrop(); }
1555
+ $("exportBtn").disabled=false; $("gifBtn").disabled=false; $("stopBtn").style.display="none";
1556
+ $("expNote").style.display="none";
1557
+ $("bar").style.display="none";
1558
+ keepAwake(false);
1559
+ V.currentTime=inT;
1560
+ estimate();
1561
+ }
1562
+
1563
+ // ---- report ----
1564
+ const notes=[];
1565
+ if(lastExt==="webm" && !isGif) notes.push("Saved as .webm — this browser can't record MP4. Plays in Chrome, Edge, Firefox and VLC.");
1566
+ if(cut) notes.push("Playback stalled on at least one clip, so it may be cut short.");
1567
+ if(slow && !isGif) notes.push("Your computer couldn't play the video at full speed, so clips may run slightly slow. Try a smaller output size or lower quality.");
1568
+ if(failed) notes.push(failed+" clip(s) could not be saved.");
1569
+
1570
+ if(multi){
1571
+ $("saved").style.display = saved.length ? "block" : "none";
1572
+ $("savedWhere").textContent = cancelExport
1573
+ ? "Stopped — "+saved.length+" of "+list.length+" saved"
1574
+ : "Saved "+saved.length+" clip"+(saved.length===1?"":"s")+(dirHandle? " to “"+dirHandle.name+"”" : " to your Downloads folder");
1575
+ $("savedList").innerHTML="";
1576
+ saved.forEach(n=>{ const li=document.createElement("li"); li.textContent=n; $("savedList").appendChild(li); });
1577
+ if(!dirHandle && saved.length>1) notes.push("Chrome asks permission the first time a page saves several files — choose Allow if you see that prompt.");
1578
+ $("savedNote").textContent = notes.join(" ");
1579
+ setStatus(cancelExport ? "Stopped." : "Done — "+saved.length+" clip"+(saved.length===1?"":"s")+".");
1580
+ }else{
1581
+ $("outNote").textContent = notes.join(" ");
1582
+ setStatus(cancelExport ? "Stopped." : (saved[0] ? "Saved "+saved[0] : "Nothing was saved."));
1583
+ }
1584
+ }
1585
+
1586
+ function clipFileName(i, s, t, multi){
1587
+ const base = safeName(srcName,60) || "clip";
1588
+ if(lastExt==="gif"){
1589
+ const lbl0 = safeName(s.name,40);
1590
+ return base+"_"+(multi? String(i+1).padStart(2,"0")+"_" : "")+(lbl0 || stamp(s.start))+"_"+t.w+"px.gif";
1591
+ }
1592
+ if(!multi) return base+"_"+stamp(s.start)+"_"+t.w+"x"+t.h+"_"+t.f+"fps."+lastExt;
1593
+ const lbl = safeName(s.name,40);
1594
+ return base+"_"+String(i+1).padStart(2,"0")+"_"+(lbl || stamp(s.start))+"."+lastExt;
1595
+ }
1596
+ function pushDownload(blob, name){
1597
+ try{
1598
+ const a=document.createElement("a");
1599
+ a.href=URL.createObjectURL(blob); a.download=name; a.style.display="none";
1600
+ document.body.appendChild(a); a.click();
1601
+ setTimeout(()=>{ URL.revokeObjectURL(a.href); a.remove(); }, 12000);
1602
+ return name;
1603
+ }catch(e){ return null; }
1604
+ }
1605
+ function download(){
1606
+ if(!lastBlob || !lastBlob.size) return null;
1607
+ const m = lastMeta || Object.assign(targets(), {at:inT, name:""});
1608
+ const base = safeName(srcName,60) || "clip";
1609
+ const lbl = safeName(m.name,40);
1610
+ const name = lastExt==="gif"
1611
+ ? base+"_"+(lbl || stamp(m.at))+"_"+m.w+"px.gif"
1612
+ : base+"_"+(lbl || stamp(m.at))+"_"+m.w+"x"+m.h+"_"+m.f+"fps."+lastExt;
1613
+ return pushDownload(lastBlob, name);
1614
+ }
1615
+ $("dlBtn").addEventListener("click", ()=>{ download(); });
1616
+ $("clearRes").addEventListener("click", clearResult);
1617
+ function clearResult(){
1618
+ lastBlob=null; lastMeta=null; $("result").style.display="none";
1619
+ const ov=$("outVid"); if(ov.src){ URL.revokeObjectURL(ov.src); ov.removeAttribute("src"); }
1620
+ const oi=$("outImg"); if(oi.src){ URL.revokeObjectURL(oi.src); oi.removeAttribute("src"); }
1621
+ setStatus("");
1622
+ }
1623
+ function clearSaved(){ $("saved").style.display="none"; $("savedList").innerHTML=""; $("savedNote").textContent=""; }
1624
+ function setStatus(s){ $("status").textContent=s; }
1625
+
1626
+ window.__vt = {
1627
+ get state(){ return {ready:$("app").style.display==="block",loads:loadSeq,dur,inT,outT,natW,natH,srcFps,
1628
+ exporting,size:lastBlob&&lastBlob.size,ext:lastExt,
1629
+ clips:segments.map(s=>({start:+s.start.toFixed(3),end:+s.end.toFixed(3),name:s.name}))}; },
1630
+ load, doExport, addClip,
1631
+ gif(){ return doExport("gif"); },
1632
+ set(a,b){ inT=a; outT=b; refresh(); },
1633
+ setCrop(x,y,w,h){ setCrop(x,y,w,h); showCrop(true); cropChanged(true); },
1634
+ getCrop(){ return crop && {...crop}; },
1635
+ setAR(v,l){ applyAR(v, l||String(v)); },
1636
+ arLabel(){ return cropARLabel; },
1637
+ setName(i,n){ segments[i].name=n; refresh(); },
1638
+ clearClips(){ segments=[]; activeSeg=-1; refresh(); }
1639
+ };
1640
+ })();
1641
+ </script>
1642
+ </body>
1643
+ </html>