diff --git a/lib/ex_webrtc/peer_connection.ex b/lib/ex_webrtc/peer_connection.ex index cee8caaa..e0066903 100644 --- a/lib/ex_webrtc/peer_connection.ex +++ b/lib/ex_webrtc/peer_connection.ex @@ -293,15 +293,23 @@ defmodule ExWebRTC.PeerConnection do defp apply_remote_description(_type, sdp, state) do # TODO apply steps listed in RFC 8829 5.10 media = hd(sdp.media) - {:ice_ufrag, ufrag} = ExSDP.Media.get_attribute(media, :ice_ufrag) - {:ice_pwd, pwd} = ExSDP.Media.get_attribute(media, :ice_pwd) - :ok = ICEAgent.set_remote_credentials(state.ice_agent, ufrag, pwd) - :ok = ICEAgent.gather_candidates(state.ice_agent) + with {:ice_ufrag, ufrag} <- ExSDP.Media.get_attribute(media, :ice_ufrag), + {:ice_pwd, pwd} <- ExSDP.Media.get_attribute(media, :ice_pwd), + {:ok, transceivers} <- get_transceivers(sdp, state) do + :ok = ICEAgent.set_remote_credentials(state.ice_agent, ufrag, pwd) + :ok = ICEAgent.gather_candidates(state.ice_agent) + transceivers = Map.merge(transceivers, state.transceivers) + {:ok, %{state | current_remote_desc: sdp, transceivers: transceivers}} + else + nil -> {:error, :missing_ice_ufrag_or_pwd} + end + end + + defp get_transceivers(sdp, state) do transceivers = - sdp.media - |> Enum.reduce(%{}, fn media -> + Enum.reduce_while(sdp.media, %{}, fn media, transceivers -> {:mid, mid} = ExSDP.Media.get_attribute(media, :mid) # if there is no direction, the default is sendrecv # see RFC 3264, sec. 6.1 @@ -320,17 +328,15 @@ defmodule ExWebRTC.PeerConnection do {tr.mid, tr} end) - |> Map.merge(state.transceivers) - - {:ok, %{state | current_remote_desc: sdp, transceivers: transceivers}} end defp find_or_create_transceiver(mid, direction, transceivers) when direction in [:sendrecv, :recvonly] do - Enum.find(transceivers, %RTPTransceiver{mid: mid, direction: :recvonly}, fn - {nil, tr} when tr.direction == direction -> tr - _other -> nil + Enum.find(transceivers, {nil, %RTPTransceiver{mid: mid, direction: :recvonly}}, fn + {nil, tr} -> tr.direction == direction + _other -> false end) + |> elem(1) end defp find_or_create_transceiver(mid, :sendonly, _transceivers) do