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

// FindAACFormat finds the AAC media and format.
func FindAACFormat(desc *description.Session) (*format.MPEG4Audio, *description.Media, error) {
	var aacFormat *format.MPEG4Audio
	aacMedia := desc.FindFormat(&aacFormat)
	if aacMedia == nil {
		return nil, nil, errors.New("media AAC not found")
	}

	return aacFormat, aacMedia, nil
}

// ProcessAAC processes AAC flow and returns PTS and AUS.
func ProcessAAC(
	c *gortsplib.Client,
	aacMedia *description.Media,
	aacRTPDec *rtpmpeg4audio.Decoder,
	pkt *rtp.Packet,
) (
	int64,
	[][]byte,
	error) {
	// Decode timestamp.
	pts, ok := c.PacketPTS2(aacMedia, pkt)
	if !ok {
		return 0, nil, fmt.Errorf("waiting for timestamp\n")
	}

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

	return pts, aus, nil
}
