Replace RtpDemuxerCriteria member with discrete variables

Instead of keeping an RtpDemuxerCriteria object as a member, replace it
with distinct member variables (mid_, payload_types_, ssrcs_) inside
BaseChannel. The RtpDemuxerCriteria object is now constructed on the
stack, on the network thread, when needed (a step that clarifies the
intended threading slightly).

This disentangles the mid, which is const and must be readable from the
worker and network threads, from other demuxer properties. The channel
implementations also only use the ssrcs and payload_types properties of
the RtpDemuxerCriteria, don't need the full object and now there is not
a duplicate copy of payload_types_.

Those changes unlock the ability to further move parts of the channel
implementation over to the network thread and get rid of some of the
thread hopping.

Some more work needs to be done to fully move the demuxer state to the
network thread however.

Bug: webrtc:42222117
Change-Id: I42f8861c0ed04a8d19656edba7f0053142f07b06
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/456060
Reviewed-by: Henrik Boström <hbos@webrtc.org>
Commit-Queue: Tomas Gunnarsson <tommi@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#47144}
diff --git a/pc/channel.cc b/pc/channel.cc
index 2c39a40..a3f4f40 100644
--- a/pc/channel.cc
+++ b/pc/channel.cc
@@ -31,6 +31,7 @@
 #include "api/sequence_checker.h"
 #include "api/task_queue/pending_task_safety_flag.h"
 #include "api/task_queue/task_queue_base.h"
+#include "call/rtp_demuxer.h"
 #include "media/base/codec.h"
 #include "media/base/media_channel.h"
 #include "media/base/rid_description.h"
@@ -192,7 +193,7 @@
           crypto_options.srtp.enable_encrypted_rtp_header_extensions
               ? RtpExtension::kPreferEncryptedExtension
               : RtpExtension::kDiscardEncryptedExtension),
