1
0
Fork 0
mirror of https://gitlab.com/futo-org/fcast.git synced 2025-06-24 21:25:23 +00:00

Added dotnet FCast client.

This commit is contained in:
Koen 2024-01-06 13:20:01 +01:00
parent f0fa5c067f
commit c4e9303cc3
8 changed files with 1191 additions and 0 deletions

398
clients/terminal-dotnet/.gitignore vendored Normal file
View file

@ -0,0 +1,398 @@
## 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/main/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/
[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
*.tlog
*.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 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# 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/
# Visual Studio History (VSHistory) files
.vshistory/
# 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
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

View file

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\FCastClient\FCastClient.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NestedArgs" Version="1.0.0" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,353 @@
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using FCastClient;
using NestedArgs;
internal class Program
{
private static async Task Main(string[] args)
{
Command rootCommand = new CommandBuilder("fcast", "Control FCast Receiver through the terminal.")
.Option(new Option()
{
LongName = "connection_type",
ShortName = 'c',
Description = "Type of connection: tcp or ws (websocket)",
DefaultValue = "tcp",
IsRequired = false
})
.Option(new Option()
{
LongName = "host",
ShortName = 'h',
Description = "The host address to send the command to",
IsRequired = true
})
.Option(new Option()
{
LongName = "port",
ShortName = 'p',
Description = "The port to send the command to",
IsRequired = false
})
.SubCommand(new CommandBuilder("play", "Play media")
.Option(new Option()
{
LongName = "mime_type",
ShortName = 'm',
Description = "Mime type (e.g., video/mp4)",
IsRequired = true
})
.Option(new Option()
{
LongName = "file",
ShortName = 'f',
Description = "File content to play",
IsRequired = false
})
.Option(new Option()
{
LongName = "url",
ShortName = 'u',
Description = "URL to the content",
IsRequired = false
})
.Option(new Option()
{
LongName = "content",
ShortName = 'c',
Description = "The actual content",
IsRequired = false
})
.Option(new Option()
{
LongName = "timestamp",
ShortName = 't',
Description = "Timestamp to start playing",
DefaultValue = "0",
IsRequired = false
})
.Option(new Option()
{
LongName = "speed",
ShortName = 's',
Description = "Factor to multiply playback speed by",
DefaultValue = "1",
IsRequired = false
})
.Option(new Option()
{
LongName = "header",
ShortName = 'H',
Description = "HTTP header to add to request",
IsRequired = false,
AllowMultiple = true
})
.Build())
.SubCommand(new CommandBuilder("seek", "Seek to a timestamp")
.Option(new Option()
{
LongName = "timestamp",
ShortName = 't',
Description = "Timestamp to start playing",
IsRequired = true
})
.Build())
.SubCommand(new CommandBuilder("pause", "Pause media").Build())
.SubCommand(new CommandBuilder("resume", "Resume media").Build())
.SubCommand(new CommandBuilder("stop", "Stop media").Build())
.SubCommand(new CommandBuilder("listen", "Listen to incoming events").Build())
.SubCommand(new CommandBuilder("setvolume", "Set the volume")
.Option(new Option()
{
LongName = "volume",
ShortName = 'v',
Description = "Volume level (0-1)",
IsRequired = true
})
.Build())
.SubCommand(new CommandBuilder("setspeed", "Set the playback speed")
.Option(new Option()
{
LongName = "speed",
ShortName = 's',
Description = "Factor to multiply playback speed by",
IsRequired = true
})
.Build())
.Build();
CommandMatches matches = rootCommand.Parse(args);
var host = matches.Value("host")!;
var connectionType = matches.Value("connection_type")!;
var port = matches.ValueAsInt32("port") ?? connectionType switch
{
"tcp" => 46899,
"ws" => 46898,
_ => throw new Exception($"{connectionType} is not a valid connection type.")
};
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
Console.CancelKeyPress += (_, _) =>
{
cancellationTokenSource.Cancel();
};
using var session = await EstablishConnection(host, port, connectionType, cancellationToken);
await session.SendMessageAsync(Opcode.Version, new VersionMessage() { Version = 1 }, cancellationToken);
switch (matches.SubCommand)
{
case "play":
{
var playMatches = matches.SubCommandMatch!;
var mimeType = playMatches.Value("mime_type")!;
var timestamp = playMatches.ValueAsDouble("timestamp")!;
var speed = playMatches.ValueAsDouble("speed")!;
var headers = playMatches.Values("header")?.Select(SplitHeader).ToDictionary(v => v.Key, v => v.Value);
if (playMatches.Has("file"))
{
IPAddress localAddress;
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(host, port);
localAddress = (socket.LocalEndPoint as IPEndPoint)!.Address;
}
var path = playMatches.Value("file")!;
var (url, task) = HostFileAndGetUrl(localAddress, path, mimeType, cancellationToken);
await session.SendMessageAsync(Opcode.Play, new PlayMessage()
{
Container = mimeType,
Speed = speed,
Time = timestamp,
Url = url,
Headers = headers
}, cancellationToken);
Console.WriteLine("Waiting for video to finish. Press CTRL+C to exit.");
await task;
}
else
{
var url = playMatches.Value("url");
var content = playMatches.Value("content");
await session.SendMessageAsync(Opcode.Play, new PlayMessage()
{
Container = mimeType,
Content = content,
Speed = speed,
Time = timestamp,
Url = url,
Headers = headers
}, cancellationToken);
}
break;
}
case "seek":
{
await session.SendMessageAsync(Opcode.Seek, new SeekMessage() { Time = matches.SubCommandMatch!.ValueAsDouble("timestamp")!.Value }, cancellationToken);
break;
}
case "pause":
{
await session.SendMessageAsync(Opcode.Pause, cancellationToken);
break;
}
case "resume":
{
await session.SendMessageAsync(Opcode.Resume, cancellationToken);
break;
}
case "stop":
{
await session.SendMessageAsync(Opcode.Stop, cancellationToken);
break;
}
case "listen":
{
Console.WriteLine("Listening. Press CTRL+C to exit.");
await session.ReceiveLoopAsync(cancellationToken);
break;
}
case "setvolume":
{
await session.SendMessageAsync(Opcode.SetVolume, new SetVolumeMessage() { Volume = matches.SubCommandMatch!.ValueAsDouble("volume")!.Value }, cancellationToken);
break;
}
case "setspeed":
{
await session.SendMessageAsync(Opcode.SetSpeed, new SetSpeedMessage() { Speed = matches.SubCommandMatch!.ValueAsDouble("speed")!.Value }, cancellationToken);
break;
}
default:
Console.WriteLine("Invalid command. Use --help for more information.");
break;
}
}
private static int GetAvailablePort()
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
return ((IPEndPoint)socket.LocalEndPoint!).Port;
}
public static (string url, Task serverTask) HostFileAndGetUrl(IPAddress localAddress, string filePath, string mimeType, CancellationToken cancellationToken)
{
var listener = new HttpListener();
listener.Prefixes.Add($"http://{localAddress}:{GetAvailablePort()}/");
listener.Start();
var url = listener.Prefixes.First();
Console.WriteLine($"Server started on {url}.");
var serverTask = Task.Run(async () =>
{
DateTime lastRequestTime = DateTime.Now;
int activeConnections = 0;
while (!cancellationToken.IsCancellationRequested)
{
if (activeConnections == 0 && (DateTime.Now - lastRequestTime).TotalSeconds > 300)
{
Console.WriteLine("No activity on server, closing...");
break;
}
if (listener.IsListening)
{
var contextTask = listener.GetContextAsync();
await Task.WhenAny(contextTask, Task.Delay(Timeout.Infinite, cancellationToken));
if (cancellationToken.IsCancellationRequested)
break;
var context = contextTask.Result;
Console.WriteLine("Request received.");
try
{
Interlocked.Increment(ref activeConnections);
lastRequestTime = DateTime.Now;
var response = context.Response;
response.ContentType = mimeType;
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
await fileStream.CopyToAsync(response.OutputStream);
response.OutputStream.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error handling request: {ex.Message}");
}
finally
{
Interlocked.Decrement(ref activeConnections);
}
}
else
{
await Task.Delay(5000);
}
}
listener.Stop();
}, cancellationToken);
return (url, serverTask);
}
public static (string Key, string Value) SplitHeader(string input)
{
int colonIndex = input.IndexOf(':');
if (colonIndex == -1)
{
throw new Exception("Header format invalid");
}
string beforeColon = input.Substring(0, colonIndex);
string afterColon = input.Substring(colonIndex + 1);
return (beforeColon, afterColon);
}
private static async Task<FCastSession> EstablishConnection(string host, int port, string connectionType, CancellationToken cancellationToken)
{
switch (connectionType.ToLower())
{
case "tcp":
return await EstablishTcpConnection(host, port, cancellationToken);
case "ws":
return await EstablishWebSocketConnection(host, port, cancellationToken);
default:
throw new ArgumentException("Invalid connection type: " + connectionType);
}
}
private static async Task<FCastSession> EstablishTcpConnection(string host, int port, CancellationToken cancellationToken)
{
TcpClient client = new TcpClient();
await client.ConnectAsync(host, port, cancellationToken);
return new FCastSession(client.GetStream());
}
private static async Task<FCastSession> EstablishWebSocketConnection(string host, int port, CancellationToken cancellationToken)
{
ClientWebSocket webSocket = new ClientWebSocket();
string scheme = "ws";
string uriString = $"{scheme}://{host}:{port}";
Uri serverUri = new Uri(uriString);
await webSocket.ConnectAsync(serverUri, cancellationToken);
return new FCastSession(new WebSocketStream(webSocket));
}
}

