-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathengine.go
More file actions
1676 lines (1581 loc) · 52.3 KB
/
Copy pathengine.go
File metadata and controls
1676 lines (1581 loc) · 52.3 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package meowcaller
import (
"context"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
"unsafe"
"github.com/purpshell/meowcaller/signaling"
"go.mau.fi/whatsmeow"
waBinary "go.mau.fi/whatsmeow/binary"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
"google.golang.org/protobuf/proto"
)
// engine is the internal media + signaling engine behind Client/Call. It owns the
// whatsmeow event wiring (offer / preaccept / accept / relaylatency / mute_v2 / ack /
// terminate), the low-level <ack>/<call> node interception, the relay election and the
// per-frame media loop (encode a Player's frames out, decode the peer's frames into a
// sink). This is where the orchestration formerly hand-rolled in examples/cli has been
// lifted to; Client and Call are the public face over it.
type engine struct {
c *Client
mu sync.Mutex
calls map[string]*engineCall // keyed by call-id
sendCallNode func(context.Context, waBinary.Node) error
requestCallNode func(context.Context, waBinary.Node, string) (*waBinary.Node, error)
rawCallHookErr error
}
// engineCall is the engine's per-call state: the public Call handle plus the inputs
// needed to bring media up (the decrypted callKey and the relay endpoint, both of
// which can arrive separately), the media goroutine cancel handle, and the deferred
// accept bookkeeping.
type engineCall struct {
call *Call
callKey []byte
relay *relayData
selfLID string
peerLID string
creator types.JID // call-creator JID (for accept/relaylatency)
from types.JID // the <call> "from" — where stanzas are addressed
direction CallDirection
codec AudioCodec // audio codec for this call, selected from voip_settings (MLow default)
localVideo bool // this client is sending, or has requested to send, video
remoteVideo bool // the peer is sending video to this client
videoGate bool // outbound upgrade is waiting for peer acceptance
peerVideoUpgrade bool // the peer's inbound upgrade is waiting for local acceptance
videoTx *videoSender // video send pipeline, live while media runs
appDataTx *appDataSender
rekeyPeer func(string) error
group bool
groupUpdate *groupCallUpdate
groupReceivers *participantReceiveRegistry
groupRawEpoch []byte
groupEpochTxID uint32
hasGroupEpoch bool
started bool
cancel context.CancelFunc // tears down this call's media goroutine
waitingRoomCancel context.CancelFunc
inviteSelfDevice groupCallDevice
invitePeerDevice groupCallDevice
// The callee <accept> is deferred until the caller's <mute_v2> arrives.
acceptPending bool
}
// newEngine creates the engine for a Client.
func newEngine(c *Client) *engine {
e := &engine{c: c, calls: map[string]*engineCall{}}
if c != nil && c.wa != nil {
e.sendCallNode = func(ctx context.Context, node waBinary.Node) error {
return c.wa.DangerousInternals().SendNode(ctx, node)
}
e.requestCallNode = func(ctx context.Context, node waBinary.Node, requestID string) (*waBinary.Node, error) {
di := c.wa.DangerousInternals()
waiter := di.WaitResponse(requestID)
defer di.CancelResponse(requestID, waiter)
if err := di.SendNode(ctx, node); err != nil {
return nil, err
}
select {
case response := <-waiter:
if response == nil {
return nil, errors.New("meowcaller: call request returned no response")
}
return response, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
return e
}
func (e *engine) requireRawCallAdapter() error {
// Source of truth: https://github.com/tulir/whatsmeow/blob/e9a033b24933cc8d90fa5ff8991b1268ba80a140/client.go#L110-L120
if e == nil {
return errors.New("meowcaller: raw call adapter is unavailable")
}
e.mu.Lock()
defer e.mu.Unlock()
if e.rawCallHookErr != nil {
return fmt.Errorf("meowcaller: raw call adapter is unavailable: %w", e.rawCallHookErr)
}
return nil
}
// onEndFn returns the Call's OnEnd listener under its lock (the field is unexported
// and guarded by Call.mu; same-package engine code reads it through here).
func (c *Call) onEndFn() func(string) {
c.mu.Lock()
defer c.mu.Unlock()
return c.onEnd
}
// onReadyFn returns the Call's OnReady listener under its lock.
func (c *Call) onReadyFn() func() {
c.mu.Lock()
defer c.mu.Unlock()
return c.onReady
}
// playerAndSink returns the Call's current Player and sink under its lock (the engine's
// media loop reads them every frame so a later Subscribe/Receive takes effect live).
func (c *Call) playerAndSink() (*Player, AudioSink) {
c.mu.Lock()
defer c.mu.Unlock()
return c.player, c.sink
}
// install wires the whatsmeow call event handlers and the <ack>/<call> interception.
// Call before the whatsmeow client connects.
func (e *engine) install() {
if err := e.installCallAckHook(); err != nil {
e.mu.Lock()
e.rawCallHookErr = err
e.mu.Unlock()
e.c.log.Error().Err(err).Msg("raw call adapter is unavailable")
}
e.c.wa.AddEventHandler(func(evt any) {
switch ev := evt.(type) {
case *events.CallOffer:
e.onOffer(ev)
case *events.CallPreAccept:
e.onPreAccept(ev)
case *events.CallAccept:
e.onAccept(ev)
case *events.CallRelayLatency:
e.onRelay(ev.CallID, ev.Data)
e.onRelayLatency(ev)
case *events.CallTransport:
e.onRelay(ev.CallID, ev.Data)
case *events.CallTerminate:
e.onTerminate(ev.CallID, ev.Reason)
case *events.CallReject:
e.onReject(ev)
case *events.UnknownCallEvent:
e.onUnknownCallEvent(ev.Node)
}
})
}
func (e *engine) sendReaction(callID, emoji string) error {
e.mu.Lock()
m := e.calls[callID]
if m == nil || m.call == nil || m.call.State() == CallPhaseEnded {
e.mu.Unlock()
return errors.New("meowcaller: call is not active")
}
sender := m.appDataTx
e.mu.Unlock()
if sender == nil {
return errAppDataUnavailable
}
return sender.sendReaction(emoji)
}
// entry returns (creating if needed) the per-call state for callID.
func (e *engine) entry(callID string) *engineCall {
if e.calls[callID] == nil {
e.calls[callID] = &engineCall{}
}
return e.calls[callID]
}
// lookup returns the per-call state for callID, or nil.
func (e *engine) lookup(callID string) *engineCall {
e.mu.Lock()
defer e.mu.Unlock()
return e.calls[callID]
}
func (e *engine) callIsVideo(callID string) bool {
e.mu.Lock()
defer e.mu.Unlock()
m := e.calls[callID]
return m != nil && (m.localVideo || m.remoteVideo)
}
func (e *engine) callIsSendingVideo(callID string) bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.calls[callID] != nil && e.calls[callID].localVideo
}
func (e *engine) callIsReceivingVideo(callID string) bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.calls[callID] != nil && e.calls[callID].remoteVideo
}
func (e *engine) transmitCallNode(ctx context.Context, node waBinary.Node) error {
if e.sendCallNode == nil {
return errors.New("meowcaller: call signaling is unavailable")
}
return e.sendCallNode(ctx, node)
}
func (e *engine) nextCallNodeID() string {
if e.c != nil && e.c.wa != nil {
return e.c.wa.GenerateMessageID()
}
var id [8]byte
_, _ = rand.Read(id[:])
return strings.ToUpper(hex.EncodeToString(id[:]))
}
// sendVideoFrame packetizes one encoded H.264 access unit and sends it to the relay, if a
// video send pipeline is live for the call.
func (e *engine) sendVideoFrame(callID string, au []byte, duration time.Duration) error {
e.mu.Lock()
var vs *videoSender
if m := e.calls[callID]; m != nil {
vs = m.videoTx
}
e.mu.Unlock()
if vs == nil {
return errors.New("meowcaller: call has no active video media")
}
vs.send(au, duration)
return nil
}
func (e *engine) transitionVideo(callID string, transition int) error {
e.mu.Lock()
m := e.calls[callID]
if m == nil || m.call == nil || m.call.State() == CallPhaseEnded {
e.mu.Unlock()
return errors.New("meowcaller: call is not active")
}
to, creator, sender := m.from, m.creator, m.videoTx
localVideoActive := m.localVideo
switch transition {
case signaling.VideoStateUpgradeRequestV2:
m.localVideo = true
m.videoGate = true
case signaling.VideoStateUpgradeAccept:
if !m.peerVideoUpgrade {
e.mu.Unlock()
return errors.New("meowcaller: no pending peer video upgrade")
}
m.peerVideoUpgrade = false
case signaling.VideoStateStopped:
m.localVideo = false
m.videoGate = false
default:
e.mu.Unlock()
return fmt.Errorf("meowcaller: unsupported local video transition %d", transition)
}
e.mu.Unlock()
if sender != nil {
if transition == signaling.VideoStateStopped {
sender.disable()
} else if transition == signaling.VideoStateUpgradeRequestV2 {
sender.enable(true)
}
}
build := func(state int, dec string, orientation *int) waBinary.Node {
return signaling.BuildVideoStateWithParams(signaling.VideoStateParams{
CallID: callID, To: to, CallCreator: creator, WrapperID: e.nextCallNodeID(),
State: state, Dec: dec, DeviceOrientation: orientation,
})
}
send := func(state int, dec string, orientation *int) error {
return e.transmitCallNode(context.Background(), build(state, dec, orientation))
}
var err error
switch transition {
case signaling.VideoStateUpgradeRequestV2:
orientation := 0
err = send(transition, signaling.VideoDecRequest, &orientation)
case signaling.VideoStateUpgradeAccept:
if !localVideoActive {
orientation := 0
err = send(signaling.VideoStateStopped, "", &orientation)
}
if err == nil {
err = send(transition, signaling.VideoDecAccept, nil)
}
case signaling.VideoStateStopped:
orientation := 0
err = send(transition, "", &orientation)
}
if err == nil || transition == signaling.VideoStateStopped {
return err
}
e.mu.Lock()
var currentSender *videoSender
if current := e.calls[callID]; current == m {
if transition == signaling.VideoStateUpgradeAccept {
current.peerVideoUpgrade = true
} else {
current.localVideo = false
current.videoGate = false
currentSender = current.videoTx
}
}
e.mu.Unlock()
if currentSender != nil {
currentSender.disable()
}
return err
}
func (e *engine) setVideoEnabled(callID string, enabled bool) error {
e.mu.Lock()
m := e.calls[callID]
if m == nil || m.call == nil || m.call.State() == CallPhaseEnded {
e.mu.Unlock()
return errors.New("meowcaller: call is not active")
}
m.localVideo = enabled
m.videoGate = false
to, creator, sender := m.from, m.creator, m.videoTx
e.mu.Unlock()
if sender != nil {
if enabled {
sender.enable(false)
} else {
sender.disable()
}
}
state, dec := signaling.VideoStateDisabled, ""
if enabled {
state, dec = signaling.VideoStateEnabled, signaling.VideoStateDecH264
}
node := signaling.BuildVideoStateWithParams(signaling.VideoStateParams{
CallID: callID, To: to, CallCreator: creator, WrapperID: e.nextCallNodeID(),
State: state, Dec: dec,
})
err := e.transmitCallNode(context.Background(), node)
if err == nil || !enabled {
return err
}
e.mu.Lock()
if current := e.calls[callID]; current == m {
current.localVideo = false
}
e.mu.Unlock()
if sender != nil {
sender.disable()
}
return err
}
func (e *engine) setVideoOrientation(callID string, orientation int) error {
if orientation < 0 || orientation > 3 {
return fmt.Errorf("meowcaller: video orientation %d is outside 0..3", orientation)
}
e.mu.Lock()
m := e.calls[callID]
if m == nil || m.call == nil || m.call.State() == CallPhaseEnded || !m.localVideo {
e.mu.Unlock()
return errors.New("meowcaller: call has no active video media")
}
to, creator := m.from, m.creator
e.mu.Unlock()
node := signaling.BuildVideoStateWithParams(signaling.VideoStateParams{
CallID: callID, To: to, CallCreator: creator, WrapperID: e.nextCallNodeID(),
State: signaling.VideoStateEnabled, DeviceOrientation: &orientation,
})
return e.transmitCallNode(context.Background(), node)
}
// placeCall resolves target to a LID, builds and sends the <offer>, registers the Call,
// and returns it; media starts when the peer answers and the relay endpoint arrives.
func (e *engine) placeCall(ctx context.Context, target string, opts CallOptions) (*Call, error) {
cli := e.c.wa
self := cli.Store.GetLID()
if self.IsEmpty() {
return nil, errors.New("meowcaller: no own LID on this session")
}
peerLID, err := resolvePeerLID(ctx, cli, target)
if err != nil {
return nil, err
}
e.c.log.Info().Str("peer_lid", peerLID.String()).Str("self_lid", self.String()).Msg("resolved peer LID")
devices, err := cli.GetUserDevices(ctx, []types.JID{peerLID})
if err != nil {
return nil, fmt.Errorf("device discovery: %w", err)
}
if len(devices) == 0 {
return nil, fmt.Errorf("peer %s has no devices (unreachable / not on WhatsApp)", peerLID)
}
var callKey [32]byte
if _, err := rand.Read(callKey[:]); err != nil {
return nil, err
}
deviceKeys := make([]signaling.OfferDeviceKey, 0, len(devices))
needIdentity := false
for _, dev := range devices {
ct, encType, ni, err := encryptCallKeyForDevice(ctx, cli, dev, callKey[:])
if err != nil {
return nil, fmt.Errorf("encrypt callKey for %s: %w", dev, err)
}
needIdentity = needIdentity || ni
deviceKeys = append(deviceKeys, signaling.OfferDeviceKey{DeviceJid: dev, Ciphertext: ct, EncType: encType})
}
// pkmsg offers must carry our signed device identity so the peer can verify the new
// session; the server drops the offer (no ack) otherwise.
var deviceIdentity []byte
if needIdentity {
deviceIdentity, err = proto.Marshal(cli.Store.Account)
if err != nil {
return nil, fmt.Errorf("marshal device identity: %w", err)
}
}
// Include the peer's privacy token when we have one (the server requires it to
// place a call to a contact with privacy enabled).
var privacyToken []byte
if pt, err := cli.Store.PrivacyTokens.GetPrivacyToken(ctx, peerLID); err == nil && pt != nil {
privacyToken = pt.Token
}
callID := newCallID()
offer := signaling.BuildOffer(&signaling.OfferParams{
CallID: callID,
To: peerLID,
CallCreator: self,
DeviceKeys: deviceKeys,
PrivacyToken: privacyToken,
Capability: signaling.CapabilityOffer,
DeviceIdentity: deviceIdentity,
Video: opts.Video,
})
// The builder leaves the <call> stanza id to the I/O layer; without it the server
// can't route/ack the offer, so it never reaches the callee.
offer.Attrs["id"] = cli.GenerateMessageID()
call := &Call{eng: e, id: callID, peer: peerLID, phase: CallPhaseCalling}
e.mu.Lock()
m := e.entry(callID)
m.call = call
m.callKey = callKey[:]
m.selfLID = self.String()
m.peerLID = peerLID.String()
m.creator = self
m.from = peerLID
m.direction = CallDirectionOutgoing
m.localVideo = opts.Video
m.remoteVideo = opts.Video
m.inviteSelfDevice = groupCallDevice{
JID: self, CapabilityVersion: 1,
Capability: append([]byte(nil), signaling.CapabilityOffer...),
}
e.mu.Unlock()
e.c.diag.Emit("keying", map[string]any{
"call_id": callID, "direction": "out", "self_lid": self.String(),
"peer_lid": peerLID.String(), "device_count": len(deviceKeys),
"call_key_hex": hex.EncodeToString(callKey[:]),
})
if err := cli.DangerousInternals().SendNode(ctx, offer); err != nil {
return nil, fmt.Errorf("send offer: %w", err)
}
e.c.log.Info().Str("call_id", callID).Bool("video", opts.Video).Msg("offer sent; media starts when the relay endpoint arrives")
e.c.diag.Emit("meta", map[string]any{"event": "offer_sent", "call_id": callID, "peer_lid": peerLID.String(), "direction": "out", "video": opts.Video})
return call, nil
}
// onOffer handles an inbound <offer> event: it decrypts the callKey, captures any relay
// data, registers the Call in the Ringing phase, sends the <preaccept> eagerly (a
// preparation step, independent of the later Answer/Reject), and fires the
// OnIncomingCall listener. Only the <accept> is deferred to Answer.
func (e *engine) onOffer(ev *events.CallOffer) {
// Source of truth: https://github.com/purpshell/meowcaller/blob/33854919e64bdd4b053054ac9764d8fc63027b57/datasheets/voip-group-invite-accept.md#L28-L40
groupSnapshot, isGroup, groupErr := signaling.ParseGroupInviteSnapshot(ev.Data)
if groupErr != nil {
e.c.log.Warn().Err(groupErr).Str("call_id", ev.CallID).Msg("parse inbound group offer failed")
return
}
if isGroup {
e.onGroupOffer(ev, groupCallUpdateFromSignaling(*groupSnapshot))
return
}
// A "call ended" notification arrives offer-shaped, carrying is_call_ended/
// terminate_reason (e.g. accepted_elsewhere). It is not a live call — engaging it
// (preaccept/accept) just earns an "accept error 500". Ignore it.
oag := ev.Data.AttrGetter()
if oag.OptionalString("is_call_ended") == "1" || oag.OptionalString("terminate_reason") != "" {
e.c.log.Warn().Str("call_id", ev.CallID).Msg("ignoring already-ended offer; not a live call")
return
}
callKey, err := decryptInboundCallKey(context.Background(), e.c.wa, ev)
if err != nil {
e.c.log.Warn().Err(err).Str("call_id", ev.CallID).Msg("decrypt callKey failed")
return
}
e.c.log.Info().Int("key_bytes", len(callKey)).Str("call_id", ev.CallID).Msg("decrypted inbound callKey")
e.c.diag.Emit("keying", map[string]any{
"call_id": ev.CallID, "direction": "in", "from": ev.From.String(),
"call_key_hex": hex.EncodeToString(callKey),
})
peer := ev.CallCreator
if peer.IsEmpty() {
peer = ev.From
}
e.c.diag.Emit("meta", map[string]any{
"event": "offer_received", "call_id": ev.CallID,
"from": ev.From.String(), "peer": peer.String(),
})
call := &Call{eng: e, id: ev.CallID, peer: peer, phase: CallPhaseRinging}
e.mu.Lock()
m := e.entry(ev.CallID)
m.call = call
m.callKey = callKey
m.selfLID = e.c.wa.Store.GetLID().String()
m.peerLID = peer.String()
m.creator = ev.CallCreator
m.from = ev.From
m.direction = CallDirectionIncoming
// A <video> child marks a call that starts with both video directions enabled.
isVideo := signaling.OfferHasVideo(ev.Data)
m.localVideo = isVideo
m.remoteVideo = isVideo
m.inviteSelfDevice = groupCallDevice{
JID: e.c.wa.Store.GetLID(), CapabilityVersion: 1,
Capability: append([]byte(nil), signaling.CapabilityOffer...),
}
if device, ok := inviteDeviceCapability(ev.From, ev.Data); ok {
m.invitePeerDevice = device
}
if r := findRelay(ev.Data); r != nil {
m.relay = parseRelayData(r)
if !m.relay.peerJID.IsEmpty() {
m.peerLID = m.relay.peerJID.String()
}
}
e.applyVoipSettingsCodec(m, ev.Data, ev.CallID)
e.mu.Unlock()
if isVideo {
e.c.log.Info().Str("call_id", ev.CallID).Msg("inbound call advertises video")
}
// Preaccept eagerly: it is a preparation step, done independently of the later
// Answer/Reject decision. It keeps the offer alive and joins the relay election while
// the integrator decides — even a call the user goes on to decline has usually already
// been preaccepted.
if err := e.sendPreaccept(ev.CallID, ev.From, ev.CallCreator, isVideo); err != nil {
e.c.log.Warn().Err(err).Str("call_id", ev.CallID).Msg("preaccept failed")
}
if fn := e.c.incomingCallHandler(); fn != nil {
fn(call)
}
}
func (e *engine) onGroupOffer(ev *events.CallOffer, update groupCallUpdate) {
// Source of truth: https://github.com/purpshell/meowcaller/blob/33854919e64bdd4b053054ac9764d8fc63027b57/datasheets/voip-group-invite-accept.md#L28-L40
peer := ev.CallCreator
if peer.IsEmpty() {
peer = ev.From
}
call := &Call{eng: e, id: ev.CallID, peer: peer, phase: CallPhaseRinging}
isVideo := signaling.OfferHasVideo(ev.Data)
e.mu.Lock()
m := e.entry(ev.CallID)
m.call = call
m.selfLID = e.c.wa.Store.GetLID().String()
m.peerLID = peer.String()
m.creator = ev.CallCreator
if m.creator.IsEmpty() {
m.creator = peer
}
m.from = types.NewJID(ev.CallID, "call")
m.direction = CallDirectionIncoming
m.group = true
m.localVideo = isVideo
m.remoteVideo = isVideo
creator := m.creator
e.mu.Unlock()
e.applyGroupUpdate(update)
preaccept, err := signaling.BuildActiveGroupPreaccept(
ev.CallID,
creator,
e.nextCallNodeID(),
isVideo,
)
if err != nil {
e.c.log.Warn().Err(err).Str("call_id", ev.CallID).Msg("build group preaccept failed")
return
}
if err = e.transmitCallNode(context.Background(), preaccept); err != nil {
e.c.log.Warn().Err(err).Str("call_id", ev.CallID).Msg("send group preaccept failed")
return
}
e.c.log.Info().Str("call_id", ev.CallID).Bool("video", isVideo).Msg("active group invite preaccepted")
if fn := e.c.incomingCallHandler(); fn != nil {
fn(call)
}
}
// sendPreaccept sends the <preaccept> for an inbound call — a preparation step done
// eagerly when the offer arrives (see onOffer), independent of the later Answer/Reject
// decision. Video calls also advertise the H.264 decoder before the final accept.
func (e *engine) sendPreaccept(callID string, to, creator types.JID, video bool) error {
pre := signaling.BuildPreaccept(
callID,
to,
creator,
e.c.wa.DangerousInternals().GenerateRequestID(),
[]string{"16000"},
video,
)
if err := e.c.wa.DangerousInternals().SendNode(context.Background(), pre); err != nil {
return fmt.Errorf("send preaccept: %w", err)
}
e.c.log.Info().Str("call_id", callID).Msg("preaccepted (preparation; awaiting Answer/Reject)")
return nil
}
// answer accepts an inbound call: it marks the call to accept (the actual <accept> is
// deferred until the caller's <mute_v2>, which onCallRaw fires) and brings media up. The
// <preaccept> was already sent eagerly when the offer arrived, so Answer only commits to
// the call. Media comes up once callKey+relay are both known.
func (e *engine) answer(c *Call) error {
m := e.lookup(c.id)
if m == nil {
return fmt.Errorf("meowcaller: unknown call %s", c.id)
}
if m.group {
// Source of truth: https://github.com/purpshell/meowcaller/blob/676ebee3eca513b5348fab36cae5c560cc791238/datasheets/voip-group-invite-accept.md#L26-L45
accept, err := signaling.BuildActiveGroupAccept(c.id, m.creator, e.nextCallNodeID())
if err != nil {
return err
}
if err = e.transmitCallNode(context.Background(), accept); err != nil {
return fmt.Errorf("meowcaller: send group accept: %w", err)
}
c.setPhase(CallPhaseConnecting)
e.maybeStartMedia(c.id)
return nil
}
e.mu.Lock()
m.acceptPending = true
e.mu.Unlock()
c.setPhase(CallPhaseConnecting)
e.maybeStartMedia(c.id)
return nil
}
// sendAccept sends the deferred callee <accept> (once), in the WA-Web format (metadata +
// single rate — the peer keeps the call alive with this; capability+both-rates fails).
func (e *engine) sendAccept(callID string, to, creator types.JID) {
e.mu.Lock()
m := e.calls[callID]
if m == nil || !m.acceptPending {
e.mu.Unlock()
return
}
isVideo := m.localVideo || m.remoteVideo
m.acceptPending = false
e.mu.Unlock()
accept := signaling.BuildAccept(&signaling.AcceptParams{
CallID: callID, To: to, CallCreator: creator,
AudioRates: []string{"16000"},
Metadata: waBinary.Attrs{"peer_abtest_bucket_id_list": "125208,94276"},
Video: isVideo,
})
accept.Attrs["id"] = e.c.wa.DangerousInternals().GenerateRequestID()
if err := e.c.wa.DangerousInternals().SendNode(context.Background(), accept); err != nil {
e.c.log.Error().Err(err).Str("call_id", callID).Msg("send accept failed")
return
}
e.c.log.Info().Str("call_id", callID).Bool("video", isVideo).Msg("accepted (after mute_v2)")
}
// reject declines an inbound call.
func (e *engine) reject(c *Call) error {
m := e.lookup(c.id)
to, creator := c.peer, c.peer
if m != nil {
to, creator = m.from, m.creator
}
rej := signaling.BuildReject(c.id, to, creator)
rej.Attrs["id"] = e.nextCallNodeID()
e.finishCall(c.id, "rejected")
if err := e.transmitCallNode(context.Background(), rej); err != nil {
return fmt.Errorf("send reject: %w", err)
}
return nil
}
// hangup ends a call (either direction) and tears down its media.
func (e *engine) hangup(c *Call) error {
m := e.lookup(c.id)
to, creator := c.peer, c.peer
if m != nil {
to, creator = m.from, m.creator
}
term := signaling.BuildTerminate(&signaling.TerminateParams{CallID: c.id, To: to, CallCreator: creator})
term.Attrs["id"] = e.nextCallNodeID()
e.finishCall(c.id, "hangup")
if err := e.transmitCallNode(context.Background(), term); err != nil {
return fmt.Errorf("send terminate: %w", err)
}
return nil
}
// onRelay records relay data from a relaylatency/transport/ack stanza and starts media
// once both the callKey and the relay endpoint are known.
func (e *engine) onRelay(callID string, data *waBinary.Node) {
r := findRelay(data)
if r == nil {
return
}
rd := parseRelayData(r)
var rekeyPeer func(string) error
var peerLID string
e.mu.Lock()
m := e.calls[callID]
if m == nil {
e.mu.Unlock()
return
}
m.relay = rd
if !rd.peerJID.IsEmpty() {
peerLID = rd.peerJID.String()
if peerLID != m.peerLID {
m.peerLID = peerLID
rekeyPeer = m.rekeyPeer
}
}
e.mu.Unlock()
if rekeyPeer != nil {
if err := rekeyPeer(peerLID); err != nil {
e.c.log.Warn().Err(err).Str("call_id", callID).Str("peer_lid", peerLID).
Msg("failed to rekey media to relay-elected peer")
} else {
e.c.log.Info().Str("call_id", callID).Str("peer_lid", peerLID).
Msg("rekeyed media to relay-elected peer")
}
}
e.maybeStartMedia(callID)
}
// onRelayLatency answers the caller's relaylatency probes (the callee's half of the
// relay election). It does NOT send the accept — that is deferred until <mute_v2>.
func (e *engine) onRelayLatency(ev *events.CallRelayLatency) {
m := e.lookup(ev.CallID)
if m == nil || m.direction != CallDirectionIncoming {
return
}
rl := findChild(ev.Data, "relaylatency")
if rl == nil {
return
}
var probes []rlProbe
for i := range rl.GetChildren() {
te := &rl.GetChildren()[i]
if te.Tag != "te" {
continue
}
ag := te.AttrGetter()
probes = append(probes, rlProbe{
latency: decodeLatency(ag.String("latency")),
relayName: ag.String("relay_name"),
addr: nodeBytes(te),
})
}
for _, p := range probes {
resp := signaling.BuildRelayLatency(&signaling.RelayLatencyParams{
CallID: ev.CallID,
To: ev.From,
CallCreator: ev.CallCreator,
LatencyMs: p.latency,
RelayName: p.relayName,
AddressBytes: p.addr,
})
resp.Attrs["id"] = e.c.wa.GenerateMessageID()
if err := e.c.wa.DangerousInternals().SendNode(context.Background(), resp); err != nil {
e.c.log.Error().Err(err).Str("call_id", ev.CallID).Msg("send relaylatency failed")
return
}
}
}
// onPreAccept records that the peer's device received and started preparing an outgoing call.
func (e *engine) onPreAccept(ev *events.CallPreAccept) {
m := e.lookup(ev.CallID)
if m == nil || m.direction != CallDirectionOutgoing {
return
}
if m.call != nil && m.call.State() == CallPhaseCalling {
m.call.setPhase(CallPhaseRinging)
}
if device, ok := inviteDeviceCapability(ev.From, ev.Data); ok {
e.mu.Lock()
if current := e.calls[ev.CallID]; current != nil {
current.invitePeerDevice = device
}
e.mu.Unlock()
}
e.c.log.Info().
Str("call_id", ev.CallID).
Str("from", ev.From.String()).
Str("platform", ev.RemotePlatform).
Msg("peer preaccepted outgoing call")
e.c.diag.Emit("meta", map[string]any{
"event": "peer_preaccept", "call_id": ev.CallID,
"from": ev.From.String(), "platform": ev.RemotePlatform,
})
}
// onAccept records that the peer answered an outgoing call. Media may already be running
// from relay allocation, but inbound RTP is still what marks the call ready/active.
func (e *engine) onAccept(ev *events.CallAccept) {
m := e.lookup(ev.CallID)
if m == nil || m.direction != CallDirectionOutgoing {
return
}
if m.call != nil && m.call.State() == CallPhaseEnded {
return
}
if m.group {
// Source of truth: https://github.com/purpshell/meowcaller/blob/676ebee3eca513b5348fab36cae5c560cc791238/datasheets/voip-group-invite-accept.md#L26-L45
if m.call != nil && m.call.State() < CallPhaseConnecting {
m.call.setPhase(CallPhaseConnecting)
}
if m.call != nil {
m.call.markPeerAccepted()
}
e.c.log.Info().Str("call_id", ev.CallID).Str("from", ev.From.String()).Msg("participant accepted group call")
e.maybeStartMedia(ev.CallID)
return
}
e.mu.Lock()
var rekeyPeer func(string) error
answeringPeer := ev.From.String()
if current := e.calls[ev.CallID]; current != nil {
if device, ok := inviteDeviceCapability(ev.From, ev.Data); ok {
current.invitePeerDevice = device
}
e.applyVoipSettingsCodec(current, ev.Data, ev.CallID)
if !ev.From.IsEmpty() {
current.from = ev.From
answeringPeer = preferQualifiedPeer(current.peerLID, ev.From)
}
if answeringPeer != "" && answeringPeer != current.peerLID {
current.peerLID = answeringPeer
rekeyPeer = current.rekeyPeer
}
}
e.mu.Unlock()
if rekeyPeer != nil {
if err := rekeyPeer(answeringPeer); err != nil {
e.c.log.Warn().Err(err).Str("call_id", ev.CallID).Str("peer_lid", answeringPeer).Msg("failed to rekey media to answering device")
} else {
e.c.log.Info().Str("call_id", ev.CallID).Str("peer_lid", answeringPeer).Msg("rekeyed media to answering device")
}
}
if m.call != nil && m.call.State() < CallPhaseConnecting {
m.call.setPhase(CallPhaseConnecting)
}
if m.call != nil {
m.call.markPeerAccepted()
}
e.c.log.Info().
Str("call_id", ev.CallID).
Str("from", ev.From.String()).
Str("platform", ev.RemotePlatform).
Bool("video", m.localVideo || m.remoteVideo).
Msg("peer accepted outgoing call")
e.c.diag.Emit("meta", map[string]any{
"event": "peer_accept", "call_id": ev.CallID,
"from": ev.From.String(), "platform": ev.RemotePlatform, "video": m.localVideo || m.remoteVideo,
})
e.maybeStartMedia(ev.CallID)
}
func inviteDeviceCapability(device types.JID, node *waBinary.Node) (groupCallDevice, bool) {
// Source of truth: https://github.com/purpshell/meowcaller/blob/1ebd064663ac336ff3d1fc65d9baa974148fe73e/datasheets/voip-group-participant-invite.md#L36-L72
if device.IsEmpty() {
return groupCallDevice{}, false
}
capability := findChild(node, "capability")
if capability == nil {
return groupCallDevice{}, false
}
value, ok := capability.Content.([]byte)
if !ok || len(value) == 0 {
return groupCallDevice{}, false
}
version, err := strconv.ParseUint(capability.AttrGetter().String("ver"), 10, 32)
if err != nil {
return groupCallDevice{}, false
}
return groupCallDevice{
JID: device, CapabilityVersion: uint32(version),
Capability: append([]byte(nil), value...),
}, true
}
func preferQualifiedPeer(current string, signaled types.JID) string {
if signaled.IsEmpty() {
return current
}
parsed, err := types.ParseJID(current)
if err == nil &&
parsed.User == signaled.User &&
parsed.Server == signaled.Server &&
parsed.Device != 0 &&
signaled.Device == 0 {
return current
}
return signaled.String()
}
// onReject tears down an outgoing call when the peer declines it.
func (e *engine) onReject(ev *events.CallReject) {
m := e.lookup(ev.CallID)
if m == nil {
return
}
e.c.log.Info().
Str("call_id", ev.CallID).
Str("from", ev.From.String()).
Msg("peer rejected call")
e.c.diag.Emit("meta", map[string]any{
"event": "peer_reject", "call_id": ev.CallID, "from": ev.From.String(),
})
e.finishCall(ev.CallID, "rejected")
}
// rlProbe is one relay candidate from a relaylatency probe.
type rlProbe struct {
latency uint32
relayName string
addr []byte
}
// applyVoipSettingsCodec finds the <voip_settings> blob under node (an inbound
// <offer> or an outbound call <ack>), parses it, and records the selected audio
// codec on the call. Absent or unparseable settings leave the call on MLow. The
// caller holds e.mu.
func (e *engine) applyVoipSettingsCodec(m *engineCall, node *waBinary.Node, callID string) {
vsNode := findChild(node, "voip_settings")
if vsNode == nil {
return
}
content, _ := vsNode.Content.([]byte)
vs, err := signaling.ParseVoipSettings(content, e.c.log)
if err != nil {
e.c.log.Debug().Err(err).Str("call_id", callID).Msg("voip_settings parse failed; keeping mlow")
return
}
m.codec = selectAudioCodec(vs)
e.c.log.Info().