-      demuxer_criteria_(mid),
+      mid_(std::string(mid)),
       ssrc_generator_(ssrc_generator) {
   RTC_DCHECK_RUN_ON(worker_thread_);
   RTC_DCHECK(media_send_channel_);
@@ -225,7 +226,8 @@
 
   // We don't need to call OnDemuxerCriteriaUpdatePending/Complete because
   // there's no previous criteria to worry about.
-  if (!rtp_transport->RegisterRtpDemuxerSink(demuxer_criteria_, this)) {
+  RtpDemuxerCriteria criteria = demuxer_criteria();
+  if (!rtp_transport->RegisterRtpDemuxerSink(criteria, this)) {
     return false;
   }
   rtp_transport_ = rtp_transport;
@@ -578,10 +580,11 @@
 
   // TODO(bugs.webrtc.org/13536): See if we can do this asynchronously.
 
-  if (update_demuxer)
+  if (update_demuxer) {
     media_receive_channel()->OnDemuxerCriteriaUpdatePending();
+  }
 
-  bool success = network_thread()->BlockingCall([&]() mutable {
+  bool success = network_thread()->BlockingCall([&] {
     RTC_DCHECK_RUN_ON(network_thread());
     if (!rtp_transport_) {
       // To repro this situation, run the
@@ -597,10 +600,11 @@
     if (!update_demuxer)
       return true;
 
-    if (!rtp_transport_->RegisterRtpDemuxerSink(demuxer_criteria_, this)) {
+    RtpDemuxerCriteria criteria = demuxer_criteria();
+    if (!rtp_transport_->RegisterRtpDemuxerSink(criteria, this)) {
       error_desc =
           StringFormat("Failed to apply demuxer criteria for '%s': '%s'.",
-                       mid().c_str(), demuxer_criteria_.ToString().c_str());
+                       mid().c_str(), criteria.ToString().c_str());
       return false;
     }
     return true;
@@ -614,28 +618,36 @@
 
 bool BaseChannel::RegisterRtpDemuxerSink_w() {
   media_receive_channel()->OnDemuxerCriteriaUpdatePending();
-  // Copy demuxer criteria, since they're a worker-thread variable
-  // and we want to pass them to the network thread
-  bool ret = network_thread_->BlockingCall(
-      [this, demuxer_criteria = demuxer_criteria_] {
-        RTC_DCHECK_RUN_ON(network_thread());
-        if (!rtp_transport_) {
-          // Transport was disconnected before attempting to update the
-          // criteria. This can happen while setting the remote description.
-          // See chromium:1295469 for an example.
-          return false;
-        }
-        // Note that RegisterRtpDemuxerSink first unregisters the sink if
-        // already registered. So this will change the state of the class
-        // whether the call succeeds or not.
-        return rtp_transport_->RegisterRtpDemuxerSink(demuxer_criteria, this);
-      });
+  bool ret = network_thread_->BlockingCall([&] {
+    RTC_DCHECK_RUN_ON(network_thread());
+    if (!rtp_transport_) {
+      // Transport was disconnected before attempting to update the
+      // criteria. This can happen while setting the remote description.
+      // See chromium:1295469 for an example.
+      return false;
+    }
+    // Note that RegisterRtpDemuxerSink first unregisters the sink if
+    // already registered. So this will change the state of the class
+    // whether the call succeeds or not.
+    RtpDemuxerCriteria criteria = demuxer_criteria();
+    return rtp_transport_->RegisterRtpDemuxerSink(criteria, this);
+  });
 
   media_receive_channel()->OnDemuxerCriteriaUpdateComplete();
 
   return ret;
 }
 
+RtpDemuxerCriteria BaseChannel::demuxer_criteria() const {
+  RTC_DCHECK_RUN_ON(network_thread());
+  RtpDemuxerCriteria criteria(mid_);
+  if (payload_type_demuxing_enabled_) {
+    criteria.payload_types() = payload_types_;
+  }
+  criteria.ssrcs() = ssrcs_;
+  return criteria;
+}
+
 void BaseChannel::EnableMedia_w() {
   if (enabled_)
     return;
@@ -702,8 +714,6 @@
 
   payload_type_demuxing_enabled_ = enabled;
 
-  bool config_changed = false;
-
   if (!enabled) {
     // TODO(crbug.com/11477): This will remove *all* unsignaled streams (those
     // without an explicitly signaled SSRC), which may include streams that
@@ -711,27 +721,16 @@
     // streams that were matched based on payload type alone, but currently
     // there is no straightforward way to identify those streams.
     media_receive_channel()->ResetUnsignaledRecvStream();
-    if (!demuxer_criteria_.payload_types().empty()) {
-      config_changed = true;
-      demuxer_criteria_.payload_types().clear();
+    if (!payload_types_.empty()) {
+      return RegisterRtpDemuxerSink_w();
     }
   } else if (!payload_types_.empty()) {
-    for (const auto& type : payload_types_) {
-      if (demuxer_criteria_.payload_types().insert(type).second) {
-        config_changed = true;
-      }
-    }
-  } else {
-    RTC_DCHECK(demuxer_criteria_.payload_types().empty());
+    return RegisterRtpDemuxerSink_w();
   }
 
   RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0);
 
-  if (!config_changed)
-    return true;
-
-  // Note: This synchronously hops to the network thread.
-  return RegisterRtpDemuxerSink_w();
+  return true;
 }
 
 bool BaseChannel::UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
@@ -881,8 +880,8 @@
     ssrcs.insert(new_stream.ssrcs.begin(), new_stream.ssrcs.end());
   }
 
-  if (demuxer_criteria_.ssrcs() != ssrcs) {
-    demuxer_criteria_.ssrcs() = std::move(ssrcs);
+  if (ssrcs_ != ssrcs) {
+    ssrcs_ = std::move(ssrcs);
     needs_re_registration = true;
   }
 
@@ -912,23 +911,17 @@
 }
 
 bool BaseChannel::MaybeAddHandledPayloadType(int payload_type) {
-  bool demuxer_criteria_modified = false;
-  if (payload_type_demuxing_enabled_) {
-    demuxer_criteria_modified = demuxer_criteria_.payload_types()
-                                    .insert(static_cast<uint8_t>(payload_type))
-                                    .second;
-  }
   // Even if payload type demuxing is currently disabled, we need to remember
   // the payload types in case it's re-enabled later.
-  payload_types_.insert(static_cast<uint8_t>(payload_type));
-  return demuxer_criteria_modified;
+  bool inserted =
+      payload_types_.insert(static_cast<uint8_t>(payload_type)).second;
+  return inserted && payload_type_demuxing_enabled_;
 }
 
 bool BaseChannel::ClearHandledPayloadTypes() {
-  const bool was_empty = demuxer_criteria_.payload_types().empty();
-  demuxer_criteria_.payload_types().clear();
+  const bool was_empty = payload_types_.empty();
   payload_types_.clear();
-  return !was_empty;
+  return !was_empty && payload_type_demuxing_enabled_;
 }
 
 bool BaseChannel::CheckRtpExtensionValidity(
@@ -1066,6 +1059,7 @@
 
   if (type == SdpType::kAnswer || type == SdpType::kPrAnswer) {
     AudioSenderParameter send_params = last_send_params_;
+    RTC_DCHECK(!send_params.mid.empty());
     send_params.extensions = header_extensions;
     send_params.extmap_allow_mixed = content->extmap_allow_mixed();
     if (!media_send_channel()->SetSenderParameters(send_params)) {
diff --git a/pc/channel.h b/pc/channel.h
index d651d06..8a30c46 100644
--- a/pc/channel.h
+++ b/pc/channel.h
@@ -95,7 +95,7 @@
 
   TaskQueueBase* worker_thread() const { return worker_thread_; }
   Thread* network_thread() const { return network_thread_; }
-  const std::string& mid() const override { return demuxer_criteria_.mid(); }
+  const std::string& mid() const override { return mid_; }
   // TODO(deadbeef): This is redundant; remove this.
   absl::string_view transport_name() const override {
     RTC_DCHECK_RUN_ON(network_thread());
@@ -306,6 +306,9 @@
       const RtpHeaderExtensions& extensions,
       std::string& error_desc) RTC_RUN_ON(worker_thread());
 
+  // Registers a demuxer criteria with the transport, on the network thread.
+  // This function will fail if there's no transport of if a sink is already
+  // registered for this channel's demuxer_critera().
   bool RegisterRtpDemuxerSink_w() RTC_RUN_ON(worker_thread());
 
   // Return description of media channel to facilitate logging
@@ -319,6 +322,11 @@
       RTC_RUN_ON(network_thread());
   void DisconnectFromRtpTransport_n() RTC_RUN_ON(network_thread());
   void SignalSentPacket_n(const SentPacketInfo& sent_packet);
+  // Only called on the network thread, so should be marked as
+  // `RTC_RUN_ON(network_thread());` but currently accesses variables
+  // that are associated with the worker thread. Those operations are
+  // done in a synchronous way, so they're safe, but not ideal.
+  RtpDemuxerCriteria demuxer_criteria() const RTC_NO_THREAD_SAFETY_ANALYSIS;
 
   TaskQueueBase* const worker_thread_;
   Thread* const network_thread_;
@@ -374,9 +382,8 @@
   RtpHeaderExtensions historical_rtp_header_extensions_
       RTC_GUARDED_BY(worker_thread());
 
-  // TODO(bugs.webrtc.org/12239): Modified on worker thread, accessed
-  // on network thread in RegisterRtpDemuxerSink_n (called from Init_w)
-  RtpDemuxerCriteria demuxer_criteria_;
+  const std::string mid_;
+  flat_set<uint32_t> ssrcs_ RTC_GUARDED_BY(worker_thread());
   // This generator is used to generate SSRCs for local streams.
   // This is needed in cases where SSRCs are not negotiated or set explicitly
   // like in Simulcast.