Video_Tools / Nugget Video Trimmer v1.6.html
PoopMan333's picture
Upload Nugget Video Trimmer v1.6.html
9fcd033 verified
Raw
History Blame
75.6 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nugget Video Trimmer</title>
<style>
:root{
--bg:#0e1116; --panel:#161b22; --panel2:#1c232d; --line:#2a323d;
--txt:#e6edf3; --dim:#8b98a5; --accent:#4cc2ff; --accent2:#2a9fd6;
--ok:#3fb950; --warn:#d29922; --danger:#f85149;
--r:10px;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%}
body{
background:var(--bg); color:var(--txt);
font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
-webkit-font-smoothing:antialiased;
}
.wrap{max-width:1180px;margin:0 auto;padding:20px 20px 60px}
header{display:flex;align-items:center;gap:12px;margin-bottom:18px}
header h1{font-size:17px;margin:0;font-weight:600;letter-spacing:.2px}
header .sub{color:var(--dim);font-size:12.5px}
header .ver{color:var(--dim);font-size:12px;font-variant-numeric:tabular-nums;
border:1px solid var(--line);border-radius:99px;padding:3px 10px;background:var(--panel)}
.spacer{flex:1}
button{
font:inherit;color:var(--txt);background:var(--panel2);border:1px solid var(--line);
padding:7px 13px;border-radius:8px;cursor:pointer;transition:.12s;
}
button:hover:not(:disabled){background:#242d39;border-color:#3a4553}
button:disabled{opacity:.4;cursor:not-allowed}
button.primary{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
button.primary:hover:not(:disabled){background:#6bcfff}
button.ghost{background:transparent}
button.danger{color:#ffb4ae;border-color:#5a2b2b}
button.danger:hover:not(:disabled){background:#341c1c;border-color:#7a3a3a}
.icobtn{padding:7px 11px;font-variant-numeric:tabular-nums}
.small{padding:5px 10px;font-size:12.5px}
/* ---------- drop zone ---------- */
#drop{
border:2px dashed var(--line);border-radius:14px;padding:64px 24px;text-align:center;
background:var(--panel);cursor:pointer;transition:.15s;
}
#drop:hover,#drop.over{border-color:var(--accent);background:#12212b}
#drop h2{margin:0 0 6px;font-size:18px;font-weight:600}
#drop p{margin:0;color:var(--dim);font-size:13px}
#drop .big{font-size:38px;line-height:1;margin-bottom:14px;opacity:.65}
/* ---------- layout ---------- */
#app{display:none}
.grid{display:grid;grid-template-columns:1fr 316px;gap:18px;align-items:start}
@media(max-width:900px){.grid{grid-template-columns:1fr}}
.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:14px}
.card h3{margin:0 0 12px;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim);font-weight:600}
.stage{background:#000;border-radius:var(--r);overflow:hidden;display:flex;align-items:center;justify-content:center;position:relative;border:1px solid var(--line)}
.stage video,.stage canvas{max-width:100%;max-height:56vh;display:block}
#exportCanvas{display:none}
.badge{position:absolute;top:10px;left:10px;z-index:3;background:rgba(0,0,0,.66);backdrop-filter:blur(4px);
padding:4px 9px;border-radius:6px;font-size:11.5px;color:#cfe;letter-spacing:.3px}
/* ---------- crop overlay ---------- */
#cropLayer{position:absolute;display:none;touch-action:none;z-index:2}
#cropBox{position:absolute;box-shadow:0 0 0 9999px rgba(4,7,11,.62);
border:1px solid rgba(255,255,255,.92);cursor:move;box-sizing:border-box}
#cropBox::after{content:"";position:absolute;inset:0;pointer-events:none;
background:
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)),
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));}
.ch{position:absolute;width:16px;height:16px;background:#fff;border:1px solid rgba(0,0,0,.65);border-radius:3px;z-index:2}
.ch:hover{background:var(--accent)}
.ch[data-h=nw]{left:-8px;top:-8px;cursor:nwse-resize}
.ch[data-h=ne]{right:-8px;top:-8px;cursor:nesw-resize}
.ch[data-h=sw]{left:-8px;bottom:-8px;cursor:nesw-resize}
.ch[data-h=se]{right:-8px;bottom:-8px;cursor:nwse-resize}
.ch[data-h=n]{left:calc(50% - 8px);top:-8px;cursor:ns-resize}
.ch[data-h=s]{left:calc(50% - 8px);bottom:-8px;cursor:ns-resize}
.ch[data-h=w]{left:-8px;top:calc(50% - 8px);cursor:ew-resize}
.ch[data-h=e]{right:-8px;top:calc(50% - 8px);cursor:ew-resize}
.cropdims{position:absolute;left:50%;transform:translateX(-50%);bottom:5px;
background:rgba(0,0,0,.75);color:#dff;padding:2px 8px;border-radius:5px;
font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none}
#cropBtn.on{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
#cropBtn.on .kbd{background:rgba(0,0,0,.15);border-color:rgba(0,0,0,.25);color:#04121c}
.arlab{color:var(--dim);font-size:11px;text-transform:uppercase;letter-spacing:.6px;margin:2px 0 5px}
.arRow{margin-bottom:8px}
.arcustom{display:flex;align-items:center;gap:6px;margin-bottom:4px}
.arcustom input{width:100%;min-width:0;text-align:center}
.arcustom span{color:var(--dim)}
.arcustom.on input{border-color:var(--accent)}
/* ---------- transport ---------- */
.transport{display:flex;align-items:center;gap:8px;margin-top:12px;flex-wrap:wrap}
.tc{font-variant-numeric:tabular-nums;font-size:13px;color:var(--dim)}
.tc b{color:var(--txt);font-weight:600}
/* ---------- timeline ---------- */
.tl-wrap{margin-top:14px;user-select:none}
.tl{position:relative;height:70px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;overflow:hidden;touch-action:none;cursor:pointer}
#strip{position:absolute;inset:0;display:flex;opacity:.9}
#strip canvas{height:100%;flex:1 1 0;min-width:0;object-fit:cover}
.mask{position:absolute;top:0;bottom:0;background:rgba(6,9,13,.72);pointer-events:none}
.sel{position:absolute;top:0;bottom:0;border-left:2px solid var(--accent);border-right:2px solid var(--accent);
box-shadow:inset 0 0 0 1px rgba(76,194,255,.25);pointer-events:none}
.handle{position:absolute;top:0;bottom:0;width:16px;margin-left:-8px;cursor:ew-resize;touch-action:none;z-index:5}
.handle::after{content:"";position:absolute;left:5px;top:50%;transform:translateY(-50%);
width:6px;height:26px;border-radius:3px;background:var(--accent);box-shadow:0 0 0 1px rgba(0,0,0,.4)}
.handle:hover::after{background:#8bd8ff}
.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)}
.ruler{display:flex;justify-content:space-between;margin-top:5px;color:var(--dim);font-size:11px;font-variant-numeric:tabular-nums}
/* saved clips drawn along the bottom of the timeline */
#segBand{position:absolute;left:0;right:0;bottom:0;height:16px;pointer-events:none;z-index:4}
.segbar{position:absolute;bottom:0;height:16px;min-width:3px;background:rgba(63,185,80,.42);
border:1px solid rgba(63,185,80,.95);border-radius:3px;overflow:hidden;
font-size:9.5px;line-height:14px;text-align:center;color:#dfffe6;font-weight:600}
.segbar.on{background:rgba(76,194,255,.5);border-color:#8bd8ff;color:#eaf7ff}
.marks{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;align-items:center}
.pill{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:12.5px;font-variant-numeric:tabular-nums}
.pill span{color:var(--dim)}
.pill b{font-weight:600}
.pill.dur b{color:var(--accent)}
.edit{cursor:text;border-bottom:1px dotted #4a5663;padding-bottom:1px}
.edit:hover{border-bottom-color:var(--accent);color:var(--accent)}
.edit input{width:88px;padding:0 3px;border:1px solid var(--accent);border-radius:4px;
background:#0b0f14;color:var(--txt);font:inherit;font-weight:600;text-align:center}
/* ---------- clip list ---------- */
#clipsWrap{display:none;margin-top:18px}
.clips-head{display:flex;align-items:center;gap:10px;margin-bottom:8px}
.clips-head h3{margin:0;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim);font-weight:600}
#clipList{border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel)}
.crow{display:flex;align-items:center;gap:10px;padding:7px 10px;border-top:1px solid var(--line);font-size:12.5px}
.crow:first-child{border-top:none}
.crow:hover{background:var(--panel2)}
.crow.on{background:#12212b;box-shadow:inset 2px 0 0 var(--accent)}
.cnum{width:20px;color:var(--dim);font-variant-numeric:tabular-nums;flex:none}
.cname{flex:1 1 90px;min-width:60px;max-width:230px}
.cname input{width:100%;background:transparent;border:1px solid transparent;border-radius:6px;
padding:2px 6px;color:var(--txt);font:inherit}
.cname input:hover{border-color:var(--line)}
.cname input:focus{outline:none;border-color:var(--accent);background:#0b0f14}
.cname input::placeholder{color:#5a6572}
.ctimes{font-variant-numeric:tabular-nums;color:var(--dim);flex:none}
.ctimes b{color:var(--txt);font-weight:600}
.cdur{font-variant-numeric:tabular-nums;color:var(--accent);font-weight:600;width:64px;text-align:right;flex:none}
.cbtns{display:flex;gap:4px;flex:none}
.cbtns button{padding:3px 8px;font-size:11.5px;border-radius:6px}
@media(max-width:760px){ .ctimes{display:none} }
/* ---------- settings ---------- */
.row{display:flex;align-items:center;gap:8px;margin-bottom:10px}
.row label{flex:0 0 78px;color:var(--dim);font-size:12.5px}
input[type=text],input[type=number],select{
font:inherit;background:var(--panel2);color:var(--txt);border:1px solid var(--line);
border-radius:7px;padding:6px 8px;width:100%;min-width:0;
}
input:focus,select:focus{outline:none;border-color:var(--accent)}
input[type=range]{width:100%;accent-color:var(--accent)}
.seg{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px}
.seg button{padding:5px 9px;font-size:12.5px;border-radius:7px}
.seg button.on{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
.hint{color:var(--dim);font-size:11.5px;margin:-4px 0 12px}
.chk{display:flex;align-items:center;gap:7px;color:var(--dim);font-size:12.5px;margin-bottom:10px;cursor:pointer}
hr{border:none;border-top:1px solid var(--line);margin:14px 0}
.est{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:9px 11px;font-size:12.5px;margin-bottom:12px}
.est div{display:flex;justify-content:space-between;margin:2px 0}
.est span{color:var(--dim)}
.est b{font-variant-numeric:tabular-nums;font-weight:600}
#exportBtn{width:100%;padding:11px}
#gifBtn{width:100%;padding:9px;margin-top:8px}
#stopBtn{width:100%;padding:9px;margin-top:8px;display:none}
.bar{height:6px;background:var(--panel2);border-radius:99px;overflow:hidden;margin-top:10px;display:none}
.bar i{display:block;height:100%;width:0;background:var(--accent);transition:width .2s}
#status{font-size:12px;color:var(--dim);margin-top:8px;text-align:center;min-height:16px}
#result{display:none;margin-top:14px}
#result video{width:100%;border-radius:8px;background:#000;border:1px solid var(--line)}
#saved{display:none;margin-top:14px;border:1px solid var(--line);border-radius:8px;background:var(--panel2);padding:10px 12px}
#saved h4{margin:0 0 6px;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim)}
#savedList{margin:0;padding-left:16px;font-size:12px;color:var(--txt);line-height:1.7;max-height:190px;overflow:auto}
.note{font-size:11.5px;color:var(--warn);margin-top:8px;line-height:1.4}
.kbd{display:inline-block;background:var(--panel2);border:1px solid var(--line);border-bottom-width:2px;
border-radius:5px;padding:0 5px;font-size:11px;font-family:ui-monospace,Menlo,Consolas,monospace}
.keys{color:var(--dim);font-size:11.5px;margin-top:12px;line-height:1.9}
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>Nugget Video Trimmer</h1>
<span class="sub">trim &middot; resize &middot; fps &middot; quality</span>
<span class="spacer"></span>
<button id="newBtn" class="ghost" style="display:none">Load another video</button>
<span class="ver">v1.6</span>
</header>
<div id="drop">
<div class="big">&#9634;</div>
<h2>Drop a video here</h2>
<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>
<input type="file" id="file" accept="video/*" hidden>
</div>
<div id="app">
<div class="grid">
<!-- LEFT -->
<div>
<div class="stage" id="stage">
<video id="video" playsinline></video>
<canvas id="exportCanvas"></canvas>
<div id="cropLayer">
<div id="cropBox" data-h="move">
<span class="ch" data-h="nw"></span><span class="ch" data-h="n"></span><span class="ch" data-h="ne"></span>
<span class="ch" data-h="w"></span><span class="ch" data-h="e"></span>
<span class="ch" data-h="sw"></span><span class="ch" data-h="s"></span><span class="ch" data-h="se"></span>
<span class="cropdims" id="cropDims"></span>
</div>
</div>
<div class="badge" id="srcBadge"></div>
</div>
<div class="transport">
<button id="playBtn" class="icobtn" title="Play / pause (Space)">&#9654;</button>
<button id="prevF" class="icobtn" title="Previous frame (&larr;)">&#8676;</button>
<button id="nextF" class="icobtn" title="Next frame (&rarr;)">&#8677;</button>
<span class="tc"><b id="curTime">0:00.00</b> / <span id="totTime">0:00.00</span></span>
<span class="spacer"></span>
<button id="cropBtn" title="Show or hide the crop box (C)">Crop &nbsp;<span class="kbd">C</span></button>
<button id="setIn">Set start &nbsp;<span class="kbd">I</span></button>
<button id="setOut">Set end &nbsp;<span class="kbd">O</span></button>
<button id="loopBtn" class="ghost" title="Loop the selection">Loop: off</button>
</div>
<div class="tl-wrap">
<div class="tl" id="tl">
<div id="strip"></div>
<div class="mask" id="maskL"></div>
<div class="mask" id="maskR"></div>
<div class="sel" id="sel"></div>
<div id="segBand"></div>
<div class="playhead" id="ph"></div>
<div class="handle" id="hIn"></div>
<div class="handle" id="hOut"></div>
</div>
<div class="ruler"><span>0:00</span><span id="rulMid"></span><span id="rulEnd"></span></div>
<div class="marks">
<span class="pill"><span>Start</span> <b id="pIn" class="edit" title="Click to type an exact time">0:00.00</b></span>
<span class="pill"><span>End</span> <b id="pOut" class="edit" title="Click to type an exact time">0:00.00</b></span>
<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>
<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>
<button id="resetSel" class="ghost small">Reset to full clip</button>
</div>
<div class="keys">
<span class="kbd">Space</span> play/pause &nbsp; <span class="kbd">&larr;</span><span class="kbd">&rarr;</span> step 1 frame &nbsp;
<span class="kbd">Shift</span>+<span class="kbd">&larr;</span><span class="kbd">&rarr;</span> step 1 sec &nbsp;
<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
<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>).
</div>
<!-- clip list: only appears once you add something -->
<div id="clipsWrap">
<div class="clips-head">
<h3 id="clipsTitle">Clip list</h3>
<span class="spacer"></span>
<button id="clearClips" class="ghost small">Clear all</button>
</div>
<div id="clipList"></div>
<div class="hint" style="margin-top:8px">
Export uses this list — the timeline selection is only used for adding new clips.
Use ▶ to preview a clip, Set to overwrite it with the current timeline selection, ✕ to remove it. Click its times to type exact values.
Names are optional and become the file name.
</div>
</div>
</div>
</div>
<!-- RIGHT -->
<div>
<div class="card">
<div id="cropSection" style="display:none">
<h3>Crop &amp; aspect ratio</h3>
<div class="seg arRow">
<button data-ar="0" data-lbl="free">Free</button>
<button data-ar="src" data-lbl="original">Original</button>
<button data-ar="1" data-lbl="1:1">1:1 square</button>
</div>
<div class="arlab">Landscape</div>
<div class="seg arRow">
<button data-ar="2.33333" data-lbl="21:9">21:9</button>
<button data-ar="1.77778" data-lbl="16:9">16:9</button>
<button data-ar="1.5" data-lbl="3:2">3:2</button>
<button data-ar="1.33333" data-lbl="4:3">4:3</button>
</div>
<div class="arlab">Portrait</div>
<div class="seg arRow">
<button data-ar="0.5625" data-lbl="9:16">9:16</button>
<button data-ar="0.5" data-lbl="1:2">1:2</button>
<button data-ar="0.66667" data-lbl="2:3">2:3</button>
<button data-ar="0.75" data-lbl="3:4">3:4</button>
<button data-ar="0.8" data-lbl="4:5">4:5</button>
</div>
<div class="arlab">Custom</div>
<div class="arcustom" id="arCustom">
<input type="number" id="arW" min="1" max="9999" step="1" placeholder="9">
<span>:</span>
<input type="number" id="arH" min="1" max="9999" step="1" placeholder="16">
<button id="arApply" class="small">Use</button>
</div>
<div class="hint" id="cropInfo" style="margin:8px 0"></div>
<button id="cropMax" class="small" style="width:100%">Biggest box that fits</button>
<hr>
</div>
<h3>Size</h3>
<div class="seg" id="scaleSeg">
<button data-s="1">100%</button>
<button data-s="0.75">75%</button>
<button data-s="0.5">50%</button>
<button data-s="0.25">25%</button>
</div>
<div class="row">
<label>Width</label><input type="number" id="w" min="16" step="2">
</div>
<div class="row">
<label>Height</label><input type="number" id="h" min="16" step="2">
</div>
<label class="chk"><input type="checkbox" id="lockAr" checked> Lock aspect ratio</label>
<div class="hint" id="sizeHint"></div>
<hr>
<h3>Frame rate</h3>
<div class="seg" id="fpsSeg"></div>
<div class="row">
<label>Custom</label><input type="number" id="fps" min="1" max="120" step="1">
</div>
<div class="hint">Higher than the source frame rate won't add detail.</div>
<hr>
<h3>Quality</h3>
<input type="range" id="q" min="0" max="100" value="78">
<div class="hint" id="qHint"></div>
<label class="chk"><input type="checkbox" id="keepAudio" checked> Include audio</label>
<div class="est">
<div><span>Output</span><b id="eSize"></b></div>
<div><span>Bitrate</span><b id="eRate"></b></div>
<div><span>Encoder</span><b id="eCodec"></b></div>
<div><span id="eBytesLbl">Est. file size</span><b id="eBytes"></b></div>
<div><span>Export takes about</span><b id="eTime"></b></div>
</div>
<button id="exportBtn" class="primary">Export clip</button>
<button id="gifBtn">Export as GIF</button>
<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>
<button id="stopBtn" class="danger">Stop</button>
<div class="bar" id="bar"><i id="barI"></i></div>
<div id="status"></div>
<div class="hint" id="expNote" style="display:none;margin:8px 0 0;text-align:center">
Leave this tab on screen — if you switch away, the export pauses and picks up when you come back.
</div>
<div id="result">
<video id="outVid" controls></video>
<img id="outImg" alt="" style="display:none;width:100%;border-radius:8px;background:#000;border:1px solid var(--line)">
<div style="display:flex;gap:8px;margin-top:10px">
<button id="dlBtn" class="primary" style="flex:1">Download again</button>
<button id="clearRes" class="ghost">Clear</button>
</div>
<div class="note" id="outNote"></div>
</div>
<div id="saved">
<h4 id="savedWhere">Saved</h4>
<ol id="savedList"></ol>
<div class="note" id="savedNote"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
"use strict";
(function(){
/* ---------------- helpers ---------------- */
const $ = id => document.getElementById(id);
const clamp = (v,a,b) => Math.min(b, Math.max(a, v));
function tc(t, frac){ // 1:23.45 / 1:05:03.20
if(!isFinite(t)||t<0) t=0;
const h = Math.floor(t/3600);
const m = Math.floor((t-h*3600)/60), s = t - h*3600 - m*60;
const mm = h ? String(m).padStart(2,"0") : String(m);
const hh = h ? h+":" : "";
return frac===false ? hh+mm+":"+String(Math.floor(s)).padStart(2,"0")
: hh+mm+":"+(s<10?"0":"")+s.toFixed(2);
}
function stamp(t){ t=Math.max(0,t||0); return Math.floor(t/60)+"m"+String(Math.floor(t%60)).padStart(2,"0")+"s"; }
function bytes(n){
if(!isFinite(n)) return "—";
if(n < 1024*1024) return (n/1024).toFixed(0)+" KB";
if(n < 1024*1024*1024) return (n/1048576).toFixed(1)+" MB";
return (n/1073741824).toFixed(2)+" GB";
}
function even(n){ n = Math.round(n); return n%2 ? n+1 : n; }
function safeName(s, n){ return String(s||"").replace(/[\\/:*?"<>|\x00-\x1f]+/g,"-").replace(/^\.+/,"").trim().slice(0,n||60); }
function once(el,ev){ return new Promise(r=>el.addEventListener(ev,r,{once:true})); }
/* ---------------- state ---------------- */
const V = $("video");
let srcUrl=null, srcName="clip", dur=0, natW=0, natH=0, srcFps=30;
let inT=0, outT=0, looping=false, dragging=null, exporting=false, cancelExport=false;
let audioCtx=null, mediaSrc=null, monitorGain=null, streamDest=null;
let lastBlob=null, lastExt="webm", lastMeta=null;
let segments=[], activeSeg=-1, segId=0;
/* ---------------- file loading ---------------- */
const drop=$("drop"), fileInput=$("file");
fileInput.addEventListener("click", e=>e.stopPropagation());
drop.addEventListener("click", ()=>fileInput.click());
fileInput.addEventListener("change", e=>{ if(e.target.files[0]) load(e.target.files[0]); e.target.value=""; });
["dragenter","dragover"].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.add("over")}));
["dragleave","drop"].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.remove("over")}));
// ONE drop handler only, on the window — two handlers meant a drop started the load twice
window.addEventListener("dragover", e=>e.preventDefault());
window.addEventListener("drop", e=>{
e.preventDefault(); drop.classList.remove("over");
const f = e.dataTransfer && e.dataTransfer.files[0];
if(f) load(f);
});
$("newBtn").addEventListener("click", ()=>fileInput.click());
const DROP_HTML = drop.innerHTML;
let loadSeq = 0; // only the newest load() is allowed to touch the UI
let loadedOnce = false;
async function load(file){
if(exporting){ alert("Hang on until the export finishes, then load the next video."); return; }
if(segments.length && loadedOnce &&
!confirm("Loading a new video clears the clip list ("+segments.length+" clips). Continue?")) return;
const myId = ++loadSeq;
const newUrl = URL.createObjectURL(file);
const prevUrl = srcUrl;
const bail = (msg)=>{
URL.revokeObjectURL(newUrl);
if(myId !== loadSeq) return; // a newer load took over — stay quiet
srcUrl = prevUrl;
if(loadedOnce){ // don't destroy a session that's already open
if(V.src !== prevUrl && prevUrl){ V.src = prevUrl; }
alert(msg+"\n\nYour current video is still open.");
}else{
drop.innerHTML = DROP_HTML; drop.style.display="block"; $("app").style.display="none";
alert(msg);
}
};
srcName = (file.name||"clip").replace(/\.[^.]+$/,"") || "clip";
srcUrl = newUrl;
clearResult(); clearSaved();
V.src = newUrl;
V.muted = false;
const how = await new Promise(res=>{
let settled=false, timer=0;
const done = v => { if(settled) return; settled=true; clearTimeout(timer);
V.onloadedmetadata=null; V.onerror=null; res(v); };
V.onloadedmetadata = ()=>done("ok");
V.onerror = ()=>done("err");
timer = setTimeout(()=>done("slow"), 120000);
});
if(myId !== loadSeq){ URL.revokeObjectURL(newUrl); return; }
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).");
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.");
dur = V.duration;
if(!isFinite(dur) || dur<=0){ // some WebM/MKV files report no duration until you seek past the end
try{
V.currentTime = 1e7;
await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,2500))]);
dur = isFinite(V.duration) ? V.duration : V.currentTime;
V.currentTime = 0;
await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,1500))]);
}catch(e){}
}
if(myId !== loadSeq){ URL.revokeObjectURL(newUrl); return; }
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.");
if(prevUrl) URL.revokeObjectURL(prevUrl); // safe now: the new file is definitely in
natW = V.videoWidth || 640; natH = V.videoHeight || 360;
inT = 0; outT = dur;
segments = []; activeSeg = -1;
removeCrop();
if(!loadedOnce) drop.innerHTML = '<div class="big">&#9634;</div><h2>Reading video…</h2><p>one moment</p>';
srcFps = 30;
await detectFps();
if(myId !== loadSeq) return;
loadedOnce = true;
drop.style.display="none"; $("app").style.display="block"; $("newBtn").style.display="inline-block";
$("w").value = natW; $("h").value = natH;
$("totTime").textContent = tc(dur);
$("rulEnd").textContent = tc(dur,false);
$("rulMid").textContent = tc(dur/2,false);
buildFpsSeg();
$("fps").value = Math.round(srcFps);
$("srcBadge").textContent = natW+"×"+natH+" · "+Math.round(srcFps)+" fps · "+tc(dur,false);
document.title = srcName+" — Nugget Video Trimmer";
markScale(1);
refresh(); update();
buildStrip(newUrl, myId);
}
/* estimate source fps by counting presented frames over a short muted sample */
async function detectFps(){
if(!("requestVideoFrameCallback" in HTMLVideoElement.prototype)) return;
const prevMuted = V.muted;
V.muted = true;
let stop = false;
try{
V.currentTime = Math.min(0.2, dur/4);
await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,1500))]);
let first=null, last=null, n=0;
const done = new Promise(res=>{
const finish = ()=>{ stop=true; res(); };
const cb=(now,md)=>{
if(stop) return;
if(first===null) first=md.mediaTime; else { last=md.mediaTime; n++; }
if(n>=12 || (last!==null && last-first>0.5)) return finish();
V.requestVideoFrameCallback(cb);
};
V.requestVideoFrameCallback(cb);
setTimeout(finish, 1400); // rVFC never fired (or is throttled) — give up
});
await V.play().catch(()=>{});
await done;
if(n>2 && last>first){
const f = n/(last-first);
if(f>4 && f<125) srcFps = Math.round(f*100)/100;
}
}catch(e){}
stop = true;
try{ V.pause(); }catch(e){}
V.muted = prevMuted;
V.currentTime = 0;
await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,800))]);
}
/* ---------------- filmstrip ---------------- */
async function buildStrip(url, id){
const strip=$("strip"); strip.innerHTML="";
const N=12, tw=160, th=90, total=dur;
const v=document.createElement("video");
v.src=url; v.muted=true; v.playsInline=true;
try{
await Promise.race([once(v,"loadeddata"), once(v,"error"), new Promise(r=>setTimeout(r,15000))]);
}catch(e){ return; }
for(let i=0;i<N;i++){
if(id !== loadSeq){ v.removeAttribute("src"); return; }
const c=document.createElement("canvas"); c.width=tw; c.height=th;
strip.appendChild(c);
try{
v.currentTime = Math.min(total-0.03, (i+0.5)*total/N);
await Promise.race([once(v,"seeked"), new Promise(r=>setTimeout(r,1500))]);
c.getContext("2d").drawImage(v,0,0,tw,th);
}catch(e){}
}
v.removeAttribute("src");
}
/* ---------------- transport ---------------- */
$("playBtn").addEventListener("click", togglePlay);
function togglePlay(){
if(exporting) return;
if(V.paused){ if(V.currentTime<inT-0.01||V.currentTime>=outT-0.01) V.currentTime=inT; V.play(); }
else V.pause();
}
V.addEventListener("play", ()=>$("playBtn").innerHTML="&#10073;&#10073;");
V.addEventListener("pause",()=>$("playBtn").innerHTML="&#9654;");
V.addEventListener("timeupdate", update);
V.addEventListener("seeked", update);
function rafLoop(){
if(!V.paused && !exporting){
if(V.currentTime>=outT-0.02){ if(looping){ V.currentTime=inT; } else { V.pause(); V.currentTime=outT; } }
update();
}
requestAnimationFrame(rafLoop);
}
requestAnimationFrame(rafLoop);
$("prevF").addEventListener("click", ()=>step(-1));
$("nextF").addEventListener("click", ()=>step(1));
function step(dir, big){
V.pause();
const d = big ? 1 : 1/(srcFps||30);
V.currentTime = clamp(V.currentTime + dir*d, 0, dur);
}
/* Setting a start later than the current end used to clamp the start back onto
the end. Marking a new clip after the previous one is the normal way to work,
so the other mark gets out of the way instead. */
function setIn(t){
inT = clamp(t, 0, Math.max(0, dur-0.02));
if(outT <= inT + 0.02) outT = dur; // start moved past the end — open the end up
refresh();
}
function setOut(t){
outT = clamp(t, 0.02, dur);
if(inT >= outT - 0.02) inT = 0; // end moved before the start — open the start up
refresh();
}
$("setIn").addEventListener("click", ()=>setIn(V.currentTime));
$("setOut").addEventListener("click", ()=>setOut(V.currentTime));
$("resetSel").addEventListener("click", ()=>{ inT=0; outT=dur; refresh(); });
$("loopBtn").addEventListener("click", e=>{ looping=!looping; e.target.textContent="Loop: "+(looping?"on":"off"); e.target.classList.toggle("ghost",!looping); });
/* ---------------- click-to-type time fields ---------------- */
function parseTime(s){ // "1:23.4", "0:05", "83.4", "1:02:03"
s = String(s).trim(); if(!s) return null;
const parts = s.split(":").map(x=>parseFloat(x));
if(parts.some(x=>isNaN(x))) return null;
return parts.reduce((a,x)=>a*60+x, 0);
}
function makeTimeEditor(el, get, set){
el.addEventListener("click", function(e){
e.stopPropagation();
if(exporting || el.querySelector("input")) return;
const inp = document.createElement("input");
inp.value = tc(get()); el.textContent=""; el.appendChild(inp);
inp.focus(); inp.select();
let done=false;
const commit = ok => {
if(done) return; done=true;
const v = ok ? parseTime(inp.value) : null;
inp.remove();
if(v !== null && isFinite(v)) set(v);
refresh();
};
inp.addEventListener("blur", ()=>commit(true));
inp.addEventListener("click", ev=>ev.stopPropagation());
inp.addEventListener("keydown", ev=>{
ev.stopPropagation();
if(ev.key==="Enter"){ ev.preventDefault(); commit(true); }
if(ev.key==="Escape"){ ev.preventDefault(); commit(false); }
});
});
}
makeTimeEditor($("pIn"), ()=>inT, v=>{ setIn(v); V.currentTime=inT; });
makeTimeEditor($("pOut"), ()=>outT, v=>{ setOut(v); V.currentTime=outT; });
makeTimeEditor($("pDur"), ()=>outT-inT, v=>{
const len = clamp(v, 0.02, dur);
if(inT + len <= dur){ outT = inT + len; }
else { outT = dur; inT = Math.max(0, dur - len); }
V.currentTime = inT;
});
document.addEventListener("keydown", e=>{
if(exporting) return;
const t=e.target.tagName;
if(t==="INPUT"||t==="SELECT"||t==="TEXTAREA") return;
const k=e.key;
if(k===" "){ e.preventDefault(); togglePlay(); }
else if(k==="ArrowLeft"){ e.preventDefault(); step(-1, e.shiftKey); }
else if(k==="ArrowRight"){ e.preventDefault(); step(1, e.shiftKey); }
else if(k==="i"||k==="I"){ setIn(V.currentTime); }
else if(k==="o"||k==="O"){ setOut(V.currentTime); }
else if(k==="a"||k==="A"){ e.preventDefault(); addClip(); }
else if(k==="c"||k==="C"){ e.preventDefault(); toggleCrop(); }
else if(k==="Home"){ V.currentTime=inT; }
else if(k==="End"){ V.currentTime=outT; }
});
/* ---------------- timeline drag ---------------- */
const tl=$("tl");
function posToTime(clientX){
const r=tl.getBoundingClientRect();
return clamp((clientX-r.left)/r.width,0,1)*dur;
}
tl.addEventListener("pointerdown", e=>{
if(exporting||!dur) return;
if(e.target===$("hIn")) dragging="in";
else if(e.target===$("hOut")) dragging="out";
else { dragging="seek"; V.pause(); V.currentTime=posToTime(e.clientX); }
tl.setPointerCapture(e.pointerId);
});
tl.addEventListener("pointermove", e=>{
if(!dragging) return;
const t=posToTime(e.clientX);
if(dragging==="in"){ inT=clamp(t,0,outT-0.02); V.currentTime=inT; }
else if(dragging==="out"){ outT=clamp(t,inT+0.02,dur); V.currentTime=outT; }
else V.currentTime=t;
refresh();
});
["pointerup","pointercancel"].forEach(ev=>tl.addEventListener(ev,()=>dragging=null));
function refresh(){
const a = dur? inT/dur*100 : 0, b = dur? outT/dur*100 : 100;
$("maskL").style.left="0"; $("maskL").style.width=a+"%";
$("maskR").style.left=b+"%"; $("maskR").style.width=(100-b)+"%";
$("sel").style.left=a+"%"; $("sel").style.width=(b-a)+"%";
$("hIn").style.left=a+"%"; $("hOut").style.left=b+"%";
if(activeSeg>=0){ // highlight only while the selection still matches
const sg=segments[activeSeg];
if(!sg || Math.abs(sg.start-inT)>0.001 || Math.abs(sg.end-outT)>0.001) activeSeg=-1;
}
if(!$("pIn").querySelector("input")) $("pIn").textContent=tc(inT);
if(!$("pOut").querySelector("input")) $("pOut").textContent=tc(outT);
if(!$("pDur").querySelector("input")) $("pDur").textContent=tc(outT-inT);
renderClips(); renderBand(); estimate();
}
function update(){
$("curTime").textContent=tc(V.currentTime);
$("ph").style.left=(dur? V.currentTime/dur*100 : 0)+"%";
}
/* ---------------- clip list ---------------- */
$("addClip").addEventListener("click", addClip);
function addClip(){
if(exporting || !dur) return;
if(outT - inT < 0.05){ setStatus("Selection is too short to add."); return; }
segments.push({id:++segId, start:inT, end:outT, name:""});
activeSeg = segments.length-1;
setStatus("");
refresh();
}
$("clearClips").addEventListener("click", ()=>{
if(exporting || !segments.length) return;
if(segments.length>1 && !confirm("Remove all "+segments.length+" clips from the list?")) return;
segments=[]; activeSeg=-1; refresh();
});
function renderClips(){
const wrap=$("clipsWrap"), list=$("clipList");
wrap.style.display = segments.length ? "block" : "none";
$("clipsTitle").textContent = "Clip list ("+segments.length+")";
if(!segments.length){ list.innerHTML=""; return; }
if(list.querySelector("input:focus")) return; // don't yank a field being typed in
list.innerHTML="";
segments.forEach((s,i)=>{
const row=document.createElement("div");
row.className="crow"+(i===activeSeg?" on":"");
const num=document.createElement("span"); num.className="cnum"; num.textContent=(i+1);
const nameWrap=document.createElement("span"); nameWrap.className="cname";
const name=document.createElement("input");
name.type="text"; name.value=s.name||""; name.placeholder="name (optional)"; name.maxLength=40;
name.addEventListener("input", ()=>{ s.name=name.value; });
name.addEventListener("keydown", ev=>{ ev.stopPropagation(); if(ev.key==="Enter") name.blur(); });
name.addEventListener("click", ev=>ev.stopPropagation());
nameWrap.appendChild(name);
const times=document.createElement("span"); times.className="ctimes";
const bS=document.createElement("b"); bS.className="edit"; bS.textContent=tc(s.start);
const bE=document.createElement("b"); bE.className="edit"; bE.textContent=tc(s.end);
times.appendChild(bS); times.appendChild(document.createTextNode(" → ")); times.appendChild(bE);
makeTimeEditor(bS, ()=>s.start, v=>{ s.start = clamp(v, 0, s.end-0.02); });
makeTimeEditor(bE, ()=>s.end, v=>{ s.end = clamp(v, s.start+0.02, dur); });
const d=document.createElement("span"); d.className="cdur"; d.textContent=tc(s.end-s.start);
const btns=document.createElement("span"); btns.className="cbtns";
const prev=document.createElement("button");
prev.textContent="▶"; prev.title="Load this clip onto the timeline and play it";
prev.addEventListener("click", ev=>{ ev.stopPropagation();
if(exporting) return;
activeSeg=i; inT=s.start; outT=s.end; V.currentTime=s.start; refresh();
V.play().catch(()=>{}); });
const use=document.createElement("button");
use.textContent="Set"; use.title="Replace this clip's start and end with the current timeline selection";
use.addEventListener("click", ev=>{ ev.stopPropagation();
if(exporting) return;
s.start=inT; s.end=outT; activeSeg=i; refresh(); });
const del=document.createElement("button");
del.textContent="✕"; del.title="Remove this clip"; del.className="danger";
del.addEventListener("click", ev=>{ ev.stopPropagation();
if(exporting) return;
segments.splice(i,1);
if(activeSeg>=segments.length) activeSeg=segments.length-1;
refresh(); });
btns.appendChild(prev); btns.appendChild(use); btns.appendChild(del);
row.appendChild(num); row.appendChild(nameWrap); row.appendChild(times);
row.appendChild(d); row.appendChild(btns);
row.addEventListener("click", ()=>{ // preview this clip on the timeline
if(exporting) return;
activeSeg=i; inT=s.start; outT=s.end; V.currentTime=s.start; refresh();
});
list.appendChild(row);
});
}
function renderBand(){
const band=$("segBand"); band.innerHTML="";
if(!dur) return;
segments.forEach((s,i)=>{
const el=document.createElement("div");
el.className="segbar"+(i===activeSeg?" on":"");
el.style.left=(s.start/dur*100)+"%";
el.style.width=Math.max(0.4,(s.end-s.start)/dur*100)+"%";
el.textContent=(i+1);
band.appendChild(el);
});
}
/* the list is what gets exported; with an empty list it's just the selection */
function exportList(){
return segments.length ? segments.map(s=>({start:s.start,end:s.end,name:s.name}))
: [{start:inT,end:outT,name:""}];
}
function totalLen(){ return exportList().reduce((a,s)=>a+Math.max(0,s.end-s.start),0); }
/* ---------------- crop ----------------
Held in source pixels so it survives any output size change. Everything that
sizes the output asks srcW()/srcH() rather than the video's own dimensions. */
let crop=null, cropAR=0, cropARLabel="free", curScale=1;
function srcW(){ return crop ? crop.w : natW; }
function srcH(){ return crop ? crop.h : natH; }
function drawSource(dctx, dw, dh){
dctx.imageSmoothingEnabled=true; dctx.imageSmoothingQuality="high";
if(crop) dctx.drawImage(V, crop.x, crop.y, crop.w, crop.h, 0, 0, dw, dh);
else dctx.drawImage(V, 0, 0, dw, dh);
}
function videoBox(){
const st=$("stage").getBoundingClientRect(), v=V.getBoundingClientRect();
return {left:v.left-st.left, top:v.top-st.top, w:v.width, h:v.height};
}
function layoutCrop(){
if(!crop || !natW) return;
const L=$("cropLayer"), b=videoBox();
if(!b.w || !b.h) return;
L.style.left=b.left+"px"; L.style.top=b.top+"px";
L.style.width=b.w+"px"; L.style.height=b.h+"px";
const sx=b.w/natW, sy=b.h/natH, B=$("cropBox");
B.style.left=(crop.x*sx)+"px"; B.style.top=(crop.y*sy)+"px";
B.style.width=(crop.w*sx)+"px"; B.style.height=(crop.h*sy)+"px";
$("cropDims").textContent = Math.round(crop.w)+" × "+Math.round(crop.h);
}
function cropChanged(finalise){
if(crop){
crop.x=Math.max(0,Math.round(crop.x)); crop.y=Math.max(0,Math.round(crop.y));
crop.w=Math.min(Math.round(crop.w), natW-crop.x);
crop.h=Math.min(Math.round(crop.h), natH-crop.y);
}
layoutCrop();
$("cropInfo").textContent = crop
? "Keeping "+crop.w+" × "+crop.h+" ("+cropARLabel+") out of "+natW+" × "+natH+" · drag the box or its handles"
: "";
if(finalise){ // only resize the output once the drag ends
if(curScale){ W.value=even(srcW()*curScale); H.value=even(srcH()*curScale); markScale(curScale); }
else if(lock.checked){ H.value=even((+W.value||srcW())*srcH()/srcW()); }
}
estimate();
}
function setCrop(x,y,w,h){
w=Math.max(16,Math.min(w,natW)); h=Math.max(16,Math.min(h,natH));
crop={x:clamp(x,0,natW-w), y:clamp(y,0,natH-h), w, h};
}
function snapToAR(ar){
if(!ar || !crop) return;
const cx=crop.x+crop.w/2, cy=crop.y+crop.h/2;
let w=Math.min(natW, Math.max(crop.w, crop.h*ar)), h=w/ar;
if(h>natH){ h=natH; w=h*ar; }
setCrop(cx-w/2, cy-h/2, w, h);
}
function biggestFit(ar){
let w=natW, h=natW/(ar||natW/natH);
if(h>natH){ h=natH; w=h*(ar||natW/natH); }
setCrop((natW-w)/2, (natH-h)/2, w, h);
}
function showCrop(on){
$("cropLayer").style.display = on ? "block" : "none";
$("cropSection").style.display = on ? "block" : "none";
$("cropBtn").classList.toggle("on", on);
}
$("cropBtn").addEventListener("click", toggleCrop);
function toggleCrop(){
if(exporting || !dur) return;
if(crop){ removeCrop(); return; }
if(cropAR) biggestFit(cropAR);
else setCrop(natW*0.1, natH*0.1, natW*0.8, natH*0.8);
showCrop(true); markAR(); cropChanged(true);
}
function removeCrop(){
crop=null; cropAR=0; cropARLabel="free";
showCrop(false);
if(curScale){ W.value=even(natW*curScale); H.value=even(natH*curScale); markScale(curScale); }
$("cropInfo").textContent="";
estimate();
}
$("cropMax").addEventListener("click", ()=>{ if(!crop) return; biggestFit(cropAR||natW/natH); cropChanged(true); });
function applyAR(ar, label){
cropAR = ar; cropARLabel = label;
markAR();
if(cropAR) snapToAR(cropAR);
cropChanged(true);
}
document.querySelectorAll(".arRow").forEach(row=>{
row.addEventListener("click", e=>{
const b=e.target.closest("button"); if(!b || !crop) return;
const v=b.dataset.ar;
applyAR(v==="src" ? natW/natH : parseFloat(v), v==="src" ? "original" : b.dataset.lbl);
});
});
function useCustomAR(){
if(!crop) return;
const a=+$("arW").value, b=+$("arH").value;
if(!(a>0) || !(b>0)){ $("arW").focus(); return; }
applyAR(a/b, a+":"+b);
}
$("arApply").addEventListener("click", useCustomAR);
["arW","arH"].forEach(id=>$(id).addEventListener("keydown", e=>{
e.stopPropagation();
if(e.key==="Enter"){ e.preventDefault(); useCustomAR(); }
}));
function markAR(){
let matched=false;
document.querySelectorAll(".arRow button").forEach(b=>{
const v=b.dataset.ar, val = v==="src" ? (natW/natH) : parseFloat(v);
const on = (!cropAR && v==="0") || (cropAR>0 && Math.abs(val-cropAR) < 0.004);
b.classList.toggle("on", on);
if(on) matched=true;
});
$("arCustom").classList.toggle("on", !matched && cropAR>0);
}
let cropDrag=null;
$("cropLayer").addEventListener("pointerdown", e=>{
const h=e.target.dataset.h;
if(!h || exporting || !crop) return;
e.preventDefault();
const b=videoBox();
cropDrag={h, s:{...crop}, px:e.clientX, py:e.clientY, sx:b.w/natW, sy:b.h/natH};
$("cropLayer").setPointerCapture(e.pointerId);
});
$("cropLayer").addEventListener("pointermove", e=>{
if(!cropDrag) return;
const dx=(e.clientX-cropDrag.px)/cropDrag.sx, dy=(e.clientY-cropDrag.py)/cropDrag.sy;
const s=cropDrag.s, H=cropDrag.h, ar=cropAR;
if(H==="move"){
setCrop(s.x+dx, s.y+dy, s.w, s.h);
}else if(ar){
if(H==="n"||H==="s"){
let hh = H==="n" ? s.h-dy : s.h+dy;
hh=Math.max(16,Math.min(hh,natH)); let ww=hh*ar;
if(ww>natW){ ww=natW; hh=ww/ar; }
const cx=s.x+s.w/2, y = H==="n" ? (s.y+s.h)-hh : s.y;
setCrop(cx-ww/2, y, ww, hh);
}else if(H==="e"||H==="w"){
let ww = H==="w" ? s.w-dx : s.w+dx;
ww=Math.max(16,Math.min(ww,natW)); let hh=ww/ar;
if(hh>natH){ hh=natH; ww=hh*ar; }
const cy=s.y+s.h/2, x = H==="w" ? (s.x+s.w)-ww : s.x;
setCrop(x, cy-hh/2, ww, hh);
}else{ // corner: opposite corner stays put
const west=H.indexOf("w")>=0, north=H.indexOf("n")>=0;
const ax = west ? s.x+s.w : s.x, ay = north ? s.y+s.h : s.y;
const availW = west ? ax : natW-ax, availH = north ? ay : natH-ay;
let ww = Math.max(west ? s.w-dx : s.w+dx, (north ? s.h-dy : s.h+dy)*ar);
ww = Math.max(16, Math.min(ww, availW, availH*ar));
const hh = ww/ar;
setCrop(west ? ax-ww : ax, north ? ay-hh : ay, ww, hh);
}
}else{
let l=s.x, tp=s.y, r=s.x+s.w, bt=s.y+s.h;
if(H.indexOf("w")>=0) l=clamp(s.x+dx, 0, r-16);
if(H.indexOf("e")>=0) r=clamp(s.x+s.w+dx, l+16, natW);
if(H.indexOf("n")>=0) tp=clamp(s.y+dy, 0, bt-16);
if(H.indexOf("s")>=0) bt=clamp(s.y+s.h+dy, tp+16, natH);
setCrop(l, tp, r-l, bt-tp);
}
cropChanged(false);
});
["pointerup","pointercancel"].forEach(ev=>$("cropLayer").addEventListener(ev, ()=>{
if(cropDrag){ cropDrag=null; cropChanged(true); }
}));
window.addEventListener("resize", layoutCrop);
if(window.ResizeObserver) new ResizeObserver(layoutCrop).observe($("stage"));
V.addEventListener("loadeddata", layoutCrop);
/* ---------------- size ---------------- */
const W=$("w"), H=$("h"), lock=$("lockAr");
$("scaleSeg").addEventListener("click", e=>{
const b=e.target.closest("button"); if(!b) return;
const s=parseFloat(b.dataset.s);
W.value=even(srcW()*s); H.value=even(srcH()*s); markScale(s); estimate();
});
function markScale(s){
curScale = s;
[...$("scaleSeg").children].forEach(b=>b.classList.toggle("on", parseFloat(b.dataset.s)===s));
}
W.addEventListener("input", ()=>{ if(lock.checked && srcW()) H.value=even(W.value*srcH()/srcW()); markScale(null); estimate(); });
H.addEventListener("input", ()=>{ if(lock.checked && srcH()) W.value=even(H.value*srcW()/srcH()); markScale(null); estimate(); });
/* ---------------- fps ---------------- */
function buildFpsSeg(){
const seg=$("fpsSeg"); seg.innerHTML="";
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);
opts.forEach(f=>{
const b=document.createElement("button");
b.textContent = (f===Math.round(srcFps)? "Same ("+f+")" : f);
b.dataset.f=f;
b.addEventListener("click",()=>{ $("fps").value=f; markFps(); estimate(); });
seg.appendChild(b);
});
markFps();
}
function markFps(){
const f=+$("fps").value;
[...$("fpsSeg").children].forEach(b=>b.classList.toggle("on", +b.dataset.f===f));
}
$("fps").addEventListener("input", ()=>{ markFps(); estimate(); });
/* ---------------- quality / estimate ---------------- */
$("q").addEventListener("input", estimate);
$("keepAudio").addEventListener("change", estimate);
/* bits per pixel per frame. The browser's recorder is a realtime encoder, so it
needs noticeably more bitrate than an offline one to look the same. At the
78 default this is ~7 Mbps for 720p30 and ~16 Mbps for 1080p30. */
function qualityBpp(){
const q=+$("q").value/100;
return 0.035 * Math.pow(0.55/0.035, q); // 0.035 → 0.55
}
function targets(){
const w=even(clamp(+W.value||srcW(),16,7680)), h=even(clamp(+H.value||srcH(),16,4320));
const f=clamp(+$("fps").value||Math.round(srcFps),1,120);
const bitrate=Math.round(clamp(w*h*f*qualityBpp(), 250000, 120000000));
return {w,h,f,bitrate};
}
function estimate(){
const t=targets(), n=exportList().length, len=totalLen();
$("eSize").textContent = t.w+"×"+t.h;
$("eRate").textContent = (t.bitrate/1e6).toFixed(2)+" Mbps";
$("eBytesLbl").textContent = n>1 ? "Est. size, all "+n : "Est. file size";
$("eCodec").textContent = codecLabel();
$("eBytes").textContent = bytes(t.bitrate*len/8 + (wantAudio()?192000:0)*len/8);
$("eTime").textContent = len<1 ? "—" : (len<60? Math.ceil(len)+" s" : Math.ceil(len/60)+" min");
const q=+$("q").value;
$("qHint").textContent = (q<25?"Small file — fine for quick previews"
: q<50?"Balanced — good for email and chat"
: q<72?"High — good for web and presentations"
: q<90?"Very high — hard to tell from the original"
: "Maximum — biggest file, best detail");
$("sizeHint").textContent = (crop ? "Cropped to "+crop.w+"×"+crop.h+" (from "+natW+"×"+natH+")."
: "Source "+natW+"×"+natH+".")+" Width and height are rounded to even numbers.";
$("exportBtn").textContent = n>1 ? "Export "+n+" clips" : (segments.length===1 ? "Export 1 clip" : "Export clip");
$("gifBtn").textContent = n>1 ? "Export "+n+" GIFs" : "Export as GIF";
}
/* ---------------- recording engine ---------------- */
/* H.264 High profile first — Baseline (the old default) has no CABAC and no
B-frames, which is a big quality loss at the same bitrate. Level 5.2 so 4K
is inside the profile limits. */
const MIMES = [
"video/mp4;codecs=avc1.640034,mp4a.40.2", // High 5.2
"video/mp4;codecs=avc1.64002A,mp4a.40.2", // High 4.2
"video/mp4;codecs=avc1.4D402A,mp4a.40.2", // Main 4.2
"video/mp4;codecs=avc1.640034",
"video/mp4",
"video/webm;codecs=vp9,opus",
"video/webm;codecs=vp9",
"video/webm;codecs=vp8,opus",
"video/webm"
];
function pickMime(){
for(const m of MIMES) if(window.MediaRecorder && MediaRecorder.isTypeSupported(m)) return m;
return "";
}
function codecLabel(){
const m = pickMime();
if(!m) return "none";
if(/avc1\.64/.test(m)) return "H.264 High";
if(/avc1\.4D/.test(m)) return "H.264 Main";
if(/avc1/.test(m)) return "H.264";
if(/mp4/.test(m)) return "MP4";
if(/vp9/.test(m)) return "VP9";
if(/vp8/.test(m)) return "VP8";
return m;
}
function wantAudio(){ const c=$("keepAudio"); return !c || c.checked; }
function setupAudio(){
if(audioCtx) return;
try{
audioCtx = new (window.AudioContext||window.webkitAudioContext)();
mediaSrc = audioCtx.createMediaElementSource(V);
monitorGain = audioCtx.createGain(); monitorGain.gain.value = 1;
mediaSrc.connect(monitorGain); monitorGain.connect(audioCtx.destination);
streamDest = audioCtx.createMediaStreamDestination();
mediaSrc.connect(streamDest);
}catch(e){ audioCtx=null; }
}
/* records V from `a` to `z` onto the export canvas; resolves with {blob,ext,stalled,speed} */
/* A clock that keeps ticking when the tab is in the background.
The bug this fixes: the whole export used to run inside requestAnimationFrame.
Chrome stops firing rAF when a tab is hidden (or the window is fully covered),
so the canvas was never repainted and the "we've reached the end, stop now"
check never ran. Result: one frozen video frame plus audio, recording on until
the source video ended. Web Audio runs on a realtime thread the browser does
not throttle, so it drives things now; rAF and a timer are extra safety. */
function makeClock(fn){
const stops=[];
try{
if(audioCtx && audioCtx.createScriptProcessor){
const node = audioCtx.createScriptProcessor(1024, 1, 1); // ~21 ms, ~47 Hz
const mute = audioCtx.createGain(); mute.gain.value = 0;
node.onaudioprocess = ()=>fn();
node.connect(mute); mute.connect(audioCtx.destination);
stops.push(()=>{ node.onaudioprocess=null; try{ node.disconnect(); mute.disconnect(); }catch(e){} });
}
}catch(e){}
if(typeof requestAnimationFrame === "function"){
let alive=true, raf=0;
const loop=()=>{ if(!alive) return; fn(); raf=requestAnimationFrame(loop); };
raf=requestAnimationFrame(loop);
stops.push(()=>{ alive=false; try{ cancelAnimationFrame(raf); }catch(e){} });
}
const id=setInterval(fn, 60);
stops.push(()=>clearInterval(id));
return ()=>stops.forEach(f=>{ try{ f(); }catch(e){} });
}
let wakeLock=null;
async function keepAwake(on){
try{
if(on && navigator.wakeLock && !wakeLock){ wakeLock = await navigator.wakeLock.request("screen"); }
else if(!on && wakeLock){ await wakeLock.release(); wakeLock=null; }
}catch(e){ wakeLock=null; }
}
async function recordRange(a, z, t, mime, ctx, cv, onProg){
const len = Math.max(0.02, z-a);
// Let the canvas sample on its own clock. Driving frames by hand with
// requestFrame() was tried and measured worse: roughly one run in three came
// out badly short (0.85 s for a 2.00 s clip), whereas this is consistent.
const cStream = cv.captureStream(t.f);
const tracks = [...cStream.getVideoTracks()];
if(streamDest && wantAudio()) tracks.push(...streamDest.stream.getAudioTracks());
const stream = new MediaStream(tracks);
let rec;
try{ rec = new MediaRecorder(stream, {mimeType:mime, videoBitsPerSecond:t.bitrate, audioBitsPerSecond:192000}); }
catch(e){ rec = new MediaRecorder(stream, {mimeType:mime}); }
const chunks=[];
rec.ondataavailable = e => { if(e.data && e.data.size) chunks.push(e.data); };
const stopped = new Promise(r => rec.onstop = r);
const paintFrame = ()=> drawSource(ctx, t.w, t.h);
V.currentTime = a;
await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,5000))]);
drawSource(ctx, t.w, t.h);
let stopClock=null, stopping=false, stalled=false, aborted=false;
let wall0=0, media0=a, speed=1, pausedTotal=0, pausedAt=0, hiddenPaused=false;
let lastT=V.currentTime, stallMs=0, prevNow=performance.now();
const frameMs = 1000/Math.max(1,t.f);
let nextFrameAt = 0;
const maxMs = len*1000*3 + 8000; // a clip can never run away, whatever else breaks
const stop = ()=>{
if(stopClock){ stopClock(); stopClock=null; }
const el=(performance.now()-wall0-pausedTotal)/1000;
if(el>0.2) speed=(V.currentTime-media0)/el;
V.pause();
try{ rec.stop(); }catch(e){}
};
// Chrome may stop decoding video for a hidden tab, so recording while hidden
// can't be trusted. Pause instead and pick up where we left off.
const onVis = ()=>{
if(stopping) return;
if(document.hidden && !hiddenPaused){
hiddenPaused=true; pausedAt=performance.now();
try{ V.pause(); }catch(e){}
try{ if(rec.state==="recording") rec.pause(); }catch(e){}
setStatus("Paused — come back to this tab to carry on exporting");
}else if(!document.hidden && hiddenPaused){
hiddenPaused=false; pausedTotal += performance.now()-pausedAt;
prevNow=performance.now(); nextFrameAt=0;
try{ if(rec.state==="paused") rec.resume(); }catch(e){}
V.play().catch(()=>{});
keepAwake(true);
}
};
document.addEventListener("visibilitychange", onVis);
const tick = ()=>{
if(stopping || hiddenPaused) return;
const now=performance.now();
if(now >= nextFrameAt){
paintFrame();
nextFrameAt = (nextFrameAt && now - nextFrameAt < frameMs) ? nextFrameAt + frameMs : now + frameMs;
}
if(Math.abs(V.currentTime-lastT)>0.001){ lastT=V.currentTime; stallMs=0; } else { stallMs += now-prevNow; }
prevNow=now;
if(onProg) onProg(clamp((V.currentTime-a)/len,0,1), Math.max(0,len-(V.currentTime-a)));
if(cancelExport || V.currentTime >= z-0.005 || V.ended ||
stallMs > 10000 || (now-wall0-pausedTotal) > maxMs){
stopping=true;
if(cancelExport) aborted=true; // half a clip is worse than none
if(stallMs>10000 || (now-wall0-pausedTotal)>maxMs) stalled=true;
stop();
}
};
const onEnded = ()=>{ if(!stopping){ stopping=true; stop(); } };
V.addEventListener("ended", onEnded);
// start playback FIRST, then the recorder — otherwise the frozen first frame
// gets baked into the front of the clip and the output runs long
V.playbackRate = 1;
try{ await V.play(); }
catch(e){
document.removeEventListener("visibilitychange", onVis);
V.removeEventListener("ended",onEnded);
try{ cStream.getTracks().forEach(x=>x.stop()); }catch(e2){}
throw new Error("Couldn't start playback: "+e.message);
}
wall0 = performance.now(); media0 = V.currentTime; prevNow = wall0; nextFrameAt = 0;
rec.start(200);
stopClock = makeClock(tick);
await stopped;
if(stopClock){ stopClock(); stopClock=null; }
document.removeEventListener("visibilitychange", onVis);
V.removeEventListener("ended", onEnded);
try{ cStream.getTracks().forEach(x=>x.stop()); }catch(e){}
const type = mime.split(";")[0];
return { blob:new Blob(chunks,{type}), ext:(type.indexOf("mp4")>=0?"mp4":"webm"), stalled, speed, aborted };
}
/* ---------------- GIF encoder ----------------
Written out longhand so the file stays self-contained and works offline.
GIF is limited to 256 colours per frame, so each frame gets its own palette
(median cut) and Floyd-Steinberg dithering to stop gradients banding. */
const _hist=new Int32Array(32768), _rs=new Int32Array(32768), _gs=new Int32Array(32768), _bs=new Int32Array(32768);
const _bins=new Int32Array(32768), _cache=new Int16Array(32768);
function gifBytes(){
let b=new Uint8Array(1<<18), n=0;
const grow=k=>{ if(n+k<=b.length) return; let L=b.length; while(L<n+k) L*=2;
const t=new Uint8Array(L); t.set(b.subarray(0,n)); b=t; };
return {
u8(v){ grow(1); b[n++]=v&255; },
u16(v){ grow(2); b[n++]=v&255; b[n++]=(v>>8)&255; },
str(s){ grow(s.length); for(let i=0;i<s.length;i++) b[n++]=s.charCodeAt(i); },
raw(a){ grow(a.length); b.set(a,n); n+=a.length; },
size(){ return n; },
out(){ return b.slice(0,n); }
};
}
function buildPalette(data, maxColors){
_hist.fill(0); _rs.fill(0); _gs.fill(0); _bs.fill(0);
for(let i=0;i<data.length;i+=4){
const r=data[i], g=data[i+1], b=data[i+2];
const k=((r>>3)<<10)|((g>>3)<<5)|(b>>3);
_hist[k]++; _rs[k]+=r; _gs[k]+=g; _bs[k]+=b;
}
let m=0; for(let k=0;k<32768;k++) if(_hist[k]) _bins[m++]=k;
const stat=(s,e)=>{
let rmin=31,rmax=0,gmin=31,gmax=0,bmin=31,bmax=0;
for(let i=s;i<e;i++){ const k=_bins[i], r=(k>>10)&31, g=(k>>5)&31, b=k&31;
if(r<rmin)rmin=r; if(r>rmax)rmax=r;
if(g<gmin)gmin=g; if(g>gmax)gmax=g;
if(b<bmin)bmin=b; if(b>bmax)bmax=b; }
const dr=rmax-rmin, dg=gmax-gmin, db=bmax-bmin;
let chan=0, ext=dr;
if(dg>ext){ chan=1; ext=dg; }
if(db>ext){ chan=2; ext=db; }
return {s,e,chan,ext};
};
let boxes=[stat(0,m)];
while(boxes.length<maxColors){
let bi=-1, best=0;
for(let i=0;i<boxes.length;i++){ const B=boxes[i];
if(B.e-B.s<2) continue;
if(B.ext>best){ best=B.ext; bi=i; } }
if(bi<0) break;
const B=boxes[bi], shift=B.chan===0?10:B.chan===1?5:0;
const sub=Array.from(_bins.subarray(B.s,B.e));
sub.sort((x,y)=>(((x>>shift)&31)-((y>>shift)&31)));
_bins.set(sub,B.s);
let total=0; for(let i=B.s;i<B.e;i++) total+=_hist[_bins[i]];
let acc=0, mid=B.s+1;
for(let i=B.s;i<B.e;i++){ acc+=_hist[_bins[i]]; if(acc*2>=total){ mid=i+1; break; } }
if(mid<=B.s) mid=B.s+1;
if(mid>=B.e) mid=B.e-1;
boxes.splice(bi,1,stat(B.s,mid),stat(mid,B.e));
}
const pal=new Uint8Array(768);
for(let i=0;i<boxes.length;i++){
const B=boxes[i]; let c=0,R=0,G=0,Bl=0;
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]; }
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); }
}
return {pal, count:Math.max(1,boxes.length)};
}
function mapToPalette(data, w, h, pal, palCount, dither){
const idx=new Uint8Array(w*h);
_cache.fill(-1);
const nearest=(r,g,b)=>{
const key=((r>>3)<<10)|((g>>3)<<5)|(b>>3);
const hit=_cache[key]; if(hit>=0) return hit;
let bd=Infinity, bi=0;
for(let i=0;i<palCount;i++){
const dr=r-pal[i*3], dg=g-pal[i*3+1], db=b-pal[i*3+2];
const d=dr*dr*3+dg*dg*6+db*db; // roughly luma-weighted
if(d<bd){ bd=d; bi=i; }
}
_cache[key]=bi; return bi;
};
if(!dither){
for(let p=0,q=0;q<idx.length;q++,p+=4) idx[q]=nearest(data[p],data[p+1],data[p+2]);
return idx;
}
const buf=new Float32Array(w*h*3);
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]; }
const cl=v=>v<0?0:(v>255?255:v);
for(let y=0;y<h;y++){
for(let x=0;x<w;x++){
const q=y*w+x, o=q*3;
const r=cl(buf[o]), g=cl(buf[o+1]), b=cl(buf[o+2]);
const i=nearest(r|0,g|0,b|0); idx[q]=i;
const er=(r-pal[i*3])*0.75, eg=(g-pal[i*3+1])*0.75, eb=(b-pal[i*3+2])*0.75;
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; }
if(y+1<h){
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; }
{ const oo=(q+w)*3; buf[oo]+=er*0.3125; buf[oo+1]+=eg*0.3125; buf[oo+2]+=eb*0.3125; }
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; }
}
}
}
return idx;
}
function lzwWrite(minCodeSize, indices, g){
const CLEAR=1<<minCodeSize, EOI=CLEAR+1;
let codeSize=minCodeSize+1, next=EOI+1;
let dict=new Map(), cur=0, curBits=0;
const block=[];
const flush=()=>{ if(block.length){ g.u8(block.length); for(let i=0;i<block.length;i++) g.u8(block[i]); block.length=0; } };
const emit=code=>{
cur |= code<<curBits; curBits += codeSize;
while(curBits>=8){ block.push(cur&255); cur>>>=8; curBits-=8; if(block.length===255) flush(); }
};
g.u8(minCodeSize);
emit(CLEAR);
let prefix=indices[0];
for(let i=1;i<indices.length;i++){
const k=indices[i], key=prefix*256+k, found=dict.get(key);
if(found!==undefined){ prefix=found; continue; }
emit(prefix);
if(next===4096){
emit(CLEAR); dict=new Map(); next=EOI+1; codeSize=minCodeSize+1;
}else{
// grow the code width BEFORE claiming the code, so the decoder — which
// builds its table one code behind — switches width at the same place
if(next >= (1<<codeSize) && codeSize<12) codeSize++;
dict.set(key,next); next++;
}
prefix=k;
}
emit(prefix); emit(EOI);
if(curBits>0){ block.push(cur&255); if(block.length===255) flush(); }
flush();
g.u8(0);
}
function whileVisible(){
if(!document.hidden) return Promise.resolve();
setStatus("Paused — come back to this tab to carry on");
return new Promise(res=>{
const h=()=>{ if(!document.hidden){ document.removeEventListener("visibilitychange",h); res(); } };
document.addEventListener("visibilitychange",h);
});
}
/* Renders by seeking frame by frame rather than playing in real time, so it is
exact and doesn't care how fast the machine is. */
async function renderGif(a, z, t, ctx, cv, onProg){
const len=Math.max(0.02, z-a);
const delay=Math.max(2, Math.round(100/Math.min(20, t.f))); // GIF delays are in 1/100 s
const w=t.w, h=t.h;
const n=Math.max(1, Math.min(900, Math.round(len*100/delay)));
const g=gifBytes();
g.str("GIF89a"); g.u16(w); g.u16(h); g.u8(0x70); g.u8(0); g.u8(0);
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
let aborted=false, t0=performance.now();
for(let i=0;i<n;i++){
if(cancelExport){ aborted=true; break; }
await whileVisible();
V.currentTime = Math.min(z-0.001, a + i*delay/100);
await Promise.race([once(V,"seeked"), new Promise(r=>setTimeout(r,3000))]);
drawSource(ctx, w, h);
const img=ctx.getImageData(0,0,w,h);
const {pal,count}=buildPalette(img.data, 256);
const idx=mapToPalette(img.data, w, h, pal, count, true);
g.u8(0x21); g.u8(0xF9); g.u8(4); g.u8(0x04); g.u16(delay); g.u8(0); g.u8(0);
g.u8(0x2C); g.u16(0); g.u16(0); g.u16(w); g.u16(h); g.u8(0x87);
g.raw(pal);
lzwWrite(8, idx, g);
if(onProg){
const per=(performance.now()-t0)/(i+1)/1000;
onProg((i+1)/n, Math.max(0,(n-i-1)*per));
}
if((i&1)===0) await new Promise(r=>setTimeout(r,0)); // keep the page responsive
}
g.u8(0x3B);
return { blob:new Blob([g.out()],{type:"image/gif"}), ext:"gif", stalled:false, speed:1, aborted,
frames:n, fps:Math.round(1000/delay)/10 };
}
/* ---------------- export ---------------- */
$("exportBtn").addEventListener("click", ()=>doExport("video"));
$("gifBtn").addEventListener("click", ()=>doExport("gif"));
$("stopBtn").addEventListener("click", ()=>{ cancelExport=true; setStatus("Stopping…"); });
async function doExport(mode){
if(exporting || !dur) return;
const isGif = mode === "gif";
const t = targets();
const list = exportList().filter(s => s.end - s.start >= 0.05);
if(!list.length){ setStatus("Selection is too short."); return; }
const multi = list.length > 1;
const mime = isGif ? "image/gif" : pickMime();
if(!mime){ setStatus("This browser can't record video. Try Chrome or Edge."); return; }
if(isGif){ // GIFs balloon quickly — say so before spending the time
const gfps = Math.min(20, t.f);
const frames = Math.round(list.reduce((x,sg)=>x+(sg.end-sg.start),0) * gfps);
if(t.w*t.h*frames > 90e6 &&
!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;
}
// several files → put them in a folder of your choosing (must happen on the click)
let dirHandle = null;
if(multi && window.showDirectoryPicker){
try{
dirHandle = await window.showDirectoryPicker({id:"nugget-clips", mode:"readwrite", startIn:"videos"});
}catch(e){
if(e && e.name === "AbortError"){ setStatus("Export cancelled — no folder chosen."); return; }
dirHandle = null; // not supported here; fall back to downloads
}
}
exporting=true; cancelExport=false;
clearResult(); clearSaved();
$("exportBtn").disabled=true; $("gifBtn").disabled=true;
$("exportBtn").textContent = isGif ? "Building GIF…" : "Exporting…";
$("stopBtn").style.display="block";
$("expNote").style.display="block";
$("bar").style.display="block"; $("barI").style.width="0%";
V.pause();
const cv=$("exportCanvas"); cv.width=t.w; cv.height=t.h;
const ctx=cv.getContext("2d",{alpha:false});
ctx.imageSmoothingEnabled=true; ctx.imageSmoothingQuality="high";
ctx.fillStyle="#000"; ctx.fillRect(0,0,t.w,t.h);
V.style.display="none"; cv.style.display="block"; $("cropLayer").style.display="none";
setupAudio();
if(audioCtx && audioCtx.state==="suspended"){ try{ await audioCtx.resume(); }catch(e){} }
if(monitorGain) monitorGain.gain.value = 0;
keepAwake(true);
const total = list.reduce((a,s)=>a+(s.end-s.start),0);
let doneLen = 0, saved = [], slow = false, cut = false, failed = 0;
try{
for(let i=0;i<list.length;i++){
if(cancelExport) break;
const s = list[i];
const len = s.end - s.start;
const label = multi ? "Clip "+(i+1)+" of "+list.length+" · " : "";
const onProg = (p, left)=>{
const overall = (doneLen + p*len)/total;
$("barI").style.width=(overall*100).toFixed(1)+"%";
setStatus(label+(isGif?"building GIF ":"recording ")+Math.round(p*100)+"% · about "+Math.ceil(left)+"s left");
};
const r = isGif ? await renderGif(s.start, s.end, t, ctx, cv, onProg)
: await recordRange(s.start, s.end, t, mime, ctx, cv, onProg);
doneLen += len;
lastExt = r.ext;
if(r.stalled) cut = true;
if(!r.stalled && r.speed < 0.9) slow = true;
if(r.aborted) break; // stopped part-way through this clip — discard it
if(!r.blob.size){ failed++; continue; }
const fname = clipFileName(i, s, t, multi);
if(dirHandle){
setStatus(label+"saving…");
try{
const fh = await dirHandle.getFileHandle(fname, {create:true});
const ws = await fh.createWritable();
await ws.write(r.blob); await ws.close();
saved.push(fname+" ("+bytes(r.blob.size)+")");
}catch(e){ failed++; saved.push(fname+" — could not be written: "+e.message); }
}else if(multi){
pushDownload(r.blob, fname);
saved.push(fname+" ("+bytes(r.blob.size)+")");
await new Promise(r2=>setTimeout(r2,400)); // let the browser keep up
}else{
lastBlob = r.blob;
lastMeta = {w:t.w, h:t.h, f:t.f, at:s.start, name:s.name};
const url = URL.createObjectURL(lastBlob);
if(isGif){ $("outImg").src=url; $("outImg").style.display="block"; $("outVid").style.display="none"; }
else { $("outVid").src=url; $("outVid").style.display="block"; $("outImg").style.display="none"; }
$("result").style.display="block";
const n = download();
saved.push((n||fname)+" ("+bytes(r.blob.size)+")");
}
}
}catch(err){
setStatus(err.message);
}finally{
exporting=false;
if(monitorGain) monitorGain.gain.value=1;
cv.style.display="none"; V.style.display="block";
if(crop){ showCrop(true); layoutCrop(); }
$("exportBtn").disabled=false; $("gifBtn").disabled=false; $("stopBtn").style.display="none";
$("expNote").style.display="none";
$("bar").style.display="none";
keepAwake(false);
V.currentTime=inT;
estimate();
}
// ---- report ----
const notes=[];
if(lastExt==="webm" && !isGif) notes.push("Saved as .webm — this browser can't record MP4. Plays in Chrome, Edge, Firefox and VLC.");
if(cut) notes.push("Playback stalled on at least one clip, so it may be cut short.");
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.");
if(failed) notes.push(failed+" clip(s) could not be saved.");
if(multi){
$("saved").style.display = saved.length ? "block" : "none";
$("savedWhere").textContent = cancelExport
? "Stopped — "+saved.length+" of "+list.length+" saved"
: "Saved "+saved.length+" clip"+(saved.length===1?"":"s")+(dirHandle? " to “"+dirHandle.name+"”" : " to your Downloads folder");
$("savedList").innerHTML="";
saved.forEach(n=>{ const li=document.createElement("li"); li.textContent=n; $("savedList").appendChild(li); });
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.");
$("savedNote").textContent = notes.join(" ");
setStatus(cancelExport ? "Stopped." : "Done — "+saved.length+" clip"+(saved.length===1?"":"s")+".");
}else{
$("outNote").textContent = notes.join(" ");
setStatus(cancelExport ? "Stopped." : (saved[0] ? "Saved "+saved[0] : "Nothing was saved."));
}
}
function clipFileName(i, s, t, multi){
const base = safeName(srcName,60) || "clip";
if(lastExt==="gif"){
const lbl0 = safeName(s.name,40);
return base+"_"+(multi? String(i+1).padStart(2,"0")+"_" : "")+(lbl0 || stamp(s.start))+"_"+t.w+"px.gif";
}
if(!multi) return base+"_"+stamp(s.start)+"_"+t.w+"x"+t.h+"_"+t.f+"fps."+lastExt;
const lbl = safeName(s.name,40);
return base+"_"+String(i+1).padStart(2,"0")+"_"+(lbl || stamp(s.start))+"."+lastExt;
}
function pushDownload(blob, name){
try{
const a=document.createElement("a");
a.href=URL.createObjectURL(blob); a.download=name; a.style.display="none";
document.body.appendChild(a); a.click();
setTimeout(()=>{ URL.revokeObjectURL(a.href); a.remove(); }, 12000);
return name;
}catch(e){ return null; }
}
function download(){
if(!lastBlob || !lastBlob.size) return null;
const m = lastMeta || Object.assign(targets(), {at:inT, name:""});
const base = safeName(srcName,60) || "clip";
const lbl = safeName(m.name,40);
const name = lastExt==="gif"
? base+"_"+(lbl || stamp(m.at))+"_"+m.w+"px.gif"
: base+"_"+(lbl || stamp(m.at))+"_"+m.w+"x"+m.h+"_"+m.f+"fps."+lastExt;
return pushDownload(lastBlob, name);
}
$("dlBtn").addEventListener("click", ()=>{ download(); });
$("clearRes").addEventListener("click", clearResult);
function clearResult(){
lastBlob=null; lastMeta=null; $("result").style.display="none";
const ov=$("outVid"); if(ov.src){ URL.revokeObjectURL(ov.src); ov.removeAttribute("src"); }
const oi=$("outImg"); if(oi.src){ URL.revokeObjectURL(oi.src); oi.removeAttribute("src"); }
setStatus("");
}
function clearSaved(){ $("saved").style.display="none"; $("savedList").innerHTML=""; $("savedNote").textContent=""; }
function setStatus(s){ $("status").textContent=s; }
window.__vt = {
get state(){ return {ready:$("app").style.display==="block",loads:loadSeq,dur,inT,outT,natW,natH,srcFps,
exporting,size:lastBlob&&lastBlob.size,ext:lastExt,
clips:segments.map(s=>({start:+s.start.toFixed(3),end:+s.end.toFixed(3),name:s.name}))}; },
load, doExport, addClip,
gif(){ return doExport("gif"); },
set(a,b){ inT=a; outT=b; refresh(); },
setCrop(x,y,w,h){ setCrop(x,y,w,h); showCrop(true); cropChanged(true); },
getCrop(){ return crop && {...crop}; },
setAR(v,l){ applyAR(v, l||String(v)); },
arLabel(){ return cropARLabel; },
setName(i,n){ segments[i].name=n; refresh(); },
clearClips(){ segments=[]; activeSeg=-1; refresh(); }
};
})();
</script>
</body>
</html>