package srt

import (
	"bytes"

	srt "github.com/datarhei/gosrt"
	"github.com/langhuihui/gomem"
	task "github.com/langhuihui/gotask"
	mpegts "m7s.live/v5/pkg/format/ts"
)

type Receiver struct {
	task.Task
	mpegts.MpegTsStream
	srt.Conn
}

func (r *Receiver) Start() error {
	r.Allocator = gomem.NewScalableMemoryAllocator(1 << gomem.MinPowerOf2)
	r.Using(r.Allocator, r.Publisher)
	r.OnStop(r.Conn.Close)
	return nil
}

func (r *Receiver) Run() error {
	for !r.IsStopped() {
		packet, err := r.ReadPacket()
		if err != nil {
			return err
		}
		err = r.Feed(bytes.NewReader(packet.Data()))
		if err != nil {
			return err
		}
	}
	return r.StopReason()
}
