Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat svc simulcast #266

Merged
merged 12 commits into from
May 2, 2024
Merged

Feat svc simulcast #266

merged 12 commits into from
May 2, 2024

Conversation

giangndm
Copy link
Contributor

@giangndm giangndm commented Apr 26, 2024

Pull Request

Description

This PR implement SVC and Simulcast suport

Related Issue

If this pull request is related to any issue, please mention it here.

Checklist

  • I have tested the changes locally.
  • I have reviewed the code changes.
  • I have updated the documentation, if necessary.
  • I have added appropriate tests, if applicable.

Screenshots

If applicable, add screenshots to help explain the changes made.

Additional Notes

Add any additional notes or context about the pull request here.

Copy link

coderabbitai bot commented Apr 26, 2024

Walkthrough

Walkthrough

The updates primarily focus on refining syntax, enhancing logging, and expanding media handling capabilities across various files in the project. Key changes include the introduction of new structures for media packet selection and bitrate control, adjustments in function syntax, and improved metadata management within media packets. These refinements aim to enhance performance and clarity in media processing modules.

Changes

Files Summary
bin/public/whip/whip.demo.js, bin/public/whip/whip.js Syntax and structural adjustments, SDP offer modifications.
packages/media_core/src/.../cluster.rs, packages/media_core/src/.../endpoint.rs, packages/media_core/src/.../local_track/*.rs Enhanced media packet handling, added selectors for bitrate and packet control, updated logging.
packages/media_utils/src/*.rs Added new modules for sequence and timestamp rewriting.
packages/protocol/src/media.rs, packages/transport_webrtc/src/media/*.rs Introduced new structures and functions for media conversion and packet rewriting. Enhanced codec handling for H264, VP8, and VP9.
packages/transport_webrtc/src/lib.rs Restructured module imports, removed and added modules.

🐇💬
Oh, hark! What changes we now see,
From whip's demo to media's spree.
Bits and bytes, they dance and twirl,
In a digital ballet, a code-world swirl.
Cheers to the devs, with minds so bright,
Crafting code by day and by night! 🌟🎉

(\__/) ||
(•ㅅ•) ||
/   づ

Recent Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between c42e37b and dfd9c12.
Files ignored due to path filters (6)
  • Cargo.lock is excluded by !**/*.lock, !**/*.lock
  • Cargo.toml is excluded by !**/*.toml
  • bin/Cargo.toml is excluded by !**/*.toml
  • packages/media_core/Cargo.toml is excluded by !**/*.toml
  • packages/media_utils/Cargo.toml is excluded by !**/*.toml
  • packages/transport_webrtc/Cargo.toml is excluded by !**/*.toml
Files selected for processing (28)
  • bin/public/whip/whip.demo.js (1 hunks)
  • bin/public/whip/whip.js (1 hunks)
  • packages/media_core/src/cluster.rs (1 hunks)
  • packages/media_core/src/cluster/room/channel_pub.rs (3 hunks)
  • packages/media_core/src/cluster/room/channel_sub.rs (4 hunks)
  • packages/media_core/src/cluster/room/metadata.rs (1 hunks)
  • packages/media_core/src/endpoint.rs (1 hunks)
  • packages/media_core/src/endpoint/internal/local_track.rs (8 hunks)
  • packages/media_core/src/endpoint/internal/local_track/packet_selector.rs (1 hunks)
  • packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs (1 hunks)
  • packages/media_core/src/endpoint/internal/local_track/packet_selector/video_single.rs (1 hunks)
  • packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp8_sim.rs (1 hunks)
  • packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp9_svc.rs (1 hunks)
  • packages/media_core/src/endpoint/internal/remote_track.rs (4 hunks)
  • packages/media_utils/src/lib.rs (1 hunks)
  • packages/media_utils/src/seq_extend.rs (1 hunks)
  • packages/media_utils/src/seq_rewrite.rs (1 hunks)
  • packages/media_utils/src/ts_rewrite.rs (1 hunks)
  • packages/protocol/src/media.rs (2 hunks)
  • packages/transport_webrtc/src/lib.rs (1 hunks)
  • packages/transport_webrtc/src/media/bit_read.rs (1 hunks)
  • packages/transport_webrtc/src/media/h264.rs (1 hunks)
  • packages/transport_webrtc/src/media/mod.rs (1 hunks)
  • packages/transport_webrtc/src/media/vp8.rs (1 hunks)
  • packages/transport_webrtc/src/media/vp9.rs (1 hunks)
  • packages/transport_webrtc/src/transport.rs (6 hunks)
  • packages/transport_webrtc/src/transport/whep.rs (6 hunks)
  • packages/transport_webrtc/src/transport/whip.rs (6 hunks)
Files skipped from review due to trivial changes (2)
  • bin/public/whip/whip.demo.js
  • packages/media_core/src/cluster/room/metadata.rs
Additional Context Used
GitHub Check Runs (2)
codecov/patch success (30)

packages/media_core/src/cluster/room/channel_sub.rs: [warning] 79-79: packages/media_core/src/cluster/room/channel_sub.rs#L79
Added line #L79 was not covered by tests


packages/media_core/src/cluster/room/channel_sub.rs: [warning] 81-81: packages/media_core/src/cluster/room/channel_sub.rs#L81
Added line #L81 was not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 61-62: packages/media_core/src/endpoint/internal/local_track.rs#L61-L62
Added lines #L61 - L62 were not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 83-83: packages/media_core/src/endpoint/internal/local_track.rs#L83
Added line #L83 was not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 91-95: packages/media_core/src/endpoint/internal/local_track.rs#L91-L95
Added lines #L91 - L95 were not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 126-127: packages/media_core/src/endpoint/internal/local_track.rs#L126-L127
Added lines #L126 - L127 were not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 138-138: packages/media_core/src/endpoint/internal/local_track.rs#L138
Added line #L138 was not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 153-153: packages/media_core/src/endpoint/internal/local_track.rs#L153
Added line #L153 was not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 156-156: packages/media_core/src/endpoint/internal/local_track.rs#L156
Added line #L156 was not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 158-166: packages/media_core/src/endpoint/internal/local_track.rs#L158-L166
Added lines #L158 - L166 were not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 168-170: packages/media_core/src/endpoint/internal/local_track.rs#L168-L170
Added lines #L168 - L170 were not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 172-172: packages/media_core/src/endpoint/internal/local_track.rs#L172
Added line #L172 was not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 174-178: packages/media_core/src/endpoint/internal/local_track.rs#L174-L178
Added lines #L174 - L178 were not covered by tests


packages/media_core/src/endpoint/internal/local_track.rs: [warning] 185-189: packages/media_core/src/endpoint/internal/local_track.rs#L185-L189
Added lines #L185 - L189 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 99-105: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L99-L105
Added lines #L99 - L105 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 129-129: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L129
Added line #L129 was not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 172-172: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L172
Added line #L172 was not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 192-198: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L192-L198
Added lines #L192 - L198 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 208-209: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L208-L209
Added lines #L208 - L209 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 211-213: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L211-L213
Added lines #L211 - L213 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 216-218: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L216-L218
Added lines #L216 - L218 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 221-223: packages/media_core/src/endpoint/internal/local_track/packet_selector.rs#L221-L223
Added lines #L221 - L223 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 41-43: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L41-L43
Added lines #L41 - L43 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 73-73: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L73
Added line #L73 was not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 75-79: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L75-L79
Added lines #L75 - L79 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 88-88: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L88
Added line #L88 was not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 90-92: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L90-L92
Added lines #L90 - L92 were not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 94-94: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L94
Added line #L94 was not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 107-107: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L107
Added line #L107 was not covered by tests


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 115-115: packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs#L115
Added line #L115 was not covered by tests

clippy success (29)

packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 89-95:
this if statement can be collapsed


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 88-88:
called map(f) on an Option value where f is a closure that returns the unit type ()


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 111-111:
called map(f) on an Option value where f is a closure that returns the unit type ()


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 180-180:
this expression creates a reference which is immediately dereferenced by the compiler


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 181-181:
called map(f) on an Option value where f is a closure that returns the unit type ()


packages/media_core/src/endpoint/internal/local_track/packet_selector.rs: [warning] 227-227:
Box::new(_) of default value


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 50-50:
unused variable: sim


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 38-38:
binary comparison to literal Option::None


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs: [warning] 53-73:
if chain can be rewritten with match


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp8_sim.rs: [warning] 58-58:
binary comparison to literal Option::None


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp8_sim.rs: [warning] 74-128:
if chain can be rewritten with match


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp8_sim.rs: [warning] 76-86:
if chain can be rewritten with match


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp9_svc.rs: [warning] 87-143:
if chain can be rewritten with match


packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp9_svc.rs: [warning] 89-101:
if chain can be rewritten with match


packages/media_core/src/endpoint/internal/remote_track.rs: [warning] 105-105:
assigning the result of Clone::clone() may be inefficient


packages/media_core/src/endpoint/internal/remote_track.rs: [warning] 111-111:
assigning the result of Clone::clone() may be inefficient


packages/media_utils/src/ts_rewrite.rs: [warning] 40-40:
casting to the same type is unnecessary (i64 -> i64)


packages/protocol/src/media.rs: [warning] 64-64:
unneeded return statement


packages/protocol/src/media.rs: [warning] 99-99:
unneeded return statement


packages/transport_webrtc/src/media/h264.rs: [warning] 24-24:
unused variable: payload


packages/transport_webrtc/src/media/h264.rs: [warning] 24-24:
unused variable: sim


packages/transport_webrtc/src/media/mod.rs: [warning] 51-51:
called map(..).flatten() on Option


packages/transport_webrtc/src/media/mod.rs: [warning] 56-56:
called map(..).flatten() on Option


packages/transport_webrtc/src/media/mod.rs: [warning] 61-61:
called map(..).flatten() on Option


packages/transport_webrtc/src/media/vp8.rs: [warning] 18-18:
field assignment outside of initializer for an instance created with Default::default()


packages/transport_webrtc/src/media/vp9.rs: [warning] 39-43:
all variants have the same prefix: Err


packages/transport_webrtc/src/media/vp9.rs: [warning] 93-93:
empty doc comment


packages/transport_webrtc/src/media/vp9.rs: [warning] 95-95:
empty doc comment


packages/transport_webrtc/src/transport/whep.rs: [warning] 80-80:
unused variable: cfg

Additional comments not posted (61)
packages/media_utils/src/lib.rs (2)

2-2: Ensure that the seq_extend module is correctly implemented and integrated.

Verification successful

The verification process has confirmed that the seq_extend module is correctly implemented and integrated within the media_utils package. The module is declared and its functionality (RtpSeqExtend) is made publicly available, indicating proper integration.

  • File: media_utils/src/lib.rs
    • Integration: pub use seq_extend::RtpSeqExtend; confirms that the seq_extend module's functionalities are accessible.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `seq_extend` module is correctly implemented and integrated within the `media_utils` package.

# Test: Search for the `seq_extend` module usage in other files. Expect: Matches.
rg --files-with-matches --type rust $'use .*seq_extend' | xargs cat

Length of output: 302


8-11: Public exports for RtpSeqExtend, SeqRewrite, and TsRewrite are correctly declared.

Ensure these modules are utilized appropriately in other parts of the project.

Verification successful

The verification process involves checking if the exported modules RtpSeqExtend, SeqRewrite, and TsRewrite are utilized appropriately in other parts of the project. The script output shows that these modules are indeed used in various parts of the code, particularly in the TransportWebrtc struct and related functions. This confirms that the modules are not only declared but are actively integrated and used within the project's codebase.

Given this information, the review comment stating that the public exports are correctly declared and should be checked for appropriate usage in other parts of the project is consistent with the findings from the script output. The modules are utilized effectively, which aligns with the expectations set in the review comment.

Conclusion:

  • The verification confirms that the modules RtpSeqExtend, SeqRewrite, and TsRewrite are utilized appropriately across the project.
  • The review comment is accurate as the modules are indeed integrated and used in the codebase.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the exported modules `RtpSeqExtend`, `SeqRewrite`, and `TsRewrite` are utilized appropriately in other parts of the project.

# Test: Search for usage of the exported modules in other files. Expect: Matches.
rg --files-with-matches --type rust $'use .*RtpSeqExtend|use .*SeqRewrite|use .*TsRewrite' | xargs cat

Length of output: 98251

packages/transport_webrtc/src/lib.rs (2)

1-1: Ensure that all declared modules (media, shared_port, transport, worker) are correctly implemented and integrated.


1-1: Public exports for ExtIn, ExtOut, Variant, VariantParams, GroupInput, GroupOutput, MediaWorkerWebrtc, and WebrtcOwner are correctly declared.

Ensure these modules are utilized appropriately in other parts of the project.

Verification successful

The exported entities from the transport_webrtc module (ExtIn, ExtOut, Variant, VariantParams, GroupInput, GroupOutput, MediaWorkerWebrtc, and WebrtcOwner) are utilized effectively across various parts of the project. They are integrated into core functionalities such as event handling, RPC processing, and system initialization, confirming their appropriate usage in the context of the project.

  • MediaServerWorker class: Utilizes MediaWorkerWebrtc, GroupInput, and WebrtcOwner in its methods for handling different tasks and events.
  • runtime_worker module and run_media_server function: Use ExtIn and ExtOut for handling external communications and processing.
  • Handling RPC requests: Variant and VariantParams are used to manage different types of WebRTC connections.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the exported entities in `transport_webrtc` are utilized appropriately in other parts of the project.

# Test: Search for usage of the exported entities in other files. Expect: Matches.
rg --files-with-matches --type rust $'use .*ExtIn|use .*ExtOut|use .*Variant|use .*VariantParams|use .*GroupInput|use .*GroupOutput|use .*MediaWorkerWebrtc|use .*WebrtcOwner' | xargs cat

Length of output: 18553

packages/media_core/src/endpoint/internal/local_track/packet_selector/video_single.rs (1)

6-23: The VideoSingleSelector class is correctly implemented as per the VideoSelector interface.

