| 1 | // Copyright 2026 LiveKit, Inc. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Packet trailer support for end-to-end frame metadata propagation. |
| 16 | //! |
| 17 | //! This module provides functionality to embed user-supplied metadata |
| 18 | //! in encoded video frames as trailers. The timestamps/frameIDs are preserved |
| 19 | //! through the WebRTC pipeline and can be extracted on the receiver side. |
| 20 | //! |
| 21 | //! On the send side, user timestamps/frameIDs are stored in the handler's internal |
| 22 | //! map keyed by RTP timestamp. When the encoder produces a frame, |
| 23 | //! the transformer looks up the metadata via the frame's CaptureTime(). |
| 24 | //! |
| 25 | //! On the receive side, extracted frame metadata is stored in an |
| 26 | //! internal map keyed by RTP timestamp. Decoded frames look up their |
| 27 | //! metadata via lookup_frame_metadata(rtp_timestamp). |
| 28 | |
| 29 | use std::sync::Arc; |
| 30 | |
| 31 | use cxx::SharedPtr; |
| 32 | use webrtc_sys::packet_trailer::ffi as sys_pt; |
| 33 | |
| 34 | use crate::{ |
| 35 | peer_connection_factory::PeerConnectionFactory, rtp_receiver::RtpReceiver, |
| 36 | rtp_sender::RtpSender, |
| 37 | }; |
| 38 | |
| 39 | /// Stage reached by a native local video frame in the publish pipeline. |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 41 | pub enum PublishTimingStage { |
| 42 | /// The adapted raw frame was handed to WebRTC's encoder path. |
| 43 | EncoderUpload, |
| 44 | /// WebRTC produced an encoded frame for packetization. |
| 45 | EncoderOutput, |
| 46 | /// The encoded frame was handed back to WebRTC's packetizer. |
| 47 | WebrtcPacketize, |
| 48 | } |
| 49 | |
| 50 | /// Stage reached by a native remote video frame in the subscribe pipeline. |
| 51 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 52 | pub enum SubscribeTimingStage { |
| 53 | /// WebRTC produced an encoded frame after RTP depacketization. |
| 54 | WebrtcReceive, |
| 55 | /// The encoded frame was handed to WebRTC's decoder. |
| 56 | DecoderUpload, |
| 57 | /// WebRTC produced a decoded frame for the native video sink. |
| 58 | DecoderOutput, |
| 59 | } |
| 60 | |
| 61 | /// Timestamped native local video publish pipeline event. |
| 62 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 63 | pub struct PublishTimingEvent { |
| 64 | /// Publish pipeline stage reached by the frame. |
| 65 | pub stage: PublishTimingStage, |
| 66 | /// Wall-clock time when this stage was observed, in microseconds since the Unix epoch. |
| 67 | pub timestamp_us: u64, |
| 68 | /// User capture timestamp associated with this frame, in microseconds since the Unix epoch. |
| 69 | pub capture_timestamp_us: u64, |
| 70 | /// Optional application frame ID associated with this frame. |
| 71 | pub frame_id: Option<u32>, |
| 72 | } |
| 73 | |
| 74 | /// Timestamped native remote video subscribe pipeline event. |
| 75 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 76 | pub struct SubscribeTimingEvent { |
| 77 | /// Subscribe pipeline stage reached by the frame. |
| 78 | pub stage: SubscribeTimingStage, |
| 79 | /// Wall-clock time when this stage was observed, in microseconds since the Unix epoch. |
| 80 | pub timestamp_us: u64, |
| 81 | /// User capture timestamp associated with this frame, in microseconds since the Unix epoch. |
| 82 | pub capture_timestamp_us: u64, |
| 83 | /// Optional application frame ID associated with this frame. |
| 84 | pub frame_id: Option<u32>, |
| 85 | } |
| 86 | |
| 87 | /// Callback invoked for native local video publish timing events. |
| 88 | pub type PublishTimingObserver = Arc<dyn Fn(PublishTimingEvent) + Send + Sync + 'static>; |
| 89 | /// Callback invoked for native remote video subscribe timing events. |
| 90 | pub type SubscribeTimingObserver = Arc<dyn Fn(SubscribeTimingEvent) + Send + Sync + 'static>; |
| 91 | |
| 92 | impl From<sys_pt::VideoPublishTimingStage> for PublishTimingStage { |
| 93 | fn from(stage: sys_pt::VideoPublishTimingStage) -> Self { |
| 94 | match stage { |
| 95 | sys_pt::VideoPublishTimingStage::EncoderUpload => Self::EncoderUpload, |
| 96 | sys_pt::VideoPublishTimingStage::EncoderOutput => Self::EncoderOutput, |
| 97 | sys_pt::VideoPublishTimingStage::WebrtcPacketize => Self::WebrtcPacketize, |
| 98 | _ => Self::WebrtcPacketize, |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | impl From<sys_pt::VideoPublishTimingEvent> for PublishTimingEvent { |
| 104 | fn from(event: sys_pt::VideoPublishTimingEvent) -> Self { |
| 105 | Self { |
| 106 | stage: event.stage.into(), |
| 107 | timestamp_us: event.timestamp_us, |
| 108 | capture_timestamp_us: event.capture_timestamp_us, |
| 109 | frame_id: (event.frame_id != 0).then_some(event.frame_id), |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | impl From<sys_pt::VideoSubscribeTimingStage> for SubscribeTimingStage { |
| 115 | fn from(stage: sys_pt::VideoSubscribeTimingStage) -> Self { |
| 116 | match stage { |
| 117 | sys_pt::VideoSubscribeTimingStage::WebrtcReceive => Self::WebrtcReceive, |
| 118 | sys_pt::VideoSubscribeTimingStage::DecoderUpload => Self::DecoderUpload, |
| 119 | sys_pt::VideoSubscribeTimingStage::DecoderOutput => Self::DecoderOutput, |
| 120 | _ => Self::DecoderOutput, |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | impl From<sys_pt::VideoSubscribeTimingEvent> for SubscribeTimingEvent { |
| 126 | fn from(event: sys_pt::VideoSubscribeTimingEvent) -> Self { |
| 127 | Self { |
| 128 | stage: event.stage.into(), |
| 129 | timestamp_us: event.timestamp_us, |
| 130 | capture_timestamp_us: event.capture_timestamp_us, |
| 131 | frame_id: (event.frame_id != 0).then_some(event.frame_id), |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// Handler for packet trailer embedding/extraction on RTP streams. |
| 137 | /// |
| 138 | /// For sender side: Stores frame metadata keyed by capture timestamp |
| 139 | /// and embeds them as binary payload trailers on encoded frames before they |
| 140 | /// are sent. Use `store_frame_metadata()` to associate metadata with |
| 141 | /// a captured frame. |
| 142 | /// |
| 143 | /// For receiver side: Extracts frame metadata from received frames |
| 144 | /// and makes them available for retrieval via `lookup_frame_metadata()`. |
| 145 | #[derive(Clone)] |
| 146 | pub struct PacketTrailerHandler { |
| 147 | sys_handle: SharedPtr<sys_pt::PacketTrailerHandler>, |
| 148 | } |
| 149 | |
| 150 | impl PacketTrailerHandler { |
| 151 | /// Enable or disable timestamp embedding/extraction. |
| 152 | pub fn set_enabled(&self, enabled: bool) { |
| 153 | self.sys_handle.set_enabled(enabled); |
| 154 | } |
| 155 | |
| 156 | /// Check if timestamp embedding/extraction is enabled. |
| 157 | pub fn enabled(&self) -> bool { |
| 158 | self.sys_handle.enabled() |
| 159 | } |
| 160 | |
| 161 | /// Lookup the frame metadata for a given RTP timestamp (receiver side). |
| 162 | /// Returns `Some((user_timestamp, frame_id, user_data))` if found, |
| 163 | /// `None` otherwise. The entry is removed from the map after a |
| 164 | /// successful lookup. |
| 165 | pub fn lookup_frame_metadata(&self, rtp_timestamp: u32) -> Option<(u64, u32, Vec<u8>)> { |
| 166 | let ts = self.sys_handle.lookup_timestamp(rtp_timestamp); |
| 167 | if ts != u64::MAX { |
| 168 | let frame_id = self.sys_handle.last_lookup_frame_id(); |
| 169 | let user_data = self.sys_handle.last_lookup_user_data(); |
| 170 | Some((ts, frame_id, user_data)) |
| 171 | } else { |
| 172 | None |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// Store frame metadata for a given capture timestamp (sender side). |
| 177 | /// |
| 178 | /// The `capture_timestamp_us` must be the TimestampAligner-adjusted |
| 179 | /// timestamp (as produced by `VideoTrackSource::on_captured_frame`), |
| 180 | /// NOT the original `timestamp_us` from the VideoFrame. The transformer |
| 181 | /// looks up the metadata by the frame's `CaptureTime()` which is |
| 182 | /// derived from the aligned value. |
| 183 | /// |
| 184 | /// In normal usage this is called automatically by the C++ layer -- |
| 185 | /// callers should set `user_timestamp` and `frame_id` on the |
| 186 | /// `VideoFrame` and let `capture_frame` / `on_captured_frame` handle |
| 187 | /// the rest. |
| 188 | pub fn store_frame_metadata( |
| 189 | &self, |
| 190 | capture_timestamp_us: i64, |
| 191 | user_timestamp: u64, |
| 192 | frame_id: u32, |
| 193 | user_data: &[u8], |
| 194 | ) { |
| 195 | self.sys_handle.store_frame_metadata( |
| 196 | capture_timestamp_us, |
| 197 | user_timestamp, |
| 198 | frame_id, |
| 199 | user_data, |
| 200 | ); |
| 201 | } |
| 202 | |
| 203 | pub(crate) fn sys_handle(&self) -> SharedPtr<sys_pt::PacketTrailerHandler> { |
| 204 | self.sys_handle.clone() |
| 205 | } |
| 206 | |
| 207 | /// Set the callback receiving sender-side publish timing events. |
| 208 | pub fn set_publish_timing_observer(&self, observer: Option<PublishTimingObserver>) { |
| 209 | if let Some(observer) = observer { |
| 210 | self.sys_handle.set_publish_timing_observer(Box::new( |
| 211 | webrtc_sys::packet_trailer::VideoPublishTimingObserverWrapper::new(Box::new( |
| 212 | move |event| observer(event.into()), |
| 213 | )), |
| 214 | )); |
| 215 | } else { |
| 216 | self.sys_handle.clear_publish_timing_observer(); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// Set the callback receiving receiver-side subscribe timing events. |
| 221 | pub fn set_subscribe_timing_observer(&self, observer: Option<SubscribeTimingObserver>) { |
| 222 | if let Some(observer) = observer { |
| 223 | self.sys_handle.set_subscribe_timing_observer(Box::new( |
| 224 | webrtc_sys::packet_trailer::VideoSubscribeTimingObserverWrapper::new(Box::new( |
| 225 | move |event| observer(event.into()), |
| 226 | )), |
| 227 | )); |
| 228 | } else { |
| 229 | self.sys_handle.clear_subscribe_timing_observer(); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | pub(crate) fn emit_subscribe_timing( |
| 234 | &self, |
| 235 | stage: SubscribeTimingStage, |
| 236 | capture_timestamp_us: u64, |
| 237 | frame_id: u32, |
| 238 | ) { |
| 239 | let stage = match stage { |
| 240 | SubscribeTimingStage::WebrtcReceive => sys_pt::VideoSubscribeTimingStage::WebrtcReceive, |
| 241 | SubscribeTimingStage::DecoderUpload => sys_pt::VideoSubscribeTimingStage::DecoderUpload, |
| 242 | SubscribeTimingStage::DecoderOutput => sys_pt::VideoSubscribeTimingStage::DecoderOutput, |
| 243 | }; |
| 244 | self.sys_handle.emit_subscribe_timing(stage, capture_timestamp_us, frame_id); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /// Create a sender-side packet trailer handler. |
| 249 | /// |
| 250 | /// This handler will embed frame metadata into encoded frames before |
| 251 | /// they are packetized and sent. Use `store_frame_metadata()` to |
| 252 | /// associate metadata with a captured frame's capture timestamp. |
| 253 | pub fn create_sender_handler( |
| 254 | peer_factory: &PeerConnectionFactory, |
| 255 | sender: &RtpSender, |
| 256 | ) -> PacketTrailerHandler { |
| 257 | PacketTrailerHandler { |
| 258 | sys_handle: sys_pt::new_packet_trailer_sender( |
| 259 | peer_factory.handle.sys_handle.clone(), |
| 260 | sender.handle.sys_handle.clone(), |
| 261 | ), |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// Create a receiver-side packet trailer handler. |
| 266 | /// |
| 267 | /// This handler will extract frame metadata from received frames |
| 268 | /// and store them in a map keyed by RTP timestamp. Use |
| 269 | /// `lookup_frame_metadata(rtp_timestamp)` to retrieve the metadata |
| 270 | /// for a specific decoded frame. |
| 271 | pub fn create_receiver_handler( |
| 272 | peer_factory: &PeerConnectionFactory, |
| 273 | receiver: &RtpReceiver, |
| 274 | ) -> PacketTrailerHandler { |
| 275 | PacketTrailerHandler { |
| 276 | sys_handle: sys_pt::new_packet_trailer_receiver( |
| 277 | peer_factory.handle.sys_handle.clone(), |
| 278 | receiver.handle.sys_handle.clone(), |
| 279 | ), |
| 280 | } |
| 281 | } |