拆分m行的SDP(字符串)以更改视频编解码器

时间:2017-03-17 12:33:29

标签: javascript string replace pattern-matching sdp

我希望最后有一种方法可以将VP9或H.264设置为SDP中的首选视频编解码器。

所以我在SDP中寻找m行:

m=video 9 UDP/TLS/RTP/SAVPF 96 98 100 102 127 97 99 101 125

我的SDP的控制台日志:

Screenshot of console log

在这种情况下,我会得到并使用VP8(96)作为视频编解码器而不是VP9(98)。所以我想检查98 / VP9是否可行/可用,并希望将其设置在开头/第一个位置以实际使用它。

到目前为止我得到了什么:

if(sdpOrigin == 'local') {
    let lines = sdp.split('\n').map(l => l.trim());
    lines.forEach(function(line) {
        if (line.indexOf('m=video') === 0) {
            let parts = line.substr(28); // Should be avoided!
            let vp9_order = parts.indexOf("98");
            let array = parts.split(/\s+/);
            console.log("array", array); // 96 98 100 102 127 97 99 101 125
            if (vp9_order > 0) {
                array.splice(vp9_order, 1);
                array.unshift("98");
            }
            console.log("array-new", array); // 98 96 100 102 127 97 99 101 125

            // How do I update my SDP now with the new codec order?

        }
    })
}

这种方法在我看来是不好的,因为我得到了我想要的m行,但是我在位置'28'处修复子串,所以如果在更改之前它会被破坏。

最后,我的SDP中应该有以下“m行”:

m=video 9 UDP/TLS/RTP/SAVPF 98 96 100 102 127 97 99 101 125

有人可以帮我吗?

3 个答案:

答案 0 :(得分:3)

您应该首先按行空格分割行,然后根据SDP specification将其分成相应的字段:

let fields = line.split(/\s+/);
if (fields[0] === 'm=video') {
    let [ type, port, proto, ...formats] = fields;

    let vp9_order = formats.indexOf("98");
    if (vp9_order > 0) {
        formats.splice(vp9_order, 1);  // remove from existing position
        formats.unshift("98");         // and prepend
    }
    line = [ type, port, proto, ...formats].join(' ');
}

答案 1 :(得分:1)

此方法可用于自己修改SDP。您可以修改SDP以强制使用h264,vp9或vp8编解码器。

<script src="https://cdn.webrtc-experiment.com/CodecsHandler.js"></script>
sdp = CodecsHandler.preferCodec(sdp, 'h264');
sdp = CodecsHandler.preferCodec(sdp, 'vp8');
sdp = CodecsHandler.preferCodec(sdp, 'vp9');

答案 2 :(得分:0)

是这样的:

// Returns a new m= line with the specified codec as the first one.
function setDefaultCodec(mLine, payload) {
  var elements = mLine.split(' ');

  // Just copy the first three parameters; codec order starts on fourth.
  var newLine = elements.slice(0, 3);

  // Put target payload first and copy in the rest.
  newLine.push(payload);
  for (var i = 3; i < elements.length; i++) {
    if (elements[i] !== payload) {
      newLine.push(elements[i]);
    }
  }
  return newLine.join(' ');
}