Back to Home

WebRTC video in Qt: jitter buffer + NACK

The article describes the implementation of WebRTC video client on C++/Qt using libdatachannel. Detailed analysis of jitter buffer, NACK mechanism, VP8/VP9 frame assembly and Pion server with interceptors.

WebRTC in Qt: full stack with NACK and jitter buffer
Advertisement 728x90

Implementing WebRTC Video with Jitter Buffer and NACK in a Qt Client

WebRTC uses UDP to minimize transmission overhead. Clients exchange SDP descriptors, use STUN/TURN for NAT traversal, ICE to maintain connections, and a signaling server for coordination. SFU/MCU servers act as middleboxes for stream forwarding. A 1080p@30fps VP8 stream requires ~600 Kbps without key frames. Packet loss dramatically increases load through PLI requests and NACK. The jitter buffer resolves packet ordering issues.

Key tasks: signaling/MCU server with NACK support, retransmission mechanism, client-side jitter buffer.

Pion Server with NACK Support

The server is implemented in Go using the Pion library. We register default interceptors for NACK:

Google AdInline article slot
type Controller interface {
	HandleConnection(c *common.SafeWebSocket)
	JoinRoom(peer *common.Peer, msg Msg) error
	LeaveRoom(peer *common.Peer, msg Msg) error
}

type controller struct {
	logger *zap.Logger

	roomRepo repository.RoomRepo
	api      *webrtc.API
}

func NewController(logger *zap.Logger, roomRepo repository.RoomRepo) Controller {
	settingEngine := webrtc.SettingEngine{}
	settingEngine.SetAnsweringDTLSRole(webrtc.DTLSRoleServer)
	mediaEngine := &webrtc.MediaEngine{}
	mediaEngine.RegisterDefaultCodecs()
	interceptorRegistry := interceptor.Registry{}

	if err := webrtc.RegisterDefaultInterceptorsWithOptions(mediaEngine, &interceptorRegistry,
		webrtc.WithNackGeneratorOptions(nack.GeneratorSize(8192)),
		webrtc.WithNackResponderOptions(nack.ResponderSize(8192)),
	); err != nil {
		logger.Error("failed to register interceptor", zap.Error(err))

		panic(err)
	}

	api := webrtc.NewAPI(
		webrtc.WithMediaEngine(mediaEngine),
		webrtc.WithSettingEngine(settingEngine),
		webrtc.WithInterceptorRegistry(&interceptorRegistry),
	)

	ctrl := &controller{
		api:      api,
		logger:   logger,
		roomRepo: roomRepo,
	}

	go func() { // Send RTCP I-frame request every two seconds
		ticker := time.NewTicker(2 * time.Second)
		for _ := range ticker.C {
			roomIds := ctrl.roomRepo.GetRooms()
			for _, roomId := range roomIds {
				go ctrl.dispatch(roomId)
			}
		}
	}()

	return ctrl
}

Network emulation with packet loss:

sudo tc qdisc add dev lo root netem delay 50ms 20ms loss 1%

Qt Client Using libdatachannel

The browser serves as the video source via a minimal HTTP server. The C++ client uses libdatachannel + Qt without requiring full Chromium.

Establishing peer connection:

Google AdInline article slot
void ConferenceClient::connectClient(QString url, QString roomId)
{
    rtc::InitLogger(rtc::LogLevel::Debug);

    this->pc.onLocalDescription(this->pcOnLocalDescription(roomId));
    this->pc.onLocalCandidate(this->pcOnLocalCandidate());
    this->pc.onGatheringStateChange(this->pcOnGatheringStateChange());

    this->pc.onIceStateChange([](auto state) {
        std::cout << "Ice state changed: " << state << std::endl;
    });
    this->pc.onStateChange([](auto state) {
        std::cout << "state changed: " << state << std::endl;
    });

    this->ws.onOpen(this->wsOnOpen(roomId));
    this->ws.onMessage(this->wsOnMessage());

    this->pc.onTrack(this->pcOnTrack());
    this->ws.open(url.toStdString());
}

Handling Tracks and Packets

For each track, we create a structure with a jitter buffer (LRUCache) and a frame queue:

std::function<void(std::shared_ptr<rtc::Track>)> ConferenceClient::pcOnTrack() {
    return [this](std::shared_ptr<rtc::Track> track) {
        auto mid = track->description().mid();

        this->track_index[mid]
            = {track, 0, "NO_VALUE", 0, 0, LRUCache<std::uint32_t, jitterbuffer>(256)};

        this->player->initMid(mid);
        bool isVideo = true;

        if (track->description().type() == "audio") {
            isVideo = false;

            track->setMediaHandler(std::make_shared<rtc::OpusRtpDepacketizer>());
            track->chainMediaHandler(std::make_shared<rtc::RtcpReceivingSession>());
            track->onFrame(this->trackOnFrame(mid, isVideo));
        } else {
            track->onMessage(this->pcOnMessage(mid));
        }

        track->onOpen([track]() { track->requestKeyframe(); });
        track->onClosed([this, mid]() { this->player->destroy(mid); });
    };
}

Key aspects of RTP packet handling:

  • Discarding late packets (rtpHeader->timestamp() < lastCompletedTs)
  • RTX retransmission – restoring original seqNumber and payloadType
  • Endianness – RTP data is big-endian; platform is little-endian
  • Frame queue as std::map<uint32_t, pair<long, vector<byte>>> indexed by RTP timestamp
  • Playback after PLAYER_DELAY following first frame packet arrival

Reassembling VP8/VP9 Frames

std::function<void(rtc::message_variant)> ConferenceClient::pcOnMessage(std::string mid)
{
    return [this, mid](rtc::message_variant msg) {
        // ... timestamp check, RTX processing ...
        
        std::vector<std::byte> frame;

        if (!frame_cache.exist(pkgTs)
            && (track->description().rtpMap(PT)->format == MyApp::VP8CODEC
                || track->description().rtpMap(PT)->format == MyApp::VP9CODEC)) {
            frame_cache.put(pkgTs, jitterbuffer());

            track_info.ssrc = rtpHeader->ssrc();

            track_info.frame_queue[pkgTs] = std::make_pair(nowTs, std::vector<std::byte>());

            codec = track->description().rtpMap(PT)->format;
            codecPT = PT;
        }

        jitterbuffer &buff = frame_cache.get(pkgTs);

        if (codec == MyApp::VP9CODEC) {
            frame = buff.addVp9Packet(std::move(msg), track_info.lastCompletedTs);
        } else if (codec == MyApp::VP8CODEC) {
            frame = buff.addVp8Packet(std::move(msg), track_info.lastCompletedTs);
        }

        if (frame.size() > 0) {
            track_info.frame_queue[pkgTs].second = std::move(frame);
        }
        // ... playback and NACK ...
    };
}

Key Takeaways

  • libdatachannel requires manual implementation of jitter buffer and NACK
  • Pion interceptors automatically handle NACK with buffer sizes set to 8192
  • Frame queue uses std::map for natural ordering by RTP timestamp
  • RTX mappings are negotiated in SDP offer/answer
  • Playback occurs after PLAYER_DELAY post-first-frame arrival
  • Periodic RTCP PLI sent every 2 seconds

— Editorial Team

Google AdInline article slot
Advertisement 728x90

Read Next