-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathroom.go
More file actions
1317 lines (1224 loc) · 35.5 KB
/
room.go
File metadata and controls
1317 lines (1224 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021-2024 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"encoding/json"
"fmt"
"maps"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"github.com/pion/webrtc/v4"
"github.com/urfave/cli/v3"
"google.golang.org/protobuf/encoding/protojson"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
lksdk "github.com/livekit/server-sdk-go/v2"
"github.com/livekit/livekit-cli/v2/pkg/util"
)
var (
// simulcastURLRegex matches h264 or h265 simulcast URLs in format <codec>://<host:port>/<width>x<height> or <codec>://<socket_path>/<width>x<height>
simulcastURLRegex = regexp.MustCompile(`^(h264|h265)://(.+)/(\d+)x(\d+)$`)
RoomCommands = []*cli.Command{
{
Name: "room",
Usage: "Create or delete rooms and manage existing room properties",
Commands: []*cli.Command{
{
Name: "create",
Usage: "Create a room",
ArgsUsage: "ROOM_NAME",
Before: createRoomClient,
Action: createRoom,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Hidden: true,
},
&cli.StringFlag{
Name: "room-egress-file",
Usage: "RoomCompositeRequest `JSON` file (see examples/room-composite-file.json)",
TakesFile: true,
},
&cli.StringFlag{
Name: "participant-egress-file",
Usage: "ParticipantEgress `JSON` file (see examples/auto-participant-egress.json)",
TakesFile: true,
},
&cli.StringFlag{
Name: "track-egress-file",
Usage: "AutoTrackEgress `JSON` file (see examples/auto-track-egress.json)",
TakesFile: true,
},
&cli.StringFlag{
Name: "agents-file",
Usage: "Agents configuration `JSON` file",
TakesFile: true,
},
&cli.StringFlag{
Name: "room-preset",
Usage: "`NAME` of the room configuration preset to associate with the created room",
},
&cli.UintFlag{
Name: "min-playout-delay",
Usage: "Minimum playout delay for video (in `MS`)",
},
&cli.UintFlag{
Name: "max-playout-delay",
Usage: "Maximum playout delay for video (in `MS`)",
},
&cli.BoolFlag{
Name: "sync-streams",
Usage: "Improve A/V sync by placing them in the same stream. when enabled, transceivers will not be reused",
},
&cli.UintFlag{
Name: "empty-timeout",
Usage: "Number of `SECS` to keep the room open before any participant joins",
},
&cli.UintFlag{
Name: "departure-timeout",
Usage: "Number of `SECS` to keep the room open after the last participant leaves",
},
&cli.BoolFlag{
Name: "replay-enabled",
Usage: "experimental (not yet available)",
Hidden: true,
},
},
},
{
Name: "list",
Usage: "List or search for active rooms by name",
Before: createRoomClient,
Action: listRooms,
ArgsUsage: "[ROOM_NAME ...]",
Flags: []cli.Flag{jsonFlag},
},
{
Name: "update",
Usage: "Modify properties of an active room",
Before: createRoomClient,
Action: updateRoomMetadata,
Flags: []cli.Flag{
hidden(optional(roomFlag)),
&cli.StringFlag{
Name: "metadata",
Required: true,
},
},
ArgsUsage: "ROOM_NAME",
},
{
Name: "delete",
Usage: "Delete a room",
UsageText: "lk room delete [OPTIONS] ROOM_NAME",
Before: createRoomClient,
Action: deleteRoom,
ArgsUsage: "ROOM_NAME_OR_ID",
},
{
Name: "join",
Usage: "Joins a room as a participant",
UsageText: "lk room join [OPTIONS] ROOM_NAME",
Action: joinRoom,
ArgsUsage: "ROOM_NAME",
Flags: []cli.Flag{
optional(identityFlag),
optional(roomFlag),
openFlag,
&cli.BoolFlag{
Name: "publish-demo",
Usage: "Publish demo video as a loop",
},
&cli.StringSliceFlag{
Name: "publish",
TakesFile: true,
Usage: "`FILES` to publish as tracks to room (supports .h264, .ivf, .ogg). " +
"Can be used multiple times to publish multiple files. " +
"Can publish from Unix or TCP socket using the format '<codec>:///<socket_path>' or '<codec>://<host:port>' respectively. Valid codecs are \"h264\", \"h265\", \"vp8\", \"opus\". " +
"For simulcast: use 2-3 h264:// or h265:// URLs with format '<codec>://<host:port>/<width>x<height>' or '<codec>:///path/to/<socket_path>/<width>x<height>' (all layers must use the same codec; quality determined by width order)",
},
&cli.StringFlag{
Name: "publish-data",
Usage: "Publish user data to the room.",
},
&cli.StringFlag{
Name: "publish-dtmf",
Usage: "Publish DTMF digits to the room. Character 'w' adds 0.5 sec delay.",
},
&cli.FloatFlag{
Name: "fps",
Usage: "If video files are published, indicates `FPS` of video",
},
&cli.StringFlag{
Name: "h26x-streaming-format",
Usage: "Format to use when reading H.264 from file or socket, \"annex-b\" OR \"length-prefixed\"",
Value: "annex-b",
},
&cli.BoolFlag{
Name: "exit-after-publish",
Usage: "When publishing, exit after file or stream is complete",
},
&cli.StringSliceFlag{
Name: "attribute",
Usage: "set attributes in key=value format, can be used multiple times",
},
&cli.StringFlag{
Name: "attribute-file",
Usage: "read attributes from a `JSON` file",
TakesFile: true,
},
&cli.BoolFlag{
Name: "auto-subscribe",
Usage: "Automatically subscribe to published tracks.",
Value: false,
},
&cli.StringFlag{
Name: "metadata",
Usage: "`JSON` metadata which will be passed to participant",
},
},
},
{
Name: "participants",
Usage: "Manage room participants",
Before: createRoomClient,
Commands: []*cli.Command{
{
Name: "list",
Usage: "List or search for active rooms by name",
Action: listParticipants,
ArgsUsage: "ROOM_NAME",
},
{
Name: "get",
Usage: "Fetch metadata of a room participant",
ArgsUsage: "ID",
Before: createRoomClient,
Action: getParticipant,
Flags: []cli.Flag{
roomFlag,
optional(identityFlag),
},
},
{
Name: "remove",
Usage: "Remove a participant from a room",
ArgsUsage: "ID",
Before: createRoomClient,
Action: removeParticipant,
Flags: []cli.Flag{
roomFlag,
optional(identityFlag),
},
},
{
Name: "forward",
Usage: "Forward a participant to a different room",
Before: createRoomClient,
Action: forwardParticipant,
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringFlag{
Name: "destination-room",
Usage: "`NAME` of the destination room",
},
},
},
{
Name: "move",
Usage: "Move a participant to a different room",
Before: createRoomClient,
Action: moveParticipant,
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringFlag{
Name: "destination-room",
Usage: "`NAME` of the destination room",
},
},
},
{
Name: "update",
Usage: "Change the metadata and permissions for a room participant",
ArgsUsage: "ID",
Before: createRoomClient,
Action: updateParticipant,
Flags: []cli.Flag{
roomFlag,
optional(identityFlag),
&cli.StringFlag{
Name: "metadata",
Usage: "JSON describing participant metadata (existing values for unset fields)",
},
&cli.StringFlag{
Name: "permissions",
Usage: "JSON describing participant permissions (existing values for unset fields)",
},
},
},
},
},
{
Name: "mute-track",
Usage: "Mute or unmute a track",
UsageText: "lk room mute-track OPTIONS TRACK_SID",
ArgsUsage: "TRACK_SID",
Before: createRoomClient,
Action: muteTrack,
MutuallyExclusiveFlags: []cli.MutuallyExclusiveFlags{{
Flags: [][]cli.Flag{
{
&cli.BoolFlag{
Name: "mute",
Aliases: []string{"m"},
Usage: "Mute the track",
},
&cli.BoolFlag{
Name: "unmute",
Aliases: []string{"u"},
Usage: "Unmute the track",
},
},
},
}},
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringFlag{
Hidden: true, // deprecated: use ARG0
Name: "track",
Usage: "Track `SID` to mute",
},
},
},
{
Name: "update-subscriptions",
Usage: "Subscribe or unsubscribe from a track",
UsageText: "lk room update-subscriptions OPTIONS TRACK_SID",
ArgsUsage: "TRACK_SID",
Before: createRoomClient,
Action: updateSubscriptions,
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringSliceFlag{
Hidden: true, // deprecated: use ARG0
Name: "track",
Usage: "Track `SID` to subscribe/unsubscribe",
},
},
MutuallyExclusiveFlags: []cli.MutuallyExclusiveFlags{{
Flags: [][]cli.Flag{{
&cli.BoolFlag{
Name: "subscribe",
Aliases: []string{"s"},
Usage: "Subscribe to the track",
},
&cli.BoolFlag{
Name: "unsubscribe",
Aliases: []string{"S"},
Usage: "Unsubscribe to the track",
},
}},
}},
},
{
Name: "send-data",
Before: createRoomClient,
Action: sendData,
Usage: "Send arbitrary JSON data to client",
UsageText: "lk room send-data [OPTIONS] DATA",
ArgsUsage: "JSON",
Flags: []cli.Flag{
roomFlag,
&cli.StringFlag{
Hidden: true, // deprecated: use ARG0
Name: "data",
Usage: "`JSON` payload to send to client",
},
&cli.StringFlag{
Name: "topic",
Usage: "`TOPIC` of the message",
},
&cli.StringSliceFlag{
Name: "identity",
Usage: "One or more participant identities to send the message to. When empty, broadcasts to the entire room",
},
},
},
},
},
// Deprecated commands kept for compatibility
{
Hidden: true, // deprecated: use `room create`
Name: "create-room",
Before: createRoomClient,
Action: createRoom,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "name of the room",
Required: true,
},
&cli.StringFlag{
Name: "room-egress-file",
Usage: "RoomCompositeRequest json file (see examples/room-composite-file.json)",
},
&cli.StringFlag{
Name: "participant-egress-file",
Usage: "ParticipantEgress json file (see examples/auto-participant-egress.json)",
},
&cli.StringFlag{
Name: "track-egress-file",
Usage: "AutoTrackEgress json file (see examples/auto-track-egress.json)",
},
&cli.StringFlag{
Name: "agents-file",
Usage: "Agents configuration json file",
},
&cli.StringFlag{
Name: "room-configuration",
Usage: "Name of the room configuration to associate with the created room",
},
&cli.UintFlag{
Name: "min-playout-delay",
Usage: "minimum playout delay for video (in ms)",
},
&cli.UintFlag{
Name: "max-playout-delay",
Usage: "maximum playout delay for video (in ms)",
},
&cli.BoolFlag{
Name: "sync-streams",
Usage: "improve A/V sync by placing them in the same stream. when enabled, transceivers will not be reused",
},
&cli.UintFlag{
Name: "empty-timeout",
Usage: "number of seconds to keep the room open before any participant joins",
},
&cli.UintFlag{
Name: "departure-timeout",
Usage: "number of seconds to keep the room open after the last participant leaves",
},
&cli.BoolFlag{
Name: "replay-enabled",
Usage: "experimental (not yet available)",
Hidden: true,
},
},
},
{
Hidden: true, // deprecated: use `room list``
Name: "list-rooms",
Before: createRoomClient,
Action: listRooms,
},
{
Hidden: true, // deprecated: use `room list`
Name: "list-room",
Before: createRoomClient,
Action: _deprecatedListRoom,
Flags: []cli.Flag{
roomFlag,
},
},
{
Hidden: true, // deprecated: use `room update-metadata`
Name: "update-room-metadata",
Before: createRoomClient,
Action: _deprecatedUpdateRoomMetadata,
Flags: []cli.Flag{
roomFlag,
&cli.StringFlag{
Name: "metadata",
},
},
},
{
Hidden: true, // deprecated: use `room participants list`
Name: "list-participants",
Before: createRoomClient,
Action: _deprecatedListParticipants,
Flags: []cli.Flag{
roomFlag,
},
},
{
Hidden: true, // deprecated: use `room participants get`
Name: "get-participant",
Before: createRoomClient,
Action: getParticipant,
Flags: []cli.Flag{
roomFlag,
identityFlag,
},
},
{
Hidden: true, // deprecated: use `room participants remove`
Name: "remove-participant",
Before: createRoomClient,
Action: removeParticipant,
Flags: []cli.Flag{
roomFlag,
identityFlag,
},
},
{
Hidden: true, // deprecated: use `room participants update`
Name: "update-participant",
Before: createRoomClient,
Action: updateParticipant,
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringFlag{
Name: "metadata",
Usage: "`JSON` describing participant metadata",
},
&cli.StringFlag{
Name: "permissions",
Usage: "`JSON` describing participant permissions (existing values for unset fields)",
},
},
},
{
Hidden: true, // deprecated: use `room mute-track`
Name: "mute-track",
Usage: "Mute or unmute a track",
UsageText: "lk room mute-track OPTIONS TRACK_SID",
ArgsUsage: "TRACK_SID",
Before: createRoomClient,
Action: muteTrack,
MutuallyExclusiveFlags: []cli.MutuallyExclusiveFlags{{
Flags: [][]cli.Flag{
{
&cli.BoolFlag{
Name: "m",
Aliases: []string{"mute", "muted"},
Usage: "Mute the track",
},
&cli.BoolFlag{
Name: "u",
Aliases: []string{"unmute"},
Usage: "Unmute the track",
},
},
},
}},
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringFlag{
Hidden: true, // deprecated: use ARG0
Name: "track",
Usage: "Track `SID` to mute",
},
},
},
{
Hidden: true, // deprecated: use `room update-subscriptions`
Name: "update-subscriptions",
Usage: "Subscribe or unsubscribe from a track",
UsageText: "lk room update-subscriptions OPTIONS TRACK_SID",
ArgsUsage: "TRACK_SID",
Before: createRoomClient,
Action: updateSubscriptions,
Flags: []cli.Flag{
roomFlag,
identityFlag,
&cli.StringSliceFlag{
Hidden: true, // deprecated: use ARG0
Name: "track",
Usage: "Track `SID` to subscribe/unsubscribe",
},
&cli.BoolFlag{
Name: "subscribe",
Usage: "Set to true to subscribe, otherwise it'll unsubscribe",
},
},
},
{
Hidden: true, // deprecated: use `room send-data`
Name: "send-data",
Before: createRoomClient,
Action: sendData,
Usage: "Send arbitrary JSON data to client",
UsageText: "lk room send-data [OPTIONS] DATA",
ArgsUsage: "JSON",
Flags: []cli.Flag{
roomFlag,
&cli.StringFlag{
Hidden: true, // deprecated: use ARG0
Name: "data",
Usage: "`JSON` payload to send to client",
},
&cli.StringFlag{
Name: "topic",
Usage: "`TOPIC` of the message",
},
&cli.StringSliceFlag{
Hidden: true, // deprecated: use `--participant-ids`
Name: "participantID",
Usage: "list of participantID to send the message to",
},
},
},
}
roomClient *lksdk.RoomServiceClient
)
func createRoomClient(ctx context.Context, cmd *cli.Command) (context.Context, error) {
_, err := requireProject(ctx, cmd)
if err != nil {
return nil, err
}
roomClient = lksdk.NewRoomServiceClient(project.URL, project.APIKey, project.APISecret, withDefaultClientOpts(project)...)
return nil, nil
}
func createRoom(ctx context.Context, cmd *cli.Command) error {
name, err := extractFlagOrArg(cmd, "name")
if err != nil {
return err
}
req := &livekit.CreateRoomRequest{
Name: name,
}
if roomEgressFile := cmd.String("room-egress-file"); roomEgressFile != "" {
roomEgress := &livekit.RoomCompositeEgressRequest{}
b, err := os.ReadFile(roomEgressFile)
if err != nil {
return err
}
if err = protojson.Unmarshal(b, roomEgress); err != nil {
return err
}
req.Egress = &livekit.RoomEgress{Room: roomEgress}
}
if participantEgressFile := cmd.String("participant-egress-file"); participantEgressFile != "" {
participantEgress := &livekit.AutoParticipantEgress{}
b, err := os.ReadFile(participantEgressFile)
if err != nil {
return err
}
if err = protojson.Unmarshal(b, participantEgress); err != nil {
return err
}
if req.Egress == nil {
req.Egress = &livekit.RoomEgress{}
}
req.Egress.Participant = participantEgress
}
if trackEgressFile := cmd.String("track-egress-file"); trackEgressFile != "" {
trackEgress := &livekit.AutoTrackEgress{}
b, err := os.ReadFile(trackEgressFile)
if err != nil {
return err
}
if err = protojson.Unmarshal(b, trackEgress); err != nil {
return err
}
if req.Egress == nil {
req.Egress = &livekit.RoomEgress{}
}
req.Egress.Tracks = trackEgress
}
if agentsFile := cmd.String("agents-file"); agentsFile != "" {
agent := &livekit.RoomAgent{}
b, err := os.ReadFile(agentsFile)
if err != nil {
return err
}
if err = protojson.Unmarshal(b, agent); err != nil {
return err
}
req.Agents = agent.Dispatches
}
if roomPreset := cmd.String("room-preset"); roomPreset != "" {
req.RoomPreset = roomPreset
}
if cmd.Uint("min-playout-delay") != 0 {
fmt.Printf("setting min playout delay: %d\n", cmd.Uint("min-playout-delay"))
req.MinPlayoutDelay = uint32(cmd.Uint("min-playout-delay"))
}
if maxPlayoutDelay := cmd.Uint("max-playout-delay"); maxPlayoutDelay != 0 {
fmt.Printf("setting max playout delay: %d\n", maxPlayoutDelay)
req.MaxPlayoutDelay = uint32(maxPlayoutDelay)
}
if syncStreams := cmd.Bool("sync-streams"); syncStreams {
fmt.Printf("setting sync streams: %t\n", syncStreams)
req.SyncStreams = syncStreams
}
if emptyTimeout := cmd.Uint("empty-timeout"); emptyTimeout != 0 {
fmt.Printf("setting empty timeout: %d\n", emptyTimeout)
req.EmptyTimeout = uint32(emptyTimeout)
}
if departureTimeout := cmd.Uint("departure-timeout"); departureTimeout != 0 {
fmt.Printf("setting departure timeout: %d\n", departureTimeout)
req.DepartureTimeout = uint32(departureTimeout)
}
if replayEnabled := cmd.Bool("replay-enabled"); replayEnabled {
fmt.Printf("setting replay enabled: %t\n", replayEnabled)
req.ReplayEnabled = replayEnabled
}
room, err := roomClient.CreateRoom(ctx, req)
if err != nil {
return err
}
util.PrintJSON(room)
return nil
}
func listRooms(ctx context.Context, cmd *cli.Command) error {
names, _ := extractArgs(cmd)
if cmd.Bool("verbose") && len(names) > 0 {
fmt.Printf(
"Querying rooms matching %s",
strings.Join(util.MapStrings(names, util.WrapWith("\"")), ", "),
)
}
req := livekit.ListRoomsRequest{}
if len(names) > 0 {
req.Names = names
}
res, err := roomClient.ListRooms(ctx, &req)
if err != nil {
return err
}
if cmd.Bool("json") {
util.PrintJSON(res)
} else {
table := util.CreateTable().Headers("RoomID", "Name", "Participants", "Publishers")
for _, rm := range res.Rooms {
table.Row(
rm.Sid,
rm.Name,
fmt.Sprintf("%d", rm.NumParticipants),
fmt.Sprintf("%d", rm.NumPublishers),
)
}
fmt.Println(table)
}
return nil
}
func _deprecatedListRoom(ctx context.Context, cmd *cli.Command) error {
res, err := roomClient.ListRooms(ctx, &livekit.ListRoomsRequest{
Names: []string{cmd.String("room")},
})
if err != nil {
return err
}
if len(res.Rooms) == 0 {
fmt.Printf("there is no matching room with name: %s\n", cmd.String("room"))
return nil
}
rm := res.Rooms[0]
util.PrintJSON(rm)
return nil
}
func deleteRoom(ctx context.Context, cmd *cli.Command) error {
roomId, err := extractArg(cmd)
if err != nil {
return err
}
_, err = roomClient.DeleteRoom(ctx, &livekit.DeleteRoomRequest{
Room: roomId,
})
if err != nil {
return err
}
fmt.Println("deleted room", roomId)
return nil
}
func updateRoomMetadata(ctx context.Context, cmd *cli.Command) error {
roomName, _ := extractArg(cmd)
res, err := roomClient.UpdateRoomMetadata(ctx, &livekit.UpdateRoomMetadataRequest{
Room: roomName,
Metadata: cmd.String("metadata"),
})
if err != nil {
return err
}
fmt.Println("Updated room metadata")
util.PrintJSON(res)
return nil
}
func _deprecatedUpdateRoomMetadata(ctx context.Context, cmd *cli.Command) error {
roomName := cmd.String("room")
res, err := roomClient.UpdateRoomMetadata(ctx, &livekit.UpdateRoomMetadataRequest{
Room: roomName,
Metadata: cmd.String("metadata"),
})
if err != nil {
return err
}
fmt.Println("Updated room metadata")
util.PrintJSON(res)
return nil
}
func joinRoom(ctx context.Context, cmd *cli.Command) error {
publishUrls := cmd.StringSlice("publish")
// Determine simulcast mode by checking if any URL has simulcast format
simulcastMode := false
for _, url := range publishUrls {
if simulcastURLRegex.MatchString(url) {
simulcastMode = true
break
}
}
// Validate publish flags
if len(publishUrls) > 3 {
return fmt.Errorf("no more than 3 --publish flags can be specified, got %d", len(publishUrls))
}
// If simulcast mode, validate all URLs are h264 or h265 format with dimensions
if simulcastMode {
if len(publishUrls) == 1 {
return fmt.Errorf("simulcast mode requires 2-3 streams, but only 1 was provided")
}
var firstCodec string
for i, url := range publishUrls {
parts, err := parseSimulcastURL(url)
if err != nil {
return fmt.Errorf("publish flag %d: %w", i+1, err)
}
if i == 0 {
firstCodec = parts.codec
} else if parts.codec != firstCodec {
return fmt.Errorf("publish flag %d: simulcast layers must use the same codec; expected %s://, got %s://", i+1, firstCodec, parts.codec)
}
}
}
_, err := requireProject(ctx, cmd)
if err != nil {
return err
}
roomName, err := extractFlagOrArg(cmd, "room")
if err != nil {
return err
}
participantIdentity := cmd.String("identity")
if participantIdentity == "" {
participantIdentity = util.ExpandTemplate("participant-%x")
fmt.Printf("Using generated participant identity [%s]\n", util.Accented(participantIdentity))
}
autoSubscribe := cmd.Bool("auto-subscribe")
done := make(chan os.Signal, 1)
roomCB := &lksdk.RoomCallback{
OnParticipantConnected: func(p *lksdk.RemoteParticipant) {
logger.Infow("participant connected",
"kind", p.Kind(),
"participantID", p.SID(),
"participant", p.Identity(),
)
},
OnParticipantDisconnected: func(p *lksdk.RemoteParticipant) {
logger.Infow("participant disconnected",
"kind", p.Kind(),
"participantID", p.SID(),
"participant", p.Identity(),
)
},
ParticipantCallback: lksdk.ParticipantCallback{
OnDataPacket: func(p lksdk.DataPacket, params lksdk.DataReceiveParams) {
identity := params.SenderIdentity
switch p := p.(type) {
case *lksdk.UserDataPacket:
logger.Infow("received data", "data", p.Payload, "participant", identity)
case *livekit.SipDTMF:
logger.Infow("received dtmf", "digits", p.Digit, "participant", identity)
default:
logger.Infow("received unsupported data", "data", p, "participant", identity)
}
},
OnConnectionQualityChanged: func(update *livekit.ConnectionQualityInfo, p lksdk.Participant) {
logger.Debugw("connection quality changed", "participant", p.Identity(), "quality", update.Quality)
},
OnTrackSubscribed: func(track *webrtc.TrackRemote, pub *lksdk.RemoteTrackPublication, participant *lksdk.RemoteParticipant) {
logger.Infow("track subscribed",
"kind", pub.Kind(),
"trackID", pub.SID(),
"source", pub.Source(),
"participant", participant.Identity(),
)
},
OnTrackUnsubscribed: func(track *webrtc.TrackRemote, pub *lksdk.RemoteTrackPublication, participant *lksdk.RemoteParticipant) {
logger.Infow("track unsubscribed",
"kind", pub.Kind(),
"trackID", pub.SID(),
"source", pub.Source(),
"participant", participant.Identity(),
)
},
OnTrackUnpublished: func(pub *lksdk.RemoteTrackPublication, participant *lksdk.RemoteParticipant) {
logger.Infow("track unpublished",
"kind", pub.Kind(),
"trackID", pub.SID(),
"source", pub.Source(),
"participant", participant.Identity(),
)
},
OnTrackMuted: func(pub lksdk.TrackPublication, participant lksdk.Participant) {
logger.Infow("track muted",
"kind", pub.Kind(),
"trackID", pub.SID(),
"source", pub.Source(),
"participant", participant.Identity(),
)
},
OnTrackUnmuted: func(pub lksdk.TrackPublication, participant lksdk.Participant) {
logger.Infow("track unmuted",
"kind", pub.Kind(),
"trackID", pub.SID(),
"source", pub.Source(),
"participant", participant.Identity(),
)
},
},
OnRoomMetadataChanged: func(metadata string) {
logger.Infow("room metadata changed", "metadata", metadata)
},
OnReconnecting: func() {
logger.Infow("reconnecting to room")
},
OnReconnected: func() {
logger.Infow("reconnected to room")
},
OnDisconnected: func() {
logger.Infow("disconnected from room")
close(done)
},
}
participantAttributes, err := parseKeyValuePairs(cmd, "attribute")
if err != nil {
return fmt.Errorf("failed to parse participant attributes: %w", err)
}
// Read attributes from JSON file if specified
if attrFile := cmd.String("attribute-file"); attrFile != "" {
fileData, err := os.ReadFile(attrFile)
if err != nil {
return fmt.Errorf("failed to read attribute file: %w", err)
}
var fileAttrs map[string]string
if err := json.Unmarshal(fileData, &fileAttrs); err != nil {
return fmt.Errorf("failed to parse attribute file as JSON: %w", err)
}
// Add attributes from file to the existing ones
maps.Copy(participantAttributes, fileAttrs)
}
room, err := lksdk.ConnectToRoom(project.URL, lksdk.ConnectInfo{
APIKey: project.APIKey,
APISecret: project.APISecret,
RoomName: roomName,
ParticipantIdentity: participantIdentity,
ParticipantAttributes: participantAttributes,
ParticipantMetadata: cmd.String("metadata"),
}, roomCB, lksdk.WithAutoSubscribe(autoSubscribe))
if err != nil {
return err
}
defer room.Disconnect()
logger.Infow("connected to room", "room", room.Name())
signal.Notify(done, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
if cmd.Bool("publish-demo") {
if err = publishDemo(room); err != nil {
return err
}
}
exitAfterPublish := cmd.Bool("exit-after-publish")