-
Notifications
You must be signed in to change notification settings - Fork 202
/
events.go
121 lines (97 loc) · 1.94 KB
/
events.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package engine
import (
"reflect"
"time"
"m7s.live/engine/v4/common"
)
type Event[T any] struct {
Time time.Time
Target T `json:"-" yaml:"-"`
}
func CreateEvent[T any](target T) (event Event[T]) {
event.Time = time.Now()
event.Target = target
return
}
// PulseEvent 心跳事件
type PulseEvent struct {
Event[struct{}]
}
type StreamEvent struct {
Event[*Stream]
}
// StateEvent 状态机事件
type StateEvent struct {
StreamEvent
Action StreamAction
From StreamState
}
// ErrorEvent 错误事件
type ErrorEvent struct {
Event[any]
Error error
}
func (se StateEvent) Next() (next StreamState, ok bool) {
next, ok = StreamFSM[se.From][se.Action]
return
}
type SEwaitPublish struct {
StateEvent
Publisher IPublisher
}
type SEpublish struct {
StateEvent
}
type SEtrackAvaliable struct {
StateEvent
}
type SErepublish struct {
StateEvent
}
type SEwaitClose struct {
StateEvent
}
type SEclose struct {
StateEvent
}
type SEcreate struct {
StreamEvent
}
type SEKick struct {
Event[struct{}]
}
type UnsubscribeEvent struct {
Event[ISubscriber]
}
type AddTrackEvent struct {
Event[common.Track]
}
// InvitePublishEvent 邀请推流事件(按需拉流)
type InvitePublish struct {
Event[string]
}
func TryInvitePublish(streamPath string) {
s := Streams.Get(streamPath)
if s == nil || s.Publisher == nil {
EventBus <- InvitePublish{Event: CreateEvent(streamPath)}
}
}
// InviteTrackEvent 邀请推送指定 Track 事件(转码需要)
type InviteTrackEvent struct {
Event[string]
ISubscriber
}
func InviteTrack(name string, suber ISubscriber) {
EventBus <- InviteTrackEvent{Event: CreateEvent(name), ISubscriber: suber}
}
var handlers = make(map[reflect.Type][]any)
func ListenEvent[T any](handler func(event T)) {
t := reflect.TypeOf(handler).In(0)
handlers[t] = append(handlers[t], handler)
}
func EmitEvent[T any](event T) {
t := reflect.TypeOf(event)
for _, handler := range handlers[t] {
handler.(func(event T))(event)
}
}