docs(comfyui): bind director replacement reference batch142

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-11-01 10:50:03 +08:00
co-authored by multica-agent
parent 4d8b87f040
commit ac8ecd6812
107 changed files with 138697 additions and 1 deletions
@@ -0,0 +1,6 @@
tree 4880aaab394a32188aafe603caffb17c870acb10
parent fcfa42394d6347b4f04295041afdd7d92ba78c12
author yolain <yolain@163.com> 1786122945 +0800
committer yolain <yolain@163.com> 1786122945 +0800
fix: task segments were deleted along with video segments
@@ -0,0 +1,2 @@
From https://github.com/yolain/ComfyUI-Easy-Media
* branch 1254e0e0afa9afee268027b9540fdc91c888ebc5 -> FETCH_HEAD
@@ -0,0 +1,5 @@
{
"object": "1254e0e0afa9afee268027b9540fdc91c888ebc5",
"commit": "1254e0e0afa9afee268027b9540fdc91c888ebc5",
"tag": "1254e0e0afa9afee268027b9540fdc91c888ebc5"
}
@@ -0,0 +1,6 @@
tree 4880aaab394a32188aafe603caffb17c870acb10
parent fcfa42394d6347b4f04295041afdd7d92ba78c12
author yolain <yolain@163.com> 1786122945 +0800
committer yolain <yolain@163.com> 1786122945 +0800
fix: task segments were deleted along with video segments
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,581 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Check, Columns2, Download, FilePlay, Pause, Play, Settings2, Volume2, VolumeX } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Slider } from '@/components/ui/slider'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { useCanvasScale } from '@/hooks/use-canvas-scale'
import type { ReactWidgetProps } from '@/lib/create-react-widget'
import { LocaleContext, useT } from '@/lib/i18n'
import { cn } from '@/lib/utils'
import type { ComfyApp } from '@comfyorg/comfyui-frontend-types'
type CompareMode = 'source' | 'compare' | 'output'
export interface CompareVideoSettings {
save_output: boolean
filename_prefix: string
}
const DEFAULT_COMPARE_VIDEO_SETTINGS: CompareVideoSettings = {
save_output: false,
filename_prefix: 'ComfyUI',
}
export interface CompareVideoResult {
filename: string
subfolder?: string
type?: 'input' | 'output' | 'temp'
}
export interface CompareVideoPayload {
source?: CompareVideoResult | null
output?: CompareVideoResult | null
fps?: number | null
frame_count?: number | null
duration?: number | null
}
interface CompareVideoInnerProps {
app: ComfyApp
node: CompareVideoNode
settings: CompareVideoSettings
onSettingsChange: (settings: CompareVideoSettings) => void
}
type ExecutedHandler = (output: unknown) => void
type CompareVideoEventCallback = (event: CustomEvent<unknown>) => void
interface CompareVideoEventApi {
addEventListener?: (type: string, callback: CompareVideoEventCallback) => void
removeEventListener?: (type: string, callback: CompareVideoEventCallback) => void
addCustomEventListener?: (type: string, callback: CompareVideoEventCallback) => void
removeCustomEventListener?: (type: string, callback: CompareVideoEventCallback) => void
}
interface CompareVideoNode {
id?: string | number
onExecuted?: ExecutedHandler
__easyMediaCompareVideos?: CompareVideoPayload | null
__easyMediaSyncPlay?: () => void
}
function resultToUrl(result: CompareVideoResult | null | undefined): string | null {
if (!result?.filename) return null
const type = result.type ?? 'temp'
const subfolder = result.subfolder ?? ''
return `/view?filename=${encodeURIComponent(result.filename)}&type=${encodeURIComponent(type)}&subfolder=${encodeURIComponent(subfolder)}`
}
function normalizeCompareVideoPayload(value: unknown): CompareVideoPayload | null {
if (Array.isArray(value)) {
for (const item of value) {
const payload = normalizeCompareVideoPayload(item)
if (payload) return payload
}
return null
}
if (!value || typeof value !== 'object') return null
return value as CompareVideoPayload
}
function normalizeCompareVideoSettings(value: unknown): CompareVideoSettings {
if (!value || typeof value !== 'object') return DEFAULT_COMPARE_VIDEO_SETTINGS
const record = value as Record<string, unknown>
return {
save_output: record.save_output === true,
filename_prefix: typeof record.filename_prefix === 'string'
? record.filename_prefix
: DEFAULT_COMPARE_VIDEO_SETTINGS.filename_prefix,
}
}
function parseCompareVideoPayload(output: unknown): CompareVideoPayload | null {
if (!output || typeof output !== 'object') return null
const record = output as Record<string, unknown>
const direct = normalizeCompareVideoPayload(record.compare_videos)
if (direct) return direct
const nestedOutput = record.output
if (nestedOutput && typeof nestedOutput === 'object') {
const nestedDirect = normalizeCompareVideoPayload((nestedOutput as Record<string, unknown>).compare_videos)
if (nestedDirect) return nestedDirect
}
const ui = record.ui
if (ui && typeof ui === 'object') {
const nested = normalizeCompareVideoPayload((ui as Record<string, unknown>).compare_videos)
if (nested) return nested
}
return null
}
function executedEventBelongsToNode(detail: unknown, node: CompareVideoNode): boolean {
if (!detail || typeof detail !== 'object') return true
const eventNode = (detail as Record<string, unknown>).node
if (eventNode === undefined || eventNode === null || node.id === undefined || node.id === null) return true
return String(eventNode) === String(node.id)
}
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return '0:00'
const minutes = Math.floor(seconds / 60)
const wholeSeconds = Math.floor(seconds % 60)
return `${minutes}:${wholeSeconds.toString().padStart(2, '0')}`
}
function seek(video: HTMLVideoElement | null, time: number) {
if (!video || !Number.isFinite(time)) return
try {
video.currentTime = time
} catch (error) {
console.error('[CompareVideoWidget] failed to seek video:', error)
}
}
export function CompareVideoWidget({ app, node, value, onChange }: Readonly<ReactWidgetProps<CompareVideoSettings>>) {
const locale = app?.ui?.settings?.settingsValues?.['Comfy.Locale']
const compareNode = node as CompareVideoNode
const settings = normalizeCompareVideoSettings(value)
return (
<LocaleContext.Provider value={locale}>
<CompareVideoWidgetInner app={app} node={compareNode} settings={settings} onSettingsChange={onChange} />
</LocaleContext.Provider>
)
}
function CompareVideoSettingsFields({
settings,
onSettingsChange,
}: Readonly<Pick<CompareVideoInnerProps, 'settings' | 'onSettingsChange'>>) {
const t = useT()
return (
<div className="flex w-64 flex-col gap-3">
<Button
type="button"
variant="ghost"
role="checkbox"
aria-checked={settings.save_output}
className="h-auto cursor-pointer justify-start gap-2 px-0 py-1 hover:bg-transparent"
onClick={() => onSettingsChange({ ...settings, save_output: !settings.save_output })}
>
<span
className={cn(
'flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border border-border',
settings.save_output && 'border-primary bg-primary text-primary-foreground',
)}
>
{settings.save_output ? <Check className="h-3 w-3" /> : null}
</span>
<span>{t('compareVideo.saveOutput')}</span>
</Button>
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
<span>{t('compareVideo.filenamePrefix')}</span>
<Input
value={settings.filename_prefix}
placeholder="ComfyUI"
aria-label={t('compareVideo.filenamePrefix')}
onChange={(event) => onSettingsChange({ ...settings, filename_prefix: event.currentTarget.value })}
/>
</label>
</div>
)
}
function CompareVideoWidgetInner({ app, node, settings, onSettingsChange }: Readonly<CompareVideoInnerProps>) {
const t = useT()
const canvasScale = useCanvasScale(app)
const sourceRef = useRef<HTMLVideoElement>(null)
const outputRef = useRef<HTMLVideoElement>(null)
const stageRef = useRef<HTMLDivElement>(null)
const [payload, setPayload] = useState<CompareVideoPayload | null>(() => node.__easyMediaCompareVideos ?? null)
const [mode, setMode] = useState<CompareMode>('compare')
const [split, setSplit] = useState(50)
const [isPointerInside, setIsPointerInside] = useState(false)
const [isPlaying, setIsPlaying] = useState(false)
const [muted, setMuted] = useState(false)
const [volume, setVolume] = useState(0.75)
const [currentTime, setCurrentTime] = useState(0)
const [metadataDuration, setMetadataDuration] = useState(0)
const sourceUrl = useMemo(() => resultToUrl(payload?.source), [payload])
const outputUrl = useMemo(() => resultToUrl(payload?.output), [payload])
const hasSource = Boolean(sourceUrl)
const hasOutput = Boolean(outputUrl)
const canCompare = hasSource && hasOutput
const duration = Math.max(payload?.duration ?? 0, metadataDuration, 0)
const visibleMode: CompareMode = canCompare ? mode : hasSource ? 'source' : 'output'
const displaySplit = canCompare
? visibleMode === 'source'
? 100
: visibleMode === 'output'
? 0
: split
: hasSource ? 100 : 0
const animateComparison = visibleMode !== 'compare' || !isPointerInside
useEffect(() => {
function applyExecutedOutput(output: unknown) {
const nextPayload = parseCompareVideoPayload(output)
if (!nextPayload) return
node.__easyMediaCompareVideos = nextPayload
setPayload(nextPayload)
setCurrentTime(0)
setIsPlaying(false)
setMetadataDuration(0)
setMode(nextPayload.source && nextPayload.output ? 'compare' : nextPayload.source ? 'source' : 'output')
}
const original = node.onExecuted as ExecutedHandler | undefined
const wrapped = function onCompareVideosExecuted(this: unknown, output: unknown) {
original?.call(this, output)
applyExecutedOutput(output)
}
node.onExecuted = wrapped
const api = app.api as CompareVideoEventApi | undefined
const handleExecuted: CompareVideoEventCallback = (event) => {
if (!executedEventBelongsToNode(event.detail, node)) return
applyExecutedOutput(event.detail)
}
api?.addEventListener?.('executed', handleExecuted)
api?.addCustomEventListener?.('executed', handleExecuted)
return () => {
if (node.onExecuted === wrapped) node.onExecuted = original
api?.removeEventListener?.('executed', handleExecuted)
api?.removeCustomEventListener?.('executed', handleExecuted)
}
}, [app.api, node])
useEffect(() => {
if (sourceRef.current) {
sourceRef.current.muted = muted || hasOutput
sourceRef.current.volume = volume
}
if (outputRef.current) {
outputRef.current.muted = muted
outputRef.current.volume = volume
}
}, [hasOutput, muted, volume])
useEffect(() => {
if (!canCompare && hasSource) setMode('source')
if (!canCompare && hasOutput) setMode('output')
}, [canCompare, hasOutput, hasSource])
const syncVideos = useCallback((time: number) => {
seek(sourceRef.current, time)
seek(outputRef.current, time)
}, [])
const playVideos = useCallback(() => {
setIsPlaying(true)
for (const video of [sourceRef.current, outputRef.current]) {
if (!video) continue
const playResult = video.play()
if (playResult) {
playResult.catch((error: unknown) => {
console.error('[CompareVideoWidget] failed to play video:', error)
setIsPlaying(false)
})
}
}
}, [])
const pauseVideos = useCallback(() => {
setIsPlaying(false)
sourceRef.current?.pause()
outputRef.current?.pause()
}, [])
useEffect(() => {
node.__easyMediaSyncPlay = () => {
syncVideos(0)
setCurrentTime(0)
playVideos()
}
return () => {
if (node.__easyMediaSyncPlay) delete node.__easyMediaSyncPlay
}
}, [node, playVideos, syncVideos])
function updateSplitFromPointer(event: React.PointerEvent<HTMLDivElement>) {
if (!canCompare || visibleMode !== 'compare') return
const rect = stageRef.current?.getBoundingClientRect()
if (!rect) return
const scale = canvasScale > 0 ? canvasScale : 1
const localX = (event.clientX - rect.left) / scale
const width = rect.width / scale
const percent = width > 0 ? (localX / width) * 100 : 50
setSplit(Math.max(0, Math.min(100, percent)))
}
function handleTimeUpdate(event: React.SyntheticEvent<HTMLVideoElement>) {
const video = event.currentTarget
const master = outputRef.current ?? sourceRef.current
if (video !== master) return
setCurrentTime(video.currentTime)
const other = video === sourceRef.current ? outputRef.current : sourceRef.current
if (other && Math.abs(other.currentTime - video.currentTime) > 0.08) {
seek(other, video.currentTime)
}
}
function handleEnded() {
syncVideos(0)
setCurrentTime(0)
if (isPlaying) playVideos()
}
function handleSeek(value: number[]) {
const nextTime = value[0] ?? 0
setCurrentTime(nextTime)
syncVideos(nextTime)
}
function cycleMode() {
setMode((current) => current === 'compare' ? 'source' : current === 'source' ? 'output' : 'compare')
}
function downloadOutputVideo() {
if (!outputUrl || !payload?.output?.filename) return
try {
const anchor = document.createElement('a')
anchor.href = outputUrl
anchor.download = payload.output.filename
anchor.rel = 'noopener'
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
} catch (error) {
console.error('[CompareVideoWidget] failed to download output video:', error)
}
}
if (!payload || (!hasSource && !hasOutput)) {
return (
<div className="flex h-full min-h-[260px] w-full flex-col items-center justify-center gap-4 rounded border border-border bg-background p-4 text-xs text-muted-foreground">
<p>{t('compareVideo.empty')}</p>
<CompareVideoSettingsFields settings={settings} onSettingsChange={onSettingsChange} />
</div>
)
}
return (
<TooltipProvider>
<div className="group relative h-full min-h-[320px] w-full overflow-hidden rounded border border-border bg-background text-foreground">
<div
ref={stageRef}
className="relative h-full min-h-[320px] overflow-hidden bg-black"
onPointerEnter={() => setIsPointerInside(true)}
onPointerMove={(event) => {
updateSplitFromPointer(event)
}}
onPointerLeave={() => {
setIsPointerInside(false)
if (visibleMode === 'compare') setSplit(50)
}}
onPointerCancel={() => {
setIsPointerInside(false)
if (visibleMode === 'compare') setSplit(50)
}}
>
{sourceUrl ? (
<video
ref={sourceRef}
className={cn(
'absolute inset-0 h-full w-full object-contain',
!hasSource && 'invisible',
)}
src={sourceUrl}
loop
muted={muted || hasOutput}
playsInline
preload="auto"
onLoadedMetadata={(event) => {
const nextDuration = event.currentTarget.duration || 0
if (!hasOutput) setMetadataDuration(nextDuration)
}}
onTimeUpdate={handleTimeUpdate}
onEnded={handleEnded}
/>
) : null}
{outputUrl ? (
<video
ref={outputRef}
className={cn(
'absolute inset-0 h-full w-full object-contain',
!hasOutput && 'invisible',
)}
style={{
clipPath: `inset(0 0 0 ${displaySplit}%)`,
transition: animateComparison ? 'clip-path 260ms ease' : undefined,
}}
src={outputUrl}
loop
muted={muted}
playsInline
preload="auto"
onLoadedMetadata={(event) => {
const nextDuration = event.currentTarget.duration || 0
setMetadataDuration(nextDuration)
}}
onTimeUpdate={handleTimeUpdate}
onEnded={handleEnded}
/>
) : null}
{hasSource && visibleMode == 'compare' ? (
<Badge className="absolute left-3 top-2 bg-muted/60 text-foreground shadow-sm hover:bg-muted/90">
{t('compareVideo.source')}
</Badge>
) : null}
{hasOutput && visibleMode =='compare' ? (
<Badge className="absolute right-3 top-2 bg-muted/60 text-foreground shadow-sm hover:bg-muted/90">
{t('compareVideo.output')}
</Badge>
) : null}
{canCompare ? (
<div
className="pointer-events-none absolute inset-y-0 w-px bg-white shadow"
style={{
left: `${displaySplit}%`,
transition: animateComparison ? 'left 260ms ease' : undefined,
}}
/>
) : null}
{canCompare ? (
<Button
type="button"
className="absolute left-1/2 top-2 -translate-x-1/2 cursor-pointer bg-muted/60 text-foreground shadow hover:bg-muted/90"
onClick={cycleMode}
onPointerDown={(event) => event.stopPropagation()}
size="sm"
variant="secondary"
>
{visibleMode === 'source' ? <FilePlay className="h-4 w-4" /> : visibleMode === 'output' ? <FilePlay className="h-4 w-4" /> : <Columns2 className="h-4 w-4" />}
{visibleMode === 'source' ? t('compareVideo.sourceOnly') : visibleMode === 'output' ? t('compareVideo.outputOnly') : t('compareVideo.compare')}
</Button>
) : null}
</div>
<div
data-compare-video-toolbar
className="@container/compare-video-controls pointer-events-none absolute inset-x-0 bottom-0 z-10 grid translate-y-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 border-t border-border bg-background/90 px-1 opacity-0 shadow-sm backdrop-blur-sm transition-[opacity,transform] duration-300 ease-out @max-[420px]/compare-video-controls:grid-cols-[minmax(0,1fr)_auto] @max-[420px]/compare-video-controls:gap-x-1 @max-[420px]/compare-video-controls:gap-y-0 @max-[420px]/compare-video-controls:px-2 @max-[420px]/compare-video-controls:py-1 group-hover:pointer-events-auto group-hover:translate-y-0 group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:translate-y-0 group-focus-within:opacity-100"
>
<div
data-compare-video-playback
className="@max-[420px]/compare-video-controls:col-start-1 @max-[420px]/compare-video-controls:row-start-2"
>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="cursor-pointer"
onClick={isPlaying ? pauseVideos : playVideos}
aria-label={isPlaying ? t('compareVideo.pause') : t('compareVideo.play')}
>
{isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
</Button>
</TooltipTrigger>
<TooltipContent>{isPlaying ? t('compareVideo.pause') : t('compareVideo.play')}</TooltipContent>
</Tooltip>
</div>
<div
data-compare-video-seek
className="grid min-w-0 grid-cols-[auto_minmax(4rem,1fr)_auto] items-center gap-2 @max-[420px]/compare-video-controls:col-span-2 @max-[420px]/compare-video-controls:col-start-1 @max-[420px]/compare-video-controls:row-start-1 @max-[420px]/compare-video-controls:w-full @max-[420px]/compare-video-controls:px-1 @max-[420px]/compare-video-controls:py-1"
>
<span className="w-10 text-right text-[11px] tabular-nums text-muted-foreground">{formatTime(currentTime)}</span>
<div className="min-w-0">
<Slider
className="w-full"
value={[Math.min(currentTime, duration || currentTime)]}
min={0}
max={Math.max(duration, currentTime, 0.01)}
step={0.01}
onValueChange={handleSeek}
aria-label={t('compareVideo.seek')}
/>
</div>
<span className="w-10 text-[11px] tabular-nums text-muted-foreground">{formatTime(duration)}</span>
</div>
<div
data-compare-video-actions
className="flex items-center gap-2 @max-[420px]/compare-video-controls:col-start-2 @max-[420px]/compare-video-controls:row-start-2 @max-[420px]/compare-video-controls:gap-1"
>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="cursor-pointer"
onClick={() => setMuted((current) => !current)}
aria-label={muted ? t('compareVideo.unmute') : t('compareVideo.mute')}
>
{muted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
</Button>
</TooltipTrigger>
<TooltipContent>{muted ? t('compareVideo.unmute') : t('compareVideo.mute')}</TooltipContent>
</Tooltip>
<div data-compare-video-volume>
<Slider
className="w-20"
value={[volume]}
min={0}
max={1}
step={0.01}
onValueChange={(value) => setVolume(value[0] ?? 0)}
aria-label={t('compareVideo.volume')}
/>
</div>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="cursor-pointer"
aria-label={t('compareVideo.settings')}
>
<Settings2 className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-auto">
<CompareVideoSettingsFields settings={settings} onSettingsChange={onSettingsChange} />
</PopoverContent>
</Popover>
{hasOutput ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="cursor-pointer"
aria-label={t('compareVideo.downloadOutput')}
onClick={downloadOutputVideo}
>
<Download className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('compareVideo.downloadOutput')}</TooltipContent>
</Tooltip>
) : null}
</div>
</div>
</div>
</TooltipProvider>
)
}
export { parseCompareVideoPayload }
@@ -0,0 +1,5 @@
// Custom ComfyUI widget components
export { TimelineWidget } from './TimelineWidget'
export { MultiTrackWidget } from './MultiTrackWidget'
export { CompareVideoWidget } from './compareVideoWidget'
export type { CompareVideoPayload } from './compareVideoWidget'
@@ -0,0 +1,76 @@
export interface BrowserVideoMetadata {
duration: number
width: number
height: number
}
export function loadBrowserVideoMetadata(src: string): Promise<BrowserVideoMetadata> {
return new Promise((resolve, reject) => {
const video = document.createElement('video')
video.preload = 'metadata'
video.muted = true
video.onloadedmetadata = () => {
resolve({
duration: Number.isFinite(video.duration) ? video.duration : 0,
width: video.videoWidth,
height: video.videoHeight,
})
}
video.onerror = () => reject(new Error(`Unable to load video metadata: ${src}`))
video.src = src
})
}
export function captureVideoPosterFrame(src: string, sourceTime = 0.1): Promise<string> {
return new Promise((resolve, reject) => {
const video = document.createElement('video')
video.preload = 'auto'
video.muted = true
video.playsInline = true
function drawFrame() {
try {
const width = video.videoWidth
const height = video.videoHeight
if (width <= 0 || height <= 0) {
reject(new Error(`Unable to capture video frame: ${src}`))
return
}
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
if (!context) {
reject(new Error('Unable to create canvas context for video frame'))
return
}
context.drawImage(video, 0, 0, width, height)
canvas.toBlob((blob) => {
if (!blob) {
reject(new Error(`Unable to encode video frame: ${src}`))
return
}
resolve(URL.createObjectURL(blob))
}, 'image/jpeg', 0.8)
} catch (error) {
reject(error instanceof Error ? error : new Error(`Unable to capture video frame: ${src}`))
}
}
video.onloadeddata = () => {
const targetTime = Number.isFinite(video.duration)
? Math.max(0, Math.min(sourceTime, Math.max(0, video.duration - 0.001)))
: Math.max(0, sourceTime)
if (targetTime > 0) {
video.currentTime = targetTime
return
}
drawFrame()
}
video.onseeked = drawFrame
video.onerror = () => reject(new Error(`Unable to load video frame: ${src}`))
video.src = src
})
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,23 @@
tree e3ebe2cd5c0ce6ae7cf2a8da1b7e4f92f6a7efaa
parent baef7047a385f2d7bebff363c5beef76a2264d22
author smthemex <138738845+smthemex@users.noreply.github.com> 1785831922 +0800
committer GitHub <noreply@github.com> 1785831922 +0800
gpgsig -----BEGIN PGP SIGNATURE-----
wsFcBAABCAAQBQJqcaHyCRC1aQ7uu5UhlAAALHIQAC4w4PBa1cCtxmdMlSWOVYF2
WH1TF6xn7dt0ObrCmxSx9Eky3+i0yevXKhLV7jnLb765PDXzSmRek4zPkvWJgmMo
jdG6HEj53IGnzScc7LPZ+aHhE5WN9XYQk6ERThXOEnPUjv6JOkPAuAa0Vz6BHALl
+jcGUpjqRiKIrSWD3WM8m2Tzp0V4B6o57d8zH9xhy1UWlmE/EzrN69O/G877lNBi
Jd9mVQu9lSp/hOLnwuh5ZJIoG+FlLcFRYtc5WRUS3rU/nPGnClTVpGFlqYoycuEi
qWaRRhnMhhTzY7wWbyVRKnaXymyBAvVVkF6h3EUP0hF/HyGRo4nHGbIw2GKBXKl0
0wA5mTPvYSuI0f94zeAPLx1QNrDdIVC8SkDtBSvTB6IHNDkPkUjaKo+kMvQS/wAp
N8lll9D4sIauF5SnhT/u3mQfh6clMJm4RAlMyvShBQ6sGn3fxJt5xPMWDL44+6si
PnnG9coLJdO05igvtwbLR/kYXfBwscPyfif48nb/064jHhCIq7mlJxXakj+kZiXA
2+JxrQTaOKyvwhcSPieEtG89R4b6TNY/nEh4eKOEZxcCelUE94U4CrHZb0L44ueL
GKBgrxAJTM320I6BcRupzGfR57upFv25zywKcNEPxX9+qRbd3YfcEY3lddk92+yH
LbBl6EP9Hrp6N2XShS2w
=eN1K
-----END PGP SIGNATURE-----
Add files via upload
@@ -0,0 +1,2 @@
From https://github.com/smthemex/ComfyUI_UniBlockSwap
* branch a019e82c45185beb5f3a2273a6b47b9f88e001b9 -> FETCH_HEAD
@@ -0,0 +1,7 @@
{
"url": "https://api.comfy.org/nodes/uniblockswap",
"status": 200,
"time": "2026-11-01T02:39:40.670959+00:00",
"basis": "graph cnr_id for swap; exact T8 project name for aux-only node; unknown if query unavailable",
"sha256": "5736ad979814bae39eafcd0b9f753ef9972d864c6809a3ec24616ace6d0cee3c"
}
@@ -0,0 +1 @@
{"author":"","banner_url":"","category":"","created_at":"2026-07-13T07:44:20.098574Z","description":"A universal swap node that supports ComfyUI native workflow, allowing 4_6G users to experience Klein9B or other large models","downloads":19709,"github_stars":147,"icon":"","id":"uniblockswap","latest_version":{"changelog":"","createdAt":"2026-08-04T09:12:43.040793Z","dependencies":[],"deprecated":false,"downloadUrl":"","id":"6ef516c6-4c7e-4ab6-8fcb-a8a1aa84ab3e","node_id":"uniblockswap","status":"NodeVersionStatusActive","supported_accelerators":[],"supported_comfyui_frontend_version":"","supported_comfyui_version":"","supported_os":[],"tags":[],"version":"1.1.1"},"license":"{\"file\": \"LICENSE\"}","name":"ComfyUI_UniBlockSwap","publisher":{"createdAt":"2025-10-07T03:17:11.960073Z","description":"","id":"smthemex","logo":"","members":[{"user":{"name":""}}],"name":"smthemex","source_code_repo":"","status":"PublisherStatusActive","support":"","website":""},"rating":0,"repository":"https://github.com/smthemex/ComfyUI_UniBlockSwap","search_ranking":5,"status":"NodeStatusActive","supported_accelerators":[],"supported_comfyui_frontend_version":"","supported_comfyui_version":"","supported_os":[],"tags":[]}
@@ -0,0 +1,5 @@
{
"object": "a019e82c45185beb5f3a2273a6b47b9f88e001b9",
"commit": "a019e82c45185beb5f3a2273a6b47b9f88e001b9",
"tag": "a019e82c45185beb5f3a2273a6b47b9f88e001b9"
}
@@ -0,0 +1,23 @@
tree e3ebe2cd5c0ce6ae7cf2a8da1b7e4f92f6a7efaa
parent baef7047a385f2d7bebff363c5beef76a2264d22
author smthemex <138738845+smthemex@users.noreply.github.com> 1785831922 +0800
committer GitHub <noreply@github.com> 1785831922 +0800
gpgsig -----BEGIN PGP SIGNATURE-----
wsFcBAABCAAQBQJqcaHyCRC1aQ7uu5UhlAAALHIQAC4w4PBa1cCtxmdMlSWOVYF2
WH1TF6xn7dt0ObrCmxSx9Eky3+i0yevXKhLV7jnLb765PDXzSmRek4zPkvWJgmMo
jdG6HEj53IGnzScc7LPZ+aHhE5WN9XYQk6ERThXOEnPUjv6JOkPAuAa0Vz6BHALl
+jcGUpjqRiKIrSWD3WM8m2Tzp0V4B6o57d8zH9xhy1UWlmE/EzrN69O/G877lNBi
Jd9mVQu9lSp/hOLnwuh5ZJIoG+FlLcFRYtc5WRUS3rU/nPGnClTVpGFlqYoycuEi
qWaRRhnMhhTzY7wWbyVRKnaXymyBAvVVkF6h3EUP0hF/HyGRo4nHGbIw2GKBXKl0
0wA5mTPvYSuI0f94zeAPLx1QNrDdIVC8SkDtBSvTB6IHNDkPkUjaKo+kMvQS/wAp
N8lll9D4sIauF5SnhT/u3mQfh6clMJm4RAlMyvShBQ6sGn3fxJt5xPMWDL44+6si
PnnG9coLJdO05igvtwbLR/kYXfBwscPyfif48nb/064jHhCIq7mlJxXakj+kZiXA
2+JxrQTaOKyvwhcSPieEtG89R4b6TNY/nEh4eKOEZxcCelUE94U4CrHZb0L44ueL
GKBgrxAJTM320I6BcRupzGfR57upFv25zywKcNEPxX9+qRbd3YfcEY3lddk92+yH
LbBl6EP9Hrp6N2XShS2w
=eN1K
-----END PGP SIGNATURE-----
Add files via upload
@@ -0,0 +1,78 @@
{
"sha": "e3ebe2cd5c0ce6ae7cf2a8da1b7e4f92f6a7efaa",
"truncated": false,
"tree": [
{
"path": "LICENSE",
"mode": "100644",
"type": "blob",
"sha": "0e8d3f9b6e351b6249fabf1d0fbe75d4506b67f4"
},
{
"path": "README.md",
"mode": "100644",
"type": "blob",
"sha": "61ace346b573e856fa2ccb268ba4822b9b080c86"
},
{
"path": "__init__.py",
"mode": "100644",
"type": "blob",
"sha": "8f76d5ba3b275b7b2c563ec00ce4597bf60f0c02"
},
{
"path": "block_swap.py",
"mode": "100644",
"type": "blob",
"sha": "746aee539ff6a270a8385fe0aed9c59319f912ac"
},
{
"path": "example_workflows/bernini.png",
"mode": "100644",
"type": "blob",
"sha": "f93214198b3b3229ee53a6903a29410b454f2286"
},
{
"path": "example_workflows/boogu.png",
"mode": "100644",
"type": "blob",
"sha": "298bffa2653f5c74d7a5939295022c8ccde4aa95"
},
{
"path": "example_workflows/example_minimax.png",
"mode": "100644",
"type": "blob",
"sha": "2524293bf235bc8da238c00aafa5ad3e23ff6e4c"
},
{
"path": "example_workflows/klein9B.png",
"mode": "100644",
"type": "blob",
"sha": "48eda54aee031f6ef7264451719aa1cea7b24ba8"
},
{
"path": "example_workflows/krea2.png",
"mode": "100644",
"type": "blob",
"sha": "5489408e8cd4b48d85dc913b7a220d955a29aad9"
},
{
"path": "example_workflows/swap.json",
"mode": "100644",
"type": "blob",
"sha": "8708e51cb4bb4d719939a7aa8657ae5405ea0c07"
},
{
"path": "pyproject.toml",
"mode": "100644",
"type": "blob",
"sha": "8ef15a7693e649ca54a84f86b6e6e5f3a82e141e"
},
{
"path": "uniblockswap_node.py",
"mode": "100644",
"type": "blob",
"sha": "eeaae3eb7864e0722f562c02ab27cd8d5a10a259"
}
]
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 smthemex
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,3 @@
from .uniblockswap_node import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
@@ -0,0 +1,301 @@
"""
UniBlockSwap - Universal single-block swap for ComfyUI.
Safetensor blocks: freed to meta on swap, restored by vbar automatically.
GGUF blocks: freed to CPU on swap, moved to GPU when accessed.
"""
import gc
import logging
import torch
import torch.nn as nn
logger = logging.getLogger(__name__)
CONTAINER_NAMES = (
"blocks", "transformer_blocks", "double_blocks", "single_blocks",
"input_blocks", "output_blocks", "middle_block", "layers",
"double_stream_layers", "single_stream_layers",
"block",
)
def find_blocks(model):
for name in CONTAINER_NAMES:
c = getattr(model, name, None)
if isinstance(c, (nn.ModuleList, list)) and len(c) > 0 and hasattr(c[0], "forward"):
return name, c
return None, None
def _has_ggml_params(module):
"""Check if module has GGMLTensor parameters (quantized GGUF weights)."""
for p in module.parameters():
if hasattr(p, 'tensor_type'):
return True
return False
def _free_to_meta(module):
"""Free param data to meta tensor - NO CPU copy created.
The module structure is preserved. next load() restores from backup."""
for param in module.parameters(recurse=False):
param.data = torch.empty(0, device='meta')
class SwappableModuleList(nn.ModuleList):
def __init__(self, modules, compute_device, offload_device,
non_swap_count=0):
super().__init__(modules)
self.compute_device = compute_device
self.offload_device = offload_device
self.non_swap_count = non_swap_count
self.total_count = len(modules)
self._loaded_swap_idx = -1
self.container_name = ''
def _load_swap(self, local_idx):
idx = local_idx + self.non_swap_count
if local_idx == self._loaded_swap_idx:
return
if self._loaded_swap_idx >= 0:
prev = self._loaded_swap_idx + self.non_swap_count
try:
# FREE previous block GPU memory
if _has_ggml_params(self._modules[str(prev)]):
# GGUF: move quantized data to CPU (preserves GGMLTensor attributes)
self._modules[str(prev)].to(self.offload_device)
else:
# Safetensor: set to meta (vbar restores automatically)
_free_to_meta(self._modules[str(prev)])
for m in self._modules[str(prev)].modules():
for attr in ('_v', '_prefetch', '_v_signature'):
if hasattr(m, attr):
try:
delattr(m, attr)
except Exception:
pass
except Exception:
pass
# LOAD current block if GGUF
if _has_ggml_params(self._modules[str(idx)]):
self._modules[str(idx)].to(self.compute_device)
# else: safetensor - vbar handles restoration
self._loaded_swap_idx = local_idx
def offload_swap_blocks(self):
for i in range(self.non_swap_count, self.total_count):
try:
if _has_ggml_params(self._modules[str(i)]):
self._modules[str(i)].to(self.offload_device)
else:
_free_to_meta(self._modules[str(i)])
for m in self._modules[str(i)].modules():
for attr in ('_v', '_prefetch', '_v_signature'):
if hasattr(m, attr):
try:
delattr(m, attr)
except Exception:
pass
except Exception:
pass
self._loaded_swap_idx = -1
def _apply(self, fn, recurse=True):
"""Apply fn to non-swap blocks only.
CRITICAL: Prevents model.to(device_to) from moving swap block
GGMLTensors to GPU, which would cause a VRAM spike (12GB).
Safetensor swap blocks are already meta (no-op), so this only
affects GGUF paths.
nn.ModuleList._apply(recurse=False) applies fn to all _modules
entries INCLUDING swap blocks. We skip that and handle only
non_swap_count blocks manually.
"""
for i in range(self.non_swap_count):
try:
child = self._modules.get(str(i))
if child is not None:
child._apply(fn, recurse)
except Exception:
pass
return self
def __getattr__(self, name):
try:
idx = int(name)
if 0 <= idx < self.total_count:
return self.__getitem__(idx)
except (ValueError, TypeError):
pass
raise AttributeError(f"'{type(self).__name__}' has no attribute '{name}'")
def __getitem__(self, idx):
if idx >= self.non_swap_count:
self._load_swap(idx - self.non_swap_count)
return super().__getitem__(idx)
def __iter__(self):
for idx in range(self.total_count):
yield self.__getitem__(idx)
def install_block_swap(diffusion_model, compute_device, offload_device,
num_blocks=-1):
all_containers = []
for name in CONTAINER_NAMES:
c = getattr(diffusion_model, name, None)
if isinstance(c, (nn.ModuleList, list)) and len(c) > 0 and hasattr(c[0], "forward"):
all_containers.append((name, c))
if not all_containers:
return None, lambda: None, set()
first_swl = None
all_names = set()
for name, orig in all_containers:
total = len(orig)
n = num_blocks if num_blocks > 0 else total
n = max(1, min(n, total))
swl = SwappableModuleList(
orig, compute_device, offload_device,
non_swap_count=total - n,
)
swl.container_name = name
setattr(diffusion_model, name, swl)
all_names.add(name)
if first_swl is None:
first_swl = swl
logger.info("UniBlockSwap: '%s' = %d blocks, swapping %d",
name, total, n)
# For GGUF: offload swap blocks to CPU immediately.
# Safetensor blocks stay on GPU (original behavior).
for i in range(total - n, total):
blk = swl._modules[str(i)]
if _has_ggml_params(blk):
blk.to(offload_device)
orig_fwd = diffusion_model.forward
def wrapped(*args, **kwargs):
try:
return orig_fwd(*args, **kwargs)
finally:
if torch.cuda.is_available():
torch.cuda.synchronize(compute_device)
gc.collect()
torch.cuda.empty_cache()
diffusion_model.forward = wrapped
def cleanup():
diffusion_model.forward = orig_fwd
for name, orig in all_containers:
setattr(diffusion_model, name, orig)
all_swls = []
for name in CONTAINER_NAMES:
c = getattr(diffusion_model, name, None)
if hasattr(c, 'offload_swap_blocks'):
all_swls.append(c)
return first_swl, cleanup, all_names, all_swls
def find_te_containers(cond_stage_model):
results = []
seen_ids = set()
def _recurse(module, depth=0):
if depth > 20:
return
for name in CONTAINER_NAMES:
c = getattr(module, name, None)
if (isinstance(c, (nn.ModuleList, list)) and
len(c) > 0 and hasattr(c[0], "forward") and
id(c) not in seen_ids):
seen_ids.add(id(c))
results.append((name, c, module))
for child_name, child in module.named_children():
if isinstance(child, (nn.ModuleList, list)):
continue
_recurse(child, depth + 1)
_recurse(cond_stage_model)
return results
def install_te_block_swap(cond_stage_model, compute_device, offload_device,
num_blocks=-1):
containers = find_te_containers(cond_stage_model)
if not containers:
return [], lambda: None, set()
mgr_list = []
container_names = set()
parent_to_mgrs = {}
for name, orig, parent in containers:
total = len(orig)
n = num_blocks if num_blocks > 0 else total
n = max(1, min(n, total))
swl = SwappableModuleList(
orig, compute_device, offload_device,
non_swap_count=total - n,
)
swl.container_name = name
setattr(parent, name, swl)
mgr_list.append(swl)
container_names.add(name)
parent_id = id(parent)
if parent_id not in parent_to_mgrs:
parent_to_mgrs[parent_id] = (parent, parent.forward, [])
parent_to_mgrs[parent_id][2].append(swl)
logger.info("UniBlockSwapTE: '%s' (%s) = %d blocks, swapping %d",
name, type(parent).__name__, total, n)
for i in range(total - n, total):
blk = swl._modules[str(i)]
if _has_ggml_params(blk):
blk.to(offload_device)
else:
_free_to_meta(blk)
wrapped_parents = []
for parent_id, (parent, orig_fwd, parent_mgrs) in parent_to_mgrs.items():
def make_wrapped(_orig_fwd=orig_fwd, _mgrs=parent_mgrs, _cdevice=compute_device,
_root=cond_stage_model):
def wrapped(*args, **kwargs):
try:
return _orig_fwd(*args, **kwargs)
finally:
for m in _mgrs:
m.offload_swap_blocks()
backup_cleaner = getattr(_root, '_uniblockswap_backup_cleanup', None)
patcher = getattr(_root, '_patcher_ref', None)
if backup_cleaner is not None and patcher is not None:
backup_cleaner(patcher)
if torch.cuda.is_available():
torch.cuda.synchronize(_cdevice)
gc.collect()
torch.cuda.empty_cache()
return wrapped
parent.forward = make_wrapped()
wrapped_parents.append((parent, orig_fwd))
def cleanup():
for name, orig, parent in containers:
current = getattr(parent, name, None)
if hasattr(current, 'offload_swap_blocks'):
setattr(parent, name, orig)
for parent, orig_fwd in wrapped_parents:
parent.forward = orig_fwd
return mgr_list, cleanup, container_names
@@ -0,0 +1,15 @@
[project]
name = "uniblockswap"
description = "A universal swap node that supports ComfyUI native workflow, allowing 4_6G users to experience Klein9B or other large models"
version = "1.0.0"
license = {file = "LICENSE"}
[project.urls]
Repository = "https://github.com/smthemex/ComfyUI_UniBlockSwap"
# Used by Comfy Registry https://registry.comfy.org
[tool.comfy]
PublisherId = "smthemex"
DisplayName = "ComfyUI_UniBlockSwap"
Icon = ""
includes = []
@@ -0,0 +1,330 @@
import logging
import torch
import comfy.model_management as mm
import comfy.patcher_extension
import gc
from .block_swap import install_block_swap, install_te_block_swap, _free_to_meta, _has_ggml_params
logger = logging.getLogger(__name__)
def _get_diffusion_model(patcher):
if patcher is None:
return None
model_obj = getattr(patcher, "model", patcher)
diffusion = getattr(model_obj, "diffusion_model", None)
if diffusion is not None and isinstance(diffusion, torch.nn.Module):
return diffusion
if isinstance(model_obj, torch.nn.Module):
return model_obj
inner = getattr(patcher, "model", None)
if inner is not None and isinstance(inner, torch.nn.Module):
return inner
return None
def _get_cond_stage_model(clip_obj):
"""Extract the cond_stage_model from a CLIP wrapper."""
if clip_obj is None:
return None
cond_stage = getattr(clip_obj, "cond_stage_model", None)
if cond_stage is not None and isinstance(cond_stage, torch.nn.Module):
return cond_stage
return None
def _free_block_cleanup(swl):
"""Free swap block memory during ON_CLEANUP.
Safetensor: _free_to_meta (release to meta, vbar handles restore).
GGUF: to(offload_device) (quantized data to CPU, GGMLTensor preserved).
"""
for i in range(swl.non_swap_count, swl.total_count):
try:
blk = swl._modules.get(str(i))
if blk is None:
continue
if _has_ggml_params(blk):
blk.to(swl.offload_device)
else:
_free_to_meta(blk)
for m in blk.modules():
for attr in ('_v', '_prefetch', '_v_signature',
'ggml_weight', 'ggml_weight_data'):
if hasattr(m, attr):
try:
delattr(m, attr)
except Exception:
pass
except Exception:
pass
def clear_comfyui_cache_except(exclude_patcher=None):
"""Clear all models from GPU to CPU (unpatch), except exclude_patcher.
This frees VRAM used by TE/VAE/etc without touching the DIT model.
"""
cf_models = mm.loaded_models()
for pipe in cf_models:
if exclude_patcher is not None and pipe is exclude_patcher:
continue
try:
pipe.unpatch_model(device_to=torch.device("cpu"))
except Exception:
pass
mm.soft_empty_cache()
torch.cuda.empty_cache()
max_gpu_memory = torch.cuda.max_memory_allocated()
print(f"After Max GPU memory allocated: {max_gpu_memory / 1000 ** 3:.2f} GB")
class UniBlockSwap:
"""Swap blocks one-at-a-time between GPU/CPU to reduce VRAM.
Supports both safetensor and GGUF models.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"model": ("MODEL",)},
"optional": {
"num_blocks": ("INT", {
"default": -1, "min": -1, "max": 10000, "step": 1,
"tooltip": "Blocks from end to swap. -1 = all, 0 = disable",
}),
},
}
RETURN_TYPES = ("MODEL",)
RETURN_NAMES = ("model",)
FUNCTION = "apply_swap"
CATEGORY = "model/loaders"
DESCRIPTION = "Swap blocks one-at-a-time between GPU/CPU to reduce VRAM."
def apply_swap(self, model, num_blocks=-1):
if num_blocks == 0:
return (model,)
patcher = model.clone()
if hasattr(model, 'backup'):
model.backup.clear()
patcher.backup = {}
clear_comfyui_cache_except(patcher)
diffusion_model = _get_diffusion_model(patcher)
if diffusion_model is None:
logger.warning("UniBlockSwap: no diffusion model found")
return (patcher,)
compute = mm.get_torch_device()
offload = mm.unet_offload_device()
logger.info("UniBlockSwap: %s, compute=%s, offload=%s",
type(diffusion_model).__name__, compute, offload)
mgr, cleanup, _dit_swap_names, _dit_all_swls = install_block_swap(
diffusion_model, compute, offload,
num_blocks=num_blocks,
)
if mgr is None:
return (patcher,)
def _is_dit_swap_key(key):
parts = key.split(".")
for i, part in enumerate(parts):
if part in _dit_swap_names and i + 1 < len(parts):
next_part = parts[i + 1]
if next_part.lstrip("-").isdigit():
return True
return False
def _on_load(p, device_to, lowvram, force, full):
try:
mgr.offload_swap_blocks()
for key in list(p.backup.keys()):
if _is_dit_swap_key(key):
p.backup.pop(key, None)
except Exception:
pass
mm.soft_empty_cache()
gc.collect()
patcher.add_callback_with_key(
comfy.patcher_extension.CallbacksMP.ON_LOAD,
"UniBlockSwap", _on_load,
)
# Detect if this patcher is a GGUFModelPatcher (which handles GGMLTensor weights).
_is_gguf = hasattr(patcher, 'mmap_released')
_orig_patch = patcher.patch_weight_to_device
def _skip_swap_patch(key, *args, **kwargs):
if _is_dit_swap_key(key):
if _is_gguf:
# GGUF: completely skip. _load_swap manages GPU loading.
return
# Safetensor: call original, delete backup.
result = _orig_patch(key, *args, **kwargs)
if key in patcher.backup:
patcher.backup.pop(key, None)
return result
return _orig_patch(key, *args, **kwargs)
patcher.patch_weight_to_device = _skip_swap_patch
# CRITICAL: _load_list filter for GGUF to prevent load() from
# iterating over swap blocks and calling m.to(device_to) on each,
# which would load all GGUF swap blocks to GPU at once (12GB spike).
if _is_gguf:
_orig_load_list = patcher._load_list
def _filtered_load_list(*args, **kwargs):
raw = _orig_load_list(*args, **kwargs)
return [item for item in raw if not _is_dit_swap_key(item[-3])]
patcher._load_list = _filtered_load_list
def _on_dit_cleanup(p):
try:
for swl in _dit_all_swls:
_free_block_cleanup(swl)
for key in list(p.backup.keys()):
if _is_dit_swap_key(key):
p.backup.pop(key, None)
for _ in range(3):
gc.collect()
except Exception:
pass
patcher.add_callback_with_key(
comfy.patcher_extension.CallbacksMP.ON_CLEANUP,
"UniBlockSwap", _on_dit_cleanup,
)
patcher.model._uniblockswap_cleanup = cleanup
return (patcher,)
class UniBlockSwapTE:
"""Swap text encoder blocks one-at-a-time between GPU/CPU to save VRAM."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"clip": ("CLIP",)},
"optional": {
"num_blocks": ("INT", {
"default": -1, "min": -1, "max": 10000, "step": 1,
"tooltip": "Blocks from end to swap. -1 = all, 0 = disable",
}),
},
}
RETURN_TYPES = ("CLIP",)
RETURN_NAMES = ("clip",)
FUNCTION = "apply_swap"
CATEGORY = "model/loaders"
DESCRIPTION = "Swap text encoder blocks one-at-a-time between GPU/CPU to reduce VRAM."
def apply_swap(self, clip, num_blocks=-1):
if num_blocks == 0:
return (clip,)
new_clip = clip.clone()
cond_stage = _get_cond_stage_model(new_clip)
if cond_stage is None:
logger.warning("UniBlockSwapTE: no cond_stage_model found")
return (new_clip,)
new_clip.patcher.backup = {}
mm.soft_empty_cache()
torch.cuda.empty_cache()
gc.collect()
compute = new_clip.patcher.load_device
offload = new_clip.patcher.offload_device
logger.info("UniBlockSwapTE: %s, compute=%s, offload=%s",
type(cond_stage).__name__, compute, offload)
mgr_list, cleanup, container_names = install_te_block_swap(
cond_stage, compute, offload,
num_blocks=num_blocks,
)
if not mgr_list:
logger.info("UniBlockSwapTE: no block containers found in %s",
type(cond_stage).__name__)
return (new_clip,)
def _is_swap_key(key):
for mgr in mgr_list:
cname = getattr(mgr, 'container_name', '')
if not cname:
continue
parts = key.split(".")
for i, part in enumerate(parts):
if part == cname and i + 1 < len(parts):
next_part = parts[i + 1]
if next_part.lstrip("-").isdigit():
return True
return False
def _purge_swap_from_backup(p):
if len(p.backup) == 0:
return
try:
keys_to_del = [k for k in p.backup if _is_swap_key(k)]
for k in keys_to_del:
p.backup.pop(k, None)
except Exception:
pass
def _on_load(p, device_to, lowvram, force, full):
_purge_swap_from_backup(p)
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
new_clip.patcher.add_callback_with_key(
comfy.patcher_extension.CallbacksMP.ON_LOAD,
"UniBlockSwapTE", _on_load,
)
_orig_patch = new_clip.patcher.patch_weight_to_device
def _skip_swap_patch(key, *args, **kwargs):
if _is_swap_key(key):
return
return _orig_patch(key, *args, **kwargs)
new_clip.patcher.patch_weight_to_device = _skip_swap_patch
_orig_load_list = new_clip.patcher._load_list
def _filtered_load_list(*args, **kwargs):
raw = _orig_load_list(*args, **kwargs)
return [item for item in raw if not _is_swap_key(item[-3])]
new_clip.patcher._load_list = _filtered_load_list
new_clip.patcher.model._uniblockswap_te_cleanup = cleanup
def _on_cleanup(p):
try:
for mgr in mgr_list:
_free_block_cleanup(mgr)
_purge_swap_from_backup(p)
for _ in range(3):
gc.collect()
except Exception:
pass
new_clip.patcher.add_callback_with_key(
comfy.patcher_extension.CallbacksMP.ON_CLEANUP,
"UniBlockSwapTE", _on_cleanup,
)
return (new_clip,)
NODE_CLASS_MAPPINGS = {
"UniBlockSwap": UniBlockSwap,
"UniBlockSwapTE": UniBlockSwapTE,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"UniBlockSwap": "UniBlockSwap",
"UniBlockSwapTE": "UniBlockSwap TE",
}
@@ -0,0 +1,6 @@
tree d5fd2d4e0ede50a1e3cd664e7f183956b755a786
parent 1c8040bbae3e8e86b68ed8eb2f8f8450494f5ee8
author T8mars <20331866@qq.com> 1786081082 +0800
committer T8mars <20331866@qq.com> 1786081082 +0800
release 1.3.2 with media and 2MP compatibility
@@ -0,0 +1,2 @@
From https://github.com/T8mars/comfyui-minimax-h3-audio-T8
* branch 4174fd49e3e37e6787d1505749dc44a8be309209 -> FETCH_HEAD
@@ -0,0 +1,7 @@
{
"url": "https://api.comfy.org/nodes/minimax-h3-audio-t8",
"status": 200,
"time": "2026-11-01T02:39:41.064154+00:00",
"basis": "graph cnr_id for swap; exact T8 project name for aux-only node; unknown if query unavailable",
"sha256": "8012ccc5cb6e6971f1b89b98f026b1f76cb444a6a36d09ea7cf8673684e8996a"
}
@@ -0,0 +1 @@
{"author":"","banner_url":"","category":"","created_at":"2026-08-19T17:41:57.573586Z","description":"MiniMax H3 joint AV, audio refine, long-video, reference control, motion analysis, temporal restoration, and acceleration nodes for ComfyUI","downloads":16552,"github_stars":1239,"icon":"https://avatars.githubusercontent.com/u/96167788","id":"minimax-h3-audio-t8","latest_version":{"changelog":"","createdAt":"2026-10-29T08:12:10.607781Z","dependencies":[],"deprecated":false,"downloadUrl":"","id":"d02e1efe-1451-4594-9829-afa3dd6c03fc","node_id":"minimax-h3-audio-t8","status":"NodeVersionStatusFlagged","supported_accelerators":["GPU :: NVIDIA CUDA"],"supported_comfyui_frontend_version":"","supported_comfyui_version":"","supported_os":["Microsoft :: Windows"],"tags":[],"version":"1.103.0"},"license":"{\"file\": \"LICENSE\"}","name":"MiniMax H3 Audio T8","publisher":{"createdAt":"2025-10-03T10:03:16.947798Z","description":"","id":"t8star","logo":"","members":[{"user":{"name":"T8star-Aix"}}],"name":"T8star-Aix","source_code_repo":"","status":"PublisherStatusActive","support":"","website":""},"rating":0,"repository":"https://github.com/T8mars/comfyui-minimax-h3-audio-T8","search_ranking":5,"status":"NodeStatusActive","supported_accelerators":["GPU :: NVIDIA CUDA"],"supported_comfyui_frontend_version":"","supported_comfyui_version":"","supported_os":["Microsoft :: Windows"],"tags":[]}
@@ -0,0 +1,5 @@
{
"object": "4174fd49e3e37e6787d1505749dc44a8be309209",
"commit": "4174fd49e3e37e6787d1505749dc44a8be309209",
"tag": "4174fd49e3e37e6787d1505749dc44a8be309209"
}
@@ -0,0 +1,6 @@
tree d5fd2d4e0ede50a1e3cd664e7f183956b755a786
parent 1c8040bbae3e8e86b68ed8eb2f8f8450494f5ee8
author T8mars <20331866@qq.com> 1786081082 +0800
committer T8mars <20331866@qq.com> 1786081082 +0800
release 1.3.2 with media and 2MP compatibility
@@ -0,0 +1,306 @@
{
"sha": "d5fd2d4e0ede50a1e3cd664e7f183956b755a786",
"truncated": false,
"tree": [
{
"path": ".gitattributes",
"mode": "100644",
"type": "blob",
"sha": "70c43eeafef64cdf2dc1ed1a266093c37f22623a"
},
{
"path": ".gitignore",
"mode": "100644",
"type": "blob",
"sha": "dde623cc1bdd69c79912105249b45162d271f33d"
},
{
"path": "LICENSE",
"mode": "100644",
"type": "blob",
"sha": "5b2100407d0dde97bc9bdb20f3c3f73d6adf2b6f"
},
{
"path": "README.md",
"mode": "100644",
"type": "blob",
"sha": "d2ba95fa4ba92b808dfc25c1d006aa758d3c4cd9"
},
{
"path": "__init__.py",
"mode": "100644",
"type": "blob",
"sha": "42e2bb57b4312c972905187fa8b51eb7f1f04713"
},
{
"path": "audio_ops.py",
"mode": "100644",
"type": "blob",
"sha": "d27e0d729439a73ccee50758b90add19e8cbd98f"
},
{
"path": "conditioning.py",
"mode": "100644",
"type": "blob",
"sha": "d797fe54646629e114218b9b5948e8cbe6d4bd44"
},
{
"path": "core.py",
"mode": "100644",
"type": "blob",
"sha": "b3f6c8690094c89f12f50e0ef18be38a69063f5a"
},
{
"path": "docs/README_ComfyUI.md",
"mode": "100644",
"type": "blob",
"sha": "b8f90b62e6912230dd13f4525bda7d717a3c37bf"
},
{
"path": "docs/VERIFICATION_REPORT.md",
"mode": "100644",
"type": "blob",
"sha": "4b71b1bd4fe15ebffebad49d0731c036476fa8f6"
},
{
"path": "docs/VRAM_VALIDATION.md",
"mode": "100644",
"type": "blob",
"sha": "32c57c310139378a6554b0b234552d53ecc5adaf"
},
{
"path": "examples/H3_Turbo_Stable_4V4A\uff08AV\u54044\u6b65\uff09.json",
"mode": "100644",
"type": "blob",
"sha": "c146c8e476e72d4f7772fe7448d192b0bbe7efa2"
},
{
"path": "examples/README.md",
"mode": "100644",
"type": "blob",
"sha": "db628ba74f07709d77ba37e964185492dc360c96"
},
{
"path": "examples/audio_lock_api.json",
"mode": "100644",
"type": "blob",
"sha": "6f57df41d1a1f6973dcc0a098a8adf6be2a6a60b"
},
{
"path": "examples/dual_clock_4step_api.json",
"mode": "100644",
"type": "blob",
"sha": "526c1b89fab7f535073b6263fda92ff27b7755b9"
},
{
"path": "examples/multirate_exp_api.json",
"mode": "100644",
"type": "blob",
"sha": "834db96ae993085b49bccff9e80ff216f1174be3"
},
{
"path": "examples/still_image_edit_api.json",
"mode": "100644",
"type": "blob",
"sha": "ff7821dbd9efaaf8f331ff6939ebbc26e90813ba"
},
{
"path": "examples/workflows/H3_Still_Edit_22Frames_EXP.json",
"mode": "100644",
"type": "blob",
"sha": "74348403a55f9d1244cde3f1226484c5d9802bff"
},
{
"path": "examples/workflows/H3_Turbo_EXP_4V10A.json",
"mode": "100644",
"type": "blob",
"sha": "8465692272e7ba0653e8f3f29f741ed2424987c2"
},
{
"path": "examples/workflows/H3_Turbo_EXP_4V8A.json",
"mode": "100644",
"type": "blob",
"sha": "84b4acc9adc37bc9772c520e749d0b888b05ab93"
},
{
"path": "examples/workflows/H3_Turbo_Stable_4V4A.json",
"mode": "100644",
"type": "blob",
"sha": "b737f944bc9c854248e1ae0a33bab44e68f003f5"
},
{
"path": "examples/\u53cc\u65f6\u949f\u91c7\u6837\u6b65\u6570\u5206\u79bbExp.json",
"mode": "100644",
"type": "blob",
"sha": "404b701a4aaace9af5810e7ca6df3c60c9647e02"
},
{
"path": "features.json",
"mode": "100644",
"type": "blob",
"sha": "0c4f2d3edce85a417d4c244a12ed48fed027f431"
},
{
"path": "meta.json",
"mode": "100644",
"type": "blob",
"sha": "714ed58f7de0d5b006f7148a62463892dcfff590"
},
{
"path": "nodes.py",
"mode": "100644",
"type": "blob",
"sha": "59465edfd0bddcd33c9122e44ccf3d4d76457c39"
},
{
"path": "nodes_multirate_exp.py",
"mode": "100644",
"type": "blob",
"sha": "613034e2008d1de0687541fa8ec363788f81a136"
},
{
"path": "nodes_still_exp.py",
"mode": "100644",
"type": "blob",
"sha": "13e8fcc55e4c8a943ec21589bf4619c6de0663e1"
},
{
"path": "preflight.py",
"mode": "100644",
"type": "blob",
"sha": "a07eb27f1f30af0a968b46fde457015c541e922a"
},
{
"path": "prompt_tags.py",
"mode": "100644",
"type": "blob",
"sha": "8b7870fc00dd89cffa205c5a9715e2deaa480f47"
},
{
"path": "pyproject.toml",
"mode": "100644",
"type": "blob",
"sha": "8131549331b874602ecf0af3607e6600dc2aebad"
},
{
"path": "requirements.txt",
"mode": "100644",
"type": "blob",
"sha": "9b9d2e5198c9aed35cc63c7442be12f4315436d2"
},
{
"path": "sampling.py",
"mode": "100644",
"type": "blob",
"sha": "38790e83153826e7b568525081e9c741aef3a497"
},
{
"path": "sampling_multirate_exp.py",
"mode": "100644",
"type": "blob",
"sha": "df623d8dfec385d12b21fc3bd459b248e488ec07"
},
{
"path": "still_image.py",
"mode": "100644",
"type": "blob",
"sha": "1b42532529d2b75a53acb8dc30462a9710eb7df2"
},
{
"path": "tests/conftest.py",
"mode": "100644",
"type": "blob",
"sha": "cf89a6232276f1f7f10a8016e8499c9217824f74"
},
{
"path": "tests/helpers.py",
"mode": "100644",
"type": "blob",
"sha": "c8f8d1f0d9cfaf475101730d438beaaba935f0c4"
},
{
"path": "tests/test_audio_ops.py",
"mode": "100644",
"type": "blob",
"sha": "12913fec128b3c0a7f26f1aec6ea61332762ee18"
},
{
"path": "tests/test_conditioning.py",
"mode": "100644",
"type": "blob",
"sha": "56ffdffbf62f33905818d3fd5805bde747e2ecc5"
},
{
"path": "tests/test_core.py",
"mode": "100644",
"type": "blob",
"sha": "fb1bacbad761814eaa78261eafb450b705335fc3"
},
{
"path": "tests/test_preflight_and_registration.py",
"mode": "100644",
"type": "blob",
"sha": "8c0b4af563d1516ec91829c88a8adf3513508184"
},
{
"path": "tests/test_prompt_tags.py",
"mode": "100644",
"type": "blob",
"sha": "004f3731f76f979b0329de0ee440c00bfb6ce4fd"
},
{
"path": "tests/test_sampling.py",
"mode": "100644",
"type": "blob",
"sha": "79d77016680b31a1ce97efd2f8dc0c429e70c63c"
},
{
"path": "tests/test_sampling_multirate_exp.py",
"mode": "100644",
"type": "blob",
"sha": "8db0ca02f837f547f3198dc1b2bfe6f98e15c35a"
},
{
"path": "tests/test_still_image.py",
"mode": "100644",
"type": "blob",
"sha": "ab54266b428a4d4aa6c15934c63b39ace9fbeb0a"
},
{
"path": "tests/test_timing.py",
"mode": "100644",
"type": "blob",
"sha": "ba0f330623ead2105e5fa397b2a7217a44daad8a"
},
{
"path": "tests/test_vram_validation.py",
"mode": "100644",
"type": "blob",
"sha": "caf0278c549c5a2b87dca6d42b768cd09925434b"
},
{
"path": "timing.py",
"mode": "100644",
"type": "blob",
"sha": "f32a9e228fb96dae7be62e94b5c7c38984197d8e"
},
{
"path": "tools/convert_minimax_h3_lora_for_comfyui.py",
"mode": "100644",
"type": "blob",
"sha": "877686fb3442c152346615e11c711b03a3416365"
},
{
"path": "tools/validate_h3_vram.py",
"mode": "100644",
"type": "blob",
"sha": "2c766bf8cd9f7661ade99c02ea8807eca5607295"
},
{
"path": "web/task_type_labels.js",
"mode": "100644",
"type": "blob",
"sha": "d17359d0cdcd6f5417fa1236d87189b1618629c4"
}
]
}
@@ -0,0 +1,13 @@
SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 MiniMax H3 Audio T8 contributors
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See <https://www.gnu.org/licenses/gpl-3.0.html> for the full
license text. The containing ComfyUI distribution also includes a copy of GPLv3.
@@ -0,0 +1,25 @@
if __package__:
from .nodes import comfy_entrypoint
else: # Allows direct test collection from a hyphenated custom-node directory.
import importlib.util
from pathlib import Path
import sys
import types
_package_name = "_minimax_h3_audio_t8_direct"
_package_root = Path(__file__).resolve().parent
_package = types.ModuleType(_package_name)
_package.__path__ = [str(_package_root)]
sys.modules.setdefault(_package_name, _package)
_spec = importlib.util.spec_from_file_location(f"{_package_name}.nodes", _package_root / "nodes.py")
_nodes = importlib.util.module_from_spec(_spec)
sys.modules[_spec.name] = _nodes
assert _spec.loader is not None
_spec.loader.exec_module(_nodes)
comfy_entrypoint = _nodes.comfy_entrypoint
WEB_DIRECTORY = "./web"
__all__ = ["comfy_entrypoint", "WEB_DIRECTORY"]
@@ -0,0 +1,143 @@
from __future__ import annotations
import json
import torch
import torch.nn.functional as torch_functional
import torchaudio
from comfy_extras.nodes_audio import vae_decode_audio
from .core import encode_audio_once, nested_av_parts, replace_audio_latent, validate_audio
def inject_audio_latent(av_latent: dict, source_audio: dict, audio_vae, mode: str, strength: float):
mode = mode.lower()
if mode not in {"lock", "remix"}:
raise ValueError("Audio latent control mode must be lock or remix")
if not 0.0 <= strength <= 1.0:
raise ValueError("strength must be between 0 and 1")
encoded = encode_audio_once(audio_vae, source_audio)
denoise = 0.0 if mode == "lock" else strength
return replace_audio_latent(av_latent, encoded, denoise), source_audio
def decode_av_latent(av_latent: dict, video_vae, audio_vae):
video, audio = nested_av_parts(av_latent)
images = video_vae.decode(video)
if images.ndim == 5:
images = images.reshape(-1, *images.shape[-3:])
decoded_audio = vae_decode_audio(audio_vae, {"samples": audio})
video_latent = {key: value for key, value in av_latent.items() if key not in {"samples", "noise_mask"}}
audio_latent = video_latent.copy()
video_latent["samples"] = video
audio_latent["samples"] = audio
masks = av_latent.get("noise_mask")
if getattr(masks, "is_nested", False):
video_mask, audio_mask = masks.unbind()
video_latent["noise_mask"] = video_mask
audio_latent["noise_mask"] = audio_mask
return images, decoded_audio, video_latent, audio_latent
def _resample(waveform: torch.Tensor, source_rate: int, target_rate: int) -> torch.Tensor:
if source_rate == target_rate:
return waveform
return torchaudio.functional.resample(waveform, source_rate, target_rate)
def _match_channels(waveform: torch.Tensor, target_channels: int) -> torch.Tensor:
channels = waveform.shape[1]
if channels == target_channels:
return waveform
if channels == 1:
return waveform.expand(-1, target_channels, -1)
if target_channels == 1:
return waveform.mean(dim=1, keepdim=True)
# For uncommon multichannel inputs, make a deterministic stereo-compatible downmix.
mono = waveform.mean(dim=1, keepdim=True)
return mono.expand(-1, target_channels, -1)
def mix_audio(
source_audio: dict,
generated_audio: dict,
source_gain_db: float = 0.0,
generated_gain_db: float = -6.0,
duck_generated: float = 0.5,
output_sample_rate: str = "source",
peak_limit_dbfs: float = -1.0,
):
source, source_rate = validate_audio(source_audio, "source_audio")
generated, generated_rate = validate_audio(generated_audio, "generated_audio")
if output_sample_rate == "source":
target_rate = source_rate
elif output_sample_rate == "generated":
target_rate = generated_rate
else:
target_rate = int(output_sample_rate)
source = _resample(source, source_rate, target_rate)
generated = _resample(generated, generated_rate, target_rate)
target_channels = max(source.shape[1], generated.shape[1])
source = _match_channels(source, target_channels)
generated = _match_channels(generated, target_channels)
target_samples = max(source.shape[-1], generated.shape[-1])
source = torch_functional.pad(source, (0, target_samples - source.shape[-1]))
generated = torch_functional.pad(generated, (0, target_samples - generated.shape[-1]))
source = source * (10.0 ** (source_gain_db / 20.0))
generated = generated * (10.0 ** (generated_gain_db / 20.0))
if duck_generated > 0:
envelope = source.abs().mean(dim=1, keepdim=True)
window = max(1, round(target_rate * 0.02))
envelope = torch_functional.avg_pool1d(envelope, window, stride=1, padding=window // 2)
envelope = envelope[..., :target_samples]
activity = (envelope / 0.05).clamp(0.0, 1.0)
generated = generated * (1.0 - float(duck_generated) * activity)
mixed = source + generated
limit = 10.0 ** (peak_limit_dbfs / 20.0)
peak = mixed.abs().amax(dim=(1, 2), keepdim=True).clamp_min(1e-8)
scale = torch.minimum(torch.ones_like(peak), torch.full_like(peak, limit) / peak)
mixed = mixed * scale
return {"waveform": mixed, "sample_rate": target_rate}
def trim_av_output(frames: torch.Tensor, start_seconds: float, duration_seconds: float, audio=None, fps: float = 24.0):
if frames.ndim != 4:
raise ValueError(f"frames must be IMAGE [N,H,W,C], got {tuple(frames.shape)}")
if start_seconds < 0 or duration_seconds <= 0 or fps <= 0:
raise ValueError("trim start must be nonnegative; duration and fps must be positive")
start_frame = round(start_seconds * fps)
frame_count = max(1, round(duration_seconds * fps))
end_frame = start_frame + frame_count
if end_frame > frames.shape[0]:
raise ValueError(
f"Requested output frames [{start_frame}:{end_frame}] exceed decoded frame count {frames.shape[0]}"
)
trimmed_frames = frames[start_frame:end_frame]
trimmed_audio = None
if audio is not None:
waveform, sample_rate = validate_audio(audio)
start_sample = round(start_seconds * sample_rate)
sample_count = round(duration_seconds * sample_rate)
sliced = waveform[..., start_sample : start_sample + sample_count]
if sliced.shape[-1] < sample_count:
sliced = torch_functional.pad(sliced, (0, sample_count - sliced.shape[-1]))
trimmed_audio = {"waveform": sliced, "sample_rate": sample_rate}
report = json.dumps(
{
"start_seconds": start_seconds,
"requested_duration_seconds": duration_seconds,
"fps": fps,
"start_frame": start_frame,
"frame_count": frame_count,
"actual_video_duration_seconds": frame_count / fps,
},
ensure_ascii=False,
indent=2,
)
return trimmed_frames, trimmed_audio, report
@@ -0,0 +1,339 @@
from __future__ import annotations
import inspect
import math
import torch
import node_helpers
from comfy.ldm.minimax.model import PackedLayout
from comfy.model_base import MiniMaxH3 as MiniMaxH3BaseModel
from .core import (
CANVAS_MULTIPLE,
FPS,
MAX_PIXELS,
REF_IMAGE_SHORT_EDGE,
adapt_canvas,
align_frame_count_down,
empty_av_latent,
encode_audio_once,
fit_audio_latent,
nested_av_parts,
replace_audio_latent,
resize_image,
sorted_autogrow_items,
sorted_autogrow_values,
)
from .prompt_tags import media_map_json, prepare_prompt
HYBRID_KEYFRAME_SENTINEL = "t8_keyframe_latent"
def assert_hybrid_layout_contract() -> None:
"""Fail loudly if upstream starts packing our sentinel as a real reference.
Current ComfyUI replaces keyframe cond latents with the ref latent list when
both payloads are present. The sentinel makes that latent list start with the
keyframes while PackedLayout intentionally ignores its unknown ref kind.
"""
extra_conds_source = inspect.getsource(MiniMaxH3BaseModel.extra_conds)
required_contract = 'payload["cond_video_latents"] = [r["latent"] for r in refs if "latent" in r]'
if required_contract not in extra_conds_source:
raise RuntimeError(
"This ComfyUI build changed MiniMax H3 ref/keyframe latent assembly; "
"the T8 Hybrid path is disabled until its ordering can be revalidated."
)
keyframe = {"resolved_frame_index": 0, "latent": torch.zeros(1)}
baseline = PackedLayout(1, 2, 2, 2, 1, keyframes=[keyframe], frame_count=5)
hybrid = PackedLayout(
1,
2,
2,
2,
1,
keyframes=[keyframe],
refs=[{"kind": HYBRID_KEYFRAME_SENTINEL, "latent": torch.zeros(1)}],
frame_count=5,
)
if baseline.segments != hybrid.segments or baseline.seq_len != hybrid.seq_len:
raise RuntimeError(
"This ComfyUI build changed MiniMax H3 PackedLayout reference handling; "
"the T8 exact-keyframe + reference compatibility path is disabled to prevent corrupt conditioning."
)
def resolve_task_type(task_type: str, first_frame, last_frame, has_refs: bool) -> str:
first = first_frame is not None
last = last_frame is not None
requested = (task_type or "auto").lower()
if requested == "auto":
if has_refs and (first or last):
return "hybrid"
if has_refs:
return "ref2va"
if first and last:
return "fl2va"
if first:
return "i2va"
if last:
return "l2va"
return "t2va"
requirements = {
"t2va": (False, False, False),
"i2va": (True, False, False),
"fl2va": (True, True, False),
"l2va": (False, True, False),
"ref2va": (False, False, True),
"hybrid": (None, None, True),
}
if requested not in requirements:
raise ValueError(f"Unknown MiniMax H3 task type: {task_type}")
need_first, need_last, need_refs = requirements[requested]
if need_first is not None and first != need_first:
raise ValueError(f"{requested.upper()} first_frame connection does not match the selected task")
if need_last is not None and last != need_last:
raise ValueError(f"{requested.upper()} last_frame connection does not match the selected task")
if need_refs and not has_refs:
raise ValueError(f"{requested.upper()} requires at least one reference media input")
if requested == "hybrid" and not (first or last):
raise ValueError("HYBRID requires first_frame and/or last_frame")
if requested not in {"ref2va", "hybrid"} and has_refs:
raise ValueError(f"{requested.upper()} cannot include reference media; use Auto or Hybrid")
return requested
def _resize_reference_image(image, width: int, height: int, ref_image_size: str):
h, w = int(image.shape[1]), int(image.shape[2])
if ref_image_size == "match":
scale = min(1.0, math.sqrt((width * height) / (w * h)))
else:
scale = min(1.0, REF_IMAGE_SHORT_EDGE / min(w, h))
target_width = max(CANVAS_MULTIPLE, round(w * scale / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
target_height = max(CANVAS_MULTIPLE, round(h * scale / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
return resize_image(image[:1], target_width, target_height), target_width, target_height
def _encode_reference_audio(audio_vae, audio: dict):
latent = encode_audio_once(audio_vae, audio)
return latent, int(latent.shape[-1])
def build_conditioning(
clip,
video_vae,
audio_vae,
prompt: str,
width: int,
height: int,
length: int,
task_type: str = "auto",
audio_mode: str = "lock_source",
audio_denoise_strength: float = 0.35,
add_source_as_reference: bool = True,
prompt_primary_audio_ordinal: int = 1,
strict_prompt_tags: bool = True,
ref_image_size: str = "match",
reference_video_policy: str = "official_2_to_15s",
drive_audio=None,
final_audio=None,
first_frame=None,
last_frame=None,
ref_images=None,
ref_videos=None,
ref_video_audios=None,
ref_audios=None,
):
if width % 32 or height % 32:
raise ValueError("MiniMax H3 width and height must be divisible by 32")
if width * height > MAX_PIXELS:
raise ValueError(
f"Requested canvas has {width * height:,} pixels and exceeds the configured "
f"MiniMax H3 2.0MP cap of {MAX_PIXELS:,} pixels (1920x1088); reduce width/height"
)
if not 0.0 <= audio_denoise_strength <= 1.0:
raise ValueError("audio_denoise_strength must be between 0 and 1")
ref_image_values = sorted_autogrow_values(ref_images)
ref_video_entries = sorted_autogrow_items(ref_videos)
ref_video_values = [value for _, value in ref_video_entries]
ref_audio_values = sorted_autogrow_values(ref_audios)
ref_video_audio_by_ordinal = dict(sorted_autogrow_items(ref_video_audios))
if len(ref_image_values) > 9 or len(ref_video_values) > 3 or len(ref_audio_values) > 3:
raise ValueError("MiniMax H3 reference limits are 9 pictures, 3 videos, and 3 standalone audios")
video_ordinals = {ordinal for ordinal, _ in ref_video_entries}
orphan_soundtracks = sorted(set(ref_video_audio_by_ordinal) - video_ordinals)
if orphan_soundtracks:
raise ValueError(
"Reference-video soundtrack(s) have no same-numbered video: "
+ ", ".join(map(str, orphan_soundtracks))
)
mode = audio_mode.lower()
if mode not in {"native", "reference_only", "lock_source", "remix_source"}:
raise ValueError(f"Unknown audio mode: {audio_mode}")
if mode != "native" and drive_audio is None:
raise ValueError(f"Audio mode {audio_mode} requires drive_audio")
if drive_audio is None and add_source_as_reference:
add_source_as_reference = False
latent, frame_count = empty_av_latent(width, height, length)
_, template_audio = nested_av_parts(latent)
keyframes = []
keyframe_images = []
picture_labels: list[str] = []
if first_frame is not None:
image = resize_image(first_frame[:1], width, height, "disabled")
keyframe_images.append(image)
picture_labels.append("first_frame (exact frame 0)")
keyframes.append({"resolved_frame_index": 0, "latent": video_vae.encode(image)})
if last_frame is not None:
image = resize_image(last_frame[:1], width, height, "center")
keyframe_images.append(image)
picture_labels.append(f"last_frame (exact frame {frame_count - 1})")
keyframes.append({"resolved_frame_index": frame_count - 1, "latent": video_vae.encode(image)})
real_ref_items: list[dict] = []
real_ref_blocks: list[dict] = []
video_labels: list[str] = []
audio_labels: list[str] = []
for index, image in enumerate(ref_image_values, 1):
resized, ref_width, ref_height = _resize_reference_image(image, width, height, ref_image_size)
encoded = video_vae.encode(resized)
real_ref_items.append({"type": "image", "data": resized})
real_ref_blocks.append(
{
"kind": "image",
"latent_h": ref_height // 16,
"latent_w": ref_width // 16,
"latent": encoded,
}
)
picture_labels.append(f"ref_image_{index}")
for index, (video_ordinal, frames) in enumerate(ref_video_entries, 1):
if frames.ndim != 4 or frames.shape[0] < 5:
raise ValueError(f"ref_video_{index} must contain at least 5 IMAGE frames")
input_frame_count = int(frames.shape[0])
if reference_video_policy == "official_2_to_15s" and not (2 * FPS <= input_frame_count <= 15 * FPS):
raise ValueError(
f"ref_video_{index} has {input_frame_count} frames; official guidance is 48-360 frames at 24fps"
)
source_height, source_width = int(frames.shape[1]), int(frames.shape[2])
canvas_width, canvas_height = adapt_canvas(source_width, source_height)
if source_width * source_height < canvas_width * canvas_height:
canvas_width = max(CANVAS_MULTIPLE, round(source_width / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
canvas_height = max(CANVAS_MULTIPLE, round(source_height / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
frames = resize_image(frames, canvas_width, canvas_height)
frames = frames[:frame_count]
aligned_count = align_frame_count_down(int(frames.shape[0]))
if aligned_count < 5:
raise ValueError(f"ref_video_{index} is too short after 17n+5 alignment")
frames = frames[:aligned_count]
encoded_video = video_vae.encode(frames)
soundtrack = ref_video_audio_by_ordinal.get(video_ordinal)
encoded_soundtrack, soundtrack_t = None, 0
if soundtrack is not None:
encoded_soundtrack, soundtrack_t = _encode_reference_audio(audio_vae, soundtrack)
real_ref_items.append({"type": "audio"})
audio_labels.append(f"ref_video_audio_{video_ordinal}")
sample_indices = list(range(0, frames.shape[0], FPS // 2))
real_ref_items.append(
{
"type": "video",
"data": frames[sample_indices],
"timestamps": [sample_index / FPS for sample_index in sample_indices],
}
)
real_ref_blocks.append(
{
"kind": "video_audio" if soundtrack_t else "video",
"latent_t": int(encoded_video.shape[2]),
"latent_h": canvas_height // 16,
"latent_w": canvas_width // 16,
"ref_audio_t": soundtrack_t,
"latent": encoded_video,
"audio_latent": encoded_soundtrack,
}
)
video_labels.append(f"ref_video_{video_ordinal}")
encoded_source = None
source_audio_ordinal = 0
if drive_audio is not None:
encoded_source = fit_audio_latent(encode_audio_once(audio_vae, drive_audio), template_audio)
if add_source_as_reference:
real_ref_items.append({"type": "audio"})
real_ref_blocks.append(
{
"kind": "audio",
"ref_audio_t": int(encoded_source.shape[-1]),
"audio_latent": encoded_source,
}
)
audio_labels.append("drive_audio (primary source)")
source_audio_ordinal = len(audio_labels)
for index, audio in enumerate(ref_audio_values, 1):
encoded_audio, audio_t = _encode_reference_audio(audio_vae, audio)
real_ref_items.append({"type": "audio"})
real_ref_blocks.append({"kind": "audio", "ref_audio_t": audio_t, "audio_latent": encoded_audio})
audio_labels.append(f"ref_audio_{index}")
has_refs = bool(real_ref_blocks)
resolved_task = resolve_task_type(task_type, first_frame, last_frame, has_refs)
counts = {"pictures": len(picture_labels), "videos": len(video_labels), "audios": len(audio_labels)}
conditioned_prompt, prompt_warnings = prepare_prompt(
prompt,
counts,
source_audio_ordinal=source_audio_ordinal,
prompt_primary_audio_ordinal=prompt_primary_audio_ordinal,
strict=strict_prompt_tags,
)
if keyframes and real_ref_blocks:
assert_hybrid_layout_contract()
ref_items = [{"type": "image", "data": image} for image in keyframe_images] + real_ref_items
refs = [
{"kind": HYBRID_KEYFRAME_SENTINEL, "latent": keyframe["latent"]}
for keyframe in keyframes
] + real_ref_blocks
tokens = clip.tokenize(conditioned_prompt, minimax_ref_items=ref_items)
elif real_ref_blocks:
refs = real_ref_blocks
tokens = clip.tokenize(conditioned_prompt, minimax_ref_items=real_ref_items)
else:
refs = []
tokens = clip.tokenize(conditioned_prompt, images=keyframe_images)
conditioning = clip.encode_from_tokens_scheduled(tokens)
values = {}
if keyframes:
values.update({"minimax_keyframes": keyframes, "minimax_frame_count": frame_count})
if refs:
values["minimax_refs"] = refs
if values:
conditioning = node_helpers.conditioning_set_values(conditioning, values)
if mode == "lock_source":
latent = replace_audio_latent(latent, encoded_source, 0.0)
elif mode == "remix_source":
latent = replace_audio_latent(latent, encoded_source, audio_denoise_strength)
media_map = media_map_json(picture_labels, video_labels, audio_labels, source_audio_ordinal)
report_lines = [
f"task={resolved_task}",
f"audio_mode={mode}",
f"frames={frame_count} ({frame_count / FPS:.3f}s at 24fps)",
f"pictures={len(picture_labels)}, videos={len(video_labels)}, audios={len(audio_labels)}",
f"source_audio_tag={'<Audio ' + str(source_audio_ordinal) + '>' if source_audio_ordinal else 'none'}",
]
report_lines.extend(f"warning: {warning}" for warning in prompt_warnings)
output_audio = final_audio if final_audio is not None else drive_audio
return conditioning, latent, output_audio, conditioned_prompt, media_map, "\n".join(report_lines)
@@ -0,0 +1,227 @@
from __future__ import annotations
import math
from collections.abc import Mapping
import torch
import torchaudio
import comfy.model_management
import comfy.nested_tensor
import comfy.utils
CANVAS_MULTIPLE = 32
BASE_SHORT_EDGE = 768
VRAM_CAUTION_PIXELS = 1344 * 768
MAX_PIXELS = 1920 * 1088
REF_IMAGE_SHORT_EDGE = 2048
FPS = 24
AUDIO_LATENT_FPS = 40
MIN_TRAINED_FRAMES = 124
MAX_TRAINED_FRAMES = 362
def align_frame_count(frame_count: int) -> int:
"""Snap up to MiniMax H3's 17n+5 frame grid."""
frame_count = max(5, int(frame_count))
return frame_count + ((5 - frame_count) % 17)
def align_frame_count_down(frame_count: int) -> int:
frame_count = int(frame_count)
return frame_count - ((frame_count - 5) % 17)
def video_latent_t(frame_count: int) -> int:
return 2 if frame_count <= 5 else ((frame_count - 5) // 17) * 5 + 2
def temporal_shape(length: int) -> tuple[int, int, int]:
frame_count = align_frame_count(length)
duration = frame_count / FPS
return frame_count, video_latent_t(frame_count), round(duration * AUDIO_LATENT_FPS)
def adapt_canvas(width: int, height: int) -> tuple[int, int]:
if width <= 0 or height <= 0:
raise ValueError("Width and height must be positive")
ratio = width / height
if ratio >= 1.0:
nominal_width, nominal_height = BASE_SHORT_EDGE * ratio, BASE_SHORT_EDGE
else:
nominal_width, nominal_height = BASE_SHORT_EDGE, BASE_SHORT_EDGE / ratio
if nominal_width * nominal_height > MAX_PIXELS:
scale = math.sqrt(MAX_PIXELS / (nominal_width * nominal_height))
nominal_width *= scale
nominal_height *= scale
return (
max(CANVAS_MULTIPLE, round(nominal_width / CANVAS_MULTIPLE) * CANVAS_MULTIPLE),
max(CANVAS_MULTIPLE, round(nominal_height / CANVAS_MULTIPLE) * CANVAS_MULTIPLE),
)
def resize_image(image: torch.Tensor, width: int, height: int, crop: str = "disabled") -> torch.Tensor:
if image.ndim != 4:
raise ValueError(f"Expected IMAGE [B,H,W,C], got {tuple(image.shape)}")
samples = image[..., :3].movedim(-1, 1)
samples = comfy.utils.common_upscale(samples, width, height, "lanczos", crop)
return samples.movedim(1, -1)
def empty_av_latent(width: int, height: int, length: int) -> tuple[dict, int]:
if width % 32 or height % 32:
raise ValueError("MiniMax H3 width and height must be divisible by 32")
frame_count, latent_t, audio_t = temporal_shape(length)
device = comfy.model_management.intermediate_device()
video = torch.zeros((1, 24, latent_t, height // 16, width // 16), device=device)
audio = torch.zeros((1, 32, 2, audio_t), device=device)
return {"samples": comfy.nested_tensor.NestedTensor((video, audio))}, frame_count
def nested_av_parts(av_latent: dict) -> tuple[torch.Tensor, torch.Tensor]:
if not isinstance(av_latent, dict) or "samples" not in av_latent:
raise ValueError("Expected a MiniMax H3 joint AV LATENT")
samples = av_latent["samples"]
if not getattr(samples, "is_nested", False):
raise ValueError("Expected a nested MiniMax H3 joint video/audio latent")
parts = tuple(samples.unbind())
if len(parts) != 2:
raise ValueError(f"Expected exactly two AV latent parts, got {len(parts)}")
video, audio = parts
if video.ndim != 5 or audio.ndim != 4:
raise ValueError(
"Unexpected MiniMax H3 AV latent layout: "
f"video={tuple(video.shape)}, audio={tuple(audio.shape)}"
)
if video.shape[0] != 1 or audio.shape[0] != 1:
raise ValueError("MiniMax H3 currently supports batch size 1 only")
return video, audio
def classify_h3_vae(vae) -> str:
"""Classify ComfyUI H3 VAE wrappers without relying on audio_sample_rate.
ComfyUI initializes ``audio_sample_rate`` on every generic VAE wrapper,
including MiniMax H3 video VAEs. The latent contract and wrapped model
class are the stable discriminators for the two H3 VAE families.
"""
if vae is None:
return "unknown"
first_stage = getattr(vae, "first_stage_model", None)
class_name = type(first_stage).__name__ if first_stage is not None else ""
if class_name == "MiniMaxH3VideoVAE":
return "video"
if class_name == "MiniMaxH3AudioVAE":
return "audio"
latent_channels = getattr(vae, "latent_channels", None)
latent_dim = getattr(vae, "latent_dim", None)
if latent_channels == 24 and latent_dim == 3:
return "video"
if latent_channels == 32 and latent_dim == 2:
return "audio"
return "unknown"
def validate_audio(audio: Mapping, name: str = "audio") -> tuple[torch.Tensor, int]:
if not isinstance(audio, Mapping):
raise ValueError(f"{name} must be a connected AUDIO value")
waveform = audio.get("waveform")
sample_rate = audio.get("sample_rate")
if not isinstance(waveform, torch.Tensor) or sample_rate is None:
raise ValueError(f"{name} is missing waveform or sample_rate")
if waveform.ndim != 3:
raise ValueError(f"{name} must use [batch,channels,samples], got {tuple(waveform.shape)}")
if waveform.shape[0] < 1 or waveform.shape[1] < 1 or waveform.shape[2] < 1:
raise ValueError(f"{name} is empty")
if waveform.shape[0] != 1:
raise ValueError(f"{name} must have batch size 1 for MiniMax H3")
return waveform, int(sample_rate)
def encode_audio_once(audio_vae, audio: Mapping) -> torch.Tensor:
waveform, sample_rate = validate_audio(audio)
vae_sample_rate = int(getattr(audio_vae, "audio_sample_rate", 32000))
if sample_rate != vae_sample_rate:
waveform = torchaudio.functional.resample(waveform, sample_rate, vae_sample_rate)
latent = audio_vae.encode(waveform[:1].movedim(1, -1))
if not isinstance(latent, torch.Tensor) or latent.ndim != 4:
raise ValueError("The audio VAE did not return [B,C,stereo,T] latent data")
return latent
def fit_audio_latent(encoded_audio: torch.Tensor, template_audio: torch.Tensor) -> torch.Tensor:
if encoded_audio.ndim != 4 or template_audio.ndim != 4:
raise ValueError("MiniMax H3 audio latents must use [B,C,stereo,T]")
if encoded_audio.shape[1:-1] != template_audio.shape[1:-1]:
raise ValueError(
"Audio VAE latent layout mismatch: "
f"got {tuple(encoded_audio.shape)}, target {tuple(template_audio.shape)}"
)
if encoded_audio.shape[0] != template_audio.shape[0]:
if encoded_audio.shape[0] == 1:
encoded_audio = encoded_audio.expand(template_audio.shape[0], -1, -1, -1)
else:
raise ValueError("Audio latent batch cannot be matched to the AV latent")
target_t = template_audio.shape[-1]
if encoded_audio.shape[-1] > target_t:
encoded_audio = encoded_audio[..., :target_t]
elif encoded_audio.shape[-1] < target_t:
padding = encoded_audio.new_zeros((*encoded_audio.shape[:-1], target_t - encoded_audio.shape[-1]))
encoded_audio = torch.cat((encoded_audio, padding), dim=-1)
return encoded_audio.to(device=template_audio.device, dtype=template_audio.dtype)
def sorted_autogrow_items(values: Mapping | None) -> list[tuple[int, object]]:
if not values:
return []
def sort_key(item):
key = str(item[0])
try:
return int(key.rsplit("_", 1)[-1])
except ValueError:
return 10_000
output = []
for key, value in sorted(values.items(), key=sort_key):
if value is None:
continue
try:
ordinal = int(str(key).rsplit("_", 1)[-1])
except ValueError:
ordinal = len(output) + 1
output.append((ordinal, value))
return output
def sorted_autogrow_values(values: Mapping | None) -> list:
return [value for _, value in sorted_autogrow_items(values)]
def split_noise_masks(av_latent: dict, video: torch.Tensor, audio: torch.Tensor):
masks = av_latent.get("noise_mask")
if masks is None:
return None, None
if getattr(masks, "is_nested", False):
parts = tuple(masks.unbind())
if len(parts) == 2:
return parts
# A legacy video-only mask must never be silently discarded.
if isinstance(masks, torch.Tensor):
return masks, None
raise ValueError("Unsupported AV noise_mask layout")
def replace_audio_latent(av_latent: dict, encoded_audio: torch.Tensor, denoise_strength: float) -> dict:
video, template_audio = nested_av_parts(av_latent)
fitted = fit_audio_latent(encoded_audio, template_audio)
video_mask, _ = split_noise_masks(av_latent, video, template_audio)
if video_mask is None:
video_mask = torch.ones_like(video)
audio_mask = torch.full_like(fitted, float(denoise_strength))
output = av_latent.copy()
output["samples"] = comfy.nested_tensor.NestedTensor((video, fitted))
output["noise_mask"] = comfy.nested_tensor.NestedTensor((video_mask, audio_mask))
return output
@@ -0,0 +1,316 @@
from __future__ import annotations
from comfy_api.latest import ComfyExtension, io
from .audio_ops import decode_av_latent, inject_audio_latent, mix_audio, trim_av_output
from .conditioning import build_conditioning
from .nodes_multirate_exp import MiniMaxH3MultiRateSamplerEXPT8
from .nodes_still_exp import (
MiniMaxH3StillConditioningT8,
MiniMaxH3StillDecodeT8,
MiniMaxH3StillPreflightT8,
)
from .preflight import run_preflight
from .prompt_tags import prepare_prompt
from .sampling import setup_dual_clock_sampling
from .timing import make_timing_plan, window_audio
CATEGORY = "T8/MiniMax H3/Audio"
MAX_RESOLUTION = 16384
class MiniMaxH3AudioConditioningT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3AudioConditioningT8",
display_name="MiniMax H3 Audio Conditioning (T8)",
description="Unified native H3 T2VA/I2VA/FL2VA/L2VA/Ref2VA/hybrid conditioning with correct media tags and source-audio control.",
category=CATEGORY,
inputs=[
io.Clip.Input("clip", tooltip="Native MiniMax H3 Qwen3-VL CLIP."),
io.Vae.Input("video_vae", tooltip="MiniMax H3 video VAE."),
io.Vae.Input("audio_vae", tooltip="MiniMax H3 audio VAE."),
io.String.Input("prompt", multiline=True, dynamic_prompts=True),
io.Int.Input("width", default=1344, min=32, max=MAX_RESOLUTION, step=32),
io.Int.Input("height", default=768, min=32, max=MAX_RESOLUTION, step=32),
io.Int.Input("length", default=124, min=5, max=3600, step=17, tooltip="24fps; snapped up to the 17n+5 H3 grid."),
io.Combo.Input("task_type", options=["auto", "T2VA", "I2VA", "FL2VA", "L2VA", "Ref2VA", "Hybrid"], default="auto"),
io.Combo.Input("audio_mode", options=["lock_source", "remix_source", "reference_only", "native"], default="lock_source", tooltip="lock_source preserves source latent; remix_source denoises it; reference_only/native generate target audio."),
io.Float.Input("audio_denoise_strength", default=0.35, min=0.0, max=1.0, step=0.01, advanced=True),
io.Boolean.Input("add_source_as_reference", default=True, tooltip="Presents drive_audio to Qwen/DiT as an official <Audio N> reference."),
io.Int.Input("prompt_primary_audio_ordinal", default=1, min=0, max=9, step=1, tooltip="Prompt audio ordinal intended as the primary source; remapped after video soundtracks. Use 0 to disable.", advanced=True),
io.Boolean.Input("strict_prompt_tags", default=True, advanced=True),
io.Combo.Input("ref_image_size", options=["match", "max"], default="match", advanced=True),
io.Combo.Input("reference_video_policy", options=["official_2_to_15s", "model_minimum"], default="official_2_to_15s", advanced=True),
io.Audio.Input("drive_audio", optional=True),
io.Audio.Input("final_audio", optional=True, tooltip="Optional clean/stem track passed through for final mux; defaults to drive_audio."),
io.Image.Input("first_frame", optional=True),
io.Image.Input("last_frame", optional=True),
io.Autogrow.Input("ref_images", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Image.Input("ref_image"), prefix="ref_image_", min=0, max=9)),
io.Autogrow.Input("ref_videos", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Image.Input("ref_video", tooltip="IMAGE frame batch at 24fps."), prefix="ref_video_", min=0, max=3)),
io.Autogrow.Input("ref_video_audios", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Audio.Input("ref_video_audio"), prefix="ref_video_audio_", min=0, max=3)),
io.Autogrow.Input("ref_audios", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Audio.Input("ref_audio"), prefix="ref_audio_", min=0, max=3)),
],
outputs=[
io.Conditioning.Output(display_name="positive"),
io.Latent.Output(display_name="av_latent"),
io.Audio.Output(display_name="mux_audio"),
io.String.Output(display_name="conditioned_prompt"),
io.String.Output(display_name="media_map_json"),
io.String.Output(display_name="report"),
],
)
@classmethod
def execute(cls, clip, video_vae, audio_vae, prompt, width, height, length, task_type, audio_mode,
audio_denoise_strength, add_source_as_reference, prompt_primary_audio_ordinal,
strict_prompt_tags, ref_image_size, reference_video_policy, drive_audio=None,
final_audio=None, first_frame=None, last_frame=None, ref_images=None, ref_videos=None,
ref_video_audios=None, ref_audios=None):
return io.NodeOutput(*build_conditioning(
clip, video_vae, audio_vae, prompt, width, height, length, task_type, audio_mode,
audio_denoise_strength, add_source_as_reference, prompt_primary_audio_ordinal,
strict_prompt_tags, ref_image_size, reference_video_policy, drive_audio, final_audio,
first_frame, last_frame, ref_images, ref_videos, ref_video_audios, ref_audios,
))
class MiniMaxH3AudioLatentControlT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3AudioLatentControlT8",
display_name="MiniMax H3 Audio Latent Control (T8)",
description="Injects source audio once and preserves an existing video noise mask.",
category=CATEGORY,
inputs=[
io.Latent.Input("av_latent"), io.Audio.Input("source_audio"), io.Vae.Input("audio_vae"),
io.Combo.Input("mode", options=["lock", "remix"], default="lock"),
io.Float.Input("strength", default=0.35, min=0.0, max=1.0, step=0.01),
],
outputs=[io.Latent.Output(display_name="av_latent"), io.Audio.Output(display_name="source_audio")],
)
@classmethod
def execute(cls, av_latent, source_audio, audio_vae, mode, strength):
return io.NodeOutput(*inject_audio_latent(av_latent, source_audio, audio_vae, mode, strength))
class MiniMaxH3DurationPlannerT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3DurationPlannerT8",
display_name="MiniMax H3 Duration Planner (T8)",
category=CATEGORY,
inputs=[
io.Float.Input("scene_start_seconds", default=0.0, min=0.0, max=86400.0, step=0.01),
io.Float.Input("scene_duration_seconds", default=5.0, min=0.04, max=900.0, step=0.01),
io.Float.Input("warmup_seconds", default=0.0, min=0.0, max=60.0, step=0.01),
io.Float.Input("cooldown_seconds", default=0.0, min=0.0, max=60.0, step=0.01),
io.Boolean.Input("ensure_minimum_context", default=True),
io.Float.Input("source_duration_seconds", default=0.0, min=0.0, max=86400.0, step=0.01, advanced=True, tooltip="0 means unknown; the Audio Window node reads it from AUDIO."),
],
outputs=[
io.Int.Output("length"), io.Float.Output("render_duration_seconds"),
io.Float.Output("source_slice_start_seconds"), io.Float.Output("source_slice_duration_seconds"),
io.Float.Output("final_trim_start_seconds"), io.Float.Output("final_duration_seconds"),
io.String.Output("prompt_timing_note"), io.String.Output("report_json"),
],
)
@classmethod
def execute(cls, scene_start_seconds, scene_duration_seconds, warmup_seconds, cooldown_seconds,
ensure_minimum_context, source_duration_seconds):
plan = make_timing_plan(scene_start_seconds, scene_duration_seconds, warmup_seconds,
cooldown_seconds, ensure_minimum_context, source_duration_seconds)
return io.NodeOutput(plan.frame_count, plan.render_duration_seconds, plan.source_slice_start_seconds,
plan.source_slice_duration_seconds, plan.final_trim_start_seconds,
plan.final_duration_seconds, plan.prompt_note(), plan.report())
class MiniMaxH3AudioWindowT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3AudioWindowT8",
display_name="MiniMax H3 Audio Window (T8)",
description="Slices/pads source AUDIO to an aligned H3 context and returns exact final trim metadata.",
category=CATEGORY,
inputs=[
io.Audio.Input("audio"),
io.Float.Input("scene_start_seconds", default=0.0, min=0.0, max=86400.0, step=0.01),
io.Float.Input("scene_duration_seconds", default=5.0, min=0.04, max=900.0, step=0.01),
io.Float.Input("warmup_seconds", default=0.0, min=0.0, max=60.0, step=0.01),
io.Float.Input("cooldown_seconds", default=0.0, min=0.0, max=60.0, step=0.01),
io.Boolean.Input("ensure_minimum_context", default=True),
],
outputs=[io.Audio.Output("context_audio"), io.Int.Output("length"),
io.Float.Output("final_trim_start_seconds"), io.Float.Output("final_duration_seconds"),
io.String.Output("prompt_timing_note"), io.String.Output("report_json")],
)
@classmethod
def execute(cls, audio, scene_start_seconds, scene_duration_seconds, warmup_seconds, cooldown_seconds,
ensure_minimum_context):
source_duration = audio["waveform"].shape[-1] / int(audio["sample_rate"])
plan = make_timing_plan(scene_start_seconds, scene_duration_seconds, warmup_seconds,
cooldown_seconds, ensure_minimum_context, source_duration)
return io.NodeOutput(window_audio(audio, plan), plan.frame_count, plan.final_trim_start_seconds,
plan.final_duration_seconds, plan.prompt_note(), plan.report())
class MiniMaxH3PromptTagsT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3PromptTagsT8", display_name="MiniMax H3 Prompt Tags (T8)", category=CATEGORY,
inputs=[
io.String.Input("prompt", multiline=True, dynamic_prompts=True),
io.Int.Input("picture_count", default=0, min=0, max=11),
io.Int.Input("video_count", default=0, min=0, max=3),
io.Int.Input("audio_count", default=1, min=0, max=9),
io.Int.Input("source_audio_ordinal", default=1, min=0, max=9),
io.Int.Input("prompt_primary_audio_ordinal", default=1, min=0, max=9),
io.Boolean.Input("strict", default=True),
], outputs=[io.String.Output("prompt"), io.String.Output("report")],
)
@classmethod
def execute(cls, prompt, picture_count, video_count, audio_count, source_audio_ordinal,
prompt_primary_audio_ordinal, strict):
normalized, warnings = prepare_prompt(prompt, {"pictures": picture_count, "videos": video_count,
"audios": audio_count}, source_audio_ordinal,
prompt_primary_audio_ordinal, strict)
return io.NodeOutput(normalized, "OK" if not warnings else "\n".join(warnings))
class MiniMaxH3AVDecodeT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3AVDecodeT8", display_name="MiniMax H3 AV Decode (T8)", category=CATEGORY,
inputs=[io.Latent.Input("av_latent"), io.Vae.Input("video_vae"), io.Vae.Input("audio_vae")],
outputs=[io.Image.Output("frames"), io.Audio.Output("generated_audio"),
io.Latent.Output("video_latent"), io.Latent.Output("audio_latent")],
)
@classmethod
def execute(cls, av_latent, video_vae, audio_vae):
return io.NodeOutput(*decode_av_latent(av_latent, video_vae, audio_vae))
class MiniMaxH3AudioMixT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3AudioMixT8", display_name="MiniMax H3 Audio Mix (T8)", category=CATEGORY,
inputs=[
io.Audio.Input("source_audio"), io.Audio.Input("generated_audio"),
io.Float.Input("source_gain_db", default=0.0, min=-60.0, max=24.0, step=0.1),
io.Float.Input("generated_gain_db", default=-6.0, min=-60.0, max=24.0, step=0.1),
io.Float.Input("duck_generated", default=0.5, min=0.0, max=1.0, step=0.01),
io.Combo.Input("output_sample_rate", options=["source", "generated", "48000", "44100", "32000"], default="source"),
io.Float.Input("peak_limit_dbfs", default=-1.0, min=-12.0, max=0.0, step=0.1),
], outputs=[io.Audio.Output("mixed_audio")],
)
@classmethod
def execute(cls, source_audio, generated_audio, source_gain_db, generated_gain_db,
duck_generated, output_sample_rate, peak_limit_dbfs):
return io.NodeOutput(mix_audio(source_audio, generated_audio, source_gain_db, generated_gain_db,
duck_generated, output_sample_rate, peak_limit_dbfs))
class MiniMaxH3OutputTrimT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3OutputTrimT8", display_name="MiniMax H3 Output Trim (T8)", category=CATEGORY,
description="Applies Duration Planner trim metadata to decoded IMAGE frames and optional AUDIO.",
inputs=[
io.Image.Input("frames"),
io.Float.Input("start_seconds", default=0.0, min=0.0, max=900.0, step=0.001),
io.Float.Input("duration_seconds", default=5.0, min=0.04, max=900.0, step=0.001),
io.Float.Input("fps", default=24.0, min=1.0, max=240.0, step=0.001, advanced=True),
io.Audio.Input("audio", optional=True),
],
outputs=[io.Image.Output("frames"), io.Audio.Output("audio"), io.String.Output("report_json")],
)
@classmethod
def execute(cls, frames, start_seconds, duration_seconds, fps, audio=None):
return io.NodeOutput(*trim_av_output(frames, start_seconds, duration_seconds, audio, fps))
class MiniMaxH3PreflightT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3PreflightT8", display_name="MiniMax H3 Preflight (T8)", category=CATEGORY,
inputs=[
io.Int.Input("width", default=1344, min=32, max=MAX_RESOLUTION, step=32),
io.Int.Input("height", default=768, min=32, max=MAX_RESOLUTION, step=32),
io.Int.Input("length", default=124, min=5, max=3600),
io.Combo.Input("audio_mode", options=["lock_source", "remix_source", "reference_only", "native"], default="lock_source"),
io.Model.Input("model", optional=True), io.Vae.Input("video_vae", optional=True),
io.Vae.Input("audio_vae", optional=True), io.Audio.Input("drive_audio", optional=True),
io.Autogrow.Input("ref_images", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Image.Input("ref_image"), prefix="ref_image_", min=0, max=9)),
io.Autogrow.Input("ref_videos", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Image.Input("ref_video"), prefix="ref_video_", min=0, max=3)),
io.Autogrow.Input("ref_audios", optional=True, template=io.Autogrow.TemplatePrefix(input=io.Audio.Input("ref_audio"), prefix="ref_audio_", min=0, max=3)),
], outputs=[io.Boolean.Output("ready"), io.Int.Output("warning_count"), io.String.Output("report_json")],
)
@classmethod
def execute(cls, width, height, length, audio_mode, model=None, video_vae=None, audio_vae=None,
drive_audio=None, ref_images=None, ref_videos=None, ref_audios=None):
return io.NodeOutput(*run_preflight(width, height, length, audio_mode, model, video_vae, audio_vae,
drive_audio, ref_images, ref_videos, ref_audios))
class MiniMaxH3DualClockSamplerT8(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="MiniMaxH3DualClockSamplerT8",
display_name="MiniMax H3 Dual-Clock Sampler (T8)",
description=(
"Four-step H3 Euler setup with separate video/audio clocks. "
"Outputs a coherently shifted model, sampler, and native flow sigmas."
),
category=CATEGORY,
inputs=[
io.Model.Input("model"),
io.Latent.Input("av_latent"),
io.Int.Input("steps", default=4, min=1, max=1000),
io.Float.Input("shift_video", default=12.0, min=0.01, max=100.0, step=0.01, advanced=True),
io.Float.Input("shift_audio", default=3.0, min=0.01, max=100.0, step=0.01, advanced=True),
],
outputs=[
io.Model.Output(display_name="model"),
io.Sampler.Output(display_name="sampler"),
io.Sigmas.Output(display_name="sigmas"),
],
)
@classmethod
def execute(cls, model, av_latent, steps, shift_video, shift_audio):
return io.NodeOutput(*setup_dual_clock_sampling(
model, av_latent, steps, shift_video, shift_audio
))
class MiniMaxH3AudioT8Extension(ComfyExtension):
async def get_node_list(self):
return [MiniMaxH3AudioConditioningT8, MiniMaxH3AudioLatentControlT8,
MiniMaxH3DurationPlannerT8, MiniMaxH3AudioWindowT8, MiniMaxH3PromptTagsT8,
MiniMaxH3AVDecodeT8, MiniMaxH3AudioMixT8, MiniMaxH3OutputTrimT8,
MiniMaxH3PreflightT8, MiniMaxH3DualClockSamplerT8,
MiniMaxH3MultiRateSamplerEXPT8, MiniMaxH3StillConditioningT8,
MiniMaxH3StillPreflightT8, MiniMaxH3StillDecodeT8]
def comfy_entrypoint():
return MiniMaxH3AudioT8Extension()
@@ -0,0 +1,117 @@
from __future__ import annotations
import json
import torch
from comfy.ldm.minimax.model import MiniMaxH3Model
from .core import (
MAX_PIXELS,
MAX_TRAINED_FRAMES,
MIN_TRAINED_FRAMES,
VRAM_CAUTION_PIXELS,
align_frame_count,
classify_h3_vae,
sorted_autogrow_values,
validate_audio,
)
def run_preflight(
width: int,
height: int,
length: int,
audio_mode: str,
model=None,
video_vae=None,
audio_vae=None,
drive_audio=None,
ref_images=None,
ref_videos=None,
ref_audios=None,
):
errors: list[str] = []
warnings: list[str] = []
facts: dict[str, object] = {}
if width <= 0 or height <= 0 or width % 32 or height % 32:
errors.append("width and height must be positive multiples of 32")
pixels = width * height
facts["pixels"] = pixels
facts["max_pixel_area"] = MAX_PIXELS
if pixels > MAX_PIXELS:
errors.append(
f"canvas has {pixels:,} pixels; configured H3 2.0MP cap is "
f"{MAX_PIXELS:,} pixels (1920x1088)"
)
elif pixels > VRAM_CAUTION_PIXELS:
warnings.append(
f"high-resolution canvas has {pixels:,} pixels; this is supported up to "
"1920x1088 but may require substantially more VRAM"
)
aligned = align_frame_count(length)
facts["aligned_frames"] = aligned
if aligned != length:
warnings.append(f"length {length} will snap up to {aligned} on the 17n+5 grid")
if not MIN_TRAINED_FRAMES <= aligned <= MAX_TRAINED_FRAMES:
warnings.append(
f"{aligned} frames is outside the approximately trained {MIN_TRAINED_FRAMES}-{MAX_TRAINED_FRAMES} range"
)
if model is not None:
diffusion_model = getattr(getattr(model, "model", None), "diffusion_model", None)
if not isinstance(diffusion_model, MiniMaxH3Model):
errors.append("model is not a native ComfyUI MiniMax H3 diffusion model")
if video_vae is not None:
video_vae_kind = classify_h3_vae(video_vae)
facts["video_vae_kind"] = video_vae_kind
if video_vae_kind == "audio":
errors.append("video_vae is an H3 audio VAE; connect the H3 video VAE")
if audio_vae is not None:
audio_vae_kind = classify_h3_vae(audio_vae)
facts["audio_vae_kind"] = audio_vae_kind
if audio_vae_kind == "video":
errors.append("audio_vae is an H3 video VAE; connect the H3 audio VAE")
facts["audio_vae_sample_rate"] = int(getattr(audio_vae, "audio_sample_rate", 32000))
if audio_mode != "native" and drive_audio is None:
errors.append(f"audio mode {audio_mode} requires drive_audio")
if drive_audio is not None:
try:
waveform, sample_rate = validate_audio(drive_audio, "drive_audio")
facts["drive_audio_sample_rate"] = sample_rate
facts["drive_audio_duration_seconds"] = waveform.shape[-1] / sample_rate
if not torch.isfinite(waveform).all():
errors.append("drive_audio contains NaN or infinite samples")
else:
peak = float(waveform.abs().max())
rms = float(torch.sqrt(torch.mean(waveform.float().square())))
facts["drive_audio_peak"] = peak
facts["drive_audio_rms"] = rms
if peak > 1.0:
warnings.append(f"drive_audio peak {peak:.3f} exceeds 0 dBFS and may clip")
if rms < 1e-4:
warnings.append("drive_audio is effectively silent")
except ValueError as error:
errors.append(str(error))
pictures = sorted_autogrow_values(ref_images)
videos = sorted_autogrow_values(ref_videos)
audios = sorted_autogrow_values(ref_audios)
facts.update({"reference_images": len(pictures), "reference_videos": len(videos), "reference_audios": len(audios)})
if len(pictures) > 9 or len(videos) > 3 or len(audios) > 3:
errors.append("reference counts exceed H3 limits (9 pictures / 3 videos / 3 audios)")
for index, frames in enumerate(videos, 1):
if not isinstance(frames, torch.Tensor) or frames.ndim != 4:
errors.append(f"ref_video_{index} is not an IMAGE frame batch")
elif not 48 <= frames.shape[0] <= 360:
warnings.append(f"ref_video_{index} has {frames.shape[0]} frames; official guidance is 48-360 at 24fps")
ready = not errors
report = json.dumps(
{"ready": ready, "errors": errors, "warnings": warnings, "facts": facts},
ensure_ascii=False,
indent=2,
)
return ready, len(warnings), report
@@ -0,0 +1,16 @@
[project]
name = "minimax-h3-audio-t8"
version = "1.3.2"
description = "MiniMax H3 audio, dual-clock sampling, and experimental Ref2VA still-image editing nodes for ComfyUI"
readme = "README.md"
requires-python = ">=3.10"
license = { text = "GPL-3.0-or-later" }
dependencies = []
[tool.pytest.ini_options]
addopts = "--import-mode=importlib"
testpaths = ["tests"]
norecursedirs = ["artifacts"]
[tool.ruff.lint.per-file-ignores]
"tools/*.py" = ["T201"]
@@ -0,0 +1 @@
# No extra packages. torch and torchaudio are supplied by ComfyUI.
@@ -0,0 +1,179 @@
from __future__ import annotations
import math
import torch
import comfy.model_sampling
import comfy.samplers
import comfy.utils
from comfy.k_diffusion.sampling import to_d
from .core import nested_av_parts
class MiniMaxH3FlowSampling(comfy.model_sampling.ModelSamplingDiscreteFlow, comfy.model_sampling.CONST):
@property
def audio_scale(self):
# The custom sampler advances the unpacked audio stream on its own clock.
# New ComfyUI H3 builds require this property, but must not additionally
# carry/scale audio onto the video clock (that would apply the transform twice).
return 1.0
def model_uses_raw_audio_velocity(model) -> bool:
"""Detect the post-2026-08-06 ComfyUI MiniMax H3 sampling protocol."""
base_model = getattr(model, "model", None)
return callable(getattr(base_model, "audio_scale", None))
def shift_sigma(base_sigma, shift: float):
return shift * base_sigma / (1.0 + (shift - 1.0) * base_sigma)
def time_shift_sigma(sigma, from_shift: float, to_shift: float):
base_sigma = sigma / (from_shift + sigma * (1.0 - from_shift))
return shift_sigma(base_sigma, to_shift)
def time_shift_slope(sigma, from_shift: float, to_shift: float):
base_sigma = sigma / (from_shift + sigma * (1.0 - from_shift))
numerator = to_shift * (1.0 + (from_shift - 1.0) * base_sigma) ** 2
denominator = from_shift * (1.0 + (to_shift - 1.0) * base_sigma) ** 2
return numerator / denominator
def native_flow_sigmas(steps: int, shift_video: float) -> torch.Tensor:
base_sigmas = torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float32)
return shift_sigma(base_sigmas, shift_video)
def _audio_step_scale(
sigma_video,
sigma_audio,
slope_audio,
denoise_mask,
audio_velocity_is_raw: bool,
):
flat_scale = -sigma_video
dual_scale = -sigma_audio if audio_velocity_is_raw else -sigma_audio / slope_audio
if denoise_mask is None:
return dual_scale
return flat_scale + denoise_mask * (dual_scale - flat_scale)
def sample_minimax_h3_dual_clock_euler(
model,
x,
sigmas,
extra_args=None,
callback=None,
disable=None,
*,
video_values: int,
packed_values: int,
shift_video: float,
shift_audio: float,
audio_velocity_is_raw: bool = False,
):
extra_args = {} if extra_args is None else extra_args
if x.shape[-1] != packed_values:
raise ValueError(
"MiniMax H3 packed latent changed after sampler setup: "
f"expected {packed_values} values, got {x.shape[-1]}"
)
denoise_mask = extra_args.get("denoise_mask")
audio_mask = None
if denoise_mask is not None:
if denoise_mask.shape[-1] != packed_values:
raise ValueError("MiniMax H3 denoise mask does not match the packed AV latent")
audio_mask = denoise_mask[..., video_values:]
s_in = x.new_ones([x.shape[0]])
for step in comfy.utils.model_trange(len(sigmas) - 1, disable=disable):
sigma_video = sigmas[step]
sigma_video_next = sigmas[step + 1]
denoised = model(x, sigma_video * s_in, **extra_args)
derivative = to_d(x, sigma_video, denoised)
sigma_audio = time_shift_sigma(sigma_video, shift_video, shift_audio)
sigma_audio_next = time_shift_sigma(sigma_video_next, shift_video, shift_audio)
slope_audio = time_shift_slope(sigma_video, shift_video, shift_audio)
video_delta = sigma_video_next - sigma_video
audio_delta = sigma_audio_next - sigma_audio
if not audio_velocity_is_raw:
# Older ComfyUI H3 builds returned an audio velocity multiplied by
# d(sigma_audio)/d(sigma_video), so their update needs the inverse.
audio_delta = audio_delta / slope_audio
if audio_mask is not None:
audio_delta = video_delta + audio_mask * (audio_delta - video_delta)
if callback is not None:
endpoint_scale = _audio_step_scale(
sigma_video,
sigma_audio,
slope_audio,
audio_mask,
audio_velocity_is_raw,
)
denoised[..., video_values:] = x[..., video_values:] + derivative[..., video_values:] * endpoint_scale
callback({
"x": x,
"i": step,
"sigma": sigma_video,
"sigma_hat": sigma_video,
"denoised": denoised,
})
x = torch.cat((
x[..., :video_values] + derivative[..., :video_values] * video_delta,
x[..., video_values:] + derivative[..., video_values:] * audio_delta,
), dim=-1)
return x
def setup_dual_clock_sampling(model, av_latent: dict, steps: int, shift_video: float, shift_audio: float):
video, audio = nested_av_parts(av_latent)
if video.shape[1] != 24 or audio.shape[1] != 32 or audio.shape[2] != 2:
raise ValueError(
"Unexpected MiniMax H3 AV channels: "
f"video={tuple(video.shape)}, audio={tuple(audio.shape)}"
)
patched_model = model.clone()
audio_velocity_is_raw = model_uses_raw_audio_velocity(model)
original_sampling = model.get_model_object("model_sampling")
model_sampling = MiniMaxH3FlowSampling(model.model.model_config)
model_sampling.set_parameters(shift=shift_video)
if hasattr(original_sampling, "noise_scale"):
model_sampling.set_noise_scale(original_sampling.noise_scale)
patched_model.add_object_patch("model_sampling", model_sampling)
transformer_options = patched_model.model_options.get("transformer_options", {}).copy()
transformer_options["minimax_h3_sigma_shift_video"] = shift_video
transformer_options["minimax_h3_sigma_shift_audio"] = shift_audio
patched_model.model_options["transformer_options"] = transformer_options
video_values = math.prod(video.shape[1:])
packed_values = video_values + math.prod(audio.shape[1:])
def sampler_function(model_wrap, x, sigmas, extra_args=None, callback=None, disable=None):
return sample_minimax_h3_dual_clock_euler(
model_wrap,
x,
sigmas,
extra_args=extra_args,
callback=callback,
disable=disable,
video_values=video_values,
packed_values=packed_values,
shift_video=shift_video,
shift_audio=shift_audio,
audio_velocity_is_raw=audio_velocity_is_raw,
)
sampler_function.__name__ = "sample_minimax_h3_dual_clock_euler"
sampler = comfy.samplers.KSAMPLER(sampler_function)
sigmas = native_flow_sigmas(steps, shift_video)
return patched_model, sampler, sigmas
@@ -0,0 +1,92 @@
from __future__ import annotations
from dataclasses import asdict, dataclass
import json
import math
from .core import FPS, MIN_TRAINED_FRAMES, align_frame_count, validate_audio
@dataclass(frozen=True)
class TimingPlan:
frame_count: int
render_duration_seconds: float
source_slice_start_seconds: float
source_slice_duration_seconds: float
left_pad_seconds: float
right_pad_seconds: float
final_trim_start_seconds: float
final_duration_seconds: float
main_prompt_start_seconds: float
main_prompt_end_seconds: float
def report(self) -> str:
return json.dumps(asdict(self), ensure_ascii=False, indent=2)
def prompt_note(self) -> str:
return (
f"Timing: context starts at 0.00s; main requested action starts at "
f"{self.main_prompt_start_seconds:.2f}s and ends at {self.main_prompt_end_seconds:.2f}s."
)
def make_timing_plan(
scene_start_seconds: float,
scene_duration_seconds: float,
warmup_seconds: float = 0.0,
cooldown_seconds: float = 0.0,
ensure_minimum_context: bool = True,
source_duration_seconds: float = 0.0,
) -> TimingPlan:
if scene_start_seconds < 0:
raise ValueError("scene_start_seconds cannot be negative")
if scene_duration_seconds <= 0:
raise ValueError("scene_duration_seconds must be positive")
if warmup_seconds < 0 or cooldown_seconds < 0:
raise ValueError("warmup_seconds and cooldown_seconds cannot be negative")
required = warmup_seconds + scene_duration_seconds + cooldown_seconds
if ensure_minimum_context:
required = max(required, MIN_TRAINED_FRAMES / FPS)
extra = max(0.0, required - (warmup_seconds + scene_duration_seconds + cooldown_seconds))
ideal_start = scene_start_seconds - warmup_seconds - extra / 2.0
ideal_end = scene_start_seconds + scene_duration_seconds + cooldown_seconds + extra / 2.0
frame_count = align_frame_count(math.ceil((ideal_end - ideal_start) * FPS - 1e-9))
render_duration = frame_count / FPS
# Grid alignment extends the tail, never shifts the user's requested scene.
ideal_end = ideal_start + render_duration
slice_start = max(0.0, ideal_start)
left_pad = max(0.0, -ideal_start)
available_end = source_duration_seconds if source_duration_seconds > 0 else ideal_end
slice_end = min(ideal_end, available_end)
slice_duration = max(0.0, slice_end - slice_start)
right_pad = max(0.0, render_duration - left_pad - slice_duration)
trim_start = scene_start_seconds - ideal_start
return TimingPlan(
frame_count=frame_count,
render_duration_seconds=render_duration,
source_slice_start_seconds=slice_start,
source_slice_duration_seconds=slice_duration,
left_pad_seconds=left_pad,
right_pad_seconds=right_pad,
final_trim_start_seconds=trim_start,
final_duration_seconds=scene_duration_seconds,
main_prompt_start_seconds=trim_start,
main_prompt_end_seconds=trim_start + scene_duration_seconds,
)
def window_audio(audio: dict, plan: TimingPlan) -> dict:
waveform, sample_rate = validate_audio(audio)
start = round(plan.source_slice_start_seconds * sample_rate)
count = round(plan.source_slice_duration_seconds * sample_rate)
sliced = waveform[..., start : start + count]
left_count = round(plan.left_pad_seconds * sample_rate)
target_count = round(plan.render_duration_seconds * sample_rate)
output = waveform.new_zeros((waveform.shape[0], waveform.shape[1], target_count))
writable = min(sliced.shape[-1], max(0, target_count - left_count))
if writable:
output[..., left_count : left_count + writable] = sliced[..., :writable]
return {"waveform": output, "sample_rate": sample_rate}