Compare commits

..
18 Commits
Author SHA1 Message Date
gramps 1d35a7400f docs(37): close defaults/current split and advance the queue 2026-11-10 18:10:35 -08:00
gramps e6c6913994 feat(37): expose the staged-scene factory reset
App Settings can now restore only the staged canonical scene. The VM saves
pending edits first, resets that scene, reloads immediately, and keeps the same
scene staged. Other scene edits survive; the action is disabled while live or
recording. 615 tests green, clean build with 0 warnings.

Reference: OBS Scene Collections keep scene/source sets distinct:
https://obsproject.com/kb/scene-collections
2026-11-10 18:09:16 -08:00
gramps 41064bdd13 feat(37): expose the all-scenes factory reset
App Settings now offers a clearly described all-scenes reset. It is disabled
while live or recording and reloads the restored layout immediately. The
integration test drives the real VM command and checks the Settings binding.
614 tests green, clean build with 0 warnings.

Reference: OBS Scene Collections are a distinct saved set of scenes and sources:
https://obsproject.com/kb/scene-collections
2026-11-10 18:05:35 -08:00
gramps b8eb2b4451 feat(37): restore all scenes to factory defaults 2026-11-10 17:59:28 -08:00
gramps ff1c1965e0 fix(37): preserve camera choice when restoring default layouts
Build-mismatch restoration now keeps the currently selected webcam identity,
restores default scene placements against that camera, and leaves cameras absent
when none is selected. The integration regression test pins the creator's camera
choice and restored default geometry.
612 tests green, clean build with 0 warnings.
2026-11-10 17:56:24 -08:00
gramps c4da06b56b feat(37): reset one scene to its factory snapshot
The per-scene reset restores that scene's settings, layers, webcam placement,
and background-path settings while leaving other scenes' current edits alone.
A focused integration test covers the restore/isolation behavior.
611 tests green, clean build with 0 warnings.

Reference: OBS scene collections store scenes and sources as a saved set:
https://obsproject.com/kb/scene-collections
2026-11-10 17:52:20 -08:00
gramps 1c6fc3223d feat(37): restore the default layout when the build ID changes
A mismatched or missing current-build stamp restores the immutable default
snapshot atomically before the VM loads scenes. The new integration case edits
current on build A, opens on build B, and verifies the factory layout returns.
610 tests green, clean build with 0 warnings.

Reference: OBS scene collections keep scenes/sources as a separate saved set:
https://obsproject.com/kb/scene-collections
2026-11-10 17:48:43 -08:00
gramps 37791086ae feat(37): keep a default layout snapshot beside the current layout
The matching-build persistence slice is in place: existing layouts are captured
once as defaults, first-run factory scenes are saved and captured before the
creator can edit, and same-build startup continues to load current rows. Default
asset references survive current-layout saves.

One integration test covers the current-layout roundtrip and immutable default.
609 tests green, clean build with 0 warnings.

Reference scan: OBS stores scene collections separately from output profiles;
this split keeps layout state independent in the same SQLite store:
https://obsproject.com/kb/scene-collections
2026-11-10 17:45:39 -08:00
gramps b093609ad3 docs(14): close mic gain slice after creator test 2026-11-10 17:40:44 -08:00
gramps de787e0dad docs(65): replay clips complete; queue moves to 66 2026-11-10 12:55:06 -08:00
gramps 5fcfa545e5 feat(65): the replay layer plays — once in Live, looping everywhere else
608 green, 0 warnings. Completes the layer half of TASK 65.

- **(+) → Replay Clip** adds an ordinary media layer with an app-owned path, one per scene, silent by
  default (`MediaMuted`) and looping only outside Live — the compositor needs no special case.
- **F10 saves → the Live layer plays it once, then hides** (`SessionCompleted` → invisible, guard
  cleared). Every other scene with a replay layer keeps looping the kept set, advancing on each clip's
  completion, wrapping at the end.
- **The guard the creator asked for:** while that Live replay is playing, **F10 is inert** with a plain
  explanation. That is what replaces the impossible "exclude the layer from its own clip" — with one
  encoder and two muxes the clip *is* the program, so the fix is to not clip a clip.

`ReplayLayerTests` drives the real VM: one layer per scene, muted by default, once-through in Live,
looping in BRB, and a stray F10 with clips off writes nothing.
2026-11-10 12:54:54 -08:00
gramps a5c2061b55 feat(65): the replay layer exists in the model; the exclusion problem is solved by the guard
Slice 5a, scaffolding only. 607 green.

- `Source.IsReplayLayer` + schema column + roundtrip: a media layer that shows saved clips instead of a
  chosen file. The compositor needs to know nothing — it is a media layer whose path the VM owns.
- **Two spec corrections from the creator (2026-11-10), recorded in the task:**
  1. The immediate replay of a fresh clip happens **only in the Live scene**. While it plays, **F10 is
     inert** ("replay in progress").
  2. That guard replaces the "layer excluded from its own clip" idea, which is **impossible** with one
     encoder and two muxes: the clip is a second mux of the same frames, so it necessarily contains what
     viewers saw. No second encode, no fiction about a clean feed.

Remaining for 65: the add-layer menu entry, `ClipSaved` → play (Live: once then hide; elsewhere: loop the
kept set), `SessionCompleted` → advance or hide, and silent-by-default audio.
2026-11-10 12:48:41 -08:00
gramps 28657918f9 feat(65): F10 saves a clip; the gear drawer owns the three settings
Slice 4. 607 green, 0 warnings. Clips remain **off by default** and, while off, the ring is never
constructed — so no reader thread and no encoder output exist until someone asks for the feature.

- **F10** (`HotkeyId.SaveClip`, default F10, remappable in the hotkey dialog) snapshots the ring, writes
  the file, prunes to the retention count and toasts the name. Empty ring → "nothing to clip yet"
  instead of a zero-byte file; clips off → says so and points at Settings.
- **Settings**: Enable, length (10 or 15, default 10), keep (3/4/5, default 3). Persisted in the layout
  store and **coerced on load** — a bad stored value falls back to a legal one, so the ring can never be
  sized for a length the UI cannot show.
- The ring is sized from length × tier bitrate × 1.25 and rebuilt if either changes; it is created at
  session start and dropped at stop, so memory is only spent while a show is running.
- The drawer states the boundary in the creator's terms: "A capture, not an editor: for trimming,
  captions or a library, use a video editor."

Still to come: the replay layer itself (play once then hide in Live, loop the kept clips elsewhere).
2026-11-10 12:41:39 -08:00
gramps f7d3d1301e feat(65): clips on disk — write one, keep 3/4/5, delete the oldest
Slice 3 of TASK 65. 606 green, 0 warnings.

