engine

package module
v3.0.0-alpha1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2021 License: AGPL-3.0 Imports: 17 Imported by: 28

README

m7s核心引擎

该项目为m7s的引擎部分,该部分逻辑是流媒体服务器的核心转发逻辑。仅包含最基础的功能,不含任何网络协议部分,但包含了一个插件的引入机制,其他功能均由插件实现

引擎的基本功能

  • 引擎初始化会加载配置文件,并逐个调用插件的Run函数
  • 具有发布功能的插件,会通过GetStream函数创建一个流,即Stream对象,这个Stream对象随后可以被订阅
  • Stream对象中含有两个列表,一个是VideoTracks一个是AudioTracks用来存放视频数据和音频数据
  • 每一个VideoTrack或者AudioTrack中包含一个RingBuffer,用来存储发布者提供的数据,同时提供订阅者访问。
  • 具有订阅功能的插件,会通过GetStream函数获取到一个流,然后选择VideoTracks、AudioTracks里面的RingBuffer进行连续的读取

发布插件如何发布流

以rtmp协议为例子

if pub := new(engine.Publisher); pub.Publish(streamPath) {
    pub.Type = "RTMP"
    stream = pub.Stream
    err = nc.SendMessage(SEND_STREAM_BEGIN_MESSAGE, nil)
    err = nc.SendMessage(SEND_PUBLISH_START_MESSAGE, newPublishResponseMessageData(nc.streamID, NetStream_Publish_Start, Level_Status))
} else {
    err = nc.SendMessage(SEND_PUBLISH_RESPONSE_MESSAGE, newPublishResponseMessageData(nc.streamID, NetStream_Publish_BadName, Level_Error))
}

默认会创建一个VideoTrack和一个AudioTrack 当我们接收到数据的时候就可以朝里面填充物数据了

rec_video = func(msg *Chunk) {
    // 等待AVC序列帧
    if msg.Body[1] != 0 {
        return
    }
    vt := stream.VideoTracks[0]
    var ts_video uint32
    var info codec.AVCDecoderConfigurationRecord
    //0:codec,1:IsAVCSequence,2~4:compositionTime
    if _, err := info.Unmarshal(msg.Body[5:]); err == nil {
        vt.SPSInfo, err = codec.ParseSPS(info.SequenceParameterSetNALUnit)
        vt.SPS = info.SequenceParameterSetNALUnit
        vt.PPS = info.PictureParameterSetNALUnit
    }
    vt.RtmpTag = msg.Body
    nalulenSize := int(info.LengthSizeMinusOne&3 + 1)
    rec_video = func(msg *Chunk) {
        nalus := msg.Body[5:]
        if msg.Timestamp == 0xffffff {
            ts_video += msg.ExtendTimestamp
        } else {
            ts_video += msg.Timestamp // 绝对时间戳
        }
        for len(nalus) > nalulenSize {
            nalulen := 0
            for i := 0; i < nalulenSize; i++ {
                nalulen += int(nalus[i]) << (8 * (nalulenSize - i - 1))
            }
            vt.Push(ts_video, nalus[nalulenSize:nalulen+nalulenSize])
            nalus = nalus[nalulen+nalulenSize:]
        }
    }
    close(stream.WaitPub)
}

在填充数据之前,需要获取到SPS和PPS,然后设置好,因为订阅者需要先发送这个数据 然后通过Track到Push函数将数据填充到RingBuffer里面去

订阅插件如何订阅流

