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.
Keep the guide clip's sound on a guide-based result when requested
Bowen Xue686691eccb73
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex 2da7746..5b219b6 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -1164,6 +1164,9 @@ def _run(args):shutil.copyfile(destination.with_suffix('.engine.json'), artifacts / 'first-pass.engine.json')from .preview import upscale_readsreport['preview']['upscale_reads'] = upscale_reads(request['cache'], report['video'], upscaler_checkpoint)+ if not preview and any(row.get('keep_source_audio') for row in media.get('references', [])):+ from .guide_audio import apply as keep_source_audio+ report['keep_source_audio'] = keep_source_audio(destination, media)report['success'] = Trueexcept BaseException as error:from .diagnostic_resources import exception_detailsdiff --git a/freevideo_engine/guide_audio.py b/freevideo_engine/guide_audio.pynew file mode 100644index 0000000..d70b6e9--- /dev/null+++ b/freevideo_engine/guide_audio.py@@ -0,0 +1,95 @@+"""Keep the guide clip's own sound on a finished guide-based result.++The video stream is copied packet by packet; only the audio stream is replaced, with+the guide's audio trimmed or padded with silence to the video length. Requests+without "keep_source_audio" never reach this module.+"""+from fractions import Fraction+from pathlib import Path++import av+import numpy as np+++def has_audio(path):+ try:+ with av.open(str(path)) as container:+ return bool(container.streams.audio)+ except av.error.FFmpegError as error:+ raise ValueError('Cannot read the guide clip: %s' % error) from error+++def _video_seconds(container, stream):+ end = 0+ for packet in container.demux(stream):+ if packet.pts is not None and packet.duration is not None:+ end = max(end, packet.pts + packet.duration)+ if not end:+ raise ValueError('Cannot measure the video length')+ return float(end * stream.time_base)+++def _guide_samples(path, rate, layout):+ """Decode the guide's first audio stream to float planar samples at the output format."""+ blocks = []+ with av.open(str(path)) as container:+ stream = container.streams.audio[0]+ resampler = av.AudioResampler(format='fltp', layout=layout, rate=rate)+ for frame in container.decode(stream):+ for out in resampler.resample(frame):+ blocks.append(out.to_ndarray())+ for out in resampler.resample(None):+ blocks.append(out.to_ndarray())+ channels = len(av.AudioLayout(layout).channels)+ return np.concatenate(blocks, axis=1) if blocks else np.zeros((channels, 0), np.float32)+++def replace_audio(video, guide, output, *, rate=48000, layout='stereo'):+ """Write ``output``: ``video``'s picture untouched plus ``guide``'s audio fitted to its length."""+ video, guide, output = Path(video), Path(guide), Path(output)+ if not has_audio(guide):+ raise ValueError('The guide clip has no audio stream')+ with av.open(str(video)) as source:+ picture = source.streams.video[0]+ seconds = _video_seconds(source, picture)+ wanted = round(seconds * rate)+ samples = _guide_samples(guide, rate, layout)[:, :wanted]+ if samples.shape[1] < wanted:+ samples = np.pad(samples, ((0, 0), (0, wanted - samples.shape[1])))+ with av.open(str(video)) as source, av.open(str(output), 'w', format='mp4') as result:+ picture = source.streams.video[0]+ copied = result.add_stream_from_template(picture)+ sound = result.add_stream('aac', rate=rate, layout=layout)+ for packet in source.demux(picture):+ if packet.dts is None:+ continue+ packet.stream = copied+ result.mux(packet)+ position = 0+ while position < wanted:+ block = np.ascontiguousarray(samples[:, position:position + 1024])+ frame = av.AudioFrame.from_ndarray(block, format='fltp', layout=layout)+ frame.sample_rate = rate+ frame.pts = position+ frame.time_base = Fraction(1, rate)+ for packet in sound.encode(frame):+ result.mux(packet)+ position += block.shape[1]+ for packet in sound.encode(None):+ result.mux(packet)+ return seconds+++def apply(video, media):+ """Replace ``video`` in place when the request's guide asks to keep its audio. Returns True if replaced."""+ guide = next((row for row in media.get('references', []) if row.get('guide') and row.get('keep_source_audio')), None)+ if guide is None:+ return False+ video = Path(video)+ temporary = video.with_name(video.stem + '.remux.mp4')+ try:+ replace_audio(video, guide['path'], temporary)+ temporary.replace(video)+ finally:+ temporary.unlink(missing_ok=True)+ return Truediff --git a/freevideo_engine/media_request.py b/freevideo_engine/media_request.pyindex f28aa6d..56571c7 100644--- a/freevideo_engine/media_request.py+++ b/freevideo_engine/media_request.py@@ -55,7 +55,7 @@ def read(path):raise ValueError('Invalid ' + field + ' entry')if field != 'references' and 'early_steps' in entry:raise ValueError('early_steps is only allowed on video references')- allowed = {'path', 'kind', 'early_steps', 'sound', 'guide'} if field == 'references' else {'path', 'strength', 'alpha'}+ allowed = {'path', 'kind', 'early_steps', 'sound', 'guide', 'keep_source_audio'} if field == 'references' else {'path', 'strength', 'alpha'}if set(entry) - allowed:raise ValueError('Unknown ' + field + ' fields')row = file_info(entry.get('path'))@@ -76,6 +76,10 @@ def read(path):# keep exactly the same rows and cache key as before.if entry['guide']:row['guide'] = True+ if 'keep_source_audio' in entry:+ validate_keep_source_audio(entry, row['path'])+ if entry['keep_source_audio']:+ row['keep_source_audio'] = Trueelse:if Path(row['path']).suffix.lower() != '.safetensors':raise ValueError('LoRA requires safetensors; pickle adapters are not loaded')@@ -140,6 +144,19 @@ def validate_guide(row):raise ValueError('A guide clip cannot use early_steps')+def validate_keep_source_audio(row, path):+ """Keeping the guide's sound needs a guide clip that has an audio stream."""+ if type(row['keep_source_audio']) is not bool:+ raise ValueError('keep_source_audio must be true or false')+ if not row['keep_source_audio']:+ return+ if row.get('guide') is not True:+ raise ValueError('keep_source_audio is only allowed on a guide clip')+ from .guide_audio import has_audio+ if not has_audio(path):+ raise ValueError('keep_source_audio needs a guide clip with an audio stream')++def reference_stages(media):"""Active references at each boundary; zero-step inputs never reach an encoder."""refs = media.get('references', [])@@ -160,7 +177,7 @@ def cache_key(prompt, media, canvas):for key in ('first', 'last', 'references'):value = media.get(key)if value:- identity[key] = [{k: v for k, v in row.items() if k != 'path'}+ identity[key] = [{k: v for k, v in row.items() if k not in ('path', 'keep_source_audio')}for row in value] if isinstance(value, list) else value['sha256']return 'multimodal:' + json.dumps(identity, sort_keys=True, ensure_ascii=False)