toBytes method

Uint8List toBytes()

Implementation

Uint8List toBytes() {
  // Each chunk: 4 (SSRC) + 2 (type+len) + cname bytes + 1 (END=0),
  // padded up to a 4-byte boundary.
  final chunkBytes = <Uint8List>[];
  for (final c in chunks) {
    final cnameBytes = Uint8List.fromList(c.cname.codeUnits);
    assert(cnameBytes.length <= 255, 'CNAME too long');
    var len = 4 + 2 + cnameBytes.length + 1;
    final pad = (4 - (len % 4)) % 4;
    final buf = Uint8List(len + pad);
    final bd = ByteData.sublistView(buf);
    bd.setUint32(0, c.ssrc & 0xFFFFFFFF);
    buf[4] = sdesCname;
    buf[5] = cnameBytes.length;
    buf.setRange(6, 6 + cnameBytes.length, cnameBytes);
    // buf[6 + cnameBytes.length] is the END (0) item, already zero.
    chunkBytes.add(buf);
  }
  final body = chunkBytes.fold<int>(0, (a, b) => a + b.length);
  final total = 4 + body;
  final out = Uint8List(total);
  final bd = ByteData.sublistView(out);
  out[0] = (rtcpVersion << 6) | (chunks.length & 0x1F);
  out[1] = rtcpPtSdes;
  bd.setUint16(2, (total ~/ 4) - 1);
  var offset = 4;
  for (final c in chunkBytes) {
    out.setRange(offset, offset + c.length, c);
    offset += c.length;
  }
  return out;
}