View file

@ -0,0 +1,53 @@
# What is FCast?
FCast is a protocol designed for wireless streaming of audio and video content between devices. Unlike alternative protocols like Chromecast and AirPlay, FCast is an open source protocol that allows for custom receiver implementations, enabling third-party developers to create their own receiver devices or integrate the FCast protocol into their own apps.
# Building
Setup a rust development environment and type:
```
cargo build
```
# Usage
Example usage of the fcast client.
```
# Play a mp4 video URL (1.0 playbackspeed explicit)
./fcast -h localhost play --mime_type video/mp4 --url http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4 -t 10 -s 1.0
# Play a mp4 video URL using WebSockets
./fcast -h localhost -c ws play --mime_type video/mp4 --url http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4 -t 10
# Play a local mp4
./fcast -h 192.168.1.62 play --mime_type video/mp4 -f /home/koen/Downloads/BigBuckBunny.mp4
# Play a DASH URL
./fcast -h localhost play --mime_type application/dash+xml --url https://dash.akamaized.net/digitalprimates/fraunhofer/480p_video/heaac_2_0_with_video/Sintel/sintel_480p_heaac2_0.mpd
# Play local DASH content
cat dash.mpd | ./fcast -h localhost play --mime_type application/dash+xml
# Pause playing
./fcast -h localhost pause
# Resume playback
./fcast -h localhost resume
# Seek to time 100
./fcast -h localhost seek -t 100
# Listen for playback updates
./fcast -h localhost listen
# Stop playback
./fcast -h localhost stop
# Set volume to half
./fcast -h localhost setvolume -v 0.5
# Set speed to double
./fcast -h localhost setspeed -s 2.0
```

