package media

import (
	"errors"
	"fmt"
	"github.com/bluenviron/gortsplib/v4"
	"github.com/bluenviron/gortsplib/v4/pkg/description"
	"github.com/bluenviron/gortsplib/v4/pkg/format"
	"github.com/bluenviron/gortsplib/v4/pkg/format/rtplpcm"
	"github.com/pion/rtp"
	"log"
)

// CheckG711Format finds the G711 media and format.
func CheckG711Format(desc *description.Session) (*format.G711, *description.Media, error) {
	var g711Format *format.G711
	g711Media := desc.FindFormat(&g711Format)
	if g711Media == nil {
		return nil, nil, errors.New("media G711 not found")
	}

	return g711Format, g711Media, nil
}

// ProcG711 processes G711 flow and returns PTS and AU.
func ProcG711(c *gortsplib.Client, g711Media *description.Media, g711RTPDec *rtplpcm.Decoder, pkt *rtp.Packet) (
	int64, []byte, error) {
	// Decode timestamp.
	pts, ok := c.PacketPTS2(g711Media, pkt)
	if !ok {
		log.Printf("waiting for timestamp\n")
		return 0, nil, nil
	}

	// Extract access unit from RTP packets.
	au, err := g711RTPDec.Decode(pkt)
	if err != nil {
		return 0, nil, fmt.Errorf("decoding G711 RTP packet: %w", err)
	}

	return pts, au, nil
}