Compare commits
53
Commits
785b5ff8f3
...
42228c7aab
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42228c7aab | ||
|
|
4b3d3f2645 | ||
|
|
4855d5cf8d | ||
|
|
0fa3006da7 | ||
|
|
134103c08b | ||
|
|
b84802e657 | ||
|
|
b39439abdc | ||
|
|
555ff5c0ac | ||
|
|
bc62bd81ec | ||
|
|
92d875c343 | ||
|
|
ed32151136 | ||
|
|
e53f9974a5 | ||
|
|
4a43b3e229 | ||
|
|
a8f27db4c2 | ||
|
|
b4e952fda9 | ||
|
|
bef818f4a1 | ||
|
|
dbcb69278f | ||
|
|
30824c6d6e | ||
|
|
70e2c48136 | ||
|
|
3db964e5cf | ||
|
|
a6f15a4bc3 | ||
|
|
f7e1b76cdd | ||
|
|
0f08fd7ade | ||
|
|
3261293d57 | ||
|
|
a1d861608f | ||
|
|
0fade9702b | ||
|
|
27f655c8de | ||
|
|
9611cee199 | ||
|
|
dd51f7842a | ||
|
|
ec1091a170 | ||
|
|
d8c1bdba24 | ||
|
|
f2c43909c8 | ||
|
|
0de953ef66 | ||
|
|
3fde7fcfe6 | ||
|
|
72cb3ad55a | ||
|
|
a80108dd96 | ||
|
|
adf9883ae9 | ||
|
|
77eebdb2ce | ||
|
|
17d835353d | ||
|
|
3a56807ee3 | ||
|
|
5577aaaf91 | ||
|
|
69e595da25 | ||
|
|
0f4a035376 | ||
|
|
242a13ca30 | ||
|
|
e37215d9c4 | ||
|
|
a814bcd502 | ||
|
|
7bb1207fb2 | ||
|
|
ea24405ba2 | ||
|
|
21db8a17b8 | ||
|
|
2670ac022b | ||
|
|
776f84fb88 | ||
|
|
db563c8644 | ||
|
|
77d7208bfa |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 2.8 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 423 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 422 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.8 MiB After Width: | Height: | Size: 383 KiB |
+203
-50
@@ -29,6 +29,7 @@
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
<Helpers:LogInRangeConverter x:Key="LogInRange"/>
|
||||
<Helpers:ClosedBoxTemplateSelector x:Key="BorderColorTemplates"
|
||||
ClosedTemplate="{StaticResource BorderColorClosedTemplate}"
|
||||
RowTemplate="{StaticResource BorderColorRowTemplate}"/>
|
||||
@@ -37,11 +38,62 @@
|
||||
<Border Background="{StaticResource Brush.SurfaceContainer}" CornerRadius="6" Padding="12">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- ALERT STACK (creator design 2026-11-05): standing state on top, transient
|
||||
events beneath, newest first, pushing the panel's content down. Only red
|
||||
rows live here. Row 1 is the Steam licence indicator and is never displaced;
|
||||
it shows a pin while higher tiers are unavailable, and a close control once
|
||||
ownership is verified (that close is permanent). Clicking a row runs its
|
||||
action: the licence indicator opens About, an event opens the Logs tab with
|
||||
that event's lines painted. -->
|
||||
<!-- Alerts and the panel content are different kinds of thing (state vs. the
|
||||
scene you are editing), so they are separated by space AND a rule: without it
|
||||
the stack read as the first rows of the layer list (creator, 2026-11-05). -->
|
||||
<StackPanel Grid.Row="0" Visibility="{Binding HasAttentionAlerts, Converter={StaticResource BoolToVis}}">
|
||||
<ItemsControl ItemsSource="{Binding AttentionAlerts}" Margin="0,0,0,2">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Margin="0,0,0,4" Padding="8,6" CornerRadius="4" Cursor="Hand"
|
||||
Background="{StaticResource Brush.ErrorContainer}"
|
||||
BorderBrush="{StaticResource Brush.Error}" BorderThickness="1">
|
||||
<Border.InputBindings>
|
||||
<MouseBinding MouseAction="LeftClick"
|
||||
Command="{Binding DataContext.ActivateAlertCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
CommandParameter="{Binding}"/>
|
||||
</Border.InputBindings>
|
||||
<DockPanel LastChildFill="True">
|
||||
<Button DockPanel.Dock="Right" VerticalAlignment="Top" Margin="6,0,0,0"
|
||||
Style="{StaticResource IconButton}" Width="20" Height="20"
|
||||
ToolTip="Dismiss"
|
||||
Command="{Binding DataContext.DismissAlertCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
|
||||
CommandParameter="{Binding}"
|
||||
Visibility="{Binding CanDismiss, Converter={StaticResource BoolToVis}}">
|
||||
<Path Data="M4,4 L16,16 M16,4 L4,16" Stroke="{StaticResource Brush.Error}"
|
||||
StrokeThickness="2" Width="12" Height="12" Stretch="Uniform"/>
|
||||
</Button>
|
||||
<!-- Pinned rows show the pin INSTEAD of a close control: the icon is
|
||||
the state ("standing indicator"), not a disabled button. -->
|
||||
<Path DockPanel.Dock="Right" Data="M12,2 L12,9 M8,9 H16 L14,15 H10 Z M10,15 L10,21 M14,15 L14,21"
|
||||
Stroke="{StaticResource Brush.Error}" StrokeThickness="1.6"
|
||||
Width="14" Height="14" Stretch="Uniform" VerticalAlignment="Top"
|
||||
Margin="6,2,2,0" ToolTip="Standing indicator"
|
||||
Visibility="{Binding ShowsPin, Converter={StaticResource BoolToVis}}"/>
|
||||
<TextBlock Text="{Binding Text}" Style="{StaticResource AppLogEntryText}"
|
||||
TextWrapping="Wrap" VerticalAlignment="Center"
|
||||
Foreground="{StaticResource Brush.Error}"/>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<Border Style="{StaticResource PropertyDivider}" Margin="0,4,0,10"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Edit mode (offline): layers + properties -->
|
||||
<Grid Grid.Row="0" Visibility="{Binding IsEditMode, Converter={StaticResource BoolToVis}}">
|
||||
<Grid Grid.Row="1" Visibility="{Binding IsEditMode, Converter={StaticResource BoolToVis}}">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
@@ -70,6 +122,8 @@
|
||||
IsEnabled="{Binding CanAddWebcam}"
|
||||
ToolTip="{Binding WebcamAddToolTip}"/>
|
||||
<MenuItem Header="Image" Command="{Binding AddImageCommand}"/>
|
||||
<MenuItem Header="Video File" Command="{Binding AddMediaCommand}"
|
||||
ToolTip="Play a video file in the scene (mp4, mov, avi, mkv, webm)"/>
|
||||
<MenuItem Header="Text" Command="{Binding AddSourceCommand}" CommandParameter="{x:Static models:SourceType.TextOverlay}"/>
|
||||
<MenuItem Header="Countdown" Command="{Binding AddSourceCommand}" CommandParameter="{x:Static models:SourceType.Countdown}"
|
||||
Visibility="{Binding IsCountdownAvailable, Converter={StaticResource BoolToVis}}"
|
||||
@@ -472,35 +526,6 @@
|
||||
Style="{StaticResource PropertyHint}" Margin="10,2,0,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Webcam geometry (TASK 57): under the vertical tier the camera
|
||||
keeps its OWN placement, so these fields edit the LIVE one —
|
||||
the placement the current tier shows. Gated on the VM's
|
||||
IsWebcamSelected (the same condition as the mirror/shape row
|
||||
above) so the webcam's border/background section stays the
|
||||
one panel bound to SelectedElement.IsWebcam. -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsDraggable, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Geometry" Style="{StaticResource PropertyHeader}"/>
|
||||
<!-- TASK 61: the four fields share ONE fixed width — wide enough
|
||||
for the largest geometry value (1920, plus a typed sign) and
|
||||
no wider, so Y/H no longer stretch to fill the row. -->
|
||||
<DockPanel Margin="10,0,0,4" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="X" Style="{StaticResource PropertyFieldLabel}" Width="16"/>
|
||||
<TextBox Text="{Binding SelectedElement.X, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
<TextBlock DockPanel.Dock="Left" Text=" Y" Style="{StaticResource PropertyFieldLabel}" Width="20" Margin="8,0,0,0"/>
|
||||
<TextBox Text="{Binding SelectedElement.Y, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
</DockPanel>
|
||||
<DockPanel Margin="10,0,0,4" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="W" Style="{StaticResource PropertyFieldLabel}" Width="16"/>
|
||||
<TextBox Text="{Binding SelectedElement.Width, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
<TextBlock DockPanel.Dock="Left" Text=" H" Style="{StaticResource PropertyFieldLabel}" Width="20" Margin="8,0,0,0"/>
|
||||
<TextBox Text="{Binding SelectedElement.Height, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Webcam border config -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsWebcam, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Border Color" Style="{StaticResource PropertyHeader}"/>
|
||||
@@ -688,23 +713,6 @@
|
||||
|
||||
<!-- Web source config -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsWebSource, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Geometry" Style="{StaticResource PropertyHeader}"/>
|
||||
<DockPanel Margin="0,0,0,4">
|
||||
<TextBlock DockPanel.Dock="Left" Text="X" Style="{StaticResource PropertyFieldLabel}" Width="16"/>
|
||||
<TextBox Text="{Binding SelectedElement.X, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}"/>
|
||||
<TextBlock DockPanel.Dock="Left" Text=" Y" Style="{StaticResource PropertyFieldLabel}" Width="20" Margin="8,0,0,0"/>
|
||||
<TextBox Text="{Binding SelectedElement.Y, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}"/>
|
||||
</DockPanel>
|
||||
<DockPanel Margin="0,0,0,4">
|
||||
<TextBlock DockPanel.Dock="Left" Text="W" Style="{StaticResource PropertyFieldLabel}" Width="16"/>
|
||||
<TextBox Text="{Binding SelectedElement.Width, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}"/>
|
||||
<TextBlock DockPanel.Dock="Left" Text=" H" Style="{StaticResource PropertyFieldLabel}" Width="20" Margin="8,0,0,0"/>
|
||||
<TextBox Text="{Binding SelectedElement.Height, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}"/>
|
||||
</DockPanel>
|
||||
<TextBlock Text="URI" Style="{StaticResource PropertyHeader}"/>
|
||||
<DockPanel Margin="10,0,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource IconButton}"
|
||||
@@ -725,6 +733,99 @@
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Media (video file) config — TASK 21 -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsMediaSource, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<DockPanel Margin="0,0,0,0">
|
||||
<Button DockPanel.Dock="Right" Content="▶ Play"
|
||||
Command="{Binding ReplayMediaCommand}"
|
||||
CommandParameter="{Binding SelectedElement}"
|
||||
Style="{StaticResource PropertyButton}" Padding="8,2" FontSize="11"
|
||||
ToolTip="Play this clip in the preview from the beginning"/>
|
||||
<TextBlock Text="Video File" Style="{StaticResource PropertyHeader}" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
<Grid Margin="10,0,0,2">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0" Text="{Binding SelectedElement.MediaFileDisplay}"
|
||||
Style="{StaticResource PropertyFieldLabel}"
|
||||
TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
ToolTip="{Binding SelectedElement.MediaPath}"/>
|
||||
<Button Grid.Column="1" Content="Change…" Command="{Binding ChangeMediaFileCommand}"
|
||||
CommandParameter="{Binding SelectedElement}" Style="{StaticResource PropertyButton}"
|
||||
Margin="4,0,0,0" Padding="8,2" FontSize="11"/>
|
||||
</Grid>
|
||||
<CheckBox Style="{StaticResource PropertyPillCheck}" Margin="10,4,0,4"
|
||||
Content="Loop" IsChecked="{Binding SelectedElement.MediaIsLooping, Mode=TwoWay}"
|
||||
ToolTip="Restart from the beginning at the end of the file — for starting-soon and BRB loops"/>
|
||||
<TextBlock Text="Clip finished — holding the last frame."
|
||||
Style="{StaticResource PropertyHint}"
|
||||
Visibility="{Binding SelectedElement.IsMediaFinished, Converter={StaticResource BoolToVis}}"/>
|
||||
<DockPanel Margin="10,0,0,4">
|
||||
<CheckBox DockPanel.Dock="Left" Style="{StaticResource PropertyPillCheck}"
|
||||
Content="Mute" IsChecked="{Binding SelectedElement.MediaMuted, Mode=TwoWay}"
|
||||
ToolTip="Silence this layer's sound. The picture keeps playing."/>
|
||||
</DockPanel>
|
||||
<DockPanel Margin="10,0,0,4">
|
||||
<TextBlock DockPanel.Dock="Left" Text="Level" Style="{StaticResource PropertyFieldLabel}" Width="40"/>
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding SelectedElement.MediaVolume, StringFormat={}{0:P0}}"
|
||||
Style="{StaticResource PropertyFieldLabel}" Width="34" TextAlignment="Right"/>
|
||||
<Slider Minimum="0" Maximum="1" Width="120"
|
||||
Value="{Binding SelectedElement.MediaVolume, Mode=TwoWay}"
|
||||
VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
<TextBlock Text="Sound plays through the desktop audio controls, like game audio."
|
||||
Style="{StaticResource PropertyHint}"/>
|
||||
|
||||
</StackPanel>
|
||||
|
||||
<!-- Green/Blue Screen (TASK 64): a video layer OR the alert box's
|
||||
own clip. The app offers, the creator accepts — never silent. -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.ShowsChromaKey, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<Border Style="{StaticResource PropertyDivider}"/>
|
||||
<TextBlock Text="Green/Blue Screen" Style="{StaticResource PropertyHeader}"/>
|
||||
|
||||
<Border Margin="10,0,0,4" Padding="6,5" CornerRadius="4"
|
||||
Background="{StaticResource Brush.Outline}"
|
||||
Visibility="{Binding SelectedElement.HasChromaSuggestion, Converter={StaticResource BoolToVis}}">
|
||||
<DockPanel>
|
||||
<Border DockPanel.Dock="Left" Width="12" Height="12" CornerRadius="2"
|
||||
Margin="0,0,6,0" VerticalAlignment="Center"
|
||||
Background="{Binding SelectedElement.ChromaSuggestionColor}"
|
||||
ToolTip="The screen colour this clip was shot against"/>
|
||||
<Button DockPanel.Dock="Right" Content="Remove it"
|
||||
Style="{StaticResource PropertyButton}" Padding="8,2" FontSize="11"
|
||||
Command="{Binding AcceptChromaSuggestionCommand}"
|
||||
CommandParameter="{Binding SelectedElement}"/>
|
||||
<TextBlock Text="{Binding SelectedElement.ChromaSuggestionText}"
|
||||
Style="{StaticResource PropertyFieldLabel}" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<CheckBox Style="{StaticResource PropertyPillCheck}" Margin="10,0,0,4"
|
||||
Content="Remove the background" IsChecked="{Binding SelectedElement.ChromaKeyEnabled, Mode=TwoWay}"
|
||||
ToolTip="Key out the green/blue backdrop so the layers beneath show through"/>
|
||||
<TextBlock Text="Removed automatically — green screen detected."
|
||||
Style="{StaticResource PropertyHint}"
|
||||
Visibility="{Binding SelectedElement.HasAutoChromaKey, Converter={StaticResource BoolToVis}}"/>
|
||||
<DockPanel Margin="10,0,0,4">
|
||||
<TextBlock DockPanel.Dock="Left" Text="Amount" Style="{StaticResource PropertyFieldLabel}" Width="52"/>
|
||||
<Slider Minimum="0" Maximum="0.5" Width="110"
|
||||
Value="{Binding SelectedElement.ChromaKeySimilarity, Mode=TwoWay}"
|
||||
VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
<DockPanel Margin="10,0,0,4">
|
||||
<TextBlock DockPanel.Dock="Left" Text="Softness" Style="{StaticResource PropertyFieldLabel}" Width="52"/>
|
||||
<Slider Minimum="0" Maximum="0.5" Width="110"
|
||||
Value="{Binding SelectedElement.ChromaKeySoftness, Mode=TwoWay}"
|
||||
VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
<CheckBox Style="{StaticResource PropertyPillCheck}" Margin="10,0,0,4"
|
||||
Content="Fringe" IsChecked="{Binding SelectedElement.ChromaKeySpill, Mode=TwoWay}"
|
||||
ToolTip="Clean the coloured rim the screen leaves on hair and edges"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Chat box config -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsChatBox, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Chat Overlay" Style="{StaticResource PropertyHeader}"/>
|
||||
@@ -989,13 +1090,41 @@
|
||||
Margin="0,4,0,0"
|
||||
Visibility="{Binding BackgroundSizeMismatch, Converter={StaticResource BoolToVis}}"/>
|
||||
</StackPanel>
|
||||
<!-- Geometry is ALWAYS the last section (creator ruling 2026-11-05):
|
||||
opacity sits at the top of the properties list and X/Y/W/H at the
|
||||
bottom, for every draggable element, so the eye can find them in
|
||||
the same place whatever layer is selected. For the webcam under
|
||||
the vertical tier this edits the LIVE placement (TASK 57). -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsDraggable, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Geometry" Style="{StaticResource PropertyHeader}"/>
|
||||
<!-- TASK 61: the four fields share ONE fixed width — wide enough
|
||||
for the largest geometry value (1920, plus a typed sign) and
|
||||
no wider, so Y/H no longer stretch to fill the row. -->
|
||||
<DockPanel Margin="10,0,0,4" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="X" Style="{StaticResource PropertyFieldLabel}" Width="16"/>
|
||||
<TextBox Text="{Binding SelectedElement.X, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
<TextBlock DockPanel.Dock="Left" Text=" Y" Style="{StaticResource PropertyFieldLabel}" Width="20" Margin="8,0,0,0"/>
|
||||
<TextBox Text="{Binding SelectedElement.Y, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
</DockPanel>
|
||||
<DockPanel Margin="10,0,0,4" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="W" Style="{StaticResource PropertyFieldLabel}" Width="16"/>
|
||||
<TextBox Text="{Binding SelectedElement.Width, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
<TextBlock DockPanel.Dock="Left" Text=" H" Style="{StaticResource PropertyFieldLabel}" Width="20" Margin="8,0,0,0"/>
|
||||
<TextBox Text="{Binding SelectedElement.Height, UpdateSourceTrigger=PropertyChanged, StringFormat=F0}"
|
||||
Style="{StaticResource YtTextBoxCompact}" Width="44"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
|
||||
<!-- Live mode: YouTube Live Chat (entire left panel replaced) -->
|
||||
<Grid Grid.Row="0" Visibility="{Binding IsEditMode, Converter={StaticResource InverseBoolToVis}}">
|
||||
<Grid Grid.Row="1" Visibility="{Binding IsEditMode, Converter={StaticResource InverseBoolToVis}}">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
@@ -1117,12 +1246,36 @@
|
||||
VirtualizingPanel.VirtualizationMode="Recycling">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<DockPanel Margin="6,4">
|
||||
<!-- An alert row is an entry point to its detail: clicking it opens
|
||||
this tab and paints the sequence range that event produced. -->
|
||||
<Border Padding="2,1" CornerRadius="3">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Value="True">
|
||||
<DataTrigger.Binding>
|
||||
<MultiBinding Converter="{StaticResource LogInRange}">
|
||||
<Binding Path="Sequence"/>
|
||||
<Binding Path="DataContext.HighlightedLogFrom"
|
||||
RelativeSource="{RelativeSource AncestorType=UserControl}"/>
|
||||
<Binding Path="DataContext.HighlightedLogTo"
|
||||
RelativeSource="{RelativeSource AncestorType=UserControl}"/>
|
||||
</MultiBinding>
|
||||
</DataTrigger.Binding>
|
||||
<Setter Property="Background" Value="{StaticResource Brush.ErrorContainer}"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<DockPanel Margin="4,3">
|
||||
<TextBlock DockPanel.Dock="Left" Text="{Binding TypeLabel}"
|
||||
Style="{StaticResource AppLogEntryText}" FontWeight="Bold"
|
||||
Margin="0,0,8,0"/>
|
||||
<TextBlock Text="{Binding Text}" Style="{StaticResource AppLogEntryText}"/>
|
||||
<TextBlock Text="{Binding Text}" Style="{StaticResource AppLogEntryText}"
|
||||
TextWrapping="Wrap"/>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Models;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
@@ -178,8 +179,9 @@ public partial class LeftPanel : UserControl
|
||||
var position = e.GetPosition(listBox);
|
||||
if (!_isDragging)
|
||||
{
|
||||
if (Math.Abs(position.X - _dragStartPoint.X) < SystemParameters.MinimumHorizontalDragDistance &&
|
||||
Math.Abs(position.Y - _dragStartPoint.Y) < SystemParameters.MinimumVerticalDragDistance)
|
||||
if (!DragReorderMath.ExceededThreshold(
|
||||
position.X - _dragStartPoint.X, position.Y - _dragStartPoint.Y,
|
||||
SystemParameters.MinimumHorizontalDragDistance, SystemParameters.MinimumVerticalDragDistance))
|
||||
return;
|
||||
_isDragging = true;
|
||||
listBox.CaptureMouse();
|
||||
@@ -193,12 +195,10 @@ public partial class LeftPanel : UserControl
|
||||
return;
|
||||
|
||||
var targetIndex = listBox.Items.IndexOf(targetItem);
|
||||
if (targetIndex < 0) return;
|
||||
var landed = DragReorderMath.TryMove(items, _dragIndex, targetIndex);
|
||||
if (landed < 0) return;
|
||||
|
||||
var dragged = items[_dragIndex];
|
||||
items.RemoveAt(_dragIndex);
|
||||
items.Insert(targetIndex, dragged);
|
||||
_dragIndex = targetIndex;
|
||||
_dragIndex = landed;
|
||||
_lastHoveredItem = targetItem;
|
||||
_dragReordered = true;
|
||||
}
|
||||
|
||||
+77
-28
@@ -15,7 +15,7 @@
|
||||
</Button.Template>
|
||||
</Button>
|
||||
|
||||
<Border Background="{StaticResource Brush.Background}" CornerRadius="8" Width="650" MaxHeight="700"
|
||||
<Border Background="{StaticResource Brush.Background}" CornerRadius="8" Width="820" MaxHeight="860"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Center"
|
||||
Padding="28" BorderBrush="#333" BorderThickness="1">
|
||||
<Grid>
|
||||
@@ -76,42 +76,91 @@
|
||||
Background="{StaticResource Brush.SurfaceContainerLow}"
|
||||
Visibility="{Binding IsAboutOpen, Converter={StaticResource BoolToVis}}">
|
||||
|
||||
<!-- Hub view -->
|
||||
<StackPanel Visibility="{Binding IsHubVisible, Converter={StaticResource BoolToVis}}">
|
||||
<Image Source="/LlamaCasty;component/Assets/llamacasty-logo.jpg" Height="125" Stretch="Uniform"
|
||||
HorizontalAlignment="Center" Margin="0,0,0,12"/>
|
||||
<TextBlock Text="{Binding AppVersionLabel}" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12"
|
||||
HorizontalAlignment="Center" Margin="0,4,0,0"/>
|
||||
<TextBlock Text="Live streaming for YouTube — simple enough that even the most right-brained person can intuit it."
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="13" TextWrapping="Wrap" MaxWidth="380"
|
||||
TextAlignment="Center" Margin="0,16,0,0"/>
|
||||
<TextBlock x:Name="UpgradeCopy"
|
||||
Text="Free at 720p30. The paid version unlocks higher stream and recording quality. One-time purchase; no subscription. Launch price $79, then $99 on the announced date."
|
||||
<!-- Hub view — a conversion surface, not a credits page (creator, 2026-11-05):
|
||||
large logo, one tagline, the offer in three short blocks, one primary CTA,
|
||||
everything else demoted. A paying customer never sees the price. -->
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto"
|
||||
Visibility="{Binding IsHubVisible, Converter={StaticResource BoolToVis}}">
|
||||
<StackPanel>
|
||||
<Image Source="/LlamaCasty;component/Assets/llamacasty-logo.jpg"
|
||||
Width="520" Stretch="Uniform" HorizontalAlignment="Center" Margin="0,0,0,10"/>
|
||||
|
||||
<Button x:Name="ReleaseBadgeButton" Content="{Binding AppReleaseLabel}"
|
||||
Style="{StaticResource PillBadgeButton}"
|
||||
Command="{Binding OpenPremiumCommand}"
|
||||
HorizontalAlignment="Center" Margin="0,0,0,10"
|
||||
ToolTip="Pre-release — opens llamacasty.com when clicked"/>
|
||||
|
||||
<TextBlock x:Name="AboutTagline"
|
||||
Text="1-2-3, and go live to the world on YouTube!"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="17" FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" MaxWidth="640" TextAlignment="Center"
|
||||
HorizontalAlignment="Center" Margin="0,4,0,18"/>
|
||||
|
||||
<Grid MaxWidth="640" HorizontalAlignment="Center" Margin="0,0,0,4">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="Free" Margin="0,0,14,4"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="13" FontWeight="SemiBold"/>
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding FreeOfferText}" Margin="0,0,0,4"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="13" TextWrapping="Wrap"/>
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Paid" Margin="0,0,14,4"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="13" FontWeight="SemiBold"/>
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding PaidOfferText}" Margin="0,0,0,4"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="13" TextWrapping="Wrap"/>
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.ColumnSpan="2" Text="{Binding TrustLine}"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12"
|
||||
TextWrapping="Wrap" MaxWidth="380" TextAlignment="Center" Margin="0,12,0,0"/>
|
||||
<Button x:Name="UpgradeLinkButton" Content="Learn more at llamacasty.com"
|
||||
Command="{Binding OpenPremiumCommand}" Style="{StaticResource YtButtonSecondary}"
|
||||
HorizontalAlignment="Center" Margin="0,12,0,0"
|
||||
TextWrapping="Wrap" Margin="0,6,0,0"/>
|
||||
</Grid>
|
||||
|
||||
<!-- Free: the offer. Owned: thanks, no price. -->
|
||||
<StackPanel x:Name="UpgradeBlock"
|
||||
Visibility="{Binding IsAppOwned, Converter={StaticResource InverseBoolToVis}}"
|
||||
HorizontalAlignment="Center" Margin="0,18,0,0">
|
||||
<TextBlock x:Name="AboutPriceLine" Text="{Binding PriceLine}"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="16" FontWeight="Bold"
|
||||
HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding PriceNote}" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12"
|
||||
TextAlignment="Center" TextWrapping="Wrap" MaxWidth="520" Margin="0,2,0,10"/>
|
||||
<Button x:Name="UpgradeCtaButton" Content="{Binding UpgradeCtaLabel}"
|
||||
Command="{Binding OpenPremiumCommand}"
|
||||
Style="{StaticResource YtButton}"
|
||||
HorizontalAlignment="Center" Padding="22,10" FontSize="14"
|
||||
ToolTip="Opens llamacasty.com in your browser when clicked"/>
|
||||
<TextBlock Text="Made by gramps · llama chile shop" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12"
|
||||
HorizontalAlignment="Center" Margin="0,16,0,8"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Creator hub links -->
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,0,0,8">
|
||||
<TextBlock x:Name="OwnedStateText" Text="{Binding LicenceStateLabel}"
|
||||
Foreground="{StaticResource Brush.Positive}" FontSize="13" FontWeight="SemiBold"
|
||||
HorizontalAlignment="Center" Margin="0,18,0,0"
|
||||
Visibility="{Binding IsAppOwned, Converter={StaticResource BoolToVis}}"/>
|
||||
|
||||
<!-- Secondary destinations, one row, deliberately quieter than the CTA. -->
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,22,0,0">
|
||||
<Button Content="llama chile shop on YouTube" Command="{Binding OpenChannelCommand}"
|
||||
Style="{StaticResource YtButtonSecondary}" Margin="0,0,8,0"/>
|
||||
Style="{StaticResource YtButtonSecondary}" Margin="0,0,8,0" FontSize="11" Padding="10,5"/>
|
||||
<Button Content="Mastodon" Command="{Binding OpenMastodonCommand}"
|
||||
Style="{StaticResource YtButtonSecondary}"/>
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
|
||||
Style="{StaticResource YtButtonSecondary}" Margin="0,0,8,0" FontSize="11" Padding="10,5"/>
|
||||
<Button Content="Buy me a coffee" Command="{Binding OpenCoffeeCommand}"
|
||||
Style="{StaticResource YtButtonSecondary}"/>
|
||||
Style="{StaticResource YtButtonSecondary}" Margin="0,0,8,0" FontSize="11" Padding="10,5"/>
|
||||
<Button Content="Licenses & legal" Command="{Binding OpenLicensesCommand}"
|
||||
Style="{StaticResource YtButtonSecondary}" FontSize="11" Padding="10,5"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Content="Licenses & legal" Command="{Binding OpenLicensesCommand}"
|
||||
Style="{StaticResource YtButtonSecondary}" HorizontalAlignment="Center"
|
||||
Margin="0,16,0,0"/>
|
||||
<TextBlock x:Name="AboutCopyright" Text="{Binding CopyrightLabel}"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"
|
||||
HorizontalAlignment="Center" Margin="0,18,0,4"/>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Licensing/legal panel -->
|
||||
<StackPanel Visibility="{Binding IsLicensesOpen, Converter={StaticResource BoolToVis}}">
|
||||
|
||||
+74
-15
@@ -167,6 +167,17 @@
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
<Setter Property="Stretch" Value="Fill"/>
|
||||
</DataTrigger>
|
||||
|
||||
<!-- A video file layer is a frame source too. Without this trigger its Image stayed
|
||||
Collapsed and the clip was invisible in the preview while the decode ran — the
|
||||
same defect the alert box hit on 2026-09-26. -->
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding IsMediaSource}" Value="True"/>
|
||||
<Condition Binding="{Binding IsRectShape}" Value="True"/>
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</MultiDataTrigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding IsWebcam}" Value="True"/>
|
||||
@@ -198,6 +209,15 @@
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</MultiDataTrigger>
|
||||
<!-- A round-clipped video layer uses the same unit-circle path, or it would
|
||||
render in the output and be invisible in the preview (2026-11-05). -->
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding IsMediaSource}" Value="True"/>
|
||||
<Condition Binding="{Binding IsRoundShape}" Value="True"/>
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</MultiDataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Image.Style>
|
||||
@@ -748,27 +768,66 @@
|
||||
<StackPanel Visibility="{Binding Ypp.IsSignedOut, Converter={StaticResource InverseBoolToVis}}">
|
||||
<TextBlock Text="{Binding Ypp.DisplayName}" Foreground="{StaticResource Brush.OnSurface}" FontSize="13"
|
||||
FontWeight="SemiBold" Margin="0,0,0,10"/>
|
||||
<TextBlock Text="SUBSCRIBERS — TIER 1 · FAN FUNDING" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<TextBlock Text="{Binding Ypp.Tier1SubsText}" Foreground="{StaticResource Brush.OnSurface}" FontSize="13"/>
|
||||
<Border Height="8" Background="{StaticResource Brush.SurfaceContainerHigh}" CornerRadius="4" Margin="0,4,0,10">
|
||||
<!-- TASK 39·2 — the three metrics that count, with the threshold
|
||||
that applies TODAY (the long-form bar doubles 2027-02-01; that is
|
||||
data, not a code change). YouTube decides eligibility; these are
|
||||
estimates and the drawer says so. No red/green scoring. -->
|
||||
<TextBlock Text="SUBSCRIBERS" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<DockPanel Margin="0,0,0,2">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding Ypp.SubscribersText}"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="12"
|
||||
FontFamily="{StaticResource FontFamily.Mono}"/>
|
||||
<TextBlock Text="Ad revenue tier" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"/>
|
||||
</DockPanel>
|
||||
<Border Height="8" Background="{StaticResource Brush.SurfaceContainerHigh}" CornerRadius="4" Margin="0,0,0,10">
|
||||
<Border Height="8" Background="{StaticResource Brush.Tertiary}" CornerRadius="4" HorizontalAlignment="Left"
|
||||
Width="{Binding Ypp.Tier1SubsBarWidth}"/>
|
||||
Width="{Binding Ypp.SubscribersBarWidth}"/>
|
||||
</Border>
|
||||
<TextBlock Text="SUBSCRIBERS — TIER 2 · AD REVENUE" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<TextBlock Text="{Binding Ypp.Tier2SubsText}" Foreground="{StaticResource Brush.OnSurface}" FontSize="13"/>
|
||||
<Border Height="8" Background="{StaticResource Brush.SurfaceContainerHigh}" CornerRadius="4" Margin="0,4,0,10">
|
||||
|
||||
<TextBlock Text="LONG-FORM WATCH HOURS · 12 MONTHS" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<DockPanel Margin="0,0,0,2">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding Ypp.WatchHoursText}"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="12"
|
||||
FontFamily="{StaticResource FontFamily.Mono}"/>
|
||||
<TextBlock Text="Public videos" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"/>
|
||||
</DockPanel>
|
||||
<Border Height="8" Background="{StaticResource Brush.SurfaceContainerHigh}" CornerRadius="4" Margin="0,0,0,4">
|
||||
<Border Height="8" Background="{StaticResource Brush.Tertiary}" CornerRadius="4" HorizontalAlignment="Left"
|
||||
Width="{Binding Ypp.Tier2SubsBarWidth}"/>
|
||||
Width="{Binding Ypp.WatchHoursBarWidth}"/>
|
||||
</Border>
|
||||
<TextBlock Text="PUBLIC UPLOADS (90 DAYS)" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<TextBlock Text="{Binding Ypp.UploadsText}" Foreground="{StaticResource Brush.OnSurface}" FontSize="13"/>
|
||||
<Border Height="8" Background="{StaticResource Brush.SurfaceContainerHigh}" CornerRadius="4" Margin="0,4,0,6">
|
||||
<TextBlock Text="Bar rises to 8,000 h on 1 Feb 2027."
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="0,0,0,10"/>
|
||||
|
||||
<TextBlock Text="SHORTS VIEWS · 90 DAYS" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<DockPanel Margin="0,0,0,2">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding Ypp.ShortsViewsText}"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="12"
|
||||
FontFamily="{StaticResource FontFamily.Mono}"/>
|
||||
<TextBlock Text="Shorts feed" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"/>
|
||||
</DockPanel>
|
||||
<Border Height="8" Background="{StaticResource Brush.SurfaceContainerHigh}" CornerRadius="4" Margin="0,0,0,8">
|
||||
<Border Height="8" Background="{StaticResource Brush.Tertiary}" CornerRadius="4" HorizontalAlignment="Left"
|
||||
Width="{Binding Ypp.UploadsBarWidth}"/>
|
||||
Width="{Binding Ypp.ShortsViewsBarWidth}"/>
|
||||
</Border>
|
||||
<TextBlock Text="LONG-FORM WATCH HOURS + SHORTS VIEWS" Style="{StaticResource YtLabel}" Margin="0,10,0,2"/>
|
||||
<TextBlock Text="These arrive with the extended analytics update — subscriber + upload + standing progress is live now."
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="12" TextWrapping="Wrap"/>
|
||||
|
||||
<TextBlock Text="{Binding Ypp.CriteriaMetText}"
|
||||
Foreground="{StaticResource Brush.OnSurface}" FontSize="12" FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" Margin="0,0,0,2"/>
|
||||
<TextBlock Text="Either view route qualifies — subscribers plus watch hours, or subscribers plus Shorts views."
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"
|
||||
TextWrapping="Wrap" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="{Binding Ypp.ThresholdsAsOfText}"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"
|
||||
TextWrapping="Wrap" Margin="0,0,0,8"/>
|
||||
|
||||
<TextBlock Text="{Binding Ypp.WatchMetricsMissingText}"
|
||||
Foreground="{StaticResource Brush.Attention}" FontSize="11" TextWrapping="Wrap"
|
||||
Margin="0,0,0,8"
|
||||
Visibility="{Binding Ypp.HasWatchMetrics, Converter={StaticResource InverseBoolToVis}}"/>
|
||||
|
||||
<TextBlock Text="FAN FUNDING TIER · 500 SUBSCRIBERS" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
<TextBlock Text="{Binding Ypp.Tier1SubsText}" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11"
|
||||
FontFamily="{StaticResource FontFamily.Mono}" Margin="0,0,0,10"/>
|
||||
|
||||
<TextBlock Text="COMPLIANCE CHECKLIST" Style="{StaticResource YtLabel}" Margin="0,14,0,4"/>
|
||||
<TextBlock Text="CHANNEL STANDING" Style="{StaticResource YtLabel}" Margin="0,0,0,2"/>
|
||||
|
||||
@@ -79,6 +79,18 @@
|
||||
<TextBlock Text="Zoom box follows" Foreground="{StaticResource Brush.OnSurface}" FontSize="11" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
|
||||
<!-- ═══ VIDEO CLIPS (TASK 64) ═══ -->
|
||||
<TextBlock Text="Video clips" Style="{StaticResource SectionHeader}" Margin="0,6,0,4"/>
|
||||
<DockPanel Margin="10,0,0,10">
|
||||
<ToggleButton DockPanel.Dock="Right" Style="{StaticResource PillToggle}"
|
||||
IsChecked="{Binding AutoChromaScreen, Mode=TwoWay}" VerticalAlignment="Center"
|
||||
ToolTip="On: a clip shot against a clear green or blue screen is keyed as soon as it is added. Off: the app asks first."/>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Auto Green/Blue Screen" Foreground="{StaticResource Brush.OnSurface}" FontSize="11"/>
|
||||
<TextBlock Text="Removes a detected screen without asking." Style="{StaticResource PropertyHint}"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
|
||||
<!-- ═══ SCENE TRANSITIONS ═══ -->
|
||||
<TextBlock Text="Scene transition" Style="{StaticResource SectionHeader}" Margin="0,6,0,4"/>
|
||||
<TextBlock Text="Type" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="10,0,0,2"/>
|
||||
|
||||
@@ -107,6 +107,15 @@
|
||||
<Button Content="{Binding PrimaryStartButtonLabel}" Style="{StaticResource YtButton}"
|
||||
Height="32" Margin="10,0,0,0" Command="{Binding PrimaryStartCommand}"
|
||||
Visibility="{Binding ShowPrimaryStartButton, Converter={StaticResource BoolToVis}}"/>
|
||||
<!-- TASK 32·3: the drop ended this broadcast. YouTube cannot resume a completed one, so
|
||||
the only honest action is a new broadcast — one click, saved details, and the title
|
||||
says it is a resume so the channel shows what happened. -->
|
||||
<Button x:Name="BackOnAirButton" Content="{Binding BackOnAirLabel}"
|
||||
Style="{StaticResource YtButton}" Height="32" Margin="10,0,0,0"
|
||||
Background="{StaticResource Brush.Primary}"
|
||||
Command="{Binding BackOnAirCommand}"
|
||||
ToolTip="Start a new broadcast from your saved details — this begins a new video"
|
||||
Visibility="{Binding IsOffAirAfterDrop, Converter={StaticResource BoolToVis}}"/>
|
||||
<!-- No separate TEST button (creator ruling 2026-10-30): EDIT decides whether
|
||||
the ON-AIR start is the real livestream or the test one. -->
|
||||
</StackPanel>
|
||||
@@ -120,6 +129,12 @@
|
||||
Foreground="White" Margin="8,0,0,0" VerticalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding LiveElapsedText}" Foreground="White" FontSize="14"
|
||||
FontFamily="Consolas" VerticalAlignment="Center" Margin="8,0,0,0"/>
|
||||
<!-- TASK 32·2: measured facts only — elapsed seconds and which attempt. No countdown:
|
||||
YouTube's cutoff is not a constant we can promise. -->
|
||||
<TextBlock x:Name="ReconnectDetail" Text="{Binding ReconnectDetailText}"
|
||||
Foreground="{StaticResource Brush.Attention}" FontSize="13"
|
||||
FontFamily="Consolas" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
Visibility="{Binding IsReconnecting, Converter={StaticResource BoolToVis}}"/>
|
||||
<Button Content="{Binding EndButtonText}" Style="{StaticResource YtButton}"
|
||||
Background="{StaticResource Brush.Primary}" Margin="14,0,0,0"
|
||||
Command="{Binding EndStreamCommand}"/>
|
||||
|
||||
+26
-13
@@ -62,19 +62,32 @@ on the partner dashboard — the dashboard's Downloads page only re-offers the S
|
||||
| Partner support | `help.steampowered.com/en/wizard/HelpWithPublishing` |
|
||||
| Steamworks.NET (managed wrapper) | `nuget.org/packages/Steamworks.NET` |
|
||||
|
||||
1. **Steamworks account** → onboarding (NDA, identity, company details, tax interview, payout bank,
|
||||
then the **$100 Steam Direct fee** per app). The store page cannot be configured before the fee.
|
||||
2. **App IDs.** One paid app and its associated free Demo. The Demo has its own App ID; it checks
|
||||
ownership of the paid app with `BIsSubscribedApp(paidAppId)`.
|
||||
3. **Builds.** Keep one codebase. Steam gives the Demo a separate release checklist/build setup;
|
||||
shared depots can avoid duplicating common files once the paid app is released.
|
||||
4. **Steamworks SDK.** `./scripts/steam-sdk.sh ~/Downloads/steamworks_sdk_165.zip` extracts
|
||||
`steam_api64.dll` from `sdk/redistributable_bin/win64/` into `steam/` (gitignored) and stages
|
||||
`steam_appid.txt` = 480 — Valve's Spacewar app, so `SteamAPI.Init()` works locally before
|
||||
LlamaCasty has an App ID. Add `--contentbuilder` on the machine that uploads a depot. The csproj
|
||||
copies the DLL **beside the exe** (`Link`) with `ExcludeFromSingleFile`, and copies
|
||||
`steam_appid.txt` in Debug only — never into a depot. The managed side is the `Steamworks.NET`
|
||||
package (`SteamApps.BIsSubscribedApp`).
|
||||
### Status (updated 2026-11-05 — this is a WAIT on Valve, not a task of ours)
|
||||
|
||||
| Step | State |
|
||||
|---|---|
|
||||
| Partner account created | ✅ done by the creator |
|
||||
| Identity verification | ⏳ **pending** — Valve reviewing |
|
||||
| Tax interview | ⏳ submitted; Valve quotes **up to 30 business days** to review |
|
||||
| $100 Steam Direct fee | ✅ **paid** (creator, 2026-11-05) — a store page can be configured once identity clears |
|
||||
| App IDs (paid app + free Demo) | **not yet assigned** |
|
||||
| Store page | not created |
|
||||
| Build review | not started |
|
||||
|
||||
**Critical path from 2026-11-05**, using Valve's own published windows:
|
||||
|
||||
1. identity + tax review — up to **30 business days** (~6 calendar weeks) → mid-December
|
||||
2. fee paid, app IDs assigned, store page built and submitted
|
||||
3. store page review — **up to 12 business days** (Valve's current backlog; docs still say 3–5)
|
||||
4. page public **≥2 weeks before release** (Valve's rule)
|
||||
5. build review — **up to 12 business days**
|
||||
|
||||
**Earliest realistic launch: early-to-mid February 2027.** The launch-price deadline is no longer a
|
||||
date: it now ends **30 days after the store page goes live** (2026-11-05), so Valve's queue cannot make
|
||||
the public claim wrong.
|
||||
|
||||
Nothing below can start until step 1 clears; none of it blocks the app work.
|
||||
|
||||
5. **Store page** configured and made public **two weeks before release** — Valve's rule, and it is
|
||||
the window where wishlists accumulate.
|
||||
|
||||
|
||||
+29
-13
@@ -1,24 +1,40 @@
|
||||
# HANDOFF — 2026-11-04 (TASK 3·17 — static text layers)
|
||||
# HANDOFF — 2026-11-09 (TASK 33 policy; vertical checks passed)
|
||||
|
||||
## State
|
||||
|
||||
- `main`; TASK 53 is complete and TASK 3·17 is complete in three commits: `60c4a00`, `58eb640`,
|
||||
and the final output/compositing phase.
|
||||
- Text layers persist independently, edit as static multiline text, and share one cached raster between
|
||||
preview and output. The frame pump only reads the raster cache; no WPF render occurs on its thread.
|
||||
- The app clean build has 0 warnings. 524 tests passed with the documented physical mouse-injection test
|
||||
and known audio test excluded; the new text renderer, preview/output, and pump-cache tests pass.
|
||||
- The four stray `Assets/llamacasty-*` exports were deleted 2026-11-04 — unreferenced by the csproj,
|
||||
XAML or scripts (recipe in `MyMistakes.md`).
|
||||
- `main`. TASK 21 (video layer + soundtrack), TASK 64 (green/blue screen) and TASK 32·4 (fragmented MP4)
|
||||
are complete; TASK 49 is retired (YouTube owns chat moderation — we just don't paint tombstones).
|
||||
- **Starting art**: `Assets/starting-background.jpg` is the corrected onboarding screen (earlier
|
||||
images in `Assets/archive/`). Bundled art is hash-keyed into the layout DB, so
|
||||
`StampDefaultBackgroundAsset` compares bytes and re-stamps on a mismatch — no version bump.
|
||||
- Left panel alert stack shipped: Steam licence indicator pinned at row 1, event rows LIFO, click →
|
||||
About or Logs with the event's lines painted. Detail: `docs/ai/ui-surface.md`.
|
||||
- Site: demo video (silent loop) is the hero; Starting screen is in the scenes section.
|
||||
- **TASK 33 complete** (`0fa3006`): cause-classified step-down — shed our capture cost, then fps →
|
||||
resolution for the machine; bitrate only for the upload; one-way with recovery behind a flag.
|
||||
- **Creator hands cleared 2026-11-09**: vertical camera check 1–6 pass; vertical cadence 29.8/s.
|
||||
- Tests: 588 green; `FAST=1 ./scripts/verify.sh` ≈ 4 min.
|
||||
|
||||
## Next action
|
||||
|
||||
- Next action: select the next queued task from `TASKS.md`.
|
||||
- Do not push absent a checkpoint request.
|
||||
- **App queue starts at 34** (scheduled streams; cite its research flags first), then 35/37/40/50/55,
|
||||
Move transitions, 9·5.
|
||||
- Site repo commits are local (`llgit.llamachile.tube`); deploy is `./deploy.sh`, not a push.
|
||||
- Do not push the app absent a checkpoint request.
|
||||
- **Steam is a wait, not a task:** identity verification pending, tax review in Valve's queue (up to 30
|
||||
business days). No app IDs, no store page, Release entitlement fails closed.
|
||||
|
||||
## Landmines
|
||||
|
||||
- `LayerReorderPersistenceTests.RealMouseDrag_OnTheLayerList_PersistsTheReorder` injects physical
|
||||
mouse input. Do not run it while the desktop is in use.
|
||||
- **The preview pane draws frame-source layers from a whitelist of DataTriggers.** A layer type with no
|
||||
trigger is invisible in the preview while its decode looks healthy. Add the trigger with the layer
|
||||
type; pin it with `MediaPreviewDisplayTests`.
|
||||
- **A bundled-art "version" heal cannot work**: the constant and the embedded resource are compiled at
|
||||
different moments, so a bump can race the image it is meant to ship. Compare bytes
|
||||
(`LayoutStore.AssetMatches`). Also: `AllBackgrounds()` returns only the LIVE scene's rows.
|
||||
- Pack URIs for bundled assets must be assembly-qualified (`/LlamaCasty;component/Assets/…`): the
|
||||
unqualified form resolves against the entry assembly, which is the test host under `dotnet test`.
|
||||
- Media sessions are keyed by **path + look** (`MainViewModel.MediaSessionKey`); never acquire by raw path.
|
||||
- **The audio pipe allows ONE server per name**; DEBUG suffixes it (id, else pid), Release does not.
|
||||
- Integration tests constructing `MainWindow` must set a temporary `LayoutPathOverride` and clear it in `finally`.
|
||||
- Bundled FFmpeg stays outside the single-file exe (`ExcludeFromSingleFile="true"`).
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
|
||||
namespace ytLive.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// The arithmetic behind dragging a row in the layer list, kept out of the window's code-behind so it
|
||||
/// can be tested without a mouse. It used to live inline in the preview-mouse handlers, and the only
|
||||
/// test that covered it injected REAL cursor movement (<c>SetCursorPos</c> + <c>mouse_event</c>) — which
|
||||
/// took over whatever machine ran the tests and failed whenever the desktop was busy. 2026-11-05: the
|
||||
/// arithmetic moved here (pure, tested), the injected-input test was deleted.
|
||||
/// </summary>
|
||||
public static class DragReorderMath
|
||||
{
|
||||
/// <summary>True once the pointer has travelled far enough to mean "drag", not "click". WPF's
|
||||
/// own thresholds are the caller's (<c>SystemParameters.MinimumHorizontal/VerticalDragDistance</c>).</summary>
|
||||
public static bool ExceededThreshold(double dx, double dy, double horizontal, double vertical)
|
||||
=> Math.Abs(dx) >= horizontal || Math.Abs(dy) >= vertical;
|
||||
|
||||
/// <summary>Moves one item to the position currently occupied by another. Returns the index the
|
||||
/// item actually landed on (the caller keeps dragging from there), or -1 when the move is a no-op
|
||||
/// or the indices are out of range.
|
||||
/// <para>Order matters: the item is removed first, so a downward move inserts at the target's old
|
||||
/// index and lands exactly under the pointer — this is the behaviour the mouse test used to pin.</para>
|
||||
/// </summary>
|
||||
public static int TryMove(IList items, int from, int to)
|
||||
{
|
||||
if (items == null || from < 0 || to < 0 || from >= items.Count || to >= items.Count) return -1;
|
||||
if (from == to) return -1;
|
||||
|
||||
var moved = items[from]!;
|
||||
items.RemoveAt(from);
|
||||
items.Insert(to, moved);
|
||||
return to;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
|
||||
namespace ytLive.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Paces a frame stream to wall-clock deadlines instead of sleeping a fixed interval after each
|
||||
/// frame. The difference matters: a fixed sleep ADDS the frame's own decode/copy cost, so a 30 fps
|
||||
/// clip with 20 ms of work per frame plays at 1/(33+20) ≈ 19 fps — which is what a 1080p video layer
|
||||
/// did (measured 20.9 fps on a 30 fps clip, 2026-11-05). Here the target is <c>start + n × frame</c>,
|
||||
/// so work is absorbed by the interval when it fits, and a stream that has fallen behind resyncs
|
||||
/// instead of bursting to catch up.
|
||||
/// </summary>
|
||||
public sealed class FramePacer
|
||||
{
|
||||
private long _nextTicks = long.MinValue;
|
||||
|
||||
/// <summary>How long to wait after emitting the frame at <paramref name="now"/>. Returns zero
|
||||
/// when the frame is already due (or late).</summary>
|
||||
public TimeSpan DelayFor(TimeSpan frameDuration, TimeSpan now)
|
||||
{
|
||||
if (frameDuration <= TimeSpan.Zero) return TimeSpan.Zero;
|
||||
|
||||
if (_nextTicks == long.MinValue)
|
||||
{
|
||||
_nextTicks = now.Ticks + frameDuration.Ticks;
|
||||
return frameDuration;
|
||||
}
|
||||
|
||||
var remaining = TimeSpan.FromTicks(_nextTicks - now.Ticks);
|
||||
_nextTicks += frameDuration.Ticks;
|
||||
|
||||
if (remaining < TimeSpan.Zero)
|
||||
{
|
||||
// Late (the frame's work exceeded its interval): resync to now rather than emitting a
|
||||
// burst of frames back-to-back, which the viewer would see as a speed-up.
|
||||
_nextTicks = now.Ticks + frameDuration.Ticks;
|
||||
return TimeSpan.Zero;
|
||||
}
|
||||
|
||||
// Never wait longer than one interval, even if the caller's clock stood still (a fake delay
|
||||
// in a test, or a suspended machine): a longer sleep would be a pause, not pacing.
|
||||
return remaining > frameDuration ? frameDuration : remaining;
|
||||
}
|
||||
|
||||
/// <summary>Restarts the schedule (a new playback pass begins at the top of the file).</summary>
|
||||
public void Reset() => _nextTicks = long.MinValue;
|
||||
}
|
||||
@@ -69,6 +69,18 @@ public static class InstanceProfile
|
||||
public static string? WebViewDataFolder => null;
|
||||
#endif
|
||||
|
||||
/// <summary>The audio pipe name for this process. The pipe server allows exactly ONE instance, so a
|
||||
/// shared name means the second app on the machine can never go live — it throws "All pipe instances
|
||||
/// are busy" (2026-11-06: Release recording, Debug trying to go live). Release keeps the plain name;
|
||||
/// a DEBUG build ALWAYS appends a suffix — its claimed id, or the process id when it has none — so a
|
||||
/// debug run launched straight from the IDE can never collide with the Release build beside it.</summary>
|
||||
public static string AudioPipeName(string baseName)
|
||||
#if DEBUG
|
||||
=> Id is { } id ? $"{baseName}_{id}" : $"{baseName}_pid{Environment.ProcessId}";
|
||||
#else
|
||||
=> baseName;
|
||||
#endif
|
||||
|
||||
/// <summary>The one real user profile: <c>%APPDATA%\ytLlive</c>. Note the historical
|
||||
/// double-L — do not "fix" it, users already have their layouts there.</summary>
|
||||
public static string DefaultRoot => Path.Combine(
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace ytLive.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// True when a log entry's sequence falls inside the range a clicked alert points at. Two numbers
|
||||
/// rather than a membership collection: the log list is virtualised, and rows that are already
|
||||
/// realised do not re-evaluate when a collection changes — but they do when a bound number changes.
|
||||
/// </summary>
|
||||
public sealed class LogInRangeConverter : IMultiValueConverter
|
||||
{
|
||||
public object Convert(object[] values, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (values.Length < 3) return false;
|
||||
if (values[0] is not long sequence) return false;
|
||||
if (values[1] is not long from || values[2] is not long to) return false;
|
||||
if (from == 0 && to == 0) return false;
|
||||
return sequence >= from && sequence <= to;
|
||||
}
|
||||
|
||||
public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, CultureInfo culture)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
@@ -145,13 +145,6 @@
|
||||
ItemContainerStyle="{StaticResource YtQualityComboBoxItem}"
|
||||
ToolTip="{Binding ResolutionHelp}"
|
||||
IsEnabled="{Binding CanChangeQuality}"/>
|
||||
<Border x:Name="EntitlementErrorPanel" Margin="0,6,0,0" Padding="8,6"
|
||||
Background="{StaticResource Brush.ErrorContainer}"
|
||||
BorderBrush="{StaticResource Brush.Error}" BorderThickness="1" CornerRadius="4"
|
||||
Visibility="{Binding EntitlementErrorMessage, Converter={StaticResource NotNullToVis}}">
|
||||
<TextBlock x:Name="EntitlementErrorText" Text="{Binding EntitlementErrorMessage}"
|
||||
Foreground="{StaticResource Brush.Error}" FontSize="11" TextWrapping="Wrap"/>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
@@ -201,6 +201,10 @@ public partial class MainWindow : Window
|
||||
if (form.IsDrawerOpen) form.CloseDrawerCommand.Execute(null);
|
||||
if (ypp.IsDrawerOpen) ypp.CloseDrawerCommand.Execute(null);
|
||||
if (test.IsDrawerOpen) test.CloseDrawerCommand.Execute(null);
|
||||
// The Settings (gear) and Socials drawers live in the same host but were left out of this
|
||||
// guard, so clicking anywhere else left them open (reported 2026-11-05).
|
||||
_viewModel.CloseSettingsDrawerIfOpen();
|
||||
_viewModel.CloseSocialsDrawer();
|
||||
}
|
||||
if (_previewPane.IsClickInsidePreview(original)) return;
|
||||
if (_leftPanel.IsClickInside(original)) return;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>
|
||||
/// One row in the left panel's alert stack (creator design, 2026-11-05). The stack sits above the
|
||||
/// panel's content and pushes it down, so an alert is seen without hunting for a tab.
|
||||
/// <para><b>Pinned</b> rows are standing state, not errors to clear: they show a pin instead of a
|
||||
/// close control and are only removed when the state itself changes (the Steam licence indicator
|
||||
/// becomes dismissible — and its dismissal permanent — once ownership is verified).</para>
|
||||
/// <para>Clicking a row runs its action: the licence indicator opens About; an event alert opens the
|
||||
/// Logs tab with that event's lines highlighted.</para>
|
||||
/// <para>Rows are text only — a heading line above the message was redundant and pushed the stack past
|
||||
/// its two-line budget (creator, 2026-11-05).</para>
|
||||
/// </summary>
|
||||
public sealed record AttentionAlert(
|
||||
string Id,
|
||||
string Text,
|
||||
bool IsPinned,
|
||||
AttentionAlertAction Action,
|
||||
long LogFrom = 0,
|
||||
long LogTo = 0)
|
||||
{
|
||||
/// <summary>True while a close control should be shown (a dismissible row).</summary>
|
||||
public bool CanDismiss => !IsPinned;
|
||||
|
||||
/// <summary>True while the row should show the pin glyph instead of a close control.</summary>
|
||||
public bool ShowsPin => IsPinned;
|
||||
}
|
||||
|
||||
public enum AttentionAlertAction
|
||||
{
|
||||
/// <summary>Open the About panel (the licence indicator).</summary>
|
||||
About,
|
||||
|
||||
/// <summary>Open the Logs tab and highlight this event's lines.</summary>
|
||||
Logs,
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>One Super Chat or Super Sticker event, as YouTube reports it.</summary>
|
||||
public sealed record SuperChatEvent(
|
||||
string Id,
|
||||
ChatEventKind Kind,
|
||||
long AmountMicros,
|
||||
string Currency,
|
||||
string? DisplayAmount,
|
||||
DateTime PublishedAt);
|
||||
|
||||
/// <summary>
|
||||
/// TASK 3·20: what this session's rewards added up to — <b>in memory only</b>.
|
||||
/// <para>Derived on demand from <c>superChatEvents.list</c> rather than persisted: YouTube is the system
|
||||
/// of record for money, and keeping a local ledger would contradict the published promise that no
|
||||
/// viewer, member or donor information is retained after the session ends.</para>
|
||||
/// <para>Totals are kept <b>per currency</b> and never summed across currencies — a $5 and a €5 are not
|
||||
/// $10, and a single blended number would be a lie.</para>
|
||||
/// </summary>
|
||||
public sealed record SessionRewardSummary(
|
||||
int SuperChatCount,
|
||||
int SuperStickerCount,
|
||||
IReadOnlyDictionary<string, long> MicrosByCurrency,
|
||||
DateTime? FirstEventAt,
|
||||
DateTime? LastEventAt)
|
||||
{
|
||||
public static readonly SessionRewardSummary Empty = new(
|
||||
0, 0, new Dictionary<string, long>(), null, null);
|
||||
|
||||
public int TotalEvents => SuperChatCount + SuperStickerCount;
|
||||
|
||||
public bool HasEvents => TotalEvents > 0;
|
||||
|
||||
/// <summary>Filters to a session window and rolls the events up. Events outside
|
||||
/// [<paramref name="sinceUtc"/>, <paramref name="untilUtc"/>] are ignored, which is what makes a
|
||||
/// report "this session" rather than "this channel".</summary>
|
||||
public static SessionRewardSummary From(
|
||||
IEnumerable<SuperChatEvent> events, DateTime sinceUtc, DateTime? untilUtc = null)
|
||||
{
|
||||
var until = untilUtc ?? DateTime.MaxValue;
|
||||
var inWindow = events
|
||||
.Where(e => e.PublishedAt >= sinceUtc && e.PublishedAt <= until)
|
||||
.OrderBy(e => e.PublishedAt)
|
||||
.ToList();
|
||||
|
||||
if (inWindow.Count == 0) return Empty;
|
||||
|
||||
var byCurrency = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var e in inWindow)
|
||||
{
|
||||
var currency = string.IsNullOrWhiteSpace(e.Currency) ? "?" : e.Currency.ToUpperInvariant();
|
||||
byCurrency.TryGetValue(currency, out var total);
|
||||
byCurrency[currency] = total + Math.Max(0, e.AmountMicros);
|
||||
}
|
||||
|
||||
return new SessionRewardSummary(
|
||||
inWindow.Count(e => e.Kind == ChatEventKind.SuperChat),
|
||||
inWindow.Count(e => e.Kind == ChatEventKind.SuperSticker),
|
||||
byCurrency,
|
||||
inWindow[0].PublishedAt,
|
||||
inWindow[^1].PublishedAt);
|
||||
}
|
||||
|
||||
/// <summary>Money lines for display, e.g. "USD $12.34 · EUR €4.00". Empty when there is nothing to
|
||||
/// show — a creator who never monetized must never be shown a zero.</summary>
|
||||
public IReadOnlyList<string> MoneyLines()
|
||||
=> MicrosByCurrency
|
||||
.Where(pair => pair.Value > 0)
|
||||
.OrderByDescending(pair => pair.Value)
|
||||
.Select(pair => $"{pair.Key} {Format(pair.Key, pair.Value)}")
|
||||
.ToList();
|
||||
|
||||
private static string Format(string currency, long micros)
|
||||
{
|
||||
var amount = micros / 1_000_000m;
|
||||
var symbol = currency switch
|
||||
{
|
||||
"USD" => "$",
|
||||
"EUR" => "€",
|
||||
"GBP" => "£",
|
||||
"CAD" => "CA$",
|
||||
"AUD" => "A$",
|
||||
_ => string.Empty,
|
||||
};
|
||||
return symbol.Length > 0
|
||||
? symbol + amount.ToString("0.00", CultureInfo.InvariantCulture)
|
||||
: amount.ToString("0.00", CultureInfo.InvariantCulture) + " " + currency;
|
||||
}
|
||||
}
|
||||
+171
-3
@@ -1,5 +1,6 @@
|
||||
using System.Windows.Media;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Services;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
@@ -110,6 +111,7 @@ public class Source : SceneElement
|
||||
Raise(nameof(IsTextOverlay));
|
||||
Raise(nameof(IsScoreboard));
|
||||
Raise(nameof(IsTicker));
|
||||
Raise(nameof(ShowsChromaKey));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,7 +120,8 @@ public class Source : SceneElement
|
||||
/// and sizes it in the preview, so it needs the same selection box, grab and resize handle
|
||||
/// (creator ruling 2026-11-01).</summary>
|
||||
public override bool IsDraggable => Type is SourceType.Image or SourceType.WebSource or SourceType.ChatBox
|
||||
or SourceType.TextOverlay or SourceType.AlertBox or SourceType.Blur or SourceType.Ticker;
|
||||
or SourceType.TextOverlay or SourceType.AlertBox or SourceType.Blur or SourceType.Ticker
|
||||
or SourceType.MediaSource;
|
||||
|
||||
/// <summary>Live captures, chat, web sources and media are dynamic; static art is fixed.</summary>
|
||||
public override ElementKind Kind => Type is SourceType.DisplayCapture or SourceType.WindowCapture
|
||||
@@ -238,9 +241,16 @@ public class Source : SceneElement
|
||||
set
|
||||
{
|
||||
if (Set(ref _mediaPath, value))
|
||||
{
|
||||
Raise(nameof(IsMediaSource));
|
||||
Raise(nameof(MediaFileDisplay));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The chosen file's name for the properties panel (path stays in the model).</summary>
|
||||
public string MediaFileDisplay =>
|
||||
string.IsNullOrWhiteSpace(_mediaPath) ? "No video chosen" : System.IO.Path.GetFileName(_mediaPath);
|
||||
|
||||
private bool _mediaIsLooping;
|
||||
public bool MediaIsLooping
|
||||
@@ -256,6 +266,31 @@ public class Source : SceneElement
|
||||
set => Set(ref _mediaVolume, Math.Clamp(value, 0.0, 1.0));
|
||||
}
|
||||
|
||||
private bool _mediaMuted;
|
||||
/// <summary>Silences this layer's soundtrack (the picture keeps playing). One decoder is
|
||||
/// shared per file, so the level/mute are the file's — the layer is the control.</summary>
|
||||
public bool MediaMuted
|
||||
{
|
||||
get => _mediaMuted;
|
||||
set => Set(ref _mediaMuted, value);
|
||||
}
|
||||
|
||||
private bool _isMediaRunning;
|
||||
/// <summary>True while the clip is decoding. False means it has played out and is holding its
|
||||
/// last frame — the panel then offers "Play again" instead of leaving a frozen picture with no
|
||||
/// explanation (the 2026-11-05 "clicking Loop did nothing" report).</summary>
|
||||
public bool IsMediaRunning
|
||||
{
|
||||
get => _isMediaRunning;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isMediaRunning, value)) Raise(nameof(IsMediaFinished));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsMediaFinished => !IsMediaRunning;
|
||||
|
||||
|
||||
private MediaPlaybackState _mediaPlaybackState = MediaPlaybackState.Stopped;
|
||||
public MediaPlaybackState MediaPlaybackState
|
||||
{
|
||||
@@ -265,6 +300,133 @@ public class Source : SceneElement
|
||||
|
||||
public override bool IsMediaSource => Type == SourceType.MediaSource;
|
||||
|
||||
// ── Green/Blue Screen keying (TASK 64) ────────────────────────────────────────────
|
||||
// Settings live on the LAYER. The decoder is keyed by (path + these settings), so two
|
||||
// layers with the same look share one decode and two different looks get two decoders.
|
||||
|
||||
private bool _chromaKeyEnabled;
|
||||
public bool ChromaKeyEnabled
|
||||
{
|
||||
get => _chromaKeyEnabled;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaKeyEnabled, value))
|
||||
{
|
||||
Raise(nameof(ChromaKey));
|
||||
Raise(nameof(HasChromaSuggestion));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string _chromaKeyColor = "#00B140";
|
||||
/// <summary>The screen colour as it was shot (the detector's median), not a canonical green.</summary>
|
||||
public string ChromaKeyColor
|
||||
{
|
||||
get => _chromaKeyColor;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaKeyColor, value)) Raise(nameof(ChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
private double _chromaKeySimilarity = 0.12;
|
||||
/// <summary>Creator-facing "Amount": how far from the key colour still counts as screen.</summary>
|
||||
public double ChromaKeySimilarity
|
||||
{
|
||||
get => _chromaKeySimilarity;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaKeySimilarity, Math.Clamp(value, 0, 0.5))) Raise(nameof(ChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
private double _chromaKeySoftness = 0.08;
|
||||
/// <summary>Creator-facing "Softness": the width of the fade at the keyed edge.</summary>
|
||||
public double ChromaKeySoftness
|
||||
{
|
||||
get => _chromaKeySoftness;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaKeySoftness, Math.Clamp(value, 0, 0.5))) Raise(nameof(ChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
private bool _chromaKeySpill = true;
|
||||
/// <summary>Creator-facing "Fringe": clean the coloured rim the screen leaves on hair and edges.</summary>
|
||||
public bool ChromaKeySpill
|
||||
{
|
||||
get => _chromaKeySpill;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaKeySpill, value)) Raise(nameof(ChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
private ChromaScreen _chromaScreen = ChromaScreen.Green;
|
||||
public ChromaScreen ChromaScreen
|
||||
{
|
||||
get => _chromaScreen;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaScreen, value)) Raise(nameof(ChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The look this layer asks its decoder for — the one place the settings become an
|
||||
/// ffmpeg chain and a session signature.</summary>
|
||||
public ChromaKeyOptions ChromaKey
|
||||
=> new(ChromaKeyEnabled, ChromaKeyColor, ChromaKeySimilarity, ChromaKeySoftness, ChromaKeySpill, ChromaScreen);
|
||||
|
||||
private ChromaKeySuggestion _chromaSuggestion;
|
||||
/// <summary>The detector's offer for this clip. Transient by design — never persisted, because
|
||||
/// it is a hint about a file, not a setting the creator made.</summary>
|
||||
public ChromaKeySuggestion ChromaSuggestion
|
||||
{
|
||||
get => _chromaSuggestion;
|
||||
set
|
||||
{
|
||||
_chromaSuggestion = value;
|
||||
Raise(nameof(ChromaSuggestion));
|
||||
Raise(nameof(HasChromaSuggestion));
|
||||
Raise(nameof(ChromaSuggestionText));
|
||||
Raise(nameof(HasChromaSuggestionColor));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while there is an offer the creator has not accepted.</summary>
|
||||
public bool HasChromaSuggestion => !ChromaKeyEnabled && ChromaSuggestion.Screen != ChromaScreen.None;
|
||||
|
||||
private bool _chromaKeyAutoApplied;
|
||||
/// <summary>True when the app applied the key on its own (the "Auto Green/Blue Screen"
|
||||
/// setting). The panel says so, so an automatic change is never silent.</summary>
|
||||
public bool ChromaKeyAutoApplied
|
||||
{
|
||||
get => _chromaKeyAutoApplied;
|
||||
set
|
||||
{
|
||||
if (Set(ref _chromaKeyAutoApplied, value)) Raise(nameof(HasAutoChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasAutoChromaKey => ChromaKeyAutoApplied && ChromaKeyEnabled;
|
||||
|
||||
/// <summary>Which layers get the Green/Blue Screen block: a video layer, or the alert box's
|
||||
/// own clip (TASK 64 — a clip is a clip).</summary>
|
||||
public bool ShowsChromaKey => IsMediaSource
|
||||
|| (Type == SourceType.AlertBox && !AlertUseDefaultVideo && !string.IsNullOrWhiteSpace(AlertVideoPath));
|
||||
|
||||
public string ChromaSuggestionText => ChromaSuggestion.Screen switch
|
||||
{
|
||||
ChromaScreen.Green => "Looks like a green screen.",
|
||||
ChromaScreen.Blue => "Looks like a blue screen.",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
/// <summary>The detected colour, for the swatch next to the offer.</summary>
|
||||
public string ChromaSuggestionColor => ChromaSuggestion.ColorHex ?? "#00B140";
|
||||
|
||||
public bool HasChromaSuggestionColor => ChromaSuggestion.ColorHex != null;
|
||||
|
||||
// Alert video config (TASK 47): the shipped default clip lives in the Asset
|
||||
// table (seeded like image assets); the creator's replacement is a FILE PATH
|
||||
// reference only — never into the DB (creator ruling, 2026-09-26). Runtime
|
||||
@@ -280,14 +442,20 @@ public class Source : SceneElement
|
||||
public string? AlertVideoPath
|
||||
{
|
||||
get => _alertVideoPath;
|
||||
set => Set(ref _alertVideoPath, value);
|
||||
set
|
||||
{
|
||||
if (Set(ref _alertVideoPath, value)) Raise(nameof(ShowsChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
private bool _alertUseDefaultVideo = true;
|
||||
public bool AlertUseDefaultVideo
|
||||
{
|
||||
get => _alertUseDefaultVideo;
|
||||
set => Set(ref _alertUseDefaultVideo, value);
|
||||
set
|
||||
{
|
||||
if (Set(ref _alertUseDefaultVideo, value)) Raise(nameof(ShowsChromaKey));
|
||||
}
|
||||
}
|
||||
|
||||
public bool AlertShowTicker
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
using System;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>Why the policy acted. Reported in the toast and the session report, so it is never
|
||||
/// guessed at again after the fact.</summary>
|
||||
public enum StepCause
|
||||
{
|
||||
None,
|
||||
/// <summary>The machine could not produce the frame: stalls, late renders, pump drops.</summary>
|
||||
Machine,
|
||||
/// <summary>The frames were produced but the sink could not take them: encoder drops.</summary>
|
||||
Upload,
|
||||
/// <summary>Both kinds of evidence in the same window — doing nothing is the only safe move.</summary>
|
||||
Ambiguous,
|
||||
}
|
||||
|
||||
public enum StepAction
|
||||
{
|
||||
None,
|
||||
/// <summary>Cheapest first: halve LlamaCasty's own capture cost, change nothing the viewer sees.</summary>
|
||||
ShedCaptureCadence,
|
||||
LowerFrameRate,
|
||||
LowerResolution,
|
||||
LowerBitrate,
|
||||
RaiseFrameRate,
|
||||
RaiseResolution,
|
||||
RaiseBitrate,
|
||||
}
|
||||
|
||||
/// <summary>One statistics window as the pump and the encoder report it. Nothing here is derived
|
||||
/// from the network directly: congestion shows up as frames the encoder failed to produce in
|
||||
/// wall-clock time, and backpressure shows up as submit wait.</summary>
|
||||
public readonly record struct StepDownSample(
|
||||
double WindowSeconds,
|
||||
int PumpStalls,
|
||||
int PumpDrops,
|
||||
int EncoderDrops,
|
||||
double AvgRenderMs,
|
||||
double AvgSubmitWaitMs);
|
||||
|
||||
/// <summary>The decision and the numbers behind it. <paramref name="Why"/> is for the log; the
|
||||
/// creator-facing sentence is built in the VM from <see cref="Cause"/>.</summary>
|
||||
public readonly record struct StepDownDecision(StepCause Cause, StepAction Action, string? Why)
|
||||
{
|
||||
public bool Acted => Action != StepAction.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decides when a session must give up quality, and why (TASK 33).
|
||||
///
|
||||
/// <para><b>Two levers, never mixed.</b> Machine starvation is answered with less work (60 → 30 fps,
|
||||
/// then 1080 → 720); upload congestion is answered with fewer bits, sized by the observed loss
|
||||
/// fraction. Resolution is never used as a bandwidth lever, because 1080p30 and 720p60 cost the same
|
||||
/// 6–8 Mbps: dropping pixels at an unchanged bitrate relieves nothing.</para>
|
||||
///
|
||||
/// <para><b>One-way by default.</b> A step-down that climbs back is an encoder restart, which is a
|
||||
/// visible hitch; the creator ruled that a show does not oscillate. The state machine still carries
|
||||
/// the ceiling, so enabling recovery later is a constructor flag rather than a rewrite.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class StepDownPolicy
|
||||
{
|
||||
/// <summary>Minimum evidence before acting: ~15 s of qualifying windows.</summary>
|
||||
internal const double QualifyingSeconds = 15.0;
|
||||
|
||||
/// <summary>A sample window shorter than this is ignored — the pump reports every 5 s.</summary>
|
||||
internal const double MinWindowSeconds = 4.0;
|
||||
|
||||
internal const double CooldownSeconds = 30.0;
|
||||
|
||||
/// <summary>Loss fraction at or above which the upload lever fires.</summary>
|
||||
internal const double UploadLossThreshold = 0.05;
|
||||
|
||||
/// <summary>Render time relative to the frame budget that counts as machine starvation.</summary>
|
||||
internal const double RenderBudgetFraction = 0.9;
|
||||
|
||||
internal const int StallThreshold = 5;
|
||||
|
||||
/// <summary>Clean seconds required before climbing when recovery is enabled.</summary>
|
||||
internal const double ClimbAfterCleanSeconds = 180.0;
|
||||
|
||||
/// <summary>A climb followed by a fall inside this window freezes the session at the low value.</summary>
|
||||
internal const double FlapWindowSeconds = 120.0;
|
||||
|
||||
private readonly bool _vertical;
|
||||
private readonly bool _allowClimb;
|
||||
private readonly int _ceilingFps;
|
||||
private readonly int _ceilingWidth;
|
||||
private readonly int _ceilingHeight;
|
||||
private readonly double _ceilingBitrateMbps;
|
||||
private readonly double _floorBitrateMbps;
|
||||
|
||||
private double _qualifyingSeconds;
|
||||
private double _cleanSeconds;
|
||||
private double _lastStepAt = double.NegativeInfinity;
|
||||
private double _lastRaiseAt = double.NegativeInfinity;
|
||||
private bool _frozen;
|
||||
private bool _shedCapture;
|
||||
|
||||
public StepDownPolicy(bool vertical, int startFps, double startBitrateMbps, bool allowClimb = false)
|
||||
: this(vertical ? 1080 : 1920, vertical ? 1920 : 1080, startFps, startBitrateMbps, allowClimb)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Explicit geometry: the tier the creator actually chose, which is what decides the
|
||||
/// step budget (a 1080 start gets three, a 720 start gets one).</summary>
|
||||
public StepDownPolicy(int startWidth, int startHeight, int startFps, double startBitrateMbps,
|
||||
bool allowClimb = false)
|
||||
{
|
||||
_vertical = startHeight > startWidth;
|
||||
_allowClimb = allowClimb;
|
||||
_ceilingFps = startFps;
|
||||
_ceilingWidth = startWidth;
|
||||
_ceilingHeight = startHeight;
|
||||
_ceilingBitrateMbps = startBitrateMbps;
|
||||
_floorBitrateMbps = _vertical ? 4.0 : 3.0;
|
||||
|
||||
Fps = startFps;
|
||||
Width = startWidth;
|
||||
Height = startHeight;
|
||||
BitrateMbps = startBitrateMbps;
|
||||
|
||||
// Creator ruling 2026-11-09: a 1080p start may spend three steps; 720 and vertical get one.
|
||||
StepsAllowed = startWidth >= 1920 ? 3 : 1;
|
||||
}
|
||||
|
||||
public int Fps { get; private set; }
|
||||
public int Width { get; private set; }
|
||||
public int Height { get; private set; }
|
||||
public double BitrateMbps { get; private set; }
|
||||
public int StepsUsed { get; private set; }
|
||||
public int StepsAllowed { get; }
|
||||
public bool Frozen => _frozen;
|
||||
/// <summary>True when no lever has anything left: 30 fps, the floor geometry, the floor bitrate.</summary>
|
||||
public bool AtFloor => Fps <= 30
|
||||
&& (_vertical || Width <= 1280)
|
||||
&& BitrateMbps <= _floorBitrateMbps + 0.001;
|
||||
|
||||
public double FrameBudgetMs => 1000.0 / Math.Max(1, Fps);
|
||||
|
||||
/// <summary>Classifies one window and, when the evidence is strong enough and the budget allows,
|
||||
/// applies exactly one change. <paramref name="elapsed"/> is time since the session started.</summary>
|
||||
public StepDownDecision Observe(in StepDownSample sample, TimeSpan elapsed)
|
||||
{
|
||||
if (sample.WindowSeconds < MinWindowSeconds) return new StepDownDecision(StepCause.None, StepAction.None, null);
|
||||
|
||||
var now = elapsed.TotalSeconds;
|
||||
var budget = FrameBudgetMs;
|
||||
|
||||
var machine = sample.PumpStalls >= StallThreshold
|
||||
|| sample.PumpDrops > 0
|
||||
|| sample.AvgRenderMs > budget * RenderBudgetFraction;
|
||||
|
||||
var loss = sample.EncoderDrops / Math.Max(1.0, Fps * sample.WindowSeconds);
|
||||
var upload = loss >= UploadLossThreshold;
|
||||
|
||||
if (machine && upload)
|
||||
{
|
||||
_qualifyingSeconds = 0;
|
||||
_cleanSeconds = 0;
|
||||
return new StepDownDecision(StepCause.Ambiguous, StepAction.None,
|
||||
$"render {sample.AvgRenderMs:0.0}ms, stalls {sample.PumpStalls}, loss {loss:P0} — not acting");
|
||||
}
|
||||
|
||||
if (!machine && !upload)
|
||||
{
|
||||
_qualifyingSeconds = 0;
|
||||
_cleanSeconds += sample.WindowSeconds;
|
||||
return TryClimb(sample, now);
|
||||
}
|
||||
|
||||
_cleanSeconds = 0;
|
||||
_qualifyingSeconds += sample.WindowSeconds;
|
||||
if (_qualifyingSeconds < QualifyingSeconds)
|
||||
return new StepDownDecision(machine ? StepCause.Machine : StepCause.Upload, StepAction.None, null);
|
||||
|
||||
if (now - _lastStepAt < CooldownSeconds)
|
||||
return new StepDownDecision(machine ? StepCause.Machine : StepCause.Upload, StepAction.None, "cooldown");
|
||||
|
||||
// Machine starvation: shed OUR cost before the viewer's tier is touched. Costs no step and is
|
||||
// not a quality change — if it does not fix the starvation, the fps ladder runs next window.
|
||||
if (machine && !_shedCapture)
|
||||
{
|
||||
_shedCapture = true;
|
||||
_qualifyingSeconds = 0;
|
||||
_lastStepAt = now;
|
||||
return new StepDownDecision(StepCause.Machine, StepAction.ShedCaptureCadence,
|
||||
"halving capture cost before lowering quality");
|
||||
}
|
||||
|
||||
if (StepsUsed >= StepsAllowed)
|
||||
return new StepDownDecision(machine ? StepCause.Machine : StepCause.Upload, StepAction.None,
|
||||
"step budget spent — holding");
|
||||
|
||||
var decision = machine ? StepMachine() : StepUpload(loss);
|
||||
if (!decision.Acted) return decision;
|
||||
|
||||
if (now - _lastRaiseAt < FlapWindowSeconds) _frozen = true;
|
||||
|
||||
StepsUsed++;
|
||||
_lastStepAt = now;
|
||||
_qualifyingSeconds = 0;
|
||||
return decision;
|
||||
}
|
||||
|
||||
private StepDownDecision StepMachine()
|
||||
{
|
||||
if (Fps > 30)
|
||||
{
|
||||
Fps = 30;
|
||||
return new StepDownDecision(StepCause.Machine, StepAction.LowerFrameRate,
|
||||
$"frame rate 60 → 30 to give the machine its time back");
|
||||
}
|
||||
|
||||
// The vertical tier's floor IS its only geometry (1080×1920), so it has no resolution step.
|
||||
if (!_vertical && (Width > 1280 || Height > 720))
|
||||
{
|
||||
Width = 1280;
|
||||
Height = 720;
|
||||
return new StepDownDecision(StepCause.Machine, StepAction.LowerResolution,
|
||||
$"resolution {Width}×{Height} — fewer pixels to composite");
|
||||
}
|
||||
|
||||
return new StepDownDecision(StepCause.Machine, StepAction.None, "at the machine floor — holding");
|
||||
}
|
||||
|
||||
private StepDownDecision StepUpload(double loss)
|
||||
{
|
||||
var reduction = Math.Max(0.5, BitrateMbps * loss);
|
||||
var next = Math.Max(_floorBitrateMbps, BitrateMbps - reduction);
|
||||
if (next >= BitrateMbps - 0.05)
|
||||
return new StepDownDecision(StepCause.Upload, StepAction.None, "at the bitrate floor — holding");
|
||||
|
||||
var from = BitrateMbps;
|
||||
BitrateMbps = Math.Round(next, 1);
|
||||
return new StepDownDecision(StepCause.Upload, StepAction.LowerBitrate,
|
||||
$"{from:0.0} → {BitrateMbps:0.0} Mbps on {loss:P0} loss");
|
||||
}
|
||||
|
||||
private StepDownDecision TryClimb(in StepDownSample sample, double now)
|
||||
{
|
||||
if (!_allowClimb || _frozen) return new StepDownDecision(StepCause.None, StepAction.None, null);
|
||||
if (StepsUsed == 0) return new StepDownDecision(StepCause.None, StepAction.None, null);
|
||||
if (_cleanSeconds < ClimbAfterCleanSeconds) return new StepDownDecision(StepCause.None, StepAction.None, null);
|
||||
if (now - _lastStepAt < CooldownSeconds) return new StepDownDecision(StepCause.None, StepAction.None, null);
|
||||
|
||||
var (action, caused) = RaiseOneStep();
|
||||
if (!caused) return new StepDownDecision(StepCause.None, StepAction.None, null);
|
||||
|
||||
StepsUsed = Math.Max(0, StepsUsed - 1);
|
||||
_lastRaiseAt = now;
|
||||
_lastStepAt = now;
|
||||
_cleanSeconds = 0;
|
||||
return new StepDownDecision(StepCause.None, action, "conditions clean — one step back up");
|
||||
}
|
||||
|
||||
private (StepAction Action, bool Changed) RaiseOneStep()
|
||||
{
|
||||
if (Fps < _ceilingFps)
|
||||
{
|
||||
Fps = _ceilingFps;
|
||||
return (StepAction.RaiseFrameRate, true);
|
||||
}
|
||||
|
||||
if (Width < _ceilingWidth || Height < _ceilingHeight)
|
||||
{
|
||||
Width = _ceilingWidth;
|
||||
Height = _ceilingHeight;
|
||||
return (StepAction.RaiseResolution, true);
|
||||
}
|
||||
|
||||
if (BitrateMbps < _ceilingBitrateMbps - 0.05)
|
||||
{
|
||||
BitrateMbps = Math.Round(Math.Min(_ceilingBitrateMbps, BitrateMbps + 1.0), 1);
|
||||
return (StepAction.RaiseBitrate, true);
|
||||
}
|
||||
|
||||
return (StepAction.None, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 39·2: the three metrics that count towards YouTube Partner Program eligibility, as progress
|
||||
/// towards the ad-revenue thresholds.
|
||||
/// <para><b>YouTube decides.</b> This only reports what the published numbers say; it never claims
|
||||
/// eligibility, and it cannot see strikes, AdSense state, 2FA or the review decision.</para>
|
||||
/// <para><b>The view criteria are either/or</b> — 4,000 public watch hours <i>or</i> 10M Shorts views —
|
||||
/// so "2 of 3" is reported with that qualifier rather than implying all three must pass.</para>
|
||||
/// </summary>
|
||||
public sealed record YppProgress(
|
||||
long Subscribers,
|
||||
long SubscriberTarget,
|
||||
long WatchHours,
|
||||
long WatchHoursTarget,
|
||||
long ShortsViews,
|
||||
long ShortsViewsTarget)
|
||||
{
|
||||
public bool SubscribersMet => Subscribers >= SubscriberTarget;
|
||||
public bool WatchHoursMet => WatchHours >= WatchHoursTarget;
|
||||
public bool ShortsViewsMet => ShortsViews >= ShortsViewsTarget;
|
||||
|
||||
/// <summary>Criteria currently met (0–3). Two of three can mean eligible: subs plus EITHER view route.</summary>
|
||||
public int CriteriaMet => (SubscribersMet ? 1 : 0) + (WatchHoursMet ? 1 : 0) + (ShortsViewsMet ? 1 : 0);
|
||||
|
||||
/// <summary>True when the subscriber bar AND at least one view route are satisfied — the shape of the
|
||||
/// published rule. Still not a qualification claim: YouTube reviews it.</summary>
|
||||
public bool MeetsPublishedRule => SubscribersMet && (WatchHoursMet || ShortsViewsMet);
|
||||
|
||||
public double SubscribersFraction => Fraction(Subscribers, SubscriberTarget);
|
||||
public double WatchHoursFraction => Fraction(WatchHours, WatchHoursTarget);
|
||||
public double ShortsViewsFraction => Fraction(ShortsViews, ShortsViewsTarget);
|
||||
|
||||
public string SubscribersText => $"{Compact(Subscribers)} / {Compact(SubscriberTarget)}";
|
||||
public string WatchHoursText => $"{Compact(WatchHours)} / {Compact(WatchHoursTarget)} h";
|
||||
public string ShortsViewsText => $"{Compact(ShortsViews)} / {Compact(ShortsViewsTarget)}";
|
||||
|
||||
public string CriteriaMetText => CriteriaMet == 1
|
||||
? "1 of 3 criteria met — YouTube reviews eligibility."
|
||||
: $"{CriteriaMet} of 3 criteria met — YouTube reviews eligibility.";
|
||||
|
||||
private static double Fraction(long value, long target)
|
||||
=> target <= 0 ? 0 : Math.Clamp((double)value / target, 0, 1);
|
||||
|
||||
/// <summary>1,234 → "1,234"; 12,345 → "12.3k"; 1,234,567 → "1.23M". Mono-face friendly and stable
|
||||
/// in width, so the three bars do not jitter as values move.</summary>
|
||||
internal static string Compact(long value) => value switch
|
||||
{
|
||||
>= 1_000_000 => (value / 1_000_000d).ToString("0.##", CultureInfo.InvariantCulture) + "M",
|
||||
>= 10_000 => (value / 1_000d).ToString("0.#", CultureInfo.InvariantCulture) + "k",
|
||||
_ => value.ToString("N0", CultureInfo.InvariantCulture),
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,10 @@ public static class YppThresholds
|
||||
/// <summary>The date the Tier-2 ad-revenue bars double for new applicants.</summary>
|
||||
public static readonly DateTime Tier2DoublingDate = new(2027, 2, 1);
|
||||
|
||||
/// <summary>When these thresholds were last read from YouTube's published requirements. Shown in the
|
||||
/// drawer and asserted by a test, because YouTube moves the bar and a stale bar must not look current.</summary>
|
||||
public static readonly DateTime AsOfUtc = new(2026, 11, 5);
|
||||
|
||||
/// <summary>Fan-funding tier (before the full ad/YouTube Premium revenue tier).</summary>
|
||||
public static TierThreshold Tier1 { get; } = new("Fan funding", 500, 3_000, 3_000_000);
|
||||
|
||||
|
||||
+19
-177
@@ -1,6 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using ytLive.Helpers;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using ytLive.Services.Audio;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
@@ -11,10 +10,10 @@ namespace ytLive.Services;
|
||||
/// same file, both paced to real time. The alert box owns a decoder per event
|
||||
/// (start at play, dispose at drain) — unlike MediaSource's app-wide refcounted
|
||||
/// session, an alert REPLAYS the same clip each event, so a fresh decode per
|
||||
/// play is required. Video is rawvideo BGRA scaled to the box rect (the
|
||||
/// <see cref="MediaVideoSource"/> shape); audio is ffmpeg <c>f32le</c> at the
|
||||
/// mixer's native 48 kHz stereo (so the mixer ring needs no resampler). The
|
||||
/// fade is applied by the alert layer, not here.
|
||||
/// play is required. The fade is applied by the alert layer, not here.
|
||||
/// <para>Since TASK 21's audio slice this is a thin wrapper over the shared
|
||||
/// <see cref="VideoClipPipe"/> (the same pipe a media layer uses); the alert case
|
||||
/// simply never sets <c>Looping</c>.</para>
|
||||
/// </summary>
|
||||
public interface IAlertClipDecoder : IDisposable
|
||||
{
|
||||
@@ -35,30 +34,14 @@ public interface IAlertClipDecoder : IDisposable
|
||||
event Action? Completed;
|
||||
}
|
||||
|
||||
/// <summary>Default <see cref="IAlertClipDecoder"/>: two ffmpeg subprocesses on
|
||||
/// the same file. Video via <see cref="RawVideoFrameReader"/> on a <c>rawvideo
|
||||
/// bgra</c> pipe (-an), audio via an <c>f32le -ac 2 -ar 48000</c> pipe (-vn).
|
||||
/// The seams (locator, process factory, frame-rate probe, delay) let tests drive
|
||||
/// a fake decoder without a real codec or Windows.</summary>
|
||||
/// <summary>Default <see cref="IAlertClipDecoder"/>: the shared clip pipe with looping off.</summary>
|
||||
public sealed class AlertClipDecoder : IAlertClipDecoder
|
||||
{
|
||||
public event Action<VideoFrame>? FrameAvailable;
|
||||
public event Action<AudioSample>? AudioReady;
|
||||
public event Action? Completed;
|
||||
|
||||
private const int AudioSampleRate = 48000;
|
||||
private const int AudioChannels = 2;
|
||||
private const int AudioChunkFloats = 4800; // 50ms of stereo
|
||||
|
||||
private readonly string _path;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
private readonly IFfmpegLocator _locator;
|
||||
private readonly Func<IDecodeProcess> _processFactory;
|
||||
private readonly IFrameRateProbe? _probe;
|
||||
private readonly Func<TimeSpan, CancellationToken, Task> _delay;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private Task? _run;
|
||||
private readonly VideoClipPipe _clip;
|
||||
|
||||
public AlertClipDecoder(
|
||||
string path,
|
||||
@@ -67,161 +50,20 @@ public sealed class AlertClipDecoder : IAlertClipDecoder
|
||||
IFfmpegLocator locator,
|
||||
Func<IDecodeProcess> processFactory,
|
||||
IFrameRateProbe? frameRateProbe = null,
|
||||
Func<TimeSpan, CancellationToken, Task>? delay = null)
|
||||
Func<TimeSpan, CancellationToken, Task>? delay = null,
|
||||
ChromaKeyOptions? chromaKey = null)
|
||||
{
|
||||
_path = path;
|
||||
_width = width;
|
||||
_height = height;
|
||||
_locator = locator;
|
||||
_processFactory = processFactory;
|
||||
_probe = frameRateProbe;
|
||||
_delay = delay ?? ((t, ct) => Task.Delay(t, ct));
|
||||
_clip = new VideoClipPipe(
|
||||
path, width, height, locator, processFactory, frameRateProbe, delay,
|
||||
audio: true, chromaKey: chromaKey);
|
||||
_clip.FrameAvailable += frame => FrameAvailable?.Invoke(frame);
|
||||
_clip.AudioAvailable += sample => AudioReady?.Invoke(sample);
|
||||
_clip.Completed += () => Completed?.Invoke();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_run != null) return;
|
||||
_run = Task.Run(RunAsync, CancellationToken.None);
|
||||
}
|
||||
public void Start() => _ = _clip.StartAsync();
|
||||
|
||||
public void Stop() => _cts.Cancel();
|
||||
public void Stop() => _ = _clip.StopAsync();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
var ct = _cts.Token;
|
||||
var videoFrames = 0;
|
||||
var audioChunks = 0;
|
||||
var failed = false;
|
||||
try
|
||||
{
|
||||
double? frameRate = null;
|
||||
if (_probe != null)
|
||||
frameRate = await _probe.ProbeAsync(_path, ct).ConfigureAwait(false);
|
||||
var frameDuration = frameRate is > 0 ? TimeSpan.FromSeconds(1.0 / frameRate.Value) : TimeSpan.Zero;
|
||||
|
||||
var ffmpegPath = await _locator.LocateAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var videoTask = RunVideoAsync(ffmpegPath, frameDuration, ct);
|
||||
var audioTask = RunAudioAsync(ffmpegPath, ct);
|
||||
videoFrames = await videoTask.ConfigureAwait(false);
|
||||
audioChunks = await audioTask.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
failed = true;
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A failed decode is not fatal: the alert layer falls back to the six
|
||||
// animations (or the frame it already holds) exactly as a missing file.
|
||||
// Logged so a silent blank box traces back to a decode failure.
|
||||
failed = true;
|
||||
AppLog.Write(ex, $"Alert clip decode failed ({Path.GetFileName(_path)})", AppLogErrorClass.Class2);
|
||||
}
|
||||
|
||||
if (!ct.IsCancellationRequested)
|
||||
{
|
||||
AppLog.Write($"Alert clip end: {Path.GetFileName(_path)} frames={videoFrames} audioChunks={audioChunks} failed={failed}");
|
||||
Completed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> RunVideoAsync(string ffmpegPath, TimeSpan frameDuration, CancellationToken ct)
|
||||
{
|
||||
var args =
|
||||
$"-hide_banner -loglevel error -i \"{_path}\" " +
|
||||
$"-f rawvideo -pix_fmt bgra -vf scale={_width}:{_height} -an -";
|
||||
using var process = _processFactory();
|
||||
process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpegPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true,
|
||||
});
|
||||
|
||||
var reader = new RawVideoFrameReader(_width, _height);
|
||||
var buffer = new byte[65536];
|
||||
var stream = process.StandardOutput;
|
||||
var frames = 0;
|
||||
while (!ct.IsCancellationRequested && !process.HasExited)
|
||||
{
|
||||
var read = await stream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
|
||||
if (read <= 0) break;
|
||||
var chunk = new byte[read];
|
||||
Buffer.BlockCopy(buffer, 0, chunk, 0, read);
|
||||
foreach (var frame in reader.Feed(chunk))
|
||||
{
|
||||
frames++;
|
||||
FrameAvailable?.Invoke(frame);
|
||||
if (frameDuration > TimeSpan.Zero)
|
||||
await _delay(frameDuration, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
private async Task<int> RunAudioAsync(string ffmpegPath, CancellationToken ct)
|
||||
{
|
||||
var args =
|
||||
$"-hide_banner -loglevel error -i \"{_path}\" " +
|
||||
$"-f f32le -ac {AudioChannels} -ar {AudioSampleRate} -vn -";
|
||||
using var process = _processFactory();
|
||||
process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpegPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true,
|
||||
});
|
||||
|
||||
var stream = process.StandardOutput;
|
||||
var raw = new byte[65536];
|
||||
var carry = new byte[0];
|
||||
var floatScratch = new float[AudioChunkFloats];
|
||||
var floatIndex = 0;
|
||||
var chunks = 0;
|
||||
// The pipe is byte-delimited only: a read may split a float, so leftover
|
||||
// bytes are carried into the next read instead of dropped (a dropped
|
||||
// half-float would desync the entire stream).
|
||||
while (!ct.IsCancellationRequested && !process.HasExited)
|
||||
{
|
||||
var read = await stream.ReadAsync(raw, 0, raw.Length, ct).ConfigureAwait(false);
|
||||
if (read <= 0) break;
|
||||
var total = carry.Length + read;
|
||||
var bytes = total <= raw.Length ? raw : new byte[total];
|
||||
if (carry.Length > 0)
|
||||
{
|
||||
Buffer.BlockCopy(carry, 0, bytes, 0, carry.Length);
|
||||
Buffer.BlockCopy(raw, 0, bytes, carry.Length, read);
|
||||
}
|
||||
var floatsTo = total - (total % 4);
|
||||
for (var i = 0; i < floatsTo && floatIndex < floatScratch.Length; i += 4)
|
||||
floatScratch[floatIndex++] = BitConverter.ToSingle(bytes, i);
|
||||
carry = total > floatsTo ? bytes[floatsTo..total] : new byte[0];
|
||||
|
||||
while (floatIndex == floatScratch.Length)
|
||||
{
|
||||
chunks++;
|
||||
AudioReady?.Invoke(new AudioSample(floatScratch, AudioSampleRate, AudioChannels));
|
||||
// Pace the NEXT chunk so the whole clip's audio lands at real-time
|
||||
// cadence (the fade in the alert layer tracks the same wall clock).
|
||||
await _delay(TimeSpan.FromSeconds(AudioChunkFloats / (double)(AudioSampleRate * AudioChannels)), ct).ConfigureAwait(false);
|
||||
floatScratch = new float[AudioChunkFloats];
|
||||
floatIndex = 0;
|
||||
}
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
public void Dispose() => _clip.Dispose();
|
||||
}
|
||||
|
||||
@@ -283,6 +283,25 @@ public sealed class AudioMixer : IDisposable
|
||||
LoopbackLevelChanged?.Invoke(level);
|
||||
}
|
||||
|
||||
/// <summary>Drops a MEDIA clip's audio into the desktop/game ring (TASK 21's audio slice).
|
||||
/// It joins that group on purpose: the desktop fader and the mic auto-ducker then apply
|
||||
/// exactly as they do to game audio and TRAX, so a BRB bed ducks under the creator's
|
||||
/// voice without a second audio knob. The layer's own level/mute are applied upstream
|
||||
/// by <see cref="MediaVideoSourceManager"/>.</summary>
|
||||
public void EnqueueDesktopMediaAudio(AudioSample sample)
|
||||
{
|
||||
var data = sample.Samples;
|
||||
if (data.Length == 0) return;
|
||||
if (sample.SampleRate != OutputSampleRate)
|
||||
data = ResampleLoopback(data, sample.SampleRate);
|
||||
if (sample.Channels == 1)
|
||||
data = UpmixToStereo(data);
|
||||
_loopbackBuffer.Write(data);
|
||||
|
||||
var level = _loopbackMeter.Push(new AudioSample(data, OutputSampleRate, sample.Channels));
|
||||
LoopbackLevelChanged?.Invoke(level);
|
||||
}
|
||||
|
||||
/// <summary>Drops the alert clip's audio into its own ring (TASK 47 — the
|
||||
/// stream-alert video's soundtrack, pre-scaled by the alert layer to
|
||||
/// volume × fade). Mixed at unity into the live output — NO auto-duck: an
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·3 — naming the broadcast that resumes a dropped show. A resumed stream is a NEW broadcast
|
||||
/// with a new VOD (YouTube cannot resume a completed one), so the title has to say so; otherwise the
|
||||
/// channel grows two identically named videos and the creator has to explain it.
|
||||
/// <para>Pure, because the interesting cases are the boring ones: a title already marked, a second drop
|
||||
/// in the same session, and YouTube's 100-character limit.</para>
|
||||
/// </summary>
|
||||
public static class BroadcastTitle
|
||||
{
|
||||
public const int MaxLength = 100;
|
||||
|
||||
private static readonly Regex ResumeMarker =
|
||||
new(@"\s*\(resumed(?: \d+)?\)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
/// <summary>The title for resume number <paramref name="resumeCount"/> (1 = first re-air).
|
||||
/// Any existing marker is replaced rather than stacked, and the base is truncated so the whole
|
||||
/// title fits YouTube's limit.</summary>
|
||||
public static string ForResume(string? title, int resumeCount)
|
||||
{
|
||||
var baseTitle = ResumeMarker.Replace(title ?? string.Empty, string.Empty).Trim();
|
||||
if (baseTitle.Length == 0) baseTitle = "LlamaCasty";
|
||||
|
||||
var marker = resumeCount <= 1 ? " (resumed)" : $" (resumed {Math.Max(2, resumeCount)})";
|
||||
var room = MaxLength - marker.Length;
|
||||
if (baseTitle.Length > room) baseTitle = baseTitle[..room].TrimEnd();
|
||||
return baseTitle + marker;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>What a clip's background looks like, as far as keying goes.</summary>
|
||||
public enum ChromaScreen
|
||||
{
|
||||
/// <summary>No usable backdrop — say nothing to the creator.</summary>
|
||||
None,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TASK 64: "this clip was shot against a green screen". <c>Coverage</c> × <c>Tightness</c>:
|
||||
/// how much of the frame is the colour, and how consistent that colour is. A painted screen
|
||||
/// scores near 1; a lawn or a football pitch scores low because the greens disagree.
|
||||
/// </summary>
|
||||
public readonly record struct ChromaKeySuggestion(
|
||||
ChromaScreen Screen,
|
||||
string? ColorHex,
|
||||
double Confidence)
|
||||
{
|
||||
/// <summary>The screen is uniform enough to key without the creator touching a slider.</summary>
|
||||
public bool IsHighConfidence => Screen != ChromaScreen.None && Confidence >= HighConfidenceFloor;
|
||||
|
||||
public const double HighConfidenceFloor = 0.85;
|
||||
public const double SuggestFloor = 0.65;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TASK 64: finds a green or blue screen in a decoded frame — the "clueless creator" half of
|
||||
/// the feature. Pure and allocation-light (it only samples an outer ring and a coarse grid), so
|
||||
/// it runs on the probe frame without touching ffmpeg twice.
|
||||
/// <para><b>It never decides anything.</b> A suggestion is offered to the creator; auto-apply is
|
||||
/// an explicit setting and only fires at <see cref="ChromaKeySuggestion.IsHighConfidence"/>.
|
||||
/// Wrongly keying a lawn is destructive, so "None" is a normal, expected answer.</para>
|
||||
/// </summary>
|
||||
public static class ChromaKeyDetector
|
||||
{
|
||||
// Hue windows in degrees. Green sits 75–165 (a real screen reads ~120–145), blue 185–265.
|
||||
private const double GreenHueFrom = 75, GreenHueTo = 165;
|
||||
private const double BlueHueFrom = 185, BlueHueTo = 265;
|
||||
|
||||
// A screen is saturated and not dark. These also exclude letterbox bars (near-black,
|
||||
// no saturation) and blown-out highlights from the denominator, so black bars do not
|
||||
// count against an otherwise perfect screen.
|
||||
private const double MinSaturation = 0.35;
|
||||
private const double MinValue = 0.15;
|
||||
|
||||
// No upper brightness bound ON PURPOSE (found on a real clip 2026-11-05): a clean painted
|
||||
// screen is fully saturated, so its value sits at ~1.0 and a 0.98 ceiling rejected the
|
||||
// greenest possible screen. White highlights are excluded by the SATURATION floor instead,
|
||||
// which is the property that actually separates them from a screen.
|
||||
|
||||
// The screen's own pixels must agree with each other: a painted surface is flat, a lawn
|
||||
// is not. This is what keeps "green field" from being keyed.
|
||||
private const double HueTightness = 12.0;
|
||||
|
||||
/// <summary>Samples an outer ring (the subject sits in the middle, the screen fills the
|
||||
/// edges) and reports what it saw.</summary>
|
||||
public static ChromaKeySuggestion Detect(VideoFrame frame)
|
||||
{
|
||||
if (frame.Width < 8 || frame.Height < 8) return Empty;
|
||||
|
||||
var ring = Math.Max(2, (int)Math.Round(Math.Min(frame.Width, frame.Height) * 0.15));
|
||||
var step = Math.Max(1, Math.Min(frame.Width, frame.Height) / 96);
|
||||
|
||||
var hues = new List<double>();
|
||||
var sameHue = 0;
|
||||
double hueSum = 0;
|
||||
long rSum = 0, gSum = 0, bSum = 0;
|
||||
var considered = 0;
|
||||
var green = 0;
|
||||
var blue = 0;
|
||||
|
||||
for (var y = 0; y < frame.Height; y += step)
|
||||
{
|
||||
var inVerticalRing = y < ring || y >= frame.Height - ring;
|
||||
for (var x = 0; x < frame.Width; x += step)
|
||||
{
|
||||
if (!inVerticalRing && x >= ring && x < frame.Width - ring) continue;
|
||||
|
||||
var i = y * frame.Stride + x * 4;
|
||||
var b = frame.BgraPixels[i];
|
||||
var g = frame.BgraPixels[i + 1];
|
||||
var r = frame.BgraPixels[i + 2];
|
||||
if (frame.BgraPixels[i + 3] < 8) continue; // transparent: not the backdrop
|
||||
|
||||
var (hue, saturation, value) = ToHsv(r, g, b);
|
||||
if (saturation < MinSaturation || value < MinValue) continue;
|
||||
|
||||
considered++;
|
||||
if (hue is >= GreenHueFrom and <= GreenHueTo) green++;
|
||||
else if (hue is >= BlueHueFrom and <= BlueHueTo) blue++;
|
||||
else continue;
|
||||
|
||||
hues.Add(hue);
|
||||
hueSum += hue;
|
||||
rSum += r;
|
||||
gSum += g;
|
||||
bSum += b;
|
||||
}
|
||||
}
|
||||
|
||||
if (considered < 64) return Empty;
|
||||
|
||||
var screen = green >= blue
|
||||
? (green == 0 ? ChromaScreen.None : ChromaScreen.Green)
|
||||
: ChromaScreen.Blue;
|
||||
if (screen == ChromaScreen.None) return Empty;
|
||||
|
||||
var accepted = hues.Count;
|
||||
var coverage = (double)accepted / considered;
|
||||
|
||||
// Tint stability: how many of the accepted pixels sit within ±HueTightness of the
|
||||
// median hue. A painted screen ≈ 1.0; grass, foliage and sunlight ≈ far less.
|
||||
hues.Sort();
|
||||
var median = hues[hues.Count / 2];
|
||||
foreach (var hue in hues)
|
||||
{
|
||||
var delta = Math.Abs(hue - median);
|
||||
if (delta > 180) delta = 360 - delta;
|
||||
if (delta <= HueTightness) sameHue++;
|
||||
}
|
||||
var tightness = (double)sameHue / accepted;
|
||||
|
||||
var confidence = coverage * tightness;
|
||||
if (confidence < ChromaKeySuggestion.SuggestFloor) return Empty;
|
||||
|
||||
// The keyed colour is the screen as it was actually shot, not a canonical green:
|
||||
// similarity is a distance, so the median of the sampled pixels keys far better.
|
||||
var keyed = Math.Max(1, accepted);
|
||||
var color = $"#{rSum / keyed:X2}{gSum / keyed:X2}{bSum / keyed:X2}";
|
||||
return new ChromaKeySuggestion(screen, color, confidence);
|
||||
}
|
||||
|
||||
private static readonly ChromaKeySuggestion Empty = new(ChromaScreen.None, null, 0);
|
||||
|
||||
private static (double Hue, double Saturation, double Value) ToHsv(byte r, byte g, byte b)
|
||||
{
|
||||
var rf = r / 255.0;
|
||||
var gf = g / 255.0;
|
||||
var bf = b / 255.0;
|
||||
var max = Math.Max(rf, Math.Max(gf, bf));
|
||||
var min = Math.Min(rf, Math.Min(gf, bf));
|
||||
var delta = max - min;
|
||||
|
||||
double hue = 0;
|
||||
if (delta > 1e-6)
|
||||
{
|
||||
if (max == rf) hue = 60 * (((gf - bf) / delta) % 6);
|
||||
else if (max == gf) hue = 60 * (((bf - rf) / delta) + 2);
|
||||
else hue = 60 * (((rf - gf) / delta) + 4);
|
||||
}
|
||||
if (hue < 0) hue += 360;
|
||||
|
||||
var saturation = max <= 0 ? 0 : delta / max;
|
||||
return (hue, saturation, max);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 64: reads ONE frame out of a video file so the app can look at its background before
|
||||
/// the creator says anything. Kept behind an interface so tests never spawn ffmpeg, and separate
|
||||
/// from the decode pipe because this is a read, not a playback session.
|
||||
/// </summary>
|
||||
public interface IChromaProbe
|
||||
{
|
||||
/// <summary>The file's first usable frame at a small size, or null when it cannot be read
|
||||
/// (bad path, unsupported file, ffmpeg gave nothing). Null is a normal answer: the layer
|
||||
/// simply gets no suggestion.</summary>
|
||||
Task<VideoFrame?> ProbeAsync(string path, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Default <see cref="IChromaProbe"/>: one ffmpeg pass, scaled to 160×90 so the look is
|
||||
/// cheap and the detector sees plenty of the backdrop.</summary>
|
||||
public sealed class FfmpegChromaProbe : IChromaProbe
|
||||
{
|
||||
private const int ProbeWidth = 160;
|
||||
private const int ProbeHeight = 90;
|
||||
|
||||
private readonly IFfmpegLocator _locator;
|
||||
private readonly Func<IDecodeProcess> _processFactory;
|
||||
|
||||
public FfmpegChromaProbe(IFfmpegLocator locator, Func<IDecodeProcess> processFactory)
|
||||
{
|
||||
_locator = locator;
|
||||
_processFactory = processFactory;
|
||||
}
|
||||
|
||||
public async Task<VideoFrame?> ProbeAsync(string path, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return null;
|
||||
try
|
||||
{
|
||||
var ffmpegPath = await _locator.LocateAsync(cancellationToken).ConfigureAwait(false);
|
||||
var args =
|
||||
$"-hide_banner -loglevel error -i \"{path}\" -frames:v 1 -an " +
|
||||
$"-f rawvideo -pix_fmt bgra -vf scale={ProbeWidth}:{ProbeHeight} -";
|
||||
|
||||
using var process = _processFactory();
|
||||
process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpegPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true,
|
||||
});
|
||||
|
||||
var frames = await Task.Run(() =>
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
process.StandardOutput.CopyTo(buffer);
|
||||
var reader = new RawVideoFrameReader(ProbeWidth, ProbeHeight);
|
||||
var fed = reader.Feed(buffer.ToArray());
|
||||
return fed;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return frames.Count > 0 ? frames[0] : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Helpers.AppLog.Write($"ChromaProbe: '{Path.GetFileName(path)}' unreadable: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,12 @@ public static class FfmpegArgs
|
||||
AddVideoTags(args, options, videoEncoder);
|
||||
args.AddRange(["-c:a", "aac",
|
||||
"-ar", options.AudioSampleRate.ToString(), "-ac", options.AudioChannels.ToString()]);
|
||||
// TASK 32·4: FRAGMENTED mp4. A plain MP4 writes its index (moov) at the end, so a
|
||||
// power cut or a killed process leaves the video bytes on disk in a file nothing can
|
||||
// open — the whole recording, not the tail. Fragmented writes the index first and
|
||||
// flushes a playable fragment at every keyframe, so an interrupted file still plays up
|
||||
// to the last fragment. Record block only: the FLV stream output has no index.
|
||||
args.AddRange(["-movflags", "+frag_keyframe+empty_moov+default_base_moof"]);
|
||||
args.AddRange(["-f", "mp4", options.RecordPath!]);
|
||||
}
|
||||
|
||||
|
||||
@@ -129,6 +129,14 @@ public sealed class FramePump : IDisposable
|
||||
/// <summary>Raised when the encoder cannot start or dies mid-stream. The pump stops itself.</summary>
|
||||
public event EventHandler<string>? Failed;
|
||||
|
||||
/// <summary>TASK 32·1: the ENCODER died (the push dropped) — recoverable, unlike a compositor fault.
|
||||
/// Raised before the pump stops, so the session can relaunch the push instead of ending.</summary>
|
||||
public event EventHandler<string>? EncoderFailed;
|
||||
|
||||
/// <summary>TASK 33: the same 5-second window the stats line reports, structured — so a policy can
|
||||
/// tell machine starvation from encoder backpressure without parsing prose.</summary>
|
||||
public event EventHandler<FramePumpStats>? StatsReported;
|
||||
|
||||
public FramePump(
|
||||
Func<Scene?> sceneProvider,
|
||||
Func<SceneElement, VideoFrame?> frameResolver,
|
||||
@@ -240,6 +248,21 @@ public sealed class FramePump : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>TASK 33: relaunch the pump and encoder at a new tier, over the same URL and audio pipe.
|
||||
///
|
||||
/// <para>Full stop + start rather than an encoder swap, deliberately: <see cref="StopAsync"/> awaits
|
||||
/// the loop and flushes the encoder, so no in-flight submit can land on a disposed process. A bare
|
||||
/// swap races exactly that and would fault the loop — which ends the broadcast, the one thing a
|
||||
/// quality step-down must never do. The cost is a short freeze, already accepted by the ladder.</para>
|
||||
/// </summary>
|
||||
public async Task<bool> ChangeEncoderAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await StopAsync(cancellationToken);
|
||||
if (cancellationToken.IsCancellationRequested) return false;
|
||||
await StartAsync(cancellationToken);
|
||||
return IsRunning;
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
IFfmpegEncoder? encoder;
|
||||
@@ -422,6 +445,21 @@ public sealed class FramePump : IDisposable
|
||||
_log?.Invoke($"FramePump parts ({statRenders} renders/5s): {parts}");
|
||||
_timings.Reset();
|
||||
|
||||
// Structured twin of the line above, raised before the counters reset. `dropped` is the
|
||||
// ENCODER's count (ffmpeg blocked); a renderer that duplicates frames is already visible
|
||||
// as render time + stalls, and FramesRendered is ambiguous by design (paste cache).
|
||||
StatsReported?.Invoke(this, new FramePumpStats(
|
||||
WindowSeconds: 5,
|
||||
FramesSubmitted: statFrames,
|
||||
FramesRendered: statRenders,
|
||||
AvgRenderMs: statRenders > 0 ? renderTicks / freq * 1000 / statRenders : 0,
|
||||
AvgSubmitMs: statFrames > 0 ? submitTicks / freq * 1000 / statFrames : 0,
|
||||
AvgWaitMs: statRenders > 0 ? waitTicks / freq * 1000 / statRenders : 0,
|
||||
WorstRenderMs: worstRender / freq * 1000,
|
||||
WorstSubmitMs: worstSubmit / freq * 1000,
|
||||
Dropped: dropped,
|
||||
Stalls: stalls));
|
||||
|
||||
worstRender = 0;
|
||||
worstSubmit = 0;
|
||||
renderTicks = submitTicks = resolveTicks = waitTicks = 0;
|
||||
@@ -969,7 +1007,9 @@ public sealed class FramePump : IDisposable
|
||||
private void OnProcessFailed(object? sender, string message)
|
||||
{
|
||||
_log?.Invoke($"FramePump: encoder process failed: {message}");
|
||||
Failed?.Invoke(this, message);
|
||||
// A dead push is not a dead session: the broadcast may still be live, so this is the
|
||||
// recoverable signal (TASK 32·1). Fatal pump faults still go through Failed.
|
||||
EncoderFailed?.Invoke(this, message);
|
||||
_ = StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace ytLive.Services.Encoder;
|
||||
|
||||
/// <summary>One 5-second window of pump and encoder evidence, structured.
|
||||
///
|
||||
/// <para>The stats line in the log is for humans; this is for the policy that has to decide whether
|
||||
/// the machine or the connection is the problem. Note which counter is which:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="Stalls"/> and <see cref="AvgRenderMs"/> are the MACHINE's evidence — the pump
|
||||
/// could not produce a frame in time.</item>
|
||||
/// <item><see cref="Dropped"/> is the ENCODER's — frames submitted but not accepted downstream. It
|
||||
/// rises when ffmpeg is blocked, which under CBR means the socket, not the renderer.</item>
|
||||
/// <item><see cref="FramesRendered"/> is deliberately NOT used for classification: a static scene
|
||||
/// legitimately reuses the paste cache and renders few frames while completely healthy.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public readonly record struct FramePumpStats(
|
||||
double WindowSeconds,
|
||||
int FramesSubmitted,
|
||||
int FramesRendered,
|
||||
double AvgRenderMs,
|
||||
double AvgSubmitMs,
|
||||
double AvgWaitMs,
|
||||
double WorstRenderMs,
|
||||
double WorstSubmitMs,
|
||||
int Dropped,
|
||||
int Stalls);
|
||||
@@ -52,7 +52,7 @@ public sealed class SteamEntitlement : IEntitlement
|
||||
if (_paidAppId == 0)
|
||||
{
|
||||
_cached = false;
|
||||
_errorMessage = "The paid Steam app ID is not configured for this build. Contact the creator or support.";
|
||||
_errorMessage = "Steam licensing is not configured in this build.";
|
||||
return false;
|
||||
}
|
||||
if (_cached is { } known) return known;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using ytLive.Services.Audio;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
@@ -17,6 +19,11 @@ public interface IMediaFrameSource : IDisposable
|
||||
/// <summary>Raised (on a worker thread) for each decoded frame.</summary>
|
||||
event Action<VideoFrame>? FrameAvailable;
|
||||
|
||||
/// <summary>Raised (on a worker thread) per chunk of the file's own soundtrack
|
||||
/// (48 kHz stereo float). The manager applies the layer's level/mute and hands it
|
||||
/// to the mixer; a source with no audio simply never raises it.</summary>
|
||||
event Action<AudioSample>? AudioAvailable;
|
||||
|
||||
/// <summary>Raised when the file finishes decoding (natural EOF) — not raised
|
||||
/// while <see cref="Looping"/> is true.</summary>
|
||||
event Action? Completed;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ytLive.Helpers;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·5: can we actually reach YouTube's ingest right now? One TCP connect, nothing else.
|
||||
/// <para>This is prevention, not recovery: "I forgot the VPN" used to produce a broadcast that YouTube
|
||||
/// created and nobody ever saw — the app looked live while the push had nowhere to go. Checking the
|
||||
/// socket before the API call means the failure is a message, not a ghost broadcast.</para>
|
||||
/// </summary>
|
||||
public interface IIngestProbe
|
||||
{
|
||||
/// <summary>True when the ingest host accepted a TCP connection. False on any failure — the
|
||||
/// point is a fast, unambiguous answer, not a diagnosis.</summary>
|
||||
Task<bool> CanReachAsync(string rtmpUrl, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Default probe: parse the RTMP URL, connect to the host on its port (1935 for rtmp) with a
|
||||
/// short timeout. Failures are logged and reported as "not reachable".</summary>
|
||||
public sealed class TcpIngestProbe : IIngestProbe
|
||||
{
|
||||
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(2);
|
||||
|
||||
private readonly TimeSpan _timeout;
|
||||
|
||||
public TcpIngestProbe(TimeSpan? timeout = null) => _timeout = timeout ?? DefaultTimeout;
|
||||
|
||||
public async Task<bool> CanReachAsync(string rtmpUrl, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!TryParse(rtmpUrl, out var host, out var port))
|
||||
{
|
||||
AppLog.Write($"Ingest probe: '{rtmpUrl}' is not a usable RTMP URL");
|
||||
return false;
|
||||
}
|
||||
|
||||
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutCts.CancelAfter(_timeout);
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(host, port, timeoutCts.Token).ConfigureAwait(false);
|
||||
return client.Connected;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
AppLog.Write($"Ingest probe: {host}:{port} did not answer within {_timeout.TotalSeconds:0.#} s");
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"Ingest probe: {host}:{port} unreachable: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>rtmp://a.rtmp.youtube.com/live2/key → (a.rtmp.youtube.com, 1935).
|
||||
/// rtmps uses 443, which is what YouTube's secure ingest listens on.</summary>
|
||||
internal static bool TryParse(string? rtmpUrl, out string host, out int port)
|
||||
{
|
||||
host = string.Empty;
|
||||
port = 1935;
|
||||
if (string.IsNullOrWhiteSpace(rtmpUrl)) return false;
|
||||
if (!Uri.TryCreate(rtmpUrl, UriKind.Absolute, out var uri)) return false;
|
||||
if (string.IsNullOrWhiteSpace(uri.Host)) return false;
|
||||
|
||||
host = uri.Host;
|
||||
port = uri.IsDefaultPort
|
||||
? (uri.Scheme.Equals("rtmps", StringComparison.OrdinalIgnoreCase) ? 443 : 1935)
|
||||
: uri.Port;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,20 @@ public partial class LayoutStore : IDisposable
|
||||
return (string)cmd.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
/// <summary>True when the asset already holds exactly these bytes. Used to decide whether a
|
||||
/// bundled image needs re-seeding: comparing bytes cannot go stale the way a version constant
|
||||
/// can (the constant and the embedded resource were built at different moments twice).</summary>
|
||||
public bool AssetMatches(string assetId, byte[] data)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(assetId)) return false;
|
||||
var hash = Convert.ToHexString(SHA256.HashData(data));
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT 1 FROM Asset WHERE Id = $id AND Hash = $hash;";
|
||||
cmd.Parameters.AddWithValue("$id", assetId);
|
||||
cmd.Parameters.AddWithValue("$hash", hash);
|
||||
return cmd.ExecuteScalar() != null;
|
||||
}
|
||||
|
||||
// ─── License (TASK 10 — Polar billing) ───
|
||||
|
||||
/// <summary>The saved license key, or null if never entered.</summary>
|
||||
|
||||
@@ -113,7 +113,9 @@ public partial class LayoutStore : IDisposable
|
||||
AlertVideoAssetId, AlertVideoPath, AlertUseDefaultVideo, AlertShowTicker, AlertVideoVolume, SortOrder,
|
||||
AlertDisplayMethod, IsBrandLogo, BlurAmount, AlertAudioPath, AlertAudioLoop,
|
||||
TextContent, TextFontFamily, TextFontSize, TextColor, TextBold, TextItalic,
|
||||
TextUnderline, TextAlignment, TextVerticalAlignment
|
||||
TextUnderline, TextAlignment, TextVerticalAlignment, MediaMuted,
|
||||
ChromaKeyEnabled, ChromaKeyColor, ChromaKeySimilarity, ChromaKeySoftness,
|
||||
ChromaKeySpill, ChromaScreen
|
||||
FROM Source ORDER BY SortOrder
|
||||
""";
|
||||
using var reader = cmd.ExecuteReader();
|
||||
@@ -183,6 +185,17 @@ public partial class LayoutStore : IDisposable
|
||||
|| !Enum.IsDefined((TextLayerVerticalAlignment)reader.GetInt32(49))
|
||||
? TextLayerVerticalAlignment.Top
|
||||
: (TextLayerVerticalAlignment)reader.GetInt32(49),
|
||||
MediaMuted = reader.GetInt32(reader.GetOrdinal("MediaMuted")) != 0,
|
||||
ChromaKeyEnabled = reader.GetInt32(reader.GetOrdinal("ChromaKeyEnabled")) != 0,
|
||||
ChromaKeyColor = reader.IsDBNull(reader.GetOrdinal("ChromaKeyColor"))
|
||||
? "#00B140"
|
||||
: reader.GetString(reader.GetOrdinal("ChromaKeyColor")),
|
||||
ChromaKeySimilarity = reader.GetDouble(reader.GetOrdinal("ChromaKeySimilarity")),
|
||||
ChromaKeySoftness = reader.GetDouble(reader.GetOrdinal("ChromaKeySoftness")),
|
||||
ChromaKeySpill = reader.GetInt32(reader.GetOrdinal("ChromaKeySpill")) != 0,
|
||||
ChromaScreen = reader.IsDBNull(reader.GetOrdinal("ChromaScreen"))
|
||||
? ChromaScreen.Green
|
||||
: (ChromaScreen)reader.GetInt32(reader.GetOrdinal("ChromaScreen")),
|
||||
};
|
||||
if (!sourcesByScene.TryGetValue(sceneId, out var list))
|
||||
sourcesByScene[sceneId] = list = new List<(Source, int)>();
|
||||
|
||||
@@ -378,6 +378,50 @@ public partial class LayoutStore : IDisposable
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN MediaPlaybackState TEXT NOT NULL DEFAULT 'Stopped';";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
if (!columns.Contains("MediaMuted"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN MediaMuted INTEGER NOT NULL DEFAULT 0;";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
// TASK 64: green/blue screen settings per layer (applied in the decode pipe).
|
||||
if (!columns.Contains("ChromaKeyEnabled"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChromaKeyEnabled INTEGER NOT NULL DEFAULT 0;";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
if (!columns.Contains("ChromaKeyColor"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChromaKeyColor TEXT NOT NULL DEFAULT '#00B140';";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
if (!columns.Contains("ChromaKeySimilarity"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChromaKeySimilarity REAL NOT NULL DEFAULT 0.12;";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
if (!columns.Contains("ChromaKeySoftness"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChromaKeySoftness REAL NOT NULL DEFAULT 0.08;";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
if (!columns.Contains("ChromaKeySpill"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChromaKeySpill INTEGER NOT NULL DEFAULT 1;";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
if (!columns.Contains("ChromaScreen"))
|
||||
{
|
||||
using var cmd = _connection.CreateCommand();
|
||||
cmd.CommandText = "ALTER TABLE Source ADD COLUMN ChromaScreen INTEGER NOT NULL DEFAULT 0;";
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
// TASK 47: alert video config. The default clip asset id + the creator's
|
||||
// replacement path (a FILE reference, never a stored BLOB) + the pill,
|
||||
|
||||
@@ -94,7 +94,9 @@ public partial class LayoutStore : IDisposable
|
||||
AlertVideoAssetId, AlertVideoPath, AlertUseDefaultVideo, AlertShowTicker, AlertVideoVolume,
|
||||
AlertDisplayMethod, IsBrandLogo, BlurAmount, AlertAudioPath, AlertAudioLoop,
|
||||
TextContent, TextFontFamily, TextFontSize, TextColor, TextBold, TextItalic,
|
||||
TextUnderline, TextAlignment, TextVerticalAlignment)
|
||||
TextUnderline, TextAlignment, TextVerticalAlignment, MediaMuted,
|
||||
ChromaKeyEnabled, ChromaKeyColor, ChromaKeySimilarity,
|
||||
ChromaKeySoftness, ChromaKeySpill, ChromaScreen)
|
||||
VALUES ($id, $sceneId, $assetId, $type, $name, $isEnabled,
|
||||
$x, $y, $w, $h, $opacity, $monitor,
|
||||
$clip, $mirrored, $isBackground, $captureKey, $showDesktop, $sort,
|
||||
@@ -104,7 +106,9 @@ public partial class LayoutStore : IDisposable
|
||||
$alertVideoAssetId, $alertVideoPath, $alertUseDefaultVideo, $alertShowTicker, $alertVideoVolume,
|
||||
$alertDisplayMethod, $isBrandLogo, $blurAmount, $alertAudioPath, $alertAudioLoop,
|
||||
$textContent, $textFontFamily, $textFontSize, $textColor, $textBold, $textItalic,
|
||||
$textUnderline, $textAlignment, $textVerticalAlignment)
|
||||
$textUnderline, $textAlignment, $textVerticalAlignment, $mediaMuted,
|
||||
$chromaEnabled, $chromaColor, $chromaSimilarity, $chromaSoftness,
|
||||
$chromaSpill, $chromaScreen)
|
||||
""";
|
||||
cmd.Transaction = tx;
|
||||
var idP = cmd.Parameters.Add("$id", SqliteType.Text);
|
||||
@@ -137,6 +141,13 @@ public partial class LayoutStore : IDisposable
|
||||
var mediaPathP = cmd.Parameters.Add("$mediaPath", SqliteType.Text);
|
||||
var mediaIsLoopingP = cmd.Parameters.Add("$mediaIsLooping", SqliteType.Integer);
|
||||
var mediaVolumeP = cmd.Parameters.Add("$mediaVolume", SqliteType.Real);
|
||||
var mediaMutedP = cmd.Parameters.Add("$mediaMuted", SqliteType.Integer);
|
||||
var chromaEnabledP = cmd.Parameters.Add("$chromaEnabled", SqliteType.Integer);
|
||||
var chromaColorP = cmd.Parameters.Add("$chromaColor", SqliteType.Text);
|
||||
var chromaSimilarityP = cmd.Parameters.Add("$chromaSimilarity", SqliteType.Real);
|
||||
var chromaSoftnessP = cmd.Parameters.Add("$chromaSoftness", SqliteType.Real);
|
||||
var chromaSpillP = cmd.Parameters.Add("$chromaSpill", SqliteType.Integer);
|
||||
var chromaScreenP = cmd.Parameters.Add("$chromaScreen", SqliteType.Integer);
|
||||
var mediaPlaybackStateP = cmd.Parameters.Add("$mediaPlaybackState", SqliteType.Text);
|
||||
var alertVideoAssetIdP = cmd.Parameters.Add("$alertVideoAssetId", SqliteType.Text);
|
||||
var alertVideoPathP = cmd.Parameters.Add("$alertVideoPath", SqliteType.Text);
|
||||
@@ -198,6 +209,13 @@ public partial class LayoutStore : IDisposable
|
||||
mediaPathP.Value = (object?)source.MediaPath ?? DBNull.Value;
|
||||
mediaIsLoopingP.Value = source.MediaIsLooping ? 1 : 0;
|
||||
mediaVolumeP.Value = source.MediaVolume;
|
||||
mediaMutedP.Value = source.MediaMuted ? 1 : 0;
|
||||
chromaEnabledP.Value = source.ChromaKeyEnabled ? 1 : 0;
|
||||
chromaColorP.Value = source.ChromaKeyColor;
|
||||
chromaSimilarityP.Value = source.ChromaKeySimilarity;
|
||||
chromaSoftnessP.Value = source.ChromaKeySoftness;
|
||||
chromaSpillP.Value = source.ChromaKeySpill ? 1 : 0;
|
||||
chromaScreenP.Value = (int)source.ChromaScreen;
|
||||
mediaPlaybackStateP.Value = source.MediaPlaybackState.ToString();
|
||||
alertVideoAssetIdP.Value = (object?)source.AlertVideoAssetId ?? DBNull.Value;
|
||||
alertVideoPathP.Value = (object?)source.AlertVideoPath ?? DBNull.Value;
|
||||
|
||||
@@ -48,6 +48,25 @@ public partial class LayoutStore : IDisposable
|
||||
/// <summary>Zoom box follow mode (creator ruling 2026-11-01): false = ANCHOR (the capture
|
||||
/// stays on the point that was clicked, the default), true = FOLLOW (the capture re-anchors
|
||||
/// to the box centre while it is dragged).</summary>
|
||||
/// <summary>TASK 64: key a detected green/blue screen without asking. Off by default — the
|
||||
/// app offers, the creator accepts; this switch is for the creator who is tired of clicking.</summary>
|
||||
/// <summary>Creator closed the Steam licence indicator while ownership was verified. Honoured only
|
||||
/// while Steam keeps confirming ownership — losing it brings the indicator back (2026-11-05).</summary>
|
||||
public bool LoadSteamLicenceIndicatorDismissed() => GetSetting("Steam.LicenceIndicatorDismissed") == "1";
|
||||
|
||||
public void SaveSteamLicenceIndicatorDismissed(bool dismissed)
|
||||
=> UpsertSetting("Steam.LicenceIndicatorDismissed", dismissed ? "1" : "0");
|
||||
|
||||
/// <summary>TASK 3·20: show money in the app's own analytics surfaces. OFF by default — most
|
||||
/// creators never monetize, and a $0.00 report is a spit in the face (creator ruling 2026-11-05).</summary>
|
||||
public bool LoadShowMonetaryMetrics() => GetSetting("Metrics.ShowMonetary") == "1";
|
||||
|
||||
public void SaveShowMonetaryMetrics(bool show) => UpsertSetting("Metrics.ShowMonetary", show ? "1" : "0");
|
||||
|
||||
public bool LoadAutoChromaScreen() => GetSetting("Video.AutoChromaScreen") == "1";
|
||||
|
||||
public void SaveAutoChromaScreen(bool enabled) => UpsertSetting("Video.AutoChromaScreen", enabled ? "1" : "0");
|
||||
|
||||
public bool LoadZoomFollowBox() => GetSetting("Zoom.FollowBox") == "1";
|
||||
|
||||
public void SaveZoomFollowBox(bool follow) => UpsertSetting("Zoom.FollowBox", follow ? "1" : "0");
|
||||
|
||||
+27
-116
@@ -1,38 +1,35 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using ytLive.Services.Audio;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 21: decodes a local media file (any format ffmpeg handles) into
|
||||
/// <see cref="VideoFrame"/>s for a MediaSource. Implements
|
||||
/// <see cref="IMediaFrameSource"/>: raises <see cref="FrameAvailable"/> per
|
||||
/// frame and <see cref="IMediaFrameSource.Completed"/> on natural EOF (unless
|
||||
/// <see cref="IMediaFrameSource.Looping"/>). Spawns ffmpeg with
|
||||
/// <c>-f rawvideo -pix_fmt bgra</c> and drains the raw BGRA pipe via
|
||||
/// <see cref="RawVideoFrameReader"/>. The decoder process and emitters are seams
|
||||
/// so tests run without a real codec or audio device.
|
||||
/// <see cref="VideoFrame"/>s for a MediaSource. This is the <see cref="IMediaFrameSource"/>
|
||||
/// shape over the shared <see cref="VideoClipPipe"/> — the same pipe an alert clip uses
|
||||
/// (TASK 47), so the two features cannot drift apart again in how they decode.
|
||||
/// <para>Video AND the file's own soundtrack are decoded. The manager scales the audio by
|
||||
/// the layer's level/mute and hands it to the mixer's desktop group.</para>
|
||||
/// <para><b>Keying (TASK 64) is a decode option</b>: pass <see cref="ChromaKeyOptions"/> and the
|
||||
/// green/blue screen is removed inside ffmpeg's pipe, so the preview bitmap and the composited
|
||||
/// frame both carry the keyed alpha. Two looks = two sources; identical looks share one.</para>
|
||||
/// </summary>
|
||||
public sealed class MediaVideoSource : IMediaFrameSource
|
||||
{
|
||||
public event Action<VideoFrame>? FrameAvailable;
|
||||
public event Action<AudioSample>? AudioAvailable;
|
||||
public event Action? Completed;
|
||||
|
||||
public string Key => _path;
|
||||
|
||||
public bool Looping { get; set; }
|
||||
public bool Looping
|
||||
{
|
||||
get => _clip.Looping;
|
||||
set => _clip.Looping = value;
|
||||
}
|
||||
|
||||
private readonly string _path;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
private readonly IFfmpegLocator _locator;
|
||||
private readonly Func<IDecodeProcess> _processFactory;
|
||||
private readonly IFrameRateProbe? _probe;
|
||||
private readonly Func<TimeSpan, CancellationToken, Task> _delay;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private IDisposable? _run;
|
||||
private IDecodeProcess? _active;
|
||||
private readonly VideoClipPipe _clip;
|
||||
|
||||
public MediaVideoSource(
|
||||
string path,
|
||||
@@ -41,107 +38,21 @@ public sealed class MediaVideoSource : IMediaFrameSource
|
||||
IFfmpegLocator locator,
|
||||
Func<IDecodeProcess> processFactory,
|
||||
IFrameRateProbe? frameRateProbe = null,
|
||||
Func<TimeSpan, CancellationToken, Task>? delay = null)
|
||||
Func<TimeSpan, CancellationToken, Task>? delay = null,
|
||||
ChromaKeyOptions? chromaKey = null)
|
||||
{
|
||||
_path = path;
|
||||
_width = width;
|
||||
_height = height;
|
||||
_locator = locator;
|
||||
_processFactory = processFactory;
|
||||
_probe = frameRateProbe;
|
||||
_delay = delay ?? ((t, ct) => Task.Delay(t, ct));
|
||||
_clip = new VideoClipPipe(
|
||||
path, width, height, locator, processFactory, frameRateProbe, delay,
|
||||
audio: true, chromaKey: chromaKey);
|
||||
_clip.FrameAvailable += frame => FrameAvailable?.Invoke(frame);
|
||||
_clip.AudioAvailable += sample => AudioAvailable?.Invoke(sample);
|
||||
_clip.Completed += () => Completed?.Invoke();
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_run != null) return Task.CompletedTask;
|
||||
_run = _cts.Token.Register(StopInternal);
|
||||
_ = Task.Run(RunAsync, CancellationToken.None);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public Task StartAsync(CancellationToken cancellationToken = default) => _clip.StartAsync(cancellationToken);
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_run = null;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public Task StopAsync() => _clip.StopAsync();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
_active?.Dispose();
|
||||
}
|
||||
|
||||
private void StopInternal() => KillProcess();
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
double? frameRate = null;
|
||||
if (_probe != null)
|
||||
frameRate = await _probe.ProbeAsync(_path, _cts.Token).ConfigureAwait(false);
|
||||
var frameDuration = frameRate is > 0 ? TimeSpan.FromSeconds(1.0 / frameRate.Value) : TimeSpan.Zero;
|
||||
|
||||
var ffmpegPath = await _locator.LocateAsync(_cts.Token).ConfigureAwait(false);
|
||||
var args =
|
||||
$"-hide_banner -loglevel error -i \"{_path}\" " +
|
||||
$"-f rawvideo -pix_fmt bgra -vf scale={_width}:{_height} -an -";
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpegPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
|
||||
do
|
||||
{
|
||||
using (var process = _processFactory())
|
||||
{
|
||||
_active = process;
|
||||
process.Start(startInfo);
|
||||
|
||||
var reader = new RawVideoFrameReader(_width, _height);
|
||||
var buffer = new byte[65536];
|
||||
var stream = process.StandardOutput;
|
||||
while (!_cts.IsCancellationRequested && !process.HasExited)
|
||||
{
|
||||
var read = await stream.ReadAsync(buffer, 0, buffer.Length, _cts.Token).ConfigureAwait(false);
|
||||
if (read <= 0) break;
|
||||
foreach (var frame in reader.Feed(buffer.AsSpan(0, read).ToArray()))
|
||||
{
|
||||
FrameAvailable?.Invoke(frame);
|
||||
if (frameDuration > TimeSpan.Zero)
|
||||
await _delay(frameDuration, _cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
_active = null;
|
||||
}
|
||||
while (Looping && !_cts.IsCancellationRequested);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail($"Media decode failed: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_cts.IsCancellationRequested)
|
||||
Completed?.Invoke();
|
||||
}
|
||||
|
||||
private void Fail(string message) => Console.Error.WriteLine(message);
|
||||
|
||||
private void KillProcess()
|
||||
{
|
||||
try { _active?.Kill(); } catch { /* already exited */ }
|
||||
}
|
||||
public void Dispose() => _clip.Dispose();
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Services.Audio;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
@@ -23,8 +24,13 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
public string Key { get; }
|
||||
public IMediaFrameSource Source { get; }
|
||||
public Action<VideoFrame>? FrameHandler;
|
||||
public Action<AudioSample>? AudioHandler;
|
||||
public Action? CompletedHandler;
|
||||
public bool Finished;
|
||||
public int RefCount;
|
||||
public bool Started;
|
||||
public bool AudioMuted;
|
||||
public double AudioVolume = 1.0;
|
||||
public WriteableBitmap? PreviewBitmap;
|
||||
public VideoFrame? LatestFrame;
|
||||
public bool FramePending;
|
||||
@@ -37,8 +43,10 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private readonly Func<string, IMediaFrameSource?> _sourceFactory;
|
||||
// (file path, the layer's look) → decoder. The SESSION key is separate: path + look.
|
||||
private readonly Func<string, ChromaKeyOptions?, IMediaFrameSource?> _sourceFactory;
|
||||
private readonly Dispatcher? _uiDispatcher;
|
||||
private readonly Func<string, bool>? _loopProvider;
|
||||
private readonly Dictionary<string, MediaSession> _sessions = new();
|
||||
private readonly object _gate = new();
|
||||
|
||||
@@ -48,14 +56,28 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
/// <summary>Raised when a media decoder cannot be created (bad path).</summary>
|
||||
public event Action<string, string>? MediaFailed;
|
||||
|
||||
public MediaVideoSourceManager(Func<string, IMediaFrameSource?> sourceFactory, Dispatcher? uiDispatcher = null)
|
||||
/// <summary>Raised (worker thread) per audio chunk of a file's own soundtrack, already
|
||||
/// scaled by the session's level and dropped when muted.</summary>
|
||||
public event Action<string, AudioSample>? AudioAvailable;
|
||||
|
||||
public MediaVideoSourceManager(
|
||||
Func<string, ChromaKeyOptions?, IMediaFrameSource?> sourceFactory,
|
||||
Dispatcher? uiDispatcher = null,
|
||||
Func<string, bool>? loopProvider = null)
|
||||
{
|
||||
_sourceFactory = sourceFactory;
|
||||
_uiDispatcher = uiDispatcher;
|
||||
_loopProvider = loopProvider;
|
||||
}
|
||||
|
||||
/// <summary>Increments the refcount for a file, starting the decoder the first time.</summary>
|
||||
public async Task<bool> AcquireAsync(string key)
|
||||
/// <summary>Increments the refcount for a file, starting the decoder the first time.
|
||||
/// <paramref name="keyOptions"/> is the layer's look (TASK 64): the caller keys sessions by
|
||||
/// path + look, so two looks on one file are two decoders and identical looks share one.</summary>
|
||||
public async Task<bool> AcquireAsync(string key, ChromaKeyOptions? keyOptions = null)
|
||||
=> await AcquireAsync(key, key, keyOptions).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Acquires by session key, decoding <paramref name="path"/> with the given look.</summary>
|
||||
public async Task<bool> AcquireAsync(string key, string path, ChromaKeyOptions? keyOptions = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key)) return false;
|
||||
|
||||
@@ -74,7 +96,7 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
IMediaFrameSource? source;
|
||||
try
|
||||
{
|
||||
source = _sourceFactory(key);
|
||||
source = _sourceFactory(path, keyOptions);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -90,6 +112,14 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
session = new MediaSession(key, source);
|
||||
session.FrameHandler = frame => OnFrameAvailable(session, frame);
|
||||
session.Source.FrameAvailable += session.FrameHandler;
|
||||
session.AudioHandler = sample => OnAudioAvailable(session, sample);
|
||||
session.Source.AudioAvailable += session.AudioHandler;
|
||||
session.CompletedHandler = () => OnSessionCompleted(session);
|
||||
session.Source.Completed += session.CompletedHandler;
|
||||
// Loop intent lives on the Source (per scene), so the caller supplies the
|
||||
// per-path answer ("any live reference loops"). Applied before Start so a
|
||||
// zero-length or instantly-EOF file cannot slip past a later assignment.
|
||||
session.Source.Looping = _loopProvider?.Invoke(key) ?? false;
|
||||
_sessions[key] = session;
|
||||
shouldStart = true;
|
||||
}
|
||||
@@ -108,6 +138,8 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
lock (_gate)
|
||||
_sessions.Remove(key);
|
||||
session.Source.FrameAvailable -= session.FrameHandler;
|
||||
if (session.AudioHandler != null) session.Source.AudioAvailable -= session.AudioHandler;
|
||||
if (session.CompletedHandler != null) session.Source.Completed -= session.CompletedHandler;
|
||||
AppLog.Write($"MediaSource: failed to start decoder '{key}': {ex.Message}");
|
||||
MediaFailed?.Invoke(key, ex.Message);
|
||||
await SafeStopAsync(session.Source);
|
||||
@@ -128,6 +160,8 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
|
||||
if (toStop == null) return;
|
||||
toStop.Source.FrameAvailable -= toStop.FrameHandler;
|
||||
if (toStop.AudioHandler != null) toStop.Source.AudioAvailable -= toStop.AudioHandler;
|
||||
if (toStop.CompletedHandler != null) toStop.Source.Completed -= toStop.CompletedHandler;
|
||||
await SafeStopAsync(toStop.Source);
|
||||
toStop.PreviewBitmap = null;
|
||||
}
|
||||
@@ -146,6 +180,8 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
|
||||
if (toStop == null) return;
|
||||
toStop.Source.FrameAvailable -= toStop.FrameHandler;
|
||||
if (toStop.AudioHandler != null) toStop.Source.AudioAvailable -= toStop.AudioHandler;
|
||||
if (toStop.CompletedHandler != null) toStop.Source.Completed -= toStop.CompletedHandler;
|
||||
await SafeStopAsync(toStop.Source);
|
||||
toStop.PreviewBitmap = null;
|
||||
}
|
||||
@@ -158,6 +194,120 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
return _sessions.TryGetValue(key, out var session) ? session.LatestFrame : null;
|
||||
}
|
||||
|
||||
/// <summary>Raised when a file plays out (natural end, no loop) — the layer is then holding its
|
||||
/// last frame and the creator can start it again.</summary>
|
||||
public event Action<string>? SessionCompleted;
|
||||
|
||||
/// <summary>True while a decode session exists for the file — the caller uses this to
|
||||
/// keep one acquire per path instead of stacking refcounts on every layout pass.</summary>
|
||||
public bool HasSession(string key)
|
||||
{
|
||||
lock (_gate)
|
||||
return _sessions.ContainsKey(key);
|
||||
}
|
||||
|
||||
/// <summary>The files with a live session, for reconciling a layout load.</summary>
|
||||
public IReadOnlyList<string> GetActiveKeys()
|
||||
{
|
||||
lock (_gate)
|
||||
return new List<string>(_sessions.Keys);
|
||||
}
|
||||
|
||||
/// <summary>Applies a loop change to a running session (the creator flipped the
|
||||
/// toggle). No-op when the file has no session.</summary>
|
||||
/// <summary>False once the file has played to the end. A finished session keeps its last frame
|
||||
/// (and its refcount), so "play again" is a restart, not a re-acquire.</summary>
|
||||
public bool IsRunning(string key)
|
||||
{
|
||||
lock (_gate)
|
||||
return _sessions.TryGetValue(key, out var session) && session.Started && !session.Finished;
|
||||
}
|
||||
|
||||
/// <summary>Restarts a finished file from the top (the Loop switch or "Play again"). The session is
|
||||
/// kept, so the shared preview bitmap and the frame consumers stay valid.</summary>
|
||||
public async Task<bool> RestartAsync(string key)
|
||||
{
|
||||
MediaSession? session;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_sessions.TryGetValue(key, out session)) return false;
|
||||
session.Finished = false;
|
||||
session.Started = false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await session.Source.StartAsync().ConfigureAwait(false);
|
||||
session.Started = true;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"MediaSource: restarting '{key}' failed: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetLooping(string key, bool looping)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_sessions.TryGetValue(key, out var session))
|
||||
session.Source.Looping = looping;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The layer's sound controls for this file. One decoder is shared per path,
|
||||
/// so the level/mute are per SESSION: whichever layer the creator last touched wins —
|
||||
/// the alternative (one decoder per layer) would play the same file twice.</summary>
|
||||
public void SetAudioSettings(string key, double volume, bool muted)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_sessions.TryGetValue(key, out var session)) return;
|
||||
session.AudioVolume = Math.Clamp(volume, 0, 1);
|
||||
session.AudioMuted = muted;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSessionCompleted(MediaSession session)
|
||||
{
|
||||
if (!TryGetActiveSession(session)) return;
|
||||
lock (_gate)
|
||||
{
|
||||
if (session.Source.Looping) return; // it will restart itself
|
||||
session.Finished = true;
|
||||
}
|
||||
SessionCompleted?.Invoke(session.Key);
|
||||
}
|
||||
|
||||
private void OnAudioAvailable(MediaSession session, AudioSample sample)
|
||||
{
|
||||
if (!TryGetActiveSession(session)) return;
|
||||
|
||||
double volume;
|
||||
bool muted;
|
||||
lock (_gate)
|
||||
{
|
||||
volume = session.AudioVolume;
|
||||
muted = session.AudioMuted;
|
||||
}
|
||||
if (muted || volume <= 0) return;
|
||||
|
||||
if (volume < 0.999)
|
||||
{
|
||||
// Copy before scaling: the source owns its buffer and may recycle it.
|
||||
var scaled = new float[sample.Samples.Length];
|
||||
var gain = (float)volume;
|
||||
for (var i = 0; i < scaled.Length; i++)
|
||||
scaled[i] = sample.Samples[i] * gain;
|
||||
AudioAvailable?.Invoke(session.Key, new AudioSample(scaled, sample.SampleRate, sample.Channels));
|
||||
return;
|
||||
}
|
||||
|
||||
AudioAvailable?.Invoke(session.Key, sample);
|
||||
}
|
||||
|
||||
/// <summary>The shared preview bitmap for a file (so a config created after the
|
||||
/// first frame can adopt the running bitmap), or null.</summary>
|
||||
public WriteableBitmap? GetPreviewBitmap(string key)
|
||||
@@ -178,6 +328,8 @@ public sealed class MediaVideoSourceManager : IDisposable
|
||||
foreach (var session in sessions)
|
||||
{
|
||||
session.Source.FrameAvailable -= session.FrameHandler;
|
||||
if (session.AudioHandler != null) session.Source.AudioAvailable -= session.AudioHandler;
|
||||
if (session.CompletedHandler != null) session.Source.Completed -= session.CompletedHandler;
|
||||
_ = SafeStopAsync(session.Source);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,30 @@ namespace ytLive.Services;
|
||||
/// frame is emitted whenever that many bytes have accumulated. Pure and fully
|
||||
/// deterministic, so it is tested with a synthetic byte stream — no ffmpeg, no
|
||||
/// process, no audio device needed.
|
||||
/// <para><b>Fill a preallocated frame, do not re-concatenate a pending buffer</b> (2026-11-05).
|
||||
/// The previous version copied the whole accumulated partial frame on every <c>Feed</c>, so a
|
||||
/// 1080p frame arriving in 64 KB reads cost ~64 copies of a growing 8 MB buffer — about 0.5 GB of
|
||||
/// copying per frame, which capped playback at ~4 fps no matter what the pacing said (reported as
|
||||
/// "playing at a hideously slow rate"; measured 6 frames in 3 s on a 30 fps clip). Now the cost is
|
||||
/// one copy per frame plus one copy of the tail that spans reads.</para>
|
||||
/// </summary>
|
||||
public sealed class RawVideoFrameReader
|
||||
{
|
||||
private readonly int _frameBytes;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
private byte[]? _pending;
|
||||
|
||||
// Staging buffer for the frame currently being assembled. It BECOMES the emitted frame's
|
||||
// pixel array, then a fresh one is allocated — so a frame is copied exactly once.
|
||||
private byte[] _frame;
|
||||
private int _count;
|
||||
|
||||
public RawVideoFrameReader(int width, int height)
|
||||
{
|
||||
_width = width;
|
||||
_height = height;
|
||||
_frameBytes = width * height * 4;
|
||||
_frame = new byte[_frameBytes];
|
||||
}
|
||||
|
||||
/// <summary>Feeds <paramref name="bytes"/> read from the pipe and returns any
|
||||
@@ -27,32 +38,23 @@ public sealed class RawVideoFrameReader
|
||||
/// next call — frames never split or merge across reads.</summary>
|
||||
public List<VideoFrame> Feed(byte[] bytes)
|
||||
{
|
||||
var pending = _pending;
|
||||
byte[] combined;
|
||||
if (pending != null && pending.Length > 0)
|
||||
{
|
||||
combined = new byte[pending.Length + bytes.Length];
|
||||
Buffer.BlockCopy(pending, 0, combined, 0, pending.Length);
|
||||
Buffer.BlockCopy(bytes, 0, combined, pending.Length, bytes.Length);
|
||||
_pending = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
combined = bytes;
|
||||
}
|
||||
|
||||
var frames = new List<VideoFrame>();
|
||||
var offset = 0;
|
||||
while (combined.Length - offset >= _frameBytes)
|
||||
{
|
||||
var frame = new byte[_frameBytes];
|
||||
Buffer.BlockCopy(combined, offset, frame, 0, _frameBytes);
|
||||
frames.Add(new VideoFrame(_width, _height, frame));
|
||||
offset += _frameBytes;
|
||||
}
|
||||
if (bytes.Length == 0) return frames;
|
||||
|
||||
if (offset < combined.Length)
|
||||
_pending = combined[offset..];
|
||||
var offset = 0;
|
||||
while (offset < bytes.Length)
|
||||
{
|
||||
var take = Math.Min(_frameBytes - _count, bytes.Length - offset);
|
||||
Buffer.BlockCopy(bytes, offset, _frame, _count, take);
|
||||
_count += take;
|
||||
offset += take;
|
||||
|
||||
if (_count < _frameBytes) continue;
|
||||
|
||||
frames.Add(new VideoFrame(_width, _height, _frame));
|
||||
_frame = new byte[_frameBytes];
|
||||
_count = 0;
|
||||
}
|
||||
|
||||
return frames;
|
||||
}
|
||||
|
||||
@@ -64,10 +64,14 @@ public sealed class ScreenCaptureFrameSource : IScreenCaptureSource
|
||||
// accommodate in-flight frames) and publishes only monotonically newer frames
|
||||
// (MonotonicGate — a slow older completion must never overwrite a newer LatestFrame).
|
||||
private static readonly TimeSpan MinConvertInterval = TimeSpan.FromMilliseconds(10);
|
||||
/// <summary>TASK 33: the "shed our own load first" cadence — 30 conversions/s instead of ~100.
|
||||
/// The viewer's tier does not change; only how often we pay for a readback.</summary>
|
||||
private static readonly TimeSpan ShedConvertInterval = TimeSpan.FromMilliseconds(33);
|
||||
private static readonly TimeSpan TelemetryInterval = TimeSpan.FromSeconds(2);
|
||||
private const int MaxConcurrentConversions = 3;
|
||||
private const int PoolBufferCount = 5;
|
||||
private DateTime _lastConvertAt = DateTime.MinValue;
|
||||
private TimeSpan _convertInterval = MinConvertInterval;
|
||||
private DateTime _telemetryFrom = DateTime.UtcNow;
|
||||
private DateTime _lastTelemetry = DateTime.UtcNow;
|
||||
private long _skippedCadence;
|
||||
@@ -79,6 +83,10 @@ public sealed class ScreenCaptureFrameSource : IScreenCaptureSource
|
||||
public string Key { get; }
|
||||
public event Action<VideoFrame>? FrameAvailable;
|
||||
|
||||
/// <summary>TASK 33: halve our own capture cost before asking the creator to accept a lower tier.
|
||||
/// Idempotent; the pump keeps its declared fps either way (it pads), so no output contract changes.</summary>
|
||||
public void ShedLoad(bool shed) => _convertInterval = shed ? ShedConvertInterval : MinConvertInterval;
|
||||
|
||||
internal ScreenCaptureFrameSource(string key, GraphicsCaptureItem item)
|
||||
{
|
||||
Key = key;
|
||||
@@ -171,7 +179,7 @@ public sealed class ScreenCaptureFrameSource : IScreenCaptureSource
|
||||
return;
|
||||
}
|
||||
var now = DateTime.UtcNow;
|
||||
if (now - _lastConvertAt < MinConvertInterval)
|
||||
if (now - _lastConvertAt < _convertInterval)
|
||||
{
|
||||
_skippedCadence++;
|
||||
frame.Dispose();
|
||||
|
||||
@@ -55,6 +55,15 @@ public sealed class ScreenCaptureManager : IDisposable
|
||||
_uiDispatcher = uiDispatcher;
|
||||
}
|
||||
|
||||
/// <summary>TASK 33: applies the capture-load shed to every live capture. Before this, the only
|
||||
/// lever for machine starvation was the viewer's tier — the app charged them for its own cost.</summary>
|
||||
public void ShedLoad(bool shed)
|
||||
{
|
||||
lock (_gate)
|
||||
foreach (var session in _sessions.Values)
|
||||
if (session.Source is ScreenCaptureFrameSource source) source.ShedLoad(shed);
|
||||
}
|
||||
|
||||
/// <summary>Increments the refcount for a target key, starting capture the first time.</summary>
|
||||
public async Task<bool> AcquireAsync(string key)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using ytLive.Models;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 33 slice 2: the session's adaptor between the pump's evidence and the pure policy. One planner
|
||||
/// per broadcast, because the policy is stateful (budget, cooldown, current tier) and a step must
|
||||
/// survive across windows.
|
||||
///
|
||||
/// <para>It deliberately does not act. It answers "should this session change something, and why"; the
|
||||
/// view model owns the restart, the toast and the session-report line. Keeping the effects out is what
|
||||
/// makes the whole ladder testable without an encoder running.</para>
|
||||
/// </summary>
|
||||
public sealed class StepDownPlanner
|
||||
{
|
||||
private readonly StepDownPolicy _policy;
|
||||
private readonly DateTime _startedUtc;
|
||||
|
||||
public StepDownPlanner(StepDownPolicy policy, DateTime startedUtc)
|
||||
{
|
||||
_policy = policy;
|
||||
_startedUtc = startedUtc;
|
||||
}
|
||||
|
||||
public StepDownPolicy Policy => _policy;
|
||||
|
||||
/// <summary>Current tier after any applied steps, in the shape the encoder restart needs.</summary>
|
||||
public (int Width, int Height, int Fps, double BitrateMbps) Current =>
|
||||
(_policy.Width, _policy.Height, _policy.Fps, _policy.BitrateMbps);
|
||||
|
||||
public StepDownDecision Observe(in FramePumpStats stats, DateTime nowUtc)
|
||||
{
|
||||
var sample = new StepDownSample(
|
||||
WindowSeconds: stats.WindowSeconds,
|
||||
PumpStalls: stats.Stalls,
|
||||
PumpDrops: 0, // the pump pads with the last frame; FramesRendered is ambiguous
|
||||
EncoderDrops: stats.Dropped,
|
||||
AvgRenderMs: stats.AvgRenderMs,
|
||||
AvgSubmitWaitMs: stats.AvgSubmitMs);
|
||||
|
||||
return _policy.Observe(sample, nowUtc - _startedUtc);
|
||||
}
|
||||
|
||||
/// <summary>The plain sentence the creator sees, chosen by cause. Never a mechanism string: "ffmpeg
|
||||
/// exited", "dropped 8", an HTTP code are log findings, not an explanation of what happened to them.
|
||||
/// </summary>
|
||||
public static string Describe(in StepDownDecision decision, (int Width, int Height, int Fps, double BitrateMbps) landed)
|
||||
=> decision.Action switch
|
||||
{
|
||||
StepAction.LowerFrameRate =>
|
||||
"LlamaCasty couldn't keep up with your scene, so it lowered the frame rate to " +
|
||||
$"{landed.Fps}. Your connection wasn't the problem.",
|
||||
StepAction.LowerResolution =>
|
||||
"LlamaCasty couldn't keep up with your scene, so it lowered the picture to " +
|
||||
$"{landed.Width}×{landed.Height}. Your connection wasn't the problem.",
|
||||
StepAction.LowerBitrate =>
|
||||
$"Your upload couldn't hold the bitrate, so LlamaCasty lowered it to {landed.BitrateMbps:0.0} Mbps " +
|
||||
"to stop the freezing. It will stay there for this stream.",
|
||||
StepAction.RaiseFrameRate or StepAction.RaiseResolution or StepAction.RaiseBitrate =>
|
||||
"Conditions were clean for a while, so LlamaCasty restored one step of quality.",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
/// <summary>One line for the session report, so a later question is answered from data.</summary>
|
||||
public static string ReportLine(DateTime whenLocal, in StepDownDecision decision) =>
|
||||
decision.Action switch
|
||||
{
|
||||
StepAction.None => string.Empty,
|
||||
StepAction.LowerFrameRate or StepAction.LowerResolution =>
|
||||
$"{whenLocal:HH:mm} quality stepped down — encoder ({decision.Why})",
|
||||
StepAction.LowerBitrate =>
|
||||
$"{whenLocal:HH:mm} quality stepped down — upload ({decision.Why})",
|
||||
_ => $"{whenLocal:HH:mm} quality restored ({decision.Why})",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>What YouTube says about the broadcast once a push is back.</summary>
|
||||
public enum BroadcastLiveness
|
||||
{
|
||||
/// <summary>Could not tell (no token, network, API hiccup) — treat as recovered.</summary>
|
||||
Unknown,
|
||||
|
||||
/// <summary>The broadcast is still live/ready: the push landed and the show continues.</summary>
|
||||
Live,
|
||||
|
||||
/// <summary>The broadcast is complete. It cannot be resumed; the push is talking to a dead ingest.</summary>
|
||||
Complete,
|
||||
}
|
||||
|
||||
/// <summary>Everything the recovery loop needs from the app, as delegates so it can be tested
|
||||
/// without ffmpeg, without a network, and without a window.</summary>
|
||||
public sealed class StreamRecoverySteps
|
||||
{
|
||||
/// <summary>Recreates the audio pipe server. The old one is unusable after its client died
|
||||
/// (single-instance server), and the encoder cannot start without it.</summary>
|
||||
public required Func<CancellationToken, Task> RestartAudio { get; init; }
|
||||
|
||||
/// <summary>Starts the push. True when the encoder came up.</summary>
|
||||
public required Func<CancellationToken, Task<bool>> StartPush { get; init; }
|
||||
|
||||
/// <summary>Asks YouTube whether the broadcast survived. Only called after a push starts.</summary>
|
||||
public required Func<CancellationToken, Task<BroadcastLiveness>> CheckBroadcast { get; init; }
|
||||
|
||||
/// <summary>State for the alert stack: attempt numbers and the outcome.</summary>
|
||||
public required Action<string> Report { get; init; }
|
||||
|
||||
/// <summary>The record: one line per attempt, into the app log.</summary>
|
||||
public required Action<string> Log { get; init; }
|
||||
|
||||
public Func<TimeSpan, CancellationToken, Task> Delay { get; init; }
|
||||
= (delay, ct) => delay <= TimeSpan.Zero ? Task.CompletedTask : Task.Delay(delay, ct);
|
||||
}
|
||||
|
||||
public enum RecoveryOutcome
|
||||
{
|
||||
Recovered,
|
||||
GaveUp,
|
||||
Cancelled,
|
||||
BroadcastComplete,
|
||||
}
|
||||
|
||||
public sealed record RecoveryResult(RecoveryOutcome Outcome, int Attempts, TimeSpan Elapsed);
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·1 — the blip retry. When the encoder dies while the session is live, relaunch the same push
|
||||
/// against the same ingest, restarting the audio pipe each time (its server is single-instance and the
|
||||
/// dead client leaves it unusable).
|
||||
/// <para><b>The check that stops us lying:</b> a reconnect can succeed at the socket level after
|
||||
/// YouTube has already ended the broadcast. So each successful start asks the API whether the broadcast
|
||||
/// is still there; "complete" ends recovery instead of showing a live sign over a dead stream.</para>
|
||||
/// </summary>
|
||||
public sealed class StreamRecovery
|
||||
{
|
||||
private readonly StreamRetryPolicy _policy;
|
||||
private readonly StreamRecoverySteps _steps;
|
||||
|
||||
public StreamRecovery(StreamRetryPolicy policy, StreamRecoverySteps steps)
|
||||
{
|
||||
_policy = policy;
|
||||
_steps = steps;
|
||||
}
|
||||
|
||||
public async Task<RecoveryResult> RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
var attempts = 0;
|
||||
|
||||
for (var attempt = 0; attempt < _policy.Attempts; attempt++)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) return Result(RecoveryOutcome.Cancelled);
|
||||
attempts = attempt + 1;
|
||||
|
||||
var wait = _policy.WaitBefore(attempt);
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
try { await _steps.Delay(wait, cancellationToken).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { return Result(RecoveryOutcome.Cancelled); }
|
||||
}
|
||||
|
||||
if (cancellationToken.IsCancellationRequested) return Result(RecoveryOutcome.Cancelled);
|
||||
|
||||
_steps.Report($"Stream dropped — reconnecting (attempt {attempts} of {_policy.Attempts})");
|
||||
_steps.Log($"RECONNECT: attempt {attempts} of {_policy.Attempts} — restarting the audio pipe and the push");
|
||||
|
||||
try
|
||||
{
|
||||
await _steps.RestartAudio(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_steps.Log($"RECONNECT: audio pipe restart failed on attempt {attempts}: {ex.Message}");
|
||||
continue;
|
||||
}
|
||||
|
||||
bool started;
|
||||
try
|
||||
{
|
||||
started = await _steps.StartPush(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_steps.Log($"RECONNECT: push restart failed on attempt {attempts}: {ex.Message}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!started)
|
||||
{
|
||||
_steps.Log($"RECONNECT: attempt {attempts} of {_policy.Attempts} failed — the encoder did not come up");
|
||||
continue;
|
||||
}
|
||||
|
||||
var liveness = BroadcastLiveness.Unknown;
|
||||
try
|
||||
{
|
||||
liveness = await _steps.CheckBroadcast(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_steps.Log($"RECONNECT: could not check the broadcast on attempt {attempts}: {ex.Message}");
|
||||
}
|
||||
|
||||
if (liveness == BroadcastLiveness.Complete)
|
||||
{
|
||||
_steps.Report("Stream ended — YouTube reports this broadcast complete. It cannot be resumed.");
|
||||
_steps.Log("RECONNECT: push came back, but the broadcast is complete — cannot resume");
|
||||
return Result(RecoveryOutcome.BroadcastComplete);
|
||||
}
|
||||
|
||||
_steps.Report($"Stream recovered after {clock.Elapsed.TotalSeconds:0.0} s");
|
||||
_steps.Log($"RECONNECT: push re-established after {clock.Elapsed.TotalSeconds:0.0} s — still live");
|
||||
return Result(RecoveryOutcome.Recovered);
|
||||
}
|
||||
|
||||
_steps.Report($"Stream dropped — {_policy.Attempts} attempts failed. The stream is off air.");
|
||||
_steps.Log($"RECONNECT: gave up after {_policy.Attempts} attempts — stream is off air");
|
||||
return Result(RecoveryOutcome.GaveUp);
|
||||
|
||||
RecoveryResult Result(RecoveryOutcome outcome) => new(outcome, attempts, clock.Elapsed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·1: how many times to relaunch the push, and how long to wait between tries.
|
||||
/// <para><b>Minimum waits, deliberately</b> (creator ruling 2026-11-05): YouTube is not generous about
|
||||
/// holding a broadcast whose ingest has gone quiet, so every second spent not pushing is grace spent.
|
||||
/// The first attempt is immediate — there is nothing to wait for when the socket has just died.</para>
|
||||
/// <para>Pure so the schedule is asserted without waiting on it.</para>
|
||||
/// </summary>
|
||||
public sealed class StreamRetryPolicy
|
||||
{
|
||||
/// <summary>Immediate, then +1 s, +2 s, +3 s — four attempts inside about six seconds.</summary>
|
||||
public static readonly StreamRetryPolicy Default = new(new[]
|
||||
{
|
||||
TimeSpan.Zero,
|
||||
TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(2),
|
||||
TimeSpan.FromSeconds(3),
|
||||
});
|
||||
|
||||
public IReadOnlyList<TimeSpan> Waits { get; }
|
||||
|
||||
public StreamRetryPolicy(IReadOnlyList<TimeSpan> waits)
|
||||
{
|
||||
if (waits == null || waits.Count == 0)
|
||||
throw new ArgumentException("A retry policy needs at least one attempt.", nameof(waits));
|
||||
Waits = waits;
|
||||
}
|
||||
|
||||
public int Attempts => Waits.Count;
|
||||
|
||||
/// <summary>The wait BEFORE <paramref name="attemptIndex"/> (0-based).</summary>
|
||||
public TimeSpan WaitBefore(int attemptIndex)
|
||||
=> attemptIndex < 0 || attemptIndex >= Waits.Count ? TimeSpan.Zero : Waits[attemptIndex];
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 3·20: reads the channel's recent Super Chat / Super Sticker events so a session report can be
|
||||
/// shown without storing anything.
|
||||
/// <para><b>YouTube is the authority.</b> This service only asks; it keeps no ledger, and the events it
|
||||
/// returns are the ones YouTube still considers valid (removed or refunded events do not come back).</para>
|
||||
/// <para>Scope: the endpoint is authorised by the app's existing <c>auth/youtube</c> scope, so no
|
||||
/// re-consent is needed — unlike the Analytics API, which does.</para>
|
||||
/// </summary>
|
||||
public interface ISuperChatEventSource
|
||||
{
|
||||
/// <summary>The most recent events for a channel (YouTube caps the window at roughly 30 days).</summary>
|
||||
Task<IReadOnlyList<SuperChatEvent>> GetRecentAsync(
|
||||
string channelId, int maxResults = 200, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class SuperChatEventService : ISuperChatEventSource
|
||||
{
|
||||
private const string ApiBase = "https://www.googleapis.com/youtube/v3";
|
||||
private readonly YouTubeAuthService _auth;
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public SuperChatEventService(YouTubeAuthService auth, HttpClient? http = null)
|
||||
{
|
||||
_auth = auth;
|
||||
_http = http ?? new HttpClient();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<SuperChatEvent>> GetRecentAsync(
|
||||
string channelId, int maxResults = 200, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(channelId)) return Array.Empty<SuperChatEvent>();
|
||||
if (_auth.CurrentChannel?.AccessToken is not { } token) return Array.Empty<SuperChatEvent>();
|
||||
|
||||
_http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var url = $"{ApiBase}/superChatEvents?part=snippet&maxResults={Math.Clamp(maxResults, 1, 200)}" +
|
||||
$"&channelId={Uri.EscapeDataString(channelId)}";
|
||||
try
|
||||
{
|
||||
var response = await _http.GetAsync(url, cancellationToken).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
AppLog.Write($"superChatEvents.list failed: {(int)response.StatusCode}");
|
||||
return Array.Empty<SuperChatEvent>();
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Parse(json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"superChatEvents.list failed: {ex.Message}");
|
||||
return Array.Empty<SuperChatEvent>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pure parse of a <c>superChatEvents.list</c> response. Both event types carry their money
|
||||
/// in a different object, so a sticker must not be silently dropped.</summary>
|
||||
internal static IReadOnlyList<SuperChatEvent> Parse(string json)
|
||||
{
|
||||
var events = new List<SuperChatEvent>();
|
||||
using var document = JsonDocument.Parse(json);
|
||||
if (!document.RootElement.TryGetProperty("items", out var items)) return events;
|
||||
|
||||
foreach (var item in items.EnumerateArray())
|
||||
{
|
||||
if (!item.TryGetProperty("snippet", out var snippet)) continue;
|
||||
|
||||
var id = item.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? string.Empty : string.Empty;
|
||||
var publishedAt = snippet.TryGetProperty("publishedAt", out var published)
|
||||
&& DateTime.TryParse(published.GetString(), out var parsed)
|
||||
? parsed.ToUniversalTime()
|
||||
: DateTime.UtcNow;
|
||||
|
||||
var kind = ChatEventKind.SuperChat;
|
||||
JsonElement details;
|
||||
if (snippet.TryGetProperty("superChatDetails", out var chat))
|
||||
details = chat;
|
||||
else if (snippet.TryGetProperty("superStickerDetails", out var sticker))
|
||||
{
|
||||
details = sticker;
|
||||
kind = ChatEventKind.SuperSticker;
|
||||
}
|
||||
else
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var micros = details.TryGetProperty("amountMicros", out var amount)
|
||||
&& amount.ValueKind == JsonValueKind.Number
|
||||
&& amount.TryGetInt64(out var value)
|
||||
? value
|
||||
: 0;
|
||||
var currency = details.TryGetProperty("currency", out var cur) && cur.ValueKind == JsonValueKind.String
|
||||
? cur.GetString() ?? string.Empty
|
||||
: string.Empty;
|
||||
var display = details.TryGetProperty("amountDisplayString", out var shown)
|
||||
&& shown.ValueKind == JsonValueKind.String
|
||||
? shown.GetString()
|
||||
: null;
|
||||
|
||||
events.Add(new SuperChatEvent(id, kind, micros, currency, display, publishedAt));
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Services.Audio;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// One video FILE played through ffmpeg — the shared pipe behind every clip, so a media
|
||||
/// layer (TASK 21) and an alert clip (TASK 47) decode identically. Owns two subprocesses
|
||||
/// on the same file: video (<c>rawvideo bgra</c>, scaled to the target rect) and audio
|
||||
/// (<c>f32le -ac 2 -ar 48000</c>, matching the mixer's native format so no resampler is
|
||||
/// needed). Both are paced to real time, so the picture and the sound stay together even
|
||||
/// though they arrive on separate pipes.
|
||||
/// <para><b>Looping is the media case</b>: on natural EOF the whole pass restarts — a fresh
|
||||
/// pair of processes, because a <see cref="Process"/> cannot be re-started. An alert clip
|
||||
/// never loops, so its wrapper simply never sets <see cref="Looping"/>.</para>
|
||||
/// <para>The seams (locator, process factory, frame-rate probe, delay) exist so tests drive
|
||||
/// a fake decoder with no ffmpeg, no codec, and no audio device.</para>
|
||||
/// </summary>
|
||||
public sealed class VideoClipPipe : IDisposable
|
||||
{
|
||||
/// <summary>Pipe read size. A 1080p BGRA frame is ~8 MB, so 64 KB reads meant 127 awaits and
|
||||
/// 127 reader calls per frame; 256 KB keeps the syscall count sane without a large allocation.</summary>
|
||||
private const int ReadBufferBytes = 256 * 1024;
|
||||
|
||||
public const int AudioSampleRate = 48000;
|
||||
public const int AudioChannels = 2;
|
||||
private const int AudioChunkFloats = 4800; // 50 ms of stereo
|
||||
|
||||
public event Action<VideoFrame>? FrameAvailable;
|
||||
public event Action<AudioSample>? AudioAvailable;
|
||||
public event Action? Completed;
|
||||
|
||||
/// <summary>Restart the pass on natural EOF (media/BRB loops).</summary>
|
||||
public bool Looping { get; set; }
|
||||
|
||||
private readonly string _path;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
private readonly IFfmpegLocator _locator;
|
||||
private readonly Func<IDecodeProcess> _processFactory;
|
||||
private readonly IFrameRateProbe? _probe;
|
||||
private readonly Func<TimeSpan, CancellationToken, Task> _delay;
|
||||
private readonly bool _audio;
|
||||
private readonly ChromaKeyOptions? _key;
|
||||
private readonly FramePacer _pacer = new();
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private bool _running;
|
||||
private IDecodeProcess? _activeVideo;
|
||||
private IDecodeProcess? _activeAudio;
|
||||
|
||||
public VideoClipPipe(
|
||||
string path,
|
||||
int width,
|
||||
int height,
|
||||
IFfmpegLocator locator,
|
||||
Func<IDecodeProcess> processFactory,
|
||||
IFrameRateProbe? frameRateProbe = null,
|
||||
Func<TimeSpan, CancellationToken, Task>? delay = null,
|
||||
bool audio = true,
|
||||
ChromaKeyOptions? chromaKey = null)
|
||||
{
|
||||
_path = path;
|
||||
_width = width;
|
||||
_height = height;
|
||||
_locator = locator;
|
||||
_processFactory = processFactory;
|
||||
_probe = frameRateProbe;
|
||||
_delay = delay ?? ((t, ct) => Task.Delay(t, ct));
|
||||
_audio = audio;
|
||||
_key = chromaKey;
|
||||
}
|
||||
|
||||
/// <summary>Runs one pass (or a loop of passes). A pass that ended naturally leaves the pipe
|
||||
/// restartable — the creator can ask a finished clip to play again, which is what the Loop
|
||||
/// switch and the "Play again" button need.</summary>
|
||||
public Task StartAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_running) return Task.CompletedTask;
|
||||
_running = true;
|
||||
_ = Task.Run(RunAsync, CancellationToken.None);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
_cts.Cancel();
|
||||
Kill(_activeVideo);
|
||||
Kill(_activeAudio);
|
||||
_running = false;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_running = false;
|
||||
_cts.Dispose();
|
||||
_activeVideo?.Dispose();
|
||||
_activeAudio?.Dispose();
|
||||
}
|
||||
|
||||
private void StopInternal()
|
||||
{
|
||||
_running = false;
|
||||
Kill(_activeVideo);
|
||||
Kill(_activeAudio);
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
var ct = _cts.Token;
|
||||
var frames = 0;
|
||||
var chunks = 0;
|
||||
try
|
||||
{
|
||||
double? frameRate = null;
|
||||
if (_probe != null)
|
||||
frameRate = await _probe.ProbeAsync(_path, ct).ConfigureAwait(false);
|
||||
var frameDuration = frameRate is > 0 ? TimeSpan.FromSeconds(1.0 / frameRate.Value) : TimeSpan.Zero;
|
||||
|
||||
var ffmpegPath = await _locator.LocateAsync(ct).ConfigureAwait(false);
|
||||
|
||||
do
|
||||
{
|
||||
// Both pipes per pass, awaited together: a restart must begin a new
|
||||
// video AND a new audio stream, or the picture drifts from the sound
|
||||
// after the first loop.
|
||||
var video = RunVideoAsync(ffmpegPath, frameDuration, ct);
|
||||
var audio = _audio ? RunAudioAsync(ffmpegPath, ct) : Task.FromResult(0);
|
||||
frames += await video.ConfigureAwait(false);
|
||||
chunks += await audio.ConfigureAwait(false);
|
||||
}
|
||||
while (Looping && !ct.IsCancellationRequested);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_running = false;
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A failed decode is not fatal: the alert layer falls back to its animations,
|
||||
// and a media layer just holds its last frame.
|
||||
AppLog.Write($"Video clip decode failed ({Path.GetFileName(_path)}): {ex.Message}");
|
||||
_running = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_running = false;
|
||||
if (!ct.IsCancellationRequested)
|
||||
{
|
||||
AppLog.Write($"Video clip end: {Path.GetFileName(_path)} frames={frames} audioChunks={chunks}");
|
||||
Completed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> RunVideoAsync(string ffmpegPath, TimeSpan frameDuration, CancellationToken ct)
|
||||
{
|
||||
var passStart = Stopwatch.GetTimestamp();
|
||||
var args =
|
||||
$"-hide_banner -loglevel error -i \"{_path}\" " +
|
||||
$"-f rawvideo -pix_fmt bgra -vf {VideoFilterChain.BuildVideo(_width, _height, _key)} -an -";
|
||||
using var process = _processFactory();
|
||||
_activeVideo = process;
|
||||
process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpegPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true,
|
||||
});
|
||||
|
||||
var reader = new RawVideoFrameReader(_width, _height);
|
||||
var buffer = new byte[ReadBufferBytes];
|
||||
_pacer.Reset();
|
||||
var stream = process.StandardOutput;
|
||||
var frames = 0;
|
||||
while (!ct.IsCancellationRequested && !process.HasExited)
|
||||
{
|
||||
var read = await stream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
|
||||
if (read <= 0) break;
|
||||
var chunk = new byte[read];
|
||||
Buffer.BlockCopy(buffer, 0, chunk, 0, read);
|
||||
foreach (var frame in reader.Feed(chunk))
|
||||
{
|
||||
frames++;
|
||||
FrameAvailable?.Invoke(frame);
|
||||
if (frameDuration > TimeSpan.Zero)
|
||||
{
|
||||
// Deadline pacing: sleep what is LEFT of this frame's interval, so the frame's
|
||||
// own work is not added on top (see FramePacer).
|
||||
var wait = _pacer.DelayFor(frameDuration, Stopwatch.GetElapsedTime(passStart));
|
||||
if (wait > TimeSpan.Zero)
|
||||
await _delay(wait, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
_activeVideo = null;
|
||||
return frames;
|
||||
}
|
||||
|
||||
private async Task<int> RunAudioAsync(string ffmpegPath, CancellationToken ct)
|
||||
{
|
||||
var args =
|
||||
$"-hide_banner -loglevel error -i \"{_path}\" " +
|
||||
$"-f f32le -ac {AudioChannels} -ar {AudioSampleRate} -vn -";
|
||||
using var process = _processFactory();
|
||||
_activeAudio = process;
|
||||
process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpegPath,
|
||||
Arguments = args,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true,
|
||||
});
|
||||
|
||||
var stream = process.StandardOutput;
|
||||
var passStart = Stopwatch.GetTimestamp();
|
||||
var pacer = new FramePacer();
|
||||
var raw = new byte[65536];
|
||||
var carry = Array.Empty<byte>();
|
||||
var floatScratch = new float[AudioChunkFloats];
|
||||
var floatIndex = 0;
|
||||
var chunks = 0;
|
||||
// The pipe is byte-delimited only: a read may split a float, so leftover
|
||||
// bytes are carried into the next read instead of dropped (a dropped
|
||||
// half-float would desync the entire stream).
|
||||
while (!ct.IsCancellationRequested && !process.HasExited)
|
||||
{
|
||||
var read = await stream.ReadAsync(raw, 0, raw.Length, ct).ConfigureAwait(false);
|
||||
if (read <= 0) break;
|
||||
var total = carry.Length + read;
|
||||
var bytes = total <= raw.Length ? raw : new byte[total];
|
||||
if (carry.Length > 0)
|
||||
{
|
||||
Buffer.BlockCopy(carry, 0, bytes, 0, carry.Length);
|
||||
Buffer.BlockCopy(raw, 0, bytes, carry.Length, read);
|
||||
}
|
||||
var floatsTo = total - (total % 4);
|
||||
for (var i = 0; i < floatsTo && floatIndex < floatScratch.Length; i += 4)
|
||||
floatScratch[floatIndex++] = BitConverter.ToSingle(bytes, i);
|
||||
carry = total > floatsTo ? bytes[floatsTo..total] : Array.Empty<byte>();
|
||||
|
||||
while (floatIndex == floatScratch.Length)
|
||||
{
|
||||
chunks++;
|
||||
AudioAvailable?.Invoke(new AudioSample(floatScratch, AudioSampleRate, AudioChannels));
|
||||
// Deadline pacing, exactly like the video pipe: sleep only what is LEFT of this
|
||||
// chunk's 50 ms. A fixed sleep added the read cost every chunk, so audio fell
|
||||
// progressively behind the picture on a long clip (2026-11-05).
|
||||
var wait = pacer.DelayFor(
|
||||
TimeSpan.FromSeconds(AudioChunkFloats / (double)(AudioSampleRate * AudioChannels)),
|
||||
Stopwatch.GetElapsedTime(passStart));
|
||||
if (wait > TimeSpan.Zero)
|
||||
await _delay(wait, ct).ConfigureAwait(false);
|
||||
floatScratch = new float[AudioChunkFloats];
|
||||
floatIndex = 0;
|
||||
}
|
||||
}
|
||||
_activeAudio = null;
|
||||
return chunks;
|
||||
}
|
||||
|
||||
private static void Kill(IDecodeProcess? process)
|
||||
{
|
||||
try { process?.Kill(); } catch { /* already exited */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 64: the key's settings for one layer, in the app's own terms. <see cref="Color"/> is the
|
||||
/// screen as the creator's camera saw it (whatever the detector measured), not a canonical green.
|
||||
/// </summary>
|
||||
public sealed record ChromaKeyOptions(
|
||||
bool Enabled,
|
||||
string Color,
|
||||
double Similarity,
|
||||
double Softness,
|
||||
bool Spill,
|
||||
ChromaScreen Screen = ChromaScreen.Green)
|
||||
{
|
||||
public static readonly ChromaKeyOptions Off = new(false, "#00B140", 0.12, 0.08, true);
|
||||
|
||||
/// <summary>Creator-facing defaults when a detector suggestion is accepted: a little
|
||||
/// tolerance around the measured colour, a soft edge, and spill cleanup on.</summary>
|
||||
public static ChromaKeyOptions For(ChromaKeySuggestion suggestion)
|
||||
=> new(true, suggestion.ColorHex ?? "#00B140", 0.12, 0.08, true, suggestion.Screen);
|
||||
|
||||
/// <summary>Identifies this look, so decode sessions can be shared per look rather than
|
||||
/// duplicated per layer (two layers keyed identically reuse one decoder).</summary>
|
||||
public string Signature => Enabled
|
||||
? FormattableString.Invariant(
|
||||
$"{Color.ToUpperInvariant()}|{Similarity:0.###}|{Softness:0.###}|{Spill}|{Screen}")
|
||||
: "off";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TASK 64: builds the ffmpeg filter chain for a clip. Keying happens IN THE DECODE PIPE, not in
|
||||
/// this process: the bundled ffmpeg keys with slices of its own CPU cost, emits straight-alpha
|
||||
/// BGRA (verified against the shipped binary: keyed pixels come out with alpha 0), and — the
|
||||
/// point — the pipe is upstream of BOTH consumers (the shared preview bitmap and the compositor's
|
||||
/// frame), so the creator's preview and the stream cannot disagree.
|
||||
/// <para>Order matters: scale first (cheaper, and the edge is computed at output size), then key,
|
||||
/// then despill, then force BGRA so the alpha survives the pipe.</para>
|
||||
/// </summary>
|
||||
public static class VideoFilterChain
|
||||
{
|
||||
/// <summary>The video half of a clip's `-vf`. Unkeyed clips keep the old single-scale chain.</summary>
|
||||
public static string BuildVideo(int width, int height, ChromaKeyOptions? key = null)
|
||||
{
|
||||
var scale = $"scale={width}:{height}";
|
||||
if (key is not { Enabled: true }) return scale;
|
||||
|
||||
var parts = new List<string>(4)
|
||||
{
|
||||
scale,
|
||||
$"colorkey={NormalizeColor(key.Color)}:{Number(key.Similarity)}:{Number(key.Softness)}",
|
||||
};
|
||||
if (key.Spill)
|
||||
parts.Add($"despill=type={(key.Screen == ChromaScreen.Blue ? "blue" : "green")}");
|
||||
parts.Add("format=bgra");
|
||||
return string.Join(",", parts);
|
||||
}
|
||||
|
||||
/// <summary>ffmpeg takes `0xRRGGBB`. Anything unparseable falls back to the app default
|
||||
/// rather than producing a filter string ffmpeg would reject at spawn time.</summary>
|
||||
private static string NormalizeColor(string? hex)
|
||||
{
|
||||
var value = (hex ?? string.Empty).Trim();
|
||||
if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) value = value[2..];
|
||||
if (value.StartsWith('#')) value = value[1..];
|
||||
if (value.Length != 6) return "0x00B140";
|
||||
foreach (var c in value)
|
||||
if (!Uri.IsHexDigit(c)) return "0x00B140";
|
||||
return "0x" + value.ToUpperInvariant();
|
||||
}
|
||||
|
||||
private static string Number(double value)
|
||||
=> Math.Clamp(value, 0, 1).ToString("0.###", CultureInfo.InvariantCulture);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ytLive.Helpers;
|
||||
|
||||
namespace ytLive.Services;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 39·2: the two numbers YouTube only publishes through the **Analytics** API — long-form watch
|
||||
/// hours (trailing 12 months) and Shorts-feed views (trailing 90 days).
|
||||
/// <para>This is the one place the app needs a scope beyond <c>auth/youtube</c>: the Analytics API
|
||||
/// requires <c>yt-analytics.readonly</c>, which means a one-time Google re-consent. Until that scope is
|
||||
/// granted, the drawer says so instead of inventing numbers.</para>
|
||||
/// <para>Values are estimates: Analytics lags, and YouTube's own validity filtering decides what counts
|
||||
/// towards eligibility.</para>
|
||||
/// </summary>
|
||||
public interface IWatchMetricsSource
|
||||
{
|
||||
/// <summary>Estimated public long-form watch hours over the trailing 12 months, or null when the
|
||||
/// Analytics scope is not granted / the read failed.</summary>
|
||||
Task<long?> GetLongFormWatchHoursAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Shorts-feed views over the trailing 90 days, or null.</summary>
|
||||
Task<long?> GetShortsViewsAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class YouTubeAnalyticsService : IWatchMetricsSource
|
||||
{
|
||||
private const string ApiBase = "https://youtubeanalytics.googleapis.com/v2/reports";
|
||||
|
||||
private readonly YouTubeAuthService _auth;
|
||||
private readonly HttpClient _http;
|
||||
private readonly Func<DateTime> _now;
|
||||
|
||||
public YouTubeAnalyticsService(YouTubeAuthService auth, HttpClient? http = null, Func<DateTime>? now = null)
|
||||
{
|
||||
_auth = auth;
|
||||
_http = http ?? new HttpClient();
|
||||
_now = now ?? (() => DateTime.UtcNow);
|
||||
}
|
||||
|
||||
public async Task<long?> GetLongFormWatchHoursAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Minutes watched for long-form videos over the trailing year → hours.
|
||||
var minutes = await QueryTotalAsync(
|
||||
"estimatedMinutesWatched", "creatorContentType==video", 365, cancellationToken).ConfigureAwait(false);
|
||||
return minutes is null ? null : (long)Math.Round(minutes.Value / 60.0);
|
||||
}
|
||||
|
||||
public async Task<long?> GetShortsViewsAsync(CancellationToken cancellationToken = default)
|
||||
=> await QueryTotalAsync("views", "creatorContentType==shorts", 90, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
private async Task<long?> QueryTotalAsync(
|
||||
string metric, string filter, int days, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_auth.HasAnalyticsScope) return null;
|
||||
if (_auth.CurrentChannel?.AccessToken is not { } token) return null;
|
||||
|
||||
var end = _now().Date;
|
||||
var start = end.AddDays(-days);
|
||||
var url = $"{ApiBase}?ids=channel==MINE" +
|
||||
$"&startDate={start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}" +
|
||||
$"&endDate={end.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}" +
|
||||
$"&metrics={Uri.EscapeDataString(metric)}" +
|
||||
$"&filters={Uri.EscapeDataString(filter)}";
|
||||
|
||||
try
|
||||
{
|
||||
_http.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
var response = await _http.GetAsync(url, cancellationToken).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
AppLog.Write($"Analytics query failed ({metric}): {(int)response.StatusCode}");
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
return ParseTotal(json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"Analytics query failed ({metric}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pure: the Analytics API answers with columnHeaders + rows; a channel with no data in the
|
||||
/// window returns no rows at all, which must read as "no data" rather than zero.</summary>
|
||||
internal static long? ParseTotal(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
if (!document.RootElement.TryGetProperty("rows", out var rows)) return null;
|
||||
if (rows.ValueKind != JsonValueKind.Array || rows.GetArrayLength() == 0) return null;
|
||||
var row = rows[0];
|
||||
if (row.ValueKind != JsonValueKind.Array || row.GetArrayLength() == 0) return null;
|
||||
var value = row[0];
|
||||
return value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out var total) ? total : null;
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,14 @@ public class YouTubeChatService : IDisposable
|
||||
|
||||
public event Action<ChatMessage>? MessageReceived;
|
||||
|
||||
internal void NotifyChatEnded() => ChatEnded?.Invoke();
|
||||
|
||||
/// <summary>Raised when YouTube puts a <c>chatEndedEvent</c> in the feed — the chat is over, which
|
||||
/// means the broadcast is. TASK 32·2 uses it as a cheap prompt to check the broadcast status
|
||||
/// immediately instead of waiting for the next health poll. It never decides anything by itself:
|
||||
/// <c>liveBroadcasts.list</c> stays authoritative.</summary>
|
||||
public event Action? ChatEnded;
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOpts = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -80,6 +88,7 @@ public class YouTubeChatService : IDisposable
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var page = ParsePage(json);
|
||||
if (json.Contains("chatEndedEvent", StringComparison.Ordinal)) NotifyChatEnded();
|
||||
|
||||
if (page.NextPageToken != null)
|
||||
_nextPageToken = page.NextPageToken;
|
||||
@@ -106,6 +115,27 @@ public class YouTubeChatService : IDisposable
|
||||
/// <summary>One liveChat/messages page → typed chat messages + pagination +
|
||||
/// the server's poll cadence. Internal + separated from the HTTP so the six
|
||||
/// event parses are deterministically testable without any network.</summary>
|
||||
/// <summary>True for the types that carry something a viewer should read. `snippet.hasDisplayContent`
|
||||
/// is authoritative when present; tombstones and chat-mode events are never shown (they exist to
|
||||
/// mark a deletion or a mode change, and carry no message).</summary>
|
||||
internal static bool HasDisplayableContent(JsonElement snippet, string type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case "tombstone":
|
||||
case "chatEndedEvent":
|
||||
case "sponsorOnlyModeStartedEvent":
|
||||
case "sponsorOnlyModeEndedEvent":
|
||||
case "messageDeletedEvent":
|
||||
case "messageRetractedEvent":
|
||||
case "userBannedEvent":
|
||||
return false;
|
||||
}
|
||||
|
||||
return !snippet.TryGetProperty("hasDisplayContent", out var has)
|
||||
|| has.ValueKind != JsonValueKind.False;
|
||||
}
|
||||
|
||||
internal static ChatPage ParsePage(string json)
|
||||
{
|
||||
var data = JsonSerializer.Deserialize<JsonElement>(json);
|
||||
@@ -126,9 +156,16 @@ public class YouTubeChatService : IDisposable
|
||||
{
|
||||
var snippet = item.GetProperty("snippet");
|
||||
var type = snippet.TryGetProperty("type", out var t) && t.ValueKind == JsonValueKind.String
|
||||
? t.GetString()
|
||||
? t.GetString() ?? "textMessageEvent"
|
||||
: "textMessageEvent";
|
||||
|
||||
// YouTube owns moderation: blocked words, held-for-review messages and deleted
|
||||
// messages are filtered before the feed ever reaches us (2026-11-05 ruling —
|
||||
// TASK 49's local wordlist retired). What DOES arrive are event markers rather
|
||||
// than chat: a `tombstone` (a deleted message's placeholder, carrying no text at
|
||||
// all) and the silent chat-mode events. They get no row on the overlay.
|
||||
if (!HasDisplayableContent(snippet, type)) continue;
|
||||
|
||||
var message = new ChatMessage
|
||||
{
|
||||
Id = item.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? Guid.NewGuid().ToString() : Guid.NewGuid().ToString(),
|
||||
@@ -157,9 +194,15 @@ public class YouTubeChatService : IDisposable
|
||||
message.Kind = ChatEventKind.SuperChat;
|
||||
if (snippet.TryGetProperty("superChatDetails", out var scDetails))
|
||||
{
|
||||
if (scDetails.TryGetProperty("displayString", out var display)
|
||||
// YouTube names the pre-rendered amount `amountDisplayString`; the old
|
||||
// `displayString` lookup never matched, so every Super Chat fell back to a
|
||||
// recomposed amount and mangled non-dollar locales (fixed 2026-11-05).
|
||||
if (scDetails.TryGetProperty("amountDisplayString", out var display)
|
||||
&& display.ValueKind == JsonValueKind.String)
|
||||
message.SuperChatDisplayString = display.GetString();
|
||||
else if (scDetails.TryGetProperty("displayString", out var legacyDisplay)
|
||||
&& legacyDisplay.ValueKind == JsonValueKind.String)
|
||||
message.SuperChatDisplayString = legacyDisplay.GetString();
|
||||
if (scDetails.TryGetProperty("amountMicros", out var amt)
|
||||
&& amt.ValueKind == JsonValueKind.Number)
|
||||
message.SuperChatAmount = amt.GetDouble() / 1_000_000.0;
|
||||
|
||||
@@ -182,6 +182,25 @@ public class YouTubeStreamService
|
||||
/// "public"), read from YouTube rather than trusted from local state — the creator can
|
||||
/// change visibility mid-stream from the broadcast form. Null when signed out or the
|
||||
/// read fails (the caller then does nothing destructive).</summary>
|
||||
/// <summary>TASK 32·1: the broadcast's lifecycle status (<c>created</c>/<c>ready</c>/<c>testing</c>/
|
||||
/// <c>live</c>/<c>complete</c>), or null when it cannot be read. Used after a reconnect: a push can
|
||||
/// succeed at the socket level while YouTube has already ended the broadcast.</summary>
|
||||
public async Task<string?> GetBroadcastStatusAsync(string broadcastId)
|
||||
{
|
||||
if (!await EnsureToken()) return null;
|
||||
|
||||
_http.DefaultRequestHeaders.Authorization = new("Bearer", _auth.CurrentChannel!.AccessToken);
|
||||
var response = await _http.GetAsync(
|
||||
$"{ApiBase}/liveBroadcasts?part=status&id={Uri.EscapeDataString(broadcastId)}");
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
|
||||
var json = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync());
|
||||
if (!json.TryGetProperty("items", out var items) || items.GetArrayLength() == 0) return null;
|
||||
if (!items[0].TryGetProperty("status", out var status)) return null;
|
||||
if (!status.TryGetProperty("lifeCycleStatus", out var lifeCycle)) return null;
|
||||
return lifeCycle.ValueKind == JsonValueKind.String ? lifeCycle.GetString() : null;
|
||||
}
|
||||
|
||||
public async Task<string?> GetBroadcastPrivacyAsync(string broadcastId)
|
||||
{
|
||||
if (!await EnsureToken()) return null;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Windows.Input;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Models;
|
||||
@@ -25,6 +28,16 @@ public sealed class YppTrackerViewModel : ViewModelBase
|
||||
private readonly Func<bool> _isConnected;
|
||||
private readonly Func<string?> _displayName;
|
||||
|
||||
// TASK 3·20 — the session report is DERIVED, never stored: ask YouTube for the channel's recent
|
||||
// reward events and roll them up for the window that starts when this session did.
|
||||
private readonly Func<ISuperChatEventSource> _rewardEvents;
|
||||
private readonly Func<string?> _channelId;
|
||||
private readonly Func<DateTime?> _sessionStartedAtUtc;
|
||||
|
||||
// TASK 39·2 — the two numbers only the Analytics API publishes. Null source (or a missing scope)
|
||||
// means the drawer says so rather than inventing values.
|
||||
private readonly Func<IWatchMetricsSource?> _watchMetrics;
|
||||
|
||||
private bool _isDrawerOpen;
|
||||
private bool _isLoading;
|
||||
private bool _isRefreshing;
|
||||
@@ -43,12 +56,20 @@ public sealed class YppTrackerViewModel : ViewModelBase
|
||||
Func<LayoutStore> store,
|
||||
Func<ChannelStatsService> stats,
|
||||
Func<bool> isConnected,
|
||||
Func<string?> displayName)
|
||||
Func<string?> displayName,
|
||||
Func<ISuperChatEventSource>? rewardEvents = null,
|
||||
Func<string?>? channelId = null,
|
||||
Func<DateTime?>? sessionStartedAtUtc = null,
|
||||
Func<IWatchMetricsSource?>? watchMetrics = null)
|
||||
{
|
||||
_store = store;
|
||||
_stats = stats;
|
||||
_isConnected = isConnected;
|
||||
_displayName = displayName;
|
||||
_rewardEvents = rewardEvents ?? (() => null!);
|
||||
_channelId = channelId ?? (() => null);
|
||||
_sessionStartedAtUtc = sessionStartedAtUtc ?? (() => null);
|
||||
_watchMetrics = watchMetrics ?? (() => null);
|
||||
|
||||
RefreshCommand = new RelayCommand(_ => _ = RefreshAsync());
|
||||
ToggleDrawerCommand = new RelayCommand(_ => IsDrawerOpen = !IsDrawerOpen);
|
||||
@@ -58,6 +79,7 @@ public sealed class YppTrackerViewModel : ViewModelBase
|
||||
OpenAdsenseCommand = new RelayCommand(_ => OpenUrl(AdsenseGuideUrl));
|
||||
|
||||
(_twoFactorEnabled, _adsenseLinked) = _store().LoadYppChecklist();
|
||||
_showMonetaryMetrics = _store().LoadShowMonetaryMetrics();
|
||||
_lastRefreshedAtUtc = _store().LoadYppLastRefreshedAtUtc();
|
||||
}
|
||||
|
||||
@@ -92,6 +114,63 @@ public sealed class YppTrackerViewModel : ViewModelBase
|
||||
|
||||
public bool IsSignedOut => !_isConnected();
|
||||
|
||||
private SessionRewardSummary _sessionRewards = SessionRewardSummary.Empty;
|
||||
|
||||
/// <summary>This session's reward events, derived on demand. Never persisted.</summary>
|
||||
public SessionRewardSummary SessionRewards
|
||||
{
|
||||
get => _sessionRewards;
|
||||
private set
|
||||
{
|
||||
_sessionRewards = value;
|
||||
OnPropertyChanged(nameof(SessionRewards));
|
||||
OnPropertyChanged(nameof(HasSessionRewards));
|
||||
OnPropertyChanged(nameof(SessionCountsText));
|
||||
OnPropertyChanged(nameof(SessionMoneyLines));
|
||||
OnPropertyChanged(nameof(HasSessionMoney));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasSessionRewards => _sessionRewards.HasEvents;
|
||||
|
||||
/// <summary>Counts are always neutral — "3 Super Chats" says nothing about money, and most
|
||||
/// creators have none.</summary>
|
||||
public string SessionCountsText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_sessionRewards.HasEvents) return string.Empty;
|
||||
var parts = new List<string>();
|
||||
if (_sessionRewards.SuperChatCount > 0) parts.Add($"{_sessionRewards.SuperChatCount} Super Chat{(_sessionRewards.SuperChatCount == 1 ? "" : "s")}");
|
||||
if (_sessionRewards.SuperStickerCount > 0) parts.Add($"{_sessionRewards.SuperStickerCount} Super Sticker{(_sessionRewards.SuperStickerCount == 1 ? "" : "s")}");
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Money is shown only when the creator asked for it AND there is something to show.
|
||||
/// A creator who never monetized never sees a zero (creator ruling 2026-11-05).</summary>
|
||||
public IReadOnlyList<string> SessionMoneyLines
|
||||
=> ShowMonetaryMetrics ? _sessionRewards.MoneyLines() : Array.Empty<string>();
|
||||
|
||||
public bool HasSessionMoney => SessionMoneyLines.Count > 0;
|
||||
|
||||
private bool _showMonetaryMetrics;
|
||||
|
||||
/// <summary>"Show monetary metrics" — lives in this drawer, persisted, OFF by default. Turning it on
|
||||
/// is also what would justify requesting the monetary Analytics scope; while it is off the app never
|
||||
/// asks Google for money data.</summary>
|
||||
public bool ShowMonetaryMetrics
|
||||
{
|
||||
get => _showMonetaryMetrics;
|
||||
set
|
||||
{
|
||||
if (!SetProperty(ref _showMonetaryMetrics, value)) return;
|
||||
_store().SaveShowMonetaryMetrics(value);
|
||||
OnPropertyChanged(nameof(SessionMoneyLines));
|
||||
OnPropertyChanged(nameof(HasSessionMoney));
|
||||
}
|
||||
}
|
||||
|
||||
public string? LoadError
|
||||
{
|
||||
get => _loadError;
|
||||
@@ -139,6 +218,38 @@ public sealed class YppTrackerViewModel : ViewModelBase
|
||||
public double Tier2SubsProgress => Progress(SubscriberCount, YppThresholds.Tier2Now.Subscribers);
|
||||
public double UploadsProgress => Progress(UploadsLast90Days, YppThresholds.UploadsRequiredPer90Days);
|
||||
|
||||
private long? _watchHours;
|
||||
private long? _shortsViews;
|
||||
|
||||
/// <summary>The three eligibility metrics, with the threshold that applies today (the long-form bar
|
||||
/// doubles on 1 Feb 2027 — the date is data, not a code change).</summary>
|
||||
public YppProgress Eligibility => new(
|
||||
SubscriberCount,
|
||||
YppThresholds.Tier2Now.Subscribers,
|
||||
_watchHours ?? 0,
|
||||
YppThresholds.Tier2Now.WatchHours,
|
||||
_shortsViews ?? 0,
|
||||
YppThresholds.Tier2Now.ShortsViews);
|
||||
|
||||
/// <summary>True once the Analytics scope is granted and both numbers came back. Without it the two
|
||||
/// view bars cannot be drawn honestly, so the drawer says what is missing instead.</summary>
|
||||
public bool HasWatchMetrics => _watchHours.HasValue && _shortsViews.HasValue;
|
||||
|
||||
public string WatchMetricsMissingText =>
|
||||
"Watch hours and Shorts views need YouTube Analytics access — one-time consent, granted from the "
|
||||
+ "button below. Until then those two bars stay empty.";
|
||||
|
||||
public double SubscribersBarWidth => Eligibility.SubscribersFraction * BarMaxWidth;
|
||||
public double WatchHoursBarWidth => Eligibility.WatchHoursFraction * BarMaxWidth;
|
||||
public double ShortsViewsBarWidth => Eligibility.ShortsViewsFraction * BarMaxWidth;
|
||||
|
||||
public string SubscribersText => Eligibility.SubscribersText;
|
||||
public string WatchHoursText => Eligibility.WatchHoursText;
|
||||
public string ShortsViewsText => Eligibility.ShortsViewsText;
|
||||
public string CriteriaMetText => Eligibility.CriteriaMetText;
|
||||
public string ThresholdsAsOfText =>
|
||||
$"Thresholds as published {YppThresholds.AsOfUtc:d MMMM yyyy} · estimates, can lag.";
|
||||
|
||||
public double Tier1SubsBarWidth => Progress(SubscriberCount, YppThresholds.Tier1.Subscribers) * BarMaxWidth;
|
||||
public double Tier2SubsBarWidth => Progress(SubscriberCount, YppThresholds.Tier2Now.Subscribers) * BarMaxWidth;
|
||||
public double UploadsBarWidth => Progress(UploadsLast90Days, YppThresholds.UploadsRequiredPer90Days) * BarMaxWidth;
|
||||
@@ -203,11 +314,80 @@ public sealed class YppTrackerViewModel : ViewModelBase
|
||||
await RefreshAsync();
|
||||
}
|
||||
|
||||
/// <summary>Asks Analytics for the two view metrics. Missing scope → nulls, and the drawer explains
|
||||
/// what to do; nothing is guessed.</summary>
|
||||
private async Task RefreshWatchMetricsAsync()
|
||||
{
|
||||
var source = _watchMetrics();
|
||||
if (source == null)
|
||||
{
|
||||
_watchHours = null;
|
||||
_shortsViews = null;
|
||||
RaiseProgress();
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_watchHours = await source.GetLongFormWatchHoursAsync();
|
||||
_shortsViews = await source.GetShortsViewsAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"Watch metrics unavailable: {ex.Message}");
|
||||
_watchHours = null;
|
||||
_shortsViews = null;
|
||||
}
|
||||
RaiseProgress();
|
||||
}
|
||||
|
||||
private void RaiseProgress()
|
||||
{
|
||||
OnPropertyChanged(nameof(Eligibility));
|
||||
OnPropertyChanged(nameof(HasWatchMetrics));
|
||||
OnPropertyChanged(nameof(SubscribersBarWidth));
|
||||
OnPropertyChanged(nameof(WatchHoursBarWidth));
|
||||
OnPropertyChanged(nameof(ShortsViewsBarWidth));
|
||||
OnPropertyChanged(nameof(SubscribersText));
|
||||
OnPropertyChanged(nameof(WatchHoursText));
|
||||
OnPropertyChanged(nameof(ShortsViewsText));
|
||||
OnPropertyChanged(nameof(CriteriaMetText));
|
||||
OnPropertyChanged(nameof(ThresholdsAsOfText));
|
||||
}
|
||||
|
||||
/// <summary>Asks YouTube for the channel's recent reward events and keeps only this session's.
|
||||
/// Nothing is written down: the report is a view over YouTube's data, not a local ledger.</summary>
|
||||
private async Task RefreshSessionRewardsAsync()
|
||||
{
|
||||
var started = _sessionStartedAtUtc();
|
||||
var channel = _channelId();
|
||||
var source = _rewardEvents();
|
||||
if (started == null || string.IsNullOrWhiteSpace(channel) || source == null)
|
||||
{
|
||||
SessionRewards = SessionRewardSummary.Empty;
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var events = await source.GetRecentAsync(channel);
|
||||
SessionRewards = SessionRewardSummary.From(events, started.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"Session rewards unavailable: {ex.Message}");
|
||||
SessionRewards = SessionRewardSummary.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RefreshAsync()
|
||||
{
|
||||
if (_isRefreshing) return;
|
||||
_isRefreshing = true;
|
||||
IsLoading = true;
|
||||
|
||||
await RefreshSessionRewardsAsync();
|
||||
await RefreshWatchMetricsAsync();
|
||||
LoadError = null;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -20,7 +20,7 @@ corrected. No new scope mid-week; anything discovered goes on a list for day 6.
|
||||
| **1 · Mon** — licensing | Paid-app ownership check (`BIsSubscribedApp`) + Debug fake + app-wide `IsAppOwned` · greyed tier entries · About conversion copy + llamacasty.com link · current-launch Logs tab (replaces the separate system-message strip) · Debug-only `InternalsVisibleTo` | A locked tier opens About without changing the selected free tier or leaving the app; the site opens only from its link |
|
||||
| **2 · Tue** — release blockers | Visibility flow (creator-selected at release; development/test stays Private) · `OutputProfile` entitlement: 30 fps free / 60 fps paid regardless of resolution · ~~`StreamConfig` defaults~~ retired (no production call sites) · TASK 53 (vertical resolution check ✅; remaining output contract open) · 9·5 webcam identity key · Move transitions (per-layer carry-across-scenes) | Visibility is selectable at creation and live-editable; the 30/60-fps gate is tested; remaining Day 2 items stay queued |
|
||||
| **3 · Wed** — resilience | TASK 32: blip retry → measured grace → amber RECONNECTING → one-click Back on air → fragmented MP4 → ingest pre-flight · 33 bandwidth step-down | Killing the network mid-broadcast recovers without ending it |
|
||||
| **4 · Thu** — content & media | 3·17 Text layer · 21 media acquisition wiring + file picker + loop/volume UI · 49 chat profanity filter · 34 scheduled streams | Text layer renders/persists; media file plays, loops, has volume; scheduled stream created |
|
||||
| **4 · Thu** — content & media | ~~3·17 Text layer~~ ✅ · ~~21 media acquisition wiring~~ ✅ (picker, loop, lifecycle) · 49 chat profanity filter · 34 scheduled streams | Text layer renders/persists; media file plays, loops; scheduled stream created |
|
||||
| **5 · Fri** — data & settings | 3·20 RewardEvent persistence + `superChatEvents.list` backfill · 39·2 YPP slice 2 · 37 defaults-vs-current split · 35 scene-linked audio · 40·A/C/D settings round · 55·2–3 disk hygiene | Session report reads persisted events; defaults can be reverted; temp clips cleaned |
|
||||
| **6 · Sat** — finish & prove | 50 publish recording · preview undo (Ctrl+Z) · 14 creator feedback batch · 36 gold pass · full sweep: clean build, whole per-class suite, `publish.sh` artifact, EULA/privacy/notices in the artifact · commit + push | Gold pass list empty; artifact stages; suite green; pushed |
|
||||
|
||||
@@ -29,11 +29,9 @@ in the middle.
|
||||
|
||||
## Next up (after the surge slice)
|
||||
|
||||
**TASK 3·17 — the Text layer** is scheduled in the surge (day 4). Placeholder detail retained for
|
||||
the unit itself: `AddSource` creates it 0×0, all four compositor paths `continue` past it,
|
||||
`FramePump`'s hash skips it, it is not draggable, and it has no text/font/colour properties or
|
||||
persistence. Text content, font family/size/weight/style, colour, alignment, drag/resize,
|
||||
persisted; renderer mirrors `Services/ChatBoxRenderer.cs`.
|
||||
**Start here:** TASK 33 (bandwidth step-down) — the last unbuilt piece of the resilience row, and the
|
||||
only launch blocker left in code. Then TASK 34 (scheduled streams; its two research flags must be
|
||||
cited first), then 35 / 37 / 40·A/C/D / 55·2–3. TASK 32 is complete, Back on air included.
|
||||
|
||||
## Queue
|
||||
|
||||
@@ -43,22 +41,23 @@ persisted; renderer mirrors `Services/ChatBoxRenderer.cs`.
|
||||
|---|---|---|---|
|
||||
| 53 | ✅ | Output-format contract — six size/FPS modes, vertical YouTube playback, and recordings visually accepted | [`task-53`](TASKS/task-53-output-formats.md) |
|
||||
| — | ✅ | Output entitlement code: free at 30 fps / paid at 60 fps regardless of resolution; Steam App ID is still pending | [`commercial`](docs/ai/commercial.md) |
|
||||
| 3·17 | ☐ **NEXT** | **Text layer** — content, font family/size/weight/style, colour, alignment, drag/resize, persisted | [`task-03`](TASKS/task-03-capture-pipeline.md) |
|
||||
| 21 | 🔶 | Media source: acquisition wiring + file picker + loop/volume UI (decoder, manager, pacing, loop all shipped — **no `AcquireAsync` caller exists**) | [`task-21`](TASKS/task-21-media-source.md) |
|
||||
| 3·17 | ✅ | **Text layer** — content, font family/size/weight/style, colour, alignment, drag/resize, persisted (done 2026-11-04) | [`task-03`](TASKS/task-03-capture-pipeline.md) |
|
||||
| 21 | ✅ | Media source: video file added from the (+) menu decodes, composites, plays its soundtrack, loops, and stops with its last reference (done 2026-11-05) | [`task-21`](TASKS/task-21-media-source.md) |
|
||||
| 64 | ✅ | **Green/Blue Screen** — detect + key from the decode pipe, offer on add, Amount/Softness/Fringe, opt-in auto-apply, alert clips included, persisted (done 2026-11-05) | [`task-64`](TASKS/task-64-green-blue-screen.md) |
|
||||
| — | ☐ | Transitions **Move**: per-layer carry-across-scenes flag, per-scene placement, fixed z band | [`ui-surface`](docs/ai/ui-surface.md) |
|
||||
| 55·2–3 | ☐ | Disk hygiene: delete `%TEMP%` alert clips on close + sweep at startup; low-disk guard before REC (slice 1 shipped) | [`task-55`](TASKS/task-55-disk-hygiene.md) |
|
||||
| 40·A/C/D | ☐ | App Settings: active-camera picker; persist output resolution + surface transition defaults + confirm-before-End; accent consolidation | [`task-40`](TASKS/task-40-app-settings-round.md) |
|
||||
| 3·20 | ☐ | RewardEvent persistence: canonical `RewardEvents` table + `superChatEvents.list` 30-day backfill (the session report and journey read it) | [`task-03`](TASKS/task-03-capture-pipeline.md) |
|
||||
| 32 | ☐ | Stream resilience: blip retry → measured grace + amber "RECONNECTING" → one-click Back on air → fragmented MP4 → ingest pre-flight | [`task-32`](TASKS/task-32-stream-resilience.md) |
|
||||
| 33 | ☐ | Bandwidth auto step-down: pure policy over dropped-frame rate, one-way within a broadcast | [`task-33`](TASKS/task-33-bandwidth-step-down.md) |
|
||||
| 3·20 | ✅ | Session report — **derived from `superChatEvents.list` on demand, not persisted** (YouTube is the authority; no ledger). Per-currency totals, money off by default (done 2026-11-05) | [`task-03`](TASKS/task-03-capture-pipeline.md) |
|
||||
| 32 | ✅ | Stream resilience: fragmented MP4, blip retry, poll-driven RECONNECTING (no countdown — YouTube's cutoff is not a constant), ingest pre-flight, one-click Back on air (`BackOnAirTests`) | [`task-32`](TASKS/task-32-stream-resilience.md) |
|
||||
| 33 | 🔶 | Auto step-down — **`StepDownPolicy` + 12 unit tests done 2026-11-09** (two ladders, budgets, floors, cooldown, ambiguity, recovery behind a flag); policy, planner, VM watch, encoder relaunch and the toast are in (17 tests); remaining: shed our own capture cost before the fps step, and the session-report line | [`task-33`](TASKS/task-33-bandwidth-step-down.md) |
|
||||
| 34 | ☐ | Scheduled streams (Text-drawer version) | [`task-34`](TASKS/task-34-scheduled-streams.md) |
|
||||
| 35 | ☐ | Scene-linked audio | [`task-35`](TASKS/task-35-scene-linked-audio.md) |
|
||||
| 37 | ☐ | Defaults vs current layout split (build-id); enables one-click revert to defaults | [`task-37`](TASKS/task-37-defaults-current-split.md) |
|
||||
| — | ✅ | **Preview undo (Ctrl+Z / Ctrl+Shift+Z)** — done 2026-11-01: `Models/PreviewHistory` + `MainViewModel.Preview`, one step per gesture, gated on `EditingActive`, cleared on layout load. Property edits not yet in the stack | [`ui-surface`](docs/ai/ui-surface.md) |
|
||||
| 39·2 | ☐ | YPP slice 2: Analytics scopes, watch-hours/Shorts velocity + ETA | [`task-39`](TASKS/task-39-ypp-journey-tracker.md) |
|
||||
| 49 | ☐ | Chat profanity filter: local, opt-in, **non-persistent**, user-supplied word list | [`task-49`](TASKS/task-49-chat-profanity-filter.md) |
|
||||
| 39·2 | ✅ | YPP slice 2 — three eligibility bars (subs / watch hours / Shorts views) from Analytics, dated thresholds with a staleness test, "x of 3 criteria met" (done 2026-11-05) | [`task-39`](TASKS/task-39-ypp-journey-tracker.md) |
|
||||
| 49 | ❌ | Chat profanity filter — **retired 2026-11-05**: YouTube owns moderation (blocked words + hold for review run before the API). Replaced by not rendering YouTube's moderation markers (tombstones / no-display events) | [`task-49`](TASKS/task-49-chat-profanity-filter.md) |
|
||||
| 50 | ☐ | One-button publish of the local recording (resumable upload) | [`task-50`](TASKS/task-50-publish-recording.md) |
|
||||
| 54 | 🔶 | Freemium: EULA + privacy shipped; free Steam Demo and paid app use one codebase; paid app ID and Steam Demo setup still pending | [`task-54`](TASKS/task-54-marcom-free-merch.md) |
|
||||
| 54 | 🔶 | Freemium: EULA + privacy shipped; one codebase for free Demo + paid app. **Blocked on Valve**: identity verification pending, tax review up to 30 business days; app IDs, store page and build review all follow | [`task-54`](TASKS/task-54-marcom-free-merch.md) |
|
||||
| — | 🔶 | **Steam ownership** — `BIsSubscribedApp(paidAppId)` + Debug fake + app-wide `IsAppOwned`; paid app ID awaits Steamworks | [`commercial`](docs/ai/commercial.md) |
|
||||
| — | ❌ | **Polar subscription path** — retired 2026-11-01 with the one-price model. Design kept in `decisions.md`, not built | [`decisions`](docs/ai/decisions.md) |
|
||||
| — | ✅ | **OutputProfile gate** — resolver + `EncoderOptions` wiring (`Models/OutputProfile.cs`, one ffmpeg/two outputs, dev override); higher tiers follow `IsAppOwned` | [`commercial`](docs/ai/commercial.md) |
|
||||
|
||||
@@ -35,10 +35,14 @@
|
||||
**Creator rulings:** a free-subscriber mention is a plain chat row — NO sub alert (YouTube
|
||||
emits no public event for free subs), NO viewer count (vetoed), and every card draws the
|
||||
"made with LlamaCasty!" brand line (each broadcast = free product placement). **Precursor
|
||||
(still open): the reward-event persistence half — the canonical `RewardEvents` SQLite table
|
||||
(all six types persisted per broadcast) + `superChatEvents.list` backfill + the session-report
|
||||
rollup (TASK 10 → "Related work — monetization awareness"). The shipped alert path parses
|
||||
events into `ChatMessage` directly in memory; the report reads that table once it exists.**
|
||||
✅ **RESOLVED 2026-11-05 — derived, not persisted.** The creator's ruling: YouTube is the authority
|
||||
for monetization, so the app asks it on demand instead of keeping a ledger. `Services/SuperChatEventService.cs`
|
||||
reads `superChatEvents.list` (existing `auth/youtube` scope — no re-consent), `Models/SessionRewardSummary.cs`
|
||||
rolls it up for the session window with **per-currency totals that are never summed together**, and the YPP
|
||||
drawer shows "THIS SESSION" counts. No table, no migration, no backfill, and the published promise that no
|
||||
viewer/member/donor information is retained stays literally true.
|
||||
**Money is off by default** ("Show monetary metrics", in the drawer, persisted): counts are neutral, and a
|
||||
creator who never monetized is never shown a zero. Tests: `SessionRewardReportTests`.**
|
||||
21. ✅ **Show Desktop toggle** — `Source.ShowDesktop` bool persisted in DB (schema migration + LayoutStore read/write). When checked, primary monitor captures regardless of fullscreen game state. Toggling off falls back to running game or releases to static placeholder. `ClearBackdropCaptureAsync` clears `CaptureKey` + `VideoImageSource` so static fallback renders. Toggle on Live backdrop context menu (IsCheckable MenuItem).
|
||||
22. ✅ **Top bar — status light + avatar + Log In button** — red/green/pulsing ellipse (disconnected/connected/live). Avatar border visible only when connected, loads via `BitmapImage` code-behind. "Log In" button visible when disconnected, calls `StartStreamCommand` → GoLiveWindow. `ShowStartStream` now requires `IsConnected`.
|
||||
23. ✅ **Chat preview — one-at-a-time mock messages** — `RunMockChatPreviewAsync`: simple async loop, displays `MockChatMessages[n]` via `Take(n+1)`, 1000ms between messages, wraps at end. `ChatPreviewEnabled` property on Source (default true). Stops on real messages, restarts on fade timer clear.
|
||||
|
||||
@@ -5,54 +5,48 @@
|
||||
|
||||
**Goal:** play video files (MP4, MOV, AVI) into scenes — starting soon videos, BRB loops, intro/outro clips.
|
||||
|
||||
### Status: 🔶 In progress — Increment A (model + persistence) + Increment B (decoder) + slice 1 (manager + resolver/preview wire-in) + slice 2a/2b (ffprobe probe + native-FPS pacing) + slice 3 (loop mechanism) shipped. **Remaining: the UI picker slice (AddMedia command + file dialog + Acquire/Release wiring + loop-flag wiring) — GUI, handed off to build/verify natively on Windows (see HANDOFF → "UI picker slice — handoff spec").**
|
||||
### Status: ✅ Complete 2026-11-05 — a video file added in the (+) menu decodes, composites into the
|
||||
preview and the stream, loops on the creator's toggle, and stops when the layer or its last scene
|
||||
reference goes away, and **the file's own soundtrack plays into the stream** (item 10).
|
||||
|
||||
1. ✅ `MediaSourceType` enum: `Video`, `Audio` (audio-only files via media source)
|
||||
2. ✅ `SourceType.MediaSource` addition to the enum
|
||||
3. ✅ `MediaSourceModel`: `MediaPath`, `MediaIsLooping`, `MediaVolume` (0-1), `MediaPlaybackState` — persisted in LayoutStore (schema migration + SELECT/INSERT + round-trip test)
|
||||
4. ✅ `MediaVideoSource` implements `IMediaFrameSource`: FFmpeg raw video decoder → `VideoFrame` pipeline — spawns ffmpeg `-f rawvideo -pix_fmt bgra`, drains the pipe via pure `RawVideoFrameReader` (`Services/RawVideoFrameReader.cs`), raises `FrameAvailable`/`Completed`; lifecycle is `StartAsync`/`StopAsync`; decode process behind `IDecodeProcess`/`FfmpegDecodeProcess` seam (binary-stdout mirror of `IEncoderProcess`). Shipped 2026-08-31; refactored onto `IMediaFrameSource` with this slice.
|
||||
4b. ✅ Slice 2a — native-FPS probe seam: `FfmpegFrameRateParser` (pure, prefers `avg_frame_rate=` then `r_frame_rate=`, rational N/N/M, unknown→null) + `IFrameRateProbe`/`FfmpegFrameRateProbe` (derives sibling `ffprobe.exe` from the located ffmpeg dir, reuses the `IDecodeProcess` seam; null if ffprobe absent) + `FfmpegLocator.ProbeFileName` now also extracts `ffprobe.exe` from the pinned archive (conditional). Tests: `FfmpegFrameRateParserTests` (6 pure units + 1 probe integration via fake locator/process) + `FfmpegLocatorTests` still green — 15/15.
|
||||
5. ✅ `IMediaFrameSource` + `MediaVideoSourceManager` (`Services/IMediaFrameSource.cs`, `Services/MediaVideoSourceManager.cs`): app-wide decode-session ownership refcounted by `MediaPath` with a `Func<string, IMediaFrameSource?>` factory seam; `AcquireAsync`/`ReleaseAsync`/`ReleaseAllAsync`/`GetLatestFrame`; coalesces frames onto the UI dispatcher onto a single shared `WriteableBitmap` per file (mirror of `ScreenCaptureManager`); `MediaFailed` + `PreviewBitmapChanged`. Unit tests + one integration test (bitmap share/coalesce) — `MediaVideoSourceManagerTests`, 5/5 pass.
|
||||
6. ✅ Native-FPS pacing (slice 2b): `MediaVideoSource` takes optional `IFrameRateProbe?` + `Func<TimeSpan,CancellationToken,Task>? delay` seams, probes FPS once in `RunAsync`, and delays by 1/fps after each emitted frame; unknown/absent probe → no pacing. Test: `MediaVideoSource_PacesFramesByProbedFps` (fake probe + recording delay, one delay per frame ≈ 1ms).
|
||||
7. ☐ Wire into `FramePump` resolver — `Source { Type: MediaSource }` → latest video frame — **resolver + preview routing + manager wired; session acquisition (start/stop on add/remove) still open (comes with the UI picker)**
|
||||
8. ☐ Wire into `SceneCompositor` — render media source as an image element at its position/size
|
||||
9. ✅ Loop control (mechanism) — `IMediaFrameSource.Looping`; `MediaVideoSource` takes a `Func<IDecodeProcess>` process factory and restarts the decode on natural EOF when `Looping` (fresh process per pass, since a `Process` can't be re-`Start()`ed). Test: `MediaVideoSource_LoopsUntilLoopDisabled` (single frame re-emits across passes, `Completed` only after loop cleared). Wiring `Source.MediaIsLooping` into the flag lands with the UI-picker (acquisition) slice.
|
||||
10. ☐ Volume control — per-source volume slider for audio playback
|
||||
11. ☐ UI: file picker (filtered to video formats), loop toggle, volume slider
|
||||
12. ☐ Schema migration for media source settings (file path, loop, volume)
|
||||
13. ☐ Tests: video frame extraction, loop behavior, volume scaling, file validation
|
||||
5. ✅ `IMediaFrameSource` + `MediaVideoSourceManager` (`Services/IMediaFrameSource.cs`, `Services/MediaVideoSourceManager.cs`): app-wide decode-session ownership refcounted by `MediaPath` with a `Func<string, IMediaFrameSource?>` factory seam; `AcquireAsync`/`ReleaseAsync`/`ReleaseAllAsync`/`GetLatestFrame`/`HasSession`/`GetActiveKeys`/`SetLooping`; coalesces frames onto the UI dispatcher onto a single shared `WriteableBitmap` per file (mirror of `ScreenCaptureManager`); `MediaFailed` + `PreviewBitmapChanged`. Unit tests + one integration test (bitmap share/coalesce) — `MediaVideoSourceManagerTests`.
|
||||
6. ✅ Native-FPS pacing (slice 2b): `MediaVideoSource` takes optional `IFrameRateProbe?` + `Func<TimeSpan,CancellationToken,Task>? delay` seams, probes FPS once in `RunAsync`, and delays by 1/fps after each emitted frame; unknown/absent probe → no pacing. Test: `MediaVideoSource_PacesFramesByProbedFps`.
|
||||
7. ✅ Wire into `FramePump` resolver — `Source { Type: MediaSource }` → latest video frame, and the same
|
||||
resolver serves preview and thumbnails (`FramePump` defaults `resolver` to the frame resolver).
|
||||
8. ✅ Wire into `SceneCompositor` — media renders through the generic `frameFor(element)` path at the
|
||||
element's rect, so no compositor change was needed.
|
||||
9. ✅ Loop control — `IMediaFrameSource.Looping`; `MediaVideoSource` restarts the decode on natural EOF
|
||||
when `Looping` (fresh process per pass). `MediaIsLooping` reaches the session through the manager's
|
||||
per-path `loopProvider` at start and `SetLooping` on a live toggle. Rule (recorded): the path's
|
||||
session loops if **any** live media reference has it on, because one decoder is shared per path.
|
||||
10. ✅ File audio + volume — the shared clip pipe decodes the soundtrack (`f32le -ac 2 -ar 48000 -vn`,
|
||||
50 ms chunks paced to real time, byte-carry across reads) and the layer carries **Mute** + **Level**.
|
||||
The manager applies them per session (one decoder per path, so the last layer touched wins — the
|
||||
alternative would play the same file twice) and the audio joins the DESKTOP/GAME group in
|
||||
`AudioMixer.EnqueueDesktopMediaAudio`, so the desktop fader and the voice ducker behave exactly as
|
||||
they do for game audio and TRAX. Test: `MediaSourceAudioTests` (chunks, level scaling, mute, and the
|
||||
layer's sound reaching the desktop meter).
|
||||
11. ✅ UI: `AddMediaCommand` (+ menu → "Video File", video-filtered `OpenFileDialog`), `ChangeMediaFileCommand`
|
||||
("Change…" in the properties panel), loop toggle, video name display.
|
||||
12. ✅ Schema migration for media source settings (file path, loop, volume) — shipped with item 3.
|
||||
13. ✅ Tests: decode/loop/pacing at the unit level, and `MediaSourceAcquisitionTests` (the Good Dog for the
|
||||
wiring): add a file → one decoder starts, frames reach the layer, loop flip reaches the decoder, remove → stops.
|
||||
|
||||
### Design decisions
|
||||
|
||||
- **FFmpeg handles all formats** — no codec-specific code. FFmpeg already in the project.
|
||||
- **Audio plays through the desktop channel** — media source audio is captured by the WASAPI loopback (like TRAX/game audio). No separate audio routing needed.
|
||||
- **Audio joins the desktop/game group** (creator ruling 2026-11-05) — the clip's sound is decoded by
|
||||
the same pipe as its picture, mixed directly into the stream (not played locally and captured), and
|
||||
grouped with game audio so one fader and the ducker cover it. A per-layer Mute/Level sits on top.
|
||||
Chosen over TRAX-style local playback because it works regardless of the creator's desktop-capture
|
||||
state, and because an alert clip needs the same direct route anyway.
|
||||
- **This pairs with TRAX** — TRAX is background music, media source is background video. Together they make non-Live scenes (Starting/BRB/Ending) feel polished.
|
||||
- **Not a full NLE** — no trimming, no multi-track, no effects. Just "play this video in the scene."
|
||||
|
||||
### UI picker slice — spec (imported from HANDOFF 2026-09-01 so it can't be lost by a rewrite)
|
||||
|
||||
Nothing `AcquireAsync`s a media path yet, so **no frames flow in a running app** — decoder, manager,
|
||||
pacing, and loop mechanism are shipped and unit-tested, but a media Source has no way to start a
|
||||
session. Deliverables, in order:
|
||||
|
||||
1. **File picker + add/remove commands** (mirror `MainViewModel.Trax.cs:68` `OpenFileDialog` usage).
|
||||
A "Media" source action opens an `OpenFileDialog` filtered to video (mp4/mov/avi); on OK set
|
||||
`Source.MediaPath`, add to scene, and **`AcquireAsync(MediaPath)`**; on remove
|
||||
**`ReleaseAsync(MediaPath)`** (refcounted — not `ReleaseAllAsync`, unless the path leaves the
|
||||
layout entirely). On `StagedScene` layout loads/teardown, release every media path no longer
|
||||
present and acquire new ones so sessions track the live layout.
|
||||
2. **Wire `Source.MediaIsLooping` → `IMediaFrameSource.Looping`** — needs a manager-level per-**path**
|
||||
loop provider. Ambiguity to rule + record: sessions are refcounted per `MediaPath` and shared
|
||||
across scenes, but `MediaIsLooping` is per-`Source`. Chosen rule: the path's session `Looping` =
|
||||
**any** live reference has it on (shared behaviour). Record it in the slice commit.
|
||||
3. **Loop toggle + volume slider** in the source context menu / inspector (items 10/11).
|
||||
4. `MediaVolume`/`MediaPlaybackState` wiring — audio path for media is future work (desktop loopback
|
||||
already carries it, TRAX-style; `MediaVolume` slider can drive the local file's audio separately
|
||||
later — out of this slice).
|
||||
|
||||
**Design notes to preserve:** `ResolveOutputFrame` reads `_mediaManager.GetLatestFrame(MediaPath)`;
|
||||
`OnMediaPreviewBitmapChanged` adopts the shared `WriteableBitmap` per path; `MediaFailed` →
|
||||
`OnMediaFailed` (currently `Debug.WriteLine` — surface in UI via toast, TASK 24 stack). The compositor
|
||||
scales any frame size — media renders through the generic `frameFor(element)` path, no compositor
|
||||
change. First GUI smoke test: add a short real mp4 on native Windows, confirm it plays and previews.
|
||||
|
||||
- **Layers are defined in Live first** (creator 2026-11-05): this unit adds the layer and the picker in
|
||||
the ordinary (+) menu, with no per-scene availability rules. Which scenes may host a video layer is a
|
||||
later pass, and scene-only layers (an ending credit roll, for instance) are defined after that pass.
|
||||
|
||||
@@ -11,29 +11,58 @@ the API — creator ruling 2026-09-01): no lying in the copy.
|
||||
|
||||
**Slices (one integration test each, in order):**
|
||||
|
||||
1. ☐ **Blip retry** — app-side encoder restart: push dies while live (ProcessFailed / stdin
|
||||
1. ✅ **Blip retry** (shipped 2026-11-05) — app-side encoder restart: push dies while live (ProcessFailed / stdin
|
||||
backpressure death) → bounded-backoff relaunch (2s/5s/10s, N attempts) against the cached
|
||||
constant reusable-stream ingest URL. Success = push running again while the broadcast is still
|
||||
live; viewers never know. Fixes the map's stale "ffmpeg does reconnect" claim (corrected
|
||||
2026-09-01: reconnect flags are input-side only). Test: fake process fails once then starts →
|
||||
pump recovers without surfacing to the VM.
|
||||
2. ☐ **Measured grace + the sign** — while the push is dead, escalate the existing health poll
|
||||
(30s → ~5s). ON-AIR dot goes **amber "RECONNECTING"** with a mm:ss countdown to the observed
|
||||
YouTube cutoff; the grace length is a **measured, pinned constant** — probe it on a real private
|
||||
test stream, cite the observation (spin-guard rule; do NOT invent a number). Poll reports the
|
||||
broadcast `complete` → dot **red "OFF AIR"**, primary button relabels **"● Back on air"** and
|
||||
pulses. Test: fake status provider drives the dot through live → reconnecting → cut-off.
|
||||
3. ☐ **One-click Back on air** — the relabeled button fires the existing go-live path with saved
|
||||
**Shipped:** `Services/StreamRetryPolicy.cs` (immediate, +1 s, +2 s, +3 s — minimum waits, because
|
||||
YouTube's grace is short), `Services/StreamRecovery.cs` (the loop, with the audio pipe recreated per
|
||||
attempt because its single-instance server is unusable after the old client died), and
|
||||
`FramePump.EncoderFailed` separating a dead push (recoverable) from a fatal pump fault. Each episode
|
||||
reports into the left panel's alert stack; a reconnect that lands on a **complete** broadcast is
|
||||
reported as such instead of showing a live sign over a dead stream. Tests: `StreamRecoveryTests`.
|
||||
2. 🔶 **Poll-driven sign — NO invented countdown** (spec revised 2026-11-05, creator challenge:
|
||||
*"I really don't think that's going to be a constant — it's going to depend on so many variables, some
|
||||
that are dark to us"*). The original plan was a measured grace constant and a countdown to YouTube's
|
||||
cutoff. **Dropped**: YouTube's cutoff is server-side and depends on things we cannot observe
|
||||
(ingest node health, prior stream quality, region, load), so any pinned number is a guess wearing a
|
||||
timer. What ships instead:
|
||||
- **Amber RECONNECTING** in the top bar, with **measured** facts only: elapsed time and attempt
|
||||
count ("RECONNECTING · 0:12 · attempt 2 of 4"). No countdown.
|
||||
- **The status poll speeds up** while recovering (30 s → ~4 s) and drives the truth. Signals used,
|
||||
cheapest first: `liveBroadcasts.list` `status.lifeCycleStatus` (authoritative `complete`),
|
||||
`liveStreams.list` `status.streamStatus`/`healthStatus` (is the push being received), and the
|
||||
**`chatEndedEvent`** YouTube already puts in the chat feed we poll — free, and previously skipped.
|
||||
- At `complete`: **red OFF AIR**, stop retrying, and (slice 3) offer **Back on air**.
|
||||
Test: a fake status provider drives the sign through live → reconnecting → off air; a `chatEndedEvent`
|
||||
triggers an immediate status check rather than a decision of its own.
|
||||
|
||||
3. ✅ **One-click Back on air** (shipped 2026-11-05) — the relabeled button fires the existing go-live path with saved
|
||||
`Broadcast.*` + cached stream, dialog skipped: new broadcast, new VOD (accepted cost, stated
|
||||
in-product). Test: seeded saved form + fake stream service → click creates + pushes, no dialog.
|
||||
4. ☐ **Crash-safe recording** — fragmented MP4 on the record block (`-movflags
|
||||
**Shipped:** `Services/BroadcastTitle.cs` (pure — resume marker replaces rather than stacks, base
|
||||
truncated to YouTube's 100 characters) and `MainViewModel.BackOnAirCommand`, which reuses the ordinary
|
||||
go-live path with the saved details and the cached stream: new broadcast, new VOD, no dialog. The
|
||||
button appears only after a drop ended the session, in place of the normal start button, and the
|
||||
ordinary start button steps aside so there is exactly one way forward. Tests: `BackOnAirTests`.
|
||||
4. ✅ **Crash-safe recording** (shipped 2026-11-05) — fragmented MP4 on the record block (`-movflags
|
||||
frag_keyframe+empty_moov+default_base_moof`): plain MP4's trailing moov atom means a power loss
|
||||
kills the WHOLE file. Rename-on-stop unchanged. Closes the TASK 18 "MKV as an option" design-note
|
||||
remnant (fragmented MP4 chosen over MKV: single container, YouTube-upload-native — verify player/
|
||||
editor tolerance, cite the research). Test: `FfmpegArgs` emits the movflags only on the record block.
|
||||
5. ☐ **Pre-flight** — before broadcast insert, one TCP probe to the ingest host:1935 (~2s timeout).
|
||||
editor tolerance, cite the research). Test: `Args_RecordBlock_IsFragmentedMp4_SoACrashKeepsTheFile` — the flags are on the record block and
|
||||
absent from the streaming block. Verified by construction only: the file still needs one real
|
||||
interrupted-take check on Windows (kill ffmpeg mid-recording, play the result).
|
||||
5. ✅ **Pre-flight** (shipped 2026-11-05) — before broadcast insert, one TCP probe to the ingest host:1935 (~2s timeout).
|
||||
Unreachable → Error toast, no insert, no ghost broadcast ("check VPN/network"). The "forgot the
|
||||
VPN" story, solved as prevention instead of recovery. Test: fake probe failure aborts go-live before any API call.
|
||||
**Shipped:** `Services/IngestProbe.cs` (`IIngestProbe` + `TcpIngestProbe`, 2 s timeout, rtmp→1935 /
|
||||
rtmps→443) and `MainViewModel.IngestPreflightAsync`, called BEFORE the first API call whenever a
|
||||
cached ingest URL exists (first run probes after resolving the stream, still before any broadcast is
|
||||
created). Tests: `IngestPreflightTests` — unreachable aborts, reachable continues, and the probe is
|
||||
exercised against real sockets (a listening port answers true, the same port closed answers false
|
||||
quickly).
|
||||
|
||||
### Design decisions
|
||||
|
||||
|
||||
@@ -1,21 +1,73 @@
|
||||
# TASK 33 — Bandwidth auto step-down (queued 2026-09-01; v1 per the complete-v1 ruling)
|
||||
# TASK 33 — Automatic step-down when the show can't hold its tier (queued 2026-09-01; v1)
|
||||
|
||||
> Catalog: [`TASKS.md`](../TASKS.md) — status and requirements live here.
|
||||
> Design settled with the creator 2026-11-09. **Not a magenta question of taste: this is the app
|
||||
> admitting it is part of the problem when it is.**
|
||||
|
||||
**Goal:** the stream degrades *predictably and honestly* instead of drowning viewers in freeze frames
|
||||
— and when LlamaCasty itself is the starving process, it says so out loud instead of blaming the
|
||||
creator's connection. The `variable` reusable stream (shipped) makes every step zero-API: a tier or
|
||||
bitrate change is just an encoder relaunch at the same URL.
|
||||
|
||||
**Goal:** when the upload can't hold the tier, drop it automatically instead of drowning viewers in
|
||||
freeze frames. The `variable` reusable stream (shipped) makes this zero-API; the governor that decides
|
||||
WHEN is what TASKS.md:25 always claimed existed and was never built.
|
||||
## Cause first, lever second
|
||||
|
||||
1. ☐ Pure `StepDownPolicy` — sliding window over the encoder's reported dropped-frame rate
|
||||
(`StreamHealth`, already parsed): sustained overrun → downgrade exactly one 16:9 tier
|
||||
(1080p60 → 1080p30 → 720p60 → 720p30). Hysteresis cooldown; **one-way within a broadcast**
|
||||
(no oscillation — a recovered connection doesn't climb back mid-show; the creator may manually
|
||||
step up). Vertical tier stays a manual choice.
|
||||
2. ☐ Restart machinery = TASK 32 slice 1 (tier change is an encoder relaunch at new W×H/FPS over the
|
||||
same pipe/URL; the master canvas is 1920×1080 regardless, so geometry never rewrites).
|
||||
3. ☐ Surface: the resolution badge + dropdown update to the landed tier; ONE Info toast
|
||||
("Quality lowered to hold your stream") — no nagging after that.
|
||||
4. ☐ Tests: pure-policy units (drop-rate windows, one-way, cooldown) + the ONE integration: fake
|
||||
health stream with sustained drops → exactly one lower-tier encoder restart.
|
||||
| Cause | Signal | Lever |
|
||||
|---|---|---|
|
||||
| **Machine starvation** — the PC (often the game) can't make the frame | pump stalls, render time over the frame budget, frames never produced | reduce work: **60 → 30 fps**, then **1080 → 720** |
|
||||
| **Upload congestion** — the socket can't carry the bits | frames produced on schedule but rejected; encoder queue full; **rising submit block time** (pump already logs `avg submit` / `avg wait`) | reduce bits: **8.0 → 6.4 → 5.1 → 4.1 Mbps** (~20% steps), geometry untouched |
|
||||
|
||||
Resolution is **not** a bandwidth lever: 1080p30 and 720p60 are both 6 Mbps in the shipped table, so
|
||||
that step relieves nothing. Fps is **not** a congestion lever: same bitrate, same socket.
|
||||
|
||||
## Shed our own load before asking the viewer to pay
|
||||
|
||||
1. If our capture/convert cadence is what starves, **halve our own capture rate first**
|
||||
(`ScreenCaptureFrameSource.ShedLoad`, 10 ms → 33 ms between conversions) — same output tier, less of
|
||||
the creator's machine. It costs no step and changes nothing the viewer sees.
|
||||
2. Only then step fps, then resolution.
|
||||
|
||||
**Shipped 2026-11-09** — `StepDownPolicy` + `StepDownPlanner` + `FramePump.ChangeEncoderAsync` +
|
||||
`MainViewModel.StepDown`, 18 tests. The shed runs on machine evidence before the budget is touched.
|
||||
|
||||
## Budgets, floors, terminal state
|
||||
|
||||
| Start | Steps allowed | Worst case it can reach |
|
||||
|---|---|---|
|
||||
| 1080p60 | **3, any mix of the two ladders** | 720p30 @ 6.4 Mbps |
|
||||
| 720p60 | **1** | 720p30 @ 4.8 Mbps |
|
||||
| Vertical 1080p60 | **1** | Vertical 1080p30 @ 6.4 Mbps |
|
||||
|
||||
- Floors: 16:9 never below **720p30**; vertical never below **Vertical 1080p30**.
|
||||
- Budget exhausted → **hold**, keep streaming, one persistent warning naming the cause, manual
|
||||
step-up stays available. Never disconnect, never nag repeatedly.
|
||||
- Trigger: ≥5% dropped over 15 s, twice, 30 s cooldown between steps. Mixed/ambiguous evidence does
|
||||
nothing. One-way within a broadcast (no climb-back; revisit with session data).
|
||||
|
||||
## Own the mistake in plain words
|
||||
|
||||
A toast that reports a mechanism is a bug in the toast. Every message names **what happened, who
|
||||
caused it, and what the app already did** — no exception text, no error codes:
|
||||
|
||||
- ours: *"LlamaCasty couldn't keep up with your scene, so it lowered the frame rate to 30. Your
|
||||
connection wasn't the problem."*
|
||||
- theirs: *"Your upload couldn't hold 8 Mbps, so LlamaCasty dropped it to 6.4 to stop the freezing.
|
||||
It will stay there for this stream."*
|
||||
|
||||
One toast per step, plus one **Logs-tab** line (`quality stepped down 12:04 — encoder` / `— upload`,
|
||||
cause-tagged) so support answers from data, not memory. It is logged rather than added to the session
|
||||
report on purpose: that report is the money summary, and quality chatter in it would bury the numbers. Wording rules live in
|
||||
[`docs/ai/ui-surface.md`](../docs/ai/ui-surface.md) → Toast notifications.
|
||||
|
||||
## Tests
|
||||
|
||||
Pure `StepDownPolicy` units (classifier, both ladders, budgets, floors, cooldown, one-way, ambiguity →
|
||||
no action) + the ONE integration: a fake health stream with sustained drops of each cause produces the
|
||||
matching step and exactly one encoder restart.
|
||||
|
||||
## Reference
|
||||
|
||||
OBS Dynamic Bitrate (27.2) is the established answer for the congestion half: bitrate-only, small
|
||||
steps, hysteresis. **Adopted:** bitrate as the sole congestion lever, stepped with cooldown.
|
||||
**Discarded for v1:** its automatic climb-back (the creator's one-way ruling). **Ours:** the
|
||||
machine-side ladder and "shed our own cost first" — OBS has no equivalent, and that is the half that
|
||||
matters when the game and the app share one machine.
|
||||
|
||||
@@ -91,7 +91,22 @@ MyMistakes.
|
||||
- 2FA: `https://myaccount.google.com/signinoptions/two-step-verification`
|
||||
- AdSense: `https://support.google.com/youtube/answer/72851`
|
||||
|
||||
## Slice 2 (outline, queued)
|
||||
## Slice 2 — ✅ SHIPPED 2026-11-05 (the three bars)
|
||||
|
||||
Shipped as designed: `yt-analytics.readonly` behind `IWatchMetricsSource`, three bars (subscribers,
|
||||
long-form watch hours, Shorts views) against `YppThresholds.Tier2Now`, and one line —
|
||||
"x of 3 criteria met — YouTube reviews eligibility." Notes recorded with it:
|
||||
|
||||
- **The view routes are either/or**, so the line is qualified in the drawer ("subscribers plus watch
|
||||
hours, or subscribers plus Shorts views"); `YppProgress.MeetsPublishedRule` encodes that shape.
|
||||
- **Thresholds carry a publication date** (`YppThresholds.AsOfUtc`, shown in the drawer) and a test
|
||||
fails once that reading is older than 180 days — YouTube moves the bar and a stale bar must not look
|
||||
current. The 2027-02-01 doubling is data, not a code change.
|
||||
- **No analytics scope → no invented numbers**: the drawer says what is missing instead of drawing
|
||||
empty bars as zero.
|
||||
- Money stays behind the drawer's "Show monetary metrics" toggle (TASK 3·20).
|
||||
|
||||
## Slice 2 (original outline, for reference)
|
||||
|
||||
`yt-analytics.readonly` (+ re-consent) → `YouTubeAnalyticsService` behind `IChannelStatsProvider`
|
||||
(`ai.md`): long-form `estimatedMinutesWatched` (12-mo), Shorts-feed views (90-d), then velocity /
|
||||
|
||||
@@ -4,7 +4,30 @@
|
||||
> **Research: [`TASKS/research-store-certification.md`](research-store-certification.md) §12.**
|
||||
> Carved out 2026-09-27; shares a scope lock with nothing else.
|
||||
|
||||
**Status:** ☐ Queued — not blocked (does not depend on the route decision)
|
||||
**Status:** ❌ **Retired 2026-11-05** — YouTube owns chat moderation (creator ruling). What replaced it:
|
||||
`Services/YouTubeChatService.cs` no longer turns YouTube's own moderation markers into chat rows
|
||||
(`tombstone`, `hasDisplayContent:false`, chat-mode events), with tests in
|
||||
`ytLive.Tests/ChatModerationParseTests.cs`. The reasoning and citations are below and in
|
||||
`docs/ai/decisions.md`; the body of this file is kept so the option is not re-derived from scratch.
|
||||
|
||||
### Why retired
|
||||
|
||||
- YouTube's **blocked words** filter ("block live chat messages that contain or closely match certain
|
||||
words") and **hold for review** both run upstream of the API: blocked/held messages are not returned
|
||||
by `liveChatMessages.list` (community evidence: held messages never appear —
|
||||
<https://stackoverflow.com/questions/74511524/>). Ours would be a second list, a second set of false
|
||||
positives and a second support surface for a switch the creator already owns.
|
||||
- Deleted messages arrive as a `tombstone` — "signifies that a message used to exist … it has since
|
||||
been deleted … only liveChatId, type and publishedAt are present"
|
||||
(<https://developers.google.com/youtube/data/live/reference/rest/v3/liveChatMessages>). The parser had
|
||||
no filter, so a deletion rendered as a **blank chat row**. That is the actual defect, and it is fixed.
|
||||
- Deletion events (`messageDeletedEvent`/`messageRetractedEvent`/`userBannedEvent`) are documented in
|
||||
the resource but have not been delivered to clients for years
|
||||
(<https://stackoverflow.com/questions/44346893/>), so no client-side moderation machinery can be built
|
||||
on them. The parser skips them if they ever do arrive.
|
||||
|
||||
The constraints below are therefore **moot for us and binding on YouTube** — except constraint 4, which is
|
||||
why the Super Chat parse path still asserts that reward fields are never reinterpreted.
|
||||
|
||||
**Goal:** let the creator decide what reaches the projected chat box, without the app ever
|
||||
becoming a moderator that stores what people said.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# TASK 64 — Green/blue screen (chroma) for video clips
|
||||
|
||||
> Catalog: [`TASKS.md`](../TASKS.md) — status and requirements live here.
|
||||
> Queued 2026-11-05 at the creator's direction, straight after TASK 21's audio slice.
|
||||
|
||||
**Goal:** a creator who drops in a clip shot against a green or blue screen gets the background
|
||||
removed — without knowing what "chroma key", "similarity" or "spill" mean. The app *notices* the
|
||||
screen and offers to remove it; the creator never has to pick a colour.
|
||||
|
||||
**Why this is not the retired "colour-key" item:** `docs/ai/decisions.md` buried chroma key in the
|
||||
webcam background-removal context (ML model, lighting, NVIDIA gives it free — support hell). This is a
|
||||
different job: the creator supplies the clip, ffmpeg does the arithmetic, there is no model and no
|
||||
lighting to blame. The reversal is recorded there.
|
||||
|
||||
---
|
||||
|
||||
## 0. What already exists (verified 2026-11-05, bundled ffmpeg N-126342)
|
||||
|
||||
- `colorkey` / `chromakey` (colour, `similarity`, `blend`) and `despill` (`green`/`blue`, `mix`) are all
|
||||
present in the shipped binary and slice-threaded.
|
||||
- A probe of the bundled binary showed keyed pixels come out of the pipe with **alpha 0** and straight
|
||||
(un-premultiplied) colour — `colorkey=…,format=bgra` → `63 175 0 0` vs `63 175 0 255` unkeyed. The
|
||||
compositor already blends straight alpha, and media frames are not flagged `IsOpaque`, so no
|
||||
compositor change is needed.
|
||||
- Consequence: keying costs **zero app-side CPU** — it is one more term in the decode pipe's `-vf`,
|
||||
which is also the only place that feeds **both** consumers (the shared preview bitmap and the
|
||||
compositor's `LatestFrame`). A C# post-process would have to be wired twice.
|
||||
|
||||
## 1. Decisions (creator, 2026-11-05)
|
||||
|
||||
- **Suggest, never override.** Detection offers; the creator clicks. Opt-in setting for auto-apply.
|
||||
- **Green and blue.** The keyed colour is the *detected* screen colour (real screens read 0x00B140,
|
||||
not 0x00FF00), not a canonical green.
|
||||
- **"Auto Green/Blue Screen"** is the setting name. No engineering words in the UI (never "chroma",
|
||||
never "colour key"): the panel section is **Green/Blue Screen**, the sliders are **Amount**,
|
||||
**Softness**, **Fringe**.
|
||||
- **A clip is a clip** — alert clips get the same treatment from the same settings block.
|
||||
- **High confidence only** may auto-apply; medium shows the offer; low says nothing.
|
||||
- Settings are **per layer** (they belong to the layer in the UI). Sessions are keyed by
|
||||
**path + settings signature**, so two layers with identical settings still share one decoder.
|
||||
|
||||
## 2. Slices (one Good Dog each)
|
||||
|
||||
| # | Slice | Test |
|
||||
|---|---|---|
|
||||
| A | ✅ media audio + shared clip pipe (TASK 21) | shipped `2670ac0` |
|
||||
| B | ✅ Pure `Services/ChromaKeyDetector.cs`: sample a `VideoFrame` → green / blue / none + suggested colour + confidence | synthetic frames: green, blue, gradient, letterboxed, lawn (must say none) |
|
||||
| C | ✅ Pure `Services/VideoFilterChain.cs`: options → `-vf` string (`scale → colorkey → despill → format=bgra`) | exact string assertions (encoder `FfmpegArgs` style) |
|
||||
| D | ✅ Detect on add: one `-frames:v 1` probe (mirror `IFrameRateProbe`) → suggestion in the panel; no rendering change | add a green-screen file → suggestion appears with its colour |
|
||||
| E | ✅ Apply: session key `path|key-settings`, filter chain in the pipe, level/mute untouched | keyed layer over art shows the art through keyed pixels **and** the preview bitmap carries alpha |
|
||||
| F | ✅ "Auto Green/Blue Screen" opt-in (App Settings; high confidence only, and the panel says it was automatic), alert clips keyed through the same settings block, spill shipped as the **Fringe** switch | slider reaches the chain and the restart preserves loop state |
|
||||
|
||||
## 3. Landmines for whoever builds this
|
||||
|
||||
- **Two consumers.** The preview bitmap and `LatestFrame` fork inside `MediaVideoSourceManager`; keying
|
||||
must happen upstream (in the pipe), or one path shows green.
|
||||
- **Parameter change = decoder restart** (`-vf` is fixed at spawn). Debounce, and carry loop + refcount
|
||||
across the restart instead of tearing the session down.
|
||||
- **Session identity.** `ResolveOutputFrame` and the preview-bitmap adoption must derive the session key
|
||||
from the same helper as the panel, or a keyed and an unkeyed layer on one file fight over one decoder.
|
||||
- **Detection is a second reader of the file** — one frame, async, never on the UI thread; a failed
|
||||
probe means "no suggestion", never a broken layer.
|
||||
- **Letterboxing** (black bars) breaks naive border sampling — detect and exclude them first.
|
||||
|
||||
## 4. Known limits (honest)
|
||||
|
||||
- The offer is made **when a clip is added or changed** — not at every launch. The settings persist,
|
||||
so a keyed layer comes back keyed; it just does not re-offer the probe.
|
||||
- Auto-apply fires only at high confidence. Medium confidence always asks, low says nothing.
|
||||
- The key is the layer's, but the decode is shared per **path + look**: two layers on one file with
|
||||
different Amount/Softness values are two decoders (and therefore two audio streams, muted upstream
|
||||
unless enabled) — rare, and the alternative is silently sharing the wrong picture.
|
||||
+58
-1
@@ -48,8 +48,65 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Secondary buttons used to be YtButton with the SAME tone as the panel behind them, so they
|
||||
read as plain text (creator, 2026-11-05: "you can tell they're buttons b/c our styling hasn't
|
||||
been applied"). They now sit on a higher surface with a hairline border, and show a focus ring
|
||||
so a keyboard user can find the one that matters. -->
|
||||
<Style x:Key="YtButtonSecondary" TargetType="Button" BasedOn="{StaticResource YtButton}">
|
||||
<Setter Property="Background" Value="{StaticResource Brush.SurfaceContainer}"/>
|
||||
<Setter Property="Background" Value="{StaticResource Brush.SurfaceContainerHigh}"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource Brush.OnSurface}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Grid>
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}"
|
||||
BorderBrush="{StaticResource Brush.Outline}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Sm}"
|
||||
Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<Border x:Name="Glow" Background="White" CornerRadius="{StaticResource Radius.Sm}" Opacity="0"/>
|
||||
<Border x:Name="Focus" BorderBrush="{StaticResource Brush.Primary}" BorderThickness="2"
|
||||
CornerRadius="{StaticResource Radius.Sm}" Opacity="0" Margin="-2"/>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Glow" Property="Opacity" Value="0.08"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="Glow" Property="Opacity" Value="0.16"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="Focus" Property="Opacity" Value="1"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.45"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- The release badge: a pill that is itself a button (it links to the product site until the
|
||||
Steam store page exists). -->
|
||||
<Style x:Key="PillBadgeButton" TargetType="Button">
|
||||
<Setter Property="Foreground" Value="{StaticResource Brush.OnSurfaceVariant}"/>
|
||||
<Setter Property="FontSize" Value="11"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Padding" Value="10,3"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="{StaticResource Brush.SurfaceContainerHigh}"
|
||||
BorderBrush="{StaticResource Brush.Outline}" BorderThickness="1"
|
||||
CornerRadius="999" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="IconButton" TargetType="Button">
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// The left panel's alert stack (creator design, 2026-11-05): standing state on top, transient events
|
||||
/// beneath it, newest first, pushing the panel's content down. Only red rows belong here — the panel
|
||||
/// is where "something needs you" lives, so it never fills with chatter.
|
||||
/// <para><b>Row 1 is the Steam licence indicator</b> and nothing displaces it. It is pinned while
|
||||
/// higher output tiers are unavailable, and becomes dismissible — permanently — once ownership is
|
||||
/// verified. If ownership is later lost, it comes back as a pinned indicator, because that is a change
|
||||
/// of state rather than a preference.</para>
|
||||
/// </summary>
|
||||
public partial class MainViewModel
|
||||
{
|
||||
private const string SteamLicenceAlertId = "steam-licence";
|
||||
|
||||
private readonly ObservableCollection<AttentionAlert> _attentionAlerts = new();
|
||||
private bool _steamLicenceDismissed;
|
||||
|
||||
public ObservableCollection<AttentionAlert> AttentionAlerts => _attentionAlerts;
|
||||
|
||||
public bool HasAttentionAlerts => _attentionAlerts.Count > 0;
|
||||
|
||||
public RelayCommand<AttentionAlert> DismissAlertCommand => new(DismissAlert);
|
||||
|
||||
public RelayCommand<AttentionAlert> ActivateAlertCommand => new(ActivateAlert);
|
||||
|
||||
/// <summary>The licence indicator's text (creator wording, 2026-11-05): the limit this build runs
|
||||
/// at, plus where to find out why. Not a warning — the resolution picker explains the detail, and
|
||||
/// clicking the row opens About.</summary>
|
||||
private string SteamLicenceText()
|
||||
{
|
||||
var entitled = 30;
|
||||
if (QualityOptions.Length > 0)
|
||||
{
|
||||
entitled = QualityOptions
|
||||
.Where(option => HasProOutput || !option.RequiresPro)
|
||||
.Select(option => option.Fps)
|
||||
.DefaultIfEmpty(30)
|
||||
.Max();
|
||||
}
|
||||
return $"Steam ID Limit: {entitled}fps\nClick for More Info";
|
||||
}
|
||||
|
||||
/// <summary>Recomputes row 1 in place. Called at startup and whenever ownership changes.</summary>
|
||||
private void RefreshSteamLicenceAlert()
|
||||
{
|
||||
var existing = _attentionAlerts.FirstOrDefault(alert => alert.Id == SteamLicenceAlertId);
|
||||
var hidden = IsAppOwned && _steamLicenceDismissed;
|
||||
|
||||
if (hidden)
|
||||
{
|
||||
if (existing != null) _attentionAlerts.Remove(existing);
|
||||
RaiseAttentionChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
var alert = new AttentionAlert(
|
||||
SteamLicenceAlertId,
|
||||
SteamLicenceText(),
|
||||
IsPinned: !IsAppOwned,
|
||||
AttentionAlertAction.About);
|
||||
|
||||
var index = existing == null ? -1 : _attentionAlerts.IndexOf(existing);
|
||||
if (index < 0) _attentionAlerts.Insert(0, alert);
|
||||
else _attentionAlerts[index] = alert; // same row, updated state
|
||||
RaiseAttentionChanged();
|
||||
}
|
||||
|
||||
/// <summary>Pushes an event alert. Newest sits directly under the licence indicator; older ones
|
||||
/// stack beneath, so the newest is the one nearest the eye.</summary>
|
||||
private AttentionAlert? PushAttentionAlert(string id, string text, long logFrom, long logTo)
|
||||
{
|
||||
var alert = new AttentionAlert(id, text, IsPinned: false, AttentionAlertAction.Logs, logFrom, logTo);
|
||||
var insertAt = _attentionAlerts.Count(alert => alert.Id == SteamLicenceAlertId);
|
||||
var existing = _attentionAlerts.FirstOrDefault(candidate => candidate.Id == id);
|
||||
if (existing != null)
|
||||
{
|
||||
// Same event advancing (reconnecting attempt 2 → 3): update the row, never duplicate it.
|
||||
_attentionAlerts[_attentionAlerts.IndexOf(existing)] = alert;
|
||||
}
|
||||
else
|
||||
{
|
||||
_attentionAlerts.Insert(insertAt, alert);
|
||||
}
|
||||
RaiseAttentionChanged();
|
||||
return alert;
|
||||
}
|
||||
|
||||
/// <summary>Test seam: pushes an event row without a stream session behind it.</summary>
|
||||
internal AttentionAlert? PushAttentionAlertForTest(string id, string text, long logFrom, long logTo)
|
||||
=> PushAttentionAlert(id, text, logFrom, logTo);
|
||||
|
||||
private void RemoveAttentionAlert(string id)
|
||||
{
|
||||
var existing = _attentionAlerts.FirstOrDefault(alert => alert.Id == id);
|
||||
if (existing == null) return;
|
||||
_attentionAlerts.Remove(existing);
|
||||
RaiseAttentionChanged();
|
||||
}
|
||||
|
||||
private void DismissAlert(AttentionAlert? alert)
|
||||
{
|
||||
if (alert == null || alert.IsPinned) return;
|
||||
|
||||
if (alert.Id == SteamLicenceAlertId)
|
||||
{
|
||||
// Permanent for this profile: the creator said "I have seen it". Only honoured while
|
||||
// ownership holds — RefreshSteamLicenceAlert ignores it when Steam stops confirming.
|
||||
_steamLicenceDismissed = true;
|
||||
_layoutStore.SaveSteamLicenceIndicatorDismissed(true);
|
||||
}
|
||||
|
||||
RemoveAttentionAlert(alert.Id);
|
||||
}
|
||||
|
||||
private void ActivateAlert(AttentionAlert? alert)
|
||||
{
|
||||
if (alert == null) return;
|
||||
|
||||
if (alert.Action == AttentionAlertAction.About)
|
||||
{
|
||||
ShowAbout();
|
||||
return;
|
||||
}
|
||||
|
||||
// Event alert: open the log and paint this event's lines, so the alert is an entry point to
|
||||
// the detail rather than a dead end.
|
||||
HighlightLogRange(alert.LogFrom, alert.LogTo);
|
||||
SelectLogsTab(true);
|
||||
}
|
||||
|
||||
private void RaiseAttentionChanged() => OnPropertyChanged(nameof(HasAttentionAlerts));
|
||||
}
|
||||
@@ -488,19 +488,27 @@ public partial class MainViewModel
|
||||
/// carries none. A custom image (Browse…) always wins and is never overwritten.</summary>
|
||||
private void StampDefaultBackgroundAsset(Source background, string sceneName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(background.AssetId)) return;
|
||||
if (!background.UseDefaultBackground && !string.IsNullOrWhiteSpace(background.CustomBackgroundPath)) return;
|
||||
var asset = DefaultBackgroundAsset(sceneName);
|
||||
if (asset == null) return;
|
||||
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"pack://application:,,,/Assets/{asset}", UriKind.Absolute);
|
||||
// Assembly-qualified on purpose: the unqualified form resolves against the ENTRY assembly,
|
||||
// which is LlamaCasty.exe in production but the test host under `dotnet test` — so the seed
|
||||
// silently did nothing there (and the art test could not see the bundled image).
|
||||
var uri = new Uri($"pack://application:,,,/LlamaCasty;component/Assets/{asset}", UriKind.Absolute);
|
||||
using var stream = Application.GetResourceStream(uri)?.Stream;
|
||||
if (stream == null) return;
|
||||
using var ms = new MemoryStream();
|
||||
stream.CopyTo(ms);
|
||||
background.AssetId = AddAsset(ms.ToArray());
|
||||
var bytes = ms.ToArray();
|
||||
|
||||
// Already the shipped art → leave it. Compared by BYTES, not by a version stamp: assets are
|
||||
// hash-keyed on first seed, so a replaced bundled image never reaches an existing profile on
|
||||
// its own, and the version constant proved just as stale (2026-11-06).
|
||||
if (_layoutStore.AssetMatches(background.AssetId!, bytes)) return;
|
||||
background.AssetId = AddAsset(bytes);
|
||||
}
|
||||
catch { /* non-critical — the app works without default art */ }
|
||||
}
|
||||
|
||||
@@ -140,7 +140,10 @@ public partial class MainViewModel : ViewModelBase
|
||||
path, width, height,
|
||||
new FfmpegLocator(),
|
||||
() => new FfmpegDecodeProcess(),
|
||||
frameRateProbe: new FfmpegFrameRateProbe(new FfmpegLocator(), () => new FfmpegDecodeProcess()));
|
||||
frameRateProbe: new FfmpegFrameRateProbe(new FfmpegLocator(), () => new FfmpegDecodeProcess()),
|
||||
// TASK 64: an alert clip is a clip — it keys through the same settings block. The
|
||||
// layout has one alert box, so its settings are the ones the next alert uses.
|
||||
chromaKey: AlertBoxChromaKey());
|
||||
|
||||
/// <summary>Stamp the shipped llama placeholder into the Asset table at startup
|
||||
/// (idempotent — hash-keyed UpsertAsset dedupes). Best-effort: if it fails the
|
||||
@@ -179,6 +182,13 @@ public partial class MainViewModel : ViewModelBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The alert zone's own green/blue screen settings (one alert box per layout).</summary>
|
||||
private ChromaKeyOptions? AlertBoxChromaKey()
|
||||
=> Scenes.SelectMany(scene => scene.Elements).OfType<Source>()
|
||||
.FirstOrDefault(source => source.IsAlertBox)?.ChromaKey is { Enabled: true } key
|
||||
? key
|
||||
: null;
|
||||
|
||||
private void BrowseAlertVideo(Source? box)
|
||||
{
|
||||
if (box == null || box.Type != SourceType.AlertBox) return;
|
||||
@@ -190,6 +200,8 @@ public partial class MainViewModel : ViewModelBase
|
||||
if (dialog.ShowDialog() != true) return;
|
||||
box.AlertVideoPath = dialog.FileName;
|
||||
box.AlertUseDefaultVideo = false;
|
||||
// Offer the key for the chosen clip (same detector as a media layer).
|
||||
_ = SuggestChromaKeyAsync(box);
|
||||
}
|
||||
|
||||
private void BrowseAlertAudio(Source? box)
|
||||
|
||||
@@ -16,6 +16,19 @@ public partial class MainViewModel
|
||||
|
||||
public ObservableCollection<AppLogEntry> CurrentLaunchLogEntries => _currentLaunchLogEntries;
|
||||
public ObservableCollection<AppLogEntry> PinnedLogEntries => _pinnedLogEntries;
|
||||
|
||||
// The event range a clicked alert points at. A range rather than a collection: the log list is
|
||||
// virtualised, and a membership change would not re-evaluate realised rows — two numbers do.
|
||||
private long _highlightedLogFrom;
|
||||
private long _highlightedLogTo;
|
||||
public long HighlightedLogFrom => _highlightedLogFrom;
|
||||
public long HighlightedLogTo => _highlightedLogTo;
|
||||
|
||||
private void HighlightLogRange(long from, long to)
|
||||
{
|
||||
SetProperty(ref _highlightedLogFrom, from, nameof(HighlightedLogFrom));
|
||||
SetProperty(ref _highlightedLogTo, to, nameof(HighlightedLogTo));
|
||||
}
|
||||
public bool HasPinnedLogEntries => _pinnedLogEntries.Count > 0;
|
||||
public RelayCommand<AppLogEntry> AcknowledgeLogEntryCommand => new(AcknowledgeLogEntry);
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Microsoft.Win32;
|
||||
using ytLive.Models;
|
||||
using ytLive.Services;
|
||||
using ytLive.Services.Audio;
|
||||
|
||||
namespace ytLive.ViewModels;
|
||||
|
||||
@@ -10,6 +15,10 @@ namespace ytLive.ViewModels;
|
||||
// partials: the readonly manager field is assigned in the core constructor, the
|
||||
// shared WriteableBitmap published per file is adopted by every media Source whose
|
||||
// MediaPath matches, and ResolveOutputFrame feeds the live compositor.
|
||||
//
|
||||
// TASK 64 changed what a "session" is: it is now keyed by file path + the layer's LOOK
|
||||
// (green/blue screen settings), because the key is applied inside the decode pipe. Two
|
||||
// layers with the same look share one decoder; two different looks get two.
|
||||
public partial class MainViewModel
|
||||
{
|
||||
// Decode resolution: the 1920x1080 master. Media frames are scaled to the
|
||||
@@ -17,19 +26,329 @@ public partial class MainViewModel
|
||||
private const int MediaDecodeWidth = 1920;
|
||||
private const int MediaDecodeHeight = 1080;
|
||||
|
||||
private const string VideoFileFilter =
|
||||
"Video files (*.mp4;*.mov;*.avi;*.mkv;*.webm)|*.mp4;*.mov;*.avi;*.mkv;*.webm|All files (*.*)|*.*";
|
||||
|
||||
private readonly MediaVideoSourceManager _mediaManager;
|
||||
|
||||
// MediaVideoSourceManager publishes one shared WriteableBitmap per file; every
|
||||
// media Source pointing at that path picks it up for the preview/canvas.
|
||||
private void OnMediaPreviewBitmapChanged(string path, WriteableBitmap bitmap)
|
||||
// Reads one frame of a clip so the layer can offer "looks like a green screen" (TASK 64).
|
||||
private readonly IChromaProbe? _chromaProbe;
|
||||
|
||||
// One probe per file per launch — the answer belongs to the file, not to the layer.
|
||||
private readonly HashSet<string> _chromaProbedPaths = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private bool _autoChromaScreen;
|
||||
|
||||
/// <summary>"Auto Green/Blue Screen": apply a detected screen without asking. Off by default —
|
||||
/// the app offers, and only a creator who turns this on gets it done for them. Fires only on
|
||||
/// high-confidence detections, because a wrong automatic key eats the picture.</summary>
|
||||
public bool AutoChromaScreen
|
||||
{
|
||||
foreach (var source in Scenes.SelectMany(s => s.Elements.OfType<Source>())
|
||||
.Where(s => s.IsMediaSource && s.MediaPath == path))
|
||||
get => _autoChromaScreen;
|
||||
set
|
||||
{
|
||||
if (!SetProperty(ref _autoChromaScreen, value)) return;
|
||||
_layoutStore.SaveAutoChromaScreen(value);
|
||||
}
|
||||
}
|
||||
|
||||
// One subscription per media Source, so removing a layer stops the listener as
|
||||
// well as the decoder (a scene element outlives its layer list row).
|
||||
private readonly Dictionary<string, PropertyChangedEventHandler> _mediaHandlers = new();
|
||||
|
||||
/// <summary>What a decode session is: the file plus the look applied in the pipe (TASK 64).
|
||||
/// A path cannot contain '|', so the key is unambiguous and human-readable in logs.</summary>
|
||||
internal static string MediaSessionKey(string path, ChromaKeyOptions key)
|
||||
=> $"{path}|{key.Signature}";
|
||||
|
||||
internal static string MediaSessionKey(Source source)
|
||||
=> source.MediaPath is { } path ? MediaSessionKey(path, source.ChromaKey) : string.Empty;
|
||||
|
||||
// MediaVideoSourceManager publishes one shared WriteableBitmap per session; every
|
||||
// media Source pointing at that path+look picks it up for the preview/canvas.
|
||||
private void OnMediaPreviewBitmapChanged(string sessionKey, WriteableBitmap bitmap)
|
||||
{
|
||||
foreach (var source in Scenes.SelectMany(s => s.Elements).OfType<Source>())
|
||||
if (source.IsMediaSource && MediaSessionKey(source) == sessionKey)
|
||||
source.VideoImageSource = bitmap;
|
||||
}
|
||||
|
||||
// Called from the encoder error path is out of scope (TASK 21 sees the decoder
|
||||
// fail at startup); log to the debug console for now, surfaced via the UI later.
|
||||
private static void OnMediaFailed(string path, string message)
|
||||
=> System.Diagnostics.Debug.WriteLine($"MediaSource: '{path}' failed: {message}");
|
||||
private void OnMediaFailed(string path, string message)
|
||||
{
|
||||
Helpers.AppLog.Write($"MediaSource: '{path}' failed: {message}");
|
||||
_notifications.Warning("Couldn't play that video", System.IO.Path.GetFileName(SessionPath(path)));
|
||||
}
|
||||
|
||||
// ---------- add / change the file ----------
|
||||
|
||||
private void AddMedia()
|
||||
{
|
||||
if (PickVideoFile() is { } path)
|
||||
AddMediaSource(path);
|
||||
}
|
||||
|
||||
private string? PickVideoFile(string title = "Choose a video file")
|
||||
{
|
||||
var dialog = new OpenFileDialog
|
||||
{
|
||||
Title = title,
|
||||
Filter = VideoFileFilter,
|
||||
};
|
||||
return dialog.ShowDialog() == true ? dialog.FileName : null;
|
||||
}
|
||||
|
||||
/// <summary>Adds a MediaSource layer for <paramref name="path"/> to the staged scene.
|
||||
/// Internal so the Good Dog test drives the real add path without a file dialog.</summary>
|
||||
internal void AddMediaSource(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return;
|
||||
AddSource(SourceType.MediaSource, path);
|
||||
}
|
||||
|
||||
private void ChangeMediaFile(Source? source)
|
||||
{
|
||||
if (source is not { IsMediaSource: true }) return;
|
||||
if (PickVideoFile("Replace the video") is not { } path) return;
|
||||
PushPreviewUndo();
|
||||
source.ChromaSuggestion = default;
|
||||
source.MediaPath = path;
|
||||
}
|
||||
|
||||
// ---------- green / blue screen detection (TASK 64) ----------
|
||||
|
||||
/// <summary>Looks at one frame of the clip and stores the offer on the layer. Runs off the
|
||||
/// UI thread through the probe seam; a file that cannot be read simply gets no offer.
|
||||
/// Works for a video layer and for the alert box's own clip — a clip is a clip.</summary>
|
||||
private async System.Threading.Tasks.Task SuggestChromaKeyAsync(Source source)
|
||||
{
|
||||
if (source.ChromaKeyEnabled) return;
|
||||
if (ClipPathFor(source) is not { } path) return;
|
||||
if (_chromaProbe == null) return;
|
||||
|
||||
var frame = await _chromaProbe.ProbeAsync(path).ConfigureAwait(true);
|
||||
if (frame == null) return;
|
||||
if (!string.Equals(ClipPathFor(source), path, StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var suggestion = ChromaKeyDetector.Detect(frame);
|
||||
source.ChromaSuggestion = suggestion;
|
||||
|
||||
if (AutoChromaScreen && suggestion.IsHighConfidence)
|
||||
{
|
||||
AcceptChromaSuggestion(source);
|
||||
source.ChromaKeyAutoApplied = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The file a layer plays: a video layer's clip, or the alert box's replacement clip.
|
||||
/// The shipped alert default is not probed — it is ours, and it is not a screen shoot.</summary>
|
||||
private static string? ClipPathFor(Source source)
|
||||
=> source.IsMediaSource
|
||||
? source.MediaPath
|
||||
: source.Type == SourceType.AlertBox && !source.AlertUseDefaultVideo
|
||||
? source.AlertVideoPath
|
||||
: null;
|
||||
|
||||
/// <summary>Accepts the detector's offer: the layer keys the colour the camera actually saw.</summary>
|
||||
private void AcceptChromaSuggestion(Source? source)
|
||||
{
|
||||
if (source is not { IsMediaSource: true } || source.ChromaSuggestion.Screen == ChromaScreen.None) return;
|
||||
PushPreviewUndo();
|
||||
var key = ChromaKeyOptions.For(source.ChromaSuggestion);
|
||||
source.ChromaKeyColor = key.Color;
|
||||
source.ChromaKeySimilarity = key.Similarity;
|
||||
source.ChromaKeySoftness = key.Softness;
|
||||
source.ChromaKeySpill = key.Spill;
|
||||
source.ChromaScreen = key.Screen;
|
||||
source.ChromaKeyAutoApplied = false;
|
||||
source.ChromaKeyEnabled = true;
|
||||
}
|
||||
|
||||
// ---------- session lifecycle (one session per path + look) ----------
|
||||
|
||||
/// <summary>Starts decoding the file if nothing else already is, and subscribes to the
|
||||
/// layer so a file swap, a loop flip or a look change reaches the right session.</summary>
|
||||
private void RegisterMediaSource(Source source)
|
||||
{
|
||||
if (_mediaHandlers.ContainsKey(source.Id)) return;
|
||||
|
||||
var lastKey = MediaSessionKey(source);
|
||||
|
||||
void OnSourceChanged(object? _, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName is nameof(Source.MediaPath) or nameof(Source.ChromaKeyEnabled)
|
||||
or nameof(Source.ChromaKeyColor) or nameof(Source.ChromaKeySimilarity)
|
||||
or nameof(Source.ChromaKeySoftness) or nameof(Source.ChromaKeySpill)
|
||||
or nameof(Source.ChromaScreen))
|
||||
{
|
||||
var next = MediaSessionKey(source);
|
||||
if (string.Equals(next, lastKey, StringComparison.OrdinalIgnoreCase)) return;
|
||||
var previous = lastKey;
|
||||
lastKey = next;
|
||||
// A look change is a different decode: let the old session go (if nothing
|
||||
// else uses it) and start the new one.
|
||||
ReleaseMediaIfUnused(previous);
|
||||
EnsureMediaSession(next);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.PropertyName == nameof(Source.MediaIsLooping) && MediaSessionKey(source) is { Length: > 0 } key)
|
||||
{
|
||||
var looping = AnyMediaReferenceLoops(key);
|
||||
_mediaManager.SetLooping(key, looping);
|
||||
// Loop is only consulted at end-of-file by a LIVE decoder, so flipping it on a clip
|
||||
// that already finished used to do nothing at all (reported 2026-11-05). Start it.
|
||||
if (looping && !_mediaManager.IsRunning(key))
|
||||
_ = RestartMediaAsync(source, key);
|
||||
}
|
||||
else if (e.PropertyName is nameof(Source.MediaVolume) or nameof(Source.MediaMuted)
|
||||
&& MediaSessionKey(source) is { Length: > 0 } audioKey)
|
||||
{
|
||||
ApplyMediaAudioSettings(audioKey);
|
||||
}
|
||||
}
|
||||
|
||||
_mediaHandlers[source.Id] = OnSourceChanged;
|
||||
source.PropertyChanged += OnSourceChanged;
|
||||
|
||||
if (source.MediaPath is { Length: > 0 } path)
|
||||
{
|
||||
EnsureMediaSession(MediaSessionKey(path, source.ChromaKey));
|
||||
|
||||
// One probe per file per launch: the answer depends on the file, not the layer.
|
||||
if (source.ChromaSuggestion.Screen == ChromaScreen.None && !_chromaProbedPaths.Contains(path))
|
||||
{
|
||||
_chromaProbedPaths.Add(path);
|
||||
_ = SuggestChromaKeyAsync(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UnregisterMediaSource(Source source)
|
||||
{
|
||||
if (_mediaHandlers.Remove(source.Id, out var handler))
|
||||
source.PropertyChanged -= handler;
|
||||
}
|
||||
|
||||
private void EnsureMediaSession(string? sessionKey)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sessionKey)) return;
|
||||
if (_mediaManager.HasSession(sessionKey))
|
||||
{
|
||||
ApplyMediaAudioSettings(sessionKey);
|
||||
return;
|
||||
}
|
||||
_ = AcquireMediaSessionAsync(sessionKey);
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task AcquireMediaSessionAsync(string sessionKey)
|
||||
{
|
||||
var source = Scenes.SelectMany(s => s.Elements).OfType<Source>()
|
||||
.FirstOrDefault(s => s.IsMediaSource && MediaSessionKey(s) == sessionKey);
|
||||
if (source?.MediaPath is not { } path) return;
|
||||
|
||||
if (!await _mediaManager.AcquireAsync(sessionKey, path, source.ChromaKey)) return;
|
||||
source.IsMediaRunning = true;
|
||||
source.MediaPlaybackState = MediaPlaybackState.Playing;
|
||||
|
||||
// A session can be running before this layer existed (shared look), in which
|
||||
// case the bitmap is already published and will not be raised again for us.
|
||||
if (_mediaManager.GetPreviewBitmap(sessionKey) is { } bitmap)
|
||||
OnMediaPreviewBitmapChanged(sessionKey, bitmap);
|
||||
|
||||
ApplyMediaAudioSettings(sessionKey);
|
||||
}
|
||||
|
||||
/// <summary>The session's sound controls: one decoder is shared per path+look, so the level
|
||||
/// and mute are per session — the layer that was last touched is the one that wins.</summary>
|
||||
private void ApplyMediaAudioSettings(string sessionKey)
|
||||
{
|
||||
var source = Scenes.SelectMany(s => s.Elements).OfType<Source>()
|
||||
.FirstOrDefault(s => s.IsMediaSource && MediaSessionKey(s) == sessionKey);
|
||||
if (source == null) return;
|
||||
_mediaManager.SetAudioSettings(sessionKey, source.MediaVolume, source.MediaMuted);
|
||||
}
|
||||
|
||||
/// <summary>A clip's own soundtrack joins the desktop/game group, so the desktop fader and
|
||||
/// the voice ducker treat it exactly like game audio (TASK 21 audio slice).</summary>
|
||||
/// <summary>A clip played out: say so on the layer, so the panel stops pretending it is playing.</summary>
|
||||
private void OnMediaSessionCompleted(string sessionKey)
|
||||
{
|
||||
foreach (var source in Scenes.SelectMany(s => s.Elements).OfType<Source>())
|
||||
if (source.IsMediaSource && MediaSessionKey(source) == sessionKey)
|
||||
{
|
||||
source.IsMediaRunning = false;
|
||||
source.MediaPlaybackState = MediaPlaybackState.Stopped;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Starts a finished clip again from the top (the panel's "Play again").</summary>
|
||||
private void ReplayMedia(Source? source)
|
||||
{
|
||||
if (source is not { IsMediaSource: true }) return;
|
||||
var key = MediaSessionKey(source);
|
||||
if (key.Length == 0) return;
|
||||
|
||||
_ = RestartMediaAsync(source, key);
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task RestartMediaAsync(Source source, string sessionKey)
|
||||
{
|
||||
if (!_mediaManager.HasSession(sessionKey))
|
||||
{
|
||||
EnsureMediaSession(sessionKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (await _mediaManager.RestartAsync(sessionKey))
|
||||
{
|
||||
source.IsMediaRunning = true;
|
||||
source.MediaPlaybackState = MediaPlaybackState.Playing;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnMediaAudioAvailable(string sessionKey, AudioSample sample)
|
||||
=> _audioMixer.EnqueueDesktopMediaAudio(sample);
|
||||
|
||||
/// <summary>Shared sessions or not, the loop state is the session's: any live reference
|
||||
/// asking for a loop makes that one decoder loop (recorded rule, TASK 21).</summary>
|
||||
private bool AnyMediaReferenceLoops(string sessionKey)
|
||||
=> Scenes.SelectMany(s => s.Elements).OfType<Source>()
|
||||
.Any(s => s.IsMediaSource && MediaSessionKey(s) == sessionKey && s.MediaIsLooping);
|
||||
|
||||
private bool HasMediaReference(string sessionKey)
|
||||
=> Scenes.SelectMany(s => s.Elements).OfType<Source>()
|
||||
.Any(s => s.IsMediaSource && string.Equals(MediaSessionKey(s), sessionKey, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private void ReleaseMediaIfUnused(string? sessionKey)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sessionKey)) return;
|
||||
if (!_mediaManager.HasSession(sessionKey)) return;
|
||||
if (HasMediaReference(sessionKey)) return;
|
||||
_ = _mediaManager.ReleaseAsync(sessionKey);
|
||||
}
|
||||
|
||||
/// <summary>After a layout load: subscribe every persisted media layer and start one
|
||||
/// session per distinct path+look; release sessions the layout no longer uses.</summary>
|
||||
private void ReacquireMediaSources()
|
||||
{
|
||||
var sources = Scenes.SelectMany(s => s.Elements).OfType<Source>()
|
||||
.Where(s => s.IsMediaSource && !string.IsNullOrWhiteSpace(s.MediaPath))
|
||||
.ToList();
|
||||
|
||||
foreach (var source in sources)
|
||||
RegisterMediaSource(source);
|
||||
|
||||
var wanted = sources.Select(MediaSessionKey)
|
||||
.Where(key => key.Length > 0)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
foreach (var stale in _mediaManager.GetActiveKeys()
|
||||
.Where(key => !wanted.Contains(key, StringComparer.OrdinalIgnoreCase))
|
||||
.ToList())
|
||||
_ = _mediaManager.ReleaseAllAsync(stale);
|
||||
}
|
||||
|
||||
/// <summary>A session key carries a file path and a look; the toast wants the file name.</summary>
|
||||
private static string SessionPath(string sessionKey)
|
||||
=> sessionKey.Split('|')[0];
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ public partial class MainViewModel
|
||||
EntitlementErrorMessage = _entitlement.ErrorMessage;
|
||||
if (!changed) return;
|
||||
OnPropertyChanged(nameof(HasProOutput));
|
||||
OnPropertyChanged(nameof(LicenceStateLabel));
|
||||
RefreshSteamLicenceAlert();
|
||||
if (!HasProOutput && _selectedQuality is { RequiresPro: true } && CanChangeQuality)
|
||||
SelectedQuality = QualityOptions.Single(option => option.Display == OutputProfile.FreeFallbackName);
|
||||
}
|
||||
@@ -77,6 +79,8 @@ public partial class MainViewModel
|
||||
if (!DevBuild.IsDevelopment) return;
|
||||
if (!SetProperty(ref _developerMode, value)) return;
|
||||
OnPropertyChanged(nameof(HasProOutput));
|
||||
OnPropertyChanged(nameof(LicenceStateLabel));
|
||||
RefreshSteamLicenceAlert();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
@@ -29,6 +30,34 @@ public partial class MainViewModel : ViewModelBase
|
||||
public const string CoffeeUrl = "https://buymeacoffee.com/llamachiley";
|
||||
public static string AppVersionLabel => $"Version {typeof(MainViewModel).Assembly.GetName().Version?.ToString(3)}";
|
||||
|
||||
// ── About box copy (creator ruling, 2026-11-05). The price and its end date live HERE, once, so
|
||||
// the app, the site and docs/commercial.md cannot drift apart. ──
|
||||
public const string LaunchPrice = "$79";
|
||||
public const string StandardPrice = "$99";
|
||||
/// <summary>When the launch price ends. Deliberately EVENT-relative, not a date: the store page is
|
||||
/// in Valve's queue (identity verification + tax review), so a fixed date would be a public promise
|
||||
/// we cannot keep if their backlog slips (creator ruling 2026-11-05).</summary>
|
||||
public const string LaunchPriceEndsLabel = "30 days after the store page goes live";
|
||||
|
||||
/// <summary>The release state shown as a badge. Not the assembly version — that number is for
|
||||
/// log lines, not for the creator.</summary>
|
||||
public static string AppReleaseLabel => "Pre-Release";
|
||||
|
||||
public string UpgradeCtaLabel => $"Unlock 60 fps — {LaunchPrice}";
|
||||
public string PriceLine => $"Launch price {LaunchPrice}";
|
||||
public string PriceNote => $"{LaunchPriceEndsLabel} — after that {StandardPrice}, locked for life.";
|
||||
public string FreeOfferText => "Livestream and record at 30 fps.";
|
||||
public string PaidOfferText => "Unlocks 60 fps for streaming and recording.";
|
||||
public string TrustLine => "One-time purchase · lifetime licence · no account, no subscription, no tracking.";
|
||||
|
||||
/// <summary>Footer copyright. The year is the current one, not a hardcoded literal, so a build
|
||||
/// shipped next year does not carry a stale date.</summary>
|
||||
public string CopyrightLabel => $"© {DateTime.Now.Year} Llama Chile Shop";
|
||||
|
||||
/// <summary>Shown instead of the price and CTA once ownership is verified: a paying customer is
|
||||
/// never sold to.</summary>
|
||||
public string LicenceStateLabel => IsAppOwned ? "Licence: owned via Steam — thank you." : string.Empty;
|
||||
|
||||
/// <summary>The About hub's optional product-information link.</summary>
|
||||
public bool IsPremiumAvailable => PremiumUrl.Length > 0;
|
||||
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Services;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
namespace ytLive.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·1 — a dropped push is retried instead of ending the session. The loop itself lives in
|
||||
/// <see cref="StreamRecovery"/> (pure, testable); this partial supplies the app-side steps and reports
|
||||
/// each episode into the left panel's alert stack.
|
||||
/// <para>Deliberately narrow: only the ENCODER dying is recoverable. A compositor fault still goes
|
||||
/// through <see cref="OnFramePumpFailed"/> and ends the session, because retrying it would loop.</para>
|
||||
/// </summary>
|
||||
public partial class MainViewModel
|
||||
{
|
||||
private CancellationTokenSource? _recoveryCts;
|
||||
|
||||
/// <summary>True while a push is being relaunched — the top bar shows amber RECONNECTING.</summary>
|
||||
public bool IsReconnecting
|
||||
{
|
||||
get => _isReconnecting;
|
||||
private set
|
||||
{
|
||||
if (!SetProperty(ref _isReconnecting, value)) return;
|
||||
RaiseTopBarModes();
|
||||
OnPropertyChanged(nameof(ReconnectDetailText));
|
||||
ApplyReconnectPollCadence();
|
||||
}
|
||||
}
|
||||
|
||||
private bool _isReconnecting;
|
||||
|
||||
/// <summary>True after a drop ended the session with the broadcast gone: the show is over and the
|
||||
/// only honest action left is a new broadcast. Drives the red OFF AIR line and the
|
||||
/// "Back on air" button (TASK 32·3).</summary>
|
||||
public bool IsOffAirAfterDrop
|
||||
{
|
||||
get => _isOffAirAfterDrop;
|
||||
private set
|
||||
{
|
||||
if (!SetProperty(ref _isOffAirAfterDrop, value)) return;
|
||||
RaiseTopBarModes();
|
||||
OnPropertyChanged(nameof(ShowPrimaryStartButton));
|
||||
OnPropertyChanged(nameof(BackOnAirLabel));
|
||||
}
|
||||
}
|
||||
|
||||
private bool _isOffAirAfterDrop;
|
||||
|
||||
public string BackOnAirLabel => "● Back on air";
|
||||
|
||||
private RelayCommand? _backOnAirCommand;
|
||||
|
||||
/// <summary>One click: build a new broadcast from the saved details and push — no dialog, and the
|
||||
/// title carries the resume marker so the channel shows what happened.</summary>
|
||||
public RelayCommand BackOnAirCommand =>
|
||||
_backOnAirCommand ??= new RelayCommand(_ => BackOnAir(), _ => IsOffAirAfterDrop && IsOffline);
|
||||
|
||||
/// <summary>How many times this session has been resumed — the title marker counts.</summary>
|
||||
private int _resumeCount;
|
||||
|
||||
/// <summary>The title the dropped show was using, kept so the resumed broadcast is named after it
|
||||
/// rather than after whatever the form happens to hold now.</summary>
|
||||
private string? _lastLiveTitle;
|
||||
|
||||
private void BackOnAir()
|
||||
{
|
||||
if (!IsOffAirAfterDrop) return;
|
||||
|
||||
_resumeCount++;
|
||||
StreamTitle = BroadcastTitle.ForResume(_lastLiveTitle ?? StreamTitle, _resumeCount);
|
||||
WindowTitle = $"{StreamTitle} — LlamaCasty";
|
||||
|
||||
// Clear the state BEFORE starting: the go-live path reuses the primary-button gate, and a
|
||||
// session that starts while this flag is set would show two ways to start at once.
|
||||
IsOffAirAfterDrop = false;
|
||||
|
||||
AppLog.Write($"RECONNECT: back on air as a new broadcast — '{StreamTitle}'");
|
||||
OnAirPillOn = true;
|
||||
StartStreamingSession(alsoRecord: false); // the ordinary path: new broadcast, same cached stream
|
||||
}
|
||||
|
||||
/// <summary>Test seam: puts the view-model in the post-drop state without a live session.</summary>
|
||||
internal void MarkOffAirAfterDropForTest(string? title)
|
||||
{
|
||||
_lastLiveTitle = title;
|
||||
IsOffAirAfterDrop = true;
|
||||
}
|
||||
|
||||
/// <summary>The attempt currently in flight (0 when idle).</summary>
|
||||
public int ReconnectAttempt
|
||||
{
|
||||
get => _reconnectAttempt;
|
||||
private set
|
||||
{
|
||||
if (!SetProperty(ref _reconnectAttempt, value)) return;
|
||||
OnPropertyChanged(nameof(ReconnectDetailText));
|
||||
}
|
||||
}
|
||||
|
||||
private int _reconnectAttempt;
|
||||
|
||||
/// <summary>Whole seconds since the drop — measured, never predicted.</summary>
|
||||
public int ReconnectElapsedSeconds
|
||||
{
|
||||
get => _reconnectElapsedSeconds;
|
||||
private set
|
||||
{
|
||||
if (!SetProperty(ref _reconnectElapsedSeconds, value)) return;
|
||||
OnPropertyChanged(nameof(ReconnectDetailText));
|
||||
}
|
||||
}
|
||||
|
||||
private int _reconnectElapsedSeconds;
|
||||
private System.Windows.Threading.DispatcherTimer? _reconnectTick;
|
||||
|
||||
/// <summary>While recovering, ask YouTube much more often — the status IS the sign, so it has to
|
||||
/// keep up with a reconnect that can succeed or die inside a few seconds.</summary>
|
||||
private void ApplyReconnectPollCadence()
|
||||
{
|
||||
if (IsReconnecting)
|
||||
{
|
||||
_healthPollTimer.Interval = TimeSpan.FromSeconds(4);
|
||||
_reconnectTick ??= new System.Windows.Threading.DispatcherTimer
|
||||
{
|
||||
Interval = TimeSpan.FromSeconds(1),
|
||||
};
|
||||
_reconnectTick.Tick -= OnReconnectTick;
|
||||
_reconnectTick.Tick += OnReconnectTick;
|
||||
_reconnectTick.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
_healthPollTimer.Interval = TimeSpan.FromSeconds(30);
|
||||
if (_reconnectTick != null)
|
||||
{
|
||||
_reconnectTick.Stop();
|
||||
_reconnectTick.Tick -= OnReconnectTick;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReconnectTick(object? sender, EventArgs e)
|
||||
=> ReconnectElapsedSeconds = (int)Math.Round(_reconnectStarted?.Elapsed.TotalSeconds ?? 0);
|
||||
|
||||
// Measured from the drop, so the displayed seconds are facts rather than a projection.
|
||||
private System.Diagnostics.Stopwatch? _reconnectStarted;
|
||||
|
||||
private void OnEncoderFailed(object? sender, string message)
|
||||
{
|
||||
if (!IsLive && !IsRecording) return;
|
||||
if (_recoveryCts != null) return; // one recovery at a time
|
||||
if (!IsLive) return; // a recording-only session has nothing to relive
|
||||
|
||||
AppLog.Write($"RECONNECT: encoder process failed: {message}");
|
||||
_recoveryCts = new CancellationTokenSource();
|
||||
_ = RecoverStreamAsync(message, _recoveryCts.Token);
|
||||
}
|
||||
|
||||
private async Task RecoverStreamAsync(string reason, CancellationToken cancellationToken)
|
||||
{
|
||||
ReconnectElapsedSeconds = 0;
|
||||
_reconnectStarted = System.Diagnostics.Stopwatch.StartNew();
|
||||
IsReconnecting = true;
|
||||
ReconnectAttempt = 0;
|
||||
var dropped = _reconnectStarted;
|
||||
|
||||
var logFrom = AppLog.SnapshotCurrentLaunch().Count > 0
|
||||
? AppLog.SnapshotCurrentLaunch()[^1].Sequence + 1
|
||||
: 1;
|
||||
|
||||
var recovery = new StreamRecovery(
|
||||
StreamRetryPolicy.Default,
|
||||
new StreamRecoverySteps
|
||||
{
|
||||
RestartAudio = _ =>
|
||||
{
|
||||
// The audio pipe's server is single-instance and its client just died, so it has
|
||||
// to be recreated before ffmpeg can attach — otherwise the restart fails on a
|
||||
// missing input.
|
||||
_audioMixer.StopLive();
|
||||
_audioMixer.StartLive(InstanceProfile.AudioPipeName(EncoderOptions.DefaultAudioPipeName));
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
StartPush = async ct =>
|
||||
{
|
||||
await _framePump.StartAsync(ct);
|
||||
return _framePump.IsRunning;
|
||||
},
|
||||
CheckBroadcast = async ct =>
|
||||
{
|
||||
if (_currentBroadcastId == null || _reusableStream?.Id == null)
|
||||
return BroadcastLiveness.Unknown;
|
||||
var status = await _youtubeStream.GetBroadcastStatusAsync(_currentBroadcastId);
|
||||
return status switch
|
||||
{
|
||||
"complete" => BroadcastLiveness.Complete,
|
||||
null => BroadcastLiveness.Unknown,
|
||||
_ => BroadcastLiveness.Live,
|
||||
};
|
||||
},
|
||||
Report = text =>
|
||||
{
|
||||
var progress = text.StartsWith("Stream dropped", StringComparison.Ordinal)
|
||||
? ParseAttempt(text)
|
||||
: 0;
|
||||
if (progress > 0) ReconnectAttempt = progress;
|
||||
|
||||
var to = AppLog.SnapshotCurrentLaunch() is { Count: > 0 } entries
|
||||
? entries[^1].Sequence
|
||||
: logFrom;
|
||||
PushAttentionAlert(
|
||||
"stream-recovery",
|
||||
text,
|
||||
logFrom,
|
||||
Math.Max(logFrom, to));
|
||||
},
|
||||
Log = line => AppLog.Write(line, AppLogMessageType.Error, AppLogErrorClass.Class2),
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
var result = await recovery.RunAsync(cancellationToken);
|
||||
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case RecoveryOutcome.Recovered:
|
||||
ReconnectAttempt = result.Attempts;
|
||||
AppLog.WriteSuccess(
|
||||
$"RECONNECT: recovered on attempt {result.Attempts} after {result.Elapsed.TotalSeconds:0.0} s");
|
||||
break;
|
||||
|
||||
case RecoveryOutcome.Cancelled:
|
||||
// The creator stopped the stream mid-recovery: nothing to report.
|
||||
break;
|
||||
|
||||
default:
|
||||
// Gave up, or the broadcast was already complete: this session is over. The alert
|
||||
// stack keeps the reason; the normal stop path clears pills, audio and recording.
|
||||
// Then the honest next step is offered as one click — a NEW broadcast (TASK 32·3),
|
||||
// which is the only way back on air once YouTube has completed this one.
|
||||
AppLog.Write("RECONNECT: session ended — the broadcast could not be recovered",
|
||||
AppLogMessageType.Error, AppLogErrorClass.Class1);
|
||||
var droppedTitle = StreamTitle;
|
||||
StopStream();
|
||||
MarkOffAirAfterDropForTest(null);
|
||||
_lastLiveTitle = droppedTitle;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write(ex, "RECONNECT: recovery loop faulted");
|
||||
StopStream();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reconnectStarted = null;
|
||||
IsReconnecting = false;
|
||||
ReconnectAttempt = 0;
|
||||
_recoveryCts?.Dispose();
|
||||
_recoveryCts = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ParseAttempt(string text)
|
||||
{
|
||||
// "Stream dropped — reconnecting (attempt 2 of 4)"
|
||||
var marker = text.IndexOf("attempt ", StringComparison.Ordinal);
|
||||
if (marker < 0) return 0;
|
||||
var rest = text[(marker + "attempt ".Length)..];
|
||||
var space = rest.IndexOf(' ');
|
||||
return int.TryParse(space > 0 ? rest[..space] : rest, out var attempt) ? attempt : 0;
|
||||
}
|
||||
|
||||
/// <summary>The creator asked to stop: never race a stop against a relaunch.</summary>
|
||||
private void CancelStreamRecovery() => _recoveryCts?.Cancel();
|
||||
|
||||
/// <summary>YouTube ended the chat: ask the broadcast status now rather than at the next tick.
|
||||
/// The API decides — this signal only saves up to 30 s of lying to the creator.</summary>
|
||||
private void OnChatEnded()
|
||||
{
|
||||
if (!IsLive) return;
|
||||
AppLog.Write("Chat ended event received — checking the broadcast status now");
|
||||
_ = PollHealthAsync();
|
||||
}
|
||||
}
|
||||
@@ -34,8 +34,9 @@ public partial class MainViewModel
|
||||
SettingsDrawerOpen = true;
|
||||
}
|
||||
|
||||
/// <summary>Called by the other drawers when they open, so settings yields to them.</summary>
|
||||
private void CloseSettingsDrawerIfOpen()
|
||||
/// <summary>Called by the other drawers when they open, so settings yields to them — and by the
|
||||
/// window's click-outside guard, so the gear tab retracts like every other drawer (2026-11-05).</summary>
|
||||
internal void CloseSettingsDrawerIfOpen()
|
||||
{
|
||||
if (_settingsDrawerOpen) SettingsDrawerOpen = false;
|
||||
}
|
||||
|
||||
@@ -15,14 +15,19 @@ namespace ytLive.ViewModels;
|
||||
public partial class MainViewModel
|
||||
{
|
||||
private void AddSource(object? parameter)
|
||||
{
|
||||
var sourceType = parameter is SourceType typed
|
||||
? typed
|
||||
: Enum.TryParse<SourceType>(parameter?.ToString(), true, out var parsed) ? parsed : SourceType.Image;
|
||||
AddSource(sourceType);
|
||||
}
|
||||
|
||||
private void AddSource(SourceType sourceType, string? mediaPath = null)
|
||||
{
|
||||
var scene = StagedScene;
|
||||
if (scene == null) return;
|
||||
PushPreviewUndo();
|
||||
|
||||
var sourceType = parameter is SourceType typed
|
||||
? typed
|
||||
: Enum.TryParse<SourceType>(parameter?.ToString(), true, out var parsed) ? parsed : SourceType.Image;
|
||||
// Privacy blur is a Live-scene tool: it exists to hide the creator's desktop, and every
|
||||
// other scene's art is authored. Rejecting here (not only in the (+) menu) keeps a stale
|
||||
// menu item or a scripted call from planting one on BRB.
|
||||
@@ -40,6 +45,7 @@ public partial class MainViewModel
|
||||
SourceType.AlertBox => "Stream Alerts",
|
||||
SourceType.Ticker => "Ticker",
|
||||
SourceType.Scoreboard => "Scoreboard",
|
||||
SourceType.MediaSource => "Video",
|
||||
_ => "Layer",
|
||||
};
|
||||
|
||||
@@ -62,6 +68,7 @@ public partial class MainViewModel
|
||||
? $"{baseName}-{webCount}"
|
||||
: NextSourceName(scene, baseName),
|
||||
Type = sourceType,
|
||||
MediaPath = mediaPath,
|
||||
X = sourceType == SourceType.TextOverlay ? 160
|
||||
: sourceType == SourceType.ChatBox ? 1400
|
||||
: sourceType == SourceType.AlertBox ? 620
|
||||
@@ -79,6 +86,7 @@ public partial class MainViewModel
|
||||
: sourceType == SourceType.AlertBox ? 680
|
||||
: sourceType == SourceType.Scoreboard ? 1920
|
||||
: sourceType == SourceType.Ticker ? 1920
|
||||
: sourceType == SourceType.MediaSource ? 1920
|
||||
: sourceType == SourceType.Blur ? 240 : 0,
|
||||
Height = sourceType == SourceType.TextOverlay ? 140
|
||||
: sourceType == SourceType.WebSource ? 480
|
||||
@@ -86,6 +94,7 @@ public partial class MainViewModel
|
||||
: sourceType == SourceType.AlertBox ? 200
|
||||
: sourceType == SourceType.Scoreboard ? 56
|
||||
: sourceType == SourceType.Ticker ? 48
|
||||
: sourceType == SourceType.MediaSource ? 1080
|
||||
: sourceType == SourceType.Blur ? 160 : 0,
|
||||
};
|
||||
|
||||
@@ -104,6 +113,9 @@ public partial class MainViewModel
|
||||
};
|
||||
}
|
||||
|
||||
if (sourceType == SourceType.MediaSource)
|
||||
RegisterMediaSource(source);
|
||||
|
||||
if (sourceType == SourceType.ChatBox)
|
||||
{
|
||||
source.PropertyChanged += (_, e) =>
|
||||
@@ -286,7 +298,18 @@ public partial class MainViewModel
|
||||
}
|
||||
if (element is Source { Type: SourceType.WebSource } webSource)
|
||||
_webView2Manager?.Unregister(webSource.Id);
|
||||
|
||||
// Media: the layer stops listening, and its decode session stops once no scene
|
||||
// references the same file + look any more (TASK 64: sessions are per path + look).
|
||||
string? mediaSessionKey = null;
|
||||
if (element is Source mediaSource && mediaSource.IsMediaSource)
|
||||
{
|
||||
mediaSessionKey = MediaSessionKey(mediaSource);
|
||||
UnregisterMediaSource(mediaSource);
|
||||
}
|
||||
|
||||
_sceneGraph.RemoveElement(scene, element);
|
||||
ReleaseMediaIfUnused(mediaSessionKey);
|
||||
|
||||
if (element is WebcamSceneConfig)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Models;
|
||||
using ytLive.Services;
|
||||
using ytLive.Services.Encoder;
|
||||
|
||||
namespace ytLive.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 33, slice 3: the session's step-down watch — policy feed, one encoder relaunch, one toast.
|
||||
///
|
||||
/// <para>Kept in its own file because it is the only place that both reads the pump's stats and acts on
|
||||
/// the session; the pure decision lives in <see cref="StepDownPolicy"/>, the sentence in
|
||||
/// <see cref="StepDownPlanner"/>.</para>
|
||||
/// </summary>
|
||||
public partial class MainViewModel
|
||||
{
|
||||
private StepDownPlanner? _stepDownPlanner;
|
||||
private (int Width, int Height, int Fps, double BitrateMbps)? _encoderTierOverride;
|
||||
private bool _stepDownBusy;
|
||||
|
||||
/// <summary>Starts the watch for this broadcast. Called once per session, before the pump starts.</summary>
|
||||
private void StartStepDownWatch()
|
||||
{
|
||||
var quality = OutputProfile.Resolve(SelectedQuality, QualityOptions, HasProOutput);
|
||||
_encoderTierOverride = null;
|
||||
_stepDownPlanner = new StepDownPlanner(
|
||||
new StepDownPolicy(quality.Width, quality.Height, quality.Fps, quality.Bitrate),
|
||||
_sessionStartedAtUtc ?? DateTime.UtcNow);
|
||||
_framePump.StatsReported += OnPumpStatsReported;
|
||||
}
|
||||
|
||||
/// <summary>Ends the watch. Called from StopStream on every path, so a stale planner can never
|
||||
/// carry a spent budget into the next broadcast.</summary>
|
||||
private void StopStepDownWatch()
|
||||
{
|
||||
_framePump.StatsReported -= OnPumpStatsReported;
|
||||
_stepDownPlanner = null;
|
||||
_encoderTierOverride = null;
|
||||
_stepDownBusy = false;
|
||||
_screenCaptureManager.ShedLoad(false); // never carry a shed cadence into the next show
|
||||
}
|
||||
|
||||
/// <summary>Runs on the PUMP thread, so it must never block: the restart it may trigger stops the
|
||||
/// very loop that raised this event. Decide here (pure and fast), act on the dispatcher.</summary>
|
||||
private void OnPumpStatsReported(object? sender, FramePumpStats stats)
|
||||
{
|
||||
if (_stepDownPlanner is not { } planner) return;
|
||||
|
||||
var decision = planner.Observe(stats, DateTime.UtcNow);
|
||||
if (!decision.Acted) return;
|
||||
|
||||
var dispatcher = Application.Current?.Dispatcher;
|
||||
if (dispatcher == null) return;
|
||||
_ = dispatcher.InvokeAsync(() => ApplyStepDownAsync(decision));
|
||||
}
|
||||
|
||||
private async void ApplyStepDownAsync(StepDownDecision decision)
|
||||
{
|
||||
var planner = _stepDownPlanner;
|
||||
if (planner == null || _stepDownBusy) return;
|
||||
|
||||
_stepDownBusy = true;
|
||||
var landed = planner.Current;
|
||||
try
|
||||
{
|
||||
if (decision.Action == StepAction.ShedCaptureCadence)
|
||||
{
|
||||
_screenCaptureManager.ShedLoad(true);
|
||||
AppLog.Write($"Capture load shed: {decision.Why}");
|
||||
return;
|
||||
}
|
||||
|
||||
_encoderTierOverride = landed;
|
||||
AppLog.Write($"Quality step-down: {decision.Why}");
|
||||
await _framePump.ChangeEncoderAsync();
|
||||
|
||||
// Show what is actually going out. The dropdown keeps the creator's choice — the policy
|
||||
// does not get to rewrite their intent, only the encoder's output.
|
||||
CurrentHealth.FPS = landed.Fps;
|
||||
CurrentHealth.CurrentBitrate = landed.BitrateMbps;
|
||||
ResolutionBadgeText = $"{landed.Width}×{landed.Height} @ {landed.Fps} fps · lowered";
|
||||
OnPropertyChanged(nameof(CurrentHealth));
|
||||
OnPropertyChanged(nameof(ResolutionBadgeText));
|
||||
|
||||
var copy = StepDownPlanner.Describe(decision, landed);
|
||||
if (copy.Length > 0)
|
||||
_notifications.Info("Quality lowered", copy);
|
||||
|
||||
AppLog.Write($"Quality step-down complete: {StepDownPlanner.ReportLine(DateTime.Now, decision)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"Quality step-down failed: {ex.Message}", AppLogMessageType.Error, AppLogErrorClass.Class2);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stepDownBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,19 +66,55 @@ public partial class MainViewModel : ViewModelBase
|
||||
_liveElapsed = TimeSpan.Zero;
|
||||
_recordLength = TimeSpan.Zero;
|
||||
ResetHealth(StreamStatus.Offline);
|
||||
_audioMixer.StartLive(EncoderOptions.DefaultAudioPipeName);
|
||||
if (!TryStartAudioPipe()) return;
|
||||
IsRecording = true;
|
||||
LiveScene = StagedScene;
|
||||
await _framePump.StartAsync();
|
||||
}
|
||||
|
||||
private void BeginGoLive(bool alsoRecord)
|
||||
/// <summary>Starts the live audio pipe, or explains why it cannot and rolls the session back.
|
||||
/// <para>This used to throw straight out of the Go Live button: the pipe server allows one instance,
|
||||
/// so with a second LlamaCasty running on the same machine the click killed the app
|
||||
/// ("All pipe instances are busy", 2026-11-06). A click must never be able to end the process.</para>
|
||||
/// </summary>
|
||||
private bool TryStartAudioPipe()
|
||||
{
|
||||
var pipeName = InstanceProfile.AudioPipeName(EncoderOptions.DefaultAudioPipeName);
|
||||
try
|
||||
{
|
||||
_audioMixer.StartLive(pipeName);
|
||||
AppLog.Write($"Audio pipe: {pipeName}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write(ex, "Audio pipe could not be started — session aborted");
|
||||
_notifications.Error("Couldn't start the audio",
|
||||
"Another copy of LlamaCasty is already using the audio pipe. Close it, then try again.");
|
||||
StopStream();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds the Start Stream dialog's model from the Stream Info tab. Re-reads the store
|
||||
/// first: the form is loaded once at startup, and a second LlamaCasty on the same profile (the dev
|
||||
/// instance, or Release recording while Debug goes live) writes its edits straight to the store, so
|
||||
/// this process's copy can be empty while the tab the creator filled in is not (2026-11-06).</summary>
|
||||
internal GoLiveViewModel CreateGoLiveDialog()
|
||||
{
|
||||
BroadcastForm.Load();
|
||||
var dialog = new GoLiveViewModel(() => SignInAsync(), _youtubeAuth.CurrentChannel)
|
||||
{
|
||||
StreamTitle = BroadcastForm.Title,
|
||||
StreamDescription = BroadcastForm.Description,
|
||||
};
|
||||
AppLog.Write($"Go Live dialog: title='{dialog.StreamTitle}' description={dialog.StreamDescription.Length} chars");
|
||||
return dialog;
|
||||
}
|
||||
|
||||
private void BeginGoLive(bool alsoRecord)
|
||||
{
|
||||
var dialog = CreateGoLiveDialog();
|
||||
var window = new ytLive.GoLiveWindow(dialog) { Owner = System.Windows.Application.Current.MainWindow };
|
||||
if (window.ShowDialog() != true) return;
|
||||
|
||||
@@ -120,10 +156,14 @@ public partial class MainViewModel : ViewModelBase
|
||||
? "LlamaCasty"
|
||||
: $"{StreamTitle} — LlamaCasty";
|
||||
StreamStatus = StreamStatus.Streaming;
|
||||
// TASK 3·20: the session report window starts here. Derived on demand from YouTube, never
|
||||
// persisted, and reset when the session ends.
|
||||
_sessionStartedAtUtc = DateTime.UtcNow;
|
||||
ResetHealth(StreamStatus.Streaming);
|
||||
_audioMixer.StartLive(EncoderOptions.DefaultAudioPipeName);
|
||||
if (!TryStartAudioPipe()) return;
|
||||
_liveElapsed = TimeSpan.Zero;
|
||||
_recordLength = TimeSpan.Zero;
|
||||
StartStepDownWatch();
|
||||
|
||||
var recordStarted = false;
|
||||
if (alsoRecord)
|
||||
@@ -147,6 +187,22 @@ public partial class MainViewModel : ViewModelBase
|
||||
/// <summary>Creates the record file (auto-named <c>ty-…-0000.mp4</c> in the record
|
||||
/// folder) and returns its path, or null when the folder can't be prepared.</summary>
|
||||
|
||||
/// <summary>TASK 32·5 — is YouTube's ingest reachable right now? A false answer aborts go-live
|
||||
/// before anything is created on YouTube: "I forgot the VPN" used to produce a broadcast that
|
||||
/// nobody ever saw, and the app looked live while the push had nowhere to go.</summary>
|
||||
internal async Task<bool> IngestPreflightAsync(string rtmpUrl)
|
||||
{
|
||||
var probe = IngestProbeOverride ?? new TcpIngestProbe();
|
||||
if (await probe.CanReachAsync(rtmpUrl)) return true;
|
||||
|
||||
AppLog.Write("Ingest unreachable — go-live aborted before creating a broadcast",
|
||||
AppLogMessageType.Error, AppLogErrorClass.Class1);
|
||||
_notifications.Error("Can't reach YouTube's ingest",
|
||||
"Nothing was created on YouTube. Check your network or VPN, then try again.");
|
||||
StopStream(); // rollback: no ghost broadcast, no half-lit session
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>One-click go-live (TASK 5): ensure the reusable stream, create a
|
||||
/// broadcast bound to it, then start the frame pump. The pump reads the RTMP
|
||||
/// URL once at startup (FramePump.StartAsync), so the stream URL must be set
|
||||
@@ -156,6 +212,13 @@ public partial class MainViewModel : ViewModelBase
|
||||
{
|
||||
try
|
||||
{
|
||||
// TASK 32·5 — prevention. With a cached ingest URL we probe BEFORE the first API call, so
|
||||
// a dead network costs nothing and leaves nothing behind on YouTube. First run (no cached
|
||||
// URL yet) probes once the stream is resolved, still before any broadcast is created.
|
||||
var cachedIngest = _reusableStreamUrl;
|
||||
if (!string.IsNullOrWhiteSpace(cachedIngest) && !await IngestPreflightAsync(cachedIngest))
|
||||
return;
|
||||
|
||||
var stream = await _youtubeStream.GetOrCreateReusableStreamAsync();
|
||||
if (stream == null)
|
||||
{
|
||||
@@ -170,6 +233,9 @@ public partial class MainViewModel : ViewModelBase
|
||||
_reusableStreamUrl = stream.RtmpUrl;
|
||||
_layoutStore.SaveReusableStream(stream);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cachedIngest) && !await IngestPreflightAsync(stream.RtmpUrl))
|
||||
return;
|
||||
|
||||
_currentBroadcastId = await _youtubeStream.CreateBroadcast(
|
||||
StreamTitle, StreamDescription, DateTime.UtcNow);
|
||||
_broadcastSeenLive = false;
|
||||
@@ -339,10 +405,14 @@ public partial class MainViewModel : ViewModelBase
|
||||
|
||||
private async void StopStream()
|
||||
{
|
||||
CancelStreamRecovery(); // a stop wins over a relaunch in flight
|
||||
StopStepDownWatch();
|
||||
RemoveAttentionAlert("stream-recovery");
|
||||
var wasLive = IsLive;
|
||||
var wasRecording = IsRecording;
|
||||
|
||||
StreamStatus = StreamStatus.Offline;
|
||||
_sessionStartedAtUtc = null;
|
||||
IsRecording = false;
|
||||
LiveScene = null;
|
||||
EditingActive = true;
|
||||
@@ -426,6 +496,11 @@ public partial class MainViewModel : ViewModelBase
|
||||
{
|
||||
var url = _rtmpUrlProvider();
|
||||
var quality = OutputProfile.Resolve(SelectedQuality, QualityOptions, HasProOutput);
|
||||
// TASK 33: while a session is live, a step-down owns the emitted tier even though the dropdown
|
||||
// still shows what the creator picked. Their intent is not edited by the policy.
|
||||
if (_encoderTierOverride is { } landed)
|
||||
quality = new QualityOption($"{landed.Width}p{landed.Fps}", landed.Fps,
|
||||
landed.BitrateMbps, landed.Width, landed.Height);
|
||||
var compositor = BuildCompositorOptions();
|
||||
return new EncoderOptions
|
||||
{
|
||||
@@ -439,6 +514,8 @@ public partial class MainViewModel : ViewModelBase
|
||||
InputHeight = compositor.OutputHeight,
|
||||
Fps = quality.Fps,
|
||||
BitrateKbps = (int)Math.Round(quality.Bitrate * 1000),
|
||||
// Same derivation as the mixer's StartLive call: a dev instance serves its own pipe.
|
||||
AudioPipeName = InstanceProfile.AudioPipeName(EncoderOptions.DefaultAudioPipeName),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ public partial class MainViewModel : ViewModelBase
|
||||
/// and the old gate needed a sign-in or a lit pill — signed-out creators found a
|
||||
/// blank bar). No dead ends: an unarmed Start records (local needs no account);
|
||||
/// sign-in lives in the Start context menu.</summary>
|
||||
public bool ShowPrimaryStartButton => IsOffline && !IsRecording;
|
||||
public bool ShowPrimaryStartButton => IsOffline && !IsRecording && !IsOffAirAfterDrop;
|
||||
|
||||
/// <summary>Either output selected makes the button actionable.</summary>
|
||||
public bool CanStartSession => RecordPillOn || OnAirPillOn;
|
||||
@@ -271,12 +271,22 @@ public partial class MainViewModel : ViewModelBase
|
||||
|
||||
/// <summary>The reality word: TEST while a test broadcast runs, LIVE while on the
|
||||
/// air, REC during a local-record session.</summary>
|
||||
public string RunningText => IsTestStream ? "TEST" : IsLive ? "LIVE" : "REC";
|
||||
public string RunningText => IsReconnecting
|
||||
? "RECONNECTING"
|
||||
: IsTestStream ? "TEST" : IsLive ? "LIVE" : "REC";
|
||||
|
||||
/// <summary>Measured facts only while reconnecting: how long, and which attempt. No countdown —
|
||||
/// YouTube's cutoff is not a constant we can promise (spec revised 2026-11-05).</summary>
|
||||
public string ReconnectDetailText => IsReconnecting
|
||||
? $"0:{ReconnectElapsedSeconds:00} · attempt {Math.Max(1, ReconnectAttempt)} of {StreamRetryPolicy.Default.Attempts}"
|
||||
: string.Empty;
|
||||
|
||||
/// <summary>Reality dot color, one meaning per mode: gold = test, red = live,
|
||||
/// green = recording. The pre-spec pulsing lamp never shipped; the word + bar
|
||||
/// color carry the state and the dot just pins it.</summary>
|
||||
public string RunningDotBrush => IsTestStream
|
||||
public string RunningDotBrush => IsReconnecting
|
||||
? ThemeBrush.Hex("Brush.Attention")
|
||||
: IsTestStream
|
||||
? ThemeBrush.Hex("Brush.TestContainer")
|
||||
: IsLive
|
||||
? ThemeBrush.Hex("Brush.Primary")
|
||||
@@ -406,6 +416,10 @@ public partial class MainViewModel : ViewModelBase
|
||||
set => SetProperty(ref _previewGlowThickness, value);
|
||||
}
|
||||
|
||||
/// <summary>When the current/last streaming session started — the window a session report covers.
|
||||
/// Null when no session has run since launch.</summary>
|
||||
private DateTime? _sessionStartedAtUtc;
|
||||
|
||||
public string LiveElapsedText
|
||||
{
|
||||
get => _liveElapsedText;
|
||||
|
||||
@@ -23,7 +23,11 @@ public partial class MainViewModel
|
||||
() => _layoutStore,
|
||||
() => ChannelStatsFactoryOverride?.Invoke() ?? new ChannelStatsService(_youtubeAuth),
|
||||
() => IsConnected,
|
||||
() => _youtubeAuth.CurrentChannel?.DisplayName);
|
||||
() => _youtubeAuth.CurrentChannel?.DisplayName,
|
||||
rewardEvents: () => new SuperChatEventService(_youtubeAuth),
|
||||
channelId: () => _youtubeAuth.CurrentChannel?.ChannelId,
|
||||
sessionStartedAtUtc: () => _sessionStartedAtUtc,
|
||||
watchMetrics: () => new YouTubeAnalyticsService(_youtubeAuth));
|
||||
|
||||
TestSession = new TestSessionViewModel(
|
||||
_youtubeStream,
|
||||
|
||||
@@ -188,6 +188,12 @@ public partial class MainViewModel : ViewModelBase
|
||||
public ICommand AddSceneCommand { get; }
|
||||
public ICommand AddSourceCommand { get; }
|
||||
public ICommand AddImageCommand { get; }
|
||||
public ICommand AddMediaCommand { get; }
|
||||
public ICommand ChangeMediaFileCommand { get; }
|
||||
/// <summary>Accepts the detector's green/blue-screen offer on a clip (TASK 64).</summary>
|
||||
public ICommand AcceptChromaSuggestionCommand { get; }
|
||||
/// <summary>Starts a finished clip again from the top.</summary>
|
||||
public ICommand ReplayMediaCommand { get; }
|
||||
public ICommand RemoveSourceCommand { get; }
|
||||
public ICommand EditElementCommand { get; }
|
||||
public ICommand ToggleElementVisibilityCommand { get; }
|
||||
@@ -220,6 +226,7 @@ public partial class MainViewModel : ViewModelBase
|
||||
ApplyStreamQuality(_selectedQuality);
|
||||
|
||||
_youtubeChat.MessageReceived += OnChatMessageReceived;
|
||||
_youtubeChat.ChatEnded += OnChatEnded;
|
||||
|
||||
_liveTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||||
_liveTimer.Tick += OnLiveTimerTick;
|
||||
@@ -260,6 +267,16 @@ public partial class MainViewModel : ViewModelBase
|
||||
AddSourceCommand = new RelayCommand(parameter => AddSource(parameter));
|
||||
AddWebcamCommand = new RelayCommand(_ => _ = AddWebcamToStagedSceneAsync());
|
||||
AddImageCommand = new RelayCommand(_ => AddImage());
|
||||
AddMediaCommand = new RelayCommand(_ => AddMedia());
|
||||
ChangeMediaFileCommand = new RelayCommand(
|
||||
element => ChangeMediaFile(element as Source),
|
||||
element => element is Source { IsMediaSource: true });
|
||||
ReplayMediaCommand = new RelayCommand(
|
||||
element => ReplayMedia(element as Source),
|
||||
element => element is Source { IsMediaSource: true });
|
||||
AcceptChromaSuggestionCommand = new RelayCommand(
|
||||
element => AcceptChromaSuggestion(element as Source),
|
||||
element => element is Source { HasChromaSuggestion: true });
|
||||
RemoveSourceCommand = new RelayCommand(element => { PushPreviewUndo(); RemoveElement(element as SceneElement); });
|
||||
EditElementCommand = new RelayCommand(element => BeginEditElement(element as SceneElement));
|
||||
ToggleElementVisibilityCommand = new RelayCommand(element => { PushPreviewUndo(); ToggleElementVisibility(element as SceneElement); });
|
||||
@@ -333,6 +350,9 @@ public partial class MainViewModel : ViewModelBase
|
||||
MicSourceName = _layoutStore.LoadMicSourceName();
|
||||
AudioSyncOffsetMs = _layoutStore.LoadAudioSyncOffsetMs();
|
||||
_zoomFollowsBox = _layoutStore.LoadZoomFollowBox();
|
||||
_autoChromaScreen = _layoutStore.LoadAutoChromaScreen();
|
||||
_steamLicenceDismissed = _layoutStore.LoadSteamLicenceIndicatorDismissed();
|
||||
RefreshSteamLicenceAlert();
|
||||
MonoOutput = _layoutStore.LoadMonoOutput(); // applied to the mixer by the setter
|
||||
_musicPlayer.UserGain = (float)Helpers.GainDb.FromDb(TraxDefaultDb); // background by default
|
||||
InitScoreboard();
|
||||
@@ -395,15 +415,25 @@ public partial class MainViewModel : ViewModelBase
|
||||
_screenCaptureManager.PreviewBitmapChanged += OnScreenPreviewBitmapChanged;
|
||||
_screenCaptureManager.CaptureFailed += OnScreenCaptureFailed;
|
||||
|
||||
_chromaProbe = ChromaProbeOverride
|
||||
?? new FfmpegChromaProbe(new FfmpegLocator(), () => new FfmpegDecodeProcess());
|
||||
|
||||
_mediaManager = new MediaVideoSourceManager(
|
||||
path => new MediaVideoSource(
|
||||
MediaFrameSourceFactoryOverride is { } overrideFactory
|
||||
? (path, _) => overrideFactory(path)
|
||||
: (path, chromaKey) => new MediaVideoSource(
|
||||
path, MediaDecodeWidth, MediaDecodeHeight,
|
||||
new FfmpegLocator(), () => new FfmpegDecodeProcess(),
|
||||
frameRateProbe: new FfmpegFrameRateProbe(
|
||||
new FfmpegLocator(), () => new FfmpegDecodeProcess())),
|
||||
System.Windows.Application.Current?.Dispatcher);
|
||||
new FfmpegLocator(), () => new FfmpegDecodeProcess()),
|
||||
chromaKey: chromaKey),
|
||||
System.Windows.Application.Current?.Dispatcher,
|
||||
// Loop intent is per Source; the manager needs the per-*path* answer.
|
||||
AnyMediaReferenceLoops);
|
||||
_mediaManager.PreviewBitmapChanged += OnMediaPreviewBitmapChanged;
|
||||
_mediaManager.MediaFailed += OnMediaFailed;
|
||||
_mediaManager.AudioAvailable += OnMediaAudioAvailable;
|
||||
_mediaManager.SessionCompleted += OnMediaSessionCompleted;
|
||||
|
||||
_chatLayer = new ChatOverlayLayer(new ChatBoxRenderer());
|
||||
_alertLayer = new AlertOverlayLayer(
|
||||
@@ -428,6 +458,7 @@ public partial class MainViewModel : ViewModelBase
|
||||
transition: _transition,
|
||||
sceneGraph: _sceneGraph);
|
||||
_framePump.Failed += OnFramePumpFailed;
|
||||
_framePump.EncoderFailed += OnEncoderFailed;
|
||||
_framePump.HealthUpdated += OnFramePumpHealthUpdated;
|
||||
|
||||
LoadLayout();
|
||||
@@ -466,6 +497,17 @@ public partial class MainViewModel : ViewModelBase
|
||||
/// real ONNX model. Mirrors <see cref="CameraFrameSourceFactoryOverride"/>.</summary>
|
||||
internal static Services.BackgroundEffects.IPersonSegmenter? PersonSegmenterOverride { get; set; }
|
||||
|
||||
/// <summary>Test seam (TASK 21): a fake media decoder so a test can prove add/release
|
||||
/// lifecycle without spawning ffmpeg. Mirrors <see cref="CameraFrameSourceFactoryOverride"/>.</summary>
|
||||
internal static Func<string, IMediaFrameSource?>? MediaFrameSourceFactoryOverride { get; set; }
|
||||
|
||||
/// <summary>Test seam (TASK 64): a fake chroma probe so tests never spawn ffmpeg to look at
|
||||
/// a clip's backdrop.</summary>
|
||||
internal static IChromaProbe? ChromaProbeOverride { get; set; }
|
||||
|
||||
/// <summary>Test seam (TASK 32·5): a fake ingest probe so tests never open a socket.</summary>
|
||||
internal static IIngestProbe? IngestProbeOverride { get; set; }
|
||||
|
||||
private void LoadLayout()
|
||||
{
|
||||
_isLoading = true;
|
||||
@@ -518,6 +560,7 @@ public partial class MainViewModel : ViewModelBase
|
||||
UpdateBackgroundImage();
|
||||
ReacquireWebcam();
|
||||
ReacquireScreenCaptures();
|
||||
ReacquireMediaSources();
|
||||
RegisterLoadedWebSources();
|
||||
_socials = _layoutStore.Socials;
|
||||
RenderSocialBarFrame();
|
||||
@@ -664,7 +707,8 @@ public partial class MainViewModel : ViewModelBase
|
||||
Source { Type: SourceType.Scoreboard } => _scoreboardPresenter?.Frame,
|
||||
Source { Type: SourceType.AlertBox } alertBox => RenderAlertBox(alertBox),
|
||||
Source { Type: SourceType.WebSource } web => _webView2Manager?.GetLatestFrame(web.Id),
|
||||
Source { IsMediaSource: true, MediaPath: not null } media => _mediaManager.GetLatestFrame(media.MediaPath),
|
||||
Source { IsMediaSource: true, MediaPath: not null } media
|
||||
=> _mediaManager.GetLatestFrame(MediaSessionKey(media)),
|
||||
Source { AssetId: not null } image => StaticPixelCache.Get(image.AssetId),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
## Price (creator ruling 2026-11-05)
|
||||
|
||||
- **Launch price $79** — one-time purchase, lifetime licence, no subscription, no account, no tracking.
|
||||
- **Promotion ends 30 days after the store page goes live** (revised 2026-11-05 — the earlier fixed date,
|
||||
April 1 2027, depended on Valve's review queue, which is outside our control); after that the price is
|
||||
**$99, locked for life**.
|
||||
- Free tier: livestream and record at **30 fps**. Paid unlocks **60 fps** for both.
|
||||
- The numbers live in `ViewModels/MainViewModel.Overlays.cs` (`LaunchPrice`, `StandardPrice`,
|
||||
`LaunchPriceEndsLabel`) so the About box, the site copy and this file cannot drift apart. Change them
|
||||
there first, then here.
|
||||
|
||||
# Commercial: pricing, entitlement, channels, support
|
||||
|
||||
The single source of truth for what LlamaCasty charges, what a licence entitles, how it ships and
|
||||
@@ -66,6 +77,11 @@ the purchase funnel. Both use the same code. The demo checks whether the current
|
||||
the paid app, then exposes the higher output tiers. The app-wide `IsAppOwned` value is the binary
|
||||
ownership result used by later feature checks.
|
||||
|
||||
- **Steamworks status (2026-11-05):** partner account created; **identity verification pending** and the
|
||||
tax interview is in Valve's queue (they quote up to **30 business days**). No app IDs are assigned and
|
||||
no store page exists yet, so the Release build still fails closed on entitlement — by design. Earliest
|
||||
realistic launch is early-to-mid February 2027; the 2027-04-01 launch-price deadline therefore has
|
||||
~7 weeks of buffer. Detail: [`Distribution.md`](../../Distribution.md) §2.
|
||||
- **Steam owns the purchase.** The demo calls `BIsSubscribedApp(paidAppId)` after `SteamAPI.Init`,
|
||||
behind `IEntitlement` (`Services/Entitlement/`). It is a local check against Steam's own state —
|
||||
no server, key, lease, or LlamaCasty account.
|
||||
|
||||
@@ -204,6 +204,19 @@ Do not build these; each was explicitly ruled out.
|
||||
- Per-source audio sync offset — global offset shipped (TASK 22); per-source is the OBS mixer
|
||||
rabbit hole and breaks the one-knob audio rule.
|
||||
- Chroma key / NVIDIA-only background removal (the bundled ONNX path is the one shipped).
|
||||
**Partly reversed 2026-11-05 (TASK 64):** a *video clip* may be keyed — green or blue, detected
|
||||
from the clip, performed by the bundled ffmpeg `colorkey`/`despill` in the decode pipe, offered
|
||||
never forced. The original objection was webcam background removal (ML model, lighting, support
|
||||
weight); none of it applies to a clip the creator supplied. The webcam still gets the shipped ONNX
|
||||
path, and NVIDIA-only effects stay out.
|
||||
- **Chat profanity filtering is YouTube's job (2026-11-05, creator ruling):** TASK 49's local wordlist is
|
||||
retired. YouTube's blocked-words filter and hold-for-review both run upstream of `liveChatMessages.list`
|
||||
(held messages are never returned: <https://stackoverflow.com/questions/74511524/>), so a local list would
|
||||
duplicate a switch the creator already owns. The rule that replaces it: **never render what YouTube has
|
||||
removed** — a deleted message arrives as a `tombstone` with no text
|
||||
(<https://developers.google.com/youtube/data/live/reference/rest/v3/liveChatMessages>) and is skipped, as are
|
||||
`hasDisplayContent:false` messages and chat-mode events. Deletion events are documented but not delivered
|
||||
(<https://stackoverflow.com/questions/44346893/>), so no client-side moderation machinery is built on them.
|
||||
- Virtual camera output — a different product and a device-driver swamp; our output is one
|
||||
YouTube stream.
|
||||
- Replay buffer, stream clipping, multi-destination restreaming, an in-app bug reporter, and an
|
||||
|
||||
@@ -139,6 +139,24 @@ save/load round trips are exact: an element removed in the UI (`RemoveElement`
|
||||
close) does **not** come back after reload (`LayoutStorePersistenceTests` guards this).
|
||||
|
||||
|
||||
## Session performance evidence
|
||||
|
||||
`python3 scripts/session-stats.py` mines every `startup*.log` (primary, rotated, and per-instance)
|
||||
into one row per FramePump session: tier, scene, measured fps, drops, stalls, average/worst render,
|
||||
capture rate — and the **sink**, which is the whole point:
|
||||
|
||||
| Sink | How it is recognised | What it proves |
|
||||
|---|---|---|
|
||||
| `RECORD` | `Recording ended` / `Recording discarded` | the machine alone — no socket |
|
||||
| `TEST` | `Test session dock open` / `Test chat simulation` | the machine + socket, no audience |
|
||||
| `LIVE` | `Broadcast created` / `Broadcast bound` | everything, network included |
|
||||
| `UNKNOWN` | no marker (crashed or paused) | nothing — investigate before quoting it |
|
||||
|
||||
Verdicts: `holds` = 0 drops, 0 stalls, average render under **half** the frame budget; `strained` =
|
||||
under the full budget; otherwise `over-budget`. Worst render is printed but never judged — it is
|
||||
dominated by one-off startup hitches. This is the evidence source for the minimum-configuration
|
||||
table in `product.md`: recordings first, because the network cannot pollute them.
|
||||
|
||||
## Persistence & external accounts (lookup)
|
||||
|
||||
- Layout: `%APPDATA%\ytLlive\ytLlive.db` (SQLite, schema v8 — scenes, sources, assets by SHA-256
|
||||
|
||||
@@ -24,6 +24,18 @@ what makes a face judder while the file looks flawless. (The "webcam renders at
|
||||
used to sit in this map was WRONG: it came from a different session and counted every newly rendered
|
||||
layer, not webcam arrivals. Corrected 2026-10-05.)
|
||||
|
||||
**Vertical-tier take (2026-11-09).** `ty-20261109-1142-036-0005.mp4`, Release, 1080×1920 @ 30 fps,
|
||||
300 s, webcam in its default bottom-right tile. Cropped the tile, downscaled to 160×88 grey and
|
||||
diffed frame to frame: **29.8 distinct images/s overall, median 30-second window 30.0/s, worst 24/s,
|
||||
one 4-frame repeat run in 9026 frames.** The app's own lines agree — `webcam 28.4–30.0/s` against
|
||||
`arrivals 29.9–30.1/s`. So the 25.6/s failure above does **not** reproduce in the vertical tier, and
|
||||
the vertical take therefore does not block the cadence units.
|
||||
|
||||
⚠️ Threshold matters. A naive `mean abs diff > 1.0` on a downscaled tile reports long "0.0/s"
|
||||
stretches during low motion — that is the measurement failing, not the camera. Duplicates encode to
|
||||
near-zero (<0.02); a still face with sensor noise sits around 0.3–0.7. Use ~0.05 and read the
|
||||
histogram before believing a count.
|
||||
|
||||
**`Helpers/FrameCadence.cs`** — one pure counter, three feeds. `Add(timestamp)` on any shared
|
||||
monotonic clock; `Summarize()` → frames, rate (gaps ÷ span, NOT frames ÷ span — N frames span N-1
|
||||
periods), gaps, hitches (default threshold 50ms ≈ 1.5× a 30fps period), longest and average gap;
|
||||
@@ -790,6 +802,28 @@ Full suite 290/291 passing, the sole failure the pre-existing compositor pixel t
|
||||
() => new FfmpegDecodeProcess())` as the probe.
|
||||
Still open: session acquisition on add/remove (UI picker) + wiring `Source.MediaIsLooping` into
|
||||
`IMediaFrameSource.Looping` (needs a manager-level per-path loop provider, comes with the picker slice).
|
||||
**Acquisition shipped 2026-11-05:** `AddMediaCommand` (`MainViewModel.Media.cs`) opens a video-filtered
|
||||
`OpenFileDialog` and `AddMediaSource(path)` adds a `MediaSource` layer through the ordinary `AddSource`
|
||||
path, defaulting to a full-canvas 1920x1080 rect, then `RegisterMediaSource` subscribes the layer and
|
||||
`EnsureMediaSession` starts one decoder per **distinct path** (`HasSession` guard keeps refcounts at 0/1).
|
||||
Remove (`RemoveElement`) unsubscribes and releases only when no scene references the file any more;
|
||||
`ReacquireMediaSources` runs after `LoadLayout` so persisted layers get sessions and stale files are
|
||||
released (`GetActiveKeys`). Loop is a manager-level per-path answer: the ctor takes
|
||||
`Func<string,bool>? loopProvider` (production: "any live media reference loops"), applied before
|
||||
`StartAsync`, and `SetLooping(key, bool)` applies a live toggle. A file swap releases the old path after
|
||||
the layer no longer references it. **Sound ships with it (2026-11-05):** both `MediaVideoSource` and
|
||||
`AlertClipDecoder` are now thin wrappers over one `Services/VideoClipPipe.cs` (video pipe + `f32le`
|
||||
audio pipe, both real-time paced, loop restarts both), so a clip is a clip. The manager applies the
|
||||
layer's Level/Mute per session and raises `AudioAvailable`, and `MainViewModel` feeds it to
|
||||
`AudioMixer.EnqueueDesktopMediaAudio` — the DESKTOP/GAME ring, so the desktop fader and the voice
|
||||
ducker apply. The alert clip keeps its own unity-gain ring (`EnqueueAlertAudio`, never ducked).
|
||||
**Green/blue screen (TASK 64)** rides the same pipe as a decode option: `VideoFilterChain.BuildVideo`
|
||||
appends `colorkey=…` + `despill=…` + `format=bgra` after the scale, so the key is computed by ffmpeg
|
||||
and both consumers (shared preview bitmap, compositor frame) carry the same alpha — no app-side
|
||||
per-pixel pass, no second render path. A media session is therefore keyed by **path + look**
|
||||
(`MainViewModel.MediaSessionKey`), so two layers with identical settings share one decoder and two
|
||||
different looks get two. The offer comes from `ChromaKeyDetector` over one probed frame
|
||||
(`FfmpegChromaProbe`); settings persist on the `Source` row.
|
||||
- **Social bar on the output (bar bug-fix branch):** the `FramePump` takes an optional
|
||||
`socialBar: Func<(VideoFrame? Frame, SocialBarPosition Position)>?` seam, re-read **every frame** (so a
|
||||
mid-stream position flip applies immediately). The strip is pre-rasterized by `Compositor/SocialBarRenderer.cs`
|
||||
|
||||
+11
-1
@@ -249,7 +249,17 @@ devices, no timers).
|
||||
(Before this wiring the seams defaulted to unity and the controls were decorative.) `StopStream` →
|
||||
`StopLive()` (closes the pipe → ffmpeg audio EOF) **BEFORE** stopping the frame pump (video EOF) —
|
||||
the reverse order stalls on pipe backpressure. `FfmpegEncoder` itself is untouched; the VM owns the
|
||||
pipe lifecycle.
|
||||
pipe lifecycle. **Recordings are fragmented MP4 (TASK 32·4, 2026-11-05):** the record block carries
|
||||
`-movflags +frag_keyframe+empty_moov+default_base_moof`, so the index is written first and a playable
|
||||
fragment is flushed at every keyframe. A plain MP4 puts its index at the end, which is why a power cut
|
||||
or a killed process previously left the whole take unreadable. The FLV stream block never gets it.
|
||||
**Two clip-audio rings join that mix (2026-11-05):** `EnqueueAlertAudio` (TASK 47) is pre-scaled by the
|
||||
alert layer and mixed at **unity, never ducked** — an alert must be heard over the mic.
|
||||
`EnqueueDesktopMediaAudio` (TASK 21's audio slice) is the opposite on purpose: a video layer's
|
||||
soundtrack joins the **desktop/game ring**, so the desktop fader and the auto-ducker apply exactly as
|
||||
they do for game audio and TRAX. Both are fed by the shared `Services/VideoClipPipe.cs`; the layer's
|
||||
own Mute/Level are applied upstream by `MediaVideoSourceManager` (level/mute are per **session**, since
|
||||
one decoder is shared per file path).
|
||||
- **Audio sync offset (TASK 22):** after the limiter, `FillAndMix` routes the whole interleaved stereo
|
||||
mix through a **`AudioSyncDelay`** (`Services/Audio/AudioSyncDelay.cs`) — a pure delay line whose
|
||||
offset comes from a `Func<int> syncOffsetMs` seam (the VM's global `AudioSyncOffsetMs`, **−500..+500
|
||||
|
||||
+10
-1
@@ -93,7 +93,16 @@ published decisions (recorded in `TASKS/task-43-native-alerts.md`):
|
||||
AND the file exists; the shipped `Assets/alert-default.mp4` is stamped into the `Asset`
|
||||
table at startup (`AlertDefaultVideoKey` setting; the prune keeps it via UNION) and
|
||||
read-at-play; any decode failure falls back to the six `AlertRenderer` animations
|
||||
(deliberate, not an error). Fades in/out via **`FadeDurationSeconds = 0.30`**
|
||||
(deliberate, not an error). **Known overlap (recorded 2026-11-05):** the video half of
|
||||
`AlertClipDecoder.RunVideoAsync` and `MediaVideoSource.RunAsync` are near-duplicates —
|
||||
same ffmpeg args (`-f rawvideo -pix_fmt bgra -vf scale=W:H -an -`), same
|
||||
`RawVideoFrameReader` feed loop, same `IFrameRateProbe` + delay pacing, both behind
|
||||
`IDecodeProcess`. Consolidated 2026-11-05 with the media audio slice: both are now thin wrappers over
|
||||
one `Services/VideoClipPipe.cs` (video pipe + `f32le` audio pipe, real-time paced, loop restarts both),
|
||||
so decode behaviour cannot drift between them again. What still differs is ownership and role: alerts
|
||||
are per-play and disposed at drain, media is a refcounted per-path session; alerts play once, media
|
||||
loops; alert audio is mixed at unity and never ducked, media audio joins the desktop/game group.
|
||||
Fades in/out via **`FadeDurationSeconds = 0.30`**
|
||||
(`AlertOverlayLayer` const): fade-in by `elapsed` on straight-alpha frame copies;
|
||||
EOF → freeze-frame → fade-out → drain (the clip branch of `Advance` **clears
|
||||
`_current` before `AdvanceToNext`** — the miss that the TASK 47 test caught). Audio
|
||||
|
||||
@@ -298,6 +298,18 @@ comments removed in Q1 2026 alone, child safety the #2 reason at 124.6M). **No f
|
||||
— chat history, moderation logs, analytics, crash payloads — may quietly break that
|
||||
assumption.** If one is ever proposed, the 11.12 position must be re-argued first.
|
||||
|
||||
### Monetization: derived, never a ledger (2026-11-05)
|
||||
|
||||
YouTube is the **sole authority** for monetization progress and qualification; the API exposes **no**
|
||||
eligibility field (`channels.list` has no monetization part; `auditDetails` needs an MCN scope). So the app
|
||||
**asks YouTube on demand** (`superChatEvents.list` for the session report; Analytics for the YPP bars in
|
||||
TASK 39·2) and **stores nothing**. That keeps the promise above literally true — there is no reward ledger
|
||||
to retain — and it means the app never has to model YouTube's moving thresholds as our own data.
|
||||
|
||||
**Money is off by default** ("Show monetary metrics", in the YPP drawer, persisted): counts are neutral,
|
||||
and a creator who never monetized is never shown a zero. Amounts are estimates that can be restated for
|
||||
weeks, and are labelled as such wherever they appear.
|
||||
|
||||
### Minors
|
||||
|
||||
The **operator is 13+ by construction**, not by promise: LlamaCasty requires a YouTube
|
||||
|
||||
@@ -1,9 +1,64 @@
|
||||
## About box (2026-11-05)
|
||||
|
||||
A conversion surface, not a credits page: **820×860 modal**, ~520 px logo, a `Pre-Release` pill that is
|
||||
itself a button (links to llamacasty.com until a Steam store page exists), the tagline
|
||||
"1-2-3, and go live to the world on YouTube!", the offer as three short blocks (free 30 fps · paid
|
||||
60 fps · one-time/lifetime/no-tracking), then the launch price and **one primary CTA**
|
||||
("Unlock 60 fps — $79"). Secondary destinations are one quiet row; the footer is `© Llama Chile Shop`.
|
||||
|
||||
**A paying customer is never sold to:** with ownership verified the price/CTA block collapses and is
|
||||
replaced by `Licence: owned via Steam — thank you.` The old tagline ("simple enough that even the most
|
||||
right-brained person can intuit it") and the "Made by gramps" line are gone for good.
|
||||
`YtButtonSecondary` carries a higher surface, a hairline border and a keyboard focus ring — before this
|
||||
the secondary buttons were the same tone as the panel behind them and read as plain text.
|
||||
|
||||
## Left panel alert stack (2026-11-05)
|
||||
|
||||
A stack of red rows at the top of the left panel, **above both mode grids** (so it shows while editing
|
||||
and while live) and pushing the panel's content down. Only red rows belong there — it is the surface for
|
||||
"something needs you", never chatter.
|
||||
|
||||
- **Rows are text only, two lines at most** — no heading line above the message (creator, 2026-11-05:
|
||||
the heading was redundant and pushed the stack past its budget).
|
||||
- **Row 1 is always the Steam licence indicator** and nothing displaces it. It reads as status, not a
|
||||
warning: `Steam ID Limit: 30fps` / `Click for More Info` (60fps once owned), both numbers derived from
|
||||
`QualityOptions` and `HasProOutput`. It shows a **pin** (standing indicator, no close control) while higher tiers are
|
||||
unavailable, and a **close control once ownership is verified** — that close is persisted
|
||||
(`Steam.LicenceIndicatorDismissed`) and permanent *while ownership holds*; losing ownership restores
|
||||
the row as pinned, because that is a change of state rather than a preference. Click → About.
|
||||
- **Event rows stack beneath it, newest first**, one row per episode (a reconnect advancing its state
|
||||
updates its own row rather than adding another). Each is dismissible. Click → the Logs tab opens with
|
||||
that event's sequence range painted red (`HighlightedLogFrom/To` + `LogInRangeConverter`; two numbers
|
||||
rather than a collection because the log list is virtualised and realised rows do not re-evaluate on
|
||||
membership changes).
|
||||
- The old red panel under the quality picker is **gone** — this stack replaced it.
|
||||
|
||||
## Preview pane — frame-source layers are a WHITELIST
|
||||
|
||||
`PreviewPane.xaml`'s per-layer `Image` is **Collapsed by default** and switched on by one DataTrigger
|
||||
per layer type that renders a frame (`IsImageSource`, `IsChatBox`, `IsAlertBox`, `IsTicker`,
|
||||
`IsScoreboard`, `IsTextOverlay`, `IsWebSource`, the webcam variants, and — since 2026-11-05 —
|
||||
`IsMediaSource` + `IsRectShape`). **A new frame-source layer type that forgets its trigger is
|
||||
invisible in the preview while its decode logs healthy.** That has now bitten the alert box
|
||||
(2026-09-26), the scoreboard, and the video layer. Add the trigger in the same commit as the layer
|
||||
type, and pin it with a test that asserts the bound `Image` is `Visible` — see
|
||||
`ytLive.Tests/MediaPreviewDisplayTests.cs`.
|
||||
|
||||
# UI surface: control room, patterns & transitions
|
||||
|
||||
The control-surface layout, scene strip, preview rail, hotkeys, broadcast drawer, toasts,
|
||||
transitions, brand logo, launch geometry, and the theme/properties-panel conventions.
|
||||
Read before changing anything the creator looks at.
|
||||
|
||||
**Frame-source layers are drawn by a WHITELIST (2026-11-05).** `PreviewPane.xaml`'s per-layer `Image`
|
||||
is `Collapsed` by default and switched on by one DataTrigger per layer type that renders a frame
|
||||
(`IsImageSource`, `IsChatBox`, `IsAlertBox`, `IsTicker`, `IsScoreboard`, `IsTextOverlay`,
|
||||
`IsWebSource`, webcam variants, and — since 2026-11-05 — `IsMediaSource` with `IsRectShape`).
|
||||
**A new frame-source layer type that forgets its trigger is invisible in the preview while the
|
||||
decode logs healthy.** This has now bitten the alert box (2026-09-26), the scoreboard, and the video
|
||||
layer, so add the trigger in the same commit as the layer type, and pin it with a test that asserts
|
||||
the bound `Image` is `Visible` (see `MediaPreviewDisplayTests`).
|
||||
|
||||
## Launch POSITION is derived, never restored (2026-10-04)
|
||||
|
||||
Creator ruling: the window must open in the **upper-left of its screen with ~75px padding**, because
|
||||
@@ -159,6 +214,12 @@ MIT — notice #10 in `THIRD-PARTY-NOTICES.txt`). Facts that cost a hunt:
|
||||
- Calls marshal to the captured Dispatcher (`_dispatcher.Invoke`) — encoder/pump events fire off-thread.
|
||||
|
||||
Migrated MessageBoxes: both webcam-acquire warnings, image-read warning, sign-in unsuccessful/failed.
|
||||
- **A toast names the cause, the culprit and the remedy (2026-11-09).** A message that reports a
|
||||
mechanism is a bug in the message: "All pipe instances are busy", an HTTP status, an ffmpeg exit
|
||||
code are all findings for the log, not for the creator. Every user-facing message says what
|
||||
happened, **whose fault it was** (the machine, the connection, or LlamaCasty itself), and what the
|
||||
app already did about it. When it is ours, say so plainly — an app that blames the creator's
|
||||
connection for its own starvation is lying, and they will believe it and go buy a new router.
|
||||
Promoted from log-only (each keeps its AppLog line): go-live prep failures ×3 (reusable stream,
|
||||
broadcast insert, prep exception), frame-pump death while live, mic-missing at startup, premium lapse,
|
||||
saved-session refresh failure (sign-out notice). Deliberately left log-only: offline license re-validation
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mine LlamaCasty's own logs for per-session performance evidence.
|
||||
|
||||
Why this exists (2026-11-09): a recording and a livestream share the entire pipeline — capture,
|
||||
compositing, one ffmpeg at the selected tier. Only the sink differs. That makes recordings the
|
||||
cleanest evidence for the machine-side minimum configuration, because the network cannot pollute
|
||||
the numbers, and livestreams the evidence for everything else.
|
||||
|
||||
Usage
|
||||
python3 scripts/session-stats.py # every log under %APPDATA%\\ytLlive
|
||||
python3 scripts/session-stats.py path/to/startup.log ...
|
||||
python3 scripts/session-stats.py --json
|
||||
|
||||
What a "session" is: from `FramePump started` (which carries the tier and scene) to the next start
|
||||
or end of file, with the sink inferred from the markers inside it:
|
||||
|
||||
Test session dock / Test chat simulation -> TEST (private broadcast, real socket)
|
||||
Broadcast created / Broadcast bound -> LIVE
|
||||
Recording ended / Recording discarded -> RECORD (both -> LIVE+RECORD)
|
||||
no marker -> UNKNOWN (crashed launch, or a paused session)
|
||||
|
||||
TEST is the one that looks like LIVE and behaves like RECORD: the full pipeline and the socket, but
|
||||
no audience and simulated chat. It is good machine evidence and useless congestion evidence.
|
||||
|
||||
`holds` is the published-minimum rule, deliberately strict: zero pump drops, zero stalls, and worst
|
||||
render under HALF the frame budget — headroom, not survivability.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from statistics import mean
|
||||
|
||||
TIER_RE = re.compile(
|
||||
r"FramePump started \((\d+)×(\d+) @ (\d+) fps\).*scene='([^']*)'")
|
||||
STATS_RE = re.compile(
|
||||
r"FramePump stats: (\d+)/(\d+) frames per (\d+)s from (\d+) renders, "
|
||||
r"avg render ([\d.]+)ms.*?avg submit ([\d.]+)ms, avg wait ([\d.]+)ms, "
|
||||
r"worst render ([\d.]+)ms, worst submit ([\d.]+)ms, dropped (\d+), stalls (\d+)")
|
||||
CAPTURE_RE = re.compile(
|
||||
r"ScreenCapture telemetry \[([^\]]+)\]: \d+ frames in [\d.]+s \(([\d.]+)/s\), "
|
||||
r"conv avg (\d+)ms max (\d+)ms")
|
||||
STAMP_RE = re.compile(r"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3})")
|
||||
BUILD_RE = re.compile(r"Build ([0-9a-f]{6,})")
|
||||
|
||||
TEST_MARKERS = ("Test session dock open", "Test chat simulation")
|
||||
LIVE_MARKERS = ("Broadcast created:", "Broadcast bound:")
|
||||
RECORD_MARKERS = ("Recording ended", "Recording discarded")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
log: str
|
||||
started: str = ""
|
||||
build: str = ""
|
||||
scene: str = ""
|
||||
width: int = 0
|
||||
height: int = 0
|
||||
fps: int = 0
|
||||
test: bool = False
|
||||
live: bool = False
|
||||
record: bool = False
|
||||
samples: int = 0
|
||||
frames: int = 0
|
||||
dropped: int = 0
|
||||
stalls: int = 0
|
||||
avg_render: float = 0.0
|
||||
worst_render: float = 0.0
|
||||
avg_submit: float = 0.0
|
||||
avg_wait: float = 0.0
|
||||
capture_rates: list[float] = field(default_factory=list)
|
||||
capture_conv: list[int] = field(default_factory=list)
|
||||
stall_events: int = 0
|
||||
|
||||
@property
|
||||
def sink(self) -> str:
|
||||
if self.test:
|
||||
return "TEST"
|
||||
if self.live and self.record:
|
||||
return "LIVE+REC"
|
||||
if self.live:
|
||||
return "LIVE"
|
||||
if self.record:
|
||||
return "RECORD"
|
||||
return "UNKNOWN"
|
||||
|
||||
@property
|
||||
def tier(self) -> str:
|
||||
return f"{self.width}x{self.height}@{self.fps}"
|
||||
|
||||
@property
|
||||
def seconds(self) -> float:
|
||||
return self.samples * 5.0
|
||||
|
||||
@property
|
||||
def measured_fps(self) -> float:
|
||||
return self.frames / self.seconds if self.seconds else 0.0
|
||||
|
||||
@property
|
||||
def verdict(self) -> str:
|
||||
# Deliberately judged on the AVERAGE: `worst render` includes one-off startup hitches
|
||||
# (100 ms while the first frame bakes) that say nothing about sustained capability.
|
||||
budget = 1000.0 / self.fps if self.fps else 0.0
|
||||
if not self.samples:
|
||||
return "no-data"
|
||||
if self.dropped or self.stalls or self.avg_render > budget:
|
||||
return "over-budget"
|
||||
if self.avg_render > budget / 2:
|
||||
return "strained"
|
||||
return "holds"
|
||||
|
||||
|
||||
def default_root() -> str:
|
||||
r"""%APPDATA%\ytLlive, including when the script is run from WSL (no APPDATA set)."""
|
||||
if os.environ.get("APPDATA"):
|
||||
return os.path.join(os.environ["APPDATA"], "ytLlive")
|
||||
# WSL / Linux: the Windows profile is mounted under /mnt/c/Users/<name>.
|
||||
candidates = sorted(glob.glob("/mnt/c/Users/*/AppData/Roaming/ytLlive"))
|
||||
if candidates:
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
return os.path.expanduser("~/AppData/Roaming/ytLlive")
|
||||
|
||||
|
||||
def default_logs() -> list[str]:
|
||||
root = default_root()
|
||||
paths = sorted(glob.glob(os.path.join(root, "startup*.log")))
|
||||
paths += sorted(glob.glob(os.path.join(root, "instances", "*", "startup*.log")))
|
||||
return paths
|
||||
|
||||
|
||||
def parse(paths: list[str]) -> list[Session]:
|
||||
sessions: list[Session] = []
|
||||
for path in paths:
|
||||
try:
|
||||
lines = open(path, encoding="utf-8", errors="ignore").read().splitlines()
|
||||
except OSError as exc:
|
||||
print(f"skip {path}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
current: Session | None = None
|
||||
build = ""
|
||||
for line in lines:
|
||||
build_match = BUILD_RE.search(line)
|
||||
if build_match:
|
||||
build = build_match.group(1)
|
||||
stamp = STAMP_RE.match(line)
|
||||
tier = TIER_RE.search(line)
|
||||
if tier:
|
||||
current = Session(
|
||||
log=os.path.basename(path),
|
||||
started=stamp.group(1) if stamp else "",
|
||||
build=build,
|
||||
width=int(tier.group(1)),
|
||||
height=int(tier.group(2)),
|
||||
fps=int(tier.group(3)),
|
||||
scene=tier.group(4),
|
||||
)
|
||||
sessions.append(current)
|
||||
continue
|
||||
if current is None:
|
||||
continue
|
||||
if "FramePump stall:" in line:
|
||||
current.stall_events += 1
|
||||
continue
|
||||
stats = STATS_RE.search(line)
|
||||
if stats:
|
||||
current.samples += 1
|
||||
current.frames += int(stats.group(1))
|
||||
current.avg_render += float(stats.group(5))
|
||||
current.avg_submit += float(stats.group(6))
|
||||
current.avg_wait += float(stats.group(7))
|
||||
current.worst_render = max(current.worst_render, float(stats.group(8)))
|
||||
current.dropped += int(stats.group(10))
|
||||
current.stalls += int(stats.group(11))
|
||||
continue
|
||||
capture = CAPTURE_RE.search(line)
|
||||
if capture:
|
||||
current.capture_rates.append(float(capture.group(2)))
|
||||
current.capture_conv.append(int(capture.group(3)))
|
||||
continue
|
||||
if any(m in line for m in TEST_MARKERS):
|
||||
current.test = True
|
||||
if any(m in line for m in LIVE_MARKERS):
|
||||
current.live = True
|
||||
if any(m in line for m in RECORD_MARKERS):
|
||||
current.record = True
|
||||
|
||||
for s in sessions:
|
||||
if s.samples:
|
||||
s.avg_render /= s.samples
|
||||
s.avg_submit /= s.samples
|
||||
s.avg_wait /= s.samples
|
||||
return [s for s in sessions if s.samples]
|
||||
|
||||
|
||||
def table(sessions: list[Session]) -> str:
|
||||
head = (f"{'started':<24}{'build':<10}{'sink':<8}{'tier':<15}{'scene':<10}{'dur':>6}"
|
||||
f"{'fps':>6}{'drop':>6}{'stalls':>7}{'avgRen':>8}{'worstRen':>10}"
|
||||
f"{'cap/s':>7}{'conv':>6} verdict")
|
||||
out = [head, "-" * len(head)]
|
||||
for s in sessions:
|
||||
cap = mean(s.capture_rates) if s.capture_rates else 0.0
|
||||
conv = mean(s.capture_conv) if s.capture_conv else 0
|
||||
out.append(
|
||||
f"{s.started:<24}{s.build[:8]:<10}{s.sink:<8}{s.tier:<15}{s.scene[:9]:<10}{s.seconds:>5.0f}s"
|
||||
f"{s.measured_fps:>6.1f}{s.dropped:>6}{s.stalls:>7}{s.avg_render:>8.1f}"
|
||||
f"{s.worst_render:>10.1f}{cap:>7.1f}{conv:>6.0f} {s.verdict}")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def summary(sessions: list[Session]) -> str:
|
||||
groups: dict[tuple[str, str], list[Session]] = {}
|
||||
for s in sessions:
|
||||
groups.setdefault((s.tier, s.sink), []).append(s)
|
||||
out = ["", f"{'tier':<16}{'sink':<9}{'sessions':>9}{'holds':>7}{'strained':>10}{'over':>6}"]
|
||||
for (tier, sink), rows in sorted(groups.items()):
|
||||
holds = sum(1 for r in rows if r.verdict == "holds")
|
||||
strained = sum(1 for r in rows if r.verdict == "strained")
|
||||
over = sum(1 for r in rows if r.verdict == "over-budget")
|
||||
out.append(f"{tier:<16}{sink:<9}{len(rows):>9}{holds:>7}{strained:>10}{over:>6}")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Per-session performance evidence from LlamaCasty logs.")
|
||||
ap.add_argument("logs", nargs="*", help="log files (default: every startup*.log under %%APPDATA%%\\ytLlive)")
|
||||
ap.add_argument("--json", action="store_true", help="machine-readable output")
|
||||
args = ap.parse_args()
|
||||
|
||||
paths = args.logs or default_logs()
|
||||
if not paths:
|
||||
print("no logs found", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
sessions = parse(paths)
|
||||
if args.json:
|
||||
print(json.dumps([asdict(s) | {"sink": s.sink, "verdict": s.verdict,
|
||||
"measured_fps": round(s.measured_fps, 2)}
|
||||
for s in sessions], indent=2))
|
||||
return 0
|
||||
|
||||
print(table(sessions))
|
||||
print(summary(sessions))
|
||||
print("\nholds = 0 drops, 0 stalls, worst render under half the frame budget. "
|
||||
"RECORD and TEST isolate the machine; LIVE adds the network and the audience.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+25
-1
@@ -10,6 +10,17 @@
|
||||
# Requires WINDOWS dotnet (never Linux dotnet — it re-downloads the windowsdesktop packs
|
||||
# over the slow 9p bridge; see docs/ai/environment.md -> Run). Reads the Windows path from the
|
||||
# WSL mount.
|
||||
#
|
||||
# Two switches, both for running this on a machine somebody is using:
|
||||
# FAST=1 skip the twelve heaviest test classes (527 tests, ~50s of test time) —
|
||||
# most of their cost is the RealApp fixture: the WPF App, its XAML resources
|
||||
# and audio/WebView2 startup, created once and charged to whichever UI test
|
||||
# runs first. Full suite: 575 tests, ~1m50s.
|
||||
# PHYSICAL_TESTS=1 include tests that drive the REAL cursor (SetCursorPos + mouse_event).
|
||||
# Excluded by default: running them hijacks the machine you are typing on.
|
||||
# (The old mouse-drag test is gone; its arithmetic is pure now — see
|
||||
# DragReorderMathTests. The switch stays for anything of that kind later.)
|
||||
# Scoped runs while working: dotnet vstest <dll> --TestCaseFilter:"FullyQualifiedName~TheClass"
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
@@ -53,7 +64,20 @@ echo "══ 3/4 TEST SUITE ══"
|
||||
TESTDLL="$ROOTWIN\\ytLive.Tests\\bin\\Debug\\net8.0-windows10.0.19041.0\\ytLive.Tests.dll"
|
||||
"$DOTNET" build "$ROOTWIN\\ytLive.Tests\\ytLive.Tests.csproj" > /dev/null
|
||||
set +e
|
||||
RUN_RAW="$("$DOTNET" vstest "$TESTDLL" 2>&1)"
|
||||
TEST_ARGS=("$TESTDLL")
|
||||
FILTER="FullyQualifiedName!~RealMouseDrag"
|
||||
if [ "${FAST:-0}" = "1" ]; then
|
||||
for slow in ZoomBoxInteractionTests TextLayerOutputTests NotificationAreaIntegrationTests \
|
||||
WebcamStartupResourceTests SocialsPreviewTests TopBarModeTests \
|
||||
TextLayerEditorPreviewTests TextLayerDropdownTests WebcamMenuGateTests \
|
||||
SceneThumbnailTests AlertTickerPreviewDisplayTests FramePumpTests; do
|
||||
FILTER="$FILTER&FullyQualifiedName!~$slow"
|
||||
done
|
||||
fi
|
||||
if [ "${PHYSICAL_TESTS:-0}" != "1" ]; then
|
||||
TEST_ARGS+=("--TestCaseFilter:$FILTER")
|
||||
fi
|
||||
RUN_RAW="$("$DOTNET" vstest "${TEST_ARGS[@]}" 2>&1)"
|
||||
TEST_EXIT=$?
|
||||
set -e
|
||||
echo "$RUN_RAW" | grep -iE "Passed!|Failed!" | tail -1
|
||||
|
||||
@@ -43,11 +43,15 @@ launch set already in `MARCOM.md`.
|
||||
| Feature | The video it earns |
|
||||
|---|---|
|
||||
| Five built scenes with art | "Your stream is built before you open the app" — the KISS thesis in 90 seconds |
|
||||
| Display / window capture with game detection | "It found my game by itself" |
|
||||
| Fullscreen-game detection on the Live background | "It found my game by itself" |
|
||||
| **Capture Window** (preview right-click → Capture Window…, or Change Capture… on the row) | "Stream one app, not your whole desktop" — and why the pick is session-scoped, not saved |
|
||||
| **Capture Desktop → display list** | "Stream your second monitor" — including the auto-switch when a game opens elsewhere |
|
||||
| Webcam placement: drag, resize, mirror, rect/round, border colour + animation | "Make your cam look intentional" |
|
||||
| Webcam background blur / removal | the most demo-able feature on the list |
|
||||
| **Privacy blur layer** (box or circle, covers everything, brand exempt) | "The moment you need to hide something" — nobody expects it |
|
||||
| Zoom magnifier (anchor or follow, Ctrl to close) | "Look at this part of my screen" |
|
||||
| **Green/blue screen removal** (chroma key, auto-detects the screen colour, opt-in suggestion in Settings) | distinguisher: "no physical green sheet" — and it works on alert clips too, because a clip is a clip |
|
||||
| **Video file layers** (add a clip; its audio joins the mixer, loops, per-layer mute + level) | "play a video inside your scene" — ending reels, trailers, countdowns |
|
||||
| **"How to Blur" — privacy blur layer** (box or circle, covers everything, brand exempt) | its own video, not a segment: "The moment you need to hide something" — nobody expects it. Webcam blur is the separate row above |
|
||||
| Zoom: left-click in preview while live, Ctrl+right-click while editing, Ctrl closes; Circle / 9:16 / 16:9 shapes, anchor or follow | "Zoom in on anything, mid-stream" |
|
||||
| Vertical 9:16 tier with locked camera + chat | "Stream Shorts-style from one app" |
|
||||
| One mic control: volume, mute, meter | the anti-mixer pitch |
|
||||
| Voice polish: bass, treble, gate, compressor | A/B demo — sells without explanation |
|
||||
@@ -57,22 +61,32 @@ launch set already in `MARCOM.md`.
|
||||
| Mono fold | accessibility, and it is the creator's own story |
|
||||
| Lip-sync offset | "fix audio drift in one slider" |
|
||||
| One-click go-live, settings auto-filled | the headline |
|
||||
| **Edit the live broadcast on air** (title, description, tags, visibility from the Stream Info drawer; same fields prefill the Go Live dialog) | "change your stream title without restarting" |
|
||||
| **Global hotkeys** (F1–F5 scenes, F6 start/stop, F7 mic, F8 desktop audio, F9 TRAX; OS-level, so they work while your game has focus) | "run the whole show from the keyboard" |
|
||||
| Layout autosave | "close the app, come back, it is where you left it" |
|
||||
| Record with no account, no sign-in | "you do not need YouTube to press record" |
|
||||
| Test stream (private, simulated chat) | "practice without an audience" |
|
||||
| **Resilience**: ingest pre-flight (dead network never creates a ghost broadcast), reconnect without ending the stream, one-click **Back on air**, crash-safe fragmented MP4 | "the network dropped and the stream came back" — proof beats a feature list |
|
||||
| Chat overlay (fonts, colours, fade, never stored) | privacy + looks |
|
||||
| Alerts: built-in clip, custom video, sound byte, ticker | "your Super Chat moment" |
|
||||
| Social bar | "your handles, validated" |
|
||||
| Scoreboard layer | session tallies, monetization-adjacent |
|
||||
| Drag/resize with undo, transitions (cut/fade/move/wipe) | polish demo |
|
||||
| Drag/resize with undo, transitions (cut/fade/wipe — **Move is still queued**, see below) | polish demo |
|
||||
| Local recording + rename on stop | "record and keep it" |
|
||||
| YPP journey tracker | the monetization-awareness hook nobody else ships |
|
||||
|
||||
**Film first:** privacy blur, auto-ducking, webcam blur. The two most demo-able, and the blur is
|
||||
unique to this app.
|
||||
**Film first:** privacy blur ("How to Blur"), auto-ducking, green/blue screen removal. Those three
|
||||
sell in twenty seconds with no narration, and no competitor ships the first or the third.
|
||||
|
||||
**This table is the running list.** Every subject the creator names — in passing, in a bug report,
|
||||
or in a support answer — gets a row here the moment it is said, even if the video is months away.
|
||||
That, not a backlog, is how the channel keeps its inventory.
|
||||
|
||||
## Features to film after the surge lands
|
||||
|
||||
Text layer · media file picking · scheduled streams · stream resilience / reconnect · bandwidth
|
||||
step-down · publish-recording · YPP slice 2 · visibility picker. Filming these early means filming
|
||||
Text layer · scheduled streams (TASK 34) · bandwidth step-down (33) · publish-recording (50) ·
|
||||
YPP slice 2 (39·2) · visibility picker at release · **Move transition** (per-layer carry-across-scenes) ·
|
||||
scene-linked audio (35). Filming these early means filming
|
||||
something that does not exist yet.
|
||||
|
||||
## Channel roles — do not blur them
|
||||
|
||||
@@ -75,6 +75,69 @@ public sealed class AboutHubTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The About box is a conversion surface (creator, 2026-11-05): a large logo, the 1-2-3 tagline,
|
||||
/// the offer, one primary CTA with the price on it — and a paying customer sees none of the price.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void About_ShowsTheOfferToFreeUsers_AndNothingToSellToOwners()
|
||||
{
|
||||
_app.Run(() =>
|
||||
{
|
||||
var tempDb = Path.Combine(Path.GetTempPath(), $"llamacasty-about-{Guid.NewGuid():N}.db");
|
||||
MainViewModel.LayoutPathOverride = tempDb;
|
||||
MainWindow? window = null;
|
||||
try
|
||||
{
|
||||
window = new MainWindow();
|
||||
var vm = (MainViewModel)window.DataContext;
|
||||
vm.EntitlementOverride = new FakeEntitlement(false, "Steam licensing is not configured in this build.");
|
||||
window.Show();
|
||||
vm.OpenAboutCommand.Execute(null);
|
||||
window.UpdateLayout();
|
||||
|
||||
var badge = FindVisualChildByName<Button>(window, "ReleaseBadgeButton");
|
||||
Assert.NotNull(badge);
|
||||
Assert.Equal("Pre-Release", badge!.Content);
|
||||
Assert.NotNull(badge.Command); // the badge links out until the Steam page exists
|
||||
|
||||
var tagline = FindVisualChildByName<TextBlock>(window, "AboutTagline");
|
||||
Assert.NotNull(tagline);
|
||||
Assert.Equal("1-2-3, and go live to the world on YouTube!", tagline!.Text);
|
||||
// The old line insulted the creator and is gone for good.
|
||||
Assert.DoesNotContain("right-brained", TextOf(window));
|
||||
|
||||
var price = FindVisualChildByName<TextBlock>(window, "AboutPriceLine");
|
||||
Assert.Equal("Launch price $79", price!.Text);
|
||||
|
||||
var cta = FindVisualChildByName<Button>(window, "UpgradeCtaButton");
|
||||
Assert.NotNull(cta);
|
||||
Assert.Equal("Unlock 60 fps — $79", cta!.Content);
|
||||
var upgradeBlock = FindVisualChildByName<StackPanel>(window, "UpgradeBlock");
|
||||
Assert.Equal(Visibility.Visible, upgradeBlock!.Visibility);
|
||||
|
||||
var copyright = FindVisualChildByName<TextBlock>(window, "AboutCopyright");
|
||||
Assert.Equal($"© {DateTime.Now.Year} Llama Chile Shop", copyright!.Text);
|
||||
Assert.DoesNotContain("Made by gramps", TextOf(window));
|
||||
|
||||
// A paying customer is never sold to.
|
||||
vm.EntitlementOverride = new FakeEntitlement(true);
|
||||
window.UpdateLayout();
|
||||
Assert.Equal(Visibility.Collapsed, FindVisualChildByName<StackPanel>(window, "UpgradeBlock")!.Visibility);
|
||||
var owned = FindVisualChildByName<TextBlock>(window, "OwnedStateText");
|
||||
Assert.Equal(Visibility.Visible, owned!.Visibility);
|
||||
Assert.Contains("owned", owned.Text, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window?.Close();
|
||||
MainViewModel.LayoutPathOverride = null;
|
||||
SqliteConnection.ClearAllPools();
|
||||
try { File.Delete(tempDb); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Free_user_gets_1080p30_and_cannot_select_or_change_to_60fps()
|
||||
{
|
||||
@@ -96,10 +159,13 @@ public sealed class AboutHubTests
|
||||
var lockedTier = vm.QualityOptions.First(option => option.Fps == 60);
|
||||
Assert.Same(freeTier, vm.SelectedQuality);
|
||||
|
||||
var errorPanel = (Border)window.FindName("EntitlementErrorPanel");
|
||||
var errorText = (TextBlock)window.FindName("EntitlementErrorText");
|
||||
Assert.Equal(Visibility.Visible, errorPanel.Visibility);
|
||||
Assert.Contains("Open Steam, sign in", errorText.Text);
|
||||
// The old red panel under the quality picker is gone (2026-11-05): the licence state
|
||||
// lives in the left panel's alert stack now, as a pinned status indicator.
|
||||
Assert.Null(window.FindName("EntitlementErrorPanel"));
|
||||
var licenceRow = vm.AttentionAlerts.Single(alert => alert.Id == "steam-licence");
|
||||
Assert.True(licenceRow.IsPinned);
|
||||
Assert.Contains("Steam ID Limit: 30fps", licenceRow.Text);
|
||||
Assert.Contains("Click for More Info", licenceRow.Text);
|
||||
|
||||
var picker = (ComboBox)window.FindName("QualityPicker");
|
||||
Assert.True(vm.CanChangeQuality);
|
||||
@@ -151,6 +217,30 @@ public sealed class AboutHubTests
|
||||
});
|
||||
}
|
||||
|
||||
private static T? FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(parent, i);
|
||||
if (child is FrameworkElement element && element.Name == name && child is T typed) return typed;
|
||||
if (FindVisualChildByName<T>(child, name) is { } found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Every TextBlock string in the tree — for asserting that removed copy is really gone.</summary>
|
||||
private static string TextOf(DependencyObject parent)
|
||||
{
|
||||
var text = new System.Text.StringBuilder();
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(parent, i);
|
||||
if (child is TextBlock block) text.Append(block.Text).Append('\n');
|
||||
text.Append(TextOf(child));
|
||||
}
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static T? FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
|
||||
|
||||
@@ -44,11 +44,13 @@ public class AlertClipDecoderTests
|
||||
await completed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.Equal(3, forwarded);
|
||||
// One pacing delay per emitted frame, each = 1/100s (the probed rate).
|
||||
Assert.Equal(forwarded, delays.Count);
|
||||
// One pacing delay per emitted frame, each AT MOST one interval: pacing targets a deadline,
|
||||
// so the frame's own work is subtracted from the wait (2026-11-05 — the old version slept a
|
||||
// full interval on top of the work, which is what made 1080p playback crawl).
|
||||
Assert.NotEmpty(delays); // the decoder paces at all
|
||||
foreach (var d in delays)
|
||||
Assert.True(Math.Abs((d - TimeSpan.FromMilliseconds(10)).TotalMilliseconds) < 0.001,
|
||||
$"expected ~10ms, got {d.TotalMilliseconds}ms");
|
||||
Assert.True(d > TimeSpan.Zero && d <= TimeSpan.FromMilliseconds(10),
|
||||
$"expected a wait of at most 10ms, got {d.TotalMilliseconds}ms");
|
||||
}
|
||||
|
||||
private sealed class FakeDecodeProcess : IDecodeProcess
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
using ytLive.Services.Entitlement;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The left panel's alert stack (creator design, 2026-11-05). Row 1 is the Steam licence indicator and
|
||||
/// nothing displaces it: pinned (no close) while higher tiers are unavailable, closable — permanently —
|
||||
/// once ownership is verified, and back as pinned if ownership is later lost.
|
||||
/// <para>Event rows stack beneath it, newest first, each dismissible, and clicking one opens the Logs
|
||||
/// tab with that event's lines painted (the range is what the row carries).</para>
|
||||
/// </summary>
|
||||
[Collection("RealApp")]
|
||||
public sealed class AttentionAlertStackTests
|
||||
{
|
||||
private readonly RealAppHost _app;
|
||||
|
||||
public AttentionAlertStackTests(RealAppHost app) => _app = app;
|
||||
|
||||
[Fact]
|
||||
public void LicenceIndicator_IsPinnedFirst_AndShowsStatusNotAPunishment()
|
||||
{
|
||||
WithVm(vm =>
|
||||
{
|
||||
// A Debug build fakes ownership; this test is about the NOT-OWNED state.
|
||||
vm.EntitlementOverride = new FakeEntitlement(false, "Steam licensing is not configured in this build.");
|
||||
|
||||
var row = Assert.Single(vm.AttentionAlerts);
|
||||
Assert.Equal("steam-licence", row.Id);
|
||||
Assert.True(row.IsPinned);
|
||||
Assert.True(row.ShowsPin);
|
||||
Assert.False(row.CanDismiss);
|
||||
Assert.Equal(AttentionAlertAction.About, row.Action);
|
||||
// Two lines at most: the heading above the message was redundant.
|
||||
Assert.DoesNotContain("\n\n", row.Text);
|
||||
|
||||
// Creator wording: the limit this build runs at, and where to find out why.
|
||||
Assert.Contains("Steam ID Limit: 30fps", row.Text);
|
||||
Assert.Contains("Click for More Info", row.Text);
|
||||
Assert.DoesNotContain("unavailable", row.Text, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OwnedLicence_MakesTheIndicatorClosable_AndTheCloseIsPermanent()
|
||||
{
|
||||
WithVm((vm, db) =>
|
||||
{
|
||||
vm.EntitlementOverride = new FakeEntitlement(true);
|
||||
|
||||
var row = Assert.Single(vm.AttentionAlerts);
|
||||
Assert.False(row.IsPinned);
|
||||
Assert.False(row.ShowsPin);
|
||||
Assert.True(row.CanDismiss);
|
||||
Assert.Contains("Steam ID Limit: 60fps", row.Text);
|
||||
|
||||
vm.DismissAlertCommand.Execute(row);
|
||||
Assert.Empty(vm.AttentionAlerts);
|
||||
|
||||
// Permanent: a fresh view-model on the same profile must not bring it back…
|
||||
var reloaded = new MainViewModel();
|
||||
Assert.DoesNotContain(reloaded.AttentionAlerts, alert => alert.Id == "steam-licence");
|
||||
|
||||
// …but losing ownership restores it as a pinned indicator: a change of state, not a preference.
|
||||
reloaded.EntitlementOverride = new FakeEntitlement(false, "Steam licensing is not configured in this build.");
|
||||
var restored = reloaded.AttentionAlerts.First(alert => alert.Id == "steam-licence");
|
||||
Assert.True(restored.IsPinned);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PinnedIndicator_CannotBeDismissed()
|
||||
{
|
||||
WithVm(vm =>
|
||||
{
|
||||
vm.EntitlementOverride = new FakeEntitlement(false, "Steam licensing is not configured in this build.");
|
||||
var row = vm.AttentionAlerts.Single();
|
||||
vm.DismissAlertCommand.Execute(row);
|
||||
Assert.Single(vm.AttentionAlerts); // still there: it is state, not an alert to clear
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventRows_StackBeneathTheIndicator_NewestFirst_AndDismissIndividually()
|
||||
{
|
||||
WithVm(vm =>
|
||||
{
|
||||
vm.EntitlementOverride = new FakeEntitlement(false, "Steam licensing is not configured in this build.");
|
||||
vm.PushAttentionAlertForTest("drop-1", "Stream dropped — reconnecting (attempt 1 of 4)", 10, 12);
|
||||
vm.PushAttentionAlertForTest("drop-2", "Stream dropped — reconnecting (attempt 2 of 4)", 13, 15);
|
||||
|
||||
Assert.Equal(new[] { "steam-licence", "drop-2", "drop-1" }, vm.AttentionAlerts.Select(a => a.Id));
|
||||
// Newest event sits directly under the indicator.
|
||||
Assert.Contains("attempt 2", vm.AttentionAlerts[1].Text);
|
||||
Assert.Contains("attempt 1", vm.AttentionAlerts[2].Text);
|
||||
|
||||
// The same event advancing updates its row instead of adding another.
|
||||
vm.PushAttentionAlertForTest("drop-2", "Stream recovered after 1.4 s", 13, 16);
|
||||
Assert.Equal(3, vm.AttentionAlerts.Count);
|
||||
Assert.Contains("recovered", vm.AttentionAlerts[1].Text);
|
||||
|
||||
vm.DismissAlertCommand.Execute(vm.AttentionAlerts[1]);
|
||||
Assert.Equal(2, vm.AttentionAlerts.Count);
|
||||
Assert.Equal("steam-licence", vm.AttentionAlerts[0].Id);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClickingAnEventRow_OpensTheLogsTab_AndHighlightsItsRange()
|
||||
{
|
||||
WithVm(vm =>
|
||||
{
|
||||
vm.PushAttentionAlertForTest("drop-1", "Stream dropped", 41, 47);
|
||||
|
||||
vm.ActivateAlertCommand.Execute(vm.AttentionAlerts[1]);
|
||||
|
||||
Assert.True(vm.IsLogsTabSelected);
|
||||
Assert.Equal(41, vm.HighlightedLogFrom);
|
||||
Assert.Equal(47, vm.HighlightedLogTo);
|
||||
});
|
||||
}
|
||||
|
||||
private void WithVm(Action<MainViewModel> body) => WithVm((vm, _) => body(vm));
|
||||
|
||||
private void WithVm(Action<MainViewModel, string> body)
|
||||
{
|
||||
_app.Run(() =>
|
||||
{
|
||||
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-alerts-{Guid.NewGuid():N}.db");
|
||||
MainViewModel.LayoutPathOverride = tempDb;
|
||||
var window = new MainWindow();
|
||||
var vm = (MainViewModel)window.DataContext;
|
||||
try
|
||||
{
|
||||
body(vm, tempDb);
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
MainViewModel.LayoutPathOverride = null;
|
||||
SqliteConnection.ClearAllPools();
|
||||
try { File.Delete(tempDb); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using Xunit;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Services.Audio;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 2026-11-06 crash: two LlamaCasty instances on one machine, the second one died on the Go Live click with
|
||||
/// <c>IOException: All pipe instances are busy</c>. The audio pipe server allows exactly ONE instance and the
|
||||
/// name was a shared constant, so this pins both halves of the fix — the collision is real, and each dev
|
||||
/// instance now gets its own name.
|
||||
/// </summary>
|
||||
public sealed class AudioPipeInstanceTests : IDisposable
|
||||
{
|
||||
private readonly string? _original = Environment.GetEnvironmentVariable(InstanceProfile.InstanceVariable);
|
||||
|
||||
public void Dispose() => Environment.SetEnvironmentVariable(InstanceProfile.InstanceVariable, _original);
|
||||
|
||||
[Fact]
|
||||
public void ASecondServerOnTheSameName_CannotStart_WhichIsWhatKilledTheSecondInstance()
|
||||
{
|
||||
var name = $"ytllive_test_{Guid.NewGuid():N}";
|
||||
using var first = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
|
||||
|
||||
var error = Record.Exception(() =>
|
||||
new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous));
|
||||
|
||||
Assert.NotNull(error);
|
||||
Assert.IsType<IOException>(error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADevInstanceServesItsOwnPipeName()
|
||||
{
|
||||
Environment.SetEnvironmentVariable(InstanceProfile.InstanceVariable, null);
|
||||
#if DEBUG
|
||||
// No claimed id (launched from the IDE) must still never collide with the Release build's pipe.
|
||||
var unnamed = InstanceProfile.AudioPipeName("ytllive_audio");
|
||||
Assert.StartsWith("ytllive_audio_pid", unnamed);
|
||||
Assert.Equal(unnamed, InstanceProfile.AudioPipeName("ytllive_audio"));
|
||||
#else
|
||||
Assert.Equal("ytllive_audio", InstanceProfile.AudioPipeName("ytllive_audio"));
|
||||
#endif
|
||||
|
||||
Environment.SetEnvironmentVariable(InstanceProfile.InstanceVariable, "2");
|
||||
Assert.Equal("ytllive_audio_2", InstanceProfile.AudioPipeName("ytllive_audio"));
|
||||
|
||||
Environment.SetEnvironmentVariable(InstanceProfile.InstanceVariable, "qa");
|
||||
Assert.Equal("ytllive_audio_qa", InstanceProfile.AudioPipeName("ytllive_audio"));
|
||||
Assert.NotEqual(InstanceProfile.AudioPipeName("ytllive_audio"),
|
||||
WithInstance("3", () => InstanceProfile.AudioPipeName("ytllive_audio")));
|
||||
}
|
||||
|
||||
private static string WithInstance(string id, Func<string> read)
|
||||
{
|
||||
var original = Environment.GetEnvironmentVariable(InstanceProfile.InstanceVariable);
|
||||
try
|
||||
{
|
||||
Environment.SetEnvironmentVariable(InstanceProfile.InstanceVariable, id);
|
||||
return read();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable(InstanceProfile.InstanceVariable, original);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheMixerRefusesAStartedSecondTime_ButAWriterOnATakenNameThrows()
|
||||
{
|
||||
// The mixer's own guard is idempotent (StartLive twice is a no-op); the exception came from the
|
||||
// pipe itself, which the VM now catches and reports instead of letting it end the process.
|
||||
var name = $"ytllive_test_{Guid.NewGuid():N}";
|
||||
var writer = new NamedPipeAudioWriter();
|
||||
writer.Start(name);
|
||||
try
|
||||
{
|
||||
var second = Record.Exception(() => new NamedPipeAudioWriter().Start(name));
|
||||
Assert.IsType<IOException>(second);
|
||||
}
|
||||
finally
|
||||
{
|
||||
writer.Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Xunit;
|
||||
using ytLive.Services;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·3 — Back on air. Once YouTube completes a broadcast it cannot be resumed, so the only honest
|
||||
/// route back is a NEW broadcast: one click, saved details, no dialog, and a title that says it is a
|
||||
/// resume (otherwise the channel grows two identically named videos).
|
||||
/// </summary>
|
||||
// Constructs a MainViewModel directly, and `LayoutPathOverride` is static: it belongs in the serialised
|
||||
// collection with the other direct-construction tests, or a parallel sibling can swap the layout path
|
||||
// underneath it (observed as a one-off failure in a full run, green in isolation).
|
||||
[Collection("MainViewModelLayoutPath")]
|
||||
public class BackOnAirTests
|
||||
{
|
||||
[Fact]
|
||||
public void ResumeTitle_MarksTheFirstReAir()
|
||||
=> Assert.Equal("Friday Night Show (resumed)", BroadcastTitle.ForResume("Friday Night Show", 1));
|
||||
|
||||
[Fact]
|
||||
public void ResumeTitle_CountsASecondDrop_InsteadOfStackingMarkers()
|
||||
=> Assert.Equal("Friday Night Show (resumed 2)", BroadcastTitle.ForResume("Friday Night Show (resumed)", 2));
|
||||
|
||||
[Fact]
|
||||
public void ResumeTitle_FitsYouTubesHundredCharacterLimit()
|
||||
{
|
||||
var longTitle = new string('x', 140);
|
||||
var resumed = BroadcastTitle.ForResume(longTitle, 1);
|
||||
|
||||
Assert.Equal(BroadcastTitle.MaxLength, resumed.Length);
|
||||
Assert.EndsWith(" (resumed)", resumed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResumeTitle_HandlesAnEmptyTitle()
|
||||
=> Assert.Equal("LlamaCasty (resumed)", BroadcastTitle.ForResume(" ", 1));
|
||||
|
||||
[Fact]
|
||||
public void AfterADrop_TheCreatorIsOfferedOneClickBackOnAir()
|
||||
{
|
||||
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-backonair-{Guid.NewGuid():N}.db");
|
||||
MainViewModel.LayoutPathOverride = tempDb;
|
||||
var vm = new MainViewModel();
|
||||
try
|
||||
{
|
||||
Assert.False(vm.IsOffAirAfterDrop);
|
||||
Assert.False(vm.BackOnAirCommand.CanExecute(null));
|
||||
|
||||
vm.MarkOffAirAfterDropForTest("Friday Night Show");
|
||||
|
||||
Assert.True(vm.IsOffAirAfterDrop);
|
||||
Assert.True(vm.BackOnAirCommand.CanExecute(null));
|
||||
Assert.Equal("● Back on air", vm.BackOnAirLabel);
|
||||
// The ordinary start button steps aside so there is exactly one way forward.
|
||||
Assert.False(vm.ShowPrimaryStartButton);
|
||||
}
|
||||
finally
|
||||
{
|
||||
MainViewModel.LayoutPathOverride = null;
|
||||
SqliteConnection.ClearAllPools();
|
||||
try { File.Delete(tempDb); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Xunit;
|
||||
using ytLive.Services;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 2026-11-06: replacing a bundled background reached new installs only. Default art is hash-keyed into the
|
||||
/// layout database on first seed, so an existing profile kept the old image for ever. A version-stamp heal
|
||||
/// failed twice (first it iterated `AllBackgrounds()`, which returns only the LIVE scene's rows; then the
|
||||
/// constant and the embedded resource were built at different moments). The seed now compares BYTES, which
|
||||
/// is what this test pins: a profile already pointing at other art is re-stamped without any version bump.
|
||||
/// </summary>
|
||||
[Collection("RealApp")]
|
||||
public sealed class BackgroundDefaultArtTests
|
||||
{
|
||||
private readonly RealAppHost _app;
|
||||
|
||||
public BackgroundDefaultArtTests(RealAppHost app) => _app = app;
|
||||
|
||||
[Fact]
|
||||
public void ReplacingTheBundledArt_ReSeedsAnExistingProfile() => _app.Run(() =>
|
||||
{
|
||||
// The bundled art is a WPF resource, so this needs a real Application to resolve the pack URI.
|
||||
var tempDb = Path.Combine(Path.GetTempPath(), $"ytLlive-art-{Guid.NewGuid():N}.db");
|
||||
MainViewModel.LayoutPathOverride = tempDb;
|
||||
try
|
||||
{
|
||||
// First launch: the seeded art is whatever ships today.
|
||||
var first = new MainViewModel();
|
||||
var firstId = StartingBackgroundId(first);
|
||||
Assert.False(string.IsNullOrWhiteSpace(firstId), "the bundled Starting art never seeded");
|
||||
var firstBytes = AssetLength(tempDb, firstId!);
|
||||
|
||||
// Simulate a profile stamped with the OLD art. No version flag is touched — the seed has to
|
||||
// notice the bytes are not the shipped ones by itself.
|
||||
using (var connection = new SqliteConnection($"Data Source={tempDb}"))
|
||||
{
|
||||
connection.Open();
|
||||
using var plant = connection.CreateCommand();
|
||||
plant.CommandText = """
|
||||
INSERT OR REPLACE INTO Asset (Id, Hash, Data, PixelWidth, PixelHeight)
|
||||
VALUES ('old-art', 'deadbeef', zeroblob(1024), 1920, 1080);
|
||||
UPDATE Source SET AssetId = 'old-art' WHERE IsBackground = 1;
|
||||
""";
|
||||
plant.ExecuteNonQuery();
|
||||
}
|
||||
SqliteConnection.ClearAllPools();
|
||||
|
||||
var second = new MainViewModel();
|
||||
var secondId = StartingBackgroundId(second);
|
||||
Assert.NotNull(secondId);
|
||||
|
||||
// Re-stamped to the SHIPPED art — which, being the same bytes, is the same asset row the
|
||||
// first launch created. What matters is that the planted "old art" is gone.
|
||||
Assert.NotEqual("old-art", secondId);
|
||||
Assert.Equal(firstId, secondId);
|
||||
Assert.Equal(File.ReadAllBytes(Path.Combine(
|
||||
AppContext.BaseDirectory, "..", "..", "..", "..", "Assets", "starting-background.jpg")).Length,
|
||||
AssetLength(tempDb, secondId!));
|
||||
Assert.NotEqual(firstBytes, 0);
|
||||
|
||||
// Idempotent: a third launch finds the shipped bytes already in place and must not re-seed.
|
||||
var third = new MainViewModel();
|
||||
Assert.Equal(secondId, StartingBackgroundId(third));
|
||||
}
|
||||
finally
|
||||
{
|
||||
MainViewModel.LayoutPathOverride = null;
|
||||
SqliteConnection.ClearAllPools();
|
||||
try { File.Delete(tempDb); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
});
|
||||
|
||||
private static string? StartingBackgroundId(MainViewModel vm)
|
||||
=> vm.Scenes
|
||||
.Where(scene => ytLive.Models.SceneCatalog.Is(scene.Name, ytLive.Models.SceneCatalog.Starting))
|
||||
.SelectMany(scene => scene.Elements.OfType<ytLive.Models.Source>())
|
||||
.FirstOrDefault(element => element.IsBackground)?.AssetId;
|
||||
|
||||
private static int AssetLength(string dbPath, string assetId)
|
||||
{
|
||||
using var connection = new SqliteConnection($"Data Source={dbPath}");
|
||||
connection.Open();
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT length(Data) FROM Asset WHERE Id = $id;";
|
||||
cmd.Parameters.AddWithValue("$id", assetId);
|
||||
return Convert.ToInt32(cmd.ExecuteScalar());
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,21 @@ public sealed class BroadcastPullOutTests
|
||||
vm.BroadcastForm.Load();
|
||||
Assert.Equal("Hello", vm.BroadcastForm.Title);
|
||||
|
||||
// Go Live must read what the STORE holds, not this process's copy. Two instances share the
|
||||
// real profile (Release recording while Debug goes live), and the other one's edits never
|
||||
// reach this process's in-memory form — that is how the creator got an empty dialog while
|
||||
// the Stream Info tab was filled in (2026-11-06).
|
||||
using (var otherInstance = new LayoutStore(tempDb))
|
||||
otherInstance.SaveBroadcastMetadata(new BroadcastMetadata
|
||||
{
|
||||
Title = "Written by the other instance",
|
||||
Description = "And its description",
|
||||
});
|
||||
|
||||
var dialog = vm.CreateGoLiveDialog();
|
||||
Assert.Equal("Written by the other instance", dialog.StreamTitle);
|
||||
Assert.Equal("And its description", dialog.StreamDescription);
|
||||
|
||||
Assert.False(vm.BroadcastForm.IsDrawerOpen);
|
||||
vm.BroadcastForm.ToggleDrawerCommand.Execute(null);
|
||||
Assert.True(vm.BroadcastForm.IsDrawerOpen);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ytLive.Services;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// TASK 32·2 — the reconnecting sign is driven by what YouTube says, not by a timer (spec revised
|
||||
/// 2026-11-05: the creator pointed out that the cutoff is not a constant, it depends on variables
|
||||
/// "some that are dark to us"). So: the chat-ended marker is a prompt to check, the broadcast status
|
||||
/// decides, and a completion ends recovery honestly.
|
||||
/// </summary>
|
||||
public class ChatEndedSignalTests
|
||||
{
|
||||
[Fact]
|
||||
public void ChatEndedEvent_IsNotAChatRow_ButItIsASignal()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"items": [
|
||||
{"id":"e1","snippet":{"type":"chatEndedEvent","publishedAt":"2026-11-05T10:00:00.000Z"}}
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
// It never becomes a message…
|
||||
Assert.Empty(YouTubeChatService.ParsePage(json).Messages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePollingService_RaisesChatEnded_ForThatMarker()
|
||||
{
|
||||
var service = new YouTubeChatService(new YouTubeAuthService("id", "secret"));
|
||||
var raised = 0;
|
||||
service.ChatEnded += () => raised++;
|
||||
|
||||
service.NotifyChatEnded();
|
||||
|
||||
Assert.Equal(1, raised);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BroadcastComplete_EndsRecovery_InsteadOfPretendingToBeLive()
|
||||
{
|
||||
var reported = new List<string>();
|
||||
var recovery = new StreamRecovery(new StreamRetryPolicy(new[] { TimeSpan.Zero }), new StreamRecoverySteps
|
||||
{
|
||||
RestartAudio = _ => Task.CompletedTask,
|
||||
StartPush = _ => Task.FromResult(true),
|
||||
CheckBroadcast = _ => Task.FromResult(BroadcastLiveness.Complete),
|
||||
Report = reported.Add,
|
||||
Log = _ => { },
|
||||
});
|
||||
|
||||
var result = await recovery.RunAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(RecoveryOutcome.BroadcastComplete, result.Outcome);
|
||||
Assert.Contains(reported, text => text.Contains("complete") && text.Contains("cannot be resumed"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System.Linq;
|
||||
using Xunit;
|
||||
using ytLive.Services;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 2026-11-05 ruling (retires TASK 49's local wordlist): YouTube owns chat moderation, so the
|
||||
/// behaviour we owe it is not a second list — it is <b>not showing what YouTube has removed</b>.
|
||||
/// The feed sends deleted messages as a <c>tombstone</c> placeholder carrying no text, and marks
|
||||
/// non-displayable events with <c>hasDisplayContent: false</c>; both used to become blank rows on
|
||||
/// the overlay (the parser had no filter at all).
|
||||
/// </summary>
|
||||
public class ChatModerationParseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Tombstone_NeverBecomesAChatRow()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"items": [
|
||||
{"id":"d1","snippet":{"type":"tombstone","liveChatId":"c","publishedAt":"2026-11-05T10:00:00.000Z"}},
|
||||
{"id":"m1","snippet":{"type":"textMessageEvent","hasDisplayContent":true,
|
||||
"textMessageDetails":{"messageText":"hello"},"publishedAt":"2026-11-05T10:00:01.000Z"},
|
||||
"authorDetails":{"displayName":"Viewer","channelId":"UC1"}}
|
||||
],
|
||||
"nextPageToken":"n"
|
||||
}
|
||||
""";
|
||||
|
||||
var page = YouTubeChatService.ParsePage(json);
|
||||
|
||||
Assert.Single(page.Messages);
|
||||
Assert.Equal("hello", page.Messages[0].Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MessagesWithoutDisplayContent_AreSkipped()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"items": [
|
||||
{"id":"m1","snippet":{"type":"textMessageEvent","hasDisplayContent":false,
|
||||
"publishedAt":"2026-11-05T10:00:00.000Z"},
|
||||
"authorDetails":{"displayName":"Muted","channelId":"UC1"}},
|
||||
{"id":"m2","snippet":{"type":"textMessageEvent","hasDisplayContent":true,
|
||||
"textMessageDetails":{"messageText":"visible"},"publishedAt":"2026-11-05T10:00:01.000Z"},
|
||||
"authorDetails":{"displayName":"Viewer","channelId":"UC2"}}
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
var page = YouTubeChatService.ParsePage(json);
|
||||
|
||||
Assert.Single(page.Messages);
|
||||
Assert.Equal("visible", page.Messages[0].Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChatModeEvents_AreNotChat()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"items": [
|
||||
{"id":"e1","snippet":{"type":"sponsorOnlyModeStartedEvent","hasDisplayContent":false,
|
||||
"publishedAt":"2026-11-05T10:00:00.000Z"}},
|
||||
{"id":"e2","snippet":{"type":"chatEndedEvent","publishedAt":"2026-11-05T10:00:01.000Z"}}
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
Assert.Empty(YouTubeChatService.ParsePage(json).Messages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RealChatStillParses_WithAuthorAndSuperChat()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"items": [
|
||||
{"id":"m1","snippet":{"type":"superChatEvent","hasDisplayContent":true,
|
||||
"superChatDetails":{"amountMicros":12340000,"currency":"USD","amountDisplayString":"$12.34",
|
||||
"userComment":"nice stream"},"publishedAt":"2026-11-05T10:00:00.000Z"},
|
||||
"authorDetails":{"displayName":"Funder","channelId":"UC9","isChatSponsor":true}}
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
var message = Assert.Single(YouTubeChatService.ParsePage(json).Messages);
|
||||
|
||||
Assert.Equal("Funder", message.AuthorName);
|
||||
Assert.True(message.IsSuperChat);
|
||||
// Constraint that survives the TASK 49 retirement: reward fields are never reinterpreted.
|
||||
Assert.Equal("$12.34", message.SuperChatDisplayString);
|
||||
Assert.Equal("nice stream", message.Message);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user