Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
fix(hang): move post-decode rescue to panel-side SIGKILL + gallery + speed
mrbizarro94bd6965865f
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex f4b71d7..f1055f1 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -3769,7 +3769,25 @@ def list_outputs(# post-build limit is what governs how much we send to the browser.# The scan cost is dominated by stat() calls — 1000 mp4s on APFS is# <50 ms in practice, well inside the 1.5 s poll cadence.- video_files = sorted(OUTPUT.glob("*.mp4"), key=lambda p: p.stat().st_mtime, reverse=True)+ # Filter out Extend's pre-downscale cache files (`<base>_dnWIDTHxHEIGHT.mp4`).+ # These are intermediate inputs the extend pipeline produces from a+ # source clip — never something a user generated. They leaked into the+ # gallery with a misleading "21:19"-style label because _outputDurationLabel+ # falls back to mtime when no sidecar elapsed_sec exists. Hide them at+ # the source instead of patching the label downstream — they're cache,+ # not outputs. Pattern: `_dn\d+x\d+(_ext\d+_...)?` covers both bare+ # downscales and chained extends. Mr Bizarro 2026-05-21.+ _DN_CACHE_RX = re.compile(r"_dn\d+x\d+$")+ def _is_dn_cache(p: Path) -> bool:+ # Stem ends exactly with `_dnWIDTHxHEIGHT` AND has no sidecar.+ # A real Extend OUTPUT has the timestamp suffix `_ext\d+_…` after+ # the dn segment, so it won't match this stem-end regex; a cache+ # file matches because nothing follows the dn segment. The sidecar+ # absence is belt-and-suspenders against any future render whose+ # filename happens to terminate this way.+ return bool(_DN_CACHE_RX.search(p.stem)) and not (p.parent / (p.stem + ".mp4.json")).is_file()+ video_files = [p for p in sorted(OUTPUT.glob("*.mp4"), key=lambda p: p.stat().st_mtime, reverse=True)+ if not _is_dn_cache(p)]image_root = UPLOADS / "library" / "manual"image_exts = {".png", ".jpg", ".jpeg", ".webp"}image_candidates: list[tuple[Path, float]] = []@@ -4044,7 +4062,19 @@ class WarmHelper:raise RuntimeError(f"helper failed to start: {ready}")push(f"helper ready · model={ready.get('model')} · low_memory={ready.get('low_memory')}")- def _read_until(self, target_events: list[str], timeout: float | None = None) -> dict | None:+ def _read_until(self, target_events: list[str], timeout: float | None = None,+ log_hook: callable | None = None,+ panic_check: callable | None = None) -> dict | None:+ """Read helper events until one of `target_events` arrives.++ ``log_hook(line)`` is invoked for every log line the helper emits+ — used by the post-decode panic to spot the decode-done log.++ ``panic_check()`` runs on every idle select tick. If it returns a+ dict, that dict is returned IMMEDIATELY as if the helper had sent+ it — used to synthesize a done event when the helper has hung in+ post-decode but the file is on disk.+ """if not self.proc or not self.proc.stdout:return Nonedeadline = time.time() + timeout if timeout else None@@ -4057,6 +4087,13 @@ class WarmHelper:while True:if deadline and time.time() > deadline:return None+ # Panic check runs every tick — even when the helper is silent —+ # so the post-decode hang (helper not emitting anything, file+ # already on disk) gets rescued promptly.+ if panic_check is not None:+ synth = panic_check()+ if synth is not None:+ return synthrlist, _, _ = select.select([stdout], [], [], poll_interval)if not rlist:continue # idle slice — re-check deadline@@ -4075,15 +4112,118 @@ class WarmHelper:ev = json.loads(line)except json.JSONDecodeError:push(line)+ if log_hook is not None:+ try: log_hook(line)+ except Exception: passcontinueev_type = ev.get("event")if ev_type == "log":- push(ev.get("line", ""))+ log_line = ev.get("line", "")+ push(log_line)+ if log_hook is not None:+ try: log_hook(log_line)+ except Exception: passelif ev_type in target_events:return evelse:push(f"helper {ev_type}: {json.dumps(ev)[:200]}")+ # Marker the helper's decode wrapper logs once the upstream decoder+ # has finished writing the mp4 + muxing the audio. Spotted by the+ # post-decode-hang panic to start the grace clock.+ _DECODE_DONE_RX = re.compile(r"\[Decoding (?:video \+ audio \+ muxing|done)\] done in", re.IGNORECASE)++ def _build_post_decode_panic(self, job_spec: dict):+ """Return (log_hook, panic_check) for `_read_until` that rescues+ the panel from the MLX/Metal post-decode hang.++ Background+ ----------+ On `DistilledPipeline.generate_two_stage` (T2V/I2V Balanced) and+ `ExtendPipeline.extend_from_video`, the helper writes the output+ mp4, emits upstream's "[Decoding ... done in X.Xs]" log line,+ and then Python execution stalls 5-15 minutes in the function-+ return path. The stall is in Metal command-buffer completion+ handlers; they block every Python thread's GIL access, so an+ in-process daemon-thread watchdog can't fire (it's starved by+ the very thing it's meant to escape — tried + observed+ 2026-05-21).++ Rescue+ ------+ SIGKILL the helper from the PANEL (a separate process — no GIL+ contention possible) once we see:+ 1. The decode-done log line (proves the decoder finished and+ wrote the file), AND+ 2. A grace period has passed without the helper sending+ "done"/"error"/"exit", AND+ 3. The output file is on disk with reasonable size.++ Synthesize a "done" event from the known output_path so the+ panel marks the job succeeded. Helper respawns on next job+ (~30s spawn cost). Vastly better trade than the 15-min hang.++ Only mp4-producing actions get the panic (image gen + train+ don't hit this path).+ """+ params = job_spec.get("params", {}) or {}+ action = job_spec.get("action") or params.get("command") or ""+ output_path = params.get("output_path", "") or ""+ job_id = job_spec.get("id", "?")+ # Only arm for actions known to hit the MLX/Metal post-decode hang.+ # generate covers T2V/I2V Balanced (DistilledPipeline.generate_two_stage);+ # extend covers ExtendPipeline. A2V, FFLF, image, train have all+ # been observed returning cleanly, so leave them alone.+ ARMABLE_ACTIONS = {"generate", "extend"}+ if action not in ARMABLE_ACTIONS or not output_path:+ return None, None++ state = {"decode_done_at": None, "panicked": False}+ GRACE_SEC = 45+ MIN_FILE_BYTES = 8 * 1024 # generous floor — partial mp4s are MUCH smaller++ def log_hook(line: str):+ if state["decode_done_at"] is None and self._DECODE_DONE_RX.search(line or ""):+ state["decode_done_at"] = time.time()+ push(f"[panel-watchdog] {action} {job_id}: decode-done signal seen, "+ f"grace clock armed ({GRACE_SEC}s).")++ def panic_check():+ if state["panicked"] or state["decode_done_at"] is None:+ return None+ elapsed = time.time() - state["decode_done_at"]+ if elapsed < GRACE_SEC:+ return None+ try:+ if not os.path.exists(output_path):+ return None+ if os.path.getsize(output_path) < MIN_FILE_BYTES:+ return None+ except OSError:+ return None+ # All conditions met — helper is stuck in MLX deallocator.+ state["panicked"] = True+ push(+ f"[panel-watchdog] {action} {job_id}: post-decode hang "+ f"detected — file on disk ({os.path.getsize(output_path)} "+ f"bytes) but helper silent for {elapsed:.0f}s after "+ f"decode-done. SIGKILLing helper; render counted as done."+ )+ # SIGKILL from a background thread to avoid blocking the panic+ # tick. The kill is fully external so the helper's GIL+ # situation doesn't matter.+ threading.Thread(target=self.kill, daemon=True,+ name="phos-panic-kill").start()+ return {+ "event": "done",+ "id": job_id,+ "output": output_path,+ "elapsed_sec": None, # unknown timing — file timing only+ "watchdog_forced_exit": True,+ }++ return log_hook, panic_check+def run(self, job_spec: dict) -> dict:# Whole-run serialization so concurrent callers don't both park in# _read_until and grab each other's done/error events. See __init__@@ -4097,7 +4237,12 @@ class WarmHelper:self.proc.stdin.flush()except (BrokenPipeError, OSError) as exc:raise RuntimeError(f"helper stdin closed: {exc}")- ev = self._read_until(["done", "error", "exit"])+ log_hook, panic_check = self._build_post_decode_panic(job_spec)+ ev = self._read_until(+ ["done", "error", "exit"],+ log_hook=log_hook,+ panic_check=panic_check,+ )return self._dispatch_run_event(ev)def _dispatch_run_event(self, ev: dict | None) -> dict:@@ -4827,7 +4972,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,"video_path": f("video_path", ""),"extend_frames": max(1, int(f("extend_frames", "5") or 5)),"extend_direction": f("extend_direction", "after"),- "extend_steps": max(1, int(f("extend_steps", "12") or 12)),+ "extend_steps": max(1, int(f("extend_steps", "8") or 8)),"extend_cfg": float(f("extend_cfg", "1.0") or 1.0),# keyframe (FFLF) mode params.# Two-keyframe path (start_image + end_image) is the legacy panel@@ -6067,10 +6212,16 @@ def run_job_inner(job: dict) -> None:# native resolution. At 1280×704 + CFG 3.0 we OOM into swap on 64 GB# Macs (peak ~47 GB resident + 12 GB swap → 240s/step). Default to# cfg_scale=1.0 (no CFG, ~half the activation memory, fits cleanly)- # and 12 steps. Form exposes a "Quality" toggle that flips to+ # and 8 steps. Form exposes a "Quality" toggle that flips to# cfg=3.0 + steps=30 for users with the headroom.+ #+ # Speed default cut from 12 → 8 (Mr Bizarro 2026-05-21: "is that+ # not too slow?"). At cfg=1.0 (single-branch) on the dev+ # transformer, steps 8-12 add marginal quality but cost ~30-60s+ # each. 8 steps lands ~6 min at 768×416 instead of ~11 min for+ # the same +6 frame extension.cfg_scale = float(p.get("extend_cfg") or 1.0)- steps = int(p["extend_steps"]) if p.get("extend_steps") else 12+ steps = int(p["extend_steps"]) if p.get("extend_steps") else 8job_spec = {"action": "extend","id": job["id"],@@ -24237,8 +24388,13 @@ function animateFromPhoto(payload) {function _outputDurationLabel(o) {const s = (o && typeof o.elapsed_sec === 'number') ? o.elapsed_sec : null;if (s == null) {- // Fallback: show time-of-day from mtime so empty cards aren't worse.- return o.mtime ? o.mtime.slice(11, 16) : '—';+ // No render-elapsed in sidecar — show a relative timestamp instead+ // of HH:MM, which looked like a render duration and was confusing+ // (Mr Bizarro 2026-05-21: pointed at a "21:19" label that looked+ // like a 21-minute render but was actually the file's wall-clock+ // mtime). Empty card is better than misleading.+ return (o && o.mtime && typeof _relTimeFromMtime === 'function')+ ? _relTimeFromMtime(o.mtime) : '—';}if (s < 60) return `${Math.round(s)} s`;if (s < 3600) return `${Math.floor(s / 60)} m ${Math.round(s % 60)} s`;diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex 03a455d..8c8314b 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -491,138 +491,15 @@ _VIDEO_DECODER_PATCH_INSTALLED = False_A2V_FRAME_RATE_PATCH_INSTALLED = False-class _PostDecodeWatchdog:- """Bulletproof escape hatch for the post-decode MLX/Metal deallocator hang.-- The Symptom- ------------ On the ``DistilledPipeline.generate_two_stage`` path (T2V/I2V Balanced- post-May-9 upstream refactor) and on ``ExtendPipeline``, the helper- writes the output mp4 to disk successfully and emits upstream's- "[Decoding video + audio + muxing] done in X.Xs" log line — then- Python execution stalls for 5-15 minutes before reaching the next- statement. The stall is in the function-return path itself, likely- Metal command-buffer completion handlers holding the GIL while the- local refs go out of scope. Diagnostic prints placed AFTER the- decode call never fire during the stall. The panel sits on "running"- the entire time, and from the user's perspective the render- "froze." Killing the helper is the only way out.-- The Fix- -------- Run a daemon thread that watches the output file. Once the file- exists with reasonable size (proves decode completed), give the- main thread a short grace period to finish naturally. If the- main thread DOESN'T emit "done" within that window, the watchdog:-- 1. Emits the "done" event itself (file IS on disk, so this is- not lying to the panel — the render succeeded).- 2. Calls ``os._exit(0)`` to bypass MLX's deallocator chains- entirely. ``os._exit`` doesn't run atexit handlers, doesn't- flush threads, and crucially doesn't need the GIL — it tells- the kernel to terminate the process immediately.-- The panel respawns the helper on the next job (~30s spawn cost).- That's a vastly better trade than 15-minute hangs.-- Usage- ------ wd = _PostDecodeWatchdog(- output_path=p["output_path"],- t0=t0,- job_id=job_id,- seed_used=seed,- action_label="extend",- )- wd.arm(grace_sec=30)- try:- pipe._decode_and_save_video(...)- ...- emit({"event": "done", ...})- wd.disarm() # main thread succeeded, watchdog stands down- except Exception:- wd.disarm()- raise- """+# NOTE — an earlier `_PostDecodeWatchdog` daemon-thread class lived+# here. It cannot fire under the MLX/Metal post-decode hang: the+# completion-handler chain blocks every Python thread's GIL access,+# so the daemon thread is starved by the very thing it was meant to+# escape. The rescue lives in the panel (mlx_ltx_panel.py,+# `WarmHelper._build_post_decode_panic`) where SIGKILL across the+# subprocess boundary works regardless of what the helper is holding+# internally. See ROADMAP for the full diagnosis.- def __init__(self, *, output_path: str, t0: float, job_id: str,- seed_used: int, action_label: str) -> None:- self.output_path = output_path- self.t0 = t0- self.job_id = job_id- self.seed_used = seed_used- self.action_label = action_label- self._disarmed = threading.Event()- self._thread: threading.Thread | None = None-- def arm(self, *, grace_sec: int = 30, absolute_cap_sec: int = 900) -> None:- """Start the watchdog. Idempotent."""- if self._thread and self._thread.is_alive():- return- self._disarmed.clear()- self._thread = threading.Thread(- target=self._run, args=(grace_sec, absolute_cap_sec),- name=f"phos-watchdog-{self.action_label}", daemon=True,- )- self._thread.start()-- def disarm(self) -> None:- """Tell the watchdog the main thread finished cleanly. Idempotent."""- self._disarmed.set()-- def _run(self, grace_sec: int, absolute_cap_sec: int) -> None:- start = time.time()- # Phase 1: wait for the output file to materialize. Decode could- # take ~10-60 seconds depending on res/frames; we don't want to- # arm the grace clock until we KNOW decode succeeded.- while not self._disarmed.is_set():- if time.time() - start > absolute_cap_sec:- return # absolute timeout — give up silently- try:- if (os.path.exists(self.output_path) and- os.path.getsize(self.output_path) > 1024):- break # file is on disk → enter phase 2- except OSError:- pass- time.sleep(1.0)- if self._disarmed.is_set():- return- # Phase 2: file exists. Give main thread the grace period to- # finish its emit("done") naturally. If it does, we exit- # quietly. If not, we assume the post-decode hang has happened.- if self._disarmed.wait(grace_sec):- return # main thread emitted done within grace- # Force the exit. The output IS on disk — the render succeeded.- elapsed = round(time.time() - self.t0, 2)- try:- sys.stderr.write(- f"[watchdog] {self.action_label}: main thread hung in "- f"post-decode MLX deallocator for >{grace_sec}s after "- f"file landed. Emitting done + force-exiting helper. "- f"Panel will respawn on next job.\n"- )- sys.stderr.flush()- except Exception:- pass- try:- emit({- "event": "done",- "id": self.job_id,- "output": self.output_path,- "elapsed_sec": elapsed,- "seed_used": self.seed_used,- "watchdog_forced_exit": True,- })- except Exception:- pass- try:- _real_stdout.flush()- except Exception:- pass- # os._exit terminates immediately — no atexit, no threading- # cleanup, no GIL needed. This is the whole point: bypass- # whatever Metal handler chain has the main thread stuck.- os._exit(0)def _install_video_decoder_patch() -> None:@@ -1866,23 +1743,17 @@ for line in sys.__stdin__:_free_pipe_for_decode(pipe)emit({"event": "log", "line": "step:free_generation_modules done"})emit({"event": "log", "line": "step:decode_and_save start"})- # Post-decode watchdog: on the DistilledPipeline two-stage- # path (T2V/I2V Balanced after the May-9 upstream refactor),- # Python stalls 5-15 minutes between the decoder's final- # write and the very next statement here — the function-- # return path itself hangs in MLX/Metal deallocator chains.- # Arming the watchdog BEFORE the call means that if main- # thread freezes, the daemon thread emits "done" and- # os._exit(0)s the helper. The file IS on disk by then- # (decoder logs "Decoding ... done" before returning), so- # the panel gets a truthful success event and the next- # job spawns a fresh helper. Mr Bizarro 2026-05-21:- # "fix it. What do you mean 'deferred to roadmap'?".- _wd = _PostDecodeWatchdog(- output_path=kwargs["output_path"], t0=t0, job_id=job_id,- seed_used=seed, action_label=f"generate:{mode}",- )- _wd.arm(grace_sec=30)+ # Post-decode hang: on DistilledPipeline.generate_two_stage+ # (T2V/I2V Balanced) the function-return path stalls 5-15 min+ # in MLX/Metal deallocator chains that hold every Python+ # thread's GIL access. An in-process daemon-thread watchdog+ # CAN'T fire (Metal holds something the watchdog needs to+ # advance). Rescue is done in the PANEL — `WarmHelper.run`+ # detects the decode-done log line, waits a grace period,+ # and SIGKILLs the helper if no done event arrives. The+ # output file is intact on disk by then so the panel+ # synthesizes a done event from the known output_path.+ # See `WarmHelper._build_post_decode_panic` in mlx_ltx_panel.py.# FIX 2026-05-14: upstream renamed fps= → frame_rate= (keyword-only).out_path = pipe._decode_and_save_video(video_latent, audio_latent, kwargs["output_path"], frame_rate=kwargs["frame_rate"])emit({"event": "log", "line": "step:decode_and_save done"})@@ -1903,13 +1774,6 @@ for line in sys.__stdin__:# that BEFORE the done event made the panel sit on "running"# for the full cleanup window (Mr Bizarro caught this 2026-05-21).emit(done_event)- # Tell the post-decode watchdog the main thread emitted done- # cleanly. If the watchdog isn't armed (use_model_upscale- # branch), this is a no-op via UnboundLocalError catch below.- try:- _wd.disarm()- except (NameError, UnboundLocalError):- pass# Now drop the latent refs. The panel has already moved on; the# helper just needs to be clean by the time the next job arrives.try:@@ -1918,10 +1782,6 @@ for line in sys.__stdin__:passexcept Exception as exc:_last_activity = time.time()- try:- _wd.disarm()- except (NameError, UnboundLocalError):- passemit({"event": "error", "id": job_id, "error": str(exc), "trace": traceback.format_exc()})finally:try:@@ -1962,13 +1822,16 @@ for line in sys.__stdin__:# extends into swap (240s/step instead of ~25s/step). The panel# exposes a "Fast" / "Quality" toggle that flips this to 3.0.cfg_scale = float(p.get("cfg_scale", 1.0))- num_steps = int(p.get("steps", 12))+ num_steps = int(p.get("steps", 8))# TeaCache for Extend (2026-05-18). Active only if the boot-time# patch landed AND the job spec doesn't explicitly opt out. The# monkey-patched guided_denoise_loop reads _EXTEND_TC_CONFIG to- # decide whether to construct a controller. Threshold defaults- # match the Stage-1 calibration's `LTX2_TEACACHE_THRESH=0.5`.+ # decide whether to construct a controller. Threshold bumped+ # from 0.5 → 0.7 on 2026-05-21 — at the lower step count (8+ # default) more aggressive block-skip pays off more, and at+ # cfg=1.0 single-branch denoising the quality cost is minimal.+ # Job spec can still override via `teacache_thresh`.enable_tc = bool(p.get("enable_teacache", True)) and _EXTEND_TC_PATCH_OKtc_thresh = p.get("teacache_thresh")if tc_thresh is not None:@@ -1976,6 +1839,8 @@ for line in sys.__stdin__:tc_thresh = float(tc_thresh)except (TypeError, ValueError):tc_thresh = None+ if tc_thresh is None:+ tc_thresh = 0.7 # was upstream default 0.5_EXTEND_TC_CONFIG = {"enable": enable_tc,"thresh": tc_thresh,@@ -1983,7 +1848,7 @@ for line in sys.__stdin__:}if enable_tc:emit({"event": "log",- "line": f"TeaCache active on extend (thresh={tc_thresh if tc_thresh is not None else 'default 0.5'})."})+ "line": f"TeaCache active on extend (thresh={tc_thresh})."})with _override_default_negative_prompt(p.get("negative_prompt")) as neg_active:if neg_active:emit({"event": "log", "line": "Avoid terms active via native CFG negative prompt."})@@ -2005,18 +1870,12 @@ for line in sys.__stdin__:pipe._loaded = Falseaggressive_cleanup()pipe._load_decoders()- # Post-decode watchdog: Extend hits the SAME MLX/Metal- # deallocator hang as I2V Balanced. The output file lands- # before the hang; the watchdog forces a clean done +- # process exit so the panel doesn't sit on "running" for- # 10+ minutes. Helper respawns on next job (~30s spawn- # cost). See _PostDecodeWatchdog docstring for the full- # rationale.- _wd = _PostDecodeWatchdog(- output_path=p["output_path"], t0=t0, job_id=job_id,- seed_used=seed, action_label="extend",- )- _wd.arm(grace_sec=30)+ # Post-decode hang: Extend hits the same MLX/Metal deallocator+ # freeze as I2V Balanced. Rescue is panel-side in+ # `WarmHelper._build_post_decode_panic` — an in-process daemon+ # thread can't fire because Metal holds GIL access during the+ # deallocator chain. See the same comment in the `generate`+ # action above.# FIX 2026-05-14: upstream made frame_rate= keyword-only required.pipe._decode_and_save_video(video_lat, audio_lat, p["output_path"], frame_rate=float(p.get("frame_rate", 24.0)))elapsed = round(time.time() - t0, 2)@@ -2026,13 +1885,8 @@ for line in sys.__stdin__:"output": p["output_path"], "elapsed_sec": elapsed,"seed_used": seed,})- _wd.disarm()except Exception as exc:_last_activity = time.time()- try:- _wd.disarm()- except (NameError, UnboundLocalError):- passemit({"event": "error", "id": job_id, "error": str(exc), "trace": traceback.format_exc()})finally:# Always clear the per-call TeaCache config so a future