Skip to content

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.

Voice-only video references: small, low-frame-rate picture; audio-only mp4 judged by streams

Bowen Xue10ebf68c343c
diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py
index 906d04a..cff93a7 100644
--- a/freevideo_engine/agent/jobs.py
+++ b/freevideo_engine/agent/jobs.py
@@ -1655,8 +1655,9 @@ class Jobs:
role=role))
for i, item in enumerate(spec['media'].get('references', []), 1):
asset = dict(file=self.media_file(row, item, 'reference-%02d' % i, target=target), role='reference')
- if 'early_steps' in item:
- asset['early_steps'] = item['early_steps']
+ for key in ('early_steps', 'voice_only'):
+ if key in item:
+ asset[key] = item[key]
assets.append(asset)
return assets
assets = resolve()
diff --git a/freevideo_engine/agent/media.py b/freevideo_engine/agent/media.py
index a274a13..502ca4f 100644
--- a/freevideo_engine/agent/media.py
+++ b/freevideo_engine/agent/media.py
@@ -5,7 +5,7 @@ import math
from pathlib import Path
import uuid
-from ..comfy_assets import media_kind
+from ..comfy_assets import media_kind_of
FPS = 24
MAX_SAMPLES = 64
@@ -20,7 +20,7 @@ SHARP_SIDE = 384 # Sharpness is measured on a copy this size: fast, and blind t
def inspect(path):
path = _file(path)
- kind = media_kind(path.name)
+ kind = media_kind_of(path)
info = dict(path=str(path), name=path.name, kind=kind, bytes=path.stat().st_size)
if kind == 'image':
from PIL import Image
@@ -726,7 +726,7 @@ def _file(path, kind=None):
path = Path(path)
if not path.is_file():
raise ValueError('No such media file: %s' % path.name)
- if kind and media_kind(path.name) != kind:
+ if kind and media_kind_of(path) != kind:
raise ValueError('%s is not a %s file' % (path.name, kind))
return path
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index ff7bab3..5318d9f 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -138,6 +138,9 @@ def media(image=False, *, local=False, clip=False, video=False, early=False):
properties['early_steps'] = number(1, 32, integer=True, description=
'A reference video only: it guides the first pass for this many steps and is dropped afterwards, '
'including from the second pass. Omitted: the video guides every step.')
+ properties['voice_only'] = {'type': 'boolean', 'description':
+ 'A reference video used only for its voice: the picture is encoded small and at a low frame rate, '
+ 'the sound is unchanged. Not with early_steps.'}
if clip:
properties.pop('frame')
properties.pop('edit')
diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py
index 515b934..a9bc04e 100644
--- a/freevideo_engine/comfy_assets.py
+++ b/freevideo_engine/comfy_assets.py
@@ -65,6 +65,25 @@ def media_kind(filename):
raise ValueError('Choose a supported image, video or audio file')
+def media_kind_of(path):
+ """The kind of an existing file: the extension, except that a video container without a picture
+ stream but with sound (an audio-only mp4) is audio. An unreadable file keeps its extension's kind."""
+ kind = media_kind(Path(path).name)
+ if kind != 'video':
+ return kind
+ try:
+ import av
+ import av.stream
+ attached = getattr(getattr(av.stream, 'Disposition', None), 'attached_pic', 0)
+ with av.open(str(path)) as container:
+ if (container.streams.audio
+ and all(attached and stream.disposition & attached for stream in container.streams.video)):
+ return 'audio'
+ except Exception:
+ pass
+ return kind
+
+
def resolve_assets(serialized, input_directory):
serialized = optional_text(serialized, '[]')
if not isinstance(serialized, str) or len(serialized) > 128 * 1024:
@@ -75,7 +94,7 @@ def resolve_assets(serialized, input_directory):
root = Path(input_directory).resolve()
result = {}
for row in rows:
- if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'keep_source_audio', 'depth',
+ if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'voice_only', 'keep_source_audio', 'depth',
'use', 'range', 'segment'}:
raise ValueError('Invalid media item')
if 'depth' in row:
@@ -105,7 +124,7 @@ def resolve_assets(serialized, input_directory):
raise ValueError('Media link points outside ComfyUI input') from None
if not path.is_file():
raise ValueError('Upload or select the missing media file: ' + name)
- kind = media_kind(name)
+ kind = media_kind_of(path)
from .original_audio import fields
audio_fields = fields(dict(row, kind=kind))
if role in ('first', 'last'):
@@ -136,6 +155,11 @@ def resolve_assets(serialized, input_directory):
validate_guide(dict(row, kind=kind))
if row['guide']:
reference['guide'] = True
+ if 'voice_only' in row:
+ from .media_request import validate_voice_only
+ validate_voice_only(dict(row, kind=kind))
+ if row['voice_only']:
+ reference['voice_only'] = True
if 'keep_source_audio' in row:
from .media_request import validate_keep_source_audio
validate_keep_source_audio(dict(row, kind=kind), path)
diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.py
index 2c7255b..2e34f3c 100644
--- a/freevideo_engine/media_encoding.py
+++ b/freevideo_engine/media_encoding.py
@@ -14,6 +14,7 @@ from pathlib import Path
REFERENCE_FRAMES = 360 # 15 s at 24 fps, the longest H3 generation
+VOICE_ONLY_CANVAS = {'width': 256, 'height': 144} # a clip kept only for its voice is encoded this small
def reference_frames(canvas):
@@ -178,6 +179,8 @@ def prepare(media, canvas, directory):
ref['early_steps'] = row['early_steps']
if row.get('guide'):
ref['guide'] = True
+ if row.get('voice_only'):
+ ref['voice_only'] = True
numbers[kind] += 1
longer, length, used = False, None, limit / 24.
target = directory / ('reference-%02d.npy' % index)
@@ -195,7 +198,8 @@ def prepare(media, canvas, directory):
if not container.streams.video:
raise ValueError('Reference video has no video stream')
stream = container.streams.video[0]
- width, height = reference_size(stream.width, stream.height, canvas)
+ voice_only = bool(row.get('voice_only'))
+ width, height = reference_size(stream.width, stream.height, VOICE_ONLY_CANVAS if voice_only else canvas)
length = clip_seconds(container, stream)
pixels = np.lib.format.open_memmap(target, mode='w+', dtype=np.uint8, shape=(limit, height, width, 3))
origin = None
@@ -220,12 +224,23 @@ def prepare(media, canvas, directory):
count += 1
previous = image
del previous
+ step = 1
+ if voice_only:
+ # Every third frame (8 fps), or every second (12 fps) when that would leave too few frames.
+ step = next((n for n in (3, 2) if count // n >= 22), 1)
+ kept = np.array(pixels[:count:step])
+ del pixels
+ pixels, count = kept, len(kept)
count = count - (count - 5) % 17
if count < 22:
raise ValueError('The reference video is too short; it needs to be at least about 1 s long.')
- pixels.flush()
- ref.update(pixels=str(target), frames=count, normalized_fps=24, width=width, height=height, crop_mode='video_24fps')
- used = count / 24.
+ if voice_only:
+ np.save(target, pixels[:count], allow_pickle=False)
+ else:
+ pixels.flush()
+ ref.update(pixels=str(target), frames=count, normalized_fps=24 // step, width=width, height=height,
+ crop_mode='voice_%dfps' % (24 // step) if voice_only else 'video_24fps')
+ used = count * step / 24.
# The clip's own sound is a reference too, unless the request turned it off.
soundtrack, longer_audio, _ = (None, False, None) if row.get('sound') is False or row.get('guide') else \
_audio(path, directory / ('reference-%02d-audio.npy' % index), limit / 24.)
@@ -233,7 +248,7 @@ def prepare(media, canvas, directory):
if soundtrack:
ref['audio'] = soundtrack
ref_items.append({'type': 'audio'})
- selected = list(range(0, count, 12))
+ selected = list(range(0, count, 12 // step))
sampled = torch.from_numpy(np.array(pixels[selected])).float().div_(255)
if not row.get('guide'):
# A guide only supplies motion latents; it is not described to the
diff --git a/freevideo_engine/media_request.py b/freevideo_engine/media_request.py
index 12eda47..4bc1dd0 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', 'keep_source_audio', 'use', 'range', 'segment'} if field == 'references'
+ allowed = ({'path', 'kind', 'early_steps', 'sound', 'guide', 'voice_only', 'keep_source_audio', 'use', 'range', 'segment'} if field == 'references'
else {'path', 'strength', 'alpha'})
if set(entry) - allowed:
raise ValueError('Unknown ' + field + ' fields')
@@ -77,6 +77,10 @@ def read(path):
# keep exactly the same rows and cache key as before.
if entry['guide']:
row['guide'] = True
+ if 'voice_only' in entry:
+ validate_voice_only(entry)
+ if entry['voice_only']:
+ row['voice_only'] = True
if 'keep_source_audio' in entry:
validate_keep_source_audio(entry, row['path'])
if entry['keep_source_audio']:
@@ -149,6 +153,16 @@ def validate_guide(row):
raise ValueError('A guide clip cannot use early_steps')
+def validate_voice_only(row):
+ """A voice-only video supplies its sound; its picture is kept small and slow because only the voice is wanted."""
+ if row.get('kind') != 'video':
+ raise ValueError('voice_only is only allowed on video references')
+ if type(row['voice_only']) is not bool:
+ raise ValueError('Video reference voice_only must be true or false')
+ if row['voice_only'] and (row.get('guide') or row.get('sound') is False or 'early_steps' in row):
+ raise ValueError('A voice-only clip cannot be a guide, silent or 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: