package ffmpeg

/*
#include <libavcodec/avcodec.h>
#include <libavcodec/packet.h>
*/
import "C"
import "unsafe"

// Packet represents an encoded data packet
type Packet struct {
	ptr *C.AVPacket
}

// AllocPacket allocates an empty packet
func AllocPacket() *Packet {
	return &Packet{
		ptr: C.av_packet_alloc(),
	}
}

// FreePacket frees the packet
func (p *Packet) Free() {
	if p.ptr != nil {
		C.av_packet_free(&p.ptr)
		p.ptr = nil
	}
}

// PacketFromC converts a C pointer to Packet
func PacketFromC(ptr *C.AVPacket) *Packet {
	return &Packet{ptr: ptr}
}

// CPtr returns the underlying C pointer
func (p *Packet) CPtr() *C.AVPacket {
	return p.ptr
}

// Data returns the packet data
func (p *Packet) Data() []byte {
	if p.ptr == nil {
		return nil
	}
	size := int(p.ptr.size)
	if size <= 0 || p.ptr.data == nil {
		return nil
	}
	return C.GoBytes(unsafe.Pointer(p.ptr.data), C.int(size))
}

// Size returns the packet size
func (p *Packet) Size() int {
	if p.ptr == nil {
		return 0
	}
	return int(p.ptr.size)
}

// PTS returns the presentation timestamp
func (p *Packet) PTS() int64 {
	if p.ptr == nil {
		return 0
	}
	return int64(p.ptr.pts)
}

// DTS returns the decoding timestamp
func (p *Packet) DTS() int64 {
	if p.ptr == nil {
		return 0
	}
	return int64(p.ptr.dts)
}

// SetPTS sets the presentation timestamp
func (p *Packet) SetPTS(pts int64) {
	if p.ptr != nil {
		p.ptr.pts = C.int64_t(pts)
	}
}

// SetDTS sets the decoding timestamp
func (p *Packet) SetDTS(dts int64) {
	if p.ptr != nil {
		p.ptr.dts = C.int64_t(dts)
	}
}

// StreamIndex returns the stream index
func (p *Packet) StreamIndex() int {
	if p.ptr == nil {
		return -1
	}
	return int(p.ptr.stream_index)
}

// SetStreamIndex sets the stream index
func (p *Packet) SetStreamIndex(idx int) {
	if p.ptr != nil {
		p.ptr.stream_index = C.int(idx)
	}
}

// Flags returns the packet flags
func (p *Packet) Flags() int {
	if p.ptr == nil {
		return 0
	}
	return int(p.ptr.flags)
}

// Unref unreferences the packet data
func (p *Packet) Unref() {
	if p.ptr != nil {
		C.av_packet_unref(p.ptr)
	}
}
