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

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

	return lpcmFormat, lpcmMedia, nil
}

// ProcessLPCM processes LPCM flow and returns PTS and SAMPLES.
func ProcessLPCM(
	c *gortsplib.Client,
	lpcmMedia *description.Media,
	lpcmRTPDec *rtplpcm.Decoder,
	pkt *rtp.Packet,
) (
	int64,
	[]byte,
	error) {
	// Decode timestamp.
	pts, ok := c.PacketPTS2(lpcmMedia, pkt)
	if !ok {
		return 0, nil, fmt.Errorf("waiting for timestamp\n")
	}

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

	return pts, samples, err
}