Ensure that the methods of VideoSingleSelector are correctly utilized in the video handling logic.

packages/transport_webrtc/src/media/h264.rs (1)

7-22: The parse_rtp function correctly handles the parsing of RTP packets for H264 video streams.

Ensure that the parse_rtp function is correctly utilized in the RTP handling logic.

Verification successful

The parse_rtp function for H264 video streams is correctly utilized in the RTP handling logic, as evidenced by its integration and usage in the media/mod.rs file. This confirms that the function is appropriately applied within the broader system.

  • Location: packages/transport_webrtc/src/media/mod.rs
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `parse_rtp` function for H264 video streams is correctly utilized in the RTP handling logic.

# Test: Search for usage of `parse_rtp` function in other files. Expect: Matches.
rg --files-with-matches --type rust $'parse_rtp.*H264' | xargs cat

Length of output: 1010



Script:

#!/bin/bash
# Description: Search for calls to the `parse_rtp` function across the codebase to verify its correct utilization in the RTP handling logic.

# Test: Search for calls to `parse_rtp` function in Rust files. Expect: Matches showing how the function is integrated and used.
rg --type rust 'parse_rtp\('

Length of output: 744

packages/transport_webrtc/src/media/bit_read.rs (1)

2-37: The BitRead trait and its implementation are correctly defined for byte buffer manipulation.

Ensure that the BitRead trait is correctly utilized in the packet handling logic.

packages/media_utils/src/seq_extend.rs (1)

22-64: The RtpSeqExtend struct and its methods are correctly implemented for extending RTP sequence numbers.

Ensure that the RtpSeqExtend methods are correctly utilized in the RTP handling logic.

packages/media_utils/src/ts_rewrite.rs (1)

8-71: The TsRewrite struct and its methods are correctly implemented for rewriting timestamps in RTP packets.

Ensure that the TsRewrite methods are correctly utilized in the RTP handling logic.

packages/transport_webrtc/src/media/vp8.rs (2)

4-99: The parse_rtp function correctly handles the parsing of RTP packets for VP8 video streams.

Ensure that the parse_rtp function is correctly utilized in the RTP handling logic.


101-136: The rewrite_rtp function for VP8 video streams is correctly implemented.

Ensure that the rewrite_rtp function is correctly utilized in the RTP handling logic.

Verification successful

The expanded search for the rewrite_rtp function usage across the Rust files in the codebase has provided a comprehensive view of how this function is integrated within the RTP handling logic. The function is indeed utilized in the context of handling VP8 video streams, as evidenced by its presence in the code snippet related to VP8 stream processing. This confirms that the function is not only defined but also actively used in the relevant parts of the system.

Given this information, the initial review comment stating that the rewrite_rtp function for VP8 video streams is correctly implemented and should be verified for correct utilization in the RTP handling logic is substantiated. The function is appropriately integrated and used within the system, aligning with the expectations set in the review.

Conclusion:

  • The rewrite_rtp function is correctly implemented and utilized within the RTP handling logic for VP8 video streams.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `rewrite_rtp` function for VP8 video streams is correctly utilized in the RTP handling logic.

# Test: Search for usage of `rewrite_rtp` function in other files. Expect: Matches.
rg --files-with-matches --type rust $'rewrite_rtp.*VP8' | xargs cat

Length of output: 68



Script:

#!/bin/bash
# Description: Broaden the search to verify the usage of the `rewrite_rtp` function in the RTP handling logic.

# Test: Search for any usage of `rewrite_rtp` function in Rust files, not limited to direct mentions of VP8.
rg --files-with-matches --type rust 'rewrite_rtp' | xargs cat

Length of output: 24114

packages/protocol/src/media.rs (1)

107-124: Ensure proper error handling or documentation for cases where target_bitrate_kbps cannot provide a stable connection as noted by the TODO comment.

Verification successful

The review comment is verified as the method select_layer does not currently handle cases where target_bitrate_kbps cannot provide a stable connection, which is noted by the TODO comment in the code. The usages of this method in various parts of the codebase do not show any handling for a None return value, which would be necessary if no suitable layer could be selected for the given bitrate. This suggests that the method and its usages need to be updated to handle such cases appropriately.

  • File: packages/protocol/src/media.rs - The method select_layer should include logic to return None when no stable connection can be provided.
  • Usages: Various files in packages/media_core/src/endpoint/internal/local_track/packet_selector/ - These usages should include checks and appropriate handling for a None return value from select_layer.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the method `select_layer` handles cases where `target_bitrate_kbps` cannot provide a stable connection.

# Search for usages of `select_layer` and ensure they handle None appropriately.
rg --type rust $'select_layer' --context 5

Length of output: 15687

packages/media_core/src/endpoint.rs (1)

6-6: Ensure that all necessary imports are included for the types used in this file.

packages/media_core/src/cluster.rs (1)

65-65: Ensure that the Media event correctly handles the additional u64 parameter.

Verification successful

The review of the Media event in the MediaCluster class shows that the additional u64 parameter is being handled correctly as per the changes in the codebase. The usage in packages/media_core/src/cluster.rs aligns with the new structure, confirming that the implementation is consistent with the intended modifications.

  • File: packages/media_core/src/cluster.rs
    • Usage: The Media event is correctly implemented with a u64 parameter followed by a MediaPacket.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `Media` event correctly handles the additional `u64` parameter.

# Search for usages of the `Media` event and verify parameter handling.
rg --type rust $'Media\\(' --context 5

Length of output: 15249

packages/media_core/src/endpoint/internal/local_track.rs (2)

26-27: Good practice to modularize functionality into separate modules. This keeps the code clean and maintainable.


50-51: Initialization of PacketSelector and TimePivot directly in the struct is clean and ensures that all necessary components are ready for use when an instance is created.

packages/transport_webrtc/src/transport.rs (4)

16-21: Introduction of RtpSeqExtend and Small2dMap is appropriate for handling RTP sequence number extensions and managing a 2D map of socket addresses, respectively.


29-29: Good encapsulation of WebRTC-specific media conversion logic within LocalMediaConvert.


79-80: Proper initialization of LocalMediaConvert and RtpSeqExtend map in the TransportWebrtc struct ensures that these components are ready for immediate use.


92-99: The configuration of RTP extensions and codec support within the Rtc builder is crucial for supporting various media types and quality adjustments.

packages/transport_webrtc/src/transport/whip.rs (8)

15-15: The addition of CodecConfig import is appropriate for handling codec configurations in the TransportWebrtcWhip struct.


20-20: The addition of RemoteMediaConvert import is necessary for media conversion functionalities that have been added to the TransportWebrtcWhip struct.


52-52: The addition of media_convert field in TransportWebrtcWhip struct is crucial for handling media conversions, aligning with the PR's objectives to enhance media handling capabilities.


64-64: Initialization of media_convert with a default value in the constructor ensures that the media conversion functionalities are ready to use immediately after the object's instantiation.


70-72: The method on_codec_config correctly sets the codec configuration for the media_convert object. This is essential for ensuring that media conversion is performed with the correct codec settings.


113-113: The handling of RequestKeyFrame event by requesting a key frame using the Str0mKeyframe output is correctly implemented. This is crucial for managing video stream quality and responsiveness.


156-164: The conversion of RTP packets using media_convert and logging detailed packet information are well-implemented. This enhances the visibility and traceability of media packet handling, which is vital for debugging and monitoring.


256-260: The conditional assignment of MediaScaling based on the presence of simulcast in the media packet is a critical enhancement for supporting scalable video coding. This allows dynamic adjustment of video quality based on network conditions and client capabilities.

packages/media_core/src/endpoint/internal/local_track/packet_selector/video_h264_sim.rs (5)

16-29: The constructor for Selector correctly calculates the target bitrate in kbps and initializes the selector with appropriate layers and target layer. This setup is crucial for the selector's functionality in choosing the correct video layer.


31-44: The method select_layer effectively updates the target layer based on the current bitrate. This dynamic adjustment is essential for responsive video quality management.


46-95: The method try_switch handles layer switching logic, including requesting key frames when necessary. This is a complex but crucial part of managing video quality and ensuring smooth transitions between layers.


97-109: The method is_allow correctly determines if a packet is allowed based on its layer, which is essential for filtering out packets that do not match the current target layer.


117-130: The select method orchestrates layer selection and packet switching, integrating the functionalities of try_switch and is_allow. This method is central to the selector's operation, ensuring that only appropriate packets are forwarded.

packages/transport_webrtc/src/media/vp9.rs (7)

8-12: The function parse_rtp correctly extracts key frame information and SVC parameters from the payload, which is essential for handling VP9 streams appropriately.


15-35: The function rewrite_rtp effectively rewrites the RTP payload to adjust the PictureID based on the SVC parameters. This is crucial for maintaining correct reference frames in video streams.


106-168: The method parse_from in Vp9Header struct comprehensively parses the VP9 RTP header, extracting various fields like picture ID, layer indices, and reference indices. This detailed parsing is vital for accurate handling of VP9 streams.


170-197: The method parse_picture_id correctly parses the Picture ID from the packet, handling both 7-bit and 15-bit IDs. This functionality is essential for tracking frame dependencies in VP9 streams.


199-207: The method parse_layer_info and its helper methods correctly extract layer information from the packet, which is crucial for layer-based encoding in VP9.


