feat/calls #62
27 changed files with 604 additions and 86 deletions
Support avatar video sources for SRTP calls
Use the shared LibVLC audio-video pipeline for camera-free calls on Linux and Android. Add capability signaling, microphone-only Android capture, avatar lifecycle handling and regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
commit
f05dd48ac7
|
|
@ -6,6 +6,8 @@
|
|||
|
||||
### Added
|
||||
|
||||
* [PostIt/Calls] Allow direct SRTP calls without a camera on Linux and Android by transmitting the user's avatar as repeating video with microphone audio through the existing LibVLC H.264/AAC pipeline. Announce transport-specific support, retain video reception and address-disclosure consent, and capture only microphone audio on Android in avatar mode. Add avatar lifecycle, UI, signaling and real IPv4/IPv6 media regressions; document validation and remaining Android device testing.
|
||||
|
||||
* [PostIt/Chat] Add audio-only WebRTC calls on Linux and Android with the user's avatar as a static image, microphone-only capture, dedicated navigation and capability-aware invitations. Keep direct SRTP audio-video only; add signaling, UI and Linux native-media regressions.
|
||||
|
||||
* [PostIt/Chat] Filter video invitations and private messages by announced per-connection preferences, stop affected calls when preferences change, and prepare mode-aware audio signaling. Audio-only calls and static images are not implemented yet; legacy clients without preferences remain reachable.
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ que cette preference soit desactivee pour les deux participants. Les groupes
|
|||
et les clients navigateur ne sont pas implementes.
|
||||
Depuis le chat textuel, selectionner un membre present puis « Ouvrir l'appel »
|
||||
ou « Ouvrir l'appel audio » prepare le pair sans demarrer les medias. La page
|
||||
WebRTC propose les deux modes : un utilisateur autorisant l'audio et la video
|
||||
WebRTC et le panneau SRTP proposent les deux modes : un utilisateur autorisant l'audio et la video
|
||||
peut appeler en audio seul. Les invitations entrantes disposent
|
||||
d'un bouton pour ouvrir cette meme page sans selection de membre. Passer du
|
||||
chat a la page d'appel ne raccroche pas ; quitter la page d'appel termine les
|
||||
|
|
@ -74,8 +74,13 @@ La cible couvre :
|
|||
automatique ni de migration transparente d'un appel existant.
|
||||
|
||||
Le panneau WebRTC ne demande pas d'adresse ni de port RTP manuel. Le panneau
|
||||
SRTP direct ne prend en charge que l'audio-video. Il demande une adresse locale, un port UDP pair et le consentement au
|
||||
SRTP direct demande une adresse locale, un port UDP pair et le consentement au
|
||||
partage d'adresse ; il requiert HTTPS pour proteger les cles de signalisation.
|
||||
Son flux reste toujours audio-video H.264/AAC, sur Linux comme sur Android :
|
||||
le mode « audio » remplace seulement la camera par l'avatar de l'emetteur,
|
||||
repete en video pendant tout l'appel. Il ne supprime pas la piste video.
|
||||
La capacite `SupportsLanAudioOnly`, distincte de celle de WebRTC, annonce
|
||||
ce mode sans camera et exclut les anciens clients qui ne savent pas le lancer.
|
||||
Les invitations sont dirigees vers le panneau correspondant, sans bascule
|
||||
automatique entre transports. Sans masquage,
|
||||
un consentement explicite au partage IP reste requis. Activer le masquage
|
||||
|
|
@ -186,6 +191,24 @@ L'implémentation est dans
|
|||
Android utilise
|
||||
[AndroidLanCallMedia](../../src/PostIt/PostIt.Android/Services/AndroidLanCallMedia.cs)
|
||||
avec les mêmes contrats et clés SRTP.
|
||||
|
||||
### Source video : camera ou avatar
|
||||
|
||||
« Appeler en audio » ne requiert aucune camera. Apres acceptation, PostIt
|
||||
charge le propre avatar du participant depuis son profil, le normalise en
|
||||
PNG 320 x 320 dans un fichier temporaire propre a l'appel et transmet cette
|
||||
image avec son microphone via le meme moteur LibVLC. Le correspondant affiche
|
||||
la video decodee, pas une image telechargee separement. Un avatar indisponible
|
||||
termine explicitement l'appel, sans ouvrir la camera ni substituer une image
|
||||
generique. Le fichier temporaire est supprime apres liberation des medias.
|
||||
|
||||
Le demultiplexeur `image` de LibVLC genere des trames pendant une duree
|
||||
illimitee (`image-duration=-1`, 30 images/s), plutot qu'un clip de dix secondes.
|
||||
L'horloge differe selon la source microphone : sur Linux, l'image en temps reel
|
||||
pilote l'entree PulseAudio esclave ; pour le pipe ADTS Android, l'audio pilote
|
||||
l'image esclave sur sa propre chronologie. Encodage H.264/AAC, reception video
|
||||
et audio, controles de reception et chiffrement SRTP restent communs.
|
||||
WebRTC conserve son implementation audio seule distincte, sans piste video.
|
||||
Les contrôles et les deux surfaces vidéo sont intégrés à la page du chat.
|
||||
Il n'y a pas de service de salles supplémentaire, d'enregistrement,
|
||||
de fichier média temporaire ou de moteur WebRTC Android ajouté.
|
||||
|
|
@ -244,11 +267,18 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté.
|
|||
- Les permissions caméra, microphone et notifications sont demandées
|
||||
après acceptation et réception de l'endpoint distant, avant la capture.
|
||||
Un refus termine explicitement l'appel, sans tentative de capture de repli.
|
||||
En mode avatar, seules les permissions microphone et notifications sont
|
||||
demandees ; le service de premier plan active uniquement le type microphone.
|
||||
Aucune camera ni surface d'encodage video Android n'est ouverte.
|
||||
- Camera2, MediaRecorder et la rotation EGL sont ceux des Podcasts.
|
||||
Le descripteur du pipe MPEG-TS est lu directement par LibVLC (`fd://`)
|
||||
puis remultiplexé vers SRTP, **sans réencodage**, HLS ou fichier média.
|
||||
Le pipe système assure une mémoire bornée ; il n'y a pas de file de
|
||||
segments ni de lecture de capture par callbacks managés.
|
||||
En mode avatar, MediaRecorder fournit uniquement le microphone AAC/ADTS
|
||||
dans un pipe ; LibVLC lit ce pipe et l'image, puis encode le flux audio-video
|
||||
commun. La preview locale est l'avatar, le retour distant reste une surface
|
||||
video LibVLC.
|
||||
- La prévisualisation réutilise la surface EGL existante. Le retour
|
||||
distant utilise la surface Android LibVLC déjà employée pour les Podcasts.
|
||||
La rotation capteur/écran tient compte de celle déjà portée par la matrice
|
||||
|
|
@ -304,6 +334,9 @@ l'ajout d'un moteur WebRTC ou d'une cryptographie propre au projet.
|
|||
pas ici de diagnostiquer précisément une panne média silencieuse :
|
||||
l'utilisateur peut raccrocher, et la perte de SignalR arrête toujours
|
||||
la capture. Pas encore de mesure de qualité ou de latence affichée.
|
||||
Une regression avec preview a aussi observe des compteurs nuls malgre
|
||||
les callbacks audio/video actifs ; son retest a reussi. Cette limite
|
||||
intermittente des statistiques natives n'est pas corrigee par le mode avatar.
|
||||
|
||||
### Validation effectuée et restante
|
||||
|
||||
|
|
@ -315,6 +348,10 @@ synthétique fourni explicitement et de vrais sockets UDP de bouclage :
|
|||
- même échange avec la branche de prévisualisation locale activée
|
||||
(sortie factice dans ce test sans fenêtre).
|
||||
- entrée MPEG-TS déjà encodée à travers un pipe, sans transcodage.
|
||||
- avatar fourni comme image a LibVLC, avec audio bidirectionnel et progression
|
||||
audio/video apres douze secondes, en IPv4/IPv6, y compris avec mauvaise cle ;
|
||||
- meme chemin avec une source PulseAudio synthetique isolee et avec un pipe
|
||||
AAC/ADTS cadence simulant la capture microphone Android.
|
||||
|
||||
Les tests de signalisation couvrent consentement, sélection d'un seul
|
||||
appareil, confidentialité, HTTPS, validation des endpoints et arrêt.
|
||||
|
|
@ -335,14 +372,24 @@ dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
|
|||
Sans cette entrée explicite, ces tests sont ignorés, pas remplacés par un
|
||||
succès fictif. Les tests de contrôle s'exécutent sans caméra.
|
||||
Le test de pipe utilise `POSTIT_TEST_TS`, un MPEG-TS H.264/AAC explicite.
|
||||
Les tests avatar utilisent `POSTIT_TEST_IMAGE` et `POSTIT_TEST_AUDIO`
|
||||
(fichier WAV d'au moins vingt secondes), ou `POSTIT_TEST_AUDIO_SOURCE`
|
||||
(URI d'une source de test, notamment un moniteur PulseAudio isole).
|
||||
Le test de pipe microphone utilise `POSTIT_TEST_AAC` (AAC/ADTS explicite d'au
|
||||
moins vingt secondes). Ces tests n'ouvrent aucune camera.
|
||||
|
||||
Une activité **Debug uniquement**,
|
||||
[AndroidLanCallTestActivity](../../src/PostIt/PostIt.Tests/AndroidLanCallTestActivity.cs),
|
||||
[AndroidLanCallTestActivity](../../src/PostIt/PostIt.Tests/Fixtures/AndroidLanCallTestActivity.cs),
|
||||
teste l'adaptateur réel sur téléphone : caméra avant/microphone, surfaces
|
||||
de retour et prévisualisation attachées, deux moteurs SRTP en UDP de
|
||||
bouclage, retour synthétique et rejet d'une mauvaise clé. Elle n'utilise
|
||||
ni compte ni API ; elle ne valide donc pas à elle seule un appel SignalR
|
||||
entre deux comptes. L'activité n'est pas compilée dans l'APK Release.
|
||||
L'extra chaine `avatar=true` selectionne l'image de test et le microphone
|
||||
sans enumerer ni ouvrir de camera. Le chemin avatar Android est compile et
|
||||
son entree AAC/ADTS est testee avec LibVLC sous Linux ; l'execution de cette
|
||||
variante sur telephone reste a effectuer. Aucun deploiement automatique n'est
|
||||
necessaire pour les tests Linux.
|
||||
|
||||
Pour la lancer sur un appareil de développement dont les permissions
|
||||
ont été accordées, installer l'APK Debug et ses assemblies via
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ using System.Runtime.Versioning;
|
|||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Media.Imaging;
|
||||
using PostIt.Services;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
||||
|
|
@ -19,6 +20,7 @@ internal sealed class AndroidLanCallMedia : ILanCallMedia
|
|||
private readonly TaskCompletionSource _captureEnded = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly Task _receiving;
|
||||
private IPodcastCapture? _capture;
|
||||
private Bitmap? _avatar;
|
||||
private bool _disposed;
|
||||
|
||||
public Control LocalVideo => _local;
|
||||
|
|
@ -70,6 +72,20 @@ internal sealed class AndroidLanCallMedia : ILanCallMedia
|
|||
_ = ObserveCaptureAsync(_capture);
|
||||
}
|
||||
|
||||
public async Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_capture != null) throw new InvalidOperationException("La capture de cet appel est deja demarree.");
|
||||
if (microphone != "microphone") throw new ArgumentException("Microphone Android invalide.", nameof(microphone));
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
|
||||
_avatar = new Bitmap(imagePath);
|
||||
_local.Content = new Image { Source = _avatar, Height = 140 };
|
||||
_capture = await AndroidPodcastCapture.StartAvatarCallAsync(
|
||||
(fd, token) => _media.StartAvatarSendingAsync(remote, imagePath, $"fd/aac://{fd}", token),
|
||||
_media.StopAsync, linked.Token);
|
||||
_ = ObserveCaptureAsync(_capture);
|
||||
}
|
||||
|
||||
private async Task ObserveCaptureAsync(IPodcastCapture capture)
|
||||
{
|
||||
try
|
||||
|
|
@ -100,6 +116,7 @@ internal sealed class AndroidLanCallMedia : ILanCallMedia
|
|||
finally
|
||||
{
|
||||
_local.Content = null;
|
||||
_avatar?.Dispose();
|
||||
try { await _media.StopAsync(); }
|
||||
finally
|
||||
{
|
||||
|
|
|
|||
|
|
@ -120,16 +120,29 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
Func<int, CancellationToken, Task> output, Func<Task> stopOutput, CancellationToken ct) =>
|
||||
StartCoreAsync(camera, microphone, null, output, stopOutput, ct, false);
|
||||
|
||||
private static async Task<IPodcastCapture> StartCoreAsync(string camera, string? microphone,
|
||||
internal static Task<IPodcastCapture> StartAvatarCallAsync(
|
||||
Func<int, CancellationToken, Task> output, Func<Task> stopOutput, CancellationToken ct) =>
|
||||
StartCoreAsync(null, "microphone", null, output, stopOutput, ct, false);
|
||||
|
||||
private static async Task<IPodcastCapture> StartCoreAsync(string? camera, string? microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, Func<Task>? stopOutput, CancellationToken ct, bool blur)
|
||||
{
|
||||
await RequestPermissionsAsync(microphone, ct);
|
||||
if (camera != null)
|
||||
await RequestPermissionsAsync(microphone, ct);
|
||||
else
|
||||
{
|
||||
var current = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
await PodcastPermissions.EnsureAsync(current, true, ct, camera: false);
|
||||
if (!MainActivity.IsForeground)
|
||||
throw new InvalidOperationException("Revenez dans PostIt pour demarrer le microphone.");
|
||||
}
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activite Android indisponible.");
|
||||
if (!await CaptureGate.WaitAsync(0, ct))
|
||||
throw new InvalidOperationException("La camera est deja utilisee par un apercu, un podcast ou un appel.");
|
||||
throw new InvalidOperationException("La capture est deja utilisee par un apercu, un podcast ou un appel.");
|
||||
PodcastCaptureService service;
|
||||
try { service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct, pipeOutput != null); }
|
||||
try { service = await PodcastCaptureService.StartAsync(activity, microphone is not null, ct, pipeOutput != null,
|
||||
camera: camera != null); }
|
||||
catch
|
||||
{
|
||||
CaptureGate.Release();
|
||||
|
|
@ -140,7 +153,11 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct, blur);
|
||||
if (camera != null)
|
||||
await capture.StartNativeAsync(camera, microphone is not null, output, pipeOutput, ct, blur);
|
||||
else
|
||||
await capture.StartMicrophoneAsync(pipeOutput
|
||||
?? throw new InvalidOperationException("Sortie microphone de l'appel indisponible."), ct);
|
||||
return capture;
|
||||
}
|
||||
catch
|
||||
|
|
@ -150,6 +167,42 @@ internal sealed class AndroidPodcastCapture : IPodcastCapture
|
|||
}
|
||||
}
|
||||
|
||||
private async Task StartMicrophoneAsync(Func<int, CancellationToken, Task> output, CancellationToken ct)
|
||||
{
|
||||
await _stopGate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
|
||||
#pragma warning disable CS0618
|
||||
_recorder = OperatingSystem.IsAndroidVersionAtLeast(31)
|
||||
? new MediaRecorder(_context) : new MediaRecorder();
|
||||
#pragma warning restore CS0618
|
||||
_recorder.Error += OnRecorderError;
|
||||
_recorder.SetAudioSource(AudioSource.Mic);
|
||||
_recorder.SetOutputFormat(OutputFormat.AacAdts);
|
||||
_recorder.SetAudioSamplingRate(48000);
|
||||
_recorder.SetAudioChannels(1);
|
||||
_recorder.SetAudioEncodingBitRate(96000);
|
||||
_recorder.SetAudioEncoder(AudioEncoder.Aac);
|
||||
var pipe = ParcelFileDescriptor.CreatePipe()
|
||||
?? throw new IOException("Creation du canal microphone impossible.");
|
||||
_readPipe = pipe[0];
|
||||
_writePipe = pipe[1];
|
||||
_recorder.SetOutputFile(_writePipe.FileDescriptor);
|
||||
await Task.Run(_recorder.Prepare, ct);
|
||||
await output(_readPipe.Fd, ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_stopRequested) throw new System.OperationCanceledException("Demarrage de la capture annule.");
|
||||
await Task.Run(_recorder.Start, ct);
|
||||
_started = true;
|
||||
_writePipe.Close();
|
||||
_writePipe.Dispose();
|
||||
_writePipe = null;
|
||||
}
|
||||
finally { _stopGate.Release(); }
|
||||
}
|
||||
|
||||
private async Task StartNativeAsync(string cameraId, bool microphone,
|
||||
Func<Stream, CancellationToken, Task>? output,
|
||||
Func<int, CancellationToken, Task>? pipeOutput, CancellationToken ct, bool blur)
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ public sealed class PodcastCaptureService : Service
|
|||
internal AndroidPodcastCapture? Capture { get; set; }
|
||||
|
||||
public static async Task<PodcastCaptureService> StartAsync(Activity activity, bool microphone,
|
||||
CancellationToken ct, bool call = false)
|
||||
CancellationToken ct, bool call = false, bool camera = true)
|
||||
{
|
||||
if (_pending is not null) throw new InvalidOperationException("Un direct Android est deja en cours.");
|
||||
var pending = new TaskCompletionSource<PodcastCaptureService>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
|
@ -30,7 +30,7 @@ public sealed class PodcastCaptureService : Service
|
|||
try
|
||||
{
|
||||
var intent = new Intent(activity, typeof(PodcastCaptureService))
|
||||
.PutExtra("microphone", microphone).PutExtra("call", call);
|
||||
.PutExtra("microphone", microphone).PutExtra("call", call).PutExtra("camera", camera);
|
||||
activity.StartForegroundService(intent);
|
||||
return await pending.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
}
|
||||
|
|
@ -68,8 +68,10 @@ public sealed class PodcastCaptureService : Service
|
|||
var builder = new NotificationCompat.Builder(this, Channel);
|
||||
builder.SetSmallIcon(global::Android.Resource.Drawable.IcMenuCamera);
|
||||
var call = intent?.GetBooleanExtra("call", false) == true;
|
||||
builder.SetContentTitle(call ? "Appel audio-video LAN/VPN" : "Podcast en direct");
|
||||
builder.SetContentText(call ? "Camera et microphone actifs. Toucher pour revenir a l'appel."
|
||||
var camera = intent?.GetBooleanExtra("camera", true) != false;
|
||||
builder.SetContentTitle(call ? camera ? "Appel audio-video LAN/VPN" : "Appel audio LAN/VPN" : "Podcast en direct");
|
||||
builder.SetContentText(call ? camera ? "Camera et microphone actifs. Toucher pour revenir a l'appel."
|
||||
: "Avatar et microphone actifs. Toucher pour revenir a l'appel."
|
||||
: "Camera active. Toucher pour revenir au direct.");
|
||||
builder.SetContentIntent(open);
|
||||
builder.SetOngoing(true);
|
||||
|
|
@ -78,7 +80,7 @@ public sealed class PodcastCaptureService : Service
|
|||
var type = (ForegroundService)0;
|
||||
if (OperatingSystem.IsAndroidVersionAtLeast(30))
|
||||
{
|
||||
type = ForegroundService.TypeCamera;
|
||||
if (camera) type = ForegroundService.TypeCamera;
|
||||
if (intent?.GetBooleanExtra("microphone", false) == true) type |= ForegroundService.TypeMicrophone;
|
||||
}
|
||||
ServiceCompat.StartForeground(this, NotificationId, notification, (int)type);
|
||||
|
|
|
|||
|
|
@ -32,9 +32,11 @@ internal static class PodcastPermissions
|
|||
_pending = pending;
|
||||
ActivityCompat.RequestPermissions(activity, permissions, RequestCode);
|
||||
if (!await pending.Task.WaitAsync(ct))
|
||||
throw new UnauthorizedAccessException(notifications
|
||||
throw new UnauthorizedAccessException(!camera && microphone
|
||||
? notifications ? "Autorisez le microphone et les notifications pour l'appel."
|
||||
: "Autorisez le microphone pour l'appel."
|
||||
: notifications
|
||||
? "Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser."
|
||||
: microphone && !camera ? "Autorisez le microphone pour l'appel."
|
||||
: microphone ? "Autorisez la camera et le microphone pour l'appel."
|
||||
: "Autorisez la camera pour la previsualisation.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,31 @@ public sealed class CallTransportRoutingTests
|
|||
Assert.False(webRtc.Busy);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Audio_page_keeps_srtp_avatar_call_and_received_video_available_without_camera_controls()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
await using var lan = new LanCallViewModel(signaling, loadAvatar: (_, _) => Task.FromResult<Bitmap?>(null))
|
||||
{
|
||||
RemoteVideo = new Border()
|
||||
};
|
||||
var chat = new ChatViewModel(settings: new Settings()) { LanCall = lan, IsConnected = true };
|
||||
var page = new CallPage { DataContext = new AudioCallPageViewModel(chat) };
|
||||
var window = new Window { Content = page };
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
Assert.True(page.FindControl<StackPanel>("LanCallPanel")!.IsVisible);
|
||||
Assert.False(page.FindControl<ComboBox>("LanCamera")!.IsVisible);
|
||||
Assert.False(page.FindControl<Button>("LanVideoInvite")!.IsVisible);
|
||||
Assert.True(page.FindControl<Button>("LanAudioInvite")!.IsEffectivelyVisible);
|
||||
var video = page.FindControl<ContentControl>("LanRemoteVideo")!;
|
||||
Assert.True(video.IsEffectivelyVisible);
|
||||
Assert.Same(lan.RemoteVideo, video.Content);
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Audio_page_shows_static_image_and_hides_video_and_srtp_controls()
|
||||
{
|
||||
|
|
@ -204,6 +229,8 @@ public sealed class CallTransportRoutingTests
|
|||
throw new NotSupportedException();
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException();
|
||||
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException();
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
public Task EndAsync(Guid callId, CancellationToken ct = default)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -34,14 +34,15 @@ public sealed class AndroidLanCallTestActivity : Activity
|
|||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(55));
|
||||
var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true", timeout.Token);
|
||||
var outcome = await RunAsync(result, Intent?.GetStringExtra("wrongKey") == "true",
|
||||
Intent?.GetStringExtra("avatar") == "true", timeout.Token);
|
||||
File.WriteAllText(result, outcome);
|
||||
}
|
||||
catch (Exception error) { File.WriteAllText(result, "FAIL\n" + error); }
|
||||
finally { Finish(); }
|
||||
}
|
||||
|
||||
private async Task<string> RunAsync(string result, bool wrongKey, CancellationToken ct)
|
||||
private async Task<string> RunAsync(string result, bool wrongKey, bool avatar, CancellationToken ct)
|
||||
{
|
||||
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
|
||||
while (!MainActivity.IsForeground || (Avalonia.Application.Current as App)?.View == null)
|
||||
|
|
@ -60,6 +61,7 @@ public sealed class AndroidLanCallTestActivity : Activity
|
|||
var navigation = app.View!.FindControl<NavigationPage>("NavRoot")
|
||||
?? throw new InvalidOperationException("Main navigation unavailable.");
|
||||
var attached = false;
|
||||
var imagePath = Path.Combine(CacheDir!.AbsolutePath, $"lan-call-avatar-{Guid.NewGuid():N}.png");
|
||||
try
|
||||
{
|
||||
await peer.StartReceivingAsync(ct);
|
||||
|
|
@ -87,20 +89,30 @@ public sealed class AndroidLanCallTestActivity : Activity
|
|||
File.WriteAllText(result, "RUNNING\nstage=return SRTP sender");
|
||||
await peer.StartEncodedSendingAsync(call.Endpoint,
|
||||
pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32(), ct);
|
||||
File.WriteAllText(result, "RUNNING\nstage=enumerating cameras");
|
||||
var devices = AndroidLanCallMedia.GetDevices();
|
||||
var front = devices.Cameras.FirstOrDefault(c => c.Name == "Camera avant")
|
||||
?? throw new InvalidOperationException("Front camera required; no rear-camera fallback.");
|
||||
var endpoint = wrongKey ? peer.Endpoint with { Key = new string('0', 32) } : peer.Endpoint;
|
||||
File.WriteAllText(result, "RUNNING\nstage=front camera and SRTP");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => call.StartSendingAsync(endpoint, front.Value, "microphone", ct));
|
||||
if (avatar)
|
||||
{
|
||||
using var image = PostIt.Helpers.ImageHelper.LoadFromResource(new Uri("avares://PostIt/Assets/Icon.png"));
|
||||
image.Save(imagePath, Avalonia.Media.Imaging.PngBitmapEncoderOptions.Default);
|
||||
File.WriteAllText(result, "RUNNING\nstage=avatar, microphone and SRTP without camera");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => call.StartAvatarSendingAsync(endpoint, imagePath, "microphone", ct));
|
||||
}
|
||||
else
|
||||
{
|
||||
File.WriteAllText(result, "RUNNING\nstage=enumerating cameras");
|
||||
var devices = AndroidLanCallMedia.GetDevices();
|
||||
var front = devices.Cameras.FirstOrDefault(c => c.Name == "Camera avant")
|
||||
?? throw new InvalidOperationException("Front camera required; no rear-camera fallback.");
|
||||
File.WriteAllText(result, "RUNNING\nstage=front camera and SRTP");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => call.StartSendingAsync(endpoint, front.Value, "microphone", ct));
|
||||
}
|
||||
File.WriteAllText(result, "RUNNING\nstage=receiving camera and return media");
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
while (elapsed.Elapsed < TimeSpan.FromSeconds(wrongKey ? 10 : 25))
|
||||
{
|
||||
if (call.Completion.IsCompleted) await call.Completion;
|
||||
if (peer.Completion.IsCompleted) await peer.Completion;
|
||||
if (!wrongKey && elapsed.Elapsed >= TimeSpan.FromSeconds(10) &&
|
||||
if (!wrongKey && elapsed.Elapsed >= TimeSpan.FromSeconds(12) &&
|
||||
decoded.Frames >= 100 && decoded.Samples > 144000 && call.HasRemoteMedia) break;
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
|
|
@ -108,9 +120,9 @@ public sealed class AndroidLanCallTestActivity : Activity
|
|||
if (wrongKey ? decoded.Frames != 0 || decoded.Samples != 0
|
||||
: decoded.Frames < 100 || decoded.Samples <= 144000)
|
||||
throw new IOException($"Unexpected camera decode: frames={decoded.Frames}, samples={decoded.Samples}.");
|
||||
return $"PASS\nfrontCamera=true\nwrongKey={wrongKey}\n" +
|
||||
return $"PASS\nfrontCamera={!avatar}\navatar={avatar}\nwrongKey={wrongKey}\n" +
|
||||
$"cameraFrames={decoded.Frames}\ncameraAudioSamples={decoded.Samples}\nelapsedMs={elapsed.ElapsedMilliseconds}\nreturnAudioVideo=true\n" +
|
||||
"transport=SRTP/UDP loopback\npreview=attached\nsource=camera+microphone,return=explicit fixture\ncleanup=complete";
|
||||
$"transport=SRTP/UDP loopback\npreview=attached\nsource={(avatar ? "avatar" : "camera")}+microphone,return=explicit fixture\ncleanup=complete";
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -123,6 +135,7 @@ public sealed class AndroidLanCallTestActivity : Activity
|
|||
}
|
||||
File.WriteAllText(result, "RUNNING\nstage=dispose call");
|
||||
if (call != null) await Dispatcher.UIThread.InvokeAsync(async () => await call.DisposeAsync());
|
||||
File.Delete(imagePath);
|
||||
File.WriteAllText(result, "RUNNING\nstage=stop return peer");
|
||||
await peer.StopAsync();
|
||||
source.Dispose();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
using Avalonia.Controls;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Media.Imaging;
|
||||
using PostIt.Helpers;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels.Chat;
|
||||
using PostIt.ViewModels;
|
||||
|
|
@ -115,21 +117,102 @@ public sealed class LanCallViewModelTests
|
|||
return vm;
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Call_without_camera_sends_own_avatar_and_microphone_and_cleans_up(bool caller)
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var media = new FakeMedia();
|
||||
string? avatarUser = null;
|
||||
await using var vm = new LanCallViewModel(signaling, (_, _) => media, loadAvatar: (user, _) =>
|
||||
{
|
||||
avatarUser = user;
|
||||
return Task.FromResult<Bitmap?>(ImageHelper.LoadFromResource(new Uri("avares://PostIt/Assets/Icon.png")));
|
||||
})
|
||||
{
|
||||
Address = "127.0.0.1", Microphone = new("Mic", "default"),
|
||||
AllowAddressDisclosure = true, Room = "General", Target = "bob"
|
||||
};
|
||||
vm.Addresses.Add("127.0.0.1");
|
||||
if (caller) await vm.InviteAudioCommand.ExecuteAsync(null);
|
||||
else
|
||||
{
|
||||
signaling.Invite(vm, signaling.Call with { DisplayMode = CallDisplayMode.AudioOnly });
|
||||
await WaitAsync(() => vm.Incoming);
|
||||
await vm.AcceptCommand.ExecuteAsync(null);
|
||||
}
|
||||
Assert.True(vm.AudioOnly);
|
||||
Assert.Null(vm.Camera);
|
||||
if (caller) signaling.Ready();
|
||||
await WaitAsync(() => signaling.Sent.Count > 0);
|
||||
Assert.Equal(caller ? "alice" : "bob", avatarUser);
|
||||
Assert.Same(media.LocalVideo, vm.LocalVideo);
|
||||
Assert.Same(media.RemoteVideo, vm.RemoteVideo);
|
||||
Assert.False(media.Sending);
|
||||
signaling.RemoteEndpoint(signaling.Call.Id);
|
||||
await WaitAsync(() => media.Sending);
|
||||
Assert.Null(media.Camera);
|
||||
var imagePath = Assert.IsType<string>(media.AvatarPath);
|
||||
Assert.True(File.Exists(imagePath));
|
||||
await vm.HangupAsync();
|
||||
Assert.True(media.Disposed);
|
||||
Assert.False(File.Exists(imagePath));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Audio_only_invitation_on_srtp_is_rejected_without_opening_media()
|
||||
public async Task Unavailable_own_avatar_ends_call_without_opening_media_or_camera()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var created = false;
|
||||
await using var vm = Configure(signaling, (_, _) =>
|
||||
await using var vm = new LanCallViewModel(signaling, (_, _) =>
|
||||
{
|
||||
created = true;
|
||||
return new FakeMedia();
|
||||
});
|
||||
signaling.Invite(vm, signaling.Call with { DisplayMode = CallDisplayMode.AudioOnly });
|
||||
await WaitAsync(() => signaling.EndedCalls.Count != 0);
|
||||
}, loadAvatar: (_, _) => Task.FromResult<Bitmap?>(null))
|
||||
{
|
||||
Address = "127.0.0.1", Microphone = new("Mic", "default"),
|
||||
AllowAddressDisclosure = true, Room = "General", Target = "bob"
|
||||
};
|
||||
vm.Addresses.Add("127.0.0.1");
|
||||
await vm.InviteAudioCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => !vm.Busy);
|
||||
Assert.False(created);
|
||||
Assert.Empty(signaling.Sent);
|
||||
Assert.Contains("avatar est indisponible", vm.Status);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Hangup_cancels_pending_avatar_download_without_opening_media()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var loading = false;
|
||||
var created = false;
|
||||
await using var vm = new LanCallViewModel(signaling, (_, _) =>
|
||||
{
|
||||
created = true;
|
||||
return new FakeMedia();
|
||||
}, loadAvatar: async (_, ct) =>
|
||||
{
|
||||
loading = true;
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
return null;
|
||||
})
|
||||
{
|
||||
Address = "127.0.0.1", Microphone = new("Mic", "default"),
|
||||
AllowAddressDisclosure = true, Room = "General", Target = "bob"
|
||||
};
|
||||
vm.Addresses.Add("127.0.0.1");
|
||||
await vm.InviteAudioCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => loading);
|
||||
await vm.HangupAsync().WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
|
||||
Assert.False(created);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains("audio seul", vm.Status);
|
||||
Assert.Empty(signaling.Sent);
|
||||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
|
|
@ -331,11 +414,20 @@ public sealed class LanCallViewModelTests
|
|||
public bool Sending { get; private set; }
|
||||
public bool Disposed { get; private set; }
|
||||
public bool DelayStartup { get; init; }
|
||||
public string? Camera { get; private set; }
|
||||
public string? AvatarPath { get; private set; }
|
||||
public async Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct)
|
||||
{
|
||||
Sending = true;
|
||||
Camera = camera;
|
||||
if (DelayStartup) await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
public Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct)
|
||||
{
|
||||
Sending = true;
|
||||
AvatarPath = imagePath;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public void Fail() => _completion.TrySetException(new IOException("test media failure"));
|
||||
public ValueTask DisposeAsync() { Disposed = true; _completion.TrySetResult(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
|
|
@ -347,18 +439,24 @@ public sealed class LanCallViewModelTests
|
|||
public event Action<CallEnded>? Ended;
|
||||
public event Action<Guid, CallSignal>? Signal;
|
||||
public event Action? Interrupted;
|
||||
public CallSession Call { get; } = Session();
|
||||
public CallSession Call { get; private set; } = Session();
|
||||
public List<CallSignal> Sent { get; } = [];
|
||||
public List<Guid> EndedCalls { get; } = [];
|
||||
public int Invites { get; private set; }
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default)
|
||||
{ Invites++; return Task.FromResult(Call); }
|
||||
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
Invites++;
|
||||
Call = Call with { DisplayMode = CallDisplayMode.AudioOnly };
|
||||
return Task.FromResult(Call);
|
||||
}
|
||||
public Task AcceptAsync(Guid id, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
|
||||
public Task EndAsync(Guid id, CancellationToken ct = default)
|
||||
{ EndedCalls.Add(id); Ended?.Invoke(new(id, "hangup")); return Task.CompletedTask; }
|
||||
public Task SendAsync(Guid id, CallSignal signal, CancellationToken ct = default)
|
||||
{ Sent.Add(signal); return Task.CompletedTask; }
|
||||
public void Invite(LanCallViewModel _, CallSession call) => Invitation?.Invoke(call);
|
||||
public void Invite(LanCallViewModel _, CallSession call) { Call = call; Invitation?.Invoke(call); }
|
||||
public void Ready() => Accepted?.Invoke(new(Call, []));
|
||||
public void RemoteEndpoint(Guid id) => Signal?.Invoke(id, new("rtp-endpoint",
|
||||
Endpoint: new("127.0.0.1", 5006, new string('c', 32), new string('d', 28))));
|
||||
|
|
|
|||
|
|
@ -17,6 +17,120 @@ public sealed class LinuxLanCallMediaTests(ITestOutputHelper output)
|
|||
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_MEDIA"));
|
||||
public static bool HasTsFixture => OperatingSystem.IsLinux() &&
|
||||
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_TS"));
|
||||
public static bool HasAudioFixture => OperatingSystem.IsLinux() &&
|
||||
(File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO")) ||
|
||||
!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO_SOURCE"))) &&
|
||||
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE"));
|
||||
public static bool HasAacFixture => OperatingSystem.IsLinux() &&
|
||||
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_AAC")) &&
|
||||
File.Exists(Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE"));
|
||||
|
||||
[Theory(Skip = "Set POSTIT_TEST_AAC to ADTS and POSTIT_TEST_IMAGE to an avatar; requires Linux LibVLC SRTP.",
|
||||
SkipUnless = nameof(HasAacFixture))]
|
||||
[InlineData("127.0.0.1")]
|
||||
[InlineData("::1")]
|
||||
public async Task Avatar_video_and_live_aac_pipe_use_the_same_libvlc_pipeline(string address)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var port = FreePort(address: address);
|
||||
await using var sender = new LibVlcLanCallMedia(address, port, headless: true);
|
||||
await using var receiver = new LibVlcLanCallMedia(address, FreePort(port, address), headless: true);
|
||||
using var decoded = new DecodedVideo(receiver.Receiver);
|
||||
using var pipe = new AnonymousPipeServerStream(PipeDirection.Out);
|
||||
await using var source = File.OpenRead(Environment.GetEnvironmentVariable("POSTIT_TEST_AAC")!);
|
||||
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var pump = Task.Run(async () =>
|
||||
{
|
||||
var buffer = new byte[512];
|
||||
while (await source.ReadAsync(buffer, lifetime.Token) is var count && count > 0)
|
||||
{
|
||||
await pipe.WriteAsync(buffer.AsMemory(0, count), lifetime.Token);
|
||||
await Task.Delay(40, lifetime.Token);
|
||||
}
|
||||
}, ct);
|
||||
try
|
||||
{
|
||||
await receiver.StartReceivingAsync(ct);
|
||||
await sender.StartAvatarSendingAsync(receiver.Endpoint,
|
||||
Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE")!,
|
||||
$"fd/aac://{pipe.ClientSafePipeHandle.DangerousGetHandle().ToInt32()}", ct);
|
||||
await Task.Delay(TimeSpan.FromSeconds(12), ct);
|
||||
if (sender.Completion.IsCompleted) await sender.Completion;
|
||||
if (receiver.Completion.IsCompleted) await receiver.Completion;
|
||||
Assert.True(receiver.HasRemoteMedia);
|
||||
var frames = decoded.Frames;
|
||||
var samples = decoded.AudioSamples;
|
||||
await Task.Delay(1500, ct);
|
||||
Assert.True(decoded.Frames > frames);
|
||||
Assert.True(decoded.AudioSamples > samples);
|
||||
}
|
||||
finally
|
||||
{
|
||||
lifetime.Cancel();
|
||||
await sender.StopAsync();
|
||||
try { await pump; }
|
||||
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
|
||||
}
|
||||
}
|
||||
|
||||
[Theory(Skip = "Set POSTIT_TEST_AUDIO to WAV and POSTIT_TEST_IMAGE to an avatar; requires Linux LibVLC SRTP.",
|
||||
SkipUnless = nameof(HasAudioFixture))]
|
||||
[InlineData("127.0.0.1", false)]
|
||||
[InlineData("::1", false)]
|
||||
[InlineData("127.0.0.1", true)]
|
||||
[InlineData("::1", true)]
|
||||
public async Task Two_peers_receive_avatar_video_and_audio_beyond_default_image_duration_and_reject_wrong_keys(
|
||||
string address, bool wrongKey)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var port = FreePort(address: address);
|
||||
await using var first = new LibVlcLanCallMedia(address, port, headless: true);
|
||||
await using var second = new LibVlcLanCallMedia(address, FreePort(port, address), headless: true);
|
||||
using var firstDecoded = new DecodedVideo(first.Receiver);
|
||||
using var secondDecoded = new DecodedVideo(second.Receiver);
|
||||
await first.StartReceivingAsync(ct);
|
||||
await second.StartReceivingAsync(ct);
|
||||
var image = Environment.GetEnvironmentVariable("POSTIT_TEST_IMAGE")!;
|
||||
var audio = Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO_SOURCE");
|
||||
if (string.IsNullOrEmpty(audio))
|
||||
{
|
||||
var uri = new Uri(Path.GetFullPath(Environment.GetEnvironmentVariable("POSTIT_TEST_AUDIO")!)).AbsoluteUri;
|
||||
audio = "file/wav:" + uri["file:".Length..];
|
||||
}
|
||||
await first.StartAvatarSendingAsync(wrongKey ? second.Endpoint with { Key = new string('0', 32) }
|
||||
: second.Endpoint, image, audio, ct);
|
||||
await second.StartAvatarSendingAsync(first.Endpoint, image, audio, ct);
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
while (elapsed.Elapsed < TimeSpan.FromSeconds(12))
|
||||
{
|
||||
if (first.Completion.IsCompleted) await first.Completion;
|
||||
if (second.Completion.IsCompleted) await second.Completion;
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
var frames = firstDecoded.Frames;
|
||||
var samples = firstDecoded.AudioSamples;
|
||||
var secondFrames = secondDecoded.Frames;
|
||||
var secondSamples = secondDecoded.AudioSamples;
|
||||
await Task.Delay(1500, ct);
|
||||
output.WriteLine($"First: decoded={first.Statistics.DecodedAudio}, samples={firstDecoded.AudioSamples}; " +
|
||||
$"second: decoded={second.Statistics.DecodedAudio}, samples={secondDecoded.AudioSamples}");
|
||||
Assert.True(first.HasRemoteMedia);
|
||||
Assert.True(firstDecoded.AudioSamples > 4800);
|
||||
Assert.True(firstDecoded.Frames > frames);
|
||||
Assert.True(firstDecoded.AudioSamples > samples);
|
||||
if (wrongKey)
|
||||
{
|
||||
Assert.False(second.HasRemoteMedia);
|
||||
Assert.Equal(0, secondDecoded.AudioSamples);
|
||||
Assert.Equal(0, secondDecoded.Frames);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.True(second.HasRemoteMedia);
|
||||
Assert.True(secondDecoded.AudioSamples > secondSamples);
|
||||
Assert.True(secondDecoded.Frames > secondFrames);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory(Skip = "Requires Linux LibVLC.", SkipUnless = nameof(HasFixture))]
|
||||
[InlineData("127.0.0.1")]
|
||||
|
|
|
|||
|
|
@ -354,6 +354,8 @@ public sealed class WebRtcCallViewModelTests
|
|||
}
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("Legacy LAN transport must not be used");
|
||||
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("Legacy LAN transport must not be used");
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
|
||||
public Task EndAsync(Guid callId, CancellationToken ct = default)
|
||||
{ EndedCalls.Add(callId); return Task.CompletedTask; }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Platform;
|
||||
|
|
@ -16,13 +17,13 @@ public static class ImageHelper
|
|||
return new Bitmap(AssetLoader.Open(resourceUri));
|
||||
}
|
||||
|
||||
public static async Task<Bitmap?> LoadFromWeb(Uri url)
|
||||
public static async Task<Bitmap?> LoadFromWeb(Uri url, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await HttpClient.GetAsync(url).ConfigureAwait(false);
|
||||
using var response = await HttpClient.GetAsync(url, ct).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
|
||||
var data = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
|
||||
return new Bitmap(new MemoryStream(data));
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
|
|
|
|||
|
|
@ -45,6 +45,12 @@ public sealed class CallSignalingClient : IWebRtcCallSignaling, IDisposable
|
|||
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLan, room, user, ct);
|
||||
}
|
||||
|
||||
public Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLanAudio, room, user, ct);
|
||||
}
|
||||
|
||||
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
|
|
|
|||
|
|
@ -144,6 +144,8 @@ public sealed class ChatHubConnection : IAsyncDisposable
|
|||
connection.InvokeAsync(CallHubMethods.SetContactPreferences,
|
||||
new ContactPreferences(_api.Settings.AllowAudioCalls, _api.Settings.AllowVideoCalls,
|
||||
_api.Settings.AllowPrivateMessages, Platform.CreateWebRtcMedia != null ||
|
||||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()),
|
||||
Platform.CreateLanCallMedia != null ||
|
||||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid())), ct);
|
||||
|
||||
public async Task StopAsync(CancellationToken ct = default)
|
||||
|
|
|
|||
|
|
@ -14,4 +14,5 @@ public interface ILanCallMedia : IAsyncDisposable
|
|||
Task Completion { get; }
|
||||
bool HasRemoteMedia { get; }
|
||||
Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct);
|
||||
Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ public interface ILanCallSignaling
|
|||
event Action<Guid, CallSignal>? Signal;
|
||||
event Action? Interrupted;
|
||||
Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default);
|
||||
Task<CallSession> InviteLanAudioAsync(string room, string user, CancellationToken ct = default);
|
||||
Task AcceptAsync(Guid callId, CancellationToken ct = default);
|
||||
Task EndAsync(Guid callId, CancellationToken ct = default);
|
||||
Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
|
|
@ -99,6 +100,28 @@ public sealed class LibVlcLanCallMedia : IAsyncDisposable
|
|||
public Task StartSendingAsync(LanCallEndpoint remote, string camera, string microphone, CancellationToken ct) =>
|
||||
StartSendingAsync(remote, vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), true, ct);
|
||||
|
||||
public Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string audioSource, CancellationToken ct) =>
|
||||
StartSendingAsync(remote, vlc => CreateAvatarMedia(vlc, imagePath, audioSource), false, ct);
|
||||
|
||||
internal static Media CreateAvatarMedia(LibVLC vlc, string imagePath, string audioSource)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(imagePath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(audioSource);
|
||||
if (!File.Exists(imagePath)) throw new FileNotFoundException("Avatar d'appel introuvable.", imagePath);
|
||||
var uri = new Uri(Path.GetFullPath(imagePath)).AbsoluteUri;
|
||||
var imageSource = "file/image:" + uri["file:".Length..];
|
||||
// Pulse uses wall-clock timestamps; ADTS/file inputs start at zero and clock the image slave.
|
||||
var realtime = audioSource.StartsWith("pulse://", StringComparison.Ordinal);
|
||||
var media = new Media(vlc, realtime ? imageSource : audioSource, FromType.FromLocation);
|
||||
media.AddOption(":image-duration=-1");
|
||||
media.AddOption(":image-fps=30/1");
|
||||
media.AddOption(":image-chroma=I420");
|
||||
if (realtime) media.AddOption(":image-realtime");
|
||||
media.AddOption(":input-slave=" + (realtime ? audioSource : imageSource));
|
||||
media.AddOption(":live-caching=200");
|
||||
return media;
|
||||
}
|
||||
|
||||
internal async Task StartSendingAsync(LanCallEndpoint remote, Func<LibVLC, Media> source,
|
||||
bool preview, CancellationToken ct, bool transcode = true)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ using System;
|
|||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Threading;
|
||||
using LibVLCSharp.Avalonia;
|
||||
using Yavsc.Abstract.Chat.Calls;
|
||||
|
|
@ -12,6 +14,8 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
|
|||
{
|
||||
private readonly LibVlcLanCallMedia _media;
|
||||
private readonly VideoView _local;
|
||||
private readonly ContentControl _localContent;
|
||||
private Bitmap? _avatar;
|
||||
private readonly VideoView _remote;
|
||||
private readonly TaskCompletionSource _localReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
|
|
@ -20,7 +24,7 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
|
|||
private bool _disposed;
|
||||
private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public Control LocalVideo => _local;
|
||||
public Control LocalVideo => _localContent;
|
||||
public Control RemoteVideo => _remote;
|
||||
public LanCallEndpoint Endpoint => _media.Endpoint;
|
||||
public Task Completion { get; }
|
||||
|
|
@ -30,6 +34,12 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
|
|||
{
|
||||
_media = new LibVlcLanCallMedia(localAddress, port);
|
||||
_local = new VideoView { MediaPlayer = _media.Sender, MinHeight = 140 };
|
||||
_localContent = new ContentControl
|
||||
{
|
||||
Content = _local,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Stretch,
|
||||
VerticalContentAlignment = VerticalAlignment.Stretch
|
||||
};
|
||||
_remote = new VideoView { MediaPlayer = _media.Receiver, MinHeight = 260 };
|
||||
_local.LayoutUpdated += OnLocalLayout;
|
||||
_remote.LayoutUpdated += OnRemoteLayout;
|
||||
|
|
@ -81,6 +91,16 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
|
|||
await _media.StartSendingAsync(remote, camera, microphone, ct);
|
||||
}
|
||||
|
||||
public async Task StartAvatarSendingAsync(LanCallEndpoint remote, string imagePath, string microphone, CancellationToken ct)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_avatar != null) throw new InvalidOperationException("La capture de cet appel est deja demarree.");
|
||||
_avatar = new Bitmap(imagePath);
|
||||
_local.MediaPlayer = null;
|
||||
_localContent.Content = new Image { Source = _avatar, Height = 140 };
|
||||
await _media.StartAvatarSendingAsync(remote, imagePath, $"pulse://{microphone}", ct);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
|
@ -94,6 +114,8 @@ public sealed class LinuxLanCallVideo : ILanCallMedia
|
|||
{
|
||||
_local.MediaPlayer = null;
|
||||
_remote.MediaPlayer = null;
|
||||
_localContent.Content = null;
|
||||
_avatar?.Dispose();
|
||||
try { await _media.DisposeAsync(); }
|
||||
finally
|
||||
{
|
||||
|
|
|
|||
|
|
@ -4,5 +4,7 @@ public sealed class AudioCallPageViewModel(ChatViewModel chat) : CallPageViewMod
|
|||
{
|
||||
public override string Header => "Appel audio";
|
||||
public override bool IsAudioPage => true;
|
||||
public override string Description => "Appel audio WebRTC. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel.";
|
||||
public override string Description => Chat.LanCall?.SupportsAudioOnly == true
|
||||
? "Appel audio WebRTC ou SRTP direct. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel."
|
||||
: "Appel audio WebRTC. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel.";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ public class CallPageViewModel(ChatViewModel chat) : ViewModelBase
|
|||
{
|
||||
public virtual string Header => "Appel audio-video";
|
||||
public virtual bool IsAudioPage => false;
|
||||
public bool ShowLanCalls => !IsAudioPage && Chat.SupportsLanCalls;
|
||||
public bool ShowLanCalls => Chat.SupportsLanCalls && (!IsAudioPage || Chat.LanCall?.SupportsAudioOnly == true);
|
||||
public virtual string Description => "Choisissez WebRTC ou SRTP direct. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel.";
|
||||
public ChatViewModel Chat { get; } = chat;
|
||||
public override bool CanNavigateNext { get; protected set; } = false;
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ namespace PostIt.ViewModels.Chat
|
|||
public partial WebRtcCallViewModel? VideoCall { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(OpenAudioCallCommand), nameof(ShowCallCommand))]
|
||||
public partial LanCallViewModel? LanCall { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
|
|
@ -191,7 +191,7 @@ namespace PostIt.ViewModels.Chat
|
|||
[RelayCommand(CanExecute = nameof(CanOpenAudioCall))]
|
||||
private Task OpenAudioCallAsync() => NavigateToCallAsync(configureTarget: true, audio: true);
|
||||
|
||||
private bool CanOpenAudioCall() => CanOpenCall() && VideoCall != null;
|
||||
private bool CanOpenAudioCall() => CanOpenCall() && (VideoCall != null || LanCall?.SupportsAudioOnly == true);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanShowCall))]
|
||||
private Task ShowCallAsync() => NavigateToCallAsync(configureTarget: false);
|
||||
|
|
@ -202,7 +202,8 @@ namespace PostIt.ViewModels.Chat
|
|||
{
|
||||
var app = App.Current as App ?? throw new InvalidOperationException("Application indisponible.");
|
||||
var page = configureTarget ? PrepareCallPage() : new CallPageViewModel(this);
|
||||
if (VideoCall?.Busy == true ? VideoCall.AudioOnly : audio && LanCall?.Busy != true)
|
||||
if (VideoCall?.Busy == true ? VideoCall.AudioOnly :
|
||||
LanCall?.Busy == true ? LanCall.AudioOnly : audio)
|
||||
page = new AudioCallPageViewModel(this);
|
||||
await app.PushPageAsync(page);
|
||||
}
|
||||
|
|
@ -411,16 +412,20 @@ namespace PostIt.ViewModels.Chat
|
|||
// Le hub est [Authorize] : on attache le Bearer OIDC.
|
||||
|
||||
Calls = new CallSignalingClient(_connection);
|
||||
var avatars = new ActivityApiClient(_api, () => _settings.ApiUrl,
|
||||
() => _settings.Authentication.Authority);
|
||||
Task<Avalonia.Media.Imaging.Bitmap?> LoadAvatar(string user) =>
|
||||
ImageHelper.LoadFromWeb(new Uri(avatars.BuildAvatarXsUrl(user)));
|
||||
if (SupportsVideoCalls)
|
||||
{
|
||||
var avatars = new ActivityApiClient(_api, () => _settings.ApiUrl,
|
||||
() => _settings.Authentication.Authority);
|
||||
VideoCall = new WebRtcCallViewModel(Calls, settings: _settings,
|
||||
loadAvatar: user => ImageHelper.LoadFromWeb(new Uri(avatars.BuildAvatarXsUrl(user))))
|
||||
loadAvatar: LoadAvatar)
|
||||
{ Room = SelectedRoom ?? "" };
|
||||
}
|
||||
if (SupportsLanCalls)
|
||||
LanCall = new LanCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" };
|
||||
LanCall = new LanCallViewModel(Calls, settings: _settings,
|
||||
loadAvatar: (user, token) => ImageHelper.LoadFromWeb(new Uri(avatars.BuildAvatarXsUrl(user)), token))
|
||||
{ Room = SelectedRoom ?? "" };
|
||||
Calls.Invitation += call =>
|
||||
{
|
||||
if ((call.Transport == Yavsc.Abstract.Chat.Calls.CallTransports.LanSrtp && !SupportsLanCalls) ||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,15 @@
|
|||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
|
@ -19,6 +22,8 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
{
|
||||
private readonly ILanCallSignaling _signaling;
|
||||
private readonly Func<string, int, ILanCallMedia> _createMedia;
|
||||
private readonly Func<string, CancellationToken, Task<Bitmap?>>? _loadAvatar;
|
||||
private string? _avatarPath;
|
||||
private readonly SemaphoreSlim _events = new(1);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private CancellationTokenSource? _callLifetime;
|
||||
|
|
@ -26,6 +31,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
private CallSession? _call;
|
||||
private bool _disposed;
|
||||
private bool _accepting;
|
||||
private bool _caller;
|
||||
private bool _endpointReceived;
|
||||
private string? _activeCamera;
|
||||
private string? _activeMicrophone;
|
||||
|
|
@ -48,18 +54,23 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
[ObservableProperty] public partial string Status { get; set; } = "Appel LAN/VPN : aucun appel.";
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure))]
|
||||
public partial bool Incoming { get; set; }
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure))]
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure)), NotifyPropertyChangedFor(nameof(IsAudioCall))]
|
||||
public partial bool Busy { get; set; }
|
||||
[ObservableProperty] public partial bool Preparing { get; set; }
|
||||
[ObservableProperty] public partial Control? LocalVideo { get; set; }
|
||||
[ObservableProperty] public partial Control? RemoteVideo { get; set; }
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(IsAudioCall))]
|
||||
public partial bool AudioOnly { get; set; }
|
||||
public bool IsAudioCall => Busy && AudioOnly;
|
||||
public bool SupportsAudioOnly => _loadAvatar != null;
|
||||
public bool CanConfigure => !Busy || Incoming;
|
||||
|
||||
public LanCallViewModel(ILanCallSignaling signaling, Func<string, int, ILanCallMedia>? createMedia = null,
|
||||
Settings? settings = null)
|
||||
Settings? settings = null, Func<string, CancellationToken, Task<Bitmap?>>? loadAvatar = null)
|
||||
{
|
||||
_signaling = signaling;
|
||||
_settings = settings;
|
||||
_loadAvatar = loadAvatar;
|
||||
_createMedia = createMedia ?? Platform.CreateLanCallMedia ??
|
||||
((address, port) => new LinuxLanCallVideo(address, port));
|
||||
signaling.Invitation += OnInvitation;
|
||||
|
|
@ -178,7 +189,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
foreach (var device in streamer.GetAudioCaptureDevices()) Microphones.Add(new(device.Key, device.Value));
|
||||
}
|
||||
RestoreDevices();
|
||||
Status = Cameras.Count == 0 ? "Aucune camera detectee. Verifiez les peripheriques puis actualisez."
|
||||
Status = Cameras.Count == 0 ? "Aucune camera detectee ; un appel audio seul reste possible si disponible."
|
||||
: Incoming && _call != null
|
||||
? $"{_call.Caller} propose un appel dans {_call.RoomName}. Selectionnez vos peripheriques puis acceptez ou refusez."
|
||||
: "Selectionnez le pair, l'adresse IPv4/IPv6 locale ou publique et les peripheriques. Utilisez un casque.";
|
||||
|
|
@ -197,31 +208,44 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
finally { _restoringPreferences = false; }
|
||||
}
|
||||
|
||||
private void ValidateSelection()
|
||||
private void ValidateSelection(bool audioOnly)
|
||||
{
|
||||
if (!AllowAddressDisclosure)
|
||||
throw new InvalidOperationException("Confirmez le partage de votre adresse IP avec le pair.");
|
||||
if (Camera == null || Microphone == null)
|
||||
throw new InvalidOperationException("Une camera et un microphone sont requis.");
|
||||
if (Microphone == null || (!audioOnly && Camera == null))
|
||||
throw new InvalidOperationException(audioOnly ? "Un microphone est requis."
|
||||
: "Une camera et un microphone sont requis.");
|
||||
if (audioOnly && !SupportsAudioOnly)
|
||||
throw new InvalidOperationException("Le chargement de l'avatar est indisponible pour cet appel SRTP.");
|
||||
if (Address == null || !Addresses.Contains(Address) || !LanCallNetwork.IsUnicastAddress(Address) ||
|
||||
!int.TryParse(Port, out var port) || port is < 1024 or > 65534 || port % 2 != 0)
|
||||
throw new InvalidOperationException("Selectionnez une adresse locale et un port UDP pair (1024-65534).");
|
||||
_activeCamera = Camera.Value;
|
||||
_activeCamera = audioOnly ? null : Camera!.Value;
|
||||
_activeMicrophone = Microphone.Value;
|
||||
_activeAddress = Address;
|
||||
_activePort = port;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private Task InviteAsync() => RunAsync(async () =>
|
||||
private Task InviteAsync() => InviteCoreAsync(false);
|
||||
|
||||
[RelayCommand]
|
||||
private Task InviteAudioAsync() => InviteCoreAsync(true);
|
||||
|
||||
private Task InviteCoreAsync(bool audioOnly) => RunAsync(async () =>
|
||||
{
|
||||
if (Busy) throw new InvalidOperationException("Un appel est deja en cours.");
|
||||
ValidateSelection();
|
||||
ValidateSelection(audioOnly);
|
||||
if (string.IsNullOrWhiteSpace(Target) || string.IsNullOrWhiteSpace(Room))
|
||||
throw new InvalidOperationException("Selectionnez une salle jointe et un autre utilisateur.");
|
||||
Busy = true;
|
||||
_call = await _signaling.InviteLanAsync(Room, Target.Trim(), _lifetime.Token);
|
||||
if (_call.Transport != CallTransports.LanSrtp || _call.DisplayMode != CallDisplayMode.AudioVideo)
|
||||
AudioOnly = audioOnly;
|
||||
_caller = true;
|
||||
_call = audioOnly
|
||||
? await _signaling.InviteLanAudioAsync(Room, Target.Trim(), _lifetime.Token)
|
||||
: await _signaling.InviteLanAsync(Room, Target.Trim(), _lifetime.Token);
|
||||
if (_call.Transport != CallTransports.LanSrtp ||
|
||||
_call.DisplayMode != (audioOnly ? CallDisplayMode.AudioOnly : CallDisplayMode.AudioVideo))
|
||||
throw new InvalidOperationException("Mode d'appel SRTP incompatible.");
|
||||
Status = $"Invitation envoyee a {_call.Callee} ; attente du consentement.";
|
||||
});
|
||||
|
|
@ -231,7 +255,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
{
|
||||
if (_call == null || !Incoming)
|
||||
throw new InvalidOperationException("Aucune invitation a accepter.");
|
||||
ValidateSelection();
|
||||
ValidateSelection(_call.DisplayMode == CallDisplayMode.AudioOnly);
|
||||
Incoming = false;
|
||||
_accepting = true;
|
||||
await _signaling.AcceptAsync(_call.Id, _lifetime.Token);
|
||||
|
|
@ -250,7 +274,8 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (call.Transport != CallTransports.LanSrtp) return;
|
||||
Queue(async () =>
|
||||
{
|
||||
if (call.DisplayMode != CallDisplayMode.AudioVideo)
|
||||
if (call.DisplayMode is not (CallDisplayMode.AudioVideo or CallDisplayMode.AudioOnly) ||
|
||||
(call.DisplayMode == CallDisplayMode.AudioOnly && !SupportsAudioOnly))
|
||||
{
|
||||
await _signaling.EndAsync(call.Id, _lifetime.Token);
|
||||
Status = "Le mode audio seul n'est pas disponible en SRTP.";
|
||||
|
|
@ -259,11 +284,13 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (_call != null) throw new InvalidOperationException("Invitation concurrente inattendue.");
|
||||
if (call.RelayOnly) throw new InvalidOperationException("Le mode LAN ne peut pas masquer les adresses IP.");
|
||||
_call = call;
|
||||
_caller = false;
|
||||
AudioOnly = call.DisplayMode == CallDisplayMode.AudioOnly;
|
||||
Room = call.RoomName;
|
||||
Target = call.Caller;
|
||||
Busy = true;
|
||||
Incoming = true;
|
||||
Status = $"{call.Caller} propose un appel SRTP dans {call.RoomName}. Acceptez ou refusez.";
|
||||
Status = $"{call.Caller} propose un appel {(AudioOnly ? "audio " : "")}SRTP dans {call.RoomName}. Acceptez ou refusez.";
|
||||
await Task.CompletedTask;
|
||||
});
|
||||
}
|
||||
|
|
@ -273,13 +300,24 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (_call?.Id != accepted.Session.Id) return;
|
||||
if (_media != null) throw new InvalidOperationException("Acceptation repetee.");
|
||||
if (accepted.Session.Transport != CallTransports.LanSrtp || accepted.Session.RelayOnly ||
|
||||
accepted.Session.DisplayMode != CallDisplayMode.AudioVideo ||
|
||||
accepted.Session.DisplayMode != _call.DisplayMode ||
|
||||
(Incoming && !_accepting))
|
||||
throw new InvalidOperationException("Acceptation ou politique de transport inattendue.");
|
||||
_call = accepted.Session;
|
||||
Incoming = false;
|
||||
_accepting = false;
|
||||
_callLifetime = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
if (AudioOnly)
|
||||
{
|
||||
var user = _caller ? _call.Caller : _call.Callee;
|
||||
using var avatar = await _loadAvatar!(user, _callLifetime.Token)
|
||||
?? throw new InvalidOperationException("Votre avatar est indisponible. Verifiez votre profil et reessayez.");
|
||||
_callLifetime.Token.ThrowIfCancellationRequested();
|
||||
_avatarPath = Path.Combine(Path.GetTempPath(), $"postit-call-avatar-{Guid.NewGuid():N}.png");
|
||||
using var scaled = avatar.CreateScaledBitmap(new PixelSize(320, 320), BitmapInterpolationMode.HighQuality);
|
||||
using var file = new FileStream(_avatarPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||
scaled.Save(file, PngBitmapEncoderOptions.Default);
|
||||
}
|
||||
_media = _createMedia(_activeAddress!, _activePort);
|
||||
LocalVideo = _media.LocalVideo;
|
||||
RemoteVideo = _media.RemoteVideo;
|
||||
|
|
@ -295,8 +333,12 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
signal.Endpoint?.IsValid() != true || _endpointReceived)
|
||||
throw new InvalidOperationException("Destination SRTP manquante, invalide ou repetee.");
|
||||
_endpointReceived = true;
|
||||
await _media.StartSendingAsync(signal.Endpoint, _activeCamera!, _activeMicrophone!, _callLifetime.Token);
|
||||
Status = "Emission SRTP demarree ; verification de la reception audio-video.";
|
||||
if (AudioOnly)
|
||||
await _media.StartAvatarSendingAsync(signal.Endpoint, _avatarPath!, _activeMicrophone!, _callLifetime.Token);
|
||||
else
|
||||
await _media.StartSendingAsync(signal.Endpoint, _activeCamera!, _activeMicrophone!, _callLifetime.Token);
|
||||
Status = AudioOnly ? "Emission avatar et microphone SRTP demarree ; verification de la reception audio-video."
|
||||
: "Emission SRTP demarree ; verification de la reception audio-video.";
|
||||
});
|
||||
|
||||
private void OnEnded(CallEnded ended) => QueueStop(ended.CallId, async () =>
|
||||
|
|
@ -331,7 +373,9 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
received = true;
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (_call?.Id == id) Status = "Reception audio-video SRTP etablie (LAN/VPN).";
|
||||
if (_call?.Id == id) Status = AudioOnly
|
||||
? "Reception audio-video SRTP etablie, camera remplacee par votre avatar (LAN/VPN)."
|
||||
: "Reception audio-video SRTP etablie (LAN/VPN).";
|
||||
});
|
||||
}
|
||||
if (!received && start.Elapsed > TimeSpan.FromSeconds(30))
|
||||
|
|
@ -397,14 +441,26 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
{
|
||||
LocalVideo = null;
|
||||
RemoteVideo = null;
|
||||
AudioOnly = false;
|
||||
_callLifetime?.Dispose();
|
||||
_callLifetime = null;
|
||||
Status = status;
|
||||
}
|
||||
if (notify && call != null)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
await _signaling.EndAsync(call.Id, timeout.Token);
|
||||
try
|
||||
{
|
||||
if (_avatarPath != null)
|
||||
{
|
||||
File.Delete(_avatarPath);
|
||||
_avatarPath = null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (notify && call != null)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
await _signaling.EndAsync(call.Id, timeout.Token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -63,19 +63,20 @@
|
|||
</StackPanel>
|
||||
</StackPanel>
|
||||
<StackPanel x:Name="LanCallPanel" IsVisible="{Binding ShowLanCalls}">
|
||||
<TextBlock Text="Appel audio-video direct IPv4/IPv6 SRTP (LAN/VPN ou IP publique)"
|
||||
<TextBlock Text="Appel direct IPv4/IPv6 SRTP (LAN/VPN ou IP publique)"
|
||||
FontSize="20" FontWeight="SemiBold" TextWrapping="Wrap" Margin="0,0,0,8" />
|
||||
<StackPanel DataContext="{Binding Chat.LanCall}" x:DataType="vm:LanCallViewModel"
|
||||
IsEnabled="{Binding $parent[ContentPage].((vm:CallPageViewModel)DataContext).Chat.IsConnected}" Spacing="8">
|
||||
<TextBlock Text="Connexion directe sans TURN ni traversee NAT : le pair connait votre IP. Le masquage IP doit etre desactive dans les profils des deux participants. Les medias sont chiffres par SRTP. Ouvrez le port UDP pair choisi et le suivant ; HTTPS est requis pour la signalisation. Casque recommande."
|
||||
<TextBlock Text="Connexion directe sans TURN ni traversee NAT : le pair connait votre IP. Le masquage IP doit etre desactive dans les profils des deux participants. Les medias sont chiffres par SRTP. En mode audio, votre avatar remplace la camera dans le flux video et est transmis au pair avec le microphone. Ouvrez le port UDP pair choisi et le suivant ; HTTPS est requis pour la signalisation. Casque recommande."
|
||||
TextWrapping="Wrap" />
|
||||
<WrapPanel IsEnabled="{Binding CanConfigure}" IsVisible="{Binding !RemoteVideo}">
|
||||
<Button Content="Actualiser les peripheriques" Command="{Binding RefreshDevicesCommand}" Margin="0,0,8,4" />
|
||||
<ComboBox Width="160" ItemsSource="{Binding Addresses}" SelectedItem="{Binding Address}"
|
||||
PlaceholderText="Adresse IPv4/IPv6 de cette machine" Margin="0,0,8,4" />
|
||||
<TextBox Width="80" Text="{Binding Port}" PlaceholderText="Port pair" Margin="0,0,8,4" />
|
||||
<ComboBox Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
|
||||
PlaceholderText="Camera" Margin="0,0,8,4">
|
||||
<ComboBox x:Name="LanCamera" Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
|
||||
PlaceholderText="Camera" Margin="0,0,8,4"
|
||||
IsVisible="{Binding !$parent[ContentPage].((vm:CallPageViewModel)DataContext).IsAudioPage}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="services:CaptureDevice">
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
|
|
@ -96,14 +97,17 @@
|
|||
IsChecked="{Binding AllowAddressDisclosure}" IsEnabled="{Binding CanConfigure}"
|
||||
IsVisible="{Binding !RemoteVideo}" />
|
||||
<WrapPanel>
|
||||
<Button Content="Appeler dans la salle active" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
|
||||
<Button x:Name="LanVideoInvite" Content="Appeler en audio-video" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}"
|
||||
IsVisible="{Binding !$parent[ContentPage].((vm:CallPageViewModel)DataContext).IsAudioPage}" Margin="0,0,8,4" />
|
||||
<Button x:Name="LanAudioInvite" Content="Appeler en audio" Command="{Binding InviteAudioCommand}" IsEnabled="{Binding !Busy}"
|
||||
IsVisible="{Binding SupportsAudioOnly}" Margin="0,0,8,4" />
|
||||
<Button Content="Accepter" Command="{Binding AcceptCommand}" IsEnabled="{Binding Incoming}" Margin="0,0,8,4" />
|
||||
<Button Content="Refuser / Raccrocher" Command="{Binding HangupCommand}" IsEnabled="{Binding Busy}" Margin="0,0,8,4" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
|
||||
<Grid ColumnDefinitions="*,2*" Height="280" IsVisible="{Binding !!RemoteVideo}">
|
||||
<ContentControl Content="{Binding LocalVideo}" Margin="0,0,8,0" />
|
||||
<ContentControl Grid.Column="1" Content="{Binding RemoteVideo}" />
|
||||
<ContentControl x:Name="LanRemoteVideo" Grid.Column="1" Content="{Binding RemoteVideo}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ public static class CallHubMethods
|
|||
public const string Invite = "InviteCall";
|
||||
public const string InviteAudio = "InviteAudioCall";
|
||||
public const string InviteLan = "InviteLanCall";
|
||||
public const string InviteLanAudio = "InviteLanAudioCall";
|
||||
public const string Accept = "AcceptCall";
|
||||
public const string End = "EndCall";
|
||||
public const string Signal = "SendCallSignal";
|
||||
|
|
@ -18,7 +19,7 @@ public static class CallHubMethods
|
|||
}
|
||||
|
||||
public sealed record ContactPreferences(bool AllowAudioCalls, bool AllowVideoCalls, bool AllowPrivateMessages,
|
||||
bool SupportsAudioOnly = false);
|
||||
bool SupportsAudioOnly = false, bool SupportsLanAudioOnly = false);
|
||||
|
||||
public enum CallDisplayMode
|
||||
{
|
||||
|
|
|
|||
|
|
@ -26,6 +26,9 @@ public partial class ChatHub
|
|||
public Task<CallSession> InviteLanCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.LanSrtp);
|
||||
|
||||
public Task<CallSession> InviteLanAudioCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.LanSrtp, CallDisplayMode.AudioOnly);
|
||||
|
||||
private async Task<CallSession> InviteCoreAsync(string roomName, string callee, string transport,
|
||||
CallDisplayMode mode = CallDisplayMode.AudioVideo)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ public sealed class CallSignalingService(
|
|||
try
|
||||
{
|
||||
_contactPreferences[connection] = preferences;
|
||||
foreach (var call in _calls.Values.Where(c => !AllowsCallMode(connection, c.Session.DisplayMode)).ToArray())
|
||||
foreach (var call in _calls.Values.Where(c => !AllowsCallMode(connection, c.Session.DisplayMode, c.Session.Transport)).ToArray())
|
||||
{
|
||||
if (call.CallerConnection == connection || call.AcceptedConnection == connection)
|
||||
await FinishCoreAsync(call, "contact-preference-changed");
|
||||
|
|
@ -62,9 +62,11 @@ public sealed class CallSignalingService(
|
|||
public ContactPreferences? GetContactPreferences(string connection) =>
|
||||
_contactPreferences.TryGetValue(connection, out var preferences) ? preferences : null;
|
||||
|
||||
private bool AllowsCallMode(string connection, CallDisplayMode mode) => mode switch
|
||||
private bool AllowsCallMode(string connection, CallDisplayMode mode, string transport) => mode switch
|
||||
{
|
||||
CallDisplayMode.AudioVideo => GetContactPreferences(connection)?.AllowVideoCalls != false,
|
||||
CallDisplayMode.AudioOnly when transport == CallTransports.LanSrtp => GetContactPreferences(connection) is
|
||||
{ AllowAudioCalls: true, SupportsLanAudioOnly: true },
|
||||
CallDisplayMode.AudioOnly => GetContactPreferences(connection) is
|
||||
{ AllowAudioCalls: true, SupportsAudioOnly: true },
|
||||
_ => false
|
||||
|
|
@ -99,16 +101,14 @@ public sealed class CallSignalingService(
|
|||
ValidateTransport(transport, relayOnly);
|
||||
if (displayMode is not (CallDisplayMode.AudioVideo or CallDisplayMode.AudioOnly))
|
||||
throw new HubException("Unknown call mode.");
|
||||
if (transport == CallTransports.LanSrtp && displayMode == CallDisplayMode.AudioOnly)
|
||||
throw new HubException("Audio-only calls require WebRTC.");
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await ExpireCoreAsync();
|
||||
if (!AllowsCallMode(callerConnection, displayMode))
|
||||
if (!AllowsCallMode(callerConnection, displayMode, transport))
|
||||
throw new HubException("This call mode is unavailable on the calling connection.");
|
||||
calleeConnections = calleeConnections
|
||||
.Where(connection => AllowsCallMode(connection, displayMode)).ToArray();
|
||||
.Where(connection => AllowsCallMode(connection, displayMode, transport)).ToArray();
|
||||
if (calleeConnections.Length == 0)
|
||||
throw new HubException("The participant has no device accepting this call mode.");
|
||||
if (_calls.Count >= 128 || _calls.Values.Any(c =>
|
||||
|
|
|
|||
|
|
@ -62,9 +62,6 @@ public sealed class CallSignalingTests
|
|||
await f.Service.SetContactPreferencesAsync("alice-device", new(true, true, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-1", new(true, false, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-2", new(true, true, true));
|
||||
await Assert.ThrowsAsync<HubException>(() => f.Service.InviteAsync(
|
||||
"General", "alice", "bob", "alice-device", ["bob-1"], false,
|
||||
transport: CallTransports.LanSrtp, displayMode: CallDisplayMode.AudioOnly));
|
||||
await Assert.ThrowsAsync<HubException>(() => f.Service.InviteAsync(
|
||||
"General", "alice", "bob", "alice-device", ["bob-2"], false,
|
||||
displayMode: CallDisplayMode.AudioOnly));
|
||||
|
|
@ -82,6 +79,23 @@ public sealed class CallSignalingTests
|
|||
displayMode: (CallDisplayMode)42));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Srtp_audio_only_requires_its_own_capability_and_audio_preference()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Options.EnableLanCalls = true;
|
||||
await f.Service.SetContactPreferencesAsync("alice-device", new(true, true, true, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-1", new(true, true, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-2", new(true, false, true, false, true));
|
||||
var call = await f.Service.InviteAsync("General", "alice", "bob", "alice-device",
|
||||
["bob-1", "bob-2"], false, CallTransports.LanSrtp, CallDisplayMode.AudioOnly);
|
||||
Assert.Equal(["bob-2"], Assert.Single(f.Hub.Messages).Targets);
|
||||
await f.Service.AcceptAsync(call.Id, "bob", "bob-2", false);
|
||||
Assert.Equal(CallDisplayMode.AudioOnly, Assert.IsType<CallAccepted>(f.Hub.Messages.Last().Arguments[0]).Session.DisplayMode);
|
||||
await f.Service.SetContactPreferencesAsync("bob-2", new(false, true, true, false, true));
|
||||
Assert.Equal("contact-preference-changed", Assert.IsType<CallEnded>(f.Hub.Messages.Last().Arguments[0]).Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invitation_does_not_grant_media_signaling_or_disclose_turn_credentials()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue