/*
rfc 3550
*/
package icspacketgen

import (
	"encoding/binary"
	"math/rand"
	"time"
)

type RTPDataHeader struct {
	PayloadType int
	Sequence    int
	Timestamp   int
	SSRC        int
}

type RTPHeader struct {
	part      uint16 //v,p,x,m,pt
	seq       uint16
	timestamp uint32
	ssrc      uint32
}

const RTPHEADER_LEN = 12

func NewRTP() *RTPDataHeader {
	r := &RTPDataHeader{}
	return r
}

func (r *RTPDataHeader) MakeRTPData(pt uint8, seq *uint16, timestamp *uint32, ssrc uint32, payload []byte) []byte {
	payloadSize := len(payload)
	rtp := make([]byte, RTPHEADER_LEN+payloadSize)

	//version
	rtp[0] = uint8(2) << 6
	//padding
	rtp[0] |= uint8(1) << 5
	//payload type
	rtp[1] = uint8(pt)

	//sequence number
	binary.BigEndian.PutUint16(rtp[2:4], *seq)
	//timestamp
	binary.BigEndian.PutUint32(rtp[4:8], *timestamp)
	//ssrc
	binary.BigEndian.PutUint32(rtp[8:12], ssrc)
	//payload
	copy(rtp[12:], payload)

	//fmt.Println("RTP>>>", rtp)

	incSeq(seq)
	incTimeStamp(timestamp)

	return rtp
}

func incTimeStamp(ts *uint32) {
	*ts += uint32(160)
}

func incSeq(seq *uint16) {
	*seq++
}

func GenSSRC() uint32 {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	ret := r.Uint32()
	//fmt.Println(">>>", ret)

	return ret
}
