forked from Monibuca/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.go
90 lines (81 loc) · 1.8 KB
/
hook.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
package engine
import (
"context"
"reflect"
"runtime"
"sync"
)
type TransCodeReq struct {
*Subscriber
RequestCodec string
}
const (
HOOK_SUBSCRIBE = "Subscribe"
HOOK_UNSUBSCRIBE = "UnSubscibe"
HOOK_STREAMCLOSE = "StreamClose"
HOOK_PUBLISH = "Publish"
HOOK_REQUEST_TRANSAUDIO = "RequestTransAudio"
)
var Hooks = make(map[string]*RingBuffer)
var hookLocker sync.Mutex
func addHookRing(name string) (r *RingBuffer) {
r = r.Init(context.TODO(), 10)
Hooks[name] = r
return
}
func AddHooks(hooks map[string]interface{}) {
hookLocker.Lock()
for name, hook := range hooks {
rl, ok := Hooks[name]
if !ok {
rl = addHookRing(name)
}
vf := reflect.ValueOf(hook)
if vf.Kind() != reflect.Func {
panic("callback is not a function")
}
go rl.Clone().ReadLoop(vf.Call)
}
hookLocker.Unlock()
}
func AddHook(name string, callback interface{}) {
hookLocker.Lock()
rl, ok := Hooks[name]
if !ok {
rl = addHookRing(name)
}
hookLocker.Unlock()
vf := reflect.ValueOf(callback)
if vf.Kind() != reflect.Func {
panic("callback is not a function")
}
rl.Clone().ReadLoop(vf.Call)
}
func AddHookConditional(name string, callback interface{}, goon func() bool) {
hookLocker.Lock()
rl, ok := Hooks[name]
if !ok {
rl = addHookRing(name)
}
hookLocker.Unlock()
vf := reflect.ValueOf(callback)
if vf.Kind() != reflect.Func {
panic("callback is not a function")
}
rl.Clone().ReadLoopConditional(vf.Call, goon)
}
func TriggerHook(name string, payload ...interface{}) {
args := make([]reflect.Value, len(payload))
for i, arg := range payload {
args[i] = reflect.ValueOf(arg)
}
defer runtime.Gosched() //防止连续写入
hookLocker.Lock()
defer hookLocker.Unlock()
if rl, ok := Hooks[name]; ok {
rl.Write(args)
} else {
rl = addHookRing(name)
rl.Write(args)
}
}