Update pc/ to use C++ lambdas instead of rtc::Bind

(and a subclass of QueuedTask in one place, where needed for move
semantics).

Bug: webrtc:11339
Change-Id: I109de41a8753f177db1bbb8d21b6744eb3ad2de0
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/201734
Commit-Queue: Niels Moller <nisse@webrtc.org>
Reviewed-by: Steve Anton <steveanton@webrtc.org>
Reviewed-by: Henrik Boström <hbos@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#33021}
diff --git a/pc/channel.cc b/pc/channel.cc
index 98a8f9d..ff983d1 100644
--- a/pc/channel.cc
+++ b/pc/channel.cc
@@ -22,7 +22,6 @@
 #include "p2p/base/packet_transport_internal.h"
 #include "pc/channel_manager.h"
 #include "pc/rtp_media_utils.h"
-#include "rtc_base/bind.h"
 #include "rtc_base/byte_order.h"
 #include "rtc_base/checks.h"
 #include "rtc_base/copy_on_write_buffer.h"
@@ -39,7 +38,6 @@
 namespace cricket {
 namespace {
 
-using ::rtc::Bind;
 using ::rtc::UniqueRandomIdGenerator;
 using ::webrtc::PendingTaskSafetyFlag;
 using ::webrtc::SdpType;
@@ -273,10 +271,14 @@
 }
 
 bool BaseChannel::Enable(bool enable) {
-  worker_thread_->Invoke<void>(
-      RTC_FROM_HERE,
-      Bind(enable ? &BaseChannel::EnableMedia_w : &BaseChannel::DisableMedia_w,
-           this));
+  worker_thread_->Invoke<void>(RTC_FROM_HERE, [this, enable] {
+    RTC_DCHECK_RUN_ON(worker_thread());
+    if (enable) {
+      EnableMedia_w();
+    } else {
+      DisableMedia_w();
+    }
+  });
   return true;
 }
 
@@ -284,25 +286,26 @@
                                   SdpType type,
                                   std::string* error_desc) {
   TRACE_EVENT0("webrtc", "BaseChannel::SetLocalContent");
-  return InvokeOnWorker<bool>(
-      RTC_FROM_HERE,
-      Bind(&BaseChannel::SetLocalContent_w, this, content, type, error_desc));
+  return InvokeOnWorker<bool>(RTC_FROM_HERE, [this, content, type, error_desc] {
+    return SetLocalContent_w(content, type, error_desc);
+  });
 }
 
 bool BaseChannel::SetRemoteContent(const MediaContentDescription* content,
                                    SdpType type,
                                    std::string* error_desc) {
   TRACE_EVENT0("webrtc", "BaseChannel::SetRemoteContent");
-  return InvokeOnWorker<bool>(
-      RTC_FROM_HERE,
-      Bind(&BaseChannel::SetRemoteContent_w, this, content, type, error_desc));
+  return InvokeOnWorker<bool>(RTC_FROM_HERE, [this, content, type, error_desc] {
+    return SetRemoteContent_w(content, type, error_desc);
+  });
 }
 
 void BaseChannel::SetPayloadTypeDemuxingEnabled(bool enabled) {
   TRACE_EVENT0("webrtc", "BaseChannel::SetPayloadTypeDemuxingEnabled");
-  InvokeOnWorker<void>(
-      RTC_FROM_HERE,
-      Bind(&BaseChannel::SetPayloadTypeDemuxingEnabled_w, this, enabled));
+  InvokeOnWorker<void>(RTC_FROM_HERE, [this, enabled] {
+    RTC_DCHECK_RUN_ON(worker_thread());
+    SetPayloadTypeDemuxingEnabled_w(enabled);
+  });
 }
 
 bool BaseChannel::UpdateRtpTransport(std::string* error_desc) {
@@ -362,8 +365,10 @@
 int BaseChannel::SetOption(SocketType type,
                            rtc::Socket::Option opt,
                            int value) {
-  return network_thread_->Invoke<int>(
-      RTC_FROM_HERE, Bind(&BaseChannel::SetOption_n, this, type, opt, value));
+  return network_thread_->Invoke<int>(RTC_FROM_HERE, [this, type, opt, value] {
+    RTC_DCHECK_RUN_ON(network_thread());
+    return SetOption_n(type, opt, value);
+  });
 }
 
 int BaseChannel::SetOption_n(SocketType type,
@@ -1062,8 +1067,9 @@
 }
 
 void VideoChannel::FillBitrateInfo(BandwidthEstimationInfo* bwe_info) {
-  InvokeOnWorker<void>(RTC_FROM_HERE, Bind(&VideoMediaChannel::FillBitrateInfo,
-                                           media_channel(), bwe_info));
+  VideoMediaChannel* mc = media_channel();
+  InvokeOnWorker<void>(RTC_FROM_HERE,
+                       [mc, bwe_info] { mc->FillBitrateInfo(bwe_info); });
 }
 
 bool VideoChannel::SetLocalContent_w(const MediaContentDescription* content,
@@ -1292,9 +1298,10 @@
 bool RtpDataChannel::SendData(const SendDataParams& params,
                               const rtc::CopyOnWriteBuffer& payload,
                               SendDataResult* result) {
-  return InvokeOnWorker<bool>(
-      RTC_FROM_HERE, Bind(&DataMediaChannel::SendData, media_channel(), params,
-                          payload, result));
+  DataMediaChannel* mc = media_channel();
+  return InvokeOnWorker<bool>(RTC_FROM_HERE, [mc, &params, &payload, result] {
+    return mc->SendData(params, payload, result);
+  });
 }
 
 bool RtpDataChannel::CheckDataChannelTypeFromContent(
diff --git a/pc/jsep_transport_controller.cc b/pc/jsep_transport_controller.cc
index 4999f2a..b7ab279 100644
--- a/pc/jsep_transport_controller.cc
+++ b/pc/jsep_transport_controller.cc
@@ -18,7 +18,6 @@
 #include "p2p/base/ice_transport_internal.h"
 #include "p2p/base/port.h"
 #include "pc/srtp_filter.h"
-#include "rtc_base/bind.h"
 #include "rtc_base/checks.h"
 #include "rtc_base/thread.h"
 
@@ -93,9 +92,8 @@
 JsepTransportController::~JsepTransportController() {
   // Channel destructors may try to send packets, so this needs to happen on
   // the network thread.
-  network_thread_->Invoke<void>(
-      RTC_FROM_HERE,
-      rtc::Bind(&JsepTransportController::DestroyAllJsepTransports_n, this));
+  network_thread_->Invoke<void>(RTC_FROM_HERE,
+                                [this] { DestroyAllJsepTransports_n(); });
 }
 
 RTCError JsepTransportController::SetLocalDescription(
diff --git a/pc/peer_connection.cc b/pc/peer_connection.cc
index 9ba7dae..eb68a5b 100644
--- a/pc/peer_connection.cc
+++ b/pc/peer_connection.cc
@@ -45,7 +45,6 @@
 #include "pc/sctp_transport.h"
 #include "pc/simulcast_description.h"
 #include "pc/webrtc_session_description_factory.h"
-#include "rtc_base/bind.h"
 #include "rtc_base/helpers.h"
 #include "rtc_base/ip_address.h"
 #include "rtc_base/location.h"
@@ -529,9 +528,10 @@
   // there.
   const auto pa_result =
       network_thread()->Invoke<InitializePortAllocatorResult>(
-          RTC_FROM_HERE,
-          rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
-                    stun_servers, turn_servers, configuration));
+          RTC_FROM_HERE, [this, &stun_servers, &turn_servers, &configuration] {
+            return InitializePortAllocator_n(stun_servers, turn_servers,
+                                             configuration);
+          });
 
   // Note if STUN or TURN servers were supplied.
   if (!stun_servers.empty()) {
@@ -1344,16 +1344,20 @@
     NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
   }
 
+  const bool has_local_description = local_description() != nullptr;
+
   // In theory this shouldn't fail.
   if (!network_thread()->Invoke<bool>(
-          RTC_FROM_HERE,
-          rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
-                    stun_servers, turn_servers, modified_config.type,
-                    modified_config.ice_candidate_pool_size,
-                    modified_config.GetTurnPortPrunePolicy(),
-                    modified_config.turn_customizer,
-                    modified_config.stun_candidate_keepalive_interval,
-                    static_cast<bool>(local_description())))) {
+          RTC_FROM_HERE, [this, &stun_servers, &turn_servers, &modified_config,
+                          has_local_description] {
+            return ReconfigurePortAllocator_n(
+                stun_servers, turn_servers, modified_config.type,
+                modified_config.ice_candidate_pool_size,
+                modified_config.GetTurnPortPrunePolicy(),
+                modified_config.turn_customizer,
+                modified_config.stun_candidate_keepalive_interval,
+                has_local_description);
+          })) {
     LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
                          "Failed to apply configuration to PortAllocator.");
   }
