Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Quality levels: Medium samples two passes from a larger first pass, Max runs all 20 steps
Bowen Xuef2c25e6e4f82
diff --git a/freevideo_engine/agent/drama.py b/freevideo_engine/agent/drama.pyindex 8908a9d..e47f12b 100644--- a/freevideo_engine/agent/drama.py+++ b/freevideo_engine/agent/drama.py@@ -159,7 +159,7 @@ def check(play):long = isinstance(seconds, (int, float)) and not isinstance(seconds, bool) and seconds > 15if ((shot.get('continue') or long) and play.get('quality') in specs.QUALITYand not specs.QUALITY[play['quality']][0] and all(p['path'] != '/quality' for p in problems)):- problem('/quality', '"light" (two-pass) when a shot continues another or is longer than 15 s')+ problem('/quality', '"light" or "medium" (two-pass) when a shot continues another or is longer than 15 s')if long and (shot.get('first') is not None or shot.get('references') and not shot.get('continue')):problem(path + '/seconds', 'at most 15 with a first frame or references')elif long and not shot.get('continue') and _carded(play, shot):diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.pyindex 8789fac..56a6ccf 100644--- a/freevideo_engine/agent/guide.py+++ b/freevideo_engine/agent/guide.py@@ -73,10 +73,10 @@ GUIDE = {'the draft and looks plainer than a direct generation, so keep the direct one when the user prefers its look.',],'quality': [- 'Steps per quality: "light" = 8 first-pass steps + 3 refine steps, two-pass (default); "medium" = 8 steps, '- '"high" = 20 steps with a step cache, "max" = 20 steps with a step cache that skips less work, each in one pass. '- '"max" runs plain 20 steps when the GPU has no room for its cache. On a Mac, "high" is the same and '- '"max" is 20 plain steps.',+ 'Steps per quality: "light" = 8 first-pass steps + 3 refine steps, two-pass, the first pass at half size '+ '(default); "medium" = the same 8 + 3 two-pass with a larger first pass, for more detail; "high" = 20 steps '+ 'with a step cache and "max" = 20 plain steps, each in one pass. The same on a Mac. sampling.two_pass=false '+ 'without base_steps runs 20 steps.','Two-pass generation runs only with 8 first-pass steps. Any other base_steps (for example 20 with ''two_pass=true) runs in one pass of that many steps; the job notice says so. A preview is always two-pass ''with 8 steps.',@@ -85,7 +85,7 @@ GUIDE = {'Single-block frames are 24 fps on a 17n+5 grid (6 s -> 6.583 s, 10 s -> 10.125 s). ''Under 30 s defaults to one generation when the device supports this size and quality; unknown limits use 15 s. ''Otherwise it uses as few parts as possible, each at least 10 s; how many depends on how long this computer can generate in one run, and the parts continue and join automatically. '- 'Multiple blocks or continue_from need two-pass text generation: quality "light" '+ 'Multiple blocks or continue_from need two-pass text generation: quality "light" or "medium" ''or sampling.two_pass=true and no preview. Their only media is media.references with at most 3 pictures, ''which every continuing part also sees (keeps the same people); first_frame_reference then gives way to them. ''Multi-block output is cut to the planned duration. POST /plan shows the chain plan. 'diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.pyindex 98be19e..56ec0f9 100644--- a/freevideo_engine/agent/jobs.py+++ b/freevideo_engine/agent/jobs.py@@ -134,10 +134,10 @@ def continuation_problems(spec, prefix='', *, editor=None):if spec.get('sampling_note'):# Two-pass was asked for with a first-pass count other than 8: it runs one pass.problem = schema.diagnostic(prefix + '/quality',- '"light" (two-pass), or sampling.two_pass=true with base_steps=8,' + why, None)+ '"light" or "medium" (two-pass), or sampling.two_pass=true with base_steps=8,' + why, None)got = '%d first-pass steps (one pass)' % spec['base_steps']else:- problem = schema.diagnostic(prefix + '/quality', '"light" (two-pass), or sampling.two_pass=true,' + why, None)+ problem = schema.diagnostic(prefix + '/quality', '"light" or "medium" (two-pass), or sampling.two_pass=true,' + why, None)got = '"%s" (one pass)' % spec['quality']problems.append(dict(problem, got=got, message=problem['message'].replace('received None', 'received ' + got)))if spec['preview']:diff --git a/freevideo_engine/agent/length.py b/freevideo_engine/agent/length.pyindex a44e149..bf86e0e 100644--- a/freevideo_engine/agent/length.py+++ b/freevideo_engine/agent/length.py@@ -47,7 +47,8 @@ def single_frame_limit(spec, *, port=None, table=None):same = [row for row in tiers.values()if row.get('steps') == spec['base_steps'] and row.get('two_pass') == spec['two_pass']and (not spec['two_pass'] or spec['refine_steps'] == 3)]- tier = next((row for row in same if row.get('step_cache') == spec.get('step_cache')),+ tier = next((row for row in same if row.get('step_cache') == spec.get('step_cache')+ and row.get('upscale', 2) == spec.get('upscale_factor', 2)),same[0] if same else {})index = next((i for i, row in enumerate(table.get('sizes', []))if (row['width'], row['height']) == (spec['width'], spec['height'])), None)diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex a7b05b4..e0fa113 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -225,7 +225,8 @@ def capabilities(port, jobs):fps=24, base_steps=[1, 32], refine_steps=[1, 31], references=32, loras=32, lora_strength=[-4, 4],upload_bytes=2 * 1024 ** 3, vlm_images=24, takes=8, batch_jobs=64),quality={name: dict(two_pass=plan[0], base_steps=plan[1], refine_steps=plan[2],- step_cache=quality_tiers.step_cache(name, quality_tiers.on_mac()))+ step_cache=quality_tiers.step_cache(name, quality_tiers.on_mac()),+ upscale_factor=quality_tiers.upscale_factor(name, quality_tiers.on_mac()))for name, plan in specs.QUALITY.items()},aspects=sorted(specs.ASPECTS), native_megapixels=.98,tasks=GUIDE['tasks'], media_extensions={k: sorted(v) for k, v in EXTENSIONS.items()},diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.pyindex d72982c..dfca3b7 100644--- a/freevideo_engine/agent/schema.py+++ b/freevideo_engine/agent/schema.py@@ -14,7 +14,8 @@ from .. import tiersS = 'https://json-schema.org/draft/2020-12/schema'PREFIX = '/freevideo/agent/v1'# (two_pass, base_steps, refine_steps) of each level on this platform; the step-# cache a level adds is tiers.step_cache(name, mac) (on Mac only high has one, easycache-av).+# cache a level adds is tiers.step_cache(name, mac) (only high has one, easycache-av),+# its two-pass upscale factor tiers.upscale_factor(name, mac) (medium samples a larger first pass).QUALITY = {name: tiers.plan(name, mac=tiers.on_mac()) for name in tiers.TIERS}ASPECTS = {'16:9': (16, 9), '9:16': (9, 16), '1:1': (1, 1), '4:3': (4, 3), '3:4': (3, 4),'21:9': (21, 9), '2:3': (2, 3), '3:2': (3, 2)}@@ -182,7 +183,8 @@ def generate(*, local=False):'then': {'not': {'anyOf': [{'required': [k]} for k in ('width', 'height')]}}},{'if': {'if': {'required': ['sampling'], 'properties': {'sampling': {'required': ['two_pass']}}},'then': {'properties': {'sampling': {'properties': {'two_pass': {'const': False}}}}},- 'else': {'required': ['quality'], 'properties': {'quality': {'not': {'const': 'light'}}}}},+ 'else': {'required': ['quality'], 'properties': {'quality': {'not': {'enum': [+ name for name, plan in QUALITY.items() if plan[0]]}}}}},'then': {'properties': {'preview': {'const': False}}}},# A preview is two-pass, which runs only with 8 first-pass steps: refused when the effective# first-pass count is another number, given in sampling or inherited from the quality.@@ -194,7 +196,7 @@ def generate(*, local=False):{'required': ['sampling'], 'properties': {'sampling': {'required': ['base_steps'], 'not': {'required': ['two_pass']},'properties': {'base_steps': {'not': {'const': 8}}}},- 'quality': {'const': 'light'}}},+ 'quality': {'enum': [name for name, plan in QUALITY.items() if plan[0]]}}},{'required': ['sampling', 'quality'], 'properties': {'sampling': {'required': ['two_pass'], 'not': {'required': ['base_steps']},'properties': {'two_pass': {'const': True}}},diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.pyindex a148bd7..c3fdeb4 100644--- a/freevideo_engine/agent/spec.py+++ b/freevideo_engine/agent/spec.py@@ -131,6 +131,9 @@ def sampling(value):quality = value.get('quality', contract.generate()['properties']['quality']['default'])two, base, refine = QUALITY[quality]custom = value.get('sampling', {})+ if two and custom.get('two_pass') is False and 'base_steps' not in custom:+ # One pass always samples 20 steps unless the caller gives its own count.+ base = 20two, base, refine = custom.get('two_pass', two), custom.get('base_steps', base), custom.get('refine_steps', refine)note = Noneif two:@@ -138,13 +141,18 @@ def sampling(value):# Only the 8-step first pass goes two-pass; any other count is one pass, said once in the answer.note = one_pass_note(base)two = two and note is None- # A level's step cache stays only with that level's own plan; custom sampling runs every step.- cache = tiers.step_cache(quality, mac) if QUALITY[quality] == (two, base, refine) else None+ # A level's step cache and upscale factor stay only with that level's own plan; custom sampling+ # runs every step and upscales 2x.+ own = QUALITY[quality] == (two, base, refine)+ cache = tiers.step_cache(quality, mac) if own else None+ factor = tiers.upscale_factor(quality, mac) if own and two else 2if custom:quality = next((k for k, v in QUALITY.items() if v == (two, base, refine)- and tiers.step_cache(k, mac) == cache), 'custom')+ and tiers.step_cache(k, mac) == cache+ and (not two or tiers.upscale_factor(k, mac) == factor)), 'custom')return dict(quality=quality, two_pass=two, base_steps=base, refine_steps=refine,- **({'step_cache': cache} if cache else {}), **({'sampling_note': note} if note else {}))+ **({'step_cache': cache} if cache else {}), **({'upscale_factor': factor} if factor != 2 else {}),+ **({'sampling_note': note} if note else {}))def generation_media(value):@@ -283,6 +291,8 @@ def comfy_prompt(spec, node, *, prompt, assets, refine_from=''):inputs['first_frame_reference'] = Trueif spec.get('step_cache'):inputs['step_cache'] = spec['step_cache']+ if spec.get('upscale_factor', 2) != 2 and spec['two_pass'] and not spec['preview']:+ inputs['upscale_factor'] = '%g' % spec['upscale_factor']graph = {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs,'_meta': {'title': 'FreeVideo · ' + (spec.get('label') or 'Agent job')}}}if assets:diff --git a/freevideo_engine/capabilities.py b/freevideo_engine/capabilities.pyindex 817fad6..4dee623 100644--- a/freevideo_engine/capabilities.py+++ b/freevideo_engine/capabilities.py@@ -219,7 +219,7 @@ def _machine(machine, in_use=None):def _request(width, height, frames, steps, two_pass, task='t2va', refine=3,- references=None, reference_rows=None):+ references=None, reference_rows=None, upscale=2):"""Scalar request shared by admission and offline, recorded-row reviews."""from .two_pass import render_canvascanvas = dict(render_canvas(geometry(width, height, frames=frames))[0], task=task, steps=steps)@@ -233,23 +233,25 @@ def _request(width, height, frames, steps, two_pass, task='t2va', refine=3,canvas.update(reference_video_tokens=rows['video'], reference_audio_tokens=rows['audio'])if duration is not None:canvas['reference_seconds'] = duration- sampling = sampling_plan(canvas, two_pass, task, base_steps=steps, refine_steps=refine)+ sampling = sampling_plan(canvas, two_pass, task, base_steps=steps, refine_steps=refine, scale=upscale)# A small canvas runs in one pass even with two-pass on; follow the plan.request = dict(canvas, base_steps=steps, refine_steps=sampling['refine_steps'],two_pass=sampling['enabled'], flow='full',sampling_geometry={k: sampling[k] for k in ('first', 'second') if sampling[k]})+ if sampling.get('scale', 2) != 2:+ request['upscale_factor'] = sampling['scale']return canvas, sampling, requestdef _admit(machine, width, height, frames, steps, two_pass, task='t2va', refine=3,- references=None, reference_rows=None, step_cache=None):+ references=None, reference_rows=None, step_cache=None, upscale=2):"""Admission of one request; `step_cache` asks the planner for a first-pass cache.The request carries the cache the planner keeps (on Mac only the audio-video EasyCache), so itsestimate and history follow what the engine will actually run."""canvas, sampling, request = _request(width, height, frames, steps, two_pass, task, refine,- references, reference_rows)+ references, reference_rows, upscale)rows = dict(video=canvas.get('reference_video_tokens', 0), audio=canvas.get('reference_audio_tokens', 0))try:if machine['mac']:@@ -336,7 +338,8 @@ def _calibration(machine, hardware, records, params, version):request, _, _ = _admit(machine, shape['width'], shape['height'], shape['frames'],row['base_steps'], row['two_pass'], row['task'],row['refine_steps'] if row['two_pass'] else 3,- reference_rows=refs, step_cache=row.get('step_cache'))+ reference_rows=refs, step_cache=row.get('step_cache'),+ upscale=row.get('upscale_factor', 2))if request is None:continuerequest['lora_count'] = int(bool(row.get('adapters')))@@ -365,6 +368,7 @@ def _whole_records(records, request, adapters):and r.get('adapters', False) == adapters and r.get('two_pass') == request['two_pass']and r.get('base_steps') == request['base_steps'] and r.get('refine_steps') == request['refine_steps']and r.get('step_cache') == request.get('step_cache')+ and r.get('upscale_factor', 2) == request.get('upscale_factor', 2)and ((request['task'] == 't2va' and r.get('reference_rows') is None)or (valid_reference_rows(r.get('reference_rows')) and r['reference_rows'] == rows))]@@ -418,11 +422,11 @@ def build(machine, records, *, aspect='16:9', size=None, task='t2va', adapters=Ftiers = {}for name, tier in quality_tiers.table(machine['mac']).items():- steps, two_pass, step_cache = tier['steps'], tier['two_pass'], tier['step_cache']+ steps, two_pass, step_cache, upscale = tier['steps'], tier['two_pass'], tier['step_cache'], tier['upscale']times, codes, maxima, frame_maxima, limits = [], [], [], [], []for size_row in sizes:admitted = {f: _admit(machine, size_row['width'], size_row['height'], f, steps, two_pass, task,- references=references, step_cache=step_cache)+ references=references, step_cache=step_cache, upscale=upscale)for f in range(39, lengths[-1]['frames'] + 1, 17)}estimates = {}for f, (request, _, _) in admitted.items():@@ -448,7 +452,7 @@ def build(machine, records, *, aspect='16:9', size=None, task='t2va', adapters=Frow_codes.append(code)times.append(row_times)codes.append(row_codes)- tiers[name] = dict(steps=steps, two_pass=two_pass, step_cache=step_cache, estimate_seconds=times,+ tiers[name] = dict(steps=steps, two_pass=two_pass, step_cache=step_cache, upscale=upscale, estimate_seconds=times,max_seconds=maxima, max_frames=frame_maxima, limit=limits, plan=codes)default = next((i for i, s in enumerate(sizes) if s['pixels'] == .98), 0)result = dict(version=1, status='ready',diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.pyindex acbda45..399a450 100644--- a/freevideo_engine/cli.py+++ b/freevideo_engine/cli.py@@ -119,6 +119,9 @@ def main():help='First-pass steps (default: 8, or explicit profile). Changes may reduce quality.')generate.add_argument('--refine-steps', type=int, choices=range(1, 32), default=3, metavar='1..31',help='Second-pass steps (default: 3, independent schedule). Other counts use the original tail.')+ generate.add_argument('--upscale-factor', type=float, choices=(2., 1.5, 1.2), default=2., metavar='{2,1.5,1.2}',+ help='Two-pass learned upscale factor (default 2: half-size first pass). 1.5 and 1.2 sample '+ 'a larger first pass (44%% / 69%% of the pixels) for the same output size.')upscale = generate.add_mutually_exclusive_group()upscale.add_argument('--preview', action='store_true',help='Two-pass only: stop after the half-resolution first pass, save it as a quick preview, 'diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.pyindex 4744945..d112fb3 100644--- a/freevideo_engine/comfy_bridge.py+++ b/freevideo_engine/comfy_bridge.py@@ -209,7 +209,7 @@ class WholeVideoProgress:@classmethoddef for_request(cls, machine, canvas, output_directory, *, base_steps=8,refine_steps=3, two_pass=True, preview=False, upscale=False,- encoder_prewarm=None, options=None, step_cache=None):+ encoder_prewarm=None, options=None, step_cache=None, upscale_factor=2):import platformfrom .effort_forecast import start_contextstarted, opened = time.perf_counter(), time.monotonic()@@ -224,7 +224,7 @@ class WholeVideoProgress:tracker = cls(hardware=hardware, records=records, cold_flags=flags, started=started,request=dict(canvas, base_steps=base_steps, refine_steps=refine_steps,two_pass=two_pass, flow='upscale' if upscale else 'preview' if preview else 'full',- step_cache=step_cache),+ step_cache=step_cache, upscale_factor=upscale_factor),**(options or {}))tracker.history = (output_directory, machine, opened)return tracker@@ -1180,8 +1180,11 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,force_regenerate=False, base_steps=8, refine_steps=3, comfy_metadata=None,prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None,continue_from=None, frames=None, first_frame_reference=False, voice_reference=False, hide_tail=False,- step_cache=None):+ step_cache=None, upscale_factor=2):from .tiers import STEP_CACHES+ from .two_pass import SCALES+ if upscale_factor not in SCALES:+ raise ValueError('Upscale factor must be one of ' + ', '.join('%g' % value for value in SCALES))if step_cache == 'none':step_cache = Noneif step_cache not in STEP_CACHES:@@ -1219,6 +1222,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,refine_steps = int(argument(arguments, '--refine-steps', 3))# The second pass never uses a step cache; the preview's own command keeps its flag.step_cache = argument(arguments, '--step-cache')+ if preview or upscale:+ # A preview stays the quick half-size first pass, and its upscale continues that same pass.+ upscale_factor = 2from .preview import validate_flagsvalidate_flags(preview, upscale, two_pass, base_steps)from .two_pass import validate_steps@@ -1287,6 +1293,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,'--base-steps', str(base_steps), '--refine-steps', str(refine_steps)]if step_cache is not None:command += ['--step-cache', step_cache]+ if two_pass and upscale_factor != 2:+ command += ['--upscale-factor', '%g' % upscale_factor]if frames is not None:position = command.index('--seconds')command[position:position + 2] = ['--frames', str(frames)]@@ -1325,7 +1333,7 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,whole_progress = WholeVideoProgress.for_request(machine, canvas, output_directory,base_steps=base_steps, refine_steps=refine_steps, two_pass=two_pass,preview=preview, upscale=bool(upscale), encoder_prewarm=state['encoder_prewarm'],- step_cache=None if upscale else step_cache)+ step_cache=None if upscale else step_cache, upscale_factor=upscale_factor)except Exception:# A progress estimate cannot prevent generation, even without its parameters.try:@@ -1412,7 +1420,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,sampled, output_size = sampling_canvas(generated_canvas, staged=bool(preview or upscale), media=extra.get('media'),conditioned=bool(extra.get('conditioning')))planned = plan(sampled, two_pass, 'ref2va' if anchored or pictured else task_for(extra.get('media', {})),- base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale))+ base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale),+ scale=upscale_factor)if continue_from is not None:from .continuation import ADALN_TASK, ANCHOR_ADALN_TASK, MISSING, validate_snapshot, summaryvalidate_route(task='ref2va' if anchored or pictured else task_for(extra.get('media', {})),@@ -1432,7 +1441,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,# An encoded ending carries no first frame of the film, so nothing anchors this run.anchored = Falseplanned = plan(sampled, two_pass, task_for(extra.get('media', {})),- base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale))+ base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale),+ scale=upscale_factor)if continuation is None:from .continuation import OVERLAP_FRAMESstate['continuation'] = dict(overlap_frames=OVERLAP_FRAMES,@@ -1541,7 +1551,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,from .two_pass import steps, plancompleted_steps = steps(report.get('sampling_plan'))expected_plan = plan(sampled, two_pass, report.get('profile', {}).get('engine', {}).get('task', 't2va'),- base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale))+ base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale),+ scale=upscale_factor)shown = sampledif preview:# A preview decodes its first pass at the planned smaller canvas.diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.pyindex 3d8c511..da63ee3 100644--- a/freevideo_engine/comfy_library.py+++ b/freevideo_engine/comfy_library.py@@ -1077,7 +1077,7 @@ def register():try:canvas = geometry(int(request.query['width']), int(request.query['height']),seconds=float(request.query['seconds']))- from .two_pass import plan, sampling_canvas+ from .two_pass import SCALES, plan, sampling_canvascanvas = sampling_canvas(canvas)[0]task = request.query.get('task', 't2va')_, machine = installation()@@ -1085,17 +1085,22 @@ def register():rows = await asyncio.to_thread(local_records, folder_paths.get_output_directory(), device)adapters = request.query.get('adapters') == '1'# A small canvas runs in one pass whatever the switch says. A cached- # level is keyed "<steps>:<cache>". Without a run of it, plain runs- # stand in: the first-block cache is counted at full time, since the+ # level is keyed "<steps>:<cache>", a two-pass upscale factor other+ # than 2 "<steps>x<factor>". Without a run of it, plain runs stand+ # in: the first-block cache is counted at full time, since the# planner may not keep it on this card.share = {'fbcache': 1.}- result = {name: {(str(steps) + (':' + cache if cache else '')):- estimate(rows, canvas, base_steps=steps,- two_pass=plan(canvas, enabled, task, base_steps=steps)['enabled'],- task=task, adapters=adapters, step_cache=cache, cache_share=share.get(cache))- for steps, cache in (((8, None),) if enabled else- ((8, None), (12, None), (16, None), (20, None),- (20, 'easycache-av'), (20, 'fbcache')))}++ def one(steps, cache, enabled, factor):+ sampled = plan(canvas, enabled, task, base_steps=steps, scale=factor)+ return estimate(rows, canvas, base_steps=steps, two_pass=sampled['enabled'], task=task,+ adapters=adapters, step_cache=cache, cache_share=share.get(cache),+ upscale_factor=sampled.get('scale', 2))+ result = {name: {(str(steps) + (':' + cache if cache else '') + ('x%g' % factor if factor != 2 else '')):+ one(steps, cache, enabled, factor)+ for steps, cache, factor in ([(8, None, factor) for factor in SCALES] if enabled else+ ((8, None, 2), (12, None, 2), (16, None, 2), (20, None, 2),+ (20, 'easycache-av', 2), (20, 'fbcache', 2)))}for name, enabled in (('single', False), ('two_pass', True))}return web.json_response(result, headers={'Cache-Control': 'no-store'})except (OSError, ValueError, TypeError, KeyError):diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.pyindex 87678ee..e54ffee 100644--- a/freevideo_engine/comfy_nodes.py+++ b/freevideo_engine/comfy_nodes.py@@ -49,6 +49,18 @@ def step_cache_option(value):return {'step_cache': value} if value in STEP_CACHE_OPTIONS and value != 'none' else {}+UPSCALE_OPTIONS = ('2', '1.5', '1.2') # two_pass.SCALES as the widget shows them+++def upscale_option(value):+ """Bridge keyword for the Upscale factor widget; 2, a value that is not an option, or a workflow without+ the widget adds nothing. Workflows saved before it existed hold '' in its position."""+ if isinstance(value, bool) or not isinstance(value, (str, int, float)):+ return {}+ text = value if isinstance(value, str) else '%g' % value+ return {'upscale_factor': float(text)} if text in UPSCALE_OPTIONS and text != '2' else {}++class FreeVideoGenerate(io.ComfyNode):@classmethoddef define_schema(cls):@@ -108,8 +120,10 @@ class FreeVideoGenerate(io.ComfyNode):# Last, so the widget values of saved workflows keep their positions.io.Combo.Input('step_cache', display_name='Step cache', options=list(STEP_CACHE_OPTIONS), default='none',optional=True, advanced=True,- tooltip='Reuses work between similar sampling steps to finish sooner, with a small change to the result. '- 'High uses easycache-av; Max uses fbcache.'),+ tooltip='Reuses work between similar sampling steps to finish sooner, with a small change to the result.'),+ io.Combo.Input('upscale_factor', display_name='Upscale factor', options=list(UPSCALE_OPTIONS), default='2',+ optional=True, advanced=True,+ tooltip='Two-pass only: a smaller factor starts from a larger first pass, for more detail and a longer run.'),],outputs=[io.Video.Output('video'), io.String.Output('report', display_name='Report JSON')],hidden=[io.Hidden.unique_id, io.Hidden.prompt, io.Hidden.extra_pnginfo],@@ -118,11 +132,12 @@ class FreeVideoGenerate(io.ComfyNode):@classmethoddef validate_inputs(cls, text, width, height, seconds, seed, continue_from='', frames=0, two_pass=True,- preview=False, refine_from='', base_steps=8, refine_steps=3, step_cache='none'):+ preview=False, refine_from='', base_steps=8, refine_steps=3, step_cache='none',+ upscale_factor='2'):# ComfyUI marks every input named here when a check fails, so only the checked widgets are# listed. Linked pictures, media and conditioning have no value before the run anyway.- # step_cache is named so ComfyUI skips its option list: an older saved workflow puts '' there,- # and execute samples in full for any value that is not an option.+ # step_cache and upscale_factor are named so ComfyUI skips their option lists: an older saved+ # workflow puts '' there, and execute uses no cache and the 2x upscale for a value that is not an option.refine_from = optional_text(refine_from)try:options = request_options(continue_from, node_frames(frames))@@ -158,7 +173,7 @@ class FreeVideoGenerate(io.ComfyNode):references=None, loras=None, conditioning=None, media=None, two_pass=True,force_regenerate=False, base_steps=8, refine_steps=3, preview=False, refine_from='',continue_from='', frames=0, first_frame_reference=False, voice_reference=False, hide_tail=False,- step_cache='none'):+ step_cache='none', upscale_factor='2'):from server import PromptServerfrom .comfy_chain import block_context, block_finished, report_fieldsrefine_from, continue_from = optional_text(refine_from), optional_text(continue_from)@@ -302,6 +317,7 @@ class FreeVideoGenerate(io.ComfyNode):**({'voice_reference': True} if voice_reference is True and options.get('continue_from') else {}),**({'hide_tail': True} if hide_tail is True else {}),**step_cache_option(step_cache),+ **upscale_option(upscale_factor),**({'report_extra': {'chain': report_fields(chain)}} if chain is not None else {}))relative = output.relative_to(output_root)report = output.with_suffix('.request.json').read_text(encoding='utf-8')diff --git a/freevideo_engine/comfy_share.py b/freevideo_engine/comfy_share.pyindex 3421d24..c887878 100644--- a/freevideo_engine/comfy_share.py+++ b/freevideo_engine/comfy_share.py@@ -63,6 +63,9 @@ def details(root, identity):from .tiers import STEP_CACHESif plan.get('step_cache') in STEP_CACHES[1:]:result['sampling_plan']['step_cache'] = plan['step_cache']+ from .two_pass import SCALES+ if plan.get('enabled') is True and plan.get('scale') in SCALES[1:]:+ result['sampling_plan']['scale'] = plan['scale']result['id'] = identityresult['graph'] = saved_graph(path)return resultdiff --git a/freevideo_engine/effort_forecast.py b/freevideo_engine/effort_forecast.pyindex 22dc747..f253c1b 100644--- a/freevideo_engine/effort_forecast.py+++ b/freevideo_engine/effort_forecast.py@@ -86,6 +86,9 @@ def timing_record(report, gpu_uuid, system, *, stage_details=True):if cache is not None:# Rows without the key are plain runs, as every run before the caches was.record['step_cache'] = cache+ if plan.get('enabled') and plan.get('scale', 2) != 2:+ # Rows without the key upscaled 2x, as every two-pass run before the factor was.+ record['upscale_factor'] = plan['scale']if not stage_details:# The slider history carries no flow marker, and a preview (one pass)# is never a whole-request sample: estimate() would read its missing@@ -155,17 +158,25 @@ def report_step_cache(report):def estimate(records, canvas, *, base_steps=8, refine_steps=3, two_pass=True, task='t2va', adapters=False,- step_cache=None, cache_share=None):+ step_cache=None, cache_share=None, upscale_factor=2):"""Whole-request seconds from local runs of this shape.Runs with the requested step cache come first. Without one, plain runs standin with their first pass scaled by `cache_share` (tiers.sampling_share bydefault) and a wider range; a cached run never stands in for a plain request.+ A two-pass run with another upscale factor stands in the same way, its+ sampling scaled by tiers.upscale_share."""from .two_pass import validate_steps- from .tiers import sampling_share+ from .tiers import sampling_share, upscale_sharevalidate_steps(base_steps, refine_steps, two_pass)share = sampling_share(step_cache) if cache_share is None else cache_share+ if two_pass and upscale_factor != 2:+ # The factor this canvas really runs: a small canvas samples both passes at its own size.+ from .two_pass import plan+ upscale_factor = plan(dict(width=canvas['width'], height=canvas['height'], frames=canvas['frames']), True,+ base_steps=base_steps, refine_steps=refine_steps, scale=upscale_factor).get('scale', 2)+ upscale_factor = upscale_factor if two_pass else 2candidates = []for row in records:if (row.get('flow', 'full') != 'full' or row['task'] != task or row['adapters'] != adapters@@ -194,6 +205,11 @@ def estimate(records, canvas, *, base_steps=8, refine_steps=3, two_pass=True, taswitched = Trueif two_pass and row['two_pass'] == two_pass:seconds += (refine_steps - row['refine_steps']) * row['passes'][1]['incremental']+ factor = row.get('upscale_factor', 2)+ if factor != upscale_factor:+ sampled = sum(part['seconds'] for part in row['passes'])+ seconds += (upscale_share(upscale_factor) / upscale_share(factor) - 1) * sampled+ switched = Trueif positive(seconds):candidates.append((seconds, row, switched))if not candidates:diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex bc5d26b..9b921ec 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -8,6 +8,7 @@ import sysfrom .long_paths import io_path, plain_textfrom .diagnostics import Redactorfrom .tiers import STEP_CACHES, TIERS, on_mac, table_level+from .two_pass import SCALESSTEP_OUTPUT = '\n\nFull step output:\n'@@ -71,9 +72,10 @@ def sampling_table_details(value):and type(details['missing_bytes']) is int and details['missing_bytes'] > 0and type(details['decimal_sizes']) is bool and isinstance(details['available'], list)and all(type(i) is int and 0 <= i <= 3 for i in details['available'])- and details.get('step_cache') in STEP_CACHES):+ and details.get('step_cache') in STEP_CACHES and details.get('scale', 2) in SCALES):return {key: details[key] for key in- ('base_steps', 'two_pass', 'refine_steps', 'missing_bytes', 'available', 'decimal_sizes', 'step_cache')+ ('base_steps', 'two_pass', 'refine_steps', 'missing_bytes', 'available', 'decimal_sizes', 'step_cache',+ 'scale')if key in details}except (ValueError, KeyError, TypeError):pass@@ -88,7 +90,7 @@ def sampling_table_failure(value, *, zh=False):language = 1 if zh else 0# Tables follow the step count; the cache tells high from max at 20 steps.level = table_level(details['base_steps'], details['two_pass'], details['refine_steps'],- details.get('step_cache'), on_mac())+ details.get('step_cache'), on_mac(), details.get('scale', 2))index = list(TIERS).index(level) if level else Nonenames = [('“%s”' if zh else '%s') % QUALITY_LEVELS[i][language] for i in sorted(set(details['available']))]available = ''diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex b4d0bc5..3d79a00 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -347,6 +347,12 @@ def run(args):raise+def upscale_factor(args):+ """The two-pass upscale factor a command asked for: 2 (the original half-size first pass) unless given."""+ factor = getattr(args, 'upscale_factor', None)+ return 2 if factor in (None, 2) else factor++def dialogue_reason(prompt):"""Shared eligibility for opening-voice references and hidden dialogue tails."""from .prompt_vlm.rules import split_source@@ -575,7 +581,8 @@ def _run(args):if continuation is not None:from .two_pass import plan as continuation_planvalidate_route(task=profile['engine'].get('task', 't2va'), anchor=anchored)- planned = continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps)+ planned = continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps,+ scale=upscale_factor(args))if two_pass and not planned['enabled'] and base_steps != 8:raise ValueError(planned['reason'] + ' A continuation needs two-pass generation.')continuation_first = planned['first']@@ -847,7 +854,7 @@ def _run(args):from .two_pass import plan as plan_sampling, ensure_checkpointsampling_plan = plan_sampling(canvas, two_pass, profile['engine'].get('task', 't2va'),base_steps=base_steps, refine_steps=refine_steps,- staged=bool(preview or refine_source))+ staged=bool(preview or refine_source), scale=upscale_factor(args))report['sampling_plan'] = sampling_planif continuation is not None:validate_route(task=profile['engine'].get('task', 't2va'), anchor=anchored,diff --git a/freevideo_engine/keyframes.py b/freevideo_engine/keyframes.pyindex ed3131a..35ce093 100644--- a/freevideo_engine/keyframes.py+++ b/freevideo_engine/keyframes.py@@ -11,9 +11,13 @@ def first_pass_conditions(conditions, target, canvas):ComfyUI conditioning, where the source pixels are no longer available."""from torch.nn import functional as F- from .two_pass import plan- sampling = plan(target, staged=True)- if any(canvas[key] != sampling['first'][key] for key in ('width', 'height', 'frames')):+ from .two_pass import plan, SCALES+ # The first-pass canvas tells the upscale factor apart: each factor has its own size.+ for scale in SCALES:+ sampling = plan(target, staged=True, scale=scale)+ if all(canvas[key] == sampling['first'][key] for key in ('width', 'height', 'frames')):+ break+ else:raise ValueError('Keyframe resize must match the planned first-pass canvas')anchors, latents = conditionsleft, top = (sampling['crop'][key] // 16 for key in ('left', 'top'))diff --git a/freevideo_engine/macos_generate.py b/freevideo_engine/macos_generate.pyindex eedc4be..358caf8 100644--- a/freevideo_engine/macos_generate.py+++ b/freevideo_engine/macos_generate.py@@ -167,8 +167,9 @@ def run(args):from .two_pass import sampling_canvascanvas, output_size = sampling_canvas(canvas, staged=bool(preview or refine_source), media=media,conditioned=bool(args.conditioning))+ from .generate import upscale_factorsampling = plan(canvas, args.two_pass, task, base_steps=args.base_steps or 8, refine_steps=args.refine_steps,- staged=bool(preview or refine_source))+ staged=bool(preview or refine_source), scale=upscale_factor(args))from .paths import base_path, checkpoint_pathbase = str(Path(args.base or base_path()).resolve())adapters = [row for row in media.get('loras', []) if row['strength'] != 0]diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.pyindex 3e5a15e..5ce24cc 100644--- a/freevideo_engine/macos_runtime.py+++ b/freevideo_engine/macos_runtime.py@@ -619,7 +619,7 @@ class Engine:def generate(self, conditioning, seed, *, width, height, frames, two_pass=True, refine_steps=3,upscaler_checkpoint=None, first_pass_saved=None, reuse_weights=False,- refinement_resident_bytes=None, phase_changed=None, staged=False):+ refinement_resident_bytes=None, phase_changed=None, staged=False, scale=2):"""Optional cross-pass weight lifetime, isolated to this one request.Product admission remains separate. Retention obeys each sample's live@@ -636,7 +636,7 @@ class Engine:options = dict(width=width, height=height, frames=frames, two_pass=two_pass,refine_steps=refine_steps, upscaler_checkpoint=upscaler_checkpoint,first_pass_saved=first_pass_saved, phase_changed=phase_changed,- refinement_resident_bytes=refinement_resident_bytes, staged=staged)+ refinement_resident_bytes=refinement_resident_bytes, staged=staged, scale=scale)if getattr(self, '_reuse_sampling_weights', False) or getattr(self, '_shared_residency', None) is not None:raise RuntimeError('Native sampling weight lifetimes cannot overlap')if not reuse_weights:@@ -654,7 +654,7 @@ class Engine:def _generate(self, conditioning, seed, *, width, height, frames, two_pass=True, refine_steps=3,upscaler_checkpoint=None, first_pass_saved=None,- refinement_resident_bytes=None, phase_changed=None, staged=False):+ refinement_resident_bytes=None, phase_changed=None, staged=False, scale=2):"""Use the shared canvas/schedule, including the original audio clock.Single-pass behavior remains explicit; memory pressure never disables@@ -668,7 +668,7 @@ class Engine:if self.canvas is not None and any(canvas[k] != self.canvas[k] for k in ('width', 'height', 'frames')):raise ValueError('Native generation differs from its loaded target canvas')sampling = plan(canvas, enabled=two_pass, task=self.task,- base_steps=self.steps, refine_steps=refine_steps, staged=staged)+ base_steps=self.steps, refine_steps=refine_steps, staged=staged, scale=scale)if phase_changed is not None:phase_changed('first-pass')video, audio, first = self.sample(conditioning, seed, **sampling['first'],diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.pyindex d51a3e8..ef90112 100644--- a/freevideo_engine/macos_stages.py+++ b/freevideo_engine/macos_stages.py@@ -381,7 +381,7 @@ def worker(value):frames=value['canvas']['frames'], two_pass=True, refine_steps=sampling['refine_steps'],reuse_weights=True, refinement_resident_bytes=admission['refinement_resident_bytes'],first_pass_saved=first_saved, phase_changed=changed,- staged=sampling.get('staged', False))+ staged=sampling.get('staged', False), scale=sampling.get('scale', 2))result.update(sampling_passes=measured['sampling_passes'],shared_sampling_residency=measured['shared_sampling_residency'],latent_upscale=measured['latent_upscale'], sampling_phase='latent-save')diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.pyindex faa7239..83bc223 100644--- a/freevideo_engine/policy.py+++ b/freevideo_engine/policy.py@@ -607,7 +607,8 @@ def feasible_alternatives(hardware, canvas, **options):from .two_pass import plansampling = canvas['sampling_plan']candidate['sampling_plan'] = plan(candidate, sampling['enabled'], canvas.get('task', 't2va'),- base_steps=sampling['base_steps'], refine_steps=sampling['refine_steps'] or 3)+ base_steps=sampling['base_steps'], refine_steps=sampling['refine_steps'] or 3,+ scale=sampling.get('scale', 2))choose(hardware, **dict(options, canvas=candidate))return Trueexcept (ResourceBudgetError, ValueError):diff --git a/freevideo_engine/precompile.py b/freevideo_engine/precompile.pyindex 7495902..41da313 100644--- a/freevideo_engine/precompile.py+++ b/freevideo_engine/precompile.py@@ -83,6 +83,9 @@ def recent_shapes(history, limit=SHAPES):frames=geometry.get('frames'), two_pass=bool(plan.get('enabled')),base_steps=plan.get('base_steps', geometry.get('steps', 8)),refine_steps=plan.get('refine_steps') or 3)+ if plan.get('enabled') and plan.get('scale', 2) != 2:+ # Only another factor adds the key, so the shapes of 2x requests stay as they were.+ shape['upscale_factor'] = plan['scale']if not all(type(shape[name]) is int and shape[name] > 0 for name in ('width', 'height', 'frames', 'base_steps')):continuekey = json.dumps(shape, sort_keys=True)@@ -122,7 +125,8 @@ def plan_request(machine, shape, history, identity):profile['engine'].update(steps=shape['base_steps'], task=shape['task'],base=machine['base'], checkpoint=machine['checkpoint'])sampling_plan = plan(canvas, shape['two_pass'], shape['task'],- base_steps=shape['base_steps'], refine_steps=shape['refine_steps'])+ base_steps=shape['base_steps'], refine_steps=shape['refine_steps'],+ scale=shape.get('upscale_factor', 2))if sampling_plan['enabled'] or sampling_plan['version'] == 2:canvas['sampling_plan'] = sampling_planprofile = tuned(profile, machine, hardware, canvas, sampling_plan, shape['text_tokens'][0])diff --git a/freevideo_engine/request_assets.py b/freevideo_engine/request_assets.pyindex 624695b..82e8ddb 100644--- a/freevideo_engine/request_assets.py+++ b/freevideo_engine/request_assets.py@@ -28,7 +28,7 @@ def _sampling(root, machine, request):canvas = sampling_canvas(geometry(request['width'], request['height'], seconds=request['seconds']))[0]two_pass = bool(request.get('two_pass', True))sampled = plan(canvas, two_pass, task, base_steps=request.get('base_steps', 8),- refine_steps=request.get('refine_steps', 3))+ refine_steps=request.get('refine_steps', 3), scale=request.get('upscale_factor', 2))rows = sampling_assets.pending(root, machine, sampled, task)items = []if rows:diff --git a/freevideo_engine/sampling_assets.py b/freevideo_engine/sampling_assets.pyindex c860988..1ef47a8 100644--- a/freevideo_engine/sampling_assets.py+++ b/freevideo_engine/sampling_assets.py@@ -383,7 +383,8 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, envirorefine_steps=sampling.get('refine_steps', 0), missing_bytes=total,available=available_levels(cache, shared, manifest, kind, catalog),decimal_sizes=sys.platform == 'darwin',- **({'step_cache': sampling['step_cache']} if sampling.get('step_cache') else {}))+ **({'step_cache': sampling['step_cache']} if sampling.get('step_cache') else {}),+ **({'scale': sampling['scale']} if sampling.get('scale', 2) != 2 else {}))raise SamplingTableUnavailable(details, failure.cause) from failure.causeif failure is not None:raise failurediff --git a/freevideo_engine/stage_estimate.py b/freevideo_engine/stage_estimate.pyindex b2f597c..884e585 100644--- a/freevideo_engine/stage_estimate.py+++ b/freevideo_engine/stage_estimate.py@@ -159,11 +159,15 @@ def canvases(r):first = dict(full, width=32*uw*m, height=32*uh*m)else:first = dict(full)- # two_pass.plan() runs a first pass under SMALL_FIRST_PASS_PIXELS (138,240) as one pass at the- # target size, except when the first pass itself is wanted (a preview or the upscale of one).+ # two_pass.plan() samples a first pass under SMALL_FIRST_PASS_PIXELS (138,240) at the target+ # size, except when the first pass itself is wanted (a preview or the upscale of one).if (not sg.get('first') and two and r.get('flow') not in ('preview', 'upscale')and first != full and first['width']*first['height'] < 138240):return full, full, full+ if not sg.get('first') and two and min(w, h) >= 512 and r.get('upscale_factor', 2) != 2:+ # A smaller factor starts larger; the size check above is on the 2x first pass, as in plan().+ from .two_pass import first_canvas+ first = first_canvas(full, r['upscale_factor'])[0]second = dict(full, **(sg.get('second') or {}))decode = first if r.get('flow') == 'preview' else fullreturn first, second, decodediff --git a/freevideo_engine/tiers.py b/freevideo_engine/tiers.pyindex df19dc6..c6d4439 100644--- a/freevideo_engine/tiers.py+++ b/freevideo_engine/tiers.py@@ -4,22 +4,23 @@ Every entry (editor, Agent API, ComfyUI capabilities, estimates, docs) readsits level -> plan mapping from here; tests/test_tiers.py checks the entriesthat cannot import it (web JS, prose docs) against this table.-- light: two-pass, 8 + 3 steps.-- medium: one pass of 8 steps.+- light: two-pass, 8 + 3 steps, first pass at half size (2x learned upscale).+- medium: two-pass, 8 + 3 steps, a larger first pass (`upscale`, below 2).- high: one pass of 20 steps with the audio-video EasyCache.-- max: one pass of 20 steps with the first-block cache. The planner keeps that- cache only where the card has room for it; otherwise the request samples all- 20 steps in full (engine.json/debug record the cache actually used).--Only a two-pass level samples a second time. Single-pass levels carry-REFINE_STEPS only as the neutral value the `refine_steps` field needs; it is-never run for them. `step_cache` is the engine's cache key: None,-'easycache-av' (audio-video EasyCache) or 'fbcache' (first-block cache).--On Mac (MPS) only the audio-video EasyCache is ported: high is the same plan-as everywhere else and max is one pass of 20 steps without a cache (TIERS_MAC).-Results made before that, one pass of 16 steps without a cache, still count as-high (LEGACY_MAC_HIGH).+- max: one pass of 20 steps, every step sampled.++A level in one pass always samples 20 steps; fewer steps come only from a+user's own setting. Only a two-pass level samples a second time. Single-pass+levels carry REFINE_STEPS only as the neutral value the `refine_steps` field+needs; it is never run for them, and their `upscale` is 2 (no factor).+`step_cache` is the engine's cache key: None, 'easycache-av' (audio-video+EasyCache) or 'fbcache' (first-block cache, no level uses it; a request may+still ask for it). `upscale` is the two-pass learned upscale factor+(two_pass.SCALES): change medium's number here, and everything follows.++Mac (MPS) runs the same levels (TIERS_MAC). Results made before the+audio-video EasyCache was ported there, one pass of 16 steps without a cache,+still count as high (LEGACY_MAC_HIGH)."""import sys@@ -27,13 +28,13 @@ REFINE_STEPS = 3STEP_CACHES = (None, 'easycache-av', 'fbcache')TIERS = {- 'light': dict(steps=8, two_pass=True, step_cache=None),- 'medium': dict(steps=8, two_pass=False, step_cache=None),- 'high': dict(steps=20, two_pass=False, step_cache='easycache-av'),- 'max': dict(steps=20, two_pass=False, step_cache='fbcache'),+ 'light': dict(steps=8, two_pass=True, step_cache=None, upscale=2),+ 'medium': dict(steps=8, two_pass=True, step_cache=None, upscale=1.5),+ 'high': dict(steps=20, two_pass=False, step_cache='easycache-av', upscale=2),+ 'max': dict(steps=20, two_pass=False, step_cache=None, upscale=2),}-TIERS_MAC = dict(TIERS, max=dict(steps=20, two_pass=False, step_cache=None))-LEGACY_MAC_HIGH = dict(steps=16, two_pass=False, step_cache=None)+TIERS_MAC = TIERS+LEGACY_MAC_HIGH = dict(steps=16, two_pass=False, step_cache=None, upscale=2)# Sampling time of a cached pass as a share of the same pass without a cache,# for estimates that have no run with that cache yet. B200, 20 s clips@@ -49,6 +50,14 @@ LEGACY_MAC_HIGH = dict(steps=16, two_pass=False, step_cache=None)# is plain 20 steps.SAMPLING_SHARE = {None: 1., 'easycache-av': .64, 'fbcache': .9}+# Sampling time (both passes) of a two-pass request with this upscale factor,+# as a share of the same request at 2x, for estimates without a run of that+# factor. 1.5: H200, 1344x768 20 s, 221.5 s against 177.8 s+# (/mnt/fvbench/eng5/tiers/REPORT.md section 2); the stage model gives 1.25-1.30+# from 10 to 20 s on 8-141 GiB cards. 1.2: the stage model only (1.62-1.78),+# not yet measured.+UPSCALE_SHARE = {2: 1., 1.5: 1.27, 1.2: 1.72}+def on_mac():"""FreeVideo runs on Apple's MPS backend on every Mac."""@@ -69,26 +78,35 @@ def step_cache(name, mac=False):return table(mac)[name]['step_cache']-def name_for(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, mac=False):- """The level with exactly this plan, or None for custom sampling."""+def upscale_factor(name, mac=False):+ """The learned upscale factor of a two-pass level; 2 for every other level."""+ return table(mac)[name]['upscale']+++def name_for(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, mac=False, upscale=2):+ """The level with exactly this plan, or None for custom sampling.++ `upscale` tells the two-pass levels apart; a single pass has no factor."""+ upscale = upscale if two_pass else 2found = next((name for name, tier in table(mac).items()if tier['steps'] == steps and tier['two_pass'] == two_pass- and (not two_pass or refine_steps == REFINE_STEPS) and tier['step_cache'] == step_cache), None)- if found is None and mac and (steps, two_pass, step_cache) == tuple(LEGACY_MAC_HIGH.values()):+ and (not two_pass or refine_steps == REFINE_STEPS) and tier['step_cache'] == step_cache+ and tier['upscale'] == upscale), None)+ if found is None and mac and (steps, two_pass, step_cache, upscale) == tuple(LEGACY_MAC_HIGH.values()):return 'high'return found-def table_level(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, mac=False):+def table_level(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, mac=False, upscale=2):"""The level whose sampling table a plan needs, for naming a missing download.Tables follow the step count only. Prefer the exact level (the cache tells- high from max at 20 steps), then the other platform's table (20 steps- without a cache is "max", as on Mac; 16 steps is the earlier Mac "high"), then the first- level with that step count.+ high from max at 20 steps), then the other platform's table (16 steps is+ the earlier Mac "high"), then the first level with that step count (light+ for 8 + 3, whatever the upscale factor)."""- found = name_for(steps, two_pass, refine_steps, step_cache, mac) or name_for(- steps, two_pass, refine_steps, step_cache, not mac)+ found = name_for(steps, two_pass, refine_steps, step_cache, mac, upscale) or name_for(+ steps, two_pass, refine_steps, step_cache, not mac, upscale)return found or next((name for name, tier in TIERS.items()if tier['steps'] == steps and tier['two_pass'] == two_passand (not two_pass or refine_steps == REFINE_STEPS)), None)@@ -97,3 +115,8 @@ def table_level(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, macdef sampling_share(cache):"""Estimated sampling time with this effective cache, as a share of the plain pass."""return SAMPLING_SHARE.get(cache, 1.)+++def upscale_share(factor):+ """Estimated two-pass sampling time with this upscale factor, as a share of 2x."""+ return UPSCALE_SHARE.get(factor, 1.)diff --git a/freevideo_engine/two_pass.py b/freevideo_engine/two_pass.pyindex d32bb40..12dec3b 100644--- a/freevideo_engine/two_pass.py+++ b/freevideo_engine/two_pass.py@@ -37,7 +37,8 @@ def one_pass_note(base_steps):# A first pass below this many pixels is too small for the learned lift: about# a third of the clips at 768x512 and every clip at 512x512 had coloured-# bursts, and none did from 480x288 (960x544) upward. Those sizes run in one pass.+# bursts, and none did from 480x288 (960x544) upward. Those sizes sample both+# passes at the target size, without the lift.SMALL_FIRST_PASS_PIXELS = 138240@@ -98,18 +99,42 @@ def sampling_canvas(canvas, *, staged=False, media=None, conditioned=False):return render_canvas(canvas)-def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, staged=False):+# Learned-upscale factors a level may ask for. 2 is the original half-size+# first pass; 1.5 and 1.2 sample a larger first pass (44% and 69% of the final+# pixels: 896x512 and 1120x640 for 1344x768) and lift it by that factor.+SCALES = (2, 1.5, 1.2)+++def first_canvas(target, scale):+ """The first-pass canvas and its lift for a factor below 2: multiples of 32 whose+ lift by `scale` is also a multiple of 32 and covers the target (center-cropped)."""+ from fractions import Fraction+ factor = Fraction(scale).limit_denominator(10) # exactly 3/2 or 6/5, not the binary float++ def side(length):+ units = -(-Fraction(length, 32) // factor) # ceil(length / 32 / factor)+ units = -(-units // factor.denominator) * factor.denominator # the lift stays a multiple of 32+ return 32 * int(units), int(32 * units * factor)+ (w, lift_w), (h, lift_h) = side(target['width']), side(target['height'])+ return dict(width=w, height=h, frames=target['frames']), dict(width=lift_w, height=lift_h, frames=target['frames'])+++def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, staged=False, scale=2):"""Align the smaller canvas, lift, center-crop, then refine at the target.Odd multiples of 32 need up to 32 extra pixels before the latent crop.Small canvases use a smaller factor or same-size refinement. A first pass- below SMALL_FIRST_PASS_PIXELS is replaced by one pass at the target size,- unless the first pass itself is wanted (a preview or its upscale: staged).- Memory pressure never changes this math.+ below SMALL_FIRST_PASS_PIXELS is sampled at the target size instead (same-size+ refinement), unless the first pass itself is wanted (a preview or its upscale: staged).+ Memory pressure never changes this math. `scale` below 2 samples a larger+ first pass (SCALES) on canvases of at least 512 on the short side; 2 is the+ original plan, byte for byte."""from .geometry import geometryfrom .media_request import TASKSvalidate_steps(base_steps, refine_steps, enabled)+ if scale not in SCALES:+ raise ValueError('Two-pass upscale factor must be one of ' + ', '.join('%g' % value for value in SCALES))if task not in TASKS:raise ValueError('Unsupported two-pass conditioning task: ' + str(task))target = geometry(canvas['width'], canvas['height'], frames=canvas['frames'])@@ -127,6 +152,8 @@ def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, sta# A preview and its upscale keep the first pass they were made with; the# receipt says so, because a replay without the flag would take the one-pass rule.result['staged'] = True+ if min(target['width'], target['height']) < 512:+ scale = 2 # a small canvas keeps its own factor belowif min(target['width'], target['height']) >= 512:first = dict(width=((target['width'] + 63) // 64) * 32,height=((target['height'] + 63) // 64) * 32, frames=target['frames'])@@ -139,16 +166,22 @@ def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, stamultiple = max((divisor + 1) // 2, (8 + unit_w - 1) // unit_w, (8 + unit_h - 1) // unit_h)first = dict(width=32 * unit_w * multiple, height=32 * unit_h * multiple, frames=target['frames'])lift = dict(shape)- crop = dict(left=(lift['width'] - target['width']) // 2,- top=(lift['height'] - target['height']) // 2,- width=target['width'], height=target['height'])upscaling = first != liftif upscaling and first['width'] * first['height'] < SMALL_FIRST_PASS_PIXELS:- if not staged:- single = plan(canvas, False, task, base_steps=base_steps)- return dict(single, requested=True,- reason='Small canvas: one pass at the target size.')- result['staged'] = True+ # Judged on the 2x first pass, so a smaller factor never samples less than 2x does.+ if staged:+ result['staged'] = True+ else:+ first = lift = dict(shape)+ upscaling, scale = False, 2+ if upscaling and scale != 2:+ first, lift = first_canvas(target, scale)+ if not upscaling:+ crop = dict(left=0, top=0, width=target['width'], height=target['height'])+ else:+ crop = dict(left=(lift['width'] - target['width']) // 2,+ top=(lift['height'] - target['height']) // 2,+ width=target['width'], height=target['height'])result.update(enabled=True, mode='vdn%d-lbh-tail%d' % (base_steps, refine_steps),refine_steps=refine_steps, total_steps=base_steps + refine_steps,first=first, second=shape, upscale_target=lift, crop=crop,@@ -163,6 +196,10 @@ def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, staresult.update(version=3, mode='vdn%d-lbh-community3' % base_steps,refine_schedule=COMMUNITY, video_sigmas=list(VIDEO_SIGMAS),reason='%d steps on a smaller canvas, learned latent upscale, then three independent refinement steps.' % base_steps)+ if scale != 2 and upscaling:+ # Recorded only off the original factor, so 2x plans (and their cache keys) are unchanged.+ result.update(scale=scale, mode=result['mode'] + '-x%g' % scale,+ reason=result['reason'].replace('learned latent upscale', 'learned %gx latent upscale' % scale))if not upscaling:result['reason'] = 'Small canvas: %d steps and %d refinement steps at the same target size, without upscaling.' % (base_steps, refine_steps)return resultdiff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.pyindex f190ad3..b7e1269 100644--- a/freevideo_engine/worker.py+++ b/freevideo_engine/worker.py@@ -95,7 +95,8 @@ def generate(request, resident=None):request['engine_options'].get('task', 't2va'),base_steps=request['engine_options'].get('steps', 8),refine_steps=request['sampling_plan']['refine_steps'] if request['sampling_plan']['enabled'] else 3,- staged=request['sampling_plan'].get('staged', False))+ staged=request['sampling_plan'].get('staged', False),+ scale=request['sampling_plan'].get('scale', 2))if request['sampling_plan'] != expected:raise ValueError('Sampling plan does not match the requested canvas and task')metrics['sampling_plan'] = expecteddiff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjsindex bd4a878..65fe2b1 100644--- a/scripts/test_freevideo_entry.mjs+++ b/scripts/test_freevideo_entry.mjs@@ -196,7 +196,8 @@ test('main browser entry registers both views and preserves node hooks', async t['frames', 'Total frames', '帧数', 141],['first_frame_reference', 'First-frame reference', '首帧参考', true, '减小漂移'],['step_cache', 'Step cache', '步间缓存', 'none',- '复用相近采样步之间的计算,更快完成,结果会有细微变化。精细档用 easycache-av,极致档用 fbcache。'],+ '复用相近采样步之间的计算,更快完成,结果会有细微变化。'],+ ['upscale_factor', 'Upscale factor', '放大倍数', '2', '二次采样时成片相对首遍的放大倍数。'],['voice_reference', 'Voice reference', 'Voice reference', true],['hide_tail', 'Hide dialogue tail', 'Hide dialogue tail', true],];diff --git a/web/capability_view.js b/web/capability_view.jsindex ec2e6b8..524ce7e 100644--- a/web/capability_view.js+++ b/web/capability_view.js@@ -1,5 +1,5 @@import { referenceItems } from './prompt_references.js';-import { stepCacheOf } from './sampling_effort.js';+import { stepCacheOf, upscaleOf } from './sampling_effort.js';const PRESETS = [.5, .75, .98, 1.5, 2];const COLUMN_SPACING = 'equal'; // 'equal' or 'width'@@ -45,7 +45,7 @@ export function aboutTime(seconds, t) {// documented task fallback, rather than pretending the known subset is all of it.export function capabilityContext(node, state) {if (linked(node, 'conditioning') || linked(node, 'width') || linked(node, 'height')- || ['base_steps', 'refine_steps', 'two_pass', 'step_cache'].some(name => linked(node, name))) return null;+ || ['base_steps', 'refine_steps', 'two_pass', 'step_cache', 'upscale_factor'].some(name => linked(node, name))) return null;let items, assets;try { items = referenceItems(node); assets = JSON.parse(value(upstream(node, 'media'), 'assets') || '[]'); }catch { return null; }@@ -77,15 +77,17 @@ export function capabilityContext(node, state) {return query.toString();}-// The grid's level with exactly this plan; a step cache tells High from Max at 20 steps.-const gridTier = (grid, steps, twoPass, refine, stepCache) => Object.values(grid.tiers || {}).find(v => v.steps === steps- && v.two_pass === twoPass && (!v.two_pass || refine === 3) && stepCacheOf(v.step_cache) === stepCacheOf(stepCache));+// The grid's level with exactly this plan; a step cache tells High from Max at 20 steps, the+// upscale factor Light from Medium (a row without one is 2x).+const gridTier = (grid, steps, twoPass, refine, stepCache, upscale = 2) => Object.values(grid.tiers || {}).find(v => v.steps === steps+ && v.two_pass === twoPass && (!v.two_pass || refine === 3) && stepCacheOf(v.step_cache) === stepCacheOf(stepCache)+ && (!v.two_pass || upscaleOf(v.upscale) === upscaleOf(upscale)));export function capabilitySurface(grid, state) {if (grid?.version !== 1 || grid.status !== 'ready' || typeof grid.revision !== 'string' || !grid.machine?.system|| /darwin|mac|apple/i.test(grid.machine.system)|| !Array.isArray(grid.sizes) || !grid.sizes.length || !Array.isArray(grid.lengths)) return null;- const tier = gridTier(grid, state.steps, state.twoPass, state.refine, state.stepCache);+ const tier = gridTier(grid, state.steps, state.twoPass, state.refine, state.stepCache, state.upscale);if (!tier || !Array.isArray(tier.estimate_seconds) || !Array.isArray(tier.max_seconds)) return null;const lengths = grid.lengths.map(l => l.seconds);if (!lengths.length || lengths.some((s, i) => !Number.isInteger(s) || s < 2 || (i && s <= lengths[i - 1]))) return null;@@ -245,7 +247,7 @@ export function createCapabilityView({node, api, t, getState, onPick, onEstimatefunction paint(animate = false) {if (!surface || !opened || element.hidden || !plot.clientWidth) return;const dpr = Math.max(1, window.devicePixelRatio || 1), width = Math.round(plot.clientWidth * dpr), height = Math.round(plot.clientHeight * dpr);- const key = `${grid.revision}:${getState().steps}:${getState().twoPass}:${stepCacheOf(getState().stepCache)}:${width}:${height}:${query}`;+ const key = `${grid.revision}:${getState().steps}:${getState().twoPass}:${stepCacheOf(getState().stepCache)}:${upscaleOf(getState().upscale)}:${width}:${height}:${query}`;if (key === drawn) { current(); return; }drawn = key;if (animate && canvas.width && !matchMedia('(prefers-reduced-motion: reduce)').matches) {@@ -375,9 +377,9 @@ export function createCapabilityView({node, api, t, getState, onPick, onEstimateapi.addEventListener('freevideo_capabilities', changed);const outside = event => { if (!plot.contains(event.target)) hideHover(); };node && window.addEventListener('pointerdown', outside);- return {element, update, estimate(steps, twoPass, refine, stepCache = null) {+ return {element, update, estimate(steps, twoPass, refine, stepCache = null, upscale = 2) {if (!grid || !surface) return '';- const tier = gridTier(grid, steps, twoPass, refine, stepCache);+ const tier = gridTier(grid, steps, twoPass, refine, stepCache, upscale);const i = grid.sizes.findIndex(s => s.width === Number(value(node, 'width')) && s.height === Number(value(node, 'height')));const j = grid.lengths.findIndex(l => l.seconds === Number(value(node, 'seconds')));const seconds = tier?.estimate_seconds?.[i]?.[j];diff --git a/web/chain_support.js b/web/chain_support.jsindex 94ab4f2..218e024 100644--- a/web/chain_support.js+++ b/web/chain_support.js@@ -1,6 +1,6 @@// Pure helpers the creative panel's long-video planning shares with the editor store; kept out of// editor_store.js so the panel does not load the editing implementation.-import { stepCacheOf } from './sampling_effort.js';+import { stepCacheOf, upscaleOf } from './sampling_effort.js';const clockDefault = {now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id)};export const chainRoute = (id, action) => '/freevideo/chain' + (id ? '/' + encodeURIComponent(id) : '') + (action ? '/' + action : '');@@ -39,8 +39,10 @@ function capabilityTier(reply, settings) {if (!tiers || typeof tiers !== 'object') return reply;if (tiers[settings?.tier]) return tiers[settings.tier];const steps = Number(settings?.base_steps), twoPass = !!settings?.two_pass, cache = stepCacheOf(settings?.step_cache);+ const factor = twoPass ? upscaleOf(settings?.upscale_factor) : 2;return Object.values(tiers).find(tier => tier.steps === steps && tier.two_pass === twoPass- && (!twoPass || Number(settings?.refine_steps) === 3) && stepCacheOf(tier.step_cache) === cache) || {};+ && (!twoPass || Number(settings?.refine_steps) === 3) && stepCacheOf(tier.step_cache) === cache+ && (tier.two_pass ? upscaleOf(tier.upscale) : 2) === factor) || {};}export function capabilityPoints(reply, {width, height, settings = {}}) {const tier = capabilityTier(reply, settings);diff --git a/web/editor_entry.js b/web/editor_entry.jsindex 685c568..0a576e2 100644--- a/web/editor_entry.js+++ b/web/editor_entry.js@@ -11,7 +11,7 @@ function editorPanel(node) {const values = Object.fromEntries((node.widgets || []).filter(widget => widget.name).map(widget => [widget.name, widget.value]));return {node: node.id, width: values.width, height: values.height, text: values.text || '', settings: Object.fromEntries(Object.entries({two_pass: values.two_pass, base_steps: values.base_steps, refine_steps: values.refine_steps,- step_cache: values.step_cache, seed: values.seed, sampling_effort: values.sampling_effort}).filter(([, value]) => value !== undefined)),+ step_cache: values.step_cache, upscale_factor: values.upscale_factor, seed: values.seed, sampling_effort: values.sampling_effort}).filter(([, value]) => value !== undefined)),references: mediaReferences(node),async snapshot() {if (node.freevideoEditorLooping?.()) throw new Error('loop_active');diff --git a/web/error_panel.js b/web/error_panel.jsindex d3c6735..c445225 100644--- a/web/error_panel.js+++ b/web/error_panel.js@@ -1,6 +1,6 @@// Shared by the Studio and graph view. Text only; never render exception HTML.import {detectBrowserExtension, browserExtensionAdvice, extensionSteps} from './browser_extension.js';-import {SAMPLING_EFFORTS, STEP_CACHES, tableLevel} from './sampling_effort.js';+import {SAMPLING_EFFORTS, STEP_CACHES, UPSCALE_FACTORS, tableLevel} from './sampling_effort.js';import {failureIssue, failureStage} from './failure_issue.js';const reports = new WeakSet();const captured = new WeakMap();@@ -81,10 +81,11 @@ function knownError(text) {&& typeof d.two_pass === 'boolean' && Number.isInteger(d.refine_steps) && d.refine_steps >= 0 && d.refine_steps <= 31&& Number.isSafeInteger(d.missing_bytes) && d.missing_bytes > 0 && typeof d.decimal_sizes === 'boolean'&& Array.isArray(d.available) && d.available.every(i => Number.isInteger(i) && i >= 0 && i <= 3)- && (d.step_cache === undefined || STEP_CACHES.includes(d.step_cache)))+ && (d.step_cache === undefined || STEP_CACHES.includes(d.step_cache))+ && (d.scale === undefined || UPSCALE_FACTORS.includes(d.scale)))return {kind: 'sampling-table', base_steps: d.base_steps, two_pass: d.two_pass, refine_steps: d.refine_steps,missing_bytes: d.missing_bytes, decimal_sizes: d.decimal_sizes, available: [...new Set(d.available)].sort(),- ...(d.step_cache ? {step_cache: d.step_cache} : {})};+ ...(d.step_cache ? {step_cache: d.step_cache} : {}), ...(d.scale && d.scale !== 2 ? {scale: d.scale} : {})};} catch { /* Malformed metadata stays in technical details. */ }}return PLAIN_ERRORS.find(error => line === error.message || error.aliases?.includes(line)@@ -227,6 +228,8 @@ export function createErrorReport(detail, context = {}) {}const cache = Array.isArray(inputs?.step_cache) && inputs.step_cache.length === 1 ? inputs.step_cache[0] : inputs?.step_cache;if (typeof cache === 'string' && (cache === 'none' || STEP_CACHES.includes(cache))) settings.step_cache = cache;+ const factor = Array.isArray(inputs?.upscale_factor) && inputs.upscale_factor.length === 1 ? inputs.upscale_factor[0] : inputs?.upscale_factor;+ if (typeof factor === 'string' && UPSCALE_FACTORS.map(String).includes(factor)) settings.upscale_factor = factor;const progress = {};for (const key of ['phase', 'stage']) if (typeof context.progress?.[key] === 'string') progress[key] = clean(context.progress[key]);for (const key of ['done', 'total']) if (Number.isFinite(context.progress?.[key])) progress[key] = context.progress[key];@@ -272,14 +275,16 @@ export function failureAdvice(value, t, known = knownError(value)) {if (known?.kind === 'sampling-table') {// Names and plan matching follow sampling_effort.js; metadata carries no user text.const levels = SAMPLING_EFFORTS.map(tier => [tier.name, tier.zh]);- const level = tableLevel(known.base_steps, known.two_pass, known.refine_steps, known.step_cache ?? null);+ const level = tableLevel(known.base_steps, known.two_pass, known.refine_steps, known.step_cache ?? null, known.scale ?? 2);const index = SAMPLING_EFFORTS.findIndex(tier => tier.name === level?.name);const custom = index < 0;+ // Tables follow the step count: a level with the same steps and passes (Light and Medium) needs the same download.+ const available = known.available.filter(i => SAMPLING_EFFORTS[i]?.steps !== known.base_steps || SAMPLING_EFFORTS[i].twoPass !== known.two_pass);// Iris: a level name and its 档 never break apart. The summary is set as text,// so word joiners (U+2060) keep each group on one line instead of markup.const keep = value => [...value].join('\u2060');const join = language => {- const names = known.available.map(i => language ? `“${levels[i][1]}”` : levels[i][0]);+ const names = available.map(i => language ? `“${levels[i][1]}”` : levels[i][0]);if (language) names[names.length - 1] += '档';const kept = language ? names.map(keep) : names;return kept.length < 2 ? kept[0] || '' : kept.slice(0, -1).join(language ? '、' : ', ') + (language ? '或' : ' or ') + kept.at(-1);@@ -297,8 +302,8 @@ export function failureAdvice(value, t, known = knownError(value)) {: [`The ${levels[index][0]} quality level is not downloaded yet`, `${keep(`“${levels[index][1]}”档`)}还没下载`];const what = custom ? ['This step count', '这个步数'] : ['This level', '这一档'];return {...row('sampling-table', title,- [`${what[0]} needs a download (about ${size}) that did not finish this time. Generate again when online and it downloads automatically.${known.available.length ? ` You can also use ${join(0)} for now.` : ''}`,- `${what[1]}要先下载(约 ${size}),这次没能下载。联网后再生成一次,会自动下载。${known.available.length ? `也可以先用${join(1)}。` : ''}`], ['', '']), plain: true};+ [`${what[0]} needs a download (about ${size}) that did not finish this time. Generate again when online and it downloads automatically.${available.length ? ` You can also use ${join(0)} for now.` : ''}`,+ `${what[1]}要先下载(约 ${size}),这次没能下载。联网后再生成一次,会自动下载。${available.length ? `也可以先用${join(1)}。` : ''}`], ['', '']), plain: true};}// ComfyUI and worker tracebacks carry English exceptions. Translate these// actionable failures through the existing signature/advice path.diff --git a/web/freevideo.js b/web/freevideo.jsindex 30f1b42..ae5fb80 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -755,7 +755,8 @@ app.registerExtension({['continue_from', '接着生成'],['frames', '帧数'],['first_frame_reference', '首帧参考', '减小漂移'],- ['step_cache', '步间缓存', '复用相近采样步之间的计算,更快完成,结果会有细微变化。精细档用 easycache-av,极致档用 fbcache。'],+ ['step_cache', '步间缓存', '复用相近采样步之间的计算,更快完成,结果会有细微变化。'],+ ['upscale_factor', '放大倍数', '二次采样时成片相对首遍的放大倍数。'],]) {const widget = this.widgets?.find(w => w.name === name);if (widget) {diff --git a/web/optional_inputs.js b/web/optional_inputs.jsindex 3bf7416..b145858 100644--- a/web/optional_inputs.js+++ b/web/optional_inputs.js@@ -2,9 +2,11 @@// shape. A workflow restored from an older version, or a widget list that moved,// can leave an empty or missing value in them, and Comfy then rejects the whole// request. Keep each of them to a value the server accepts.-const DEFAULTS = {refine_from: '', continue_from: '', frames: 0, first_frame_reference: false, step_cache: 'none'};+const DEFAULTS = {refine_from: '', continue_from: '', frames: 0, first_frame_reference: false, step_cache: 'none', upscale_factor: '2'};// A workflow saved before Step cache existed holds '' where it now sits.const STEP_CACHE_OPTIONS = ['none', 'easycache-av', 'fbcache'];+// Likewise for Upscale factor, appended after Step cache.+const UPSCALE_OPTIONS = ['2', '1.5', '1.2'];// The words a script, an older workflow or String(null) leaves behind for "not given".const EMPTY_WORDS = new Set(['none', 'null', 'undefined', 'nan']);@@ -27,6 +29,7 @@ export function optionalInputValue(name, value) {if (name === 'refine_from' || name === 'continue_from') return optionalText(value);if (name === 'first_frame_reference') return value === true;if (name === 'step_cache') return STEP_CACHE_OPTIONS.includes(value) ? value : 'none';+ if (name === 'upscale_factor') return UPSCALE_OPTIONS.includes(value) ? value : '2';return value;}diff --git a/web/prompt_draft.js b/web/prompt_draft.jsindex 9b8e419..f28e583 100644--- a/web/prompt_draft.js+++ b/web/prompt_draft.js@@ -3,11 +3,11 @@const FILE = '/userdata/' + encodeURIComponent('freevideo/prompt-draft.json');const WIDGETS = ['text', 'width', 'height', 'seconds', 'seed', 'control_after_generate', 'two_pass','base_steps', 'refine_steps', 'force_regenerate', 'preview', 'refine_from', 'continue_from', 'frames', 'first_frame_reference',- 'voice_reference', 'hide_tail', 'step_cache'];-const DEFAULTS = ['', 1344, 768, 10, 2026090903, 'randomize', true, 8, 3, false, false, '', '', 0, false, false, false, 'none'];+ 'voice_reference', 'hide_tail', 'step_cache', 'upscale_factor'];+const DEFAULTS = ['', 1344, 768, 10, 2026090903, 'randomize', true, 8, 3, false, false, '', '', 0, false, false, false, 'none', '2'];const SAVED_WIDGETS = WIDGETS.filter(name => !['text', 'force_regenerate', 'refine_from', 'continue_from', 'frames','voice_reference', 'hide_tail'].includes(name));-const STEP_CACHE_OPTIONS = ['none', 'easycache-av', 'fbcache'];+const STEP_CACHE_OPTIONS = ['none', 'easycache-av', 'fbcache'], UPSCALE_OPTIONS = ['2', '1.5', '1.2'];const PROPERTIES = ['freevideo_aspect', 'freevideo_pixels', 'freevideo_seconds', 'freevideo_single','freevideo_block_seconds', 'freevideo_run_mode', 'freevideo_batch_count'];const OUTBOX = 'freevideo.prompt-pending';@@ -50,7 +50,8 @@ export function applyPromptDraft(workflow, draft) {const value = draft.widgets?.[name], index = WIDGETS.indexOf(name);if (value === undefined || typeof value !== typeof DEFAULTS[index]|| (typeof value === 'number' && !Number.isFinite(value))- || (name === 'step_cache' && !STEP_CACHE_OPTIONS.includes(value))) continue;+ || (name === 'step_cache' && !STEP_CACHE_OPTIONS.includes(value))+ || (name === 'upscale_factor' && !UPSCALE_OPTIONS.includes(value))) continue;while (node.widgets_values.length <= index) node.widgets_values.push(DEFAULTS[node.widgets_values.length]);node.widgets_values[index] = value;}diff --git a/web/sampling_effort.js b/web/sampling_effort.jsindex 4b6281a..14af234 100644--- a/web/sampling_effort.js+++ b/web/sampling_effort.js@@ -1,25 +1,32 @@// One editor control. The queued request remains an immutable graph snapshot.-// Each level is a complete plan (freevideo_engine/tiers.py): Light is two-pass 8 + 3;-// the others sample once, High and Max with a step cache.+// Each level is a complete plan (freevideo_engine/tiers.py): Light and Medium are two-pass 8 + 3,+// told apart by the learned upscale factor (Medium starts from a larger first pass); High and Max+// sample 20 steps once, High with a step cache. `upscale` is 2 for every single-pass level.const frozen = rows => Object.freeze(rows.map(row => Object.freeze({...row})));export const SAMPLING_EFFORTS = frozen([- {name: 'Light', zh: '轻量', steps: 8, twoPass: true, stepCache: null, color: '#3dd6b5'},- {name: 'Medium', zh: '标准', steps: 8, twoPass: false, stepCache: null, color: '#4ea8ff'},- {name: 'High', zh: '精细', steps: 20, twoPass: false, stepCache: 'easycache-av', color: '#9d7bff'},- {name: 'Max', zh: '极致', steps: 20, twoPass: false, stepCache: 'fbcache', color: '#ffa94d'},+ {name: 'Light', zh: '轻量', steps: 8, twoPass: true, stepCache: null, upscale: 2, color: '#3dd6b5'},+ {name: 'Medium', zh: '标准', steps: 8, twoPass: true, stepCache: null, upscale: 1.5, color: '#4ea8ff'},+ {name: 'High', zh: '精细', steps: 20, twoPass: false, stepCache: 'easycache-av', upscale: 2, color: '#9d7bff'},+ {name: 'Max', zh: '极致', steps: 20, twoPass: false, stepCache: null, upscale: 2, color: '#ffa94d'},]);-// Mac (MPS) has the audio-video EasyCache only: High is as everywhere, Max samples 20 steps in full.-const MAC = {Max: {stepCache: null}};-export const SAMPLING_EFFORTS_MAC = frozen(SAMPLING_EFFORTS.map(tier => ({...tier, ...MAC[tier.name]})));+// Mac runs the same levels.+export const SAMPLING_EFFORTS_MAC = SAMPLING_EFFORTS;// Mac results made before the cache came: High was 16 steps without one.export const legacyMacEffort = (steps, twoPass, stepCache = null) =>steps === 16 && !twoPass && stepCacheOf(stepCache) === null ? SAMPLING_EFFORTS_MAC.find(tier => tier.name === 'High') : undefined;export const effortName = (t, tier) => t(tier.name, tier.zh);export const STEP_CACHES = Object.freeze([null, 'easycache-av', 'fbcache']);+// The two-pass learned upscale factors (two_pass.SCALES); the `upscale_factor` widget holds them as text.+export const UPSCALE_FACTORS = Object.freeze([2, 1.5, 1.2]);// The cache a `step_cache` value names; 'none', '' and a missing value sample in full.export const stepCacheOf = value => (typeof value === 'string' && value && value !== 'none' ? value : null);+// The factor an `upscale_factor` value (or a result's sampling_plan.scale) names; anything else, or none, is 2.+export function upscaleOf(value) {+ const factor = typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN;+ return UPSCALE_FACTORS.includes(factor) ? factor : 2;+}// The levels of the machine a capability grid describes: its own table when the// grid lists one, else the Mac table on a Mac, else the default table.@@ -31,22 +38,44 @@ export function effortsFrom(grid) {const row = tiers[tier.name.toLowerCase()];if (!row || !Number.isInteger(row.steps) || typeof row.two_pass !== 'boolean') return tier;return {...tier, steps: row.steps, twoPass: row.two_pass,- stepCache: 'step_cache' in row ? stepCacheOf(row.step_cache) : tier.stepCache};+ stepCache: 'step_cache' in row ? stepCacheOf(row.step_cache) : tier.stepCache,+ upscale: !row.two_pass ? 2 : 'upscale' in row ? upscaleOf(row.upscale) : tier.upscale};}));}-// The level a plan matches, or undefined for custom steps.-export function effortFor(steps, twoPass, refine, stepCache = null, levels = SAMPLING_EFFORTS) {- const cache = stepCacheOf(stepCache);+// The level a plan matches, or undefined for custom steps; the upscale factor tells the+// two-pass levels apart (a single pass has none).+export function effortFor(steps, twoPass, refine, stepCache = null, levels = SAMPLING_EFFORTS, upscale = 2) {+ const cache = stepCacheOf(stepCache), factor = twoPass ? upscaleOf(upscale) : 2;return levels.find(tier => tier.steps === steps && tier.twoPass === twoPass && (!twoPass || refine === 3)- && tier.stepCache === cache);+ && tier.stepCache === cache && tier.upscale === factor);+}++// The level a result's sampling_plan names. Results made with the earlier 8 + 2 default count as+// Light; `scale` (absent when 2) tells Light from Medium; an earlier Mac result of 16 steps is High.+export function resultEffort(plan) {+ const p = plan || {}, steps = p.base_steps, refine = p.enabled ? p.refine_steps : 0;+ return effortFor(steps, !!p.enabled, p.enabled && steps === 8 && refine === 2 ? 3 : refine, p.step_cache ?? null, SAMPLING_EFFORTS, p.scale ?? 2)+ || legacyMacEffort(steps, !!p.enabled, p.step_cache ?? null);}+// The steps and factor switching two-pass leaves. Off from an 8-step first pass samples the+// single-pass levels' 20 steps; on from a single-pass level gives Light. Typed steps stay.+export function passSwitch(on, steps, refine, stepCache = null, levels = SAMPLING_EFFORTS) {+ if (!on) return {steps: steps === 8 ? levels.find(tier => !tier.twoPass)?.steps ?? 20 : steps, refine, upscale: 2};+ const light = levels.find(tier => tier.twoPass && tier.upscale === 2);+ return effortFor(steps, false, refine, stepCache, levels) && light ? {steps: light.steps, refine: 3, upscale: 2} : {steps, refine, upscale: 2};+}++// A continuation samples 8 + 3 in two passes: it keeps the factor of a two-pass level, else 2 (widget text).+export const continuationUpscale = (steps, twoPass, refine, stepCache, upscale, levels = SAMPLING_EFFORTS) =>+ String(effortFor(Number(steps), twoPass !== false, Number(refine), stepCache, levels, upscale)?.twoPass ? upscaleOf(upscale) : 2);+// The level whose sampling table a plan needs, for naming a missing download (tiers.table_level):-// the exact level of either table (the cache tells High from Max at 20 steps; 20 steps-// without a cache is Max, as on Mac; 16 steps is the earlier Mac High), else the first level with those steps.-export function tableLevel(steps, twoPass, refine, stepCache = null) {- return effortFor(steps, twoPass, refine, stepCache) || effortFor(steps, twoPass, refine, stepCache, SAMPLING_EFFORTS_MAC)+// the exact level (the cache tells High from Max at 20 steps, the factor Light from Medium; 16 steps+// is the earlier Mac High), else the first level with those steps (Light for 8 + 3, whatever the factor).+export function tableLevel(steps, twoPass, refine, stepCache = null, upscale = 2) {+ return effortFor(steps, twoPass, refine, stepCache, SAMPLING_EFFORTS, upscale)|| legacyMacEffort(steps, twoPass, stepCache) || SAMPLING_EFFORTS.find(tier => tier.steps === steps && tier.twoPass === twoPass && (!twoPass || refine === 3));}@@ -78,7 +107,7 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}, levels});const custom = el('span', 'fv-effort-custom', t('Custom steps', '自定义步数')); custom.hidden = true;element.append(header, rail, names, custom);- let selected = 0, disabled = false, pointer = null, draft = 0, currentSteps = 8, currentRefine = 3, twoPass = true, stepCache = null, reason = '';+ let selected = 0, disabled = false, pointer = null, draft = 0, currentSteps = 8, currentRefine = 3, twoPass = true, stepCache = null, upscale = 2, reason = '';function paint(position) {element.style.setProperty('--fv-position', position / 3);const index = Math.round(position), tier = efforts[index];@@ -100,7 +129,7 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}, levelsfunction cancel() {const id = pointer; pointer = null; delete rail.dataset.dragging;if (id !== null && rail.hasPointerCapture(id)) rail.releasePointerCapture(id);- update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, stepCache, disabled, reason});+ update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, stepCache, upscale, disabled, reason});onPreview(null);}rail.onpointerdown = event => {@@ -132,11 +161,11 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}, levels};function update(state) {currentSteps = Number(state.baseSteps); currentRefine = Number(state.refineSteps);- twoPass = state.twoPass; stepCache = stepCacheOf(state.stepCache); disabled = state.disabled; reason = state.reason || '';+ twoPass = state.twoPass; stepCache = stepCacheOf(state.stepCache); upscale = upscaleOf(state.upscale); disabled = state.disabled; reason = state.reason || '';rail.tabIndex = disabled ? -1 : 0; rail.setAttribute('aria-disabled', String(disabled));element.dataset.disabled = String(disabled);if (pointer !== null) return;- const level = effortFor(currentSteps, twoPass, currentRefine, stepCache, efforts);+ const level = effortFor(currentSteps, twoPass, currentRefine, stepCache, efforts, upscale);// Custom steps sit at the nearest level, preferring one with the same pass count.const distance = v => Math.abs(v.steps - currentSteps) * 2 + (v.twoPass !== twoPass);selected = level ? efforts.indexOf(level) : efforts.reduce((best, v, i) => distance(v) < distance(efforts[best]) ? i : best, 0);@@ -152,10 +181,10 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}, levels}// The machine's own table (effortsFrom); the names stay, the plans follow the machine.function setLevels(next) {- const same = (a, b) => a.steps === b.steps && a.twoPass === b.twoPass && a.stepCache === b.stepCache;+ const same = (a, b) => a.steps === b.steps && a.twoPass === b.twoPass && a.stepCache === b.stepCache && a.upscale === b.upscale;if (!next || next.length !== efforts.length || next.every((tier, i) => same(tier, efforts[i]))) return;efforts = next;- update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, stepCache, disabled, reason});+ update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, stepCache, upscale, disabled, reason});}return {element, update, setLevels, levels: () => efforts, setEstimate(text, title = '') { estimate.textContent = text; if (title) estimate.title = title; else estimate.removeAttribute('title'); }, dispose: cancel};}diff --git a/web/share.js b/web/share.jsindex ad82a6f..cbe45c2 100644--- a/web/share.js+++ b/web/share.js@@ -1,6 +1,6 @@import {api} from '../../scripts/api.js';import {closeDialog} from './motion.js';-import {SAMPLING_EFFORTS_MAC, effortFor, effortName, legacyMacEffort} from './sampling_effort.js';+import {effortName, resultEffort} from './sampling_effort.js';import {fontCSS as bundledFontCSS, fontLoaded, loadFont} from './fonts.js';import {shareLayout} from './share_layout.js';import {videoUnavailableText} from './studio_extend.js';@@ -36,11 +36,7 @@ export function drawShareCard(canvas,frame,logo,record,t) {const g=record.geometry||{}, shape=shareLayout(g.width||frame?.naturalWidth||1344,g.height||frame?.naturalHeight||768);canvas.width=shape.width;canvas.height=shape.height;const ctx=canvas.getContext('2d'),w=shape.width,y=shape.rect[3],H=shape.footer,pad=44,wide=w>=1000;- const p=record.sampling_plan||{},steps=p.base_steps,refine=p.enabled?p.refine_steps:0;- // Results made with the earlier 8 + 2 default count as Light.- // A Mac result names its level from the Mac table (Max 20 without a cache; earlier High 16 steps).- const plan=[steps,!!p.enabled,p.enabled&&steps===8&&refine===2?3:refine,p.step_cache??null];- const tier=effortFor(...plan)||effortFor(...plan,SAMPLING_EFFORTS_MAC)||legacyMacEffort(steps,!!p.enabled,p.step_cache??null), accent=tier?.color||'#8fa3bb';+ const steps=record.sampling_plan?.base_steps, tier=resultEffort(record.sampling_plan), accent=tier?.color||'#8fa3bb';ctx.fillStyle='#0b1016';ctx.fillRect(0,0,w,shape.height);ctx.clearRect(...shape.rect);const bg=ctx.createLinearGradient(0,y,0,y+H);bg.addColorStop(0,'#131b26');bg.addColorStop(1,'#0b1016');ctx.fillStyle=bg;ctx.fillRect(0,y,w,H);diff --git a/web/studio.js b/web/studio.jsindex b861ad0..111c1c8 100644--- a/web/studio.js+++ b/web/studio.js@@ -27,7 +27,7 @@ import { openCastLibrary } from './cast_source.js';import { uploadMedia } from './media_upload.js';import { reconcileLoraTriggers } from './lora_triggers.js';import { createVerdicts, describeVerdict, feedbackDraft } from './lora_check.js';-import { createSamplingEffort, effortFor, effortsFrom, stepCacheOf } from './sampling_effort.js';+import { continuationUpscale, createSamplingEffort, effortFor, effortsFrom, passSwitch, stepCacheOf, upscaleOf } from './sampling_effort.js';import { resultActions, previewBadge, icon, actionsUnavailable } from './result_actions.js';import { createPromptEnhancer } from './prompt_enhance.js';import { createRequestAssets, enabledLoras, referenceFiles } from './request_assets.js';@@ -775,6 +775,9 @@ export function openStudio(node, {extendFrom = null} = {}) {// A level's step cache; custom steps and workflows without the input sample every step.const stepCacheNow = () => stepCacheOf(value(node, 'step_cache'));const clearStepCache = () => { if (stepCacheNow()) set(node, 'step_cache', 'none'); };+ // The two-pass learned upscale factor; a single pass has none (2).+ const upscaleNow = () => upscaleOf(value(node, 'upscale_factor'));+ const setUpscale = factor => { if (widget(node, 'upscale_factor') && value(node, 'upscale_factor') !== String(factor)) set(node, 'upscale_factor', String(factor)); };const effort = createSamplingEffort(t, {onChange: tier => {baseSteps.value = tier.steps;refineSteps.value = 3;@@ -783,14 +786,23 @@ export function openStudio(node, {extendFrom = null} = {}) {set(node, 'two_pass', twoPass.checked);set(node, 'refine_steps', 3);set(node, 'step_cache', tier.stepCache || 'none');+ set(node, 'upscale_factor', String(tier.upscale));syncSamplingSteps();- }, onPreview: tier => tier ? showEffortEstimate(tier.steps, tier.twoPass, tier.stepCache) : showEffortEstimate()});+ }, onPreview: tier => tier ? showEffortEstimate(tier.steps, tier.twoPass, tier.stepCache, tier.upscale) : showEffortEstimate()});const samplingSettings = el('div', null, 'fv-sampling-settings');const previewFirst = el('input'); previewFirst.type = 'checkbox'; previewFirst.checked = value(node, 'preview') === true;function choosePassMode(mode) {if (extension.source) return;const wantsTwoPass = mode !== 'off', wantsPreview = mode === 'preview';- if (twoPass.checked !== wantsTwoPass) { twoPass.checked = wantsTwoPass; autoSinglePass = false; set(node, 'two_pass', wantsTwoPass); clearStepCache(); }+ if (twoPass.checked !== wantsTwoPass) {+ // A level in one pass samples 20 steps; two-pass from one is Light. Typed steps stay.+ const next = passSwitch(wantsTwoPass, Number(baseSteps.value), Number(refineSteps.value), stepCacheNow(), effort.levels());+ twoPass.checked = wantsTwoPass; autoSinglePass = false; set(node, 'two_pass', wantsTwoPass); clearStepCache(); setUpscale(next.upscale);+ if (next.steps !== Number(baseSteps.value) && !linked(node, 'base_steps') && widget(node, 'base_steps')) {+ baseSteps.value = String(next.steps); set(node, 'base_steps', next.steps);+ if (next.refine !== Number(refineSteps.value) && set(node, 'refine_steps', next.refine)) refineSteps.value = String(next.refine);+ }+ }if (previewFirst.checked !== wantsPreview) { previewFirst.checked = wantsPreview; set(node, 'preview', wantsPreview); }syncSamplingSteps(); updateRunButton();}@@ -911,13 +923,17 @@ export function openStudio(node, {extendFrom = null} = {}) {// The run button exists only further down; until then its label is set there.let runButtonReady = false;function syncSamplingSteps() {- if (extension.source) { baseSteps.value = '8'; refineSteps.value = '3'; twoPass.checked = true; set(node, 'two_pass', true); clearStepCache(); autoSinglePass = false; }+ if (extension.source) {+ const factor = continuationUpscale(baseSteps.value, twoPass.checked, refineSteps.value, stepCacheNow(), value(node, 'upscale_factor'), effort.levels());+ baseSteps.value = '8'; refineSteps.value = '3'; twoPass.checked = true; set(node, 'two_pass', true); clearStepCache(); setUpscale(factor); autoSinglePass = false;+ }const baseLinked = linked(node, 'base_steps');- // Two-pass is offered at 8 first-pass steps. A saved workflow that already- // uses it with other steps is shown as custom and left unchanged.- const unavailable = Number(baseSteps.value) !== 8 && !twoPass.checked;+ // Two-pass is offered at 8 first-pass steps, and from a single-pass level (it then gives Light).+ // A saved workflow that already uses it with other steps is shown as custom and left unchanged.+ const onePassLevel = !twoPass.checked && !baseLinked && Boolean(effortFor(Number(baseSteps.value), false, Number(refineSteps.value), stepCacheNow(), effort.levels()));+ const unavailable = Number(baseSteps.value) !== 8 && !twoPass.checked && !onePassLevel;twoPass.disabled = Boolean(extension.source) || unavailable || linked(node, 'two_pass') || !widget(node, 'two_pass');- twoPassStatus.textContent = Number(baseSteps.value) !== 8 ? t('Needs an 8-step first pass', '一采需 8 步') : '';+ twoPassStatus.textContent = Number(baseSteps.value) !== 8 && !onePassLevel ? t('Needs an 8-step first pass', '一采需 8 步') : '';twoPassLabel.classList.toggle('fv-two-pass-unavailable', unavailable);// A preview stops after the first pass, so it needs two-pass sampling.if (!twoPass.checked && previewFirst.checked) {@@ -940,14 +956,19 @@ export function openStudio(node, {extendFrom = null} = {}) {}}effort.update({baseSteps: Number(baseSteps.value), refineSteps: Number(refineSteps.value),- twoPass: twoPass.checked, stepCache: stepCacheNow(),- disabled: baseSteps.disabled || linked(node, 'two_pass') || linked(node, 'refine_steps') || linked(node, 'step_cache'),- reason: extension.source ? t('A continuation uses the Light level.', '接着生成使用轻量档。') : ''});+ twoPass: twoPass.checked, stepCache: stepCacheNow(), upscale: upscaleNow(),+ disabled: baseSteps.disabled || linked(node, 'two_pass') || linked(node, 'refine_steps') || linked(node, 'step_cache') || linked(node, 'upscale_factor'),+ reason: extension.source ? continuationReason() : ''});refreshEffortEstimate();}syncSamplingSteps();advanced.append(samplingFields, samplingWarning);- function showEffortEstimate(steps = Number(baseSteps.value), twoPassPlan = twoPass.checked, cache = stepCacheNow()) {+ // A continuation keeps a two-pass level (Light or Medium).+ function continuationReason() {+ const level = effortFor(8, true, 3, null, effort.levels(), upscaleNow());+ return level?.name === 'Medium' ? t('A continuation uses the Medium level.', '接着生成使用标准档。') : t('A continuation uses the Light level.', '接着生成使用轻量档。');+ }+ function showEffortEstimate(steps = Number(baseSteps.value), twoPassPlan = twoPass.checked, cache = stepCacheNow(), factor = upscaleNow()) {const parts = lengthControl.plan?.count > 1 ? t(`${lengthControl.plan.count} parts`, `分 ${lengthControl.plan.count} 段`) : '';// A request that fits one run keeps its own estimate while the longest run is unknown.if ((lengthControl.capabilityState === 'pending' || lengthControl.capabilityState === 'unavailable')@@ -960,16 +981,17 @@ export function openStudio(node, {extendFrom = null} = {}) {if (lengthControl.needsPlan && !lengthControl.plan) { effort.setEstimate(''); return; }if (lengthControl.plan?.count > 1) {const plan = lengthControl.plan;- const seconds = steps === Number(baseSteps.value) && twoPassPlan === twoPass.checked && cache === stepCacheNow()+ const seconds = steps === Number(baseSteps.value) && twoPassPlan === twoPass.checked && cache === stepCacheNow() && factor === upscaleNow()? sumPartEstimates(plan, lengthControl.estimate) : null;effort.setEstimate(seconds > 0 ? t(`${plan.count} parts · about ${Math.ceil(seconds / 60)} min`, `分 ${plan.count} 段 · 约 ${Math.ceil(seconds / 60)} 分钟`): t(`${plan.count} parts`, `分 ${plan.count} 段`));return;}- const rangeEstimate = capabilityView?.estimate(steps, twoPassPlan, arguments.length ? 3 : Number(refineSteps.value), cache);+ const rangeEstimate = capabilityView?.estimate(steps, twoPassPlan, arguments.length ? 3 : Number(refineSteps.value), cache, factor);if (rangeEstimate) { effort.setEstimate(rangeEstimate); return; }const mode = twoPassPlan ? 'two_pass' : 'single';- const estimate = effortEstimate[mode]?.[cache ? `${steps}:${cache}` : String(steps)];+ // Keys: "<steps>[:<cache>][x<factor> when two-pass and not 2]".+ const estimate = effortEstimate[mode]?.[`${steps}${cache ? ':' + cache : ''}${twoPassPlan && factor !== 2 ? 'x' + factor : ''}`];// A previewed level always refines three steps; the current plan may not.if (estimate?.status !== 'estimated' || (mode === 'two_pass' && !arguments.length && Number(refineSteps.value) !== 3)) {effort.setEstimate('', t('No estimate is available for these settings.', '当前设置暂无预计用时。'));@@ -1002,9 +1024,9 @@ export function openStudio(node, {extendFrom = null} = {}) {const requestWidth = extension.source?.geometry.width ?? value(node, 'width');const requestHeight = extension.source?.geometry.height ?? value(node, 'height');lengthControl?.refresh({width: requestWidth, height: requestHeight, task, adapters,- settings: {tier: effortFor(Number(baseSteps.value), twoPass.checked, Number(refineSteps.value), stepCacheNow(), effort.levels())?.name.toLowerCase() || 'custom',+ settings: {tier: effortFor(Number(baseSteps.value), twoPass.checked, Number(refineSteps.value), stepCacheNow(), effort.levels(), upscaleNow())?.name.toLowerCase() || 'custom',base_steps: Number(baseSteps.value), refine_steps: Number(refineSteps.value), two_pass: twoPass.checked,- step_cache: stepCacheNow()}}, force);+ step_cache: stepCacheNow(), upscale_factor: upscaleNow()}}, force);requestAssetsQuery = () => {const query = new URLSearchParams({width: requestWidth, height: requestHeight, seconds: value(node, 'seconds'), task,base_steps: baseSteps.value, refine_steps: refineSteps.value, two_pass: twoPass.checked ? '1' : '0',@@ -1704,7 +1726,7 @@ export function openStudio(node, {extendFrom = null} = {}) {dialog.onclose = () => { disposed = true; for (const f of cleanup) f(); stage.querySelector('video')?.pause(); dialog.remove(); if (current?.dialog === dialog) { current = null; viewChanged('nodes', node); } };capabilityView = createCapabilityView({node, api, t, getState: () => ({ratio,custom: selected === 'custom', steps: Number(baseSteps.value), twoPass: twoPass.checked,- refine: Number(refineSteps.value), stepCache: stepCacheNow(), disabled: Boolean(extension.source) || dimensionsLinked || seconds.disabled}),+ refine: Number(refineSteps.value), stepCache: stepCacheNow(), upscale: upscaleNow(), disabled: Boolean(extension.source) || dimensionsLinked || seconds.disabled}),onEstimate: () => showEffortEstimate(), onGrid: grid => effort.setLevels(effortsFrom(grid)), onPick: point => {pixels = point.pixels; mp.value = String(pixels);set(node, 'width', point.width); set(node, 'height', point.height);diff --git a/web/studio_extend.js b/web/studio_extend.jsindex a5453ac..fa8971b 100644--- a/web/studio_extend.js+++ b/web/studio_extend.js@@ -1,3 +1,4 @@+import {continuationUpscale} from './sampling_effort.js';export const EXTEND_PROPERTY = 'freevideo_extend';export const EXTEND_TEXT = Object.freeze({action: ['Extend', '接着生成'],@@ -56,7 +57,7 @@ export async function readExtendRecord(api, record) {}export function createExtendState(node, read, write) {- const keys = ['width', 'height', 'seconds', 'two_pass', 'preview', 'base_steps', 'refine_steps', 'step_cache'];+ const keys = ['width', 'height', 'seconds', 'two_pass', 'preview', 'base_steps', 'refine_steps', 'step_cache', 'upscale_factor'];return {get source() { return node.properties?.[EXTEND_PROPERTY]?.source || null; },enter(record) {@@ -74,10 +75,13 @@ export function createExtendState(node, read, write) {seconds = Math.floor(seconds * 1000 + 1e-6) / 1000;const source = structuredClone(record); source.geometry = {...g, seconds};node.properties[EXTEND_PROPERTY] = {source, previous};+ const v = previous.values;for (const [key, value] of Object.entries({width: g.width, height: g.height,seconds: Math.min(60, seconds), text: '', preview: false,- // A continuation always runs the Light plan: two passes, 8 + 3 steps, no step cache.- two_pass: true, base_steps: 8, refine_steps: 3, step_cache: 'none'})) write(key, value);+ // A continuation always runs two passes, 8 + 3 steps, no step cache: Light, or Medium when that is the level.+ two_pass: true, base_steps: 8, refine_steps: 3, step_cache: 'none',+ ...(v.upscale_factor !== undefined+ ? {upscale_factor: continuationUpscale(v.base_steps, v.two_pass, v.refine_steps, v.step_cache, v.upscale_factor)} : {})})) write(key, value);node.properties.freevideo_seconds = seconds;node.properties.freevideo_aspect = 'custom';node.properties.freevideo_pixels = g.width * g.height / 1024 ** 2;@@ -100,8 +104,9 @@ export function extendSnapshot(snapshot, node, source, {multiple = false} = {})if (!source) return snapshot;const copy = structuredClone(snapshot), inputs = copy.output[String(node)].inputs;inputs.width = source.geometry.width; inputs.height = source.geometry.height;+ const factor = continuationUpscale(inputs.base_steps ?? 8, inputs.two_pass, inputs.refine_steps ?? 3, inputs.step_cache, inputs.upscale_factor);inputs.preview = false; inputs.refine_from = ''; inputs.two_pass = true;- for (const [key, value] of [['base_steps', 8], ['refine_steps', 3], ['step_cache', 'none']]) if (key in inputs) inputs[key] = value;+ for (const [key, value] of [['base_steps', 8], ['refine_steps', 3], ['step_cache', 'none'], ['upscale_factor', factor]]) if (key in inputs) inputs[key] = value;// A continuation takes no first or last frame and no pre-encoded conditioning.for (const key of ['first', 'last', 'conditioning']) delete inputs[key];if (multiple) delete inputs.continue_from; else inputs.continue_from = source.video;