251-274: The method parse_ref_indices accurately parses reference indices from the packet, which are essential for inter-picture prediction in VP9.


276-358: The method parse_ssdata correctly parses scalability structure data from the packet, extracting information about spatial layers and their resolutions. This is crucial for handling spatial scalability in VP9 streams.

packages/media_core/src/endpoint/internal/local_track/packet_selector.rs (10)

73-85: The constructor for PacketSelector initializes various fields to their default states, preparing the selector for operation. This setup is essential for the selector's functionality.


87-96: The method on_tick handles periodic tasks such as requesting key frames if needed. This functionality is crucial for maintaining video quality and responsiveness.


98-105: The reset method correctly reinitializes the selector's state, which is necessary when the media source changes.


107-112: The method set_target_bitrate updates the target bitrate for selecting the appropriate video layer, which is essential for adaptive bitrate streaming.


114-120: The select method dispatches packet selection to the appropriate handler based on the media kind (audio or video). This separation ensures that media-specific logic is applied correctly.


122-135: The method select_audio allows all audio packets, reinitializing rewrite utilities if the audio source changes. This is appropriate for handling audio streams where all packets are typically necessary.


137-150: The method select_video handles video packet selection and rewriting, applying more complex logic than audio due to the nature of video data. This method is crucial for filtering and adjusting video packets appropriately.


152-185: The method select_video_inner contains the core logic for video packet selection, including handling source changes and key frame requests. This method is central to the video handling capabilities of the selector.


187-204: The method pop_output manages the output actions from the selector, such as requesting key frames. This method ensures that necessary actions are taken based on the selector's state and events.


207-230: The function create_selector dynamically creates the appropriate video selector based on the packet metadata. This flexibility is essential for handling different video codecs and formats.

bin/public/whip/whip.js (1)

57-60: The commented-out code for modifying the SDP offer seems important for the new SVC and Simulcast functionalities. If this is intended to be used, consider uncommenting or clarify why it's commented.

packages/media_core/src/cluster/room/channel_sub.rs (1)

196-197: The MediaMeta variant Opus is used here with an optional audio_level. Ensure that all possible None cases are handled appropriately in the consuming code to avoid runtime errors.

packages/media_utils/src/seq_rewrite.rs (1)

174-515: Comprehensive unit tests for sequence number handling.

The unit tests provided in the file comprehensively cover the functionality of the SeqRewrite struct, including edge cases and typical scenarios. This thorough testing is crucial for ensuring the reliability of sequence number handling in media streaming contexts.

packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp9_svc.rs (5)

25-28: The Ctx struct is well-defined and appropriate for its use case.


41-57: The new method is correctly implemented and effectively logs the initialization process.


59-77: The select_layer method correctly handles layer selection and logs significant changes.


171-209: The is_allow method is well-implemented, effectively handling packet permissions based on layer conditions.


225-232: The select method effectively integrates layer selection, switching, and packet allowance checks.

packages/media_core/src/endpoint/internal/local_track/packet_selector/video_vp8_sim.rs (3)

21-25: Struct Ctx is well-defined and uses appropriate types for its fields.


35-49: Method new correctly initializes the Selector with appropriate logging.


225-473: The unit tests are comprehensive and effectively validate the functionality of the Selector.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@giangndm giangndm force-pushed the feat-svc-simulcast branch from 5bad59e to d6e35b1 Compare May 1, 2024 18:35
Copy link

@github-advanced-security github-advanced-security bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clippy found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

Copy link

codecov bot commented May 2, 2024

Codecov Report

Attention: Patch coverage is 68.86712% with 731 lines in your changes are missing coverage. Please review.

Project coverage is 51.22%. Comparing base (c42e37b) to head (dfd9c12).

Files Patch % Lines
packages/transport_webrtc/src/media/vp9.rs 0.00% 200 Missing ⚠️
packages/transport_webrtc/src/media/mod.rs 0.00% 131 Missing ⚠️
packages/transport_webrtc/src/media/vp8.rs 0.00% 114 Missing ⚠️
packages/protocol/src/media.rs 36.95% 58 Missing ⚠️
...es/media_core/src/endpoint/internal/local_track.rs 0.00% 36 Missing ⚠️
packages/transport_webrtc/src/transport.rs 0.00% 31 Missing ⚠️
...ernal/local_track/packet_selector/video_vp9_svc.rs 91.64% 29 Missing ⚠️
...c/endpoint/internal/local_track/packet_selector.rs 85.24% 27 Missing ⚠️
...ernal/local_track/packet_selector/video_vp8_sim.rs 93.64% 22 Missing ⚠️
...rnal/local_track/packet_selector/video_h264_sim.rs 90.62% 18 Missing ⚠️
... and 9 more
Additional details and impacted files
@@             Coverage Diff             @@
##           master     #266       +/-   ##
===========================================
+ Coverage   38.81%   51.22%   +12.40%     
===========================================
  Files          41       53       +12     
  Lines        3506     5808     +2302     
