engine

package module
v3.0.0-alpha9 Latest Latest
Warning

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

Go to latest
Published: May 5, 2021 License: AGPL-3.0 Imports: 19 Imported by: 28 modules, 28 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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(vt.WaitFirst)
}

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

订阅插件如何订阅流

subscriber := engine.Subscriber{
    Type: "RTMP",
    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.GetVideoTrack("h264"), subscriber.OriginAudioTrack
    if vt != nil {
        var lastVideoTime uint32
        err = nc.SendMessage(SEND_FULL_VDIEO_MESSAGE, &AVPack{Payload: vt.RtmpTag})
        subscriber.OnVideo = func(pack engine.VideoPack) {
            if lastVideoTime == 0 {
                lastVideoTime = pack.Timestamp
            }
            t := pack.Timestamp - lastVideoTime
            lastVideoTime = pack.Timestamp
            payload := codec.Nalu2RTMPTag(pack.Payload)
            defer utils.RecycleSlice(payload)
            err = nc.SendMessage(SEND_VIDEO_MESSAGE, &AVPack{Timestamp: t, Payload: payload})
        }
    }
    if at != nil {
        var lastAudioTime uint32
        var aac byte
        if at.SoundFormat == 10 {
            aac = at.RtmpTag[0]
            err = nc.SendMessage(SEND_FULL_AUDIO_MESSAGE, &AVPack{Payload: at.RtmpTag})
        }
        subscriber.OnAudio = func(pack engine.AudioPack) {
            if lastAudioTime == 0 {
                lastAudioTime = pack.Timestamp
            }
            t := pack.Timestamp - lastAudioTime
            lastAudioTime = pack.Timestamp
            payload := codec.Audio2RTMPTag(aac, pack.Payload)
            defer utils.RecycleSlice(payload)
            err = nc.SendMessage(SEND_AUDIO_MESSAGE, &AVPack{Timestamp: t, Payload: payload})
        }
    }
    go subscriber.Play(at, vt)
}
  • 在发送数据前,需要先发送音视频的序列帧

Documentation

Index

Constants

View Source
const (
	HOOK_SUBSCRIBE          = "Subscribe"
	HOOK_UNSUBSCRIBE        = "UnSubscibe"
	HOOK_STREAMCLOSE        = "StreamClose"
	HOOK_PUBLISH            = "Publish"
	HOOK_REQUEST_TRANSAUDIO = "RequestTransAudio"
)
View Source
const Version = "3.0.1"

Variables

View Source
var (

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

Streams 所有的流集合

Functions

func AddHook

func AddHook(name string, callback func(interface{}))

func AddHookWithContext

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

func DisposeTracks

func DisposeTracks(tracks ...Track)

一定要在写入Track的协程中调用该函数,这个函数的作用是防止订阅者无限等待

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
}

func (*AudioPack) ToRTMPTag

func (at *AudioPack) ToRTMPTag(aac byte) []byte

type AudioTrack

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

func NewAudioTrack

func NewAudioTrack() *AudioTrack

func (*AudioTrack) Push

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

Push 来自发布者推送的音频

func (*AudioTrack) PushRTP

func (at *AudioTrack) PushRTP(pack rtp.Packet)

func (*AudioTrack) SetASC

func (at *AudioTrack) SetASC(asc []byte)

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 发布者是否正在发布

func (*Publisher) Update

func (p *Publisher) Update()

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      sync.Map
	AudioTracks      sync.Map
	OriginVideoTrack *VideoTrack //原始视频轨
	OriginAudioTrack *AudioTrack //原始音频轨
	// 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(codec string, at *AudioTrack) *AudioTrack

func (*Stream) AddVideoTrack

func (r *Stream) AddVideoTrack(codec string, vt *VideoTrack) *VideoTrack

func (*Stream) Close

func (r *Stream) Close()

func (*Stream) SetOriginAT

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

func (*Stream) SetOriginVT

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

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 `json:"-"`

	Ctx2          context.Context `json:"-"`
	*Stream       `json:"-"`
	ID            string
	TotalDrop     int //总丢帧
	TotalPacket   int
	Type          string
	BufferLength  int
	Delay         uint32
	SubscribeTime time.Time
	Sign          string
	OffsetTime    uint32
	OnAudio       func(pack AudioPack) `json:"-"`
	OnVideo       func(pack VideoPack) `json:"-"`
	// contains filtered or unexported fields
}

Subscriber 订阅者实体定义

func DeleteSliceItem_Subscriber

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

func (*Subscriber) Close

func (s *Subscriber) Close()

Close 关闭订阅者

func (*Subscriber) GetAudioTrack

func (s *Subscriber) GetAudioTrack(codecs ...string) (at *AudioTrack)

func (*Subscriber) GetVideoTrack

func (s *Subscriber) GetVideoTrack(codec string) *VideoTrack

func (*Subscriber) IsClosed

func (s *Subscriber) IsClosed() bool

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

func (*Subscriber) Play

func (s *Subscriber) Play(at *AudioTrack, vt *VideoTrack)

Play 开始播放

func (*Subscriber) PlayAudio

func (s *Subscriber) PlayAudio(at *AudioTrack)

func (*Subscriber) PlayVideo

func (s *Subscriber) PlayVideo(vt *VideoTrack)

func (*Subscriber) Subscribe

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

Subscribe 开始订阅 将Subscriber与Stream关联

func (*Subscriber) WaitAudioTrack

func (s *Subscriber) WaitAudioTrack(codecs ...string) *AudioTrack

func (*Subscriber) WaitVideoTrack

func (s *Subscriber) WaitVideoTrack(codec string) *VideoTrack

type TSSlice

type TSSlice []uint32

func (TSSlice) Len

func (s TSSlice) Len() int

func (TSSlice) Less

func (s TSSlice) Less(i, j int) bool

func (TSSlice) Swap

func (s TSSlice) Swap(i, j int)

type Track

type Track interface {
	PushRTP(rtp.Packet)
	GetBPS(int)
	Dispose()
}

type TrackWaiter

type TrackWaiter struct {
	Track
	*sync.Cond
}

func (*TrackWaiter) Ok

func (tw *TrackWaiter) Ok(t Track)

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) Dispose

func (t *Track_Audio) Dispose()

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) Dispose

func (t *Track_Video) Dispose()

func (*Track_Video) GetBPS

func (t *Track_Video) GetBPS(payloadLen int)

type TransCodeReq

type TransCodeReq struct {
	*Subscriber
	RequestCodec string
}

type VideoPack

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

func (*VideoPack) ToRTMPTag

func (vp *VideoPack) ToRTMPTag() []byte

type VideoTrack

type VideoTrack struct {
	IDRIndex byte //最近的关键帧位置,首屏渲染
	Track_Video
	SPS     []byte `json:"-"`
	PPS     []byte `json:"-"`
	SPSInfo codec.SPSInfo
	GOP     byte            //关键帧间隔
	RtmpTag []byte          `json:"-"` //rtmp需要先发送一个序列帧,包含SPS和PPS
	WaitIDR context.Context `json:"-"`
	// contains filtered or unexported fields
}

func NewVideoTrack

func NewVideoTrack() *VideoTrack

func (*VideoTrack) Push

func (vt *VideoTrack) Push(pack VideoPack)

Push 来自发布者推送的视频

func (*VideoTrack) PushRTP

func (vt *VideoTrack) PushRTP(pack rtp.Packet)

func (*VideoTrack) SetRtmpTag

func (vt *VideoTrack) SetRtmpTag()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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