Skip to content

Instantly share code, notes, and snippets.

@recursivecodes
Last active September 6, 2023 17:11
Show Gist options
  • Select an option

  • Save recursivecodes/d2ea1d222a64a2519bdb8ce7e83e9db7 to your computer and use it in GitHub Desktop.

Select an option

Save recursivecodes/d2ea1d222a64a2519bdb8ce7e83e9db7 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.WebRTC;
using UnityEngine.Networking;
public class WebRTCPublish : MonoBehaviour{
RTCPeerConnection peerConnection;
MediaStreamTrack track;
Camera cam;
void Start() {
StartCoroutine(WebRTC.Update());
peerConnection = new RTCPeerConnection();
peerConnection.OnIceConnectionChange = state => { Debug.Log(state); };
cam = GetComponent<Camera>();
track = cam.CaptureStreamTrack(1280, 720);
peerConnection.AddTrack(track);
StartCoroutine(DoWHIP());
}
IEnumerator DoWHIP() {
var offer = peerConnection.CreateOffer();
yield return offer;
var offerDesc = offer.Desc;
var opLocal = peerConnection.SetLocalDescription(ref offerDesc);
yield return opLocal;
var filteredSdp = "";
foreach (string sdpLine in offer.Desc.sdp.Split("\r\n")) {
if (!sdpLine.StartsWith("a=extmap")) {
filteredSdp += sdpLine + "\r\n";
}
}
Debug.Log(filteredSdp);
using (UnityWebRequest www = new UnityWebRequest("[WHIP URL]")) {
www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.ASCII.GetBytes(filteredSdp));
www.downloadHandler = new DownloadHandlerBuffer();
www.method = UnityWebRequest.kHttpVerbPOST;
www.SetRequestHeader("Content-Type", "application/sdp");
www.SetRequestHeader("Authorization", "Bearer [STAGE PARTICIPANT TOKEN]");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success) {
Debug.Log(www.error);
}
else {
var answer = new RTCSessionDescription { type = RTCSdpType.Answer, sdp = www.downloadHandler.text };
var opRemote = peerConnection.SetRemoteDescription(ref answer);
yield return opRemote;
if (opRemote.IsError) {
Debug.Log(opRemote.Error);
}
}
}
}
void OnDestroy() {
peerConnection.Close();
peerConnection.Dispose();
track.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment