sipsorcery-org / sipsorcery

A WebRTC, SIP and VoIP library for C# and .NET. Designed for real-time communications apps.
https://sipsorcery-org.github.io/sipsorcery
Other
1.42k stars 431 forks source link

WebRtc MediaStreamTrack `Stop & Mute` feature #1046

Closed MrAliSalehi closed 6 months ago

MrAliSalehi commented 7 months ago

Hi There I'm looking for a way to simulate the Mute and Stop options in my MediaStream, something like this:

public class MediaStreamTrack : IObserverInterface
{
    private bool _ended;
    private bool _enabled;
    private readonly IMediaStreamTrackInterface _track;
    private MediaStreamTrack(IMediaStreamTrackInterface track)
    {
        _track = track;
        _track.RegisterObserver(this);
    }
    public static MediaStreamTrack Create(IMediaStreamTrackInterface track) => new(track);

    public void OnChanged()
    {
        if (_track.State == IMediaStreamTrackInterface.TrackState.Ended)
            Stop();
    }

    public bool IsMuted() => _ended ? !_enabled : !_track.Enabled;

    public void Mute(bool muted)
    {
        if (_ended)
            _enabled = !muted;
        else
            _track.Enabled = !muted;
    }
    public IMediaStreamTrackInterface Track() => _track;

    public void OnPeerConnectionClosed() => Stop();
    private void Stop()
    {
        _track.UnregisterObserver(this);
        _ended = true;
        _enabled = _track.Enabled;
    }
}

this code was taken from a similar implementation of WebRtc in CPP and was translated into C#, as a simple prototype

any Ideas? Thanks!

sipsorcery commented 7 months ago

The sofphone sample has examples of putting audi and video streams on and off hold see here.

MrAliSalehi commented 7 months ago

is there any way to do it from the MediaStreamTrack? and I thought SIPAgent wasn't for webrtc stuff, interesting

sipsorcery commented 7 months ago

Whoops, you're correct. Disregard the softphone & SIP agent angle.

You can't do if from the MediaStreamTrack, instead you can do if from the IVideoSource or IAudioSource, that get connected to the MediaStreamTrack, using their Pause and Resume methods. See here for how that connection is made.

Only works for your locally added streams. For remote streams it is theoretically possible to send a new SDP offer with the sendrecv attribute set to sendonly but that behaviour has not been extensively tested with this library.