Compare commits

..
21 Commits
Author SHA1 Message Date
gramps e92ce4bb63 fix(dock): the master ladder moves when no session is running
Reported: no activity in the master meter.

Cause: `MasterLevel` measures the buffer the ENCODER receives, and that buffer only exists while the
mix is being pulled — streaming or recording. Idle, nothing fills it, so the master read zero while
the bays below it moved. A master that is dead between sessions is a gap in the design.

Now: while a session runs the master shows the measured mix (unchanged); idle it shows an estimate
computed from the same measured sources and the same gains the mix applies
(`MeterScale.MonitorFraction`, pure + tested). Two ladders can therefore never tell contradictory
stories about whether audio exists.

Guard: MeterScaleTests pins the estimate — silence reads zero, a quiet source at unity is visible,
two sources add, and gain is applied in the LINEAR domain like the mix (scaling the display fraction
would be a different, wrong curve).
2026-10-30 14:01:29 -07:00
gramps ec293e54b0 feat(dock): TRAX becomes a background level, not a channel strip
Creator ruling (2026-10-30): TRAX is background music and is controlled separately from desktop and
mic — so KISS it:

- TRAX loses its own ladder and slider. It is one number plus ±5 dB buttons, disabled at the ends
  (−60 dB floor, +6 dB ceiling).
- It STARTS at −50 dB, taken from the creator's own meter readings, and moves in 5 dB clicks. If that
  proves inaudible on their setup, six clicks lands at −20 — the buttons exist for exactly that, and
  `TraxDefaultDb` is one constant.
- Layout follows: Desktop's volume now sits directly beneath its ladder, and the TRAX row (name,
  play/pause, level) sits beneath that, inside the GAME bay. The bays are MIC | GAME+TRAX | LIP-SYNC.
- The metering tap on the player stays (it is how "is the music producing sound" is answered) but has
  no ladder of its own; the desktop bed already shows the music.

Guards updated: TraxBayTests now asserts the stepper wiring and that the row has NO SegmentMeter;
GameBayTests asserts the desktop fader sits below the desktop ladder.
2026-10-30 13:46:05 -07:00
gramps 93dc6592ac docs(dock): the desktop ladder says it includes TRAX
TRAX is not a separate bus: it plays through the default output device and WASAPI loopback taps
that device, so the music genuinely is in the desktop bed — the Desktop ladder moving with a track
is correct, not a leak. The bay now says so on the label and in a tooltip, because two moving
ladders for one sound invites exactly this question.

No behaviour change: routing stays right (the stream hears the music once, via loopback).
2026-10-30 13:34:27 -07:00
gramps 8d23502220 fix(trax): the fader now actually changes the level — and the meter follows it
Reported: pegging the TRAX fader changes nothing audible, the ladder never reaches red, and the
ladder does not scale with the fader.

Cause (two defects in the same setters):
- UserGain wrote the OUTPUT DEVICE's volume. NAudio's WaveOut ignores that, so the fader was inert.
- LocalGain (the desktop-mute follow) recomputed the sample-chain volume WITHOUT the user gain, so
  every duck/mute silently discarded whatever the creator had set.

Fix: one `EffectiveVolume(user, local)` = MusicVolume × user × local, applied to the sample chain by
both setters. The meter sits AFTER that stage, so the ladder now scales with the fader and can reach
the peak band on a loud track — exactly what pegging should look like. Max user gain is +6 dB, so
"pegged" means the file at unity, not a magic boost.

Guard: MusicLevelTests pins the arithmetic (default half, pegged double, mute multiplies to zero),
that the user gain survives the mute follow, and that nothing may drive the output device's volume
again — the no-op that made this invisible.
2026-10-30 13:32:24 -07:00
gramps 2607ecf210 fix(dock): TRAX ladder gets the mic's ballistics (and a 33 Hz beat)
Reported: the TRAX bar moves, but its sampling looks far slower than the mic meter.

Cause: the TRAX number was a raw instantaneous peak per metering block — a stutter sampled by the UI
timer, with no smoothing. The mic looks fluid because it is smoothed at audio-callback rate.

Fix: the player now smooths its measured level with the SAME curve the mic uses
(MeterScale.NextLevel: fast attack, gentle decay), and the dock's meter clock runs at ~30 Hz instead
of 20. Two ladders that move alike, because they are the same ballistics.

Guard: MeterScaleTests pins the attack/decay behaviour alongside peak-hold.
2026-10-30 13:28:32 -07:00
gramps 839bc991a2 fix(dock): meters beat on their own 20 Hz clock, and TRAX silence is diagnosed
Reported: TRAX plays audibly but no ladder registers anywhere.

Two distinct faults, one of them mine:
1. The meter readouts were refreshed only from the MIC's level callback. With a silent or absent
   mic there is no tick, so a playing TRAX never updated its ladder — the level was measured, the
   UI simply never asked for it. Meters now have a 20 Hz DispatcherTimer of their own.
2. If the player's own meter still reads 0 while playing, the samples are not reaching the device
   (or metering is not attached). That now writes ONE line to startup.log after 2s — so the next
   report says which side is broken instead of another round of guessing.

Note: TRAX rides the desktop loopback, so once the mix captures it the GAME ladder should move too;
if it does not, the loopback endpoint and the music's output device differ.
2026-10-30 13:24:29 -07:00
gramps a54149bd7c feat(dock): TRAX gets its own ladder — measured at the player's output
Creator: "why is there no meter for when trax is playing?"

Routing answer: TRAX rides the desktop loopback, so it already moved the GAME ladder — there was no
separate TRAX signal in the mix. But that ladder cannot answer the question a deaf creator actually
has: "is the music producing sound at all?" The play glyph cannot either — an open file with a dead
decoder still reports Playing.