var subscriber engine.Subscriber
subscriber.Type = "RTMP"
subscriber.ID = fmt.Sprintf("%s|%d", conn.RemoteAddr().String(), nc.streamID)
if err = subscriber.Subscribe(streamPath); err == nil {
    streams[nc.streamID] = &subscriber
    err = nc.SendMessage(SEND_CHUNK_SIZE_MESSAGE, uint32(nc.writeChunkSize))
    err = nc.SendMessage(SEND_STREAM_IS_RECORDED_MESSAGE, nil)
    err = nc.SendMessage(SEND_STREAM_BEGIN_MESSAGE, nil)
    err = nc.SendMessage(SEND_PLAY_RESPONSE_MESSAGE, newPlayResponseMessageData(nc.streamID, NetStream_Play_Reset, Level_Status))
    err = nc.SendMessage(SEND_PLAY_RESPONSE_MESSAGE, newPlayResponseMessageData(nc.streamID, NetStream_Play_Start, Level_Status))
    vt, at := subscriber.VideoTracks[0], subscriber.AudioTracks[0]
    err = nc.SendMessage(SEND_FULL_VDIEO_MESSAGE, &AVPack{Payload: vt.RtmpTag})
    if at.SoundFormat == 10 {
        err = nc.SendMessage(SEND_FULL_AUDIO_MESSAGE, &AVPack{Payload: at.RtmpTag})
    }
    var lastAudioTime, lastVideoTime uint32
    go (&engine.TrackCP{at, vt}).Play(subscriber.Context, func(pack engine.AudioPack) {
        if lastAudioTime == 0 {
            lastAudioTime = pack.Timestamp
        }
        t := pack.Timestamp - lastAudioTime
        lastAudioTime = pack.Timestamp
        l := len(pack.Payload) + 1
        if at.SoundFormat == 10 {
            l++
        }
        payload := utils.GetSlice(l)
        defer utils.RecycleSlice(payload)
        payload[0] = at.RtmpTag[0]
        if at.SoundFormat == 10 {
            payload[1] = 1
        }
        copy(payload[2:], pack.Payload)
        err = nc.SendMessage(SEND_AUDIO_MESSAGE, &AVPack{Timestamp: t, Payload: payload})
    }, func(pack engine.VideoPack) {
        if lastVideoTime == 0 {
            lastVideoTime = pack.Timestamp
        }
        t := pack.Timestamp - lastVideoTime
        lastVideoTime = pack.Timestamp
        payload := utils.GetSlice(9 + len(pack.Payload))
        defer utils.RecycleSlice(payload)
        if pack.NalType == codec.NALU_IDR_Picture {
            payload[0] = 0x17
        } else {
            payload[0] = 0x27
        }
        payload[1] = 0x01
        utils.BigEndian.PutUint32(payload[5:], uint32(len(pack.Payload)))
        copy(payload[9:], pack.Payload)
        err = nc.SendMessage(SEND_VIDEO_MESSAGE, &AVPack{Timestamp: t, Payload: payload})
    })
}
  • 在发送数据前,需要先发送音视频对序列帧
  • 这里使用了TrackCP类将一对音视频Track组合在一起,然后调用Play函数传入两个回调函数,一个接受音频一个接受视频
  • 有些协议音视频是分开发送的,就可以直接调用Track的Play即可

Documentation

Index

Constants

View Source
const Version = "3.0.1"

Variables

View Source
var (

	// ConfigRaw 配置信息的原始数据
	ConfigRaw []byte
	StartTime time.Time                        //启动时间
	Plugins   = make(map[string]*PluginConfig) // Plugins 所有的插件配置
)
View Source
var Hooks = NewRing_Hook()
View Source
var Streams sync.Map

Streams 所有的流集合

Functions

func AddHook

func AddHook(name string, channel chan interface{})

func AddHookWithContext

func AddHookWithContext(name string, channel chan interface{}, ctx context.Context)

func InstallPlugin

func InstallPlugin(opt *PluginConfig)

InstallPlugin 安装插件

func Run

func Run(configFile string) (err error)

Run 启动Monibuca引擎

func TriggerHook

func TriggerHook(hook Hook)

Types

type AudioPack

type AudioPack struct {
	Timestamp      uint32
	Payload        []byte
	SequenceNumber uint16
}

type AudioTrack

type AudioTrack struct {
	Track_Audio
	SoundFormat byte   //4bit
	SoundRate   int    //2bit
	SoundSize   byte   //1bit
	SoundType   byte   //1bit
	RtmpTag     []byte //rtmp协议需要先发这个帧
	ASC         []byte //audio special configure
}

func (*AudioTrack) Play added in v3.1.3

func (at *AudioTrack) Play(ctx context.Context, callback func(AudioPack))

func (*AudioTrack) Push

func (at *AudioTrack) Push(timestamp uint32, payload []byte)

Push 来自发布者推送的音频

type Hook

type Hook struct {
	Name    string
	Payload interface{}
}

type PluginConfig

type PluginConfig struct {
	Name      string                       //插件名称
	Config    interface{}                  //插件配置
	Version   string                       //插件版本
	Dir       string                       //插件代码路径
	Run       func()                       //插件启动函数
	HotConfig map[string]func(interface{}) //热修改配置
}

PluginConfig 插件配置定义

type Publisher

type Publisher struct {
	context.Context

	AutoUnPublish bool //	当无人订阅时自动停止发布
	*Stream       `json:"-"`
	Type          string //类型,用来区分不同的发布者
	// contains filtered or unexported fields
}

Publisher 发布者实体定义

func (*Publisher) Close

func (p *Publisher) Close()

Close 关闭发布者

func (*Publisher) Publish

func (p *Publisher) Publish(streamPath string) bool

Publish 发布者进行发布操作

func (*Publisher) Running

func (p *Publisher) Running() bool

Running 发布者是否正在发布

type RingItem_Audio

type RingItem_Audio struct {
	AudioPack
	sync.WaitGroup
	*bytes.Buffer
	UpdateTime time.Time
}

type RingItem_Hook

type RingItem_Hook struct {
	Hook
	sync.WaitGroup
	*bytes.Buffer
	UpdateTime time.Time
}

type RingItem_Video

type RingItem_Video struct {
	VideoPack
	sync.WaitGroup
	*bytes.Buffer
	UpdateTime time.Time
}

type Ring_Audio

type Ring_Audio struct {
	Current *RingItem_Audio

	Index byte
	// contains filtered or unexported fields
}

Ring 环形缓冲,使用数组实现

func NewRing_Audio

func NewRing_Audio() (r *Ring_Audio)

NewRing 创建Ring

func (*Ring_Audio) GetAt

func (r *Ring_Audio) GetAt(index byte) *RingItem_Audio

GetAt 获取指定索引处的引用

func (*Ring_Audio) GetBuffer

func (r *Ring_Audio) GetBuffer() *bytes.Buffer

func (*Ring_Audio) GetLast

func (r *Ring_Audio) GetLast() *RingItem_Audio

GetLast 获取上一个位置的引用

func (*Ring_Audio) GetNext

func (r *Ring_Audio) GetNext() *RingItem_Audio

GetNext 获取下一个位置的引用

func (*Ring_Audio) GoBack

func (r *Ring_Audio) GoBack()

GoBack 移动到上一个位置

func (*Ring_Audio) GoNext

func (r *Ring_Audio) GoNext()

GoNext 移动到下一个位置

func (*Ring_Audio) GoTo

func (r *Ring_Audio) GoTo(index byte)

GoTo 移动到指定索引处

func (*Ring_Audio) NextR

func (r *Ring_Audio) NextR()

NextR 读下一个

func (*Ring_Audio) NextW

func (r *Ring_Audio) NextW()

NextW 写下一个

func (*Ring_Audio) SubRing

func (r *Ring_Audio) SubRing(index byte) *Ring_Audio

func (*Ring_Audio) Timeout

func (r *Ring_Audio) Timeout(t time.Duration) bool

Timeout 发布者是否超时了

type Ring_Hook

type Ring_Hook struct {
	Current *RingItem_Hook

	Index byte
	// contains filtered or unexported fields
}

Ring 环形缓冲,使用数组实现

func NewRing_Hook

func NewRing_Hook() (r *Ring_Hook)

NewRing 创建Ring

func (*Ring_Hook) GetAt

func (r *Ring_Hook) GetAt(index byte) *RingItem_Hook

GetAt 获取指定索引处的引用

func (*Ring_Hook) GetBuffer

func (r *Ring_Hook) GetBuffer() *bytes.Buffer

func (*Ring_Hook) GetLast

func (r *Ring_Hook) GetLast() *RingItem_Hook

GetLast 获取上一个位置的引用

func (*Ring_Hook) GetNext

func (r *Ring_Hook) GetNext() *RingItem_Hook

GetNext 获取下一个位置的引用

func (*Ring_Hook) GoBack

func (r *Ring_Hook) GoBack()

GoBack 移动到上一个位置

func (*Ring_Hook) GoNext

func (r *Ring_Hook) GoNext()

GoNext 移动到下一个位置

func (*Ring_Hook) GoTo

func (r *Ring_Hook) GoTo(index byte)

GoTo 移动到指定索引处

func (*Ring_Hook) NextR

func (r *Ring_Hook) NextR()

NextR 读下一个

func (*Ring_Hook) NextW

func (r *Ring_Hook) NextW()

NextW 写下一个

func (*Ring_Hook) SubRing

func (r *Ring_Hook) SubRing(index byte) *Ring_Hook

func (*Ring_Hook) Timeout

func (r *Ring_Hook) Timeout(t time.Duration) bool

Timeout 发布者是否超时了

type Ring_Video

type Ring_Video struct {
	Current *RingItem_Video

	Index byte
	// contains filtered or unexported fields
}

Ring 环形缓冲,使用数组实现

func NewRing_Video

func NewRing_Video() (r *Ring_Video)

NewRing 创建Ring

func (*Ring_Video) GetAt

func (r *Ring_Video) GetAt(index byte) *RingItem_Video

GetAt 获取指定索引处的引用

func (*Ring_Video) GetBuffer

func (r *Ring_Video) GetBuffer() *bytes.Buffer

func (*Ring_Video) GetLast

func (r *Ring_Video) GetLast() *RingItem_Video

GetLast 获取上一个位置的引用

func (*Ring_Video) GetNext

func (r *Ring_Video) GetNext() *RingItem_Video

GetNext 获取下一个位置的引用

func (*Ring_Video) GoBack

func (r *Ring_Video) GoBack()

GoBack 移动到上一个位置

func (*Ring_Video) GoNext

func (r *Ring_Video) GoNext()

GoNext 移动到下一个位置

func (*Ring_Video) GoTo

func (r *Ring_Video) GoTo(index byte)

GoTo 移动到指定索引处

