commit ea45bef2978e116e499d64ad295ea06d37dc95ae Author: Alexander Shabarshov Date: Sat Jul 4 12:20:15 2026 +0100 Add project files. diff --git a/.copilot/copilot-instructions.md b/.copilot/copilot-instructions.md new file mode 100644 index 0000000..1ded924 --- /dev/null +++ b/.copilot/copilot-instructions.md @@ -0,0 +1,31 @@ +You are c# programmer. I'm senior c# programmer with 30+ years of experience. +Do not be overconfident about your answers - they are 70% incorrect. +Do not say "final solution". Do not start every reply with my name. +Do not use emoji or non-ascii symbols. Do not explain "why it work". + +I'm developing ffmpeg-based audio player for music students. + +Features: + + * Play/Stop/Pause/FF/FB + * Source track separation to "drums", "bass", "other", "vocals", "guitar", "piano" + * Audio mixer for stems with on/off switch, gain and pane controls + * Change playback speed without changing pitch + * A-B loop repeat with multiple segments + * Wave form visualisation on the playback position indicator + +Rules: + + * Very latest everything: .NET 10, C# language features, all nuget packages + * Use Microsoft DI for resolving implementations. + * Absolutely no per-frame allocations. Use `AudioBufferPool` to "borrow" buffers. + +Architecture: + + * AudioCore - all data processing algorithms. Namespaces: + * AudioCore.Models - data models + * AudioCore.Interfaces - all public interfaces + * AudioCore.Impl - implementations + * AudioCore_Tests - unit tests using MSTest + * ABStemPlayer - Avalonia 12 UI. Namespace: ABStemPlayer + diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c995d8e --- /dev/null +++ b/.gitignore @@ -0,0 +1,366 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +*.patch +*.onnx diff --git a/ABStemPlayer.slnx b/ABStemPlayer.slnx new file mode 100644 index 0000000..040e449 --- /dev/null +++ b/ABStemPlayer.slnx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/ABStemPlayer/ABStemPlayer.csproj b/ABStemPlayer/ABStemPlayer.csproj new file mode 100644 index 0000000..1da5771 --- /dev/null +++ b/ABStemPlayer/ABStemPlayer.csproj @@ -0,0 +1,31 @@ + + + WinExe + net10.0 + enable + app.manifest + true + + + + + + + + + + + + + + + None + All + + + + + + + + diff --git a/ABStemPlayer/App.axaml b/ABStemPlayer/App.axaml new file mode 100644 index 0000000..12924f9 --- /dev/null +++ b/ABStemPlayer/App.axaml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/ABStemPlayer/App.axaml.cs b/ABStemPlayer/App.axaml.cs new file mode 100644 index 0000000..993798d --- /dev/null +++ b/ABStemPlayer/App.axaml.cs @@ -0,0 +1,38 @@ +using ABStemPlayer.Views; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using Microsoft.Extensions.DependencyInjection; + +namespace ABStemPlayer; + +public partial class App : Application +{ + private readonly ServiceProvider _provider = null!; + + public App() { } + + public App(ServiceProvider provider) + { + _provider = provider; + } + + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + var vm = _provider.GetRequiredService(); + + desktop.MainWindow = new MainWindow + { + DataContext = vm + }; + } + + base.OnFrameworkInitializationCompleted(); + } +} \ No newline at end of file diff --git a/ABStemPlayer/Assets/avalonia-logo.ico b/ABStemPlayer/Assets/avalonia-logo.ico new file mode 100644 index 0000000..f7da8bb Binary files /dev/null and b/ABStemPlayer/Assets/avalonia-logo.ico differ diff --git a/ABStemPlayer/Converters/BoolInvertConverter.cs b/ABStemPlayer/Converters/BoolInvertConverter.cs new file mode 100644 index 0000000..fe7dedf --- /dev/null +++ b/ABStemPlayer/Converters/BoolInvertConverter.cs @@ -0,0 +1,15 @@ +using System.Globalization; +using Avalonia.Data.Converters; + +namespace ABStemPlayer.Converters; + +public sealed class BoolInvertConverter : IValueConverter +{ + public static BoolInvertConverter Instance { get; } = new(); + + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) + => value is bool b ? !b : value; + + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + => value is bool b ? !b : value; +} diff --git a/ABStemPlayer/Converters/StemTypeToNameConverter.cs b/ABStemPlayer/Converters/StemTypeToNameConverter.cs new file mode 100644 index 0000000..98820dc --- /dev/null +++ b/ABStemPlayer/Converters/StemTypeToNameConverter.cs @@ -0,0 +1,30 @@ +using Avalonia.Data.Converters; +using System.Globalization; + +namespace ABStemPlayer.Converters +{ + public sealed class StemTypeToNameConverter : IValueConverter + { + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) + { + if (value is StemType type) + { + return type switch + { + StemType.Drums => "Drums", + StemType.Bass => "Bass", + StemType.Vocals => "Vocals", + StemType.Guitar => "Guitar", + StemType.Piano => "Piano", + StemType.Other => "Other", + _ => type.ToString() + }; + } + + return null; + } + + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + => throw new NotSupportedException(); + } +} diff --git a/ABStemPlayer/Converters/TimeSpanToStringConverter.cs b/ABStemPlayer/Converters/TimeSpanToStringConverter.cs new file mode 100644 index 0000000..58b07d8 --- /dev/null +++ b/ABStemPlayer/Converters/TimeSpanToStringConverter.cs @@ -0,0 +1,21 @@ +using Avalonia.Data.Converters; +using System.Globalization; + +namespace ABStemPlayer.Converters +{ + public sealed class TimeSpanToStringConverter : IValueConverter + { + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) + { + if (value is TimeSpan time) + { + return time.ToString("mm\\:ss"); + } + + return null; + } + + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + => throw new NotSupportedException(); + } +} diff --git a/ABStemPlayer/GlobalUsings.cs b/ABStemPlayer/GlobalUsings.cs new file mode 100644 index 0000000..336cbeb --- /dev/null +++ b/ABStemPlayer/GlobalUsings.cs @@ -0,0 +1,8 @@ +global using AudioCore; +global using AudioCore.Interfaces; +global using AudioCore.Models; +global using ABStemPlayer.ViewModels; +global using Avalonia; +global using CommunityToolkit.Mvvm.ComponentModel; + + diff --git a/ABStemPlayer/Program.cs b/ABStemPlayer/Program.cs new file mode 100644 index 0000000..5bbd0c0 --- /dev/null +++ b/ABStemPlayer/Program.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace ABStemPlayer; + +internal sealed class Program +{ + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) => BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + { + var services = ConfigureServices(); + var provider = services.BuildServiceProvider(); + + return AppBuilder.Configure(() => new App(provider)) + .UsePlatformDetect() +#if DEBUG + .WithDeveloperTools() +#endif + .WithInterFont() + .LogToTrace(); + } + + private static ServiceCollection ConfigureServices() + { + var services = new ServiceCollection(); + + services.AddAudioCore(); + + // View models + services.AddSingleton(); + + services.AddSingleton(); + + services.AddSingleton(); + return services; + } +} diff --git a/ABStemPlayer/ViewModels/MainWindowViewModel.cs b/ABStemPlayer/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..8cbdd14 --- /dev/null +++ b/ABStemPlayer/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,19 @@ +using System.Collections.ObjectModel; + +namespace ABStemPlayer.ViewModels; + +public sealed class MainWindowViewModel +{ + public PlaybackViewModel Playback { get; } + public MixerViewModel Mixer { get; } + public ObservableCollection Bands => Playback.Bands; + + public MainWindowViewModel( + PlaybackViewModel playback, + MixerViewModel mixer) + { + Playback = playback; + Mixer = mixer; + Playback.Mixer = mixer; + } +} diff --git a/ABStemPlayer/ViewModels/MixerViewModel.cs b/ABStemPlayer/ViewModels/MixerViewModel.cs new file mode 100644 index 0000000..984ab16 --- /dev/null +++ b/ABStemPlayer/ViewModels/MixerViewModel.cs @@ -0,0 +1,17 @@ +using System.Collections.ObjectModel; + +namespace ABStemPlayer.ViewModels; + +public sealed class MixerViewModel +{ + public ObservableCollection Stems { get; } = new(); + + public MixerViewModel() + { + foreach (var type in Enum.GetValues()) + { + Stems.Add(new StemChannelViewModel(type)); + } + } + +} diff --git a/ABStemPlayer/ViewModels/PlaybackViewModel.cs b/ABStemPlayer/ViewModels/PlaybackViewModel.cs new file mode 100644 index 0000000..33bf515 --- /dev/null +++ b/ABStemPlayer/ViewModels/PlaybackViewModel.cs @@ -0,0 +1,409 @@ +using System.Collections.ObjectModel; +using System.Windows.Input; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Platform.Storage; +using CommunityToolkit.Mvvm.Input; + +namespace ABStemPlayer.ViewModels; + +public sealed partial class PlaybackViewModel : ObservableObject +{ + private readonly IStemPlaybackEngine _engine; + private readonly IStemSeparator _separator; + private readonly IStemDecoderFactory _decoderFactory; + private readonly IStemWaveformService _waveformService; + + // ----------------------------- + // Conversion mode properties + // ----------------------------- + + [ObservableProperty] private bool _isConverting; + [ObservableProperty] private double _progress; + + private CancellationTokenSource? _conversionCts; + + public ICommand CancelConversionCommand { get; } + + // ----------------------------- + // Existing commands + // ----------------------------- + + public ICommand OpenFileCommand { get; } + public ICommand PlayCommand { get; } + public ICommand PauseCommand { get; } + public ICommand StopCommand { get; } + public ICommand RewindCommand { get; } + public ICommand FastForwardCommand { get; } + + public ICommand SetPointACommand { get; } + public ICommand SetPointBCommand { get; } + + // ----------------------------- + // Playback properties + // ----------------------------- + + [ObservableProperty] private bool _loopEnabled; + [ObservableProperty] private float _playbackSpeed = 1f; + [ObservableProperty] private TimeSpan _currentTime; + [ObservableProperty] private TimeSpan _totalTime; + [ObservableProperty] private MixerViewModel _mixer = null!; + + public ObservableCollection Segments { get; } = new(); + public ObservableCollection Bands { get; } = new(); + + + private TimeSpan? _loopA; + private TimeSpan? _loopB; + + // ----------------------------- + // Constructor + // ----------------------------- + + public PlaybackViewModel( + IStemPlaybackEngine engine, + IStemSeparator separator, + IStemDecoderFactory decoderFactory, + IStemWaveformService waveformService + ) + { + _engine = engine; + _separator = separator; + _decoderFactory = decoderFactory; + _waveformService = waveformService; + + CancelConversionCommand = new RelayCommand(_ => CancelConversion()); + + OpenFileCommand = new AsyncRelayCommand(OpenFileAsync); + PlayCommand = new AsyncRelayCommand(() => _engine.PlayAsync()); + PauseCommand = new AsyncRelayCommand(() => _engine.PauseAsync()); + StopCommand = new AsyncRelayCommand(async () => { await _engine.StopAsync(); await _engine.SeekAsync(TimeSpan.Zero); }); + + RewindCommand = new AsyncRelayCommand(() => _engine.SeekAsync(CurrentTime - TimeSpan.FromSeconds(5))); + FastForwardCommand = new AsyncRelayCommand(() => _engine.SeekAsync(CurrentTime + TimeSpan.FromSeconds(5))); + + SetPointACommand = new RelayCommand(_ => + { + _loopA = CurrentTime; + UpdateLoop(); + }); + + SetPointBCommand = new RelayCommand(_ => + { + _loopB = CurrentTime; + UpdateLoop(); + }); + + + } + + partial void OnCurrentTimeChanged(TimeSpan value) + { + foreach (var band in Bands) + { + band.UpdatePlaybackPosition(CurrentTime, TotalTime); + } + } + + partial void OnTotalTimeChanged(TimeSpan value) + { + foreach (var band in Bands) + { + band.UpdatePlaybackPosition(CurrentTime, TotalTime); + } + } + // ----------------------------- + // File open + stem conversion + //------------------------------ + + private async Task OpenFileAsync() + { + var topLevel = TopLevel.GetTopLevel( + (App.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow + ); + + if (topLevel is null) + return; + + var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + { + AllowMultiple = false, + FileTypeFilter = + [ + new FilePickerFileType("Audio") + { + Patterns = new[] { "*.mp3", "*.flac", "*.wav" } + } + ] + }); + + if (files.Count == 0) + return; + + var file = files[0]; + + await _engine.StopAsync(); + + var session = await SplitStems(file); + if (session == null) + return; + + TotalTime = session.StemSet.Stems.FirstOrDefault()?.Duration ?? TimeSpan.Zero; + CurrentTime = TimeSpan.Zero; + + await UpdateWaveForms(session); + + Bands.Clear(); + foreach ( var item in session.StemSet.Stems) + { + Bands.Add(new WaveformBandViewModel(item)); + } + + await _engine.LoadSessionAsync(session, new PlaybackProgressReporter(this)); + } + + private class PlaybackProgressReporter : IProgressReporter + { + private readonly PlaybackViewModel _vm; + public PlaybackProgressReporter(PlaybackViewModel vm) + { + _vm = vm; + } + public Task ReportProgress(TimeSpan progress, CancellationToken ct) + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + _vm.CurrentTime = progress; + }); + return Task.CompletedTask; + } + } + + private async Task UpdateWaveForms(PlaybackSession session) + { + IsConverting = true; + Progress = 0; + + _conversionCts = new CancellationTokenSource(); + var ct = _conversionCts.Token; + + var stems = session.StemSet.Stems; + var total = stems.Count; + + var reporter = new VmProgressReporter(this); + + // Thread‑safe counter + var completed = 0; + + try + { + await Task.Run(async () => + { + // Create parallel tasks + var tasks = stems.Select(async stem => + { + ct.ThrowIfCancellationRequested(); + + var decoder = _decoderFactory.Create(stem); + + var waveform = await _waveformService.ComputeWaveformAsync(stem, decoder, 200); + + stem.Waveform = waveform; + + // Update progress safely + var done = Interlocked.Increment(ref completed); + var p = (double)done / total; + + await reporter.ReportProgress(p, ct); + }).ToList(); + + // Run all tasks in parallel + await Task.WhenAll(tasks); + }, ct); + } + catch (OperationCanceledException) + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + Progress = 0; + IsConverting = false; + }); + return; + } + catch (Exception) + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + Progress = 0; + IsConverting = false; + }); + throw; + } + + IsConverting = false; + } + + + + // ----------------------------- + // Progress reporter + // ----------------------------- + + private sealed class VmProgressReporter : IProgressReporter + { + private readonly PlaybackViewModel _vm; + + public VmProgressReporter(PlaybackViewModel vm) + { + _vm = vm; + } + + public Task ReportProgress(double progress, CancellationToken ct) + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + _vm.Progress = progress * 100.0; + }); + + return Task.CompletedTask; + } + } + + + // ----------------------------- + // Stem splitting + // ----------------------------- + + private async Task SplitStems(IStorageFile file) + { + // Enter conversion mode + IsConverting = true; + Progress = 0; + + _conversionCts = new CancellationTokenSource(); + var ct = _conversionCts.Token; + + var outDir = Path.Combine(Path.GetDirectoryName(file.Path.LocalPath)!, "ABStemPlayer"); + + StemSet? stemSet = null; + + try + { + // Run separation on background thread + stemSet = await Task.Run(async () => + { + try + { + return await _separator.SeparateAsync( + new StemSeparationRequest + { + SourceFilePath = file.Path.LocalPath, + OutputDirectory = outDir + }, + new VmProgressReporter(this), + ct + ); + } + catch (Exception) + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + Progress = 0; + IsConverting = false; + }); + return null; + } + }, ct); + } + catch (OperationCanceledException) + { + // Cancelled by user + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + Progress = 0; + IsConverting = false; + }); + } + + // Exit conversion mode + IsConverting = false; + Progress = 0; + + if ( stemSet == null) + return null; + + // Build session + return new PlaybackSession + { + StemSet = stemSet, + Mixer = new MixerSettings + { + Stems = stemSet.Stems.Select(GetMixerSettings).ToList() + }, + Loop = new LoopRegion + { + Start = TimeSpan.Zero, + End = TimeSpan.Zero + }, + Speed = new PlaybackSpeedSettings + { + Speed = PlaybackSpeed + } + }; + } + + private StemMixSettings GetMixerSettings(StemTrack stem) + { + var found = Mixer.Stems.FirstOrDefault(s => s.Type == stem.Type); + if ( found != null ) + return new StemMixSettings + { + GainDb = found.GainDb, + Enabled = found.Enabled, + Pan = found.Pan + }; + + found = new StemChannelViewModel(stem.Type); + Mixer.Stems.Add(found); + return new StemMixSettings + { + GainDb = found.GainDb, + Enabled = found.Enabled, + Pan = found.Pan + }; + } + + // ----------------------------- + // Cancel conversion + // ----------------------------- + + private void CancelConversion() + { + _conversionCts?.Cancel(); + } + + // ----------------------------- + // Loop logic + // ----------------------------- + + private void UpdateLoop() + { + if (_loopA.HasValue && _loopB.HasValue && LoopEnabled) + { + var a = _loopA.Value; + var b = _loopB.Value; + + if (b > a) + _engine.SetLoop(a, b); + } + else + { + _engine.ClearLoop(); + } + } + + public void UpdateSpeed() + { + _engine.SetSpeed(PlaybackSpeed); + } +} diff --git a/ABStemPlayer/ViewModels/RelayCommand.cs b/ABStemPlayer/ViewModels/RelayCommand.cs new file mode 100644 index 0000000..8c8c569 --- /dev/null +++ b/ABStemPlayer/ViewModels/RelayCommand.cs @@ -0,0 +1,19 @@ +using System.Windows.Input; + +namespace ABStemPlayer.ViewModels; + +public sealed class RelayCommand : ICommand +{ + private readonly Action _execute; + private readonly Func? _canExecute; + + public RelayCommand(Action execute, Func? canExecute = null) + { + _execute = execute; + _canExecute = canExecute; + } + + public bool CanExecute(object? parameter) => _canExecute?.Invoke(parameter) ?? true; + public void Execute(object? parameter) => _execute(parameter); + public event EventHandler? CanExecuteChanged; +} diff --git a/ABStemPlayer/ViewModels/SegmentViewModel.cs b/ABStemPlayer/ViewModels/SegmentViewModel.cs new file mode 100644 index 0000000..e2a763c --- /dev/null +++ b/ABStemPlayer/ViewModels/SegmentViewModel.cs @@ -0,0 +1,19 @@ +namespace ABStemPlayer.ViewModels; + +public sealed class SegmentViewModel +{ + public string Name { get; set; } = string.Empty; + + public TimeSpan Start { get; set; } + public TimeSpan End { get; set; } + + public bool Active { get; set; } + + public string StartFormatted => Start.ToString("mm\\:ss"); + public string EndFormatted => End.ToString("mm\\:ss"); + + // waveform rendering helpers + public double StartX { get; set; } + public double Width { get; set; } + public double SegmentHeight { get; set; } = 80; +} diff --git a/ABStemPlayer/ViewModels/StemChannelViewModel.cs b/ABStemPlayer/ViewModels/StemChannelViewModel.cs new file mode 100644 index 0000000..563069d --- /dev/null +++ b/ABStemPlayer/ViewModels/StemChannelViewModel.cs @@ -0,0 +1,15 @@ +namespace ABStemPlayer.ViewModels; + +public partial class StemChannelViewModel : ObservableObject +{ + public StemType Type { get; } + + [ObservableProperty] private bool _enabled = true; + [ObservableProperty] private float _gainDb = 0f; + [ObservableProperty] private float _pan = 0f; + + public StemChannelViewModel(StemType type) + { + Type = type; + } +} diff --git a/ABStemPlayer/ViewModels/ViewModelBase.cs b/ABStemPlayer/ViewModels/ViewModelBase.cs new file mode 100644 index 0000000..d475151 --- /dev/null +++ b/ABStemPlayer/ViewModels/ViewModelBase.cs @@ -0,0 +1,5 @@ +namespace ABStemPlayer.ViewModels; + +public abstract class ViewModelBase : ObservableObject +{ +} diff --git a/ABStemPlayer/ViewModels/WaveformBandViewModel.cs b/ABStemPlayer/ViewModels/WaveformBandViewModel.cs new file mode 100644 index 0000000..13d5c76 --- /dev/null +++ b/ABStemPlayer/ViewModels/WaveformBandViewModel.cs @@ -0,0 +1,91 @@ +using System.Collections.ObjectModel; +using Avalonia.Media; + +namespace ABStemPlayer.ViewModels; + +public partial class WaveformBandViewModel : ObservableObject +{ + public sealed class WaveformBar + { + public double X { get; set; } // Canvas.Left + public double Y { get; set; } // Canvas.Top + public double Width { get; set; } // bar width + public double Height { get; set; } // bar height + + public override string ToString() => Height.ToString(); + } + + + private readonly StemTrack _stem; + public string BandName => _stem.Name; + + [ObservableProperty] private double _canvasWidth; + [ObservableProperty] private double _canvasHeight; + [ObservableProperty] private Geometry? _waveformGeometry; + + public ObservableCollection WaveformBars { get; } = new(); + + [ObservableProperty] private double _playbackX; + + public ObservableCollection Segments { get; } = new(); + + public TimeSpan Duration { get; set; } + public string DurationFormatted => Duration.ToString("mm\\:ss"); + + public WaveformBandViewModel(StemTrack stem) + { + _stem = stem; + } + + public void UpdatePlaybackPosition(TimeSpan current, TimeSpan total) + { + if (total <= TimeSpan.Zero || CanvasWidth <= 0) + { + PlaybackX = 0; + return; + } + + double ratio = current.TotalSeconds / total.TotalSeconds; + PlaybackX = ratio * CanvasWidth; + } + + public void UpdateBarsForCanvasSize(double canvasWidth, double canvasHeight) + { + CanvasWidth = canvasWidth; + CanvasHeight = canvasHeight; + var waveform = _stem.Waveform; + + if (waveform == null || waveform.Length == 0) + { + WaveformGeometry = null; + return; + } + + var geo = new StreamGeometry(); + + using (var ctx = geo.Open()) + { + double half = canvasHeight / 2.0; + double spacing = 1.0; + double barWidth = (canvasWidth - (waveform.Length - 1) * spacing) / waveform.Length; + + double x = 0; + + for (int i = 0; i < waveform.Length; i++) + { + double amp = Math.Abs(waveform[i]); + double h = amp * half; + + // draw vertical bar + ctx.BeginFigure(new Point(x, half - h), false); + ctx.LineTo(new Point(x, half + h)); + + x += barWidth + spacing; + } + } + + WaveformGeometry = geo; + } + + +} diff --git a/ABStemPlayer/Views/MainWindow.axaml b/ABStemPlayer/Views/MainWindow.axaml new file mode 100644 index 0000000..6785b92 --- /dev/null +++ b/ABStemPlayer/Views/MainWindow.axaml @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ABStemPlayer/Views/MainWindow.axaml.cs b/ABStemPlayer/Views/MainWindow.axaml.cs new file mode 100644 index 0000000..f05e4f4 --- /dev/null +++ b/ABStemPlayer/Views/MainWindow.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace ABStemPlayer.Views; + +public partial class MainWindow : Window +{ + public MainWindow() + { + InitializeComponent(); + } +} \ No newline at end of file diff --git a/ABStemPlayer/Views/MixerControl.axaml b/ABStemPlayer/Views/MixerControl.axaml new file mode 100644 index 0000000..0b8bb40 --- /dev/null +++ b/ABStemPlayer/Views/MixerControl.axaml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ABStemPlayer/Views/MixerControl.axaml.cs b/ABStemPlayer/Views/MixerControl.axaml.cs new file mode 100644 index 0000000..c6b4c8e --- /dev/null +++ b/ABStemPlayer/Views/MixerControl.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace ABStemPlayer.Views; + +public partial class MixerControl : UserControl +{ + public MixerControl() + { + InitializeComponent(); + } +} diff --git a/ABStemPlayer/Views/PlaybackControls.axaml b/ABStemPlayer/Views/PlaybackControls.axaml new file mode 100644 index 0000000..2245f49 --- /dev/null +++ b/ABStemPlayer/Views/PlaybackControls.axaml @@ -0,0 +1,256 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +