Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions jitter/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type Buffer struct {

initialized bool
prevSN uint16
prevTS uint32
head *packet
tail *packet

Expand Down Expand Up @@ -326,6 +327,7 @@ func (b *Buffer) popSample() []*rtp.Packet {
func (b *Buffer) popHead() *packet {
c := b.head
b.prevSN = c.packet.SequenceNumber
b.prevTS = c.packet.Timestamp
b.head = c.next
if b.head == nil {
b.tail = nil
Expand All @@ -335,6 +337,14 @@ func (b *Buffer) popHead() *packet {
return c
}

func (b *Buffer) LastSequenceNumber() uint16 {
return b.prevSN
}

func (b *Buffer) LastTimestamp() uint32 {
return b.prevTS
}

func before(a, b uint16) bool {
return (b-a)&0x8000 == 0
}
Expand Down
23 changes: 19 additions & 4 deletions opus/opus.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"github.com/livekit/protocol/logger"

"github.com/livekit/media-sdk"
"github.com/livekit/media-sdk/rtp"
"github.com/livekit/media-sdk/webm"
)

Expand Down Expand Up @@ -72,7 +71,7 @@ func Encode(w Writer, channels int, logger logger.Logger) (media.PCM16Writer, er
return &encoder{
w: w,
enc: enc,
buf: make([]byte, w.SampleRate()/rtp.DefFramesPerSec*channels),
buf: make([]byte, w.SampleRate()/media.DefFramesPerSec*channels),
logger: logger,
}, nil
}
Expand Down Expand Up @@ -132,10 +131,26 @@ func (d *decoder) WriteSample(in Sample) error {
media.StereoToMono(d.buf2, returnData)
returnData = d.buf2[:n2]
}

return d.w.WriteSample(returnData)
}

// If FEC data is not available, it falls back to PLC automatically
func (d *decoder) DecodeFEC(data []byte, pcm []int16) error {
if d.dec == nil {
return fmt.Errorf("decoder not initialized")
}

return d.dec.DecodeFEC(data, pcm)
}

func (d *decoder) DecodePLC(pcm []int16) error {
if d.dec == nil {
return fmt.Errorf("decoder not initialized")
}

return d.dec.DecodePLC(pcm)
}

func (d *decoder) resetForSample(in Sample) (int, error) {
channels := int(C.opus_packet_get_nb_channels((*C.uchar)(&in[0])))

Expand All @@ -147,7 +162,7 @@ func (d *decoder) resetForSample(in Sample) (int, error) {
}
d.dec = dec

d.buf = make([]int16, d.w.SampleRate()/rtp.DefFramesPerSec*channels)
d.buf = make([]int16, d.w.SampleRate()/media.DefFramesPerSec*channels)
d.lastChannels = channels
}

Expand Down
163 changes: 163 additions & 0 deletions opus/opus_jitter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package opus

import (
"time"

"github.com/livekit/media-sdk"
"github.com/livekit/media-sdk/jitter"
"github.com/livekit/media-sdk/rtp"
"github.com/livekit/protocol/logger"
)

const (
opusJitterMaxLatency = 60 * time.Millisecond
opusDTXFrameLength = 1
)

func HandleOpusJitter(h rtp.Handler, pcmWriter media.PCM16Writer, targetChannels int) rtp.Handler {
handler := &opusJitterHandler{
h: h,
err: make(chan error, 1),
logger: logger.GetLogger(),
}

dec, err := Decode(pcmWriter, targetChannels, handler.logger)
if err != nil {
handler.err <- err
return handler
}
handler.decoder = dec.(*decoder)

handler.buf = jitter.NewBuffer(
rtp.AudioDepacketizer{},
opusJitterMaxLatency,
func(packets []*rtp.Packet) {
for _, p := range packets {
handler.handleRTP(p)
}
},
jitter.WithPacketLossHandler(func() {
handler.pendingLoss = true
}),
)

return handler
}

type opusJitterHandler struct {
h rtp.Handler
buf *jitter.Buffer
decoder *decoder
err chan error
logger logger.Logger
nextPacket *rtp.Packet
lastPacket *rtp.Packet
pendingLoss bool
}

func (r *opusJitterHandler) String() string {
return "OpusJitter -> " + r.h.String()
}

func (r *opusJitterHandler) HandleRTP(h *rtp.Header, payload []byte) error {
r.buf.Push(&rtp.Packet{Header: *h, Payload: payload})
select {
case err := <-r.err:
return err
default:
return nil
}
}

func (r *opusJitterHandler) handleRTP(p *rtp.Packet) {
isDtx := len(p.Payload) == opusDTXFrameLength

// Not sure what to do if we have a pending loss and the packet is DTX.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good to use RTP timestamp irrespective of DTX or not. DTX packet also should have an RTP Timestamp.

But, this interface may be tricky. How does it work now? Is this pushing packets to the app or the app pulling? Ideally, the app should be pulling every x ms and this code should check for available data and if nothing available should use plc/fec as applicable.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is currently pushing to the app, jitter buffer does it's thing, the handler identifies the gaps and fills them with silence/FEC/PLC and writes to the application.

We're using the writer design SDK side, so it's all pushing to the app instead of the app polling it

if r.pendingLoss && !isDtx {
// Store the next packet for FEC
r.nextPacket = p
r.handlePacketLoss()
r.pendingLoss = false
}

if r.lastPacket != nil && (isDtx || len(r.lastPacket.Payload) == opusDTXFrameLength) {
silenceSamples := int(p.Timestamp - r.lastPacket.Timestamp)
if silenceSamples > 0 {
silenceBuf := make([]int16, silenceSamples*r.decoder.targetChannels)
if err := r.decoder.w.WriteSample(silenceBuf); err != nil {
r.logger.Warnw("failed to write silence", err)
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the decoder need to be filled with silence samples. That does not sound good. The decoder should have updated with PLC/FEC samples and should not ideally need filling with silence.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is directly writing to the PCMWriter that the decoder writes to after decoding

}

if isDtx {
r.lastPacket = p
return
}
}

if err := r.decoder.WriteSample(p.Payload); err != nil {
r.logger.Warnw("failed to decode packet", err)
}

r.lastPacket = p
}

func (r *opusJitterHandler) handlePacketLoss() {
if r.decoder == nil || r.nextPacket == nil {
return
}

lostPackets := int(r.nextPacket.SequenceNumber - r.buf.LastSequenceNumber() - 1)
if lostPackets <= 0 {
return
}

lastTs := r.buf.LastTimestamp()
nextTs := r.nextPacket.Timestamp

totalSamples := int(nextTs - lastTs)
if totalSamples <= 0 {
return
}

samplesPerPacket := totalSamples / lostPackets

if lostPackets > 1 {
// For mono audio, if we call DecodePLC right after a
// SFU generated mono silence, the concealment might not be proper.
// But, we need to pass the buffer for the exact duration of the lost audio.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not able to understand this comment.

Ideally, there should be no dependence on what SFU does. Ideally, this should not even know that it is interacting with SFU. It is just getting Opus packets and needs to deal with it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically:

  • We receive stereo audio from publisher
  • Decoder state is stereo
  • We receive mono silence from SFU
  • Decoder state becomes mono
  • We then call DecodePLC, which should use the last decoder state to get some data for concealment, and that last state is mono even though the lost packet could've been stereo

Actually worth checking how libwebrtc handles this

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is okay, if the lost packet is before the mono silence, it should not be concealed post that. Concealment should happen when it is detected. Again, pull model will make this simpler.

plcSamples := samplesPerPacket * (lostPackets - 1) * r.decoder.lastChannels
buf := make([]int16, plcSamples)

err := r.decoder.DecodePLC(buf)
if err != nil {
r.logger.Warnw("failed to recover lost packets with PLC", err)
return
}
_ = r.decoder.w.WriteSample(buf)
}

// Should we reset for the next packet before calling DecodeFEC?
// This will update the decoder's state for the next packet so it might help.
// But, it might also cause some issues if the next packet is SFU generated silence.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should make this simple.

Ideally, there is a pull and if there is data, it gets decoded, if not silence. So, maybe we need two more changes here

  1. jitter buffer in pull mode - looks like it is push mode, make it pull
  2. maybe write a module like the samplewriter which just loops and pulls data from provider for publish. Similarly, have a loop which pulls data from remote track and pushes to app. That can then apply decode or packet loss concealment.

In this push mechanism, what happens if there is a burst loss of 300 ms? There will be no handling till the next packet arrives. At that time, it will do a large conceal it looks like.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The entire pipeline is in push mode right now with the writer design. In the current implementation (regular jitter buffer, no concealment), it is push as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think we may have to build a pull mode to make this cleaner. Otherwise, doing concealment after a burst loss is already too late. The time has passsed for playing out the missing audio.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this push mechanism, what happens if there is a burst loss of 300 ms? There will be no handling till the next packet arrives. At that time, it will do a large conceal it looks like.

Good point, initially I was doing only FEC and it needed the next packet, so I had this approach. Then, I realized if multiple packets are lost, then it can only recover the last one with FEC, n-1 packets needed PLC. But yea currently, it does a large conceal when the next valid packet is popped from the jitter buffer.

channels, err := r.decoder.resetForSample(r.nextPacket.Payload)
if err != nil {
r.logger.Warnw("failed to reset decoder for FEC", err)
return
}

buf := make([]int16, samplesPerPacket*channels)
err = r.decoder.DecodeFEC(r.nextPacket.Payload, buf)
if err != nil {
r.logger.Warnw("failed to recover last lost packet with FEC", err)
return
}
_ = r.decoder.w.WriteSample(buf)
}

func (r *opusJitterHandler) Close() error {
if r.decoder != nil {
return r.decoder.Close()
}
return nil
}
10 changes: 5 additions & 5 deletions rtp/jitter.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func HandleJitter(h Handler) Handler {
}
// Jitter buffer expects to be closed (to stop the timer), but handler interface doesn't allow it.
// This should be fine, because GC can now collect timers and goroutines blocked on them if they are not referenced.
handler.buf = jitter.NewBuffer(audioDepacketizer{}, jitterMaxLatency, func(packets []*rtp.Packet) {
handler.buf = jitter.NewBuffer(AudioDepacketizer{}, jitterMaxLatency, func(packets []*rtp.Packet) {
for _, p := range packets {
handler.handleRTP(p)
}
Expand Down Expand Up @@ -73,16 +73,16 @@ func (r *jitterHandler) HandleRTP(h *rtp.Header, payload []byte) error {
}
}

type audioDepacketizer struct{}
type AudioDepacketizer struct{}

func (d audioDepacketizer) Unmarshal(packet []byte) ([]byte, error) {
func (d AudioDepacketizer) Unmarshal(packet []byte) ([]byte, error) {
return packet, nil
}

func (d audioDepacketizer) IsPartitionHead(payload []byte) bool {
func (d AudioDepacketizer) IsPartitionHead(payload []byte) bool {
return true
}

func (d audioDepacketizer) IsPartitionTail(marker bool, payload []byte) bool {
func (d AudioDepacketizer) IsPartitionTail(marker bool, payload []byte) bool {
return true
}