package formats

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"
)

// FindG711Format finds the G711 media and format.
func FindG711Format(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
}

// ProcessG711 processes G711 flow and returns PTS and AU.
func ProcessG711(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 {
		return 0, nil, fmt.Errorf("waiting for timestamp\n")
	}

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

	return pts, au, nil
}
