mirror of
https://github.com/aler9/rtsp-simple-server
synced 2025-09-27 03:56:15 +08:00
120 lines
2.1 KiB
Go
120 lines
2.1 KiB
Go
package codecprocessor
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/bluenviron/gortsplib/v5/pkg/format"
|
|
"github.com/bluenviron/gortsplib/v5/pkg/format/rtpklv"
|
|
"github.com/pion/rtp"
|
|
|
|
"github.com/bluenviron/mediamtx/internal/logger"
|
|
"github.com/bluenviron/mediamtx/internal/unit"
|
|
)
|
|
|
|
type klv struct {
|
|
RTPMaxPayloadSize int
|
|
Format *format.KLV
|
|
GenerateRTPPackets bool
|
|
Parent logger.Writer
|
|
|
|
encoder *rtpklv.Encoder
|
|
decoder *rtpklv.Decoder
|
|
randomStart uint32
|
|
}
|
|
|
|
func (t *klv) initialize() error {
|
|
if t.GenerateRTPPackets {
|
|
err := t.createEncoder()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
t.randomStart, err = randUint32()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (t *klv) createEncoder() error {
|
|
t.encoder = &rtpklv.Encoder{
|
|
PayloadMaxSize: t.RTPMaxPayloadSize,
|
|
PayloadType: t.Format.PayloadTyp,
|
|
}
|
|
return t.encoder.Init()
|
|
}
|
|
|
|
func (t *klv) ProcessUnit(uu unit.Unit) error { //nolint:dupl
|
|
u := uu.(*unit.KLV)
|
|
|
|
if u.Unit != nil {
|
|
// ensure the format processor's encoder is initialized
|
|
if t.encoder == nil {
|
|
err := t.createEncoder()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
pkts, err := t.encoder.Encode(u.Unit)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
u.RTPPackets = pkts
|
|
|
|
for _, pkt := range u.RTPPackets {
|
|
pkt.Timestamp += t.randomStart + uint32(u.PTS)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (t *klv) ProcessRTPPacket( //nolint:dupl
|
|
pkt *rtp.Packet,
|
|
ntp time.Time,
|
|
pts int64,
|
|
hasNonRTSPReaders bool,
|
|
) (unit.Unit, error) {
|
|
u := &unit.KLV{
|
|
Base: unit.Base{
|
|
RTPPackets: []*rtp.Packet{pkt},
|
|
NTP: ntp,
|
|
PTS: pts,
|
|
},
|
|
}
|
|
|
|
// remove padding
|
|
pkt.Padding = false
|
|
pkt.PaddingSize = 0
|
|
|
|
if len(pkt.Payload) > t.RTPMaxPayloadSize {
|
|
return nil, fmt.Errorf("RTP payload size (%d) is greater than maximum allowed (%d)",
|
|
len(pkt.Payload), t.RTPMaxPayloadSize)
|
|
}
|
|
|
|
// decode from RTP
|
|
if hasNonRTSPReaders || t.decoder != nil {
|
|
if t.decoder == nil {
|
|
var err error
|
|
t.decoder, err = t.Format.CreateDecoder()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
unit, err := t.decoder.Decode(pkt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
u.Unit = unit
|
|
}
|
|
|
|
// route packet as is
|
|
return u, nil
|
|
}
|