@@ -1468,8 +1472,7 @@
 void PeerConnection::SetAudioPlayout(bool playout) {
   if (!worker_thread()->IsCurrent()) {
     worker_thread()->Invoke<void>(
-        RTC_FROM_HERE,
-        rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
+        RTC_FROM_HERE, [this, playout] { SetAudioPlayout(playout); });
     return;
   }
   auto audio_state =
@@ -1480,8 +1483,7 @@
 void PeerConnection::SetAudioRecording(bool recording) {
   if (!worker_thread()->IsCurrent()) {
     worker_thread()->Invoke<void>(
-        RTC_FROM_HERE,
-        rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
+        RTC_FROM_HERE, [this, recording] { SetAudioRecording(recording); });
     return;
   }
   auto audio_state =
@@ -1524,8 +1526,7 @@
 }
 
 void PeerConnection::StopRtcEventLog() {
-  worker_thread()->Invoke<void>(
-      RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
+  worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] { StopRtcEventLog_w(); });
 }
 
 rtc::scoped_refptr<DtlsTransportInterface>
@@ -1631,8 +1632,7 @@
   rtp_manager_->Close();
 
   network_thread()->Invoke<void>(
-      RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
-                               port_allocator_.get()));
+      RTC_FROM_HERE, [this] { port_allocator_->DiscardCandidatePool(); });
 
   worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
     RTC_DCHECK_RUN_ON(worker_thread());
