feat(calls): organizer controls, live captions, background blur
| Before | After | |---|---| | Lobby only shown as a state | Organizers get a lobby banner: View (Admit / Deny each), Admit all | | No participant actions | Tile menu: Pin for me, Spotlight for everyone, Mute, Lower hand, Remove (confirm); "..." menu: Mute all | | No captions | Turn live captions on/off; two lines over the stage with the speaker's name | | Camera as is | Background blur in the camera menu: on-device person segmentation (tract + MediaPipe selfie segmenter, Apache-2.0) before the picture is sent | - Meetings now open Teams' main data channel (x-data line), needed for captions; CALLING_DATA_CHANNEL=0 turns it off. - Verified live in self-created Meet now meetings (only me): join with the data channel, spotlight self shown and cleared (HTTP 200), mute all (HTTP 202), captions started and stopped (caption bot joined), blur at 11.7 ms per frame on average. - Not yet verified with others: admit/deny, muting or removing someone, caption text from real speech. - teams.exe grows by about 23 MB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -253,6 +253,12 @@ version = "1.0.104"
253
253
source = "registry+https://github.com/rust-lang/crates.io-index"
254
254
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
255
255
256
[[package]]
257
name = "anymap3"
258
version = "1.1.0"
259
source = "registry+https://github.com/rust-lang/crates.io-index"
260
checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
261
256
262
[[package]]
257
263
name = "app"
258
264
version = "0.1.0"
@@ -624,7 +630,7 @@ dependencies = [
624
630
"log",
625
631
"num-rational",
626
632
"num-traits",
627
"pastey",
633
"pastey 0.1.1",
628
634
"rayon",
629
635
"thiserror 2.0.21",
630
636
"v_frame",
@@ -771,6 +777,15 @@ dependencies = [
771
777
"bit-vec 0.9.1",
772
778
]
773
779
780
[[package]]
781
name = "bit-set"
782
version = "0.11.1"
783
source = "registry+https://github.com/rust-lang/crates.io-index"
784
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
785
dependencies = [
786
"bit-vec 0.10.1",
787
]
788
774
789
[[package]]
775
790
name = "bit-vec"
776
791
version = "0.8.0"
@@ -783,6 +798,16 @@ version = "0.9.1"
783
798
source = "registry+https://github.com/rust-lang/crates.io-index"
784
799
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
785
800
801
[[package]]
802
name = "bit-vec"
803
version = "0.10.1"
804
source = "registry+https://github.com/rust-lang/crates.io-index"
805
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
806
dependencies = [
807
"borsh",
808
"serde",
809
]
810
786
811
[[package]]
787
812
name = "bit_field"
788
813
version = "0.10.3"
@@ -877,6 +902,30 @@ dependencies = [
877
902
"piper",
878
903
]
879
904
905
[[package]]
906
name = "borsh"
907
version = "1.8.1"
908
source = "registry+https://github.com/rust-lang/crates.io-index"
909
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
910
dependencies = [
911
"borsh-derive",
912
"bytes",
913
"cfg_aliases",
914
]
915
916
[[package]]
917
name = "borsh-derive"
918
version = "1.8.1"
919
source = "registry+https://github.com/rust-lang/crates.io-index"
920
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
921
dependencies = [
922
"once_cell",
923
"proc-macro-crate 3.5.0",
924
"proc-macro2",
925
"quote",
926
"syn 3.0.6",
927
]
928
880
929
[[package]]
881
930
name = "browser"
882
931
version = "0.1.0"
@@ -992,6 +1041,7 @@ version = "0.1.0"
992
1041
dependencies = [
993
1042
"base64 0.22.1",
994
1043
"chatsvc",
1044
"chrono",
995
1045
"cpal",
996
1046
"flate2",
997
1047
"futures-util",
@@ -1002,6 +1052,7 @@ dependencies = [
1002
1052
"session",
1003
1053
"thiserror 2.0.21",
1004
1054
"tokio",
1055
"tract-onnx",
1005
1056
"uuid",
1006
1057
"webview",
1007
1058
"windows 0.62.2",
@@ -1923,6 +1974,17 @@ version = "0.5.8"
1923
1974
source = "registry+https://github.com/rust-lang/crates.io-index"
1924
1975
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
1925
1976
1977
[[package]]
1978
name = "derive-new"
1979
version = "0.7.0"
1980
source = "registry+https://github.com/rust-lang/crates.io-index"
1981
checksum = "2cdc8d50f426189eef89dac62fabfa0abb27d5cc008f25bf4156a0203325becc"
1982
dependencies = [
1983
"proc-macro2",
1984
"quote",
1985
"syn 2.0.119",
1986
]
1987
1926
1988
[[package]]
1927
1989
name = "derive_more"
1928
1990
version = "0.99.20"
@@ -2083,6 +2145,12 @@ version = "1.2.1"
2083
2145
source = "registry+https://github.com/rust-lang/crates.io-index"
2084
2146
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
2085
2147
2148
[[package]]
2149
name = "downcast-rs"
2150
version = "2.0.2"
2151
source = "registry+https://github.com/rust-lang/crates.io-index"
2152
checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
2153
2086
2154
[[package]]
2087
2155
name = "dpi"
2088
2156
version = "0.1.2"
@@ -2128,6 +2196,12 @@ version = "1.0.20"
2128
2196
source = "registry+https://github.com/rust-lang/crates.io-index"
2129
2197
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
2130
2198
2199
[[package]]
2200
name = "dyn-hash"
2201
version = "1.0.0"
2202
source = "registry+https://github.com/rust-lang/crates.io-index"
2203
checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"
2204
2131
2205
[[package]]
2132
2206
name = "ego-tree"
2133
2207
version = "0.10.0"
@@ -2395,6 +2469,16 @@ dependencies = [
2395
2469
"winapi",
2396
2470
]
2397
2471
2472
[[package]]
2473
name = "filetime"
2474
version = "0.2.29"
2475
source = "registry+https://github.com/rust-lang/crates.io-index"
2476
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
2477
dependencies = [
2478
"cfg-if 1.0.5",
2479
"libc",
2480
]
2481
2398
2482
[[package]]
2399
2483
name = "find-msvc-tools"
2400
2484
version = "0.1.14"
@@ -2944,7 +3028,7 @@ dependencies = [
2944
3028
"gobject-sys 0.21.5",
2945
3029
"libc",
2946
3030
"system-deps 7.0.8",
2947
"windows-sys 0.52.0",
3031
"windows-sys 0.61.2",
2948
3032
]
2949
3033
2950
3034
[[package]]
@@ -3769,6 +3853,8 @@ dependencies = [
3769
3853
[[package]]
3770
3854
name = "gpui-pre-windows"
3771
3855
version = "0.3.8"
3856
source = "registry+https://github.com/rust-lang/crates.io-index"
3857
checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"
3772
3858
dependencies = [
3773
3859
"accesskit",
3774
3860
"accesskit_windows",
@@ -4536,6 +4622,15 @@ dependencies = [
4536
4622
"either",
4537
4623
]
4538
4624
4625
[[package]]
4626
name = "itertools"
4627
version = "0.15.0"
4628
source = "registry+https://github.com/rust-lang/crates.io-index"
4629
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
4630
dependencies = [
4631
"either",
4632
]
4633
4539
4634
[[package]]
4540
4635
name = "itoa"
4541
4636
version = "1.0.18"
@@ -5046,6 +5141,12 @@ dependencies = [
5046
5141
"libc",
5047
5142
]
5048
5143
5144
[[package]]
5145
name = "maplit"
5146
version = "1.0.2"
5147
source = "registry+https://github.com/rust-lang/crates.io-index"
5148
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
5149
5049
5150
[[package]]
5050
5151
name = "markdown"
5051
5152
version = "1.0.0"
@@ -5107,6 +5208,16 @@ dependencies = [
5107
5208
"syn 2.0.119",
5108
5209
]
5109
5210
5211
[[package]]
5212
name = "matrixmultiply"
5213
version = "0.3.11"
5214
source = "registry+https://github.com/rust-lang/crates.io-index"
5215
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
5216
dependencies = [
5217
"autocfg",
5218
"rawpointer",
5219
]
5220
5110
5221
[[package]]
5111
5222
name = "maybe-rayon"
5112
5223
version = "0.1.1"
@@ -5142,6 +5253,12 @@ dependencies = [
5142
5253
"libc",
5143
5254
]
5144
5255
5256
[[package]]
5257
name = "memo-map"
5258
version = "0.3.4"
5259
source = "registry+https://github.com/rust-lang/crates.io-index"
5260
checksum = "5449c8c750f1a07ea702bbd212bd999fceece9b3d1508b17023b3e174583124b"
5261
5145
5262
[[package]]
5146
5263
name = "memoffset"
5147
5264
version = "0.9.1"
@@ -5197,6 +5314,16 @@ dependencies = [
5197
5314
"unicase",
5198
5315
]
5199
5316
5317
[[package]]
5318
name = "minijinja"
5319
version = "2.24.0"
5320
source = "registry+https://github.com/rust-lang/crates.io-index"
5321
checksum = "86886cf6dbf4e614b19c9a1eec9775f021869d7eadde0fc73921a81b90c9b4c9"
5322
dependencies = [
5323
"memo-map",
5324
"serde",
5325
]
5326
5200
5327
[[package]]
5201
5328
name = "minimal-lexical"
5202
5329
version = "0.2.1"
@@ -5306,6 +5433,21 @@ dependencies = [
5306
5433
"getrandom 0.2.17",
5307
5434
]
5308
5435
5436
[[package]]
5437
name = "ndarray"
5438
version = "0.17.2"
5439
source = "registry+https://github.com/rust-lang/crates.io-index"
5440
checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
5441
dependencies = [
5442
"matrixmultiply",
5443
"num-complex",
5444
"num-integer",
5445
"num-traits",
5446
"portable-atomic",
5447
"portable-atomic-util",
5448
"rawpointer",
5449
]
5450
5309
5451
[[package]]
5310
5452
name = "ndk"
5311
5453
version = "0.9.0"
@@ -5441,6 +5583,15 @@ dependencies = [
5441
5583
"memchr",
5442
5584
]
5443
5585
5586
[[package]]
5587
name = "nom-language"
5588
version = "0.1.0"
5589
source = "registry+https://github.com/rust-lang/crates.io-index"
5590
checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29"
5591
dependencies = [
5592
"nom 8.0.0",
5593
]
5594
5444
5595
[[package]]
5445
5596
name = "noop_proc_macro"
5446
5597
version = "0.3.0"
@@ -6218,6 +6369,12 @@ version = "0.1.1"
6218
6369
source = "registry+https://github.com/rust-lang/crates.io-index"
6219
6370
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
6220
6371
6372
[[package]]
6373
name = "pastey"
6374
version = "0.2.3"
6375
source = "registry+https://github.com/rust-lang/crates.io-index"
6376
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
6377
6221
6378
[[package]]
6222
6379
name = "pathfinder_geometry"
6223
6380
version = "0.5.1"
@@ -6542,6 +6699,15 @@ dependencies = [
6542
6699
"syn 2.0.119",
6543
6700
]
6544
6701
6702
[[package]]
6703
name = "primal-check"
6704
version = "0.3.4"
6705
source = "registry+https://github.com/rust-lang/crates.io-index"
6706
checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
6707
dependencies = [
6708
"num-integer",
6709
]
6710
6545
6711
[[package]]
6546
6712
name = "proc-macro-crate"
6547
6713
version = "1.3.1"
@@ -6654,6 +6820,29 @@ dependencies = [
6654
6820
"syn 2.0.119",
6655
6821
]
6656
6822
6823
[[package]]
6824
name = "prost"
6825
version = "0.14.4"
6826
source = "registry+https://github.com/rust-lang/crates.io-index"
6827
checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
6828
dependencies = [
6829
"bytes",
6830
"prost-derive",
6831
]
6832
6833
[[package]]
6834
name = "prost-derive"
6835
version = "0.14.4"
6836
source = "registry+https://github.com/rust-lang/crates.io-index"
6837
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
6838
dependencies = [
6839
"anyhow",
6840
"itertools 0.14.0",
6841
"proc-macro2",
6842
"quote",
6843
"syn 2.0.119",
6844
]
6845
6657
6846
[[package]]
6658
6847
name = "pulp"
6659
6848
version = "0.22.3"
@@ -6866,6 +7055,16 @@ version = "0.10.1"
6866
7055
source = "registry+https://github.com/rust-lang/crates.io-index"
6867
7056
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
6868
7057
7058
[[package]]
7059
name = "rand_distr"
7060
version = "0.6.0"
7061
source = "registry+https://github.com/rust-lang/crates.io-index"
7062
checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8"
7063
dependencies = [
7064
"num-traits",
7065
"rand 0.10.3",
7066
]
7067
6869
7068
[[package]]
6870
7069
name = "rand_pcg"
6871
7070
version = "0.10.2"
@@ -6973,6 +7172,12 @@ dependencies = [
6973
7172
"objc2-quartz-core 0.3.2",
6974
7173
]
6975
7174
7175
[[package]]
7176
name = "rawpointer"
7177
version = "0.2.1"
7178
source = "registry+https://github.com/rust-lang/crates.io-index"
7179
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
7180
6976
7181
[[package]]
6977
7182
name = "rayon"
6978
7183
version = "1.12.0"
@@ -7372,6 +7577,20 @@ dependencies = [
7372
7577
"semver",
7373
7578
]
7374
7579
7580
[[package]]
7581
name = "rustfft"
7582
version = "6.4.1"
7583
source = "registry+https://github.com/rust-lang/crates.io-index"
7584
checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
7585
dependencies = [
7586
"num-complex",
7587
"num-integer",
7588
"num-traits",
7589
"primal-check",
7590
"strength_reduce",
7591
"transpose",
7592
]
7593
7375
7594
[[package]]
7376
7595
name = "rustix"
7377
7596
version = "0.38.44"
@@ -8104,6 +8323,12 @@ version = "0.4.4"
8104
8323
source = "registry+https://github.com/rust-lang/crates.io-index"
8105
8324
checksum = "d08889ec5408683408db66ad89e0e1f93dff55c73a4ccc71c427d5b277ee47e6"
8106
8325
8326
[[package]]
8327
name = "strength_reduce"
8328
version = "0.2.4"
8329
source = "registry+https://github.com/rust-lang/crates.io-index"
8330
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
8331
8107
8332
[[package]]
8108
8333
name = "strict-num"
8109
8334
version = "0.1.1"
@@ -8113,6 +8338,16 @@ dependencies = [
8113
8338
"float-cmp",
8114
8339
]
8115
8340
8341
[[package]]
8342
name = "string-interner"
8343
version = "0.20.0"
8344
source = "registry+https://github.com/rust-lang/crates.io-index"
8345
checksum = "ad3df9b59e2eded8d825c7c4363ad339a20fb6bc0b9a4778560f518f59910b15"
8346
dependencies = [
8347
"hashbrown 0.16.1",
8348
"serde",
8349
]
8350
8116
8351
[[package]]
8117
8352
name = "string_cache"
8118
8353
version = "0.8.9"
@@ -8482,6 +8717,17 @@ dependencies = [
8482
8717
"objc",
8483
8718
]
8484
8719
8720
[[package]]
8721
name = "tar"
8722
version = "0.4.46"
8723
source = "registry+https://github.com/rust-lang/crates.io-index"
8724
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
8725
dependencies = [
8726
"filetime",
8727
"libc",
8728
"xattr",
8729
]
8730
8485
8731
[[package]]
8486
8732
name = "target-lexicon"
8487
8733
version = "0.12.16"
@@ -8994,6 +9240,184 @@ dependencies = [
8994
9240
"tracing-log",
8995
9241
]
8996
9242
9243
[[package]]
9244
name = "tract-core"
9245
version = "0.23.8"
9246
source = "registry+https://github.com/rust-lang/crates.io-index"
9247
checksum = "0a5a9e07e863fc28355436c5a48fe859784832094ba1ff410357396ae87ff1e3"
9248
dependencies = [
9249
"anyhow",
9250
"anymap3",
9251
"bit-set 0.11.1",
9252
"derive-new",
9253
"downcast-rs 2.0.2",
9254
"dyn-clone",
9255
"erased-serde",
9256
"inventory",
9257
"lazy_static",
9258
"log",
9259
"maplit",
9260
"ndarray",
9261
"num-complex",
9262
"num-integer",
9263
"num-traits",
9264
"pastey 0.2.3",
9265
"rustfft",
9266
"serde",
9267
"smallvec",
9268
"tract-data",
9269
"tract-linalg",
9270
]
9271
9272
[[package]]
9273
name = "tract-data"
9274
version = "0.23.8"
9275
source = "registry+https://github.com/rust-lang/crates.io-index"
9276
checksum = "a33bafcf1d3dfa404c3271dd08304b162deb8fcfe9536290fb97e578c32d5dd5"
9277
dependencies = [
9278
"anyhow",
9279
"downcast-rs 2.0.2",
9280
"dyn-clone",
9281
"dyn-hash",
9282
"half",
9283
"inventory",
9284
"itertools 0.15.0",
9285
"lazy_static",
9286
"libm",
9287
"maplit",
9288
"ndarray",
9289
"nom 8.0.0",
9290
"nom-language",
9291
"num-integer",
9292
"num-traits",
9293
"parking_lot",
9294
"smallvec",
9295
"string-interner",
9296
]
9297
9298
[[package]]
9299
name = "tract-extra"
9300
version = "0.23.8"
9301
source = "registry+https://github.com/rust-lang/crates.io-index"
9302
checksum = "2a05c86ece0c47880c7726e08dabb72d68e9cba0cd36d44bc0aa90e2291a05db"
9303
dependencies = [
9304
"tract-nnef",
9305
]
9306
9307
[[package]]
9308
name = "tract-hir"
9309
version = "0.23.8"
9310
source = "registry+https://github.com/rust-lang/crates.io-index"
9311
checksum = "a52e3ec1f3beb16d552806386e123cf5632d4206154695a80aaecdb6ee2c5128"
9312
dependencies = [
9313
"derive-new",
9314
"log",
9315
"tract-core",
9316
]
9317
9318
[[package]]
9319
name = "tract-linalg"
9320
version = "0.23.8"
9321
source = "registry+https://github.com/rust-lang/crates.io-index"
9322
checksum = "1cc37ab328b95cef8eef98324122e9f956fd3ca197f0892e09ff90fe495fa222"
9323
dependencies = [
9324
"byteorder",
9325
"cc",
9326
"derive-new",
9327
"downcast-rs 2.0.2",
9328
"dyn-clone",
9329
"dyn-hash",
9330
"half",
9331
"inventory",
9332
"lazy_static",
9333
"libc",
9334
"log",
9335
"minijinja",
9336
"num-traits",
9337
"pastey 0.2.3",
9338
"tract-data",
9339
"walkdir",
9340
]
9341
9342
[[package]]
9343
name = "tract-nnef"
9344
version = "0.23.8"
9345
source = "registry+https://github.com/rust-lang/crates.io-index"
9346
checksum = "5d95e30d7e6c2f73516212367a5b49354c105b52285e8919ec439c84556f54b3"
9347
dependencies = [
9348
"byteorder",
9349
"erased-serde",
9350
"log",
9351
"nom 8.0.0",
9352
"nom-language",
9353
"serde",
9354
"serde_json",
9355
"simd-adler32",
9356
"tar",
9357
"tract-core",
9358
"walkdir",
9359
]
9360
9361
[[package]]
9362
name = "tract-onnx"
9363
version = "0.23.8"
9364
source = "registry+https://github.com/rust-lang/crates.io-index"
9365
checksum = "5a316674683d04c6070146badf57a7b8b9d99d4e38f586cbe3214e553d70bc2d"
9366
dependencies = [
9367
"bytes",
9368
"derive-new",
9369
"log",
9370
"memmap2",
9371
"nom 8.0.0",
9372
"nom-language",
9373
"num-integer",
9374
"num-rational",
9375
"num-traits",
9376
"prost",
9377
"smallvec",
9378
"tract-extra",
9379
"tract-hir",
9380
"tract-nnef",
9381
"tract-onnx-opl",
9382
"tract-transformers",
9383
]
9384
9385
[[package]]
9386
name = "tract-onnx-opl"
9387
version = "0.23.8"
9388
source = "registry+https://github.com/rust-lang/crates.io-index"
9389
checksum = "091e126c52d608214f8784f468c7d0be44459e7a369fb9a26f92aa593a78f4a5"
9390
dependencies = [
9391
"getrandom 0.4.3",
9392
"log",
9393
"rand 0.10.3",
9394
"rand_distr",
9395
"rustfft",
9396
"tract-extra",
9397
"tract-nnef",
9398
]
9399
9400
[[package]]
9401
name = "tract-transformers"
9402
version = "0.23.8"
9403
source = "registry+https://github.com/rust-lang/crates.io-index"
9404
checksum = "4eefbb8d21ab36b48185fc86a3e861b3b62e6dcfd97c3cc13b0dd34389b60916"
9405
dependencies = [
9406
"float-ord",
9407
"rayon",
9408
"tract-nnef",
9409
]
9410
9411
[[package]]
9412
name = "transpose"
9413
version = "0.2.3"
9414
source = "registry+https://github.com/rust-lang/crates.io-index"
9415
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
9416
dependencies = [
9417
"num-integer",
9418
"strength_reduce",
9419
]
9420
8997
9421
[[package]]
8998
9422
name = "tray-icon"
8999
9423
version = "0.21.3"
@@ -9516,7 +9940,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
9516
9940
checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
9517
9941
dependencies = [
9518
9942
"cc",
9519
"downcast-rs",
9943
"downcast-rs 1.2.1",
9520
9944
"log",
9521
9945
"rustix 1.1.5",
9522
9946
"scoped-tls",
@@ -10703,6 +11127,16 @@ version = "0.13.2"
10703
11127
source = "registry+https://github.com/rust-lang/crates.io-index"
10704
11128
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
10705
11129
11130
[[package]]
11131
name = "xattr"
11132
version = "1.6.1"
11133
source = "registry+https://github.com/rust-lang/crates.io-index"
11134
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
11135
dependencies = [
11136
"libc",
11137
"rustix 1.1.5",
11138
]
11139
10706
11140
[[package]]
10707
11141
name = "xcb"
10708
11142
version = "1.7.1"
@@ -253,6 +253,12 @@ version = "1.0.104"253
source = "registry+https://github.com/rust-lang/crates.io-index"253
source = "registry+https://github.com/rust-lang/crates.io-index"254
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"254
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"255
255
256
[[package]]257
name = "anymap3"258
version = "1.1.0"259
source = "registry+https://github.com/rust-lang/crates.io-index"260
checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"261
256
[[package]]262
[[package]]257
name = "app"263
name = "app"258
version = "0.1.0"264
version = "0.1.0"@@ -624,7 +630,7 @@ dependencies = [624
"log",630
"log",625
"num-rational",631
"num-rational",626
"num-traits",632
"num-traits",627
"pastey",633
"pastey 0.1.1",628
"rayon",634
"rayon",629
"thiserror 2.0.21",635
"thiserror 2.0.21",630
"v_frame",636
"v_frame",@@ -771,6 +777,15 @@ dependencies = [771
"bit-vec 0.9.1",777
"bit-vec 0.9.1",772
]778
]773
779
780
[[package]]781
name = "bit-set"782
version = "0.11.1"783
source = "registry+https://github.com/rust-lang/crates.io-index"784
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"785
dependencies = [786
"bit-vec 0.10.1",787
]788
774
[[package]]789
[[package]]775
name = "bit-vec"790
name = "bit-vec"776
version = "0.8.0"791
version = "0.8.0"@@ -783,6 +798,16 @@ version = "0.9.1"783
source = "registry+https://github.com/rust-lang/crates.io-index"798
source = "registry+https://github.com/rust-lang/crates.io-index"784
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"799
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"785
800
801
[[package]]802
name = "bit-vec"803
version = "0.10.1"804
source = "registry+https://github.com/rust-lang/crates.io-index"805
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"806
dependencies = [807
"borsh",808
"serde",809
]810
786
[[package]]811
[[package]]787
name = "bit_field"812
name = "bit_field"788
version = "0.10.3"813
version = "0.10.3"@@ -877,6 +902,30 @@ dependencies = [877
"piper",902
"piper",878
]903
]879
904
905
[[package]]906
name = "borsh"907
version = "1.8.1"908
source = "registry+https://github.com/rust-lang/crates.io-index"909
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"910
dependencies = [911
"borsh-derive",912
"bytes",913
"cfg_aliases",914
]915
916
[[package]]917
name = "borsh-derive"918
version = "1.8.1"919
source = "registry+https://github.com/rust-lang/crates.io-index"920
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"921
dependencies = [922
"once_cell",923
"proc-macro-crate 3.5.0",924
"proc-macro2",925
"quote",926
"syn 3.0.6",927
]928
880
[[package]]929
[[package]]881
name = "browser"930
name = "browser"882
version = "0.1.0"931
version = "0.1.0"@@ -992,6 +1041,7 @@ version = "0.1.0"992
dependencies = [1041
dependencies = [993
"base64 0.22.1",1042
"base64 0.22.1",994
"chatsvc",1043
"chatsvc",1044
"chrono",995
"cpal",1045
"cpal",996
"flate2",1046
"flate2",997
"futures-util",1047
"futures-util",@@ -1002,6 +1052,7 @@ dependencies = [1002
"session",1052
"session",1003
"thiserror 2.0.21",1053
"thiserror 2.0.21",1004
"tokio",1054
"tokio",1055
"tract-onnx",1005
"uuid",1056
"uuid",1006
"webview",1057
"webview",1007
"windows 0.62.2",1058
"windows 0.62.2",@@ -1923,6 +1974,17 @@ version = "0.5.8"1923
source = "registry+https://github.com/rust-lang/crates.io-index"1974
source = "registry+https://github.com/rust-lang/crates.io-index"1924
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"1975
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"1925
1976
1977
[[package]]1978
name = "derive-new"1979
version = "0.7.0"1980
source = "registry+https://github.com/rust-lang/crates.io-index"1981
checksum = "2cdc8d50f426189eef89dac62fabfa0abb27d5cc008f25bf4156a0203325becc"1982
dependencies = [1983
"proc-macro2",1984
"quote",1985
"syn 2.0.119",1986
]1987
1926
[[package]]1988
[[package]]1927
name = "derive_more"1989
name = "derive_more"1928
version = "0.99.20"1990
version = "0.99.20"@@ -2083,6 +2145,12 @@ version = "1.2.1"2083
source = "registry+https://github.com/rust-lang/crates.io-index"2145
source = "registry+https://github.com/rust-lang/crates.io-index"2084
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"2146
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"2085
2147
2148
[[package]]2149
name = "downcast-rs"2150
version = "2.0.2"2151
source = "registry+https://github.com/rust-lang/crates.io-index"2152
checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"2153
2086
[[package]]2154
[[package]]2087
name = "dpi"2155
name = "dpi"2088
version = "0.1.2"2156
version = "0.1.2"@@ -2128,6 +2196,12 @@ version = "1.0.20"2128
source = "registry+https://github.com/rust-lang/crates.io-index"2196
source = "registry+https://github.com/rust-lang/crates.io-index"2129
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"2197
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"2130
2198
2199
[[package]]2200
name = "dyn-hash"2201
version = "1.0.0"2202
source = "registry+https://github.com/rust-lang/crates.io-index"2203
checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"2204
2131
[[package]]2205
[[package]]2132
name = "ego-tree"2206
name = "ego-tree"2133
version = "0.10.0"2207
version = "0.10.0"@@ -2395,6 +2469,16 @@ dependencies = [2395
"winapi",2469
"winapi",2396
]2470
]2397
2471
2472
[[package]]2473
name = "filetime"2474
version = "0.2.29"2475
source = "registry+https://github.com/rust-lang/crates.io-index"2476
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"2477
dependencies = [2478
"cfg-if 1.0.5",2479
"libc",2480
]2481
2398
[[package]]2482
[[package]]2399
name = "find-msvc-tools"2483
name = "find-msvc-tools"2400
version = "0.1.14"2484
version = "0.1.14"@@ -2944,7 +3028,7 @@ dependencies = [2944
"gobject-sys 0.21.5",3028
"gobject-sys 0.21.5",2945
"libc",3029
"libc",2946
"system-deps 7.0.8",3030
"system-deps 7.0.8",2947
"windows-sys 0.52.0",3031
"windows-sys 0.61.2",2948
]3032
]2949
3033
2950
[[package]]3034
[[package]]@@ -3769,6 +3853,8 @@ dependencies = [3769
[[package]]3853
[[package]]3770
name = "gpui-pre-windows"3854
name = "gpui-pre-windows"3771
version = "0.3.8"3855
version = "0.3.8"3856
source = "registry+https://github.com/rust-lang/crates.io-index"3857
checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"3772
dependencies = [3858
dependencies = [3773
"accesskit",3859
"accesskit",3774
"accesskit_windows",3860
"accesskit_windows",@@ -4536,6 +4622,15 @@ dependencies = [4536
"either",4622
"either",4537
]4623
]4538
4624
4625
[[package]]4626
name = "itertools"4627
version = "0.15.0"4628
source = "registry+https://github.com/rust-lang/crates.io-index"4629
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"4630
dependencies = [4631
"either",4632
]4633
4539
[[package]]4634
[[package]]4540
name = "itoa"4635
name = "itoa"4541
version = "1.0.18"4636
version = "1.0.18"@@ -5046,6 +5141,12 @@ dependencies = [5046
"libc",5141
"libc",5047
]5142
]5048
5143
5144
[[package]]5145
name = "maplit"5146
version = "1.0.2"5147
source = "registry+https://github.com/rust-lang/crates.io-index"5148
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"5149
5049
[[package]]5150
[[package]]5050
name = "markdown"5151
name = "markdown"5051
version = "1.0.0"5152
version = "1.0.0"@@ -5107,6 +5208,16 @@ dependencies = [5107
"syn 2.0.119",5208
"syn 2.0.119",5108
]5209
]5109
5210
5211
[[package]]5212
name = "matrixmultiply"5213
version = "0.3.11"5214
source = "registry+https://github.com/rust-lang/crates.io-index"5215
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"5216
dependencies = [5217
"autocfg",5218
"rawpointer",5219
]5220
5110
[[package]]5221
[[package]]5111
name = "maybe-rayon"5222
name = "maybe-rayon"5112
version = "0.1.1"5223
version = "0.1.1"@@ -5142,6 +5253,12 @@ dependencies = [5142
"libc",5253
"libc",5143
]5254
]5144
5255
5256
[[package]]5257
name = "memo-map"5258
version = "0.3.4"5259
source = "registry+https://github.com/rust-lang/crates.io-index"5260
checksum = "5449c8c750f1a07ea702bbd212bd999fceece9b3d1508b17023b3e174583124b"5261
5145
[[package]]5262
[[package]]5146
name = "memoffset"5263
name = "memoffset"5147
version = "0.9.1"5264
version = "0.9.1"@@ -5197,6 +5314,16 @@ dependencies = [5197
"unicase",5314
"unicase",5198
]5315
]5199
5316
5317
[[package]]5318
name = "minijinja"5319
version = "2.24.0"5320
source = "registry+https://github.com/rust-lang/crates.io-index"5321
checksum = "86886cf6dbf4e614b19c9a1eec9775f021869d7eadde0fc73921a81b90c9b4c9"5322
dependencies = [5323
"memo-map",5324
"serde",5325
]5326
5200
[[package]]5327
[[package]]5201
name = "minimal-lexical"5328
name = "minimal-lexical"5202
version = "0.2.1"5329
version = "0.2.1"@@ -5306,6 +5433,21 @@ dependencies = [5306
"getrandom 0.2.17",5433
"getrandom 0.2.17",5307
]5434
]5308
5435
5436
[[package]]5437
name = "ndarray"5438
version = "0.17.2"5439
source = "registry+https://github.com/rust-lang/crates.io-index"5440
checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"5441
dependencies = [5442
"matrixmultiply",5443
"num-complex",5444
"num-integer",5445
"num-traits",5446
"portable-atomic",5447
"portable-atomic-util",5448
"rawpointer",5449
]5450
5309
[[package]]5451
[[package]]5310
name = "ndk"5452
name = "ndk"5311
version = "0.9.0"5453
version = "0.9.0"@@ -5441,6 +5583,15 @@ dependencies = [5441
"memchr",5583
"memchr",5442
]5584
]5443
5585
5586
[[package]]5587
name = "nom-language"5588
version = "0.1.0"5589
source = "registry+https://github.com/rust-lang/crates.io-index"5590
checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29"5591
dependencies = [5592
"nom 8.0.0",5593
]5594
5444
[[package]]5595
[[package]]5445
name = "noop_proc_macro"5596
name = "noop_proc_macro"5446
version = "0.3.0"5597
version = "0.3.0"@@ -6218,6 +6369,12 @@ version = "0.1.1"6218
source = "registry+https://github.com/rust-lang/crates.io-index"6369
source = "registry+https://github.com/rust-lang/crates.io-index"6219
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"6370
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"6220
6371
6372
[[package]]6373
name = "pastey"6374
version = "0.2.3"6375
source = "registry+https://github.com/rust-lang/crates.io-index"6376
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"6377
6221
[[package]]6378
[[package]]6222
name = "pathfinder_geometry"6379
name = "pathfinder_geometry"6223
version = "0.5.1"6380
version = "0.5.1"@@ -6542,6 +6699,15 @@ dependencies = [6542
"syn 2.0.119",6699
"syn 2.0.119",6543
]6700
]6544
6701
6702
[[package]]6703
name = "primal-check"6704
version = "0.3.4"6705
source = "registry+https://github.com/rust-lang/crates.io-index"6706
checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"6707
dependencies = [6708
"num-integer",6709
]6710
6545
[[package]]6711
[[package]]6546
name = "proc-macro-crate"6712
name = "proc-macro-crate"6547
version = "1.3.1"6713
version = "1.3.1"@@ -6654,6 +6820,29 @@ dependencies = [6654
"syn 2.0.119",6820
"syn 2.0.119",6655
]6821
]6656
6822
6823
[[package]]6824
name = "prost"6825
version = "0.14.4"6826
source = "registry+https://github.com/rust-lang/crates.io-index"6827
checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"6828
dependencies = [6829
"bytes",6830
"prost-derive",6831
]6832
6833
[[package]]6834
name = "prost-derive"6835
version = "0.14.4"6836
source = "registry+https://github.com/rust-lang/crates.io-index"6837
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"6838
dependencies = [6839
"anyhow",6840
"itertools 0.14.0",6841
"proc-macro2",6842
"quote",6843
"syn 2.0.119",6844
]6845
6657
[[package]]6846
[[package]]6658
name = "pulp"6847
name = "pulp"6659
version = "0.22.3"6848
version = "0.22.3"@@ -6866,6 +7055,16 @@ version = "0.10.1"6866
source = "registry+https://github.com/rust-lang/crates.io-index"7055
source = "registry+https://github.com/rust-lang/crates.io-index"6867
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"7056
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"6868
7057
7058
[[package]]7059
name = "rand_distr"7060
version = "0.6.0"7061
source = "registry+https://github.com/rust-lang/crates.io-index"7062
checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8"7063
dependencies = [7064
"num-traits",7065
"rand 0.10.3",7066
]7067
6869
[[package]]7068
[[package]]6870
name = "rand_pcg"7069
name = "rand_pcg"6871
version = "0.10.2"7070
version = "0.10.2"@@ -6973,6 +7172,12 @@ dependencies = [6973
"objc2-quartz-core 0.3.2",7172
"objc2-quartz-core 0.3.2",6974
]7173
]6975
7174
7175
[[package]]7176
name = "rawpointer"7177
version = "0.2.1"7178
source = "registry+https://github.com/rust-lang/crates.io-index"7179
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"7180
6976
[[package]]7181
[[package]]6977
name = "rayon"7182
name = "rayon"6978
version = "1.12.0"7183
version = "1.12.0"@@ -7372,6 +7577,20 @@ dependencies = [7372
"semver",7577
"semver",7373
]7578
]7374
7579
7580
[[package]]7581
name = "rustfft"7582
version = "6.4.1"7583
source = "registry+https://github.com/rust-lang/crates.io-index"7584
checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"7585
dependencies = [7586
"num-complex",7587
"num-integer",7588
"num-traits",7589
"primal-check",7590
"strength_reduce",7591
"transpose",7592
]7593
7375
[[package]]7594
[[package]]7376
name = "rustix"7595
name = "rustix"7377
version = "0.38.44"7596
version = "0.38.44"@@ -8104,6 +8323,12 @@ version = "0.4.4"8104
source = "registry+https://github.com/rust-lang/crates.io-index"8323
source = "registry+https://github.com/rust-lang/crates.io-index"8105
checksum = "d08889ec5408683408db66ad89e0e1f93dff55c73a4ccc71c427d5b277ee47e6"8324
checksum = "d08889ec5408683408db66ad89e0e1f93dff55c73a4ccc71c427d5b277ee47e6"8106
8325
8326
[[package]]8327
name = "strength_reduce"8328
version = "0.2.4"8329
source = "registry+https://github.com/rust-lang/crates.io-index"8330
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"8331
8107
[[package]]8332
[[package]]8108
name = "strict-num"8333
name = "strict-num"8109
version = "0.1.1"8334
version = "0.1.1"@@ -8113,6 +8338,16 @@ dependencies = [8113
"float-cmp",8338
"float-cmp",8114
]8339
]8115
8340
8341
[[package]]8342
name = "string-interner"8343
version = "0.20.0"8344
source = "registry+https://github.com/rust-lang/crates.io-index"8345
checksum = "ad3df9b59e2eded8d825c7c4363ad339a20fb6bc0b9a4778560f518f59910b15"8346
dependencies = [8347
"hashbrown 0.16.1",8348
"serde",8349
]8350
8116
[[package]]8351
[[package]]8117
name = "string_cache"8352
name = "string_cache"8118
version = "0.8.9"8353
version = "0.8.9"@@ -8482,6 +8717,17 @@ dependencies = [8482
"objc",8717
"objc",8483
]8718
]8484
8719
8720
[[package]]8721
name = "tar"8722
version = "0.4.46"8723
source = "registry+https://github.com/rust-lang/crates.io-index"8724
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"8725
dependencies = [8726
"filetime",8727
"libc",8728
"xattr",8729
]8730
8485
[[package]]8731
[[package]]8486
name = "target-lexicon"8732
name = "target-lexicon"8487
version = "0.12.16"8733
version = "0.12.16"@@ -8994,6 +9240,184 @@ dependencies = [8994
"tracing-log",9240
"tracing-log",8995
]9241
]8996
9242
9243
[[package]]9244
name = "tract-core"9245
version = "0.23.8"9246
source = "registry+https://github.com/rust-lang/crates.io-index"9247
checksum = "0a5a9e07e863fc28355436c5a48fe859784832094ba1ff410357396ae87ff1e3"9248
dependencies = [9249
"anyhow",9250
"anymap3",9251
"bit-set 0.11.1",9252
"derive-new",9253
"downcast-rs 2.0.2",9254
"dyn-clone",9255
"erased-serde",9256
"inventory",9257
"lazy_static",9258
"log",9259
"maplit",9260
"ndarray",9261
"num-complex",9262
"num-integer",9263
"num-traits",9264
"pastey 0.2.3",9265
"rustfft",9266
"serde",9267
"smallvec",9268
"tract-data",9269
"tract-linalg",9270
]9271
9272
[[package]]9273
name = "tract-data"9274
version = "0.23.8"9275
source = "registry+https://github.com/rust-lang/crates.io-index"9276
checksum = "a33bafcf1d3dfa404c3271dd08304b162deb8fcfe9536290fb97e578c32d5dd5"9277
dependencies = [9278
"anyhow",9279
"downcast-rs 2.0.2",9280
"dyn-clone",9281
"dyn-hash",9282
"half",9283
"inventory",9284
"itertools 0.15.0",9285
"lazy_static",9286
"libm",9287
"maplit",9288
"ndarray",9289
"nom 8.0.0",9290
"nom-language",9291
"num-integer",9292
"num-traits",9293
"parking_lot",9294
"smallvec",9295
"string-interner",9296
]9297
9298
[[package]]9299
name = "tract-extra"9300
version = "0.23.8"9301
source = "registry+https://github.com/rust-lang/crates.io-index"9302
checksum = "2a05c86ece0c47880c7726e08dabb72d68e9cba0cd36d44bc0aa90e2291a05db"9303
dependencies = [9304
"tract-nnef",9305
]9306
9307
[[package]]9308
name = "tract-hir"9309
version = "0.23.8"9310
source = "registry+https://github.com/rust-lang/crates.io-index"9311
checksum = "a52e3ec1f3beb16d552806386e123cf5632d4206154695a80aaecdb6ee2c5128"9312
dependencies = [9313
"derive-new",9314
"log",9315
"tract-core",9316
]9317
9318
[[package]]9319
name = "tract-linalg"9320
version = "0.23.8"9321
source = "registry+https://github.com/rust-lang/crates.io-index"9322
checksum = "1cc37ab328b95cef8eef98324122e9f956fd3ca197f0892e09ff90fe495fa222"9323
dependencies = [9324
"byteorder",9325
"cc",9326
"derive-new",9327
"downcast-rs 2.0.2",9328
"dyn-clone",9329
"dyn-hash",9330
"half",9331
"inventory",9332
"lazy_static",9333
"libc",9334
"log",9335
"minijinja",9336
"num-traits",9337
"pastey 0.2.3",9338
"tract-data",9339
"walkdir",9340
]9341
9342
[[package]]9343
name = "tract-nnef"9344
version = "0.23.8"9345
source = "registry+https://github.com/rust-lang/crates.io-index"9346
checksum = "5d95e30d7e6c2f73516212367a5b49354c105b52285e8919ec439c84556f54b3"9347
dependencies = [9348
"byteorder",9349
"erased-serde",9350
"log",9351
"nom 8.0.0",9352
"nom-language",9353
"serde",9354
"serde_json",9355
"simd-adler32",9356
"tar",9357
"tract-core",9358
"walkdir",9359
]9360
9361
[[package]]9362
name = "tract-onnx"9363
version = "0.23.8"9364
source = "registry+https://github.com/rust-lang/crates.io-index"9365
checksum = "5a316674683d04c6070146badf57a7b8b9d99d4e38f586cbe3214e553d70bc2d"9366
dependencies = [9367
"bytes",9368
"derive-new",9369
"log",9370
"memmap2",9371
"nom 8.0.0",9372
"nom-language",9373
"num-integer",9374
"num-rational",9375
"num-traits",9376
"prost",9377
"smallvec",9378
"tract-extra",9379
"tract-hir",9380
"tract-nnef",9381
"tract-onnx-opl",9382
"tract-transformers",9383
]9384
9385
[[package]]9386
name = "tract-onnx-opl"9387
version = "0.23.8"9388
source = "registry+https://github.com/rust-lang/crates.io-index"9389
checksum = "091e126c52d608214f8784f468c7d0be44459e7a369fb9a26f92aa593a78f4a5"9390
dependencies = [9391
"getrandom 0.4.3",9392
"log",9393
"rand 0.10.3",9394
"rand_distr",9395
"rustfft",9396
"tract-extra",9397
"tract-nnef",9398
]9399
9400
[[package]]9401
name = "tract-transformers"9402
version = "0.23.8"9403
source = "registry+https://github.com/rust-lang/crates.io-index"9404
checksum = "4eefbb8d21ab36b48185fc86a3e861b3b62e6dcfd97c3cc13b0dd34389b60916"9405
dependencies = [9406
"float-ord",9407
"rayon",9408
"tract-nnef",9409
]9410
9411
[[package]]9412
name = "transpose"9413
version = "0.2.3"9414
source = "registry+https://github.com/rust-lang/crates.io-index"9415
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"9416
dependencies = [9417
"num-integer",9418
"strength_reduce",9419
]9420
8997
[[package]]9421
[[package]]8998
name = "tray-icon"9422
name = "tray-icon"8999
version = "0.21.3"9423
version = "0.21.3"@@ -9516,7 +9940,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"9516
checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"9940
checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"9517
dependencies = [9941
dependencies = [9518
"cc",9942
"cc",9519
"downcast-rs",9943
"downcast-rs 1.2.1",9520
"log",9944
"log",9521
"rustix 1.1.5",9945
"rustix 1.1.5",9522
"scoped-tls",9946
"scoped-tls",@@ -10703,6 +11127,16 @@ version = "0.13.2"10703
source = "registry+https://github.com/rust-lang/crates.io-index"11127
source = "registry+https://github.com/rust-lang/crates.io-index"10704
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"11128
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"10705
11129
11130
[[package]]11131
name = "xattr"11132
version = "1.6.1"11133
source = "registry+https://github.com/rust-lang/crates.io-index"11134
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"11135
dependencies = [11136
"libc",11137
"rustix 1.1.5",11138
]11139
10706
[[package]]11140
[[package]]10707
name = "xcb"11141
name = "xcb"10708
version = "1.7.1"11142
version = "1.7.1"@@ -64,6 +64,7 @@
64
64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
65
65
- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
66
66
- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
67
- Organizer controls: lobby banner with Admit and Deny, tile menu (pin, spotlight, mute, remove), Mute all, live captions overlay, camera background blur
67
68
68
69
**App**
69
70
- Dark theme, opens instantly from the cache
@@ -64,6 +64,7 @@64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time65
- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity65
- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity66
- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer66
- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer67
- Organizer controls: lobby banner with Admit and Deny, tile menu (pin, spotlight, mute, remove), Mute all, live captions overlay, camera background blur67
68
68
**App**69
**App**69
- Dark theme, opens instantly from the cache70
- Dark theme, opens instantly from the cache@@ -2,7 +2,7 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 92 %** (79 done, 6 partial, 4 missing of 89). Partial counts half.
5
**Parity: 91 %** (79 done, 9 partial, 4 missing of 92). Partial counts half.
6
6
7
7
## By area
8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18
18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19
19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20
20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21
| [Calls and meetings](#calls-and-meetings) | 64 % | 2 | 5 | 0 |
21
| [Calls and meetings](#calls-and-meetings) | 60 % | 2 | 8 | 0 |
22
22
23
23
## Next
24
24
@@ -168,6 +168,9 @@ Feature parity with the Microsoft Teams desktop client.
168
168
| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
169
169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |
170
170
| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |
171
| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
172
| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |
173
| Background blur | Partial | Camera menu Background: None / Blur (remembered). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
171
174
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
172
175
173
176
## Agents
@@ -2,7 +2,7 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 92 %** (79 done, 6 partial, 4 missing of 89). Partial counts half.5
**Parity: 91 %** (79 done, 9 partial, 4 missing of 92). Partial counts half.6
6
7
## By area7
## By area8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |21
| [Calls and meetings](#calls-and-meetings) | 64 % | 2 | 5 | 0 |21
| [Calls and meetings](#calls-and-meetings) | 60 % | 2 | 8 | 0 |22
22
23
## Next23
## Next24
24
@@ -168,6 +168,9 @@ Feature parity with the Microsoft Teams desktop client.168
| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |168
| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |170
| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |170
| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |171
| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |172
| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |173
| Background blur | Partial | Camera menu Background: None / Blur (remembered). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |171
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |174
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |172
175
173
## Agents176
## Agents@@ -115,6 +115,7 @@ pub struct AppState {
115
115
pub call_launcher: Option<Arc<CallLauncher>>,
116
116
pub call_count: u64,
117
117
pub call_share_sound: bool,
118
pub call_background_blur: bool,
118
119
pub rings: Rings,
119
120
pub live_meetings: HashMap<String, LiveMeeting>,
120
121
pub live_refreshing: HashSet<String>,
@@ -206,6 +207,7 @@ impl AppState {
206
207
call_launcher: None,
207
208
call_count: 0,
208
209
call_share_sound: false,
210
call_background_blur: false,
209
211
rings: Rings::default(),
210
212
live_meetings: HashMap::new(),
211
213
live_refreshing: HashSet::new(),
@@ -214,6 +216,7 @@ impl AppState {
214
216
state.local_previews = load_local_previews(&state.store);
215
217
state.collapsed = state.load_collapsed();
216
218
state.call_share_sound = crate::call::load_share_sound(&state.store);
219
state.call_background_blur = crate::call::load_background_blur(&state.store);
217
220
state.load_cached_translation_settings();
218
221
if !mode.demo {
219
222
state.directory.load_cached_presence(&state.store);
@@ -115,6 +115,7 @@ pub struct AppState {115
pub call_launcher: Option<Arc<CallLauncher>>,115
pub call_launcher: Option<Arc<CallLauncher>>,116
pub call_count: u64,116
pub call_count: u64,117
pub call_share_sound: bool,117
pub call_share_sound: bool,118
pub call_background_blur: bool,118
pub rings: Rings,119
pub rings: Rings,119
pub live_meetings: HashMap<String, LiveMeeting>,120
pub live_meetings: HashMap<String, LiveMeeting>,120
pub live_refreshing: HashSet<String>,121
pub live_refreshing: HashSet<String>,@@ -206,6 +207,7 @@ impl AppState {206
call_launcher: None,207
call_launcher: None,207
call_count: 0,208
call_count: 0,208
call_share_sound: false,209
call_share_sound: false,210
call_background_blur: false,209
rings: Rings::default(),211
rings: Rings::default(),210
live_meetings: HashMap::new(),212
live_meetings: HashMap::new(),211
live_refreshing: HashSet::new(),213
live_refreshing: HashSet::new(),@@ -214,6 +216,7 @@ impl AppState {214
state.local_previews = load_local_previews(&state.store);216
state.local_previews = load_local_previews(&state.store);215
state.collapsed = state.load_collapsed();217
state.collapsed = state.load_collapsed();216
state.call_share_sound = crate::call::load_share_sound(&state.store);218
state.call_share_sound = crate::call::load_share_sound(&state.store);219
state.call_background_blur = crate::call::load_background_blur(&state.store);217
state.load_cached_translation_settings();220
state.load_cached_translation_settings();218
if !mode.demo {221
if !mode.demo {219
state.directory.load_cached_presence(&state.store);222
state.directory.load_cached_presence(&state.store);@@ -7,7 +7,7 @@ use calling::{
7
7
use gpui_kit::*;
8
8
9
9
use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};
10
use super::model::{ActiveCall, CallModel, ended_notice};
10
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
11
11
use super::pictures::CallPictures;
12
12
use super::ring::{MissedCall, RingOutcome};
13
13
use super::target::{is_organizer, plan_for_chat};
@@ -28,11 +28,16 @@ const DEMO_SMALL_MEETING: usize = 4;
28
28
const DEMO_LIVE_MINUTES: i64 = 60;
29
29
const ORGID_PREFIX: &str = "8:orgid:";
30
30
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
31
pub const BACKGROUND_BLUR_META_KEY: &str = "call_background_blur";
31
32
32
33
pub fn load_share_sound(store: &store::Store) -> bool {
33
34
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
34
35
}
35
36
37
pub fn load_background_blur(store: &store::Store) -> bool {
38
store.meta(BACKGROUND_BLUR_META_KEY).ok().flatten().as_deref() == Some("1")
39
}
40
36
41
fn now_unix() -> i64 {
37
42
chrono::Utc::now().timestamp()
38
43
}
@@ -105,6 +110,7 @@ impl AppState {
105
110
let demo = DemoCall::Meeting {
106
111
guests: demo_guests(guests),
107
112
lobby: conversation_id == DEMO_LOBBY_MEETING,
113
organizer: conversation_id != DEMO_LOBBY_MEETING,
108
114
};
109
115
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {
110
116
return;
@@ -157,6 +163,12 @@ impl AppState {
157
163
if self.call_share_sound {
158
164
self.send_call_command(CallCommand::SetShareSound(true));
159
165
}
166
if self.call_background_blur {
167
self.send_call_command(CallCommand::SetBlur(true));
168
if let Some(call) = self.call.as_mut() {
169
call.model.blur = true;
170
}
171
}
160
172
self.new_chat = false;
161
173
self.follow_call(call_id, updates, cx);
162
174
cx.emit(AppEvent::Call);
@@ -387,6 +399,75 @@ impl AppState {
387
399
cx.notify();
388
400
}
389
401
402
pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
403
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {
404
self.send_call_command(CallCommand::Admit { mri });
405
}
406
}
407
408
pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {
409
if self.call.as_ref().is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty()) {
410
self.send_call_command(CallCommand::AdmitAll);
411
}
412
}
413
414
pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
415
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {
416
self.send_call_command(CallCommand::Deny { mri });
417
}
418
}
419
420
pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
421
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
422
self.send_call_command(CallCommand::MuteParticipant { mri });
423
}
424
}
425
426
pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {
427
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
428
self.send_call_command(CallCommand::MuteAll);
429
}
430
}
431
432
pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
433
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
434
self.send_call_command(CallCommand::RemoveParticipant { mri });
435
}
436
}
437
438
pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {
439
let Some(call) = self.call.as_ref().filter(|call| call.model.can_manage() && call.model.is_active()) else {
440
return;
441
};
442
let command = if call.model.is_spotlighted(&mri) { CallCommand::StopSpotlight { mri } } else { CallCommand::Spotlight { mri } };
443
self.send_call_command(command);
444
}
445
446
pub fn toggle_call_pin(&mut self, mri: &str, cx: &mut Context<Self>) {
447
if let Some(call) = self.call.as_mut() {
448
call.model.toggle_pin(mri);
449
cx.notify();
450
}
451
}
452
453
pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {
454
let Some(call) = self.call.as_ref().filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting) else {
455
return;
456
};
457
let on = !call.model.captions_on();
458
self.send_call_command(CallCommand::SetCaptions(on));
459
}
460
461
pub fn set_call_background_blur(&mut self, on: bool, cx: &mut Context<Self>) {
462
self.call_background_blur = on;
463
let _ = self.store.set_meta(BACKGROUND_BLUR_META_KEY, if on { "1" } else { "0" });
464
if let Some(call) = self.call.as_mut() {
465
call.model.blur = on;
466
}
467
self.send_call_command(CallCommand::SetBlur(on));
468
cx.notify();
469
}
470
390
471
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
391
472
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
392
473
return;
@@ -717,6 +798,8 @@ mod tests {
717
798
has_video: false,
718
799
sharing: false,
719
800
hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),
801
spotlight: None,
802
organizer: false,
720
803
}]), cx);
721
804
state.lower_call_hand("8:orgid:a".into(), cx);
722
805
state.lower_all_call_hands(cx);
@@ -726,6 +809,105 @@ mod tests {
726
809
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));
727
810
}
728
811
812
fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {
813
calling::RosterEntry {
814
mri: mri.into(),
815
display_name: name.into(),
816
muted: false,
817
in_lobby,
818
has_video: false,
819
sharing: false,
820
hand: None,
821
spotlight: spotlit.then(|| calling::Spotlight { state_id: "sp".into(), rank: 1 }),
822
organizer: false,
823
}
824
}
825
826
#[gpui_kit::test]
827
fn organizer_controls_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
828
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
829
cx.update(|cx| {
830
attendee.update(cx, |state, cx| {
831
state.admit_call_guest("8:orgid:g".into(), cx);
832
state.admit_all_call_guests(cx);
833
state.deny_call_guest("8:orgid:g".into(), cx);
834
state.mute_call_participant("8:orgid:a".into(), cx);
835
state.mute_all_call(cx);
836
state.remove_call_participant("8:orgid:a".into(), cx);
837
state.toggle_call_spotlight("8:orgid:a".into(), cx);
838
})
839
});
840
assert_eq!(attendee_control.try_recv_command(), None);
841
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
842
cx.update(|cx| {
843
organizer.update(cx, |state, cx| {
844
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, false), guest("8:orgid:g", "Gast", true, false)]), cx);
845
state.admit_call_guest("8:orgid:g".into(), cx);
846
state.admit_all_call_guests(cx);
847
state.deny_call_guest("8:orgid:g".into(), cx);
848
state.mute_call_participant("8:orgid:a".into(), cx);
849
state.mute_all_call(cx);
850
state.remove_call_participant("8:orgid:a".into(), cx);
851
state.toggle_call_spotlight("8:orgid:a".into(), cx);
852
})
853
});
854
assert_eq!(control.try_recv_command(), Some(CallCommand::Admit { mri: "8:orgid:g".into() }));
855
assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));
856
assert_eq!(control.try_recv_command(), Some(CallCommand::Deny { mri: "8:orgid:g".into() }));
857
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteParticipant { mri: "8:orgid:a".into() }));
858
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));
859
assert_eq!(control.try_recv_command(), Some(CallCommand::RemoveParticipant { mri: "8:orgid:a".into() }));
860
assert_eq!(control.try_recv_command(), Some(CallCommand::Spotlight { mri: "8:orgid:a".into() }));
861
}
862
863
#[gpui_kit::test]
864
fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(cx: &mut TestAppContext) {
865
let (app, mut control) = app_with_commands(cx, live_meeting(true), None);
866
cx.update(|cx| {
867
app.update(cx, |state, cx| {
868
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]), cx);
869
state.toggle_call_spotlight("8:orgid:a".into(), cx);
870
state.toggle_call_pin("8:orgid:a", cx);
871
assert_eq!(state.call.as_ref().unwrap().model.pinned.as_deref(), Some("8:orgid:a"));
872
state.toggle_call_pin("8:orgid:a", cx);
873
assert_eq!(state.call.as_ref().unwrap().model.pinned, None);
874
})
875
});
876
assert_eq!(control.try_recv_command(), Some(CallCommand::StopSpotlight { mri: "8:orgid:a".into() }));
877
assert_eq!(control.try_recv_command(), None);
878
}
879
880
#[gpui_kit::test]
881
fn captions_toggle_between_on_and_off_and_only_in_meetings(cx: &mut TestAppContext) {
882
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
883
cx.update(|cx| {
884
app.update(cx, |state, cx| {
885
state.toggle_call_captions(cx);
886
state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
887
state.toggle_call_captions(cx);
888
})
889
});
890
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
891
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(false)));
892
let app = app_with_call(cx);
893
cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));
894
}
895
896
#[gpui_kit::test]
897
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
898
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
899
let store = cx.update(|cx| app.read(cx).store.clone());
900
assert!(!cx.update(|cx| app.read(cx).call_background_blur));
901
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(true, cx)));
902
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBlur(true)));
903
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.blur));
904
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
905
assert!(cx.update(|cx| reopened.read(cx).call_background_blur));
906
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(false, cx)));
907
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
908
assert!(!cx.update(|cx| reopened.read(cx).call_background_blur));
909
}
910
729
911
#[gpui_kit::test]
730
912
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {
731
913
let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
@@ -7,7 +7,7 @@ use calling::{7
use gpui_kit::*;7
use gpui_kit::*;8
8
9
use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};9
use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};10
use super::model::{ActiveCall, CallModel, ended_notice};10
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};11
use super::pictures::CallPictures;11
use super::pictures::CallPictures;12
use super::ring::{MissedCall, RingOutcome};12
use super::ring::{MissedCall, RingOutcome};13
use super::target::{is_organizer, plan_for_chat};13
use super::target::{is_organizer, plan_for_chat};@@ -28,11 +28,16 @@ const DEMO_SMALL_MEETING: usize = 4;28
const DEMO_LIVE_MINUTES: i64 = 60;28
const DEMO_LIVE_MINUTES: i64 = 60;29
const ORGID_PREFIX: &str = "8:orgid:";29
const ORGID_PREFIX: &str = "8:orgid:";30
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";30
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";31
pub const BACKGROUND_BLUR_META_KEY: &str = "call_background_blur";31
32
32
pub fn load_share_sound(store: &store::Store) -> bool {33
pub fn load_share_sound(store: &store::Store) -> bool {33
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")34
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")34
}35
}35
36
37
pub fn load_background_blur(store: &store::Store) -> bool {38
store.meta(BACKGROUND_BLUR_META_KEY).ok().flatten().as_deref() == Some("1")39
}40
36
fn now_unix() -> i64 {41
fn now_unix() -> i64 {37
chrono::Utc::now().timestamp()42
chrono::Utc::now().timestamp()38
}43
}@@ -105,6 +110,7 @@ impl AppState {105
let demo = DemoCall::Meeting {110
let demo = DemoCall::Meeting {106
guests: demo_guests(guests),111
guests: demo_guests(guests),107
lobby: conversation_id == DEMO_LOBBY_MEETING,112
lobby: conversation_id == DEMO_LOBBY_MEETING,113
organizer: conversation_id != DEMO_LOBBY_MEETING,108
};114
};109
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {115
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {110
return;116
return;@@ -157,6 +163,12 @@ impl AppState {157
if self.call_share_sound {163
if self.call_share_sound {158
self.send_call_command(CallCommand::SetShareSound(true));164
self.send_call_command(CallCommand::SetShareSound(true));159
}165
}166
if self.call_background_blur {167
self.send_call_command(CallCommand::SetBlur(true));168
if let Some(call) = self.call.as_mut() {169
call.model.blur = true;170
}171
}160
self.new_chat = false;172
self.new_chat = false;161
self.follow_call(call_id, updates, cx);173
self.follow_call(call_id, updates, cx);162
cx.emit(AppEvent::Call);174
cx.emit(AppEvent::Call);@@ -387,6 +399,75 @@ impl AppState {387
cx.notify();399
cx.notify();388
}400
}389
401
402
pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {403
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {404
self.send_call_command(CallCommand::Admit { mri });405
}406
}407
408
pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {409
if self.call.as_ref().is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty()) {410
self.send_call_command(CallCommand::AdmitAll);411
}412
}413
414
pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {415
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {416
self.send_call_command(CallCommand::Deny { mri });417
}418
}419
420
pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {421
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {422
self.send_call_command(CallCommand::MuteParticipant { mri });423
}424
}425
426
pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {427
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {428
self.send_call_command(CallCommand::MuteAll);429
}430
}431
432
pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {433
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {434
self.send_call_command(CallCommand::RemoveParticipant { mri });435
}436
}437
438
pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {439
let Some(call) = self.call.as_ref().filter(|call| call.model.can_manage() && call.model.is_active()) else {440
return;441
};442
let command = if call.model.is_spotlighted(&mri) { CallCommand::StopSpotlight { mri } } else { CallCommand::Spotlight { mri } };443
self.send_call_command(command);444
}445
446
pub fn toggle_call_pin(&mut self, mri: &str, cx: &mut Context<Self>) {447
if let Some(call) = self.call.as_mut() {448
call.model.toggle_pin(mri);449
cx.notify();450
}451
}452
453
pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {454
let Some(call) = self.call.as_ref().filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting) else {455
return;456
};457
let on = !call.model.captions_on();458
self.send_call_command(CallCommand::SetCaptions(on));459
}460
461
pub fn set_call_background_blur(&mut self, on: bool, cx: &mut Context<Self>) {462
self.call_background_blur = on;463
let _ = self.store.set_meta(BACKGROUND_BLUR_META_KEY, if on { "1" } else { "0" });464
if let Some(call) = self.call.as_mut() {465
call.model.blur = on;466
}467
self.send_call_command(CallCommand::SetBlur(on));468
cx.notify();469
}470
390
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {471
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {391
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {472
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {392
return;473
return;@@ -717,6 +798,8 @@ mod tests {717
has_video: false,798
has_video: false,718
sharing: false,799
sharing: false,719
hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),800
hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),801
spotlight: None,802
organizer: false,720
}]), cx);803
}]), cx);721
state.lower_call_hand("8:orgid:a".into(), cx);804
state.lower_call_hand("8:orgid:a".into(), cx);722
state.lower_all_call_hands(cx);805
state.lower_all_call_hands(cx);@@ -726,6 +809,105 @@ mod tests {726
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));809
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));727
}810
}728
811
812
fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {813
calling::RosterEntry {814
mri: mri.into(),815
display_name: name.into(),816
muted: false,817
in_lobby,818
has_video: false,819
sharing: false,820
hand: None,821
spotlight: spotlit.then(|| calling::Spotlight { state_id: "sp".into(), rank: 1 }),822
organizer: false,823
}824
}825
826
#[gpui_kit::test]827
fn organizer_controls_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {828
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);829
cx.update(|cx| {830
attendee.update(cx, |state, cx| {831
state.admit_call_guest("8:orgid:g".into(), cx);832
state.admit_all_call_guests(cx);833
state.deny_call_guest("8:orgid:g".into(), cx);834
state.mute_call_participant("8:orgid:a".into(), cx);835
state.mute_all_call(cx);836
state.remove_call_participant("8:orgid:a".into(), cx);837
state.toggle_call_spotlight("8:orgid:a".into(), cx);838
})839
});840
assert_eq!(attendee_control.try_recv_command(), None);841
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);842
cx.update(|cx| {843
organizer.update(cx, |state, cx| {844
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, false), guest("8:orgid:g", "Gast", true, false)]), cx);845
state.admit_call_guest("8:orgid:g".into(), cx);846
state.admit_all_call_guests(cx);847
state.deny_call_guest("8:orgid:g".into(), cx);848
state.mute_call_participant("8:orgid:a".into(), cx);849
state.mute_all_call(cx);850
state.remove_call_participant("8:orgid:a".into(), cx);851
state.toggle_call_spotlight("8:orgid:a".into(), cx);852
})853
});854
assert_eq!(control.try_recv_command(), Some(CallCommand::Admit { mri: "8:orgid:g".into() }));855
assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));856
assert_eq!(control.try_recv_command(), Some(CallCommand::Deny { mri: "8:orgid:g".into() }));857
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteParticipant { mri: "8:orgid:a".into() }));858
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));859
assert_eq!(control.try_recv_command(), Some(CallCommand::RemoveParticipant { mri: "8:orgid:a".into() }));860
assert_eq!(control.try_recv_command(), Some(CallCommand::Spotlight { mri: "8:orgid:a".into() }));861
}862
863
#[gpui_kit::test]864
fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(cx: &mut TestAppContext) {865
let (app, mut control) = app_with_commands(cx, live_meeting(true), None);866
cx.update(|cx| {867
app.update(cx, |state, cx| {868
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]), cx);869
state.toggle_call_spotlight("8:orgid:a".into(), cx);870
state.toggle_call_pin("8:orgid:a", cx);871
assert_eq!(state.call.as_ref().unwrap().model.pinned.as_deref(), Some("8:orgid:a"));872
state.toggle_call_pin("8:orgid:a", cx);873
assert_eq!(state.call.as_ref().unwrap().model.pinned, None);874
})875
});876
assert_eq!(control.try_recv_command(), Some(CallCommand::StopSpotlight { mri: "8:orgid:a".into() }));877
assert_eq!(control.try_recv_command(), None);878
}879
880
#[gpui_kit::test]881
fn captions_toggle_between_on_and_off_and_only_in_meetings(cx: &mut TestAppContext) {882
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);883
cx.update(|cx| {884
app.update(cx, |state, cx| {885
state.toggle_call_captions(cx);886
state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);887
state.toggle_call_captions(cx);888
})889
});890
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));891
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(false)));892
let app = app_with_call(cx);893
cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));894
}895
896
#[gpui_kit::test]897
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {898
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);899
let store = cx.update(|cx| app.read(cx).store.clone());900
assert!(!cx.update(|cx| app.read(cx).call_background_blur));901
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(true, cx)));902
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBlur(true)));903
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.blur));904
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));905
assert!(cx.update(|cx| reopened.read(cx).call_background_blur));906
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(false, cx)));907
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));908
assert!(!cx.update(|cx| reopened.read(cx).call_background_blur));909
}910
729
#[gpui_kit::test]911
#[gpui_kit::test]730
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {912
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {731
let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));913
let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));@@ -3,10 +3,12 @@ use std::time::{Duration, Instant};
3
3
use calling::video_frame::bgra_from_i420;
4
4
use calling::video_pattern::{PatternKind, pattern_frame};
5
5
use calling::{
6
AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,
7
IncomingRing, Progress, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
6
AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState, DeviceChoice, DeviceLists,
7
EndReason, IncomingRing, Progress, PublishedState, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
8
8
};
9
9
use calling::CameraDevice;
10
11
use super::demo_scene::self_view;
10
12
use tokio::time::{interval, sleep};
11
13
12
14
use super::model::{ECHO_MRI, ECHO_NAME};
@@ -29,6 +31,15 @@ const SHARE_START: Duration = Duration::from_secs(10);
29
31
const SHARE_END: Duration = Duration::from_secs(45);
30
32
const REACTION_EVERY_TICKS: u32 = 20;
31
33
const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];
34
const DEMO_WAITING: [&str; 3] = ["Anja Vogel", "Matteo Conti", "Hannah Weiss"];
35
const CAPTION_WORDS_PER_TICK: usize = 2;
36
const CAPTION_HOLD_TICKS: usize = 14;
37
const DEMO_CAPTIONS: [(usize, &str); 4] = [
38
(0, "Thanks everyone for joining, let us start with the release status."),
39
(1, "The build is green and the new call controls are ready for review."),
40
(2, "Can we admit the two people from the lobby before we begin?"),
41
(0, "Yes, I am letting them in now and we will share the plan on screen."),
42
];
32
43
const GUEST_PHASE: u32 = 37;
33
44
const SELF_PHASE: u32 = 211;
34
45
pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
@@ -53,7 +64,7 @@ pub type Person = (String, String);
53
64
pub enum DemoCall {
54
65
Test,
55
66
People(Vec<Person>),
56
Meeting { guests: Vec<Person>, lobby: bool },
67
Meeting { guests: Vec<Person>, lobby: bool, organizer: bool },
57
68
Incoming(Person),
58
69
}
59
70
@@ -132,6 +143,8 @@ fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
132
143
has_video: index < DEMO_CAMERAS,
133
144
sharing: false,
134
145
hand: None,
146
spotlight: None,
147
organizer: false,
135
148
})
136
149
.collect()
137
150
}
@@ -143,7 +156,7 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {
143
156
let (people, lobby) = match &script {
144
157
DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),
145
158
DemoCall::People(callees) => (callees.clone(), false),
146
DemoCall::Meeting { guests, lobby } => (guests.clone(), *lobby),
159
DemoCall::Meeting { guests, lobby, .. } => (guests.clone(), *lobby),
147
160
DemoCall::Incoming(caller) => (vec![caller.clone()], false),
148
161
};
149
162
if !ring_until_answered(&mut control, &script).await {
@@ -172,6 +185,10 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {
172
185
control.send(CallUpdate::Lobby(false));
173
186
}
174
187
let mut roster = roster_of(&people);
188
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {
189
roster.push(demo_organizer());
190
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));
191
}
175
192
if matches!(script, DemoCall::Meeting { .. }) {
176
193
for (index, rank) in DEMO_FIRST_HANDS {
177
194
if let Some(entry) = roster.get_mut(index) {
@@ -205,9 +222,9 @@ async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bo
205
222
true
206
223
}
207
224
208
fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, sharing: bool, sharer: Option<&str>, camera_on: bool) {
209
if camera_on {
210
control.video.publish(VideoKey::LocalCamera, bgra_from_i420(pattern_frame(PatternKind::Camera, tick + SELF_PHASE)));
225
fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, sharing: bool, sharer: Option<&str>, camera: Option<bool>) {
226
if let Some(blur) = camera {
227
control.video.publish(VideoKey::LocalCamera, self_view((tick + SELF_PHASE) as usize, blur));
211
228
}
212
229
for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {
213
230
let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);
@@ -223,6 +240,9 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
223
240
let mut video_ticks = 0u32;
224
241
let mut sharing = false;
225
242
let mut camera_on = false;
243
let mut blur = false;
244
let mut captions_on = false;
245
let mut caption_ticks = 0usize;
226
246
let mut video_tick = interval(VIDEO_PERIOD);
227
247
let mut muted = false;
228
248
let mut input = DeviceChoice::SystemDefault;
@@ -239,7 +259,7 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
239
259
sharing = share_now;
240
260
control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
241
261
}
242
publish_demo_video(&control, &people, video_ticks, sharing, sharer.as_deref(), camera_on);
262
publish_demo_video(&control, &people, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));
243
263
video_ticks += 1;
244
264
}
245
265
_ = tick.tick() => {
@@ -259,6 +279,12 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
259
279
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];
260
280
control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });
261
281
}
282
if captions_on {
283
if let Some(entry) = demo_caption(&people, caption_ticks) {
284
control.send(CallUpdate::Caption(entry));
285
}
286
caption_ticks += 1;
287
}
262
288
ticks += 1;
263
289
}
264
290
command = control.recv() => match command {
@@ -303,6 +329,43 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
303
329
Some(CallCommand::SendReaction(reaction)) => {
304
330
control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });
305
331
}
332
Some(CallCommand::Admit { mri }) => {
333
roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.in_lobby = false);
334
control.send(CallUpdate::Roster(roster.clone()));
335
}
336
Some(CallCommand::AdmitAll) => {
337
roster.iter_mut().for_each(|entry| entry.in_lobby = false);
338
control.send(CallUpdate::Roster(roster.clone()));
339
}
340
Some(CallCommand::Deny { mri } | CallCommand::RemoveParticipant { mri }) => {
341
roster.retain(|entry| entry.mri != mri);
342
control.send(CallUpdate::Roster(roster.clone()));
343
}
344
Some(CallCommand::MuteParticipant { mri }) => {
345
roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.muted = true);
346
control.send(CallUpdate::Roster(roster.clone()));
347
}
348
Some(CallCommand::MuteAll) => {
349
roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);
350
control.send(CallUpdate::Roster(roster.clone()));
351
}
352
Some(CallCommand::Spotlight { mri }) => {
353
let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;
354
if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
355
entry.spotlight = Some(demo_spotlight(rank));
356
}
357
control.send(CallUpdate::Roster(roster.clone()));
358
}
359
Some(CallCommand::StopSpotlight { mri }) => {
360
roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.spotlight = None);
361
control.send(CallUpdate::Roster(roster.clone()));
362
}
363
Some(CallCommand::SetCaptions(on)) => {
364
captions_on = on;
365
caption_ticks = 0;
366
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));
367
}
368
Some(CallCommand::SetBlur(on)) => blur = on,
306
369
Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
307
370
Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
308
371
end(&control, EndReason::LocalHangup);
@@ -313,6 +376,54 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
313
376
}
314
377
}
315
378
379
fn demo_organizer() -> RosterEntry {
380
RosterEntry {
381
mri: DEMO_OWN_MRI.to_owned(),
382
display_name: "You".to_owned(),
383
muted: false,
384
in_lobby: false,
385
has_video: false,
386
sharing: false,
387
hand: None,
388
spotlight: None,
389
organizer: true,
390
}
391
}
392
393
fn demo_waiting(index: usize, name: &str) -> RosterEntry {
394
RosterEntry {
395
mri: format!("8:orgid:demo-waiting-{index}"),
396
display_name: name.to_owned(),
397
muted: false,
398
in_lobby: true,
399
has_video: false,
400
sharing: false,
401
hand: None,
402
spotlight: None,
403
organizer: false,
404
}
405
}
406
407
fn demo_spotlight(rank: u64) -> PublishedState {
408
PublishedState { state_id: format!("demo-spotlight-{rank}"), rank }
409
}
410
411
fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {
412
let line = tick / (CAPTION_HOLD_TICKS * 2) % DEMO_CAPTIONS.len();
413
let within = tick % (CAPTION_HOLD_TICKS * 2);
414
let (speaker, text) = DEMO_CAPTIONS[line];
415
let words: Vec<&str> = text.split(' ').collect();
416
let shown = ((within + 1) * CAPTION_WORDS_PER_TICK).min(words.len());
417
let (mri, name) = people.get(speaker % people.len().max(1))?;
418
Some(CaptionEntry {
419
id: format!("demo-caption-{}", tick / (CAPTION_HOLD_TICKS * 2)),
420
user_id: mri.clone(),
421
display_name: name.clone(),
422
text: words[..shown].join(" "),
423
is_final: shown == words.len(),
424
})
425
}
426
316
427
fn demo_hand(rank: u64) -> RaisedHand {
317
428
RaisedHand { state_id: format!("demo-hand-{rank}"), rank }
318
429
}
@@ -336,6 +447,8 @@ fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
336
447
has_video: false,
337
448
sharing: false,
338
449
hand: Some(demo_hand(next_rank)),
450
spotlight: None,
451
organizer: false,
339
452
}),
340
453
}
341
454
}
@@ -3,10 +3,12 @@ use std::time::{Duration, Instant};3
use calling::video_frame::bgra_from_i420;3
use calling::video_frame::bgra_from_i420;4
use calling::video_pattern::{PatternKind, pattern_frame};4
use calling::video_pattern::{PatternKind, pattern_frame};5
use calling::{5
use calling::{6
AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,6
AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState, DeviceChoice, DeviceLists,7
IncomingRing, Progress, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,7
EndReason, IncomingRing, Progress, PublishedState, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,8
};8
};9
use calling::CameraDevice;9
use calling::CameraDevice;10
11
use super::demo_scene::self_view;10
use tokio::time::{interval, sleep};12
use tokio::time::{interval, sleep};11
13
12
use super::model::{ECHO_MRI, ECHO_NAME};14
use super::model::{ECHO_MRI, ECHO_NAME};@@ -29,6 +31,15 @@ const SHARE_START: Duration = Duration::from_secs(10);29
const SHARE_END: Duration = Duration::from_secs(45);31
const SHARE_END: Duration = Duration::from_secs(45);30
const REACTION_EVERY_TICKS: u32 = 20;32
const REACTION_EVERY_TICKS: u32 = 20;31
const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];33
const DEMO_FIRST_HANDS: [(usize, u64); 2] = [(2, 1), (0, 2)];34
const DEMO_WAITING: [&str; 3] = ["Anja Vogel", "Matteo Conti", "Hannah Weiss"];35
const CAPTION_WORDS_PER_TICK: usize = 2;36
const CAPTION_HOLD_TICKS: usize = 14;37
const DEMO_CAPTIONS: [(usize, &str); 4] = [38
(0, "Thanks everyone for joining, let us start with the release status."),39
(1, "The build is green and the new call controls are ready for review."),40
(2, "Can we admit the two people from the lobby before we begin?"),41
(0, "Yes, I am letting them in now and we will share the plan on screen."),42
];32
const GUEST_PHASE: u32 = 37;43
const GUEST_PHASE: u32 = 37;33
const SELF_PHASE: u32 = 211;44
const SELF_PHASE: u32 = 211;34
pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";45
pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";@@ -53,7 +64,7 @@ pub type Person = (String, String);53
pub enum DemoCall {64
pub enum DemoCall {54
Test,65
Test,55
People(Vec<Person>),66
People(Vec<Person>),56
Meeting { guests: Vec<Person>, lobby: bool },67
Meeting { guests: Vec<Person>, lobby: bool, organizer: bool },57
Incoming(Person),68
Incoming(Person),58
}69
}59
70
@@ -132,6 +143,8 @@ fn roster_of(people: &[Person]) -> Vec<RosterEntry> {132
has_video: index < DEMO_CAMERAS,143
has_video: index < DEMO_CAMERAS,133
sharing: false,144
sharing: false,134
hand: None,145
hand: None,146
spotlight: None,147
organizer: false,135
})148
})136
.collect()149
.collect()137
}150
}@@ -143,7 +156,7 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {143
let (people, lobby) = match &script {156
let (people, lobby) = match &script {144
DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),157
DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),145
DemoCall::People(callees) => (callees.clone(), false),158
DemoCall::People(callees) => (callees.clone(), false),146
DemoCall::Meeting { guests, lobby } => (guests.clone(), *lobby),159
DemoCall::Meeting { guests, lobby, .. } => (guests.clone(), *lobby),147
DemoCall::Incoming(caller) => (vec![caller.clone()], false),160
DemoCall::Incoming(caller) => (vec![caller.clone()], false),148
};161
};149
if !ring_until_answered(&mut control, &script).await {162
if !ring_until_answered(&mut control, &script).await {@@ -172,6 +185,10 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {172
control.send(CallUpdate::Lobby(false));185
control.send(CallUpdate::Lobby(false));173
}186
}174
let mut roster = roster_of(&people);187
let mut roster = roster_of(&people);188
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {189
roster.push(demo_organizer());190
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));191
}175
if matches!(script, DemoCall::Meeting { .. }) {192
if matches!(script, DemoCall::Meeting { .. }) {176
for (index, rank) in DEMO_FIRST_HANDS {193
for (index, rank) in DEMO_FIRST_HANDS {177
if let Some(entry) = roster.get_mut(index) {194
if let Some(entry) = roster.get_mut(index) {@@ -205,9 +222,9 @@ async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bo205
true222
true206
}223
}207
224
208
fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, sharing: bool, sharer: Option<&str>, camera_on: bool) {225
fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, sharing: bool, sharer: Option<&str>, camera: Option<bool>) {209
if camera_on {226
if let Some(blur) = camera {210
control.video.publish(VideoKey::LocalCamera, bgra_from_i420(pattern_frame(PatternKind::Camera, tick + SELF_PHASE)));227
control.video.publish(VideoKey::LocalCamera, self_view((tick + SELF_PHASE) as usize, blur));211
}228
}212
for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {229
for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {213
let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);230
let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);@@ -223,6 +240,9 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r223
let mut video_ticks = 0u32;240
let mut video_ticks = 0u32;224
let mut sharing = false;241
let mut sharing = false;225
let mut camera_on = false;242
let mut camera_on = false;243
let mut blur = false;244
let mut captions_on = false;245
let mut caption_ticks = 0usize;226
let mut video_tick = interval(VIDEO_PERIOD);246
let mut video_tick = interval(VIDEO_PERIOD);227
let mut muted = false;247
let mut muted = false;228
let mut input = DeviceChoice::SystemDefault;248
let mut input = DeviceChoice::SystemDefault;@@ -239,7 +259,7 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r239
sharing = share_now;259
sharing = share_now;240
control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));260
control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));241
}261
}242
publish_demo_video(&control, &people, video_ticks, sharing, sharer.as_deref(), camera_on);262
publish_demo_video(&control, &people, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));243
video_ticks += 1;263
video_ticks += 1;244
}264
}245
_ = tick.tick() => {265
_ = tick.tick() => {@@ -259,6 +279,12 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r259
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];279
let reaction = Reaction::ALL[(ticks / REACTION_EVERY_TICKS) as usize % Reaction::ALL.len()];260
control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });280
control.send(CallUpdate::Reaction { mri: mri.clone(), reaction });261
}281
}282
if captions_on {283
if let Some(entry) = demo_caption(&people, caption_ticks) {284
control.send(CallUpdate::Caption(entry));285
}286
caption_ticks += 1;287
}262
ticks += 1;288
ticks += 1;263
}289
}264
command = control.recv() => match command {290
command = control.recv() => match command {@@ -303,6 +329,43 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r303
Some(CallCommand::SendReaction(reaction)) => {329
Some(CallCommand::SendReaction(reaction)) => {304
control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });330
control.send(CallUpdate::Reaction { mri: DEMO_OWN_MRI.to_owned(), reaction });305
}331
}332
Some(CallCommand::Admit { mri }) => {333
roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.in_lobby = false);334
control.send(CallUpdate::Roster(roster.clone()));335
}336
Some(CallCommand::AdmitAll) => {337
roster.iter_mut().for_each(|entry| entry.in_lobby = false);338
control.send(CallUpdate::Roster(roster.clone()));339
}340
Some(CallCommand::Deny { mri } | CallCommand::RemoveParticipant { mri }) => {341
roster.retain(|entry| entry.mri != mri);342
control.send(CallUpdate::Roster(roster.clone()));343
}344
Some(CallCommand::MuteParticipant { mri }) => {345
roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.muted = true);346
control.send(CallUpdate::Roster(roster.clone()));347
}348
Some(CallCommand::MuteAll) => {349
roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);350
control.send(CallUpdate::Roster(roster.clone()));351
}352
Some(CallCommand::Spotlight { mri }) => {353
let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;354
if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {355
entry.spotlight = Some(demo_spotlight(rank));356
}357
control.send(CallUpdate::Roster(roster.clone()));358
}359
Some(CallCommand::StopSpotlight { mri }) => {360
roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.spotlight = None);361
control.send(CallUpdate::Roster(roster.clone()));362
}363
Some(CallCommand::SetCaptions(on)) => {364
captions_on = on;365
caption_ticks = 0;366
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));367
}368
Some(CallCommand::SetBlur(on)) => blur = on,306
Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),369
Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),307
Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {370
Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {308
end(&control, EndReason::LocalHangup);371
end(&control, EndReason::LocalHangup);@@ -313,6 +376,54 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r313
}376
}314
}377
}315
378
379
fn demo_organizer() -> RosterEntry {380
RosterEntry {381
mri: DEMO_OWN_MRI.to_owned(),382
display_name: "You".to_owned(),383
muted: false,384
in_lobby: false,385
has_video: false,386
sharing: false,387
hand: None,388
spotlight: None,389
organizer: true,390
}391
}392
393
fn demo_waiting(index: usize, name: &str) -> RosterEntry {394
RosterEntry {395
mri: format!("8:orgid:demo-waiting-{index}"),396
display_name: name.to_owned(),397
muted: false,398
in_lobby: true,399
has_video: false,400
sharing: false,401
hand: None,402
spotlight: None,403
organizer: false,404
}405
}406
407
fn demo_spotlight(rank: u64) -> PublishedState {408
PublishedState { state_id: format!("demo-spotlight-{rank}"), rank }409
}410
411
fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {412
let line = tick / (CAPTION_HOLD_TICKS * 2) % DEMO_CAPTIONS.len();413
let within = tick % (CAPTION_HOLD_TICKS * 2);414
let (speaker, text) = DEMO_CAPTIONS[line];415
let words: Vec<&str> = text.split(' ').collect();416
let shown = ((within + 1) * CAPTION_WORDS_PER_TICK).min(words.len());417
let (mri, name) = people.get(speaker % people.len().max(1))?;418
Some(CaptionEntry {419
id: format!("demo-caption-{}", tick / (CAPTION_HOLD_TICKS * 2)),420
user_id: mri.clone(),421
display_name: name.clone(),422
text: words[..shown].join(" "),423
is_final: shown == words.len(),424
})425
}426
316
fn demo_hand(rank: u64) -> RaisedHand {427
fn demo_hand(rank: u64) -> RaisedHand {317
RaisedHand { state_id: format!("demo-hand-{rank}"), rank }428
RaisedHand { state_id: format!("demo-hand-{rank}"), rank }318
}429
}@@ -336,6 +447,8 @@ fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {336
has_video: false,447
has_video: false,337
sharing: false,448
sharing: false,338
hand: Some(demo_hand(next_rank)),449
hand: Some(demo_hand(next_rank)),450
spotlight: None,451
organizer: false,339
}),452
}),340
}453
}341
}454
}@@ -0,0 +1,81 @@
1
use calling::VideoPicture;
2
use calling::blur::{MASK_HEIGHT, MASK_WIDTH, compose};
3
4
pub const SCENE_WIDTH: usize = 640;
5
pub const SCENE_HEIGHT: usize = 360;
6
const STRIPE: usize = 18;
7
const HEAD: (f32, f32, f32, f32) = (0.5, 0.36, 0.11, 0.2);
8
const SHOULDERS: (f32, f32, f32, f32) = (0.5, 0.92, 0.3, 0.38);
9
const SKIN: [u8; 3] = [226, 172, 140];
10
const SHIRT: [u8; 3] = [52, 92, 168];
11
12
fn inside(x: f32, y: f32, (center_x, center_y, radius_x, radius_y): (f32, f32, f32, f32)) -> bool {
13
let (dx, dy) = ((x - center_x) / radius_x, (y - center_y) / radius_y);
14
dx * dx + dy * dy <= 1.
15
}
16
17
fn person_at(x: f32, y: f32) -> Option<[u8; 3]> {
18
if inside(x, y, HEAD) {
19
Some(SKIN)
20
} else if inside(x, y, SHOULDERS) {
21
Some(SHIRT)
22
} else {
23
None
24
}
25
}
26
27
fn background_at(column: usize, row: usize, tick: usize) -> [u8; 3] {
28
let stripe = ((column + tick) / STRIPE + row / STRIPE).is_multiple_of(2);
29
let shade = (row * 60 / SCENE_HEIGHT) as u8;
30
if stripe { [214 - shade, 120 + shade, 60] } else { [48, 150 - shade, 168 + shade / 2] }
31
}
32
33
fn scene(tick: usize) -> Vec<u8> {
34
let mut rgba = vec![255u8; SCENE_WIDTH * SCENE_HEIGHT * 4];
35
for row in 0..SCENE_HEIGHT {
36
for column in 0..SCENE_WIDTH {
37
let (x, y) = ((column as f32 + 0.5) / SCENE_WIDTH as f32, (row as f32 + 0.5) / SCENE_HEIGHT as f32);
38
let color = person_at(x, y).unwrap_or_else(|| background_at(column, row, tick));
39
rgba[(row * SCENE_WIDTH + column) * 4..][..3].copy_from_slice(&color);
40
}
41
}
42
rgba
43
}
44
45
fn person_mask() -> Vec<f32> {
46
(0..MASK_WIDTH * MASK_HEIGHT)
47
.map(|index| {
48
let (x, y) = (((index % MASK_WIDTH) as f32 + 0.5) / MASK_WIDTH as f32, ((index / MASK_WIDTH) as f32 + 0.5) / MASK_HEIGHT as f32);
49
if person_at(x, y).is_some() { 1. } else { 0. }
50
})
51
.collect()
52
}
53
54
/// A drawn head-and-shoulders scene; the mask comes from the drawing, not from the model.
55
pub fn self_view(tick: usize, blur: bool) -> VideoPicture {
56
let mut rgba = scene(tick);
57
if blur {
58
compose(&mut rgba, SCENE_WIDTH, SCENE_HEIGHT, &person_mask());
59
}
60
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|pixel| [pixel[2], pixel[1], pixel[0], pixel[3]]).collect();
61
VideoPicture { width: SCENE_WIDTH as u32, height: SCENE_HEIGHT as u32, bgra }
62
}
63
64
#[cfg(test)]
65
mod tests {
66
use super::*;
67
68
fn roughness(picture: &VideoPicture, x: usize, y: usize) -> i32 {
69
let at = |column: usize| i32::from(picture.bgra[(y * SCENE_WIDTH + column) * 4]);
70
(0..12).map(|step| (at(x + step + 1) - at(x + step)).abs()).sum()
71
}
72
73
#[test]
74
fn blurring_the_scene_smooths_the_stripes_and_keeps_the_person() {
75
let sharp = self_view(0, false);
76
let blurred = self_view(0, true);
77
assert!(roughness(&blurred, 30, 20) * 3 < roughness(&sharp, 30, 20));
78
let center = (SCENE_HEIGHT / 2 * SCENE_WIDTH + SCENE_WIDTH / 2) * 4;
79
assert_eq!(blurred.bgra[center..center + 3], sharp.bgra[center..center + 3]);
80
}
81
}
@@ -0,0 +1,81 @@1
use calling::VideoPicture;2
use calling::blur::{MASK_HEIGHT, MASK_WIDTH, compose};3
4
pub const SCENE_WIDTH: usize = 640;5
pub const SCENE_HEIGHT: usize = 360;6
const STRIPE: usize = 18;7
const HEAD: (f32, f32, f32, f32) = (0.5, 0.36, 0.11, 0.2);8
const SHOULDERS: (f32, f32, f32, f32) = (0.5, 0.92, 0.3, 0.38);9
const SKIN: [u8; 3] = [226, 172, 140];10
const SHIRT: [u8; 3] = [52, 92, 168];11
12
fn inside(x: f32, y: f32, (center_x, center_y, radius_x, radius_y): (f32, f32, f32, f32)) -> bool {13
let (dx, dy) = ((x - center_x) / radius_x, (y - center_y) / radius_y);14
dx * dx + dy * dy <= 1.15
}16
17
fn person_at(x: f32, y: f32) -> Option<[u8; 3]> {18
if inside(x, y, HEAD) {19
Some(SKIN)20
} else if inside(x, y, SHOULDERS) {21
Some(SHIRT)22
} else {23
None24
}25
}26
27
fn background_at(column: usize, row: usize, tick: usize) -> [u8; 3] {28
let stripe = ((column + tick) / STRIPE + row / STRIPE).is_multiple_of(2);29
let shade = (row * 60 / SCENE_HEIGHT) as u8;30
if stripe { [214 - shade, 120 + shade, 60] } else { [48, 150 - shade, 168 + shade / 2] }31
}32
33
fn scene(tick: usize) -> Vec<u8> {34
let mut rgba = vec![255u8; SCENE_WIDTH * SCENE_HEIGHT * 4];35
for row in 0..SCENE_HEIGHT {36
for column in 0..SCENE_WIDTH {37
let (x, y) = ((column as f32 + 0.5) / SCENE_WIDTH as f32, (row as f32 + 0.5) / SCENE_HEIGHT as f32);38
let color = person_at(x, y).unwrap_or_else(|| background_at(column, row, tick));39
rgba[(row * SCENE_WIDTH + column) * 4..][..3].copy_from_slice(&color);40
}41
}42
rgba43
}44
45
fn person_mask() -> Vec<f32> {46
(0..MASK_WIDTH * MASK_HEIGHT)47
.map(|index| {48
let (x, y) = (((index % MASK_WIDTH) as f32 + 0.5) / MASK_WIDTH as f32, ((index / MASK_WIDTH) as f32 + 0.5) / MASK_HEIGHT as f32);49
if person_at(x, y).is_some() { 1. } else { 0. }50
})51
.collect()52
}53
54
/// A drawn head-and-shoulders scene; the mask comes from the drawing, not from the model.55
pub fn self_view(tick: usize, blur: bool) -> VideoPicture {56
let mut rgba = scene(tick);57
if blur {58
compose(&mut rgba, SCENE_WIDTH, SCENE_HEIGHT, &person_mask());59
}60
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|pixel| [pixel[2], pixel[1], pixel[0], pixel[3]]).collect();61
VideoPicture { width: SCENE_WIDTH as u32, height: SCENE_HEIGHT as u32, bgra }62
}63
64
#[cfg(test)]65
mod tests {66
use super::*;67
68
fn roughness(picture: &VideoPicture, x: usize, y: usize) -> i32 {69
let at = |column: usize| i32::from(picture.bgra[(y * SCENE_WIDTH + column) * 4]);70
(0..12).map(|step| (at(x + step + 1) - at(x + step)).abs()).sum()71
}72
73
#[test]74
fn blurring_the_scene_smooths_the_stripes_and_keeps_the_person() {75
let sharp = self_view(0, false);76
let blurred = self_view(0, true);77
assert!(roughness(&blurred, 30, 20) * 3 < roughness(&sharp, 30, 20));78
let center = (SCENE_HEIGHT / 2 * SCENE_WIDTH + SCENE_WIDTH / 2) * 4;79
assert_eq!(blurred.bgra[center..center + 3], sharp.bgra[center..center + 3]);80
}81
}@@ -1,13 +1,17 @@
1
1
mod actions;
2
2
mod demo;
3
mod demo_scene;
3
4
mod launcher;
4
5
mod model;
5
6
mod pictures;
6
7
mod ring;
7
8
mod target;
8
9
9
pub use actions::load_share_sound;
10
pub use actions::{load_background_blur, load_share_sound};
10
11
pub use launcher::CallLauncher;
11
pub use model::{ActiveCall, CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size};
12
pub use model::{
13
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout,
14
tile_size,
15
};
12
16
pub use ring::{MissedCall, RingEntry, Rings};
13
17
pub use target::plan_for_chat;
@@ -1,13 +1,17 @@1
mod actions;1
mod actions;2
mod demo;2
mod demo;3
mod demo_scene;3
mod launcher;4
mod launcher;4
mod model;5
mod model;5
mod pictures;6
mod pictures;6
mod ring;7
mod ring;7
mod target;8
mod target;8
9
9
pub use actions::load_share_sound;10
pub use actions::{load_background_blur, load_share_sound};10
pub use launcher::CallLauncher;11
pub use launcher::CallLauncher;11
pub use model::{ActiveCall, CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size};12
pub use model::{13
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout,14
tile_size,15
};12
pub use ring::{MissedCall, RingEntry, Rings};16
pub use ring::{MissedCall, RingEntry, Rings};13
pub use target::plan_for_chat;17
pub use target::plan_for_chat;@@ -2,8 +2,8 @@ use std::sync::Arc;
2
2
use std::time::{Duration, Instant};
3
3
4
4
use calling::{
5
CallCommand, CallState, CallUpdate, CameraDevice, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, Reaction, RosterEntry,
6
ShareKind, ShareSource, SpeakingDetector, VideoHub,
5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, DeviceChoice, DeviceLists, EndKind, EndReason, Progress,
6
Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
7
7
};
8
8
use tokio::sync::mpsc::UnboundedSender;
9
9
@@ -18,6 +18,8 @@ const WIDE_TILES: usize = 2;
18
18
const MEDIUM_TILES: usize = 4;
19
19
pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
20
20
pub const CHAT_OPEN_TILES: usize = 6;
21
pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);
22
const CAPTION_LINES: usize = 2;
21
23
22
24
pub struct ActiveCall {
23
25
pub id: u64,
@@ -70,6 +72,7 @@ pub struct Tile {
70
72
pub invited: bool,
71
73
pub has_video: bool,
72
74
pub hand: Option<u64>,
75
pub spotlight: Option<u64>,
73
76
}
74
77
75
78
impl Tile {
@@ -83,10 +86,27 @@ impl Tile {
83
86
invited: true,
84
87
has_video: false,
85
88
hand: None,
89
spotlight: None,
86
90
}
87
91
}
88
92
}
89
93
94
#[derive(Debug, Clone, PartialEq, Eq)]
95
pub struct Focus {
96
pub mri: String,
97
pub own: bool,
98
pub spotlight: bool,
99
pub pinned: bool,
100
}
101
102
#[derive(Debug, Clone, PartialEq, Eq)]
103
pub struct CaptionLine {
104
pub id: String,
105
pub speaker: String,
106
pub text: String,
107
pub at: Instant,
108
}
109
90
110
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91
111
pub struct GridLayout {
92
112
pub shown_others: usize,
@@ -174,6 +194,12 @@ pub struct CallModel {
174
194
pub share_sources: Vec<ShareSource>,
175
195
pub share_sound: bool,
176
196
pub own_hand: Option<u64>,
197
pub own_spotlight: Option<u64>,
198
pub organizer: bool,
199
pub pinned: Option<String>,
200
pub captions: CaptionState,
201
pub caption_lines: Vec<CaptionLine>,
202
pub blur: bool,
177
203
pub reactions: Vec<ReactionChip>,
178
204
reaction_serial: u64,
179
205
pub meeting_chat: Option<String>,
@@ -211,6 +237,12 @@ impl CallModel {
211
237
share_sources: Vec::new(),
212
238
share_sound: false,
213
239
own_hand: None,
240
own_spotlight: None,
241
organizer: false,
242
pinned: None,
243
captions: CaptionState::Off,
244
caption_lines: Vec::new(),
245
blur: false,
214
246
reactions: Vec::new(),
215
247
reaction_serial: 0,
216
248
meeting_chat: None,
@@ -306,9 +338,39 @@ impl CallModel {
306
338
CallUpdate::ShareSound(active) => self.share_sound = active,
307
339
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),
308
340
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
341
CallUpdate::Captions(state) => {
342
if state != CaptionState::On {
343
self.caption_lines.clear();
344
}
345
self.captions = state;
346
}
347
CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),
348
CallUpdate::BlurTiming(_) | CallUpdate::Organizer { .. } => {}
309
349
}
310
350
}
311
351
352
pub fn note_caption(&mut self, entry: CaptionEntry, at: Instant) {
353
if self.captions == CaptionState::Off {
354
return;
355
}
356
let speaker = if entry.display_name.is_empty() { "Someone".to_owned() } else { entry.display_name };
357
let line = CaptionLine { id: entry.id, speaker, text: entry.text, at };
358
match self.caption_lines.last_mut() {
359
Some(last) if last.id == line.id => *last = line,
360
_ => self.caption_lines.push(line),
361
}
362
let surplus = self.caption_lines.len().saturating_sub(CAPTION_LINES);
363
self.caption_lines.drain(..surplus);
364
}
365
366
pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {
367
self.caption_lines.iter().filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN).collect()
368
}
369
370
pub fn captions_on(&self) -> bool {
371
matches!(self.captions, CaptionState::Starting | CaptionState::On)
372
}
373
312
374
fn silence(&mut self) {
313
375
self.local_speaking = false;
314
376
self.remote_speaking = false;
@@ -338,8 +400,48 @@ impl CallModel {
338
400
1 + raised.filter(|other| *other < rank).count()
339
401
}
340
402
403
pub fn can_manage(&self) -> bool {
404
self.can_end_meeting || self.organizer
405
}
406
407
pub fn organizes_meeting(&self) -> bool {
408
self.kind == CallKind::Meeting && self.can_manage()
409
}
410
341
411
pub fn can_lower_hands(&self) -> bool {
342
self.can_end_meeting
412
self.can_manage()
413
}
414
415
pub fn lobby_guests(&self) -> Vec<&Tile> {
416
self.tiles.iter().filter(|tile| tile.state == TileState::InLobby).collect()
417
}
418
419
pub fn can_admit(&self) -> bool {
420
self.can_manage() && self.is_live() && !self.lobby
421
}
422
423
pub fn is_pinned(&self, mri: &str) -> bool {
424
self.pinned.as_deref() == Some(mri)
425
}
426
427
pub fn toggle_pin(&mut self, mri: &str) {
428
self.pinned = if self.is_pinned(mri) { None } else { Some(mri.to_owned()) };
429
}
430
431
pub fn is_spotlighted(&self, mri: &str) -> bool {
432
self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()
433
|| self.tiles.iter().any(|tile| tile.mri == mri && tile.spotlight.is_some())
434
}
435
436
pub fn focus(&self) -> Option<Focus> {
437
let own = |mri: &str| self.own_mri.as_deref() == Some(mri);
438
let on_stage = |mri: &str| own(mri) || self.visible_tiles().iter().any(|tile| tile.mri == mri && tile.state == TileState::Present);
439
if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {
440
return Some(Focus { mri: pinned.to_owned(), own: own(pinned), spotlight: self.is_spotlighted(pinned), pinned: true });
441
}
442
let remote = self.tiles.iter().filter(|tile| tile.state == TileState::Present).filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
443
let (_, mri) = remote.chain(self.own_spotlight.zip(self.own_mri.as_deref())).min_by_key(|(rank, _)| *rank)?;
444
Some(Focus { mri: mri.to_owned(), own: own(mri), spotlight: true, pinned: false })
343
445
}
344
446
345
447
pub fn any_hand_raised(&self) -> bool {
@@ -353,10 +455,12 @@ impl CallModel {
353
455
}
354
456
355
457
fn apply_roster(&mut self, entries: &[RosterEntry]) {
356
self.own_hand = entries
357
.iter()
358
.find(|entry| Some(&entry.mri) == self.own_mri.as_ref())
359
.and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));
458
let own_entry = entries.iter().find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
459
self.own_hand = own_entry.and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));
460
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
461
if let Some(entry) = own_entry {
462
self.organizer = entry.organizer;
463
}
360
464
for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
361
465
let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
362
466
match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
@@ -365,6 +469,7 @@ impl CallModel {
365
469
tile.muted = entry.muted;
366
470
tile.has_video = entry.has_video;
367
471
tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
472
tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
368
473
if tile.name.is_empty() {
369
474
tile.name = entry.display_name.clone();
370
475
}
@@ -378,11 +483,15 @@ impl CallModel {
378
483
invited: false,
379
484
has_video: entry.has_video,
380
485
hand: entry.hand.as_ref().map(|hand| hand.rank),
486
spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
381
487
}),
382
488
}
383
489
}
384
490
let own_mri = self.own_mri.clone();
385
491
let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
492
if self.pinned.as_deref().is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref()) {
493
self.pinned = None;
494
}
386
495
self.tiles.retain_mut(|tile| {
387
496
if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
388
497
return true;
@@ -406,14 +515,14 @@ impl CallModel {
406
515
TileState::Invited => 1,
407
516
_ => 2,
408
517
};
409
(tile.hand.is_none(), tile.hand.unwrap_or(0), state)
518
(!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), state)
410
519
});
411
520
tiles
412
521
}
413
522
414
523
pub fn strip_tiles(&self) -> Vec<&Tile> {
415
524
let mut tiles = self.visible_tiles();
416
tiles.sort_by_key(|tile| (tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));
525
tiles.sort_by_key(|tile| (!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));
417
526
tiles
418
527
}
419
528
@@ -565,9 +674,22 @@ mod tests {
565
674
has_video: false,
566
675
sharing: false,
567
676
hand: None,
677
spotlight: None,
678
organizer: false,
568
679
}
569
680
}
570
681
682
fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {
683
RosterEntry {
684
spotlight: Some(calling::Spotlight { state_id: format!("sp-{rank}"), rank }),
685
..entry(mri, name, false, false)
686
}
687
}
688
689
fn organizer_entry(mri: &str) -> RosterEntry {
690
RosterEntry { organizer: true, ..entry(mri, "Me", false, false) }
691
}
692
571
693
fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
572
694
RosterEntry {
573
695
hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),
@@ -889,4 +1011,89 @@ mod tests {
889
1011
model.apply(CallUpdate::LocalShare(None));
890
1012
assert!(!model.share_sound);
891
1013
}
1014
1015
#[test]
1016
fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1017
let mut model = meeting_with_me();
1018
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1019
model.apply(CallUpdate::Roster(vec![
1020
entry("8:orgid:a", "Ana", false, false),
1021
entry("8:orgid:g1", "Gast Eins", false, true),
1022
entry("8:orgid:g2", "Gast Zwei", false, true),
1023
]));
1024
let waiting: Vec<&str> = model.lobby_guests().iter().map(|tile| tile.name.as_str()).collect();
1025
assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);
1026
assert!(!model.can_admit());
1027
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me"), entry("8:orgid:g1", "Gast Eins", false, true)]));
1028
assert!(model.organizer && model.can_admit() && model.organizes_meeting());
1029
let mut owner = CallModel::meeting("Standup", true);
1030
owner.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1031
assert!(owner.can_admit());
1032
owner.apply(CallUpdate::Lobby(true));
1033
assert!(!owner.can_admit());
1034
}
1035
1036
#[test]
1037
fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {
1038
let mut model = meeting_with_me();
1039
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), spotlit("8:orgid:c", "Cy", 2)]));
1040
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:c".into(), own: false, spotlight: true, pinned: false }));
1041
assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));
1042
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), entry("8:orgid:c", "Cy", false, false)]));
1043
assert_eq!(model.focus().map(|focus| focus.mri), Some("8:orgid:b".to_owned()));
1044
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1045
assert_eq!(model.focus(), None);
1046
}
1047
1048
#[test]
1049
fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {
1050
let mut model = meeting_with_me();
1051
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:me", "Me", 1)]));
1052
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:me".into(), own: true, spotlight: true, pinned: false }));
1053
}
1054
1055
#[test]
1056
fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {
1057
let mut model = meeting_with_me();
1058
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1059
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 1)]));
1060
model.toggle_pin("8:orgid:a");
1061
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:a".into(), own: false, spotlight: false, pinned: true }));
1062
let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1063
assert_eq!(names[0], "Ana");
1064
model.toggle_pin("8:orgid:b");
1065
assert_eq!(model.focus().map(|focus| (focus.mri, focus.spotlight, focus.pinned)), Some(("8:orgid:b".to_owned(), true, true)));
1066
model.toggle_pin("8:orgid:b");
1067
assert_eq!(model.pinned, None);
1068
model.toggle_pin("8:orgid:a");
1069
model.apply(CallUpdate::Roster(vec![spotlit("8:orgid:b", "Bo", 1)]));
1070
assert_eq!(model.pinned, None);
1071
}
1072
1073
fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {
1074
CaptionEntry { id: id.into(), user_id: "u".into(), display_name: speaker.into(), text: text.into(), is_final }
1075
}
1076
1077
#[test]
1078
fn captions_keep_two_lines_update_partials_and_fade_after_four_seconds() {
1079
let mut model = meeting_with_me();
1080
let start = Instant::now();
1081
model.note_caption(caption("1", "Ana", "ignored while off", false), start);
1082
assert!(model.caption_lines.is_empty());
1083
model.apply(CallUpdate::Captions(CaptionState::On));
1084
model.note_caption(caption("1", "Ana", "Hello", false), start);
1085
model.note_caption(caption("1", "Ana", "Hello there", true), start);
1086
assert_eq!(model.caption_lines.len(), 1);
1087
assert_eq!(model.caption_lines[0].text, "Hello there");
1088
model.note_caption(caption("2", "", "Next", false), start + Duration::from_secs(1));
1089
model.note_caption(caption("3", "Bo", "Third", false), start + Duration::from_secs(2));
1090
let texts: Vec<&str> = model.caption_lines.iter().map(|line| line.text.as_str()).collect();
1091
assert_eq!(texts, vec!["Next", "Third"]);
1092
assert_eq!(model.caption_lines[0].speaker, "Someone");
1093
assert_eq!(model.visible_captions(start + Duration::from_secs(3)).len(), 2);
1094
assert_eq!(model.visible_captions(start + Duration::from_millis(5500)).len(), 1);
1095
assert!(model.visible_captions(start + Duration::from_secs(7)).is_empty());
1096
model.apply(CallUpdate::Captions(CaptionState::Off));
1097
assert!(model.caption_lines.is_empty() && !model.captions_on());
1098
}
892
1099
}
@@ -2,8 +2,8 @@ use std::sync::Arc;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use calling::{4
use calling::{5
CallCommand, CallState, CallUpdate, CameraDevice, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, Reaction, RosterEntry,5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, DeviceChoice, DeviceLists, EndKind, EndReason, Progress,6
ShareKind, ShareSource, SpeakingDetector, VideoHub,6
Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,7
};7
};8
use tokio::sync::mpsc::UnboundedSender;8
use tokio::sync::mpsc::UnboundedSender;9
9
@@ -18,6 +18,8 @@ const WIDE_TILES: usize = 2;18
const MEDIUM_TILES: usize = 4;18
const MEDIUM_TILES: usize = 4;19
pub const REACTION_SHOWN: Duration = Duration::from_secs(3);19
pub const REACTION_SHOWN: Duration = Duration::from_secs(3);20
pub const CHAT_OPEN_TILES: usize = 6;20
pub const CHAT_OPEN_TILES: usize = 6;21
pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);22
const CAPTION_LINES: usize = 2;21
23
22
pub struct ActiveCall {24
pub struct ActiveCall {23
pub id: u64,25
pub id: u64,@@ -70,6 +72,7 @@ pub struct Tile {70
pub invited: bool,72
pub invited: bool,71
pub has_video: bool,73
pub has_video: bool,72
pub hand: Option<u64>,74
pub hand: Option<u64>,75
pub spotlight: Option<u64>,73
}76
}74
77
75
impl Tile {78
impl Tile {@@ -83,10 +86,27 @@ impl Tile {83
invited: true,86
invited: true,84
has_video: false,87
has_video: false,85
hand: None,88
hand: None,89
spotlight: None,86
}90
}87
}91
}88
}92
}89
93
94
#[derive(Debug, Clone, PartialEq, Eq)]95
pub struct Focus {96
pub mri: String,97
pub own: bool,98
pub spotlight: bool,99
pub pinned: bool,100
}101
102
#[derive(Debug, Clone, PartialEq, Eq)]103
pub struct CaptionLine {104
pub id: String,105
pub speaker: String,106
pub text: String,107
pub at: Instant,108
}109
90
#[derive(Debug, Clone, Copy, PartialEq, Eq)]110
#[derive(Debug, Clone, Copy, PartialEq, Eq)]91
pub struct GridLayout {111
pub struct GridLayout {92
pub shown_others: usize,112
pub shown_others: usize,@@ -174,6 +194,12 @@ pub struct CallModel {174
pub share_sources: Vec<ShareSource>,194
pub share_sources: Vec<ShareSource>,175
pub share_sound: bool,195
pub share_sound: bool,176
pub own_hand: Option<u64>,196
pub own_hand: Option<u64>,197
pub own_spotlight: Option<u64>,198
pub organizer: bool,199
pub pinned: Option<String>,200
pub captions: CaptionState,201
pub caption_lines: Vec<CaptionLine>,202
pub blur: bool,177
pub reactions: Vec<ReactionChip>,203
pub reactions: Vec<ReactionChip>,178
reaction_serial: u64,204
reaction_serial: u64,179
pub meeting_chat: Option<String>,205
pub meeting_chat: Option<String>,@@ -211,6 +237,12 @@ impl CallModel {211
share_sources: Vec::new(),237
share_sources: Vec::new(),212
share_sound: false,238
share_sound: false,213
own_hand: None,239
own_hand: None,240
own_spotlight: None,241
organizer: false,242
pinned: None,243
captions: CaptionState::Off,244
caption_lines: Vec::new(),245
blur: false,214
reactions: Vec::new(),246
reactions: Vec::new(),215
reaction_serial: 0,247
reaction_serial: 0,216
meeting_chat: None,248
meeting_chat: None,@@ -306,9 +338,39 @@ impl CallModel {306
CallUpdate::ShareSound(active) => self.share_sound = active,338
CallUpdate::ShareSound(active) => self.share_sound = active,307
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),339
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),308
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),340
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),341
CallUpdate::Captions(state) => {342
if state != CaptionState::On {343
self.caption_lines.clear();344
}345
self.captions = state;346
}347
CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),348
CallUpdate::BlurTiming(_) | CallUpdate::Organizer { .. } => {}309
}349
}310
}350
}311
351
352
pub fn note_caption(&mut self, entry: CaptionEntry, at: Instant) {353
if self.captions == CaptionState::Off {354
return;355
}356
let speaker = if entry.display_name.is_empty() { "Someone".to_owned() } else { entry.display_name };357
let line = CaptionLine { id: entry.id, speaker, text: entry.text, at };358
match self.caption_lines.last_mut() {359
Some(last) if last.id == line.id => *last = line,360
_ => self.caption_lines.push(line),361
}362
let surplus = self.caption_lines.len().saturating_sub(CAPTION_LINES);363
self.caption_lines.drain(..surplus);364
}365
366
pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {367
self.caption_lines.iter().filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN).collect()368
}369
370
pub fn captions_on(&self) -> bool {371
matches!(self.captions, CaptionState::Starting | CaptionState::On)372
}373
312
fn silence(&mut self) {374
fn silence(&mut self) {313
self.local_speaking = false;375
self.local_speaking = false;314
self.remote_speaking = false;376
self.remote_speaking = false;@@ -338,8 +400,48 @@ impl CallModel {338
1 + raised.filter(|other| *other < rank).count()400
1 + raised.filter(|other| *other < rank).count()339
}401
}340
402
403
pub fn can_manage(&self) -> bool {404
self.can_end_meeting || self.organizer405
}406
407
pub fn organizes_meeting(&self) -> bool {408
self.kind == CallKind::Meeting && self.can_manage()409
}410
341
pub fn can_lower_hands(&self) -> bool {411
pub fn can_lower_hands(&self) -> bool {342
self.can_end_meeting412
self.can_manage()413
}414
415
pub fn lobby_guests(&self) -> Vec<&Tile> {416
self.tiles.iter().filter(|tile| tile.state == TileState::InLobby).collect()417
}418
419
pub fn can_admit(&self) -> bool {420
self.can_manage() && self.is_live() && !self.lobby421
}422
423
pub fn is_pinned(&self, mri: &str) -> bool {424
self.pinned.as_deref() == Some(mri)425
}426
427
pub fn toggle_pin(&mut self, mri: &str) {428
self.pinned = if self.is_pinned(mri) { None } else { Some(mri.to_owned()) };429
}430
431
pub fn is_spotlighted(&self, mri: &str) -> bool {432
self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()433
|| self.tiles.iter().any(|tile| tile.mri == mri && tile.spotlight.is_some())434
}435
436
pub fn focus(&self) -> Option<Focus> {437
let own = |mri: &str| self.own_mri.as_deref() == Some(mri);438
let on_stage = |mri: &str| own(mri) || self.visible_tiles().iter().any(|tile| tile.mri == mri && tile.state == TileState::Present);439
if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {440
return Some(Focus { mri: pinned.to_owned(), own: own(pinned), spotlight: self.is_spotlighted(pinned), pinned: true });441
}442
let remote = self.tiles.iter().filter(|tile| tile.state == TileState::Present).filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));443
let (_, mri) = remote.chain(self.own_spotlight.zip(self.own_mri.as_deref())).min_by_key(|(rank, _)| *rank)?;444
Some(Focus { mri: mri.to_owned(), own: own(mri), spotlight: true, pinned: false })343
}445
}344
446
345
pub fn any_hand_raised(&self) -> bool {447
pub fn any_hand_raised(&self) -> bool {@@ -353,10 +455,12 @@ impl CallModel {353
}455
}354
456
355
fn apply_roster(&mut self, entries: &[RosterEntry]) {457
fn apply_roster(&mut self, entries: &[RosterEntry]) {356
self.own_hand = entries458
let own_entry = entries.iter().find(|entry| Some(&entry.mri) == self.own_mri.as_ref());357
.iter()459
self.own_hand = own_entry.and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));358
.find(|entry| Some(&entry.mri) == self.own_mri.as_ref())460
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));359
.and_then(|entry| entry.hand.as_ref().map(|hand| hand.rank));461
if let Some(entry) = own_entry {462
self.organizer = entry.organizer;463
}360
for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {464
for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {361
let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };465
let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };362
match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {466
match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {@@ -365,6 +469,7 @@ impl CallModel {365
tile.muted = entry.muted;469
tile.muted = entry.muted;366
tile.has_video = entry.has_video;470
tile.has_video = entry.has_video;367
tile.hand = entry.hand.as_ref().map(|hand| hand.rank);471
tile.hand = entry.hand.as_ref().map(|hand| hand.rank);472
tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);368
if tile.name.is_empty() {473
if tile.name.is_empty() {369
tile.name = entry.display_name.clone();474
tile.name = entry.display_name.clone();370
}475
}@@ -378,11 +483,15 @@ impl CallModel {378
invited: false,483
invited: false,379
has_video: entry.has_video,484
has_video: entry.has_video,380
hand: entry.hand.as_ref().map(|hand| hand.rank),485
hand: entry.hand.as_ref().map(|hand| hand.rank),486
spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),381
}),487
}),382
}488
}383
}489
}384
let own_mri = self.own_mri.clone();490
let own_mri = self.own_mri.clone();385
let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);491
let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);492
if self.pinned.as_deref().is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref()) {493
self.pinned = None;494
}386
self.tiles.retain_mut(|tile| {495
self.tiles.retain_mut(|tile| {387
if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {496
if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {388
return true;497
return true;@@ -406,14 +515,14 @@ impl CallModel {406
TileState::Invited => 1,515
TileState::Invited => 1,407
_ => 2,516
_ => 2,408
};517
};409
(tile.hand.is_none(), tile.hand.unwrap_or(0), state)518
(!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), state)410
});519
});411
tiles520
tiles412
}521
}413
522
414
pub fn strip_tiles(&self) -> Vec<&Tile> {523
pub fn strip_tiles(&self) -> Vec<&Tile> {415
let mut tiles = self.visible_tiles();524
let mut tiles = self.visible_tiles();416
tiles.sort_by_key(|tile| (tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));525
tiles.sort_by_key(|tile| (!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));417
tiles526
tiles418
}527
}419
528
@@ -565,9 +674,22 @@ mod tests {565
has_video: false,674
has_video: false,566
sharing: false,675
sharing: false,567
hand: None,676
hand: None,677
spotlight: None,678
organizer: false,568
}679
}569
}680
}570
681
682
fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {683
RosterEntry {684
spotlight: Some(calling::Spotlight { state_id: format!("sp-{rank}"), rank }),685
..entry(mri, name, false, false)686
}687
}688
689
fn organizer_entry(mri: &str) -> RosterEntry {690
RosterEntry { organizer: true, ..entry(mri, "Me", false, false) }691
}692
571
fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {693
fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {572
RosterEntry {694
RosterEntry {573
hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),695
hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),@@ -889,4 +1011,89 @@ mod tests {889
model.apply(CallUpdate::LocalShare(None));1011
model.apply(CallUpdate::LocalShare(None));890
assert!(!model.share_sound);1012
assert!(!model.share_sound);891
}1013
}1014
1015
#[test]1016
fn lobby_guests_are_listed_for_organizers_who_may_admit() {1017
let mut model = meeting_with_me();1018
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1019
model.apply(CallUpdate::Roster(vec![1020
entry("8:orgid:a", "Ana", false, false),1021
entry("8:orgid:g1", "Gast Eins", false, true),1022
entry("8:orgid:g2", "Gast Zwei", false, true),1023
]));1024
let waiting: Vec<&str> = model.lobby_guests().iter().map(|tile| tile.name.as_str()).collect();1025
assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);1026
assert!(!model.can_admit());1027
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me"), entry("8:orgid:g1", "Gast Eins", false, true)]));1028
assert!(model.organizer && model.can_admit() && model.organizes_meeting());1029
let mut owner = CallModel::meeting("Standup", true);1030
owner.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1031
assert!(owner.can_admit());1032
owner.apply(CallUpdate::Lobby(true));1033
assert!(!owner.can_admit());1034
}1035
1036
#[test]1037
fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {1038
let mut model = meeting_with_me();1039
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), spotlit("8:orgid:c", "Cy", 2)]));1040
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:c".into(), own: false, spotlight: true, pinned: false }));1041
assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));1042
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), entry("8:orgid:c", "Cy", false, false)]));1043
assert_eq!(model.focus().map(|focus| focus.mri), Some("8:orgid:b".to_owned()));1044
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));1045
assert_eq!(model.focus(), None);1046
}1047
1048
#[test]1049
fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {1050
let mut model = meeting_with_me();1051
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:me", "Me", 1)]));1052
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:me".into(), own: true, spotlight: true, pinned: false }));1053
}1054
1055
#[test]1056
fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {1057
let mut model = meeting_with_me();1058
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1059
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 1)]));1060
model.toggle_pin("8:orgid:a");1061
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:a".into(), own: false, spotlight: false, pinned: true }));1062
let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();1063
assert_eq!(names[0], "Ana");1064
model.toggle_pin("8:orgid:b");1065
assert_eq!(model.focus().map(|focus| (focus.mri, focus.spotlight, focus.pinned)), Some(("8:orgid:b".to_owned(), true, true)));1066
model.toggle_pin("8:orgid:b");1067
assert_eq!(model.pinned, None);1068
model.toggle_pin("8:orgid:a");1069
model.apply(CallUpdate::Roster(vec![spotlit("8:orgid:b", "Bo", 1)]));1070
assert_eq!(model.pinned, None);1071
}1072
1073
fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {1074
CaptionEntry { id: id.into(), user_id: "u".into(), display_name: speaker.into(), text: text.into(), is_final }1075
}1076
1077
#[test]1078
fn captions_keep_two_lines_update_partials_and_fade_after_four_seconds() {1079
let mut model = meeting_with_me();1080
let start = Instant::now();1081
model.note_caption(caption("1", "Ana", "ignored while off", false), start);1082
assert!(model.caption_lines.is_empty());1083
model.apply(CallUpdate::Captions(CaptionState::On));1084
model.note_caption(caption("1", "Ana", "Hello", false), start);1085
model.note_caption(caption("1", "Ana", "Hello there", true), start);1086
assert_eq!(model.caption_lines.len(), 1);1087
assert_eq!(model.caption_lines[0].text, "Hello there");1088
model.note_caption(caption("2", "", "Next", false), start + Duration::from_secs(1));1089
model.note_caption(caption("3", "Bo", "Third", false), start + Duration::from_secs(2));1090
let texts: Vec<&str> = model.caption_lines.iter().map(|line| line.text.as_str()).collect();1091
assert_eq!(texts, vec!["Next", "Third"]);1092
assert_eq!(model.caption_lines[0].speaker, "Someone");1093
assert_eq!(model.visible_captions(start + Duration::from_secs(3)).len(), 2);1094
assert_eq!(model.visible_captions(start + Duration::from_millis(5500)).len(), 1);1095
assert!(model.visible_captions(start + Duration::from_secs(7)).is_empty());1096
model.apply(CallUpdate::Captions(CaptionState::Off));1097
assert!(model.caption_lines.is_empty() && !model.captions_on());1098
}892
}1099
}@@ -0,0 +1,468 @@
1
use std::sync::Arc;
2
use std::time::Instant;
3
4
use calling::{CaptionState, VideoKey};
5
use gpui_kit::assets::IconName;
6
use gpui_kit::component::button::{Button, ButtonVariants as _};
7
use gpui_kit::component::dialog::DialogFooter;
8
use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
9
use gpui_kit::component::popover::Popover;
10
use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};
11
use gpui_kit::prelude::FluentBuilder as _;
12
use gpui_kit::*;
13
14
use super::avatar::person_avatar;
15
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
16
use super::widgets::icon;
17
use crate::app_state::AppState;
18
use crate::call::{CAPTION_SHOWN, CallModel, Focus};
19
use crate::notice::truncated;
20
use crate::theme;
21
22
const BANNER_TEXT: f32 = 13.;
23
const PILL_HEIGHT: f32 = 26.;
24
const LOBBY_LIST_WIDTH: f32 = 340.;
25
const LOBBY_NAME_LIMIT: usize = 28;
26
const CAPTION_WIDTH: f32 = 720.;
27
const CAPTION_BOTTOM: f32 = 2. * 18. + CONTROL_SIZE + 1. + 16.;
28
const CAPTION_FADE_SECONDS: f32 = 1.;
29
const CAPTION_BACKGROUND: f32 = 0.72;
30
const FOCUS_RADIUS: f32 = 12.;
31
const FOCUS_AVATAR: f32 = 140.;
32
const CHIP_HEIGHT: f32 = 24.;
33
const MORE_SIZE: f32 = 28.;
34
const SMALL_CONTROL: f32 = 28.;
35
const NAME_LIMIT: usize = 32;
36
37
fn dark_text() -> Hsla {
38
hsla(0., 0., 0.08, 1.)
39
}
40
41
fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {
42
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (transparent_black(), dark_text()) };
43
div()
44
.id(id)
45
.h(px(PILL_HEIGHT))
46
.px(px(12.))
47
.flex()
48
.flex_none()
49
.items_center()
50
.rounded_full()
51
.border_1()
52
.border_color(dark_text())
53
.bg(background)
54
.text_color(foreground)
55
.text_size(px(BANNER_TEXT))
56
.font_weight(FontWeight::SEMIBOLD)
57
.cursor_pointer()
58
.hover(|button| button.opacity(0.85))
59
.child(label)
60
}
61
62
pub fn lobby_text(waiting: usize) -> String {
63
match waiting {
64
1 => "1 person is waiting in the lobby".to_owned(),
65
count => format!("{count} people are waiting in the lobby"),
66
}
67
}
68
69
fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {
70
v_flex().w(px(LOBBY_LIST_WIDTH)).gap(px(6.)).children(guests.iter().map(|(mri, name)| {
71
let (admit_app, deny_app) = (app.clone(), app.clone());
72
let (admit_mri, deny_mri) = (mri.clone(), mri.clone());
73
h_flex()
74
.w_full()
75
.gap(px(8.))
76
.items_center()
77
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(truncated(name, LOBBY_NAME_LIMIT)))
78
.child(
79
Button::new(SharedString::from(format!("lobby-admit-{mri}")))
80
.label("Admit")
81
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))),
82
)
83
.child(
84
Button::new(SharedString::from(format!("lobby-deny-{mri}")))
85
.label("Deny")
86
.ghost()
87
.on_click(move |_, _, cx| deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))),
88
)
89
}))
90
}
91
92
pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
93
if !model.can_admit() {
94
return None;
95
}
96
let guests: Vec<(String, String)> = model.lobby_guests().into_iter().map(|tile| (tile.mri.clone(), tile.name.clone())).collect();
97
if guests.is_empty() {
98
return None;
99
}
100
let list_app = app.clone();
101
let admit_app = app.clone();
102
Some(
103
h_flex()
104
.id("call-lobby-banner")
105
.w_full()
106
.h(px(BANNER_HEIGHT))
107
.flex_none()
108
.px(px(20.))
109
.gap(px(12.))
110
.items_center()
111
.justify_center()
112
.bg(theme::amber())
113
.text_color(dark_text())
114
.text_size(px(BANNER_TEXT))
115
.font_weight(FontWeight::SEMIBOLD)
116
.child(lobby_text(guests.len()))
117
.child(
118
Popover::new("call-lobby-popover")
119
.anchor(Anchor::TopLeft)
120
.offset(px(8.))
121
.trigger(Button::new("call-lobby-view").ghost().p_0().h(px(PILL_HEIGHT)).rounded_full().child(pill("call-lobby-view-face", "View", false)))
122
.content(move |_, _, _| lobby_list(&list_app, &guests)),
123
)
124
.child(
125
pill("call-lobby-admit-all", "Admit all", true)
126
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_all_call_guests(cx))),
127
)
128
.into_any_element(),
129
)
130
}
131
132
fn confirm_remove(app: &Entity<AppState>, mri: &str, name: &str, window: &mut Window, cx: &mut App) {
133
let app = app.clone();
134
let mri = mri.to_owned();
135
let heading = format!("Remove {} from the meeting?", truncated(name, NAME_LIMIT));
136
window.open_alert_dialog(cx, move |alert, _, _| {
137
let app = app.clone();
138
let mri = mri.clone();
139
let cancel = Button::new("remove-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));
140
let remove = Button::new("remove-confirm").label("Remove").danger().on_click(move |_, window, cx| {
141
app.update(cx, |state, cx| state.remove_call_participant(mri.clone(), cx));
142
window.close_dialog(cx);
143
});
144
alert
145
.title(heading.clone())
146
.description("They leave the call and can only come back if they join again.")
147
.footer(DialogFooter::new().child(cancel).child(remove))
148
.on_ok(|_, _, _| false)
149
});
150
}
151
152
pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> PopupMenu {
153
let pinned = model.is_pinned(mri);
154
let spotlighted = model.is_spotlighted(mri);
155
let organizes = model.organizes_meeting();
156
let raised = !own && model.tiles.iter().any(|tile| tile.mri == mri && tile.hand.is_some());
157
let muted = model.tiles.iter().any(|tile| tile.mri == mri && tile.muted);
158
let mut popup = popup.min_w(px(MENU_WIDTH));
159
let pin_app = app.clone();
160
let pin_mri = mri.to_owned();
161
popup = popup.item(
162
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin for me" })
163
.icon(IconName::Frame)
164
.on_click(move |_, _, cx| pin_app.update(cx, |state, cx| state.toggle_call_pin(&pin_mri, cx))),
165
);
166
if organizes {
167
let (spotlight_app, spotlight_mri) = (app.clone(), mri.to_owned());
168
popup = popup.item(
169
PopupMenuItem::new(if spotlighted { "Stop spotlight" } else { "Spotlight for everyone" })
170
.icon(IconName::Star)
171
.on_click(move |_, _, cx| spotlight_app.update(cx, |state, cx| state.toggle_call_spotlight(spotlight_mri.clone(), cx))),
172
);
173
}
174
if organizes && !own {
175
let (mute_app, mute_mri) = (app.clone(), mri.to_owned());
176
popup = popup.item(
177
PopupMenuItem::new("Mute")
178
.icon(IconName::MicOff)
179
.disabled(muted)
180
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_call_participant(mute_mri.clone(), cx))),
181
);
182
}
183
if organizes && raised {
184
let (hand_app, hand_mri) = (app.clone(), mri.to_owned());
185
popup = popup.item(
186
PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| hand_app.update(cx, |state, cx| state.lower_call_hand(hand_mri.clone(), cx))),
187
);
188
}
189
if organizes && !own {
190
let (remove_app, remove_mri, remove_name) = (app.clone(), mri.to_owned(), name.to_owned());
191
popup = popup.separator().item(
192
PopupMenuItem::new("Remove from meeting...")
193
.icon(IconName::Close)
194
.on_click(move |_, window, cx| confirm_remove(&remove_app, &remove_mri, &remove_name, window, cx)),
195
);
196
}
197
popup
198
}
199
200
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {
201
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());
202
div().absolute().top(px(10.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(
203
Button::new(SharedString::from(format!("call-tile-more-{mri}")))
204
.icon(IconName::Ellipsis)
205
.ghost()
206
.xsmall()
207
.size(px(MORE_SIZE))
208
.rounded_full()
209
.bg(black().opacity(0.55))
210
.text_color(theme::white())
211
.tooltip("More")
212
.dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| tile_menu(popup, &app, &model, &mri_owned, &name, own)),
213
)
214
}
215
216
/// Adds the right-click menu and a "..." button that shows while the pointer is over the tile.
217
pub fn attach_tile_menu(tile: Stateful<Div>, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> AnyElement {
218
let group = SharedString::from(format!("call-tile-group-{mri}"));
219
let (context_app, context_model, context_mri, context_name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());
220
tile.group(group.clone())
221
.relative()
222
.child(more_overlay(app, model, mri, name, own, group))
223
.context_menu(move |popup, _, _| tile_menu(popup, &context_app, &context_model, &context_mri, &context_name, own))
224
.into_any_element()
225
}
226
227
pub fn with_tile_menu(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, tile: AnyElement) -> AnyElement {
228
let wrapper = div().id(SharedString::from(format!("call-tile-{mri}"))).flex_none().child(tile);
229
attach_tile_menu(wrapper, app, model, mri, name, own)
230
}
231
232
pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
233
let in_meeting = model.kind == crate::call::CallKind::Meeting;
234
if !in_meeting {
235
return None;
236
}
237
let (mute_app, captions_app) = (app.clone(), app.clone());
238
let organizes = model.organizes_meeting();
239
let captions_on = model.captions_on();
240
Some(
241
Button::new("call-more")
242
.ghost()
243
.p_0()
244
.size(px(CONTROL_SIZE))
245
.rounded_full()
246
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))
247
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
248
let (mute_app, captions_app) = (mute_app.clone(), captions_app.clone());
249
let mut popup = popup.min_w(px(MENU_WIDTH));
250
if organizes {
251
popup = popup.item(
252
PopupMenuItem::new("Mute all")
253
.icon(IconName::MicOff)
254
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
255
);
256
}
257
popup.item(
258
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })
259
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })
260
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),
261
)
262
})
263
.into_any_element(),
264
)
265
}
266
267
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
268
if !model.can_use_camera() {
269
return None;
270
}
271
let app = app.clone();
272
let model = model.clone();
273
Some(
274
Button::new("call-camera-menu")
275
.ghost()
276
.p_0()
277
.size(px(SMALL_CONTROL))
278
.rounded_full()
279
.child(
280
div()
281
.id("call-camera-menu-face")
282
.size(px(SMALL_CONTROL))
283
.flex()
284
.items_center()
285
.justify_center()
286
.rounded_full()
287
.bg(theme::surface_raised())
288
.child(icon(IconName::ChevronUp, 16., theme::text())),
289
)
290
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model))
291
.into_any_element(),
292
)
293
}
294
295
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
296
let camera_app = app.clone();
297
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {
298
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));
299
});
300
let mut popup = popup.min_w(px(MENU_WIDTH)).item(PopupMenuItem::label("Camera"));
301
for item in cameras {
302
popup = popup.item(item);
303
}
304
let (none_app, blur_app) = (app.clone(), app.clone());
305
popup
306
.separator()
307
.item(PopupMenuItem::new("Background: None").checked(!model.blur).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background_blur(false, cx))))
308
.item(PopupMenuItem::new("Background: Blur").checked(model.blur).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background_blur(true, cx))))
309
}
310
311
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
312
let lines = model.visible_captions(now);
313
if lines.is_empty() {
314
return None;
315
}
316
let shown = CAPTION_SHOWN.as_secs_f32();
317
Some(
318
div()
319
.id("call-captions")
320
.absolute()
321
.left_0()
322
.right_0()
323
.bottom(px(CAPTION_BOTTOM))
324
.flex()
325
.justify_center()
326
.px(px(24.))
327
.child(
328
v_flex()
329
.w(px(CAPTION_WIDTH))
330
.max_w_full()
331
.gap(px(4.))
332
.px(px(16.))
333
.py(px(10.))
334
.rounded(px(10.))
335
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))
336
.text_color(theme::white())
337
.text_size(px(16.))
338
.children(lines.into_iter().map(|line| {
339
let age = now.saturating_duration_since(line.at).as_secs_f32();
340
let fade = ((shown - age) / CAPTION_FADE_SECONDS).clamp(0., 1.);
341
h_flex()
342
.opacity(fade)
343
.gap(px(8.))
344
.items_start()
345
.child(div().flex_none().font_weight(FontWeight::BOLD).child(format!("{}:", line.speaker)))
346
.child(div().flex_1().min_w_0().child(line.text.clone()))
347
})),
348
)
349
.into_any_element(),
350
)
351
}
352
353
fn focus_chip(label: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Div {
354
h_flex()
355
.h(px(CHIP_HEIGHT))
356
.px(px(8.))
357
.gap(px(4.))
358
.items_center()
359
.rounded_full()
360
.bg(background)
361
.text_color(foreground)
362
.text_size(px(12.))
363
.font_weight(FontWeight::SEMIBOLD)
364
.child(icon(glyph, 13., foreground))
365
.child(label)
366
}
367
368
pub fn spotlight_chip() -> Div {
369
focus_chip("Spotlight", IconName::Star, theme::amber(), dark_text())
370
}
371
372
pub fn pin_chip() -> Div {
373
focus_chip("Pinned", IconName::Frame, hsla(0., 0., 0., 0.6), theme::white())
374
}
375
376
pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focus, now: Instant) -> Option<AnyElement> {
377
let call = state.call.as_ref()?;
378
let model = &call.model;
379
let me = state.directory.me.as_ref();
380
let (name, user_id, speaking, muted, key) = if focus.own {
381
("You".to_owned(), me.map(|person| person.user_id.clone()), model.local_speaking, model.muted, VideoKey::LocalCamera)
382
} else {
383
let tile = model.tiles.iter().find(|tile| tile.mri == focus.mri)?;
384
(tile.name.clone(), tile.user_id.clone(), model.tile_speaking(tile), tile.muted, VideoKey::Person(tile.mri.clone()))
385
};
386
let image: Option<Arc<RenderImage>> = call.pictures.live(&key, now);
387
let picture = match image {
388
Some(image) => img(ImageSource::Render(image)).size_full().object_fit(ObjectFit::Contain).into_any_element(),
389
None => div()
390
.size_full()
391
.flex()
392
.items_center()
393
.justify_center()
394
.child(person_avatar(&state.directory, user_id.as_deref(), &name, FOCUS_AVATAR))
395
.into_any_element(),
396
};
397
let stage = div()
398
.id("call-focus-stage")
399
.relative()
400
.flex_1()
401
.min_w_0()
402
.h_full()
403
.overflow_hidden()
404
.rounded(px(FOCUS_RADIUS))
405
.bg(hsla(0., 0., 0.04, 1.))
406
.border_2()
407
.border_color(if speaking { theme::green() } else { transparent_black() })
408
.child(picture)
409
.child(
410
h_flex()
411
.absolute()
412
.top(px(14.))
413
.left(px(14.))
414
.gap(px(6.))
415
.when(focus.spotlight, |chips| chips.child(spotlight_chip()))
416
.when(focus.pinned, |chips| chips.child(pin_chip())),
417
)
418
.child(
419
h_flex()
420
.absolute()
421
.left(px(14.))
422
.bottom(px(14.))
423
.gap(px(8.))
424
.px(px(10.))
425
.py(px(4.))
426
.rounded(px(6.))
427
.bg(hsla(0., 0., 0., 0.6))
428
.text_color(theme::white())
429
.text_size(px(13.))
430
.font_weight(FontWeight::SEMIBOLD)
431
.child(name.clone())
432
.when(muted, |plate| plate.child(icon(IconName::MicOff, 14., theme::red()))),
433
);
434
Some(attach_tile_menu(stage, app, model, &focus.mri, &name, focus.own))
435
}
436
437
pub fn captions_state_hint(model: &CallModel) -> Option<&'static str> {
438
match model.captions {
439
CaptionState::Starting => Some("Starting live captions..."),
440
CaptionState::Failed(_) => Some("Live captions could not start"),
441
CaptionState::On | CaptionState::Off => None,
442
}
443
}
444
445
pub fn captions_hint_chip(model: &CallModel) -> Option<AnyElement> {
446
let text = captions_state_hint(model)?;
447
Some(
448
div()
449
.id("call-captions-hint")
450
.absolute()
451
.left_0()
452
.right_0()
453
.bottom(px(CAPTION_BOTTOM))
454
.flex()
455
.justify_center()
456
.child(
457
div()
458
.px(px(14.))
459
.py(px(6.))
460
.rounded_full()
461
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))
462
.text_color(theme::white())
463
.text_size(px(13.))
464
.child(text),
465
)
466
.into_any_element(),
467
)
468
}
@@ -0,0 +1,468 @@1
use std::sync::Arc;2
use std::time::Instant;3
4
use calling::{CaptionState, VideoKey};5
use gpui_kit::assets::IconName;6
use gpui_kit::component::button::{Button, ButtonVariants as _};7
use gpui_kit::component::dialog::DialogFooter;8
use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};9
use gpui_kit::component::popover::Popover;10
use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};11
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;13
14
use super::avatar::person_avatar;15
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};16
use super::widgets::icon;17
use crate::app_state::AppState;18
use crate::call::{CAPTION_SHOWN, CallModel, Focus};19
use crate::notice::truncated;20
use crate::theme;21
22
const BANNER_TEXT: f32 = 13.;23
const PILL_HEIGHT: f32 = 26.;24
const LOBBY_LIST_WIDTH: f32 = 340.;25
const LOBBY_NAME_LIMIT: usize = 28;26
const CAPTION_WIDTH: f32 = 720.;27
const CAPTION_BOTTOM: f32 = 2. * 18. + CONTROL_SIZE + 1. + 16.;28
const CAPTION_FADE_SECONDS: f32 = 1.;29
const CAPTION_BACKGROUND: f32 = 0.72;30
const FOCUS_RADIUS: f32 = 12.;31
const FOCUS_AVATAR: f32 = 140.;32
const CHIP_HEIGHT: f32 = 24.;33
const MORE_SIZE: f32 = 28.;34
const SMALL_CONTROL: f32 = 28.;35
const NAME_LIMIT: usize = 32;36
37
fn dark_text() -> Hsla {38
hsla(0., 0., 0.08, 1.)39
}40
41
fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {42
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (transparent_black(), dark_text()) };43
div()44
.id(id)45
.h(px(PILL_HEIGHT))46
.px(px(12.))47
.flex()48
.flex_none()49
.items_center()50
.rounded_full()51
.border_1()52
.border_color(dark_text())53
.bg(background)54
.text_color(foreground)55
.text_size(px(BANNER_TEXT))56
.font_weight(FontWeight::SEMIBOLD)57
.cursor_pointer()58
.hover(|button| button.opacity(0.85))59
.child(label)60
}61
62
pub fn lobby_text(waiting: usize) -> String {63
match waiting {64
1 => "1 person is waiting in the lobby".to_owned(),65
count => format!("{count} people are waiting in the lobby"),66
}67
}68
69
fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {70
v_flex().w(px(LOBBY_LIST_WIDTH)).gap(px(6.)).children(guests.iter().map(|(mri, name)| {71
let (admit_app, deny_app) = (app.clone(), app.clone());72
let (admit_mri, deny_mri) = (mri.clone(), mri.clone());73
h_flex()74
.w_full()75
.gap(px(8.))76
.items_center()77
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(truncated(name, LOBBY_NAME_LIMIT)))78
.child(79
Button::new(SharedString::from(format!("lobby-admit-{mri}")))80
.label("Admit")81
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))),82
)83
.child(84
Button::new(SharedString::from(format!("lobby-deny-{mri}")))85
.label("Deny")86
.ghost()87
.on_click(move |_, _, cx| deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))),88
)89
}))90
}91
92
pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {93
if !model.can_admit() {94
return None;95
}96
let guests: Vec<(String, String)> = model.lobby_guests().into_iter().map(|tile| (tile.mri.clone(), tile.name.clone())).collect();97
if guests.is_empty() {98
return None;99
}100
let list_app = app.clone();101
let admit_app = app.clone();102
Some(103
h_flex()104
.id("call-lobby-banner")105
.w_full()106
.h(px(BANNER_HEIGHT))107
.flex_none()108
.px(px(20.))109
.gap(px(12.))110
.items_center()111
.justify_center()112
.bg(theme::amber())113
.text_color(dark_text())114
.text_size(px(BANNER_TEXT))115
.font_weight(FontWeight::SEMIBOLD)116
.child(lobby_text(guests.len()))117
.child(118
Popover::new("call-lobby-popover")119
.anchor(Anchor::TopLeft)120
.offset(px(8.))121
.trigger(Button::new("call-lobby-view").ghost().p_0().h(px(PILL_HEIGHT)).rounded_full().child(pill("call-lobby-view-face", "View", false)))122
.content(move |_, _, _| lobby_list(&list_app, &guests)),123
)124
.child(125
pill("call-lobby-admit-all", "Admit all", true)126
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_all_call_guests(cx))),127
)128
.into_any_element(),129
)130
}131
132
fn confirm_remove(app: &Entity<AppState>, mri: &str, name: &str, window: &mut Window, cx: &mut App) {133
let app = app.clone();134
let mri = mri.to_owned();135
let heading = format!("Remove {} from the meeting?", truncated(name, NAME_LIMIT));136
window.open_alert_dialog(cx, move |alert, _, _| {137
let app = app.clone();138
let mri = mri.clone();139
let cancel = Button::new("remove-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));140
let remove = Button::new("remove-confirm").label("Remove").danger().on_click(move |_, window, cx| {141
app.update(cx, |state, cx| state.remove_call_participant(mri.clone(), cx));142
window.close_dialog(cx);143
});144
alert145
.title(heading.clone())146
.description("They leave the call and can only come back if they join again.")147
.footer(DialogFooter::new().child(cancel).child(remove))148
.on_ok(|_, _, _| false)149
});150
}151
152
pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> PopupMenu {153
let pinned = model.is_pinned(mri);154
let spotlighted = model.is_spotlighted(mri);155
let organizes = model.organizes_meeting();156
let raised = !own && model.tiles.iter().any(|tile| tile.mri == mri && tile.hand.is_some());157
let muted = model.tiles.iter().any(|tile| tile.mri == mri && tile.muted);158
let mut popup = popup.min_w(px(MENU_WIDTH));159
let pin_app = app.clone();160
let pin_mri = mri.to_owned();161
popup = popup.item(162
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin for me" })163
.icon(IconName::Frame)164
.on_click(move |_, _, cx| pin_app.update(cx, |state, cx| state.toggle_call_pin(&pin_mri, cx))),165
);166
if organizes {167
let (spotlight_app, spotlight_mri) = (app.clone(), mri.to_owned());168
popup = popup.item(169
PopupMenuItem::new(if spotlighted { "Stop spotlight" } else { "Spotlight for everyone" })170
.icon(IconName::Star)171
.on_click(move |_, _, cx| spotlight_app.update(cx, |state, cx| state.toggle_call_spotlight(spotlight_mri.clone(), cx))),172
);173
}174
if organizes && !own {175
let (mute_app, mute_mri) = (app.clone(), mri.to_owned());176
popup = popup.item(177
PopupMenuItem::new("Mute")178
.icon(IconName::MicOff)179
.disabled(muted)180
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_call_participant(mute_mri.clone(), cx))),181
);182
}183
if organizes && raised {184
let (hand_app, hand_mri) = (app.clone(), mri.to_owned());185
popup = popup.item(186
PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| hand_app.update(cx, |state, cx| state.lower_call_hand(hand_mri.clone(), cx))),187
);188
}189
if organizes && !own {190
let (remove_app, remove_mri, remove_name) = (app.clone(), mri.to_owned(), name.to_owned());191
popup = popup.separator().item(192
PopupMenuItem::new("Remove from meeting...")193
.icon(IconName::Close)194
.on_click(move |_, window, cx| confirm_remove(&remove_app, &remove_mri, &remove_name, window, cx)),195
);196
}197
popup198
}199
200
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {201
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());202
div().absolute().top(px(10.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(203
Button::new(SharedString::from(format!("call-tile-more-{mri}")))204
.icon(IconName::Ellipsis)205
.ghost()206
.xsmall()207
.size(px(MORE_SIZE))208
.rounded_full()209
.bg(black().opacity(0.55))210
.text_color(theme::white())211
.tooltip("More")212
.dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| tile_menu(popup, &app, &model, &mri_owned, &name, own)),213
)214
}215
216
/// Adds the right-click menu and a "..." button that shows while the pointer is over the tile.217
pub fn attach_tile_menu(tile: Stateful<Div>, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> AnyElement {218
let group = SharedString::from(format!("call-tile-group-{mri}"));219
let (context_app, context_model, context_mri, context_name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());220
tile.group(group.clone())221
.relative()222
.child(more_overlay(app, model, mri, name, own, group))223
.context_menu(move |popup, _, _| tile_menu(popup, &context_app, &context_model, &context_mri, &context_name, own))224
.into_any_element()225
}226
227
pub fn with_tile_menu(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, tile: AnyElement) -> AnyElement {228
let wrapper = div().id(SharedString::from(format!("call-tile-{mri}"))).flex_none().child(tile);229
attach_tile_menu(wrapper, app, model, mri, name, own)230
}231
232
pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {233
let in_meeting = model.kind == crate::call::CallKind::Meeting;234
if !in_meeting {235
return None;236
}237
let (mute_app, captions_app) = (app.clone(), app.clone());238
let organizes = model.organizes_meeting();239
let captions_on = model.captions_on();240
Some(241
Button::new("call-more")242
.ghost()243
.p_0()244
.size(px(CONTROL_SIZE))245
.rounded_full()246
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))247
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {248
let (mute_app, captions_app) = (mute_app.clone(), captions_app.clone());249
let mut popup = popup.min_w(px(MENU_WIDTH));250
if organizes {251
popup = popup.item(252
PopupMenuItem::new("Mute all")253
.icon(IconName::MicOff)254
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),255
);256
}257
popup.item(258
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })259
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })260
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),261
)262
})263
.into_any_element(),264
)265
}266
267
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {268
if !model.can_use_camera() {269
return None;270
}271
let app = app.clone();272
let model = model.clone();273
Some(274
Button::new("call-camera-menu")275
.ghost()276
.p_0()277
.size(px(SMALL_CONTROL))278
.rounded_full()279
.child(280
div()281
.id("call-camera-menu-face")282
.size(px(SMALL_CONTROL))283
.flex()284
.items_center()285
.justify_center()286
.rounded_full()287
.bg(theme::surface_raised())288
.child(icon(IconName::ChevronUp, 16., theme::text())),289
)290
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model))291
.into_any_element(),292
)293
}294
295
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {296
let camera_app = app.clone();297
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {298
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));299
});300
let mut popup = popup.min_w(px(MENU_WIDTH)).item(PopupMenuItem::label("Camera"));301
for item in cameras {302
popup = popup.item(item);303
}304
let (none_app, blur_app) = (app.clone(), app.clone());305
popup306
.separator()307
.item(PopupMenuItem::new("Background: None").checked(!model.blur).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background_blur(false, cx))))308
.item(PopupMenuItem::new("Background: Blur").checked(model.blur).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background_blur(true, cx))))309
}310
311
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {312
let lines = model.visible_captions(now);313
if lines.is_empty() {314
return None;315
}316
let shown = CAPTION_SHOWN.as_secs_f32();317
Some(318
div()319
.id("call-captions")320
.absolute()321
.left_0()322
.right_0()323
.bottom(px(CAPTION_BOTTOM))324
.flex()325
.justify_center()326
.px(px(24.))327
.child(328
v_flex()329
.w(px(CAPTION_WIDTH))330
.max_w_full()331
.gap(px(4.))332
.px(px(16.))333
.py(px(10.))334
.rounded(px(10.))335
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))336
.text_color(theme::white())337
.text_size(px(16.))338
.children(lines.into_iter().map(|line| {339
let age = now.saturating_duration_since(line.at).as_secs_f32();340
let fade = ((shown - age) / CAPTION_FADE_SECONDS).clamp(0., 1.);341
h_flex()342
.opacity(fade)343
.gap(px(8.))344
.items_start()345
.child(div().flex_none().font_weight(FontWeight::BOLD).child(format!("{}:", line.speaker)))346
.child(div().flex_1().min_w_0().child(line.text.clone()))347
})),348
)349
.into_any_element(),350
)351
}352
353
fn focus_chip(label: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Div {354
h_flex()355
.h(px(CHIP_HEIGHT))356
.px(px(8.))357
.gap(px(4.))358
.items_center()359
.rounded_full()360
.bg(background)361
.text_color(foreground)362
.text_size(px(12.))363
.font_weight(FontWeight::SEMIBOLD)364
.child(icon(glyph, 13., foreground))365
.child(label)366
}367
368
pub fn spotlight_chip() -> Div {369
focus_chip("Spotlight", IconName::Star, theme::amber(), dark_text())370
}371
372
pub fn pin_chip() -> Div {373
focus_chip("Pinned", IconName::Frame, hsla(0., 0., 0., 0.6), theme::white())374
}375
376
pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focus, now: Instant) -> Option<AnyElement> {377
let call = state.call.as_ref()?;378
let model = &call.model;379
let me = state.directory.me.as_ref();380
let (name, user_id, speaking, muted, key) = if focus.own {381
("You".to_owned(), me.map(|person| person.user_id.clone()), model.local_speaking, model.muted, VideoKey::LocalCamera)382
} else {383
let tile = model.tiles.iter().find(|tile| tile.mri == focus.mri)?;384
(tile.name.clone(), tile.user_id.clone(), model.tile_speaking(tile), tile.muted, VideoKey::Person(tile.mri.clone()))385
};386
let image: Option<Arc<RenderImage>> = call.pictures.live(&key, now);387
let picture = match image {388
Some(image) => img(ImageSource::Render(image)).size_full().object_fit(ObjectFit::Contain).into_any_element(),389
None => div()390
.size_full()391
.flex()392
.items_center()393
.justify_center()394
.child(person_avatar(&state.directory, user_id.as_deref(), &name, FOCUS_AVATAR))395
.into_any_element(),396
};397
let stage = div()398
.id("call-focus-stage")399
.relative()400
.flex_1()401
.min_w_0()402
.h_full()403
.overflow_hidden()404
.rounded(px(FOCUS_RADIUS))405
.bg(hsla(0., 0., 0.04, 1.))406
.border_2()407
.border_color(if speaking { theme::green() } else { transparent_black() })408
.child(picture)409
.child(410
h_flex()411
.absolute()412
.top(px(14.))413
.left(px(14.))414
.gap(px(6.))415
.when(focus.spotlight, |chips| chips.child(spotlight_chip()))416
.when(focus.pinned, |chips| chips.child(pin_chip())),417
)418
.child(419
h_flex()420
.absolute()421
.left(px(14.))422
.bottom(px(14.))423
.gap(px(8.))424
.px(px(10.))425
.py(px(4.))426
.rounded(px(6.))427
.bg(hsla(0., 0., 0., 0.6))428
.text_color(theme::white())429
.text_size(px(13.))430
.font_weight(FontWeight::SEMIBOLD)431
.child(name.clone())432
.when(muted, |plate| plate.child(icon(IconName::MicOff, 14., theme::red()))),433
);434
Some(attach_tile_menu(stage, app, model, &focus.mri, &name, focus.own))435
}436
437
pub fn captions_state_hint(model: &CallModel) -> Option<&'static str> {438
match model.captions {439
CaptionState::Starting => Some("Starting live captions..."),440
CaptionState::Failed(_) => Some("Live captions could not start"),441
CaptionState::On | CaptionState::Off => None,442
}443
}444
445
pub fn captions_hint_chip(model: &CallModel) -> Option<AnyElement> {446
let text = captions_state_hint(model)?;447
Some(448
div()449
.id("call-captions-hint")450
.absolute()451
.left_0()452
.right_0()453
.bottom(px(CAPTION_BOTTOM))454
.flex()455
.justify_center()456
.child(457
div()458
.px(px(14.))459
.py(px(6.))460
.rounded_full()461
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))462
.text_color(theme::white())463
.text_size(px(13.))464
.child(text),465
)466
.into_any_element(),467
)468
}@@ -6,7 +6,7 @@ use gpui_kit::assets::IconName;
6
6
use gpui_kit::component::{
7
7
button::{Button, ButtonVariants as _},
8
8
h_flex,
9
menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem},
9
menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
10
10
popover::Popover,
11
11
switch::Switch,
12
12
tooltip::Tooltip,
@@ -16,6 +16,7 @@ use gpui_kit::prelude::FluentBuilder as _;
16
16
use gpui_kit::*;
17
17
18
18
use super::avatar::person_avatar;
19
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};
19
20
use super::call_stage::render_stage;
20
21
use super::conversation::ConversationView;
21
22
use super::widgets::{count_badge, icon, symbol};
@@ -29,9 +30,9 @@ use crate::theme;
29
30
const HEADER_HEIGHT: f32 = 60.;
30
31
const RING_WIDTH: f32 = 3.;
31
32
const RING_GAP: f32 = 4.;
32
const CONTROL_SIZE: f32 = 44.;
33
pub(super) const CONTROL_SIZE: f32 = 44.;
33
34
const CONTROL_ICON: f32 = 20.;
34
const MENU_WIDTH: f32 = 280.;
35
pub(super) const MENU_WIDTH: f32 = 280.;
35
36
const PULSE_PERIOD: Duration = Duration::from_millis(1400);
36
37
const DISABLED_OPACITY: f32 = 0.4;
37
38
const TILE_GAP: f32 = 20.;
@@ -49,7 +50,7 @@ pub const NO_MICROPHONE_HINT: &str = "No microphone found";
49
50
pub const NO_CAMERA_HINT: &str = "No camera found";
50
51
pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";
51
52
pub const NO_WINDOWS_HINT: &str = "No windows found";
52
const BANNER_HEIGHT: f32 = 40.;
53
pub(super) const BANNER_HEIGHT: f32 = 40.;
53
54
const MAX_WINDOW_ITEMS: usize = 12;
54
55
pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
55
56
pub const CHAT_PANEL_WIDTH: f32 = 320.;
@@ -71,13 +72,12 @@ pub fn reaction_glyph(reaction: Reaction) -> String {
71
72
struct TileExtras {
72
73
hand: Option<usize>,
73
74
reaction: Option<(Reaction, u64)>,
75
spotlight: bool,
76
pinned: bool,
74
77
}
75
78
76
79
fn hand_badge(position: usize) -> Div {
77
80
h_flex()
78
.absolute()
79
.top(px(10.))
80
.left(px(10.))
81
81
.h(px(24.))
82
82
.px(px(8.))
83
83
.gap(px(4.))
@@ -117,9 +117,19 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
117
117
}
118
118
119
119
fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
120
let hand = extras.hand.map(|position| hand_badge(position).into_any_element());
120
let badges = (extras.hand.is_some() || extras.spotlight || extras.pinned).then(|| {
121
h_flex()
122
.absolute()
123
.top(px(10.))
124
.left(px(10.))
125
.gap(px(6.))
126
.children(extras.hand.map(hand_badge))
127
.when(extras.spotlight, |row| row.child(spotlight_chip()))
128
.when(extras.pinned, |row| row.child(pin_chip()))
129
.into_any_element()
130
});
121
131
let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));
122
hand.into_iter().chain(reaction).collect()
132
badges.into_iter().chain(reaction).collect()
123
133
}
124
134
125
135
pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
@@ -296,7 +306,7 @@ fn control_shell(id: &'static str, background: Hsla) -> Stateful<Div> {
296
306
.hover(|button| button.opacity(0.85))
297
307
}
298
308
299
fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
309
pub(super) fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
300
310
control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))
301
311
}
302
312
@@ -612,7 +622,7 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
612
622
})
613
623
}
614
624
615
fn device_items(
625
pub(super) fn device_items(
616
626
entries: Vec<DeviceEntry>,
617
627
selected: &calling::DeviceChoice,
618
628
pick: impl Fn(calling::DeviceChoice, &mut App) + Clone + 'static,
@@ -652,16 +662,6 @@ fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) ->
652
662
for item in outputs {
653
663
popup = popup.item(item);
654
664
}
655
if model.can_use_camera() {
656
let camera_app = app.clone();
657
let cameras = device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {
658
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));
659
});
660
popup = popup.separator().item(PopupMenuItem::label("Camera"));
661
for item in cameras {
662
popup = popup.item(item);
663
}
664
}
665
665
popup
666
666
}
667
667
@@ -688,23 +688,11 @@ fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remo
688
688
let extras = TileExtras {
689
689
hand: remote.hand.map(|rank| model.hand_position(rank)),
690
690
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),
691
spotlight: remote.spotlight.is_some(),
692
pinned: model.is_pinned(&remote.mri),
691
693
};
692
694
let element = person_tile_body(state, model, remote, size, now, &extras);
693
if !(model.can_lower_hands() && remote.hand.is_some()) {
694
return element;
695
}
696
let (app, mri) = (app.clone(), remote.mri.clone());
697
div()
698
.id(SharedString::from(format!("call-tile-{}", remote.mri)))
699
.flex_none()
700
.child(element)
701
.context_menu(move |popup, _, _| {
702
let (app, mri) = (app.clone(), mri.clone());
703
popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
704
app.update(cx, |state, cx| state.lower_call_hand(mri.clone(), cx));
705
}))
706
})
707
.into_any_element()
695
with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
708
696
}
709
697
710
698
fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {
@@ -726,18 +714,29 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti
726
714
tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
727
715
}
728
716
729
fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {
717
fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {
718
let own_mri = model.own_mri.clone().unwrap_or_default();
730
719
let extras = TileExtras {
731
720
hand: model.own_hand.map(|rank| model.hand_position(rank)),
732
721
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),
722
spotlight: model.own_spotlight.is_some(),
723
pinned: model.is_pinned(&own_mri),
733
724
};
725
let element = own_tile_body(state, model, size, now, &extras);
726
if own_mri.is_empty() {
727
return element;
728
}
729
with_tile_menu(app, model, &own_mri, "You", true, element)
730
}
731
732
fn own_tile_body(state: &AppState, model: &CallModel, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {
734
733
let me = state.directory.me.as_ref();
735
734
let self_view = state
736
735
.call
737
736
.as_ref()
738
737
.and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
739
738
if let Some(image) = self_view {
740
return video_tile(size, image, "You", model.local_speaking, model.muted, &extras).into_any_element();
739
return video_tile(size, image, "You", model.local_speaking, model.muted, extras).into_any_element();
741
740
}
742
741
let avatar = person_avatar(
743
742
&state.directory,
@@ -745,7 +744,7 @@ fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -
745
744
me.map_or("You", |person| person.display_name.as_str()),
746
745
size.avatar,
747
746
);
748
tile(size, avatar, "You", model.local_speaking, model.muted, None, &extras).into_any_element()
747
tile(size, avatar, "You", model.local_speaking, model.muted, None, extras).into_any_element()
749
748
}
750
749
751
750
fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {
@@ -761,14 +760,17 @@ fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, siz
761
760
cells
762
761
}
763
762
764
fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant) -> Stateful<Div> {
763
fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant, focused: Option<&str>) -> Stateful<Div> {
765
764
let mut cells: Vec<AnyElement> = model
766
765
.strip_tiles()
767
766
.into_iter()
767
.filter(|remote| Some(remote.mri.as_str()) != focused)
768
768
.map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))
769
769
.collect();
770
let own_index = model.own_cell_index(cells.len());
771
cells.insert(own_index, own_tile(state, model, STRIP_TILE, now));
770
if focused.is_none() || focused != model.own_mri.as_deref() {
771
let own_index = model.own_cell_index(cells.len());
772
cells.insert(own_index, own_tile(app, state, model, STRIP_TILE, now));
773
}
772
774
v_flex()
773
775
.id("call-strip")
774
776
.flex_none()
@@ -810,8 +812,10 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
810
812
let size = tile_size(cells_for_size);
811
813
let mut cells = remote_tiles(app, state, model, size, layout, now);
812
814
let own_index = model.own_cell_index(cells.len());
813
cells.insert(own_index, own_tile(state, model, size, now));
814
let stage = render_stage(app, state, false);
815
cells.insert(own_index, own_tile(app, state, model, size, now));
816
let focus = model.focus().filter(|_| model.screen_sharer.is_none());
817
let stage = render_stage(app, state, false).or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));
818
let focused = focus.as_ref().map(|focus| focus.mri.as_str());
815
819
816
820
let controls = h_flex()
817
821
.w_full()
@@ -823,21 +827,24 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
823
827
.border_t_1()
824
828
.border_color(theme::border())
825
829
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))
826
.child(camera_button(app, model))
830
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model)))
827
831
.child(share_button(app, model, state.call_share_sound))
828
832
.child(hand_button(app, model))
829
833
.child(reactions_button(app, model))
830
834
.child(devices_button(app, model))
835
.children(more_button(app, model))
831
836
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))
832
837
.child(leave_button(app, model, "call-leave", false))
833
838
.when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
834
839
835
840
let column = v_flex()
841
.relative()
836
842
.flex_1()
837
843
.min_w_0()
838
844
.h_full()
839
845
.bg(theme::background())
840
846
.child(header)
847
.children(lobby_banner(app, model))
841
848
.children(sharing_banner(app, model, state.call_share_sound))
842
849
.child(match stage {
843
850
Some(stage) => h_flex()
@@ -847,7 +854,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
847
854
.gap(px(TILE_GAP))
848
855
.items_center()
849
856
.child(stage)
850
.child(people_strip(app, state, model, now))
857
.child(people_strip(app, state, model, now, focused))
851
858
.into_any_element(),
852
859
None => h_flex()
853
860
.id("call-grid")
@@ -863,7 +870,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
863
870
.children(cells)
864
871
.into_any_element(),
865
872
})
866
.child(controls);
873
.child(controls)
874
.children(captions_overlay(model, now))
875
.children(captions_hint_chip(model));
867
876
Some(
868
877
h_flex()
869
878
.flex_1()
@@ -6,7 +6,7 @@ use gpui_kit::assets::IconName;6
use gpui_kit::component::{6
use gpui_kit::component::{7
button::{Button, ButtonVariants as _},7
button::{Button, ButtonVariants as _},8
h_flex,8
h_flex,9
menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem},9
menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},10
popover::Popover,10
popover::Popover,11
switch::Switch,11
switch::Switch,12
tooltip::Tooltip,12
tooltip::Tooltip,@@ -16,6 +16,7 @@ use gpui_kit::prelude::FluentBuilder as _;16
use gpui_kit::*;16
use gpui_kit::*;17
17
18
use super::avatar::person_avatar;18
use super::avatar::person_avatar;19
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};19
use super::call_stage::render_stage;20
use super::call_stage::render_stage;20
use super::conversation::ConversationView;21
use super::conversation::ConversationView;21
use super::widgets::{count_badge, icon, symbol};22
use super::widgets::{count_badge, icon, symbol};@@ -29,9 +30,9 @@ use crate::theme;29
const HEADER_HEIGHT: f32 = 60.;30
const HEADER_HEIGHT: f32 = 60.;30
const RING_WIDTH: f32 = 3.;31
const RING_WIDTH: f32 = 3.;31
const RING_GAP: f32 = 4.;32
const RING_GAP: f32 = 4.;32
const CONTROL_SIZE: f32 = 44.;33
pub(super) const CONTROL_SIZE: f32 = 44.;33
const CONTROL_ICON: f32 = 20.;34
const CONTROL_ICON: f32 = 20.;34
const MENU_WIDTH: f32 = 280.;35
pub(super) const MENU_WIDTH: f32 = 280.;35
const PULSE_PERIOD: Duration = Duration::from_millis(1400);36
const PULSE_PERIOD: Duration = Duration::from_millis(1400);36
const DISABLED_OPACITY: f32 = 0.4;37
const DISABLED_OPACITY: f32 = 0.4;37
const TILE_GAP: f32 = 20.;38
const TILE_GAP: f32 = 20.;@@ -49,7 +50,7 @@ pub const NO_MICROPHONE_HINT: &str = "No microphone found";49
pub const NO_CAMERA_HINT: &str = "No camera found";50
pub const NO_CAMERA_HINT: &str = "No camera found";50
pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";51
pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";51
pub const NO_WINDOWS_HINT: &str = "No windows found";52
pub const NO_WINDOWS_HINT: &str = "No windows found";52
const BANNER_HEIGHT: f32 = 40.;53
pub(super) const BANNER_HEIGHT: f32 = 40.;53
const MAX_WINDOW_ITEMS: usize = 12;54
const MAX_WINDOW_ITEMS: usize = 12;54
pub const LOBBY_TEXT: &str = "Waiting in the lobby...";55
pub const LOBBY_TEXT: &str = "Waiting in the lobby...";55
pub const CHAT_PANEL_WIDTH: f32 = 320.;56
pub const CHAT_PANEL_WIDTH: f32 = 320.;@@ -71,13 +72,12 @@ pub fn reaction_glyph(reaction: Reaction) -> String {71
struct TileExtras {72
struct TileExtras {72
hand: Option<usize>,73
hand: Option<usize>,73
reaction: Option<(Reaction, u64)>,74
reaction: Option<(Reaction, u64)>,75
spotlight: bool,76
pinned: bool,74
}77
}75
78
76
fn hand_badge(position: usize) -> Div {79
fn hand_badge(position: usize) -> Div {77
h_flex()80
h_flex()78
.absolute()79
.top(px(10.))80
.left(px(10.))81
.h(px(24.))81
.h(px(24.))82
.px(px(8.))82
.px(px(8.))83
.gap(px(4.))83
.gap(px(4.))@@ -117,9 +117,19 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {117
}117
}118
118
119
fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {119
fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {120
let hand = extras.hand.map(|position| hand_badge(position).into_any_element());120
let badges = (extras.hand.is_some() || extras.spotlight || extras.pinned).then(|| {121
h_flex()122
.absolute()123
.top(px(10.))124
.left(px(10.))125
.gap(px(6.))126
.children(extras.hand.map(hand_badge))127
.when(extras.spotlight, |row| row.child(spotlight_chip()))128
.when(extras.pinned, |row| row.child(pin_chip()))129
.into_any_element()130
});121
let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));131
let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));122
hand.into_iter().chain(reaction).collect()132
badges.into_iter().chain(reaction).collect()123
}133
}124
134
125
pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {135
pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {@@ -296,7 +306,7 @@ fn control_shell(id: &'static str, background: Hsla) -> Stateful<Div> {296
.hover(|button| button.opacity(0.85))306
.hover(|button| button.opacity(0.85))297
}307
}298
308
299
fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {309
pub(super) fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {300
control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))310
control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))301
}311
}302
312
@@ -612,7 +622,7 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {612
})622
})613
}623
}614
624
615
fn device_items(625
pub(super) fn device_items(616
entries: Vec<DeviceEntry>,626
entries: Vec<DeviceEntry>,617
selected: &calling::DeviceChoice,627
selected: &calling::DeviceChoice,618
pick: impl Fn(calling::DeviceChoice, &mut App) + Clone + 'static,628
pick: impl Fn(calling::DeviceChoice, &mut App) + Clone + 'static,@@ -652,16 +662,6 @@ fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) ->652
for item in outputs {662
for item in outputs {653
popup = popup.item(item);663
popup = popup.item(item);654
}664
}655
if model.can_use_camera() {656
let camera_app = app.clone();657
let cameras = device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {658
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));659
});660
popup = popup.separator().item(PopupMenuItem::label("Camera"));661
for item in cameras {662
popup = popup.item(item);663
}664
}665
popup665
popup666
}666
}667
667
@@ -688,23 +688,11 @@ fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remo688
let extras = TileExtras {688
let extras = TileExtras {689
hand: remote.hand.map(|rank| model.hand_position(rank)),689
hand: remote.hand.map(|rank| model.hand_position(rank)),690
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),690
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),691
spotlight: remote.spotlight.is_some(),692
pinned: model.is_pinned(&remote.mri),691
};693
};692
let element = person_tile_body(state, model, remote, size, now, &extras);694
let element = person_tile_body(state, model, remote, size, now, &extras);693
if !(model.can_lower_hands() && remote.hand.is_some()) {695
with_tile_menu(app, model, &remote.mri, &remote.name, false, element)694
return element;695
}696
let (app, mri) = (app.clone(), remote.mri.clone());697
div()698
.id(SharedString::from(format!("call-tile-{}", remote.mri)))699
.flex_none()700
.child(element)701
.context_menu(move |popup, _, _| {702
let (app, mri) = (app.clone(), mri.clone());703
popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {704
app.update(cx, |state, cx| state.lower_call_hand(mri.clone(), cx));705
}))706
})707
.into_any_element()708
}696
}709
697
710
fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {698
fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {@@ -726,18 +714,29 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti726
tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()714
tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()727
}715
}728
716
729
fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {717
fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {718
let own_mri = model.own_mri.clone().unwrap_or_default();730
let extras = TileExtras {719
let extras = TileExtras {731
hand: model.own_hand.map(|rank| model.hand_position(rank)),720
hand: model.own_hand.map(|rank| model.hand_position(rank)),732
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),721
reaction: model.own_chip(now).map(|chip| (chip.reaction, chip.serial)),722
spotlight: model.own_spotlight.is_some(),723
pinned: model.is_pinned(&own_mri),733
};724
};725
let element = own_tile_body(state, model, size, now, &extras);726
if own_mri.is_empty() {727
return element;728
}729
with_tile_menu(app, model, &own_mri, "You", true, element)730
}731
732
fn own_tile_body(state: &AppState, model: &CallModel, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {734
let me = state.directory.me.as_ref();733
let me = state.directory.me.as_ref();735
let self_view = state734
let self_view = state736
.call735
.call737
.as_ref()736
.as_ref()738
.and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));737
.and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));739
if let Some(image) = self_view {738
if let Some(image) = self_view {740
return video_tile(size, image, "You", model.local_speaking, model.muted, &extras).into_any_element();739
return video_tile(size, image, "You", model.local_speaking, model.muted, extras).into_any_element();741
}740
}742
let avatar = person_avatar(741
let avatar = person_avatar(743
&state.directory,742
&state.directory,@@ -745,7 +744,7 @@ fn own_tile(state: &AppState, model: &CallModel, size: TileSize, now: Instant) -745
me.map_or("You", |person| person.display_name.as_str()),744
me.map_or("You", |person| person.display_name.as_str()),746
size.avatar,745
size.avatar,747
);746
);748
tile(size, avatar, "You", model.local_speaking, model.muted, None, &extras).into_any_element()747
tile(size, avatar, "You", model.local_speaking, model.muted, None, extras).into_any_element()749
}748
}750
749
751
fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {750
fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {@@ -761,14 +760,17 @@ fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, siz761
cells760
cells762
}761
}763
762
764
fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant) -> Stateful<Div> {763
fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant, focused: Option<&str>) -> Stateful<Div> {765
let mut cells: Vec<AnyElement> = model764
let mut cells: Vec<AnyElement> = model766
.strip_tiles()765
.strip_tiles()767
.into_iter()766
.into_iter()767
.filter(|remote| Some(remote.mri.as_str()) != focused)768
.map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))768
.map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))769
.collect();769
.collect();770
let own_index = model.own_cell_index(cells.len());770
if focused.is_none() || focused != model.own_mri.as_deref() {771
cells.insert(own_index, own_tile(state, model, STRIP_TILE, now));771
let own_index = model.own_cell_index(cells.len());772
cells.insert(own_index, own_tile(app, state, model, STRIP_TILE, now));773
}772
v_flex()774
v_flex()773
.id("call-strip")775
.id("call-strip")774
.flex_none()776
.flex_none()@@ -810,8 +812,10 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E810
let size = tile_size(cells_for_size);812
let size = tile_size(cells_for_size);811
let mut cells = remote_tiles(app, state, model, size, layout, now);813
let mut cells = remote_tiles(app, state, model, size, layout, now);812
let own_index = model.own_cell_index(cells.len());814
let own_index = model.own_cell_index(cells.len());813
cells.insert(own_index, own_tile(state, model, size, now));815
cells.insert(own_index, own_tile(app, state, model, size, now));814
let stage = render_stage(app, state, false);816
let focus = model.focus().filter(|_| model.screen_sharer.is_none());817
let stage = render_stage(app, state, false).or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));818
let focused = focus.as_ref().map(|focus| focus.mri.as_str());815
819
816
let controls = h_flex()820
let controls = h_flex()817
.w_full()821
.w_full()@@ -823,21 +827,24 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E823
.border_t_1()827
.border_t_1()824
.border_color(theme::border())828
.border_color(theme::border())825
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))829
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))826
.child(camera_button(app, model))830
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model)))827
.child(share_button(app, model, state.call_share_sound))831
.child(share_button(app, model, state.call_share_sound))828
.child(hand_button(app, model))832
.child(hand_button(app, model))829
.child(reactions_button(app, model))833
.child(reactions_button(app, model))830
.child(devices_button(app, model))834
.child(devices_button(app, model))835
.children(more_button(app, model))831
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))836
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))832
.child(leave_button(app, model, "call-leave", false))837
.child(leave_button(app, model, "call-leave", false))833
.when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));838
.when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));834
839
835
let column = v_flex()840
let column = v_flex()841
.relative()836
.flex_1()842
.flex_1()837
.min_w_0()843
.min_w_0()838
.h_full()844
.h_full()839
.bg(theme::background())845
.bg(theme::background())840
.child(header)846
.child(header)847
.children(lobby_banner(app, model))841
.children(sharing_banner(app, model, state.call_share_sound))848
.children(sharing_banner(app, model, state.call_share_sound))842
.child(match stage {849
.child(match stage {843
Some(stage) => h_flex()850
Some(stage) => h_flex()@@ -847,7 +854,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E847
.gap(px(TILE_GAP))854
.gap(px(TILE_GAP))848
.items_center()855
.items_center()849
.child(stage)856
.child(stage)850
.child(people_strip(app, state, model, now))857
.child(people_strip(app, state, model, now, focused))851
.into_any_element(),858
.into_any_element(),852
None => h_flex()859
None => h_flex()853
.id("call-grid")860
.id("call-grid")@@ -863,7 +870,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E863
.children(cells)870
.children(cells)864
.into_any_element(),871
.into_any_element(),865
})872
})866
.child(controls);873
.child(controls)874
.children(captions_overlay(model, now))875
.children(captions_hint_chip(model));867
Some(876
Some(868
h_flex()877
h_flex()869
.flex_1()878
.flex_1()@@ -5,6 +5,7 @@ pub mod attachments;
5
5
pub mod avatar;
6
6
pub mod call_controls;
7
7
pub mod call_mini;
8
pub mod call_organizer;
8
9
pub mod call_stage;
9
10
pub mod call_view;
10
11
pub mod card_carousel;
@@ -5,6 +5,7 @@ pub mod attachments;5
pub mod avatar;5
pub mod avatar;6
pub mod call_controls;6
pub mod call_controls;7
pub mod call_mini;7
pub mod call_mini;8
pub mod call_organizer;8
pub mod call_stage;9
pub mod call_stage;9
pub mod call_view;10
pub mod call_view;10
pub mod card_carousel;11
pub mod card_carousel;@@ -7,6 +7,7 @@ publish.workspace = true
7
7
8
8
[dependencies]
9
9
base64.workspace = true
10
chrono.workspace = true
10
11
cpal = "0.17"
11
12
chatsvc.workspace = true
12
13
flate2 = "1"
@@ -17,6 +18,7 @@ serde.workspace = true
17
18
serde_json.workspace = true
18
19
session.workspace = true
19
20
thiserror.workspace = true
21
tract-onnx = "0.23"
20
22
tokio.workspace = true
21
23
uuid.workspace = true
22
24
@@ -7,6 +7,7 @@ publish.workspace = true7
7
8
[dependencies]8
[dependencies]9
base64.workspace = true9
base64.workspace = true10
chrono.workspace = true10
cpal = "0.17"11
cpal = "0.17"11
chatsvc.workspace = true12
chatsvc.workspace = true12
flate2 = "1"13
flate2 = "1"@@ -17,6 +18,7 @@ serde.workspace = true17
serde_json.workspace = true18
serde_json.workspace = true18
session.workspace = true19
session.workspace = true19
thiserror.workspace = true20
thiserror.workspace = true21
tract-onnx = "0.23"20
tokio.workspace = true22
tokio.workspace = true21
uuid.workspace = true23
uuid.workspace = true22
24
@@ -0,0 +1,11 @@
1
# selfie_segmentation_landscape.onnx
2
3
| Item | Value |
4
|---|---|
5
| Model | MediaPipe Selfie Segmentation, landscape (256x144) |
6
| Author | Google LLC (MediaPipe) |
7
| License | Apache License 2.0, https://www.apache.org/licenses/LICENSE-2.0 |
8
| ONNX conversion | https://huggingface.co/onnx-community/mediapipe_selfie_segmentation_landscape (`onnx/model.onnx`, Apache-2.0, repo revision 2497d5bec26c626c7b3c4edc6e1fefc21b64f6c3) |
9
| Input | `pixel_values` float32 [1, 3, 144, 256], RGB, 0..1 |
10
| Output | `alphas` float32 [1, 1, 144, 256], person probability |
11
| Changes | none; the file is used as downloaded |
@@ -0,0 +1,11 @@1
# selfie_segmentation_landscape.onnx2
3
| Item | Value |4
|---|---|5
| Model | MediaPipe Selfie Segmentation, landscape (256x144) |6
| Author | Google LLC (MediaPipe) |7
| License | Apache License 2.0, https://www.apache.org/licenses/LICENSE-2.0 |8
| ONNX conversion | https://huggingface.co/onnx-community/mediapipe_selfie_segmentation_landscape (`onnx/model.onnx`, Apache-2.0, repo revision 2497d5bec26c626c7b3c4edc6e1fefc21b64f6c3) |9
| Input | `pixel_values` float32 [1, 3, 144, 256], RGB, 0..1 |10
| Output | `alphas` float32 [1, 1, 144, 256], person probability |11
| Changes | none; the file is used as downloaded |@@ -0,0 +1,36 @@
1
let authz;
2
try {
3
authz = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {
4
method: 'POST',
5
headers: {Authorization: 'Bearer ' + token},
6
});
7
} catch (error) {
8
return {error: 'authz_unreachable'};
9
}
10
if (!authz.ok) return {error: 'authz_http_' + authz.status};
11
let skypeToken = null;
12
try {
13
skypeToken = (await authz.json()).tokens.skypeToken;
14
} catch (error) {
15
return {error: 'authz_shape'};
16
}
17
if (!skypeToken) return {error: 'authz_no_skype_token'};
18
const recorder = await acquire(args.recorderResource, args.recorderScope);
19
if (!recorder.token) return {error: 'no_recorder_token'};
20
let response;
21
try {
22
response = await fetch(args.url, {
23
method: 'POST',
24
headers: {
25
Authorization: 'Bearer ' + recorder.token,
26
'X-Skypetoken': skypeToken,
27
requestid: args.requestId,
28
'x-microsoft-skype-chain-id': args.chainId,
29
'content-type': 'application/json',
30
},
31
body: JSON.stringify({...args.body, participantSkypeToken: skypeToken}),
32
});
33
} catch (error) {
34
return {error: 'command_unreachable'};
35
}
36
return {status: response.status};
@@ -0,0 +1,36 @@1
let authz;2
try {3
authz = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {4
method: 'POST',5
headers: {Authorization: 'Bearer ' + token},6
});7
} catch (error) {8
return {error: 'authz_unreachable'};9
}10
if (!authz.ok) return {error: 'authz_http_' + authz.status};11
let skypeToken = null;12
try {13
skypeToken = (await authz.json()).tokens.skypeToken;14
} catch (error) {15
return {error: 'authz_shape'};16
}17
if (!skypeToken) return {error: 'authz_no_skype_token'};18
const recorder = await acquire(args.recorderResource, args.recorderScope);19
if (!recorder.token) return {error: 'no_recorder_token'};20
let response;21
try {22
response = await fetch(args.url, {23
method: 'POST',24
headers: {25
Authorization: 'Bearer ' + recorder.token,26
'X-Skypetoken': skypeToken,27
requestid: args.requestId,28
'x-microsoft-skype-chain-id': args.chainId,29
'content-type': 'application/json',30
},31
body: JSON.stringify({...args.body, participantSkypeToken: skypeToken}),32
});33
} catch (error) {34
return {error: 'command_unreachable'};35
}36
return {status: response.status};The contents of this binary file are not shown.
@@ -0,0 +1,40 @@
1
use std::time::Instant;
2
3
use calling::blur::{BackgroundBlur, Segmenter};
4
5
const WIDTH: usize = 640;
6
const HEIGHT: usize = 360;
7
const FRAMES: usize = 200;
8
const WARMUP: usize = 10;
9
10
fn synthetic() -> Vec<u8> {
11
(0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()
12
}
13
14
fn main() {
15
let mut arguments = std::env::args().skip(1);
16
let input = arguments.next();
17
let output = arguments.next();
18
let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
19
assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");
20
let mut blur = BackgroundBlur::new().expect("model");
21
let segmenter = Segmenter::new().expect("model");
22
for _ in 0..WARMUP {
23
blur.apply(&mut frame.clone(), WIDTH, HEIGHT);
24
}
25
let started = Instant::now();
26
for _ in 0..FRAMES {
27
segmenter.mask(&frame, WIDTH, HEIGHT).expect("mask");
28
}
29
println!("segmentation only: {:.2} ms/frame", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64);
30
let started = Instant::now();
31
let mut result = frame.clone();
32
for _ in 0..FRAMES {
33
result.copy_from_slice(&frame);
34
blur.apply(&mut result, WIDTH, HEIGHT);
35
}
36
println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());
37
if let Some(path) = output {
38
std::fs::write(path, &result).expect("output");
39
}
40
}
@@ -0,0 +1,40 @@1
use std::time::Instant;2
3
use calling::blur::{BackgroundBlur, Segmenter};4
5
const WIDTH: usize = 640;6
const HEIGHT: usize = 360;7
const FRAMES: usize = 200;8
const WARMUP: usize = 10;9
10
fn synthetic() -> Vec<u8> {11
(0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()12
}13
14
fn main() {15
let mut arguments = std::env::args().skip(1);16
let input = arguments.next();17
let output = arguments.next();18
let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));19
assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");20
let mut blur = BackgroundBlur::new().expect("model");21
let segmenter = Segmenter::new().expect("model");22
for _ in 0..WARMUP {23
blur.apply(&mut frame.clone(), WIDTH, HEIGHT);24
}25
let started = Instant::now();26
for _ in 0..FRAMES {27
segmenter.mask(&frame, WIDTH, HEIGHT).expect("mask");28
}29
println!("segmentation only: {:.2} ms/frame", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64);30
let started = Instant::now();31
let mut result = frame.clone();32
for _ in 0..FRAMES {33
result.copy_from_slice(&frame);34
blur.apply(&mut result, WIDTH, HEIGHT);35
}36
println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());37
if let Some(path) = output {38
std::fs::write(path, &result).expect("output");39
}40
}@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};
4
4
use calling::meeting::fetch_live_meeting;
5
5
use calling::relay::ic3_scope;
6
6
use calling::signaling::{CHATSVC_REGION, fetch_self};
7
use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};
7
use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};
8
8
use chatsvc::InstanceNames;
9
9
use serde_json::{Value, json};
10
10
use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
@@ -20,11 +20,18 @@ const GONE_LIMIT: Duration = Duration::from_secs(90);
20
20
const POLL: Duration = Duration::from_secs(2);
21
21
const MEDIA_DELAY: Duration = Duration::from_secs(3);
22
22
const THREAD_PROPERTY_RETRIES: usize = 8;
23
const CAPTIONS_HOLD: Duration = Duration::from_secs(10);
24
const FEATURE_LIMIT: Duration = Duration::from_secs(90);
25
const VIDEO_ENV: &str = "CALLING_VIDEO";
23
26
24
27
struct Arguments {
25
28
camera: bool,
26
29
share: bool,
27
30
extras: bool,
31
spotlight_self: bool,
32
captions: bool,
33
mute_all: bool,
34
blur: bool,
28
35
stop_media_after: Option<Duration>,
29
36
hold: Duration,
30
37
thread_out: Option<PathBuf>,
@@ -36,6 +43,10 @@ fn arguments() -> Arguments {
36
43
camera: false,
37
44
share: false,
38
45
extras: false,
46
spotlight_self: false,
47
captions: false,
48
mute_all: false,
49
blur: false,
39
50
stop_media_after: None,
40
51
hold: Duration::from_secs(10),
41
52
thread_out: None,
@@ -47,6 +58,13 @@ fn arguments() -> Arguments {
47
58
"--camera" => parsed.camera = true,
48
59
"--share" => parsed.share = true,
49
60
"--extras" => parsed.extras = true,
61
"--spotlight-self" => parsed.spotlight_self = true,
62
"--captions" => parsed.captions = true,
63
"--mute-all" => parsed.mute_all = true,
64
"--blur" => {
65
parsed.blur = true;
66
parsed.camera = true;
67
}
50
68
"--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),
51
69
"--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
52
70
"--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
@@ -83,8 +101,48 @@ async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<Str
83
101
(tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))
84
102
}
85
103
86
#[tokio::main]
87
async fn main() {
104
fn main() {
105
if arguments().blur && std::env::var_os(VIDEO_ENV).is_none() {
106
// SAFETY: nothing else runs yet; the runtime below starts after this.
107
unsafe { std::env::set_var(VIDEO_ENV, "pattern") };
108
}
109
tokio::runtime::Runtime::new().expect("runtime").block_on(run());
110
}
111
112
fn http_status(reason: &str) -> String {
113
reason
114
.split("HTTP ")
115
.nth(1)
116
.map(|rest| rest.chars().take_while(char::is_ascii_digit).collect::<String>())
117
.filter(|digits| !digits.is_empty())
118
.map_or_else(|| "no status".to_owned(), |digits| format!("HTTP {digits}"))
119
}
120
121
#[derive(Default)]
122
struct Features {
123
own_mri: Option<String>,
124
spotlight_seen: bool,
125
spotlight_cleared: bool,
126
captions_requested: bool,
127
captions_active: bool,
128
captions_stop_due: Option<Instant>,
129
captions_stopped: bool,
130
caption_events: usize,
131
blur_reports: usize,
132
blur_total_ms: f64,
133
deadline: Option<Instant>,
134
}
135
136
impl Features {
137
fn pending(&self, arguments: &Arguments) -> bool {
138
if self.deadline.is_none_or(|deadline| Instant::now() >= deadline) {
139
return false;
140
}
141
(arguments.spotlight_self && !self.spotlight_cleared) || (arguments.captions && !self.captions_stopped)
142
}
143
}
144
145
async fn run() {
88
146
let arguments = arguments();
89
147
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
90
148
let session = Session::connect(&endpoint).await.expect("browser");
@@ -159,6 +217,7 @@ async fn main() {
159
217
let mut reactions_seen = Vec::new();
160
218
let mut sharing_local_level: f32 = 0.0;
161
219
let mut sharing = false;
220
let mut features = Features::default();
162
221
let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
163
222
let mut tick = tokio::time::interval(POLL);
164
223
while ended.is_none() && Instant::now() < deadline {
@@ -177,7 +236,44 @@ async fn main() {
177
236
}
178
237
Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),
179
238
Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
239
Some(CallUpdate::OwnIdentity { mri }) => features.own_mri = Some(mri),
240
Some(CallUpdate::Captions(state)) => {
241
println!("# captions state: {}", match &state {
242
CaptionState::Off => "off".to_owned(),
243
CaptionState::Starting => "starting".to_owned(),
244
CaptionState::On => "on".to_owned(),
245
CaptionState::Failed(reason) => format!("failed ({reason})"),
246
});
247
if state == CaptionState::On && !features.captions_active {
248
features.captions_active = true;
249
features.captions_stop_due = Some(Instant::now() + CAPTIONS_HOLD);
250
}
251
if matches!(state, CaptionState::Failed(_)) {
252
features.captions_stopped = true;
253
}
254
}
255
Some(CallUpdate::Caption(_)) => features.caption_events += 1,
256
Some(CallUpdate::BlurTiming(average_ms)) => {
257
features.blur_reports += 1;
258
features.blur_total_ms += f64::from(average_ms);
259
}
260
Some(CallUpdate::Organizer { action, outcome }) => match outcome {
261
Ok(status) => println!("# organizer {action}: HTTP {status}"),
262
Err(reason) => println!("# organizer {action}: failed, {}", http_status(&reason)),
263
},
180
264
Some(CallUpdate::Roster(entries)) => {
265
let own_spotlit = entries.iter().any(|entry| Some(&entry.mri) == features.own_mri.as_ref() && entry.spotlight.is_some());
266
if own_spotlit && !features.spotlight_seen {
267
features.spotlight_seen = true;
268
println!("# own spotlight visible in the roster");
269
if let Some(mri) = features.own_mri.clone() {
270
let _ = handle.commands.send(CallCommand::StopSpotlight { mri });
271
}
272
}
273
if !own_spotlit && features.spotlight_seen && !features.spotlight_cleared {
274
features.spotlight_cleared = true;
275
println!("# own spotlight gone from the roster");
276
}
181
277
let hands = entries.iter().filter(|entry| entry.hand.is_some()).count();
182
278
if hands != hands_seen {
183
279
println!("# roster hands raised: {hands}");
@@ -222,6 +318,11 @@ async fn main() {
222
318
let _ = handle.commands.send(CallCommand::SetCamera(false));
223
319
let _ = handle.commands.send(CallCommand::StopShare);
224
320
}
321
if features.captions_stop_due.is_some_and(|due| Instant::now() >= due) {
322
features.captions_stop_due = None;
323
features.captions_stopped = true;
324
let _ = handle.commands.send(CallCommand::SetCaptions(false));
325
}
225
326
if hand_lower_due.is_some_and(|due| Instant::now() >= due) {
226
327
hand_lower_due = None;
227
328
let _ = handle.commands.send(CallCommand::SetHand(false));
@@ -240,6 +341,22 @@ async fn main() {
240
341
let _ = handle.commands.send(CallCommand::SetShareSound(true));
241
342
hand_lower_due = Some(Instant::now() + Duration::from_secs(6));
242
343
}
344
features.deadline = Some(Instant::now() + FEATURE_LIMIT);
345
if arguments.spotlight_self
346
&& let Some(mri) = features.own_mri.clone()
347
{
348
let _ = handle.commands.send(CallCommand::Spotlight { mri });
349
}
350
if arguments.mute_all {
351
let _ = handle.commands.send(CallCommand::MuteAll);
352
}
353
if arguments.captions {
354
features.captions_requested = true;
355
let _ = handle.commands.send(CallCommand::SetCaptions(true));
356
}
357
if arguments.blur {
358
let _ = handle.commands.send(CallCommand::SetBlur(true));
359
}
243
360
if arguments.share {
244
361
let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };
245
362
let _ = handle.commands.send(CallCommand::StartShare(source));
@@ -264,7 +381,7 @@ async fn main() {
264
381
}
265
382
let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())
266
383
&& join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;
267
if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file {
384
if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file && !features.pending(&arguments) {
268
385
println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");
269
386
let _ = handle.commands.send(CallCommand::EndMeeting);
270
387
end_sent_at = Some(Instant::now());
@@ -283,6 +400,16 @@ async fn main() {
283
400
Reaction::ALL.len()
284
401
);
285
402
}
403
if arguments.spotlight_self {
404
println!("# spotlight self: shown {}, cleared {}", features.spotlight_seen, features.spotlight_cleared);
405
}
406
if arguments.captions {
407
println!("# captions: became active {}, caption events {}", features.captions_active, features.caption_events);
408
}
409
if arguments.blur {
410
let average = if features.blur_reports == 0 { 0. } else { features.blur_total_ms / features.blur_reports as f64 };
411
println!("# blur: average processing {average:.1} ms over {} report(s)", features.blur_reports);
412
}
286
413
let gone_started = Instant::now();
287
414
let mut gone_after = None;
288
415
while gone_started.elapsed() < GONE_LIMIT {
@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};4
use calling::meeting::fetch_live_meeting;4
use calling::meeting::fetch_live_meeting;5
use calling::relay::ic3_scope;5
use calling::relay::ic3_scope;6
use calling::signaling::{CHATSVC_REGION, fetch_self};6
use calling::signaling::{CHATSVC_REGION, fetch_self};7
use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};7
use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};8
use chatsvc::InstanceNames;8
use chatsvc::InstanceNames;9
use serde_json::{Value, json};9
use serde_json::{Value, json};10
use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};10
use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};@@ -20,11 +20,18 @@ const GONE_LIMIT: Duration = Duration::from_secs(90);20
const POLL: Duration = Duration::from_secs(2);20
const POLL: Duration = Duration::from_secs(2);21
const MEDIA_DELAY: Duration = Duration::from_secs(3);21
const MEDIA_DELAY: Duration = Duration::from_secs(3);22
const THREAD_PROPERTY_RETRIES: usize = 8;22
const THREAD_PROPERTY_RETRIES: usize = 8;23
const CAPTIONS_HOLD: Duration = Duration::from_secs(10);24
const FEATURE_LIMIT: Duration = Duration::from_secs(90);25
const VIDEO_ENV: &str = "CALLING_VIDEO";23
26
24
struct Arguments {27
struct Arguments {25
camera: bool,28
camera: bool,26
share: bool,29
share: bool,27
extras: bool,30
extras: bool,31
spotlight_self: bool,32
captions: bool,33
mute_all: bool,34
blur: bool,28
stop_media_after: Option<Duration>,35
stop_media_after: Option<Duration>,29
hold: Duration,36
hold: Duration,30
thread_out: Option<PathBuf>,37
thread_out: Option<PathBuf>,@@ -36,6 +43,10 @@ fn arguments() -> Arguments {36
camera: false,43
camera: false,37
share: false,44
share: false,38
extras: false,45
extras: false,46
spotlight_self: false,47
captions: false,48
mute_all: false,49
blur: false,39
stop_media_after: None,50
stop_media_after: None,40
hold: Duration::from_secs(10),51
hold: Duration::from_secs(10),41
thread_out: None,52
thread_out: None,@@ -47,6 +58,13 @@ fn arguments() -> Arguments {47
"--camera" => parsed.camera = true,58
"--camera" => parsed.camera = true,48
"--share" => parsed.share = true,59
"--share" => parsed.share = true,49
"--extras" => parsed.extras = true,60
"--extras" => parsed.extras = true,61
"--spotlight-self" => parsed.spotlight_self = true,62
"--captions" => parsed.captions = true,63
"--mute-all" => parsed.mute_all = true,64
"--blur" => {65
parsed.blur = true;66
parsed.camera = true;67
}50
"--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),68
"--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),51
"--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),69
"--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),52
"--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),70
"--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),@@ -83,8 +101,48 @@ async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<Str83
(tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))101
(tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))84
}102
}85
103
86
#[tokio::main]104
fn main() {87
async fn main() {105
if arguments().blur && std::env::var_os(VIDEO_ENV).is_none() {106
// SAFETY: nothing else runs yet; the runtime below starts after this.107
unsafe { std::env::set_var(VIDEO_ENV, "pattern") };108
}109
tokio::runtime::Runtime::new().expect("runtime").block_on(run());110
}111
112
fn http_status(reason: &str) -> String {113
reason114
.split("HTTP ")115
.nth(1)116
.map(|rest| rest.chars().take_while(char::is_ascii_digit).collect::<String>())117
.filter(|digits| !digits.is_empty())118
.map_or_else(|| "no status".to_owned(), |digits| format!("HTTP {digits}"))119
}120
121
#[derive(Default)]122
struct Features {123
own_mri: Option<String>,124
spotlight_seen: bool,125
spotlight_cleared: bool,126
captions_requested: bool,127
captions_active: bool,128
captions_stop_due: Option<Instant>,129
captions_stopped: bool,130
caption_events: usize,131
blur_reports: usize,132
blur_total_ms: f64,133
deadline: Option<Instant>,134
}135
136
impl Features {137
fn pending(&self, arguments: &Arguments) -> bool {138
if self.deadline.is_none_or(|deadline| Instant::now() >= deadline) {139
return false;140
}141
(arguments.spotlight_self && !self.spotlight_cleared) || (arguments.captions && !self.captions_stopped)142
}143
}144
145
async fn run() {88
let arguments = arguments();146
let arguments = arguments();89
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());147
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());90
let session = Session::connect(&endpoint).await.expect("browser");148
let session = Session::connect(&endpoint).await.expect("browser");@@ -159,6 +217,7 @@ async fn main() {159
let mut reactions_seen = Vec::new();217
let mut reactions_seen = Vec::new();160
let mut sharing_local_level: f32 = 0.0;218
let mut sharing_local_level: f32 = 0.0;161
let mut sharing = false;219
let mut sharing = false;220
let mut features = Features::default();162
let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;221
let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;163
let mut tick = tokio::time::interval(POLL);222
let mut tick = tokio::time::interval(POLL);164
while ended.is_none() && Instant::now() < deadline {223
while ended.is_none() && Instant::now() < deadline {@@ -177,7 +236,44 @@ async fn main() {177
}236
}178
Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),237
Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),179
Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),238
Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),239
Some(CallUpdate::OwnIdentity { mri }) => features.own_mri = Some(mri),240
Some(CallUpdate::Captions(state)) => {241
println!("# captions state: {}", match &state {242
CaptionState::Off => "off".to_owned(),243
CaptionState::Starting => "starting".to_owned(),244
CaptionState::On => "on".to_owned(),245
CaptionState::Failed(reason) => format!("failed ({reason})"),246
});247
if state == CaptionState::On && !features.captions_active {248
features.captions_active = true;249
features.captions_stop_due = Some(Instant::now() + CAPTIONS_HOLD);250
}251
if matches!(state, CaptionState::Failed(_)) {252
features.captions_stopped = true;253
}254
}255
Some(CallUpdate::Caption(_)) => features.caption_events += 1,256
Some(CallUpdate::BlurTiming(average_ms)) => {257
features.blur_reports += 1;258
features.blur_total_ms += f64::from(average_ms);259
}260
Some(CallUpdate::Organizer { action, outcome }) => match outcome {261
Ok(status) => println!("# organizer {action}: HTTP {status}"),262
Err(reason) => println!("# organizer {action}: failed, {}", http_status(&reason)),263
},180
Some(CallUpdate::Roster(entries)) => {264
Some(CallUpdate::Roster(entries)) => {265
let own_spotlit = entries.iter().any(|entry| Some(&entry.mri) == features.own_mri.as_ref() && entry.spotlight.is_some());266
if own_spotlit && !features.spotlight_seen {267
features.spotlight_seen = true;268
println!("# own spotlight visible in the roster");269
if let Some(mri) = features.own_mri.clone() {270
let _ = handle.commands.send(CallCommand::StopSpotlight { mri });271
}272
}273
if !own_spotlit && features.spotlight_seen && !features.spotlight_cleared {274
features.spotlight_cleared = true;275
println!("# own spotlight gone from the roster");276
}181
let hands = entries.iter().filter(|entry| entry.hand.is_some()).count();277
let hands = entries.iter().filter(|entry| entry.hand.is_some()).count();182
if hands != hands_seen {278
if hands != hands_seen {183
println!("# roster hands raised: {hands}");279
println!("# roster hands raised: {hands}");@@ -222,6 +318,11 @@ async fn main() {222
let _ = handle.commands.send(CallCommand::SetCamera(false));318
let _ = handle.commands.send(CallCommand::SetCamera(false));223
let _ = handle.commands.send(CallCommand::StopShare);319
let _ = handle.commands.send(CallCommand::StopShare);224
}320
}321
if features.captions_stop_due.is_some_and(|due| Instant::now() >= due) {322
features.captions_stop_due = None;323
features.captions_stopped = true;324
let _ = handle.commands.send(CallCommand::SetCaptions(false));325
}225
if hand_lower_due.is_some_and(|due| Instant::now() >= due) {326
if hand_lower_due.is_some_and(|due| Instant::now() >= due) {226
hand_lower_due = None;327
hand_lower_due = None;227
let _ = handle.commands.send(CallCommand::SetHand(false));328
let _ = handle.commands.send(CallCommand::SetHand(false));@@ -240,6 +341,22 @@ async fn main() {240
let _ = handle.commands.send(CallCommand::SetShareSound(true));341
let _ = handle.commands.send(CallCommand::SetShareSound(true));241
hand_lower_due = Some(Instant::now() + Duration::from_secs(6));342
hand_lower_due = Some(Instant::now() + Duration::from_secs(6));242
}343
}344
features.deadline = Some(Instant::now() + FEATURE_LIMIT);345
if arguments.spotlight_self346
&& let Some(mri) = features.own_mri.clone()347
{348
let _ = handle.commands.send(CallCommand::Spotlight { mri });349
}350
if arguments.mute_all {351
let _ = handle.commands.send(CallCommand::MuteAll);352
}353
if arguments.captions {354
features.captions_requested = true;355
let _ = handle.commands.send(CallCommand::SetCaptions(true));356
}357
if arguments.blur {358
let _ = handle.commands.send(CallCommand::SetBlur(true));359
}243
if arguments.share {360
if arguments.share {244
let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };361
let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };245
let _ = handle.commands.send(CallCommand::StartShare(source));362
let _ = handle.commands.send(CallCommand::StartShare(source));@@ -264,7 +381,7 @@ async fn main() {264
}381
}265
let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())382
let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())266
&& join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;383
&& join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;267
if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file {384
if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file && !features.pending(&arguments) {268
println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");385
println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");269
let _ = handle.commands.send(CallCommand::EndMeeting);386
let _ = handle.commands.send(CallCommand::EndMeeting);270
end_sent_at = Some(Instant::now());387
end_sent_at = Some(Instant::now());@@ -283,6 +400,16 @@ async fn main() {283
Reaction::ALL.len()400
Reaction::ALL.len()284
);401
);285
}402
}403
if arguments.spotlight_self {404
println!("# spotlight self: shown {}, cleared {}", features.spotlight_seen, features.spotlight_cleared);405
}406
if arguments.captions {407
println!("# captions: became active {}, caption events {}", features.captions_active, features.caption_events);408
}409
if arguments.blur {410
let average = if features.blur_reports == 0 { 0. } else { features.blur_total_ms / features.blur_reports as f64 };411
println!("# blur: average processing {average:.1} ms over {} report(s)", features.blur_reports);412
}286
let gone_started = Instant::now();413
let gone_started = Instant::now();287
let mut gone_after = None;414
let mut gone_after = None;288
while gone_started.elapsed() < GONE_LIMIT {415
while gone_started.elapsed() < GONE_LIMIT {@@ -0,0 +1,431 @@
1
use std::io::Cursor;
2
use std::sync::Arc;
3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
4
use std::time::{Duration, Instant};
5
6
use libwebrtc::native::yuv_helper::i420_to_abgr;
7
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
8
use tract_onnx::prelude::*;
9
10
use crate::camera::i420_from_rgba;
11
use crate::error::{Error, Result};
12
13
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
14
pub const MASK_WIDTH: usize = 256;
15
pub const MASK_HEIGHT: usize = 144;
16
const CHANNELS: usize = 4;
17
const BACKGROUND_SCALE: usize = 4;
18
const BLUR_RADIUS: usize = 3;
19
const BLUR_PASSES: usize = 2;
20
const EDGE_LOW: f32 = 0.3;
21
const EDGE_HIGH: f32 = 0.7;
22
const OPAQUE: f32 = 0.985;
23
const MASK_SMOOTHING: f32 = 0.35;
24
const SLOW_INFERENCE: Duration = Duration::from_millis(22);
25
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
26
const AVERAGE_WEIGHT: f64 = 0.1;
27
const MAX_BANDS: usize = 4;
28
29
type Plan = std::sync::Arc<TypedRunnableModel>;
30
31
/// MediaPipe selfie segmentation (landscape, 256x144); answers the probability of "person" per mask pixel.
32
pub struct Segmenter {
33
plan: Plan,
34
}
35
36
impl Segmenter {
37
pub fn new() -> Result<Self> {
38
let plan = Self::load().map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?;
39
Ok(Segmenter { plan })
40
}
41
42
fn load() -> TractResult<Plan> {
43
let model = tract_onnx::onnx().model_for_read(&mut Cursor::new(MODEL))?;
44
let batch = model.symbols.sym("batch_size");
45
let one_image = std::collections::HashMap::from([(batch, TDim::from(1))]);
46
model.into_typed()?.set_symbols(&one_image)?.into_optimized()?.into_runnable()
47
}
48
49
pub fn mask(&self, rgba: &[u8], width: usize, height: usize) -> Result<Vec<f32>> {
50
let input = model_input(rgba, width, height);
51
let outputs = self.plan.run(tvec!(input.into())).map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?;
52
let values = outputs[0].to_plain_array_view::<f32>().map_err(|error| Error::Webrtc(format!("segmentation output: {error}")))?;
53
if values.len() != MASK_WIDTH * MASK_HEIGHT {
54
return Err(Error::Webrtc(format!("segmentation output has {} values", values.len())));
55
}
56
Ok(values.iter().map(|value| value.clamp(0., 1.)).collect())
57
}
58
}
59
60
fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {
61
let plane = MASK_WIDTH * MASK_HEIGHT;
62
let mut data = vec![0f32; 3 * plane];
63
for row in 0..MASK_HEIGHT {
64
let top = (row * 2 * height / (MASK_HEIGHT * 2)).min(height - 1);
65
let bottom = ((row * 2 + 1) * height / (MASK_HEIGHT * 2)).min(height - 1);
66
for column in 0..MASK_WIDTH {
67
let left = (column * 2 * width / (MASK_WIDTH * 2)).min(width - 1);
68
let right = ((column * 2 + 1) * width / (MASK_WIDTH * 2)).min(width - 1);
69
for channel in 0..3 {
70
let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)]
71
.iter()
72
.map(|&(y, x)| u32::from(rgba[(y * width + x) * CHANNELS + channel]))
73
.sum();
74
data[channel * plane + row * MASK_WIDTH + column] = sum as f32 / (4. * 255.);
75
}
76
}
77
}
78
Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
79
}
80
81
fn smoothstep(value: f32) -> f32 {
82
let t = ((value - EDGE_LOW) / (EDGE_HIGH - EDGE_LOW)).clamp(0., 1.);
83
t * t * (3. - 2. * t)
84
}
85
86
struct Axis {
87
first: Vec<usize>,
88
second: Vec<usize>,
89
weight: Vec<f32>,
90
}
91
92
fn axis(output: usize, input: usize) -> Axis {
93
let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };
94
for index in 0..output {
95
let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);
96
let first = position.floor() as usize;
97
axis.first.push(first);
98
axis.second.push((first + 1).min(input - 1));
99
axis.weight.push(position - first as f32);
100
}
101
axis
102
}
103
104
fn downscaled(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
105
let small_width = width.div_ceil(BACKGROUND_SCALE);
106
let small_height = height.div_ceil(BACKGROUND_SCALE);
107
let mut small = vec![0u8; small_width * small_height * 3];
108
for row in 0..small_height {
109
for column in 0..small_width {
110
let mut sums = [0u32; 3];
111
let mut count = 0u32;
112
for y in row * BACKGROUND_SCALE..((row + 1) * BACKGROUND_SCALE).min(height) {
113
for x in column * BACKGROUND_SCALE..((column + 1) * BACKGROUND_SCALE).min(width) {
114
for (channel, sum) in sums.iter_mut().enumerate() {
115
*sum += u32::from(rgba[(y * width + x) * CHANNELS + channel]);
116
}
117
count += 1;
118
}
119
}
120
for (channel, sum) in sums.iter().enumerate() {
121
small[(row * small_width + column) * 3 + channel] = (sum / count) as u8;
122
}
123
}
124
}
125
(small, small_width, small_height)
126
}
127
128
fn blur_pass(input: &[u8], output: &mut [u8], lines: usize, length: usize, line_stride: usize, step: usize) {
129
let radius = BLUR_RADIUS as isize;
130
let window = (BLUR_RADIUS * 2 + 1) as u32;
131
for line in 0..lines {
132
for channel in 0..3 {
133
let base = line * line_stride + channel;
134
let read = |index: isize| u32::from(input[base + index.clamp(0, length as isize - 1) as usize * step]);
135
let mut sum: u32 = (-radius..=radius).map(read).sum();
136
for index in 0..length {
137
output[base + index * step] = (sum / window) as u8;
138
sum = sum + read(index as isize + radius + 1) - read(index as isize - radius);
139
}
140
}
141
}
142
}
143
144
fn box_blur(image: &mut [u8], width: usize, height: usize, scratch: &mut [u8]) {
145
blur_pass(image, scratch, height, width, width * 3, 3);
146
blur_pass(scratch, image, width, height, 3, width * 3);
147
}
148
149
fn blurred_background(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
150
let (mut small, small_width, small_height) = downscaled(rgba, width, height);
151
let mut scratch = vec![0u8; small.len()];
152
for _ in 0..BLUR_PASSES {
153
box_blur(&mut small, small_width, small_height, &mut scratch);
154
}
155
(small, small_width, small_height)
156
}
157
158
struct Composer<'a> {
159
background: &'a [u8],
160
mask: &'a [f32],
161
width: usize,
162
mask_x: Axis,
163
mask_y: Axis,
164
small_x: Axis,
165
small_y: Axis,
166
small_width: usize,
167
}
168
169
impl Composer<'_> {
170
fn rows(&self, rgba: &mut [u8], first_row: usize) {
171
for (offset, line) in rgba.chunks_exact_mut(self.width * CHANNELS).enumerate() {
172
self.row(line, first_row + offset);
173
}
174
}
175
176
fn row(&self, line: &mut [u8], row: usize) {
177
let (mask_top, mask_bottom, mask_fraction) = (self.mask_y.first[row] * MASK_WIDTH, self.mask_y.second[row] * MASK_WIDTH, self.mask_y.weight[row]);
178
let (small_top, small_bottom, small_fraction) = (self.small_y.first[row] * self.small_width, self.small_y.second[row] * self.small_width, self.small_y.weight[row]);
179
for (column, pixel) in line.as_chunks_mut::<CHANNELS>().0.iter_mut().enumerate() {
180
let (left, right, across) = (self.mask_x.first[column], self.mask_x.second[column], self.mask_x.weight[column]);
181
let top = self.mask[mask_top + left] * (1. - across) + self.mask[mask_top + right] * across;
182
let bottom = self.mask[mask_bottom + left] * (1. - across) + self.mask[mask_bottom + right] * across;
183
let person = smoothstep(top * (1. - mask_fraction) + bottom * mask_fraction);
184
if person >= OPAQUE {
185
continue;
186
}
187
let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);
188
for (channel, value) in pixel.iter_mut().take(3).enumerate() {
189
let sample = |line: usize, index: usize| f32::from(self.background[(line + index) * 3 + channel]);
190
let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;
191
let lower = sample(small_bottom, left) * (1. - across) + sample(small_bottom, right) * across;
192
let blurred = upper * (1. - small_fraction) + lower * small_fraction;
193
*value = (f32::from(*value) * person + blurred * (1. - person) + 0.5) as u8;
194
}
195
}
196
}
197
}
198
199
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.
200
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
201
let (background, small_width, small_height) = blurred_background(rgba, width, height);
202
let composer = Composer {
203
background: &background,
204
mask,
205
width,
206
mask_x: axis(width, MASK_WIDTH),
207
mask_y: axis(height, MASK_HEIGHT),
208
small_x: axis(width, small_width),
209
small_y: axis(height, small_height),
210
small_width,
211
};
212
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
213
let rows_per_band = height.div_ceil(bands);
214
std::thread::scope(|scope| {
215
for (index, band) in rgba.chunks_mut(rows_per_band * width * CHANNELS).enumerate() {
216
let composer = &composer;
217
scope.spawn(move || composer.rows(band, index * rows_per_band));
218
}
219
});
220
}
221
222
/// Shared between the UI command and the camera thread.
223
#[derive(Default)]
224
pub struct BlurSettings {
225
enabled: AtomicBool,
226
average_micros: AtomicU32,
227
}
228
229
impl BlurSettings {
230
pub fn set_enabled(&self, enabled: bool) {
231
self.enabled.store(enabled, Ordering::Relaxed);
232
}
233
234
pub fn enabled(&self) -> bool {
235
self.enabled.load(Ordering::Relaxed)
236
}
237
238
pub fn average_ms(&self) -> f32 {
239
self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
240
}
241
}
242
243
/// Runs on the capture thread; loads the model on first use and stays out of the way while the setting is off.
244
pub struct BlurStage {
245
settings: Arc<BlurSettings>,
246
blur: Option<BackgroundBlur>,
247
unavailable: bool,
248
}
249
250
impl BlurStage {
251
pub fn new(settings: Arc<BlurSettings>) -> Self {
252
BlurStage { settings, blur: None, unavailable: false }
253
}
254
255
pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {
256
if !self.settings.enabled() || self.unavailable {
257
return;
258
}
259
if self.blur.is_none() {
260
match BackgroundBlur::new() {
261
Ok(blur) => self.blur = Some(blur),
262
Err(_) => {
263
self.unavailable = true;
264
return;
265
}
266
}
267
}
268
if let Some(blur) = self.blur.as_mut() {
269
blur.apply(rgba, width, height);
270
self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);
271
}
272
}
273
274
pub fn apply_i420(&mut self, buffer: I420Buffer) -> I420Buffer {
275
if !self.settings.enabled() || self.unavailable {
276
return buffer;
277
}
278
let (width, height) = (buffer.width() as usize, buffer.height() as usize);
279
let (stride_y, stride_u, stride_v) = buffer.strides();
280
let (plane_y, plane_u, plane_v) = buffer.data();
281
let mut rgba = vec![0u8; width * height * CHANNELS];
282
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * CHANNELS) as u32, width as i32, height as i32);
283
self.apply_rgba(&mut rgba, width, height);
284
i420_from_rgba(&rgba, width as u32, height as u32)
285
}
286
}
287
288
/// Background blur for camera frames: segments every `stride` frames and slows down when inference is slow.
289
pub struct BackgroundBlur {
290
segmenter: Segmenter,
291
mask: Vec<f32>,
292
frames: u64,
293
stride: u64,
294
average_ms: f64,
295
processed: u64,
296
}
297
298
impl BackgroundBlur {
299
pub fn new() -> Result<Self> {
300
Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })
301
}
302
303
pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize) {
304
let started = Instant::now();
305
if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {
306
self.segment(rgba, width, height, started);
307
}
308
self.frames += 1;
309
compose(rgba, width, height, &self.mask);
310
let elapsed = started.elapsed().as_secs_f64() * 1000.;
311
self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };
312
self.processed += 1;
313
}
314
315
fn segment(&mut self, rgba: &[u8], width: usize, height: usize, started: Instant) {
316
let Ok(fresh) = self.segmenter.mask(rgba, width, height) else {
317
return;
318
};
319
let inference = started.elapsed();
320
self.stride = if inference > VERY_SLOW_INFERENCE {
321
3
322
} else if inference > SLOW_INFERENCE {
323
2
324
} else {
325
1
326
};
327
if self.mask.is_empty() {
328
self.mask = fresh;
329
return;
330
}
331
for (current, new) in self.mask.iter_mut().zip(fresh) {
332
*current += (new - *current) * (1. - MASK_SMOOTHING);
333
}
334
}
335
336
pub fn average_ms(&self) -> f64 {
337
self.average_ms
338
}
339
}
340
341
#[cfg(test)]
342
mod tests {
343
use super::*;
344
345
const WIDTH: usize = 160;
346
const HEIGHT: usize = 90;
347
348
fn checkerboard() -> Vec<u8> {
349
let mut rgba = vec![255u8; WIDTH * HEIGHT * CHANNELS];
350
for row in 0..HEIGHT {
351
for column in 0..WIDTH {
352
let value = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 };
353
rgba[(row * WIDTH + column) * CHANNELS..][..3].fill(value);
354
}
355
}
356
rgba
357
}
358
359
fn oval_mask() -> Vec<f32> {
360
(0..MASK_WIDTH * MASK_HEIGHT)
361
.map(|index| {
362
let (x, y) = ((index % MASK_WIDTH) as f32 / MASK_WIDTH as f32 - 0.5, (index / MASK_WIDTH) as f32 / MASK_HEIGHT as f32 - 0.5);
363
if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
364
})
365
.collect()
366
}
367
368
fn pixel(rgba: &[u8], x: usize, y: usize) -> u8 {
369
rgba[(y * WIDTH + x) * CHANNELS]
370
}
371
372
fn roughness(rgba: &[u8], x: usize, y: usize) -> i32 {
373
(0..8).map(|step| (i32::from(pixel(rgba, x + step + 1, y)) - i32::from(pixel(rgba, x + step, y))).abs()).sum()
374
}
375
376
#[test]
377
fn the_person_stays_sharp_and_the_background_is_smoothed() {
378
let original = checkerboard();
379
let mut blurred = original.clone();
380
compose(&mut blurred, WIDTH, HEIGHT, &oval_mask());
381
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
382
assert_eq!(pixel(&blurred, center_x, center_y), pixel(&original, center_x, center_y));
383
assert_eq!(roughness(&blurred, center_x - 4, center_y), roughness(&original, center_x - 4, center_y));
384
assert!(roughness(&blurred, 2, 2) * 4 < roughness(&original, 2, 2));
385
assert!(roughness(&blurred, WIDTH - 12, HEIGHT - 3) * 4 < roughness(&original, WIDTH - 12, HEIGHT - 3));
386
}
387
388
#[test]
389
fn the_edge_between_person_and_background_is_feathered() {
390
let original = checkerboard();
391
let mut blurred = original.clone();
392
let mut mask = oval_mask();
393
compose(&mut blurred, WIDTH, HEIGHT, &mask);
394
let edge_row = HEIGHT / 2;
395
let changed_steps = (0..WIDTH - 1)
396
.filter(|&x| pixel(&blurred, x, edge_row) != pixel(&original, x, edge_row) && pixel(&blurred, x + 1, edge_row) == pixel(&original, x + 1, edge_row))
397
.count();
398
assert!(changed_steps <= 2, "a hard seam shows as one switch per side");
399
mask.fill(1.);
400
let mut untouched = original.clone();
401
compose(&mut untouched, WIDTH, HEIGHT, &mask);
402
assert_eq!(untouched, original);
403
}
404
405
#[test]
406
fn an_empty_mask_blurs_the_whole_frame() {
407
let original = checkerboard();
408
let mut blurred = original.clone();
409
compose(&mut blurred, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT]);
410
assert!(roughness(&blurred, 70, 40) * 4 < roughness(&original, 70, 40));
411
assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));
412
}
413
414
#[test]
415
fn the_model_answers_one_probability_per_mask_pixel() {
416
let segmenter = Segmenter::new().expect("model loads");
417
let mask = segmenter.mask(&checkerboard(), WIDTH, HEIGHT).expect("inference runs");
418
assert_eq!(mask.len(), MASK_WIDTH * MASK_HEIGHT);
419
assert!(mask.iter().all(|value| (0. ..=1.).contains(value)));
420
}
421
422
#[test]
423
fn the_blur_keeps_a_running_average_and_a_mask() {
424
let mut blur = BackgroundBlur::new().expect("model loads");
425
let mut frame = checkerboard();
426
blur.apply(&mut frame, WIDTH, HEIGHT);
427
blur.apply(&mut frame, WIDTH, HEIGHT);
428
assert!(blur.average_ms() > 0.);
429
assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);
430
}
431
}
@@ -0,0 +1,431 @@1
use std::io::Cursor;2
use std::sync::Arc;3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};4
use std::time::{Duration, Instant};5
6
use libwebrtc::native::yuv_helper::i420_to_abgr;7
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};8
use tract_onnx::prelude::*;9
10
use crate::camera::i420_from_rgba;11
use crate::error::{Error, Result};12
13
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");14
pub const MASK_WIDTH: usize = 256;15
pub const MASK_HEIGHT: usize = 144;16
const CHANNELS: usize = 4;17
const BACKGROUND_SCALE: usize = 4;18
const BLUR_RADIUS: usize = 3;19
const BLUR_PASSES: usize = 2;20
const EDGE_LOW: f32 = 0.3;21
const EDGE_HIGH: f32 = 0.7;22
const OPAQUE: f32 = 0.985;23
const MASK_SMOOTHING: f32 = 0.35;24
const SLOW_INFERENCE: Duration = Duration::from_millis(22);25
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);26
const AVERAGE_WEIGHT: f64 = 0.1;27
const MAX_BANDS: usize = 4;28
29
type Plan = std::sync::Arc<TypedRunnableModel>;30
31
/// MediaPipe selfie segmentation (landscape, 256x144); answers the probability of "person" per mask pixel.32
pub struct Segmenter {33
plan: Plan,34
}35
36
impl Segmenter {37
pub fn new() -> Result<Self> {38
let plan = Self::load().map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?;39
Ok(Segmenter { plan })40
}41
42
fn load() -> TractResult<Plan> {43
let model = tract_onnx::onnx().model_for_read(&mut Cursor::new(MODEL))?;44
let batch = model.symbols.sym("batch_size");45
let one_image = std::collections::HashMap::from([(batch, TDim::from(1))]);46
model.into_typed()?.set_symbols(&one_image)?.into_optimized()?.into_runnable()47
}48
49
pub fn mask(&self, rgba: &[u8], width: usize, height: usize) -> Result<Vec<f32>> {50
let input = model_input(rgba, width, height);51
let outputs = self.plan.run(tvec!(input.into())).map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?;52
let values = outputs[0].to_plain_array_view::<f32>().map_err(|error| Error::Webrtc(format!("segmentation output: {error}")))?;53
if values.len() != MASK_WIDTH * MASK_HEIGHT {54
return Err(Error::Webrtc(format!("segmentation output has {} values", values.len())));55
}56
Ok(values.iter().map(|value| value.clamp(0., 1.)).collect())57
}58
}59
60
fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {61
let plane = MASK_WIDTH * MASK_HEIGHT;62
let mut data = vec![0f32; 3 * plane];63
for row in 0..MASK_HEIGHT {64
let top = (row * 2 * height / (MASK_HEIGHT * 2)).min(height - 1);65
let bottom = ((row * 2 + 1) * height / (MASK_HEIGHT * 2)).min(height - 1);66
for column in 0..MASK_WIDTH {67
let left = (column * 2 * width / (MASK_WIDTH * 2)).min(width - 1);68
let right = ((column * 2 + 1) * width / (MASK_WIDTH * 2)).min(width - 1);69
for channel in 0..3 {70
let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)]71
.iter()72
.map(|&(y, x)| u32::from(rgba[(y * width + x) * CHANNELS + channel]))73
.sum();74
data[channel * plane + row * MASK_WIDTH + column] = sum as f32 / (4. * 255.);75
}76
}77
}78
Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")79
}80
81
fn smoothstep(value: f32) -> f32 {82
let t = ((value - EDGE_LOW) / (EDGE_HIGH - EDGE_LOW)).clamp(0., 1.);83
t * t * (3. - 2. * t)84
}85
86
struct Axis {87
first: Vec<usize>,88
second: Vec<usize>,89
weight: Vec<f32>,90
}91
92
fn axis(output: usize, input: usize) -> Axis {93
let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };94
for index in 0..output {95
let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);96
let first = position.floor() as usize;97
axis.first.push(first);98
axis.second.push((first + 1).min(input - 1));99
axis.weight.push(position - first as f32);100
}101
axis102
}103
104
fn downscaled(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {105
let small_width = width.div_ceil(BACKGROUND_SCALE);106
let small_height = height.div_ceil(BACKGROUND_SCALE);107
let mut small = vec![0u8; small_width * small_height * 3];108
for row in 0..small_height {109
for column in 0..small_width {110
let mut sums = [0u32; 3];111
let mut count = 0u32;112
for y in row * BACKGROUND_SCALE..((row + 1) * BACKGROUND_SCALE).min(height) {113
for x in column * BACKGROUND_SCALE..((column + 1) * BACKGROUND_SCALE).min(width) {114
for (channel, sum) in sums.iter_mut().enumerate() {115
*sum += u32::from(rgba[(y * width + x) * CHANNELS + channel]);116
}117
count += 1;118
}119
}120
for (channel, sum) in sums.iter().enumerate() {121
small[(row * small_width + column) * 3 + channel] = (sum / count) as u8;122
}123
}124
}125
(small, small_width, small_height)126
}127
128
fn blur_pass(input: &[u8], output: &mut [u8], lines: usize, length: usize, line_stride: usize, step: usize) {129
let radius = BLUR_RADIUS as isize;130
let window = (BLUR_RADIUS * 2 + 1) as u32;131
for line in 0..lines {132
for channel in 0..3 {133
let base = line * line_stride + channel;134
let read = |index: isize| u32::from(input[base + index.clamp(0, length as isize - 1) as usize * step]);135
let mut sum: u32 = (-radius..=radius).map(read).sum();136
for index in 0..length {137
output[base + index * step] = (sum / window) as u8;138
sum = sum + read(index as isize + radius + 1) - read(index as isize - radius);139
}140
}141
}142
}143
144
fn box_blur(image: &mut [u8], width: usize, height: usize, scratch: &mut [u8]) {145
blur_pass(image, scratch, height, width, width * 3, 3);146
blur_pass(scratch, image, width, height, 3, width * 3);147
}148
149
fn blurred_background(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {150
let (mut small, small_width, small_height) = downscaled(rgba, width, height);151
let mut scratch = vec![0u8; small.len()];152
for _ in 0..BLUR_PASSES {153
box_blur(&mut small, small_width, small_height, &mut scratch);154
}155
(small, small_width, small_height)156
}157
158
struct Composer<'a> {159
background: &'a [u8],160
mask: &'a [f32],161
width: usize,162
mask_x: Axis,163
mask_y: Axis,164
small_x: Axis,165
small_y: Axis,166
small_width: usize,167
}168
169
impl Composer<'_> {170
fn rows(&self, rgba: &mut [u8], first_row: usize) {171
for (offset, line) in rgba.chunks_exact_mut(self.width * CHANNELS).enumerate() {172
self.row(line, first_row + offset);173
}174
}175
176
fn row(&self, line: &mut [u8], row: usize) {177
let (mask_top, mask_bottom, mask_fraction) = (self.mask_y.first[row] * MASK_WIDTH, self.mask_y.second[row] * MASK_WIDTH, self.mask_y.weight[row]);178
let (small_top, small_bottom, small_fraction) = (self.small_y.first[row] * self.small_width, self.small_y.second[row] * self.small_width, self.small_y.weight[row]);179
for (column, pixel) in line.as_chunks_mut::<CHANNELS>().0.iter_mut().enumerate() {180
let (left, right, across) = (self.mask_x.first[column], self.mask_x.second[column], self.mask_x.weight[column]);181
let top = self.mask[mask_top + left] * (1. - across) + self.mask[mask_top + right] * across;182
let bottom = self.mask[mask_bottom + left] * (1. - across) + self.mask[mask_bottom + right] * across;183
let person = smoothstep(top * (1. - mask_fraction) + bottom * mask_fraction);184
if person >= OPAQUE {185
continue;186
}187
let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);188
for (channel, value) in pixel.iter_mut().take(3).enumerate() {189
let sample = |line: usize, index: usize| f32::from(self.background[(line + index) * 3 + channel]);190
let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;191
let lower = sample(small_bottom, left) * (1. - across) + sample(small_bottom, right) * across;192
let blurred = upper * (1. - small_fraction) + lower * small_fraction;193
*value = (f32::from(*value) * person + blurred * (1. - person) + 0.5) as u8;194
}195
}196
}197
}198
199
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.200
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {201
let (background, small_width, small_height) = blurred_background(rgba, width, height);202
let composer = Composer {203
background: &background,204
mask,205
width,206
mask_x: axis(width, MASK_WIDTH),207
mask_y: axis(height, MASK_HEIGHT),208
small_x: axis(width, small_width),209
small_y: axis(height, small_height),210
small_width,211
};212
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);213
let rows_per_band = height.div_ceil(bands);214
std::thread::scope(|scope| {215
for (index, band) in rgba.chunks_mut(rows_per_band * width * CHANNELS).enumerate() {216
let composer = &composer;217
scope.spawn(move || composer.rows(band, index * rows_per_band));218
}219
});220
}221
222
/// Shared between the UI command and the camera thread.223
#[derive(Default)]224
pub struct BlurSettings {225
enabled: AtomicBool,226
average_micros: AtomicU32,227
}228
229
impl BlurSettings {230
pub fn set_enabled(&self, enabled: bool) {231
self.enabled.store(enabled, Ordering::Relaxed);232
}233
234
pub fn enabled(&self) -> bool {235
self.enabled.load(Ordering::Relaxed)236
}237
238
pub fn average_ms(&self) -> f32 {239
self.average_micros.load(Ordering::Relaxed) as f32 / 1000.240
}241
}242
243
/// Runs on the capture thread; loads the model on first use and stays out of the way while the setting is off.244
pub struct BlurStage {245
settings: Arc<BlurSettings>,246
blur: Option<BackgroundBlur>,247
unavailable: bool,248
}249
250
impl BlurStage {251
pub fn new(settings: Arc<BlurSettings>) -> Self {252
BlurStage { settings, blur: None, unavailable: false }253
}254
255
pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {256
if !self.settings.enabled() || self.unavailable {257
return;258
}259
if self.blur.is_none() {260
match BackgroundBlur::new() {261
Ok(blur) => self.blur = Some(blur),262
Err(_) => {263
self.unavailable = true;264
return;265
}266
}267
}268
if let Some(blur) = self.blur.as_mut() {269
blur.apply(rgba, width, height);270
self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);271
}272
}273
274
pub fn apply_i420(&mut self, buffer: I420Buffer) -> I420Buffer {275
if !self.settings.enabled() || self.unavailable {276
return buffer;277
}278
let (width, height) = (buffer.width() as usize, buffer.height() as usize);279
let (stride_y, stride_u, stride_v) = buffer.strides();280
let (plane_y, plane_u, plane_v) = buffer.data();281
let mut rgba = vec![0u8; width * height * CHANNELS];282
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * CHANNELS) as u32, width as i32, height as i32);283
self.apply_rgba(&mut rgba, width, height);284
i420_from_rgba(&rgba, width as u32, height as u32)285
}286
}287
288
/// Background blur for camera frames: segments every `stride` frames and slows down when inference is slow.289
pub struct BackgroundBlur {290
segmenter: Segmenter,291
mask: Vec<f32>,292
frames: u64,293
stride: u64,294
average_ms: f64,295
processed: u64,296
}297
298
impl BackgroundBlur {299
pub fn new() -> Result<Self> {300
Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })301
}302
303
pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize) {304
let started = Instant::now();305
if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {306
self.segment(rgba, width, height, started);307
}308
self.frames += 1;309
compose(rgba, width, height, &self.mask);310
let elapsed = started.elapsed().as_secs_f64() * 1000.;311
self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };312
self.processed += 1;313
}314
315
fn segment(&mut self, rgba: &[u8], width: usize, height: usize, started: Instant) {316
let Ok(fresh) = self.segmenter.mask(rgba, width, height) else {317
return;318
};319
let inference = started.elapsed();320
self.stride = if inference > VERY_SLOW_INFERENCE {321
3322
} else if inference > SLOW_INFERENCE {323
2324
} else {325
1326
};327
if self.mask.is_empty() {328
self.mask = fresh;329
return;330
}331
for (current, new) in self.mask.iter_mut().zip(fresh) {332
*current += (new - *current) * (1. - MASK_SMOOTHING);333
}334
}335
336
pub fn average_ms(&self) -> f64 {337
self.average_ms338
}339
}340
341
#[cfg(test)]342
mod tests {343
use super::*;344
345
const WIDTH: usize = 160;346
const HEIGHT: usize = 90;347
348
fn checkerboard() -> Vec<u8> {349
let mut rgba = vec![255u8; WIDTH * HEIGHT * CHANNELS];350
for row in 0..HEIGHT {351
for column in 0..WIDTH {352
let value = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 };353
rgba[(row * WIDTH + column) * CHANNELS..][..3].fill(value);354
}355
}356
rgba357
}358
359
fn oval_mask() -> Vec<f32> {360
(0..MASK_WIDTH * MASK_HEIGHT)361
.map(|index| {362
let (x, y) = ((index % MASK_WIDTH) as f32 / MASK_WIDTH as f32 - 0.5, (index / MASK_WIDTH) as f32 / MASK_HEIGHT as f32 - 0.5);363
if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }364
})365
.collect()366
}367
368
fn pixel(rgba: &[u8], x: usize, y: usize) -> u8 {369
rgba[(y * WIDTH + x) * CHANNELS]370
}371
372
fn roughness(rgba: &[u8], x: usize, y: usize) -> i32 {373
(0..8).map(|step| (i32::from(pixel(rgba, x + step + 1, y)) - i32::from(pixel(rgba, x + step, y))).abs()).sum()374
}375
376
#[test]377
fn the_person_stays_sharp_and_the_background_is_smoothed() {378
let original = checkerboard();379
let mut blurred = original.clone();380
compose(&mut blurred, WIDTH, HEIGHT, &oval_mask());381
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);382
assert_eq!(pixel(&blurred, center_x, center_y), pixel(&original, center_x, center_y));383
assert_eq!(roughness(&blurred, center_x - 4, center_y), roughness(&original, center_x - 4, center_y));384
assert!(roughness(&blurred, 2, 2) * 4 < roughness(&original, 2, 2));385
assert!(roughness(&blurred, WIDTH - 12, HEIGHT - 3) * 4 < roughness(&original, WIDTH - 12, HEIGHT - 3));386
}387
388
#[test]389
fn the_edge_between_person_and_background_is_feathered() {390
let original = checkerboard();391
let mut blurred = original.clone();392
let mut mask = oval_mask();393
compose(&mut blurred, WIDTH, HEIGHT, &mask);394
let edge_row = HEIGHT / 2;395
let changed_steps = (0..WIDTH - 1)396
.filter(|&x| pixel(&blurred, x, edge_row) != pixel(&original, x, edge_row) && pixel(&blurred, x + 1, edge_row) == pixel(&original, x + 1, edge_row))397
.count();398
assert!(changed_steps <= 2, "a hard seam shows as one switch per side");399
mask.fill(1.);400
let mut untouched = original.clone();401
compose(&mut untouched, WIDTH, HEIGHT, &mask);402
assert_eq!(untouched, original);403
}404
405
#[test]406
fn an_empty_mask_blurs_the_whole_frame() {407
let original = checkerboard();408
let mut blurred = original.clone();409
compose(&mut blurred, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT]);410
assert!(roughness(&blurred, 70, 40) * 4 < roughness(&original, 70, 40));411
assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));412
}413
414
#[test]415
fn the_model_answers_one_probability_per_mask_pixel() {416
let segmenter = Segmenter::new().expect("model loads");417
let mask = segmenter.mask(&checkerboard(), WIDTH, HEIGHT).expect("inference runs");418
assert_eq!(mask.len(), MASK_WIDTH * MASK_HEIGHT);419
assert!(mask.iter().all(|value| (0. ..=1.).contains(value)));420
}421
422
#[test]423
fn the_blur_keeps_a_running_average_and_a_mask() {424
let mut blur = BackgroundBlur::new().expect("model loads");425
let mut frame = checkerboard();426
blur.apply(&mut frame, WIDTH, HEIGHT);427
blur.apply(&mut frame, WIDTH, HEIGHT);428
assert!(blur.average_ms() > 0.);429
assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);430
}431
}@@ -7,6 +7,7 @@ use std::time::Duration;
7
7
use chatsvc::TrouterCallback;
8
8
use futures_util::StreamExt;
9
9
use libwebrtc::audio_stream::native::NativeAudioStream;
10
use libwebrtc::data_channel::{DataChannel, DataChannelInit};
10
11
use libwebrtc::prelude::*;
11
12
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
12
13
use libwebrtc::session_description::{SdpType, SessionDescription};
@@ -18,6 +19,8 @@ use tokio::time::{Instant, interval, sleep_until, timeout};
18
19
19
20
use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
20
21
use crate::audio_io::{AudioMode, AudioSetup};
22
use crate::captions::{CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, BotAction, parse_caption_message};
23
use crate::data_channel::Depacketizer;
21
24
use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
22
25
use crate::devices::{self, DeviceChoice};
23
26
use crate::end::EndKind;
@@ -28,6 +31,7 @@ use crate::push::CallNotification;
28
31
use crate::share_audio::ShareAudio;
29
32
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
30
33
use crate::renegotiation::{MediaAction, MediaNegotiator};
34
use crate::organizer::Target;
31
35
use crate::roster::Roster;
32
36
use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
33
37
use crate::signaling::{
@@ -55,6 +59,11 @@ const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
55
59
const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
56
60
const KEEP_ALIVE_FRACTION: f64 = 0.9;
57
61
const MIC_STREAM: &str = "microphone";
62
const DATA_CHANNEL_LABEL: &str = "main-channel";
63
pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";
64
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);
65
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
66
const BOT_PREFIX: &str = "28:";
58
67
59
68
#[derive(Debug, Clone)]
60
69
pub struct CallOptions {
@@ -73,6 +82,7 @@ pub struct CallOptions {
73
82
pub wav_path: Option<PathBuf>,
74
83
pub sdp_dump_dir: Option<PathBuf>,
75
84
pub trace: bool,
85
pub data_channel: bool,
76
86
}
77
87
78
88
impl Default for CallOptions {
@@ -93,6 +103,7 @@ impl Default for CallOptions {
93
103
wav_path: None,
94
104
sdp_dump_dir: None,
95
105
trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),
106
data_channel: data_channel_from_env(),
96
107
}
97
108
}
98
109
}
@@ -185,6 +196,10 @@ pub(crate) enum Plan {
185
196
Incoming(Box<IncomingCall>),
186
197
}
187
198
199
fn data_channel_from_env() -> bool {
200
!matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))
201
}
202
188
203
pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
189
204
let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
190
205
Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
@@ -207,11 +222,13 @@ enum PeerEvent {
207
222
Connection(PeerConnectionState),
208
223
Track(RtcAudioTrack),
209
224
VideoTrack { mid: String, track: RtcVideoTrack },
225
Data(Vec<u8>),
210
226
}
211
227
212
228
struct PeerSession {
213
229
peer: PeerConnection,
214
230
events: mpsc::UnboundedReceiver<PeerEvent>,
231
_data_channel: Option<DataChannel>,
215
232
}
216
233
217
234
struct OfferedMedia {
@@ -334,13 +351,14 @@ impl CallEngine {
334
351
}
335
352
}
336
353
337
fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str) -> Result<PeerSession> {
354
fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {
338
355
let mut configuration = RtcConfiguration::default();
339
356
configuration.ice_servers = vec![grant.ice_server(relay_host)];
340
357
let peer = factory
341
358
.create_peer_connection(configuration)
342
359
.map_err(|error| Error::Webrtc(error.to_string()))?;
343
360
let (sender, events) = mpsc::unbounded_channel();
361
let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
344
362
let ice_sender = sender.clone();
345
363
peer.on_ice_connection_state_change(Some(Box::new(move |state| {
346
364
let _ = ice_sender.send(PeerEvent::Ice(state));
@@ -358,7 +376,17 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
358
376
let _ = sender.send(PeerEvent::VideoTrack { mid, track });
359
377
}
360
378
})));
361
Ok(PeerSession { peer, events })
379
Ok(PeerSession { peer, events, _data_channel: data_channel })
380
}
381
382
fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
383
let channel = peer
384
.create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
385
.map_err(|error| Error::Webrtc(error.to_string()))?;
386
channel.on_message(Some(Box::new(move |buffer| {
387
let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));
388
})));
389
Ok(channel)
362
390
}
363
391
364
392
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack) -> Result<OfferedMedia> {
@@ -500,7 +528,8 @@ async fn drive(
500
528
control.send(CallUpdate::Cameras(camera_devices(options.video).await));
501
529
refresh_share_sources(control.updates(), options.video);
502
530
503
let mut current = open_peer(&factory, &grant, &options.relay_host)?;
531
let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
532
let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
504
533
live.peers.push(current.peer.clone());
505
534
506
535
let signaling = Arc::new(inner.signaling(timeline.clone()));
@@ -633,6 +662,9 @@ async fn drive(
633
662
let mut share_sound_wanted = false;
634
663
let mut remote_audio: Option<RtcAudioTrack> = None;
635
664
let mut own_hand: Option<String> = None;
665
let mut depacketizer = Depacketizer::default();
666
let mut caption_flow = CaptionFlow::default();
667
let mut caption_deadline: Option<Instant> = None;
636
668
let mut meeting_chat = conversation.chat_thread.clone();
637
669
if let Some(thread) = &meeting_chat {
638
670
control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -768,6 +800,21 @@ async fn drive(
768
800
lobby = in_lobby;
769
801
control.send(CallUpdate::Lobby(lobby));
770
802
}
803
if caption_flow.wanted() {
804
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;
805
if caption_flow.on() {
806
caption_deadline = None;
807
}
808
}
809
}
810
}
811
Ok(CallEvent::AddParticipantFailure(_)) => {
812
replier.reply(request_id, 200, "");
813
if caption_flow.wanted() && roster.caption_bot().is_none() {
814
timeline.record("caption bot failed", "addParticipantFailure");
815
caption_flow.failed();
816
caption_deadline = None;
817
control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));
771
818
}
772
819
}
773
820
Ok(CallEvent::ConversationUpdate(body)) => {
@@ -857,6 +904,19 @@ async fn drive(
857
904
timeline.record("remote video track", format!("mid {mid}"));
858
905
live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
859
906
}
907
PeerEvent::Data(frame) => {
908
if let Some(message) = depacketizer.push(&frame)
909
&& message.data_id == CAPTIONS_DATA_ID
910
{
911
for entry in parse_caption_message(&message.payload) {
912
if caption_flow.text_arrived() {
913
caption_deadline = None;
914
control.send(CallUpdate::Captions(CaptionState::On));
915
}
916
control.send(CallUpdate::Caption(named_caption(entry, &roster)));
917
}
918
}
919
}
860
920
},
861
921
Some(event) = next_peer_event(&mut next) => match event {
862
922
PeerEvent::Connection(PeerConnectionState::Connected) => {
@@ -1004,6 +1064,62 @@ async fn drive(
1004
1064
control.send(CallUpdate::Notice("Could not lower all hands".into()));
1005
1065
}
1006
1066
}
1067
Some(CallCommand::Admit { mri }) => {
1068
let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
1069
report_organizer_result(result, "admit", "Could not admit that person", control, timeline);
1070
}
1071
Some(CallCommand::AdmitAll) => {
1072
let result = remote.signaling.admit_all(&remote.conversation, &remote.participant, &links).await;
1073
report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);
1074
}
1075
Some(CallCommand::Deny { mri }) => {
1076
let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
1077
report_organizer_result(result, "deny", "Could not deny that person", control, timeline);
1078
}
1079
Some(CallCommand::RemoveParticipant { mri }) => {
1080
let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
1081
report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);
1082
}
1083
Some(CallCommand::MuteParticipant { mri }) => {
1084
let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
1085
report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);
1086
}
1087
Some(CallCommand::MuteAll) => {
1088
let others: Vec<String> = roster
1089
.members()
1090
.iter()
1091
.filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX))
1092
.map(|member| member.mri.clone())
1093
.collect();
1094
let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
1095
report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
1096
}
1097
Some(CallCommand::Spotlight { mri }) => {
1098
let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
1099
report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
1100
}
1101
Some(CallCommand::StopSpotlight { mri }) => {
1102
let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
1103
if !state_ids.is_empty() {
1104
let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
1105
report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);
1106
}
1107
}
1108
Some(CallCommand::SetCaptions(on)) => {
1109
caption_flow.want(on);
1110
if on {
1111
caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT);
1112
control.send(CallUpdate::Captions(CaptionState::Starting));
1113
} else {
1114
caption_deadline = None;
1115
control.send(CallUpdate::Captions(CaptionState::Off));
1116
}
1117
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;
1118
if caption_flow.on() {
1119
caption_deadline = None;
1120
}
1121
}
1122
Some(CallCommand::SetBlur(on)) => local_video.set_blur(on),
1007
1123
Some(CallCommand::SendReaction(reaction)) => {
1008
1124
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1009
1125
timeline.record("reaction failed", error.to_string());
@@ -1031,6 +1147,17 @@ async fn drive(
1031
1147
_ = stats_tick.tick(), if remote_set => {
1032
1148
let snapshot = collect_stats(¤t.peer).await;
1033
1149
ticks += 1;
1150
if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
1151
caption_deadline = None;
1152
caption_flow.failed();
1153
timeline.record("captions", "did not start in time");
1154
control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));
1155
}
1156
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)
1157
&& let Some(average_ms) = local_video.blur_average_ms()
1158
{
1159
control.send(CallUpdate::BlurTiming(average_ms));
1160
}
1034
1161
let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
1035
1162
control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
1036
1163
if snapshot.selected_pair.is_some() {
@@ -1127,7 +1254,7 @@ async fn start_escalation(
1127
1254
let url = acceptance_links
1128
1255
.get("mediaRenegotiation")
1129
1256
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
1130
let session = open_peer(factory, grant, &options.relay_host)?;
1257
let session = open_peer(factory, grant, &options.relay_host, false)?;
1131
1258
let media = create_offer(&session.peer, factory, track).await?;
1132
1259
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);
1133
1260
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
@@ -1144,7 +1271,7 @@ async fn answer_on_new_peer(
1144
1271
track: &RtcAudioTrack,
1145
1272
teams_offer: &str,
1146
1273
) -> Result<(PeerSession, AnsweredMedia)> {
1147
let session = open_peer(factory, grant, &options.relay_host)?;
1274
let session = open_peer(factory, grant, &options.relay_host, false)?;
1148
1275
let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;
1149
1276
Ok((session, answered))
1150
1277
}
@@ -1247,6 +1374,77 @@ fn tell_media_descriptions(
1247
1374
});
1248
1375
}
1249
1376
1377
fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
1378
let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
1379
Target { mri, display_name }
1380
}
1381
1382
fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {
1383
if let Err(error) = &result {
1384
timeline.record(format!("{label} failed"), error.to_string());
1385
control.send(CallUpdate::Notice(notice.into()));
1386
}
1387
control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });
1388
}
1389
1390
fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
1391
if entry.display_name.is_empty() {
1392
entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();
1393
}
1394
entry
1395
}
1396
1397
#[allow(clippy::too_many_arguments)]
1398
async fn run_caption_steps(
1399
flow: &mut CaptionFlow,
1400
roster: &Roster,
1401
remote: &RemoteCall,
1402
links: &CallbackLinks,
1403
meeting_chat: Option<&str>,
1404
control: &CallControl,
1405
timeline: &Timeline,
1406
) {
1407
let fail = |flow: &mut CaptionFlow, reason: &str| {
1408
flow.failed();
1409
control.send(CallUpdate::Captions(CaptionState::Failed(reason.to_owned())));
1410
};
1411
loop {
1412
match flow.next(roster.caption_bot()) {
1413
CaptionStep::Wait => return,
1414
CaptionStep::AddBot => {
1415
let Some(thread) = meeting_chat else {
1416
return fail(flow, "This meeting has no chat for captions");
1417
};
1418
if let Err(error) = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await {
1419
timeline.record("caption bot failed", error.to_string());
1420
return fail(flow, "The captions service could not join");
1421
}
1422
}
1423
CaptionStep::Start => {
1424
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
1425
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
1426
timeline.record("caption start failed", error.to_string());
1427
return fail(flow, "Captions could not start");
1428
}
1429
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
1430
timeline.record("caption preference failed", error.to_string());
1431
}
1432
}
1433
CaptionStep::Stop => {
1434
if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())
1435
&& let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await
1436
{
1437
timeline.record("caption stop failed", error.to_string());
1438
}
1439
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
1440
timeline.record("caption preference failed", error.to_string());
1441
}
1442
}
1443
CaptionStep::ReportOn => control.send(CallUpdate::Captions(CaptionState::On)),
1444
}
1445
}
1446
}
1447
1250
1448
fn send_receive_change(control: &CallControl, change: ReceiveChange) {
1251
1449
if let Some(sharer) = change.screen_sharer {
1252
1450
control.send(CallUpdate::ScreenShare(sharer));
@@ -7,6 +7,7 @@ use std::time::Duration;7
use chatsvc::TrouterCallback;7
use chatsvc::TrouterCallback;8
use futures_util::StreamExt;8
use futures_util::StreamExt;9
use libwebrtc::audio_stream::native::NativeAudioStream;9
use libwebrtc::audio_stream::native::NativeAudioStream;10
use libwebrtc::data_channel::{DataChannel, DataChannelInit};10
use libwebrtc::prelude::*;11
use libwebrtc::prelude::*;11
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};12
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};12
use libwebrtc::session_description::{SdpType, SessionDescription};13
use libwebrtc::session_description::{SdpType, SessionDescription};@@ -18,6 +19,8 @@ use tokio::time::{Instant, interval, sleep_until, timeout};18
19
19
use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};20
use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};20
use crate::audio_io::{AudioMode, AudioSetup};21
use crate::audio_io::{AudioMode, AudioSetup};22
use crate::captions::{CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, BotAction, parse_caption_message};23
use crate::data_channel::Depacketizer;21
use crate::control::{CallCommand, CallControl, CallUpdate, Progress};24
use crate::control::{CallCommand, CallControl, CallUpdate, Progress};22
use crate::devices::{self, DeviceChoice};25
use crate::devices::{self, DeviceChoice};23
use crate::end::EndKind;26
use crate::end::EndKind;@@ -28,6 +31,7 @@ use crate::push::CallNotification;28
use crate::share_audio::ShareAudio;31
use crate::share_audio::ShareAudio;29
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};32
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};30
use crate::renegotiation::{MediaAction, MediaNegotiator};33
use crate::renegotiation::{MediaAction, MediaNegotiator};34
use crate::organizer::Target;31
use crate::roster::Roster;35
use crate::roster::Roster;32
use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};36
use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};33
use crate::signaling::{37
use crate::signaling::{@@ -55,6 +59,11 @@ const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;55
const MIN_KEEP_ALIVE_SECONDS: u64 = 60;59
const MIN_KEEP_ALIVE_SECONDS: u64 = 60;56
const KEEP_ALIVE_FRACTION: f64 = 0.9;60
const KEEP_ALIVE_FRACTION: f64 = 0.9;57
const MIC_STREAM: &str = "microphone";61
const MIC_STREAM: &str = "microphone";62
const DATA_CHANNEL_LABEL: &str = "main-channel";63
pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";64
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);65
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;66
const BOT_PREFIX: &str = "28:";58
67
59
#[derive(Debug, Clone)]68
#[derive(Debug, Clone)]60
pub struct CallOptions {69
pub struct CallOptions {@@ -73,6 +82,7 @@ pub struct CallOptions {73
pub wav_path: Option<PathBuf>,82
pub wav_path: Option<PathBuf>,74
pub sdp_dump_dir: Option<PathBuf>,83
pub sdp_dump_dir: Option<PathBuf>,75
pub trace: bool,84
pub trace: bool,85
pub data_channel: bool,76
}86
}77
87
78
impl Default for CallOptions {88
impl Default for CallOptions {@@ -93,6 +103,7 @@ impl Default for CallOptions {93
wav_path: None,103
wav_path: None,94
sdp_dump_dir: None,104
sdp_dump_dir: None,95
trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),105
trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),106
data_channel: data_channel_from_env(),96
}107
}97
}108
}98
}109
}@@ -185,6 +196,10 @@ pub(crate) enum Plan {185
Incoming(Box<IncomingCall>),196
Incoming(Box<IncomingCall>),186
}197
}187
198
199
fn data_channel_from_env() -> bool {200
!matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))201
}202
188
pub fn keep_alive_period(seconds: Option<u64>) -> Duration {203
pub fn keep_alive_period(seconds: Option<u64>) -> Duration {189
let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);204
let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);190
Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)205
Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)@@ -207,11 +222,13 @@ enum PeerEvent {207
Connection(PeerConnectionState),222
Connection(PeerConnectionState),208
Track(RtcAudioTrack),223
Track(RtcAudioTrack),209
VideoTrack { mid: String, track: RtcVideoTrack },224
VideoTrack { mid: String, track: RtcVideoTrack },225
Data(Vec<u8>),210
}226
}211
227
212
struct PeerSession {228
struct PeerSession {213
peer: PeerConnection,229
peer: PeerConnection,214
events: mpsc::UnboundedReceiver<PeerEvent>,230
events: mpsc::UnboundedReceiver<PeerEvent>,231
_data_channel: Option<DataChannel>,215
}232
}216
233
217
struct OfferedMedia {234
struct OfferedMedia {@@ -334,13 +351,14 @@ impl CallEngine {334
}351
}335
}352
}336
353
337
fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str) -> Result<PeerSession> {354
fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {338
let mut configuration = RtcConfiguration::default();355
let mut configuration = RtcConfiguration::default();339
configuration.ice_servers = vec![grant.ice_server(relay_host)];356
configuration.ice_servers = vec![grant.ice_server(relay_host)];340
let peer = factory357
let peer = factory341
.create_peer_connection(configuration)358
.create_peer_connection(configuration)342
.map_err(|error| Error::Webrtc(error.to_string()))?;359
.map_err(|error| Error::Webrtc(error.to_string()))?;343
let (sender, events) = mpsc::unbounded_channel();360
let (sender, events) = mpsc::unbounded_channel();361
let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;344
let ice_sender = sender.clone();362
let ice_sender = sender.clone();345
peer.on_ice_connection_state_change(Some(Box::new(move |state| {363
peer.on_ice_connection_state_change(Some(Box::new(move |state| {346
let _ = ice_sender.send(PeerEvent::Ice(state));364
let _ = ice_sender.send(PeerEvent::Ice(state));@@ -358,7 +376,17 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s358
let _ = sender.send(PeerEvent::VideoTrack { mid, track });376
let _ = sender.send(PeerEvent::VideoTrack { mid, track });359
}377
}360
})));378
})));361
Ok(PeerSession { peer, events })379
Ok(PeerSession { peer, events, _data_channel: data_channel })380
}381
382
fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {383
let channel = peer384
.create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())385
.map_err(|error| Error::Webrtc(error.to_string()))?;386
channel.on_message(Some(Box::new(move |buffer| {387
let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));388
})));389
Ok(channel)362
}390
}363
391
364
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack) -> Result<OfferedMedia> {392
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack) -> Result<OfferedMedia> {@@ -500,7 +528,8 @@ async fn drive(500
control.send(CallUpdate::Cameras(camera_devices(options.video).await));528
control.send(CallUpdate::Cameras(camera_devices(options.video).await));501
refresh_share_sources(control.updates(), options.video);529
refresh_share_sources(control.updates(), options.video);502
530
503
let mut current = open_peer(&factory, &grant, &options.relay_host)?;531
let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);532
let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;504
live.peers.push(current.peer.clone());533
live.peers.push(current.peer.clone());505
534
506
let signaling = Arc::new(inner.signaling(timeline.clone()));535
let signaling = Arc::new(inner.signaling(timeline.clone()));@@ -633,6 +662,9 @@ async fn drive(633
let mut share_sound_wanted = false;662
let mut share_sound_wanted = false;634
let mut remote_audio: Option<RtcAudioTrack> = None;663
let mut remote_audio: Option<RtcAudioTrack> = None;635
let mut own_hand: Option<String> = None;664
let mut own_hand: Option<String> = None;665
let mut depacketizer = Depacketizer::default();666
let mut caption_flow = CaptionFlow::default();667
let mut caption_deadline: Option<Instant> = None;636
let mut meeting_chat = conversation.chat_thread.clone();668
let mut meeting_chat = conversation.chat_thread.clone();637
if let Some(thread) = &meeting_chat {669
if let Some(thread) = &meeting_chat {638
control.send(CallUpdate::MeetingChat(thread.clone()));670
control.send(CallUpdate::MeetingChat(thread.clone()));@@ -768,6 +800,21 @@ async fn drive(768
lobby = in_lobby;800
lobby = in_lobby;769
control.send(CallUpdate::Lobby(lobby));801
control.send(CallUpdate::Lobby(lobby));770
}802
}803
if caption_flow.wanted() {804
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;805
if caption_flow.on() {806
caption_deadline = None;807
}808
}809
}810
}811
Ok(CallEvent::AddParticipantFailure(_)) => {812
replier.reply(request_id, 200, "");813
if caption_flow.wanted() && roster.caption_bot().is_none() {814
timeline.record("caption bot failed", "addParticipantFailure");815
caption_flow.failed();816
caption_deadline = None;817
control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));771
}818
}772
}819
}773
Ok(CallEvent::ConversationUpdate(body)) => {820
Ok(CallEvent::ConversationUpdate(body)) => {@@ -857,6 +904,19 @@ async fn drive(857
timeline.record("remote video track", format!("mid {mid}"));904
timeline.record("remote video track", format!("mid {mid}"));858
live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));905
live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));859
}906
}907
PeerEvent::Data(frame) => {908
if let Some(message) = depacketizer.push(&frame)909
&& message.data_id == CAPTIONS_DATA_ID910
{911
for entry in parse_caption_message(&message.payload) {912
if caption_flow.text_arrived() {913
caption_deadline = None;914
control.send(CallUpdate::Captions(CaptionState::On));915
}916
control.send(CallUpdate::Caption(named_caption(entry, &roster)));917
}918
}919
}860
},920
},861
Some(event) = next_peer_event(&mut next) => match event {921
Some(event) = next_peer_event(&mut next) => match event {862
PeerEvent::Connection(PeerConnectionState::Connected) => {922
PeerEvent::Connection(PeerConnectionState::Connected) => {@@ -1004,6 +1064,62 @@ async fn drive(1004
control.send(CallUpdate::Notice("Could not lower all hands".into()));1064
control.send(CallUpdate::Notice("Could not lower all hands".into()));1005
}1065
}1006
}1066
}1067
Some(CallCommand::Admit { mri }) => {1068
let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;1069
report_organizer_result(result, "admit", "Could not admit that person", control, timeline);1070
}1071
Some(CallCommand::AdmitAll) => {1072
let result = remote.signaling.admit_all(&remote.conversation, &remote.participant, &links).await;1073
report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);1074
}1075
Some(CallCommand::Deny { mri }) => {1076
let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;1077
report_organizer_result(result, "deny", "Could not deny that person", control, timeline);1078
}1079
Some(CallCommand::RemoveParticipant { mri }) => {1080
let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;1081
report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);1082
}1083
Some(CallCommand::MuteParticipant { mri }) => {1084
let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;1085
report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);1086
}1087
Some(CallCommand::MuteAll) => {1088
let others: Vec<String> = roster1089
.members()1090
.iter()1091
.filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX))1092
.map(|member| member.mri.clone())1093
.collect();1094
let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;1095
report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);1096
}1097
Some(CallCommand::Spotlight { mri }) => {1098
let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;1099
report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);1100
}1101
Some(CallCommand::StopSpotlight { mri }) => {1102
let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();1103
if !state_ids.is_empty() {1104
let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);1105
report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);1106
}1107
}1108
Some(CallCommand::SetCaptions(on)) => {1109
caption_flow.want(on);1110
if on {1111
caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT);1112
control.send(CallUpdate::Captions(CaptionState::Starting));1113
} else {1114
caption_deadline = None;1115
control.send(CallUpdate::Captions(CaptionState::Off));1116
}1117
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;1118
if caption_flow.on() {1119
caption_deadline = None;1120
}1121
}1122
Some(CallCommand::SetBlur(on)) => local_video.set_blur(on),1007
Some(CallCommand::SendReaction(reaction)) => {1123
Some(CallCommand::SendReaction(reaction)) => {1008
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1124
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1009
timeline.record("reaction failed", error.to_string());1125
timeline.record("reaction failed", error.to_string());@@ -1031,6 +1147,17 @@ async fn drive(1031
_ = stats_tick.tick(), if remote_set => {1147
_ = stats_tick.tick(), if remote_set => {1032
let snapshot = collect_stats(¤t.peer).await;1148
let snapshot = collect_stats(¤t.peer).await;1033
ticks += 1;1149
ticks += 1;1150
if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {1151
caption_deadline = None;1152
caption_flow.failed();1153
timeline.record("captions", "did not start in time");1154
control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));1155
}1156
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)1157
&& let Some(average_ms) = local_video.blur_average_ms()1158
{1159
control.send(CallUpdate::BlurTiming(average_ms));1160
}1034
let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };1161
let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };1035
control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });1162
control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });1036
if snapshot.selected_pair.is_some() {1163
if snapshot.selected_pair.is_some() {@@ -1127,7 +1254,7 @@ async fn start_escalation(1127
let url = acceptance_links1254
let url = acceptance_links1128
.get("mediaRenegotiation")1255
.get("mediaRenegotiation")1129
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;1256
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;1130
let session = open_peer(factory, grant, &options.relay_host)?;1257
let session = open_peer(factory, grant, &options.relay_host, false)?;1131
let media = create_offer(&session.peer, factory, track).await?;1258
let media = create_offer(&session.peer, factory, track).await?;1132
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);1259
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);1133
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;1260
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;@@ -1144,7 +1271,7 @@ async fn answer_on_new_peer(1144
track: &RtcAudioTrack,1271
track: &RtcAudioTrack,1145
teams_offer: &str,1272
teams_offer: &str,1146
) -> Result<(PeerSession, AnsweredMedia)> {1273
) -> Result<(PeerSession, AnsweredMedia)> {1147
let session = open_peer(factory, grant, &options.relay_host)?;1274
let session = open_peer(factory, grant, &options.relay_host, false)?;1148
let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;1275
let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;1149
Ok((session, answered))1276
Ok((session, answered))1150
}1277
}@@ -1247,6 +1374,77 @@ fn tell_media_descriptions(1247
});1374
});1248
}1375
}1249
1376
1377
fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {1378
let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());1379
Target { mri, display_name }1380
}1381
1382
fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {1383
if let Err(error) = &result {1384
timeline.record(format!("{label} failed"), error.to_string());1385
control.send(CallUpdate::Notice(notice.into()));1386
}1387
control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });1388
}1389
1390
fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {1391
if entry.display_name.is_empty() {1392
entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();1393
}1394
entry1395
}1396
1397
#[allow(clippy::too_many_arguments)]1398
async fn run_caption_steps(1399
flow: &mut CaptionFlow,1400
roster: &Roster,1401
remote: &RemoteCall,1402
links: &CallbackLinks,1403
meeting_chat: Option<&str>,1404
control: &CallControl,1405
timeline: &Timeline,1406
) {1407
let fail = |flow: &mut CaptionFlow, reason: &str| {1408
flow.failed();1409
control.send(CallUpdate::Captions(CaptionState::Failed(reason.to_owned())));1410
};1411
loop {1412
match flow.next(roster.caption_bot()) {1413
CaptionStep::Wait => return,1414
CaptionStep::AddBot => {1415
let Some(thread) = meeting_chat else {1416
return fail(flow, "This meeting has no chat for captions");1417
};1418
if let Err(error) = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await {1419
timeline.record("caption bot failed", error.to_string());1420
return fail(flow, "The captions service could not join");1421
}1422
}1423
CaptionStep::Start => {1424
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };1425
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {1426
timeline.record("caption start failed", error.to_string());1427
return fail(flow, "Captions could not start");1428
}1429
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {1430
timeline.record("caption preference failed", error.to_string());1431
}1432
}1433
CaptionStep::Stop => {1434
if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())1435
&& let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await1436
{1437
timeline.record("caption stop failed", error.to_string());1438
}1439
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {1440
timeline.record("caption preference failed", error.to_string());1441
}1442
}1443
CaptionStep::ReportOn => control.send(CallUpdate::Captions(CaptionState::On)),1444
}1445
}1446
}1447
1250
fn send_receive_change(control: &CallControl, change: ReceiveChange) {1448
fn send_receive_change(control: &CallControl, change: ReceiveChange) {1251
if let Some(sharer) = change.screen_sharer {1449
if let Some(sharer) = change.screen_sharer {1252
control.send(CallUpdate::ScreenShare(sharer));1450
control.send(CallUpdate::ScreenShare(sharer));@@ -1,3 +1,4 @@
1
use std::sync::Arc;
1
2
use std::time::Duration;
2
3
3
4
use libwebrtc::native::yuv_helper::abgr_to_i420;
@@ -7,6 +8,7 @@ use nokhwa::utils::{ApiBackend, CameraIndex, RequestedFormat, RequestedFormatTyp
7
8
use nokhwa::{Camera, query};
8
9
use std::sync::atomic::Ordering;
9
10
11
use crate::blur::{BlurSettings, BlurStage};
10
12
use crate::capture::Capture;
11
13
use crate::devices::{DeviceChoice, DeviceEntry};
12
14
use crate::error::{Error, Result};
@@ -41,7 +43,7 @@ fn camera_index(choice: &DeviceChoice) -> CameraIndex {
41
43
}
42
44
}
43
45
44
fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
46
pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
45
47
let mut buffer = I420Buffer::new(width, height);
46
48
let (stride_y, stride_u, stride_v) = buffer.strides();
47
49
let (plane_y, plane_u, plane_v) = buffer.data_mut();
@@ -62,6 +64,7 @@ fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
62
64
63
65
pub fn start_camera(
64
66
choice: &DeviceChoice,
67
blur: Arc<BlurSettings>,
65
68
mut deliver: impl FnMut(I420Buffer) + Send + 'static,
66
69
failed: impl FnOnce(String) + Send + 'static,
67
70
) -> Result<Capture> {
@@ -72,6 +75,7 @@ pub fn start_camera(
72
75
Ok(camera) => camera,
73
76
Err(error) => return failed(error.to_string()),
74
77
};
78
let mut blur_stage = BlurStage::new(blur);
75
79
while !stop.load(Ordering::SeqCst) {
76
80
let Ok(frame) = camera.frame() else {
77
81
std::thread::sleep(RETRY_PAUSE);
@@ -80,7 +84,9 @@ pub fn start_camera(
80
84
let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { continue };
81
85
let (width, height) = (decoded.width(), decoded.height());
82
86
if width >= 2 && height >= 2 && width % 2 == 0 && height % 2 == 0 {
83
deliver(i420_from_rgba(decoded.as_raw(), width, height));
87
let mut rgba = decoded.into_raw();
88
blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
89
deliver(i420_from_rgba(&rgba, width, height));
84
90
}
85
91
}
86
92
let _ = camera.stop_stream();
@@ -1,3 +1,4 @@1
use std::sync::Arc;1
use std::time::Duration;2
use std::time::Duration;2
3
3
use libwebrtc::native::yuv_helper::abgr_to_i420;4
use libwebrtc::native::yuv_helper::abgr_to_i420;@@ -7,6 +8,7 @@ use nokhwa::utils::{ApiBackend, CameraIndex, RequestedFormat, RequestedFormatTyp7
use nokhwa::{Camera, query};8
use nokhwa::{Camera, query};8
use std::sync::atomic::Ordering;9
use std::sync::atomic::Ordering;9
10
11
use crate::blur::{BlurSettings, BlurStage};10
use crate::capture::Capture;12
use crate::capture::Capture;11
use crate::devices::{DeviceChoice, DeviceEntry};13
use crate::devices::{DeviceChoice, DeviceEntry};12
use crate::error::{Error, Result};14
use crate::error::{Error, Result};@@ -41,7 +43,7 @@ fn camera_index(choice: &DeviceChoice) -> CameraIndex {41
}43
}42
}44
}43
45
44
fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {46
pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {45
let mut buffer = I420Buffer::new(width, height);47
let mut buffer = I420Buffer::new(width, height);46
let (stride_y, stride_u, stride_v) = buffer.strides();48
let (stride_y, stride_u, stride_v) = buffer.strides();47
let (plane_y, plane_u, plane_v) = buffer.data_mut();49
let (plane_y, plane_u, plane_v) = buffer.data_mut();@@ -62,6 +64,7 @@ fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {62
64
63
pub fn start_camera(65
pub fn start_camera(64
choice: &DeviceChoice,66
choice: &DeviceChoice,67
blur: Arc<BlurSettings>,65
mut deliver: impl FnMut(I420Buffer) + Send + 'static,68
mut deliver: impl FnMut(I420Buffer) + Send + 'static,66
failed: impl FnOnce(String) + Send + 'static,69
failed: impl FnOnce(String) + Send + 'static,67
) -> Result<Capture> {70
) -> Result<Capture> {@@ -72,6 +75,7 @@ pub fn start_camera(72
Ok(camera) => camera,75
Ok(camera) => camera,73
Err(error) => return failed(error.to_string()),76
Err(error) => return failed(error.to_string()),74
};77
};78
let mut blur_stage = BlurStage::new(blur);75
while !stop.load(Ordering::SeqCst) {79
while !stop.load(Ordering::SeqCst) {76
let Ok(frame) = camera.frame() else {80
let Ok(frame) = camera.frame() else {77
std::thread::sleep(RETRY_PAUSE);81
std::thread::sleep(RETRY_PAUSE);@@ -80,7 +84,9 @@ pub fn start_camera(80
let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { continue };84
let Ok(decoded) = frame.decode_image::<RgbAFormat>() else { continue };81
let (width, height) = (decoded.width(), decoded.height());85
let (width, height) = (decoded.width(), decoded.height());82
if width >= 2 && height >= 2 && width % 2 == 0 && height % 2 == 0 {86
if width >= 2 && height >= 2 && width % 2 == 0 && height % 2 == 0 {83
deliver(i420_from_rgba(decoded.as_raw(), width, height));87
let mut rgba = decoded.into_raw();88
blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);89
deliver(i420_from_rgba(&rgba, width, height));84
}90
}85
}91
}86
let _ = camera.stop_stream();92
let _ = camera.stop_stream();@@ -0,0 +1,309 @@
1
use serde_json::{Value, json};
2
3
use crate::roster::CaptionBot;
4
use crate::trouter_events::CallbackLinks;
5
6
pub const CAPTIONS_DATA_ID: u8 = 3;
7
pub const RECORDING_BOT_MRI: &str = "28:bdd75849-e0a6-4cce-8fc1-d7c0d4da43e5";
8
pub const RECORDER_RESOURCE: &str = "4580fd1d-e5a3-4f56-9ad1-aab0e3bf8f76";
9
pub const RECORDER_SCOPE: &str = "access_recorder_service";
10
pub const INITIATOR_TOKEN_PLACEHOLDER: &str = "@@recorder-token@@";
11
pub const COMMAND_SCRIPT: &str = include_str!("../assets/caption_command.js");
12
const BOT_MODE: &str = "RecordingAndTranscription";
13
const COMMAND_MODE: &str = "transcription";
14
const CLOSED_CAPTIONS: &str = "closedCaptions";
15
const RECOGNITION_RESULTS: &str = "recognitionResults";
16
const TEXT_TRACKS: &str = "textTracks";
17
18
#[derive(Debug, Clone, PartialEq, Eq)]
19
pub struct CaptionEntry {
20
pub id: String,
21
pub user_id: String,
22
pub display_name: String,
23
pub text: String,
24
pub is_final: bool,
25
}
26
27
#[derive(Debug, Clone, PartialEq, Eq)]
28
pub enum CaptionState {
29
Off,
30
Starting,
31
On,
32
Failed(String),
33
}
34
35
pub fn parse_caption_message(payload: &[u8]) -> Vec<CaptionEntry> {
36
let Ok(message) = serde_json::from_slice::<Value>(payload) else {
37
return Vec::new();
38
};
39
[RECOGNITION_RESULTS, TEXT_TRACKS]
40
.into_iter()
41
.filter_map(|key| message[key].as_array())
42
.flatten()
43
.filter_map(entry_from)
44
.collect()
45
}
46
47
fn entry_from(item: &Value) -> Option<CaptionEntry> {
48
let text = item["text"].as_str().or_else(|| item["rawText"].as_str())?.trim();
49
if text.is_empty() {
50
return None;
51
}
52
let user_id = item["userId"].as_str().unwrap_or_default().to_owned();
53
let id = item["utteranceId"].as_str().or_else(|| item["id"].as_str()).map_or_else(|| user_id.clone(), str::to_owned);
54
Some(CaptionEntry {
55
id,
56
user_id,
57
display_name: item["displayName"].as_str().unwrap_or_default().to_owned(),
58
text: text.to_owned(),
59
is_final: item["isFinal"].as_bool().unwrap_or(false),
60
})
61
}
62
63
pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {
64
json!({
65
"disableUnmute": false,
66
"participants": {
67
"from": from,
68
"to": [{"id": RECORDING_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],
69
},
70
"participantInvitationData": {"botData": {
71
"meetingTitle": "",
72
"clientInfo": "Teams-R4",
73
"callId": call_id,
74
"threadId": thread_id,
75
"recorderFeatures": {
76
"enablePPTSharing": true,
77
"intermediateLiveCaptions": false,
78
"actionItemsEnabled": false,
79
"enableEmailAndMeetingLanguageModel": true,
80
"ceoSummit": false,
81
"useUnmixedAudio": true,
82
"enableTranscriptMeetingChaptering": false,
83
},
84
"mode": BOT_MODE,
85
"iCalUid": null,
86
"consumerType": "Teams",
87
"spokenLanguage": "",
88
"initiatorUserToken": INITIATOR_TOKEN_PLACEHOLDER,
89
"exchangeId": null,
90
"meetingOrganizer": organizer_name,
91
}},
92
"replacementDetails": null,
93
"groupContext": null,
94
"groupChat": {"threadId": thread_id, "messageId": null},
95
"links": {
96
"addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
97
"addParticipantFailure": callbacks.conversation("addParticipantFailure"),
98
},
99
})
100
}
101
102
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103
pub enum BotAction {
104
Start,
105
Stop,
106
}
107
108
impl BotAction {
109
fn name(self) -> &'static str {
110
match self {
111
BotAction::Start => "start",
112
BotAction::Stop => "stop",
113
}
114
}
115
}
116
117
/// The skype token is added inside the page, so the body travels without it.
118
pub fn command_body(action: BotAction, own_mri: &str, participant_leg_id: &str, timestamp: &str) -> Value {
119
json!({
120
"timestamp": timestamp,
121
"participantMri": own_mri,
122
"participantLegId": participant_leg_id,
123
"action": action.name(),
124
"mode": COMMAND_MODE,
125
"processingModes": [CLOSED_CAPTIONS],
126
})
127
}
128
129
pub fn endpoint_metadata(captions: bool) -> Value {
130
json!({"holographicCapabilities": 3, "transcriptionPrefs": {"closedCaptions": captions}})
131
}
132
133
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134
pub enum CaptionStep {
135
AddBot,
136
Start,
137
Stop,
138
ReportOn,
139
Wait,
140
}
141
142
#[derive(Default)]
143
pub struct CaptionFlow {
144
wanted: bool,
145
bot_requested: bool,
146
started: bool,
147
reported: bool,
148
}
149
150
impl CaptionFlow {
151
pub fn want(&mut self, wanted: bool) {
152
self.wanted = wanted;
153
if !wanted {
154
self.reported = false;
155
}
156
}
157
158
pub fn wanted(&self) -> bool {
159
self.wanted
160
}
161
162
pub fn on(&self) -> bool {
163
self.reported
164
}
165
166
pub fn text_arrived(&mut self) -> bool {
167
self.wanted && self.started && !std::mem::replace(&mut self.reported, true)
168
}
169
170
pub fn failed(&mut self) {
171
*self = CaptionFlow::default();
172
}
173
174
pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {
175
if !self.wanted {
176
return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };
177
}
178
let Some(bot) = bot else {
179
return if std::mem::replace(&mut self.bot_requested, true) { CaptionStep::Wait } else { CaptionStep::AddBot };
180
};
181
if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {
182
return CaptionStep::Start;
183
}
184
if self.started && bot.active && !std::mem::replace(&mut self.reported, true) {
185
return CaptionStep::ReportOn;
186
}
187
CaptionStep::Wait
188
}
189
}
190
191
#[cfg(test)]
192
mod tests {
193
use super::*;
194
195
fn bot(command_url: bool, active: bool) -> CaptionBot {
196
CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active }
197
}
198
199
#[test]
200
fn recognition_results_become_entries_with_speaker_and_finality() {
201
let message = json!({"recognitionResults": [
202
{"id": "u1", "text": " Hello there ", "isFinal": false, "userId": "8:orgid:ana", "displayName": "Ana"},
203
{"id": "u2", "text": "", "userId": "8:orgid:bo"},
204
{"utteranceId": "u3", "rawText": "raw", "isFinal": true, "userId": "8:orgid:bo"},
205
]});
206
let entries = parse_caption_message(message.to_string().as_bytes());
207
assert_eq!(entries.len(), 2);
208
assert_eq!(entries[0], CaptionEntry { id: "u1".into(), user_id: "8:orgid:ana".into(), display_name: "Ana".into(), text: "Hello there".into(), is_final: false });
209
assert_eq!(entries[1].id, "u3");
210
assert!(entries[1].is_final);
211
assert_eq!(entries[1].display_name, "");
212
}
213
214
#[test]
215
fn text_tracks_count_and_other_messages_and_bad_json_do_not() {
216
let tracks = json!({"textTracks": [{"id": "t", "text": "from a track", "userId": "x", "isFinal": true}]});
217
assert_eq!(parse_caption_message(tracks.to_string().as_bytes()).len(), 1);
218
assert!(parse_caption_message(br#"{"events": [{"type": "x"}]}"#).is_empty());
219
assert!(parse_caption_message(b"not json").is_empty());
220
assert!(parse_caption_message(&[]).is_empty());
221
}
222
223
#[test]
224
fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
225
let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
226
let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);
227
let bot_data = &body["participantInvitationData"]["botData"];
228
assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
229
assert_eq!(bot_data["mode"], "RecordingAndTranscription");
230
assert_eq!(bot_data["threadId"], "19:meeting_x@thread.v2");
231
assert_eq!(bot_data["callId"], "call-1");
232
assert_eq!(bot_data["initiatorUserToken"], INITIATOR_TOKEN_PLACEHOLDER);
233
assert_eq!(body["groupChat"]["threadId"], "19:meeting_x@thread.v2");
234
assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
235
}
236
237
#[test]
238
fn start_and_stop_commands_differ_only_in_the_action() {
239
let start = command_body(BotAction::Start, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
240
let stop = command_body(BotAction::Stop, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");
241
assert_eq!(start["action"], "start");
242
assert_eq!(stop["action"], "stop");
243
assert_eq!(start["mode"], "transcription");
244
assert_eq!(start["processingModes"], json!(["closedCaptions"]));
245
assert_eq!(start["participantLegId"], "leg-1");
246
assert!(start.get("participantSkypeToken").is_none());
247
assert_eq!(start["timestamp"], stop["timestamp"]);
248
}
249
250
#[test]
251
fn the_endpoint_metadata_switches_the_caption_preference() {
252
assert_eq!(endpoint_metadata(true)["transcriptionPrefs"]["closedCaptions"], true);
253
assert_eq!(endpoint_metadata(false)["transcriptionPrefs"]["closedCaptions"], false);
254
assert_eq!(endpoint_metadata(true)["holographicCapabilities"], 3);
255
}
256
257
#[test]
258
fn the_flow_adds_the_bot_once_then_starts_then_reports_then_stops() {
259
let mut flow = CaptionFlow::default();
260
assert_eq!(flow.next(None), CaptionStep::Wait);
261
flow.want(true);
262
assert_eq!(flow.next(None), CaptionStep::AddBot);
263
assert_eq!(flow.next(None), CaptionStep::Wait);
264
assert_eq!(flow.next(Some(&bot(false, false))), CaptionStep::Wait);
265
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
266
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Wait);
267
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
268
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
269
flow.want(false);
270
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
271
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
272
}
273
274
#[test]
275
fn turning_captions_on_again_reuses_the_bot_in_the_roster() {
276
let mut flow = CaptionFlow::default();
277
flow.want(true);
278
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
279
flow.want(false);
280
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);
281
flow.want(true);
282
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Start);
283
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);
284
}
285
286
#[test]
287
fn caption_text_proves_the_captions_are_on_even_before_the_roster_says_so() {
288
let mut flow = CaptionFlow::default();
289
assert!(!flow.text_arrived());
290
flow.want(true);
291
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);
292
assert!(flow.text_arrived());
293
assert!(!flow.text_arrived());
294
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);
295
flow.want(false);
296
assert!(!flow.text_arrived());
297
}
298
299
#[test]
300
fn a_failed_invitation_allows_another_try() {
301
let mut flow = CaptionFlow::default();
302
flow.want(true);
303
assert_eq!(flow.next(None), CaptionStep::AddBot);
304
flow.failed();
305
assert!(!flow.wanted());
306
flow.want(true);
307
assert_eq!(flow.next(None), CaptionStep::AddBot);
308
}
309
}
@@ -0,0 +1,309 @@1
use serde_json::{Value, json};2
3
use crate::roster::CaptionBot;4
use crate::trouter_events::CallbackLinks;5
6
pub const CAPTIONS_DATA_ID: u8 = 3;7
pub const RECORDING_BOT_MRI: &str = "28:bdd75849-e0a6-4cce-8fc1-d7c0d4da43e5";8
pub const RECORDER_RESOURCE: &str = "4580fd1d-e5a3-4f56-9ad1-aab0e3bf8f76";9
pub const RECORDER_SCOPE: &str = "access_recorder_service";10
pub const INITIATOR_TOKEN_PLACEHOLDER: &str = "@@recorder-token@@";11
pub const COMMAND_SCRIPT: &str = include_str!("../assets/caption_command.js");12
const BOT_MODE: &str = "RecordingAndTranscription";13
const COMMAND_MODE: &str = "transcription";14
const CLOSED_CAPTIONS: &str = "closedCaptions";15
const RECOGNITION_RESULTS: &str = "recognitionResults";16
const TEXT_TRACKS: &str = "textTracks";17
18
#[derive(Debug, Clone, PartialEq, Eq)]19
pub struct CaptionEntry {20
pub id: String,21
pub user_id: String,22
pub display_name: String,23
pub text: String,24
pub is_final: bool,25
}26
27
#[derive(Debug, Clone, PartialEq, Eq)]28
pub enum CaptionState {29
Off,30
Starting,31
On,32
Failed(String),33
}34
35
pub fn parse_caption_message(payload: &[u8]) -> Vec<CaptionEntry> {36
let Ok(message) = serde_json::from_slice::<Value>(payload) else {37
return Vec::new();38
};39
[RECOGNITION_RESULTS, TEXT_TRACKS]40
.into_iter()41
.filter_map(|key| message[key].as_array())42
.flatten()43
.filter_map(entry_from)44
.collect()45
}46
47
fn entry_from(item: &Value) -> Option<CaptionEntry> {48
let text = item["text"].as_str().or_else(|| item["rawText"].as_str())?.trim();49
if text.is_empty() {50
return None;51
}52
let user_id = item["userId"].as_str().unwrap_or_default().to_owned();53
let id = item["utteranceId"].as_str().or_else(|| item["id"].as_str()).map_or_else(|| user_id.clone(), str::to_owned);54
Some(CaptionEntry {55
id,56
user_id,57
display_name: item["displayName"].as_str().unwrap_or_default().to_owned(),58
text: text.to_owned(),59
is_final: item["isFinal"].as_bool().unwrap_or(false),60
})61
}62
63
pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {64
json!({65
"disableUnmute": false,66
"participants": {67
"from": from,68
"to": [{"id": RECORDING_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}],69
},70
"participantInvitationData": {"botData": {71
"meetingTitle": "",72
"clientInfo": "Teams-R4",73
"callId": call_id,74
"threadId": thread_id,75
"recorderFeatures": {76
"enablePPTSharing": true,77
"intermediateLiveCaptions": false,78
"actionItemsEnabled": false,79
"enableEmailAndMeetingLanguageModel": true,80
"ceoSummit": false,81
"useUnmixedAudio": true,82
"enableTranscriptMeetingChaptering": false,83
},84
"mode": BOT_MODE,85
"iCalUid": null,86
"consumerType": "Teams",87
"spokenLanguage": "",88
"initiatorUserToken": INITIATOR_TOKEN_PLACEHOLDER,89
"exchangeId": null,90
"meetingOrganizer": organizer_name,91
}},92
"replacementDetails": null,93
"groupContext": null,94
"groupChat": {"threadId": thread_id, "messageId": null},95
"links": {96
"addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),97
"addParticipantFailure": callbacks.conversation("addParticipantFailure"),98
},99
})100
}101
102
#[derive(Debug, Clone, Copy, PartialEq, Eq)]103
pub enum BotAction {104
Start,105
Stop,106
}107
108
impl BotAction {109
fn name(self) -> &'static str {110
match self {111
BotAction::Start => "start",112
BotAction::Stop => "stop",113
}114
}115
}116
117
/// The skype token is added inside the page, so the body travels without it.118
pub fn command_body(action: BotAction, own_mri: &str, participant_leg_id: &str, timestamp: &str) -> Value {119
json!({120
"timestamp": timestamp,121
"participantMri": own_mri,122
"participantLegId": participant_leg_id,123
"action": action.name(),124
"mode": COMMAND_MODE,125
"processingModes": [CLOSED_CAPTIONS],126
})127
}128
129
pub fn endpoint_metadata(captions: bool) -> Value {130
json!({"holographicCapabilities": 3, "transcriptionPrefs": {"closedCaptions": captions}})131
}132
133
#[derive(Debug, Clone, Copy, PartialEq, Eq)]134
pub enum CaptionStep {135
AddBot,136
Start,137
Stop,138
ReportOn,139
Wait,140
}141
142
#[derive(Default)]143
pub struct CaptionFlow {144
wanted: bool,145
bot_requested: bool,146
started: bool,147
reported: bool,148
}149
150
impl CaptionFlow {151
pub fn want(&mut self, wanted: bool) {152
self.wanted = wanted;153
if !wanted {154
self.reported = false;155
}156
}157
158
pub fn wanted(&self) -> bool {159
self.wanted160
}161
162
pub fn on(&self) -> bool {163
self.reported164
}165
166
pub fn text_arrived(&mut self) -> bool {167
self.wanted && self.started && !std::mem::replace(&mut self.reported, true)168
}169
170
pub fn failed(&mut self) {171
*self = CaptionFlow::default();172
}173
174
pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {175
if !self.wanted {176
return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };177
}178
let Some(bot) = bot else {179
return if std::mem::replace(&mut self.bot_requested, true) { CaptionStep::Wait } else { CaptionStep::AddBot };180
};181
if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {182
return CaptionStep::Start;183
}184
if self.started && bot.active && !std::mem::replace(&mut self.reported, true) {185
return CaptionStep::ReportOn;186
}187
CaptionStep::Wait188
}189
}190
191
#[cfg(test)]192
mod tests {193
use super::*;194
195
fn bot(command_url: bool, active: bool) -> CaptionBot {196
CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active }197
}198
199
#[test]200
fn recognition_results_become_entries_with_speaker_and_finality() {201
let message = json!({"recognitionResults": [202
{"id": "u1", "text": " Hello there ", "isFinal": false, "userId": "8:orgid:ana", "displayName": "Ana"},203
{"id": "u2", "text": "", "userId": "8:orgid:bo"},204
{"utteranceId": "u3", "rawText": "raw", "isFinal": true, "userId": "8:orgid:bo"},205
]});206
let entries = parse_caption_message(message.to_string().as_bytes());207
assert_eq!(entries.len(), 2);208
assert_eq!(entries[0], CaptionEntry { id: "u1".into(), user_id: "8:orgid:ana".into(), display_name: "Ana".into(), text: "Hello there".into(), is_final: false });209
assert_eq!(entries[1].id, "u3");210
assert!(entries[1].is_final);211
assert_eq!(entries[1].display_name, "");212
}213
214
#[test]215
fn text_tracks_count_and_other_messages_and_bad_json_do_not() {216
let tracks = json!({"textTracks": [{"id": "t", "text": "from a track", "userId": "x", "isFinal": true}]});217
assert_eq!(parse_caption_message(tracks.to_string().as_bytes()).len(), 1);218
assert!(parse_caption_message(br#"{"events": [{"type": "x"}]}"#).is_empty());219
assert!(parse_caption_message(b"not json").is_empty());220
assert!(parse_caption_message(&[]).is_empty());221
}222
223
#[test]224
fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {225
let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");226
let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);227
let bot_data = &body["participantInvitationData"]["botData"];228
assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);229
assert_eq!(bot_data["mode"], "RecordingAndTranscription");230
assert_eq!(bot_data["threadId"], "19:meeting_x@thread.v2");231
assert_eq!(bot_data["callId"], "call-1");232
assert_eq!(bot_data["initiatorUserToken"], INITIATOR_TOKEN_PLACEHOLDER);233
assert_eq!(body["groupChat"]["threadId"], "19:meeting_x@thread.v2");234
assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));235
}236
237
#[test]238
fn start_and_stop_commands_differ_only_in_the_action() {239
let start = command_body(BotAction::Start, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");240
let stop = command_body(BotAction::Stop, "8:orgid:me", "leg-1", "2026-10-10T08:44:12.705Z");241
assert_eq!(start["action"], "start");242
assert_eq!(stop["action"], "stop");243
assert_eq!(start["mode"], "transcription");244
assert_eq!(start["processingModes"], json!(["closedCaptions"]));245
assert_eq!(start["participantLegId"], "leg-1");246
assert!(start.get("participantSkypeToken").is_none());247
assert_eq!(start["timestamp"], stop["timestamp"]);248
}249
250
#[test]251
fn the_endpoint_metadata_switches_the_caption_preference() {252
assert_eq!(endpoint_metadata(true)["transcriptionPrefs"]["closedCaptions"], true);253
assert_eq!(endpoint_metadata(false)["transcriptionPrefs"]["closedCaptions"], false);254
assert_eq!(endpoint_metadata(true)["holographicCapabilities"], 3);255
}256
257
#[test]258
fn the_flow_adds_the_bot_once_then_starts_then_reports_then_stops() {259
let mut flow = CaptionFlow::default();260
assert_eq!(flow.next(None), CaptionStep::Wait);261
flow.want(true);262
assert_eq!(flow.next(None), CaptionStep::AddBot);263
assert_eq!(flow.next(None), CaptionStep::Wait);264
assert_eq!(flow.next(Some(&bot(false, false))), CaptionStep::Wait);265
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);266
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Wait);267
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);268
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);269
flow.want(false);270
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);271
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);272
}273
274
#[test]275
fn turning_captions_on_again_reuses_the_bot_in_the_roster() {276
let mut flow = CaptionFlow::default();277
flow.want(true);278
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);279
flow.want(false);280
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Stop);281
flow.want(true);282
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Start);283
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::ReportOn);284
}285
286
#[test]287
fn caption_text_proves_the_captions_are_on_even_before_the_roster_says_so() {288
let mut flow = CaptionFlow::default();289
assert!(!flow.text_arrived());290
flow.want(true);291
assert_eq!(flow.next(Some(&bot(true, false))), CaptionStep::Start);292
assert!(flow.text_arrived());293
assert!(!flow.text_arrived());294
assert_eq!(flow.next(Some(&bot(true, true))), CaptionStep::Wait);295
flow.want(false);296
assert!(!flow.text_arrived());297
}298
299
#[test]300
fn a_failed_invitation_allows_another_try() {301
let mut flow = CaptionFlow::default();302
flow.want(true);303
assert_eq!(flow.next(None), CaptionStep::AddBot);304
flow.failed();305
assert!(!flow.wanted());306
flow.want(true);307
assert_eq!(flow.next(None), CaptionStep::AddBot);308
}309
}@@ -3,6 +3,7 @@ use std::sync::Arc;
3
3
4
4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
5
5
6
use crate::captions::{CaptionEntry, CaptionState};
6
7
use crate::devices::{DeviceChoice, DeviceLists};
7
8
use crate::error::{Error, Result};
8
9
use crate::mute::MuteCommand;
@@ -28,6 +29,16 @@ pub enum CallCommand {
28
29
SetHand(bool),
29
30
LowerHand { mri: String },
30
31
LowerAllHands,
32
Admit { mri: String },
33
AdmitAll,
34
Deny { mri: String },
35
MuteParticipant { mri: String },
36
MuteAll,
37
Spotlight { mri: String },
38
StopSpotlight { mri: String },
39
RemoveParticipant { mri: String },
40
SetCaptions(bool),
41
SetBlur(bool),
31
42
SendReaction(Reaction),
32
43
Hangup,
33
44
EndMeeting,
@@ -61,6 +72,10 @@ pub enum CallUpdate {
61
72
ShareSources(Vec<ShareSource>),
62
73
ShareSound(bool),
63
74
Reaction { mri: String, reaction: Reaction },
75
Captions(CaptionState),
76
Caption(CaptionEntry),
77
BlurTiming(f32),
78
Organizer { action: String, outcome: std::result::Result<u16, String> },
64
79
MeetingChat(String),
65
80
Notice(String),
66
81
}
@@ -3,6 +3,7 @@ use std::sync::Arc;3
3
4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};5
5
6
use crate::captions::{CaptionEntry, CaptionState};6
use crate::devices::{DeviceChoice, DeviceLists};7
use crate::devices::{DeviceChoice, DeviceLists};7
use crate::error::{Error, Result};8
use crate::error::{Error, Result};8
use crate::mute::MuteCommand;9
use crate::mute::MuteCommand;@@ -28,6 +29,16 @@ pub enum CallCommand {28
SetHand(bool),29
SetHand(bool),29
LowerHand { mri: String },30
LowerHand { mri: String },30
LowerAllHands,31
LowerAllHands,32
Admit { mri: String },33
AdmitAll,34
Deny { mri: String },35
MuteParticipant { mri: String },36
MuteAll,37
Spotlight { mri: String },38
StopSpotlight { mri: String },39
RemoveParticipant { mri: String },40
SetCaptions(bool),41
SetBlur(bool),31
SendReaction(Reaction),42
SendReaction(Reaction),32
Hangup,43
Hangup,33
EndMeeting,44
EndMeeting,@@ -61,6 +72,10 @@ pub enum CallUpdate {61
ShareSources(Vec<ShareSource>),72
ShareSources(Vec<ShareSource>),62
ShareSound(bool),73
ShareSound(bool),63
Reaction { mri: String, reaction: Reaction },74
Reaction { mri: String, reaction: Reaction },75
Captions(CaptionState),76
Caption(CaptionEntry),77
BlurTiming(f32),78
Organizer { action: String, outcome: std::result::Result<u16, String> },64
MeetingChat(String),79
MeetingChat(String),65
Notice(String),80
Notice(String),66
}81
}@@ -0,0 +1,121 @@
1
use std::collections::HashMap;
2
3
const FIXED_HEADER: usize = 11;
4
const START_FLAG: u8 = 0x80;
5
const DATA_ID_MASK: u8 = 0x3f;
6
const LENGTH_HIGH_MASK: u8 = 0x0f;
7
8
#[derive(Debug, Clone, PartialEq, Eq)]
9
pub struct DataMessage {
10
pub data_id: u8,
11
pub source_id: u32,
12
pub payload: Vec<u8>,
13
}
14
15
#[derive(Default)]
16
struct Pending {
17
source_id: u32,
18
remaining: u8,
19
next_sequence: u16,
20
payload: Vec<u8>,
21
started: bool,
22
}
23
24
/// Joins the fragments of the Teams framing on the `main-channel` SCTP data channel.
25
#[derive(Default)]
26
pub struct Depacketizer {
27
pending: HashMap<u8, Pending>,
28
}
29
30
impl Depacketizer {
31
pub fn push(&mut self, frame: &[u8]) -> Option<DataMessage> {
32
if frame.len() < FIXED_HEADER {
33
return None;
34
}
35
let header_length = (usize::from(frame[0] & LENGTH_HIGH_MASK) << 8) | usize::from(frame[1]);
36
if header_length < FIXED_HEADER || header_length > frame.len() {
37
return None;
38
}
39
let data_id = frame[2] & DATA_ID_MASK;
40
let sequence = u16::from_be_bytes([frame[3], frame[4]]);
41
let remaining = frame[5];
42
let source_id = u32::from_be_bytes([frame[6], frame[7], frame[8], frame[9]]);
43
let pending = self.pending.entry(data_id).or_default();
44
if frame[2] & START_FLAG != 0 {
45
*pending = Pending { source_id, remaining, next_sequence: sequence, payload: Vec::new(), started: true };
46
} else if !pending.started || pending.next_sequence != sequence {
47
*pending = Pending::default();
48
return None;
49
} else {
50
pending.remaining = pending.remaining.saturating_sub(1);
51
}
52
pending.next_sequence = sequence.wrapping_add(1);
53
pending.payload.extend_from_slice(&frame[header_length..]);
54
if pending.remaining != 0 {
55
return None;
56
}
57
let finished = std::mem::take(pending);
58
Some(DataMessage { data_id, source_id: finished.source_id, payload: finished.payload })
59
}
60
}
61
62
#[cfg(test)]
63
pub fn frame(data_id: u8, sequence: u16, remaining: u8, start: bool, source_id: u32, payload: &[u8]) -> Vec<u8> {
64
let mut bytes = vec![0x10, FIXED_HEADER as u8, data_id | if start { START_FLAG } else { 0 }];
65
bytes.extend_from_slice(&sequence.to_be_bytes());
66
bytes.push(remaining);
67
bytes.extend_from_slice(&source_id.to_be_bytes());
68
bytes.push(0);
69
bytes.extend_from_slice(payload);
70
bytes
71
}
72
73
#[cfg(test)]
74
mod tests {
75
use super::*;
76
77
#[test]
78
fn a_single_frame_is_one_message() {
79
let mut depacketizer = Depacketizer::default();
80
let message = depacketizer.push(&frame(3, 0, 0, true, 77, b"{\"a\":1}")).unwrap();
81
assert_eq!(message, DataMessage { data_id: 3, source_id: 77, payload: b"{\"a\":1}".to_vec() });
82
}
83
84
#[test]
85
fn fragments_join_in_sequence_and_other_ids_do_not_interfere() {
86
let mut depacketizer = Depacketizer::default();
87
assert!(depacketizer.push(&frame(3, 10, 2, true, 5, b"he")).is_none());
88
assert!(depacketizer.push(&frame(9, 0, 0, true, 6, b"x")).is_some());
89
assert!(depacketizer.push(&frame(3, 11, 2, false, 5, b"ll")).is_none());
90
let message = depacketizer.push(&frame(3, 12, 2, false, 5, b"o")).unwrap();
91
assert_eq!(message.payload, b"hello");
92
assert_eq!(message.source_id, 5);
93
}
94
95
#[test]
96
fn a_gap_in_the_sequence_drops_the_message() {
97
let mut depacketizer = Depacketizer::default();
98
assert!(depacketizer.push(&frame(3, 1, 1, true, 5, b"a")).is_none());
99
assert!(depacketizer.push(&frame(3, 5, 1, false, 5, b"b")).is_none());
100
assert!(depacketizer.push(&frame(3, 6, 1, false, 5, b"c")).is_none());
101
}
102
103
#[test]
104
fn a_continuation_without_a_start_and_short_frames_are_ignored() {
105
let mut depacketizer = Depacketizer::default();
106
assert!(depacketizer.push(&frame(3, 0, 0, false, 5, b"a")).is_none());
107
assert!(depacketizer.push(&[0x10, 11, 0x83]).is_none());
108
assert!(depacketizer.push(&[]).is_none());
109
}
110
111
#[test]
112
fn recipients_in_the_header_are_skipped() {
113
let mut bytes = frame(3, 0, 0, true, 5, b"");
114
bytes[1] = (FIXED_HEADER + 4) as u8;
115
bytes[10] = 1;
116
bytes.extend_from_slice(&9u32.to_be_bytes());
117
bytes.extend_from_slice(b"body");
118
let message = Depacketizer::default().push(&bytes).unwrap();
119
assert_eq!(message.payload, b"body");
120
}
121
}
@@ -0,0 +1,121 @@1
use std::collections::HashMap;2
3
const FIXED_HEADER: usize = 11;4
const START_FLAG: u8 = 0x80;5
const DATA_ID_MASK: u8 = 0x3f;6
const LENGTH_HIGH_MASK: u8 = 0x0f;7
8
#[derive(Debug, Clone, PartialEq, Eq)]9
pub struct DataMessage {10
pub data_id: u8,11
pub source_id: u32,12
pub payload: Vec<u8>,13
}14
15
#[derive(Default)]16
struct Pending {17
source_id: u32,18
remaining: u8,19
next_sequence: u16,20
payload: Vec<u8>,21
started: bool,22
}23
24
/// Joins the fragments of the Teams framing on the `main-channel` SCTP data channel.25
#[derive(Default)]26
pub struct Depacketizer {27
pending: HashMap<u8, Pending>,28
}29
30
impl Depacketizer {31
pub fn push(&mut self, frame: &[u8]) -> Option<DataMessage> {32
if frame.len() < FIXED_HEADER {33
return None;34
}35
let header_length = (usize::from(frame[0] & LENGTH_HIGH_MASK) << 8) | usize::from(frame[1]);36
if header_length < FIXED_HEADER || header_length > frame.len() {37
return None;38
}39
let data_id = frame[2] & DATA_ID_MASK;40
let sequence = u16::from_be_bytes([frame[3], frame[4]]);41
let remaining = frame[5];42
let source_id = u32::from_be_bytes([frame[6], frame[7], frame[8], frame[9]]);43
let pending = self.pending.entry(data_id).or_default();44
if frame[2] & START_FLAG != 0 {45
*pending = Pending { source_id, remaining, next_sequence: sequence, payload: Vec::new(), started: true };46
} else if !pending.started || pending.next_sequence != sequence {47
*pending = Pending::default();48
return None;49
} else {50
pending.remaining = pending.remaining.saturating_sub(1);51
}52
pending.next_sequence = sequence.wrapping_add(1);53
pending.payload.extend_from_slice(&frame[header_length..]);54
if pending.remaining != 0 {55
return None;56
}57
let finished = std::mem::take(pending);58
Some(DataMessage { data_id, source_id: finished.source_id, payload: finished.payload })59
}60
}61
62
#[cfg(test)]63
pub fn frame(data_id: u8, sequence: u16, remaining: u8, start: bool, source_id: u32, payload: &[u8]) -> Vec<u8> {64
let mut bytes = vec![0x10, FIXED_HEADER as u8, data_id | if start { START_FLAG } else { 0 }];65
bytes.extend_from_slice(&sequence.to_be_bytes());66
bytes.push(remaining);67
bytes.extend_from_slice(&source_id.to_be_bytes());68
bytes.push(0);69
bytes.extend_from_slice(payload);70
bytes71
}72
73
#[cfg(test)]74
mod tests {75
use super::*;76
77
#[test]78
fn a_single_frame_is_one_message() {79
let mut depacketizer = Depacketizer::default();80
let message = depacketizer.push(&frame(3, 0, 0, true, 77, b"{\"a\":1}")).unwrap();81
assert_eq!(message, DataMessage { data_id: 3, source_id: 77, payload: b"{\"a\":1}".to_vec() });82
}83
84
#[test]85
fn fragments_join_in_sequence_and_other_ids_do_not_interfere() {86
let mut depacketizer = Depacketizer::default();87
assert!(depacketizer.push(&frame(3, 10, 2, true, 5, b"he")).is_none());88
assert!(depacketizer.push(&frame(9, 0, 0, true, 6, b"x")).is_some());89
assert!(depacketizer.push(&frame(3, 11, 2, false, 5, b"ll")).is_none());90
let message = depacketizer.push(&frame(3, 12, 2, false, 5, b"o")).unwrap();91
assert_eq!(message.payload, b"hello");92
assert_eq!(message.source_id, 5);93
}94
95
#[test]96
fn a_gap_in_the_sequence_drops_the_message() {97
let mut depacketizer = Depacketizer::default();98
assert!(depacketizer.push(&frame(3, 1, 1, true, 5, b"a")).is_none());99
assert!(depacketizer.push(&frame(3, 5, 1, false, 5, b"b")).is_none());100
assert!(depacketizer.push(&frame(3, 6, 1, false, 5, b"c")).is_none());101
}102
103
#[test]104
fn a_continuation_without_a_start_and_short_frames_are_ignored() {105
let mut depacketizer = Depacketizer::default();106
assert!(depacketizer.push(&frame(3, 0, 0, false, 5, b"a")).is_none());107
assert!(depacketizer.push(&[0x10, 11, 0x83]).is_none());108
assert!(depacketizer.push(&[]).is_none());109
}110
111
#[test]112
fn recipients_in_the_header_are_skipped() {113
let mut bytes = frame(3, 0, 0, true, 5, b"");114
bytes[1] = (FIXED_HEADER + 4) as u8;115
bytes[10] = 1;116
bytes.extend_from_slice(&9u32.to_be_bytes());117
bytes.extend_from_slice(b"body");118
let message = Depacketizer::default().push(&bytes).unwrap();119
assert_eq!(message.payload, b"body");120
}121
}@@ -1,9 +1,12 @@
1
1
pub mod audio;
2
2
pub mod audio_io;
3
3
pub mod call;
4
pub mod blur;
4
5
pub mod camera;
6
pub mod captions;
5
7
pub mod capture;
6
8
pub mod control;
9
pub mod data_channel;
7
10
pub mod devices;
8
11
pub mod engine;
9
12
pub mod end;
@@ -14,6 +17,7 @@ mod loopback_windows;
14
17
pub mod meeting;
15
18
pub mod mixer;
16
19
pub mod mute;
20
pub mod organizer;
17
21
pub mod pcm;
18
22
pub mod push;
19
23
pub mod reaction;
@@ -43,7 +47,8 @@ pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
43
47
pub use push::Caller;
44
48
pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
45
49
pub use reaction::{Reaction, ReactionEvent};
46
pub use roster::{RaisedHand, RosterEntry};
50
pub use captions::{CaptionEntry, CaptionState};
51
pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};
47
52
pub use sound_capture::LoopbackKind;
48
53
pub use signaling::{Callee, MeetingTarget};
49
54
pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
@@ -1,9 +1,12 @@1
pub mod audio;1
pub mod audio;2
pub mod audio_io;2
pub mod audio_io;3
pub mod call;3
pub mod call;4
pub mod blur;4
pub mod camera;5
pub mod camera;6
pub mod captions;5
pub mod capture;7
pub mod capture;6
pub mod control;8
pub mod control;9
pub mod data_channel;7
pub mod devices;10
pub mod devices;8
pub mod engine;11
pub mod engine;9
pub mod end;12
pub mod end;@@ -14,6 +17,7 @@ mod loopback_windows;14
pub mod meeting;17
pub mod meeting;15
pub mod mixer;18
pub mod mixer;16
pub mod mute;19
pub mod mute;20
pub mod organizer;17
pub mod pcm;21
pub mod pcm;18
pub mod push;22
pub mod push;19
pub mod reaction;23
pub mod reaction;@@ -43,7 +47,8 @@ pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};43
pub use push::Caller;47
pub use push::Caller;44
pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};48
pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};45
pub use reaction::{Reaction, ReactionEvent};49
pub use reaction::{Reaction, ReactionEvent};46
pub use roster::{RaisedHand, RosterEntry};50
pub use captions::{CaptionEntry, CaptionState};51
pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};47
pub use sound_capture::LoopbackKind;52
pub use sound_capture::LoopbackKind;48
pub use signaling::{Callee, MeetingTarget};53
pub use signaling::{Callee, MeetingTarget};49
pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};54
pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};@@ -0,0 +1,151 @@
1
use serde_json::{Value, json};
2
3
use crate::trouter_events::CallbackLinks;
4
5
const SPOTLIGHT: &str = "spotlight";
6
const AUDIO: &str = "audio";
7
const SPECIFIED: &str = "specified";
8
const EVERYONE: &str = "all";
9
10
#[derive(Debug, Clone, Copy)]
11
pub struct Target<'a> {
12
pub mri: &'a str,
13
pub display_name: &'a str,
14
}
15
16
impl Target<'_> {
17
fn wire(&self) -> Value {
18
json!({"id": self.mri, "displayName": self.display_name})
19
}
20
}
21
22
pub fn admit_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks, cause_id: &str) -> Value {
23
json!({
24
"participants": {"from": from, "to": [target.wire()]},
25
"links": {
26
"admitFailure": callbacks.conversation("admitParticipantFailure"),
27
"admitSuccess": callbacks.conversation("admitParticipantSuccess"),
28
},
29
"debugContent": {"causeId": cause_id},
30
})
31
}
32
33
pub fn admit_all_body(from: Value, callbacks: &CallbackLinks, operation_id: &str) -> Value {
34
json!({
35
"participants": {"from": from},
36
"links": {"admitAllStatus": callbacks.conversation("admitAllStatus")},
37
"operationId": operation_id,
38
"debugContent": {"causeId": operation_id},
39
})
40
}
41
42
pub fn remove_participant_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks) -> Value {
43
json!({
44
"participants": {"from": from, "to": [target.wire()]},
45
"links": {
46
"removeParticipantSuccess": callbacks.conversation("removeParticipantSuccess"),
47
"removeParticipantFailure": callbacks.conversation("removeParticipantFailure"),
48
},
49
})
50
}
51
52
pub fn mute_participants_body(from: Value, mris: &[String]) -> Value {
53
mute_body(from, SPECIFIED, mris)
54
}
55
56
pub fn mute_everyone_body(from: Value, others: &[String]) -> Value {
57
mute_body(from, EVERYONE, others)
58
}
59
60
fn mute_body(from: Value, scope: &str, mris: &[String]) -> Value {
61
json!({
62
"from": from,
63
"scope": scope,
64
"muteParticipants": mris.iter().map(|mri| json!({"id": mri})).collect::<Vec<_>>(),
65
"mediaTypes": [AUDIO],
66
})
67
}
68
69
pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &str) -> Value {
70
let mut body = json!({
71
"from": from,
72
"publishedState": {
73
"stateType": SPOTLIGHT,
74
"level": "user",
75
"content": {},
76
"sequenceNumber": sequence_number,
77
},
78
});
79
if mri != own_mri {
80
body["scope"] = json!(SPECIFIED);
81
body["to"] = json!([{"id": mri}]);
82
}
83
body
84
}
85
86
#[cfg(test)]
87
mod tests {
88
use super::*;
89
90
fn callbacks() -> CallbackLinks {
91
CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")
92
}
93
94
fn from() -> Value {
95
json!({"id": "8:orgid:me"})
96
}
97
98
fn ana() -> Target<'static> {
99
Target { mri: "8:orgid:ana", display_name: "Ana" }
100
}
101
102
#[test]
103
fn admitting_one_names_the_person_and_both_callbacks() {
104
let body = admit_body(from(), ana(), &callbacks(), "cause-1");
105
assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");
106
assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:ana", "displayName": "Ana"}]));
107
assert!(body["links"]["admitSuccess"].as_str().unwrap().contains("/conversation/admitParticipantSuccess/"));
108
assert!(body["links"]["admitFailure"].as_str().unwrap().contains("/conversation/admitParticipantFailure/"));
109
assert_eq!(body["debugContent"]["causeId"], "cause-1");
110
}
111
112
#[test]
113
fn admitting_everyone_has_no_recipients() {
114
let body = admit_all_body(from(), &callbacks(), "op-1");
115
assert!(body["participants"].get("to").is_none());
116
assert_eq!(body["operationId"], "op-1");
117
assert!(body["links"]["admitAllStatus"].as_str().unwrap().contains("/conversation/admitAllStatus/"));
118
}
119
120
#[test]
121
fn denying_and_removing_use_the_remove_body() {
122
let body = remove_participant_body(from(), ana(), &callbacks());
123
assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
124
assert!(body["links"]["removeParticipantSuccess"].as_str().unwrap().contains("/conversation/removeParticipantSuccess/"));
125
assert!(body["links"]["removeParticipantFailure"].as_str().unwrap().contains("/conversation/removeParticipantFailure/"));
126
}
127
128
#[test]
129
fn muting_one_or_all_only_changes_the_scope() {
130
let one = mute_participants_body(from(), &["8:orgid:ana".to_owned()]);
131
assert_eq!(one["scope"], "specified");
132
assert_eq!(one["muteParticipants"], json!([{"id": "8:orgid:ana"}]));
133
assert_eq!(one["mediaTypes"], json!(["audio"]));
134
let everyone = mute_everyone_body(from(), &["8:orgid:ana".to_owned(), "8:orgid:bo".to_owned()]);
135
assert_eq!(everyone["scope"], "all");
136
assert_eq!(everyone["muteParticipants"].as_array().unwrap().len(), 2);
137
}
138
139
#[test]
140
fn spotlighting_someone_else_is_targeted_and_self_is_not() {
141
let other = spotlight_body(from(), 4, "8:orgid:ana", "8:orgid:me");
142
assert_eq!(other["publishedState"]["stateType"], "spotlight");
143
assert_eq!(other["publishedState"]["level"], "user");
144
assert_eq!(other["publishedState"]["sequenceNumber"], 4);
145
assert_eq!(other["scope"], "specified");
146
assert_eq!(other["to"], json!([{"id": "8:orgid:ana"}]));
147
let own = spotlight_body(from(), 5, "8:orgid:me", "8:orgid:me");
148
assert!(own.get("scope").is_none());
149
assert!(own.get("to").is_none());
150
}
151
}
@@ -0,0 +1,151 @@1
use serde_json::{Value, json};2
3
use crate::trouter_events::CallbackLinks;4
5
const SPOTLIGHT: &str = "spotlight";6
const AUDIO: &str = "audio";7
const SPECIFIED: &str = "specified";8
const EVERYONE: &str = "all";9
10
#[derive(Debug, Clone, Copy)]11
pub struct Target<'a> {12
pub mri: &'a str,13
pub display_name: &'a str,14
}15
16
impl Target<'_> {17
fn wire(&self) -> Value {18
json!({"id": self.mri, "displayName": self.display_name})19
}20
}21
22
pub fn admit_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks, cause_id: &str) -> Value {23
json!({24
"participants": {"from": from, "to": [target.wire()]},25
"links": {26
"admitFailure": callbacks.conversation("admitParticipantFailure"),27
"admitSuccess": callbacks.conversation("admitParticipantSuccess"),28
},29
"debugContent": {"causeId": cause_id},30
})31
}32
33
pub fn admit_all_body(from: Value, callbacks: &CallbackLinks, operation_id: &str) -> Value {34
json!({35
"participants": {"from": from},36
"links": {"admitAllStatus": callbacks.conversation("admitAllStatus")},37
"operationId": operation_id,38
"debugContent": {"causeId": operation_id},39
})40
}41
42
pub fn remove_participant_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks) -> Value {43
json!({44
"participants": {"from": from, "to": [target.wire()]},45
"links": {46
"removeParticipantSuccess": callbacks.conversation("removeParticipantSuccess"),47
"removeParticipantFailure": callbacks.conversation("removeParticipantFailure"),48
},49
})50
}51
52
pub fn mute_participants_body(from: Value, mris: &[String]) -> Value {53
mute_body(from, SPECIFIED, mris)54
}55
56
pub fn mute_everyone_body(from: Value, others: &[String]) -> Value {57
mute_body(from, EVERYONE, others)58
}59
60
fn mute_body(from: Value, scope: &str, mris: &[String]) -> Value {61
json!({62
"from": from,63
"scope": scope,64
"muteParticipants": mris.iter().map(|mri| json!({"id": mri})).collect::<Vec<_>>(),65
"mediaTypes": [AUDIO],66
})67
}68
69
pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &str) -> Value {70
let mut body = json!({71
"from": from,72
"publishedState": {73
"stateType": SPOTLIGHT,74
"level": "user",75
"content": {},76
"sequenceNumber": sequence_number,77
},78
});79
if mri != own_mri {80
body["scope"] = json!(SPECIFIED);81
body["to"] = json!([{"id": mri}]);82
}83
body84
}85
86
#[cfg(test)]87
mod tests {88
use super::*;89
90
fn callbacks() -> CallbackLinks {91
CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")92
}93
94
fn from() -> Value {95
json!({"id": "8:orgid:me"})96
}97
98
fn ana() -> Target<'static> {99
Target { mri: "8:orgid:ana", display_name: "Ana" }100
}101
102
#[test]103
fn admitting_one_names_the_person_and_both_callbacks() {104
let body = admit_body(from(), ana(), &callbacks(), "cause-1");105
assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");106
assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:ana", "displayName": "Ana"}]));107
assert!(body["links"]["admitSuccess"].as_str().unwrap().contains("/conversation/admitParticipantSuccess/"));108
assert!(body["links"]["admitFailure"].as_str().unwrap().contains("/conversation/admitParticipantFailure/"));109
assert_eq!(body["debugContent"]["causeId"], "cause-1");110
}111
112
#[test]113
fn admitting_everyone_has_no_recipients() {114
let body = admit_all_body(from(), &callbacks(), "op-1");115
assert!(body["participants"].get("to").is_none());116
assert_eq!(body["operationId"], "op-1");117
assert!(body["links"]["admitAllStatus"].as_str().unwrap().contains("/conversation/admitAllStatus/"));118
}119
120
#[test]121
fn denying_and_removing_use_the_remove_body() {122
let body = remove_participant_body(from(), ana(), &callbacks());123
assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");124
assert!(body["links"]["removeParticipantSuccess"].as_str().unwrap().contains("/conversation/removeParticipantSuccess/"));125
assert!(body["links"]["removeParticipantFailure"].as_str().unwrap().contains("/conversation/removeParticipantFailure/"));126
}127
128
#[test]129
fn muting_one_or_all_only_changes_the_scope() {130
let one = mute_participants_body(from(), &["8:orgid:ana".to_owned()]);131
assert_eq!(one["scope"], "specified");132
assert_eq!(one["muteParticipants"], json!([{"id": "8:orgid:ana"}]));133
assert_eq!(one["mediaTypes"], json!(["audio"]));134
let everyone = mute_everyone_body(from(), &["8:orgid:ana".to_owned(), "8:orgid:bo".to_owned()]);135
assert_eq!(everyone["scope"], "all");136
assert_eq!(everyone["muteParticipants"].as_array().unwrap().len(), 2);137
}138
139
#[test]140
fn spotlighting_someone_else_is_targeted_and_self_is_not() {141
let other = spotlight_body(from(), 4, "8:orgid:ana", "8:orgid:me");142
assert_eq!(other["publishedState"]["stateType"], "spotlight");143
assert_eq!(other["publishedState"]["level"], "user");144
assert_eq!(other["publishedState"]["sequenceNumber"], 4);145
assert_eq!(other["scope"], "specified");146
assert_eq!(other["to"], json!([{"id": "8:orgid:ana"}]));147
let own = spotlight_body(from(), 5, "8:orgid:me", "8:orgid:me");148
assert!(own.get("scope").is_none());149
assert!(own.get("to").is_none());150
}151
}@@ -6,13 +6,26 @@ const VIDEO: &str = "video";
6
6
const SCREEN: &str = "applicationsharing-video";
7
7
const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
8
8
const RAISE_HANDS: &str = "raiseHands";
9
const SPOTLIGHT: &str = "spotlight";
10
const ORGANIZER_ROLES: [&str; 2] = ["organizer", "coorganizer"];
11
const BOT_PREFIX: &str = "28:";
9
12
10
13
#[derive(Debug, Clone, PartialEq, Eq)]
11
pub struct RaisedHand {
14
pub struct PublishedState {
12
15
pub state_id: String,
13
16
pub rank: u64,
14
17
}
15
18
19
pub type RaisedHand = PublishedState;
20
pub type Spotlight = PublishedState;
21
22
#[derive(Debug, Clone, PartialEq, Eq)]
23
pub struct CaptionBot {
24
pub mri: String,
25
pub command_url: Option<String>,
26
pub active: bool,
27
}
28
16
29
#[derive(Debug, Clone, PartialEq, Eq)]
17
30
pub struct Member {
18
31
pub mri: String,
@@ -24,6 +37,9 @@ pub struct Member {
24
37
pub screen_source: Option<u32>,
25
38
pub streams: Vec<String>,
26
39
pub hand: Option<RaisedHand>,
40
pub spotlight: Option<Spotlight>,
41
pub organizer: bool,
42
pub captions: Option<CaptionBot>,
27
43
version: u64,
28
44
}
29
45
@@ -36,6 +52,8 @@ pub struct RosterEntry {
36
52
pub has_video: bool,
37
53
pub sharing: bool,
38
54
pub hand: Option<RaisedHand>,
55
pub spotlight: Option<Spotlight>,
56
pub organizer: bool,
39
57
}
40
58
41
59
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -60,6 +78,8 @@ impl Roster {
60
78
has_video: member.video_source.is_some(),
61
79
sharing: member.screen_source.is_some(),
62
80
hand: member.hand.clone(),
81
spotlight: member.spotlight.clone(),
82
organizer: member.organizer,
63
83
})
64
84
.collect()
65
85
}
@@ -97,6 +117,27 @@ impl Roster {
97
117
self.members.iter().find(|member| member.mri == mri)?.hand.as_ref()
98
118
}
99
119
120
pub fn spotlight_of(&self, mri: &str) -> Option<&Spotlight> {
121
self.members.iter().find(|member| member.mri == mri)?.spotlight.as_ref()
122
}
123
124
pub fn caption_bot(&self) -> Option<&CaptionBot> {
125
self.members.iter().find_map(|member| member.captions.as_ref())
126
}
127
128
pub fn name_of(&self, user_id: &str) -> Option<&str> {
129
let suffix = format!(":{user_id}");
130
self.members
131
.iter()
132
.find(|member| member.mri == user_id || member.mri.ends_with(&suffix))
133
.map(|member| member.display_name.as_str())
134
.filter(|name| !name.is_empty())
135
}
136
137
pub fn is_organizer(&self, mri: &str) -> bool {
138
self.members.iter().any(|member| member.mri == mri && member.organizer)
139
}
140
100
141
pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {
101
142
self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)
102
143
}
@@ -161,23 +202,41 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
161
202
video_source: sending_source(&in_call, VIDEO),
162
203
screen_source: sending_source(&in_call, SCREEN),
163
204
streams: stream_summaries(&in_call),
164
hand: raised_hand(participant, &endpoints),
205
hand: published_state(participant, &endpoints, RAISE_HANDS),
206
spotlight: published_state(participant, &endpoints, SPOTLIGHT),
207
organizer: is_organizer_role(participant),
208
captions: mri.starts_with(BOT_PREFIX).then(|| caption_bot(mri, &endpoints)).flatten(),
165
209
version,
166
210
}
167
211
}
168
212
169
fn raised_hand(participant: &Value, endpoints: &[&Value]) -> Option<RaisedHand> {
213
fn is_organizer_role(participant: &Value) -> bool {
214
["meetingRole", "role"]
215
.iter()
216
.filter_map(|key| participant[*key].as_str())
217
.any(|role| ORGANIZER_ROLES.contains(&role.to_ascii_lowercase().as_str()))
218
}
219
220
fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {
221
let metadata: Vec<&Value> = endpoints.iter().map(|endpoint| &endpoint["endpointMetadata"]).filter(|metadata| metadata.is_object()).collect();
222
let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);
223
let known = command_url.is_some() || metadata.iter().any(|metadata| metadata["processingModes"].is_object());
224
let active = metadata.iter().any(|metadata| metadata["processingModes"]["closedCaptions"]["state"].as_str() == Some("Active"));
225
known.then(|| CaptionBot { mri: mri.to_owned(), command_url, active })
226
}
227
228
fn published_state(participant: &Value, endpoints: &[&Value], state_type: &str) -> Option<PublishedState> {
170
229
std::iter::once(participant)
171
230
.chain(endpoints.iter().copied())
172
231
.flat_map(|holder| holder["publishedStates"].as_array().into_iter().flatten())
173
.filter(|state| state["stateType"].as_str() == Some(RAISE_HANDS))
232
.filter(|state| state["stateType"].as_str() == Some(state_type))
174
233
.find_map(|state| {
175
234
let state_id = match &state["stateId"] {
176
235
Value::String(text) => text.clone(),
177
236
Value::Null => return None,
178
237
other => other.to_string(),
179
238
};
180
Some(RaisedHand { state_id, rank: state["typeRank"].as_u64().unwrap_or(u64::MAX) })
239
Some(PublishedState { state_id, rank: state["typeRank"].as_u64().unwrap_or(u64::MAX) })
181
240
})
182
241
}
183
242
@@ -395,4 +454,99 @@ mod tests {
395
454
roster.apply(&delta(json!({"8:orgid:a": {"version": 2, "state": "active", "endpoints": {"ep": {"call": {}}}}})));
396
455
assert_eq!(roster.members()[0].display_name, "Ana");
397
456
}
457
458
fn lobby_guest(name: &str, version: u64) -> Value {
459
json!({"version": version, "state": "active", "details": {"displayName": name}, "endpoints": {"ep": {"lobby": {"mediaStreams": []}}}})
460
}
461
462
#[test]
463
fn people_in_the_lobby_are_listed_with_their_names_and_counted() {
464
let mut roster = Roster::default();
465
let mut body = delta(json!({
466
"8:orgid:me": participant("Me", 1, "active", false, 201),
467
"8:orgid:g1": lobby_guest("Gast Eins", 1),
468
"8:orgid:g2": lobby_guest("Gast Zwei", 1),
469
}));
470
body["participantCounts"] = json!({"lobbyParticipants": 2});
471
roster.apply(&body);
472
assert_eq!(roster.lobby_count, 2);
473
let waiting: Vec<String> = roster.entries().into_iter().filter(|entry| entry.in_lobby).map(|entry| entry.display_name).collect();
474
assert_eq!(waiting, vec!["Gast Eins".to_owned(), "Gast Zwei".to_owned()]);
475
assert!(roster.video_candidates("8:orgid:me").is_empty());
476
roster.apply(&delta(json!({"8:orgid:g1": participant("Gast Eins", 2, "active", true, 301)})));
477
assert_eq!(roster.is_in_lobby("8:orgid:g1"), Some(false));
478
roster.apply(&delta(json!({"8:orgid:g2": participant("Gast Zwei", 2, "inactive", true, 401)})));
479
assert_eq!(roster.is_in_lobby("8:orgid:g2"), None);
480
}
481
482
fn with_spotlight(mut person: Value, state_id: &str, rank: u64) -> Value {
483
person["publishedStates"] = json!([{"stateType": "spotlight", "content": {}, "stateId": state_id, "typeRank": rank}]);
484
person
485
}
486
487
#[test]
488
fn a_spotlight_state_marks_the_participant_and_vanishes_when_removed() {
489
let mut roster = Roster::default();
490
roster.apply(&delta(json!({
491
"8:orgid:a": with_spotlight(participant("Ana", 1, "active", false, 201), "sp-1", 1),
492
"8:orgid:b": participant("Bo", 1, "active", false, 301),
493
})));
494
assert_eq!(roster.spotlight_of("8:orgid:a"), Some(&Spotlight { state_id: "sp-1".into(), rank: 1 }));
495
assert_eq!(roster.spotlight_of("8:orgid:b"), None);
496
assert_eq!(roster.hand_of("8:orgid:a"), None);
497
assert!(roster.entries().iter().find(|entry| entry.display_name == "Ana").unwrap().spotlight.is_some());
498
roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 2, "active", false, 201)})));
499
assert_eq!(roster.spotlight_of("8:orgid:a"), None);
500
}
501
502
#[test]
503
fn the_organizer_role_comes_from_the_meeting_role() {
504
let mut roster = Roster::default();
505
let mut host = participant("Me", 1, "active", false, 201);
506
host["meetingRole"] = json!("organizer");
507
let mut presenter = participant("Ana", 1, "active", false, 301);
508
presenter["meetingRole"] = json!("presenter");
509
presenter["role"] = json!("admin");
510
let mut co_organizer = participant("Bo", 1, "active", false, 401);
511
co_organizer["meetingRole"] = json!("coorganizer");
512
roster.apply(&delta(json!({"8:orgid:me": host, "8:orgid:a": presenter, "8:orgid:b": co_organizer})));
513
assert!(roster.is_organizer("8:orgid:me"));
514
assert!(!roster.is_organizer("8:orgid:a"));
515
assert!(roster.is_organizer("8:orgid:b"));
516
}
517
518
fn recorder_bot(version: u64, active: bool) -> Value {
519
json!({"version": version, "state": "active", "details": {"displayName": "Recorder"}, "meetingRole": "presenter", "endpoints": {"ep": {
520
"call": {"mediaStreams": []},
521
"endpointMetadata": {
522
"commandUrl": "https://api.flightproxy.teams.microsoft.com/api/v2/ep/recorder/v2/oncommand/1",
523
"processingModes": {"closedCaptions": {"state": if active { "Active" } else { "Inactive" }}},
524
},
525
}}})
526
}
527
528
#[test]
529
fn the_caption_bot_is_found_by_its_command_url_and_state() {
530
let mut roster = Roster::default();
531
roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 1, "active", false, 201)})));
532
assert_eq!(roster.caption_bot(), None);
533
roster.apply(&delta(json!({"28:bot": recorder_bot(1, false)})));
534
let bot = roster.caption_bot().unwrap();
535
assert_eq!(bot.mri, "28:bot");
536
assert!(bot.command_url.as_deref().unwrap().ends_with("/v2/oncommand/1"));
537
assert!(!bot.active);
538
roster.apply(&delta(json!({"28:bot": recorder_bot(2, true)})));
539
assert!(roster.caption_bot().unwrap().active);
540
roster.apply(&delta(json!({"28:bot": {"version": 3, "state": "inactive"}})));
541
assert_eq!(roster.caption_bot(), None);
542
}
543
544
#[test]
545
fn caption_speakers_resolve_by_mri_or_object_id() {
546
let mut roster = Roster::default();
547
roster.apply(&delta(json!({"8:orgid:abc-123": participant("Ana", 1, "active", false, 201)})));
548
assert_eq!(roster.name_of("8:orgid:abc-123"), Some("Ana"));
549
assert_eq!(roster.name_of("abc-123"), Some("Ana"));
550
assert_eq!(roster.name_of("zzz"), None);
551
}
398
552
}
@@ -6,13 +6,26 @@ const VIDEO: &str = "video";6
const SCREEN: &str = "applicationsharing-video";6
const SCREEN: &str = "applicationsharing-video";7
const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];7
const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];8
const RAISE_HANDS: &str = "raiseHands";8
const RAISE_HANDS: &str = "raiseHands";9
const SPOTLIGHT: &str = "spotlight";10
const ORGANIZER_ROLES: [&str; 2] = ["organizer", "coorganizer"];11
const BOT_PREFIX: &str = "28:";9
12
10
#[derive(Debug, Clone, PartialEq, Eq)]13
#[derive(Debug, Clone, PartialEq, Eq)]11
pub struct RaisedHand {14
pub struct PublishedState {12
pub state_id: String,15
pub state_id: String,13
pub rank: u64,16
pub rank: u64,14
}17
}15
18
19
pub type RaisedHand = PublishedState;20
pub type Spotlight = PublishedState;21
22
#[derive(Debug, Clone, PartialEq, Eq)]23
pub struct CaptionBot {24
pub mri: String,25
pub command_url: Option<String>,26
pub active: bool,27
}28
16
#[derive(Debug, Clone, PartialEq, Eq)]29
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct Member {30
pub struct Member {18
pub mri: String,31
pub mri: String,@@ -24,6 +37,9 @@ pub struct Member {24
pub screen_source: Option<u32>,37
pub screen_source: Option<u32>,25
pub streams: Vec<String>,38
pub streams: Vec<String>,26
pub hand: Option<RaisedHand>,39
pub hand: Option<RaisedHand>,40
pub spotlight: Option<Spotlight>,41
pub organizer: bool,42
pub captions: Option<CaptionBot>,27
version: u64,43
version: u64,28
}44
}29
45
@@ -36,6 +52,8 @@ pub struct RosterEntry {36
pub has_video: bool,52
pub has_video: bool,37
pub sharing: bool,53
pub sharing: bool,38
pub hand: Option<RaisedHand>,54
pub hand: Option<RaisedHand>,55
pub spotlight: Option<Spotlight>,56
pub organizer: bool,39
}57
}40
58
41
#[derive(Debug, Clone, Default, PartialEq, Eq)]59
#[derive(Debug, Clone, Default, PartialEq, Eq)]@@ -60,6 +78,8 @@ impl Roster {60
has_video: member.video_source.is_some(),78
has_video: member.video_source.is_some(),61
sharing: member.screen_source.is_some(),79
sharing: member.screen_source.is_some(),62
hand: member.hand.clone(),80
hand: member.hand.clone(),81
spotlight: member.spotlight.clone(),82
organizer: member.organizer,63
})83
})64
.collect()84
.collect()65
}85
}@@ -97,6 +117,27 @@ impl Roster {97
self.members.iter().find(|member| member.mri == mri)?.hand.as_ref()117
self.members.iter().find(|member| member.mri == mri)?.hand.as_ref()98
}118
}99
119
120
pub fn spotlight_of(&self, mri: &str) -> Option<&Spotlight> {121
self.members.iter().find(|member| member.mri == mri)?.spotlight.as_ref()122
}123
124
pub fn caption_bot(&self) -> Option<&CaptionBot> {125
self.members.iter().find_map(|member| member.captions.as_ref())126
}127
128
pub fn name_of(&self, user_id: &str) -> Option<&str> {129
let suffix = format!(":{user_id}");130
self.members131
.iter()132
.find(|member| member.mri == user_id || member.mri.ends_with(&suffix))133
.map(|member| member.display_name.as_str())134
.filter(|name| !name.is_empty())135
}136
137
pub fn is_organizer(&self, mri: &str) -> bool {138
self.members.iter().any(|member| member.mri == mri && member.organizer)139
}140
100
pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {141
pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {101
self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)142
self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)102
}143
}@@ -161,23 +202,41 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M161
video_source: sending_source(&in_call, VIDEO),202
video_source: sending_source(&in_call, VIDEO),162
screen_source: sending_source(&in_call, SCREEN),203
screen_source: sending_source(&in_call, SCREEN),163
streams: stream_summaries(&in_call),204
streams: stream_summaries(&in_call),164
hand: raised_hand(participant, &endpoints),205
hand: published_state(participant, &endpoints, RAISE_HANDS),206
spotlight: published_state(participant, &endpoints, SPOTLIGHT),207
organizer: is_organizer_role(participant),208
captions: mri.starts_with(BOT_PREFIX).then(|| caption_bot(mri, &endpoints)).flatten(),165
version,209
version,166
}210
}167
}211
}168
212
169
fn raised_hand(participant: &Value, endpoints: &[&Value]) -> Option<RaisedHand> {213
fn is_organizer_role(participant: &Value) -> bool {214
["meetingRole", "role"]215
.iter()216
.filter_map(|key| participant[*key].as_str())217
.any(|role| ORGANIZER_ROLES.contains(&role.to_ascii_lowercase().as_str()))218
}219
220
fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {221
let metadata: Vec<&Value> = endpoints.iter().map(|endpoint| &endpoint["endpointMetadata"]).filter(|metadata| metadata.is_object()).collect();222
let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);223
let known = command_url.is_some() || metadata.iter().any(|metadata| metadata["processingModes"].is_object());224
let active = metadata.iter().any(|metadata| metadata["processingModes"]["closedCaptions"]["state"].as_str() == Some("Active"));225
known.then(|| CaptionBot { mri: mri.to_owned(), command_url, active })226
}227
228
fn published_state(participant: &Value, endpoints: &[&Value], state_type: &str) -> Option<PublishedState> {170
std::iter::once(participant)229
std::iter::once(participant)171
.chain(endpoints.iter().copied())230
.chain(endpoints.iter().copied())172
.flat_map(|holder| holder["publishedStates"].as_array().into_iter().flatten())231
.flat_map(|holder| holder["publishedStates"].as_array().into_iter().flatten())173
.filter(|state| state["stateType"].as_str() == Some(RAISE_HANDS))232
.filter(|state| state["stateType"].as_str() == Some(state_type))174
.find_map(|state| {233
.find_map(|state| {175
let state_id = match &state["stateId"] {234
let state_id = match &state["stateId"] {176
Value::String(text) => text.clone(),235
Value::String(text) => text.clone(),177
Value::Null => return None,236
Value::Null => return None,178
other => other.to_string(),237
other => other.to_string(),179
};238
};180
Some(RaisedHand { state_id, rank: state["typeRank"].as_u64().unwrap_or(u64::MAX) })239
Some(PublishedState { state_id, rank: state["typeRank"].as_u64().unwrap_or(u64::MAX) })181
})240
})182
}241
}183
242
@@ -395,4 +454,99 @@ mod tests {395
roster.apply(&delta(json!({"8:orgid:a": {"version": 2, "state": "active", "endpoints": {"ep": {"call": {}}}}})));454
roster.apply(&delta(json!({"8:orgid:a": {"version": 2, "state": "active", "endpoints": {"ep": {"call": {}}}}})));396
assert_eq!(roster.members()[0].display_name, "Ana");455
assert_eq!(roster.members()[0].display_name, "Ana");397
}456
}457
458
fn lobby_guest(name: &str, version: u64) -> Value {459
json!({"version": version, "state": "active", "details": {"displayName": name}, "endpoints": {"ep": {"lobby": {"mediaStreams": []}}}})460
}461
462
#[test]463
fn people_in_the_lobby_are_listed_with_their_names_and_counted() {464
let mut roster = Roster::default();465
let mut body = delta(json!({466
"8:orgid:me": participant("Me", 1, "active", false, 201),467
"8:orgid:g1": lobby_guest("Gast Eins", 1),468
"8:orgid:g2": lobby_guest("Gast Zwei", 1),469
}));470
body["participantCounts"] = json!({"lobbyParticipants": 2});471
roster.apply(&body);472
assert_eq!(roster.lobby_count, 2);473
let waiting: Vec<String> = roster.entries().into_iter().filter(|entry| entry.in_lobby).map(|entry| entry.display_name).collect();474
assert_eq!(waiting, vec!["Gast Eins".to_owned(), "Gast Zwei".to_owned()]);475
assert!(roster.video_candidates("8:orgid:me").is_empty());476
roster.apply(&delta(json!({"8:orgid:g1": participant("Gast Eins", 2, "active", true, 301)})));477
assert_eq!(roster.is_in_lobby("8:orgid:g1"), Some(false));478
roster.apply(&delta(json!({"8:orgid:g2": participant("Gast Zwei", 2, "inactive", true, 401)})));479
assert_eq!(roster.is_in_lobby("8:orgid:g2"), None);480
}481
482
fn with_spotlight(mut person: Value, state_id: &str, rank: u64) -> Value {483
person["publishedStates"] = json!([{"stateType": "spotlight", "content": {}, "stateId": state_id, "typeRank": rank}]);484
person485
}486
487
#[test]488
fn a_spotlight_state_marks_the_participant_and_vanishes_when_removed() {489
let mut roster = Roster::default();490
roster.apply(&delta(json!({491
"8:orgid:a": with_spotlight(participant("Ana", 1, "active", false, 201), "sp-1", 1),492
"8:orgid:b": participant("Bo", 1, "active", false, 301),493
})));494
assert_eq!(roster.spotlight_of("8:orgid:a"), Some(&Spotlight { state_id: "sp-1".into(), rank: 1 }));495
assert_eq!(roster.spotlight_of("8:orgid:b"), None);496
assert_eq!(roster.hand_of("8:orgid:a"), None);497
assert!(roster.entries().iter().find(|entry| entry.display_name == "Ana").unwrap().spotlight.is_some());498
roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 2, "active", false, 201)})));499
assert_eq!(roster.spotlight_of("8:orgid:a"), None);500
}501
502
#[test]503
fn the_organizer_role_comes_from_the_meeting_role() {504
let mut roster = Roster::default();505
let mut host = participant("Me", 1, "active", false, 201);506
host["meetingRole"] = json!("organizer");507
let mut presenter = participant("Ana", 1, "active", false, 301);508
presenter["meetingRole"] = json!("presenter");509
presenter["role"] = json!("admin");510
let mut co_organizer = participant("Bo", 1, "active", false, 401);511
co_organizer["meetingRole"] = json!("coorganizer");512
roster.apply(&delta(json!({"8:orgid:me": host, "8:orgid:a": presenter, "8:orgid:b": co_organizer})));513
assert!(roster.is_organizer("8:orgid:me"));514
assert!(!roster.is_organizer("8:orgid:a"));515
assert!(roster.is_organizer("8:orgid:b"));516
}517
518
fn recorder_bot(version: u64, active: bool) -> Value {519
json!({"version": version, "state": "active", "details": {"displayName": "Recorder"}, "meetingRole": "presenter", "endpoints": {"ep": {520
"call": {"mediaStreams": []},521
"endpointMetadata": {522
"commandUrl": "https://api.flightproxy.teams.microsoft.com/api/v2/ep/recorder/v2/oncommand/1",523
"processingModes": {"closedCaptions": {"state": if active { "Active" } else { "Inactive" }}},524
},525
}}})526
}527
528
#[test]529
fn the_caption_bot_is_found_by_its_command_url_and_state() {530
let mut roster = Roster::default();531
roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 1, "active", false, 201)})));532
assert_eq!(roster.caption_bot(), None);533
roster.apply(&delta(json!({"28:bot": recorder_bot(1, false)})));534
let bot = roster.caption_bot().unwrap();535
assert_eq!(bot.mri, "28:bot");536
assert!(bot.command_url.as_deref().unwrap().ends_with("/v2/oncommand/1"));537
assert!(!bot.active);538
roster.apply(&delta(json!({"28:bot": recorder_bot(2, true)})));539
assert!(roster.caption_bot().unwrap().active);540
roster.apply(&delta(json!({"28:bot": {"version": 3, "state": "inactive"}})));541
assert_eq!(roster.caption_bot(), None);542
}543
544
#[test]545
fn caption_speakers_resolve_by_mri_or_object_id() {546
let mut roster = Roster::default();547
roster.apply(&delta(json!({"8:orgid:abc-123": participant("Ana", 1, "active", false, 201)})));548
assert_eq!(roster.name_of("8:orgid:abc-123"), Some("Ana"));549
assert_eq!(roster.name_of("abc-123"), Some("Ana"));550
assert_eq!(roster.name_of("zzz"), None);551
}398
}552
}@@ -1,9 +1,11 @@
1
1
use std::collections::BTreeMap;
2
2
3
3
use serde_json::{Map, Value, json};
4
use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
5
5
6
use crate::captions::{self, BotAction};
6
7
use crate::error::{Error, Result};
8
use crate::organizer::{self, Target};
7
9
use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
8
10
use crate::relay::ic3_scope;
9
11
use crate::timeline::Timeline;
@@ -20,6 +22,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;
20
22
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
21
23
const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
22
24
const BACKEND_SUFFIX: &str = ".skype.com";
25
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
23
26
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
24
27
const CONVERSATION_LINK_NAMES: [&str; 9] = [
25
28
"conversationEnd",
@@ -169,6 +172,10 @@ pub enum LeaveReason {
169
172
Cancel,
170
173
}
171
174
175
fn spaces_scope() -> Scope {
176
Scope::new(SPACES, AUTHZ_SCOPE_NAME)
177
}
178
172
179
pub struct Signaling {
173
180
session: Session,
174
181
poll_session: Session,
@@ -381,14 +388,84 @@ impl Signaling {
381
388
}
382
389
383
390
pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
384
let body = json!({
385
"participants": {"from": from.wire()},
386
"endpointMetadata": {"holographicCapabilities": 3},
387
});
391
self.put_endpoint_metadata(conversation, from, json!({"holographicCapabilities": 3})).await
392
}
393
394
pub async fn set_caption_preference(&self, conversation: &Conversation, from: &Participant, captions: bool) -> Result<()> {
395
self.put_endpoint_metadata(conversation, from, captions::endpoint_metadata(captions)).await
396
}
397
398
async fn put_endpoint_metadata(&self, conversation: &Conversation, from: &Participant, metadata: Value) -> Result<()> {
399
let body = json!({"participants": {"from": from.wire()}, "endpointMetadata": metadata});
388
400
let url = conversation.link("updateEndpointMetadata")?;
389
401
self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())
390
402
}
391
403
404
pub async fn admit(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {
405
let body = organizer::admit_body(from.wire(), target, callbacks, &uuid::Uuid::new_v4().to_string());
406
self.send("POST admit", Method::Post, conversation.link("admit")?, Some(body)).await.map(|response| response.status)
407
}
408
409
pub async fn admit_all(&self, conversation: &Conversation, from: &Participant, callbacks: &CallbackLinks) -> Result<u16> {
410
let body = organizer::admit_all_body(from.wire(), callbacks, &uuid::Uuid::new_v4().to_string());
411
self.send("POST admitAll", Method::Post, conversation.link("admitAll")?, Some(body)).await.map(|response| response.status)
412
}
413
414
pub async fn remove_participant(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {
415
let body = organizer::remove_participant_body(from.wire(), target, callbacks);
416
self.send("POST removeParticipant", Method::Post, conversation.link("removeParticipant")?, Some(body)).await.map(|response| response.status)
417
}
418
419
pub async fn mute_participant(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {
420
let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]);
421
self.send("POST mute", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)
422
}
423
424
pub async fn mute_everyone(&self, conversation: &Conversation, from: &Participant, others: &[String]) -> Result<u16> {
425
let body = organizer::mute_everyone_body(from.wire(), others);
426
self.send("POST mute (all)", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)
427
}
428
429
pub async fn spotlight(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {
430
let body = organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri);
431
self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
432
}
433
434
pub async fn add_caption_bot(
435
&self,
436
conversation: &Conversation,
437
from: &Participant,
438
thread_id: &str,
439
callbacks: &CallbackLinks,
440
) -> Result<()> {
441
let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);
442
let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));
443
request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
444
self.exchange(&self.session, "POST add (caption bot)", request).await.map(|_| ())
445
}
446
447
pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {
448
ensure_teams_url(command_url)?;
449
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
450
let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp);
451
let arguments = json!({
452
"url": command_url,
453
"body": body,
454
"recorderResource": captions::RECORDER_RESOURCE,
455
"recorderScope": captions::RECORDER_SCOPE,
456
"requestId": uuid::Uuid::new_v4().to_string(),
457
"chainId": self.chain_id,
458
});
459
let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;
460
let status = answer["status"].as_u64().unwrap_or_default();
461
self.timeline.record("POST caption command", format!("HTTP {status}"));
462
if (200..300).contains(&status) {
463
return Ok(());
464
}
465
let reason = answer["error"].as_str().unwrap_or("no answer");
466
Err(Error::Signaling(format!("caption command answered HTTP {status} {reason}")))
467
}
468
392
469
/// One broker long poll; answers the next subscribe URL.
393
470
pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {
394
471
let mut request = self.request(Method::Get, url, None);
@@ -1,9 +1,11 @@1
use std::collections::BTreeMap;1
use std::collections::BTreeMap;2
2
3
use serde_json::{Map, Value, json};3
use serde_json::{Map, Value, json};4
use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};5
5
6
use crate::captions::{self, BotAction};6
use crate::error::{Error, Result};7
use crate::error::{Error, Result};8
use crate::organizer::{self, Target};7
use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};9
use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};8
use crate::relay::ic3_scope;10
use crate::relay::ic3_scope;9
use crate::timeline::Timeline;11
use crate::timeline::Timeline;@@ -20,6 +22,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;20
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;22
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;21
const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];23
const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];22
const BACKEND_SUFFIX: &str = ".skype.com";24
const BACKEND_SUFFIX: &str = ".skype.com";25
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";23
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";26
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";24
const CONVERSATION_LINK_NAMES: [&str; 9] = [27
const CONVERSATION_LINK_NAMES: [&str; 9] = [25
"conversationEnd",28
"conversationEnd",@@ -169,6 +172,10 @@ pub enum LeaveReason {169
Cancel,172
Cancel,170
}173
}171
174
175
fn spaces_scope() -> Scope {176
Scope::new(SPACES, AUTHZ_SCOPE_NAME)177
}178
172
pub struct Signaling {179
pub struct Signaling {173
session: Session,180
session: Session,174
poll_session: Session,181
poll_session: Session,@@ -381,14 +388,84 @@ impl Signaling {381
}388
}382
389
383
pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {390
pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {384
let body = json!({391
self.put_endpoint_metadata(conversation, from, json!({"holographicCapabilities": 3})).await385
"participants": {"from": from.wire()},392
}386
"endpointMetadata": {"holographicCapabilities": 3},393
387
});394
pub async fn set_caption_preference(&self, conversation: &Conversation, from: &Participant, captions: bool) -> Result<()> {395
self.put_endpoint_metadata(conversation, from, captions::endpoint_metadata(captions)).await396
}397
398
async fn put_endpoint_metadata(&self, conversation: &Conversation, from: &Participant, metadata: Value) -> Result<()> {399
let body = json!({"participants": {"from": from.wire()}, "endpointMetadata": metadata});388
let url = conversation.link("updateEndpointMetadata")?;400
let url = conversation.link("updateEndpointMetadata")?;389
self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())401
self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())390
}402
}391
403
404
pub async fn admit(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {405
let body = organizer::admit_body(from.wire(), target, callbacks, &uuid::Uuid::new_v4().to_string());406
self.send("POST admit", Method::Post, conversation.link("admit")?, Some(body)).await.map(|response| response.status)407
}408
409
pub async fn admit_all(&self, conversation: &Conversation, from: &Participant, callbacks: &CallbackLinks) -> Result<u16> {410
let body = organizer::admit_all_body(from.wire(), callbacks, &uuid::Uuid::new_v4().to_string());411
self.send("POST admitAll", Method::Post, conversation.link("admitAll")?, Some(body)).await.map(|response| response.status)412
}413
414
pub async fn remove_participant(&self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks) -> Result<u16> {415
let body = organizer::remove_participant_body(from.wire(), target, callbacks);416
self.send("POST removeParticipant", Method::Post, conversation.link("removeParticipant")?, Some(body)).await.map(|response| response.status)417
}418
419
pub async fn mute_participant(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {420
let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]);421
self.send("POST mute", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)422
}423
424
pub async fn mute_everyone(&self, conversation: &Conversation, from: &Participant, others: &[String]) -> Result<u16> {425
let body = organizer::mute_everyone_body(from.wire(), others);426
self.send("POST mute (all)", Method::Post, conversation.link("mute")?, Some(body)).await.map(|response| response.status)427
}428
429
pub async fn spotlight(&self, conversation: &Conversation, from: &Participant, mri: &str) -> Result<u16> {430
let body = organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri);431
self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)432
}433
434
pub async fn add_caption_bot(435
&self,436
conversation: &Conversation,437
from: &Participant,438
thread_id: &str,439
callbacks: &CallbackLinks,440
) -> Result<()> {441
let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);442
let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));443
request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);444
self.exchange(&self.session, "POST add (caption bot)", request).await.map(|_| ())445
}446
447
pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {448
ensure_teams_url(command_url)?;449
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);450
let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp);451
let arguments = json!({452
"url": command_url,453
"body": body,454
"recorderResource": captions::RECORDER_RESOURCE,455
"recorderScope": captions::RECORDER_SCOPE,456
"requestId": uuid::Uuid::new_v4().to_string(),457
"chainId": self.chain_id,458
});459
let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;460
let status = answer["status"].as_u64().unwrap_or_default();461
self.timeline.record("POST caption command", format!("HTTP {status}"));462
if (200..300).contains(&status) {463
return Ok(());464
}465
let reason = answer["error"].as_str().unwrap_or("no answer");466
Err(Error::Signaling(format!("caption command answered HTTP {status} {reason}")))467
}468
392
/// One broker long poll; answers the next subscribe URL.469
/// One broker long poll; answers the next subscribe URL.393
pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {470
pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> {394
let mut request = self.request(Method::Get, url, None);471
let mut request = self.request(Method::Get, url, None);@@ -4,6 +4,7 @@ use libwebrtc::video_frame::I420Buffer;
4
4
use tokio::task::JoinHandle;
5
5
use tokio::time::interval;
6
6
7
use crate::blur::BlurStage;
7
8
use crate::video_send::LocalSink;
8
9
9
10
pub const CAMERA_WIDTH: u32 = 640;
@@ -101,13 +102,17 @@ fn paint_screen(
101
102
v_plane[..(stride_v * height / 2) as usize].fill(128);
102
103
}
103
104
104
pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind) -> JoinHandle<()> {
105
pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind, mut blur: Option<BlurStage>) -> JoinHandle<()> {
105
106
tokio::spawn(async move {
106
107
let mut ticker = interval(Duration::from_secs(1) / kind.fps());
107
108
let mut tick = 0u32;
108
109
loop {
109
110
ticker.tick().await;
110
sink.push(pattern_frame(kind, tick));
111
let frame = pattern_frame(kind, tick);
112
sink.push(match blur.as_mut() {
113
Some(stage) => stage.apply_i420(frame),
114
None => frame,
115
});
111
116
tick = tick.wrapping_add(1);
112
117
}
113
118
})
@@ -4,6 +4,7 @@ use libwebrtc::video_frame::I420Buffer;4
use tokio::task::JoinHandle;4
use tokio::task::JoinHandle;5
use tokio::time::interval;5
use tokio::time::interval;6
6
7
use crate::blur::BlurStage;7
use crate::video_send::LocalSink;8
use crate::video_send::LocalSink;8
9
9
pub const CAMERA_WIDTH: u32 = 640;10
pub const CAMERA_WIDTH: u32 = 640;@@ -101,13 +102,17 @@ fn paint_screen(101
v_plane[..(stride_v * height / 2) as usize].fill(128);102
v_plane[..(stride_v * height / 2) as usize].fill(128);102
}103
}103
104
104
pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind) -> JoinHandle<()> {105
pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind, mut blur: Option<BlurStage>) -> JoinHandle<()> {105
tokio::spawn(async move {106
tokio::spawn(async move {106
let mut ticker = interval(Duration::from_secs(1) / kind.fps());107
let mut ticker = interval(Duration::from_secs(1) / kind.fps());107
let mut tick = 0u32;108
let mut tick = 0u32;108
loop {109
loop {109
ticker.tick().await;110
ticker.tick().await;110
sink.push(pattern_frame(kind, tick));111
let frame = pattern_frame(kind, tick);112
sink.push(match blur.as_mut() {113
Some(stage) => stage.apply_i420(frame),114
None => frame,115
});111
tick = tick.wrapping_add(1);116
tick = tick.wrapping_add(1);112
}117
}113
})118
})@@ -11,6 +11,7 @@ use libwebrtc::video_source::native::NativeVideoSource;
11
11
use libwebrtc::video_track::RtcVideoTrack;
12
12
use tokio::sync::mpsc::UnboundedSender;
13
13
14
use crate::blur::{BlurSettings, BlurStage};
14
15
use crate::camera::start_camera;
15
16
use crate::capture::Capture;
16
17
use crate::control::CallUpdate;
@@ -99,6 +100,7 @@ pub struct LocalVideo {
99
100
camera: Outgoing,
100
101
screen: Outgoing,
101
102
lines: Option<VideoLines>,
103
blur: Arc<BlurSettings>,
102
104
}
103
105
104
106
impl LocalVideo {
@@ -110,9 +112,18 @@ impl LocalVideo {
110
112
camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),
111
113
screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
112
114
lines: None,
115
blur: Arc::new(BlurSettings::default()),
113
116
}
114
117
}
115
118
119
pub fn set_blur(&self, enabled: bool) {
120
self.blur.set_enabled(enabled);
121
}
122
123
pub fn blur_average_ms(&self) -> Option<f32> {
124
(self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())
125
}
126
116
127
pub fn is_available(&self) -> bool {
117
128
self.mode != VideoMode::Off
118
129
}
@@ -170,8 +181,8 @@ impl LocalVideo {
170
181
self.camera.capture = None;
171
182
let mut sink = self.sink(&self.camera, VideoKey::LocalCamera);
172
183
let capture = match self.mode {
173
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera)),
174
_ => start_camera(choice, move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
184
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),
185
_ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
175
186
};
176
187
Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
177
188
self.camera.capture = Some(capture);
@@ -194,7 +205,7 @@ impl LocalVideo {
194
205
self.screen.capture = None;
195
206
let mut sink = self.sink(&self.screen, VideoKey::LocalScreen);
196
207
let capture = match self.mode {
197
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen)),
208
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
198
209
_ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
199
210
};
200
211
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;
@@ -11,6 +11,7 @@ use libwebrtc::video_source::native::NativeVideoSource;11
use libwebrtc::video_track::RtcVideoTrack;11
use libwebrtc::video_track::RtcVideoTrack;12
use tokio::sync::mpsc::UnboundedSender;12
use tokio::sync::mpsc::UnboundedSender;13
13
14
use crate::blur::{BlurSettings, BlurStage};14
use crate::camera::start_camera;15
use crate::camera::start_camera;15
use crate::capture::Capture;16
use crate::capture::Capture;16
use crate::control::CallUpdate;17
use crate::control::CallUpdate;@@ -99,6 +100,7 @@ pub struct LocalVideo {99
camera: Outgoing,100
camera: Outgoing,100
screen: Outgoing,101
screen: Outgoing,101
lines: Option<VideoLines>,102
lines: Option<VideoLines>,103
blur: Arc<BlurSettings>,102
}104
}103
105
104
impl LocalVideo {106
impl LocalVideo {@@ -110,9 +112,18 @@ impl LocalVideo {110
camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),112
camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),111
screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),113
screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),112
lines: None,114
lines: None,115
blur: Arc::new(BlurSettings::default()),113
}116
}114
}117
}115
118
119
pub fn set_blur(&self, enabled: bool) {120
self.blur.set_enabled(enabled);121
}122
123
pub fn blur_average_ms(&self) -> Option<f32> {124
(self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())125
}126
116
pub fn is_available(&self) -> bool {127
pub fn is_available(&self) -> bool {117
self.mode != VideoMode::Off128
self.mode != VideoMode::Off118
}129
}@@ -170,8 +181,8 @@ impl LocalVideo {170
self.camera.capture = None;181
self.camera.capture = None;171
let mut sink = self.sink(&self.camera, VideoKey::LocalCamera);182
let mut sink = self.sink(&self.camera, VideoKey::LocalCamera);172
let capture = match self.mode {183
let capture = match self.mode {173
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera)),184
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),174
_ => start_camera(choice, move |buffer| sink.push(buffer), self.report_failure("Camera"))?,185
_ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,175
};186
};176
Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;187
Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;177
self.camera.capture = Some(capture);188
self.camera.capture = Some(capture);@@ -194,7 +205,7 @@ impl LocalVideo {194
self.screen.capture = None;205
self.screen.capture = None;195
let mut sink = self.sink(&self.screen, VideoKey::LocalScreen);206
let mut sink = self.sink(&self.screen, VideoKey::LocalScreen);196
let capture = match self.mode {207
let capture = match self.mode {197
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen)),208
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),198
_ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,209
_ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,199
};210
};200
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;211
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;@@ -59,7 +59,7 @@ async fn a_generated_h264_stream_survives_the_pipeline_to_bgra_pictures() {
59
59
transceiver
60
60
.set_codec_preferences(h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs))
61
61
.unwrap();
62
let pattern = spawn_pattern(LocalSink::new(source, None), PatternKind::Camera);
62
let pattern = spawn_pattern(LocalSink::new(source, None), PatternKind::Camera, None);
63
63
64
64
let offer = sender.create_offer(OfferOptions::default()).await.unwrap();
65
65
sender.set_local_description(offer.clone()).await.unwrap();
@@ -59,7 +59,7 @@ async fn a_generated_h264_stream_survives_the_pipeline_to_bgra_pictures() {59
transceiver59
transceiver60
.set_codec_preferences(h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs))60
.set_codec_preferences(h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs))61
.unwrap();61
.unwrap();62
let pattern = spawn_pattern(LocalSink::new(source, None), PatternKind::Camera);62
let pattern = spawn_pattern(LocalSink::new(source, None), PatternKind::Camera, None);63
63
64
let offer = sender.create_offer(OfferOptions::default()).await.unwrap();64
let offer = sender.create_offer(OfferOptions::default()).await.unwrap();65
sender.set_local_description(offer.clone()).await.unwrap();65
sender.set_local_description(offer.clone()).await.unwrap();@@ -2,6 +2,7 @@ use calling::devices::shared_factory;
2
2
use calling::sdp::{LineRole, parse, stream_lines, to_teams_offer};
3
3
use calling::video_layout::{SlotTable, add_video_lines, offer_plan};
4
4
use libwebrtc::audio_source::native::NativeAudioSource;
5
use libwebrtc::data_channel::DataChannelInit;
5
6
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
6
7
use libwebrtc::prelude::*;
7
8
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
@@ -15,8 +16,13 @@ fn counter() -> impl FnMut() -> u32 {
15
16
}
16
17
17
18
async fn browser_offer() -> String {
19
offer_with(false).await
20
}
21
22
async fn offer_with(data_channel: bool) -> String {
18
23
let factory = shared_factory();
19
24
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
25
let _channel = data_channel.then(|| peer.create_data_channel("main-channel", DataChannelInit::default()).unwrap());
20
26
let source = NativeAudioSource::new(AudioSourceOptions::default(), 48_000, 1, 100);
21
27
let track = factory.create_audio_track("microphone", source);
22
28
peer.add_transceiver(
@@ -39,6 +45,20 @@ async fn browser_offer() -> String {
39
45
.to_string()
40
46
}
41
47
48
#[tokio::test]
49
async fn the_caption_data_channel_adds_one_x_data_line_after_the_video_lines() {
50
let offer = to_teams_offer(&offer_with(true).await, &offer_plan(), &mut counter()).unwrap();
51
let parsed = parse(&offer.sdp).unwrap();
52
let kinds: Vec<(&str, &str)> = parsed.media.iter().map(|media| (media.kind.as_str(), media.mid().unwrap_or_default())).collect();
53
assert_eq!(kinds.len(), 8);
54
assert_eq!(kinds[7], ("x-data", "7"));
55
assert_eq!(&kinds[..7].iter().map(|(_, mid)| *mid).collect::<Vec<_>>(), &["0", "1", "2", "3", "4", "5", "6"]);
56
assert_eq!(parsed.media[7].value("x-data-protocol"), Some("sctp"));
57
assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::Data).count(), 1);
58
let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
59
assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7"));
60
}
61
42
62
#[tokio::test]
43
63
async fn the_meeting_layout_is_signaled_like_the_web_client_offers_it() {
44
64
let browser = browser_offer().await;
@@ -2,6 +2,7 @@ use calling::devices::shared_factory;2
use calling::sdp::{LineRole, parse, stream_lines, to_teams_offer};2
use calling::sdp::{LineRole, parse, stream_lines, to_teams_offer};3
use calling::video_layout::{SlotTable, add_video_lines, offer_plan};3
use calling::video_layout::{SlotTable, add_video_lines, offer_plan};4
use libwebrtc::audio_source::native::NativeAudioSource;4
use libwebrtc::audio_source::native::NativeAudioSource;5
use libwebrtc::data_channel::DataChannelInit;5
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;6
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;6
use libwebrtc::prelude::*;7
use libwebrtc::prelude::*;7
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};8
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};@@ -15,8 +16,13 @@ fn counter() -> impl FnMut() -> u32 {15
}16
}16
17
17
async fn browser_offer() -> String {18
async fn browser_offer() -> String {19
offer_with(false).await20
}21
22
async fn offer_with(data_channel: bool) -> String {18
let factory = shared_factory();23
let factory = shared_factory();19
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();24
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();25
let _channel = data_channel.then(|| peer.create_data_channel("main-channel", DataChannelInit::default()).unwrap());20
let source = NativeAudioSource::new(AudioSourceOptions::default(), 48_000, 1, 100);26
let source = NativeAudioSource::new(AudioSourceOptions::default(), 48_000, 1, 100);21
let track = factory.create_audio_track("microphone", source);27
let track = factory.create_audio_track("microphone", source);22
peer.add_transceiver(28
peer.add_transceiver(@@ -39,6 +45,20 @@ async fn browser_offer() -> String {39
.to_string()45
.to_string()40
}46
}41
47
48
#[tokio::test]49
async fn the_caption_data_channel_adds_one_x_data_line_after_the_video_lines() {50
let offer = to_teams_offer(&offer_with(true).await, &offer_plan(), &mut counter()).unwrap();51
let parsed = parse(&offer.sdp).unwrap();52
let kinds: Vec<(&str, &str)> = parsed.media.iter().map(|media| (media.kind.as_str(), media.mid().unwrap_or_default())).collect();53
assert_eq!(kinds.len(), 8);54
assert_eq!(kinds[7], ("x-data", "7"));55
assert_eq!(&kinds[..7].iter().map(|(_, mid)| *mid).collect::<Vec<_>>(), &["0", "1", "2", "3", "4", "5", "6"]);56
assert_eq!(parsed.media[7].value("x-data-protocol"), Some("sctp"));57
assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::Data).count(), 1);58
let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());59
assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7"));60
}61
42
#[tokio::test]62
#[tokio::test]43
async fn the_meeting_layout_is_signaled_like_the_web_client_offers_it() {63
async fn the_meeting_layout_is_signaled_like_the_web_client_offers_it() {44
let browser = browser_offer().await;64
let browser = browser_offer().await;