release: browser vocal separation v0.3.0

This commit is contained in:
haixin.yang committed 2026-07-13 16:01:06 +08:00
1 parent 7489a0bc4e
commit 8ddbb0bfe0
18 files changed
+406 -24

No files matched your search

+1
View File
@@ -13,6 +13,7 @@
<meta name="theme-color" content="#101720" />
<meta name="color-scheme" content="dark" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Timeline Studio" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="manifest" href="/manifest.webmanifest" />
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "web-player",
"version": "0.2.0",
"version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "web-player",
"version": "0.2.0",
"version": "0.3.0",
"license": "MIT",
"dependencies": {
"@diffusionstudio/vits-web": "^1.0.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "web-player",
"version": "0.2.0",
"version": "0.3.0",
"private": true,
"description": "A local-first browser AI video editor for voiceovers, captions, talking avatars, and multi-track timeline export.",
"license": "MIT",
+1 -1
View File
@@ -1,4 +1,4 @@
const MODEL_CACHE_NAME = "timeline-studio-model-cache-v3";
const MODEL_CACHE_NAME = "timeline-studio-model-cache-v4";
const APP_CACHE_NAME = "timeline-studio-app-shell-v3";
const APP_SHELL_URLS = [
"/",
+18
View File
@@ -0,0 +1,18 @@
/**
* @license
* Copyright 2024 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@tensorflow/tfjs-core")):"function"==typeof define&&define.amd?define(["exports","@tensorflow/tfjs-core"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).tf=e.tf||{},e.tf)}(this,(function(e,t){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,t}var a=n(t),r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)};function i(e,t,n,a){return new(n||(n=Promise))((function(r,i){function o(e){try{u(a.next(e))}catch(e){i(e)}}function s(e){try{u(a.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}u((a=a.apply(e,t||[])).next())}))}function o(e,t){var n,a,r,i,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&i[0]?a.return:i[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,i[1])).done)return r;switch(a=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,a=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(r=o.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){o.label=i[1];break}if(6===i[0]&&o.label<r[1]){o.label=r[1],r=i;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(i);break}r[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],a=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function s(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var a,r,i=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(a=i.next()).done;)o.push(a.value)}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return o}function c(e,t,n){if(n||2===arguments.length)for(var a,r=0,i=t.length;r<i;r++)!a&&r in t||(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var d=t.env();d.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",(function(){return 15})),d.registerFlag("WEBGPU_CPU_FORWARD",(function(){return!0})),d.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE",(function(){return-1})),d.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",(function(){return!0})),d.registerFlag("WEBGPU_USE_LOW_POWER_GPU",(function(){return!1})),d.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",(function(){return 1e3})),d.registerFlag("WEBGPU_USE_PROFILE_TOOL",(function(){return!1})),d.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE",(function(){return!0})),d.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG",(function(){return!1})),d.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL",(function(){return-1})),d.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",(function(){return!1})),d.registerFlag("WEBGPU_PRINT_SHADER",(function(){return""})),d.registerFlag("WEBGPU_ENGINE_COMPILE_ONLY",(function(){return!1}));var l=function(){function e(e){e&&(this.vendor=e.vendor,this.architecture=e.architecture,this.intelGPUGeneration=this.getIntelGPUGeneration())}return e.prototype.getIntelGPUGeneration=function(){if(this.isIntel()){if(this.architecture.startsWith("gen"))return Number(this.architecture.match(/\d+/));if(this.architecture.startsWith("xe"))return 12}return 0},e.prototype.isIntel=function(){return"intel"===this.vendor},e}(),p=function(){function e(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}return e.prototype.acquireBuffer=function(e,t,n,a){var r;void 0===n&&(n=!1),void 0===a&&(a=!0);var i=h(e,t);return a?(this.freeBuffers.has(i)||this.freeBuffers.set(i,[]),this.freeBuffers.get(i).length>0?(r=this.freeBuffers.get(i).pop(),this.numFreeBuffers--):(r=this.device.createBuffer({size:e,usage:t,mappedAtCreation:n}),this.numBytesAllocated+=e)):(r=this.device.createBuffer({size:e,usage:t,mappedAtCreation:n}),this.numBytesAllocated+=e),this.usedBuffers.has(i)||this.usedBuffers.set(i,[]),this.usedBuffers.get(i).push(r),this.numUsedBuffers++,this.numBytesUseLine truncated
//# sourceMappingURL=tf-backend-webgpu.min.js.map
+18
View File
@@ -0,0 +1,18 @@
/**
* @license
* Copyright 2024 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).tf=e.tf||{})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),e}var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function a(e){var t,n;function r(t,n){try{var o=e[t](n),s=o.value,u=s instanceof i;Promise.resolve(u?s.v:s).then((function(n){if(u){var i="return"===t?"return":"next";if(!s.k||n.done)return r(i,n);n=e[i](n).value}a(o.done?"return":"normal",n)}),(function(e){r("throw",e)}))}catch(e){a("throw",e)}}function a(e,a){switch(e){case"return":t.resolve({value:a,done:!0});break;case"throw":t.reject(a);break;default:t.resolve({value:a,done:!1})}(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,a){return new Promise((function(i,o){var s={key:e,arg:a,resolve:i,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,a))}))},"function"!=typeof e.return&&(this.return=void 0)}function i(e,t){this.v=e,this.k=t}function o(){o=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r=Object.defineProperty||function(e,t,n){e[t]=n.value},a="function"==typeof Symbol?Symbol:{},i=a.iterator||"@@iterator",s=a.asyncIterator||"@@asyncIterator",u=a.toStringTag||"@@toStringTag";function c(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,n){return e[t]=n}}function l(e,t,n,a){var i=t&&t.prototype instanceof f?t:f,o=Object.create(i.prototype),s=new T(a||[]);return r(o,"_invoke",{value:w(e,n,s)}),o}function h(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var p={};function f(){}function d(){}function v(){}var m={};c(m,i,(function(){return this}));var g=Object.getPrototypeOf,y=g&&g(g(E([])));y&&y!==t&&n.call(y,i)&&(m=y);var b=v.prototype=f.prototype=Object.create(m);function x(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function k(e,t){function a(r,i,o,s){var u=h(e[r],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==typeof l&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){a("next",e,o,s)}),(function(e){a("throw",e,o,s)})):t.resolve(l).then((function(e){c.value=e,o(c)}),(function(e){return a("throw",e,o,s)}))}s(u.arg)}var i;r(this,"_invoke",{value:function(e,n){function r(){return new t((function(t,r){a(e,n,t,r)}))}return i=i?i.then(r,r):r()}})}function w(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return C()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=I(o,n);if(s){if(s===p)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var u=h(e,t,n);if("normal"===u.type){if(r=n.done?"completed":"suspendedYield",u.arg===p)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r="completed",n.method="throw",n.arg=u.arg)}}}function I(e,t){var n=t.method,r=e.iterator[n];if(void 0===r)return t.delegate=null,"throw"===n&&e.iterator.return&&(t.method="return",t.arg=void 0,I(e,t),"throw"===t.method)||"return"!==n&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+n+"' method")),p;var a=h(r,e.iterator,t.arg);if("throw"===a.type)return t.method="throw",t.arg=a.arg,t.delegate=null,p;var i=a.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,p):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,p)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function S(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function E(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,a=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return a.next=a}}return{next:C}}function C(){return{value:void 0,done:!0}}return d.prototype=v,r(b,"constructor",{value:v,configurable:!0}),r(v,"constructor",{value:d,configurable:!0}),d.displayName=c(v,u,"GeneratorFunction")Line truncated
//# sourceMappingURL=tf.min.js.map
+6 -1
View File
@@ -21,6 +21,7 @@ import { useVoiceRecorder } from "./hooks/useVoiceRecorder.js";
import { useVoiceGeneration } from "./hooks/useVoiceGeneration.js";
import { useAutoCaptions } from "./hooks/useAutoCaptions.js";
import { useSourceAudioExtraction } from "./hooks/useSourceAudioExtraction.js";
import { useVocalSeparation } from "./hooks/useVocalSeparation.js";
import { useAvatarGeneration } from "./hooks/useAvatarGeneration.js";
import { useCaptionState } from "./hooks/useCaptionState.js";
import { useAudioTrackState } from "./hooks/useAudioTrackState.js";
@@ -254,6 +255,9 @@ export function App() {
setStatus, setStatusText, setTimelineHorizon, sourceAudioBlob, sourceAudioDuration,
sourceAudioRef, sourceAudioStart, sourceAudioUrlRef, t,
});
const { separateSourceVocals, vocalSeparationJob } = useVocalSeparation({
sourceAudioBlob, sourceAudioName, replaceSourceAudio, replaceMusic, notify, t,
});
const {
chooseInterfaceLanguage, clearAllVisionState, selectTool, toggleTrackLock,
@@ -277,7 +281,7 @@ export function App() {
previewVisualSegment, script, seekTo: (...args) => seekTo(...args), setCurrentTime,
setFitMode, setImageClipCount, setImageDuration, setImageMeta, setImageName,
setImageSrc, setSelectedTrack, setSelectedVisualSegmentId, setVisualSegments,
setVisualType, sourceAudioBlob, sourceAudioDuration, sourceAudioStart, trackLocks,
setTimelineZoom, setVisualType, sourceAudioBlob, sourceAudioDuration, sourceAudioStart, trackLocks,
visualSegments, visualType,
});
@@ -539,6 +543,7 @@ export function App() {
setMediaTab, setMusicVolume, setSelectedFilterId, setSelectedSegmentId,
setSelectedStickerId, setSelectedTransitionId, setSourceAudioVolume, setVoiceTab,
sourceAudioBlob, sourceAudioDuration, sourceAudioName, sourceAudioVolume, status, t,
separateSourceVocals, vocalSeparationJob,
toggleCaptionSegmentHidden, toggleVisionOption, trOption, updateCaptionSegmentText,
updateScript, userAssets, visionJob,
}} />
+2
View File
@@ -82,6 +82,8 @@ export function EditorSidebar({ model: d }) {
generateCaptionsFromSourceAudio={d.generateCaptionsFromSourceAudio}
isGeneratingCaptions={d.status === "captioning"}
automaticCaptionProgress={d.status === "captioning" ? d.progress : 0}
separateSourceVocals={d.separateSourceVocals}
vocalSeparationJob={d.vocalSeparationJob}
hasVisual={Boolean(d.previewVisualSrc)}
visualType={d.previewVisualType}
visionAnalysis={d.previewVisionAnalysis}
+31 -18
View File
@@ -211,6 +211,8 @@ export function Timeline({
...audioLanes.map((_, index) => ["audio", `${t("voiceTrack")} ${index + 1}`, `audio-${index}`]),
["music", t("musicTrack")],
];
const isRowVisible = (track, rowId = track) =>
trackVisibility[rowId] ?? trackVisibility[track] ?? true;
const [rulerViewport, setRulerViewport] = useState({
scrollLeft: 0,
viewportWidth: 0,
@@ -459,6 +461,8 @@ export function Timeline({
showStickerTrack ? (
<div
className={`sticker-track ${selectedTrack === "sticker" ? "is-selected" : ""} ${
!trackVisibility.sticker ? "is-track-disabled" : ""
} ${
assetDropTargetTrack === "sticker" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "sticker" ? "is-drop-landing" : ""}`}
onClick={() => {
@@ -473,8 +477,7 @@ export function Timeline({
{assetDropTargetTrack === "sticker" ? (
<div className="track-drop-hint">{t("dropStickerHere")}</div>
) : null}
{trackVisibility.sticker
? stickerSegments.map((segment) => {
{stickerSegments.map((segment) => {
const segmentLeft =
timelineDuration > 0
? Math.max(0, Math.min(100, ((segment.start || 0) / timelineDuration) * 100))
@@ -510,8 +513,7 @@ export function Timeline({
<span>{segment.name}</span>
</button>
);
})
: null}
})}
{renderAssetDropSlot("sticker")}
</div>
) : null;
@@ -584,16 +586,21 @@ export function Timeline({
<div className="timeline-board">
<div className="track-labels" style={{ gridTemplateRows: timelineLabelRows }}>
{timelineTrackLabels.map(([track, label, rowId = track]) => (
<div className={selectedTrack === track ? "is-selected" : ""} key={rowId}>
<div
className={`${selectedTrack === track ? "is-selected" : ""} ${
!isRowVisible(track, rowId) ? "is-track-disabled" : ""
}`}
key={rowId}
>
<button
type="button"
aria-label={`${label} ${t("visible")}`}
onClick={(event) => {
event.stopPropagation();
toggleTrackVisibility(track);
toggleTrackVisibility(rowId);
}}
>
{trackVisibility[track] ? <Eye size={15} /> : <EyeSlash size={15} />}
{isRowVisible(track, rowId) ? <Eye size={15} /> : <EyeSlash size={15} />}
</button>
<button
type="button"
@@ -661,6 +668,8 @@ export function Timeline({
) : null}
<div
className={`image-track ${selectedTrack === "image" ? "is-selected" : ""} ${
!trackVisibility.image ? "is-track-disabled" : ""
} ${
assetDropTargetTrack === "image" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "image" ? "is-drop-landing" : ""} ${
activeTimelineClipDrag?.track === "image" ? "is-reordering" : ""
@@ -678,7 +687,7 @@ export function Timeline({
{assetDropTargetTrack === "image" ? (
<div className="track-drop-hint">{t("dropVisualHere")}</div>
) : null}
{trackVisibility.image && imageSrc
{imageSrc
? displayedVisualSegments.map((segment, index) => {
const segmentSrc = segment.src || imageSrc;
const segmentType = segment.type || visualType;
@@ -801,6 +810,8 @@ export function Timeline({
{captionLanes.map((lane, laneIndex) => (
<div
className={`caption-track ${selectedTrack === "caption" ? "is-selected" : ""} ${
!isRowVisible("caption", `caption-${laneIndex}`) ? "is-track-disabled" : ""
} ${
activeTimelineClipDrag?.track === "caption" ? "is-reordering" : ""
}`}
key={`caption-lane-${laneIndex}`}
@@ -810,8 +821,7 @@ export function Timeline({
}}
data-timeline-reorder-track="caption"
>
{trackVisibility.caption
? lane.map(({ segment, index, range: segmentRange }) => {
{lane.map(({ segment, index, range: segmentRange }) => {
const segmentDuration = segmentRange?.duration ?? 0;
const segmentLeft =
segmentRange && timelineDuration > 0
@@ -862,12 +872,13 @@ export function Timeline({
{segment.text}
</button>
);
})
: null}
})}
</div>
))}
<button
className={`audio-track source-track ${selectedTrack === "source" ? "is-selected" : ""} ${
!trackVisibility.source ? "is-track-disabled" : ""
} ${
assetDropTargetTrack === "source" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "source" ? "is-drop-landing" : ""}`}
type="button"
@@ -881,7 +892,7 @@ export function Timeline({
<div className="track-drop-hint">{t("dropSourceHere")}</div>
) : null}
{renderAssetDropSlot("source")}
{trackVisibility.source && sourceAudioBlob ? (
{sourceAudioBlob ? (
<div
className="audio-clip is-source"
style={{
@@ -897,6 +908,8 @@ export function Timeline({
{audioLanes.map((lane, laneIndex) => (
<button
className={`audio-track ${selectedTrack === "audio" ? "is-selected" : ""} ${
!isRowVisible("audio", `audio-${laneIndex}`) ? "is-track-disabled" : ""
} ${
laneIndex === 0 && assetDropTargetTrack === "audio" ? "is-drop-target" : ""
} ${laneIndex === 0 && assetDropPulseTrack === "audio" ? "is-drop-landing" : ""}`}
type="button"
@@ -911,8 +924,7 @@ export function Timeline({
<div className="track-drop-hint">{t("dropVoiceHere")}</div>
) : null}
{laneIndex === 0 ? renderAssetDropSlot("audio") : null}
{trackVisibility.audio
? lane.map((segment) => {
{lane.map((segment) => {
const left = timelineDuration > 0 ? (segment.start / timelineDuration) * 100 : 0;
const width = timelineDuration > 0 ? (segment.duration / timelineDuration) * 100 : 0;
return (
@@ -932,12 +944,13 @@ export function Timeline({
<span className="audio-clip-duration">{formatTime(segment.duration)}</span>
</div>
);
})
: null}
})}
</button>
))}
<button
className={`audio-track music-track ${selectedTrack === "music" ? "is-selected" : ""} ${
!trackVisibility.music ? "is-track-disabled" : ""
} ${
assetDropTargetTrack === "music" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "music" ? "is-drop-landing" : ""}`}
type="button"
@@ -951,7 +964,7 @@ export function Timeline({
<div className="track-drop-hint">{t("dropMusicHere")}</div>
) : null}
{renderAssetDropSlot("music")}
{trackVisibility.music && musicBlob ? (
{musicBlob ? (
<div className="audio-clip is-music" style={{ width: `${musicClipPercent}%` }}>
<WaveformStrip peaks={musicPeaks} active />
<span className="audio-clip-duration">{formatTime(musicDuration)}</span>
+15
View File
@@ -250,6 +250,8 @@ export function ToolPanel(props) {
generateCaptionsFromSourceAudio,
isGeneratingCaptions,
automaticCaptionProgress,
separateSourceVocals,
vocalSeparationJob,
hasVisual,
visualType,
visionAnalysis,
@@ -394,6 +396,19 @@ export function ToolPanel(props) {
<em>{t("aiVoiceEntryDesc")}</em>
</span>
</button>
<button
className="audio-entry-card separation-entry-card"
type="button"
disabled={!sourceAudioBlob || vocalSeparationJob.running}
onClick={separateSourceVocals}
>
<Waveform size={24} weight="duotone" />
<span>
<strong>{vocalSeparationJob.running ? t("vocalSeparationRunning") : t("vocalSeparationTitle")}</strong>
<em>{sourceAudioBlob ? (vocalSeparationJob.phase || t("vocalSeparationDesc")) : t("vocalSeparationNeedsSource")}</em>
</span>
{vocalSeparationJob.running ? <span className="inline-progress" aria-hidden="true"><span style={{ width: `${vocalSeparationJob.progress}%` }} /></span> : null}
</button>
<button
className="audio-entry-card caption-entry-card"
type="button"
+34
View File
@@ -0,0 +1,34 @@
import { useCallback, useState } from "react";
import { decodeWaveform } from "../lib/media.js";
import { separateVocals } from "../lib/vocalSeparation.js";
export function useVocalSeparation({ sourceAudioBlob, sourceAudioName, replaceSourceAudio, replaceMusic, notify, t }) {
const [job, setJob] = useState({ running: false, progress: 0, phase: "" });
const run = useCallback(async () => {
if (!sourceAudioBlob || job.running) return;
setJob({ running: true, progress: 1, phase: t("vocalSeparationPreparing") });
try {
const result = await separateVocals(sourceAudioBlob, (progress, phase) => setJob({
running: true,
progress,
phase: phase.key === "vocalSeparationProcessingChunk"
? t(phase.key).replace("{current}", phase.current).replace("{total}", phase.total)
: t(phase.key),
}));
const [voiceMeta, musicMeta] = await Promise.all([decodeWaveform(result.vocals, 96), decodeWaveform(result.accompaniment, 96)]);
const base = (sourceAudioName || "source-audio").replace(/\.[^.]+$/, "");
replaceSourceAudio(result.vocals, voiceMeta.duration, voiceMeta.peaks, `${base}-${t("vocalStemFile")}.wav`, t("vocalStemPlaced"));
replaceMusic(result.accompaniment, musicMeta.duration, musicMeta.peaks, `${base}-${t("instrumentalStemFile")}.wav`, t("instrumentalStemPlaced"));
setJob({ running: false, progress: 100, phase: t("vocalSeparationComplete") }); notify(t("vocalSeparationComplete"));
} catch (error) {
console.error(error); setJob({ running: false, progress: 0, phase: "" });
const reason = error.message === "VOCAL_RUNTIME_DOWNLOAD_FAILED"
? t("vocalSeparationRuntimeFailed")
: error.message === "VOCAL_BACKEND_UNAVAILABLE"
? t("vocalSeparationBackendFailed")
: t("vocalSeparationModelFailed");
notify(`${t("vocalSeparationFailed")}:${reason}`);
}
}, [job.running, notify, replaceMusic, replaceSourceAudio, sourceAudioBlob, sourceAudioName, t]);
return { vocalSeparationJob: job, separateSourceVocals: run };
}
+36
View File
@@ -286,6 +286,24 @@ export const UI_COPY = {
actionGuide: "行动引导",
templateSuffix: "请替换为你的文案。",
audioPanel: "音频",
vocalSeparationTitle: "AI 人声分离",
vocalSeparationDesc: "离线提取人声,并将伴奏放入音乐轨",
vocalSeparationNeedsSource: "请先上传视频或音频到源音频轨",
vocalSeparationRunning: "正在分离人声与伴奏",
vocalSeparationPreparing: "正在准备音频",
vocalSeparationLoadingModel: "正在加载 UVR 模型",
vocalSeparationUsingWebGpu: "正在使用 WebGPU 加速",
vocalSeparationUsingWebGl: "WebGPU 不可用,正在使用 WebGL",
vocalSeparationProcessingChunk: "正在分离第 {current}/{total} 段",
vocalSeparationComplete: "人声与伴奏分离完成",
vocalSeparationFailed: "人声分离失败",
vocalSeparationRuntimeFailed: "运行时下载失败",
vocalSeparationBackendFailed: "当前浏览器无法初始化音频推理后端",
vocalSeparationModelFailed: "模型无法运行",
vocalStemFile: "人声",
instrumentalStemFile: "伴奏",
vocalStemPlaced: "人声已替换到源音频轨",
instrumentalStemPlaced: "伴奏已添加到音乐轨",
aiVoiceEntryTitle: "AI 配音",
aiVoiceEntryDesc: "输入文案、选择声音并生成语音",
autoCaptionsTitle: "从原声生成字幕",
@@ -604,6 +622,24 @@ export const UI_COPY = {
actionGuide: "Call to action",
templateSuffix: "Replace with your copy.",
audioPanel: "Audio",
vocalSeparationTitle: "AI Vocal Separation",
vocalSeparationDesc: "Extract vocals offline and place the instrumental on the music track",
vocalSeparationNeedsSource: "Add video or audio to the source track first",
vocalSeparationRunning: "Separating vocals and instrumental",
vocalSeparationPreparing: "Preparing audio",
vocalSeparationLoadingModel: "Loading UVR model",
vocalSeparationUsingWebGpu: "Using WebGPU acceleration",
vocalSeparationUsingWebGl: "WebGPU unavailable, using WebGL",
vocalSeparationProcessingChunk: "Separating chunk {current}/{total}",
vocalSeparationComplete: "Vocal and instrumental separation complete",
vocalSeparationFailed: "Vocal separation failed",
vocalSeparationRuntimeFailed: "The separation runtime could not be downloaded",
vocalSeparationBackendFailed: "The browser could not initialize the audio inference backend",
vocalSeparationModelFailed: "The separation model could not run",
vocalStemFile: "vocals",
instrumentalStemFile: "instrumental",
vocalStemPlaced: "Vocals replaced the source-audio track",
instrumentalStemPlaced: "Instrumental added to the music track",
aiVoiceEntryTitle: "AI Voiceover",
aiVoiceEntryDesc: "Write script, choose a voice, generate audio",
autoCaptionsTitle: "Generate captions from source",
+5 -1
View File
@@ -33,7 +33,11 @@ export function createEditorCommandActions(d) {
}
function toggleTrackVisibility(track) {
d.setTrackVisibility((visibility) => ({ ...visibility, [track]: !visibility[track] }));
d.setTrackVisibility((visibility) => {
const baseTrack = track.replace(/-\d+$/, "");
const currentVisibility = visibility[track] ?? visibility[baseTrack] ?? true;
return { ...visibility, [track]: !currentVisibility };
});
}
function toggleTrackLock(track) {
+17
View File
@@ -11,8 +11,25 @@ import {
getVisualSegmentTimeline,
reorderTimelineItems,
} from "./timeline.js";
import {
getTimelineAutoFitZoom,
getTimelineVisibleDuration,
getTimelineZoomForVisibleDuration,
} from "./timelineScale.js";
describe("timeline primitives", () => {
it("fits an uploaded video into most of the visible timeline", () => {
const zoom = getTimelineAutoFitZoom(15);
const visibleDuration = getTimelineVisibleDuration(zoom);
expect(visibleDuration).toBeCloseTo(15 / 0.82, 2);
expect(15 / visibleDuration).toBeCloseTo(0.82, 2);
});
it("clamps automatic timeline fitting to supported zoom limits", () => {
expect(getTimelineVisibleDuration(getTimelineZoomForVisibleDuration(10_000))).toBeCloseTo(1800, 2);
expect(getTimelineVisibleDuration(getTimelineAutoFitZoom(0.5))).toBeCloseTo(5, 2);
});
it("reorders without mutating the source array", () => {
const source = [{ id: "a" }, { id: "b" }, { id: "c" }];
const result = reorderTimelineItems(source, 0, 2);
+24
View File
@@ -29,6 +29,30 @@ export function getTimelineVisibleDuration(zoom) {
);
}
export function getTimelineZoomForVisibleDuration(visibleDuration) {
const target = Math.max(
TIMELINE_MIN_VISIBLE_SECONDS,
Math.min(DEFAULT_TIMELINE_DURATION_SECONDS, Number(visibleDuration) || TIMELINE_DEFAULT_VISIBLE_SECONDS),
);
let low = TIMELINE_MIN_ZOOM;
let high = TIMELINE_MAX_ZOOM;
for (let index = 0; index < 32; index += 1) {
const middle = (low + high) / 2;
if (getTimelineVisibleDuration(middle) > target) low = middle;
else high = middle;
}
return clampTimelineZoom((low + high) / 2);
}
export function getTimelineAutoFitZoom(contentDuration, fillRatio = 0.82) {
const safeDuration = Math.max(0.5, Number(contentDuration) || 0.5);
const safeFillRatio = Math.max(0.5, Math.min(0.9, Number(fillRatio) || 0.82));
const paddedVisibleDuration = Math.max(5, safeDuration / safeFillRatio);
return getTimelineZoomForVisibleDuration(paddedVisibleDuration);
}
export function getTimelineTrackWidthPercent(timelineDuration, zoom) {
if (timelineDuration <= 0) {
return 100;
+12
View File
@@ -8,8 +8,14 @@ import {
getImageThumbnailCount,
getVisualSegmentsTotal,
} from "./timeline.js";
import { getTimelineAutoFitZoom } from "./timelineScale.js";
export function createVisualTimelineActions(d) {
function fitTimelineToVideo(duration) {
if (typeof d.setTimelineZoom !== "function") return;
d.setTimelineZoom(getTimelineAutoFitZoom(duration));
}
function getVisualDurationForAsset(asset, fallbackDuration = 4) {
if (asset?.type === "video" && asset.duration) {
return Math.min(
@@ -84,6 +90,7 @@ export function createVisualTimelineActions(d) {
d.setSelectedVisualSegmentId(segment.id);
d.setImageDuration(segment.duration);
d.setImageClipCount(getImageThumbnailCount(segment.duration));
if (asset?.type === "video") fitTimelineToVideo(segment.duration);
}
function appendVisualAssetToTimeline(asset) {
@@ -111,6 +118,7 @@ export function createVisualTimelineActions(d) {
`${asset.type === "video" ? "视频" : "图片"}素材已追加到图片轨`,
sourceSegments.length,
);
if (asset.type === "video") fitTimelineToVideo(totalDuration + segmentDuration);
d.seekTo(totalDuration);
if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration);
}
@@ -118,6 +126,7 @@ export function createVisualTimelineActions(d) {
function updateVisualAssetInTimeline(assetId, updates) {
if (!assetId) return;
d.setVisualSegments((segments) => {
const matchingSegment = segments.find((segment) => segment.assetId === assetId);
const nextSegments = segments.map((segment) =>
segment.assetId === assetId
? {
@@ -135,6 +144,9 @@ export function createVisualTimelineActions(d) {
const nextDuration = getVisualSegmentsTotal(nextSegments);
d.setImageDuration(nextDuration);
d.setImageClipCount(getImageThumbnailCount(nextDuration));
if (matchingSegment?.type === "video" && updates.duration) {
fitTimelineToVideo(nextDuration);
}
return nextSegments;
});
if (d.previewVisualSegment?.assetId === assetId || d.previewVisualSegment?.src === updates.src) {
+144
View File
@@ -0,0 +1,144 @@
const MODEL_URL = "/models/vocal-remover/model.json";
const CHUNK_SIZE = 31744;
const PADDING = 3072;
const FFT_SIZE = 6144;
const HOP_SIZE = 1024;
let modelPromise;
let runtimePromise;
let activeBackend = "webgl";
function loadScript(src) {
return new Promise((resolve, reject) => {
const existing = document.querySelector(`script[src="${src}"]`);
if (existing) { if (window.tf) resolve(); else existing.addEventListener("load", resolve, { once: true }); return; }
const script = document.createElement("script"); script.src = src; script.crossOrigin = "anonymous";
script.onload = resolve; script.onerror = () => reject(new Error("VOCAL_RUNTIME_DOWNLOAD_FAILED")); document.head.appendChild(script);
});
}
async function getRuntime() {
if (!runtimePromise) runtimePromise = (async () => {
await loadScript("/vendor/vocal-remover/tf.min.js?v=4.22.0");
if (navigator.gpu) await loadScript("/vendor/vocal-remover/tf-backend-webgpu.js?v=4.22.0");
return window.tf;
})();
return runtimePromise;
}
async function getModel(tf) {
if (!modelPromise) {
modelPromise = (async () => {
const requestedBackend = navigator.gpu && tf.findBackend("webgpu") ? "webgpu" : "webgl";
let ready = false;
try { ready = await tf.setBackend(requestedBackend); } catch { ready = false; }
if (!ready && requestedBackend === "webgpu") ready = await tf.setBackend("webgl");
if (!ready) throw new Error("VOCAL_BACKEND_UNAVAILABLE");
activeBackend = tf.getBackend();
await tf.ready();
return tf.loadGraphModel(MODEL_URL);
})();
}
return modelPromise;
}
function stft(tf, input) {
return tf.tidy(() => {
const spectrum = tf.signal.stft(input, FFT_SIZE, HOP_SIZE, FFT_SIZE, (length) => tf.signal.hannWindow(length));
const real = tf.real(spectrum).slice([0, 0], [32, 3072]).transpose();
const imag = tf.imag(spectrum).slice([0, 0], [32, 3072]).transpose();
const output = tf.stack([real, imag], 0);
return tf.where(tf.isNaN(output), tf.zerosLike(output), output);
});
}
async function inverseChannel(tf, spectrogram) {
const frames = spectrogram.shape[1];
const output = new Float32Array(FFT_SIZE + HOP_SIZE * (frames - 1));
const window = await tf.signal.hannWindow(FFT_SIZE).data();
for (let index = 0; index < frames; index += 1) {
const frame = tf.tidy(() => {
const values = spectrogram.slice([0, index, 0], [-1, 1, 2]).squeeze([1]);
return tf.spectral.irfft(tf.complex(values.slice([0, 0], [-1, 1]).squeeze(), values.slice([0, 1], [-1, 1]).squeeze()));
});
const samples = await frame.data();
frame.dispose();
const offset = index * HOP_SIZE;
for (let cursor = 0; cursor < samples.length; cursor += 1) output[offset + cursor] += samples[cursor] * window[cursor];
}
return output;
}
async function istft(tf, tensor) {
const padded = tf.pad(tensor, [[0, 0], [0, 0], [0, 1], [0, 0]]);
const shaped = padded.reshape([2, 2, 3073, 32]).transpose([0, 2, 3, 1]);
const left = shaped.slice([0, 0, 0, 0], [1, -1, -1, -1]).squeeze([0]);
const right = shaped.slice([1, 0, 0, 0], [1, -1, -1, -1]).squeeze([0]);
const result = await Promise.all([inverseChannel(tf, left), inverseChannel(tf, right)]);
tf.dispose([padded, shaped, left, right]);
return result;
}
function wavBlob(channels, sampleRate) {
const frames = channels[0].length;
const buffer = new ArrayBuffer(44 + frames * 4);
const view = new DataView(buffer);
const text = (offset, value) => [...value].forEach((char, index) => view.setUint8(offset + index, char.charCodeAt(0)));
text(0, "RIFF"); view.setUint32(4, buffer.byteLength - 8, true); text(8, "WAVE"); text(12, "fmt ");
view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 2, true);
view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 4, true); view.setUint16(32, 4, true); view.setUint16(34, 16, true);
text(36, "data"); view.setUint32(40, frames * 4, true);
let offset = 44;
for (let frame = 0; frame < frames; frame += 1) for (let channel = 0; channel < 2; channel += 1) {
const sample = Math.max(-1, Math.min(1, channels[channel][frame] || 0));
view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true); offset += 2;
}
return new Blob([buffer], { type: "audio/wav" });
}
export async function separateVocals(blob, onProgress = () => {}) {
const tf = await getRuntime();
onProgress(4, { key: "vocalSeparationLoadingModel" });
const model = await getModel(tf);
onProgress(7, {
key: activeBackend === "webgpu" ? "vocalSeparationUsingWebGpu" : "vocalSeparationUsingWebGl",
});
const context = new AudioContext({ sampleRate: 44100 });
try {
const decoded = await context.decodeAudioData((await blob.arrayBuffer()).slice(0));
const left = decoded.getChannelData(0);
const right = decoded.numberOfChannels > 1 ? decoded.getChannelData(1) : left;
const accompaniment = [[], []];
const vocals = [[], []];
const chunks = Math.ceil(left.length / CHUNK_SIZE);
for (let index = 0; index < chunks; index += 1) {
const start = index * CHUNK_SIZE;
const valid = Math.min(CHUNK_SIZE, left.length - start);
const paddedLeft = new Float32Array(CHUNK_SIZE + PADDING * 2); paddedLeft.set(left.subarray(start, start + valid), PADDING);
const paddedRight = new Float32Array(CHUNK_SIZE + PADDING * 2); paddedRight.set(right.subarray(start, start + valid), PADDING);
const input = tf.tidy(() => {
const l = stft(tf, tf.tensor1d(paddedLeft)); const r = stft(tf, tf.tensor1d(paddedRight));
return tf.stack([l, r], 3).transpose([0, 3, 1, 2]).reshape([1, 4, 3072, 32]);
});
const musicTensor = model.predict(input);
const vocalTensor = tf.sub(input, musicTensor);
const [music, voice] = await Promise.all([istft(tf, musicTensor), istft(tf, vocalTensor)]);
for (let channel = 0; channel < 2; channel += 1) {
accompaniment[channel].push(...music[channel].slice(PADDING, PADDING + valid));
vocals[channel].push(...voice[channel].slice(PADDING, PADDING + valid));
}
tf.dispose([input, musicTensor, vocalTensor]);
onProgress(8 + Math.round(((index + 1) / chunks) * 88), {
key: "vocalSeparationProcessingChunk",
current: index + 1,
total: chunks,
});
await tf.nextFrame();
}
return {
vocals: wavBlob(vocals, decoded.sampleRate),
accompaniment: wavBlob(accompaniment, decoded.sampleRate),
backend: activeBackend,
};
} finally { await context.close().catch(() => {}); }
}
+39
View File
@@ -2027,6 +2027,16 @@ button:disabled {
background: #78a3ff;
}
.separation-entry-card {
border-color: rgba(196, 126, 255, 0.3);
background: linear-gradient(135deg, rgba(170, 91, 255, 0.14), rgba(103, 181, 255, 0.08)), rgba(255, 255, 255, 0.04);
}
.separation-entry-card svg {
color: #170a20;
background: #c47eff;
}
.inline-progress {
position: absolute;
left: 12px;
@@ -3141,6 +3151,15 @@ button:disabled {
background: rgba(46, 234, 216, 0.07);
}
.track-labels div.is-track-disabled {
color: #75818c;
background: rgba(255, 255, 255, 0.018);
}
.track-labels div.is-track-disabled > button:not(:first-child) {
opacity: 0.5;
}
.track-labels button {
display: grid;
place-items: center;
@@ -3305,6 +3324,26 @@ button:disabled {
cursor: pointer;
}
.image-track.is-track-disabled,
.caption-track.is-track-disabled,
.sticker-track.is-track-disabled,
.audio-track.is-track-disabled {
background: rgba(8, 12, 16, 0.32);
}
.is-track-disabled > .image-clip,
.is-track-disabled > .caption-segment,
.is-track-disabled > .sticker-segment,
.is-track-disabled > .audio-clip {
opacity: 0.32;
filter: grayscale(0.72) saturate(0.45);
pointer-events: none;
}
.is-track-disabled .image-resize-handle {
display: none;
}
.image-track {
gap: 2px;
overflow: hidden;