Async WebRTC Hold direction problem

by jib1

HTML

<video id="video1" height="120" width="160" controls autoplay muted></video>
<video id="video2" height="120" width="160" controls autoplay></video><br>
<label><input type="checkbox" id="includeVideo">video</label>
<div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

JavaScript

var console = { log: msg => div.innerHTML += msg + "<br>" };
let pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

let track;

(async () => {
  try {
    let stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
    track = stream.getVideoTracks()[0];
    stream.removeTrack(track);
    stream.getTracks().forEach(track => pc1.addTrack(track, stream));
    pc1.addTransceiver("video", {streams: [stream]}); // replace with below
//    pc1.addTransceiver("video", {streams: [stream], direction: "inactive"});
    video1.srcObject = stream;
  } catch(e) {
    console.log(e);
  }
})();

includeVideo.onclick = async e => {
  try {
    let tc = pc1.getTransceivers().find(tc => tc.receiver.track.kind == "video");
    if (includeVideo.checked) {
      console.log(`Direction is already ${tc.direction}. Do replaceTrack`);
      tc.sender.replaceTrack(track);
//      tc.direction = "sendonly";
    } else {
      tc.sender.replaceTrack(null);
      tc.direction = "inactive";
    }
  } catch(e) {
    console.log(e);
  }
};

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = e => console.log(pc1.iceConnectionState);

pc1.onnegotiationneeded = async e => {
  try {
    await pc1.setLocalDescription(await pc1.createOffer());
    await pc2.setRemoteDescription(pc1.localDescription);
    await pc2.setLocalDescription(await pc2.createAnswer());
    await pc1.setRemoteDescription(pc2.localDescription);
  } catch(e) {
    console.log(e);
  }
};

pc2.ontrack = ({streams}) => {
  console.log("ontrack streams = " + streams.length);
  if (streams.length) video2.srcObject = streams[0];
}