@@ -1990,10 +1990,10 @@
 
 cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
   cricket::CandidateStatsList candidate_states_list;
-  network_thread()->Invoke<void>(
-      RTC_FROM_HERE,
-      rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
-                port_allocator_.get(), &candidate_states_list));
+  network_thread()->Invoke<void>(RTC_FROM_HERE, [this, &candidate_states_list] {
+    port_allocator_->GetCandidateStatsFromPooledSessions(
+        &candidate_states_list);
+  });
   return candidate_states_list;
 }
 
@@ -2196,7 +2196,7 @@
 Call::Stats PeerConnection::GetCallStats() {
   if (!worker_thread()->IsCurrent()) {
     return worker_thread()->Invoke<Call::Stats>(
-        RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
+        RTC_FROM_HERE, [this] { return GetCallStats(); });
   }
   RTC_DCHECK_RUN_ON(worker_thread());
   rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls;
diff --git a/pc/peer_connection_factory.cc b/pc/peer_connection_factory.cc
index f4f72c7..2529877 100644
--- a/pc/peer_connection_factory.cc
+++ b/pc/peer_connection_factory.cc
@@ -42,7 +42,6 @@
 #include "pc/rtp_parameters_conversion.h"
 #include "pc/session_description.h"
 #include "pc/video_track.h"
-#include "rtc_base/bind.h"
 #include "rtc_base/checks.h"
 #include "rtc_base/experiments/field_trial_parser.h"
 #include "rtc_base/experiments/field_trial_units.h"
@@ -256,12 +255,11 @@
 
   std::unique_ptr<RtcEventLog> event_log =
       worker_thread()->Invoke<std::unique_ptr<RtcEventLog>>(
-          RTC_FROM_HERE,
-          rtc::Bind(&PeerConnectionFactory::CreateRtcEventLog_w, this));
+          RTC_FROM_HERE, [this] { return CreateRtcEventLog_w(); });
 
   std::unique_ptr<Call> call = worker_thread()->Invoke<std::unique_ptr<Call>>(
       RTC_FROM_HERE,
-      rtc::Bind(&PeerConnectionFactory::CreateCall_w, this, event_log.get()));
+      [this, &event_log] { return CreateCall_w(event_log.get()); });
 
   auto result = PeerConnection::Create(context_, options_, std::move(event_log),
                                        std::move(call), configuration,
diff --git a/pc/peer_connection_integrationtest.cc b/pc/peer_connection_integrationtest.cc
index 16cd16f..a784126 100644
--- a/pc/peer_connection_integrationtest.cc
+++ b/pc/peer_connection_integrationtest.cc
@@ -897,8 +897,7 @@
     } else {
       invoker_.AsyncInvokeDelayed<void>(
           RTC_FROM_HERE, rtc::Thread::Current(),
-          rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
-                    this, type, msg),
+          [this, type, msg] { RelaySdpMessageIfReceiverExists(type, msg); },
           signaling_delay_ms_);
     }
   }
