engine

package module
v3.0.0-beta7 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2021 License: AGPL-3.0 Imports: 22 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()

Functions

func AddHook

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

func AddHookWithContext

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

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
	Raw            []byte
	SequenceNumber uint16
}

func (AudioPack) Copy

func (ap AudioPack) Copy(ts uint32) AudioPack

type AudioTrack

type AudioTrack struct {
	Track_Audio
	SoundRate       int    //2bit
	SoundSize       byte   //1bit
	Channels        byte   //1bit
	ExtraData       []byte `json:"-"` //rtmp协议需要先发这个帧
	PushByteStream  func(pack AudioPack)
	PushRaw         func(pack AudioPack)
	WriteByteStream func(writer io.Writer, pack AudioPack) //使用函数写入,避免申请内存
}

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 RTPAudio

type RTPAudio struct {
	RTPPublisher
	*AudioTrack
}

type RTPPublisher

type RTPPublisher struct {
	rtp.Packet
	Push func(payload []byte)
}

type RTPVideo

type RTPVideo struct {
	RTPPublisher
	*VideoTrack
}

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
	Flag  int32 // 0:不在写入,1:正在写入,2:已销毁
	// contains filtered or unexported fields
}

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

func NewRing_Audio

func NewRing_Audio() (r *Ring_Audio)

NewRing 创建Ring

func (*Ring_Audio) Dispose

func (r *Ring_Audio) Dispose()

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() bool

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
	Flag  int32 // 0:不在写入,1:正在写入,2:已销毁
	// contains filtered or unexported fields
}

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

func NewRing_Video

func NewRing_Video() (r *Ring_Video)

NewRing 创建Ring

func (*Ring_Video) Dispose

func (r *Ring_Video) Dispose()

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() bool

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
	Type          string        //流类型,来自发布者
	StartTime     time.Time     //流的创建时间
	Subscribers   []*Subscriber // 订阅者
	VideoTracks   Tracks
	AudioTracks   Tracks
	AutoUnPublish bool              //	当无人订阅时自动停止发布
	Transcoding   map[string]string //转码配置,key:目标编码,value:发布者提供的编码

	Close func() `json:"-"`
	// contains filtered or unexported fields
}

Stream 流定义

func FindStream

func FindStream(streamPath string) *Stream

FindStream 根据流路径查找流

func (*Stream) NewAudioTrack

func (s *Stream) NewAudioTrack(codec byte) (at *AudioTrack)

func (*Stream) NewRTPAudio

func (s *Stream) NewRTPAudio(codec byte) (r *RTPAudio)

func (*Stream) NewRTPVideo

func (s *Stream) NewRTPVideo(codec byte) (r *RTPVideo)

func (*Stream) NewVideoTrack

func (s *Stream) NewVideoTrack(codec byte) (vt *VideoTrack)

func (*Stream) Publish

func (r *Stream) Publish() bool

Publish 发布者进行发布操作

func (*Stream) Subscribe

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

Subscribe 订阅流

func (*Stream) UnSubscribe

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

UnSubscribe 取消订阅流

func (*Stream) Update

func (r *Stream) Update()

func (*Stream) WaitAudioTrack

func (r *Stream) WaitAudioTrack(codecs ...string) *AudioTrack

TODO: 触发转码逻辑

func (*Stream) WaitVideoTrack

func (r *Stream) WaitVideoTrack(codecs ...string) *VideoTrack

type StreamCollection

type StreamCollection struct {
	sync.RWMutex
	// contains filtered or unexported fields
}
var Streams StreamCollection

Streams 所有的流集合

func (*StreamCollection) Delete

func (sc *StreamCollection) Delete(streamPath string)

func (*StreamCollection) GetStream

func (sc *StreamCollection) GetStream(streamPath string) *Stream

func (*StreamCollection) ToList

func (sc *StreamCollection) ToList() (r []*Stream)

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
	SubscribeArgs    url.Values
	OnAudio          func(pack AudioPack) `json:"-"`
	OnVideo          func(pack VideoPack) `json:"-"`
	ByteStreamFormat bool
	// 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) 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关联

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 {
	GetBPS(int)
	Dispose()
}

type TrackWaiter

type TrackWaiter struct {
	Track
	*sync.Cond `json:"-"`
}

func (*TrackWaiter) Dispose

func (tw *TrackWaiter) Dispose()

func (*TrackWaiter) Ok

func (tw *TrackWaiter) Ok(t Track)

func (*TrackWaiter) Wait

func (tw *TrackWaiter) Wait(c chan<- Track)

type Track_Audio

type Track_Audio struct {
	Buffer      *Ring_Audio `json:"-"`
	Stream      *Stream     `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:"-"`
	Stream      *Stream     `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 Tracks

type Tracks struct {
	sync.RWMutex
	context.Context
	// contains filtered or unexported fields
}

func (*Tracks) AddTrack

func (ts *Tracks) AddTrack(codec string, t Track)

func (*Tracks) Codecs

func (ts *Tracks) Codecs() (result []string)

func (*Tracks) Dispose

func (ts *Tracks) Dispose()

func (*Tracks) GetTrack

func (ts *Tracks) GetTrack(codec string) (tw *TrackWaiter, ok bool)

func (*Tracks) Init

func (ts *Tracks) Init()

func (*Tracks) WaitTrack

func (ts *Tracks) WaitTrack(codecs ...string) Track

type TransCodeReq

type TransCodeReq struct {
	*Subscriber
	RequestCodec string
}

type VideoPack

type VideoPack struct {
	Timestamp       uint32
	CompositionTime uint32
	Payload         []byte
	NALUs           [][]byte
	IDR             bool // 是否关键帧
	Sequence        int
}

func (VideoPack) Clone

func (vp VideoPack) Clone() VideoPack

func (VideoPack) Copy

func (vp VideoPack) Copy(ts uint32) VideoPack

type VideoTrack

type VideoTrack struct {
	IDRIndex byte //最近的关键帧位置,首屏渲染
	Track_Video
	SPSInfo   codec.SPSInfo
	GOP       byte            //关键帧间隔
	ExtraData *VideoPack      `json:"-"` //H264(SPS、PPS) H265(VPS、SPS、PPS)
	WaitIDR   context.Context `json:"-"`

	PushByteStream  func(pack VideoPack)
	PushNalu        func(pack VideoPack)
	WriteByteStream func(writer io.Writer, pack VideoPack) //使用函数写入,避免申请内存
	// contains filtered or unexported fields
}

func (*VideoTrack) PushAnnexB

func (vt *VideoTrack) PushAnnexB(pack VideoPack)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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