Multi-scene webcam (schema v3/v4): singleton Webcam + per-scene WebcamSceneConfig, right-click OBS-style border/context menu, persisted round-to-rect restore + legacy-square 16:9 heal, dark MenuItem template, tests (25 passing)

This commit is contained in:
2026-08-07 08:24:18 -07:00
parent f31ce9fdb7
commit e037ba027b
23 changed files with 1405 additions and 287 deletions
+233 -88
View File
@@ -23,7 +23,7 @@ public class MainViewModel : ViewModelBase
private readonly DispatcherTimer _liveTimer;
private Scene? _activeScene;
private Source? _selectedSource;
private SceneElement? _selectedElement;
private ImageSource? _activeBackgroundImage;
private bool _isConnected;
private StreamStatus _streamStatus = StreamStatus.Offline;
@@ -57,11 +57,12 @@ public class MainViewModel : ViewModelBase
private DispatcherTimer? _saveDebounce;
private bool _isLoading;
// Webcam: one camera app-wide. The single Source is tracked here so the
// Add menu can be disabled and the live preview bitmap can be forwarded.
// Webcam: one camera input app-wide. The identity (DeviceId) lives on the
// Webcam entity; each scene that shows the webcam has a WebcamSceneConfig
// (webcam.{scene}.config). CameraManager still owns the single session.
private readonly ICameraEnumerator _cameraEnumerator;
private readonly CameraManager _cameraManager;
private Source? _webcamSource;
private Webcam? _webcam;
// Branding flash (monetization): a full-frame "made with ytLlive!" shown
// for ~1s every 300s on the live output, ~25% opacity. Paid unlock sets
@@ -87,11 +88,13 @@ public class MainViewModel : ViewModelBase
if (value != null && value.IsHidden) return;
if (SetProperty(ref _activeScene, value))
{
SelectedSource = null;
SelectedElement = null;
OnPropertyChanged(nameof(ShowChatInactiveMessage));
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowPreviewPlaceholder));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
OnPropertyChanged(nameof(CanAddWebcamToActiveScene));
OnPropertyChanged(nameof(CanShowWebcamInActiveScene));
UpdateActiveBackground();
}
}
@@ -103,21 +106,31 @@ public class MainViewModel : ViewModelBase
private set => SetProperty(ref _activeBackgroundImage, value);
}
public Source? SelectedSource
public SceneElement? SelectedElement
{
get => _selectedSource;
get => _selectedElement;
set
{
if (SetProperty(ref _selectedSource, value))
if (SetProperty(ref _selectedElement, value))
OnPropertyChanged(nameof(IsWebcamSelected));
}
}
/// <summary>The Add → Webcam menu item. One webcam app-wide — once one exists it's greyed out.</summary>
public bool CanAddWebcam => _webcamSource == null;
/// <summary>The Add → Webcam menu item: enabled when the active scene doesn't show the webcam yet.</summary>
public bool CanAddWebcamToActiveScene => ActiveScene?.WebcamConfig == null;
/// <summary>
/// Right-click-on-preview → "Show Webcam": offered when the active scene has no
/// webcam config (add one) or hides it (unhide — keeps the config row).
/// </summary>
public bool CanShowWebcamInActiveScene
=> ActiveScene is { } scene && (scene.WebcamConfig == null || !scene.WebcamConfig.IsVisible);
/// <summary>Swap-the-device item: enabled once a camera has been picked at all.</summary>
public bool CanChangeWebcam => _webcam != null;
/// <summary>Shows the mirror / clip-shape row in the source chip when a webcam is selected.</summary>
public bool IsWebcamSelected => SelectedSource?.Type == SourceType.Webcam;
public bool IsWebcamSelected => SelectedElement is WebcamSceneConfig;
public StreamStatus StreamStatus
{
@@ -152,9 +165,9 @@ public class MainViewModel : ViewModelBase
public bool LiveIndicatorVisible => IsLive;
public bool ShowStartStream => IsOffline;
public bool ShowChatInactiveMessage => !IsLive;
public bool ShowEmptySceneHint => ActiveScene != null && ActiveScene.Sources.Count == 0;
public bool ShowEmptySceneHint => ActiveScene != null && ActiveScene.Elements.Count == 0;
public bool ShowPreviewPlaceholder => !ShowEmptySceneHint && ActiveBackgroundImage == null;
public bool ShowSourcesEmptyHint => ActiveScene == null || ActiveScene.Sources.Count == 0;
public bool ShowSourcesEmptyHint => ActiveScene == null || ActiveScene.Elements.Count == 0;
// Paid unlock flips this off (see ai.md "Monetization"). When disabled the
// cadence timer is stopped and any active flash is hidden immediately.
@@ -185,7 +198,7 @@ public class MainViewModel : ViewModelBase
private void UpdateActiveBackground()
{
var background = ActiveScene?.Sources.FirstOrDefault(s => s.Type == SourceType.Background);
var background = ActiveScene?.Elements.OfType<Source>().FirstOrDefault(s => s.Type == SourceType.Background);
ActiveBackgroundImage = background != null && !string.IsNullOrWhiteSpace(background.AssetId)
? ImageCache.Get(background.AssetId)
: null;
@@ -315,6 +328,44 @@ public class MainViewModel : ViewModelBase
private const double MasterFrameWidth = 1920;
private const double MasterFrameHeight = 1080;
// Webcam size safeguard: no more than half the frame in any dimension
// (960x540 over the 1920x1080 master), and no less than 10% of it
// (192x108). Enforced at resize and on layout load.
public const double WebcamMaxWidth = 960;
public const double WebcamMaxHeight = 540;
public const double WebcamMinWidth = MasterFrameWidth * 0.1;
public const double WebcamMinHeight = MasterFrameHeight * 0.1;
internal static void ClampWebcamToBounds(WebcamSceneConfig config)
{
var scale = Math.Min(WebcamMaxWidth / config.Width, WebcamMaxHeight / config.Height);
if (scale < 1)
{
config.Width = Math.Round(config.Width * scale);
config.Height = Math.Round(config.Height * scale);
return;
}
var minScale = Math.Max(WebcamMinWidth / config.Width, WebcamMinHeight / config.Height);
if (minScale > 1)
{
config.Width = Math.Round(config.Width * minScale);
config.Height = Math.Round(config.Height * minScale);
}
}
// One-time heal for layouts saved before the rect dims were persisted (v3→v4):
// a Traditional webcam that ended up square (Round resize then reload lost the
// pre-Round rect) gets widened to 16:9, keeping the height. Round is skipped —
// a square bounding box is correct there — and an explicit pre-Round rect wins.
internal static void HealLegacySquareRect(WebcamSceneConfig config)
{
if (config.ClipShape != ClipShape.Traditional) return;
if (config.RectWidth != null || config.RectHeight != null) return;
if (Math.Abs(config.Width - config.Height) >= 1) return;
config.Width = Math.Round(config.Height * 16.0 / 9.0);
}
public QualityOption[] QualityOptions { get; } =
{
new("1080p60", 60, 8.0, 1920, 1080),
@@ -419,6 +470,8 @@ public class MainViewModel : ViewModelBase
public ICommand AddSourceCommand { get; }
public ICommand AddImageCommand { get; }
public ICommand RemoveSourceCommand { get; }
public ICommand ChangeWebcamCommand { get; }
public ICommand ShowWebcamCommand { get; }
public ICommand StartStreamCommand { get; }
public ICommand EndStreamCommand { get; }
public ICommand OpenSettingsCommand { get; }
@@ -466,7 +519,9 @@ public class MainViewModel : ViewModelBase
ToggleSceneVisibilityCommand = new RelayCommand(scene => ToggleSceneVisibility(scene as Scene));
AddSourceCommand = new RelayCommand(type => AddSource(type as string));
AddImageCommand = new RelayCommand(_ => AddImage());
RemoveSourceCommand = new RelayCommand(source => RemoveSource(source as Source));
RemoveSourceCommand = new RelayCommand(element => RemoveElement(element as SceneElement));
ChangeWebcamCommand = new RelayCommand(_ => _ = ChangeWebcamAsync(), _ => CanChangeWebcam);
ShowWebcamCommand = new RelayCommand(_ => ShowWebcamInActiveScene(), _ => CanShowWebcamInActiveScene);
OpenSettingsCommand = new RelayCommand(_ => ShowOverlay(nameof(IsSettingsOpen), "App Settings"));
OpenBugCommand = new RelayCommand(_ => ShowOverlay(nameof(IsBugOpen), "Report Bug"));
OpenFeatureCommand = new RelayCommand(_ => ShowOverlay(nameof(IsFeatureOpen), "Feature Request"));
@@ -555,6 +610,12 @@ public class MainViewModel : ViewModelBase
AddScene("Chat", isChatScene: true);
AddScene("Ending");
}
foreach (var scene in Scenes)
foreach (var config in scene.Elements.OfType<WebcamSceneConfig>())
{
ClampWebcamToBounds(config);
HealLegacySquareRect(config);
}
AppLog.Write($"LoadLayout: {Scenes.Count} scenes loaded");
}
finally
@@ -568,29 +629,35 @@ public class MainViewModel : ViewModelBase
AppLog.Write("LoadLayout end");
}
// Finds the persisted webcam source (at most one app-wide) and re-acquires
// its camera after a layout load / file open. Releasing the previous session
// unconditionally keeps the refcount honest even when the device is unchanged.
// After a layout load / file open: re-point the webcam identity, stop the
// previous device if it changed, and acquire the current one once per scene
// that uses it (CameraManager refcounts by DeviceId — one camera session).
private void ReacquireWebcam()
{
var webcam = Scenes.SelectMany(s => s.Sources).FirstOrDefault(s => s.Type == SourceType.Webcam);
if (ReferenceEquals(_webcamSource, webcam)) return;
var previousDevice = _webcam?.DeviceId;
_webcam = _layoutStore.Webcam;
var newDevice = _webcam?.DeviceId;
if (_webcamSource != null && !string.IsNullOrWhiteSpace(_webcamSource.DeviceId))
_ = _cameraManager.ReleaseAsync(_webcamSource.DeviceId);
if (!string.IsNullOrWhiteSpace(previousDevice) && previousDevice != newDevice)
_ = _cameraManager.ReleaseAllAsync(previousDevice);
_webcamSource = webcam;
OnPropertyChanged(nameof(CanAddWebcam));
if (webcam != null && !string.IsNullOrWhiteSpace(webcam.DeviceId))
_ = _cameraManager.AcquireAsync(webcam.DeviceId);
OnPropertyChanged(nameof(CanChangeWebcam));
OnPropertyChanged(nameof(CanAddWebcamToActiveScene));
if (_webcam == null || string.IsNullOrWhiteSpace(newDevice)) return;
if (previousDevice == newDevice) return;
foreach (var unused in Scenes.SelectMany(s => s.Elements.OfType<WebcamSceneConfig>()))
_ = _cameraManager.AcquireAsync(newDevice);
}
// CameraManager creates the shared WriteableBitmap on the UI thread at the
// device's frame size; the webcam Source's preview picks it up from here.
// device's frame size; every scene's webcam config picks it up from here.
private void OnCameraPreviewBitmapChanged(string deviceId, WriteableBitmap bitmap)
{
if (_webcamSource?.DeviceId == deviceId)
_webcamSource.VideoImageSource = bitmap;
if (_webcam?.DeviceId != deviceId) return;
foreach (var scene in Scenes)
foreach (var config in scene.Elements.OfType<WebcamSceneConfig>())
config.VideoImageSource = bitmap;
}
public void Shutdown()
@@ -606,7 +673,7 @@ public class MainViewModel : ViewModelBase
_saveDebounce?.Stop();
try
{
_layoutStore.Save(Scenes);
_layoutStore.Save(Scenes, _webcam);
}
catch (Exception ex)
{
@@ -661,31 +728,36 @@ public class MainViewModel : ViewModelBase
private void WireScene(Scene scene)
{
scene.PropertyChanged += OnScenePropertyChanged;
scene.Sources.CollectionChanged += OnSourcesChanged;
scene.Elements.CollectionChanged += OnElementsChanged;
}
private void UnwireScene(Scene scene)
{
scene.PropertyChanged -= OnScenePropertyChanged;
scene.Sources.CollectionChanged -= OnSourcesChanged;
scene.Elements.CollectionChanged -= OnElementsChanged;
}
private void OnScenePropertyChanged(object? sender, PropertyChangedEventArgs e)
=> ScheduleSave();
private void OnSourcesChanged(object? sender, NotifyCollectionChangedEventArgs e)
private void OnElementsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (Source source in e.NewItems)
source.PropertyChanged += OnSourcePropertyChanged;
foreach (SceneElement element in e.NewItems)
element.PropertyChanged += OnElementPropertyChanged;
if (e.OldItems != null)
foreach (Source source in e.OldItems)
source.PropertyChanged -= OnSourcePropertyChanged;
foreach (SceneElement element in e.OldItems)
element.PropertyChanged -= OnElementPropertyChanged;
OnPropertyChanged(nameof(CanAddWebcamToActiveScene));
ScheduleSave();
}
private void OnSourcePropertyChanged(object? sender, PropertyChangedEventArgs e)
=> ScheduleSave();
private void OnElementPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (sender is WebcamSceneConfig && e.PropertyName == nameof(SceneElement.IsVisible))
OnPropertyChanged(nameof(CanShowWebcamInActiveScene));
ScheduleSave();
}
private void ScheduleSave()
{
@@ -728,9 +800,14 @@ public class MainViewModel : ViewModelBase
var scene = ActiveScene;
if (scene == null) return;
if (string.Equals(type, "webcam", StringComparison.OrdinalIgnoreCase))
{
_ = AddWebcamToActiveSceneAsync();
return;
}
var sourceType = type?.ToLowerInvariant() switch
{
"webcam" => SourceType.Webcam,
"screen" => SourceType.DisplayCapture,
"window" => SourceType.WindowCapture,
"background" => SourceType.Background,
@@ -739,7 +816,6 @@ public class MainViewModel : ViewModelBase
};
var baseName = sourceType switch
{
SourceType.Webcam => "Webcam",
SourceType.DisplayCapture => "Screen",
SourceType.WindowCapture => "Window",
SourceType.Background => "Background",
@@ -748,12 +824,6 @@ public class MainViewModel : ViewModelBase
_ => "Source",
};
if (sourceType == SourceType.Webcam)
{
_ = AddWebcamSourceAsync();
return;
}
if (sourceType == SourceType.Background)
{
var bytes = PickImageBytes("Choose a backdrop image");
@@ -761,7 +831,7 @@ public class MainViewModel : ViewModelBase
var assetId = AddAsset(bytes);
if (assetId == null) return;
var existing = scene.Sources.FirstOrDefault(s => s.Type == SourceType.Background);
var existing = scene.Elements.OfType<Source>().FirstOrDefault(s => s.Type == SourceType.Background);
if (existing != null)
{
existing.AssetId = assetId;
@@ -769,26 +839,73 @@ public class MainViewModel : ViewModelBase
return;
}
scene.Sources.Add(new Source { Name = baseName, Type = SourceType.Background, AssetId = assetId });
scene.Elements.Add(new Source { Name = baseName, Type = SourceType.Background, AssetId = assetId });
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
UpdateActiveBackground();
return;
}
var count = scene.Sources.Count(s => s.Type == sourceType);
var count = scene.Elements.OfType<Source>().Count(s => s.Type == sourceType);
var name = count == 0 ? baseName : $"{baseName} {count + 1}";
scene.Sources.Add(new Source { Name = name, Type = sourceType });
scene.Elements.Add(new Source { Name = name, Type = sourceType });
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
UpdateActiveBackground();
}
private async Task AddWebcamSourceAsync()
// Adds the webcam to the active scene. The camera is picked once app-wide
// (first add); afterwards "Add Webcam" just places the existing webcam here
// at the default spot — each scene's config is independent (webcam.{scene}.config).
private async Task AddWebcamToActiveSceneAsync()
{
var scene = ActiveScene;
if (scene == null || _webcamSource != null) return;
if (scene == null || scene.WebcamConfig != null) return;
if (_webcam == null)
{
var dialog = new CameraPickerDialog(new CameraPickerViewModel(_cameraEnumerator))
{
Owner = Application.Current.MainWindow
};
if (dialog.ShowDialog() != true || dialog.PickedDevice == null) return;
var device = dialog.PickedDevice;
_webcam = new Webcam { DeviceId = device.Id, Name = device.DisplayName };
OnPropertyChanged(nameof(CanChangeWebcam));
}
var config = new WebcamSceneConfig
{
WebcamId = _webcam.Id,
Name = _webcam.Name,
Width = 480,
Height = 270,
X = MasterFrameWidth - 480 - 32,
Y = MasterFrameHeight - 270 - 32,
};
scene.Elements.Add(config);
SelectedElement = config;
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
UpdateActiveBackground();
var started = await _cameraManager.AcquireAsync(_webcam.DeviceId);
if (!started)
{
MessageBox.Show(
"Couldn't start that camera. It may be in use by another app, or Windows camera access may be turned off.",
"ytLlive", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
// Swaps the device on the app-wide webcam identity. The old device is stopped
// unconditionally; each scene that uses the webcam re-acquires the new one so
// the per-config refcount stays honest.
private async Task ChangeWebcamAsync()
{
if (_webcam == null) return;
var dialog = new CameraPickerDialog(new CameraPickerViewModel(_cameraEnumerator))
{
@@ -796,35 +913,49 @@ public class MainViewModel : ViewModelBase
};
if (dialog.ShowDialog() != true || dialog.PickedDevice == null) return;
var device = dialog.PickedDevice;
var source = new Source
{
Name = "Webcam",
Type = SourceType.Webcam,
DeviceId = device.Id,
Width = 480,
Height = 270,
X = 1920 - 480 - 32,
Y = 1080 - 270 - 32,
};
var oldDevice = _webcam.DeviceId;
var newDevice = dialog.PickedDevice.Id;
if (oldDevice == newDevice) return;
_webcamSource = source;
OnPropertyChanged(nameof(CanAddWebcam));
scene.Sources.Add(source);
SelectedSource = source;
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
UpdateActiveBackground();
_webcam.DeviceId = newDevice;
_webcam.Name = dialog.PickedDevice.DisplayName;
ScheduleSave();
var started = await _cameraManager.AcquireAsync(device.Id);
if (!started)
if (!string.IsNullOrWhiteSpace(oldDevice))
await _cameraManager.ReleaseAllAsync(oldDevice);
foreach (var unused in Scenes.SelectMany(s => s.Elements.OfType<WebcamSceneConfig>()))
{
MessageBox.Show(
"Couldn't start that camera. It may be in use by another app, or Windows camera access may be turned off.",
"ytLlive", MessageBoxButton.OK, MessageBoxImage.Warning);
var started = await _cameraManager.AcquireAsync(newDevice);
if (!started)
{
MessageBox.Show(
"Couldn't start that camera. It may be in use by another app, or Windows camera access may be turned off.",
"ytLlive", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
}
}
// "Show Webcam" from a right-click on the empty preview. Unhides this scene's
// existing (hidden) config — the config row survives Hide in this scene — or
// adds the webcam here for the first time (which opens the camera picker).
private void ShowWebcamInActiveScene()
{
var scene = ActiveScene;
if (scene == null) return;
var config = scene.WebcamConfig;
if (config != null)
{
config.IsVisible = true;
SelectedElement = config;
return;
}
_ = AddWebcamToActiveSceneAsync();
}
private void AddImage()
{
var scene = ActiveScene;
@@ -859,7 +990,7 @@ public class MainViewModel : ViewModelBase
{
var candidates = new List<ReuseImageCandidate>();
foreach (var scene in Scenes)
foreach (var source in scene.Sources.Where(s => s.Type == SourceType.Image && !string.IsNullOrWhiteSpace(s.AssetId)))
foreach (var source in scene.Elements.OfType<Source>().Where(s => s.Type == SourceType.Image && !string.IsNullOrWhiteSpace(s.AssetId)))
{
candidates.Add(new ReuseImageCandidate
{
@@ -919,7 +1050,7 @@ public class MainViewModel : ViewModelBase
var scene = ActiveScene;
if (scene == null || string.IsNullOrWhiteSpace(assetId)) return;
var count = scene.Sources.Count(s => s.Type == SourceType.Image);
var count = scene.Elements.OfType<Source>().Count(s => s.Type == SourceType.Image);
var name = count == 0 ? "Image" : $"Image {count + 1}";
var source = new Source { Name = name, Type = SourceType.Image, AssetId = assetId };
@@ -934,25 +1065,39 @@ public class MainViewModel : ViewModelBase
source.Y = (1080 - source.Height) / 2;
}
scene.Sources.Add(source);
SelectedSource = source;
scene.Elements.Add(source);
SelectedElement = source;
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
UpdateActiveBackground();
}
private void RemoveSource(Source? source)
// Removes an element from the active scene. For a webcam config this drops the
// scene's usage and releases one camera reference (CameraManager stops the
// session when the last using scene lets go). When the last config anywhere is
// removed, the webcam identity is cleared too — re-adding opens the picker
// again instead of silently resurrecting the old camera.
private void RemoveElement(SceneElement? element)
{
var scene = ActiveScene;
if (scene == null || source == null) return;
if (source.Type == SourceType.Webcam && ReferenceEquals(source, _webcamSource))
if (scene == null || element == null) return;
if (element is WebcamSceneConfig && _webcam != null)
{
_webcamSource = null;
OnPropertyChanged(nameof(CanAddWebcam));
if (!string.IsNullOrWhiteSpace(source.DeviceId))
_ = _cameraManager.ReleaseAsync(source.DeviceId);
if (SelectedElement == element)
SelectedElement = null;
_ = _cameraManager.ReleaseAsync(_webcam.DeviceId);
}
scene.Sources.Remove(source);
scene.Elements.Remove(element);
if (element is WebcamSceneConfig && _webcam != null
&& !Scenes.Any(s => s.Elements.OfType<WebcamSceneConfig>().Any()))
{
_webcam = null;
OnPropertyChanged(nameof(CanChangeWebcam));
OnPropertyChanged(nameof(CanAddWebcamToActiveScene));
OnPropertyChanged(nameof(CanShowWebcamInActiveScene));
}
OnPropertyChanged(nameof(ShowEmptySceneHint));
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
UpdateActiveBackground();