@@ -36,6 +36,11 @@ defmodule Shinkai.Sink.WebRTC.PeerManager do
3636 GenServer . cast ( manager , { :handle_peer_answer , from , session_id , sdp_answer } )
3737 end
3838
39+ @ spec remove_peer ( server :: pid ( ) | atom ( ) , session_id :: String . t ( ) ) :: :ok
40+ def remove_peer ( manager , session_id ) do
41+ GenServer . call ( manager , { :remove_peer , session_id } )
42+ end
43+
3944 @ impl true
4045 def init ( opts ) do
4146 { :ok ,
@@ -57,6 +62,20 @@ defmodule Shinkai.Sink.WebRTC.PeerManager do
5762 { :reply , :ok , % { state | audio_track: track } }
5863 end
5964
65+ def handle_call ( { :remove_peer , session_id } , _from , state ) do
66+ Logger . info ( "Removing WebRTC peer with session ID: #{ session_id } " )
67+
68+ case Registry . match ( Shinkai.Registry , { :webrtc , state . source_id } , { :_ , session_id } ) do
69+ [ { _pid , { pc , _session_id } } ] -> unregister ( state . source_id , pc )
70+ [ ] -> :ok
71+ end
72+
73+ { pc , sessions } = Map . pop ( state . sessions , session_id )
74+ if pc , do: PeerConnection . stop ( pc )
75+
76+ { :reply , :ok , % { state | sessions: sessions } }
77+ end
78+
6079 @ impl true
6180 def handle_cast ( { :add_peer , from } , state ) do
6281 video_tracks = if state . video_track , do: [ elem ( state . video_track , 1 ) ] , else: [ ]
@@ -125,10 +144,12 @@ defmodule Shinkai.Sink.WebRTC.PeerManager do
125144 end
126145
127146 def handle_info ( { :ex_webrtc , pid , { :connection_state_change , connection_state } } , state )
128- when connection_state in [ :failed , :closed , :disconnected ] do
129- Logger . info ( "WebRTC PeerConnection #{ inspect ( pid ) } connection state: #{ connection_state } " )
130- PeerConnection . stop ( pid )
131- Registry . unregister_match ( Shinkai.Registry , { :webrtc , state . source_id } , { pid , :_ } )
147+ when connection_state in [ :failed , :closed ] do
148+ Logger . debug (
149+ "WebRTC PeerConnection #{ inspect ( pid ) } connection state changed to: #{ connection_state } "
150+ )
151+
152+ unregister ( state . source_id , pid )
132153 { :noreply , state }
133154 end
134155
@@ -137,7 +158,7 @@ defmodule Shinkai.Sink.WebRTC.PeerManager do
137158 end
138159
139160 def handle_info ( { :ex_webrtc , _pid , msg } , state ) do
140- Logger . info ( "Unhandled ExWebRTC message: #{ inspect ( msg ) } " )
161+ # Logger.info("Unhandled ExWebRTC message: #{inspect(msg)}")
141162 { :noreply , state }
142163 end
143164
@@ -153,4 +174,9 @@ defmodule Shinkai.Sink.WebRTC.PeerManager do
153174 end
154175 end )
155176 end
177+
178+ defp unregister ( source_id , pc ) do
179+ PeerConnection . stop ( pc )
180+ Registry . unregister_match ( Shinkai.Registry , { :webrtc , source_id } , { pc , :_ } )
181+ end
156182end
0 commit comments