@@ -31,6 +31,8 @@ export class CallEventHandler {
31
31
calls : Map < string , MatrixCall > ;
32
32
callEventBuffer : MatrixEvent [ ] ;
33
33
candidateEventsByCall : Map < string , Array < MatrixEvent > > ;
34
+ nextSeqByCall : Map < string , number > = new Map ( ) ;
35
+ toDeviceEventBuffers : Map < string , Array < MatrixEvent > > = new Map ( ) ;
34
36
35
37
private eventBufferPromiseChain ?: Promise < void > ;
36
38
@@ -80,7 +82,45 @@ export class CallEventHandler {
80
82
} ;
81
83
82
84
private onToDeviceEvent = ( event : MatrixEvent ) : void => {
83
- this . callEventBuffer . push ( event ) ;
85
+ const content = event . getContent ( ) ;
86
+
87
+ if ( ! content . call_id ) {
88
+ this . callEventBuffer . push ( event ) ;
89
+ return ;
90
+ }
91
+
92
+ if ( ! this . nextSeqByCall . has ( content . call_id ) ) {
93
+ this . nextSeqByCall . set ( content . call_id , 0 ) ;
94
+ }
95
+
96
+ if ( content . seq === undefined ) {
97
+ this . callEventBuffer . push ( event ) ;
98
+ return ;
99
+ }
100
+
101
+ const nextSeq = this . nextSeqByCall . get ( content . call_id ) || 0 ;
102
+
103
+ if ( content . seq !== nextSeq ) {
104
+ if ( ! this . toDeviceEventBuffers . has ( content . call_id ) ) {
105
+ this . toDeviceEventBuffers . set ( content . call_id , [ ] ) ;
106
+ }
107
+
108
+ const buffer = this . toDeviceEventBuffers . get ( content . call_id ) ;
109
+ const index = buffer . findIndex ( ( e ) => e . getContent ( ) . seq > content . seq ) ;
110
+ buffer . splice ( index , 0 , event ) ;
111
+ } else {
112
+ const callId = content . call_id ;
113
+ this . callEventBuffer . push ( event ) ;
114
+ this . nextSeqByCall . set ( callId , content . seq + 1 ) ;
115
+
116
+ const buffer = this . toDeviceEventBuffers . get ( callId ) ;
117
+
118
+ while ( buffer . length > 0 && buffer [ 0 ] . getContent ( ) . seq === content . seq + 1 ) {
119
+ const nextEvent = buffer . pop ( ) ;
120
+ this . callEventBuffer . push ( nextEvent ) ;
121
+ this . nextSeqByCall . set ( callId , nextEvent . getContent ( ) . seq + 1 ) ;
122
+ }
123
+ }
84
124
} ;
85
125
86
126
private async evaluateEventBuffer ( eventBuffer : MatrixEvent [ ] ) {
@@ -122,6 +162,8 @@ export class CallEventHandler {
122
162
}
123
163
124
164
private async handleCallEvent ( event : MatrixEvent ) {
165
+ this . client . emit ( "received_voip_event" , event ) ;
166
+
125
167
const content = event . getContent ( ) ;
126
168
const callRoomId = (
127
169
event . getRoomId ( ) ||
0 commit comments