`ClipLibrary` is the whole of clip "management": a file lands in `clips\` beside the recordings, the
oldest is deleted past the retention count, and `Recent()` returns newest-first because that is also the
replay layer's playlist order. No gallery, no prompt, no naming.

Two guards the tests pin: an **empty snapshot never becomes a zero-byte file** (a save that fails loudly
is better than a file that won't open), and **pruning only touches our own prefix** — another file in the
folder survives.

`RingBytesFor(seconds, bitrate)` is the memory cap the ring is sized with: exact wire size × 1.25
headroom, because bitrate moves and the ring trims whole fragments.

Still to come: the replay layer, the F10 hotkey, and the Settings switch.
2026-11-10 12:35:38 -08:00
gramps 5066d81aab feat(65): the clip mux — a third output on the same ffmpeg, drained off the frame path
Slice 2 of TASK 65. 602 green, 0 warnings. **Clips are still off**: no `ClipBuffer` is passed, so the
ffmpeg command line is byte-for-byte what it was before this commit, and a test asserts exactly that
(the original args are a strict prefix of the new ones).

- `FfmpegArgs` appends a fragmented-MP4 output to `pipe:1` only when `ClipBuffer` is set. One-second
  fragments (`-frag_duration 1000000`) rather than the 4 s GOP, so a clip can start inside the window
  instead of at the last keyframe. Stats already own stderr, so stdout was free.
- `Fmp4FragmentSplitter` turns that byte stream into whole fragments: `ftyp`+`moov` is the init
  segment, each `moof`+`mdat` is a fragment. It parses box headers itself, survives a box being cut
  anywhere across reads, and **resyncs instead of throwing** — a clip fault must never take the stream
  down.
- `FfmpegEncoder` reads it on its own task, never blocking the frame path. Any exception logs and
  disables clips for the session; the broadcast is untouched.
- `IEncoderProcess` gained `StandardOutputBytes` (the seam already had the text reader for probing).

Next slices: the replay layer + retention, then the Settings switch with disabled-but-remembered controls.
2026-11-10 12:25:19 -08:00
gramps b93744ec7f feat(65): the replay ring — encoded fragments in RAM, capped by bytes
Slice 1 of TASK 65, pure memory, no encoder change yet.

A 1080p BGRA frame is 8.3 MB, so fifteen seconds of raw composite is ~7.4 GB — the 15 MB figure in the
spec is the *compressed* stream. So the ring holds fragmented-MP4 bytes that ffmpeg will write to a
pipe, and a save is init-segment + surviving fragments in order.

Two rules the tests pin: the cap is by **bytes** (bitrate moves; seconds do not), and the newest
fragments always win, because a clip that ends at the keypress is the entire point. The init segment does
not rotate and cannot be reused across encoder starts, so `Clear` drops it too — an MP4 without its moov
is noise.

Next slice: ffmpeg writes the buffer output to stdout while `-stats` stays on stderr, and the pump feeds
this ring. Not done here on purpose — an encoder change is the riskiest edit in the app and deserves its
own commit and test.
2026-11-10 11:59:02 -08:00
gramps 1a6a549e17 feat(55): stop leaving disk debts — temp clips and a low-disk guard
595 green, 0 warnings. Completes TASK 55 (slice 1, log rotation, shipped 2026-10-22).

- **`AlertClipCleanup`**: the default alert clip is materialised into `%TEMP%` for ffmpeg to read, and
  nothing ever deleted it — one orphan per profile that ever played an alert. Now: delete this session's
  file in `Shutdown`, and sweep `ytLive-alert-*.mp4` at startup for anything a crash left behind. Only
  the prefix we own is touched; a directory is never deleted.
- **`DiskSpaceGuard`**: a recording that dies of a full disk is a trust breach, so the numbers are a
  pure policy — refuse to start under **1 GB** (toast; the stream still starts, recording does not),
  warn under **5 GB** at start ("about eighty minutes" at 8 Mbps ≈ 3.6 GB/h), and one mid-show warning
  under **2 GB** — the last useful moment before the encoder fails for a reason it won't explain.
  Unreadable drives (a USB stick that just left) return null and never block a running recording.

Tests are policy-level on purpose: filling a real drive is not a test. `DiskHygieneTests` proves the
sweep only removes our own files and that the thresholds behave at both ends.
2026-11-10 11:55:42 -08:00
gramps c257de1516 feat(35): scenes remember the room — BRB mutes the mic on entry
591 green, 0 warnings.

- `Scene.SceneMutesMic` / `SceneMutesDesktop` are **nullable booleans**: null = leave the mix alone, so
  a scene is passive until the creator says otherwise. Schema columns added, NULL for every existing
  layout except one deliberate default.
- **Applied once when the scene takes the PROGRAM output** (`TransitionToScene`, only when live or
  recording). Staging a scene offline is auditioning, not a stream edit — the test asserts that.
- **The creator is boss:** a manual mute survives any transition into a scene with no opinion; a scene
  that does have one wins on its next entry. `SetMicMuted`/`SetGameMuted` are idempotent so a repeated
  "mute" cannot clobber the level that unmute would restore.
- **BRB ships muted** (creator spec) for new layouts *and* via a one-time migration for existing rows
  where the creator has never expressed an opinion.
- UI: two three-state checkboxes under the layers list ("When this scene goes live"), styled with
  `PropertyPillCheck` so the theme test holds.

`SceneAudioTests` covers the whole rule in one integration test: default state, offline staging does
nothing, live entry mutes, manual unmute survives a passive scene, an opinionated scene wins, desktop
untouched, and all three states roundtrip through save/reload.

Needs the creator's eye: the checkboxes are new chrome in the left panel (indeterminate = passive).
2026-11-10 11:51:21 -08:00
47 changed files with 2294 additions and 63 deletions
+4
View File
@@ -26,6 +26,10 @@ public partial class App : Application
AppLog.Write(args.Exception, "Dispatcher unhandled exception", AppLogErrorClass.Class1);
AppLog.Write("App OnStartup begin");
// TASK 55·2: a crash leaves the same temp clip a clean exit would have deleted.
var sweptClips = ytLive.Services.AlertClipCleanup.Sweep(System.IO.Path.GetTempPath());
if (sweptClips > 0) AppLog.Write($"Temp alert clips removed at startup: {sweptClips}");
// Attribution (2026-09-04): every take must be traceable to the exact binary
// that produced it — the wordmark shows the release counter (BuildStamp.Release);
// the per-build GUID is forensic only and lands here.
+26 -5
View File
@@ -101,6 +101,7 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
@@ -124,6 +125,8 @@
<MenuItem Header="Image" Command="{Binding AddImageCommand}"/>
<MenuItem Header="Video File" Command="{Binding AddMediaCommand}"
ToolTip="Play a video file in the scene (mp4, mov, avi, mkv, webm)"/>
<MenuItem Header="Replay Clip" Command="{Binding AddReplayLayerCommand}"
ToolTip="Plays saved replay clips: once in Live, looping in other scenes"/>
<MenuItem Header="Text" Command="{Binding AddSourceCommand}" CommandParameter="{x:Static models:SourceType.TextOverlay}"/>
<MenuItem Header="Countdown" Command="{Binding AddSourceCommand}" CommandParameter="{x:Static models:SourceType.Countdown}"
Visibility="{Binding IsCountdownAvailable, Converter={StaticResource BoolToVis}}"
@@ -341,10 +344,28 @@
HorizontalAlignment="Center" VerticalAlignment="Center"
Visibility="{Binding ShowSourcesEmptyHint, Converter={StaticResource BoolToVis}}"/>
<!-- TASK 35: the scene remembers the room. Three states on purpose:
checked = mute on entry, unchecked = unmute on entry, indeterminate = leave the
mix alone (the default, so a scene is passive until it is told). -->
<StackPanel Grid.Row="3" Margin="0,10,0,0"
Visibility="{Binding StagedScene, Converter={StaticResource NotNullToVis}}">
<TextBlock Text="WHEN THIS SCENE GOES LIVE" Style="{StaticResource SectionHeader}"/>
<CheckBox Content="Mute the mic" IsThreeState="True" Margin="10,6,0,0"
Style="{StaticResource PropertyPillCheck}"
IsChecked="{Binding SceneMutesMic, Mode=TwoWay}"
Foreground="{StaticResource Brush.OnSurface}" FontSize="12"
ToolTip="Checked mutes on entry · Unchecked unmutes on entry · Indeterminate leaves the mix alone"/>
<CheckBox Content="Mute desktop audio" IsThreeState="True" Margin="10,4,0,0"
Style="{StaticResource PropertyPillCheck}"
IsChecked="{Binding SceneMutesDesktop, Mode=TwoWay}"
Foreground="{StaticResource Brush.OnSurface}" FontSize="12"
ToolTip="Checked mutes on entry · Unchecked unmutes on entry · Indeterminate leaves the mix alone"/>
</StackPanel>
<!-- Resource alert: pinned to the bottom of the Layers panel.
Red when a required resource (the one-and-only webcam)
could not be locked; persists and re-polls until resolved. -->
<Border Grid.Row="3" Margin="0,8,0,0" Padding="8,6" CornerRadius="4"
<Border Grid.Row="4" Margin="0,8,0,0" Padding="8,6" CornerRadius="4"
Background="{StaticResource Brush.ErrorContainer}" BorderBrush="{StaticResource Brush.Error}" BorderThickness="1"
Visibility="{Binding WebcamLockAlert, Converter={StaticResource NotNullToVis}}">
<StackPanel>
@@ -358,17 +379,17 @@
<!-- ELEMENTS panel: per-element config beneath Sources.
Collapses entirely when no element is selected. -->
<Rectangle Grid.Row="4" Height="1" Fill="{StaticResource Brush.Outline}" Margin="0,22,0,10"/>
<StackPanel Grid.Row="5" Orientation="Horizontal" Margin="0,8,0,0">
<Rectangle Grid.Row="5" Height="1" Fill="{StaticResource Brush.Outline}" Margin="0,22,0,10"/>
<StackPanel Grid.Row="6" Orientation="Horizontal" Margin="0,8,0,0">
<Path Data="M12,8 A4,4 0 1 0 12.01,8 M19.4,15 L21,16.2 L19.4,19 L17.2,18.3 A7,7 0 0 1 15,19.4 L14.5,21.5 H9.5 L9,19.4 A7,7 0 0 1 6.8,18.3 L4.6,19 L3,16.2 L4.6,15 A7,7 0 0 1 4.6,9 L3,7.8 L4.6,5 L6.8,5.7 A7,7 0 0 1 9,4.6 L9.5,2.5 H14.5 L15,4.6 A7,7 0 0 1 17.2,5.7 L19.4,5 L21,7.8 L19.4,9 A7,7 0 0 1 19.4,15 Z"
Stroke="{StaticResource Brush.Tertiary}" StrokeThickness="1.6" StrokeLineJoin="Round"
Width="16" Height="16" Stretch="Uniform" VerticalAlignment="Center" Margin="0,0,6,0"/>
<TextBlock Text="PROPERTIES" Style="{StaticResource SectionHeader}" VerticalAlignment="Center"/>
</StackPanel>
<TextBlock Grid.Row="6" Text="Select an item to edit its properties" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12"
<TextBlock Grid.Row="7" Text="Select an item to edit its properties" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12"
Margin="8,4,0,0" TextWrapping="Wrap"
Visibility="{Binding SelectedElement, Converter={StaticResource NullToVis}}"/>
<ScrollViewer x:Name="ElementsScrollViewer" Grid.Row="6" VerticalScrollBarVisibility="Auto" Background="Transparent"
<ScrollViewer x:Name="ElementsScrollViewer" Grid.Row="7" VerticalScrollBarVisibility="Auto" Background="Transparent"
Visibility="{Binding SelectedElement, Converter={StaticResource NotNullToVis}}">
<StackPanel x:Name="ElementsPanel" Margin="8,4,0,0">
<StackPanel Visibility="{Binding SelectedElement.IsTextOverlay, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
+26
View File
@@ -63,6 +63,21 @@
</Popup>
<!-- ═══ ZOOM ═══ -->
<TextBlock Text="Clips" Style="{StaticResource SectionHeader}" Margin="0,10,0,4"/>
<CheckBox Content="Save replay clips" Style="{StaticResource PropertyPillCheck}" Margin="12,2,0,4"
IsChecked="{Binding ClipsEnabled, Mode=TwoWay}"
ToolTip="F10 saves the last few seconds of the show. Off by default; nothing runs while it is off."/>
<StackPanel Margin="12,0,0,4" IsEnabled="{Binding ClipsEnabled}">
<TextBlock Text="Clip length" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="0,0,0,2"/>
<ComboBox ItemsSource="{Binding ClipLengthOptions}" SelectedItem="{Binding ClipLengthText, Mode=TwoWay}"
Style="{StaticResource YtComboBox}" Height="28" Margin="0,0,0,6"/>
<TextBlock Text="Keep" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="0,0,0,2"/>
<ComboBox ItemsSource="{Binding ClipKeepOptions}" SelectedItem="{Binding ClipKeepText, Mode=TwoWay}"
Style="{StaticResource YtComboBox}" Height="28"/>
<TextBlock Text="A capture, not an editor: for trimming, captions or a library, use a video editor."
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="10" TextWrapping="Wrap" Margin="0,6,0,0"/>
</StackPanel>
<TextBlock Text="Zoom" Style="{StaticResource SectionHeader}" Margin="0,6,0,4"/>
<TextBlock Text="Zoom view shape" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="10,0,0,2"/>
@@ -108,6 +123,17 @@
Value="{Binding TransitionDurationMs, Mode=TwoWay}" VerticalAlignment="Center"/>
</DockPanel>
<!-- ═══ LAYOUT DEFAULTS (TASK 37) ═══ -->
<TextBlock Text="Layout defaults" Style="{StaticResource SectionHeader}" Margin="0,10,0,4"/>
<TextBlock Text="Replaces every scene and layer with this build’s factory layout. Your selected webcam stays the same."
Style="{StaticResource PropertyHint}" Margin="10,0,0,6"/>
<Button Content="Restore staged scene" Command="{Binding RestoreStagedSceneDefaultsCommand}"
Style="{StaticResource YtButtonSecondary}" Margin="10,0,0,4" HorizontalAlignment="Left"/>
<TextBlock Text="Resets only the scene currently staged in the preview."
Style="{StaticResource PropertyHint}" Margin="10,0,0,8"/>
<Button Content="Restore all scenes" Command="{Binding RestoreAllLayoutDefaultsCommand}"
Style="{StaticResource YtButtonSecondary}" Margin="10,0,0,10" HorizontalAlignment="Left"/>
<!-- Development panel host. Empty in a Release build: the panel itself is excluded
from the Release compile, and the code-behind only fills this inside #if DEBUG. -->
<StackPanel x:Name="DeveloperPanelHost"/>
+1 -1
View File
@@ -13,7 +13,7 @@ See [`schema.md`](../schema.md) for the memory-map conventions.
| `PreviewPane.xaml(.cs)` | Row 2 Col 1 center: 1920×1080 `OverlayCanvas`/`SelectionOverlay`/`BrandFlashLayer`/`SocialBarElement`, static TextOverlay preview image from the shared cached text raster, text drawer, outgoing-picture transition overlay, right-edge Stream Info/YPP/Socials/TEST tabs and drawers, and live controls (TRAX / game / mic meters + sliders + speakers). The list-selected draggable layer is temporarily raised in preview z-order and custom hit-testing; deselection restores the scene's unchanged order (`SelectedLayerPreviewHitTestingTests`). **TASK 57:** dragging/resizing a webcam in the vertical tier routes through `MainViewModel.MoveWebcamInVerticalTier` / `ResizeWebcamInVerticalTier` for the six-spot snap or Chat camera's two sizes. |
| `SceneThumbnailStrip.xaml(.cs)` | Top row over the preview column: five fixed-size scene cards with scene name, hotkey, staged `PROGRAM` badge, orange staged/live border |
| `LeftPanel.xaml(.cs)` | Row 2 Col 0 left panel: explicit EditingActive toggle on → Scene Layers+properties; off → YouTube chat, independent of stream status. Source add/edit/remove, list drag-to-reorder, snapshot revert-accept; TextOverlay properties edit multiline content, font type/family, size, color via the shared palette, emphasis, and horizontal/vertical alignment with a static-text notice; sub-options are indented under their headings. **TASK 51:** the webcam properties carry the Background section — `RemoveBackgroundPill` / `BlurBackgroundPill` (`PillToggle`, radio-exclusive via `WebcamSceneConfig.RemoveBackground`/`BlurBackground`) + `BackgroundStrengthSlider` (0..1, 5% snaps, shown only while an effect is on). **TASK 57:** the webcam properties carry a Geometry section (X/Y/W/H) — manual placement of the camera, bound to the **live** placement (the one the current tier shows), gated on `IsWebcamSelected` (not `SelectedElement.IsWebcam` — the TASK 51 test finds that panel by binding text and would match twice); the Shape button's `Visibility` is bound to `CanToggleClipShape`, so the circle option is NOT OFFERED in the vertical Chat layout. **TASK 58:** every drop-down, check box and field in the properties panel carries the theme's style (`YtComboBox`/`YtCheckBox`/`YtTextBoxCompact`) and paints no colour of its own — the guard is `ytLive.Tests/PropertiesStyleTests.cs`. **TASK 59:** the webcam's properties are a HIERARCHY — a `Shape` title owns the mirror switch and the shape choice (`Rect` | `Circle` as two `SegmentToggle` options, Rect selected by default, the circle option hidden where `CanToggleClipShape` is false), and every titled block (Geometry, Border Color, Border Thickness, Background) owns its content one indent deeper (Strength sits under Blur). **TASK 60:** the border-colour drop-down builds its menu from `Models/BorderColorPalette.cs` — each row is the hex plus the colour's NAME (`#e94560 Crimson`, tooltip "Crimson (#e94560)"); the swatch icon is unchanged. **TASK 61:** the four geometry fields (X/Y/W/H) share one fixed width (44px — the largest value, 1920, plus a sign) and their rows set `LastChildFill="False"`, so Y/H no longer stretch to fill the row. **TASK 62:** the border-colour field shows the palette's name beside the hex (`SelectedElement.BorderColorName`, empty for a custom hex) and keeps a fixed width so the name stays next to the hex. **TASK 63:** the border colour is picked with the **app's own drop-down** (`YtComboBox`) — the `...` button and its code-built `ContextMenu` are gone; the closed box shows the swatch + the colour's NAME, the rows show swatch + hex + name (the panel's own `DataTemplate`s + `Helpers/ClosedBoxTemplateSelector.cs`), and the hex field stays for a custom colour; `IsDescendantOf` falls back to `LogicalTreeHelper.GetParent` / `TemplatedParent` when `VisualTreeHelper.GetParent` returns `null` (at `PopupRoot`) so clicking a popup row does not trigger `MainWindow`'s deselection guard |
| `OverlayHost.xaml(.cs)` | Root-grid overlays: App Settings / Report Bug / Feature Request / About; About includes the output-quality conversion copy and an explicit llamacasty.com link, while the licensing/legal panel remains in-app. App Settings groups recording, brand-logo, preview, and transition controls. `BackToAbout_Click` lives here |
| `OverlayHost.xaml(.cs)` | Root-grid overlays: App Settings / Report Bug / Feature Request / About; About includes the output-quality conversion copy and an explicit llamacasty.com link, while the licensing/legal panel remains in-app. App Settings groups recording, brand-logo, preview, transition, and staged/all-scene layout-default controls. `BackToAbout_Click` lives here |
| `SceneThumbnailStrip.xaml.cs` | Code-behind for the strip above |
| `LeftPanel.xaml.cs` | Code-behind for the panel above |
+20 -30
View File
@@ -1,40 +1,30 @@
# HANDOFF — 2026-11-09 (TASK 33 done; queue re-ordered for 1.0)
# HANDOFF — 2026-11-10 (TASK 37 complete; queue advances to TASK 40)
## State
- `main`. TASK 21 (video layer + soundtrack), TASK 64 (green/blue screen) and TASK 32·4 (fragmented MP4)
are complete; TASK 49 is retired (YouTube owns chat moderation — we just don't paint tombstones).
- **Starting art**: `Assets/starting-background.jpg` is the corrected onboarding screen; bundled art is
hash-keyed into the layout DB, so `StampDefaultBackgroundAsset` compares bytes and re-stamps.
- Left panel alert stack shipped: Steam licence indicator pinned at row 1, event rows LIFO, click →
About or Logs with the event's lines painted. Detail: `docs/ai/ui-surface.md`.
- Site: demo video (silent loop) is the hero; Starting screen is in the scenes section.
- **TASK 33 complete** (`0fa3006`): cause-classified step-down — shed our capture cost, then fps →
resolution for the machine; bitrate only for the upload; one-way with recovery behind a flag.
- **Creator hands cleared 2026-11-09**: vertical camera check 1–6 pass; vertical cadence 29.8/s.
- Tests: 588 green; `FAST=1 ./scripts/verify.sh` ≈ 4 min.
- `main`, clean after this closeout. App commits remain local; do not push without a checkpoint request.
- **Done:** TASK 35 scene-linked audio, TASK 55 disk hygiene, TASK 65 replay clips, TASK 37 defaults/current split.
- TASK 37: SQLite keeps an immutable default snapshot beside build-stamped current rows; App Settings can
restore the staged scene or all scenes, offline only. Webcam identity survives both restore paths.
- TASK 14·15 mic input gain was closed by creator test (−2.6 dB, works great); slices 16–18 remain.
- Verification: **615 tests green, clean build with 0 warnings** (`FAST=1 ./scripts/verify.sh`).
- Steam remains blocked on Valve identity/tax review; no app IDs or store page.
## Next action
- **Queue re-ordered (creator ruling):** 35 → 37 → 40 → 55 → Move → 9·5 → 14 slices → 65 (clips) →
66 → 67 → 68 → 36. TASK 34 (scheduling) and 50 (publishing) are **retired** — platform's surface.
- **New:** 65 replay clips, 66 timed ticker, 67 per-event alert videos, 68 edit-while-live.
- Site repo commits are local (`llgit.llamachile.tube`); deploy is `./deploy.sh`, not a push.
- Do not push the app absent a checkpoint request.
- **Steam is a wait, not a task:** identity verification pending, tax review in Valve's queue (up to 30
business days). No app IDs, no store page, Release entitlement fails closed.
- Queue: **40·A/C/D → Move → 9·5 → 14·16/17/18 → 66 → 67 → 68 → 36**.
- Ask creator before TASK 68 about first-run ON-AIR default; before gold pass, settle the Release
single-instance mutex behavior.
- TASK 34 scheduling and TASK 50 recording publish are retired; YouTube owns those surfaces.
- Do not push app commits absent a checkpoint request.
## Landmines
- **The preview pane draws frame-source layers from a whitelist of DataTriggers.** A layer type with no
trigger is invisible in the preview while its decode looks healthy. Add the trigger with the layer
type; pin it with `MediaPreviewDisplayTests`.
- **A bundled-art "version" heal cannot work**: the constant and the embedded resource are compiled at
different moments, so a bump can race the image it is meant to ship. Compare bytes
(`LayoutStore.AssetMatches`). Also: `AllBackgrounds()` returns only the LIVE scene's rows.
- Pack URIs for bundled assets must be assembly-qualified (`/LlamaCasty;component/Assets/…`): the
unqualified form resolves against the entry assembly, which is the test host under `dotnet test`.
- Media sessions are keyed by **path + look** (`MainViewModel.MediaSessionKey`); never acquire by raw path.
- **The audio pipe allows ONE server per name**; DEBUG suffixes it (id, else pid), Release does not.
- Integration tests constructing `MainWindow` must set a temporary `LayoutPathOverride` and clear it in `finally`.
- Preview frame-source layers need a `PreviewPane` DataTrigger; pin each new type with a visibility test.
- Bundled-art healing compares bytes (`LayoutStore.AssetMatches`); a compiled version constant races its resource.
- Pack URIs for bundled assets must be assembly-qualified (`/LlamaCasty;component/Assets/…`).
- Media sessions are keyed by path + look; never acquire by raw path.
- Audio pipe allows one server per name; DEBUG suffixes it, Release does not.
- Any test constructing `MainWindow` must use a temporary `LayoutPathOverride` and clear it in `finally`.
- Build with the Windows `dotnet.exe` host from WSL; read render numbers in Release.
- Bundled FFmpeg stays outside the single-file exe (`ExcludeFromSingleFile="true"`).
+22
View File
@@ -72,6 +72,28 @@ public class Scene : INotifyPropertyChanged
public bool IsChatScene { get; init; }
private bool? _sceneMutesMic;
/// <summary>TASK 35: what this scene does to the mix when it takes the program output.
/// <c>null</c> = leave it alone (the default; scenes are passive until told); true mutes the mic on
/// entry. Applied once at entry, never while staging offline — auditioning a scene must not edit
/// the stream's state.</summary>
public bool? SceneMutesMic
{
get => _sceneMutesMic;
set => Set(ref _sceneMutesMic, value);
}
private bool? _sceneMutesDesktop;
/// <summary>TASK 35: as <see cref="SceneMutesMic"/>, for desktop/game audio.</summary>
public bool? SceneMutesDesktop
{
get => _sceneMutesDesktop;
set => Set(ref _sceneMutesDesktop, value);
}
/// <summary>
/// Asset-table id of this scene's top-strip tile artwork. The tile is a
/// separate image from the scene's background: the preview pane keeps
+10
View File
@@ -234,6 +234,16 @@ public class Source : SceneElement
set => Set(ref _mediaType, value);
}
private bool _isReplayLayer;
/// <summary>TASK 65: this media layer shows saved replay clips rather than a chosen file. The VM
/// owns its path and playlist; the compositor needs to know nothing.</summary>
public bool IsReplayLayer
{
get => _isReplayLayer;
set => Set(ref _isReplayLayer, value);
}
private string? _mediaPath;
public string? MediaPath
{
+60
View File
@@ -0,0 +1,60 @@
using System;
using System.IO;
namespace ytLive.Services;
/// <summary>
/// TASK 55·2: the default alert clip is materialised into <c>%TEMP%</c> so ffmpeg can read it as a file.
/// Nothing used to delete it, so every profile that ever played an alert left an orphan behind.
///
/// <para>Two touches, deliberately simple: delete this session's file on close, and sweep anything the
/// prefix matches at startup (a crash leaves the same debris a clean exit does not). Only files this app
/// created are touched — the prefix is the contract, and the sweep never deletes a directory.</para>
/// </summary>
public static class AlertClipCleanup
{
public const string Prefix = "ytLive-alert-";
/// <summary>Deletes stale alert clips left in <paramref name="directory"/>. Returns how many went.
/// Missing directory is not an error.</summary>
public static int Sweep(string directory)
{
try
{
if (!Directory.Exists(directory)) return 0;
var removed = 0;
foreach (var path in Directory.EnumerateFiles(directory, Prefix + "*.mp4"))
{
if (TryDelete(path)) removed++;
}
return removed;
}
catch (Exception ex)
{
Helpers.AppLog.Write(ex, "Alert clip sweep failed");
return 0;
}
}
/// <summary>Deletes one clip if it exists. Safe on null/blank and on a locked file.</summary>
public static bool Delete(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return false;
return TryDelete(path);
}
private static bool TryDelete(string path)
{
try
{
if (!File.Exists(path)) return false;
File.Delete(path);
return true;
}
catch (Exception ex)
{
Helpers.AppLog.Write(ex, $"Alert clip delete failed: {path}");
return false;
}
}
}
+97
View File
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ytLive.Services;
/// <summary>
/// TASK 65: where clips live and how many survive.
///
/// <para><b>Not clip management.</b> There is no gallery, no naming, no per-clip decision. A clip is
/// written to <c>clips\</c>, the oldest is deleted when the next one lands, and the only knobs are the
/// length (10 or 15 s) and how many to keep (3, 4 or 5). Anything richer belongs to a video editor.</para>
/// </summary>
public sealed class ClipLibrary
{
public const string Extension = ".mp4";
public const string FilePrefix = "clip-";
private readonly Func<string> _folder;
public ClipLibrary(Func<string> folder) => _folder = folder;
/// <summary>Bytes the ring should hold for a length and bitrate, with 25% headroom for bitrate
/// movement. This is a memory cap, not a duration — the ring trims whole fragments.</summary>
public static long RingBytesFor(int seconds, int bitrateKbps)
=> Math.Max(1, seconds) * (long)bitrateKbps * 1000 / 8 * 5 / 4;
/// <summary>Writes a clip and prunes to <paramref name="keep"/>; returns the file path, or null when
/// there was nothing to write (an empty snapshot must never become a zero-byte file).</summary>
public string? Save(byte[] mp4Bytes, DateTime nowLocal, int keep)
{
if (mp4Bytes.Length == 0) return null;
try
{
var folder = EnsureFolder();
var path = Path.Combine(folder, $"{FilePrefix}{nowLocal:yyyyMMdd-HHmmss}{Extension}");
var unique = path;
for (var n = 2; File.Exists(unique); n++)
unique = Path.Combine(folder, $"{FilePrefix}{nowLocal:yyyyMMdd-HHmmss}-{n}{Extension}");
File.WriteAllBytes(unique, mp4Bytes);
Prune(keep);
return unique;
}
catch (Exception ex)
{
Helpers.AppLog.Write(ex, "Clip save failed");
return null;
}
}
/// <summary>Newest first. The replay layer's playlist is this list, so its order matters.</summary>
public IReadOnlyList<string> Recent()
{
try
{
var folder = EnsureFolder();
return Directory.EnumerateFiles(folder, FilePrefix + "*" + Extension)
.OrderByDescending(p => p, StringComparer.OrdinalIgnoreCase)
.ToList();
}
catch (Exception ex)
{
Helpers.AppLog.Write(ex, "Clip list failed");
return Array.Empty<string>();
}
}
/// <summary>Deletes everything past the retention count. Missing folders are not an error.</summary>
public int Prune(int keep)
{
if (keep < 1) keep = 1;
var removed = 0;
foreach (var stale in Recent().Skip(keep))
{
try
{
File.Delete(stale);
removed++;
}
catch (Exception ex)
{
Helpers.AppLog.Write(ex, $"Clip prune failed: {stale}");
}
}
return removed;
}
/// <summary>The folder beside the recordings, created on demand.</summary>
public string EnsureFolder()
{
var folder = Path.Combine(_folder(), "clips");
Directory.CreateDirectory(folder);
return folder;
}
}
+91
View File
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
namespace ytLive.Services;
/// <summary>
/// TASK 65: the replay buffer's memory. ffmpeg writes fragmented MP4 to a pipe; the app keeps the last
/// N seconds of those fragments here and hands them back whole.
///
/// <para><b>Why encoded bytes and not frames:</b> a 1080p BGRA composite frame is 8.3 MB, so fifteen
/// seconds at 60 fps is ~7.4 GB of raw frames. The 15 MB figure is the compressed stream, and only that
/// fits in RAM. <b>Why whole fragments:</b> a fragment is the smallest thing that can be replayed, so the
/// cap is a byte cap and the clip may be slightly shorter than the requested seconds — never corrupt.</para>
/// </summary>
public sealed class ClipRing
{
private readonly long _capBytes;
private readonly Queue<byte[]> _fragments = new();
private byte[]? _init;
private long _bytes;
public ClipRing(long capBytes)
{
if (capBytes <= 0) throw new ArgumentOutOfRangeException(nameof(capBytes));
_capBytes = capBytes;
}
/// <summary>The stream's initialisation segment (ftyp + moov). Every replayable file needs it, and
/// it does not rotate — it is written once per encoder start.</summary>
public void SetInit(byte[] init)
{
_init = init ?? throw new ArgumentNullException(nameof(init));
RecomputeBytes();
Trim();
}
public void Append(byte[] fragment)
{
if (fragment is null || fragment.Length == 0) return;
_fragments.Enqueue(fragment);
_bytes += fragment.Length;
Trim();
}
public long Bytes => _bytes;
public int FragmentCount => _fragments.Count;
public bool IsEmpty => _init is null || _fragments.Count == 0;
/// <summary>The bytes of a playable clip, init first. Empty array when nothing has been buffered —
/// the caller must not write a zero-byte file (a failed save is better than a file that won't open).</summary>
public byte[] Snapshot()
{
if (IsEmpty) return Array.Empty<byte>();
var total = _init!.Length;
foreach (var fragment in _fragments) total += fragment.Length;
var output = new byte[total];
var offset = 0;
Buffer.BlockCopy(_init, 0, output, offset, _init.Length);
offset += _init.Length;
foreach (var fragment in _fragments)
{
Buffer.BlockCopy(fragment, 0, output, offset, fragment.Length);
offset += fragment.Length;
}
return output;
}
public void Clear()
{
_fragments.Clear();
_init = null;
_bytes = 0;
}
private void RecomputeBytes()
{
_bytes = _init?.Length ?? 0;
foreach (var fragment in _fragments) _bytes += fragment.Length;
}
/// <summary>Drop oldest fragments until the ring fits. Newest data always wins: a clip that ends at
/// the moment the creator pressed the key is the whole point.</summary>
private void Trim()
{
while (_fragments.Count > 0 && _bytes > _capBytes)
{
_bytes -= _fragments.Dequeue().Length;
}
}
}
+51
View File
@@ -0,0 +1,51 @@
using System;
namespace ytLive.Services;
/// <summary>
/// TASK 55·3: a recording that dies of a full disk is a trust breach, not a support ticket. The guard is
/// a pure threshold policy so the numbers are visible in one place and testable without a drive.
///
/// <para>Thresholds chosen 2026-11-10 for a 1080p stream at 8 Mbps (~3.6 GB/hour): refusing to start
/// under <b>1 GB</b> keeps the creator from beginning something that cannot finish; a warning under
/// <b>5 GB</b> says "you have about eighty minutes" while there is still time to act; and one mid-show
/// warning at <b>2 GB</b> is the last useful moment before the encoder fails for a reason it will not
/// explain.</para>
/// </summary>
public static class DiskSpaceGuard
{
public const long BlockStartBytes = 1L * 1024 * 1024 * 1024;
public const long WarnStartBytes = 5L * 1024 * 1024 * 1024;
public const long WarnDuringBytes = 2L * 1024 * 1024 * 1024;
public enum StartDecision
{
Ok,
Warn,
Block,
}
public static StartDecision ForStart(long freeBytes)
=> freeBytes < BlockStartBytes ? StartDecision.Block
: freeBytes < WarnStartBytes ? StartDecision.Warn
: StartDecision.Ok;
/// <summary>One warning per session, once the drive falls below the mid-recording threshold.</summary>
public static bool ShouldWarnDuring(long freeBytes) => freeBytes < WarnDuringBytes;
/// <summary>Free bytes on the drive that holds <paramref name="folder"/>, or null when it cannot be
/// read (a removable drive that just went away must not block a recording that is already running).</summary>
public static long? FreeBytes(string folder)
{
try
{
var root = System.IO.Path.GetPathRoot(System.IO.Path.GetFullPath(folder));
if (string.IsNullOrEmpty(root)) return null;
return new System.IO.DriveInfo(root).AvailableFreeSpace;
}
catch
{
return null;
}
}
}
+5
View File
@@ -50,6 +50,11 @@ public sealed class EncoderOptions
/// <summary>Name of the mixer's audio pipe (default <see cref="DefaultAudioPipeName"/>).</summary>
public string AudioPipeName { get; init; } = DefaultAudioPipeName;
/// <summary>TASK 65: when set, the encoder muxes a SECOND video output into this ring (fragmented
/// MP4 on stdout) for the replay buffer. Null = clips off, and the ffmpeg command line is exactly
/// what it was before the feature existed.</summary>
public Services.ClipRing? ClipBuffer { get; init; }
/// <summary>GOP in frames = Fps × 4s — the YouTube keyframe ≤ 4s compliance bound.</summary>
public int GopSize => Fps * 4;
}
+13
View File
@@ -52,6 +52,19 @@ public static class FfmpegArgs
args.AddRange(["-f", "mp4", options.RecordPath!]);
}
// TASK 65: the replay buffer is a third mux of the same encoded frames. Fragmented MP4 on
// stdout (stats already own stderr) — one fragment per second, so a clip can start anywhere
// inside the chosen window instead of at the last 4-second keyframe.
if (options.ClipBuffer != null)
{
AddVideoTags(args, options, videoEncoder);
args.AddRange(["-c:a", "aac",
"-ar", options.AudioSampleRate.ToString(), "-ac", options.AudioChannels.ToString()]);
args.AddRange(["-movflags", "+frag_keyframe+empty_moov+default_base_moof"]);
args.AddRange(["-frag_duration", "1000000"]);
args.AddRange(["-f", "mp4", "pipe:1"]);
}
return args;
}
+23
View File
@@ -118,6 +118,11 @@ public sealed class FfmpegEncoder : IFfmpegEncoder
_stopRequested = false;
_stderrLoop = RunStderrLoopAsync(process);
StartDrainLoop(process);
// TASK 65: the clip mux is a side channel. It reads its own thread, never blocks the frame
// path, and a fault disables clips instead of touching the stream.
if (options.ClipBuffer is { } clipRing)
_ = Task.Run(() => ReadClipOutputAsync(process, clipRing));
}
/// <summary>
@@ -239,6 +244,24 @@ public sealed class FfmpegEncoder : IFfmpegEncoder
/// ArrayPool may return a larger buffer), returned to the pool after the write
/// copies into the pipe, and stdin is closed (EOF) once the queue drains.
/// </summary>
private static async Task ReadClipOutputAsync(IEncoderProcess process, Services.ClipRing ring)
{
var splitter = new Fmp4FragmentSplitter(ring);
var buffer = new byte[64 * 1024];
try
{
var stdout = process.StandardOutputBytes;
int read;
while ((read = await stdout.ReadAsync(buffer).ConfigureAwait(false)) > 0)
splitter.Write(buffer.AsSpan(0, read));
}
catch (Exception ex)
{
// Clips stop; the broadcast does not.
AppLog.Write(ex, "Clip buffer reader failed — replay clips disabled for this session");
}
}
private void StartDrainLoop(IEncoderProcess process)
{
_drainTask = Task.Run(async () =>
+2
View File
@@ -21,6 +21,8 @@ public sealed class FfmpegEncoderProcess : IEncoderProcess
}
public Stream StandardInput => _process.StandardInput.BaseStream;
public Stream StandardOutputBytes => _process.StandardOutput.BaseStream;
public TextReader StandardOutput => _process.StandardOutput;
public TextReader StandardError => _process.StandardError;
+102
View File
@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ytLive.Services.Encoder;
/// <summary>
/// TASK 65: turns the fragmented-MP4 byte stream ffmpeg writes to stdout into a playable ring.
///
/// <para>MP4 boxes are length-prefixed, so this needs no muxer cooperation: <c>ftyp</c>+<c>moov</c> are
/// the initialisation segment, and each <c>moof</c>+<c>mdat</c> pair is one fragment. The ring only ever
/// sees whole fragments, which is what makes a snapshot playable and a trim safe.</para>
///
/// <para>Deliberately forgiving: an unparseable header clears the buffer and waits for the next one. A
/// clip that fails must never take the encoder down with it — the stream is running through the same
/// process.</para>
/// </summary>
public sealed class Fmp4FragmentSplitter
{
private readonly ClipRing _ring;
private readonly List<byte> _pending = new(capacity: 64 * 1024);
private readonly MemoryStream _init = new();
private readonly MemoryStream _fragment = new();
private bool _inFragment;
public Fmp4FragmentSplitter(ClipRing ring) => _ring = ring;
public void Write(ReadOnlySpan<byte> data)
{
foreach (var b in data) _pending.Add(b);
Drain();
}
private void Drain()
{
while (true)
{
if (_pending.Count < 8) return;
long size = ((long)_pending[0] << 24) | ((long)_pending[1] << 16) | ((long)_pending[2] << 8) | _pending[3];
var type = Encoding.ASCII.GetString(_pending.GetRange(4, 4).ToArray());
var header = 8;
if (size == 1)
{
if (_pending.Count < 16) return;
size = 0;
for (var i = 8; i < 16; i++) size = (size << 8) | _pending[i];
header = 16;
}
if (size < header || size > int.MaxValue)
{
// Not a box boundary any more; drop what we have and resync on the next write.
_pending.Clear();
return;
}
if (_pending.Count < size) return;
var box = _pending.GetRange(0, (int)size).ToArray();
_pending.RemoveRange(0, (int)size);
Route(type, box);
}
}
private void Route(string type, byte[] box)
{
switch (type)
{
case "ftyp":
_init.Write(box);
break;
case "moov":
_init.Write(box);
_ring.SetInit(_init.ToArray()); // init is complete once moov lands
break;
case "moof":
FlushFragment();
_fragment.Write(box);
_inFragment = true;
break;
case "mdat":
if (!_inFragment) return; // mdat without a moof is not replayable
_fragment.Write(box);
FlushFragment();
break;
default:
if (_inFragment) _fragment.Write(box);
break;
}
}
private void FlushFragment()
{
if (_inFragment && _fragment.Length > 0)
_ring.Append(_fragment.ToArray());
_fragment.SetLength(0);
_inFragment = false;
}
}
+4
View File
@@ -17,6 +17,10 @@ public interface IEncoderProcess : IDisposable
Stream StandardInput { get; }
TextReader StandardOutput { get; }
/// <summary>TASK 65: the same stdout as raw bytes — the replay-buffer mux writes fragmented MP4
/// here while <c>-stats</c> keeps stderr for itself.</summary>
Stream StandardOutputBytes { get; }
TextReader StandardError { get; }
bool HasExited { get; }
+3
View File
@@ -16,6 +16,8 @@ public enum HotkeyId
ToggleMicMute = 7,
ToggleGameMute = 8,
TraxPlayPause = 9,
/// <summary>TASK 65: snapshot the replay ring and save it as a clip.</summary>
SaveClip = 10,
}
/// <summary>Registers/revokes the OS-level hotkeys. Seam so tests never touch
@@ -65,6 +67,7 @@ public sealed class GlobalHotkeyManager
[HotkeyId.ToggleMicMute] = new HotkeyChord(0, 0x76), // F7
[HotkeyId.ToggleGameMute] = new HotkeyChord(0, 0x77), // F8
[HotkeyId.TraxPlayPause] = new HotkeyChord(0, 0x78), // F9
[HotkeyId.SaveClip] = new HotkeyChord(0, 0x79), // F10
};
private readonly IHotkeyRegistrar _registrar;
+6 -2
View File
@@ -16,7 +16,7 @@ public partial class LayoutStore : IDisposable
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = "SELECT Id, Name, IsHidden, IsChatScene, HasBackground, HasSocialBar, ThumbnailAssetId FROM Scene ORDER BY SortOrder";
cmd.CommandText = "SELECT Id, Name, IsHidden, IsChatScene, HasBackground, HasSocialBar, ThumbnailAssetId, SceneMutesMic, SceneMutesDesktop FROM Scene ORDER BY SortOrder";
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
@@ -29,6 +29,8 @@ public partial class LayoutStore : IDisposable
HasBackground = reader.GetInt32(4) != 0,
HasSocialBar = reader.FieldCount > 5 && !reader.IsDBNull(5) && reader.GetInt32(5) != 0,
ThumbnailAssetId = reader.FieldCount > 6 && !reader.IsDBNull(6) ? reader.GetString(6) : null,
SceneMutesMic = reader.FieldCount > 7 && !reader.IsDBNull(7) ? reader.GetInt32(7) != 0 : null,
SceneMutesDesktop = reader.FieldCount > 8 && !reader.IsDBNull(8) ? reader.GetInt32(8) != 0 : null,
});
}
}
@@ -115,7 +117,7 @@ public partial class LayoutStore : IDisposable
TextContent, TextFontFamily, TextFontSize, TextColor, TextBold, TextItalic,
TextUnderline, TextAlignment, TextVerticalAlignment, MediaMuted,
ChromaKeyEnabled, ChromaKeyColor, ChromaKeySimilarity, ChromaKeySoftness,
ChromaKeySpill, ChromaScreen
ChromaKeySpill, ChromaScreen, IsReplayLayer
FROM Source ORDER BY SortOrder
""";
using var reader = cmd.ExecuteReader();
@@ -196,6 +198,8 @@ public partial class LayoutStore : IDisposable
ChromaScreen = reader.IsDBNull(reader.GetOrdinal("ChromaScreen"))
? ChromaScreen.Green
: (ChromaScreen)reader.GetInt32(reader.GetOrdinal("ChromaScreen")),
IsReplayLayer = !reader.IsDBNull(reader.GetOrdinal("IsReplayLayer"))
&& reader.GetInt32(reader.GetOrdinal("IsReplayLayer")) != 0,
};
if (!sourcesByScene.TryGetValue(sceneId, out var list))
sourcesByScene[sceneId] = list = new List<(Source, int)>();
+47
View File
@@ -16,6 +16,8 @@ public partial class LayoutStore : IDisposable
IsHidden INTEGER NOT NULL DEFAULT 0,
IsChatScene INTEGER NOT NULL DEFAULT 0,
HasBackground INTEGER NOT NULL DEFAULT 1,
SceneMutesMic INTEGER NULL,
SceneMutesDesktop INTEGER NULL,
SortOrder INTEGER NOT NULL DEFAULT 0
);
""",
@@ -46,6 +48,7 @@ public partial class LayoutStore : IDisposable
ClipShape TEXT NOT NULL DEFAULT 'Traditional',
IsMirrored INTEGER NOT NULL DEFAULT 0,
IsBackground INTEGER NOT NULL DEFAULT 0,
IsReplayLayer INTEGER NOT NULL DEFAULT 0,
CaptureKey TEXT,
SortOrder INTEGER NOT NULL DEFAULT 0
);
@@ -139,10 +142,12 @@ public partial class LayoutStore : IDisposable
MigrateSceneTable();
MigrateSceneSocialBarColumn();
MigrateSceneThumbnailColumn();
MigrateSceneAudioColumns();
MigrateSocialsTable();
MigrateSocialEntryTable();
if (GetUserVersion() < 3)
MigrateToV3();
EnsureLayoutSnapshotSchema();
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = "PRAGMA user_version = 10;";
@@ -154,6 +159,40 @@ public partial class LayoutStore : IDisposable
// v1 → v2: Source gains ClipShape + IsMirrored (webcam clip/mirror prefs).
// CREATE TABLE IF NOT EXISTS doesn't touch existing tables, so pre-v2 DBs
// get the columns here instead.
/// <summary>TASK 35: scene-linked audio. NULL means "leave the mix alone", so a scene is passive
/// until the creator says otherwise — including every layout written before this column existed.</summary>
private void MigrateSceneAudioColumns()
{
var sceneColumns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = "PRAGMA table_info(Scene);";
using var reader = cmd.ExecuteReader();
while (reader.Read())
sceneColumns.Add(reader.GetString(1));
}
if (!sceneColumns.Contains("SceneMutesMic"))
{
using var cmd = _connection.CreateCommand();
cmd.CommandText = "ALTER TABLE Scene ADD COLUMN SceneMutesMic INTEGER NULL;";
cmd.ExecuteNonQuery();
}
if (!sceneColumns.Contains("SceneMutesDesktop"))
{
using var cmd = _connection.CreateCommand();
cmd.CommandText = "ALTER TABLE Scene ADD COLUMN SceneMutesDesktop INTEGER NULL;";
cmd.ExecuteNonQuery();
}
// BRB ships muted (creator spec), applied only where the creator has never expressed an opinion.
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = "UPDATE Scene SET SceneMutesMic = 1 WHERE SceneMutesMic IS NULL AND LOWER(TRIM(Name)) = 'brb';";
cmd.ExecuteNonQuery();
}
}
private void MigrateSourceTable()
{
var columns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
@@ -283,6 +322,14 @@ public partial class LayoutStore : IDisposable
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChatSuperChatColor TEXT NOT NULL DEFAULT '#eab308';";
cmd.ExecuteNonQuery();
}
// TASK 65: a media layer that plays the replay clips instead of a chosen file.
if (!columns.Contains("IsReplayLayer"))
{
using var cmd = _connection.CreateCommand();
cmd.CommandText = "ALTER TABLE Source ADD COLUMN IsReplayLayer INTEGER NOT NULL DEFAULT 0;";
cmd.ExecuteNonQuery();
}
if (!columns.Contains("ShowDesktop"))
{
using var cmd = _connection.CreateCommand();
+22 -4
View File
@@ -54,8 +54,10 @@ public partial class LayoutStore : IDisposable
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = """
INSERT INTO Scene (Id, Name, IsHidden, IsChatScene, HasBackground, HasSocialBar, ThumbnailAssetId, SortOrder)
VALUES ($id, $name, $isHidden, $isChat, $hasBackground, $hasSocialBar, $thumbnail, $sort)
INSERT INTO Scene (Id, Name, IsHidden, IsChatScene, HasBackground, HasSocialBar, ThumbnailAssetId,
SceneMutesMic, SceneMutesDesktop, SortOrder)
VALUES ($id, $name, $isHidden, $isChat, $hasBackground, $hasSocialBar, $thumbnail,
$mutesMic, $mutesDesktop, $sort)
""";
cmd.Transaction = tx;
var idP = cmd.Parameters.Add("$id", SqliteType.Text);
@@ -65,6 +67,8 @@ public partial class LayoutStore : IDisposable
var backgroundP = cmd.Parameters.Add("$hasBackground", SqliteType.Integer);
var socialBarP = cmd.Parameters.Add("$hasSocialBar", SqliteType.Integer);
var thumbnailP = cmd.Parameters.Add("$thumbnail", SqliteType.Text);
var mutesMicP = cmd.Parameters.Add("$mutesMic", SqliteType.Integer);
var mutesDesktopP = cmd.Parameters.Add("$mutesDesktop", SqliteType.Integer);
var sortP = cmd.Parameters.Add("$sort", SqliteType.Integer);
var sort = 0;
@@ -77,6 +81,12 @@ public partial class LayoutStore : IDisposable
backgroundP.Value = scene.HasBackground ? 1 : 0;
socialBarP.Value = scene.HasSocialBar ? 1 : 0;
thumbnailP.Value = (object?)scene.ThumbnailAssetId ?? DBNull.Value;
mutesMicP.Value = scene.SceneMutesMic.HasValue
? (object)(scene.SceneMutesMic.Value ? 1 : 0)
: DBNull.Value;
mutesDesktopP.Value = scene.SceneMutesDesktop.HasValue
? (object)(scene.SceneMutesDesktop.Value ? 1 : 0)
: DBNull.Value;
sortP.Value = sort++;
cmd.ExecuteNonQuery();
}
@@ -96,7 +106,7 @@ public partial class LayoutStore : IDisposable
TextContent, TextFontFamily, TextFontSize, TextColor, TextBold, TextItalic,
TextUnderline, TextAlignment, TextVerticalAlignment, MediaMuted,
ChromaKeyEnabled, ChromaKeyColor, ChromaKeySimilarity,
ChromaKeySoftness, ChromaKeySpill, ChromaScreen)
ChromaKeySoftness, ChromaKeySpill, ChromaScreen, IsReplayLayer)
VALUES ($id, $sceneId, $assetId, $type, $name, $isEnabled,
$x, $y, $w, $h, $opacity, $monitor,
$clip, $mirrored, $isBackground, $captureKey, $showDesktop, $sort,
@@ -108,7 +118,7 @@ public partial class LayoutStore : IDisposable
$textContent, $textFontFamily, $textFontSize, $textColor, $textBold, $textItalic,
$textUnderline, $textAlignment, $textVerticalAlignment, $mediaMuted,
$chromaEnabled, $chromaColor, $chromaSimilarity, $chromaSoftness,
$chromaSpill, $chromaScreen)
$chromaSpill, $chromaScreen, $isReplayLayer)
""";
cmd.Transaction = tx;
var idP = cmd.Parameters.Add("$id", SqliteType.Text);
@@ -148,6 +158,7 @@ public partial class LayoutStore : IDisposable
var chromaSoftnessP = cmd.Parameters.Add("$chromaSoftness", SqliteType.Real);
var chromaSpillP = cmd.Parameters.Add("$chromaSpill", SqliteType.Integer);
var chromaScreenP = cmd.Parameters.Add("$chromaScreen", SqliteType.Integer);
var replayLayerP = cmd.Parameters.Add("$isReplayLayer", SqliteType.Integer);
var mediaPlaybackStateP = cmd.Parameters.Add("$mediaPlaybackState", SqliteType.Text);
var alertVideoAssetIdP = cmd.Parameters.Add("$alertVideoAssetId", SqliteType.Text);
var alertVideoPathP = cmd.Parameters.Add("$alertVideoPath", SqliteType.Text);
@@ -216,6 +227,7 @@ public partial class LayoutStore : IDisposable
chromaSoftnessP.Value = source.ChromaKeySoftness;
chromaSpillP.Value = source.ChromaKeySpill ? 1 : 0;
chromaScreenP.Value = (int)source.ChromaScreen;
replayLayerP.Value = source.IsReplayLayer ? 1 : 0;
mediaPlaybackStateP.Value = source.MediaPlaybackState.ToString();
alertVideoAssetIdP.Value = (object?)source.AlertVideoAssetId ?? DBNull.Value;
alertVideoPathP.Value = (object?)source.AlertVideoPath ?? DBNull.Value;
@@ -422,10 +434,16 @@ public partial class LayoutStore : IDisposable
DELETE FROM Asset WHERE Id NOT IN (
SELECT AssetId FROM Source WHERE AssetId IS NOT NULL
UNION
SELECT AssetId FROM DefaultSource WHERE AssetId IS NOT NULL
UNION
SELECT ThumbnailAssetId FROM Scene WHERE ThumbnailAssetId IS NOT NULL
UNION
SELECT ThumbnailAssetId FROM DefaultScene WHERE ThumbnailAssetId IS NOT NULL
UNION
SELECT AlertVideoAssetId FROM Source WHERE AlertVideoAssetId IS NOT NULL
UNION
SELECT AlertVideoAssetId FROM DefaultSource WHERE AlertVideoAssetId IS NOT NULL
UNION
SELECT Value FROM Settings WHERE Key = 'AlertDefaultVideoAssetId'
UNION
SELECT Value FROM Settings WHERE Key = 'OnAirImageAssetId'
+17
View File
@@ -63,6 +63,23 @@ public partial class LayoutStore : IDisposable
public void SaveShowMonetaryMetrics(bool show) => UpsertSetting("Metrics.ShowMonetary", show ? "1" : "0");
/// <summary>TASK 65: replay clips. Off by default — the ring costs memory and the feature is opt-in.</summary>
public bool LoadClipsEnabled() => GetSetting("Clips.Enabled") == "1";
public void SaveClipsEnabled(bool enabled) => UpsertSetting("Clips.Enabled", enabled ? "1" : "0");
/// <summary>Clip length in seconds: 10 or 15 (default 10).</summary>
public int LoadClipSeconds()
=> int.TryParse(GetSetting("Clips.Seconds"), out var s) && (s == 10 || s == 15) ? s : 10;
public void SaveClipSeconds(int seconds) => UpsertSetting("Clips.Seconds", seconds.ToString());
/// <summary>How many clips survive on disk: 3, 4 or 5 (default 3).</summary>
public int LoadClipKeep()
=> int.TryParse(GetSetting("Clips.Keep"), out var k) && k >= 3 && k <= 5 ? k : 3;
public void SaveClipKeep(int keep) => UpsertSetting("Clips.Keep", keep.ToString());
public bool LoadAutoChromaScreen() => GetSetting("Video.AutoChromaScreen") == "1";
public void SaveAutoChromaScreen(bool enabled) => UpsertSetting("Video.AutoChromaScreen", enabled ? "1" : "0");
+348
View File
@@ -0,0 +1,348 @@
using Microsoft.Data.Sqlite;
namespace ytLive.Services;
public partial class LayoutStore : IDisposable
{
private static readonly string[] SnapshotTables =
{
"Scene", "Source", "Webcam", "WebcamSceneConfig", "Socials", "SocialEntry", "Music",
};
private const string DefaultsInitializedKey = "DefaultsInitialized";
private const string CurrentBuildIdKey = "CurrentBuildId";
private void EnsureLayoutSnapshotSchema()
{
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = """
CREATE TABLE IF NOT EXISTS LayoutSnapshotState (
Key TEXT PRIMARY KEY,
Value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS DefaultLayoutSetting (
Key TEXT PRIMARY KEY,
Value TEXT NOT NULL
);
""";
cmd.ExecuteNonQuery();
}
foreach (var table in SnapshotTables)
{
var snapshotTable = "Default" + table;
using (var create = _connection.CreateCommand())
{
create.CommandText = $"CREATE TABLE IF NOT EXISTS {snapshotTable} AS SELECT * FROM {table} WHERE 0;";
create.ExecuteNonQuery();
}
var snapshotColumns = ReadColumnNames(snapshotTable);
foreach (var (name, type, defaultValue) in ReadColumnDefinitions(table))
{
if (snapshotColumns.Contains(name, StringComparer.OrdinalIgnoreCase)) continue;
var definition = string.IsNullOrWhiteSpace(type) ? "BLOB" : type;
if (defaultValue != null) definition += " DEFAULT " + defaultValue;
using var add = _connection.CreateCommand();
add.CommandText = $"ALTER TABLE {snapshotTable} ADD COLUMN {QuoteIdentifier(name)} {definition};";
add.ExecuteNonQuery();
}
}
}
/// <summary>Captures the installed layout once as the immutable branded default. Existing databases
/// are snapshotted before MainViewModel loads them; a fresh database calls
/// <see cref="CaptureDefaultsIfMissing"/> after its factory scenes have been seeded.</summary>
public void PrepareLayoutSnapshots(string buildId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(buildId);
var defaultsInitialized = GetSnapshotState(DefaultsInitializedKey) == "1";
if (!defaultsInitialized && HasStoredScenes())
{
CaptureDefaults();
defaultsInitialized = true;
}
var currentBuildId = GetSnapshotState(CurrentBuildIdKey);
if (defaultsInitialized && !string.Equals(currentBuildId, buildId, StringComparison.Ordinal))
RestoreDefaults(buildId);
else if (!defaultsInitialized && string.IsNullOrWhiteSpace(currentBuildId))
SetSnapshotState(CurrentBuildIdKey, buildId);
}
/// <summary>Seeds the default snapshot after the first-run factory layout has been persisted.</summary>
public void CaptureDefaultsIfMissing()
{
if (GetSnapshotState(DefaultsInitializedKey) != "1")
CaptureDefaults();
}
/// <summary>Restores one existing scene by its current ID. Unknown scenes have no branded default
/// and are left untouched.</summary>
public bool RestoreDefaultScene(string sceneId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sceneId);
string? defaultSceneId;
using (var find = _connection.CreateCommand())
{
find.CommandText = """
SELECT Id FROM DefaultScene
WHERE Name = (SELECT Name FROM Scene WHERE Id = $sceneId) COLLATE NOCASE
LIMIT 1;
""";
find.Parameters.AddWithValue("$sceneId", sceneId);
defaultSceneId = find.ExecuteScalar() as string;
}
if (defaultSceneId == null) return false;
var columnsByTable = SnapshotTables.ToDictionary(table => table, ReadColumnNames);
var webcamId = GetCurrentWebcamId();
using var tx = _connection.BeginTransaction();
using (var clearBackgroundSettings = _connection.CreateCommand())
{
clearBackgroundSettings.Transaction = tx;
clearBackgroundSettings.CommandText = """
DELETE FROM Settings
WHERE Key IN (
SELECT 'BackgroundPath_' || Id FROM Source WHERE SceneId = $sceneId
UNION SELECT 'BackgroundUseDefault_' || Id FROM Source WHERE SceneId = $sceneId
UNION SELECT 'BackgroundPath_' || $sceneId
UNION SELECT 'BackgroundUseDefault_' || $sceneId
);
""";
clearBackgroundSettings.Parameters.AddWithValue("$sceneId", sceneId);
clearBackgroundSettings.ExecuteNonQuery();
}
foreach (var table in new[] { "WebcamSceneConfig", "Source" })
{
using var delete = _connection.CreateCommand();
delete.Transaction = tx;
delete.CommandText = $"DELETE FROM {table} WHERE SceneId = $sceneId;";
delete.Parameters.AddWithValue("$sceneId", sceneId);
delete.ExecuteNonQuery();
}
var sceneColumns = columnsByTable["Scene"]
.Where(column => column != "Id" && column != "SortOrder").ToArray();
var assignments = string.Join(", ", sceneColumns.Select(column =>
$"{QuoteIdentifier(column)} = (SELECT {QuoteIdentifier(column)} FROM DefaultScene WHERE Id = $defaultSceneId)"));
using (var updateScene = _connection.CreateCommand())
{
updateScene.Transaction = tx;
updateScene.CommandText = $"UPDATE Scene SET {assignments} WHERE Id = $sceneId;";
updateScene.Parameters.AddWithValue("$sceneId", sceneId);
updateScene.Parameters.AddWithValue("$defaultSceneId", defaultSceneId);
updateScene.ExecuteNonQuery();
}
CopyDefaultSceneRows("Source", sceneId, defaultSceneId, null, tx, columnsByTable["Source"]);
if (webcamId != null)
CopyDefaultSceneRows("WebcamSceneConfig", sceneId, defaultSceneId, webcamId, tx,
columnsByTable["WebcamSceneConfig"]);
using (var copyBackgroundSettings = _connection.CreateCommand())
{
copyBackgroundSettings.Transaction = tx;
copyBackgroundSettings.CommandText = """
INSERT INTO Settings (Key, Value)
SELECT Key, Value FROM DefaultLayoutSetting
WHERE Key IN (
SELECT 'BackgroundPath_' || Id FROM DefaultSource WHERE SceneId = $defaultSceneId
UNION SELECT 'BackgroundUseDefault_' || Id FROM DefaultSource WHERE SceneId = $defaultSceneId
UNION SELECT 'BackgroundPath_' || $defaultSceneId
UNION SELECT 'BackgroundUseDefault_' || $defaultSceneId
);
""";
copyBackgroundSettings.Parameters.AddWithValue("$defaultSceneId", defaultSceneId);
copyBackgroundSettings.ExecuteNonQuery();
}
tx.Commit();
return true;
}
/// <summary>Restores the full factory snapshot without changing the active build stamp.</summary>
public bool RestoreAllDefaults()
{
if (GetSnapshotState(DefaultsInitializedKey) != "1") return false;
var buildId = GetSnapshotState(CurrentBuildIdKey);
if (string.IsNullOrWhiteSpace(buildId)) return false;
RestoreDefaults(buildId);
return true;
}
private string? GetCurrentWebcamId()
{
using var cmd = _connection.CreateCommand();
cmd.CommandText = "SELECT Id FROM Webcam LIMIT 1;";
return cmd.ExecuteScalar() as string;
}
private void CopyDefaultSceneRows(string table, string sceneId, string defaultSceneId,
string? webcamId, SqliteTransaction tx, IReadOnlyList<string> columns)
{
var columnList = string.Join(", ", columns.Select(QuoteIdentifier));
var values = string.Join(", ", columns.Select(column => column switch
{
"SceneId" => "$sceneId",
"WebcamId" when webcamId != null => "$webcamId",
_ => QuoteIdentifier(column),
}));
using var copy = _connection.CreateCommand();
copy.Transaction = tx;
copy.CommandText = $"INSERT INTO {table} ({columnList}) SELECT {values} FROM Default{table} WHERE SceneId = $defaultSceneId;";
copy.Parameters.AddWithValue("$sceneId", sceneId);
copy.Parameters.AddWithValue("$defaultSceneId", defaultSceneId);
if (webcamId != null) copy.Parameters.AddWithValue("$webcamId", webcamId);
copy.ExecuteNonQuery();
}
private void CaptureDefaults()
{
var columnsByTable = SnapshotTables.ToDictionary(table => table, ReadColumnNames);
using var tx = _connection.BeginTransaction();
foreach (var table in SnapshotTables.Reverse())
{
using var delete = _connection.CreateCommand();
delete.Transaction = tx;
delete.CommandText = $"DELETE FROM Default{table};";
delete.ExecuteNonQuery();
}
foreach (var table in SnapshotTables)
{
var columns = string.Join(", ", columnsByTable[table].Select(QuoteIdentifier));
using var copy = _connection.CreateCommand();
copy.Transaction = tx;
copy.CommandText = $"INSERT INTO Default{table} ({columns}) SELECT {columns} FROM {table};";
copy.ExecuteNonQuery();
}
using (var clearSettings = _connection.CreateCommand())
{
clearSettings.Transaction = tx;
clearSettings.CommandText = "DELETE FROM DefaultLayoutSetting;";
clearSettings.ExecuteNonQuery();
}
using (var copySettings = _connection.CreateCommand())
{
copySettings.Transaction = tx;
copySettings.CommandText = """
INSERT INTO DefaultLayoutSetting (Key, Value)
SELECT Key, Value FROM Settings
WHERE Key LIKE 'BackgroundPath_%' OR Key LIKE 'BackgroundUseDefault_%';
""";
copySettings.ExecuteNonQuery();
}
using (var state = _connection.CreateCommand())
{
state.Transaction = tx;
state.CommandText = """
INSERT INTO LayoutSnapshotState (Key, Value) VALUES ($key, '1')
ON CONFLICT(Key) DO UPDATE SET Value = excluded.Value;
""";
state.Parameters.AddWithValue("$key", DefaultsInitializedKey);
state.ExecuteNonQuery();
}
tx.Commit();
}
private void RestoreDefaults(string buildId)
{
var columnsByTable = SnapshotTables.ToDictionary(table => table, ReadColumnNames);
var currentWebcamId = GetCurrentWebcamId();
using var tx = _connection.BeginTransaction();
foreach (var table in SnapshotTables.Reverse())
{
if (table == "Webcam") continue;
using var delete = _connection.CreateCommand();
delete.Transaction = tx;
delete.CommandText = $"DELETE FROM {table};";
delete.ExecuteNonQuery();
}
foreach (var table in SnapshotTables)
{
if (table == "Webcam" || (table == "WebcamSceneConfig" && currentWebcamId == null)) continue;
var columns = string.Join(", ", columnsByTable[table].Select(QuoteIdentifier));
var values = string.Join(", ", columnsByTable[table].Select(column =>
column == "WebcamId" && table == "WebcamSceneConfig"
? "$webcamId"
: QuoteIdentifier(column)));
using var copy = _connection.CreateCommand();
copy.Transaction = tx;
copy.CommandText = $"INSERT INTO {table} ({columns}) SELECT {values} FROM Default{table};";
if (table == "WebcamSceneConfig") copy.Parameters.AddWithValue("$webcamId", currentWebcamId!);
copy.ExecuteNonQuery();
}
using (var clearSettings = _connection.CreateCommand())
{
clearSettings.Transaction = tx;
clearSettings.CommandText = "DELETE FROM Settings WHERE Key LIKE 'BackgroundPath_%' OR Key LIKE 'BackgroundUseDefault_%';";
clearSettings.ExecuteNonQuery();
}
using (var copySettings = _connection.CreateCommand())
{
copySettings.Transaction = tx;
copySettings.CommandText = "INSERT INTO Settings (Key, Value) SELECT Key, Value FROM DefaultLayoutSetting;";
copySettings.ExecuteNonQuery();
}
SetSnapshotState(CurrentBuildIdKey, buildId, tx);
tx.Commit();
}
private bool HasStoredScenes()
{
using var cmd = _connection.CreateCommand();
cmd.CommandText = "SELECT EXISTS(SELECT 1 FROM Scene LIMIT 1);";
return Convert.ToInt32(cmd.ExecuteScalar()) != 0;
}
private string? GetSnapshotState(string key)
{
using var cmd = _connection.CreateCommand();
cmd.CommandText = "SELECT Value FROM LayoutSnapshotState WHERE Key = $key;";
cmd.Parameters.AddWithValue("$key", key);
return cmd.ExecuteScalar() as string;
}
private void SetSnapshotState(string key, string value, SqliteTransaction? transaction = null)
{
using var cmd = _connection.CreateCommand();
cmd.Transaction = transaction;
cmd.CommandText = """
INSERT INTO LayoutSnapshotState (Key, Value) VALUES ($key, $value)
ON CONFLICT(Key) DO UPDATE SET Value = excluded.Value;
""";
cmd.Parameters.AddWithValue("$key", key);
cmd.Parameters.AddWithValue("$value", value);
cmd.ExecuteNonQuery();
}
private List<string> ReadColumnNames(string table)
=> ReadColumnDefinitions(table).Select(column => column.Name).ToList();
private List<(string Name, string Type, string? DefaultValue)> ReadColumnDefinitions(string table)
{
var columns = new List<(string, string, string?)>();
using var cmd = _connection.CreateCommand();
cmd.CommandText = $"PRAGMA table_info({table});";
using var reader = cmd.ExecuteReader();
while (reader.Read())
columns.Add((reader.GetString(1), reader.IsDBNull(2) ? string.Empty : reader.GetString(2),
reader.IsDBNull(4) ? null : reader.GetString(4)));
return columns;
}
private static string QuoteIdentifier(string identifier)
=> "\"" + identifier.Replace("\"", "\"\"") + "\"";
}
+6 -6
View File
@@ -9,7 +9,7 @@
**Creator ruling 2026-11-09 — finish the queue before the new features, gold pass always last.**
`35 → 37 → 40·A/C/D → 55·2–3 → Move → 9·5 → 14 (slices) → 65 → 66 → 67 → 68 → 36`
`40·A/C/D → Move → 9·5 → 14 (remaining slices) → 66 → 67 → 68 → 36`
The rule behind the two retirements below: **do not rebuild the platform's own surface.** Scheduling,
publishing, moderation and channel management are YouTube's; the app owns capture → scene → sound →
@@ -19,14 +19,14 @@ output.
| Task | Status | Scope | Detail |
|---|---|---|---|
| 35 | ☐ | **Scene-linked audio** — the scene remembers the room: BRB mutes the mic, Chat restores it, applied once at the live transition | [`task-35`](TASKS/task-35-scene-linked-audio.md) |
| 37 | ☐ | **Defaults vs current layout split** — separate branded defaults from the live workspace; enables one-click revert | [`task-37`](TASKS/task-37-defaults-current-split.md) |
| 35 | ✅ | **Scene-linked audio** — the scene remembers the room: BRB ships muted, three-state checkboxes per scene, applied once when the scene takes the program output (done 2026-11-10) | [`task-35`](TASKS/task-35-scene-linked-audio.md) |
| 37 | ✅ | **Defaults vs current layout split** — immutable SQLite default snapshot, build-stamped current layout, staged-scene and all-scene reset controls (done 2026-11-10) | [`task-37`](TASKS/task-37-defaults-current-split.md) |
| 40·A/C/D | ☐ | **Settings round** — active-camera picker; persist output resolution + surface transition defaults + confirm-before-End; accent consolidation | [`task-40`](TASKS/task-40-app-settings-round.md) |
| 55·2–3 | ☐ | **Disk hygiene** — delete `%TEMP%` alert clips on close + sweep at startup; low-disk guard before REC (slice 1 shipped) | [`task-55`](TASKS/task-55-disk-hygiene.md) |
| 55 | ✅ | **Disk hygiene** — log rotation (5 MB, one roll), temp alert clips deleted on close + swept at startup, low-disk guard (block under 1 GB, warn under 5 GB at start, one warning under 2 GB mid-show) — done 2026-11-10 | [`task-55`](TASKS/task-55-disk-hygiene.md) |
| — | ☐ | **Move transition** — per-layer carry-across-scenes flag, per-scene placement, fixed z band | [`ui-surface`](docs/ai/ui-surface.md) |
| 9·5 | ☐ | **Webcam identity key reconciliation** — one stable identity per camera across re-plugs | [`task-09`](TASKS/task-09-live-stream-management.md) |
| 14 | 🔶 | **Creator feedback batch** — Branch 2 shipped; Branch 3 = mic input gain, webcam blank/standby, opacity+geometry consistency, Show-in-folder on stop | [`task-14`](TASKS/task-14-creator-feedback-batch.md) |
| 65 | ☐ | **Replay clips** — 10/15/20 s (default 15), RAM ring of fragmented MP4, F10 to save; replay layer plays once then hides in Live and loops the last 1–3 elsewhere; silent by default; three kept | [`task-65`](TASKS/task-65-replay-clips.md) |
| 14 | 🔶 | **Creator feedback batch** — Branch 2 shipped; Branch 3 remaining: webcam blank/standby, opacity+geometry consistency, Show-in-folder on stop (mic-gain slice closed after creator test 2026-11-10) | [`task-14`](TASKS/task-14-creator-feedback-batch.md) |
| 65 | ✅ | **Replay clips** — 10/15 s (default 10), RAM ring of fragmented MP4, F10 saves (inert during a Live replay); layer plays once then hides in Live, loops the kept 3/4/5 elsewhere; silent by default (done 2026-11-10) | [`task-65`](TASKS/task-65-replay-clips.md) |
| 66 | ☐ | **Timed ticker messages** — "every N minutes show this", from a creator-written list | [`task-66`](TASKS/task-66-timed-ticker.md) |
| 67 | ☐ | **Per-event alert videos** — a clip per monetization event, falling back to the default | [`task-67`](TASKS/task-67-per-event-alert-videos.md) |
| 68 | ☐ | **Editing while live** + first-run On-Air state matching the 1-2-3 screen | [`task-68`](TASKS/task-68-edit-while-live.md) |
+1 -1
View File
@@ -27,7 +27,7 @@
| # | Slice | Why |
|---|---|---|
| 15 | ☐ **Mic input gain** — a dB stage *ahead of* the gate, meter reads post-gain | A headset mic sits close enough to clear the gate; a table-mounted boom is quieter and the gate eats it. Not AGC — automatic gain pumps on breath and silence. Clipping is already the limiter's job |
| 15 | ✅ **Mic input gain closed 2026-11-10** — creator tested the mic at −2.6 dB and reports it works great; closed by creator direction | No additional input-gain stage requested |
| 16 | ☐ **Webcam blank / standby** — a visibility hotkey for the webcam layer (tenth registration), optional standby media while hidden | "My webcam has to go away *now*." The privacy blur covers the screen case; this covers the camera in one keystroke |
| 17 | ☐ **Opacity + geometry consistency** — every layer type exposes the same opacity control and the same position/size affordances | Parity across layer types. Geometry fields stay, but collapse behind a "Geometry" disclosure: keyboard-only and screen-reader users cannot drag a layer, and precise alignment between two monitors is otherwise guesswork |
| 18 | ☐ **Show in folder** — on the stop notification, reveal the finished recording | Publishing is retired to YouTube (TASK 50); the app's remaining job is "where did my file go?" |
+12 -6
View File
@@ -7,13 +7,19 @@
audio at transitions — the scene carries the room state. OBS needs scripts/plugins; native = the
creator-proof pitch.
1. ☐ `Scene` gains nullable `SceneMutesMic` / `SceneMutesDesktop` — `null` = don't touch (the default;
**Shipped 2026-11-10.** Columns `Scene.SceneMutesMic` / `SceneMutesDesktop` (nullable = passive),
three-state checkboxes under the layers list ("When this scene goes live"), applied once at the program
transition in `TransitionToScene`. `SceneAudioTests` pins the whole rule: offline staging edits nothing,
`null` never overrides a manual mute, a scene with an opinion wins on its next entry, and all three
states survive a save/reload.
1. ✅ `Scene` gains nullable `SceneMutesMic` / `SceneMutesDesktop` — `null` = don't touch (the default;
scenes are passive until told). Schema column bump + roundtrip.
2. ☐ Applied on **live transitions only** (thumbnail click / hotkey), ONCE at entry — never on
2. ✅ Applied on **live transitions only** (thumbnail click / hotkey), ONCE at entry — never on
offline staging (no surprise stream-state edits while auditioning).
3. ☐ The creator is boss: a manual mute/unmute mid-scene is never overridden until the next entry.
4. ☐ BRB ships `SceneMutesMic = true`; other scenes default `null` — creator's choice.
5. ☐ Edit UI: two checkboxes in the scene's Properties section (left panel, edit mode) — no new chrome.
6. ☐ Test (the ONE): transition applies scene state; `null` leaves state untouched; manual override
3. ✅ The creator is boss: a manual mute/unmute mid-scene is never overridden until the next entry.
4. ✅ BRB ships `SceneMutesMic = true`; other scenes default `null` — creator's choice.
5. ✅ Edit UI: two checkboxes in the scene's Properties section (left panel, edit mode) — no new chrome.
6. ✅ Test (the ONE): transition applies scene state; `null` leaves state untouched; manual override
survives until the next entry.
+16 -2
View File
@@ -1,6 +1,6 @@
# TASK 37 — Defaults vs current layout split
**Status:** ☐ Queued (2026-09-20)
**Status:** ✅ Complete (2026-11-10)
## Idea (creator directive 2026-09-20)
@@ -43,6 +43,20 @@ scene[0-4].layerList.[default | current].elementList
- A `current` stamped by a different (older/newer) build-id falls back to `default`.
- Revert-to-default restores `default` for one scene or all.
## Shipped 2026-11-10
- Current scene/source tables remain the live workspace. One-time `Default*` snapshot tables and
background-path settings live in the same SQLite file; schema additions are mirrored into the
snapshots. Existing profiles promote their saved layout once; a fresh profile snapshots its seeded
layout before creator edits. Default asset references are retained during current-layout saves.
- Startup restores the snapshot transactionally when the current build stamp differs. Matching builds
keep the saved current layout. Camera identity is never replaced by a layout restore; default scene
placements are rebound to the creator's currently selected camera.
- App Settings offers **Restore staged scene** and **Restore all scenes**, disabled while live or
recording. A one-scene reset saves pending changes in other scenes and keeps that scene staged.
- Integration coverage: `LayoutStoreSnapshotTests` and `LayoutResetIntegrationTests`.
**615 tests green; clean build, 0 warnings.**
## Cross-references
- `ai.md` — persistence architecture; `MyMistakes.md` — prior reorder persistence failures.
- `ai.md` — persistence architecture; `MyMistakes.md` — prior reorder persistence failures.
+3 -3
View File
@@ -30,9 +30,9 @@ ticket and a trust breach.
Guard: `ytLive.Tests/AppLogRotationTests.cs` (the ONE test: the log rolls at the cap, the
live file starts fresh, and the directory still holds exactly `startup.log` + `startup.1.log`
after a SECOND roll — the growth is bounded).
2. ☐ **Temp alert clip cleanup** — delete the `%TEMP%` alert clip on app close (and sweep
2. ✅ **Temp alert clip cleanup** — `Services/AlertClipCleanup` deletes the session's clip on close and sweeps `ytLive-alert-*.mp4` at startup (never anything else); shipped 2026-11-10 — delete the `%TEMP%` alert clip on app close (and sweep
stale ones at startup). Test: create, close, assert gone.
3. ☐ **Low-disk guard for recordings** — check free space on the record folder's drive before
Record starts, and warn (toast) when it runs low mid-recording. Thresholds TBD with the creator.
3. ✅ **Low-disk guard for recordings** — `Services/DiskSpaceGuard`: refuse to start under **1 GB** (toast, recording not started, stream continues), warn under **5 GB** at start, one mid-show warning under **2 GB**; shipped 2026-11-10 — check free space on the record folder's drive before
Record starts, and warn (toast) when it runs low mid-recording. Thresholds chosen for 8 Mbps ≈ 3.6 GB/h; revisit if tiers change.
**Design decisions:** keep `AppLog`'s call surface unchanged — rotation lives inside it.
+18 -2
View File
@@ -31,6 +31,11 @@ never the creator, who cannot reach a keyboard mid-moment).
## The replay layer
**Scope settled 2026-11-10:** the immediate replay of a fresh clip happens **only in the Live scene**.
While that replay is playing, **F10 is inert** ("replay in progress") — that is what replaces the
hall-of-mirrors exclusion, which is impossible with one encoder and two muxes: the clip *is* what the
stream got.
One layer type, added by the creator to the scenes they want; behaviour comes from the scene:
| Scene | Behaviour |
@@ -40,8 +45,9 @@ One layer type, added by the creator to the scenes they want; behaviour comes fr
- **Audio off by default**, toggleable per layer. The show's sound design is the creator's; a replay
should not re-mix it uninvited.
- **The replay layer is excluded from the clip's own composition.** Otherwise saving while a clip plays
records a video of a video (hall of mirrors). Viewers still see it live; the clip simply doesn't.
- **No exclusion, no second encode.** The clip is a second mux of the frames the stream already got, so
it contains whatever viewers saw. Double-clipping is prevented instead: F10 does nothing while the
Live replay is playing.
## Storage and retention
@@ -58,6 +64,16 @@ Named in `PRIVACY.md`: clips are local only, the three most recent are kept, old
automatically, and nothing is uploaded. The first save says the same in one line, so the policy is not
only a document.
## Shipped 2026-11-10
Six commits: ring (`b93744e`), clip mux (`5066d81`), library (`f7d3d13`), F10 + settings (`2865791`),
layer model (`a5c2061`), layer playback (`5fcfa54`). 608 tests.
Length **10/15 (default 10)**, keep **3/4/5 (default 3)**, off by default, guard while replaying.
**Known limits, stated on purpose:** the clip is a second mux of the program, so it contains whatever
viewers saw; there is no clean feed and no editor. The feature is a capture.
## Tests
- Ring: fragment boundaries respected, byte cap enforced, save emits a playable MP4, oldest pruned.
+1
View File
@@ -58,6 +58,7 @@ public sealed class HotkeyBindingRow : ViewModelBase
HotkeyId.ToggleMicMute => "Toggle Mic Mute",
HotkeyId.ToggleGameMute => "Toggle Desktop Audio Mute",
HotkeyId.TraxPlayPause => "TRAX Play / Pause",
HotkeyId.SaveClip => "Save Replay Clip",
_ => id.ToString(),
};
}
+32
View File
@@ -294,6 +294,38 @@ public partial class MainViewModel
/// lip-sync is right", so it deserves one click, not a drag.</summary>
internal void SetSyncOffset(int milliseconds) => AudioSyncOffsetMs = milliseconds;
/// <summary>TASK 35: mute/unmute from a scene entry. Idempotent — a scene that says "mute" while
/// the mic is already muted must not overwrite the level it would restore.</summary>
internal void SetMicMuted(bool muted)
{
if (muted == MicMuted) return;
if (muted)
{
_volumeBeforeMute = MicVolume;
MicVolume = 0;
}
else
{
MicVolume = _volumeBeforeMute ?? 0.8;
BeginVolumeFlash();
}
}
/// <summary>TASK 35: as <see cref="SetMicMuted"/>, for desktop/game audio.</summary>
internal void SetGameMuted(bool muted)
{
if (muted == GameMuted) return;
if (muted)
{
_gameVolumeBeforeMute = GameAudioVolume;
GameAudioVolume = 0;
}
else
{
GameAudioVolume = _gameVolumeBeforeMute ?? 1.0;
}
}
private void ToggleMicMute()
{
if (MicMuted)
+251
View File
@@ -0,0 +1,251 @@
using System;
using System.Linq;
using System.IO;
using ytLive.Helpers;
using ytLive.Models;
using ytLive.Services;
namespace ytLive.ViewModels;
/// <summary>
/// TASK 65, slice 4: the creator-facing half of replay clips — the setting, the ring's lifetime, and F10.
///
/// <para>Clips are a **static feature**: 10 or 15 seconds, keep 3/4/5, no editor and no gallery. Off by
/// default, and when off nothing runs — no ring, no reader thread, no encoder output — so the feature
/// costs nothing until someone asks for it.</para>
/// </summary>
public partial class MainViewModel
{
private ClipRing? _clipRing;
private ClipLibrary? _clipLibrary;
public bool ClipsEnabled
{
get => _clipsEnabled;
set
{
if (!SetProperty(ref _clipsEnabled, value)) return;
_layoutStore.SaveClipsEnabled(value);
ApplyClipSettings();
}
}
private bool _clipsEnabled;
/// <summary>10 or 15 seconds; anything else in the store is coerced by the loader.</summary>
public int ClipSeconds
{
get => _clipSeconds;
set
{
var clamped = value == 15 ? 15 : 10;
if (!SetProperty(ref _clipSeconds, clamped)) return;
_layoutStore.SaveClipSeconds(clamped);
ApplyClipSettings();
}
}
private int _clipSeconds = 10;
public int ClipKeep
{
get => _clipKeep;
set
{
var clamped = Math.Clamp(value, 3, 5);
if (!SetProperty(ref _clipKeep, clamped)) return;
_layoutStore.SaveClipKeep(clamped);
}
}
private int _clipKeep = 3;
/// <summary>String-faced pickers, because the drawer binds a ComboBox and the model keeps ints.</summary>
public string[] ClipLengthOptions { get; } = { "10 seconds", "15 seconds" };
public string ClipLengthText
{
get => ClipSeconds == 15 ? "15 seconds" : "10 seconds";
set
{
ClipSeconds = value == "15 seconds" ? 15 : 10;
OnPropertyChanged(nameof(ClipLengthText));
}
}
public string[] ClipKeepOptions { get; } = { "3 clips", "4 clips", "5 clips" };
public string ClipKeepText
{
get => $"{ClipKeep} clips";
set
{
if (int.TryParse(value.Split(' ')[0], out var keep)) ClipKeep = keep;
OnPropertyChanged(nameof(ClipKeepText));
}
}
private void LoadClipSettings()
{
_clipsEnabled = _layoutStore.LoadClipsEnabled();
_clipSeconds = _layoutStore.LoadClipSeconds();
_clipKeep = _layoutStore.LoadClipKeep();
}
/// <summary>The ring exists only while a session runs and clips are on. Sized from the chosen length
/// and the tier's bitrate, because memory is the cost and bytes are the unit.</summary>
private void ApplyClipSettings()
{
if (!_clipsEnabled || !(IsLive || IsRecording))
{
_clipRing = null;
return;
}
var quality = Models.OutputProfile.Resolve(SelectedQuality, QualityOptions, HasProOutput);
var bytes = ClipLibrary.RingBytesFor(_clipSeconds, (int)Math.Round(quality.Bitrate * 1000));
if (_clipRing is null || _clipRingCapacity != bytes)
{
_clipRing = new ClipRing(bytes);
_clipRingCapacity = bytes;
}
}
private long _clipRingCapacity;
private void StartClipRing()
{
_clipLibrary = new ClipLibrary(() => _recordFolder ?? DefaultRecordFolder());
ClipSaved -= OnClipSaved;
ClipSaved += OnClipSaved;
_clipRing = null;
_clipRingCapacity = 0;
ApplyClipSettings();
OnPropertyChanged(nameof(ClipsEnabled));
OnPropertyChanged(nameof(ClipSeconds));
OnPropertyChanged(nameof(ClipKeep));
}
private void StopClipRing()
{
ClipSaved -= OnClipSaved;
_clipRing = null;
_clipRingCapacity = 0;
_liveReplayPlaying = false;
}
/// <summary>F10. Snapshots the ring, writes a file, and prunes to the retention count. When nothing
/// has been buffered yet it says so instead of writing a file that will not open.</summary>
public void SaveReplayClip()
{
if (_liveReplayPlaying)
{
_notifications.Info("Replay in progress", "Wait for the replay to finish before saving another clip.");
return;
}
if (!_clipsEnabled)
{
_notifications.Info("Replay clips are off", "Turn them on in Settings to save a clip.");
return;
}
var bytes = _clipRing?.Snapshot() ?? Array.Empty<byte>();
if (bytes.Length == 0)
{
_notifications.Warning("Nothing to clip yet",
"The replay buffer fills while you stream — wait a few seconds, then press again.");
return;
}
var library = _clipLibrary ??= new ClipLibrary(() => _recordFolder ?? DefaultRecordFolder());
var path = library.Save(bytes, DateTime.Now, _clipKeep);
if (path == null)
{
_notifications.Error("Couldn't save the clip", "The file could not be written. Check free space.");
return;
}
AppLog.Write($"Replay clip saved: {path}");
_notifications.Success("Clip saved", Path.GetFileName(path));
ClipSaved?.Invoke(path);
}
/// <summary>Raised with the saved path so the replay layer can play it immediately.</summary>
public event Action<string>? ClipSaved;
/// <summary>True while the Live scene's replay layer is playing a fresh clip. F10 is inert during
/// that window: the clip is a second mux of the frames viewers already got, so clipping a replay
/// would record a video of a video — the guard replaces the impossible "clean feed".</summary>
public bool IsLiveReplayPlaying => _liveReplayPlaying;
private bool _liveReplayPlaying;
/// <summary>Adds the replay layer to the staged scene. One per scene; it is an ordinary media layer
/// whose path the app owns, so the compositor needs no special case.</summary>
internal void AddReplayLayer()
{
var scene = StagedScene;
if (scene is null || scene.Elements.OfType<Source>().Any(s => s.IsReplayLayer)) return;
AddSource(Models.SourceType.MediaSource, NewestClipPath());
if (StagedScene?.Elements.OfType<Source>().LastOrDefault() is not { } layer) return;
layer.Name = "Replay";
layer.IsReplayLayer = true;
layer.MediaMuted = true; // silent by default
layer.MediaIsLooping = !Models.SceneCatalog.Is(scene.Name, Models.SceneCatalog.Live);
ScheduleSave();
}
private string? NewestClipPath()
=> (_clipLibrary ??= new ClipLibrary(() => _recordFolder ?? DefaultRecordFolder())).Recent().FirstOrDefault();
/// <summary>A new clip landed: Live plays it once, every other scene keeps its loop of the kept set.</summary>
private void OnClipSaved(string path)
{
foreach (var scene in Scenes)
{
var layer = scene.Elements.OfType<Source>().FirstOrDefault(s => s.IsReplayLayer);
if (layer is null) continue;
if (Models.SceneCatalog.Is(scene.Name, Models.SceneCatalog.Live))
{
layer.MediaPath = path;
layer.MediaIsLooping = false;
layer.MediaMuted = true;
layer.IsVisible = true;
layer.MediaPlaybackState = Models.MediaPlaybackState.Playing;
_liveReplayPlaying = true;
OnPropertyChanged(nameof(IsLiveReplayPlaying));
EnsureMediaSession(MediaSessionKey(layer));
}
else if (!layer.IsMediaRunning)
{
layer.MediaPath = NewestClipPath();
layer.MediaIsLooping = true;
layer.IsVisible = true;
if (!string.IsNullOrWhiteSpace(layer.MediaPath)) EnsureMediaSession(MediaSessionKey(layer));
}
}
}
/// <summary>A replay layer's clip finished: Live hides (you were there to see it), everything else
/// advances through the kept set, looped.</summary>
private void OnReplayLayerCompleted(Source layer)
{
if (Models.SceneCatalog.Is(StagedScene?.Name ?? string.Empty, Models.SceneCatalog.Live)
&& layer == Scenes.SelectMany(s => s.Elements).OfType<Source>().FirstOrDefault(s => s.IsReplayLayer))
{
layer.IsVisible = false;
layer.MediaPlaybackState = Models.MediaPlaybackState.Stopped;
_liveReplayPlaying = false;
OnPropertyChanged(nameof(IsLiveReplayPlaying));
return;
}
var playlist = (_clipLibrary ??= new ClipLibrary(() => _recordFolder ?? DefaultRecordFolder())).Recent();
if (playlist.Count == 0) return;
var index = playlist.ToList().IndexOf(layer.MediaPath ?? string.Empty);
var next = playlist[(index + 1 + playlist.Count) % playlist.Count];
layer.MediaPath = next;
layer.MediaIsLooping = true;
EnsureMediaSession(MediaSessionKey(layer));
}
}
+1
View File
@@ -278,6 +278,7 @@ public partial class MainViewModel
{
source.IsMediaRunning = false;
source.MediaPlaybackState = MediaPlaybackState.Stopped;
if (source.IsReplayLayer) OnReplayLayerCompleted(source);
}
}
+20
View File
@@ -16,12 +16,32 @@ public partial class MainViewModel : ViewModelBase
private DateTime _recordStartTime;
private TimeSpan _recordLength;
private bool _lowDiskWarned;
private string? StartRecordFile()
{
try
{
var folder = _recordFolder ?? DefaultRecordFolder();
Directory.CreateDirectory(folder);
// TASK 55·3: never start something the drive cannot finish.
if (DiskSpaceGuard.FreeBytes(folder) is { } free)
{
var decision = DiskSpaceGuard.ForStart(free);
if (decision == DiskSpaceGuard.StartDecision.Block)
{
AppLog.Write($"Recording refused: {free / (1024 * 1024)} MB free",
AppLogMessageType.Error, AppLogErrorClass.Class2);
_notifications.Error("Not enough disk space",
"There isn't room to record safely. Free up some space or pick another record folder.");
return null;
}
if (decision == DiskSpaceGuard.StartDecision.Warn)
_notifications.Warning("Disk space is getting low",
"Your recording starts, but there isn't much room left. A long show may not fit.");
}
_lowDiskWarned = false;
var name = RecordingFile.BuildStartName(DateTime.Now) + ".mp4";
var path = Path.Combine(folder, name);
_activeRecordPath = path;
+46
View File
@@ -21,6 +21,32 @@ public partial class MainViewModel
// XAML bindings and MainViewModel call sites keep working unchanged.
public ObservableCollection<Scene> Scenes => _sceneGraph.Scenes;
/// <summary>TASK 35: the staged scene's audio state, bound by the left panel's three-state
/// checkboxes (indeterminate = leave the mix alone).</summary>
public bool? SceneMutesMic
{
get => StagedScene?.SceneMutesMic;
set
{
if (StagedScene is not { } scene || scene.SceneMutesMic == value) return;
scene.SceneMutesMic = value;
ScheduleSave();
OnPropertyChanged(nameof(SceneMutesMic));
}
}
public bool? SceneMutesDesktop
{
get => StagedScene?.SceneMutesDesktop;
set
{
if (StagedScene is not { } scene || scene.SceneMutesDesktop == value) return;
scene.SceneMutesDesktop = value;
ScheduleSave();
OnPropertyChanged(nameof(SceneMutesDesktop));
}
}
public Scene? StagedScene
{
get => _stagedScene;
@@ -38,6 +64,8 @@ public partial class MainViewModel
// (build 1082: the option vanished after the first layout load).
OnPropertyChanged(nameof(CanAddBlur));
OnPropertyChanged(nameof(StagedBrandLogo));
OnPropertyChanged(nameof(SceneMutesMic));
OnPropertyChanged(nameof(SceneMutesDesktop));
SelectedElement = null;
if (value != null)
@@ -137,9 +165,24 @@ public partial class MainViewModel
{
LiveScene = scene;
_transition.Start(SelectedTransitionType, TransitionDurationMs, null);
// TASK 35: the scene carries the room. Applied ONCE at entry, and only when the program
// output actually changes — staging a scene offline must never edit the stream's state.
ApplySceneAudio(scene);
}
}
/// <summary>TASK 35: a scene's audio state, applied once when it takes the program output.
/// <c>null</c> means "leave the mix alone" — the creator's manual mute survives until a scene that
/// actually has an opinion takes over.</summary>
private void ApplySceneAudio(Scene scene)
{
if (scene.SceneMutesMic is { } muteMic)
SetMicMuted(muteMic);
if (scene.SceneMutesDesktop is { } muteDesktop)
SetGameMuted(muteDesktop);
}
/// <summary>Raised before a scene switch so the preview can animate the old picture away.</summary>
public event Action<TransitionType, double>? PreviewTransition;
@@ -173,6 +216,7 @@ public partial class MainViewModel
case Services.HotkeyId.SceneBrb: TransitionToCanonical(SceneCatalog.Brb); break;
case Services.HotkeyId.SceneChat: TransitionToCanonical(SceneCatalog.Chat); break;
case Services.HotkeyId.SceneEnding: TransitionToCanonical(SceneCatalog.Ending); break;
case Services.HotkeyId.SaveClip: SaveReplayClip(); break;
case Services.HotkeyId.StartStopStream:
if (IsLive || IsRecording)
{
@@ -377,6 +421,8 @@ public partial class MainViewModel
Name = name.Trim(),
IsChatScene = SceneCatalog.IsChat(name),
HasBackground = SceneCatalog.HasBackground(name),
// TASK 35: BRB ships with the mic muted; every other scene is passive until told.
SceneMutesMic = SceneCatalog.Is(name, SceneCatalog.Brb) ? true : null,
};
EnsureBackground(scene);
EnsureZoomLayer(scene);
@@ -164,6 +164,7 @@ public partial class MainViewModel : ViewModelBase
_liveElapsed = TimeSpan.Zero;
_recordLength = TimeSpan.Zero;
StartStepDownWatch();
StartClipRing();
var recordStarted = false;
if (alsoRecord)
@@ -407,6 +408,7 @@ public partial class MainViewModel : ViewModelBase
{
CancelStreamRecovery(); // a stop wins over a relaunch in flight
StopStepDownWatch();
StopClipRing();
RemoveAttentionAlert("stream-recovery");
var wasLive = IsLive;
var wasRecording = IsRecording;
@@ -516,6 +518,8 @@ public partial class MainViewModel : ViewModelBase
BitrateKbps = (int)Math.Round(quality.Bitrate * 1000),
// Same derivation as the mixer's StartLive call: a dev instance serves its own pipe.
AudioPipeName = InstanceProfile.AudioPipeName(EncoderOptions.DefaultAudioPipeName),
// TASK 65: null when clips are off, which leaves ffmpeg's command line untouched.
ClipBuffer = _clipRing,
};
}
@@ -641,6 +645,16 @@ public partial class MainViewModel : ViewModelBase
_recordLength = _liveElapsed;
_recDotPulse = _recDotPulse > 0.5 ? 0.35 : 1.0;
OnPropertyChanged(nameof(RecDotOpacity));
// TASK 55·3: the last useful warning before the encoder fails for a reason it won't explain.
if (IsRecording && !_lowDiskWarned && _recordFolder is { } folder
&& DiskSpaceGuard.FreeBytes(folder) is { } free
&& DiskSpaceGuard.ShouldWarnDuring(free))
{
_lowDiskWarned = true;
_notifications.Warning("Disk space is nearly gone",
"The recording may stop on its own. Free up space now, or stop and save what you have.");
}
}
/// <summary>What happened to a finished broadcast at the keep-or-delete prompt.</summary>
+39
View File
@@ -189,6 +189,12 @@ public partial class MainViewModel : ViewModelBase
public ICommand AddSourceCommand { get; }
public ICommand AddImageCommand { get; }
public ICommand AddMediaCommand { get; }
/// <summary>TASK 65: add the replay layer to the staged scene.</summary>
public ICommand AddReplayLayerCommand { get; }
/// <summary>TASK 37: replace the current scene set with its factory snapshot.</summary>
public ICommand RestoreAllLayoutDefaultsCommand { get; }
/// <summary>TASK 37: restore only the staged canonical scene to its factory snapshot.</summary>
public ICommand RestoreStagedSceneDefaultsCommand { get; }
public ICommand ChangeMediaFileCommand { get; }
/// <summary>Accepts the detector's green/blue-screen offer on a clip (TASK 64).</summary>
public ICommand AcceptChromaSuggestionCommand { get; }
@@ -268,6 +274,11 @@ public partial class MainViewModel : ViewModelBase
AddWebcamCommand = new RelayCommand(_ => _ = AddWebcamToStagedSceneAsync());
AddImageCommand = new RelayCommand(_ => AddImage());
AddMediaCommand = new RelayCommand(_ => AddMedia());
AddReplayLayerCommand = new RelayCommand(_ => AddReplayLayer());
RestoreAllLayoutDefaultsCommand = new RelayCommand(_ => RestoreAllLayoutDefaults(),
_ => IsOffline && !IsRecording);
RestoreStagedSceneDefaultsCommand = new RelayCommand(_ => RestoreStagedSceneDefaults(),
_ => IsOffline && !IsRecording && StagedScene is { } scene && SceneCatalog.IsCanonical(scene.Name));
ChangeMediaFileCommand = new RelayCommand(
element => ChangeMediaFile(element as Source),
element => element is Source { IsMediaSource: true });
@@ -511,9 +522,11 @@ public partial class MainViewModel : ViewModelBase
private void LoadLayout()
{
_isLoading = true;
var seededFactoryLayout = false;
try
{
AppLog.Write("LoadLayout begin");
_layoutStore.PrepareLayoutSnapshots(Helpers.BuildStamp.Id);
var scenes = _layoutStore.Load();
Scenes.Clear();
foreach (var scene in scenes)
@@ -523,6 +536,7 @@ public partial class MainViewModel : ViewModelBase
{
foreach (var name in SceneCatalog.All)
AddScene(name);
seededFactoryLayout = true;
}
ReorderScenesToCanonical();
HealBackgrounds();
@@ -576,8 +590,15 @@ public partial class MainViewModel : ViewModelBase
SelectedTransitionType = parsed;
TransitionDurationMs = transDur;
LoadClipSettings();
BroadcastForm.Load();
if (seededFactoryLayout)
{
SaveLayoutNow();
_layoutStore.CaptureDefaultsIfMissing();
}
ScheduleSave();
AppLog.Write("LoadLayout end");
}
@@ -599,6 +620,8 @@ public partial class MainViewModel : ViewModelBase
_musicPlayer.Dispose();
_youtubeChat.Dispose();
_alertLayer.Dispose();
// TASK 55·2: the materialised default alert clip is ours, so we clean it up on the way out.
Services.AlertClipCleanup.Delete(_defaultAlertClipScratch);
}
public void SaveLayoutNow()
@@ -617,6 +640,22 @@ public partial class MainViewModel : ViewModelBase
}
}
private void RestoreAllLayoutDefaults()
{
if (!IsOffline || IsRecording || !_layoutStore.RestoreAllDefaults()) return;
LoadLayout();
}
private void RestoreStagedSceneDefaults()
{
if (!IsOffline || IsRecording || StagedScene is not { } staged || !SceneCatalog.IsCanonical(staged.Name)) return;
var sceneName = staged.Name;
SaveLayoutNow();
if (!_layoutStore.RestoreDefaultScene(staged.Id)) return;
LoadLayout();
StagedScene = Scenes.FirstOrDefault(scene => SceneCatalog.Is(scene.Name, sceneName)) ?? StagedScene;
}
private void ScheduleSave()
{
if (_isLoading || _saveDebounce == null) return;
+1 -1
View File
@@ -159,7 +159,7 @@ The app is a **director's control surface**, not an editor. This replaces the OB
**Current layout (2026-10-26 redesign commits):** `MainWindow` has a top bar and health banner, then a two-column work area with a fixed 360px left column and preview column. Its top row holds stream readouts/resolution on the left and the five-scene strip above the preview; the lower row holds the left panel and central preview. The bottom bar is now only a height-preserving spacer.
- **Left panel:** `EditingActive` is an explicit `EDIT` toggle, not a mode inferred from `StreamStatus`. On = scene layers + properties; off = a two-tab panel with **Live Chat** first/default and **Logs** second. Logs is a read-only view of up to 500 `AppLog` entries captured in this process; it does not load older `startup.log` contents or change file logging/rotation. Entries wrap and use the theme's type colors. Explicit Class 1/2 severity is independent of message type/source: Class 1 sorts above Class 2 in the pinned group; acknowledging unpins the entry but retains it in the chronological list. The staged scene is the preview/edit target; `LiveScene` is the program output.
- **Settings is a right-edge drawer, not a modal (2026-11-01):** the gear rail tab opens `Controls/SettingsDrawer` in the same animated-width stack as Stream Settings / YPP / Socials / TEST (`SettingsDrawerOpen`, exclusive with the other four). Categories are section headings with their controls indented under them — Zoom holds *Zoom view shape* and *Zoom box follows*. The app menu (Report Bug / Feature Request / About) hangs off a **right-click on the LlamaCasty wordmark**; left-click still opens About. The modal shell keeps only Bug / Feature / About, which is why it no longer needs a scroll viewer.
- **Settings is a right-edge drawer, not a modal (2026-11-01):** the gear rail tab opens `Controls/SettingsDrawer` in the same animated-width stack as Stream Settings / YPP / Socials / TEST (`SettingsDrawerOpen`, exclusive with the other four). Categories are section headings with their controls indented under them — Zoom holds *Zoom view shape* and *Zoom box follows*. TASK 37 adds **Restore staged scene** and **Restore all scenes** under Layout defaults; both are disabled while live or recording, and restoring a layout preserves the selected webcam. The app menu (Report Bug / Feature Request / About) hangs off a **right-click on the LlamaCasty wordmark**; left-click still opens About. The modal shell keeps only Bug / Feature / About, which is why it no longer needs a scroll viewer.
- **Top bar:** the `EDIT` toggle sits beside the REC/ON-AIR session controls; the brand and account surfaces remain at the sides. Its background uses the idle surface color when stopped. Normal ON-AIR stays `Brush.Primary` red while connecting and turns `Brush.Positive` green only after YouTube reports the broadcast `live`; stopping restores the idle color. TEST stays gold for the entire test session. Its **right edge aligns with the layers panel below** (`TopBar` column 0 is a fixed **352** = work-area margin 8 + 360px column − the bar's own 16px padding), so the button and the panel share an edge. The **settings gear moved to the preview rail** (2026-11-01): first tab, orange (`Brush.Attention`), gear icon only — left-click opens the app menu (Settings / Bug / Feature / About), right-click goes straight to App Settings.
- **Preview gestures (2026-11-01):** *edit mode* — left selects/drags/resizes, right opens the context menu, **Ctrl+right toggles the zoom box**. *Preview mode* — **left toggles the zoom box**, right opens the context menu; **Ctrl+right does nothing at all** (no chord while live or recording — one hand, always). ⚠️ **Both the Down and the Up event must be handled for a Ctrl+right-click**: WPF's `PopupControlService` opens a context menu on right-button-**up**, so suppressing only the down event leaves the menu appearing under the gesture (found 2026-11-01 in edit mode). Menus exist on the webcam layer and the backdrop; every other layer right-clicks through to the backdrop menu. Left-dragging with the zoom box open moves it, in both modes. **Ctrl-down closes it**: pressing Ctrl while the box is open dismisses it, so the same hand that opened it can put it away (`MainWindow_PreviewKeyDown`; the box cannot cancel itself on creation because Ctrl is already down before it exists). **Follow mode** is a Settings pill, default **off = Anchor**: with Follow on, dragging re-anchors the capture to the box centre (`ZoomFollowsBox`, persisted as the `Zoom.FollowBox` setting). **The gesture activates the box at the cursor**, not merely dismisses it: `ActivateZoom` no longer refuses when idle (it used to return unless `IsLive || IsRecording`, and `ToggleZoom` only ever dismissed — so the gesture did nothing at all outside a session until 2026-11-01). The social bar consumes its own click (toggle top ⇄ bottom), and the preview's tunnelling handler steps aside for it — otherwise the bar is unclickable in preview mode and drags the layer beneath it in edit mode.
- **Preview undo/redo (2026-11-01):** `Ctrl+Z` / `Ctrl+Shift+Z`, window-level bindings, live only while `EditingActive` — undo with the preview showing program output would rewrite a scene nobody is looking at. `Models/PreviewHistory` snapshots element **references** plus geometry, visibility, order and membership, so move / resize / reorder / add / remove / hide all undo in one step per gesture (`PushPreviewUndo` is called once at drag or resize start, never inside the move loop). Property edits (colour, opacity, border, font) are **not** captured yet — stated in the type's doc comment so nobody assumes otherwise. The stack clears on layout load. Guard: `ytLive.Tests/PreviewHistoryTests.cs`.
+125
View File
@@ -0,0 +1,125 @@
using System;
using System.IO;
using System.Linq;
using Xunit;
using ytLive.Services;
namespace ytLive.Tests;
/// <summary>
/// TASK 65 slice 3 — clips on disk, with retention and nothing else.
///
/// <para>The rule: write one file, delete the oldest past the count. No gallery, no prompt. The tests pin
/// the two ways that could go wrong — a zero-byte clip from an empty ring, and pruning taking something
/// that isn't ours.</para>
/// </summary>
public sealed class ClipLibraryTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"ytLlive-clips-{Guid.NewGuid():N}");
public ClipLibraryTests() => Directory.CreateDirectory(_root);
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch { /* best effort */ }
}
private ClipLibrary Library() => new(() => _root);
[Fact]
public void SaveWritesIntoClipsBesideTheRecordings()
{
var path = Library().Save(new byte[] { 1, 2, 3 }, DateTime.Now, keep: 3);
Assert.NotNull(path);
Assert.EndsWith(".mp4", path);
Assert.Equal(Path.Combine(_root, "clips"), Path.GetDirectoryName(path));
Assert.True(File.Exists(path));
}
[Fact]
public void AnEmptySnapshotNeverBecomesAZeroByteFile()
{
Assert.Null(Library().Save(Array.Empty<byte>(), DateTime.Now, keep: 3));
Assert.False(Directory.Exists(Path.Combine(_root, "clips"))
&& Directory.EnumerateFiles(Path.Combine(_root, "clips")).Any());
}
[Fact]
public void RetentionKeepsTheNewestAndDeletesTheRest()
{
var library = Library();
var folder = library.EnsureFolder();
for (var i = 0; i < 6; i++)
File.WriteAllText(Path.Combine(folder, $"clip-20261110-12000{i}.mp4"), "x");
File.WriteAllText(Path.Combine(folder, "someone-elses-file.mp4"), "keep me");
var removed = library.Prune(keep: 3);
Assert.Equal(3, removed);
var remaining = library.Recent();
Assert.Equal(3, remaining.Count);
Assert.Contains("120005", remaining[0]); // newest first
Assert.True(File.Exists(Path.Combine(folder, "someone-elses-file.mp4")));
}
[Fact]
public void RingBytesFollowLengthAndBitrate_WithHeadroom()
{
var tenAt8 = ClipLibrary.RingBytesFor(10, 8000);
var fifteenAt8 = ClipLibrary.RingBytesFor(15, 8000);
Assert.True(tenAt8 > 10L * 8000 * 1000 / 8); // more than the exact wire size
Assert.True(fifteenAt8 > tenAt8);
Assert.True(tenAt8 < 15L * 1024 * 1024); // and still modest
}
}
/// <summary>
/// TASK 65 slice 4 — the three settings behind the gear drawer. They persist, and the loader coerces
/// anything unexpected back into the allowed set: a bad value must never leave the user with a clip
/// length the ring cannot serve.
/// </summary>
public sealed class ClipSettingsTests : IDisposable
{
private readonly string _db = Path.Combine(Path.GetTempPath(), $"ytLlive-clipsettings-{Guid.NewGuid():N}.db");
public void Dispose()
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
try { File.Delete(_db); } catch { /* best effort */ }
}
[Fact]
public void SettingsPersistAndCoerce()
{
using (var store = new LayoutStore(_db))
{
Assert.False(store.LoadClipsEnabled()); // opt-in
Assert.Equal(10, store.LoadClipSeconds()); // default 10
Assert.Equal(3, store.LoadClipKeep()); // default 3
store.SaveClipsEnabled(true);
store.SaveClipSeconds(15);
store.SaveClipKeep(5);
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
using (var store = new LayoutStore(_db))
{
Assert.True(store.LoadClipsEnabled());
Assert.Equal(15, store.LoadClipSeconds());
Assert.Equal(5, store.LoadClipKeep());
store.SaveClipSeconds(7); // not a choice we offer
store.SaveClipKeep(9); // past the ceiling
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
using (var store = new LayoutStore(_db))
{
Assert.Equal(10, store.LoadClipSeconds());
Assert.Equal(3, store.LoadClipKeep());
}
}
}
+68
View File
@@ -0,0 +1,68 @@
using System;
using Xunit;
using ytLive.Services;
namespace ytLive.Tests;
/// <summary>
/// TASK 65 slice 1 — the replay ring as pure memory.
///
/// <para>The two rules that matter and are easy to break later: the cap is by <b>bytes</b> (bitrate moves,
/// seconds do not), and a snapshot is always init-segment-first, because an MP4 without its moov is not a
/// video, it is noise.</para>
/// </summary>
public sealed class ClipRingTests
{
[Fact]
public void Snapshot_IsInitThenFragmentsInOrder()
{
var ring = new ClipRing(1024);
ring.SetInit(new byte[] { 1, 2 });
ring.Append(new byte[] { 3 });
ring.Append(new byte[] { 4, 5 });
Assert.Equal(new byte[] { 1, 2, 3, 4, 5 }, ring.Snapshot());
Assert.Equal(5, ring.Bytes);
Assert.Equal(2, ring.FragmentCount);
}
[Fact]
public void TheCapDropsOldestFragments_SoTheClipEndsAtTheKeypress()
{
var ring = new ClipRing(capBytes: 10);
ring.SetInit(new byte[2]);
for (var i = 0; i < 5; i++) ring.Append(new byte[3]); // 2 + 15 = 17 → trims
Assert.True(ring.Bytes <= 10);
Assert.Equal(2, ring.FragmentCount); // newest two survive
var snapshot = ring.Snapshot();
Assert.Equal(2 + 3 + 3, snapshot.Length);
}
[Fact]
public void NothingBuffered_SnapshotsEmpty_SoTheCallerCannotWriteAZeroByteFile()
{
var ring = new ClipRing(1024);
Assert.True(ring.IsEmpty);
Assert.Empty(ring.Snapshot());
ring.SetInit(new byte[4]);
Assert.True(ring.IsEmpty); // init alone is not a clip
Assert.Empty(ring.Snapshot());
}
[Fact]
public void ClearForgetsTheInit_SoTheNextEncoderStartCannotReuseAStaleHeader()
{
var ring = new ClipRing(1024);
ring.SetInit(new byte[] { 9 });
ring.Append(new byte[] { 8 });
ring.Clear();
Assert.True(ring.IsEmpty);
Assert.Equal(0, ring.Bytes);
ring.Append(new byte[] { 7 });
Assert.Empty(ring.Snapshot()); // still no init → not playable
}
}
+101
View File
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using ytLive.Services;
using ytLive.Services.Encoder;
namespace ytLive.Tests;
/// <summary>
/// TASK 65 slice 2 — the clip mux as a side channel.
///
/// <para>Two things are pinned here and both protect the broadcast: the command line gains the clip
/// output ONLY when clips are enabled (otherwise ffmpeg's args are byte-for-byte what they were), and the
/// byte splitter turns ffmpeg's fragmented MP4 into whole fragments without ever seeing the stream path.</para>
/// </summary>
public sealed class ClipStreamTests
{
private static byte[] Box(string type, int payloadBytes)
{
var payload = Enumerable.Repeat((byte)0x41, payloadBytes).ToArray();
var box = new byte[8 + payloadBytes];
var size = box.Length;
box[0] = (byte)(size >> 24);
box[1] = (byte)(size >> 16);
box[2] = (byte)(size >> 8);
box[3] = (byte)size;
Encoding.ASCII.GetBytes(type).CopyTo(box, 4);
payload.CopyTo(box, 8);
return box;
}
[Fact]
public void TheClipOutputIsAppendedOnlyWhenClipsAreEnabled()
{
var plain = FfmpegArgs.Build(Options(clip: null), "libopenh264");
var withClips = FfmpegArgs.Build(Options(clip: new ClipRing(1 << 20)), "libopenh264");
Assert.DoesNotContain("pipe:1", plain);
Assert.Contains("pipe:1", withClips);
// The stream block must not move: everything up to the clip output is identical.
// The clip block is appended, so the original command line is a strict prefix of the new one.
Assert.Equal(plain, withClips.Take(plain.Count).ToList());
}
[Fact]
public void SplitterFeedsInitAndWholeFragments_EvenWhenBytesArriveInPieces()
{
var ring = new ClipRing(1 << 20);
var splitter = new Fmp4FragmentSplitter(ring);
var stream = new List<byte>();
stream.AddRange(Box("ftyp", 16));
stream.AddRange(Box("moov", 32));
stream.AddRange(Box("moof", 8));
stream.AddRange(Box("mdat", 40));
stream.AddRange(Box("moof", 8));
stream.AddRange(Box("mdat", 40));
// Deliberately ragged writes: a box must survive being cut anywhere.
var bytes = stream.ToArray();
var offset = 0;
foreach (var chunk in new[] { 3, 7, 11, 29, 1000 })
{
var take = Math.Min(chunk, bytes.Length - offset);
if (take <= 0) break;
splitter.Write(bytes.AsSpan(offset, take));
offset += take;
}
if (offset < bytes.Length) splitter.Write(bytes.AsSpan(offset));
Assert.Equal(2, ring.FragmentCount);
var snapshot = ring.Snapshot();
Assert.True(snapshot.Length > 0);
Assert.Equal("ftyp", Encoding.ASCII.GetString(snapshot, 4, 4)); // init comes first
}
[Fact]
public void MdatWithoutAMoofIsNotReplayable_AndIsIgnored()
{
var ring = new ClipRing(1 << 20);
var splitter = new Fmp4FragmentSplitter(ring);
splitter.Write(Box("ftyp", 8));
splitter.Write(Box("moov", 8));
splitter.Write(Box("mdat", 32)); // no moof → not a fragment
Assert.Empty(ring.Snapshot()); // init alone is not a clip
Assert.Equal(0, ring.FragmentCount);
}
private static EncoderOptions Options(ClipRing? clip) => new()
{
RtmpUrl = "rtmp://a.rtmp.youtube.com/live2/key",
Width = 1920, Height = 1080, Fps = 30, BitrateKbps = 6000,
StreamEnabled = true,
ClipBuffer = clip,
};
}
+70
View File
@@ -0,0 +1,70 @@
using System;
using System.IO;
using Xunit;
using ytLive.Services;
namespace ytLive.Tests;
/// <summary>
/// TASK 55·2–3 — the two disk debts a free app must not leave: the temp alert clip it materialises and
/// never deletes, and a recording that starts with no room to finish.
///
/// <para>Both are tested as policy, because the alternative — filling a real drive — is not a test.</para>
/// </summary>
public sealed class DiskHygieneTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), $"ytLlive-disk-{Guid.NewGuid():N}");
public DiskHygieneTests() => Directory.CreateDirectory(_dir);
public void Dispose()
{
try { Directory.Delete(_dir, recursive: true); } catch { /* best effort */ }
}
[Fact]
public void Sweep_RemovesOnlyTheClipsWeCreated()
{
var ours1 = Path.Combine(_dir, "ytLive-alert-abc.mp4");
var ours2 = Path.Combine(_dir, "ytLive-alert-def.mp4");
var theirs = Path.Combine(_dir, "someone-elses-recording.mp4");
File.WriteAllText(ours1, "x");
File.WriteAllText(ours2, "x");
File.WriteAllText(theirs, "x");
var removed = AlertClipCleanup.Sweep(_dir);
Assert.Equal(2, removed);
Assert.False(File.Exists(ours1));
Assert.False(File.Exists(ours2));
Assert.True(File.Exists(theirs)); // never touch anything that isn't ours
}
[Fact]
public void Delete_IsSafeOnMissingBlankAndNull()
{
Assert.False(AlertClipCleanup.Delete(null));
Assert.False(AlertClipCleanup.Delete(""));
Assert.False(AlertClipCleanup.Delete(Path.Combine(_dir, "not-there.mp4")));
var file = Path.Combine(_dir, "ytLive-alert-gone.mp4");
File.WriteAllText(file, "x");
Assert.True(AlertClipCleanup.Delete(file));
Assert.False(File.Exists(file));
}
[Fact]
public void RecordingIsRefusedBelowAGigabyte_WarnedBelowFive_AndQuietAbove()
{
Assert.Equal(DiskSpaceGuard.StartDecision.Block, DiskSpaceGuard.ForStart(500L * 1024 * 1024));
Assert.Equal(DiskSpaceGuard.StartDecision.Warn, DiskSpaceGuard.ForStart(2L * 1024 * 1024 * 1024));
Assert.Equal(DiskSpaceGuard.StartDecision.Ok, DiskSpaceGuard.ForStart(20L * 1024 * 1024 * 1024));
}
[Fact]
public void MidRecordingWarnsOnceBelowTwoGigabytes()
{
Assert.False(DiskSpaceGuard.ShouldWarnDuring(3L * 1024 * 1024 * 1024));
Assert.True(DiskSpaceGuard.ShouldWarnDuring(1L * 1024 * 1024 * 1024));
}
}
+1
View File
@@ -42,6 +42,7 @@ public class FfmpegEncoderTests
public Stream Stdin { get; }
public Stream StandardInput => Stdin;
public TextReader StandardOutput { get; }
public Stream StandardOutputBytes => Stream.Null;
public bool HasExited { get; private set; }
public int ExitCode { get; private set; }
public bool Killed { get; private set; }
@@ -0,0 +1,92 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Data.Sqlite;
using Xunit;
using ytLive.Models;
using ytLive.ViewModels;
namespace ytLive.Tests;
[Collection("RealApp")]
public sealed class LayoutResetIntegrationTests
{
private readonly RealAppHost _app;
public LayoutResetIntegrationTests(RealAppHost app) => _app = app;
[Fact]
public void SettingsRestoreAll_ReplacesEditedScenesWithFactoryLayout() => _app.Run(() =>
{
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-reset-{Guid.NewGuid():N}.db");
MainViewModel.LayoutPathOverride = tempDb;
MainViewModel? vm = null;
try
{
vm = new MainViewModel();
var starting = vm.Scenes.Single(scene => SceneCatalog.Is(scene.Name, SceneCatalog.Starting));
starting.Elements.Add(new Source
{
Name = "Creator-only layer",
Type = SourceType.TextOverlay,
TextContent = "Not in factory layout",
});
vm.SaveLayoutNow();
Assert.True(vm.RestoreAllLayoutDefaultsCommand.CanExecute(null));
vm.RestoreAllLayoutDefaultsCommand.Execute(null);
Assert.DoesNotContain(vm.Scenes.SelectMany(scene => scene.Elements).OfType<Source>(),
source => source.Name == "Creator-only layer");
var settingsXaml = SourceAssert.Text("Controls", "SettingsDrawer.xaml");
Assert.Contains("Content=\"Restore all scenes\"", settingsXaml);
Assert.Contains("Command=\"{Binding RestoreAllLayoutDefaultsCommand}\"", settingsXaml);
}
finally
{
vm?.Shutdown();
MainViewModel.LayoutPathOverride = null;
SqliteConnection.ClearAllPools();
try { File.Delete(tempDb); } catch { /* best-effort cleanup */ }
}
});
[Fact]
public void SettingsRestoreStagedScene_LeavesOtherSceneEditsAndSelectionIntact() => _app.Run(() =>
{
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-reset-{Guid.NewGuid():N}.db");
MainViewModel.LayoutPathOverride = tempDb;
MainViewModel? vm = null;
try
{
vm = new MainViewModel();
var starting = vm.Scenes.Single(scene => SceneCatalog.Is(scene.Name, SceneCatalog.Starting));
var brb = vm.Scenes.Single(scene => SceneCatalog.Is(scene.Name, SceneCatalog.Brb));
starting.Elements.Add(new Source { Name = "Keep this edit", Type = SourceType.TextOverlay });
brb.Elements.Add(new Source { Name = "Reset this edit", Type = SourceType.TextOverlay });
vm.SaveLayoutNow();
vm.StagedScene = brb;
Assert.True(vm.RestoreStagedSceneDefaultsCommand.CanExecute(null));
vm.RestoreStagedSceneDefaultsCommand.Execute(null);
Assert.Contains(vm.Scenes.Single(scene => SceneCatalog.Is(scene.Name, SceneCatalog.Starting))
.Elements.OfType<Source>(), source => source.Name == "Keep this edit");
Assert.DoesNotContain(vm.Scenes.Single(scene => SceneCatalog.Is(scene.Name, SceneCatalog.Brb))
.Elements.OfType<Source>(), source => source.Name == "Reset this edit");
Assert.True(SceneCatalog.Is(vm.StagedScene?.Name, SceneCatalog.Brb));
var settingsXaml = SourceAssert.Text("Controls", "SettingsDrawer.xaml");
Assert.Contains("Content=\"Restore staged scene\"", settingsXaml);
Assert.Contains("Command=\"{Binding RestoreStagedSceneDefaultsCommand}\"", settingsXaml);
}
finally
{
vm?.Shutdown();
MainViewModel.LayoutPathOverride = null;
SqliteConnection.ClearAllPools();
try { File.Delete(tempDb); } catch { /* best-effort cleanup */ }
}
});
}
+220
View File
@@ -0,0 +1,220 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Data.Sqlite;
using Xunit;
using ytLive.Models;
using ytLive.Services;
namespace ytLive.Tests;
public sealed class LayoutStoreSnapshotTests
{
[Fact]
public void SameBuild_OpensCurrentLayout_WithoutChangingDefaultSnapshot()
{
var path = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-snapshot-{Guid.NewGuid():N}.db");
const string buildId = "build-a";
try
{
using (var store = new LayoutStore(path))
{
var factory = MakeScene("Factory title");
store.Save(new[] { factory }, null, null);
store.PrepareLayoutSnapshots(buildId);
store.Save(new[] { MakeScene("Creator edit") }, null, null);
}
using (var reopened = new LayoutStore(path))
{
reopened.PrepareLayoutSnapshots(buildId);
var current = Assert.Single(reopened.Load());
Assert.Equal("Creator edit", Assert.Single(current.Elements.OfType<Source>()).Name);
using var connection = GetConnection(path);
using var command = connection.CreateCommand();
command.CommandText = "SELECT Value FROM LayoutSnapshotState WHERE Key = 'CurrentBuildId';";
Assert.Equal(buildId, command.ExecuteScalar());
command.CommandText = "SELECT Name FROM DefaultSource;";
Assert.Equal("Factory title", command.ExecuteScalar());
}
}
finally
{
SqliteConnection.ClearAllPools();
try { File.Delete(path); } catch { /* best-effort cleanup */ }
}
}
[Fact]
public void DifferentBuild_RestoresTheDefaultSnapshotBeforeLoading()
{
var path = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-snapshot-{Guid.NewGuid():N}.db");
try
{
using (var store = new LayoutStore(path))
{
store.Save(new[] { MakeScene("Factory title") }, null, null);
store.PrepareLayoutSnapshots("build-a");
store.Save(new[] { MakeScene("Creator edit") }, null, null);
}
using (var reopened = new LayoutStore(path))
{
reopened.PrepareLayoutSnapshots("build-b");
var restored = Assert.Single(reopened.Load());
Assert.Equal("Factory title", Assert.Single(restored.Elements.OfType<Source>()).Name);
using var connection = GetConnection(path);
using var command = connection.CreateCommand();
command.CommandText = "SELECT Value FROM LayoutSnapshotState WHERE Key = 'CurrentBuildId';";
Assert.Equal("build-b", command.ExecuteScalar());
}
}
finally
{
SqliteConnection.ClearAllPools();
try { File.Delete(path); } catch { /* best-effort cleanup */ }
}
}
[Fact]
public void ResetOneScene_RestoresItsFactoryLayers_AndKeepsOtherSceneEdits()
{
var path = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-snapshot-{Guid.NewGuid():N}.db");
var starting = MakeScene(SceneCatalog.Starting, "Factory starting");
var brb = MakeScene(SceneCatalog.Brb, "Factory BRB");
try
{
using (var store = new LayoutStore(path))
{
store.Save(new[] { starting, brb }, null, null);
store.PrepareLayoutSnapshots("build-a");
store.Save(new[]
{
MakeScene(starting.Id, starting.Name, "Edited starting"),
MakeScene(brb.Id, brb.Name, "Edited BRB"),
}, null, null);
}
using (var reopened = new LayoutStore(path))
{
reopened.PrepareLayoutSnapshots("build-a");
Assert.True(reopened.RestoreDefaultScene(starting.Id));
var scenes = reopened.Load();
Assert.Equal("Factory starting", Assert.Single(scenes.Single(s => s.Id == starting.Id).Elements.OfType<Source>()).Name);
Assert.Equal("Edited BRB", Assert.Single(scenes.Single(s => s.Id == brb.Id).Elements.OfType<Source>()).Name);
}
}
finally
{
SqliteConnection.ClearAllPools();
try { File.Delete(path); } catch { /* best-effort cleanup */ }
}
}
[Fact]
public void DifferentBuild_RestoresWebcamPlacement_WithoutReplacingChosenCamera()
{
var path = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-snapshot-{Guid.NewGuid():N}.db");
var sceneId = Guid.NewGuid().ToString();
var defaultWebcam = new Webcam { Id = "factory-webcam", DeviceId = "factory-device", Name = "Factory camera" };
var chosenWebcam = new Webcam { Id = "chosen-webcam", DeviceId = "chosen-device", Name = "Chosen camera" };
try
{
using (var store = new LayoutStore(path))
{
store.Save(new[] { MakeWebcamScene(sceneId, defaultWebcam.Id, 20) }, defaultWebcam, null);
store.PrepareLayoutSnapshots("build-a");
store.Save(new[] { MakeWebcamScene(sceneId, chosenWebcam.Id, 200) }, chosenWebcam, null);
}
using (var reopened = new LayoutStore(path))
{
reopened.PrepareLayoutSnapshots("build-b");
var restored = Assert.Single(reopened.Load());
var config = Assert.Single(restored.Elements.OfType<WebcamSceneConfig>());
Assert.Equal(chosenWebcam.DeviceId, reopened.Webcam?.DeviceId);
Assert.Equal(chosenWebcam.Id, config.WebcamId);
Assert.Equal(20, config.X);
}
}
finally
{
SqliteConnection.ClearAllPools();
try { File.Delete(path); } catch { /* best-effort cleanup */ }
}
}
[Fact]
public void ResetAllScenes_RestoresTheFactorySnapshot()
{
var path = Path.Combine(Path.GetTempPath(), $"ytLlive-layout-snapshot-{Guid.NewGuid():N}.db");
var starting = MakeScene(SceneCatalog.Starting, "Factory starting");
var brb = MakeScene(SceneCatalog.Brb, "Factory BRB");
try
{
using (var store = new LayoutStore(path))
{
store.Save(new[] { starting, brb }, null, null);
store.PrepareLayoutSnapshots("build-a");
store.Save(new[]
{
MakeScene(starting.Id, starting.Name, "Edited starting"),
MakeScene(brb.Id, brb.Name, "Edited BRB"),
}, null, null);
}
using (var reopened = new LayoutStore(path))
{
reopened.PrepareLayoutSnapshots("build-a");
Assert.True(reopened.RestoreAllDefaults());
var scenes = reopened.Load();
Assert.Equal("Factory starting", Assert.Single(scenes.Single(s => s.Name == SceneCatalog.Starting).Elements.OfType<Source>()).Name);
Assert.Equal("Factory BRB", Assert.Single(scenes.Single(s => s.Name == SceneCatalog.Brb).Elements.OfType<Source>()).Name);
}
}
finally
{
SqliteConnection.ClearAllPools();
try { File.Delete(path); } catch { /* best-effort cleanup */ }
}
}
private static Scene MakeScene(string sourceName)
=> MakeScene(SceneCatalog.Starting, sourceName);
private static Scene MakeScene(string sceneName, string sourceName)
=> new()
{
Name = sceneName,
Elements = { new Source { Name = sourceName, Type = SourceType.TextOverlay } },
};
private static Scene MakeScene(string id, string sceneName, string sourceName)
=> new()
{
Id = id,
Name = sceneName,
Elements = { new Source { Name = sourceName, Type = SourceType.TextOverlay } },
};
private static Scene MakeWebcamScene(string id, string webcamId, double x)
=> new()
{
Id = id,
Name = SceneCatalog.Live,
Elements = { new WebcamSceneConfig { WebcamId = webcamId, Name = "Webcam", X = x, Y = 20, Width = 320, Height = 180 } },
};
private static SqliteConnection GetConnection(string path)
{
var connection = new SqliteConnection($"Data Source={path}");
connection.Open();
return connection;
}
}
+67
View File
@@ -0,0 +1,67 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Data.Sqlite;
using Xunit;
using ytLive.Models;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>
/// TASK 65 slice 5 — the replay layer as a thing the creator can add, and the one guard that matters.
///
/// <para>The layer is an ordinary media layer with an app-owned path, so the test only has to prove the
/// flags: one per scene, silent by default, once-through in Live and looping everywhere else. Playback
/// itself rides the media manager that TASK 21 already covers.</para>
/// </summary>
[Collection("RealApp")]
public sealed class ReplayLayerTests
{
private readonly RealAppHost _app;
public ReplayLayerTests(RealAppHost app) => _app = app;
[Fact]
public void AddReplayLayer_IsOnePerScene_SilentByDefault_AndLoopsOutsideLive() => _app.Run(() =>
{
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-replay-{Guid.NewGuid():N}.db");
MainViewModel.LayoutPathOverride = tempDb;
try
{
var vm = new MainViewModel();
vm.StagedScene = vm.Scenes.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Live));
vm.AddReplayLayer();
vm.AddReplayLayer(); // second add is a no-op
var layers = vm.Scenes.SelectMany(s => s.Elements).OfType<Source>()
.Where(s => s.IsReplayLayer).ToList();
Assert.Single(layers);
var liveLayer = layers[0];
Assert.True(liveLayer.MediaMuted); // silent by default
Assert.False(liveLayer.MediaIsLooping); // Live plays once
// Any other scene loops the kept set.
vm.StagedScene = vm.Scenes.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Brb));
vm.AddReplayLayer();
var brbLayer = vm.Scenes.SelectMany(s => s.Elements).OfType<Source>()
.Single(s => s.IsReplayLayer && s != liveLayer);
Assert.True(brbLayer.MediaIsLooping);
Assert.True(brbLayer.MediaMuted);
// Clips off by default, and with no ring nothing is written by a stray F10.
Assert.False(vm.ClipsEnabled);
vm.SaveReplayClip();
var clipsFolder = Path.Combine(Path.GetDirectoryName(tempDb)!, "clips");
Assert.False(Directory.Exists(clipsFolder) && Directory.EnumerateFiles(clipsFolder).Any());
}
finally
{
MainViewModel.LayoutPathOverride = null;
SqliteConnection.ClearAllPools();
try { File.Delete(tempDb); } catch { /* best effort */ }
}
});
}
+89
View File
@@ -0,0 +1,89 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Data.Sqlite;
using Xunit;
using ytLive.Models;
using ytLive.Services;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>
/// TASK 35 — the scene remembers the room.
///
/// <para>The rule the test pins, in the creator's words: a scene's audio state is applied <b>once when
/// it takes the program output</b>. `null` means "leave the mix alone", so staging a scene offline, or
/// switching to a scene with no opinion, must never undo a manual mute.</para>
/// </summary>
[Collection("RealApp")]
public sealed class SceneAudioTests
{
private readonly RealAppHost _app;
public SceneAudioTests(RealAppHost app) => _app = app;
[Fact]
public void EnteringALiveScene_AppliesItsAudioState_OnceAndOnlyLive() => _app.Run(() =>
{
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-sceneaudio-{Guid.NewGuid():N}.db");
MainViewModel.LayoutPathOverride = tempDb;
try
{
var vm = new MainViewModel();
var brb = vm.Scenes.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Brb));
var chat = vm.Scenes.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Chat));
// Ships muted (the creator's default), while every other scene is passive.
Assert.True(brb.SceneMutesMic);
Assert.Null(chat.SceneMutesMic);
Assert.Null(brb.SceneMutesDesktop);
vm.MicVolume = 0.8;
Assert.False(vm.MicMuted);
// Staging offline: no program output, so no audio edit. The creator is auditioning.
vm.TransitionToScene(brb);
Assert.False(vm.MicMuted);
// Live: entering BRB mutes the mic.
vm.StreamStatus = StreamStatus.Streaming;
vm.TransitionToScene(vm.Scenes.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Live)));
vm.TransitionToScene(brb);
Assert.True(vm.MicMuted);
// The creator is boss: a manual unmute survives a scene with no opinion.
vm.SetMicMuted(false);
Assert.False(vm.MicMuted);
vm.TransitionToScene(chat);
Assert.False(vm.MicMuted);
// ...but a scene that DOES have an opinion wins on its next entry.
chat.SceneMutesMic = true;
vm.TransitionToScene(brb);
vm.TransitionToScene(chat);
Assert.True(vm.MicMuted);
// Desktop audio was never told anything, so it was never touched.
Assert.False(vm.GameMuted);
// Roundtrip: the three states survive a save + reload, null included.
vm.SaveLayoutNow();
SqliteConnection.ClearAllPools();
using var store = new LayoutStore(tempDb);
var reloaded = store.Load();
var reloadedBrb = reloaded.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Brb));
var reloadedChat = reloaded.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Chat));
var reloadedLive = reloaded.Single(s => SceneCatalog.Is(s.Name, SceneCatalog.Live));
Assert.True(reloadedBrb.SceneMutesMic);
Assert.True(reloadedChat.SceneMutesMic);
Assert.Null(reloadedLive.SceneMutesMic);
}
finally
{
MainViewModel.LayoutPathOverride = null;
SqliteConnection.ClearAllPools();
try { File.Delete(tempDb); } catch { /* best effort */ }
}
});
}