Deduplicate codecs matched by codec preferences

RtpTransceiver::SetCodecPreferences removes exact duplicates, so a codec
that is sent and received at different levels stays listed twice when an
application passes both its sender and its receiver capabilities.
MatchCodecPreference ignores levels when matching preferences against
supported codecs, which made both entries resolve to the same codec and
append its payload type (and any associated RTX codec) twice. Since
CodecVendor started finalizing offered and answered codec lists, the
duplicate payload type fails offer and answer creation.

Add matched codecs with CodecList::PushIfNotPresent in
MatchCodecPreference so that each codec and its associated RTX codec
appear at most once.

Fixed: chromium:585451900
Change-Id: I3354931ad9bfe0faab2418adac453e1088b7103b
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/517180
Commit-Queue: Tomas Gunnarsson <tommi@webrtc.org>
Reviewed-by: Henrik Boström <hbos@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#49302}
diff --git a/pc/codec_vendor.cc b/pc/codec_vendor.cc
index f0180dd..941f39e 100644
--- a/pc/codec_vendor.cc
+++ b/pc/codec_vendor.cc
@@ -637,6 +637,16 @@
     const CodecList& supported_codecs) {
   RTC_DCHECK_DISALLOW_THREAD_BLOCKING_CALLS();
   CodecList filtered_codecs;
+  // Adds `codec` unless it is in the list already. A preference matches a codec
+  // regardless of its level, so several preferences can match the same codec:
+  // an application that passes both its sender and its receiver capabilities
+  // lists a codec twice if it is sent and received at different levels.
+  auto add_codec = [&filtered_codecs](const Codec& codec) {
+    CodecList::PushResult result = filtered_codecs.PushIfNotPresent(codec);
+    // All the codecs come from `codecs`, where a payload type identifies one
+    // codec.
+    RTC_DCHECK_NE(result, CodecList::PushResult::kConflict);
+  };
   bool want_rtx = false;
   bool want_red = false;
 
@@ -667,7 +677,7 @@
         bool is_red_codec = found_codec_with_correct_pt->GetResiliencyType() ==
                             Codec::ResiliencyType::kRed;
         if (!is_red_codec || !red_was_added) {
-          filtered_codecs.push_back(*found_codec_with_correct_pt);
+          add_codec(*found_codec_with_correct_pt);
           red_was_added = is_red_codec ? true : red_was_added;
         }
         PayloadType id = found_codec_with_correct_pt->id;
@@ -679,7 +689,7 @@
               int apt;
               if (codec.GetParam(kCodecParamAssociatedPayloadType, &apt) &&
                   apt == id.value()) {
-                filtered_codecs.push_back(codec);
+                add_codec(codec);
                 break;
               }
             } else if (want_red && codec.GetResiliencyType() ==
@@ -697,7 +707,7 @@
                     FromString(redundant_payloads[0], &first_redundant_pt) &&
                     first_redundant_pt == id.value()) {
                   if (!red_was_added) {
-                    filtered_codecs.push_back(codec);
+                    add_codec(codec);
                     red_was_added = true;
                   }
                   break;
diff --git a/pc/peer_connection_media_unittest.cc b/pc/peer_connection_media_unittest.cc
index 5286998..424b897 100644
--- a/pc/peer_connection_media_unittest.cc
+++ b/pc/peer_connection_media_unittest.cc
@@ -2143,6 +2143,59 @@
       GetFirstVideoContentDescription(reoffer->description())->codecs().size());
 }
 
+// A codec that is sent and received at different levels is listed twice, with
+// entries that only differ in level, when an application passes both its
+// sender and its receiver capabilities to setCodecPreferences(). Both entries
+// match the codec, which must end up in the offer and in the answer once.
+TEST_F(PeerConnectionMediaTestUnifiedPlan,
+       SetCodecPreferencesWithSendAndReceiveLevelsOfCodec) {
+  // H264 Constrained Baseline, sent at level 3.1 and received at level 5.2.
+  Codec h264_send = CreateVideoCodec(100, kH264CodecName);
+  h264_send.SetParam(kH264FmtpProfileLevelId, "42e01f");
+  h264_send.SetParam(kH264FmtpPacketizationMode, "1");
+  Codec h264_recv = h264_send;
+  h264_recv.SetParam(kH264FmtpProfileLevelId, "42e034");
+  const Codec rtx = CreateVideoRtxCodec(101, 100);
+  auto make_engine = [&] {
+    auto engine = std::make_unique<FakeMediaEngine>();
+    engine->SetVideoSendCodecs({h264_send, rtx});
+    engine->SetVideoRecvCodecs({h264_recv, rtx});
+    return engine;
+  };
+  auto caller = CreatePeerConnectionWithVideo(make_engine());
+  auto callee = CreatePeerConnectionWithVideo(make_engine());
+
+  std::vector<RtpCodecCapability> preferences =
+      caller->pc_factory()->GetRtpSenderCapabilities(MediaType::VIDEO).codecs;
+  const std::vector<RtpCodecCapability> receiver_codecs =
+      caller->pc_factory()->GetRtpReceiverCapabilities(MediaType::VIDEO).codecs;
+  preferences.insert(preferences.end(), receiver_codecs.begin(),
+                     receiver_codecs.end());
+  // H264 at level 3.1, RTX, H264 at level 5.2 and RTX.
+  ASSERT_EQ(preferences.size(), 4u);
+  const auto h264_and_rtx =
+      ElementsAre(Field(&Codec::name, StrCaseEq(kH264CodecName)),
+                  Field(&Codec::name, StrCaseEq(kRtxCodecName)));
+
+  EXPECT_THAT(
+      caller->pc()->GetTransceivers()[0]->SetCodecPreferences(preferences),
+      IsRtcOk());
+  std::unique_ptr<SessionDescriptionInterface> offer =
+      caller->CreateOfferAndSetAsLocal();
+  ASSERT_THAT(offer, NotNull());
+  EXPECT_THAT(GetFirstVideoContentDescription(offer->description())->codecs(),
+              h264_and_rtx);
+
+  ASSERT_TRUE(callee->SetRemoteDescription(std::move(offer)));
+  EXPECT_THAT(
+      callee->pc()->GetTransceivers()[0]->SetCodecPreferences(preferences),
+      IsRtcOk());
+  std::unique_ptr<SessionDescriptionInterface> answer = callee->CreateAnswer();
+  ASSERT_THAT(answer, NotNull());
+  EXPECT_THAT(GetFirstVideoContentDescription(answer->description())->codecs(),
+              h264_and_rtx);
+}
+
 TEST_F(PeerConnectionMediaTestUnifiedPlan,
        SetCodecPreferencesRecvOnlyCodecOnSendOnlyTransceiver) {
   auto fake_engine = std::make_unique<FakeMediaEngine>();