===========================================
+ Hits         1361     2975     +1614     
- Misses       2145     2833      +688     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@giangndm giangndm marked this pull request as ready for review May 2, 2024 16:51
@giangndm giangndm merged commit 6279d12 into 8xFF:master May 2, 2024
10 checks passed
@github-actions github-actions bot mentioned this pull request May 2, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 26

Out of diff range and nitpick comments (5)
packages/media_core/src/cluster/room/channel_pub.rs (2)

81-81: Ensure that the logging statement provides all necessary information for debugging.

Consider adding more context to the log message, such as the media type or any other relevant metadata.


Line range hint 102-119: Consider adding assertions to verify the correctness of the media packet handling in the test cases.

Would you like me to help by adding more comprehensive assertions to these tests?

packages/media_core/src/endpoint/internal/local_track.rs (1)

22-23: Consider adding a brief comment explaining the purpose of packet_selector::PacketSelector.

bin/public/whip/whip.js (2)

1-1: Consider removing the commented-out import if it's no longer needed.


176-177: The method trickle is scheduled to run immediately after setting the local description. Consider adding a comment explaining why this is necessary, as it might not be immediately clear to other developers.

/// Mark the input as dropped.
pub fn drop_value(&mut self, input: u64) {
log::trace!("drop value {input}");
assert!(input < MAX, "{} should < MAX {}", input, MAX);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider handling sequence number assertions more gracefully.

Using assert! to enforce sequence number constraints (input < MAX) might cause the program to panic, which is not ideal in production environments. Consider replacing assertions with error handling to gracefully manage unexpected values.

/// Add more offset to base.
pub fn offset(&mut self, offset: u64) {
if self.reinit {
self.reinit_offset = Some(self.reinit_offset.unwrap_or(0) + offset);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potential risk in using unwrap_or without validation.

The use of unwrap_or(0) in the offset method assumes that reinit_offset is always valid when reinit is true. This could lead to incorrect behavior if reinit_offset is None unexpectedly. Consider adding checks or default handling before this operation.

Comment on lines +61 to +62
selector: PacketSelector::new(kind),
timer: TimePivot::build(),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The constructor correctly initializes the PacketSelector and TimePivot. However, these lines are not covered by tests.

Please ensure that unit tests cover the initialization logic in the constructor to verify that the components are set up correctly.

Comment on lines +83 to +95
fn on_cluster_event(&mut self, now: Instant, event: ClusterLocalTrackEvent) -> Option<Output> {
match event {
ClusterLocalTrackEvent::Started => todo!(),
ClusterLocalTrackEvent::SourceChanged => {
let room = self.room.as_ref()?;
log::info!("[EndpointLocalTrack] source changed => request key-frame and reset seq, ts rewrite");
Some(Output::Cluster(*room, ClusterLocalTrackControl::RequestKeyFrame))
}
ClusterLocalTrackEvent::Media(pkt) => {
log::trace!("[EndpointLocalTrack] on media payload {} seq {}", pkt.pt, pkt.seq);
ClusterLocalTrackEvent::Media(channel, mut pkt) => {
log::trace!("[EndpointLocalTrack] on media payload {:?} seq {}", pkt.meta, pkt.seq);
let now_ms = self.timer.timestamp_ms(now);
self.selector.select(self.timer.timestamp_ms(now), channel, &mut pkt)?;
self.pop_selector(now_ms);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handling of ClusterLocalTrackEvent::Media is crucial for media packet processing. However, this block is not covered by tests.

It's important to add tests for this event handling to ensure that media packets are processed correctly, especially since this involves timestamp adjustments and packet selection which are critical operations.

Comment on lines +126 to +127
self.queue.push_back(Output::Cluster(*room, ClusterLocalTrackControl::Subscribe(peer, track)));
self.selector.reset();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resetting the selector and handling subscription logic in the RPC request is a good separation of concerns. However, these lines are not covered by tests.

Consider adding unit tests for these operations to ensure that the state transitions and selector resets are handled correctly.

}
}

pub fn rewrite_rtp(payload: &mut [u8], sim: &H264Sim) {}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rewrite_rtp function has unused variables payload and sim, which should either be used or removed to clean up the code.

- pub fn rewrite_rtp(payload: &mut [u8], sim: &H264Sim) {}
+ pub fn rewrite_rtp(_payload: &mut [u8], _sim: &H264Sim) {}

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn rewrite_rtp(payload: &mut [u8], sim: &H264Sim) {}
pub fn rewrite_rtp(_payload: &mut [u8], _sim: &H264Sim) {}

Comment on lines +51 to +64
pub fn number_temporals(&self) -> u8 {
if self.0[0].is_none() {
return 0;
}

if self.0[1].is_none() {
return 1;
}

if self.0[2].is_none() {
return 2;
}

return 3;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method number_temporals can be simplified by removing the explicit return statements.

-        return 0;
+        0
-        return 1;
+        1
-        return 2;
+        2
-        return 3;
+        3

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn number_temporals(&self) -> u8 {
if self.0[0].is_none() {
return 0;
}
if self.0[1].is_none() {
return 1;
}
if self.0[2].is_none() {
return 2;
}
return 3;
pub fn number_temporals(&self) -> u8 {
if self.0[0].is_none() {
0
} else if self.0[1].is_none() {
1
} else if self.0[2].is_none() {
2
} else {
3
}

return 2;
}

return 3;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method number_layers can be simplified by removing the explicit return statement.

-        return 3;
+        3

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
return 3;
3

Comment on lines +101 to +112
RemoteTrackEvent::Media(mut media) => {
//TODO clear self.last_layer if switched to new track
if media.layers.is_some() {
log::info!("[EndpointRemoteTrack] on layers info {:?}", media.layers);
self.last_layers = media.layers.clone();
}

// We restore last_layer if key frame not contain for allow consumers fast switching
if media.meta.is_video_key() && media.layers.is_none() {
log::info!("[EndpointRemoteTrack] set layers info to key-frame {:?}", media.layers);
media.layers = self.last_layers.clone();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the cloning of last_layers by using a reference instead of cloning the entire structure.

-                    self.last_layers = media.layers.clone();
+                    self.last_layers = Some(&media.layers);
-                    media.layers = self.last_layers.clone();
+                    media.layers = self.last_layers.as_ref().cloned();

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
RemoteTrackEvent::Media(mut media) => {
//TODO clear self.last_layer if switched to new track
if media.layers.is_some() {
log::info!("[EndpointRemoteTrack] on layers info {:?}", media.layers);
self.last_layers = media.layers.clone();
}
// We restore last_layer if key frame not contain for allow consumers fast switching
if media.meta.is_video_key() && media.layers.is_none() {
log::info!("[EndpointRemoteTrack] set layers info to key-frame {:?}", media.layers);
media.layers = self.last_layers.clone();
}
RemoteTrackEvent::Media(mut media) => {
//TODO clear self.last_layer if switched to new track
if media.layers.is_some() {
log::info!("[EndpointRemoteTrack] on layers info {:?}", media.layers);
self.last_layers = Some(&media.layers);
}
// We restore last_layer if key frame not contain for allow consumers fast switching
if media.meta.is_video_key() && media.layers.is_none() {
log::info!("[EndpointRemoteTrack] set layers info to key-frame {:?}", media.layers);
media.layers = self.last_layers.as_ref().cloned();
}

Comment on lines +51 to +61
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_simulcast).flatten();
let meta = h264::parse_rtp(&rtp.payload, profile, spatial)?;
(true, layers, meta)
}
MediaCodec::Vp8 => {
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_simulcast).flatten();
let meta = vp8::parse_rtp(&rtp.payload, spatial)?;
(true, layers, meta)
}
MediaCodec::Vp9(profile) => {
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_svc).flatten();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify the calls to map and flatten by using and_then instead.

-                let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_simulcast).flatten();
+                let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().and_then(extract_simulcast);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_simulcast).flatten();
let meta = h264::parse_rtp(&rtp.payload, profile, spatial)?;
(true, layers, meta)
}
MediaCodec::Vp8 => {
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_simulcast).flatten();
let meta = vp8::parse_rtp(&rtp.payload, spatial)?;
(true, layers, meta)
}
MediaCodec::Vp9(profile) => {
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_svc).flatten();
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().and_then(extract_simulcast);
let meta = h264::parse_rtp(&rtp.payload, profile, spatial)?;
(true, layers, meta)
}
MediaCodec::Vp8 => {
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().and_then(extract_simulcast);
let meta = vp8::parse_rtp(&rtp.payload, spatial)?;
(true, layers, meta)
}
MediaCodec::Vp9(profile) => {
let layers = rtp.header.ext_vals.user_values.get::<VideoLayersAllocation>().map(extract_svc).flatten();

@giangndm giangndm deleted the feat-svc-simulcast branch June 6, 2024 00:43
giangndm added a commit to giangndm/8xFF-decentralized-media-server that referenced this pull request Nov 26, 2024
* WIP: working with seq, ts rewrite.

* WIP: working with single video stream

* WIP: allow working with vp8 simulcast

* WIP: allow re-enable vp8 egress with vp8 short-term memory

* test: add vp8 sim test, packet selector test

* feat: h264 simulcast

* feat: vp9 svc
This was referenced Feb 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant