Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Add optional dialogue, music and ambience sound separation with sub-tracks, a toolbar button and...
Bowen Xuee1c3b64f20b9
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 4982971..64906f6 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -21,6 +21,7 @@ FreeVideo code uses [Apache-2.0](LICENSE). Its dependencies and models retain th| [Eigen](https://gitlab.com/libeigen/eigen) 5.0.1, compiled into sherpa-onnx and ONNX Runtime; source: https://gitlab.com/libeigen/eigen/-/tree/5.0.1 | MPL-2.0 || [Silero VAD](https://github.com/snakers4/silero-vad) v5.0 voice-activity model, © 2020-present Silero Team (optional download with subtitles, license file downloaded with the model; the onnx-community export is downloaded with the music model) | [MIT](freevideo_engine/licenses/Silero-VAD-MIT.txt) || [ACE-Step 1.5](https://github.com/ace-step/ACE-Step-1.5) XL turbo music model, © 2026 ACEStep (optional download for music; inference subset adapted in `freevideo_engine/music/acestep_model.py`) | [MIT](freevideo_engine/licenses/ACE-Step-MIT.txt) |+| [Bandit Plus](https://zenodo.org/records/10160698) cocktail-party separation model, weights by Watcharasupat et al. (optional download for sound separation, attribution required, non-commercial); code from [Bandit](https://github.com/kwatcharasupat/source-separation), © the Bandit authors, reduced to an inference subset in `freevideo_engine/stems/bandit/` (modified) | [CC BY-NC 4.0](freevideo_engine/licenses/Bandit-CC-BY-NC-4.0.txt) (weights), [Apache-2.0](freevideo_engine/licenses/Bandit-Apache-2.0.txt) (code) || [vector-quantize-pytorch](https://github.com/lucidrains/vector-quantize-pytorch), © 2020 Phil Wang (residual FSQ decoding adapted in `freevideo_engine/music/acestep_model.py`) | [MIT](freevideo_engine/licenses/Vector-Quantize-PyTorch-MIT.txt) || [Qwen3-Embedding-0.6B](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B), © Alibaba Cloud (text encoder of the music model, downloaded with it) | [Apache-2.0](freevideo_engine/licenses/Qwen3-Embedding-Apache-2.0.txt) || [NVIDIA NeMo stt_en_conformer_ctc_small](https://huggingface.co/nvidia/stt_en_conformer_ctc_small), © NVIDIA, exported to ONNX and quantized to int8 by the sherpa-onnx project, changed from the original; not endorsed by NVIDIA (optional download for English subtitles; [notice](freevideo_engine/licenses/NeMo-stt_en_conformer_ctc_small-NOTICE.txt)) | [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/) |diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.pyindex 6c03fe6..8f11a97 100644--- a/freevideo_engine/agent/errors.py+++ b/freevideo_engine/agent/errors.py@@ -121,6 +121,10 @@ ERRORS.update({'submit the music job again with a new ref; if it fails again, write the score yourself.'),'music_failed': (409, True, 'Composing the music did not finish.','Read the project, then submit the music job again with a new ref; if it fails again, write the score yourself.'),+ 'stems_download_failed': (409, True, 'The sound separation model could not be downloaded.',+ 'Tell the user the model needs a network connection, then submit the job again with a new ref.'),+ 'stems_failed': (409, True, 'Splitting the sound did not finish.',+ 'Read the project, then submit the job again with a new ref; if it fails again, leave the sound as it is.'),'clip_source_unusable': (409, False, 'A clip\'s source is missing, or cannot be read as far as the clip uses it.','Read the project and check each clip\'s source: it must exist and play, and in + frames must stay ''within its real length. Correct the project, then export the new revision.'),@@ -235,6 +239,8 @@ def recovery(code, *, kind=None, stage='request', resumable=True):return 'Tell the user to free disk space, then submit the picture again with a new ref.'if kind == 'music' and code == 'out_of_memory':return 'Close other GPU applications, then submit the music job again with a new ref.'+ if kind == 'stems' and code == 'out_of_memory':+ return 'Close other GPU applications, then submit the job again with a new ref.'if kind == 'image' and code == 'no_memory':return 'Lower the picture dimensions or use fewer reference pictures, then submit with a new ref.'if kind in RECOVERY and stage == 'terminal':diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.pyindex f0095b9..81726d2 100644--- a/freevideo_engine/agent/guide.py+++ b/freevideo_engine/agent/guide.py@@ -144,6 +144,7 @@ GUIDE = {'On 409 project_changed, recompute edits from error.project and its current_revision, then send a new request. On clip_busy wait for generation to finish.','POST /projects/{id}/generate reserves pending parts for clip_ids or a start/frames range and fills them as the returned job finishes. POST /projects/{id}/export renders the revision you read; wait for its job.','Music: POST /projects/{id}/music with the revision you read and a caption; wait for the job, then read the project: result.clip_ids are the new clips on a2. Run it after the cut is joined; a second run needs the earlier score removed from a2.',+ 'Split sound: POST /projects/{id}/stems with the revision you read and the clip_id of a sound clip; wait for the job. The clip\'s sound is split into dialogue, music and ambience on tracks a4, a5 and a6 over the clip\'s range, and the clip itself goes silent. result.parts lists each track with its name, clip_id, start, end and frames. Offered only where features lists projects.stems; a clip is split once, and deleting the three parts gives its sound back. To save the three tracks and the original mix as four wav files, POST /projects/{id}/stems/export with the revision and the split clip\'s clip_id; the answer lists folder and files at once.','Subtitles: POST /projects/{id}/listen with mode transcribe (writes down what is said) or align (times the lines you give) and the revision you read; wait for the job and read result.lines, each with start and end frames. Then add them with a subtitles operation of cues {start, frames, text}; replace true swaps the whole track. With no speech model the job fails with no_speech_model: write the lines yourself.','The user sees one line under each picture clip: its note, or else the first line of its description. A description is generation text, often long and in English, so after you add, generate or change a clip, write a note (operation note) in the user\'s language saying what is in the picture: the subject first, then the setting, for example "Train through morning mist" (in Chinese "小火车穿过晨雾"). A short clip shows only the first few characters, about four in Chinese, and those must already make sense on their own. Do not write where the clip sits (opening, middle, ending, part 2): the order of the clips shows that. Do not write how far along it is: the clip already shows its progress. Keep it true when you change the clip again.','Reuse ref or Idempotency-Key only for the identical request. Source video/audio/thumbnail URLs require the same Agent token.',@@ -377,6 +378,9 @@ CAPABILITIES_ZH = {'没有安装语音模型时返回 no_speech_model,改为自己写字幕行',('POST', '/projects/{id}/music'): '为剪辑时间线作一段与其等长的配乐,放在第二条声音轨道的开头,音量低于视频声音并带淡入淡出。''剪辑拼好后先读取 revision,并删去该轨道上原有的配乐;首次使用会下载音乐模型(约 20 GB)',+ ('POST', '/projects/{id}/stems'): '把一个声音片段的声音分成人声、音乐和环境声,放在其下方的 a4、a5、a6 三条轨道上,原片段静音。'+ '先读取 revision 与片段 ID,等待返回的任务完成,结果 parts 给出各轨道的名称、起止帧;仅在 features 含 projects.stems 时可用',+ ('POST', '/projects/{id}/stems/export'): '把已拆开片段的人声、音乐、环境声和原混音保存为四个 wav 文件;先读取 revision 与被拆片段的 ID,返回立即给出文件夹和文件名',('POST', '/images'): '像图片编辑页面一样打开图片;提交 source,会话会保留源图片副本和图层文档',('GET', '/images/{id}'): '读取图片编辑会话的图层文档、选区和 revision;编辑前先读取 revision 和图层标识',('PUT', '/images/{id}'): '替换整个图片文档;先读取会话并提交其 revision。'diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.pyindex 9cd7488..53d5b34 100644--- a/freevideo_engine/agent/jobs.py+++ b/freevideo_engine/agent/jobs.py@@ -32,7 +32,7 @@ from ..system import windowsACTIVE = ('waiting', 'queued', 'running', 'cancelling')CAST_AGAIN = 'POST /freevideo/agent/v1/cast/%s/generate to make the reference pictures again.'DONE = ('succeeded', 'failed', 'cancelled', 'interrupted')-GPU_KINDS = ('vlm', 'enhance', 'image', 'music')+GPU_KINDS = ('vlm', 'enhance', 'image', 'music', 'stems')IMAGE_ERRORS = errors.IMAGE_ERRORSIMAGE_WAIT_ERRORS = ('busy', 'busy_video')IMAGE_WAIT_NOTICES = {@@ -1485,6 +1485,9 @@ class Jobs:elif row['kind'] == 'music':from .music import run_musicresult = run_music(self, row)+ elif row['kind'] == 'stems':+ from .stems import run_stems+ result = run_stems(self, row)else:result = self.run_assemble(row)return resultdiff --git a/freevideo_engine/agent/projects.py b/freevideo_engine/agent/projects.pyindex dd7e2f2..619935c 100644--- a/freevideo_engine/agent/projects.py+++ b/freevideo_engine/agent/projects.py@@ -11,6 +11,7 @@ from copy import deepcopyimport hashlibimport jsonimport logging+from pathlib import Pathimport reimport secretsimport threading@@ -413,6 +414,70 @@ class Projects:self._remember(ref, digest, result, client)return result+ def stems(self, identity, value, *, jobs, ref=None, client=None):+ """Queue a sound-splitting job for one sound clip of the revision the caller read."""+ schema.validate(schema.project_schema('stems'), value)+ with self.listen_lock:+ digest, replay = self._receipt('projects:stems', dict(id=identity, body=value), ref, client)+ if replay is not None:+ return replay+ stored = self._load(identity)['project']+ if stored['revision'] != value['revision']:+ raise ProjectError('project_changed', project=stored)+ clip = _clips(stored).get(value['clip_id'])+ if clip is None or not clip.get('source') or clip.get('stem_of'):+ raise _invalid('/clip_id', 'a sound clip with media that is not itself a separated part', value['clip_id'])+ job = jobs.submit(dict(kind='stems', editor_project=identity,+ **{k: v for k, v in value.items() if k != 'ref'}), client=client)[0]+ result = dict(job=jobs.view(job), jobs=[jobs.view(job)])+ self._remember(ref, digest, result, client)+ return result++ def stems_export(self, identity, value, *, ref=None, client=None):+ """Copy the four wav files of a split clip into the saved sounds; the clip must be one that was split."""+ from ..stems.separate import SeparationError, export_tracks+ schema.validate(schema.project_schema('stems_export'), value)+ with self.listen_lock:+ digest, replay = self._receipt('projects:stems_export', dict(id=identity, body=value), ref, client)+ if replay is not None:+ return replay+ stored = self._load(identity)['project']+ if stored['revision'] != value['revision']:+ raise ProjectError('project_changed', project=stored)+ parts = [clip for clip in _clips(stored).values() if clip.get('stem_of') == value['clip_id']]+ if not parts:+ raise _invalid('/clip_id', 'a clip that was split into dialogue, music and ambience', value['clip_id'])+ folder = parts[0]['source']['id'].rsplit('/', 1)[0]+ if not folder.startswith('freevideo-stems/') or folder.count('/') != 1:+ raise _invalid('/clip_id', 'a clip split by this version', value['clip_id'])+ name = folder.split('/', 1)[1]+ try:+ files = export_tracks(Path(self.root) / folder, Path(self.root) / 'freevideo-stems-saved' / name)+ except SeparationError as error:+ raise JobError('stems_failed', 'The separated sound cannot be saved (%s)' % error) from error+ result = dict(editor_project=identity, revision=stored['revision'], clip_id=value['clip_id'],+ folder='freevideo-stems-saved/' + name, files=files)+ self._remember(ref, digest, result, client)+ return result++ def lay_stems(self, identity, clip_id, sources):+ """Put the three parts on sub-tracks under the clip and silence the clip; returns the save and the new clip IDs."""+ before, refused = {}, {}+ def change(project):+ before['ids'] = set(_clips(project))+ reply = editor_runtime.runtime().call('placeStems', project, [clip_id, {+ name: dict(kind='generated', id=source.split(':', 1)[1]) for name, source in sources.items()}],+ module='model', serialize=True)[0]+ if not reply['ok']:+ refused.update(reply['error'])+ return dict(ok=True, project=project)+ return dict(ok=True, project=reply['value'])+ saved = self._update(identity, change)+ if refused:+ code = STATE_CODES.get(refused.get('code'), 'stems_failed')+ raise JobError(code, 'The separated sound cannot be laid under the clip (%s)' % refused.get('code'))+ return saved, sorted(set(_clips(saved)) - before['ids'])+def lay_music(self, identity, source):"""Put a finished score on a2 from frame 0 of the project as it is now; returns the save and the new clip IDs."""found = comfy_editor.sources(self.root, [source])[source]diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex c95fcdd..79c82b5 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -172,7 +172,13 @@ def submit_batch(jobs, body, client):return jobs.submit_request(body, client=client)[0]-def features(continuation, vlm):+def stems_supported(machine):+ """Sound separation is offered on NVIDIA machines with enough video memory, never on a Mac."""+ from ..stems.service import supported+ return supported(machine.get('vram_gib'), uuid=machine.get('gpu_uuid')) and machine.get('device_backend', 'cuda') == 'cuda'+++def features(continuation, vlm, stems=False):"""What an agent can use here (ready says whether the engine can run now). A missing name is not offered."""from .editor_runtime import availablerules = available()@@ -183,7 +189,8 @@ def features(continuation, vlm):'queue.shared': True, 'queue.busy': True, 'chain.auto': bool(continuation),'enhance': bool(vlm.get('ready')), 'drama.film': True, 'images.edit': rules,'images.layers': rules, 'images.heal': rules, 'images.render': rules, 'projects.read': True,- **{'projects.' + name: rules for name in ('insert', 'split', 'move', 'trim', 'remove', 'export', 'generate', 'listen', 'music')}}+ **{'projects.' + name: rules for name in ('insert', 'split', 'move', 'trim', 'remove', 'export', 'generate', 'listen', 'music')},+ 'projects.stems': bool(rules and stems)}def whitebox_support(jobs):@@ -221,7 +228,7 @@ def capabilities(port, jobs):return dict(api_version=API_VERSION, freevideo_version=release or __version__, build=__version__, ready=ready, problem=problem,continuation=continuation,- features=features(continuation, vlm),+ features=features(continuation, vlm, stems=stems_supported(machine)),whitebox=whitebox_support(jobs),device=dict(backend=machine.get('device_backend', 'cuda') if machine else None,vram_limit_gib=machine.get('vram_gib'), ram_limit_gib=machine.get('ram_gib')),@@ -233,6 +240,7 @@ def capabilities(port, jobs):'export': 'Render a saved revision of an editing project to a video','listen': 'Listen to the sound of an editing project for subtitle lines and times','music': 'Compose music for an editing project and lay it on its second sound track',+ 'stems': 'Split the sound of a clip into dialogue, music and ambience on sub-tracks','image_edit': 'Render a saved revision of an image session to a picture'},limits=dict(width=[256, 4096, 32], height=[256, 4096, 32], seconds=[1.625, 60 if continuation else BLOCK_SECONDS],seconds_tested=[4, 15],@@ -507,7 +515,9 @@ def register():raise JobError('page_session_required', 'Page session required')header = request.headers.get('Authorization', '')given = header[7:].strip() if header[:7].lower() == 'bearer ' else request.headers.get('X-FreeVideo-Agent', '')- if definition.get('auth', True) or given:+ # The editor page may drive a few routes with its page session instead of the token.+ by_page = bool(definition.get('page_ok')) and not given and valid_page_session(request)+ if (definition.get('auth', True) and not by_page) or given:try:token = expected()except (OSError, ValueError):@@ -2215,7 +2225,7 @@ def register():raise JobError('idempotency_conflict', 'Conflicting keys')args = [] if operation == 'create' else [identity]extra = dict(client=request.headers.get('X-FreeVideo-Client', '')[:80] or None)- if operation in ('generate', 'export', 'listen', 'music'):+ if operation in ('generate', 'export', 'listen', 'music', 'stems'):extra['jobs'] = jobsif operation == 'generate':def capability(size):@@ -2225,9 +2235,9 @@ def register():return Noneextra['capability'] = capabilityresult = await asyncio.to_thread(getattr(projects, operation), *args, value, ref=key or ref, **extra)- if operation in ('generate', 'export', 'listen', 'music'):+ if operation in ('generate', 'export', 'listen', 'music', 'stems'):await jobs.tick()- return reply(result, 201 if operation in ('create', 'generate', 'export', 'listen', 'music') else 200)+ return reply(result, 201 if operation in ('create', 'generate', 'export', 'listen', 'music', 'stems') else 200)return guarded(handler)for operation, (method, suffix, _) in contract.PROJECT_OPERATIONS.items():diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.pyindex 905a4d0..f08e9be 100644--- a/freevideo_engine/agent/schema.py+++ b/freevideo_engine/agent/schema.py@@ -337,6 +337,20 @@ def music(*, local=False):**{'x-job-kind': 'music'})+STEMS_FIELDS = dict(+ clip_id=string(64))+# False leaves the three parts unplaced: the editor page lays them itself so its own saves never clash with the job's.+STEMS_LAY = dict(lay={'type': 'boolean', 'default': True})+++def stems(*, local=False):+ return obj(dict(kind={'const': 'stems', 'type': 'string'},+ editor_project=string(34, pattern=r'^e-[0-9a-f]{32}$'),+ revision=number(1, 2**53 - 1, integer=True),+ **STEMS_FIELDS, **STEMS_LAY, **common()), ('kind', 'editor_project', 'revision', 'clip_id'),+ **{'x-job-kind': 'stems'})++def image_edit(*, local=False):return obj(dict(kind={'const': 'image_edit', 'type': 'string'},image=dict(IMAGE, description='The image session to render (POST /images).'),@@ -347,12 +361,12 @@ def image_edit(*, local=False):KINDS = dict(generate=generate, assemble=assemble, vlm=vlm, enhance=enhance, image=image,- export=export, listen=listen, music=music, image_edit=image_edit)+ export=export, listen=listen, music=music, stems=stems, image_edit=image_edit)def job_schema(*, local=False, refs=False, batch=False):# Music scores a joined cut, so it is not a storyboard row.- value = {'oneOf': [f(local=local) for kind, f in KINDS.items() if not (batch and kind == 'music')], 'x-discriminator': 'kind',+ value = {'oneOf': [f(local=local) for kind, f in KINDS.items() if not (batch and kind in ('music', 'stems'))], 'x-discriminator': 'kind','description': 'x-discriminator selects field diagnostics by kind; all accepted branches use standard oneOf.'}return batch_references(value) if refs else value@@ -469,7 +483,7 @@ def contracts(*, local=False):if method == 'GET':extra['query'] = shapeelse:- extra.update(body=shape, idempotent=True, **({'status': 201} if name in ('create', 'generate', 'export', 'listen', 'music') else {}))+ extra.update(body=shape, idempotent=True, **({'status': 201} if name in ('create', 'generate', 'export', 'listen', 'music', 'stems') else {}))routes[method, suffix] = route(summary, **extra)for name, (method, suffix, summary) in WHITEBOX_OPERATIONS.items():extra = dict(path=obj({'id': WHITEBOX}, ('id',))) if '{id}' in suffix else {}@@ -546,6 +560,10 @@ def contracts(*, local=False):auth=False, page_or_token=True)routes['PUT', '/confirmations'] = route('Only the page user may change which operations need approval.',body=confirm_settings(), auth=False, page_or_token=True)+ # The editor page separates sound itself: these four also accept its page session, which never holds the token.+ for key in (('POST', '/projects/{id}/stems'), ('POST', '/projects/{id}/stems/export'),+ ('GET', '/jobs/{id}'), ('POST', '/jobs/{id}/cancel')):+ routes[key]['page_ok'] = Truereturn routes@@ -854,12 +872,15 @@ PROJECT_OPERATIONS = {'generate': ('POST', '/projects/{id}/generate', 'Make new picture and sound for selected clips or a frame range, as the page Generate does. First get revision and clip IDs; the parts are reserved at once and fill in as the returned job finishes.'),'export': ('POST', '/projects/{id}/export', 'Render one saved revision to an MP4 in the saved videos. First get the revision; wait for the returned job, then read its result video.'),'listen': ('POST', '/projects/{id}/listen', 'Listen to the timeline sound for subtitles: mode align times lines you give, transcribe writes down what is said. First get the revision; wait for the returned job, then add the lines with the subtitles edit. Nothing is saved; with no speech model for the language the call fails with no_speech_model, so write the lines by hand.'),+ 'stems': ('POST', '/projects/{id}/stems', 'Split one clip\'s sound into dialogue, music and ambience on tracks a4-a6. First get the revision and clip ID; wait for the job, then read result.parts.'),+ 'stems_export': ('POST', '/projects/{id}/stems/export', 'Save the separated dialogue, music and ambience of a split clip, with its original mix, as four wav files in the saved sounds. First get the revision and the split clip\'s ID; the answer lists the files at once.'),'music': ('POST', '/projects/{id}/music', 'Compose music as long as the joined cut and lay it on sound track a2 at frame 0, under the video sound. First get the revision; a2 must be empty. Wait for the returned job; the first use downloads the model (20 GB).'),}PROJECT_TOOLS = dict(list='freevideo_projects', get='freevideo_project_read', create='freevideo_project_create',write='freevideo_project_write', operations='freevideo_editor_operations',generate='freevideo_project_generate', export='freevideo_export',- listen='freevideo_project_listen', music='freevideo_project_music')+ listen='freevideo_project_listen', music='freevideo_project_music',+ stems='freevideo_project_stems', stems_export='freevideo_project_stems_export')SESSION_OPERATIONS = {'create': ('POST', '/sessions', 'Create a work conversation for messages and plans shared with the user.'),@@ -980,6 +1001,8 @@ def project_schema(name):return obj(dict(revision=revision, **LISTEN_FIELDS, ref=REF), ('revision', 'mode'))if name == 'music':return obj(dict(revision=revision, **MUSIC_FIELDS, ref=REF), ('revision', 'caption'))+ if name in ('stems', 'stems_export'):+ return obj(dict(revision=revision, **STEMS_FIELDS, **(STEMS_LAY if name == 'stems' else {}), ref=REF), ('revision', 'clip_id'))if name != 'operations':return EMPTYfields = {@@ -1433,6 +1456,8 @@ def openapi():if contract.get('raw_body'):operation['requestBody'] = dict(required=True, content={'application/octet-stream': {'schema': {'type': 'string', 'format': 'binary', 'maxLength': MAX_CHAT_ATTACHMENT_BYTES}}})+ if contract.get('page_ok'):+ operation['security'] = [{'bearer': []}, {'page': []}]if contract.get('page_or_token'):operation['security'] = [{'page': []}] if suffix.endswith(('/stop', '/resume')) else [{'bearer': []}, {'page': []}]if contract['body'] is not None:@@ -1452,6 +1477,9 @@ def openapi():if suffix == '/freevideo/agent/chat/attach':operation['parameters'].append(dict(name='X-FreeVideo-CSRF', **{'in': 'header'}, required=True,schema=string(128), description='The page session CSRF token.'))+ if contract.get('page_ok'):+ operation['parameters'].append(dict(name='X-FreeVideo-CSRF', **{'in': 'header'}, required=False,+ schema=string(128), description='With the freevideo_agent_page cookie, in place of the token.'))if contract.get('page_or_token'):operation['parameters'].append(dict(name='X-FreeVideo-CSRF', **{'in': 'header'}, required=False,schema=string(128), description='Required with the freevideo_agent_page cookie, including reads.'))diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.pyindex 46846f8..f19581f 100644--- a/freevideo_engine/agent/spec.py+++ b/freevideo_engine/agent/spec.py@@ -297,6 +297,9 @@ def normalize(value, *, port=None):elif kind == 'music':result.update(editor_project=value['editor_project'], revision=value['revision'], caption=value['caption'],**{k: value[k] for k in ('seed', 'quiet') if k in value})+ elif kind == 'stems':+ result.update(editor_project=value['editor_project'], revision=value['revision'], clip_id=value['clip_id'],+ lay=value.get('lay', True))elif kind == 'image_edit':result.update(image=value['image'], revision=value['revision'])else:diff --git a/freevideo_engine/agent/stems.py b/freevideo_engine/agent/stems.pynew file mode 100644index 0000000..cecaa30--- /dev/null+++ b/freevideo_engine/agent/stems.py@@ -0,0 +1,85 @@+"""Stem jobs: the sound of one clip split into dialogue, music and ambience, laid on three sub-tracks."""+import json+import secrets+import time++from .jobs import JobError++FOLDER = 'freevideo-stems'+# A video that starts while the sound is split stops it; the job waits for the video and splits again.+PREEMPTIONS = 8+NAMES = ('dialogue', 'music', 'ambience')+++def _busy(jobs):+ port = jobs.port+ return jobs.runner_busy() or port.queue_busy() or port.image_busy() or port.vlm_busy()+++def run_stems(jobs, row, *, poll=.5):+ from ..editor_export import resolve_source+ from ..stems import service+ spec, port = row['spec'], jobs.port+ try:+ project = jobs.projects.get(spec['editor_project'])['project']+ except FileNotFoundError as error:+ raise JobError('not_found', 'The project does not exist') from error+ clip = next((clip for track in project['tracks'] if track['kind'] == 'audio' for clip in track['clips']+ if clip['id'] == spec['clip_id']), None)+ if clip is None or not clip.get('source'):+ raise JobError('invalid_request', 'The clip is not a sound clip with media')+ try:+ found = resolve_source('%s:%s' % (clip['source']['kind'], clip['source']['id']))+ except (OSError, ValueError) as error:+ raise JobError('stems_failed', 'The clip media is not readable', kind='stems') from error+ source = found['audio']+ if source is None:+ raise JobError('stems_failed', 'The clip has no sound', kind='stems')+ folder = '%s/%s-%s' % (FOLDER, row['id'], secrets.token_hex(4))+ out = port.output_path(folder + '/dialogue.mp4', create=True).parent++ def phase(name, fraction=None):+ row['_phase'] = name+ row['_detail'] = json.dumps(dict(fraction=round(fraction, 3))) if fraction is not None else None++ try:+ numbers = _split(jobs, row, service, source, out, phase, poll)+ sources = {name: 'generated:%s/%s.mp4' % (folder, name) for name in NAMES}+ if not spec.get('lay', True):+ return dict(editor_project=spec['editor_project'], clip_id=spec['clip_id'], sources=sources, parts=[], clip_ids=[],+ seconds=numbers.get('seconds'), separate_seconds=numbers.get('elapsed'))+ phase('placing')+ saved, clip_ids = jobs.projects.lay_stems(spec['editor_project'], spec['clip_id'], sources)+ except BaseException:+ for path in out.glob('*'):+ path.unlink(missing_ok=True)+ out.rmdir()+ raise+ fresh = set(clip_ids)+ parts = [dict(track=track['id'], name=track['stem'], clip_id=clip['id'], start=clip['start'], frames=clip['frames'],+ end=clip['start'] + clip['frames'])+ for track in saved['tracks'] if track.get('stem') for clip in track['clips'] if clip['id'] in fresh]+ return dict(editor_project=spec['editor_project'], revision=saved['revision'], clip_ids=clip_ids, sources=sources,+ parts=parts, seconds=numbers.get('seconds'),+ separate_seconds=numbers.get('elapsed'))+++def _split(jobs, row, service, source, out, phase, poll):+ for attempt in range(PREEMPTIONS + 1):+ try:+ return service.separate(source, out, server=getattr(jobs.port, 'server', None),+ cancelled=lambda: bool(row.get('_cancel')), phase=phase)+ except service.Preempted:+ if attempt == PREEMPTIONS:+ raise JobError('stems_failed', 'Videos kept starting while the sound was being split', kind='stems') from None+ phase('waiting')+ while True:+ if row.get('_cancel'):+ raise JobError('cancelled', 'Cancelled') from None+ time.sleep(poll)+ if not _busy(jobs):+ break+ except InterruptedError:+ raise JobError('cancelled', 'Cancelled') from None+ except service.StemsError as error:+ raise JobError(error.code, 'The sound was not split (%s)' % (error.reason or error.code), kind='stems') from Nonediff --git a/freevideo_engine/comfy_editor.py b/freevideo_engine/comfy_editor.pyindex 3c6b199..a692512 100644--- a/freevideo_engine/comfy_editor.py+++ b/freevideo_engine/comfy_editor.py@@ -30,7 +30,7 @@ from .editor_frames import frame_not_after, last_frame_endfrom .editor_limits import PROJECT_BYTESfrom .editor_speed import validate_clip, register_reversefrom .editor_transport import marker_fields-from .editor_audio import clip_fields, track_fields+from .editor_audio import STEM_TRACKS, clip_fields, track_fieldsFPS = 24MAX_IMPORT_BYTES = 8 * 1024**3@@ -187,14 +187,16 @@ def validate(record):if not _text(json.dumps(settings, ensure_ascii=False, allow_nan=False, separators=(',', ':')), 1024 * 1024):raise ValueError('Settings are too large')raw_tracks = record.get('tracks')- expected = [('v1', 'video'), ('a1', 'audio'), ('a2', 'audio')]- if not isinstance(raw_tracks, list) or len(raw_tracks) not in (2, 3):+ expected = [('v1', 'video'), ('a1', 'audio'), ('a2', 'audio'), ('a3', 'audio'), ('a4', 'audio'), ('a5', 'audio'), ('a6', 'audio')]+ if not isinstance(raw_tracks, list) or len(raw_tracks) not in (2, 3, 7):raise ValueError('Invalid tracks')tracks, seen = [], {}for raw_track, (track_id, kind) in zip(raw_tracks, expected):if (not isinstance(raw_track, dict) or raw_track.get('id') != track_id or raw_track.get('kind') != kindor not isinstance(raw_track.get('clips'), list) or len(raw_track['clips']) > 500):raise ValueError('Invalid track')+ if (raw_track.get('stem') != (STEM_TRACKS[len(tracks) - 4] if len(tracks) >= 4 else None)):+ raise ValueError('Invalid track')clips, end = [], 0for raw in raw_track['clips']:if not isinstance(raw, dict):diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.pyindex 93a1231..9b9b59d 100644--- a/freevideo_engine/comfy_nodes.py+++ b/freevideo_engine/comfy_nodes.py@@ -263,6 +263,11 @@ class FreeVideoGenerate(io.ComfyNode):note('video', path(comfy_bridge.installation_root()))except Exception as error:logging.warning('[FreeVideo] Could not record the video for the picture worker: %s', error)+ try: # nor splitting a clip's sound, which starts again after the video+ from .stems.service import stop_for_generation as stop_stems_for_generation+ stop_stems_for_generation(PromptServer.instance)+ except Exception as error:+ logging.warning('[FreeVideo] Could not stop sound separation before the video: %s', error)prewarm = {}result_reused = [False]result_report = [None]diff --git a/freevideo_engine/comfy_progress.py b/freevideo_engine/comfy_progress.pyindex fd6174d..e1226ea 100644--- a/freevideo_engine/comfy_progress.py+++ b/freevideo_engine/comfy_progress.py@@ -428,6 +428,19 @@ def register():info = await asyncio.to_thread(feedback.collect, request.query.get('report_id'))return web.json_response(info, headers={'Cache-Control': 'no-store'})+ @server.routes.get('/freevideo/stems-support')+ async def stems_support(request):+ # The editor page asks once whether to offer sound separation; the agent feature list needs a token the page never holds.+ def offered():+ from .agent.editor_runtime import available+ from .agent.routes import stems_supported+ from .comfy_bridge import installation+ try:+ return bool(available() and stems_supported(installation()[1]))+ except (OSError, ValueError):+ return False+ return web.json_response({'available': await asyncio.to_thread(offered)}, headers={'Cache-Control': 'no-store'})+@server.routes.get('/freevideo/progress')async def progress(request):return web.json_response({'progress': STATE.snapshot()},diff --git a/freevideo_engine/editor_audio.py b/freevideo_engine/editor_audio.pyindex ab605d8..30af9fd 100644--- a/freevideo_engine/editor_audio.py+++ b/freevideo_engine/editor_audio.py@@ -4,6 +4,8 @@ import refrom .editor_speed import changed, audio_changed, source_sample_start+STEM_TRACKS = ('dialogue', 'music', 'ambience')+def clip_fields(raw, kind):result = {}@@ -29,6 +31,17 @@ def clip_fields(raw, kind):if kind != 'audio' or type(raw['duck']) is not bool:raise ValueError('Invalid audio ducking')result['duck'] = raw['duck']+ if 'stem_of' in raw:+ value = raw['stem_of']+ if (kind != 'audio' or not isinstance(value, str) or not re.fullmatch(r'c[1-9]\d{0,8}', value)+ or value == raw['id'] or raw.get('link')):+ raise ValueError('Invalid separated sound')+ result['stem_of'] = value+ if 'stem_volume' in raw:+ value = raw['stem_volume']+ if kind != 'audio' or type(value) not in (int, float) or not 0 <= value <= 2:+ raise ValueError('Invalid separated sound')+ result['stem_volume'] = valuereturn result@@ -39,6 +52,10 @@ def track_fields(raw):if type(raw[name]) is not bool:raise ValueError('Invalid audio track flag')result[name] = raw[name]+ if 'stem' in raw:+ if raw['stem'] not in STEM_TRACKS:+ raise ValueError('Invalid audio track flag')+ result['stem'] = raw['stem']return resultdiff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.pyindex 01a0659..9517c45 100644--- a/freevideo_engine/editor_export.py+++ b/freevideo_engine/editor_export.py@@ -113,7 +113,7 @@ def _layout(project):project = validate(project)raw_tracks = [t for t in project['tracks'] if not is_text_track(t)]if not isinstance(raw_tracks, list) or [t.get('id') for t in raw_tracks if isinstance(t, dict)] not in (- ['v1', 'a1'], ['v1', 'a1', 'a2']):+ ['v1', 'a1'], ['v1', 'a1', 'a2'], ['v1', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6']):raise ExportError()tracks, seen = {}, set()for raw in raw_tracks:@@ -777,7 +777,7 @@ def _render_once(project, resolve, target, *, progress, cancelled, options, repaif progress:progress(written / total * .99)mixed = np.zeros((2, SAMPLES_PER_FRAME), dtype=np.float32)- for track in ('a1', 'a2'):+ for track in ('a1', 'a2', 'a3', 'a4', 'a5', 'a6'):clip = active.get(track)if track not in audio_tracks:continuediff --git a/freevideo_engine/editor_text.py b/freevideo_engine/editor_text.pyindex 8e76892..a38a0c7 100644--- a/freevideo_engine/editor_text.py+++ b/freevideo_engine/editor_text.py@@ -91,7 +91,7 @@ def validate_text_project(raw, validate_media):if row['clips']: result['tracks'].append(row)style = clean_style(raw.get('subtitle_style',{}),'subtitle')if style and any(t['kind'] == 'subtitle' for t in result['tracks']): result['subtitle_style'] = style- result['tracks'].sort(key=lambda t: ['v1','a1','a2','t1','s1'].index(t['id']))+ result['tracks'].sort(key=lambda t: ['v1','a1','a2','a3','a4','a5','a6','t1','s1'].index(t['id']))return resultdiff --git a/freevideo_engine/image_gen/image_models.json b/freevideo_engine/image_gen/image_models.jsonindex 86f7f86..269cae2 100644--- a/freevideo_engine/image_gen/image_models.json+++ b/freevideo_engine/image_gen/image_models.json@@ -685,6 +685,27 @@}]}+ ],+ "stems": [+ {+ "file": "stems/bandit_plus_cocktail.pt",+ "component": "stems",+ "bytes": 148724733,+ "sha256": "02ad94875ae060e03428af0e667a5a5cbfa1a6c2355f07f32c499be8d615ba1c",+ "repo": "BowenXue/FreeVideo-models",+ "revision": "2ed0b3b98ea92dec01699dc97d96e15cfe208d69",+ "model_id": "bandit-plus-cocktail",+ "sources": [+ {+ "id": "official",+ "url": "https://huggingface.co/BowenXue/FreeVideo-models/resolve/2ed0b3b98ea92dec01699dc97d96e15cfe208d69/stems/bandit_plus_cocktail.pt"+ },+ {+ "id": "modelscope",+ "url": "https://www.modelscope.cn/models/BowenXue/FreeVideo-models/resolve/master/stems/bandit_plus_cocktail.pt"+ }+ ]+ }]}}diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.pyindex 4fdd0c3..2308bbb 100644--- a/freevideo_engine/image_gen/image_pack.py+++ b/freevideo_engine/image_gen/image_pack.py@@ -140,7 +140,7 @@ def validate_catalog(spec):raise PackError('invalid_catalog')image_rows = spec['groups']['image']# A group of its own holds only its own component; the image group holds neither.- own = {group: spec['groups'].get(group, []) for group in ('segment', 'music')}+ own = {group: spec['groups'].get(group, []) for group in ('segment', 'music', 'stems')}found = image_rows + [row for found in own.values() for row in found]if (not image_rows or len({r['file'] for r in found}) != len(found) or set(spec['groups']) - {'image', *own}or any(row['component'] in own for row in image_rows)@@ -150,7 +150,7 @@ def validate_catalog(spec):_relative(row['file'])if (type(row['bytes']) is not int or row['bytes'] <= 0or not re.fullmatch('[0-9a-f]{64}', row['sha256'])- or row['component'] not in ('dit', 'text_encoder', 'vae', 'text_encoder_config', 'processor', 'segment', 'music')):+ or row['component'] not in ('dit', 'text_encoder', 'vae', 'text_encoder_config', 'processor', 'segment', 'music', 'stems')):raise PackError('invalid_catalog')ids = [s['id'] for s in row['sources']]required = {'official', 'modelscope'}@@ -233,8 +233,13 @@ MUSIC_NOTICE_TEXT = (b'ACE-Step 1.5, Copyright (c) 2026 ACEStep. Licensed underb'freevideo_engine/licenses/Qwen3-Embedding-Apache-2.0.txt.\nhttps://huggingface.co/Qwen/Qwen3-Embedding-0.6B\n'b'Silero VAD, Copyright (c) 2020-present Silero Team. Licensed under the MIT License; see 'b'freevideo_engine/licenses/Silero-VAD-MIT.txt.\nhttps://github.com/snakers4/silero-vad\n')+STEMS_NOTICE_TEXT = (b'Bandit Plus (cocktail-party separation model). Weights: Watcharasupat et al., CC BY-NC 4.0; see '+ b'freevideo_engine/licenses/Bandit-CC-BY-NC-4.0.txt.\nhttps://zenodo.org/records/10160698\n'+ b'Code: Copyright (c) the Bandit authors, Apache-2.0; see freevideo_engine/licenses/Bandit-Apache-2.0.txt.\n'+ b'https://github.com/kwatcharasupat/source-separation\n')NOTICES = {'image': ('NOTICE.txt', NOTICE_TEXT), 'segment': ('SAM2-NOTICE.txt', SEGMENT_NOTICE_TEXT),- 'music': ('MUSIC-NOTICE.txt', MUSIC_NOTICE_TEXT)}+ 'music': ('MUSIC-NOTICE.txt', MUSIC_NOTICE_TEXT),+ 'stems': ('STEMS-NOTICE.txt', STEMS_NOTICE_TEXT)}def _notice():@@ -929,7 +934,7 @@ def main(argv=None):commands = parser.add_subparsers(dest='command', required=True)download = commands.add_parser('download')download.add_argument('--background', action='store_true')- download.add_argument('--group', choices=('image', 'segment'), default='image')+ download.add_argument('--group', choices=('image', 'segment', 'music', 'stems'), default='image')download.add_argument('--root', type=Path)download.add_argument('--engine-root', type=Path)download.add_argument('--status-file', type=Path, required=True)diff --git a/freevideo_engine/licenses/Bandit-Apache-2.0.txt b/freevideo_engine/licenses/Bandit-Apache-2.0.txtnew file mode 100644index 0000000..3b6e7a4--- /dev/null+++ b/freevideo_engine/licenses/Bandit-Apache-2.0.txt@@ -0,0 +1,207 @@+Apache License+Version 2.0, January 2004+http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction, and+ distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by the+ copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all other+ entities that control, are controlled by, or are under common control with+ that entity. For the purposes of this definition, "control" means (i) the+ power, direct or indirect, to cause the direction or management of such+ entity, whether by contract or otherwise, or (ii) ownership of+ fifty percent (50%) or more of the outstanding shares, or (iii) beneficial+ ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity exercising+ permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation source,+ and configuration files.++ "Object" form shall mean any form resulting from mechanical transformation+ or translation of a Source form, including but not limited to compiled+ object code, generated documentation, and conversions to+ other media types.++ "Work" shall mean the work of authorship, whether in Source or Object+ form, made available under the License, as indicated by a copyright notice+ that is included in or attached to the work (an example is provided in the+ Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object form,+ that is based on (or derived from) the Work and for which the editorial+ revisions, annotations, elaborations, or other modifications represent,+ as a whole, an original work of authorship. For the purposes of this+ License, Derivative Works shall not include works that remain separable+ from, or merely link (or bind by name) to the interfaces of, the Work and+ Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including the original+ version of the Work and any modifications or additions to that Work or+ Derivative Works thereof, that is intentionally submitted to Licensor for+ inclusion in the Work by the copyright owner or by an individual or+ Legal Entity authorized to submit on behalf of the copyright owner.+ For the purposes of this definition, "submitted" means any form of+ electronic, verbal, or written communication sent to the Licensor or its+ representatives, including but not limited to communication on electronic+ mailing lists, source code control systems, and issue tracking systems+ that are managed by, or on behalf of, the Licensor for the purpose of+ discussing and improving the Work, but excluding communication that is+ conspicuously marked or otherwise designated in writing by the copyright+ owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity on+ behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++2. Grant of Copyright License.++ Subject to the terms and conditions of this License, each Contributor+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,+ royalty-free, irrevocable copyright license to reproduce, prepare+ Derivative Works of, publicly display, publicly perform, sublicense,+ and distribute the Work and such Derivative Works in+ Source or Object form.++3. Grant of Patent License.++ Subject to the terms and conditions of this License, each Contributor+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,+ royalty-free, irrevocable (except as stated in this section) patent+ license to make, have made, use, offer to sell, sell, import, and+ otherwise transfer the Work, where such license applies only to those+ patent claims licensable by such Contributor that are necessarily+ infringed by their Contribution(s) alone or by combination of their+ Contribution(s) with the Work to which such Contribution(s) was submitted.+ If You institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a+ Contribution incorporated within the Work constitutes direct or+ contributory patent infringement, then any patent licenses granted to+ You under this License for that Work shall terminate as of the date such+ litigation is filed.++4. Redistribution.++ You may reproduce and distribute copies of the Work or Derivative Works+ thereof in any medium, with or without modifications, and in Source or+ Object form, provided that You meet the following conditions:++ 1. You must give any other recipients of the Work or Derivative Works a+ copy of this License; and++ 2. You must cause any modified files to carry prominent notices stating+ that You changed the files; and++ 3. You must retain, in the Source form of any Derivative Works that You+ distribute, all copyright, patent, trademark, and attribution notices from+ the Source form of the Work, excluding those notices that do not pertain+ to any part of the Derivative Works; and++ 4. If the Work includes a "NOTICE" text file as part of its distribution,+ then any Derivative Works that You distribute must include a readable copy+ of the attribution notices contained within such NOTICE file, excluding+ those notices that do not pertain to any part of the Derivative Works,+ in at least one of the following places: within a NOTICE text file+ distributed as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or, within a+ display generated by the Derivative Works, if and wherever such+ third-party notices normally appear. The contents of the NOTICE file are+ for informational purposes only and do not modify the License.+ You may add Your own attribution notices within Derivative Works that You+ distribute, alongside or as an addendum to the NOTICE text from the Work,+ provided that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and may+ provide additional or different license terms and conditions for use,+ reproduction, or distribution of Your modifications, or for any such+ Derivative Works as a whole, provided Your use, reproduction, and+ distribution of the Work otherwise complies with the conditions+ stated in this License.++5. Submission of Contributions.++ Unless You explicitly state otherwise, any Contribution intentionally+ submitted for inclusion in the Work by You to the Licensor shall be under+ the terms and conditions of this License, without any additional+ terms or conditions. Notwithstanding the above, nothing herein shall+ supersede or modify the terms of any separate license agreement you may+ have executed with Licensor regarding such Contributions.++6. Trademarks.++ This License does not grant permission to use the trade names, trademarks,+ service marks, or product names of the Licensor, except as required for+ reasonable and customary use in describing the origin of the Work and+ reproducing the content of the NOTICE file.++7. Disclaimer of Warranty.++ Unless required by applicable law or agreed to in writing, Licensor+ provides the Work (and each Contributor provides its Contributions)+ on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,+ either express or implied, including, without limitation, any warranties+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS+ FOR A PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any risks+ associated with Your exercise of permissions under this License.++8. Limitation of Liability.++ In no event and under no legal theory, whether in tort+ (including negligence), contract, or otherwise, unless required by+ applicable law (such as deliberate and grossly negligent acts) or agreed+ to in writing, shall any Contributor be liable to You for damages,+ including any direct, indirect, special, incidental, or consequential+ damages of any character arising as a result of this License or out of+ the use or inability to use the Work (including but not limited to damages+ for loss of goodwill, work stoppage, computer failure or malfunction,+ or any and all other commercial damages or losses), even if such+ Contributor has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability.++ While redistributing the Work or Derivative Works thereof, You may choose+ to offer, and charge a fee for, acceptance of support, warranty,+ indemnity, or other liability obligations and/or rights consistent with+ this License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf of any+ other Contributor, and only if You agree to indemnify, defend, and hold+ each Contributor harmless for any liability incurred by, or claims+ asserted against, such Contributor by reason of your accepting any such+ warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work++ To apply the Apache License to your work, attach the following boilerplate+ notice, with the fields enclosed by brackets "[]" replaced with your own+ identifying information. (Don't include the brackets!) The text should be+ enclosed in the appropriate comment syntax for the file format. We also+ recommend that a file or class name and description of purpose be included+ on the same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright {{ year }} {{ organization }}++ 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.diff --git a/freevideo_engine/licenses/Bandit-CC-BY-NC-4.0.txt b/freevideo_engine/licenses/Bandit-CC-BY-NC-4.0.txtnew file mode 100644index 0000000..b90ca83--- /dev/null+++ b/freevideo_engine/licenses/Bandit-CC-BY-NC-4.0.txt@@ -0,0 +1,10 @@+Bandit Plus cocktail-party separation weights (speech / music / effects).++Credit: Karn N. Watcharasupat, Chih-Wei Wu, Iroro Orife, "Divide and Remaster / Banquet / Bandit:+Source Separation for the Cocktail Party Problem" (Bandit, Bandit Plus), and the Divide and Remaster+v3 dataset authors. Weights released at https://zenodo.org/records/10160698+Code: https://github.com/kwatcharasupat/source-separation (Apache-2.0, see Bandit-Apache-2.0.txt).++The weights are licensed under the Creative Commons Attribution-NonCommercial 4.0 International+License (CC BY-NC 4.0): https://creativecommons.org/licenses/by-nc/4.0/legalcode+FreeVideo converts the checkpoint to a plain state dictionary without changing any value.diff --git a/freevideo_engine/stems/__init__.py b/freevideo_engine/stems/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/freevideo_engine/stems/bandit/__init__.py b/freevideo_engine/stems/bandit/__init__.pynew file mode 100644index 0000000..8633475--- /dev/null+++ b/freevideo_engine/stems/bandit/__init__.py@@ -0,0 +1,2 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.diff --git a/freevideo_engine/stems/bandit/bandsplit.py b/freevideo_engine/stems/bandit/bandsplit.pynew file mode 100644index 0000000..c09876e--- /dev/null+++ b/freevideo_engine/stems/bandit/bandsplit.py@@ -0,0 +1,141 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+from typing import List, Tuple++import torch+from torch import nn++from .utils import (+ band_widths_from_specs,+ check_no_gap,+ check_no_overlap,+ check_nonzero_bandwidth,+)+++class NormFC(nn.Module):+ def __init__(+ self,+ emb_dim: int,+ bandwidth: int,+ in_channel: int,+ normalize_channel_independently: bool = False,+ treat_channel_as_feature: bool = True,+ ) -> None:+ super().__init__()++ self.treat_channel_as_feature = treat_channel_as_feature++ if normalize_channel_independently:+ raise NotImplementedError++ reim = 2++ self.norm = nn.LayerNorm(in_channel * bandwidth * reim)++ fc_in = bandwidth * reim++ if treat_channel_as_feature:+ fc_in *= in_channel+ else:+ assert emb_dim % in_channel == 0+ emb_dim = emb_dim // in_channel++ self.fc = nn.Linear(fc_in, emb_dim)++ def forward(self, xb):+ # xb = (batch, n_time, in_chan, reim * band_width)++ batch, n_time, in_chan, ribw = xb.shape+ xb = self.norm(xb.reshape(batch, n_time, in_chan * ribw))+ # (batch, n_time, in_chan * reim * band_width)++ if not self.treat_channel_as_feature:+ xb = xb.reshape(batch, n_time, in_chan, ribw)+ # (batch, n_time, in_chan, reim * band_width)++ zb = self.fc(xb)+ # (batch, n_time, emb_dim)+ # OR+ # (batch, n_time, in_chan, emb_dim_per_chan)++ if not self.treat_channel_as_feature:+ batch, n_time, in_chan, emb_dim_per_chan = zb.shape+ # (batch, n_time, in_chan, emb_dim_per_chan)+ zb = zb.reshape((batch, n_time, in_chan * emb_dim_per_chan))++ return zb # (batch, n_time, emb_dim)+++class BandSplitModule(nn.Module):+ def __init__(+ self,+ band_specs: List[Tuple[float, float]],+ emb_dim: int,+ in_channel: int,+ require_no_overlap: bool = False,+ require_no_gap: bool = True,+ normalize_channel_independently: bool = False,+ treat_channel_as_feature: bool = True,+ ) -> None:+ super().__init__()++ check_nonzero_bandwidth(band_specs)++ if require_no_gap:+ check_no_gap(band_specs)++ if require_no_overlap:+ check_no_overlap(band_specs)++ self.band_specs = band_specs+ # list of [fstart, fend) in index.+ # Note that fend is exclusive.+ self.band_widths = band_widths_from_specs(band_specs)+ self.n_bands = len(band_specs)+ self.emb_dim = emb_dim++ self.norm_fc_modules = nn.ModuleList(+ [ # type: ignore+ (+ NormFC(+ emb_dim=emb_dim,+ bandwidth=bw,+ in_channel=in_channel,+ normalize_channel_independently=normalize_channel_independently,+ treat_channel_as_feature=treat_channel_as_feature,+ )+ )+ for bw in self.band_widths+ ]+ )++ def forward(self, x: torch.Tensor):+ # x = complex spectrogram (batch, in_chan, n_freq, n_time)++ batch, in_chan, _, n_time = x.shape++ z = torch.zeros(+ size=(batch, self.n_bands, n_time, self.emb_dim),+ device=x.device+ )++ xr = torch.view_as_real(x) # batch, in_chan, n_freq, n_time, 2+ xr = torch.permute(+ xr,+ (0, 3, 1, 4, 2)+ ) # batch, n_time, in_chan, 2, n_freq+ batch, n_time, in_chan, reim, band_width = xr.shape+ for i, nfm in enumerate(self.norm_fc_modules):+ # print(f"bandsplit/band{i:02d}")+ fstart, fend = self.band_specs[i]+ xb = xr[..., fstart:fend]+ # (batch, n_time, in_chan, reim, band_width)+ xb = torch.reshape(xb, (batch, n_time, in_chan, -1))+ # (batch, n_time, in_chan, reim * band_width)+ # z.append(nfm(xb)) # (batch, n_time, emb_dim)+ z[:, i, :, :] = nfm(xb.contiguous())++ # z = torch.stack(z, dim=1)++ return zdiff --git a/freevideo_engine/stems/bandit/base.py b/freevideo_engine/stems/bandit/base.pynew file mode 100644index 0000000..32cf48c--- /dev/null+++ b/freevideo_engine/stems/bandit/base.py@@ -0,0 +1,20 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+from abc import ABC+from typing import Iterable, Mapping, Union++from torch import nn++++class BandsplitCoreBase(nn.Module, ABC):+ band_split: nn.Module+ tf_model: nn.Module+ mask_estim: Union[nn.Module, Mapping[str, nn.Module], Iterable[nn.Module]]++ def __init__(self) -> None:+ super().__init__()++ @staticmethod+ def mask(x, m):+ return x * mdiff --git a/freevideo_engine/stems/bandit/core.py b/freevideo_engine/stems/bandit/core.pynew file mode 100644index 0000000..83b3e3c--- /dev/null+++ b/freevideo_engine/stems/bandit/core.py@@ -0,0 +1,236 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+from typing import Dict, List, Optional, Tuple++import torch+from torch import nn++from .base import BandsplitCoreBase+from .bandsplit import BandSplitModule+from .maskestim import (+ MaskEstimationModule,+ OverlappingMaskEstimationModule+)+from .tfmodel import SeqBandModellingModule+++class MultiMaskBandSplitCoreBase(BandsplitCoreBase):+ def __init__(self) -> None:+ super().__init__()++ def forward(self, x, cond=None, compute_residual: bool = True):+ # x = complex spectrogram (batch, in_chan, n_freq, n_time)+ # print(x.shape)+ batch, in_chan, n_freq, n_time = x.shape+ x = torch.reshape(x, (-1, 1, n_freq, n_time))++ z = self.band_split(x) # (batch, emb_dim, n_band, n_time)++ # if torch.any(torch.isnan(z)):+ # raise ValueError("z nan")++ # print(z)+ q = self.tf_model(z) # (batch, emb_dim, n_band, n_time)+ # print(q)+++ # if torch.any(torch.isnan(q)):+ # raise ValueError("q nan")++ out = {}++ for stem, mem in self.mask_estim.items():+ m = mem(q, cond=cond)++ # if torch.any(torch.isnan(m)):+ # raise ValueError("m nan", stem)++ s = self.mask(x, m)+ s = torch.reshape(s, (batch, in_chan, n_freq, n_time))+ out[stem] = s++ return {"spectrogram": out}++++ def instantiate_mask_estim(self,+ in_channel: int,+ stems: List[str],+ band_specs: List[Tuple[float, float]],+ emb_dim: int,+ mlp_dim: int,+ cond_dim: int,+ hidden_activation: str,++ hidden_activation_kwargs: Optional[Dict] = None,+ complex_mask: bool = True,+ overlapping_band: bool = False,+ freq_weights: Optional[List[torch.Tensor]] = None,+ n_freq: Optional[int] = None,+ use_freq_weights: bool = True,+ mult_add_mask: bool = False+ ):+ if hidden_activation_kwargs is None:+ hidden_activation_kwargs = {}++ if "mne:+" in stems:+ stems = [s for s in stems if s != "mne:+"]++ if overlapping_band:+ assert freq_weights is not None+ assert n_freq is not None++ self.mask_estim = nn.ModuleDict(+ {+ stem: OverlappingMaskEstimationModule(+ band_specs=band_specs,+ freq_weights=freq_weights,+ n_freq=n_freq,+ emb_dim=emb_dim,+ mlp_dim=mlp_dim,+ in_channel=in_channel,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ use_freq_weights=use_freq_weights,+ )+ for stem in stems+ }+ )+ else:+ self.mask_estim = nn.ModuleDict(+ {+ stem: MaskEstimationModule(+ band_specs=band_specs,+ emb_dim=emb_dim,+ mlp_dim=mlp_dim,+ cond_dim=cond_dim,+ in_channel=in_channel,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ )+ for stem in stems+ }+ )++ def instantiate_bandsplit(self,+ in_channel: int,+ band_specs: List[Tuple[float, float]],+ require_no_overlap: bool = False,+ require_no_gap: bool = True,+ normalize_channel_independently: bool = False,+ treat_channel_as_feature: bool = True,+ emb_dim: int = 128+ ):+ self.band_split = BandSplitModule(+ in_channel=in_channel,+ band_specs=band_specs,+ require_no_overlap=require_no_overlap,+ require_no_gap=require_no_gap,+ normalize_channel_independently=normalize_channel_independently,+ treat_channel_as_feature=treat_channel_as_feature,+ emb_dim=emb_dim,+ )++++++++class MultiSourceMultiMaskBandSplitCoreRNN(MultiMaskBandSplitCoreBase):+ def __init__(+ self,+ in_channel: int,+ stems: List[str],+ band_specs: List[Tuple[float, float]],+ require_no_overlap: bool = False,+ require_no_gap: bool = True,+ normalize_channel_independently: bool = False,+ treat_channel_as_feature: bool = True,+ n_sqm_modules: int = 12,+ emb_dim: int = 128,+ rnn_dim: int = 256,+ bidirectional: bool = True,+ rnn_type: str = "LSTM",+ mlp_dim: int = 512,+ cond_dim: int = 0,+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs: Optional[Dict] = None,+ complex_mask: bool = True,+ overlapping_band: bool = False,+ freq_weights: Optional[List[torch.Tensor]] = None,+ n_freq: Optional[int] = None,+ use_freq_weights: bool = True,+ mult_add_mask: bool = False+ ) -> None:++ super().__init__()+ self.instantiate_bandsplit(+ in_channel=in_channel,+ band_specs=band_specs,+ require_no_overlap=require_no_overlap,+ require_no_gap=require_no_gap,+ normalize_channel_independently=normalize_channel_independently,+ treat_channel_as_feature=treat_channel_as_feature,+ emb_dim=emb_dim+ )+++ self.tf_model = (+ SeqBandModellingModule(+ n_modules=n_sqm_modules,+ emb_dim=emb_dim,+ rnn_dim=rnn_dim,+ bidirectional=bidirectional,+ rnn_type=rnn_type,+ )+ )++ self.mult_add_mask = mult_add_mask++ self.instantiate_mask_estim(+ in_channel=in_channel,+ stems=stems,+ band_specs=band_specs,+ emb_dim=emb_dim,+ mlp_dim=mlp_dim,+ cond_dim=cond_dim,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ overlapping_band=overlapping_band,+ freq_weights=freq_weights,+ n_freq=n_freq,+ use_freq_weights=use_freq_weights,+ mult_add_mask=mult_add_mask+ )++ @staticmethod+ def _mult_add_mask(x, m):++ assert m.ndim == 5++ mm = m[..., 0]+ am = m[..., 1]++ # print(mm.shape, am.shape, x.shape, m.shape)++ return x * mm + am++ def mask(self, x, m):+ if self.mult_add_mask:++ return self._mult_add_mask(x, m)+ else:+ return super().mask(x, m)+++++++++diff --git a/freevideo_engine/stems/bandit/maskestim.py b/freevideo_engine/stems/bandit/maskestim.pynew file mode 100644index 0000000..244f5e6--- /dev/null+++ b/freevideo_engine/stems/bandit/maskestim.py@@ -0,0 +1,348 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+from typing import Dict, List, Optional, Tuple, Type++import torch+from torch import nn+from torch.nn.modules import activation++from .utils import (+ band_widths_from_specs,+ check_no_gap,+ check_no_overlap,+ check_nonzero_bandwidth,+)+++class BaseNormMLP(nn.Module):+ def __init__(+ self,+ emb_dim: int,+ mlp_dim: int,+ bandwidth: int,+ in_channel: Optional[int],+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs=None,+ complex_mask: bool = True, ):++ super().__init__()+ if hidden_activation_kwargs is None:+ hidden_activation_kwargs = {}+ self.hidden_activation_kwargs = hidden_activation_kwargs+ self.norm = nn.LayerNorm(emb_dim)+ self.hidden = torch.jit.script(nn.Sequential(+ nn.Linear(in_features=emb_dim, out_features=mlp_dim),+ activation.__dict__[hidden_activation](+ **self.hidden_activation_kwargs+ ),+ ))++ self.bandwidth = bandwidth+ self.in_channel = in_channel++ self.complex_mask = complex_mask+ self.reim = 2 if complex_mask else 1+ self.glu_mult = 2+++class NormMLP(BaseNormMLP):+ def __init__(+ self,+ emb_dim: int,+ mlp_dim: int,+ bandwidth: int,+ in_channel: Optional[int],+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs=None,+ complex_mask: bool = True,+ ) -> None:+ super().__init__(+ emb_dim=emb_dim,+ mlp_dim=mlp_dim,+ bandwidth=bandwidth,+ in_channel=in_channel,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ )++ self.output = torch.jit.script(+ nn.Sequential(+ nn.Linear(+ in_features=mlp_dim,+ out_features=bandwidth * in_channel * self.reim * 2,+ ),+ nn.GLU(dim=-1),+ )+ )++ def reshape_output(self, mb):+ # print(mb.shape)+ batch, n_time, _ = mb.shape+ if self.complex_mask:+ mb = mb.reshape(+ batch,+ n_time,+ self.in_channel,+ self.bandwidth,+ self.reim+ ).contiguous()+ # print(mb.shape)+ mb = torch.view_as_complex(+ mb+ ) # (batch, n_time, in_channel, bandwidth)+ else:+ mb = mb.reshape(batch, n_time, self.in_channel, self.bandwidth)++ mb = torch.permute(+ mb,+ (0, 2, 3, 1)+ ) # (batch, in_channel, bandwidth, n_time)++ return mb++ def forward(self, qb):+ # qb = (batch, n_time, emb_dim)++ # if torch.any(torch.isnan(qb)):+ # raise ValueError("qb0")+++ qb = self.norm(qb) # (batch, n_time, emb_dim)++ # if torch.any(torch.isnan(qb)):+ # raise ValueError("qb1")++ qb = self.hidden(qb) # (batch, n_time, mlp_dim)+ # if torch.any(torch.isnan(qb)):+ # raise ValueError("qb2")+ mb = self.output(qb) # (batch, n_time, bandwidth * in_channel * reim)+ # if torch.any(torch.isnan(qb)):+ # raise ValueError("mb")+ mb = self.reshape_output(mb) # (batch, in_channel, bandwidth, n_time)++ return mb+++class MultAddNormMLP(NormMLP):+ def __init__(self, emb_dim: int, mlp_dim: int, bandwidth: int, in_channel: int | None, hidden_activation: str = "Tanh", hidden_activation_kwargs=None, complex_mask: bool = True) -> None:+ super().__init__(emb_dim, mlp_dim, bandwidth, in_channel, hidden_activation, hidden_activation_kwargs, complex_mask)++ self.output2 = torch.jit.script(+ nn.Sequential(+ nn.Linear(+ in_features=mlp_dim,+ out_features=bandwidth * in_channel * self.reim * 2,+ ),+ nn.GLU(dim=-1),+ )+ )++ def forward(self, qb):++ qb = self.norm(qb) # (batch, n_time, emb_dim)+ qb = self.hidden(qb) # (batch, n_time, mlp_dim)+ mmb = self.output(qb) # (batch, n_time, bandwidth * in_channel * reim)+ mmb = self.reshape_output(mmb) # (batch, in_channel, bandwidth, n_time)+ amb = self.output2(qb) # (batch, n_time, bandwidth * in_channel * reim)+ amb = self.reshape_output(amb) # (batch, in_channel, bandwidth, n_time)++ return mmb, amb+++class MaskEstimationModuleSuperBase(nn.Module):+ pass+++class MaskEstimationModuleBase(MaskEstimationModuleSuperBase):+ def __init__(+ self,+ band_specs: List[Tuple[float, float]],+ emb_dim: int,+ mlp_dim: int,+ in_channel: Optional[int],+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs: Dict = None,+ complex_mask: bool = True,+ norm_mlp_cls: Type[nn.Module] = NormMLP,+ norm_mlp_kwargs: Dict = None,+ ) -> None:+ super().__init__()++ self.band_widths = band_widths_from_specs(band_specs)+ self.n_bands = len(band_specs)++ if hidden_activation_kwargs is None:+ hidden_activation_kwargs = {}++ if norm_mlp_kwargs is None:+ norm_mlp_kwargs = {}++ self.norm_mlp = nn.ModuleList(+ [+ (+ norm_mlp_cls(+ bandwidth=self.band_widths[b],+ emb_dim=emb_dim,+ mlp_dim=mlp_dim,+ in_channel=in_channel,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ **norm_mlp_kwargs,+ )+ )+ for b in range(self.n_bands)+ ]+ )++ def compute_masks(self, q):+ batch, n_bands, n_time, emb_dim = q.shape++ masks = []++ for b, nmlp in enumerate(self.norm_mlp):+ # print(f"maskestim/{b:02d}")+ qb = q[:, b, :, :]+ mb = nmlp(qb)+ masks.append(mb)++ return masks++++class OverlappingMaskEstimationModule(MaskEstimationModuleBase):+ def __init__(+ self,+ in_channel: int,+ band_specs: List[Tuple[float, float]],+ freq_weights: List[torch.Tensor],+ n_freq: int,+ emb_dim: int,+ mlp_dim: int,+ cond_dim: int = 0,+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs: Dict = None,+ complex_mask: bool = True,+ norm_mlp_cls: Type[nn.Module] = NormMLP,+ norm_mlp_kwargs: Dict = None,+ use_freq_weights: bool = True,+ ) -> None:+ check_nonzero_bandwidth(band_specs)+ check_no_gap(band_specs)++ # if cond_dim > 0:+ # raise NotImplementedError++ super().__init__(+ band_specs=band_specs,+ emb_dim=emb_dim + cond_dim,+ mlp_dim=mlp_dim,+ in_channel=in_channel,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ norm_mlp_cls=norm_mlp_cls,+ norm_mlp_kwargs=norm_mlp_kwargs,+ )++ self.n_freq = n_freq+ self.band_specs = band_specs+ self.in_channel = in_channel++ if freq_weights is not None:+ for i, fw in enumerate(freq_weights):+ self.register_buffer(f"freq_weights/{i}", fw)++ self.use_freq_weights = use_freq_weights+ else:+ self.use_freq_weights = False++ self.cond_dim = cond_dim++ def forward(self, q, cond=None):+ # q = (batch, n_bands, n_time, emb_dim)++ batch, n_bands, n_time, emb_dim = q.shape++ if cond is not None:+ print(cond)+ if cond.ndim == 2:+ cond = cond[:, None, None, :].expand(-1, n_bands, n_time, -1)+ elif cond.ndim == 3:+ assert cond.shape[1] == n_time+ else:+ raise ValueError(f"Invalid cond shape: {cond.shape}")++ q = torch.cat([q, cond], dim=-1)+ elif self.cond_dim > 0:+ cond = torch.ones(+ (batch, n_bands, n_time, self.cond_dim),+ device=q.device,+ dtype=q.dtype,+ )+ q = torch.cat([q, cond], dim=-1)+ else:+ pass++ mask_list = self.compute_masks(+ q+ ) # [n_bands * (batch, in_channel, bandwidth, n_time)]++ masks = torch.zeros(+ (batch, self.in_channel, self.n_freq, n_time),+ device=q.device,+ dtype=mask_list[0].dtype,+ )++ for im, mask in enumerate(mask_list):+ fstart, fend = self.band_specs[im]+ if self.use_freq_weights:+ fw = self.get_buffer(f"freq_weights/{im}")[:, None]+ mask = mask * fw+ masks[:, :, fstart:fend, :] += mask++ return masks+++class MaskEstimationModule(OverlappingMaskEstimationModule):+ def __init__(+ self,+ band_specs: List[Tuple[float, float]],+ emb_dim: int,+ mlp_dim: int,+ in_channel: Optional[int],+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs: Dict = None,+ complex_mask: bool = True,+ **kwargs,+ ) -> None:+ check_nonzero_bandwidth(band_specs)+ check_no_gap(band_specs)+ check_no_overlap(band_specs)+ super().__init__(+ in_channel=in_channel,+ band_specs=band_specs,+ freq_weights=None,+ n_freq=None,+ emb_dim=emb_dim,+ mlp_dim=mlp_dim,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ )++ def forward(self, q, cond=None):+ # q = (batch, n_bands, n_time, emb_dim)++ masks = self.compute_masks(+ q+ ) # [n_bands * (batch, in_channel, bandwidth, n_time)]++ # TODO: currently this requires band specs to have no gap and no overlap+ masks = torch.concat(+ masks,+ dim=2+ ) # (batch, in_channel, n_freq, n_time)++ return masksdiff --git a/freevideo_engine/stems/bandit/spectral.py b/freevideo_engine/stems/bandit/spectral.pynew file mode 100644index 0000000..ae0700c--- /dev/null+++ b/freevideo_engine/stems/bandit/spectral.py@@ -0,0 +1,60 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+from typing import Dict, Optional++import torch+import torchaudio as ta+from torch import nn+++class _SpectralComponent(nn.Module):+ def __init__(+ self,+ n_fft: int = 2048,+ win_length: Optional[int] = 2048,+ hop_length: int = 512,+ window_fn: str = "hann_window",+ wkwargs: Optional[Dict] = None,+ power: Optional[int] = None,+ center: bool = True,+ normalized: bool = True,+ pad_mode: str = "constant",+ onesided: bool = True,+ **kwargs,+ ) -> None:+ super().__init__()++ assert power is None++ window_fn = torch.__dict__[window_fn]++ self.stft = (+ ta.transforms.Spectrogram(+ n_fft=n_fft,+ win_length=win_length,+ hop_length=hop_length,+ pad_mode=pad_mode,+ pad=0,+ window_fn=window_fn,+ wkwargs=wkwargs,+ power=power,+ normalized=normalized,+ center=center,+ onesided=onesided,+ )+ )++ self.istft = (+ ta.transforms.InverseSpectrogram(+ n_fft=n_fft,+ win_length=win_length,+ hop_length=hop_length,+ pad_mode=pad_mode,+ pad=0,+ window_fn=window_fn,+ wkwargs=wkwargs,+ normalized=normalized,+ center=center,+ onesided=onesided,+ )+ )diff --git a/freevideo_engine/stems/bandit/tfmodel.py b/freevideo_engine/stems/bandit/tfmodel.pynew file mode 100644index 0000000..ae709b8--- /dev/null+++ b/freevideo_engine/stems/bandit/tfmodel.py@@ -0,0 +1,177 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+import warnings++import torch+from torch import nn+from torch.nn.modules import rnn++import torch.backends.cuda+++class TimeFrequencyModellingModule(nn.Module):+ def __init__(self) -> None:+ super().__init__()+++class ResidualRNN(nn.Module):+ def __init__(+ self,+ emb_dim: int,+ rnn_dim: int,+ bidirectional: bool = True,+ rnn_type: str = "LSTM",+ use_batch_trick: bool = True,+ use_layer_norm: bool = True,+ ) -> None:+ # n_group is the size of the 2nd dim+ super().__init__()++ self.use_layer_norm = use_layer_norm+ if use_layer_norm:+ self.norm = nn.LayerNorm(emb_dim)+ else:+ self.norm = nn.GroupNorm(num_groups=emb_dim, num_channels=emb_dim)++ self.rnn = rnn.__dict__[rnn_type](+ input_size=emb_dim,+ hidden_size=rnn_dim,+ num_layers=1,+ batch_first=True,+ bidirectional=bidirectional,+ )++ self.fc = nn.Linear(+ in_features=rnn_dim * (2 if bidirectional else 1),+ out_features=emb_dim+ )++ self.use_batch_trick = use_batch_trick+ if not self.use_batch_trick:+ warnings.warn("NOT USING BATCH TRICK IS EXTREMELY SLOW!!")++ def forward(self, z):+ # z = (batch, n_uncrossed, n_across, emb_dim)++ z0 = torch.clone(z)++ # print(z.device)++ if self.use_layer_norm:+ z = self.norm(z) # (batch, n_uncrossed, n_across, emb_dim)+ else:+ z = torch.permute(+ z, (0, 3, 1, 2)+ ) # (batch, emb_dim, n_uncrossed, n_across)++ z = self.norm(z) # (batch, emb_dim, n_uncrossed, n_across)++ z = torch.permute(+ z, (0, 2, 3, 1)+ ) # (batch, n_uncrossed, n_across, emb_dim)++ batch, n_uncrossed, n_across, emb_dim = z.shape++ if self.use_batch_trick:+ z = torch.reshape(z, (batch * n_uncrossed, n_across, emb_dim))++ z = self.rnn(z.contiguous())[0] # (batch * n_uncrossed, n_across, dir_rnn_dim)++ z = torch.reshape(z, (batch, n_uncrossed, n_across, -1))+ # (batch, n_uncrossed, n_across, dir_rnn_dim)+ else:+ # Note: this is EXTREMELY SLOW+ zlist = []+ for i in range(n_uncrossed):+ zi = self.rnn(z[:, i, :, :])[0] # (batch, n_across, emb_dim)+ zlist.append(zi)++ z = torch.stack(+ zlist,+ dim=1+ ) # (batch, n_uncrossed, n_across, dir_rnn_dim)++ z = self.fc(z) # (batch, n_uncrossed, n_across, emb_dim)++ z = z + z0++ return z+++class SeqBandModellingModule(TimeFrequencyModellingModule):+ def __init__(+ self,+ n_modules: int = 12,+ emb_dim: int = 128,+ rnn_dim: int = 256,+ bidirectional: bool = True,+ rnn_type: str = "LSTM",+ parallel_mode=False,+ ) -> None:+ super().__init__()+ self.seqband = nn.ModuleList([])++ if parallel_mode:+ for _ in range(n_modules):+ self.seqband.append(+ nn.ModuleList(+ [ResidualRNN(+ emb_dim=emb_dim,+ rnn_dim=rnn_dim,+ bidirectional=bidirectional,+ rnn_type=rnn_type,+ ),+ ResidualRNN(+ emb_dim=emb_dim,+ rnn_dim=rnn_dim,+ bidirectional=bidirectional,+ rnn_type=rnn_type,+ )]+ )+ )+ else:++ for _ in range(2 * n_modules):+ self.seqband.append(+ ResidualRNN(+ emb_dim=emb_dim,+ rnn_dim=rnn_dim,+ bidirectional=bidirectional,+ rnn_type=rnn_type,+ )+ )++ self.parallel_mode = parallel_mode++ def forward(self, z):+ # z = (batch, n_bands, n_time, emb_dim)++ if self.parallel_mode:+ for sbm_pair in self.seqband:+ # z: (batch, n_bands, n_time, emb_dim)+ sbm_t, sbm_f = sbm_pair[0], sbm_pair[1]+ zt = sbm_t(z) # (batch, n_bands, n_time, emb_dim)+ zf = sbm_f(z.transpose(1, 2)) # (batch, n_time, n_bands, emb_dim)+ z = zt + zf.transpose(1, 2)+ else:+ for sbm in self.seqband:+ z = sbm(z)+ z = z.transpose(1, 2)++ # (batch, n_bands, n_time, emb_dim)+ # --> (batch, n_time, n_bands, emb_dim)+ # OR+ # (batch, n_time, n_bands, emb_dim)+ # --> (batch, n_bands, n_time, emb_dim)++ q = z+ return q # (batch, n_bands, n_time, emb_dim)+++++++++diff --git a/freevideo_engine/stems/bandit/utils.py b/freevideo_engine/stems/bandit/utils.pynew file mode 100644index 0000000..c68c7b0--- /dev/null+++ b/freevideo_engine/stems/bandit/utils.py@@ -0,0 +1,260 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+import os+from abc import abstractmethod+from typing import Callable++import numpy as np+import torch+++def hz_to_midi(frequency):+ return 12 * (np.log2(np.asanyarray(frequency)) - np.log2(440.0)) + 69+++def midi_to_hz(notes):+ return 440.0 * (2.0 ** ((np.asanyarray(notes) - 69.0) / 12.0))+++def band_widths_from_specs(band_specs):+ return [e - i for i, e in band_specs]+++def check_nonzero_bandwidth(band_specs):+ # pprint(band_specs)+ for fstart, fend in band_specs:+ if fend - fstart <= 0:+ raise ValueError("Bands cannot be zero-width")+++def check_no_overlap(band_specs):+ fend_prev = -1+ for fstart_curr, fend_curr in band_specs:+ if fstart_curr <= fend_prev:+ raise ValueError("Bands cannot overlap")+++def check_no_gap(band_specs):+ fstart, _ = band_specs[0]+ assert fstart == 0++ fend_prev = -1+ for fstart_curr, fend_curr in band_specs:+ if fstart_curr - fend_prev > 1:+ raise ValueError("Bands cannot leave gap")+ fend_prev = fend_curr+++class BandsplitSpecification:+ def __init__(self, nfft: int, fs: int) -> None:+ self.fs = fs+ self.nfft = nfft+ self.nyquist = fs / 2+ self.max_index = nfft // 2 + 1++ self.split500 = self.hertz_to_index(500)+ self.split1k = self.hertz_to_index(1000)+ self.split2k = self.hertz_to_index(2000)+ self.split4k = self.hertz_to_index(4000)+ self.split8k = self.hertz_to_index(8000)+ self.split16k = self.hertz_to_index(16000)+ self.split20k = self.hertz_to_index(20000)++ self.above20k = [(self.split20k, self.max_index)]+ self.above16k = [(self.split16k, self.split20k)] + self.above20k++ def index_to_hertz(self, index: int):+ return index * self.fs / self.nfft++ def hertz_to_index(self, hz: float, round: bool = True):+ index = hz * self.nfft / self.fs++ if round:+ index = int(np.round(index))++ return index++ def get_band_specs_with_bandwidth(+ self,+ start_index,+ end_index,+ bandwidth_hz+ ):+ band_specs = []+ lower = start_index++ while lower < end_index:+ upper = int(np.floor(lower + self.hertz_to_index(bandwidth_hz)))+ upper = min(upper, end_index)++ band_specs.append((lower, upper))+ lower = upper++ return band_specs++ @abstractmethod+ def get_band_specs(self):+ raise NotImplementedError+++++++++++++class PerceptualBandsplitSpecification(BandsplitSpecification):+ def __init__(+ self,+ nfft: int,+ fs: int,+ fbank_fn: Callable[[int, int, float, float, int], torch.Tensor],+ n_bands: int,+ f_min: float = 0.0,+ f_max: float = None+ ) -> None:+ super().__init__(nfft=nfft, fs=fs)+ self.n_bands = n_bands+ if f_max is None:+ f_max = fs / 2++ self.filterbank = fbank_fn(+ n_bands, fs, f_min, f_max, self.max_index+ )++ weight_per_bin = torch.sum(+ self.filterbank,+ dim=0,+ keepdim=True+ ) # (1, n_freqs)+ normalized_mel_fb = self.filterbank / weight_per_bin # (n_mels, n_freqs)++ freq_weights = []+ band_specs = []+ for i in range(self.n_bands):+ active_bins = torch.nonzero(self.filterbank[i, :]).squeeze().tolist()+ if isinstance(active_bins, int):+ active_bins = (active_bins, active_bins)+ if len(active_bins) == 0:+ continue+ start_index = active_bins[0]+ end_index = active_bins[-1] + 1+ band_specs.append((start_index, end_index))+ freq_weights.append(normalized_mel_fb[i, start_index:end_index])++ self.freq_weights = freq_weights+ self.band_specs = band_specs++ def get_band_specs(self):+ return self.band_specs++ def get_freq_weights(self):+ return self.freq_weights++ def save_to_file(self, dir_path: str) -> None:++ os.makedirs(dir_path, exist_ok=True)++ import pickle++ with open(os.path.join(dir_path, "mel_bandsplit_spec.pkl"), "wb") as f:+ pickle.dump(+ {+ "band_specs": self.band_specs,+ "freq_weights": self.freq_weights,+ "filterbank": self.filterbank,+ },+ f,+ )+++++def musical_filterbank(n_bands, fs, f_min, f_max, n_freqs,+ scale="constant"):++ nfft = 2 * (n_freqs - 1)+ df = fs / nfft+ # init freqs+ f_max = f_max or fs / 2+ f_min = f_min or 0+ f_min = fs / nfft++ n_octaves = np.log2(f_max / f_min)+ n_octaves_per_band = n_octaves / n_bands+ bandwidth_mult = np.power(2.0, n_octaves_per_band)++ low_midi = max(0, hz_to_midi(f_min))+ high_midi = hz_to_midi(f_max)+ midi_points = np.linspace(low_midi, high_midi, n_bands)+ hz_pts = midi_to_hz(midi_points)++ low_pts = hz_pts / bandwidth_mult+ high_pts = hz_pts * bandwidth_mult++ low_bins = np.floor(low_pts / df).astype(int)+ high_bins = np.ceil(high_pts / df).astype(int)++ fb = np.zeros((n_bands, n_freqs))++ for i in range(n_bands):+ fb[i, low_bins[i]:high_bins[i]+1] = 1.0++ fb[0, :low_bins[0]] = 1.0+ fb[-1, high_bins[-1]+1:] = 1.0++ return torch.as_tensor(fb)++class MusicalBandsplitSpecification(PerceptualBandsplitSpecification):+ def __init__(+ self,+ nfft: int,+ fs: int,+ n_bands: int,+ f_min: float = 0.0,+ f_max: float = None+ ) -> None:+ super().__init__(fbank_fn=musical_filterbank, nfft=nfft, fs=fs, n_bands=n_bands, f_min=f_min, f_max=f_max)++++++++++++++++++++if __name__ == "__main__":+ import pandas as pd++ band_defs = []++ for bands in [VocalBandsplitSpecification]:+ band_name = bands.__name__.replace("BandsplitSpecification", "")++ mbs = bands(nfft=2048, fs=44100).get_band_specs()++ for i, (f_min, f_max) in enumerate(mbs):+ band_defs.append({+ "band": band_name,+ "band_index": i,+ "f_min": f_min,+ "f_max": f_max+ })++ df = pd.DataFrame(band_defs)+ df.to_csv("vox7bands.csv", index=False)\ No newline at end of filediff --git a/freevideo_engine/stems/bandit/wrapper.py b/freevideo_engine/stems/bandit/wrapper.pynew file mode 100644index 0000000..2f5e871--- /dev/null+++ b/freevideo_engine/stems/bandit/wrapper.py@@ -0,0 +1,190 @@+# Adapted from Bandit (https://github.com/kwatcharasupat/source-separation), Copyright (c) the Bandit authors,+# Apache-2.0 (freevideo_engine/licenses/Bandit-Apache-2.0.txt). Modified: reduced to the inference subset.+from typing import Dict, List, Optional, Tuple, Union++import torch+from torch import nn++from .core import MultiSourceMultiMaskBandSplitCoreRNN+from .spectral import _SpectralComponent+from .utils import MusicalBandsplitSpecification+++def get_band_specs(band_specs, n_fft, fs, n_bands=None):+ if "musical" not in band_specs or n_bands is None:+ raise NameError(band_specs)+ specs = MusicalBandsplitSpecification(nfft=n_fft, fs=fs, n_bands=n_bands)+ return specs.get_band_specs(), specs.get_freq_weights(), True+++class BandSplitWrapperBase(nn.Module):+ bsrnn: nn.Module++ def __init__(self, **kwargs):+ super().__init__()+++++class MultiMaskMultiSourceBandSplitBase(+ BandSplitWrapperBase,+ _SpectralComponent+):+ def __init__(+ self,+ stems: List[str],+ band_specs: Union[str, List[Tuple[float, float]]],+ fs: int = 44100,+ n_fft: int = 2048,+ win_length: Optional[int] = 2048,+ hop_length: int = 512,+ window_fn: str = "hann_window",+ wkwargs: Optional[Dict] = None,+ power: Optional[int] = None,+ center: bool = True,+ normalized: bool = True,+ pad_mode: str = "constant",+ onesided: bool = True,+ n_bands: int = None,+ ) -> None:+ super().__init__(+ n_fft=n_fft,+ win_length=win_length,+ hop_length=hop_length,+ window_fn=window_fn,+ wkwargs=wkwargs,+ power=power,+ center=center,+ normalized=normalized,+ pad_mode=pad_mode,+ onesided=onesided,+ )++ if isinstance(band_specs, str):+ self.band_specs, self.freq_weights, self.overlapping_band = get_band_specs(+ band_specs,+ n_fft,+ fs,+ n_bands+ )++ self.stems = stems++ def forward(self, batch):+ # with torch.no_grad():+ audio = batch["audio"]+ cond = batch.get("condition", None)+ with torch.no_grad():+ batch["spectrogram"] = {stem: self.stft(audio[stem]) for stem in+ audio}++ X = batch["spectrogram"]["mixture"]+ length = batch["audio"]["mixture"].shape[-1]++ output = self.bsrnn(X, cond=cond)+ output["audio"] = {}++ for stem, S in output["spectrogram"].items():+ s = self.istft(S, length)+ output["audio"][stem] = s++ return batch, output+++++++class MultiMaskMultiSourceBandSplitRNN(MultiMaskMultiSourceBandSplitBase):+ def __init__(+ self,+ in_channel: int,+ stems: List[str],+ band_specs: Union[str, List[Tuple[float, float]]],+ fs: int = 44100,+ require_no_overlap: bool = False,+ require_no_gap: bool = True,+ normalize_channel_independently: bool = False,+ treat_channel_as_feature: bool = True,+ n_sqm_modules: int = 12,+ emb_dim: int = 128,+ rnn_dim: int = 256,+ cond_dim: int = 0,+ bidirectional: bool = True,+ rnn_type: str = "LSTM",+ mlp_dim: int = 512,+ hidden_activation: str = "Tanh",+ hidden_activation_kwargs: Optional[Dict] = None,+ complex_mask: bool = True,+ n_fft: int = 2048,+ win_length: Optional[int] = 2048,+ hop_length: int = 512,+ window_fn: str = "hann_window",+ wkwargs: Optional[Dict] = None,+ power: Optional[int] = None,+ center: bool = True,+ normalized: bool = True,+ pad_mode: str = "constant",+ onesided: bool = True,+ n_bands: int = None,+ use_freq_weights: bool = True,+ normalize_input: bool = False,+ mult_add_mask: bool = False,+ freeze_encoder: bool = False,+ ) -> None:+ super().__init__(+ stems=stems,+ band_specs=band_specs,+ fs=fs,+ n_fft=n_fft,+ win_length=win_length,+ hop_length=hop_length,+ window_fn=window_fn,+ wkwargs=wkwargs,+ power=power,+ center=center,+ normalized=normalized,+ pad_mode=pad_mode,+ onesided=onesided,+ n_bands=n_bands,+ )++ self.bsrnn = MultiSourceMultiMaskBandSplitCoreRNN(+ stems=stems,+ band_specs=self.band_specs,+ in_channel=in_channel,+ require_no_overlap=require_no_overlap,+ require_no_gap=require_no_gap,+ normalize_channel_independently=normalize_channel_independently,+ treat_channel_as_feature=treat_channel_as_feature,+ n_sqm_modules=n_sqm_modules,+ emb_dim=emb_dim,+ rnn_dim=rnn_dim,+ bidirectional=bidirectional,+ rnn_type=rnn_type,+ mlp_dim=mlp_dim,+ cond_dim=cond_dim,+ hidden_activation=hidden_activation,+ hidden_activation_kwargs=hidden_activation_kwargs,+ complex_mask=complex_mask,+ overlapping_band=self.overlapping_band,+ freq_weights=self.freq_weights,+ n_freq=n_fft // 2 + 1,+ use_freq_weights=use_freq_weights,+ mult_add_mask=mult_add_mask+ )++ self.normalize_input = normalize_input+ self.cond_dim = cond_dim++ if freeze_encoder:+ for param in self.bsrnn.band_split.parameters():+ param.requires_grad = False++ for param in self.bsrnn.tf_model.parameters():+ param.requires_grad = False+++++diff --git a/freevideo_engine/stems/separate.py b/freevideo_engine/stems/separate.pynew file mode 100644index 0000000..2059ab9--- /dev/null+++ b/freevideo_engine/stems/separate.py@@ -0,0 +1,200 @@+"""Split a soundtrack into dialogue, music, and ambience and effects.++The model is a band-split recurrent network (Bandit, cocktail-party version) that works on 44.1 kHz mono+signals. A track is cut into overlapping 6 s chunks (3 s hop, Hann window), a few chunks go through the+model at a time, and the windowed outputs are added back, so the peak GPU memory does not depend on the+length of the track and every output has exactly the length of the input.+"""+from fractions import Fraction+import logging+import os+from pathlib import Path+import wave++import numpy as np++SAMPLE_RATE = 44100+CHUNK_SECONDS = 6.0+HOP_SECONDS = 3.0+BATCH = 4+MIX_NAME = 'mix.wav'++# Model output name -> track name. The order is the order of the sub-tracks in the editor.+STEMS = (('speech', 'dialogue'), ('music', 'music'), ('effects', 'ambience'))+MODEL_KWARGS = dict(+ in_channel=1, stems=[name for name, _ in STEMS], band_specs='musical', n_bands=64, fs=SAMPLE_RATE,+ require_no_overlap=False, require_no_gap=True, normalize_channel_independently=False,+ treat_channel_as_feature=True, n_sqm_modules=8, emb_dim=128, rnn_dim=256, bidirectional=True,+ rnn_type='GRU', mlp_dim=512, hidden_activation='Tanh', complex_mask=True)+++class SeparationError(Exception):+ pass+++def load_model(weights, device='cuda'):+ """The network with its weights; weights is a plain state-dict file (loaded without unpickling objects)."""+ import torch+ from .bandit.wrapper import MultiMaskMultiSourceBandSplitRNN+ model = MultiMaskMultiSourceBandSplitRNN(**MODEL_KWARGS)+ state = torch.load(weights, map_location='cpu', weights_only=True)+ model.load_state_dict(state)+ return model.to(device).eval()+++def model_function(model, device):+ """Chunks [n, 1, samples] -> {model stem: [n, 1, samples]}, run without gradients."""+ import torch++ def run(chunks):+ with torch.inference_mode():+ _, output = model({'audio': {'mixture': chunks.to(device)}})+ return {name: output['audio'][name].float().cpu() for name, _ in STEMS}+ return run+++def separate_array(function, audio, *, chunk=None, hop=None, batch=BATCH, progress=lambda fraction: None):+ """audio: float tensor [channels, samples]; function maps chunks [n, 1, chunk] to {stem: [n, 1, chunk]}.++ Returns {stem: tensor [channels, samples]} with the length of the input. Every channel is separated on its own."""+ import torch+ chunk = chunk or int(CHUNK_SECONDS * SAMPLE_RATE)+ hop = hop or int(HOP_SECONDS * SAMPLE_RATE)+ channels, length = audio.shape+ if length == 0:+ raise SeparationError('empty')+ if chunk != 2 * hop:+ raise SeparationError('chunk must be twice the hop')+ # Half a chunk of mirrored context on both sides keeps the edges as well covered as the middle.+ edge = chunk - hop+ padded_length = max(length + 2 * edge, chunk)+ count = -(-(padded_length - chunk) // hop) + 1+ total = (count - 1) * hop + chunk+ padded = torch.zeros(channels, total)+ padded[:, edge:edge + length] = audio+ for left in range(1, edge + 1): # mirror as far as the signal reaches; the rest stays silent+ if left < length:+ padded[:, edge - left] = audio[:, left]+ padded[:, edge + length - 1 + left] = audio[:, length - 1 - left]+ window = torch.hann_window(chunk, periodic=True)+ starts = [index * hop for index in range(count)]+ outputs = {name: torch.zeros(channels, total) for name, _ in STEMS}+ jobs = [(channel, start) for channel in range(channels) for start in starts]+ for first in range(0, len(jobs), batch):+ part = jobs[first:first + batch]+ pieces = torch.stack([padded[channel, start:start + chunk] for channel, start in part])[:, None, :]+ if torch.any(pieces != 0):+ result = function(pieces)+ for name, _ in STEMS:+ for row, (channel, start) in enumerate(part):+ outputs[name][channel, start:start + chunk] += result[name][row, 0] * window+ progress(min(1., (first + len(part)) / len(jobs)))+ return {name: value[:, edge:edge + length].contiguous() for name, value in outputs.items()}+++def read_audio(path):+ """Decode any audio or video file to float32 [2, samples] at 44.1 kHz; returns (audio, seconds)."""+ import av+ chunks = []+ with av.open(str(path)) as container:+ if not container.streams.audio:+ raise SeparationError('no_audio')+ resampler = av.AudioResampler(format='fltp', layout='stereo', rate=SAMPLE_RATE)+ for frame in container.decode(audio=0):+ for out in resampler.resample(frame):+ chunks.append(out.to_ndarray())+ for out in resampler.resample(None) or ():+ chunks.append(out.to_ndarray())+ if not chunks:+ raise SeparationError('no_audio')+ audio = np.concatenate(chunks, axis=1).astype(np.float32)+ return audio, audio.shape[1] / SAMPLE_RATE+++def write_wav(path, audio):+ """Atomically write float [2, samples] as 16-bit PCM at 44.1 kHz."""+ path = Path(path)+ audio = np.asarray(audio)+ pcm = np.rint(np.clip(audio.T, -1, 1) * 32767).astype('<i2')+ temporary = path.with_name('.' + path.name + '.partial')+ try:+ with wave.open(str(temporary), 'wb') as output:+ output.setnchannels(audio.shape[0])+ output.setsampwidth(2)+ output.setframerate(SAMPLE_RATE)+ output.writeframes(pcm.tobytes())+ temporary.replace(path)+ finally:+ temporary.unlink(missing_ok=True)+++def write_mp4(path, audio, bit_rate=192_000):+ """AAC in an audio-only MP4, the container the timeline takes for generated media; replaced atomically."""+ import av+ path = Path(path)+ audio = np.asarray(audio, np.float32)+ partial = path.with_name('.' + path.name + '.partial')+ try:+ with av.open(str(partial), 'w', format='mp4', options={'movflags': 'faststart'}) as writer:+ stream = writer.add_stream('aac', rate=SAMPLE_RATE, layout='stereo')+ stream.codec_context.bit_rate = bit_rate+ step = 1024 * 32+ for offset in range(0, audio.shape[1], step):+ frame = av.AudioFrame.from_ndarray(np.ascontiguousarray(audio[:, offset:offset + step]),+ format='fltp', layout='stereo')+ frame.sample_rate, frame.pts, frame.time_base = SAMPLE_RATE, offset, Fraction(1, SAMPLE_RATE)+ for packet in stream.encode(frame):+ writer.mux(packet)+ for packet in stream.encode():+ writer.mux(packet)+ os.replace(partial, path)+ finally:+ partial.unlink(missing_ok=True)+++def separate_file(source, out_dir, weights, *, device='cuda', progress=lambda fraction: None):+ """Write <out_dir>/dialogue, music and ambience as .wav (export) and .mp4 (timeline), plus the original mix as+ mix.wav; returns {track: wav path} and the log numbers."""+ import time+ import torch+ began = time.monotonic()+ audio, seconds = read_audio(source)+ out_dir = Path(out_dir)+ out_dir.mkdir(parents=True, exist_ok=True)+ model = load_model(weights, device)+ if device == 'cuda':+ torch.cuda.reset_peak_memory_stats()+ stems = separate_array(model_function(model, device), torch.from_numpy(audio), progress=progress)+ peak = torch.cuda.max_memory_allocated() / 2 ** 30 if device == 'cuda' else None+ write_wav(out_dir / MIX_NAME, audio) # the original mix, exported next to the separated tracks+ paths = {}+ for name, track in STEMS:+ paths[track] = out_dir / (track + '.wav')+ write_wav(paths[track], stems[name].numpy())+ write_mp4(paths[track].with_suffix('.mp4'), stems[name].numpy())+ numbers = {'seconds': round(seconds, 3), 'elapsed': round(time.monotonic() - began, 2),+ 'peak_gib': None if peak is None else round(peak, 2)}+ logging.info('[FreeVideo] Separated %.1f s of sound in %.1f s, GPU peak %s GiB', seconds, numbers['elapsed'],+ numbers['peak_gib'])+ return paths, numbers+++def export_tracks(source_dir, destination):+ """Copy the separated tracks and the original mix (wav) of one separation into destination; returns the names.++ Nothing is written unless all four files exist, and existing files of the same names are not overwritten."""+ import shutil+ source_dir, destination = Path(source_dir), Path(destination)+ names = [track + '.wav' for _, track in STEMS] + [MIX_NAME]+ missing = [name for name in names if not (source_dir / name).is_file()]+ if missing:+ raise SeparationError('missing: ' + ', '.join(missing))+ destination.mkdir(parents=True, exist_ok=True)+ clash = [name for name in names if (destination / name).exists()]+ if clash:+ raise SeparationError('exists: ' + ', '.join(clash))+ for name in names:+ shutil.copyfile(source_dir / name, destination / (name + '.partial'))+ for name in names:+ os.replace(destination / (name + '.partial'), destination / name)+ return namesdiff --git a/freevideo_engine/stems/service.py b/freevideo_engine/stems/service.pynew file mode 100644index 0000000..0c4989b--- /dev/null+++ b/freevideo_engine/stems/service.py@@ -0,0 +1,176 @@+"""Audio separation for a clip: dialogue, music and ambience written by a one-shot worker under engine.lock.++The weights are the image pack's stems group, downloaded on first use. The worker takes the GPU the way+music does and stops when a video starts (a video is never kept waiting); the caller waits and asks again.+The feature is offered only with an NVIDIA GPU of at least MIN_VRAM_GIB and never on macOS.+"""+import logging+from pathlib import Path+import platform+import subprocess+import tempfile+import time++from ..music.service import Preempted, _Active, _result, _yield_gpu, environment++# An 8 GB card reports about 7.996 GiB, so the bar sits just under 8.+MIN_VRAM_GIB = 7.5+WORKER_SECONDS = 1800+POLL_SECONDS = .2+WEIGHTS = 'stems/bandit_plus_cocktail.pt'+++class StemsError(Exception):+ def __init__(self, code, reason=None):+ super().__init__(code)+ self.code, self.reason = code, reason+++ACTIVE = _Active()+++def stop_for_generation(server=None):+ """Called as a video starts: a separation that is starting or running stops, and engine.lock is free on return."""+ from .. import processes+ with ACTIVE.lock:+ if ACTIVE.idle.is_set():+ return+ ACTIVE.preempted = True+ process = ACTIVE.process+ if process is not None:+ processes.stop(process, grace=5)+ ACTIVE.idle.wait(30)+++def gpu_total_gib(uuid=None):+ """Physical memory in GiB of the GPU FreeVideo uses (the first one when its UUID is unknown), or None when unreadable.++ A reading is kept for the session; a failed one is tried again after RETRY_SECONDS, and waits at most 3 s."""+ key = str(uuid or 0)+ kept = _TOTAL.get(key)+ if kept is not None and (kept[0] is not None or time.monotonic() < kept[1]):+ return kept[0]+ try:+ out = subprocess.run(['nvidia-smi', '--query-gpu=memory.total', '--format=csv,noheader,nounits', '-i', key],+ capture_output=True, text=True, timeout=3, check=True).stdout+ value = float(out.split()[0]) / 1024+ except (OSError, ValueError, IndexError, subprocess.SubprocessError):+ value = None+ _TOTAL[key] = (value, time.monotonic() + RETRY_SECONDS)+ return value+++RETRY_SECONDS = 30+_TOTAL = {}+++def supported(vram_gib, system=None, total=None, uuid=None):+ """Whether the entry is offered: CUDA only, so not on macOS, and enough video memory.++ vram_gib is the limit a user may have set (normally None); the card's own size applies as well."""+ sizes = [v for v in (vram_gib, total if total is not None else gpu_total_gib(uuid)) if v is not None]+ return (system or platform.system()) != 'Darwin' and bool(sizes) and min(sizes) >= MIN_VRAM_GIB+++def ready(model_root):+ from ..image_gen import image_pack+ return image_pack.ready(model_root, group='stems')+++def install(model_root, engine_root, progress, cancelled):+ from ..image_gen import image_pack++ def check():+ if cancelled():+ raise InterruptedError('cancelled')++ def moved(value):+ if value.get('phase') == 'download' and value.get('total'):+ progress(min(1., value['done'] / value['total']))+ try:+ image_pack.install(model_root, moved, check, engine_root=engine_root, group='stems')+ except image_pack.PackError as error:+ raise StemsError('stems_download_failed', error.reason) from None+++def separate(source, out_dir, *, server=None, cancelled=lambda: False, phase=lambda name, fraction=None: None):+ """Write dialogue.wav, music.wav and ambience.wav into out_dir; returns the worker's result.++ Raises Preempted when a video started, InterruptedError when cancelled, StemsError otherwise."""+ from ..comfy_bridge import installation+ root, machine = installation()+ if not ready(machine['model_root']):+ phase('downloading', 0.)+ install(machine['model_root'], root, lambda fraction: phase('downloading', fraction), cancelled)+ if cancelled():+ raise InterruptedError('cancelled')+ phase('separating')+ with ACTIVE.lock:+ ACTIVE.preempted = False+ ACTIVE.idle.clear()+ try:+ return _run(source, out_dir, server, cancelled, root, machine)+ except BlockingIOError:+ raise Preempted() from None+ finally:+ with ACTIVE.lock:+ ACTIVE.process = None+ ACTIVE.idle.set()+++def _run(source, out_dir, server, cancelled, root, machine):+ from ..image_gen import image_pack+ from ..locking import runtime_lock+ from .. import processes, resident_process+ _yield_gpu(server)+ with runtime_lock(Path(root) / 'engine.lock', inherit=False, wait_seconds=10) as descriptor:+ env = environment(root)+ owner = resident_process.OWNER+ if owner.process is not None and owner.process.poll() is None and owner.endpoint:+ env[resident_process.ENV] = str(owner.endpoint)+ try:+ resident_process.release_idle_cache(env, descriptor)+ owner.record(action='released', reason='stems_model')+ except resident_process.SessionRestarted:+ pass+ env.pop(resident_process.ENV, None)+ command = processes.module_command(+ 'freevideo_engine.stems.worker', '--weights', image_pack.base(machine['model_root']) / WEIGHTS,+ '--source', source, '--out', out_dir, '--device', machine.get('device_backend', 'cuda'))+ command[0] = machine['comfy_python']+ env['FREEVIDEO_RUNTIME_LOCK_FD'] = str(descriptor)+ with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as errors:+ with ACTIVE.lock:+ if ACTIVE.preempted:+ raise Preempted()+ process = processes.popen(command, env=env, stdin=subprocess.DEVNULL, stdout=output, stderr=errors,+ pass_fds=(descriptor,), supervise=True, start_new_session=True)+ ACTIVE.process = process+ began, timed_out = time.monotonic(), False+ try:+ while process.poll() is None:+ timed_out = time.monotonic() - began > WORKER_SECONDS+ if cancelled() or timed_out:+ break+ time.sleep(POLL_SECONDS)+ finally:+ if process.poll() is None:+ processes.stop(process, grace=5)+ process.wait()+ with ACTIVE.lock:+ ACTIVE.process = None+ preempted = ACTIVE.preempted+ if preempted:+ raise Preempted()+ if cancelled():+ raise InterruptedError('cancelled')+ value = _result(output)+ if not value.get('ok'):+ errors.seek(0, 2)+ errors.seek(max(0, errors.tell() - 4000))+ logging.warning('[FreeVideo] Separation worker failed (exit %s, %s): %s', process.returncode,+ value.get('error') or 'no result', errors.read().decode('utf-8', 'replace'))+ code = value.get('error')+ raise StemsError('out_of_memory' if code == 'out_of_memory' else code if code == 'no_audio'+ else 'stems_failed', code if isinstance(code, str) else 'timeout' if timed_out else 'worker_exit')+ return valuediff --git a/freevideo_engine/stems/worker.py b/freevideo_engine/stems/worker.pynew file mode 100644index 0000000..8a964ca--- /dev/null+++ b/freevideo_engine/stems/worker.py@@ -0,0 +1,40 @@+"""Run one audio separation in an isolated process and emit a final machine-readable JSON line."""+import argparse+import json+from pathlib import Path+import sys+++def main(argv=None):+ code = 'bad_request'+ try:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--weights', required=True)+ parser.add_argument('--source', required=True)+ parser.add_argument('--out', required=True)+ parser.add_argument('--device', default='cuda')+ args = parser.parse_args(argv)+ from .separate import separate_file+ code = 'separation_failed'+ paths, numbers = separate_file(args.source, args.out, args.weights, device=args.device)+ result = dict(ok=True, paths={name: str(Path(path)) for name, path in paths.items()}, **numbers)+ status = 0+ except Exception as exc:+ try:+ import torch+ if isinstance(exc, torch.cuda.OutOfMemoryError):+ code = 'out_of_memory'+ except ImportError:+ pass+ if isinstance(exc, FileNotFoundError):+ code = 'model_missing'+ elif type(exc).__name__ == 'SeparationError' and exc.args:+ code = str(exc.args[0])+ result = dict(ok=False, error=code, detail=str(exc)[:2000])+ status = 1+ print(json.dumps(result, ensure_ascii=False), flush=True)+ return status+++if __name__ == '__main__':+ sys.exit(main())diff --git a/web/editor.css b/web/editor.cssindex 3a00990..41d3bb6 100644--- a/web/editor.css+++ b/web/editor.css@@ -55,6 +55,7 @@.fv-ed-preview-close svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round}.fv-editor .fv-ed-play:disabled{opacity:.4}.fv-editor:has(.fv-ed-track-row[data-track=a2]){--fv-ed-tracks-min:220px}+.fv-editor:has(.fv-ed-track-row[data-track=a4]){--fv-ed-tracks-min:330px}.fv-editor .fv-ed-track-view{height:100%}.fv-ed-picture>video{position:absolute;width:100%;height:100%;inset:0;object-fit:contain;opacity:0;pointer-events:none}.fv-ed-picture>video.fv-ed-visible{opacity:1}diff --git a/web/editor.js b/web/editor.jsindex 815c31c..9739555 100644--- a/web/editor.js+++ b/web/editor.js@@ -22,6 +22,7 @@ import {pictureSession} from './editor_picture_session.js';import {createPictureTools} from './editor_frame.js';import {openExportDialog} from './editor_export_dialog.js';import {createAudioIntegration, createSpeechSpans, handleAudioShortcut, AUDIO_SHORTCUTS} from './editor_audio.js';+import {createStemsIntegration} from './editor_stems.js';import {createSpeedComponent, readSpeedAudioSamples, handleSpeedKey, speedShortcuts} from './editor_speed.js';import {createEditorGenbar, loadEditorComponents, editorBlockStates, blockMessages} from './editor_genbar.js';import {createEditorMusic} from './editor_music.js';@@ -254,7 +255,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenlet discardOnSwitch = false, initialSelection = null, offerInitial = null, extendEntry = null;let viewKey = null, viewReady = false;let library = null, closing = false, closePromise = null, exportSnapshot = null, lastSeed = null, projectEpoch = 0;- let disposed = false, suppressSave = false, savedContent = '', initializing = true, tracks = null, genbar = null, adjustPanel = null, exportStatus = null, pointerEditing = false, deferredStamp = null;+ let stems = null, disposed = false, suppressSave = false, savedContent = '', initializing = true, tracks = null, genbar = null, adjustPanel = null, exportStatus = null, pointerEditing = false, deferredStamp = null;let capability = {maxSeconds: 15, maxFollowSeconds: 15, maxRequestFrames: null, estimate: () => null}, generationBusy = false, switching = false, generationDone = null, finishGeneration = null;let noticeTimer = null, stopExport = null, mostRecentJob = null, exportPreparing = false, guide = null;const jobWatchers = new Map(), progress = new Map(), jobStatuses = new Map(), runProgress = new Map();@@ -1141,6 +1142,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given},async cancel() {if (music.target()) { await music.cancel(); return; }+ if (stems?.active()) { await stems.cancel(); return; }const range = selectionRange(state.selection);const own = range && state.record.tracks[0].clips.find(clip => clip.job && generating(clip)&& clip.start < range.start + range.frames && clip.start + clip.frames > range.start)?.job;@@ -1314,9 +1316,11 @@ export function openEditor({api, app, from = null, panel = {}, components: givenconst transportControls = createEditorTransport({element, preview, transport, toolbar, editTools, zoomHost, state, player, t, notify});toolbar.append(adjust.toggleButton);const textTools = createEditorText({element, state, t, actions, adjust, player, toolbar, exportBox, tracksHost});- const toolbarMore = createToolbarMore({toolbar, t, keep: '.fv-ed-undo, .fv-ed-split, .fv-ed-delete, .fv-ed-adjust-toggle, .fv-ed-zoom'});+ const toolbarMore = createToolbarMore({toolbar, t, keep: '.fv-ed-undo, .fv-ed-split, .fv-ed-delete, .fv-ed-adjust-toggle, .fv-ed-zoom, .fv-ed-stems-button'});actions.speech.ability().then(value => { if (!disposed) textTools.speech(value); }).catch(() => {});const audio = createAudioIntegration({state, player, t, error, adjust, library: libraryHost, store});+ stems = createStemsIntegration({state, api, queue, store, t, error, notify, toolbar, show: job => genbar?.update(job),+ restore: () => genbar?.update(mostRecentJob ? barJob(jobStatuses.get(mostRecentJob)) : null)});registerEditorShortcuts(AUDIO_SHORTCUTS, speedShortcuts);adjust.register('speed', createSpeedComponent({state, t, onError: error}));function selectedContent() {@@ -1521,7 +1525,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenawait store.activateProject(null).catch(() => {});rememberView(); disposed = true; music.dispose(); guide?.dispose(); transportControls.dispose(); toolbarMore.dispose(); player.dispose();textTools.dispose(); adjust.dispose(); notes.dispose(); pictureEdit.dispose();- audio.dispose(); headerFit.dispose();+ audio.dispose(); stems?.dispose(); headerFit.dispose();listeners.splice(0).forEach(remove => remove());for (const node of [element, ...element.querySelectorAll('*')]) for (const name of ['onclick', 'ondblclick', 'oninput', 'onchange', 'onkeydown', 'ondragstart']) node[name] = null;unsubscribe(); stopSources(); library?.dispose(); genbar.dispose(); tracks?.dispose(); stopExport?.();diff --git a/web/editor_audio_model.js b/web/editor_audio_model.jsindex dcc0546..5d39220 100644--- a/web/editor_audio_model.js+++ b/web/editor_audio_model.js@@ -28,6 +28,14 @@ export function audioClipFields(raw, kind) {if (kind !== 'audio' || typeof raw.duck !== 'boolean') fail('audio');fields.duck = raw.duck;}+ if (raw.stem_of !== undefined) {+ if (kind !== 'audio' || typeof raw.stem_of !== 'string' || !/^c[1-9]\d{0,8}$/.test(raw.stem_of) || raw.stem_of === raw.id || raw.link) fail('stems');+ fields.stem_of = raw.stem_of;+ }+ if (raw.stem_volume !== undefined) {+ if (kind !== 'audio' || typeof raw.stem_volume !== 'number' || !(raw.stem_volume >= 0 && raw.stem_volume <= 2)) fail('stems');+ fields.stem_volume = raw.stem_volume;+ }return fields;}export function audioTrackFields(raw) {@@ -39,6 +47,11 @@ export function audioTrackFields(raw) {return fields;}export function normalizeAudioEdits(record) {+ // A clip silenced for its separated sound speaks again once no stem clip refers to it.+ const stemmed = new Set(record.tracks.flatMap(track => track.clips).map(clip => clip.stem_of));+ for (const track of record.tracks) for (const clip of track.clips) {+ if (clip.stem_volume !== undefined && !stemmed.has(clip.id)) { clip.volume = clip.stem_volume; delete clip.stem_volume; }+ }for (const track of record.tracks) for (const clip of track.clips) {for (const name of ['fade_in', 'fade_out']) if (clip[name] !== undefined) clip[name] = Math.min(clip[name], Math.floor(clip.frames / 2));}diff --git a/web/editor_menu.js b/web/editor_menu.jsindex 52f6efc..eff3e1b 100644--- a/web/editor_menu.js+++ b/web/editor_menu.js@@ -119,6 +119,7 @@ export function createTrackMenu(host, {state, t = en => en, actions = {}, hitTesconst label = document.createElement('span'), shortcut = document.createElement('span');label.className = 'fv-ed-menu-label'; label.textContent = item.label;shortcut.className = 'fv-ed-menu-shortcut'; shortcut.textContent = item.shortcut;+ if (item.tourId) button.dataset.tourId = item.tourId;button.append(label, shortcut);// Keep disabled items discoverable without explanatory tooltips.button.onclick = () => {@@ -133,7 +134,9 @@ export function createTrackMenu(host, {state, t = en => en, actions = {}, hitTesconst width = window.innerWidth || document.documentElement?.clientWidth || 1440;const height = window.innerHeight || document.documentElement?.clientHeight || 900;element.style.left = `${Math.max(8, Math.min(event.clientX, width - bounds.width - 8))}px`;- element.style.top = `${Math.max(8, Math.min(event.clientY, height - bounds.height - 8))}px`;+ // Without room below the pointer the menu opens upward from it, so it never slides over the toolbar beside it.+ const below = event.clientY + bounds.height + 8 <= height;+ element.style.top = `${Math.max(8, below ? event.clientY : event.clientY - bounds.height)}px`;(buttons[0] || element).focus({preventScroll: true});};const outside = event => { if (!element.contains(event.target)) close(); }, closeMenu = () => close();diff --git a/web/editor_model.js b/web/editor_model.jsindex d34926f..a18497a 100644--- a/web/editor_model.js+++ b/web/editor_model.js@@ -15,7 +15,7 @@ export const RULES = Object.freeze({maxSeconds: 15, singleSeconds: 30, minSecondfollowSeconds: CHAIN_RULES.min_part_seconds, fullSeconds: CHAIN_RULES.full_part_seconds,continueSeconds: CHAIN_RULES.continue_seconds, shortContinueSeconds: CHAIN_RULES.short_continue_seconds,step: 17, first: 5, overlap: 22,- maxTracks: 3, maxClips: 500, maxText: 8000, maxParts: CHAIN_RULES.max_parts, shortMaxParts: CHAIN_RULES.short_max_parts});+ maxTracks: 7, maxClips: 500, maxText: 8000, maxParts: CHAIN_RULES.max_parts, shortMaxParts: CHAIN_RULES.short_max_parts});// Slice and bound user text by Unicode code points, never UTF-16 halves.export const truncateText = (text, limit) => Array.from(text).slice(0, limit).join('');export const copyName = (name, suffix) => truncateText(name, RULES.maxText - Array.from(suffix).length) + suffix;@@ -137,11 +137,14 @@ export function parse(value) {check(value.settings === null || object(value.settings), 'settings');const settings = jsonData(value.settings);check(JSON.stringify(settings).length <= 1024 * 1024, 'settings');- check(Array.isArray(value.tracks) && value.tracks.length >= 2 && value.tracks.length <= RULES.maxTracks, 'track');+ check(Array.isArray(value.tracks) && value.tracks.length >= 2 && value.tracks.length <= RULES.maxTracks+ && value.tracks.length !== 4 && value.tracks.length !== 5 && value.tracks.length !== 6, 'track');const ids = new Set();const tracks = value.tracks.map((raw, index) => {- const id = ['v1', 'a1', 'a2'][index], kind = index === 0 ? 'video' : 'audio';+ const id = ['v1', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6'][index], kind = index === 0 ? 'video' : 'audio';check(object(raw) && raw.id === id && raw.kind === kind, 'track');+ // The three tracks after a3 are the separated sound of one clip each: all of them or none.+ check(index < 4 ? raw.stem === undefined : raw.stem === STEM_TRACKS[index - 4], 'track');check(Array.isArray(raw.clips) && raw.clips.length <= RULES.maxClips, 'track');let boundary = 0;const clips = raw.clips.map(item => {@@ -188,7 +191,7 @@ export function parse(value) {Object.assign(clip, parseSpeedData(item, kind));return clip;});- return {id, kind, clips, ...audioTrackFields(raw)};+ return {id, kind, clips, ...audioTrackFields(raw), ...(raw.stem !== undefined ? {stem: raw.stem} : {})};});const byId = new Map(tracks.flatMap(track => track.clips.map(clip => [clip.id, {clip, track}])));for (const {clip, track} of byId.values()) if (clip.link) {@@ -498,6 +501,32 @@ export function insertSource(record, {source, frames, hasVideo, hasAudio, width,if (words && storedSize(result) > STORED_ROOM) return insertSource(record, {source: given, frames, hasVideo, hasAudio, width, height, at: position, targetTrack});return result;}+// The separated sound of an audio clip: three tracks after a2 hold one clip each (dialogue, music, ambience)+// over the parent's range, and the parent goes silent. Deleting every stem clip gives the parent its volume back+// (normalizeAudioEdits), so the silence needs no separate undo.+export const STEM_TRACKS = Object.freeze(['dialogue', 'music', 'ambience']);+export function placeStems(record, id, sources) {+ const next = copy(record), parent = find(next, id);+ check(parent && trackOf(next, id).kind === 'audio' && parent.source && !parent.pending, 'missing');+ check(!trackOf(next, id).locked, 'locked');+ check(!all(next).some(clip => clip.stem_of === id), 'stems');+ check(object(sources) && STEM_TRACKS.every(name => object(sources[name])), 'source');+ audioTrack(next, 'a2'); audioTrack(next, 'a3');+ const rows = ['a4', 'a5', 'a6'].map((track, index) => {+ const row = audioTrack(next, track); row.stem = STEM_TRACKS[index];+ check(!row.locked && !row.clips.some(clip => overlaps(clip, parent.start, parent.frames)), 'audio_full');+ return row;+ });+ const volume = parent.volume;+ rows.forEach((row, index) => {+ const clip = newClip(next, row, {source: sourceData(sources[STEM_TRACKS[index]]), start: parent.start, frames: parent.frames});+ for (const name of ['in', 'length', 'splice', 'speed', 'speed_audio', 'reverse', 'fade_in', 'fade_out'])+ if (parent[name] !== undefined) clip[name] = JSON.parse(JSON.stringify(parent[name]));+ clip.stem_of = id;+ });+ parent.stem_volume = volume; parent.volume = 0;+ return finish(next);+}export function move(record, id, start, {targetTrack} = {}) {if (isText(find(record, id))) return changeText(record, id, {start});check(whole(start), 'range'); const selected = pair(record, id); check(selected.length, 'missing'); busy(selected);diff --git a/web/editor_player.js b/web/editor_player.jsindex 000a840..83d3ed1 100644--- a/web/editor_player.js+++ b/web/editor_player.js@@ -39,7 +39,8 @@ export function createEditorPlayer(host, transport, {state, sources, api, t, errconst closeIcon = document.createElementNS(pictureIcon.namespaceURI, 'svg'), closePath = document.createElementNS(pictureIcon.namespaceURI, 'path');closeIcon.setAttribute('viewBox', '0 0 16 16'); closeIcon.setAttribute('aria-hidden', 'true'); closePath.setAttribute('d', 'm4 4 8 8M12 4l-8 8'); closeIcon.append(closePath); closePreview.append(closeIcon); frame.append(closePreview);const videos = [el('video'), el('video')]; videos.forEach(video => { video.playsInline = true; video.preload = 'auto'; video.controls = false; video.setAttribute('aria-hidden', 'true'); frame.append(video); });- const audio = [el('audio'), el('audio')]; audio.forEach(value => { value.preload = 'auto'; frame.append(value); });+ // One element per sound track (a1–a6): the three separated parts play together with the voice and music tracks.+ const audio = Array.from({length: 6}, () => el('audio')); audio.forEach(value => { value.preload = 'auto'; frame.append(value); });const chainAudio = new Map(); // Separate players keep the other track's media slot stable.const allMedia = () => [...videos, ...audio, ...chainAudio.values()];const pictureGuide = createPictureGuide(host, frame, {state, t});diff --git a/web/editor_room.js b/web/editor_room.jsindex f971e1f..2494f63 100644--- a/web/editor_room.js+++ b/web/editor_room.js@@ -100,7 +100,7 @@ export function pasteContent(record, content, at) {if (isText(clip) && track.clips.some(other => other.start < end(clip) && end(other) > clip.start)) throw new EditError('overlap');track.clips.push(clip);}- next.tracks.sort((a,b) => ['v1','a1','a2','t1','s1'].indexOf(a.id) - ['v1','a1','a2','t1','s1'].indexOf(b.id));+ next.tracks.sort((a,b) => ['v1','a1','a2','a3','a4','a5','a6','t1','s1'].indexOf(a.id) - ['v1','a1','a2','a3','a4','a5','a6','t1','s1'].indexOf(b.id));next.tracks.forEach(track => track.clips.sort((a, b) => a.start - b.start));return {record: model.parse(next), ids: [...ids.values()], end: Math.max(...entries.map(item => end(item.clip)))};}diff --git a/web/editor_stems.js b/web/editor_stems.jsnew file mode 100644index 0000000..b99facc--- /dev/null+++ b/web/editor_stems.js@@ -0,0 +1,168 @@+import * as model from './editor_model.js';+import {registerMenuItem} from './editor_menu.js';+import {agentGet, agentPost, retryAgentPost} from './agent_session.js';+import {sourceKey} from './editor_store.js';++const ROOT = '/freevideo/agent/v1';+const ACTIVE = ['waiting', 'queued', 'running', 'cancelling'];+// Answers the separation can end with; anything else is reported by the editor's own error line.+const FAILURES = {+ stems_download_failed: ['The separation model could not be downloaded. Check the network and try again.', '分离模型下载失败,请检查网络后重试。'],+ out_of_memory: ['Not enough graphics memory to separate this sound.', '显存不足,无法分离这段声音。'],+ stems_failed: ['The sound could not be separated. Try again.', '声音分离失败,请重试。'],+ project_changed: ['The edit changed meanwhile. Try again.', '编辑内容已变化,请重试。'],+ clip_busy: ['This clip is still being made.', '这个片段还在生成。'],+ clip_locked: ['This clip is locked.', '这个片段已锁定。'],+ audio_full: ['The tracks for the separated sound are not free here.', '这里没有空闲的分轨位置。'],+};+const wait = ms => new Promise(resolve => setTimeout(resolve, ms));+const generatedSource = text => {+ const match = /^generated:(.+)$/.exec(String(text || ''));+ if (!match) throw new model.EditError('source');+ return {kind: 'generated', id: match[1]};+};+const children = (record, id) => record.tracks.flatMap(track => track.clips).filter(clip => clip.stem_of === id);++// A sound clip is split into dialogue, music and ambience. The job leaves the project alone (lay: false); this page+// places the three parts itself, so its own saves never clash with the job and the placement can be undone.+export function createStemsIntegration({state, api, queue, store, t, error, notify, show, restore, toolbar}) {+ let running = null, disposed = false, available = false, unsubscribe = null;+ const say = (value, fallback) => {+ const code = value?.code || value?.error?.code, text = FAILURES[code];+ if (text) notify(t(...text)); else error(value?.error || value || new Error(fallback), 'stems');+ };+ const phaseWords = progress => {+ const detail = (() => { try { return JSON.parse(progress?.detail || 'null'); } catch { return null; } })();+ switch (progress?.phase) {+ case 'downloading': return Number.isFinite(detail?.fraction)+ ? t(`Downloading the separation model ${Math.round(detail.fraction * 100)}%`, `正在下载分离模型 ${Math.round(detail.fraction * 100)}%`)+ : t('Downloading the separation model', '正在下载分离模型');+ case 'separating': return t('Separating the sound', '正在分离声音');+ case 'waiting': return t('Waiting for the video to finish', '等待视频生成完成');+ case 'placing': return t('Adding the tracks', '正在放入时间线');+ default: return t('Preparing', '正在准备');+ }+ };+ const paint = (job, stage) => show({id: `stems:${job}`, state: 'running', blocks: [], words: {stage}});+ const parent = context => context.count === 1 && context.clip;+ const splittable = context => {+ const clip = parent(context), track = clip && context.record.tracks.find(row => row.clips.includes(clip));+ return !!clip && track?.kind === 'audio' && !!clip.source && !clip.pending && clip.stem_of === undefined+ && !track.locked && !children(context.record, clip.id).length && !running;+ };+ const stemmed = context => !!parent(context) && children(context.record, context.clip.id).length > 0;+ // The sound clip the toolbar button acts on: the one sound clip inside the selection, whether it was picked alone or with its picture.+ const target = () => {+ const selection = state.selection;+ if (selection?.kind !== 'clip') return null;+ const sound = state.record.tracks.filter(track => track.kind === 'audio')+ .flatMap(track => track.clips.filter(clip => selection.ids.includes(clip.id)).map(clip => ({clip, track})));+ return sound.length === 1 && !!sound[0].clip.source && sound[0].clip.stem_of === undefined ? sound[0] : null;+ };+ let button = null, holder = null;+ const sync = () => {+ if (!button) return;+ const found = available && target();+ button.hidden = holder.hidden = !found;+ if (!found) return;+ const {clip, track} = found;+ button.disabled = !!running || !!clip.pending || track.locked || children(state.record, clip.id).length > 0;+ };+ // The entries exist only where the engine offers the separation, so other computers keep the menu they had.+ let stops = [];+ const capability = (async () => {+ try {+ const response = await api.fetchApi('/freevideo/stems-support', {cache: 'no-store'});+ const value = response.ok ? await response.json() : null;+ available = value?.available === true;+ } catch { available = false; }+ if (available && !disposed && toolbar) {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true'); svg.classList.add('fv-ed-glyph');+ const path = document.createElementNS(svg.namespaceURI, 'path');+ path.setAttribute('d', 'M2 8h1.5M5 5v6M8 3v10M11 5.5v5M14 8h-1'); path.setAttribute('fill', 'none'); path.setAttribute('stroke', 'currentColor');+ path.setAttribute('stroke-width', '1.4'); path.setAttribute('stroke-linecap', 'round'); svg.append(path);+ const text = document.createElement('span'); text.className = 'fv-ed-stems-label'; text.textContent = t('Separate tracks', '分离音轨');+ button = document.createElement('button'); button.type = 'button'; button.className = 'fv-action fv-ed-stems-button'; button.hidden = true;+ button.setAttribute('aria-label', t('Separate tracks', '分离音轨')); button.title = t('Separate tracks', '分离音轨'); button.dataset.tourId = 'audio-track-button';+ button.append(svg, text);+ button.onclick = () => { const found = target(); if (found && !button.disabled) void separate(found.clip.id); };+ holder = document.createElement('div'); holder.className = 'fv-ed-tool-group fv-ed-stems-group'; holder.hidden = true; holder.append(button);+ const anchor = toolbar.querySelector('.fv-ed-split')?.closest('.fv-ed-tool-group');+ if (anchor) anchor.after(holder); else toolbar.insertBefore(holder, toolbar.querySelector('.fv-ed-zoom'));+ unsubscribe = state.subscribe(event => { if (event.type === 'selection' || event.type === 'record') sync(); });+ sync();+ }+ if (available && !disposed) stops = [+ registerMenuItem({where: 'part', group: 'sound', label: context => context.t('Separate tracks', '分离音轨'),+ enabled: splittable, tourId: 'audio-track-entry', run: context => { void separate(context.clip.id); }}),+ registerMenuItem({where: 'part', group: 'sound', label: context => context.t('Export stems', '导出分轨'),+ enabled: stemmed, run: context => { void exportStems(context.clip.id); }}),+ ];+ })();+ async function ready() {+ await capability;+ if (!available) { notify(t('Separating audio is not available on this computer.', '这台电脑暂不支持分离音轨。')); return false; }+ await queue.flush();+ if (queue.dirty || !state.record.id) { notify(t('The edit could not be saved yet. Try again.', '编辑内容尚未保存,请稍后重试。')); return false; }+ return true;+ }+ async function separate(clipId) {+ if (running) { notify(t('A sound is already being separated.', '正在分离另一段声音。')); return false; }+ const tool = running = {cancelled: false, job: null}; sync();+ try {+ if (!await ready()) return false;+ const project = state.record.id, ref = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;+ const body = {revision: state.record.revision, clip_id: clipId, lay: false, ref};+ paint('start', phaseWords());+ const response = await retryAgentPost(api, `${ROOT}/projects/${encodeURIComponent(project)}/stems`, body);+ const answer = await response?.json().catch(() => null);+ if (!response?.ok || !answer?.job?.id && !answer?.jobs?.[0]?.id) { say(answer, 'stems_failed'); return false; }+ tool.job = (answer.job || answer.jobs[0]).id;+ let job = answer.job || answer.jobs[0];+ while (!disposed && ACTIVE.includes(job.status)) {+ paint(tool.job, tool.cancelled ? t('Stopping…', '正在停止…') : job.status === 'queued' || job.status === 'waiting' ? t('Queued', '排队中') : phaseWords(job.progress));+ const reply = await agentGet(api, `${ROOT}/jobs/${encodeURIComponent(tool.job)}?wait=25`);+ if (!reply.ok) { await wait(1000); continue; }+ job = await reply.json();+ }+ if (disposed || state.record.id !== project) return false;+ if (job.status !== 'succeeded') {+ if (job.status !== 'cancelled' && !tool.cancelled) say(job.error, 'stems_failed');+ return false;+ }+ const sources = Object.fromEntries(model.STEM_TRACKS.map(name => [name, generatedSource(job.result?.sources?.[name])]));+ await store.getSources(Object.values(sources).map(sourceKey));+ if (disposed || state.record.id !== project) return false;+ try {+ state.apply(t('Separate tracks', '分离音轨'), record => model.placeStems(record, clipId, sources));+ } catch (value) {+ if (value instanceof model.EditError) notify(t(...FAILURES[value.code === 'audio_full' ? 'audio_full' : 'stems_failed'])); else error(value, 'stems');+ return false;+ }+ return true;+ } catch (value) {+ if (value?.name !== 'AbortError') say(value, 'stems_failed');+ return false;+ } finally { running = null; sync(); restore(); }+ }+ async function cancel() {+ const tool = running; if (!tool) return false;+ tool.cancelled = true;+ if (tool.job) await agentPost(api, `${ROOT}/jobs/${encodeURIComponent(tool.job)}/cancel`, {}).catch(() => {});+ return true;+ }+ async function exportStems(clipId) {+ try {+ if (!await ready()) return false;+ const body = {revision: state.record.revision, clip_id: clipId, ref: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`};+ const response = await retryAgentPost(api, `${ROOT}/projects/${encodeURIComponent(state.record.id)}/stems/export`, body);+ const answer = await response?.json().catch(() => null);+ if (!response?.ok) { say(answer, 'stems_failed'); return false; }+ notify(t(`Saved the tracks to ${answer.folder}`, `分轨已保存到 ${answer.folder}`));+ return true;+ } catch (value) { say(value, 'stems_failed'); return false; }+ }+ return {separate, cancel, exportStems, active: () => !!running,+ dispose() { disposed = true; stops.forEach(stop => stop()); stops = []; unsubscribe?.(); holder?.remove(); button = holder = null; }};+}diff --git a/web/editor_text_model.js b/web/editor_text_model.jsindex 944f107..7ed1059 100644--- a/web/editor_text_model.js+++ b/web/editor_text_model.js@@ -59,7 +59,7 @@ export function readTextProject(raw, parseMedia) {}const style = cleanStyle(raw.subtitle_style, 'subtitle');if (Object.keys(style).length && result.tracks.some(t => t.kind === 'subtitle')) result.subtitle_style = style;- result.tracks.sort((a,b) => ['v1','a1','a2','t1','s1'].indexOf(a.id) - ['v1','a1','a2','t1','s1'].indexOf(b.id));+ result.tracks.sort((a,b) => ['v1','a1','a2','a3','a4','a5','a6','t1','s1'].indexOf(a.id) - ['v1','a1','a2','a3','a4','a5','a6','t1','s1'].indexOf(b.id));return freeze(result);}export function assertUnlocked(record, ids) {diff --git a/web/editor_tracks.css b/web/editor_tracks.cssindex dd581c8..bd5929a 100644--- a/web/editor_tracks.css+++ b/web/editor_tracks.css@@ -46,6 +46,8 @@.fv-ed-block-progress{display:none}.fv-ed-clip[data-state=running] .fv-ed-block-progress,.fv-ed-block-progress[data-queued=true]{display:block}.fv-ed-clip[data-state=failed]{border:1px solid color-mix(in srgb,var(--fv-warning) 60%,transparent);background:color-mix(in srgb,var(--fv-warning) 12%,transparent);cursor:grab}+.fv-ed-clip[data-split=true]{background:repeating-linear-gradient(to bottom,color-mix(in srgb,var(--fv-ink) 6%,transparent) 0 33.33%,transparent 33.33% 66.66%,color-mix(in srgb,var(--fv-ink) 6%,transparent) 66.66% 100%)}+.fv-ed-clip[data-split=true] .fv-ed-clip-media{opacity:.35}.fv-ed-clip-status{position:absolute;left:10px;right:4px;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap;overflow:hidden;color:var(--fv-warning);pointer-events:none}.fv-ed-clip-status svg{width:12px;height:12px;flex:none;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round}.fv-ed-clip-failure-reason{overflow:hidden;text-overflow:ellipsis}@@ -82,7 +84,7 @@.fv-ed-clip-popover button+button{margin-left:6px}.fv-ed-clip-popover{max-height:calc(100% - 16px);overflow:auto}.fv-ed-track-view [hidden]{display:none!important}-@media(max-width:520px){.fv-ed-track-view{--fv-ed-head-width:32px}.fv-ed-track-head>span:first-of-type{display:none}.fv-ed-track-zoom{right:8px}.fv-ed-clip-status{left:5px;font-size:11px}}+@media(max-width:520px){.fv-ed-track-view,.fv-studio.fv-editor .fv-ed-track-view[data-track-switches],.fv-studio.fv-editor[data-text-tracks] .fv-ed-track-view{--fv-ed-head-width:52px}.fv-studio.fv-editor .fv-ed-track-head>svg{display:none}.fv-ed-track-head{padding:0 2px;box-sizing:border-box}.fv-ed-track-head>span:first-of-type{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}.fv-ed-track-zoom{right:8px}.fv-ed-clip-status{left:5px;font-size:11px}}@media(forced-colors:active){.fv-ed-clip,.fv-ed-selection,.fv-ed-gesture-preview{border-color:Highlight}.fv-ed-playhead,.fv-ed-snap-line{background:CanvasText}}/* Gesture affordances; track slots and heads are owned by the track layout. */@@ -106,3 +108,9 @@.fv-ed-selection.fv-ed-range-blocked .fv-ed-planned-label{color:var(--fv-danger)}.fv-ed-track-view[data-cursor=not-allowed] .fv-ed-track-content,.fv-ed-track-view[data-cursor=not-allowed] .fv-ed-track-content *{cursor:not-allowed}.fv-ed-clip.fv-ed-tiny{z-index:3;border-radius:0}+.fv-editor .fv-ed-toolbar .fv-ed-stems-button{width:auto;padding:0 10px}+.fv-editor .fv-ed-toolbar .fv-ed-stems-button[hidden]{display:none}+.fv-editor .fv-ed-toolbar .fv-ed-stems-button .fv-ed-glyph{width:16px;height:16px;flex:none}+@media(max-width:520px){.fv-editor .fv-ed-toolbar .fv-ed-stems-button{width:32px;padding:0}.fv-ed-stems-label{display:none}}+.fv-editor .fv-ed-toolbar .fv-ed-stems-group{margin-left:-8px}.fv-editor .fv-ed-toolbar .fv-ed-stems-group:before{display:none}.fv-ed-stems-group[hidden]{display:none}+@media(max-width:480px){.fv-editor .fv-ed-toolbar .fv-ed-stems-group{margin-left:0}}diff --git a/web/editor_tracks.js b/web/editor_tracks.jsindex 66f94e7..1e8e79d 100644--- a/web/editor_tracks.js+++ b/web/editor_tracks.js@@ -492,12 +492,16 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =const openFailure = !popover.hidden && failedPopoverId;selectGestures.finish(null, true);cachedPlan = ''; popover.hidden = true;- const record = state.record, retained = new Set(), tracks = displayTracks(record);+ const record = state.record, retained = new Set();+ // The model keeps a2 and a3 so the separated parts sit at fixed places; while they hold nothing they stay out of sight.+ const separated = record.tracks.some(track => track.stem);+ const tracks = displayTracks(record).filter(track => !(separated && track.kind === 'audio' && !track.stem && track.id !== 'a1' && !track.clips.length));const twoAudio = tracks.some(track => track.id === 'a2');- let top = 24;+ const STEM_NAMES = {dialogue: t('Dialogue', '人声'), music: t('Music', '音乐'), ambience: t('Ambience', '环境声')};+ let top = 24, parted = false;for (const track of tracks) {- const name = track.kind === 'text' ? t('Text', '文字') : track.kind === 'subtitle' ? t('Subtitles', '字幕') : track.kind === 'video' ? t('Video', '画面') : twoAudio- ? t(`Audio ${track.id === 'a1' ? 1 : 2}`, `声音 ${track.id === 'a1' ? 1 : 2}`) : t('Audio', '声音');+ const name = track.kind === 'text' ? t('Text', '文字') : track.kind === 'subtitle' ? t('Subtitles', '字幕') : track.kind === 'video' ? t('Video', '画面') : track.stem ? STEM_NAMES[track.stem] : twoAudio+ ? t(`Audio ${track.id.slice(1)}`, `声音 ${track.id.slice(1)}`) : t('Audio', '声音');let row = rows.get(track.id);if (!row) {const node = create('div', 'fv-ed-track-row'); node.dataset.track = track.id;@@ -507,7 +511,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =const head = create('div', 'fv-ed-track-head'); head.dataset.track = track.id;head.title = name; head.append(icon(track.kind), create('span', '', name));heads.append(head); content.insertBefore(node, overlays);- row = {element: node, head, empty}; rows.set(track.id, row);+ row = {element: node, head, empty}; rows.set(track.id, row); parted ||= !!track.stem;}row.head.title = name; row.head.querySelector('span').textContent = name;row.empty.hidden = track.clips.length > 0;@@ -537,6 +541,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =previous = item.element;const visual = model.clipState(clip), key = sourceKey(clip);item.element.dataset.state = visual; item.element.dataset.track = track.id;+ item.element.dataset.split = String(track.kind === 'audio' && clip.stem_of === undefined && state.record.tracks.some(row => row.stem && row.clips.some(other => other.stem_of === clip.id)));item.element.dataset.busy = String(busy(clip)); item.element.dataset.extend = String(clip.extend && actions.generationAvailable?.() !== false && !busy(clip));// A part not generated yet is attached only to the part it continues; drawn on its own it stays a separate block.// Touching blocks are one video only when the later one continues the earlier one, or both are consecutive stretches of one source;@@ -587,6 +592,8 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =addAudio.setAttribute('aria-label', addAudio.textContent);setTrackHeight(top - 6);layout();+ // The parts of a fresh split appear under the sound they came from: show them from the top.+ if (parted) scroll.scrollTop = 0;const failure = openFailure && clips.get(openFailure);if (failure && model.clipState(failure.clip) === 'failed' && state.selection?.ids?.includes(openFailure)) failedPopover(failure);if (gesture?.type === 'move' && pointerEvent) updatePointer(pointerEvent);diff --git a/web/health.js b/web/health.jsindex 80becef..7abb15f 100644--- a/web/health.js+++ b/web/health.js@@ -14,7 +14,7 @@ const t = (en, zh) => cn ? zh : en;const launchVisit = query.get('freevideo') === 'launch';// Every script this folder ships; a test keeps the list in step with web/*.js.export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'qrcodegen.js', 'agent_activity.js', 'agent_confirm_settings.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'chat_attachments.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'chain_rules.js', 'timed_prompt.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',- 'editor.js', 'editor_actions.js', 'editor_lifecycle.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_duration.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_music.js', 'editor_music_model.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js',+ 'editor.js', 'editor_actions.js', 'editor_lifecycle.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_duration.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_stems.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_music.js', 'editor_music_model.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js','editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'done_notify.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'image_lora.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'translate_guard.js', 'output_download.js', 'port_notice.js', 'preview_scene.js','progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_sections.js', 'prompt_terms.js', 'request_assets.js', 'repair_hint.js', 'report_issue.js', 'issue_button.js', 'studio_recent.js','result_actions.js', 'result_reuse.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'replace_person.js', 'replace_state.js', 'optional_inputs.js', 'studio_queue.js', 'studio_size.js',