View file

@ -0,0 +1,46 @@
using System.Net.WebSockets;
public class WebSocketStream : Stream
{
private readonly ClientWebSocket _webSocket;
public WebSocketStream(ClientWebSocket webSocket)
{
_webSocket = webSocket;
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override void Flush() { }
public override int Read(byte[] buffer, int offset, int count)
{
var segment = new ArraySegment<byte>(buffer, offset, count);
var result = _webSocket.ReceiveAsync(segment, CancellationToken.None).Result;
return result.Count;
}
public override void Write(byte[] buffer, int offset, int count)
{
var segment = new ArraySegment<byte>(buffer, offset, count);
_webSocket.SendAsync(segment, WebSocketMessageType.Binary, true, CancellationToken.None).Wait();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
}

View file

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,240 @@
namespace FCastClient;
using System;
using System.Buffers.Binary;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
public enum SessionState
{
Idle,
WaitingForLength,
WaitingForData,
Disconnected
}
public enum Opcode
{
None = 0,
Play,
Pause,
Resume,
Stop,
Seek,
PlaybackUpdate,
VolumeUpdate,
SetVolume,
PlaybackError,
SetSpeed,
Version,
Ping,
Pong
}
public class FCastSession : IDisposable
{
private const int LengthBytes = 4;
private const int MaximumPacketLength = 32000;
private byte[] _buffer = new byte[MaximumPacketLength];
private int _bytesRead;
private int _packetLength;
private Stream _stream;
private SessionState _state;
public FCastSession(Stream stream)
{
_stream = stream;
_state = SessionState.Idle;
}
public async Task SendMessageAsync(Opcode opcode, CancellationToken cancellationToken)
{
int size = 1;
byte[] header = new byte[LengthBytes + 1];
Array.Copy(BitConverter.GetBytes(size), header, LengthBytes);
header[LengthBytes] = (byte)opcode;
Console.WriteLine($"Sent {header.Length} bytes with (opcode: {opcode}, header size: {header.Length}, no body).");
await _stream.WriteAsync(header, cancellationToken);
}
public async Task SendMessageAsync<T>(Opcode opcode, T message, CancellationToken cancellationToken) where T : class
{
string json = JsonSerializer.Serialize(message);
byte[] data = Encoding.UTF8.GetBytes(json);
int size = 1 + data.Length;
byte[] header = new byte[LengthBytes + 1];
Array.Copy(BitConverter.GetBytes(size), header, LengthBytes);
header[LengthBytes] = (byte)opcode;
byte[] packet = new byte[header.Length + data.Length];
header.CopyTo(packet, 0);
data.CopyTo(packet, header.Length);
Console.WriteLine($"Sent {packet.Length} bytes with (opcode: {opcode}, header size: {header.Length}, body size: {data.Length}, body: {json}).");
await _stream.WriteAsync(packet, cancellationToken);
}
public async Task ReceiveLoopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Start receiving.");
_state = SessionState.WaitingForLength;
byte[] buffer = new byte[1024];
while (!cancellationToken.IsCancellationRequested)
{
int bytesRead = await _stream.ReadAsync(buffer, cancellationToken);
if (bytesRead == 0)
{
Console.WriteLine("Connection shutdown gracefully.");
Dispose();
break;
}
await ProcessBytesAsync(buffer, bytesRead, cancellationToken);
}
_state = SessionState.Idle;
}
private async Task ProcessBytesAsync(byte[] receivedBytes, int length, CancellationToken cancellationToken)
{
Console.WriteLine($"{length} bytes received");
switch (_state)
{
case SessionState.WaitingForLength:
await HandleLengthBytesAsync(receivedBytes, 0, length, cancellationToken);
break;
case SessionState.WaitingForData:
await HandlePacketBytesAsync(receivedBytes, 0, length, cancellationToken);
break;
default:
Console.WriteLine($"Data received is unhandled in current session state {_state}");
break;
}
}
private async Task HandleLengthBytesAsync(byte[] receivedBytes, int offset, int length, CancellationToken cancellationToken)
{
int bytesToRead = Math.Min(LengthBytes, length);
Buffer.BlockCopy(receivedBytes, offset, _buffer, 0, bytesToRead);
_bytesRead += bytesToRead;
Console.WriteLine($"handleLengthBytes: Read {bytesToRead} bytes from packet");
if (_bytesRead >= LengthBytes)
{
_state = SessionState.WaitingForData;
_packetLength = BinaryPrimitives.ReadInt32LittleEndian(_buffer);
_bytesRead = 0;
Console.WriteLine($"Packet length header received from: {_packetLength}");
if (_packetLength > MaximumPacketLength)
{
Console.WriteLine($"Maximum packet length is 32kB, killing stream: {_packetLength}");
Dispose();
_state = SessionState.Disconnected;
throw new InvalidOperationException($"Stream killed due to packet length ({_packetLength}) exceeding maximum 32kB packet size.");
}
if (length > bytesToRead)
{
await HandlePacketBytesAsync(receivedBytes, bytesToRead, length - bytesToRead, cancellationToken);
}
}
}
private async Task HandlePacketBytesAsync(byte[] receivedBytes, int offset, int length, CancellationToken cancellationToken)
{
int bytesToRead = Math.Min(_packetLength, length);
Buffer.BlockCopy(receivedBytes, offset, _buffer, 0, bytesToRead);
_bytesRead += bytesToRead;
Console.WriteLine($"handlePacketBytes: Read {bytesToRead} bytes from packet");
if (_bytesRead >= _packetLength)
{
Console.WriteLine($"Packet finished receiving of {_packetLength} bytes.");
await HandleNextPacketAsync(cancellationToken);
_state = SessionState.WaitingForLength;
_packetLength = 0;
_bytesRead = 0;
if (length > bytesToRead)
{
await HandleLengthBytesAsync(receivedBytes, bytesToRead, length - bytesToRead, cancellationToken);
}
}
}
private async Task HandleNextPacketAsync(CancellationToken cancellationToken)
{
Console.WriteLine($"Processing packet of {_bytesRead} bytes");
Opcode opcode = (Opcode)_buffer[0];
int packetLength = _packetLength;
string? body = packetLength > 1 ? Encoding.UTF8.GetString(_buffer, 1, packetLength - 1) : null;
Console.WriteLine($"Received body: {body}");
await HandlePacketAsync(opcode, body, cancellationToken);
}
private async Task HandlePacketAsync(Opcode opcode, string? body, CancellationToken cancellationToken)
{
Console.WriteLine($"Received message with opcode {opcode}.");
switch (opcode)
{
case Opcode.PlaybackUpdate:
HandleMessage<PlaybackUpdateMessage>(body!, "Received playback update");
break;
case Opcode.VolumeUpdate:
HandleMessage<VolumeUpdateMessage>(body!, "Received volume update");
break;
case Opcode.PlaybackError:
HandleMessage<PlaybackErrorMessage>(body!, "Received playback error");
break;
case Opcode.Version:
HandleMessage<VersionMessage>(body!, "Received version");
break;
case Opcode.Ping:
Console.WriteLine("Received ping");
await SendMessageAsync(Opcode.Pong, cancellationToken);
Console.WriteLine("Sent pong");
break;
default:
Console.WriteLine("Error handling packet");
break;
}
}
private void HandleMessage<T>(string body, string logMessage) where T : class
{
if (!string.IsNullOrEmpty(body))
{
T? message = JsonSerializer.Deserialize<T>(body);
if (message != null)
{
Console.WriteLine($"{logMessage} {JsonSerializer.Serialize(message)}");
}
else
{
Console.WriteLine($"{logMessage} with malformed body.");
}
}
else
{
Console.WriteLine($"{logMessage} with no body.");
}
}
public void Dispose()
{
_stream.Dispose();
}
}

View file

@ -0,0 +1,74 @@
using System;
using System.Text.Json.Serialization;
public class PlayMessage
{
[JsonPropertyName("container")]
public required string Container { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
[JsonPropertyName("content")]
public string? Content { get; set; }
[JsonPropertyName("time")]
public double? Time { get; set; }
[JsonPropertyName("speed")]
public double? Speed { get; set; }
[JsonPropertyName("headers")]
public Dictionary<string, string>? Headers { get; set; }
}
public class SeekMessage
{
[JsonPropertyName("time")]
public required double Time { get; set; }
}
public class PlaybackUpdateMessage
{
[JsonPropertyName("time")]
public required double Time { get; set; }
[JsonPropertyName("duration")]
public required double Duration { get; set; }
[JsonPropertyName("speed")]
public required double Speed { get; set; }
[JsonPropertyName("state")]
public required int State { get; set; } // 0 = None, 1 = Playing, 2 = Paused
}
public class VolumeUpdateMessage
{
[JsonPropertyName("volume")]
public required double Volume { get; set; } // (0-1)
}
public class SetVolumeMessage
{
[JsonPropertyName("volume")]
public required double Volume { get; set; }
}
public class SetSpeedMessage
{
[JsonPropertyName("speed")]
public required double Speed { get; set; }
}
public class PlaybackErrorMessage
{
[JsonPropertyName("message")]
public required string Message { get; set; }
}
public class VersionMessage
{
[JsonPropertyName("version")]
public required ulong Version { get; set; }
}