func (*Ring_Video) NextR

func (r *Ring_Video) NextR()

NextR 读下一个

func (*Ring_Video) NextW

func (r *Ring_Video) NextW()

NextW 写下一个

func (*Ring_Video) SubRing

func (r *Ring_Video) SubRing(index byte) *Ring_Video

func (*Ring_Video) Timeout

func (r *Ring_Video) Timeout(t time.Duration) bool

Timeout 发布者是否超时了

type Stream

type Stream struct {
	context.Context

	StreamPath string
	StartTime  time.Time //流的创建时间
	*Publisher
	Subscribers []*Subscriber // 订阅者
	VideoTracks []*VideoTrack
	AudioTracks []*AudioTrack
	WaitPub     chan struct{} `json:"-"` //用于订阅和等待发布者
	HasAudio    bool
	HasVideo    bool
	EnableVideo *bool
	EnableAudio *bool
	// contains filtered or unexported fields
}

Stream 流定义

func FindStream

func FindStream(streamPath string) *Stream

FindStream 根据流路径查找流

func GetStream

func GetStream(streamPath string) (result *Stream)

GetStream 根据流路径获取流,如果不存在则创建一个新的

func (*Stream) AddAudioTrack

func (r *Stream) AddAudioTrack() (at *AudioTrack)

func (*Stream) AddVideoTrack

func (r *Stream) AddVideoTrack() (vt *VideoTrack)

func (*Stream) Close

func (r *Stream) Close()

func (*Stream) PushAudio

func (r *Stream) PushAudio(ts uint32, payload []byte)

func (*Stream) PushVideo

func (r *Stream) PushVideo(ts uint32, payload []byte)

func (*Stream) Subscribe

func (r *Stream) Subscribe(s *Subscriber)

Subscribe 订阅流

func (*Stream) UnSubscribe

func (r *Stream) UnSubscribe(s *Subscriber)

UnSubscribe 取消订阅流

type Subscriber

type Subscriber struct {
	context.Context
	*Stream `json:"-"`
	SubscriberInfo

	Sign       string
	OffsetTime uint32
	// contains filtered or unexported fields
}

Subscriber 订阅者实体定义

func DeleteSliceItem_Subscriber

func DeleteSliceItem_Subscriber(slice []*Subscriber, item *Subscriber) []*Subscriber

func (*Subscriber) Close

func (s *Subscriber) Close()

Close 关闭订阅者

func (*Subscriber) IsClosed

func (s *Subscriber) IsClosed() bool

IsClosed 检查订阅者是否已经关闭

func (*Subscriber) MarshalJSON

func (s *Subscriber) MarshalJSON() ([]byte, error)

func (*Subscriber) Subscribe

func (s *Subscriber) Subscribe(streamPath string) error

Subscribe 开始订阅

type SubscriberInfo

type SubscriberInfo struct {
	ID            string
	TotalDrop     int //总丢帧
	TotalPacket   int
	Type          string
	BufferLength  int
	Delay         uint32
	SubscribeTime time.Time
}

SubscriberInfo 订阅者可序列化信息,用于控制台输出

type Track

type Track interface {
	Push(uint32, []byte)
}

type TrackCP

type TrackCP struct {
	Audio *AudioTrack
	Video *VideoTrack
}

func (*TrackCP) Play

func (tcp *TrackCP) Play(ctx context.Context, cba func(AudioPack), cbv func(VideoPack))

type Track_Audio

type Track_Audio struct {
	Buffer      *Ring_Audio `json:"-"`
	PacketCount int
	CodecID     byte
	BPS         int
	// contains filtered or unexported fields
}

func (*Track_Audio) GetBPS

func (t *Track_Audio) GetBPS(payloadLen int)

type Track_Video

type Track_Video struct {
	Buffer      *Ring_Video `json:"-"`
	PacketCount int
	CodecID     byte
	BPS         int
	// contains filtered or unexported fields
}

func (*Track_Video) GetBPS

func (t *Track_Video) GetBPS(payloadLen int)

type VideoPack

type VideoPack struct {
	Timestamp uint32
	Payload   []byte //NALU
	NalType   byte
	Sequence  int
}

type VideoTrack

type VideoTrack struct {
	FirstScreen byte //最近的关键帧位置,首屏渲染
	Track_Video
	SPS     []byte
	PPS     []byte
	SPSInfo codec.SPSInfo
	GOP     byte   //关键帧间隔
	RtmpTag []byte //rtmp需要先发送一个序列帧,包含SPS和PPS
}

func (*VideoTrack) Play added in v3.1.3

func (vt *VideoTrack) Play(ctx context.Context, callback func(VideoPack))

func (*VideoTrack) Push

func (vt *VideoTrack) Push(timestamp uint32, payload []byte)

Push 来自发布者推送的视频

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL