@@ -31,6 +31,8 @@ export class CallEventHandler {
3131 calls : Map < string , MatrixCall > ;
3232 callEventBuffer : MatrixEvent [ ] ;
3333 candidateEventsByCall : Map < string , Array < MatrixEvent > > ;
34+ nextSeqByCall : Map < string , number > = new Map ( ) ;
35+ toDeviceEventBuffers : Map < string , Array < MatrixEvent > > = new Map ( ) ;
3436
3537 private eventBufferPromiseChain ?: Promise < void > ;
3638
@@ -80,7 +82,45 @@ export class CallEventHandler {
8082 } ;
8183
8284 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+ }
84124 } ;
85125
86126 private async evaluateEventBuffer ( eventBuffer : MatrixEvent [ ] ) {
@@ -122,6 +162,8 @@ export class CallEventHandler {
122162 }
123163
124164 private async handleCallEvent ( event : MatrixEvent ) {
165+ this . client . emit ( "received_voip_event" , event ) ;
166+
125167 const content = event . getContent ( ) ;
126168 const callRoomId = (
127169 event . getRoomId ( ) ||
0 commit comments