@@ -919,8 +918,9 @@
     } else {
       invoker_.AsyncInvokeDelayed<void>(
           RTC_FROM_HERE, rtc::Thread::Current(),
-          rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
-                    this, sdp_mid, sdp_mline_index, msg),
+          [this, sdp_mid, sdp_mline_index, msg] {
+            RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
+          },
           signaling_delay_ms_);
     }
   }
@@ -1593,12 +1593,12 @@
   }
 
   void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
-    network_thread()->Invoke<void>(
-        RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
-                                 caller()->port_allocator(), caller_flags));
-    network_thread()->Invoke<void>(
-        RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
-                                 callee()->port_allocator(), callee_flags));
+    network_thread()->Invoke<void>(RTC_FROM_HERE, [this, caller_flags] {
+      caller()->port_allocator()->set_flags(caller_flags);
+    });
+    network_thread()->Invoke<void>(RTC_FROM_HERE, [this, callee_flags] {
+      callee()->port_allocator()->set_flags(callee_flags);
+    });
   }
 
   rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
diff --git a/pc/rtc_stats_collector.cc b/pc/rtc_stats_collector.cc
index 5292008..c9a337d 100644
--- a/pc/rtc_stats_collector.cc
+++ b/pc/rtc_stats_collector.cc
@@ -1060,9 +1060,30 @@
     // reentrancy problems.
     std::vector<RequestInfo> requests;
     requests.swap(requests_);
-    signaling_thread_->PostTask(
-        RTC_FROM_HERE, rtc::Bind(&RTCStatsCollector::DeliverCachedReport, this,
-                                 cached_report_, std::move(requests)));
+
+    // Task subclass to take ownership of the requests.
+    // TODO(nisse): Delete when we can use C++14, and do lambda capture with
+    // std::move.
+    class DeliveryTask : public QueuedTask {
+     public:
+      DeliveryTask(rtc::scoped_refptr<RTCStatsCollector> collector,
+                   rtc::scoped_refptr<const RTCStatsReport> cached_report,
+                   std::vector<RequestInfo> requests)
+          : collector_(collector),
+            cached_report_(cached_report),
+            requests_(std::move(requests)) {}
+      bool Run() override {
+        collector_->DeliverCachedReport(cached_report_, std::move(requests_));
+        return true;
+      }
+
+     private:
+      rtc::scoped_refptr<RTCStatsCollector> collector_;
+      rtc::scoped_refptr<const RTCStatsReport> cached_report_;
+      std::vector<RequestInfo> requests_;
+    };
+    signaling_thread_->PostTask(std::make_unique<DeliveryTask>(
+        this, cached_report_, std::move(requests)));
   } else if (!num_pending_partial_reports_) {
     // Only start gathering stats if we're not already gathering stats. In the
     // case of already gathering stats, |callback_| will be invoked when there
@@ -1088,10 +1109,10 @@
     // ProducePartialResultsOnNetworkThread() has signaled the
     // |network_report_event_|.
     network_report_event_.Reset();
-    network_thread_->PostTask(
-        RTC_FROM_HERE,
-        rtc::Bind(&RTCStatsCollector::ProducePartialResultsOnNetworkThread,
-                  this, timestamp_us));
+    rtc::scoped_refptr<RTCStatsCollector> collector(this);
+    network_thread_->PostTask(RTC_FROM_HERE, [collector, timestamp_us] {
+      collector->ProducePartialResultsOnNetworkThread(timestamp_us);
+    });
     ProducePartialResultsOnSignalingThread(timestamp_us);
   }
 }
@@ -1160,8 +1181,9 @@
   // Signal that it is now safe to touch |network_report_| on the signaling
   // thread, and post a task to merge it into the final results.
   network_report_event_.Set();
