-
Notifications
You must be signed in to change notification settings - Fork 6
/
stream_manager.go
114 lines (90 loc) · 2.02 KB
/
stream_manager.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
package main
import (
"sync"
)
var StreamManager *streamManager
func init() {
StreamManager = NewStreamManager()
}
type streamManager struct {
streams map[StreamID]*Stream
callIds map[string]*Stream // 本SipUA的CallID与Stream的关系
lock sync.RWMutex
}
// Add 添加Stream
// 如果Stream已经存在, 返回oldStream与false
func (s *streamManager) Add(stream *Stream) (*Stream, bool) {
s.lock.Lock()
defer s.lock.Unlock()
old, ok := s.streams[stream.ID]
if ok {
return old, false
}
s.streams[stream.ID] = stream
return nil, true
}
func (s *streamManager) AddWithCallId(id string, stream *Stream) bool {
s.lock.Lock()
defer s.lock.Unlock()
if _, ok := s.callIds[id]; ok {
return false
}
s.callIds[id] = stream
return true
}
func (s *streamManager) Find(id StreamID) *Stream {
s.lock.RLock()
defer s.lock.RUnlock()
if value, ok := s.streams[id]; ok {
return value
}
return nil
}
func (s *streamManager) FindWithCallId(id string) *Stream {
s.lock.RLock()
defer s.lock.RUnlock()
if value, ok := s.callIds[id]; ok {
return value
}
return nil
}
func (s *streamManager) Remove(id StreamID) *Stream {
s.lock.Lock()
defer s.lock.Unlock()
stream, ok := s.streams[id]
delete(s.streams, id)
if ok && stream.DialogRequest != nil {
callID, _ := stream.DialogRequest.CallID()
delete(s.callIds, callID.Value())
return stream
}
return nil
}
func (s *streamManager) RemoveWithCallId(id string) *Stream {
s.lock.Lock()
defer s.lock.Unlock()
stream, ok := s.callIds[id]
if ok {
delete(s.callIds, id)
delete(s.streams, stream.ID)
return stream
}
return nil
}
func (s *streamManager) PopAll() []*Stream {
s.lock.Lock()
defer s.lock.Unlock()
var streams []*Stream
for _, stream := range s.streams {
streams = append(streams, stream)
}
s.streams = make(map[StreamID]*Stream)
s.callIds = make(map[string]*Stream)
return streams
}
func NewStreamManager() *streamManager {
return &streamManager{
streams: make(map[StreamID]*Stream, 64),
callIds: make(map[string]*Stream, 64),
}
}