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/rtpsimpleaudio"
	"github.com/pion/rtp"
)

// FindOPUSFormat finds the OPUS media and format.
func FindOPUSFormat(desc *description.Session) (*format.Opus, *description.Media, error) {
	var opusFormat *format.Opus
	opusMedia := desc.FindFormat(&opusFormat)
	if opusMedia == nil {
		return nil, nil, errors.New("media OPUS not found")
	}

	return opusFormat, opusMedia, nil
}

// ProcessOPUS processes OPUS flow and returns PTS and OP.
func ProcessOPUS(
	c *gortsplib.Client,
	opusMedia *description.Media,
	opusRTPDec *rtpsimpleaudio.Decoder,
	pkt *rtp.Packet,
) (
	int64,
	[]byte,
	error) {
	// Decode timestamp.
	pts, ok := c.PacketPTS2(opusMedia, pkt)
	if !ok {
		return 0, nil, fmt.Errorf("waiting for timestamp\n")
	}

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

	return pts, op, nil
}