+  rtc::scoped_refptr<RTCStatsCollector> collector(this);
   signaling_thread_->PostTask(
-      RTC_FROM_HERE, rtc::Bind(&RTCStatsCollector::MergeNetworkReport_s, this));
+      RTC_FROM_HERE, [collector] { collector->MergeNetworkReport_s(); });
 }
 
 void RTCStatsCollector::ProducePartialResultsOnNetworkThreadImpl(
diff --git a/pc/sctp_transport.cc b/pc/sctp_transport.cc
index 9450469..b542695 100644
--- a/pc/sctp_transport.cc
+++ b/pc/sctp_transport.cc
@@ -13,8 +13,6 @@
 #include <algorithm>
 #include <utility>
 
-#include "rtc_base/bind.h"
-
 namespace webrtc {
 
 SctpTransport::SctpTransport(
@@ -117,8 +115,9 @@
     }
   } else {
     owner_thread_->Invoke<void>(
-        RTC_FROM_HERE, rtc::Bind(&SctpTransport::Start, this, local_port,
-                                 remote_port, max_message_size));
+        RTC_FROM_HERE, [this, local_port, remote_port, max_message_size] {
+          Start(local_port, remote_port, max_message_size);
+        });
   }
 }
 
diff --git a/pc/sdp_offer_answer.cc b/pc/sdp_offer_answer.cc
index f924c40..8885276 100644
--- a/pc/sdp_offer_answer.cc
+++ b/pc/sdp_offer_answer.cc
@@ -54,7 +54,6 @@
 #include "pc/stats_collector.h"
 #include "pc/usage_pattern.h"
 #include "pc/webrtc_session_description_factory.h"
-#include "rtc_base/bind.h"
 #include "rtc_base/helpers.h"
 #include "rtc_base/location.h"
 #include "rtc_base/logging.h"
@@ -1941,8 +1940,7 @@
     // TODO(deadbeef): We already had to hop to the network thread for
     // MaybeStartGathering...
     pc_->network_thread()->Invoke<void>(
-        RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
-                                 port_allocator()));
+        RTC_FROM_HERE, [this] { port_allocator()->DiscardCandidatePool(); });
     // Make UMA notes about what was agreed to.
     ReportNegotiatedSdpSemantics(*local_description());
   }
@@ -2200,8 +2198,7 @@
     // TODO(deadbeef): We already had to hop to the network thread for
     // MaybeStartGathering...
     pc_->network_thread()->Invoke<void>(
-        RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
-                                 port_allocator()));
+        RTC_FROM_HERE, [this] { port_allocator()->DiscardCandidatePool(); });
     // Make UMA notes about what was agreed to.
     ReportNegotiatedSdpSemantics(*remote_description());
   }
@@ -3539,8 +3536,7 @@
   session_options->pooled_ice_credentials =
       pc_->network_thread()->Invoke<std::vector<cricket::IceParameters>>(
           RTC_FROM_HERE,
-          rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
-                    port_allocator()));
+          [this] { return port_allocator()->GetPooledIceCredentials(); });
   session_options->offer_extmap_allow_mixed =
       pc_->configuration()->offer_extmap_allow_mixed;
 
@@ -3804,8 +3800,7 @@
   session_options->pooled_ice_credentials =
       pc_->network_thread()->Invoke<std::vector<cricket::IceParameters>>(
           RTC_FROM_HERE,
-          rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
-                    port_allocator()));
+          [this] { return port_allocator()->GetPooledIceCredentials(); });
 }
 
 void SdpOfferAnswerHandler::GetOptionsForPlanBAnswer(
@@ -4242,9 +4237,11 @@
 
   RTCError error = pc_->worker_thread()->Invoke<RTCError>(
       RTC_FROM_HERE,
-      rtc::Bind(&SdpOfferAnswerHandler::ApplyChannelUpdates, this, type, source,
-                std::move(payload_type_demuxing_updates),
-                std::move(content_updates)));
+      [this, type, source, &payload_type_demuxing_updates, &content_updates] {
+        return ApplyChannelUpdates(type, source,
+                                   std::move(payload_type_demuxing_updates),
+                                   std::move(content_updates));
+      });
   if (!error.ok()) {
     return error;
   }
@@ -4691,10 +4688,10 @@
   RTC_DCHECK_RUN_ON(signaling_thread());
   switch (pc_->data_channel_type()) {
     case cricket::DCT_SCTP:
-      if (pc_->network_thread()->Invoke<bool>(
-              RTC_FROM_HERE,
-              rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, pc_,
-                        mid))) {
+      if (pc_->network_thread()->Invoke<bool>(RTC_FROM_HERE, [this, &mid] {
+            RTC_DCHECK_RUN_ON(pc_->network_thread());
+            return pc_->SetupDataChannelTransport_n(mid);
+          })) {
         pc_->SetSctpDataMid(mid);
       } else {
         return false;