BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / include / livekit / packet_trailer.h

packet_trailer.h

packet_trailer.h 13.3 KiB Download Raw
1/*
2 * Copyright 2025 LiveKit, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <stdint.h>
20
21#include <atomic>
22#include <deque>
23#include <memory>
24#include <optional>
25#include <span>
26#include <string>
27#include <unordered_map>
28#include <vector>
29
30#include "absl/types/optional.h"
31#include "api/frame_transformer_interface.h"
32#include "api/rtp_sender_interface.h"
33#include "api/rtp_receiver_interface.h"
34#include "api/scoped_refptr.h"
35#include "livekit/webrtc.h"
36#include "rtc_base/synchronization/mutex.h"
37#include "rust/cxx.h"
38
39// Forward declarations to avoid circular includes
40// (video_track.h -> packet_trailer.h -> peer_connection.h -> media_stream.h -> video_track.h)
41namespace livekit_ffi {
42class PeerConnectionFactory;
43class RtpSender;
44class RtpReceiver;
45enum class VideoPublishTimingStage : int32_t;
46enum class VideoSubscribeTimingStage : int32_t;
47struct VideoPublishTimingObserverWrapper;
48struct VideoSubscribeTimingObserverWrapper;
49} // namespace livekit_ffi
50
51namespace livekit_ffi {
52
53// Magic bytes to identify packet trailers: "LKTS" (LiveKit TimeStamp)
54constexpr uint8_t kPacketTrailerMagic[4] = {'L', 'K', 'T', 'S'};
55
56// Trailer envelope: [trailer_len: 1B] [magic: 4B] = 5 bytes.
57// Always present at the end of every trailer.
58constexpr size_t kTrailerEnvelopeSize = 5;
59
60// TLV element overhead: [tag: 1B] [len: 1B] = 2 bytes before value.
61// All TLV bytes (tag, len, value) are XORed with 0xFF.
62
63// TLV tag IDs. Every field is optional: a TLV is emitted only when its
64// value is set, so a trailer may carry any subset of the features.
65constexpr uint8_t kTagTimestampUs = 0x01; // value: 8 bytes big-endian uint64,
66 // omitted when timestamp is unset (0)
67constexpr uint8_t kTagFrameId = 0x02; // value: 4 bytes big-endian uint32,
68 // omitted when frame_id is unset (0)
69constexpr uint8_t kTagUserData = 0x03; // value: arbitrary bytes, omitted
70 // when empty; bounded by the
71 // remaining trailer budget
72 // (255 - fixed TLVs - envelope - 2)
73
74constexpr size_t kTimestampTlvSize = 10; // tag + len + 8-byte value
75constexpr size_t kFrameIdTlvSize = 6; // tag + len + 4-byte value
76constexpr size_t kUserDataTlvHeaderSize = 2; // tag + len, before value bytes
77
78// The trailer length is encoded in a single XORed byte, so the entire
79// trailer (TLV region + envelope) can never exceed 255 bytes. user_data
80// that would push the trailer past this budget is dropped (see
81// AppendTrailer), never truncated.
82constexpr size_t kPacketTrailerMaxTotal = 255;
83
84// Fixed-feature trailer size varies because each TLV is omitted when its
85// field is unset. The minimum non-empty trailer carries a single feature
86// (the smallest being frame_id); when no field is set, no trailer is
87// emitted at all. user_data is variable-length and accounted for separately.
88constexpr size_t kPacketTrailerMinSize =
89 kFrameIdTlvSize + kTrailerEnvelopeSize;
90constexpr size_t kPacketTrailerMaxSize =
91 kTimestampTlvSize + kFrameIdTlvSize + kTrailerEnvelopeSize;
92
93struct PacketTrailerMetadata {
94 uint64_t user_timestamp;
95 uint32_t frame_id;
96 uint32_t ssrc; // SSRC that produced this entry (for simulcast tracking)
97 std::vector<uint8_t> user_data; // arbitrary app-supplied bytes (PTF_USER_DATA)
98};
99
100/// Parses a trailer payload (TLV region followed by the trailer envelope) and
101/// returns the embedded metadata, or `std::nullopt` if the payload is missing
102/// the magic envelope or contains no recognized TLV elements.
103///
104/// Shared by the codec-agnostic trailer path and the AV1 OBU path.
105std::optional<PacketTrailerMetadata> ParseTrailerPayload(
106 std::span<const uint8_t> trailer);
107
108/// Frame transformer that appends/extracts packet trailers.
109/// This transformer can be used standalone or in conjunction with e2ee.
110///
111/// On the send side, user timestamps are stored in an internal map keyed
112/// by capture timestamp (microseconds). When TransformSend fires it
113/// looks up the user timestamp via the frame's CaptureTime().
114///
115/// On the receive side, extracted frame metadata is stored in an
116/// internal map keyed by RTP timestamp (uint32_t). Decoded frames can
117/// look up their metadata via lookup_frame_metadata(rtp_ts).
118class PacketTrailerTransformer : public webrtc::FrameTransformerInterface {
119 public:
120 enum class Direction { kSend, kReceive };
121
122 explicit PacketTrailerTransformer(Direction direction);
123 ~PacketTrailerTransformer() override = default;
124
125 // FrameTransformerInterface implementation
126 void Transform(
127 std::unique_ptr<webrtc::TransformableFrameInterface> frame) override;
128 void RegisterTransformedFrameCallback(
129 webrtc::scoped_refptr<webrtc::TransformedFrameCallback> callback) override;
130 void RegisterTransformedFrameSinkCallback(
131 webrtc::scoped_refptr<webrtc::TransformedFrameCallback> callback,
132 uint32_t ssrc) override;
133 void UnregisterTransformedFrameCallback() override;
134 void UnregisterTransformedFrameSinkCallback(uint32_t ssrc) override;
135
136 /// Enable/disable timestamp embedding
137 void set_enabled(bool enabled);
138 bool enabled() const;
139
140 /// Lookup the frame metadata associated with a given RTP timestamp.
141 /// Returns the metadata if found, nullopt otherwise.
142 /// The entry is removed from the map after lookup.
143 std::optional<PacketTrailerMetadata> lookup_frame_metadata(uint32_t rtp_timestamp);
144
145 /// Store frame metadata for a given capture timestamp (sender side).
146 /// Called from VideoTrackSource::on_captured_frame with the
147 /// TimestampAligner-adjusted timestamp, which matches CaptureTime()
148 /// in the encoder pipeline.
149 void store_frame_metadata(int64_t capture_timestamp_us,
150 uint64_t user_timestamp,
151 uint32_t frame_id,
152 rust::Slice<const uint8_t> user_data);
153
154 /// Set the observer receiving sender-side publish timing events.
155 void set_publish_timing_observer(
156 rust::Box<VideoPublishTimingObserverWrapper> observer);
157
158 /// Clear the observer receiving sender-side publish timing events.
159 void clear_publish_timing_observer();
160
161 /// Emit a sender-side publish timing event.
162 void emit_publish_timing(VideoPublishTimingStage stage,
163 uint64_t user_timestamp,
164 uint32_t frame_id) const;
165
166 /// Set the observer receiving receiver-side subscribe timing events.
167 void set_subscribe_timing_observer(
168 rust::Box<VideoSubscribeTimingObserverWrapper> observer);
169
170 /// Clear the observer receiving receiver-side subscribe timing events.
171 void clear_subscribe_timing_observer();
172
173 /// Emit a receiver-side subscribe timing event.
174 void emit_subscribe_timing(VideoSubscribeTimingStage stage,
175 uint64_t user_timestamp,
176 uint32_t frame_id) const;
177
178 private:
179 void TransformSend(
180 std::unique_ptr<webrtc::TransformableFrameInterface> frame);
181 void TransformReceive(
182 std::unique_ptr<webrtc::TransformableFrameInterface> frame);
183 void emit_subscribe_timing(VideoSubscribeTimingStage stage,
184 uint64_t user_timestamp,
185 uint32_t frame_id,
186 uint64_t timestamp_us) const;
187 bool publish_timing_enabled() const;
188 bool subscribe_timing_enabled() const;
189
190 PacketTrailerMetadata LookupSendMetadata(
191 const webrtc::TransformableFrameInterface& frame,
192 uint32_t ssrc,
193 uint32_t rtp_timestamp) const;
194
195 /// Append frame metadata trailer to frame data
196 std::vector<uint8_t> AppendTrailer(
197 std::span<const uint8_t> data,
198 uint64_t user_timestamp,
199 uint32_t frame_id,
200 const std::vector<uint8_t>& user_data,
201 bool is_av1);
202
203 /// Extract and remove frame metadata trailer from frame data
204 std::optional<PacketTrailerMetadata> ExtractTrailer(
205 std::span<const uint8_t> data,
206 std::vector<uint8_t>& out_data,
207 bool is_av1);
208
209 const Direction direction_;
210 std::atomic<bool> enabled_{true};
211 mutable webrtc::Mutex mutex_;
212 webrtc::scoped_refptr<webrtc::TransformedFrameCallback> callback_;
213 std::unordered_map<uint32_t,
214 webrtc::scoped_refptr<webrtc::TransformedFrameCallback>>
215 sink_callbacks_;
216 // Send-side map: capture timestamp (us) -> frame metadata.
217 // Populated by store_frame_metadata(), consumed by TransformSend()
218 // via CaptureTime() lookup.
219 mutable webrtc::Mutex send_map_mutex_;
220 mutable std::unordered_map<int64_t, PacketTrailerMetadata> send_map_;
221 mutable std::deque<int64_t> send_map_order_;
222 static constexpr size_t kMaxSendMapEntries = 300;
223
224 // Receive-side map: RTP timestamp -> frame metadata.
225 // Keyed by RTP timestamp so decoded frames can look up their
226 // metadata regardless of frame drops or reordering.
227 mutable webrtc::Mutex recv_map_mutex_;
228 mutable std::unordered_map<uint32_t, PacketTrailerMetadata> recv_map_;
229 mutable std::deque<uint32_t> recv_map_order_;
230 static constexpr size_t kMaxRecvMapEntries = 300;
231
232 // Simulcast tracking: detect layer switches and flush stale entries.
233 mutable uint32_t recv_active_ssrc_{0};
234
235 mutable webrtc::Mutex publish_timing_observer_mutex_;
236 std::atomic<bool> publish_timing_enabled_{false};
237 mutable std::shared_ptr<rust::Box<VideoPublishTimingObserverWrapper>>
238 publish_timing_observer_;
239 mutable webrtc::Mutex subscribe_timing_observer_mutex_;
240 std::atomic<bool> subscribe_timing_enabled_{false};
241 mutable std::shared_ptr<rust::Box<VideoSubscribeTimingObserverWrapper>>
242 subscribe_timing_observer_;
243};
244
245/// Wrapper class for Rust FFI that manages packet trailer transformers.
246class PacketTrailerHandler {
247 public:
248 PacketTrailerHandler(
249 std::shared_ptr<RtcRuntime> rtc_runtime,
250 webrtc::scoped_refptr<webrtc::RtpSenderInterface> sender);
251
252 PacketTrailerHandler(
253 std::shared_ptr<RtcRuntime> rtc_runtime,
254 webrtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver);
255
256 ~PacketTrailerHandler() = default;
257
258 /// Enable/disable timestamp embedding
259 void set_enabled(bool enabled) const;
260 bool enabled() const;
261
262 /// Lookup the user timestamp for a given RTP timestamp (receiver side).
263 /// Returns UINT64_MAX if not found. The entry is removed after lookup.
264 /// Also caches the frame_id for retrieval via last_lookup_frame_id().
265 uint64_t lookup_timestamp(uint32_t rtp_timestamp) const;
266
267 /// Returns the frame_id from the most recent successful
268 /// lookup_timestamp() call. Returns 0 if no lookup succeeded.
269 uint32_t last_lookup_frame_id() const;
270
271 /// Returns the user_data from the most recent successful
272 /// lookup_timestamp() call. Returns an empty vector if no lookup
273 /// succeeded or the frame carried no user_data.
274 rust::Vec<uint8_t> last_lookup_user_data() const;
275
276 /// Store frame metadata for a given capture timestamp (sender side).
277 void store_frame_metadata(int64_t capture_timestamp_us,
278 uint64_t user_timestamp,
279 uint32_t frame_id,
280 rust::Slice<const uint8_t> user_data) const;
281
282 /// Set the observer receiving sender-side publish timing events.
283 void set_publish_timing_observer(
284 rust::Box<VideoPublishTimingObserverWrapper> observer) const;
285
286 /// Clear the observer receiving sender-side publish timing events.
287 void clear_publish_timing_observer() const;
288
289 /// Emit a sender-side publish timing event.
290 void emit_publish_timing(VideoPublishTimingStage stage,
291 uint64_t user_timestamp,
292 uint32_t frame_id) const;
293
294 /// Set the observer receiving receiver-side subscribe timing events.
295 void set_subscribe_timing_observer(
296 rust::Box<VideoSubscribeTimingObserverWrapper> observer) const;
297
298 /// Clear the observer receiving receiver-side subscribe timing events.
299 void clear_subscribe_timing_observer() const;
300
301 /// Emit a receiver-side subscribe timing event.
302 void emit_subscribe_timing(VideoSubscribeTimingStage stage,
303 uint64_t user_timestamp,
304 uint32_t frame_id) const;
305
306 /// Access the underlying transformer for chaining.
307 webrtc::scoped_refptr<PacketTrailerTransformer> transformer() const;
308
309 private:
310 std::shared_ptr<RtcRuntime> rtc_runtime_;
311 webrtc::scoped_refptr<PacketTrailerTransformer> transformer_;
312 webrtc::scoped_refptr<webrtc::RtpSenderInterface> sender_;
313 webrtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver_;
314 mutable uint32_t last_frame_id_{0};
315 mutable std::vector<uint8_t> last_user_data_;
316};
317
318// Factory functions for Rust FFI
319
320std::shared_ptr<PacketTrailerHandler> new_packet_trailer_sender(
321 std::shared_ptr<PeerConnectionFactory> peer_factory,
322 std::shared_ptr<RtpSender> sender);
323
324std::shared_ptr<PacketTrailerHandler> new_packet_trailer_receiver(
325 std::shared_ptr<PeerConnectionFactory> peer_factory,
326 std::shared_ptr<RtpReceiver> receiver);
327
328} // namespace livekit_ffi