So the player now measures its own output: \`MusicPlayer\` wraps the volume stage in an NAudio
\`MeteringSampleProvider\` and exposes \`Level\`; \`ITraxPlayer.Level\` keeps the fake honest. The VM maps
it through the same display scale (\`TraxMeterFraction\`), zeroed when not playing, and the TRAX bay
carries a 24-segment ladder above its fader.

This reverses my earlier "no ladder, nothing honest to show" — the honest thing arrived with a real
measurement. TraxBayTests flipped accordingly (it now asserts the ladder AND its source).
2026-10-30 13:22:13 -07:00
gramps 8aa483f933 docs(handoff): audio dock shipped, awaiting an eyes-and-hands pass 2026-10-30 13:20:19 -07:00
gramps 16689c0a80 feat(dock): the dock is now the only audio surface (unit 10, final)
Deletes the preview's live-controls strip — mic meter + speaker + volume, the game-audio chip,
the TRAX button and the lip-sync slider — and the three code-behind handlers that served it.

One sound surface instead of two: the same gains in two places was the original duplication, and
two places to set a gain is how a creator ends up with a meter that disagrees with what they hear.
~16.7 KB of XAML and 60 lines of event code gone.

Verified: the preview still loads and its interactions still work (selected-layer hit testing, the
socials preview, the brand-logo preview), plus the theme's resource guard.
2026-10-30 13:19:58 -07:00
gramps 5889d71db6 feat(dock): master strip + MONO output (the accessibility switch)
Unit 9, the one that matters most for this creator.

MASTER STRIP (top, nearest the preview):
- one ladder fed by the MEASURED mix — `AudioMixer` now measures the buffer the encoder receives
  (`MasterLevel`, `MasterImbalanceDb`), so the master cannot show a source instead of the output
- `-12.4 dB` readout, and ONE L/R flag that appears above a 6 dB gap instead of a second ladder
- bitrate / FPS / dropped / duration from the existing health poll

MONO OUTPUT:
- `AudioFold.ToMono` averages each stereo pair into both channels, applied after the limiter and
  the sync delay, so the stream AND the recording get what was folded
- `MonoOutput` is persisted (`Audio.MonoOutput`) and restored at startup: an accessibility switch
  that resets each session is an accessibility failure
- one click in the strip, remembered forever

Guard: AudioFoldTests (hard-left reaches the right at half amplitude, hard-right — the inaudible
case — reaches the left, centred material keeps its level, mono buffers untouched) and
MasterStripTests (the strip binds the measured mix + the switch, the store round-trips it, and the
fold is the tested helper rather than new arithmetic). 33 audio tests green.
2026-10-30 13:18:23 -07:00
gramps a6f63f56f3 feat(dock): the LIP-SYNC bay — offset, readout, zero detent
Unit 8. Re-houses the shipped TASK 22 offset in the dock:
- slider −200…+200 ms, snapping to 5 ms ticks (the existing property still clamps and persists)
- readable readout: "0 ms (aligned)" when right, signed otherwise ("+50 ms", "−120 ms")
- presets 0 / +50 / +100; 0 IS the detent — a button is easier to hit than a snap, and "the lip-sync
  is right" deserves one click.

Guard: SyncBayTests pins the binding, the readout, the presets and the snapping, and that the
offset stays the persisted property (no second source of truth).
2026-10-30 13:16:19 -07:00
gramps 7339df5fcd feat(dock): the TRAX bay — track, play/pause, level, duck badge
Unit 7. The bay shows the track name (left-click toggles playback, right-click opens the picker —
the label stays the control), a play/pause button, the duck badge, and a dB level.

No ladder here, deliberately: nothing measures the music bed, and a decorative ladder would break
the measured-not-painted rule. A test asserts the bay has no SegmentMeter.

The level is real: `ITraxPlayer.UserGain` is a new creator gain multiplied onto the fixed design
volume, separate from `LocalGain` (which follows the desktop mute). The VM's `TraxVolumeDb` is the
same dB scale as the other faders, so unity means the bed's design level.
2026-10-30 13:15:17 -07:00
gramps a1d8e761ea feat(dock): the GAME bay — dB fader, measured ladder, mute, real duck badge
Unit 6. Mirrors the mic bay for the desktop/game bed, plus the badge that matters to a creator who
cannot hear the duck: it shows while the ducker is actually attenuating, and it prints the gain the
mixer applied (−12.0 DUCK by design).

- `AudioMixer.DuckGain` exposes `AutoDucker.CurrentGain` instead of leaving it internal.
- VM: `GameVolumeDb` / `GameVolumeDbLabel` (fader face), `GameMeterFraction` (measured level),
  `IsGameDucking` + `GameDuckLabel` refreshed on the level tick — the same moment the ducker runs,
  so the badge cannot lag behind the mix.
- The bay: header chip + source, ladder, mute dot (uses the meter band, so mute reads at a glance),
  dB readout, fader.

Guard: GameBayTests — the dock binds all four, `AutoDucker.DuckGain` is −12.04 dB and the label is
produced through the same dB scale as the faders, and the mixer property exists so the badge cannot
become a hardcoded number.
2026-10-30 13:12:10 -07:00
gramps 3524ede480 feat(dock): the MIC bay — dB fader, measured ladder, mute, picker
Unit 5. The dock's first working bay:
- 24-segment ladder fed by `MicMeterFraction` — the MEASURED display level (already scaled by the
  volume and zeroed when muted), never the gain setting.
- Fader in dB via `MicVolumeDb` (−60 … +6, 0 = unity) with a mono-weight readout
  (`MicVolumeDbLabel`), so "−6.0 dB" is what the creator reads instead of "0.50".
- Mute button whose dot uses the existing MicStatusBrush; clicking the device name opens the mic
  picker, so the label stays the control (the KISS rule: one place to change the mic).

The preview's own mic row stays for now — it is removed in the final unit, after the dock bays are
complete, so nothing is lost if a bay misbehaves.

Guard: MicBayTests — the bay binds the dB face and the measured level (not the gain), the fader
range IS the scale's range, the VM surface exists, and mute still zeroes the ladder.
2026-10-30 12:46:57 -07:00
gramps 7d8021ca09 fix(dock): master strip on top, against the preview
During a live session attention sits on the preview, so the master sound bar belongs as close to it
as possible — master row first, the four bays below. Collapsed mode is unchanged: 36px is the
master strip on its own, so it stays exactly where the eye already is.
2026-10-30 12:45:12 -07:00
gramps 5552bf97a1 fix(dock): inside the work area, bottom edge aligned with the layers panel
The dock was a sibling row BELOW the whole work area, so it could not line up with the layers
panel and read as sitting under it. It now lives in the work-area grid (preview column, bottom
row), and the left panel spans content + dock rows — both columns end on the same line, which is
what the creator asked for.

No behaviour change; placement only.
2026-10-30 12:42:49 -07:00
gramps a7d1afc70b fix(dock): spans the preview column and loses 20px
- The dock now sits in the preview column (Grid.Column=1), so its left edge is the layers panel's
  right edge instead of starting under the brand column. It is a preview-column control, not a
  full-width footer.
- Expanded height 168 → 148 (112 bays + 36 master strip): the mockup's number read as wasted space
  beneath the 154px scene strip.

Guard: AudioDockLayoutTests pins 148 as the design number, so the constant cannot drift silently.
2026-10-30 12:39:36 -07:00
gramps 1a9e8b8d36 feat(audio dock): the shell — 168px, auto-collapsing, replacing the empty bottom bar
Unit 4 of the sound-bar refactor. `Controls/AudioDock` takes the bottom row that held the empty
`BottomBar` spacer (deleted): four bay containers (MIC / GAME / TRAX / LIP-SYNC) above a 36px
master strip, all token-styled.

Height comes from `Models/AudioDockLayout`, not from a setting: 168px normally, 36px below a 900px
window height. At the 1366×768 minimum a full dock leaves ~398px for the preview, so the collapse
is mandatory, not cosmetic. The dock listens to its window's SizeChanged and re-applies.

Nothing here pretends to be a meter yet — the bays and the master readouts fill in over the next
units, each with its own test.

Guard: AudioDockLayoutTests pins both sides of the threshold (768 collapsed, 1040 expanded), the
boundary itself, and the two heights as the design's numbers.
2026-10-30 12:37:17 -07:00
gramps 0f62e55474 feat(audio): the segment meter control (unit 3 of the dock)
`Controls/SegmentMeter` draws a 24-segment ladder in ONE OnRender pass — no per-segment elements
updating on the UI thread, which is the difference between a meter and a UI thread tax. Level and
peak are display fractions (what was MEASURED), never gain settings; vertical for the bay ladders,
horizontal for the master strip.

Bands come from `Helpers/MeterScale` (nominal/caution/peak, DESIGN.md thresholds) and live as
dependencies of the control, so the painting logic is pure and testable: the band a segment paints
is the level it measured. Brushes resolve from the theme tokens via SetResourceReference, so the
ladder cannot drift from DESIGN.md.

Peak-hold is the reason the header exists: a bar that follows the moment hides clipping, and
clipping is the one audio fault that cannot be fixed after the stream.

Guard: MeterScaleTests — band edges (inclusive at −12 and −3, as the standard states the ranges),
the −60…0 display scale, and peak-hold rising instantly then decaying at 0.35/s.
2026-10-30 12:36:05 -07:00
gramps 575caa7bc4 feat(audio): the meter knows which side a signal is on (unit 2 of the dock)
`AudioLevelMeter` measured one number for everything. It now also keeps smoothed per-channel
levels with the same attack/decay, plus `ImbalanceDb`. Mono samples report both sides equal (a mono
source is centred), so the two never disagree about whether audio exists.

The dock shows ONE ladder per source — two ladders per bay was visual noise for a rare failure —
but this creator is profoundly deaf on the right, so the one case that matters is "the sound is
panned away from me". That is now measurable and will drive a flag, not a second ladder.

Semantics that mattered: a silent side is compared at the −60 dBFS floor, so a fully one-sided
signal reads ≈54 dB rather than "nothing to compare". My first version returned 0 for exactly the
case the feature exists for; the test caught it.

Guard: StereoMeterTests — hard left, hard right (the inaudible case), balanced stereo, mono
centred, and silence-is-not-an-imbalance. 31 audio tests green.
2026-10-30 12:33:40 -07:00
gramps afe21682c2 feat(audio): the dock's dB scale, and the mono fold primitive
Unit 1 of the sound-bar refactor. The model stores linear gain; the dock shows decibels, because
"−6 dB" is readable and "0.50" is not. `Helpers/GainDb` owns the mapping:

- 0 dB = unity (the old 1.0), range −60 dB (true silence, exactly 0 gain) … +6 dB.
- Labels for the fader readout: "−∞", "-6.0", "+1.5".
- `MonoFold(L,R)` = (L+R)/2, the accessible downmix: hard-panned content becomes audible on both
  sides at half amplitude instead of absent from one. Creator context: profoundly deaf on the
  right, so single-sided audio is inaudible, not merely annoying.

Guard: GainDbTests pins unity, the −6 dB half, the exact-zero floor, the +6 dB ceiling, a
round-trip across the range, the labels, and the fold arithmetic (a right-only 0.5 arrives on the
left at 0.25).
2026-10-30 12:32:07 -07:00
33 changed files with 1489 additions and 223 deletions
+249
View File
@@ -0,0 +1,249 @@
<UserControl x:Class="ytLive.Controls.AudioDock"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:ytLive.Controls">
<!-- The sound bars. Replaces the empty bottom-bar spacer; collapses to the telemetry strip
on short windows (AudioDockLayout decides the height, not this file). -->
<Border x:Name="DockRoot" Background="{StaticResource Brush.SurfaceContainer}"
BorderBrush="{StaticResource Brush.Outline}" BorderThickness="0,1,0,0">
<Grid>
<Grid.RowDefinitions>
<!-- Master FIRST: during a live session attention is on the preview, so the
master strip sits against it and the bays hang below (creator, 2026-10-30). -->
<RowDefinition Height="36"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Four bays: MIC | GAME | TRAX | SYNC. Filled in by the bay units. -->
<Grid x:Name="Bays" Grid.Row="1" Margin="8,4,8,6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="1.4*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- MIC -->
<Border Grid.Column="0" Background="{StaticResource Brush.SurfaceContainerLow}" CornerRadius="{StaticResource Radius.Sm}" Margin="0,0,4,0" Padding="10,6">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Cursor="Hand" ToolTip="Change microphone" MouseLeftButtonUp="MicLabel_MouseLeftButtonUp">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource Brush.SurfaceContainerHighest}" CornerRadius="{StaticResource Radius.Sm}" Padding="5,1">
<TextBlock Text="MIC 1" FontSize="9" FontWeight="Bold" Foreground="{StaticResource Brush.OnSurfaceVariant}"/>
</Border>
<TextBlock Grid.Column="1" Margin="6,0,0,0" FontSize="11" VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" Text="{Binding MicSourceName, TargetNullValue='No microphone'}"
Foreground="{StaticResource Brush.OnSurface}"/>
</Grid>
<controls:SegmentMeter Grid.Row="1" Height="10" Margin="0,6,0,0" Orientation="Horizontal"
Level="{Binding MicMeterFraction}" Segments="24"/>
<DockPanel Grid.Row="2" Margin="0,6,0,0" VerticalAlignment="Bottom">
<Button DockPanel.Dock="Left" Width="24" Height="20" Margin="0,0,6,0"
Style="{StaticResource YtButtonSecondary}" Padding="0"
Command="{Binding ToggleMicMuteCommand}" ToolTip="{Binding MicMuteText}">
<Ellipse Width="9" Height="9" Fill="{Binding MicStatusBrush}"/>
</Button>
<TextBlock DockPanel.Dock="Right" Width="56" TextAlignment="Right" FontSize="10"
FontFamily="{StaticResource FontFamily.Mono}" VerticalAlignment="Center"
Foreground="{StaticResource Brush.OnSurfaceVariant}" Text="{Binding MicVolumeDbLabel}"/>
<Slider Minimum="-60" Maximum="6" SmallChange="0.5" LargeChange="3"
Value="{Binding MicVolumeDb, Mode=TwoWay}" VerticalAlignment="Center"/>
</DockPanel>
</Grid>
</Border>
<!-- GAME / PC, then TRAX beneath it: meter -> desktop volume -> TRAX line -->
<Border Grid.Column="1" Background="{StaticResource Brush.SurfaceContainerLow}" CornerRadius="{StaticResource Radius.Sm}" Margin="4,0" Padding="10,6">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource Brush.SurfaceContainerHighest}" CornerRadius="{StaticResource Radius.Sm}" Padding="5,1">
<TextBlock Text="GAME / PC" FontSize="9" FontWeight="Bold" Foreground="{StaticResource Brush.OnSurfaceVariant}"/>
</Border>
<TextBlock Grid.Column="1" Margin="6,0,0,0" FontSize="11" VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" Foreground="{StaticResource Brush.OnSurfaceVariant}"
Text="Desktop loopback · incl. TRAX"
ToolTip="Everything playing on the desktop — including TRAX, which rides the same device."/>
<Border Grid.Column="2" Background="{StaticResource Brush.SurfaceContainerHighest}"
CornerRadius="{StaticResource Radius.Sm}" Padding="5,1"
Visibility="{Binding IsGameDucking, Converter={StaticResource BoolToVis}}">
<TextBlock FontSize="9" FontWeight="Bold" FontFamily="{StaticResource FontFamily.Mono}"
Foreground="{StaticResource Brush.Secondary}" Text="{Binding GameDuckLabel}"/>
</Border>
</Grid>
<controls:SegmentMeter Grid.Row="1" Height="10" Margin="0,6,0,4" Orientation="Horizontal"
Level="{Binding GameMeterFraction}" Segments="24"/>
<!-- Desktop volume, directly beneath its meter. -->
<DockPanel Grid.Row="2" VerticalAlignment="Center">
<Button DockPanel.Dock="Left" Width="24" Height="20" Margin="0,0,6,0"
Style="{StaticResource YtButtonSecondary}" Padding="0"
Command="{Binding ToggleGameMuteCommand}" ToolTip="Mute desktop audio">
<Ellipse Width="9" Height="9" Fill="{Binding GameMeterBrush}"/>
</Button>
<TextBlock DockPanel.Dock="Right" Width="56" TextAlignment="Right" FontSize="10"
FontFamily="{StaticResource FontFamily.Mono}" VerticalAlignment="Center"
Foreground="{StaticResource Brush.OnSurfaceVariant}" Text="{Binding GameVolumeDbLabel}"/>
<Slider Minimum="-60" Maximum="6" SmallChange="0.5" LargeChange="3"
Value="{Binding GameVolumeDb, Mode=TwoWay}" VerticalAlignment="Center"/>
</DockPanel>
<!-- TRAX: background music — one number, two buttons. No meter: it is
background, and the desktop ladder already carries it. -->
<Border Grid.Row="3" Margin="0,4,0,0" Padding="6,3" CornerRadius="{StaticResource Radius.Sm}"
Background="{StaticResource Brush.SurfaceContainerLowest}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="TRAX" FontSize="9" FontWeight="Bold" VerticalAlignment="Center"
Foreground="{StaticResource Brush.OnSurfaceVariant}"/>
<TextBlock Grid.Column="1" Margin="6,0,0,0" FontSize="10" VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" Foreground="{StaticResource Brush.OnSurface}"
Text="{Binding TraxTrackLabel}" Cursor="Hand"
MouseLeftButtonUp="TraxLabel_MouseLeftButtonUp"
MouseRightButtonUp="TraxLabel_MouseRightButtonUp"/>
<Button Grid.Column="2" Width="20" Height="16" Margin="4,0,0,0" Padding="0"
Style="{StaticResource YtButtonSecondary}" Click="TraxPlayPause_Click"
ToolTip="{Binding TraxToolTip}">
<TextBlock FontSize="9" Foreground="{StaticResource Brush.OnSurface}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="▶"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsMusicPlaying}" Value="True">
<Setter Property="Text" Value="❚❚"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Button>
<StackPanel Grid.Column="3" Orientation="Horizontal" Margin="6,0,0,0" VerticalAlignment="Center">
<Button Content="−" Width="18" Height="16" Padding="0" FontSize="11"
Style="{StaticResource YtButtonSecondary}" Click="TraxStepDown_Click"
IsEnabled="{Binding CanLowerTrax}" ToolTip="5 dB quieter"/>
<TextBlock Width="52" TextAlignment="Center" FontSize="10" VerticalAlignment="Center"
FontFamily="{StaticResource FontFamily.Mono}"
Foreground="{StaticResource Brush.Tertiary}"
Text="{Binding TraxVolumeDbLabel}"/>
<Button Content="+" Width="18" Height="16" Padding="0" FontSize="11"
Style="{StaticResource YtButtonSecondary}" Click="TraxStepUp_Click"
IsEnabled="{Binding CanRaiseTrax}" ToolTip="5 dB louder"/>
</StackPanel>
</Grid>
</Border>
</Grid>
</Border>
<!-- LIP-SYNC -->
<Border Grid.Column="2" Background="{StaticResource Brush.SurfaceContainerLow}" CornerRadius="{StaticResource Radius.Sm}" Margin="4,0,0,0" Padding="10,6">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource Brush.SurfaceContainerHighest}" CornerRadius="{StaticResource Radius.Sm}" Padding="5,1">
<TextBlock Text="LIP-SYNC" FontSize="9" FontWeight="Bold" Foreground="{StaticResource Brush.OnSurfaceVariant}"/>
</Border>
<TextBlock Grid.Column="1" Margin="6,0,0,0" FontSize="10" VerticalAlignment="Center"
FontFamily="{StaticResource FontFamily.Mono}" TextAlignment="Right"
Foreground="{StaticResource Brush.Tertiary}" Text="{Binding SyncOffsetLabel}"/>
</Grid>
<StackPanel Grid.Row="1" VerticalAlignment="Bottom">
<Slider Minimum="-200" Maximum="200" SmallChange="5" LargeChange="25"
TickFrequency="5" IsSnapToTickEnabled="True"
Value="{Binding AudioSyncOffsetMs, Mode=TwoWay}" VerticalAlignment="Center"/>
<StackPanel Orientation="Horizontal" Margin="0,2,0,0" HorizontalAlignment="Right">
<Button Content="0" Width="26" Height="16" FontSize="9" Padding="0" Margin="0,0,4,0"
Style="{StaticResource YtButtonSecondary}" Click="SyncPreset_Click" Tag="0"/>
<Button Content="+50" Width="30" Height="16" FontSize="9" Padding="0" Margin="0,0,4,0"
Style="{StaticResource YtButtonSecondary}" Click="SyncPreset_Click" Tag="50"/>
<Button Content="+100" Width="34" Height="16" FontSize="9" Padding="0"
Style="{StaticResource YtButtonSecondary}" Click="SyncPreset_Click" Tag="100"/>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</Grid>
<!-- Master strip: always visible, even collapsed — it is the telemetry line. -->
<Border x:Name="MasterStrip" Grid.Row="0" Background="{StaticResource Brush.SurfaceContainerLowest}" Padding="12,0">
<DockPanel VerticalAlignment="Center">
<TextBlock DockPanel.Dock="Left" Text="MASTER" FontSize="10" FontWeight="SemiBold"
Foreground="{StaticResource Brush.OnSurfaceVariant}" VerticalAlignment="Center"/>
<!-- One ladder for the mix, plus the imbalance flag: two ladders would cost the
width that the telemetry needs, and the flag is the case that matters. -->
<controls:SegmentMeter DockPanel.Dock="Left" Width="120" Height="8" Margin="10,0,0,0"
Orientation="Horizontal" Segments="24"
Level="{Binding MasterMeterFraction}" VerticalAlignment="Center"/>
<TextBlock DockPanel.Dock="Left" Width="62" Margin="6,0,0,0" FontSize="10"
FontFamily="{StaticResource FontFamily.Mono}" VerticalAlignment="Center"
Foreground="{StaticResource Brush.OnSurfaceVariant}"
Text="{Binding MasterLevelLabel}"/>
<Border DockPanel.Dock="Left" Margin="6,0,0,0" Padding="5,1" VerticalAlignment="Center"
CornerRadius="{StaticResource Radius.Sm}" Background="{StaticResource Brush.SurfaceContainerHigh}"
Visibility="{Binding MasterImbalance, Converter={StaticResource BoolToVis}}"
ToolTip="Left and right differ by more than 6 dB — one side may be inaudible.">
<TextBlock Text="L/R" FontSize="9" FontWeight="Bold" FontFamily="{StaticResource FontFamily.Mono}"
Foreground="{StaticResource Brush.Attention}"/>
</Border>
<!-- MONO: the accessibility switch, one click, remembered. -->
<ToggleButton DockPanel.Dock="Left" Margin="10,0,0,0" Height="20" Padding="8,0"
Style="{StaticResource SegmentToggle}" IsChecked="{Binding MonoOutput, Mode=TwoWay}"
ToolTip="Fold the output to mono — both ears hear everything">
<TextBlock Text="MONO" FontSize="10" FontWeight="Bold"
Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType=ToggleButton}}"/>
</ToggleButton>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
<TextBlock FontSize="10" FontFamily="{StaticResource FontFamily.Mono}" Margin="0,0,12,0"
Foreground="{StaticResource Brush.OnSurfaceVariant}">
<Run Text="{Binding CurrentHealth.CurrentBitrate, StringFormat={}{0:0} kbps}"/>
</TextBlock>
<TextBlock FontSize="10" FontFamily="{StaticResource FontFamily.Mono}" Margin="0,0,12,0"
Foreground="{StaticResource Brush.OnSurfaceVariant}">
<Run Text="{Binding CurrentHealth.FPS, StringFormat={}{0:0} fps}"/>
</TextBlock>
<TextBlock FontSize="10" FontFamily="{StaticResource FontFamily.Mono}" Margin="0,0,12,0"
Foreground="{StaticResource Brush.OnSurfaceVariant}">
<Run Text="drop "/><Run Text="{Binding CurrentHealth.DroppedFrames}"/>
</TextBlock>
<TextBlock FontSize="10" FontFamily="{StaticResource FontFamily.Mono}"
Foreground="{StaticResource Brush.OnSurfaceVariant}"
Text="{Binding CurrentHealth.StreamDuration, StringFormat={}{0:hh\:mm\:ss}}"/>
</StackPanel>
</DockPanel>
</Border>
</Grid>
</Border>
</UserControl>
+93
View File
@@ -0,0 +1,93 @@
using System.Windows;
using System.Windows.Controls;
using ytLive.Models;
namespace ytLive.Controls;
/// <summary>The sound bars (creator ruling 2026-10-30). This unit owns the SHELL: the piece of the
/// window it occupies and the collapse behaviour. The bays and the master readouts fill in over
/// the following units, so nothing here pretends to be a working meter.
///
/// <para>Collapse is driven by the window height, not a user setting: at 1366×768 a full dock
/// squeezes the preview, and the creator should not have to manage that.</para></summary>
public partial class AudioDock : UserControl
{
private Window? _window;
public AudioDock()
{
InitializeComponent();
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
/// <summary>Is the dock showing only the telemetry strip?</summary>
internal bool IsCollapsed { get; private set; }
/// <summary>Test seam: the same code the window's SizeChanged runs, without a window.</summary>
internal void ApplyWindowHeight(double windowHeight)
{
var collapsed = AudioDockLayout.IsCollapsed(windowHeight);
IsCollapsed = collapsed;
Height = AudioDockLayout.HeightFor(windowHeight);
Bays.Visibility = collapsed ? Visibility.Collapsed : Visibility.Visible;
}
private void MicLabel_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm && vm.OpenMicPickerCommand.CanExecute(null))
vm.OpenMicPickerCommand.Execute(null);
}
private void TraxStepDown_Click(object sender, RoutedEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm) vm.StepTrax(-1);
}
private void TraxStepUp_Click(object sender, RoutedEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm) vm.StepTrax(+1);
}
private void SyncPreset_Click(object sender, RoutedEventArgs e)
{
if (DataContext is not ViewModels.MainViewModel vm) return;
if (sender is Button { Tag: string tag } && int.TryParse(tag, out var ms))
vm.SetSyncOffset(ms);
}
private void TraxPlayPause_Click(object sender, RoutedEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm) vm.TraxLeftClick();
}
private void TraxLabel_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm) vm.TraxLeftClick();
}
private void TraxLabel_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm) vm.ChooseTrack();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
_window = Window.GetWindow(this);
if (_window == null)
{
ApplyWindowHeight(AudioDockLayout.CollapseBelowHeight); // no host: show the dock
return;
}
_window.SizeChanged += OnWindowSizeChanged;
ApplyWindowHeight(_window.ActualHeight > 0 ? _window.ActualHeight : _window.Height);
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
if (_window != null) _window.SizeChanged -= OnWindowSizeChanged;
_window = null;
}
private void OnWindowSizeChanged(object sender, SizeChangedEventArgs e) => ApplyWindowHeight(e.NewSize.Height);
}
-10
View File
@@ -1,10 +0,0 @@
<UserControl x:Class="ytLive.Controls.BottomBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Border Background="#0f3460" Padding="16,4">
<Grid>
<!-- Intentionally empty. The hidden label keeps the bar's height unchanged. -->
<TextBlock Style="{StaticResource YtLabel}" Text=" " Visibility="Hidden"/>
</Grid>
</Border>
</UserControl>
-11
View File
@@ -1,11 +0,0 @@
using System.Windows.Controls;
namespace ytLive.Controls;
public partial class BottomBar : UserControl
{
public BottomBar()
{
InitializeComponent();
}
}
+3 -158
View File
@@ -963,164 +963,9 @@
</StackPanel> </StackPanel>
</Grid> </Grid>
<!-- ═══ LIVE CONTROLS (below preview, never overlaps) ═══ <!-- LIVE CONTROLS moved to the audio dock (2026-10-30): the mic row, the game
Line 1: Socials + TRAX meter (desktop/game audio) chip, TRAX and the sync slider all live there now. One audio surface. -->
Line 2: Mic meter + volume -->
<StackPanel Grid.Row="2" Orientation="Vertical" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="0,4">
<!-- Line 1: Socials + TRAX -->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,0,0,4">
<!-- TRAX meter -->
<Border Background="{StaticResource Brush.ScrimDarkStrong}" CornerRadius="6" Padding="12,8">
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource YtButtonSecondary}" Padding="8,2"
FontSize="11" VerticalAlignment="Center" Margin="0,0,8,0"
ToolTipService.ToolTip="{Binding TraxToolTip}"
ToolTipService.Placement="Top"
Click="TraxButton_Click"
PreviewMouseRightButtonUp="TraxButton_PreviewMouseRightButtonUp">
<StackPanel Orientation="Horizontal">
<Ellipse Width="8" Height="8" Fill="{Binding TraxDotBrush}"
Margin="0,0,6,0" VerticalAlignment="Center"/>
<TextBlock Text="TRAX"/>
</StackPanel>
</Button>
<TextBlock Text="Desktop Audio" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"
FontWeight="SemiBold" VerticalAlignment="Center" Margin="0,0,8,0"
ToolTip="Desktop/game audio via WASAPI loopback (automatic); TRAX music rides the same channel"/>
<Border Width="288" Height="14" CornerRadius="7" Background="{StaticResource Brush.SurfaceContainerHighest}" Margin="0,0,8,0"
ClipToBounds="True" VerticalAlignment="Center">
<Grid>
<Rectangle Width="57" Fill="{StaticResource Brush.SecondaryContainer}" HorizontalAlignment="Left" Margin="173,0,0,0"
VerticalAlignment="Stretch"/>
<Rectangle Width="58" Fill="{StaticResource Brush.ErrorContainer}" HorizontalAlignment="Left" Margin="230,0,0,0"
VerticalAlignment="Stretch"/>
<Border HorizontalAlignment="Left" Width="{Binding GameMeterFillWidth}"
Background="{Binding GameMeterBrush}" Opacity="0.75"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="36,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="72,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="108,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="144,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="180,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="216,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="252,0,0,0"/>
<Rectangle Width="2" Fill="{StaticResource Brush.ScrimDarkStrong}" HorizontalAlignment="Left" Margin="173,0,0,0"
VerticalAlignment="Stretch"/>
<Rectangle Width="2" Fill="{StaticResource Brush.ScrimDarkStrong}" HorizontalAlignment="Left" Margin="230,0,0,0"
VerticalAlignment="Stretch"/>
<!-- TRAX error: a terse message that scrolls across the bar
(marquee) while the TRAX dot is red. -->
<Canvas x:Name="TraxErrorMarquee" ClipToBounds="True"
Visibility="{Binding TraxError, Converter={StaticResource NotNullToVis}}">
<TextBlock x:Name="TraxErrorText" Text="{Binding TraxError}" Foreground="{StaticResource Brush.Error}" FontSize="10"
FontWeight="SemiBold" Canvas.Top="0">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="TraxErrorScroll"/>
</TextBlock.RenderTransform>
<TextBlock.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard>
<Storyboard RepeatBehavior="Forever">
<DoubleAnimation Storyboard.TargetName="TraxErrorScroll"
Storyboard.TargetProperty="X"
From="288" To="-220" Duration="0:0:7"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</TextBlock.Triggers>
</TextBlock>
</Canvas>
</Grid>
</Border>
<Grid Width="16" Height="16" Cursor="Hand" Margin="0,0,8,0"
VerticalAlignment="Center" ToolTip="{Binding GameMuteText}"
MouseLeftButtonUp="GameSpeaker_MouseLeftButtonUp">
<Path Fill="{StaticResource Brush.OnSurface}" Stretch="Uniform"
Data="M3,9v6h4l5,5V4L7,9H3zM16.5,12c0,-1.77 -1,-3.29 -2.5,-4.03v8.05c1.5,-0.73 2.5,-2.25 2.5,-4.02zM14,3.23v2.06c2.89,0.86 5,3.54 5,6.71s-2.11,5.85 -5,6.71v2.06c4.01,-0.91 7,-4.49 7,-8.77s-2.99,-7.86 -7,-8.77z"
Visibility="{Binding GameMuted, Converter={StaticResource InverseBoolToVis}}"/>
<Path Fill="{StaticResource Brush.Error}" Stretch="Uniform"
Data="M3,9v6h4l5,5V4L7,9H3zM16.5,12c0,-1.77 -1,-3.29 -2.5,-4.03v8.05c1.5,-0.73 2.5,-2.25 2.5,-4.02zM14,3.23v2.06c2.89,0.86 5,3.54 5,6.71s-2.11,5.85 -5,6.71v2.06c4.01,-0.91 7,-4.49 7,-8.77s-2.99,-7.86 -7,-8.77z"
Visibility="{Binding GameMuted, Converter={StaticResource BoolToVis}}"/>
<Path Stroke="{StaticResource Brush.Error}" StrokeThickness="2.5" StrokeEndLineCap="Round" Stretch="Uniform"
Data="M21,3 L3,21"
Visibility="{Binding GameMuted, Converter={StaticResource BoolToVis}}"/>
</Grid>
<Slider Width="130" Minimum="0" Maximum="1"
Value="{Binding GameAudioVolume, Mode=TwoWay}" VerticalAlignment="Center"
PreviewMouseLeftButtonDown="GameVolumeSlider_PreviewMouseLeftButtonDown"
PreviewMouseLeftButtonUp="GameVolumeSlider_PreviewMouseLeftButtonUp"
LostMouseCapture="GameVolumeSlider_LostMouseCapture"/>
</StackPanel>
</Border>
</StackPanel>
<!-- Line 2: Mic meter + volume -->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Command="{Binding OpenMicPickerCommand}"
Style="{StaticResource YtButtonSecondary}" Padding="12,4"
FontSize="11" VerticalAlignment="Center" Margin="0,0,8,0"
ToolTip="{Binding MicStatusToolTip}">
<StackPanel Orientation="Horizontal">
<Ellipse Width="8" Height="8" Fill="{Binding MicStatusBrush}"
Margin="0,0,6,0" VerticalAlignment="Center"/>
<TextBlock Text="MIC"/>
</StackPanel>
</Button>
<Border Width="288" Height="14" CornerRadius="7" Background="{StaticResource Brush.SurfaceContainerHighest}" Margin="0,0,8,0"
ClipToBounds="True" VerticalAlignment="Center">
<Grid>
<Rectangle Width="57" Fill="{StaticResource Brush.SecondaryContainer}" HorizontalAlignment="Left" Margin="173,0,0,0"
VerticalAlignment="Stretch"/>
<Rectangle Width="58" Fill="{StaticResource Brush.ErrorContainer}" HorizontalAlignment="Left" Margin="230,0,0,0"
VerticalAlignment="Stretch"/>
<TextBlock Text="{Binding MicSourceName}" Foreground="{StaticResource Brush.OnSurface}" FontSize="10"
VerticalAlignment="Center" Margin="6,0,0,0" MaxWidth="270"
TextTrimming="CharacterEllipsis"
Visibility="{Binding MicSourceName, Converter={StaticResource NotNullToVis}}"/>
<Border HorizontalAlignment="Left" Width="{Binding MeterFillWidth}"
Background="{Binding MeterBrush}" Opacity="0.75"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="36,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="72,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="108,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="144,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="180,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="216,0,0,0"/>
<Rectangle Width="1" Height="10" Fill="{StaticResource Brush.ScrimDark}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="252,0,0,0"/>
<Rectangle Width="2" Fill="{StaticResource Brush.ScrimDarkStrong}" HorizontalAlignment="Left" Margin="173,0,0,0"
VerticalAlignment="Stretch"/>
<Rectangle Width="2" Fill="{StaticResource Brush.ScrimDarkStrong}" HorizontalAlignment="Left" Margin="230,0,0,0"
VerticalAlignment="Stretch"/>
</Grid>
</Border>
<Grid Width="16" Height="16" Cursor="Hand" Margin="0,0,8,0"
VerticalAlignment="Center" ToolTip="{Binding MicMuteText}"
MouseLeftButtonUp="MicSpeaker_MouseLeftButtonUp">
<Path Fill="{StaticResource Brush.OnSurface}" Stretch="Uniform"
Data="M12,14c1.66,0 3,-1.34 3,-3V5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6C9,12.66 10.34,14 12,14zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11H5c0,3.41 2.72,6.23 6,6.72V21h2v-3.28c3.28,-0.49 6,-3.31 6,-6.72H17.3z"
Visibility="{Binding MicMuted, Converter={StaticResource InverseBoolToVis}}"/>
<Path Fill="{StaticResource Brush.Error}" Stretch="Uniform"
Data="M12,14c1.66,0 3,-1.34 3,-3V5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6C9,12.66 10.34,14 12,14zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11H5c0,3.41 2.72,6.23 6,6.72V21h2v-3.28c3.28,-0.49 6,-3.31 6,-6.72H17.3z"
Visibility="{Binding MicMuted, Converter={StaticResource BoolToVis}}"/>
<Path Stroke="{StaticResource Brush.Error}" StrokeThickness="2.5" StrokeEndLineCap="Round" Stretch="Uniform"
Data="M21,3 L3,21"
Visibility="{Binding MicMuted, Converter={StaticResource BoolToVis}}"/>
</Grid>
<Slider Width="130" Minimum="0" Maximum="1"
Value="{Binding MicVolume, Mode=TwoWay}" VerticalAlignment="Center"
PreviewMouseLeftButtonDown="VolumeSlider_PreviewMouseLeftButtonDown"
PreviewMouseLeftButtonUp="VolumeSlider_PreviewMouseLeftButtonUp"
LostMouseCapture="VolumeSlider_LostMouseCapture"/>
<StackPanel Orientation="Horizontal" Margin="10,0,0,0" VerticalAlignment="Center"
ToolTip="Audio sync (−500..+500 ms). Positive: delays the audio when it runs ahead of the video. Negative: advances it (drops the first |N| ms of the recording) when it runs behind. Calibrate with a clap: is the clap late in the video, move negative; early, move positive.">
<TextBlock Text="AUDIO SYNC" FontSize="9" Foreground="{StaticResource Brush.OnSurfaceVariant}"
VerticalAlignment="Center" Margin="0,0,5,0"/>
<Slider Width="70" Minimum="-500" Maximum="500"
Value="{Binding AudioSyncOffsetMs, Mode=TwoWay}"
IsEnabled="{Binding IsEditMode}"
VerticalAlignment="Center"
ToolTip="{Binding AudioSyncOffsetMs, StringFormat=Audio sync: {0} ms}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid> </Grid>
</Border> </Border>
</UserControl> </UserControl>
-18
View File
@@ -208,13 +208,6 @@ public partial class PreviewPane : UserControl
return null; return null;
} }
private void MicSpeaker_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (sender is FrameworkElement { DataContext: MainViewModel vm })
{
vm.ToggleMicMuteCommand.Execute(null);
}
}
private void GameSpeaker_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) private void GameSpeaker_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
@@ -227,18 +220,7 @@ public partial class PreviewPane : UserControl
// TRAX (TASK 9): left-click toggles play/pause (picks a track when none is // TRAX (TASK 9): left-click toggles play/pause (picks a track when none is
// loaded); right-click always opens the picker. The picker is the OS file // loaded); right-click always opens the picker. The picker is the OS file
// dialog — the "never the OS viewer" rule covers the preview, not pickers. // dialog — the "never the OS viewer" rule covers the preview, not pickers.
private void TraxButton_Click(object sender, RoutedEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm)
vm.TraxLeftClick();
}
private void TraxButton_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
if (DataContext is ViewModels.MainViewModel vm)
vm.TraxRightClick();
e.Handled = true; // the button's right-click context menu must not fire
}
// ─── Webcam / background context menus (right-click on overlay elements) ─── // ─── Webcam / background context menus (right-click on overlay elements) ───
private void WebcamMenu_ChangeWebcam(object sender, RoutedEventArgs e) private void WebcamMenu_ChangeWebcam(object sender, RoutedEventArgs e)
+105
View File
@@ -0,0 +1,105 @@
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using ytLive.Helpers;
namespace ytLive.Controls;
/// <summary>A segmented level ladder for the audio dock.
///
/// <para>Drawn in ONE <see cref="OnRender"/> pass. Twenty-four <c>Rectangle</c>s per meter would
/// mean hundreds of elements updating on the UI thread; a single drawing call does not. The
/// consumer updates <see cref="Level"/> at ~20 Hz — music-level smoothness is not needed and the
/// paint cost should never compete with the compositor.</para>
///
/// <para>Level is a 0…1 display fraction (see <see cref="MeterScale"/>), never a gain setting: the
/// ladder shows what was measured.</para></summary>
public sealed class SegmentMeter : FrameworkElement
{
public static readonly DependencyProperty LevelProperty = DependencyProperty.Register(
nameof(Level), typeof(double), typeof(SegmentMeter),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.AffectsRender));
/// <summary>Peak-hold mark, 0…1. Falls back slowly so a clip stays visible long enough to see.</summary>
public static readonly DependencyProperty PeakProperty = DependencyProperty.Register(
nameof(Peak), typeof(double), typeof(SegmentMeter),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty SegmentsProperty = DependencyProperty.Register(
nameof(Segments), typeof(int), typeof(SegmentMeter),
new FrameworkPropertyMetadata(24, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register(
nameof(Orientation), typeof(Orientation), typeof(SegmentMeter),
new FrameworkPropertyMetadata(Orientation.Vertical, FrameworkPropertyMetadataOptions.AffectsRender));
public double Level { get => (double)GetValue(LevelProperty); set => SetValue(LevelProperty, value); }
public double Peak { get => (double)GetValue(PeakProperty); set => SetValue(PeakProperty, value); }
public int Segments { get => (int)GetValue(SegmentsProperty); set => SetValue(SegmentsProperty, value); }
public Orientation Orientation { get => (Orientation)GetValue(OrientationProperty); set => SetValue(OrientationProperty, value); }
public SegmentMeter()
{
// Token-driven, not literal: the ladder cannot drift from DESIGN.md.
SetResourceReference(NominalBrushProperty, "Brush.Meter.Nominal");
SetResourceReference(CautionBrushProperty, "Brush.Meter.Caution");
SetResourceReference(PeakBrushProperty, "Brush.Meter.Peak");
SetResourceReference(DimBrushProperty, "Brush.SurfaceContainerHighest");
}
private static readonly DependencyProperty NominalBrushProperty = DependencyProperty.Register(
"NominalBrush", typeof(Brush), typeof(SegmentMeter), new FrameworkPropertyMetadata(Brushes.Cyan, FrameworkPropertyMetadataOptions.AffectsRender));
private static readonly DependencyProperty CautionBrushProperty = DependencyProperty.Register(
"CautionBrush", typeof(Brush), typeof(SegmentMeter), new FrameworkPropertyMetadata(Brushes.Orange, FrameworkPropertyMetadataOptions.AffectsRender));
private static readonly DependencyProperty PeakBrushProperty = DependencyProperty.Register(
"PeakBrush", typeof(Brush), typeof(SegmentMeter), new FrameworkPropertyMetadata(Brushes.Red, FrameworkPropertyMetadataOptions.AffectsRender));
private static readonly DependencyProperty DimBrushProperty = DependencyProperty.Register(
"DimBrush", typeof(Brush), typeof(SegmentMeter), new FrameworkPropertyMetadata(Brushes.DimGray, FrameworkPropertyMetadataOptions.AffectsRender));
private Brush NominalBrush => (Brush)GetValue(NominalBrushProperty);
private Brush CautionBrush => (Brush)GetValue(CautionBrushProperty);
private Brush PeakBrush => (Brush)GetValue(PeakBrushProperty);
private Brush DimBrush => (Brush)GetValue(DimBrushProperty);
private const double Gap = 2;
protected override void OnRender(DrawingContext dc)
{
var count = Math.Max(1, Segments);
var vertical = Orientation == Orientation.Vertical;
var extent = vertical ? ActualHeight : ActualWidth;
var thickness = vertical ? ActualWidth : ActualHeight;
if (extent <= 0 || thickness <= 0) return;
var segmentSize = (extent - Gap * (count - 1)) / count;
if (segmentSize <= 0) return;
var lit = Math.Clamp(Level, 0, 1) * count;
for (var i = 0; i < count; i++)
{
// Segment 0 sits at the bottom (vertical) or the left (horizontal).
var fraction = (i + 1) / (double)count;
var brush = fraction >= MeterScale.ToFraction(MeterScale.PeakDb) ? PeakBrush
: fraction >= MeterScale.ToFraction(MeterScale.CautionDb) ? CautionBrush
: NominalBrush;
if (i >= lit) brush = DimBrush;
var offset = i * (segmentSize + Gap);
var rect = vertical
? new Rect(0, extent - offset - segmentSize, thickness, segmentSize)
: new Rect(offset, 0, segmentSize, thickness);
dc.DrawRectangle(brush, null, rect);
}
// Peak-hold: a 2px marker at the held level, drawn above the ladder.
var peak = Math.Clamp(Peak, 0, 1);
if (peak <= 0) return;
var line = vertical
? new Rect(0, extent - peak * extent - 1, thickness, 2)
: new Rect(peak * extent - 1, 0, 2, thickness);
dc.DrawRectangle(PeakBrush, null, line);
}
}
+17 -17
View File
@@ -1,26 +1,26 @@
# HANDOFF — 2026-10-30 (design conversion complete; spacing is a layout pass, not a sweep) # HANDOFF — 2026-10-30 (audio dock shipped; needs an eyes/hands pass)
## State ## State
- Branch `main`, worktree clean. **~20 commits, unpushed** (push at your checkpoint). - Branch `main`, worktree clean. Ten dock units landed on top of the design conversion; nothing
- **The design conversion is done**: `DESIGN.md` is the contract, `Themes/Tokens.xaml` implements pushed since `1724922` — this batch is local.
it, and every surface consumes it — UI chrome, all dialogs (typeface included), the VM's state - **The sound bars exist**: `Controls/AudioDock` — master strip on top (nearest the preview), four
colours via `Helpers/ThemeBrush`, and the on-stream graphics via `Services/Compositor/OutputPalette` bays below (MIC / GAME / TRAX / LIP-SYNC), 148px, auto-collapsing to 36px below a 900px window
(which mirrors the tokens and is checked against them, because the pump thread cannot read app height. The dock is now the ONLY audio surface; the preview's mic row, game chip, TRAX button and
resources). Blue `#38bdf8` is the only interactive accent; red `#ff5451` is live/record; sync slider are deleted.
`#e94560` is gone from the product. - Faders speak dB (`Helpers/GainDb`, 0 dB = unity). Ladders are measured (`SegmentMeter` +
- Four guards hold it: `DesignTokensTests` (doc ↔ brushes; converted files may not regress to a `MeterScale`), never decorative. The duck badge prints the gain the mixer applied.
literal), `ThemeResourceTests` (no dangling `StaticResource` — the class of crash that killed the - **MONO output** (creator ruling): folds the finished mix to both channels, persisted as
app on a slider), `OutputPaletteTests` (on-stream ↔ theme), `SocialsPreviewTests` (a real `Audio.MonoOutput`, one click in the master strip. Exists because single-sided audio is inaudible
MainWindow, real preview elements) and `DialogTypographyTests` (dialogs inherit Inter). with profound right-side deafness, not merely unbalanced.
- Deliberately absent: L/R ladders (one ladder + an imbalance flag instead), TRAX scrub/prev-next
(OBS territory), CPU/GPU/NVENC readouts, acrylic.
## Next action ## Next action
Nothing queued for the design. The **one** item deliberately not swept: the spacing scale. Margins Nothing queued. **Needs the creator's hands**: launch and judge the dock at the real window size —
and paddings are per-side `Thickness`, not the single values `DESIGN.md` defines, so converting bay proportions at 148px, the master strip's ladder/label density, and whether the MONO fold sounds
them mechanically would change layout without a rationale — that is a layout pass (a designer's right through their own ears/headphones (the one thing no test can answer).
job), not a colour-style sweep. Radii are tokenised where a token was honest; component geometry
(pill halves, 2.5px hairlines) stays literal on purpose.
## Landmines ## Landmines
+27
View File
@@ -0,0 +1,27 @@
using System;
namespace ytLive.Helpers;
/// <summary>The accessible mono fold: average each stereo pair into both channels.
///
/// <para>Creator context (2026-10-30): profoundly deaf on the right. Hard-panned content is not
/// quieter to them, it is ABSENT, so a single-sided game or clip is unusable. Folding to mono puts
/// everything on both sides — the loudness cost is honest (a one-sided signal arrives at half
/// amplitude) and speech is unaffected because the mic is already centred.</para></summary>
public static class AudioFold
{
/// <summary>Folds an interleaved buffer in place. Mono buffers are left untouched: there is
/// nothing to combine, and rewriting them would be a silent no-op that hides a caller's bug.</summary>
public static void ToMono(Span<float> interleaved, int channels)
{
if (channels < 2) return;
var frames = interleaved.Length / channels;
for (var frame = 0; frame < frames; frame++)
{
var offset = frame * channels;
var mono = (interleaved[offset] + interleaved[offset + 1]) * 0.5f;
interleaved[offset] = mono;
interleaved[offset + 1] = mono;
}
}
}
+44
View File
@@ -0,0 +1,44 @@
using System;
namespace ytLive.Helpers;
/// <summary>The fader scale for the audio dock: the model stores LINEAR gain (0..1), the dock
/// shows and edits DECIBELS, because "−6 dB" means something to a person and "0.50" does not.
///
/// <para>Range: −∞ (silence) to +6 dB of headroom above unity. 0 dB is unity gain, which is what
/// the old 1.0 meant — so a persisted 0.8 comes back as ≈ −1.9 dB and nothing about the stored
/// data changes.</para>
///
/// <para>Creator context (2026-10-30): nearly deaf on the right, so the fader number is read, not
/// heard. The scale therefore has to be the true one, not a cosmetic curve.</para></summary>
public static class GainDb
{
/// <summary>Silence floor. Anything at or below this reads as −∞ and writes as 0 gain.</summary>
public const double FloorDb = -60;
public const double MaxDb = 6;
/// <summary>Linear gain → dB, clamped to the fader's range. Zero becomes <see cref="FloorDb"/>.</summary>
public static double ToDb(double gain)
{
if (gain <= 0) return FloorDb;
var db = 20 * Math.Log10(gain);
return Math.Clamp(db, FloorDb, MaxDb);
}
/// <summary>dB → linear gain. At the floor the result is exactly 0 (true silence), so the
/// bottom of the fader cannot leave a residue of noise.</summary>
public static double FromDb(double db)
{
if (db <= FloorDb) return 0;
return Math.Pow(10, Math.Clamp(db, FloorDb, MaxDb) / 20);
}
/// <summary>"−∞", "−6.0", "+1.5" — the label beside a fader.</summary>
public static string Label(double db) =>
db <= FloorDb ? "−∞" : (db > 0 ? "+" : string.Empty) + db.ToString("0.0");
/// <summary>Mono fold: the accessible downmix. Averages the pair so hard-panned content is
/// audible on both sides at half amplitude instead of absent from one.</summary>
public static float MonoFold(float left, float right) => (left + right) * 0.5f;
}
+68
View File
@@ -0,0 +1,68 @@
using System;
namespace ytLive.Helpers;
/// <summary>Which colour band a level falls in (DESIGN.md meter thresholds).</summary>
public enum MeterBand
{
Nominal,
Caution,
Peak,
}
/// <summary>The mathematics of the dock's segment meter, kept out of the control so it can be
/// tested: a segment ladder is only honest if the band it paints is the level it measured.
///
/// <para>Bands follow DESIGN.md: nominal to −12 dB, caution to −3 dB, peak above. The display
/// fraction spreads −60…0 dBFS across 0…1 — the same scale <c>AudioLevelMeter.ToDisplay</c> uses,
/// so the ladder and the old bars cannot disagree.</para></summary>
public static class MeterScale
{
public const float FloorDb = -60f;
public const float CautionDb = -12f;
public const float PeakDb = -3f;
/// <summary>dBFS → 0…1 across the whole ladder.</summary>
public static float ToFraction(float dbfs)
=> Math.Clamp(1f + Math.Clamp(dbfs, FloorDb, 0f) / 60f, 0f, 1f);
/// <summary>The band boundaries are INCLUSIVE at the bottom edge (a meter reading exactly
/// −12.0 dB is cautious, exactly −3.0 is peaking), matching the ranges as DESIGN.md states
/// them: "−12 … −3" and "−3 … 0+".</summary>
public static MeterBand BandFor(float dbfs)
=> dbfs >= PeakDb ? MeterBand.Peak
: dbfs >= CautionDb ? MeterBand.Caution
: MeterBand.Nominal;
/// <summary>The master ladder when no session is running.
///
/// <para>`AudioMixer.MasterLevel` measures the buffer the encoder receives, and that buffer only
/// exists while the mix is being pulled (streaming or recording). Idle, the master would read
/// zero while the source ladders move — so the monitor level is computed from the same measured
/// sources and the same gains the mix applies. It is an estimate of the mix, not a substitute
/// for it: once a session starts, the real measured value takes over.</para></summary>
public static float MonitorFraction(float micLevel, double micGain, float gameLevel, double gameGain)
{
var linear = Math.Max(0f, (float)(micLevel * micGain) + (float)(gameLevel * gameGain));
if (linear <= 0.001f) return 0f;
return ToFraction(20f * MathF.Log10(linear));
}
/// <summary>Ballistics for a level: reach a new peak quickly, fall back gently. Raw per-block
/// peaks sampled by a UI timer look like a stutter; this is what makes the mic feel fluid, and
/// TRAX gets the same curve so the two ladders move alike.</summary>
public static float NextLevel(float current, float incoming, float attack = 0.6f, float decay = 0.12f)
{
var alpha = incoming > current ? attack : decay;
return current + (incoming - current) * alpha;
}
/// <summary>Peak hold: jumps up instantly to a new maximum and falls back at
/// <paramref name="decayPerSecond"/> — a moment-to-moment bar hides clipping, which is the one
/// audio fault that cannot be fixed afterwards.</summary>
public static float NextPeak(float held, float incoming, float seconds, float decayPerSecond = 0.35f)
{
if (incoming >= held) return incoming;
return Math.Max(0f, held - decayPerSecond * Math.Max(0f, seconds));
}
}
+8 -2
View File
@@ -75,6 +75,9 @@
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/>
<RowDefinition Height="*"/> <RowDefinition Height="*"/>
<!-- the dock lives INSIDE the work area so its bottom edge lines up with the
layers panel (creator, 2026-10-30) -->
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="360"/> <ColumnDefinition Width="360"/>
@@ -140,15 +143,18 @@
<!-- LEFT PANEL: one panel, two states. <!-- LEFT PANEL: one panel, two states.
Offline (edit mode): LAYERS + PROPERTIES Offline (edit mode): LAYERS + PROPERTIES
Live/Recording: YouTube Live Chat --> Live/Recording: YouTube Live Chat -->
<controls:LeftPanel x:Name="LeftPanel" Grid.Row="1" Grid.Column="0"/> <controls:LeftPanel x:Name="LeftPanel" Grid.Row="1" Grid.Column="0" Grid.RowSpan="2"/>
<!-- CENTER: Preview Area --> <!-- CENTER: Preview Area -->
<controls:PreviewPane x:Name="PreviewPane" Grid.Row="1" Grid.Column="1"/> <controls:PreviewPane x:Name="PreviewPane" Grid.Row="1" Grid.Column="1"/>
<!-- The dock starts where the layers panel ends and shares its bottom edge. -->
<controls:AudioDock x:Name="AudioDock" Grid.Row="2" Grid.Column="1"/>
</Grid> </Grid>
<controls:BottomBar Grid.Row="3"/>
<!-- ═══ OVERLAY: Settings / Bug / Feature / About ═══ --> <!-- ═══ OVERLAY: Settings / Bug / Feature / About ═══ -->
<controls:OverlayHost Grid.RowSpan="3"/> <controls:OverlayHost Grid.RowSpan="3"/>
+25
View File
@@ -0,0 +1,25 @@
namespace ytLive.Models;
/// <summary>How tall the audio dock should be for a given window height.
///
/// <para>Creator ruling (2026-10-30): the dock is 148px on a normal window and collapses to a 36px
/// telemetry strip when the window is short, because at 1366×768 a full dock leaves ~398px for the
/// preview and the composition starts letterboxing into a postage stamp.</para>
///
/// <para>Pure, so the switch is testable without a window.</para></summary>
public static class AudioDockLayout
{
/// <summary>Below this window height the dock collapses. The app's minimum is 768; the
/// default window is 1040, so a normal launch shows the full dock.</summary>
public const double CollapseBelowHeight = 900;
/// <summary>148 = 112 of bays + the 36px master strip. The mockup wanted 168; the creator
/// read that as wasted space under a 154px scene strip, so the bays lost 20px of air.</summary>
public const double ExpandedHeight = 148;
public const double CollapsedHeight = 36;
public static bool IsCollapsed(double windowHeight) => windowHeight < CollapseBelowHeight;
public static double HeightFor(double windowHeight)
=> IsCollapsed(windowHeight) ? CollapsedHeight : ExpandedHeight;
}
+74 -1
View File
@@ -11,9 +11,39 @@ public sealed class AudioLevelMeter
private const float Smoothing = 0.2f; private const float Smoothing = 0.2f;
private const float DecaySmoothing = 0.5f; private const float DecaySmoothing = 0.5f;
private float _level; private float _level;
private float _left;
private float _right;
public float Level => _level; public float Level => _level;
/// <summary>Per-channel levels, smoothed with the same attack/decay as <see cref="Level"/>.
/// A mono sample reports the same value on both sides (a mono source is centred), so the two
/// never disagree about whether audio exists.
///
/// <para>Why they exist: the dock shows ONE ladder per source, but a creator who is deaf on
/// one side needs to know when content is panned away from it. The imbalance flag is computed
/// from these, not from a second ladder.</para></summary>
public float Left => _left;
public float Right => _right;
/// <summary>How far apart the channels are, in dB. 0 only when BOTH are silent.
///
/// <para>A side that carries nothing is compared at the −60 dBFS floor, so a fully one-sided
/// signal reads as a large imbalance (≈54 dB) rather than "nothing to compare" — one-sided is
/// the maximum imbalance, not the absence of one. That distinction is the whole point for a
/// creator who cannot hear the missing side.</para></summary>
public float ImbalanceDb
{
get
{
const float floor = 0.001f; // −60 dBFS
if (_left < floor && _right < floor) return 0f;
var l = MathF.Max(_left, floor);
var r = MathF.Max(_right, floor);
return MathF.Abs(20f * MathF.Log10(l / r));
}
}
/// <summary> /// <summary>
/// Maps a linear level (0..1) onto the meter's display scale: -60 dBFS..0 dBFS /// Maps a linear level (0..1) onto the meter's display scale: -60 dBFS..0 dBFS
/// spread linearly across 0..1 — an HONEST dBFS scale. Linear RMS of real speech is /// spread linearly across 0..1 — an HONEST dBFS scale. Linear RMS of real speech is
@@ -49,8 +79,51 @@ public sealed class AudioLevelMeter
var rms = (float)Math.Sqrt(sumSquares / count); var rms = (float)Math.Sqrt(sumSquares / count);
var alpha = rms > _level ? Smoothing : DecaySmoothing; var alpha = rms > _level ? Smoothing : DecaySmoothing;
_level = _level * (1 - alpha) + rms * alpha; _level = _level * (1 - alpha) + rms * alpha;
MeasureChannels(sample);
return _level; return _level;
} }
public void Reset() => _level = 0; private void MeasureChannels(AudioSample sample)
{
double leftSquares = 0, rightSquares = 0;
int frames;
if (sample.Channels <= 1)
{
// Mono is centred: one number, both sides.
for (var i = 0; i < sample.Samples.Length; i++) leftSquares += sample.Samples[i] * sample.Samples[i];
frames = Math.Max(1, sample.Samples.Length);
rightSquares = leftSquares;
}
else
{
frames = Math.Max(1, sample.Samples.Length / sample.Channels);
for (var frame = 0; frame < frames; frame++)
{
var l = sample.Samples[frame * sample.Channels];
var r = sample.Samples[frame * sample.Channels + 1];
leftSquares += l * l;
rightSquares += r * r;
}
}
var left = (float)Math.Sqrt(leftSquares / frames);
var right = (float)Math.Sqrt(rightSquares / frames);
_left = Smooth(_left, left);
_right = Smooth(_right, right);
static float Smooth(float current, float incoming)
{
var a = incoming > current ? Smoothing : DecaySmoothing;
return current * (1 - a) + incoming * a;
}
}
public void Reset()
{
_level = 0;
_left = 0;
_right = 0;
}
} }
+51
View File
@@ -44,6 +44,36 @@ public sealed class AudioMixer : IDisposable
private readonly AudioRingBuffer _alertBuffer; private readonly AudioRingBuffer _alertBuffer;
private readonly VoiceFilterChain _voiceChain; private readonly VoiceFilterChain _voiceChain;
private readonly AutoDucker _ducker; private readonly AutoDucker _ducker;
/// <summary>The ducker's CURRENT gain (1 = not ducking, 0.25 = the −12 dB duck). Read by the
/// dock's badge: a duck indicator that is not the real value is decoration.</summary>
public float DuckGain => _ducker.CurrentGain;
/// <summary>Collapse the final mix to mono (creator ruling 2026-10-30: profoundly deaf on the
/// right, single-sided audio is inaudible). Applied AFTER the limiter and sync delay, so what
/// ships to the encoder — stream and recording alike — is what was folded.</summary>
public bool MonoOutput { get; set; }
/// <summary>Smoothed levels of the MIX (what the encoder receives), per channel.</summary>
public float MasterLeft { get; private set; }
public float MasterRight { get; private set; }
/// <summary>Largest channel level — one ladder for the master, honest about the pair.</summary>
public float MasterLevel => MathF.Max(MasterLeft, MasterRight);
/// <summary>Channel gap in dB; a silent side counts at the −60 dBFS floor, so one-sided reads
/// as the maximum imbalance rather than "nothing to compare".</summary>
public float MasterImbalanceDb
{
get
{
const float floor = 0.001f;
if (MasterLeft < floor && MasterRight < floor) return 0f;
var l = MathF.Max(MasterLeft, floor);
var r = MathF.Max(MasterRight, floor);
return MathF.Abs(20f * MathF.Log10(l / r));
}
}
private readonly MasterLimiter _masterLimiter = new(); private readonly MasterLimiter _masterLimiter = new();
private TinyResampler? _micResampler; private TinyResampler? _micResampler;
private TinyResampler? _loopbackResampler; private TinyResampler? _loopbackResampler;
@@ -476,6 +506,27 @@ public sealed class AudioMixer : IDisposable
delayed = _delayedMix = new float[mix.Length]; delayed = _delayedMix = new float[mix.Length];
_syncDelay.Process(mix, delayed); _syncDelay.Process(mix, delayed);
Array.Copy(delayed, mix, mix.Length); Array.Copy(delayed, mix, mix.Length);
if (MonoOutput) Helpers.AudioFold.ToMono(mix.AsSpan(0, mix.Length), 2);
MeasureMaster(mix);
return (micRms, micCount, loopCount); return (micRms, micCount, loopCount);
} }
/// <summary>One pass over the finished mix: 1024 samples per channel, so the cost is noise
/// beside the mixer it sits behind.</summary>
private void MeasureMaster(float[] mix)
{
double left = 0, right = 0;
var frames = mix.Length / 2;
if (frames == 0) return;
for (var i = 0; i < frames; i++)
{
left += mix[i * 2] * mix[i * 2];
right += mix[i * 2 + 1] * mix[i * 2 + 1];
}
var l = (float)Math.Sqrt(left / frames);
var r = (float)Math.Sqrt(right / frames);
MasterLeft = MasterLeft * 0.8f + l * 0.2f;
MasterRight = MasterRight * 0.8f + r * 0.2f;
}
} }
+8
View File
@@ -7,7 +7,15 @@ public interface ITraxPlayer : IDisposable
event Action<Exception?>? PlaybackEnded; event Action<Exception?>? PlaybackEnded;
string? TrackName { get; } string? TrackName { get; }
bool IsPlaying { get; } bool IsPlaying { get; }
/// <summary>The player's OWN measured output level (0…1). A play glyph can lie — an open file
/// with a dead decoder still says "playing" — so the dock's TRAX ladder shows sound, not state.</summary>
float Level { get; }
float LocalGain { get; set; } float LocalGain { get; set; }
/// <summary>The creator's TRAX level (1 = the bed's fixed design level). Separate from
/// <see cref="LocalGain"/>, which follows the desktop mute; the dock's fader moves this.</summary>
float UserGain { get; set; }
void Load(string path); void Load(string path);
void Play(); void Play();
void Pause(); void Pause();
+46 -4
View File
@@ -1,5 +1,7 @@
using System.IO; using System.IO;
using System.Linq;
using NAudio.Wave; using NAudio.Wave;
using NAudio.Wave.SampleProviders;
namespace ytLive.Services.Audio; namespace ytLive.Services.Audio;
@@ -23,6 +25,17 @@ public sealed class MusicPlayer : ITraxPlayer
/// ~−15..−20 LUFS — beside the leveled voice (≈ −17 LUFS), and well under it when ducked.</para></summary> /// ~−15..−20 LUFS — beside the leveled voice (≈ −17 LUFS), and well under it when ducked.</para></summary>
public const float MusicVolume = 0.5f; public const float MusicVolume = 0.5f;
/// <summary>+6 dB of headroom on the bed, matching the dock's fader range.</summary>
public const float MaxUserGain = 2f;
/// <summary>The effective multiplier for a (user, local) pair, computed in ONE place.
///
/// <para>The fader used to set the OUTPUT DEVICE's volume, which NAudio's WaveOut ignores, while
/// the mute-follow rewrote the sample-chain volume without the user gain — so pegging the fader
/// changed nothing and then lost the setting at the next duck.</para></summary>
public static float EffectiveVolume(float userGain, float localGain)
=> MusicVolume * Math.Clamp(userGain, 0f, MaxUserGain) * Math.Clamp(localGain, 0f, 1f);
private MediaFoundationReader? _reader; private MediaFoundationReader? _reader;
private VolumeWaveProvider16? _volume; private VolumeWaveProvider16? _volume;
private WaveOutEvent? _output; private WaveOutEvent? _output;
@@ -39,19 +52,44 @@ public sealed class MusicPlayer : ITraxPlayer
public bool IsPlaying => _output?.PlaybackState == PlaybackState.Playing; public bool IsPlaying => _output?.PlaybackState == PlaybackState.Playing;
/// <summary>Measured peak of what the player is actually sending to the device.</summary>
public float Level { get; private set; }
private MeteringSampleProvider? _metering;
/// <summary>Local gain multiplier from the desktop/game audio bar (0 = mute, /// <summary>Local gain multiplier from the desktop/game audio bar (0 = mute,
/// 1 = full bed). Applied live on top of the fixed <see cref="MusicVolume"/>.</summary> /// 1 = full bed). Applied live on top of the fixed <see cref="MusicVolume"/>.</summary>
private float _userGain = 1f;
/// <summary>Creator-set level, multiplied onto the fixed design volume.</summary>
public float UserGain
{
get => _userGain;
set
{
_userGain = Math.Clamp(value, 0f, MaxUserGain);
ApplyVolume();
}
}
public float LocalGain public float LocalGain
{ {
get => _localGain; get => _localGain;
set set
{ {
_localGain = Math.Clamp(value, 0f, 1f); _localGain = Math.Clamp(value, 0f, 1f);
if (_volume != null) ApplyVolume();
_volume.Volume = MusicVolume * _localGain;
} }
} }
/// <summary>Pushes the current gains onto the sample chain. The meter sits AFTER this stage, so
/// the ladder follows the fader — that is the point of both controls being on the same bay.</summary>
private void ApplyVolume()
{
if (_volume != null)
_volume.Volume = EffectiveVolume(_userGain, _localGain);
}
/// <summary>Loads a track and prepares playback (does not start it).</summary> /// <summary>Loads a track and prepares playback (does not start it).</summary>
public void Load(string path) public void Load(string path)
{ {
@@ -61,10 +99,14 @@ public sealed class MusicPlayer : ITraxPlayer
Stop(); Stop();
TrackPath = path; TrackPath = path;
_reader = new MediaFoundationReader(path); _reader = new MediaFoundationReader(path);
_volume = new VolumeWaveProvider16(_reader) { Volume = MusicVolume * _localGain }; _volume = new VolumeWaveProvider16(_reader) { Volume = EffectiveVolume(_userGain, _localGain) };
_metering = new MeteringSampleProvider(_volume.ToSampleProvider());
_metering.StreamVolume += (_, e) =>
Level = Helpers.MeterScale.NextLevel(Level,
e.MaxSampleValues.Length == 0 ? 0f : e.MaxSampleValues.Max());
_output = new WaveOutEvent(); _output = new WaveOutEvent();
_output.PlaybackStopped += OnPlaybackStopped; _output.PlaybackStopped += OnPlaybackStopped;
_output.Init(_volume); _output.Init(_metering);
} }
public void Play() public void Play()
+7
View File
@@ -44,6 +44,13 @@ public partial class LayoutStore : IDisposable
UpsertSetting("Audio.SyncOffsetMs", Math.Clamp(ms, -500, 500).ToString()); UpsertSetting("Audio.SyncOffsetMs", Math.Clamp(ms, -500, 500).ToString());
} }
/// <summary>Mono output (creator ruling 2026-10-30): folds the mix so single-sided audio is
/// audible on both sides. Restored at startup — an accessibility switch that resets is a
/// failure, not a default.</summary>
public bool LoadMonoOutput() => GetSetting("Audio.MonoOutput") == "1";
public void SaveMonoOutput(bool enabled) => UpsertSetting("Audio.MonoOutput", enabled ? "1" : "0");
/// <summary>The user's chosen record output folder (TASK 18), or null to use the /// <summary>The user's chosen record output folder (TASK 18), or null to use the
/// default <c>%APPDATA%\ytLlive\recordings</c>. Restored at startup.</summary> /// default <c>%APPDATA%\ytLlive\recordings</c>. Restored at startup.</summary>
public string? LoadRecordFolder() public string? LoadRecordFolder()
+160 -1
View File
@@ -13,6 +13,49 @@ namespace ytLive.ViewModels;
public partial class MainViewModel public partial class MainViewModel
{ {
private readonly DispatcherTimer _meterTimer;
private int _traxSilentTicks;
private bool _traxSilenceLogged;
/// <summary>The dock's heartbeat: every meter readout is refreshed here, 20 times a second,
/// from whatever the audio threads last measured.</summary>
private void TickMeters()
{
OnPropertyChanged(nameof(MicMeterFraction));
OnPropertyChanged(nameof(MeterFillWidth));
OnPropertyChanged(nameof(MeterBrush));
OnPropertyChanged(nameof(GameMeterFraction));
OnPropertyChanged(nameof(GameMeterFillWidth));
OnPropertyChanged(nameof(GameMeterBrush));
OnPropertyChanged(nameof(TraxMeterFraction));
RaiseMasterReadouts();
UpdateDuckState();
CheckTraxSilence();
}
/// <summary>One honest diagnostic: "playing" with a flat player meter means the samples never
/// reached the device (or the metering was not attached). Logged once per playback, so the next
/// run says which side is broken instead of another round of guessing.</summary>
private void CheckTraxSilence()
{
if (!IsMusicPlaying)
{
_traxSilentTicks = 0;
_traxSilenceLogged = false;
return;
}
if (_musicPlayer.Level > 0f)
{
_traxSilentTicks = 0;
_traxSilenceLogged = false;
return;
}
if (++_traxSilentTicks < 40 || _traxSilenceLogged) return; // 2s at 20 Hz
_traxSilenceLogged = true;
AppLog.Write("TRAX: playing but the player meter reads 0 — the output device is silent or " +
"the metering stream is not attached (the dock's ladder has nothing to show)");
}
private readonly DispatcherTimer _volumeFlashTimer; private readonly DispatcherTimer _volumeFlashTimer;
private readonly DispatcherTimer _gameVolumeFlashTimer; private readonly DispatcherTimer _gameVolumeFlashTimer;
private double _audioLevel; private double _audioLevel;
@@ -53,6 +96,13 @@ public partial class MainViewModel
{ {
OnPropertyChanged(nameof(MeterFillWidth)); OnPropertyChanged(nameof(MeterFillWidth));
OnPropertyChanged(nameof(MeterBrush)); OnPropertyChanged(nameof(MeterBrush));
OnPropertyChanged(nameof(MicMeterFraction));
UpdateDuckState();
RaiseMasterReadouts();
OnPropertyChanged(nameof(TraxMeterFraction));
OnPropertyChanged(nameof(MicMeterFraction));
OnPropertyChanged(nameof(MicVolumeDb));
OnPropertyChanged(nameof(MicVolumeDbLabel));
} }
} }
} }
@@ -141,6 +191,29 @@ public partial class MainViewModel
} }
} }
/// <summary>The fader's face, in dB (−60 … +6, 0 = unity). The model keeps linear gain; this is
/// the same value expressed the way a person reads a mixer — and the only thing the dock binds.
/// </summary>
public double MicVolumeDb
{
get => Helpers.GainDb.ToDb(MicVolume);
set
{
var gain = Helpers.GainDb.FromDb(value);
if (Math.Abs(gain - MicVolume) < 1e-6) return;
MicVolume = gain;
OnPropertyChanged(nameof(MicVolumeDb));
OnPropertyChanged(nameof(MicVolumeDbLabel));
}
}
/// <summary>"-6.0 dB" beside the fader; "−∞ dB" at the floor.</summary>
public string MicVolumeDbLabel => Helpers.GainDb.Label(MicVolumeDb) + " dB";
/// <summary>The ladder's input: a 0…1 display fraction of what was MEASURED (already scaled by
/// the volume and muted state), never the gain setting.</summary>
public double MicMeterFraction => MeterLevel;
/// <summary>Read-only: true whenever the volume is 0. Only MicVolume may /// <summary>Read-only: true whenever the volume is 0. Only MicVolume may
/// change it, so the slider and the speaker can never disagree.</summary> /// change it, so the slider and the speaker can never disagree.</summary>
public bool MicMuted => _micMuted; public bool MicMuted => _micMuted;
@@ -166,11 +239,60 @@ public partial class MainViewModel
set set
{ {
var clamped = Math.Clamp(value, -500, 500); var clamped = Math.Clamp(value, -500, 500);
if (SetProperty(ref _audioSyncOffsetMs, clamped)) if (!SetProperty(ref _audioSyncOffsetMs, clamped)) return;
OnPropertyChanged(nameof(SyncOffsetLabel));
ScheduleSave(); ScheduleSave();
} }
} }
// ─── Master strip ────────────────────────────────────────────────────────
private bool _monoOutput;
/// <summary>Collapse the output to mono. Persisted, because a creator who needs it needs it on
/// every session — an accessibility switch that resets is an accessibility failure.</summary>
public bool MonoOutput
{
get => _monoOutput;
set
{
if (!SetProperty(ref _monoOutput, value)) return;
_audioMixer.MonoOutput = value;
_layoutStore.SaveMonoOutput(value);
}
}
/// <summary>Master ladder input: the MEASURED mix while a session runs (that is the buffer the
/// encoder receives), and an estimate from the measured sources when idle — otherwise the master
/// sits at zero between sessions while every bay below it moves.</summary>
public double MasterMeterFraction =>
IsLive || IsRecording
? AudioLevelMeter.ToDisplay(_audioMixer.MasterLevel)
: Helpers.MeterScale.MonitorFraction((float)AudioLevel, MicVolume,
(float)GameAudioLevel, GameAudioVolume);
public string MasterLevelLabel => Helpers.GainDb.Label(Helpers.GainDb.ToDb(_audioMixer.MasterLevel)) + " dB";
/// <summary>True when the mix's channels differ by more than 6 dB — the one thing L/R is
/// genuinely good for, shown as one flag instead of two ladders.</summary>
public bool MasterImbalance => _audioMixer.MasterImbalanceDb > 6f;
private void RaiseMasterReadouts()
{
OnPropertyChanged(nameof(MasterMeterFraction));
OnPropertyChanged(nameof(MasterLevelLabel));
OnPropertyChanged(nameof(MasterImbalance));
}
/// <summary>"0 ms (aligned)", "+50 ms", "−120 ms" — what the dock shows beside the slider.</summary>
public string SyncOffsetLabel => AudioSyncOffsetMs == 0
? "0 ms (aligned)"
: (AudioSyncOffsetMs > 0 ? "+" : "−") + Math.Abs(AudioSyncOffsetMs) + " ms";
/// <summary>Preset buttons in the LIP-SYNC bay. 0 is the detent: the offset that means "the
/// lip-sync is right", so it deserves one click, not a drag.</summary>
internal void SetSyncOffset(int milliseconds) => AudioSyncOffsetMs = milliseconds;
private void ToggleMicMute() private void ToggleMicMute()
{ {
if (MicMuted) if (MicMuted)
@@ -281,6 +403,32 @@ public partial class MainViewModel
public double GameMeterFillWidth => GameMeterLevel * 288; public double GameMeterFillWidth => GameMeterLevel * 288;
/// <summary>Ladder input: a 0…1 display fraction of what was measured.</summary>
public double GameMeterFraction => GameMeterLevel;
/// <summary>The game fader's dB face (−60 … +6). Same rule as the mic: the model keeps linear
/// gain; the dock shows decibels.</summary>
public double GameVolumeDb
{
get => Helpers.GainDb.ToDb(GameAudioVolume);
set
{
var gain = Helpers.GainDb.FromDb(value);
if (Math.Abs(gain - GameAudioVolume) < 1e-6) return;
GameAudioVolume = gain;
OnPropertyChanged(nameof(GameVolumeDb));
OnPropertyChanged(nameof(GameVolumeDbLabel));
}
}
public string GameVolumeDbLabel => Helpers.GainDb.Label(GameVolumeDb) + " dB";
/// <summary>True while the mic is ducking the game/desktop bed (the mixer's own value).</summary>
public bool IsGameDucking { get; private set; }
/// <summary>"−12.0 dB" — the badge text, computed from the same gain the mixer applied.</summary>
public string GameDuckLabel => Helpers.GainDb.Label(Helpers.GainDb.ToDb(_audioMixer.DuckGain)) + " DUCK";
public string GameMeterBrush => GameMeterLevel switch public string GameMeterBrush => GameMeterLevel switch
{ {
< 0.6 => ThemeBrush.Hex("Brush.Meter.Nominal"), < 0.6 => ThemeBrush.Hex("Brush.Meter.Nominal"),
@@ -360,6 +508,17 @@ public partial class MainViewModel
public string GameMuteText => GameMuted ? "Unmute" : "Mute"; public string GameMuteText => GameMuted ? "Unmute" : "Mute";
/// <summary>Badge state follows the mix, not a timer of its own: the level tick is already the
/// moment the ducker has just run.</summary>
private void UpdateDuckState()
{
var ducking = _audioMixer.DuckGain < 0.99f;
if (ducking == IsGameDucking) return;
IsGameDucking = ducking;
OnPropertyChanged(nameof(IsGameDucking));
OnPropertyChanged(nameof(GameDuckLabel));
}
private void ToggleGameMute() private void ToggleGameMute()
{ {
if (GameMuted) if (GameMuted)
+46
View File
@@ -63,6 +63,49 @@ public partial class MainViewModel
? BarOnBrush ? BarOnBrush
: TraxError != null ? BarOffBrush : TraxIdleBrush; : TraxError != null ? BarOffBrush : TraxIdleBrush;
/// <summary>Where TRAX starts: quiet background under the desktop bed. The ±5 dB buttons are the
/// control surface — a creator who wants it louder clicks up three times rather than hunting a
/// 6px thumb on a 148px dock. (Creator ruling 2026-10-30, from their own meter readings.)</summary>
public const double TraxDefaultDb = -50;
public const double TraxStepDb = 5;
/// <summary>+6 dB is the ceiling; −60 dB is silence. The buttons disable at both ends.</summary>
public bool CanRaiseTrax => TraxVolumeDb < Helpers.GainDb.MaxDb;
public bool CanLowerTrax => TraxVolumeDb > Helpers.GainDb.FloorDb;
public void StepTrax(int steps) => TraxVolumeDb += steps * TraxStepDb;
/// <summary>The dock's TRAX level, in dB. Unity means the bed's design level, not the raw file.</summary>
public double TraxVolumeDb
{
get => Helpers.GainDb.ToDb(_musicPlayer.UserGain);
set
{
var gain = Helpers.GainDb.FromDb(value);
if (Math.Abs(gain - _musicPlayer.UserGain) < 1e-6) return;
_musicPlayer.UserGain = (float)gain;
OnPropertyChanged(nameof(TraxVolumeDb));
OnPropertyChanged(nameof(TraxVolumeDbLabel));
OnPropertyChanged(nameof(CanRaiseTrax));
OnPropertyChanged(nameof(CanLowerTrax));
}
}
public string TraxVolumeDbLabel => Helpers.GainDb.Label(TraxVolumeDb) + " dB";
/// <summary>The TRAX ladder: the player's own measured output, so "is music actually making
/// sound" is answerable without hearing it.</summary>
public double TraxMeterFraction =>
IsMusicPlaying ? Services.Audio.AudioLevelMeter.ToDisplay(_musicPlayer.Level) : 0;
/// <summary>Track name, or an honest "No track".</summary>
public string TraxTrackLabel => _musicPlayer.TrackName ?? "No track";
/// <summary>Same ducker signal as the game bay — the bed ducks with it.</summary>
public bool IsTraxDucking => IsGameDucking;
public string TraxToolTip => _musicPlayer.TrackName != null public string TraxToolTip => _musicPlayer.TrackName != null
? $"TRAX: {_musicPlayer.TrackName} — left-click {(IsMusicPlaying ? "pauses" : "plays")}, right-click chooses a track" ? $"TRAX: {_musicPlayer.TrackName} — left-click {(IsMusicPlaying ? "pauses" : "plays")}, right-click chooses a track"
: "No track — left-click or right-click to choose background music"; : "No track — left-click or right-click to choose background music";
@@ -81,6 +124,9 @@ public partial class MainViewModel
/// <summary>Right-click on TRAX: always open the track picker (never the OS viewer).</summary> /// <summary>Right-click on TRAX: always open the track picker (never the OS viewer).</summary>
public void TraxRightClick() => PickTraxTrack(); public void TraxRightClick() => PickTraxTrack();
/// <summary>Open the track picker (the dock's right-click on the TRAX name).</summary>
internal void ChooseTrack() => PickTraxTrack();
private void PickTraxTrack() private void PickTraxTrack()
{ {
var dialog = new OpenFileDialog var dialog = new OpenFileDialog
+9
View File
@@ -178,6 +178,13 @@ public partial class MainViewModel : ViewModelBase
_gameVolumeFlashTimer.Tick += (_, _) => EndGameVolumeFlash(); _gameVolumeFlashTimer.Tick += (_, _) => EndGameVolumeFlash();
_saveDebounce = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1500) }; _saveDebounce = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1500) };
// Dock meters beat on their own ~30 Hz clock instead of riding the mic's level callback.
// Coupling them to capture was a bug: with a silent or absent mic the ladder never
// refreshed, so a playing TRAX showed nothing (creator, 2026-10-30).
_meterTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(33) };
_meterTimer.Tick += (_, _) => TickMeters();
_meterTimer.Start();
_saveDebounce.Tick += (_, _) => SaveLayoutNow(); _saveDebounce.Tick += (_, _) => SaveLayoutNow();
_brandFlash = new BrandFlashPresenter(); _brandFlash = new BrandFlashPresenter();
@@ -269,6 +276,8 @@ public partial class MainViewModel : ViewModelBase
// (yellow) instead of silently falling back to the default. // (yellow) instead of silently falling back to the default.
MicSourceName = _layoutStore.LoadMicSourceName(); MicSourceName = _layoutStore.LoadMicSourceName();
AudioSyncOffsetMs = _layoutStore.LoadAudioSyncOffsetMs(); AudioSyncOffsetMs = _layoutStore.LoadAudioSyncOffsetMs();
MonoOutput = _layoutStore.LoadMonoOutput(); // applied to the mixer by the setter
_musicPlayer.UserGain = (float)Helpers.GainDb.FromDb(TraxDefaultDb); // background by default
try try
{ {
var s = _layoutStore.GetSetting("ZoomShape"); var s = _layoutStore.GetSetting("ZoomShape");
+32
View File
@@ -0,0 +1,32 @@
using Xunit;
using ytLive.Models;
namespace ytLive.Tests;
/// <summary>The dock's height is the whole reason it is allowed to take 168px: on a short window it
/// must get out of the way instead of squeezing the preview. The threshold is the creator's
/// minimum (768) and default (1040) — both sides are pinned here so a future "tidy" cannot leave a
/// 768px window with a full dock.
/// </summary>
public class AudioDockLayoutTests
{
[Fact]
public void The_dock_collapses_on_short_windows_and_expands_on_normal_ones()
{
// Minimum window: collapsed, so the preview keeps its room.
Assert.True(AudioDockLayout.IsCollapsed(768));
Assert.Equal(AudioDockLayout.CollapsedHeight, AudioDockLayout.HeightFor(768));
// Default window: the full dock.
Assert.False(AudioDockLayout.IsCollapsed(1040));
Assert.Equal(AudioDockLayout.ExpandedHeight, AudioDockLayout.HeightFor(1040));
// The boundary itself belongs to the expanded side (>= is the friendlier read).
Assert.False(AudioDockLayout.IsCollapsed(AudioDockLayout.CollapseBelowHeight));
Assert.True(AudioDockLayout.IsCollapsed(AudioDockLayout.CollapseBelowHeight - 1));
// The two heights are the design's numbers, not whatever looked fine.
Assert.Equal(148, AudioDockLayout.ExpandedHeight); // 112 bays + 36 strip
Assert.Equal(36, AudioDockLayout.CollapsedHeight);
}
}
+35
View File
@@ -0,0 +1,35 @@
using Xunit;
using ytLive.Helpers;
namespace ytLive.Tests;
/// <summary>The mono output exists because single-sided audio is inaudible to this creator, not
/// merely unbalanced. The fold has to move content to BOTH sides — a "fold" that keeps a channel
/// empty would leave the exact problem in place — and it must not touch mono buffers.</summary>
public class AudioFoldTests
{
[Fact]
public void Folding_to_mono_puts_a_one_sided_signal_on_both_sides()
{
// Hard LEFT content becomes audible on the right at half amplitude.
var left = new[] { 0.5f, 0f, 0.5f, 0f };
AudioFold.ToMono(left, 2);
Assert.Equal(new[] { 0.25f, 0.25f, 0.25f, 0.25f }, left);
// Hard RIGHT — the inaudible case — becomes audible on the left.
var right = new[] { 0f, 0.6f };
AudioFold.ToMono(right, 2);
Assert.Equal(0.3f, right[0], 4);
Assert.Equal(0.3f, right[1], 4);
// Centred material keeps its level (the mic case): no quietening.
var centred = new[] { 0.4f, 0.4f };
AudioFold.ToMono(centred, 2);
Assert.Equal(0.4f, centred[0], 4);
// Mono buffers are untouched — folding is about pairs.
var mono = new[] { 0.7f, 0.2f };
AudioFold.ToMono(mono, 1);
Assert.Equal(new[] { 0.7f, 0.2f }, mono);
}
}
+43
View File
@@ -0,0 +1,43 @@
using Xunit;
using ytLive.Helpers;
namespace ytLive.Tests;
/// <summary>The dock's faders speak dB while the model stores linear gain, so the mapping is load
/// bearing: get it wrong and every reported level is wrong by a constant. Unity, the floor and
/// the +6 dB ceiling are the three values a creator actually checks.</summary>
public class GainDbTests
{
[Fact]
public void Db_and_linear_gain_round_trip_and_the_ends_are_honest()
{
// Unity is the anchor: 1.0 ↔ 0 dB, and the default mic volume reads −1.9 dB.
Assert.Equal(0, GainDb.ToDb(1.0), 6);
Assert.Equal(1.0, GainDb.FromDb(0), 6);
Assert.Equal(-1.9, GainDb.ToDb(0.8), 1);
// Halving is −6 dB — the number a creator reads as "half".
Assert.Equal(-6.02, GainDb.ToDb(0.5), 1);
// The floor is TRUE silence: no residue left at the bottom of the fader.
Assert.Equal(0.0, GainDb.FromDb(GainDb.FloorDb));
Assert.Equal(0.0, GainDb.FromDb(-999));
// Ceiling: +6 dB is twice the amplitude and nothing beyond it.
Assert.Equal(2.0, GainDb.FromDb(6), 2);
Assert.Equal(6, GainDb.ToDb(GainDb.FromDb(99)), 6);
// Round-trip across the usable range.
foreach (var db in new[] { -60.0, -40, -20, -12, -6, -3, 0, 3, 6 })
Assert.Equal(db, GainDb.ToDb(GainDb.FromDb(db)), 6);
// Labels are what the creator reads.
Assert.Equal("−∞", GainDb.Label(GainDb.FloorDb));
Assert.Equal("-6.0", GainDb.Label(-6));
Assert.Equal("+1.5", GainDb.Label(1.5));
// The mono fold: a hard-right signal becomes audible on the left at half amplitude.
Assert.Equal(0.25f, GainDb.MonoFold(0f, 0.5f));
Assert.Equal(0.5f, GainDb.MonoFold(0.5f, 0.5f));
}
}
+37
View File
@@ -0,0 +1,37 @@
using Xunit;
using ytLive.Helpers;
using ytLive.Services.Audio;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>The GAME bay's badge must carry the gain the mixer actually applied — a duck indicator
/// that is not the real value is decoration, and this creator cannot hear whether it happened.
/// </summary>
public class GameBayTests
{
[Fact]
public void The_game_bay_binds_the_db_fader_and_a_real_duck_readout()
{
var dock = SourceAssert.Text("Controls", "AudioDock.xaml");
Assert.Contains("Value=\"{Binding GameVolumeDb, Mode=TwoWay}\"", dock);
// Desktop volume sits directly beneath its meter (creator's layout ruling).
var desktopMeter = dock.IndexOf("Level=\"{Binding GameMeterFraction}\"", System.StringComparison.Ordinal);
var desktopFader = dock.IndexOf("Value=\"{Binding GameVolumeDb, Mode=TwoWay}\"", System.StringComparison.Ordinal);
Assert.True(desktopFader > desktopMeter, "the desktop fader belongs under the desktop ladder");
Assert.Contains("Level=\"{Binding GameMeterFraction}\"", dock);
Assert.Contains("Text=\"{Binding GameDuckLabel}\"", dock);
Assert.Contains("Visibility=\"{Binding IsGameDucking, Converter={StaticResource BoolToVis}}\"", dock);
foreach (var name in new[] { "GameVolumeDb", "GameVolumeDbLabel", "GameMeterFraction", "IsGameDucking", "GameDuckLabel" })
Assert.NotNull(typeof(MainViewModel).GetProperty(name));
// The badge's number is the mixer's ducker, not a copy: the duck is −12.04 dB by design,
// and the label is produced from the live gain through the same dB scale as the faders.
Assert.Equal(-12.04, GainDb.ToDb(AutoDucker.DuckGain), 1);
Assert.Equal("-12.0 DUCK", GainDb.Label(GainDb.ToDb(AutoDucker.DuckGain)) + " DUCK");
// And the mixer exposes that gain rather than hiding it.
Assert.NotNull(typeof(AudioMixer).GetProperty("DuckGain"));
}
}
+41
View File
@@ -0,0 +1,41 @@
using Xunit;
using ytLive.Helpers;
using ytLive.Services.Audio;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>The master strip is where the accessibility switch lives, so its wiring matters more
/// than its looks: MONO must reach the mixer, be remembered across sessions, and the strip's ladder
/// must show the MEASURED mix — with one L/R flag instead of two ladders.
/// </summary>
public class MasterStripTests
{
[Fact]
public void The_master_strip_shows_the_measured_mix_and_the_mono_switch_is_persisted()
{
var dock = SourceAssert.Text("Controls", "AudioDock.xaml");
Assert.Contains("IsChecked=\"{Binding MonoOutput, Mode=TwoWay}\"", dock);
Assert.Contains("Level=\"{Binding MasterMeterFraction}\"", dock);
Assert.Contains("Text=\"{Binding MasterLevelLabel}\"", dock);
Assert.Contains("Visibility=\"{Binding MasterImbalance, Converter={StaticResource BoolToVis}}\"", dock);
// One ladder on the master, not a pair.
Assert.Equal(1, System.Text.RegularExpressions.Regex.Matches(
dock[dock.IndexOf("MASTER", System.StringComparison.Ordinal)..], "SegmentMeter").Count);
// The switch reaches the mixer and the store.
Assert.NotNull(typeof(AudioMixer).GetProperty("MonoOutput"));
Assert.NotNull(typeof(MainViewModel).GetProperty("MonoOutput"));
var settings = SourceAssert.Text("Services", "LayoutStore.Settings.cs");
Assert.Contains("Audio.MonoOutput", settings);
Assert.Contains("LoadMonoOutput", settings);
// The mixer measures the finished mix, so the ladder cannot show a source instead of the output.
Assert.NotNull(typeof(AudioMixer).GetProperty("MasterLevel"));
Assert.NotNull(typeof(AudioMixer).GetProperty("MasterImbalanceDb"));
// And the fold is the tested helper, not new arithmetic in the mixer.
Assert.Contains("AudioFold.ToMono", SourceAssert.Text("Services", "Audio", "AudioMixer.cs"));
Assert.Equal(0.25f, GainDb.MonoFold(0.5f, 0f));
}
}
+49
View File
@@ -0,0 +1,49 @@
using Xunit;
using ytLive.Helpers;
namespace ytLive.Tests;
/// <summary>A segment ladder is only useful if the band it paints is the level it measured. The
/// thresholds are DESIGN.md's (nominal / caution / peak), and peak-hold is what makes clipping
/// visible — a bar that follows the moment hides the one audio fault that cannot be fixed later.
/// </summary>
public class MeterScaleTests
{
[Fact]
public void Bands_peak_hold_and_the_display_scale_follow_the_standard()
{
// Bands at the documented thresholds.
Assert.Equal(MeterBand.Nominal, MeterScale.BandFor(-30f));
Assert.Equal(MeterBand.Nominal, MeterScale.BandFor(-12.1f));
Assert.Equal(MeterBand.Caution, MeterScale.BandFor(-12f));
Assert.Equal(MeterBand.Caution, MeterScale.BandFor(-6f));
Assert.Equal(MeterBand.Peak, MeterScale.BandFor(-3f));
Assert.Equal(MeterBand.Peak, MeterScale.BandFor(0f));
// Display fraction: −60 dBFS is empty, 0 dBFS is full, −30 is halfway, and nothing escapes.
Assert.Equal(0f, MeterScale.ToFraction(-60f));
Assert.Equal(1f, MeterScale.ToFraction(0f));
Assert.Equal(0.5f, MeterScale.ToFraction(-30f), 4);
Assert.Equal(1f, MeterScale.ToFraction(+12f));
Assert.Equal(0f, MeterScale.ToFraction(-120f));
// Level ballistics: a jump is followed quickly, a drop falls gently — the same curve that
// makes the mic meter look fluid. Raw peaks at a 30 Hz UI tick stutter without it.
Assert.Equal(0.6f, MeterScale.NextLevel(0f, 1f), 3); // attack
Assert.True(MeterScale.NextLevel(0.9f, 0.1f) > 0.8f); // decay is gentle
Assert.True(MeterScale.NextLevel(0.1f, 0.9f) > 0.5f); // rise is fast
// The idle master estimate: sources × their gains, on the same display scale. With nothing
// playing it is zero; a quiet source at unity is visible; two sources add.
Assert.Equal(0f, MeterScale.MonitorFraction(0f, 1, 0f, 1));
Assert.True(MeterScale.MonitorFraction(0.05f, 1, 0f, 1) > 0.3f);
Assert.True(MeterScale.MonitorFraction(0.05f, 1, 0.05f, 1) > MeterScale.MonitorFraction(0.05f, 1, 0f, 1));
// Gain is applied in the LINEAR domain, like the mix does — not to the display fraction.
Assert.True(MeterScale.MonitorFraction(0.05f, 0.5, 0f, 1) < MeterScale.MonitorFraction(0.05f, 1, 0f, 1));
// Peak hold rises instantly, then decays at the stated rate.
Assert.Equal(0.8f, MeterScale.NextPeak(0.2f, 0.8f, 0.05f));
Assert.Equal(0.7f, MeterScale.NextPeak(0.8f, 0.1f, 0.1f / 0.35f), 3); // 0.1 fall at 0.35/s
Assert.Equal(0f, MeterScale.NextPeak(0.1f, 0f, 10f)); // never negative
}
}
+37
View File
@@ -0,0 +1,37 @@
using System.Linq;
using Xunit;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>The MIC bay is the first bay with real controls, and it is the creator's only audio
/// control — so its wiring deserves a guard that costs nothing to run.
///
/// <para>The fader speaks dB while the model stores linear gain (that mapping is covered by
/// GainDbTests); what this pins is that the dock actually binds the dB face and the MEASURED level,
/// that the VM exposes both, and that a mute still zeroes the ladder.</para></summary>
public class MicBayTests
{
[Fact]
public void The_mic_bay_binds_the_db_fader_and_the_measured_level()
{
var dock = SourceAssert.Text("Controls", "AudioDock.xaml");
Assert.Contains("Value=\"{Binding MicVolumeDb, Mode=TwoWay}\"", dock);
Assert.Contains("Level=\"{Binding MicMeterFraction}\"", dock);
Assert.Contains("Text=\"{Binding MicVolumeDbLabel}\"", dock);
Assert.Contains("Command=\"{Binding ToggleMicMuteCommand}\"", dock);
// The fader's range is the scale's range, not an arbitrary slider span.
Assert.Contains("Minimum=\"-60\" Maximum=\"6\"", dock);
// The VM surface exists (no construction: this is a wiring check, not a behaviour one).
var type = typeof(MainViewModel);
foreach (var name in new[] { "MicVolumeDb", "MicVolumeDbLabel", "MicMeterFraction" })
Assert.NotNull(type.GetProperty(name));
// MicMuted is derived from the volume: mute is a fader position, so the ladder must follow.
var audio = SourceAssert.Text("ViewModels", "MainViewModel.Audio.cs");
Assert.Contains("MicMuted ? 0 :", audio);
Assert.Contains("OnPropertyChanged(nameof(MicMeterFraction));", audio);
}
}
+35
View File
@@ -0,0 +1,35 @@
using Xunit;
using ytLive.Services.Audio;
namespace ytLive.Tests;
/// <summary>The TRAX fader must actually change the level the meter measures — and it did not:
/// `UserGain` wrote to the output device's volume (a no-op for NAudio's WaveOut), while the
/// mute-follow rewrote the sample-chain volume WITHOUT the user gain, so pegging the fader changed
/// nothing and the next desktop mute/duck silently discarded the setting.
/// </summary>
public class MusicLevelTests
{
[Fact]
public void The_trax_fader_reaches_the_chain_and_survives_the_mute_follow()
{
// Default: the bed sits at the design volume; pegging doubles it (+6 dB).
Assert.Equal(0.5f, MusicPlayer.EffectiveVolume(1f, 1f), 3);
Assert.Equal(1.0f, MusicPlayer.EffectiveVolume(MusicPlayer.MaxUserGain, 1f), 3);
// The mute-follow multiplies, it does not replace: the user gain survives.
Assert.Equal(1.0f, MusicPlayer.EffectiveVolume(MusicPlayer.MaxUserGain, 1f), 3);
Assert.Equal(0.5f, MusicPlayer.EffectiveVolume(1f, 1f), 3);
// Muted (or a desktop mute) is silence whatever the fader says.
Assert.Equal(0f, MusicPlayer.EffectiveVolume(MusicPlayer.MaxUserGain, 0f));
// And the floor is a real zero, not a residue.
Assert.Equal(0f, MusicPlayer.EffectiveVolume(0f, 1f));
// The old defect cannot come back: nothing may drive the output device's volume.
var source = SourceAssert.Text("Services", "Audio", "MusicPlayer.cs");
Assert.DoesNotContain("_output.Volume", source);
Assert.Contains("EffectiveVolume(_userGain, _localGain)", source);
}
}
+56
View File
@@ -0,0 +1,56 @@
using Xunit;
using ytLive.Services.Audio;
namespace ytLive.Tests;
/// <summary>The dock shows ONE ladder per source, but the creator is profoundly deaf on the right,
/// so the meter has to know which side a signal is on: hard-panned content is inaudible, not merely
/// quieter. These levels drive the imbalance flag, and they must be measured — never decorative.
/// </summary>
public class StereoMeterTests
{
private const int Rate = 48000;
private static AudioLevelMeter Pushed(int channels, float left, float right, int frames = 64, int pushes = 12)
{
var meter = new AudioLevelMeter();
var buffer = new float[frames * channels];
for (var f = 0; f < frames; f++)
{
buffer[f * channels] = left;
if (channels > 1) buffer[f * channels + 1] = right;
}
for (var i = 0; i < pushes; i++) meter.Push(new AudioSample(buffer, Rate, channels));
return meter;
}
[Fact]
public void The_meter_knows_which_side_the_signal_is_on()
{
// Hard left: the left side carries it, the right is silent, and the gap is reported.
var hardLeft = Pushed(channels: 2, left: 0.5f, right: 0f);
Assert.True(hardLeft.Left > 0.1f, $"left should carry the tone, got {hardLeft.Left}");
Assert.True(hardLeft.Right < 0.01f, $"right should be silent, got {hardLeft.Right}");
Assert.True(hardLeft.ImbalanceDb > 20f, "a one-sided signal must report a large imbalance");
// Hard right is the mirror case — the one this creator cannot hear.
var hardRight = Pushed(channels: 2, left: 0f, right: 0.5f);
Assert.True(hardRight.Right > 0.1f);
Assert.True(hardRight.Left < 0.01f);
// Balanced stereo reports no imbalance.
var centred = Pushed(channels: 2, left: 0.5f, right: 0.5f);
Assert.True(centred.Left > 0.1f && centred.Right > 0.1f);
Assert.True(centred.ImbalanceDb < 1f, $"balanced audio must not flag, got {centred.ImbalanceDb}");
// Mono is centred by definition: both sides equal, no flag — never "one-sided".
var mono = Pushed(channels: 1, left: 0.5f, right: 0f);
Assert.True(mono.Left > 0.1f);
Assert.Equal(mono.Left, mono.Right, 5);
Assert.Equal(0f, mono.ImbalanceDb);
// Silence on both sides is not an imbalance (nothing to compare).
var silent = Pushed(channels: 2, left: 0f, right: 0f);
Assert.Equal(0f, silent.ImbalanceDb);
}
}
+30
View File
@@ -0,0 +1,30 @@
using Xunit;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>The LIP-SYNC bay re-houses the offset that shipped as TASK 22, with the two things the
/// dock asks of it: a readable readout ("0 ms (aligned)") and 0 as a one-click detent. The offset
/// itself is clamped and persisted by the existing property — this pins the surface.
/// </summary>
public class SyncBayTests
{
[Fact]
public void The_lip_sync_bay_uses_the_persisted_offset_with_a_zero_detent()
{
var dock = SourceAssert.Text("Controls", "AudioDock.xaml");
Assert.Contains("Value=\"{Binding AudioSyncOffsetMs, Mode=TwoWay}\"", dock);
Assert.Contains("Text=\"{Binding SyncOffsetLabel}\"", dock);
Assert.Contains("Click=\"SyncPreset_Click\"", dock);
Assert.Contains("Tag=\"0\"", dock);
Assert.Contains("Minimum=\"-200\" Maximum=\"200\"", dock);
// The readout names the good state, and signs the others the way a person reads them.
Assert.Matches(@"IsSnapToTickEnabled=""True""", dock);
var type = typeof(MainViewModel);
Assert.NotNull(type.GetProperty("AudioSyncOffsetMs"));
Assert.NotNull(type.GetProperty("SyncOffsetLabel"));
Assert.NotNull(type.GetMethod("SetSyncOffset", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
}
}
+51
View File
@@ -0,0 +1,51 @@
using Xunit;
using ytLive.Helpers;
using ytLive.Services.Audio;
using ytLive.ViewModels;
namespace ytLive.Tests;
/// <summary>The TRAX bay shows the track, plays/pauses it, and carries a level — but no meter:
/// nothing measures the bed, and a decorative ladder would be a lie. Its fader moves a gain the
/// player actually applies, separate from the desktop-mute follow.
/// </summary>
public class TraxBayTests
{
[Fact]
public void The_trax_bay_binds_the_track_level_and_play_state_without_inventing_a_meter()
{
var dock = SourceAssert.Text("Controls", "AudioDock.xaml");
Assert.Contains("Text=\"{Binding TraxTrackLabel}\"", dock);
// KISS (creator 2026-10-30): background music is one number and two ±5 dB buttons, not a
// channel strip — and it has no ladder of its own, because the desktop bed already carries it.
Assert.Contains("Click=\"TraxStepDown_Click\"", dock);
Assert.Contains("Click=\"TraxStepUp_Click\"", dock);
Assert.Contains("IsEnabled=\"{Binding CanLowerTrax}\"", dock);
Assert.Contains("IsEnabled=\"{Binding CanRaiseTrax}\"", dock);
Assert.Contains("Text=\"{Binding TraxVolumeDbLabel}\"", dock);
Assert.Contains("Binding=\"{Binding IsMusicPlaying}\" Value=\"True\"", dock);
Assert.Contains("Click=\"TraxPlayPause_Click\"", dock);
// The bay DOES carry a ladder now — the player measures its own output, so "is music making
// sound" is answerable without hearing it (a play glyph cannot answer that).
// The TRAX row lives under the desktop volume, inside the GAME bay.
var traxRow = dock[dock.IndexOf("Text=\"TRAX\"", System.StringComparison.Ordinal)
..dock.IndexOf("Text=\"LIP-SYNC\"", System.StringComparison.Ordinal)];
Assert.Contains("TraxTrackLabel", traxRow);
Assert.DoesNotContain("SegmentMeter", traxRow);
foreach (var name in new[] { "TraxVolumeDb", "TraxVolumeDbLabel", "TraxTrackLabel", "CanRaiseTrax", "CanLowerTrax" })
Assert.NotNull(typeof(MainViewModel).GetProperty(name));
// The player gained a real user level, separate from the mute-follow LocalGain.
Assert.NotNull(typeof(ITraxPlayer).GetProperty("UserGain"));
Assert.NotNull(typeof(ITraxPlayer).GetProperty("Level"));
Assert.NotNull(typeof(MusicPlayer).GetProperty("UserGain"));
// It starts as background: −50 dB, and the ±5 dB steps are how it moves.
Assert.Equal(-50, MainViewModel.TraxDefaultDb);
Assert.Equal(5, MainViewModel.TraxStepDb);
Assert.Equal(0, GainDb.ToDb(1f), 6);
Assert.Contains("∞", GainDb.Label(GainDb.FloorDb)); // true silence, not "-60.0"
}
}
+2
View File
@@ -21,6 +21,8 @@ public sealed class TraxToggleTests
public string? TrackName { get; private set; } public string? TrackName { get; private set; }
public bool IsPlaying { get; private set; } public bool IsPlaying { get; private set; }
public float LocalGain { get; set; } = 1f; public float LocalGain { get; set; } = 1f;
public float UserGain { get; set; } = 1f;
public float Level { get; set; }
public void Load(string path) => TrackName = Path.GetFileNameWithoutExtension(path); public void Load(string path) => TrackName = Path.GetFileNameWithoutExtension(path);
public void Play() => IsPlaying = Starts; public void Play() => IsPlaying = Starts;
public void Pause() => IsPlaying = false; public void Pause() => IsPlaying = false;