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

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

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

	// Extract access unit from RTP packets.
	au, err := h264RTPDec.Decode(pkt)
	if err != nil {
		if err != rtph264.ErrNonStartingPacketAndNoPrevious && err != rtph264.ErrMorePacketsNeeded {
			return 0, nil, fmt.Errorf("decoding H264 RTP packet: %w", err)
		}
	}

	return pts, au, nil
}
