-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathpublisher.rs
More file actions
1929 lines (1764 loc) · 70.8 KB
/
Copy pathpublisher.rs
File metadata and controls
1929 lines (1764 loc) · 70.8 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
use anyhow::Result;
use clap::{Parser, ValueEnum};
use livekit::e2ee::{key_provider::*, E2eeOptions, EncryptionType};
use livekit::options::{
self, video as video_presets, PacketTrailerFeatures, TrackPublishOptions, VideoCodec,
VideoEncoderBackend, VideoEncoding, VideoPreset,
};
use livekit::prelude::*;
use livekit::webrtc::video_frame::{FrameMetadata, I420Buffer, VideoFrame, VideoRotation};
use livekit::webrtc::video_source::native::NativeVideoSource;
use livekit::webrtc::video_source::{RtcVideoSource, VideoResolution};
use livekit_api::access_token;
use livekit_api::services::room::{CreateRoomOptions, RoomClient};
use livekit_api::services::{ServiceError, TwirpError, TwirpErrorCode};
use log::{debug, info};
use nokhwa::pixel_format::RgbFormat;
use nokhwa::utils::{
ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType,
Resolution,
};
use nokhwa::Camera;
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::env;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use yuv_sys;
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
mod argus;
mod codec_display;
mod test_pattern;
mod timestamp_burn;
mod video_display;
mod viewport_aspect;
use test_pattern::TestPattern;
use timestamp_burn::TimestampOverlay;
use video_display::{align_up, PublisherTimingSample, SharedYuv};
#[derive(Copy, Clone, Debug, ValueEnum)]
enum PublisherCodec {
H264,
H265,
VP8,
VP9,
AV1,
}
impl From<PublisherCodec> for VideoCodec {
fn from(codec: PublisherCodec) -> Self {
match codec {
PublisherCodec::H264 => VideoCodec::H264,
PublisherCodec::H265 => VideoCodec::H265,
PublisherCodec::VP8 => VideoCodec::VP8,
PublisherCodec::VP9 => VideoCodec::VP9,
PublisherCodec::AV1 => VideoCodec::AV1,
}
}
}
/// Selects the camera backend used by the publisher.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum SourceKind {
/// USB / V4L2 camera via the `nokhwa` crate (default).
Uvc,
/// NVIDIA Jetson MIPI CSI camera via libargus (Jetson-only).
Argus,
}
/// Selects the UVC camera capture pixel format.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum CaptureFormat {
/// Try YUYV first and fall back to MJPEG.
Auto,
/// Request uncompressed YUYV capture.
Yuv,
/// Request compressed MJPEG capture.
Mjpeg,
}
impl CaptureFormat {
fn frame_formats(self) -> &'static [FrameFormat] {
match self {
Self::Auto => &[FrameFormat::YUYV, FrameFormat::MJPEG],
Self::Yuv => &[FrameFormat::YUYV],
Self::Mjpeg => &[FrameFormat::MJPEG],
}
}
}
impl std::fmt::Display for CaptureFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Auto => write!(f, "auto"),
Self::Yuv => write!(f, "yuv"),
Self::Mjpeg => write!(f, "mjpeg"),
}
}
}
#[derive(Copy, Clone, Debug, ValueEnum)]
enum PublisherEncoder {
Auto,
Software,
Hardware,
Nvenc,
Vaapi,
#[value(name = "videotoolbox")]
VideoToolbox,
}
impl PublisherEncoder {
fn as_str(&self) -> &'static str {
match self {
PublisherEncoder::Auto => "auto",
PublisherEncoder::Software => "software",
PublisherEncoder::Hardware => "hardware",
PublisherEncoder::Nvenc => "nvenc",
PublisherEncoder::Vaapi => "vaapi",
PublisherEncoder::VideoToolbox => "videotoolbox",
}
}
}
impl From<PublisherEncoder> for VideoEncoderBackend {
fn from(encoder: PublisherEncoder) -> Self {
match encoder {
PublisherEncoder::Auto => VideoEncoderBackend::Auto,
PublisherEncoder::Software => VideoEncoderBackend::Software,
PublisherEncoder::Hardware => VideoEncoderBackend::Hardware,
PublisherEncoder::Nvenc => VideoEncoderBackend::Nvenc,
PublisherEncoder::Vaapi => VideoEncoderBackend::Vaapi,
PublisherEncoder::VideoToolbox => VideoEncoderBackend::VideoToolbox,
}
}
}
fn video_encoder_backend_name(backend: VideoEncoderBackend) -> &'static str {
match backend {
VideoEncoderBackend::Auto => "auto",
VideoEncoderBackend::Software => "software",
VideoEncoderBackend::Hardware => "hardware",
VideoEncoderBackend::Nvenc => "nvenc",
VideoEncoderBackend::Vaapi => "vaapi",
VideoEncoderBackend::VideoToolbox => "videotoolbox",
_ => "unknown",
}
}
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// List available cameras and exit
#[arg(long)]
list_cameras: bool,
/// List available video encoder backends and exit
#[arg(long)]
list_encoders: bool,
/// Camera index to use (numeric)
#[arg(long, default_value_t = 0)]
camera_index: usize,
/// Camera backend: `uvc` (default, V4L2/USB via nokhwa) or `argus` (Jetson MIPI CSI).
#[arg(long, value_enum, default_value_t = SourceKind::Uvc)]
source: SourceKind,
/// UVC camera capture format: `auto` tries YUYV then MJPEG; `mjpeg` uses less USB bandwidth.
#[arg(long, value_enum, default_value_t = CaptureFormat::Auto)]
format: CaptureFormat,
/// Generate a standard SMPTE color-bar test pattern instead of using a camera
#[arg(long, default_value_t = false, conflicts_with_all = ["list_cameras", "list_encoders"])]
test_pattern: bool,
/// Desired width
#[arg(long, default_value_t = 1280)]
width: u32,
/// Desired height
#[arg(long, default_value_t = 720)]
height: u32,
/// Desired framerate
#[arg(long, default_value_t = 30)]
fps: u32,
/// Max video bitrate for the main layer in bps (optional)
#[arg(long)]
max_bitrate: Option<u64>,
/// Enable simulcast publishing (low/medium/high layers as appropriate)
#[arg(long, default_value_t = false)]
simulcast: bool,
/// LiveKit participant identity
#[arg(long, default_value = "rust-camera-pub")]
identity: String,
/// LiveKit room name
#[arg(long, default_value = "video-room")]
room_name: String,
/// Minimum subscriber playout delay in milliseconds; recreates the room when set
#[arg(long)]
min_playout_delay: Option<u32>,
/// Maximum subscriber playout delay in milliseconds; recreates the room when set
#[arg(long)]
max_playout_delay: Option<u32>,
/// LiveKit server URL
#[arg(long)]
url: Option<String>,
/// LiveKit API key
#[arg(long)]
api_key: Option<String>,
/// LiveKit API secret
#[arg(long)]
api_secret: Option<String>,
/// Video codec to use for publishing
#[arg(long, value_enum, default_value_t = PublisherCodec::H264)]
codec: PublisherCodec,
/// Preferred video encoder backend to use for publishing
#[arg(long, value_enum, default_value_t = PublisherEncoder::Auto)]
encoder: PublisherEncoder,
/// Attach the current system time (microseconds since UNIX epoch) as the user timestamp on each frame
#[arg(long, default_value_t = false)]
attach_timestamp: bool,
/// Enable dynacast (pause unused simulcast layers based on subscriber demand)
#[arg(long, default_value_t = false)]
dynacast: bool,
/// Burn the attached timestamp into each video frame; does nothing unless --attach-timestamp is also enabled
#[arg(long, default_value_t = false)]
burn_timestamp: bool,
/// Attach a monotonically increasing frame ID to each published frame via the packet trailer
#[arg(long, default_value_t = false)]
attach_frame_id: bool,
/// Open a window that displays the video frames being published
#[arg(long, default_value_t = false)]
display_video: bool,
/// Burn publisher timing metrics into the local preview window
#[arg(long, default_value_t = false, requires = "display_video")]
display_timing: bool,
/// Shared encryption key for E2EE (enables AES-GCM end-to-end encryption when set)
#[arg(long)]
e2ee_key: Option<String>,
}
fn unix_time_us_now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_micros() as u64
}
const MAX_BACKEND_CAPTURE_TIMESTAMP_AGE_US: u64 = 5_000_000;
#[derive(Default)]
struct CaptureTimestampLogState {
logged_source: bool,
logged_missing: bool,
logged_invalid: bool,
}
fn validate_backend_capture_timestamp_us(
capture_timestamp: Duration,
read_wall_time_us: u64,
) -> Result<u64, &'static str> {
let capture_timestamp_us =
u64::try_from(capture_timestamp.as_micros()).map_err(|_| "overflows u64")?;
if capture_timestamp_us == 0 {
return Err("is zero");
}
if capture_timestamp_us > read_wall_time_us {
return Err("is in the future");
}
if read_wall_time_us - capture_timestamp_us > MAX_BACKEND_CAPTURE_TIMESTAMP_AGE_US {
return Err("is too old");
}
Ok(capture_timestamp_us)
}
fn select_capture_wall_time_us(
backend_capture_timestamp: Option<Duration>,
fallback_wall_time_us: u64,
read_wall_time_us: u64,
log_state: &mut CaptureTimestampLogState,
) -> u64 {
match backend_capture_timestamp {
Some(capture_timestamp) => {
match validate_backend_capture_timestamp_us(capture_timestamp, read_wall_time_us) {
Ok(capture_timestamp_us) => {
if !log_state.logged_source {
info!("Using camera capture_timestamp for user_timestamp");
log_state.logged_source = true;
}
capture_timestamp_us
}
Err(reason) => {
if !log_state.logged_invalid {
log::warn!(
"Ignoring camera capture_timestamp because it {reason}; falling back to system wall clock"
);
log_state.logged_invalid = true;
}
fallback_wall_time_us
}
}
}
None => {
if !log_state.logged_missing {
log::warn!(
"Buffer::capture_timestamp() not available; falling back to system wall clock"
);
log_state.logged_missing = true;
}
fallback_wall_time_us
}
}
}
fn is_twirp_not_found(err: &ServiceError) -> bool {
matches!(
err,
ServiceError::Twirp(TwirpError::Twirp(code))
if code.code == TwirpErrorCode::NOT_FOUND
)
}
fn requested_playout_delay(
min_playout_delay: Option<u32>,
max_playout_delay: Option<u32>,
) -> Option<(u32, u32)> {
match (min_playout_delay, max_playout_delay) {
(None, None) => None,
(min_playout_delay, max_playout_delay) => {
Some((min_playout_delay.unwrap_or_default(), max_playout_delay.unwrap_or_default()))
}
}
}
fn normalize_twirp_host(url: &str) -> String {
if let Some(rest) = url.strip_prefix("wss://") {
return format!("https://{}", rest.trim_end_matches("/rtc"));
}
if let Some(rest) = url.strip_prefix("ws://") {
return format!("http://{}", rest.trim_end_matches("/rtc"));
}
url.trim_end_matches("/rtc").to_string()
}
#[derive(Default)]
struct RollingMs {
total_ms: f64,
samples: u64,
}
impl RollingMs {
fn record(&mut self, value_ms: f64) {
self.total_ms += value_ms;
self.samples += 1;
}
fn average(&self) -> Option<f64> {
(self.samples > 0).then_some(self.total_ms / self.samples as f64)
}
fn reset(&mut self) {
*self = Self::default();
}
}
#[derive(Default)]
struct PublisherTimingSummary {
paced_wait_ms: RollingMs,
camera_frame_read_ms: RollingMs,
decode_mjpeg_ms: RollingMs,
buffer_convert_ms: RollingMs,
frame_draw_ms: RollingMs,
submit_to_webrtc_ms: RollingMs,
capture_to_webrtc_total_ms: RollingMs,
}
fn find_video_outbound_encoder(stats: &[livekit::webrtc::stats::RtcStats]) -> Option<&str> {
let mut fallback = None;
for stat in stats {
let livekit::webrtc::stats::RtcStats::OutboundRtp(outbound) = stat else {
continue;
};
if outbound.stream.kind != "video" || outbound.outbound.encoder_implementation.is_empty() {
continue;
}
let implementation = outbound.outbound.encoder_implementation.as_str();
if outbound.outbound.active {
return Some(implementation);
}
fallback.get_or_insert(implementation);
}
fallback
}
fn find_video_outbound_stats(
stats: &[livekit::webrtc::stats::RtcStats],
) -> Option<livekit::webrtc::stats::OutboundRtpStats> {
let mut fallback = None;
for stat in stats {
let livekit::webrtc::stats::RtcStats::OutboundRtp(outbound) = stat else {
continue;
};
if outbound.stream.kind != "video" {
continue;
}
if outbound.outbound.active {
return Some(outbound.clone());
}
fallback.get_or_insert_with(|| outbound.clone());
}
fallback
}
fn log_publisher_outbound_health(stats: &[livekit::webrtc::stats::RtcStats]) {
let Some(outbound) = find_video_outbound_stats(stats) else {
return;
};
info!(
"Publish health: encoded={}, sent={}, keyframes={}, packets_sent={}, bytes_sent={}, pli={}, fir={}, encoder={}",
outbound.outbound.frames_encoded,
outbound.outbound.frames_sent,
outbound.outbound.key_frames_encoded,
outbound.sent.packets_sent,
outbound.sent.bytes_sent,
outbound.outbound.pli_count,
outbound.outbound.fir_count,
outbound.outbound.encoder_implementation,
);
if outbound.outbound.frames_encoded > 0 && outbound.sent.packets_sent == 0 {
log::warn!(
"Encoder produced frames but no RTP packets were sent; the AV1 bitstream may be malformed"
);
}
if outbound.outbound.key_frames_encoded == 0 && outbound.outbound.pli_count > 0 {
log::warn!(
"Remote side requested keyframes (PLI={}) but the publisher has not encoded any keyframes",
outbound.outbound.pli_count
);
}
}
async fn update_publisher_video_stats(track: LocalVideoTrack, ctrl_c_received: Arc<AtomicBool>) {
let mut last_log =
Instant::now().checked_sub(Duration::from_secs(2)).unwrap_or_else(Instant::now);
let mut interval = tokio::time::interval(Duration::from_secs(1));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
if ctrl_c_received.load(Ordering::Acquire) {
break;
}
if let Ok(stats) = track.get_stats().await {
if last_log.elapsed() >= Duration::from_secs(2) {
log_publisher_outbound_health(&stats);
last_log = Instant::now();
}
}
interval.tick().await;
}
}
async fn update_publisher_encoder_overlay(
track: LocalVideoTrack,
shared: Arc<Mutex<SharedYuv>>,
ctrl_c_received: Arc<AtomicBool>,
) {
let mut logged_initial = false;
let mut last_implementation = String::new();
let mut interval = tokio::time::interval(Duration::from_secs(1));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
if ctrl_c_received.load(Ordering::Acquire) {
break;
}
match track.get_stats().await {
Ok(stats) => {
if let Some(implementation) = find_video_outbound_encoder(&stats) {
if implementation != last_implementation {
info!("Publisher video encoder implementation: {implementation}");
last_implementation = implementation.to_string();
}
let mut shared = shared.lock();
shared.codec_implementation = implementation.to_string();
}
logged_initial = true;
}
Err(e) if !logged_initial => {
debug!("Failed to get publisher stats for video track: {:?}", e);
logged_initial = true;
}
Err(_) => {}
}
interval.tick().await;
}
}
impl PublisherTimingSummary {
fn reset(&mut self) {
self.paced_wait_ms.reset();
self.camera_frame_read_ms.reset();
self.decode_mjpeg_ms.reset();
self.buffer_convert_ms.reset();
self.frame_draw_ms.reset();
self.submit_to_webrtc_ms.reset();
self.capture_to_webrtc_total_ms.reset();
}
}
fn format_timing_line(timings: &PublisherTimingSummary) -> String {
let line_one = vec![
format!("paced_wait {:.2}", timings.paced_wait_ms.average().unwrap_or_default()),
format!(
"camera_frame_read {:.2}",
timings.camera_frame_read_ms.average().unwrap_or_default()
),
];
let mut line_two = Vec::new();
if let Some(decode_ms) = timings.decode_mjpeg_ms.average() {
line_two.push(format!("decode_mjpeg {:.2}", decode_ms));
}
line_two.push(format!(
"convert_to_i420 {:.2}",
timings.buffer_convert_ms.average().unwrap_or_default()
));
if let Some(frame_draw_ms) = timings.frame_draw_ms.average() {
line_two.push(format!("frame_draw {:.2}", frame_draw_ms));
}
line_two.push(format!(
"submit_to_webrtc {:.2}",
timings.submit_to_webrtc_ms.average().unwrap_or_default()
));
line_two.push(format!(
"capture_to_webrtc_total {:.2}",
timings.capture_to_webrtc_total_ms.average().unwrap_or_default()
));
format!("Timing ms: {}\nTiming ms: {}", line_one.join(" | "), line_two.join(" | "))
}
const MAX_PUBLISH_TIMING_SAMPLES: usize = 300;
#[derive(Default)]
struct PublisherTimingState {
samples: HashMap<u64, PublisherTimingSample>,
order: VecDeque<u64>,
latest_complete_sample: Option<PublisherTimingSample>,
}
impl PublisherTimingState {
fn record_frame_buffer(
&mut self,
sensor_exposure_timestamp_us: u64,
got_frame_buffer_timestamp_us: u64,
frame_id: Option<u32>,
) -> PublisherTimingSample {
let sample = self.get_or_insert_sample(sensor_exposure_timestamp_us, frame_id);
sample.got_frame_buffer_timestamp_us = Some(got_frame_buffer_timestamp_us);
*sample
}
fn record_sdk_event(&mut self, event: PublishTimingEvent) -> Option<PublisherTimingSample> {
if event.capture_timestamp_us == 0 {
return None;
}
let updated_sample = {
let sample = self.get_or_insert_sample(event.capture_timestamp_us, event.frame_id);
match event.stage {
PublishTimingStage::EncoderUpload => {
sample.encoder_upload_timestamp_us = Some(event.timestamp_us);
}
PublishTimingStage::EncoderOutput => {
sample.encoder_output_timestamp_us = Some(event.timestamp_us);
}
PublishTimingStage::WebrtcPacketize => {
sample.webrtc_packetize_timestamp_us = Some(event.timestamp_us);
}
}
*sample
};
if updated_sample.is_complete() {
self.latest_complete_sample = Some(updated_sample);
Some(updated_sample)
} else {
None
}
}
fn display_sample(&self) -> Option<PublisherTimingSample> {
self.latest_complete_sample
}
fn get_or_insert_sample(
&mut self,
sensor_exposure_timestamp_us: u64,
frame_id: Option<u32>,
) -> &mut PublisherTimingSample {
if !self.samples.contains_key(&sensor_exposure_timestamp_us) {
self.samples.insert(
sensor_exposure_timestamp_us,
PublisherTimingSample::new(sensor_exposure_timestamp_us, frame_id),
);
self.order.push_back(sensor_exposure_timestamp_us);
self.prune();
}
let sample = self
.samples
.get_mut(&sensor_exposure_timestamp_us)
.expect("timing sample should exist after insertion");
if frame_id.is_some() {
sample.frame_id = frame_id;
}
sample
}
fn prune(&mut self) {
while self.order.len() > MAX_PUBLISH_TIMING_SAMPLES {
if let Some(oldest) = self.order.pop_front() {
self.samples.remove(&oldest);
if self
.latest_complete_sample
.is_some_and(|sample| sample.sensor_exposure_timestamp_us == oldest)
{
self.latest_complete_sample = None;
}
}
}
}
}
fn update_shared_timing_sample(
shared: Option<&Arc<Mutex<SharedYuv>>>,
sample: PublisherTimingSample,
) {
if let Some(shared) = shared {
let mut shared = shared.lock();
let should_update = shared.timing_sample.map_or(true, |current| {
sample.sensor_exposure_timestamp_us >= current.sensor_exposure_timestamp_us
});
if should_update {
shared.timing_sample = Some(sample);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn requested_playout_delay_is_absent_when_no_delay_flags_are_set() {
assert_eq!(requested_playout_delay(None, None), None);
}
#[test]
fn requested_playout_delay_defaults_unset_partial_delay() {
assert_eq!(requested_playout_delay(Some(120), None), Some((120, 0)));
assert_eq!(requested_playout_delay(None, Some(240)), Some((0, 240)));
assert_eq!(requested_playout_delay(Some(120), Some(240)), Some((120, 240)));
}
fn timing_event(
stage: PublishTimingStage,
capture_timestamp_us: u64,
timestamp_us: u64,
) -> PublishTimingEvent {
PublishTimingEvent { stage, timestamp_us, capture_timestamp_us, frame_id: Some(7) }
}
#[test]
fn publisher_timing_state_waits_for_complete_sample() {
let mut state = PublisherTimingState::default();
state.record_frame_buffer(1_000, 1_100, Some(7));
assert!(state.display_sample().is_none());
assert!(state
.record_sdk_event(timing_event(PublishTimingStage::EncoderUpload, 1_000, 1_200))
.is_none());
assert!(state
.record_sdk_event(timing_event(PublishTimingStage::EncoderOutput, 1_000, 1_300))
.is_none());
assert!(state.display_sample().is_none());
}
#[test]
fn publisher_timing_state_displays_packetized_sample() {
let mut state = PublisherTimingState::default();
state.record_frame_buffer(1_000, 1_100, Some(7));
state.record_sdk_event(timing_event(PublishTimingStage::EncoderUpload, 1_000, 1_200));
state.record_sdk_event(timing_event(PublishTimingStage::EncoderOutput, 1_000, 1_300));
let sample = state
.record_sdk_event(timing_event(PublishTimingStage::WebrtcPacketize, 1_000, 1_400))
.expect("packetized sample should be displayable");
assert!(sample.is_complete());
assert_eq!(state.display_sample().unwrap().webrtc_packetize_timestamp_us, Some(1_400));
}
#[test]
fn publisher_timing_shared_update_accepts_current_frame() {
let shared = Arc::new(Mutex::new(SharedYuv::default()));
let mut current = PublisherTimingSample::new(1_000, Some(1));
shared.lock().timing_sample = Some(current);
current.encoder_upload_timestamp_us = Some(1_500);
update_shared_timing_sample(Some(&shared), current);
assert_eq!(shared.lock().timing_sample.unwrap().encoder_upload_timestamp_us, Some(1_500));
}
#[test]
fn publisher_timing_shared_update_ignores_other_frames() {
let shared = Arc::new(Mutex::new(SharedYuv::default()));
let current = PublisherTimingSample::new(2_000, Some(2));
let mut stale = PublisherTimingSample::new(1_000, Some(1));
stale.encoder_upload_timestamp_us = Some(1_500);
shared.lock().timing_sample = Some(current);
update_shared_timing_sample(Some(&shared), stale);
assert_eq!(
shared.lock().timing_sample.unwrap().sensor_exposure_timestamp_us,
current.sensor_exposure_timestamp_us
);
}
#[test]
fn capture_timestamp_validation_rejects_future_timestamp() {
assert_eq!(
validate_backend_capture_timestamp_us(Duration::from_micros(1_001), 1_000),
Err("is in the future")
);
}
#[test]
fn capture_timestamp_selection_falls_back_for_invalid_backend_timestamp() {
let mut log_state = CaptureTimestampLogState::default();
let selected = select_capture_wall_time_us(
Some(Duration::from_micros(1_001)),
900,
1_000,
&mut log_state,
);
assert_eq!(selected, 900);
}
#[test]
fn capture_timestamp_selection_uses_valid_backend_timestamp() {
let mut log_state = CaptureTimestampLogState::default();
let selected = select_capture_wall_time_us(
Some(Duration::from_micros(950)),
900,
1_000,
&mut log_state,
);
assert_eq!(selected, 950);
}
}
fn list_cameras() -> Result<()> {
let cams = nokhwa::query(ApiBackend::Auto)?;
println!("Available cameras:");
for (i, cam) in cams.iter().enumerate() {
println!("{}. {}", i, cam.human_name());
}
Ok(())
}
fn list_encoders() {
println!("Available video encoder backends:");
for backend in VideoEncoderBackend::list_available() {
println!("- {}", video_encoder_backend_name(backend));
}
}
enum VideoInput {
TestPattern(TestPattern),
Camera {
camera: Camera,
is_yuyv: bool,
},
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
Argus(argus::ArgusCaptureSession),
}
#[derive(Clone, Copy)]
struct CaptureConfig {
fps: u32,
attach_timestamp: bool,
burn_timestamp: bool,
attach_frame_id: bool,
display_timing: bool,
}
fn create_i420_buffer(width: u32, height: u32, align_for_display: bool) -> I420Buffer {
if align_for_display {
let uv_width = (width + 1) / 2;
I420Buffer::with_strides(
width,
height,
align_up(width, 256),
align_up(uv_width, 256),
align_up(uv_width, 256),
)
} else {
I420Buffer::new(width, height)
}
}
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
let args = Args::parse();
let ctrl_c_received = Arc::new(AtomicBool::new(false));
tokio::spawn({
let ctrl_c_received = ctrl_c_received.clone();
async move {
let _ = tokio::signal::ctrl_c().await;
ctrl_c_received.store(true, Ordering::Release);
info!("Ctrl-C received, exiting...");
}
});
run(args, ctrl_c_received).await
}
async fn run(args: Args, ctrl_c_received: Arc<AtomicBool>) -> Result<()> {
if args.list_cameras {
return list_cameras();
}
if args.list_encoders {
list_encoders();
return Ok(());
}
// LiveKit connection details
let url = args
.url
.or_else(|| env::var("LIVEKIT_URL").ok())
.expect("LIVEKIT_URL must be provided via --url or env");
let api_key = args
.api_key
.or_else(|| env::var("LIVEKIT_API_KEY").ok())
.expect("LIVEKIT_API_KEY must be provided via --api-key or env");
let api_secret = args
.api_secret
.or_else(|| env::var("LIVEKIT_API_SECRET").ok())
.expect("LIVEKIT_API_SECRET must be provided via --api-secret or env");
if let Some((min_playout_delay, max_playout_delay)) =
requested_playout_delay(args.min_playout_delay, args.max_playout_delay)
{
let twirp_host = normalize_twirp_host(&url);
let room_client = RoomClient::with_api_key(&twirp_host, &api_key, &api_secret);
info!(
"Recreating room '{}' with playout delay min={} max={} ms",
args.room_name, min_playout_delay, max_playout_delay
);
match room_client.delete_room(&args.room_name).await {
Ok(()) => info!("Deleted existing room '{}'", args.room_name),
Err(err) if is_twirp_not_found(&err) => {
debug!("Room '{}' did not exist before recreation", args.room_name);
}
Err(err) => return Err(err.into()),
}
room_client
.create_room_with_playout_delay(
&args.room_name,
CreateRoomOptions::default(),
min_playout_delay,
max_playout_delay,
)
.await?;
}
let token = access_token::AccessToken::with_api_key(&api_key, &api_secret)
.with_identity(&args.identity)
.with_name(&args.identity)
.with_grants(access_token::VideoGrants {
room_join: true,
room: args.room_name.clone(),
can_publish: true,
can_subscribe: false,
..Default::default()
})
.to_jwt()?;
info!("Connecting to LiveKit room '{}' as '{}'...", args.room_name, args.identity);
let mut room_options = RoomOptions::default();
room_options.auto_subscribe = true;
room_options.dynacast = args.dynacast;
// Configure E2EE if an encryption key is provided
if let Some(ref e2ee_key) = args.e2ee_key {
let key_provider = KeyProvider::with_shared_key(
KeyProviderOptions::default(),
e2ee_key.as_bytes().to_vec(),
);
room_options.encryption =
Some(E2eeOptions { encryption_type: EncryptionType::Gcm, key_provider });
info!("E2EE enabled with AES-GCM encryption");
}
let (room, _) = Room::connect(&url, &token, room_options).await?;
let room = std::sync::Arc::new(room);
info!("Connected: {} - {}", room.name(), room.sid().await);
// Enable E2EE after connection
if args.e2ee_key.is_some() {
room.e2ee_manager().set_enabled(true);
info!("End-to-end encryption activated");
}
// Log room events
{
let room_clone = room.clone();
tokio::spawn(async move {
let mut events = room_clone.subscribe();
info!("Subscribed to room events");
while let Some(evt) = events.recv().await {
debug!("Room event: {:?}", evt);
}
});
}
let (width, height, video_input) = match args.source {
SourceKind::Argus => {
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
{
if args.test_pattern {
anyhow::bail!("--test-pattern is not supported with --source argus");
}
if args.display_video {
anyhow::bail!("--display-video is not supported with --source argus");
}
if args.burn_timestamp {
log::warn!(
"--burn-timestamp is ignored with --source argus (DMA buffers are not CPU-mapped on the publish path)"
);
}
let session = argus::ArgusCaptureSession::new(
args.camera_index as u32,
args.width,
args.height,
args.fps,
)?;
info!(
"Argus MIPI capture session opened: {}x{} @ {} fps (camera {})",
session.width(),
session.height(),
args.fps,
args.camera_index,
);
(session.width(), session.height(), VideoInput::Argus(session))
}
#[cfg(not(all(target_os = "linux", target_arch = "aarch64")))]
{
anyhow::bail!(
"--source argus requires Linux aarch64 on NVIDIA Jetson; this binary was built for {}-{}",