File: webrtc_transport.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1288 lines) | stat: -rw-r--r-- 46,653 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/protocol/webrtc_transport.h"

#include <algorithm>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/base64.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ref.h"
#include "base/notimplemented.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "components/webrtc/net_address_utils.h"
#include "components/webrtc/thread_wrapper.h"
#include "remoting/base/constants.h"
#include "remoting/base/logging.h"
#include "remoting/protocol/authenticator.h"
#include "remoting/protocol/errors.h"
#include "remoting/protocol/port_allocator_factory.h"
#include "remoting/protocol/sdp_message.h"
#include "remoting/protocol/transport.h"
#include "remoting/protocol/transport_context.h"
#include "remoting/protocol/webrtc_audio_module.h"
#include "third_party/libjingle_xmpp/xmllite/xmlelement.h"
#include "third_party/webrtc/api/audio/builtin_audio_processing_builder.h"
#include "third_party/webrtc/api/audio_codecs/audio_decoder_factory_template.h"
#include "third_party/webrtc/api/audio_codecs/audio_encoder_factory_template.h"
#include "third_party/webrtc/api/audio_codecs/opus/audio_decoder_opus.h"
#include "third_party/webrtc/api/audio_codecs/opus/audio_encoder_opus.h"
#include "third_party/webrtc/api/enable_media.h"
#include "third_party/webrtc/api/peer_connection_interface.h"
#include "third_party/webrtc/api/rtc_event_log/rtc_event_log_factory.h"
#include "third_party/webrtc/api/video_codecs/builtin_video_decoder_factory.h"
#include "third_party/webrtc_overrides/environment.h"

#if !defined(NDEBUG)
#include "base/command_line.h"
#endif

using jingle_xmpp::QName;
using jingle_xmpp::XmlElement;

namespace remoting::protocol {

class ScopedAllowThreadJoinForWebRtcTransport
    : public base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {};

class ScopedAllowSyncPrimitivesForWebRtcTransport
    : public base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {};

namespace {

using DataChannelState = webrtc::DataChannelInterface::DataState;

// Delay after candidate creation before sending transport-info message to
// accumulate multiple candidates. This is an optimization to reduce number of
// transport-info messages.
const int kTransportInfoSendDelayMs = 20;

// XML namespace for the transport elements.
const char kTransportNamespace[] = "google:remoting:webrtc";

// Global maximum bitrate set for the PeerConnection.
const int kMaxBitrateBps = 1e8;  // 100 Mbps.

// Frequency of polling the event and control data channels for their current
// state while waiting for them to close.
constexpr base::TimeDelta kDefaultDataChannelStatePollingInterval =
    base::Milliseconds(50);

// The maximum amount of time we will wait for the data channels to close before
// closing the PeerConnection.
constexpr base::TimeDelta kWaitForDataChannelsClosedTimeout = base::Seconds(5);

// The time to wait after receiving a disconnected state change before assuming
// that the connection is failed.
constexpr base::TimeDelta kCloseAfterDisconnectTimeout = base::Seconds(10);

base::TimeDelta data_channel_state_polling_interval =
    kDefaultDataChannelStatePollingInterval;

#if !defined(NDEBUG)
// Command line switch used to disable signature verification.
// TODO(sergeyu): Remove this flag.
const char kDisableAuthenticationSwitchName[] = "disable-authentication";
#endif

bool IsValidSessionDescriptionType(webrtc::SdpType type) {
  return type == webrtc::SdpType::kOffer || type == webrtc::SdpType::kAnswer;
}

void UpdateCodecParameters(SdpMessage& sdp_message, bool incoming) {
  // Update SDP format to use 160kbps stereo for opus codec.
  if (sdp_message.has_audio() &&
      !sdp_message.AddCodecParameter("opus",
                                     "stereo=1; maxaveragebitrate=163840")) {
    if (incoming) {
      LOG(WARNING) << "Opus not found in an incoming SDP.";
    } else {
      LOG(FATAL) << "Opus not found in SDP generated by WebRTC.";
    }
  }
}

std::string GetTransportProtocol(const webrtc::CandidatePair& candidate_pair) {
  const webrtc::Candidate& local_candidate = candidate_pair.local_candidate();
  return local_candidate.is_relay() ? local_candidate.relay_protocol()
                                    : local_candidate.protocol();
}

// Returns true if the selected candidate-pair indicates a relay connection.
bool IsConnectionRelayed(const webrtc::CandidatePair& selected_candidate_pair) {
  const webrtc::Candidate& local_candidate =
      selected_candidate_pair.local_candidate();
  const webrtc::Candidate& remote_candidate =
      selected_candidate_pair.remote_candidate();
  return local_candidate.is_relay() || remote_candidate.is_relay();
}

// Utility function to map a webrtc::Candidate string type to a
// TransportRoute::RouteType enum value.
TransportRoute::RouteType CandidateTypeToTransportRouteType(
    const webrtc::Candidate& candidate) {
  if (candidate.is_stun() || candidate.is_prflx()) {
    return TransportRoute::STUN;
  } else if (candidate.is_relay()) {
    return TransportRoute::RELAY;
  }
  DCHECK(candidate.is_local());
  return TransportRoute::DIRECT;
}

void SetSenderParameters(webrtc::RtpSenderInterface& sender,
                         const webrtc::RtpParameters& parameters) {
  ScopedAllowSyncPrimitivesForWebRtcTransport allow_wait;
  webrtc::RTCError result = sender.SetParameters(parameters);
  DCHECK(result.ok()) << "SetParameters() failed: " << result.message();
}

// Initializes default parameters for a sender that may be different from
// WebRTC's defaults.
void SetDefaultSenderParameters(
    webrtc::scoped_refptr<webrtc::RtpSenderInterface> sender) {
  if (sender->media_type() == webrtc::MediaType::VIDEO) {
    webrtc::RtpParameters parameters = sender->GetParameters();
    if (parameters.encodings.empty()) {
      LOG(ERROR) << "No encodings found for sender " << sender->id();
      return;
    }

    for (auto& encoding : parameters.encodings) {
      encoding.max_framerate = kTargetFrameRate;
    }

    SetSenderParameters(*sender, parameters);
  }
}

// A webrtc::CreateSessionDescriptionObserver implementation used to receive the
// results of creating descriptions for this end of the PeerConnection.
class CreateSessionDescriptionObserver
    : public webrtc::CreateSessionDescriptionObserver {
 public:
  typedef base::OnceCallback<void(
      std::unique_ptr<webrtc::SessionDescriptionInterface> description,
      const std::string& error)>
      ResultCallback;

  static CreateSessionDescriptionObserver* Create(
      ResultCallback result_callback) {
    return new webrtc::RefCountedObject<CreateSessionDescriptionObserver>(
        std::move(result_callback));
  }

  CreateSessionDescriptionObserver(const CreateSessionDescriptionObserver&) =
      delete;
  CreateSessionDescriptionObserver& operator=(
      const CreateSessionDescriptionObserver&) = delete;

  void OnSuccess(webrtc::SessionDescriptionInterface* desc) override {
    std::move(result_callback_).Run(base::WrapUnique(desc), std::string());
  }

  void OnFailure(webrtc::RTCError error) override {
    std::move(result_callback_).Run(nullptr, error.message());
  }

 protected:
  explicit CreateSessionDescriptionObserver(ResultCallback result_callback)
      : result_callback_(std::move(result_callback)) {}
  ~CreateSessionDescriptionObserver() override = default;

 private:
  ResultCallback result_callback_;
};

// A webrtc::SetSessionDescriptionObserver implementation used to receive the
// results of setting local and remote descriptions of the PeerConnection.
class SetSessionDescriptionObserver
    : public webrtc::SetSessionDescriptionObserver {
 public:
  typedef base::OnceCallback<void(bool success, const std::string& error)>
      ResultCallback;

  static SetSessionDescriptionObserver* Create(ResultCallback result_callback) {
    return new webrtc::RefCountedObject<SetSessionDescriptionObserver>(
        std::move(result_callback));
  }

  SetSessionDescriptionObserver(const SetSessionDescriptionObserver&) = delete;
  SetSessionDescriptionObserver& operator=(
      const SetSessionDescriptionObserver&) = delete;

  void OnSuccess() override {
    std::move(result_callback_).Run(true, std::string());
  }

  void OnFailure(webrtc::RTCError error) override {
    std::move(result_callback_).Run(false, error.message());
  }

 protected:
  explicit SetSessionDescriptionObserver(ResultCallback result_callback)
      : result_callback_(std::move(result_callback)) {}
  ~SetSessionDescriptionObserver() override = default;

 private:
  ResultCallback result_callback_;
};

class RtcEventLogOutput : public webrtc::RtcEventLogOutput {
 public:
  // |event_log_data| will be populated with the RTC event data during logging.
  // The caller owns |event_log_data| and must keep it alive as long as
  // WebRTC provides event logging to this instance (that is, until
  // PeerConnection::StopEventLog() is called, or the PeerConnection is
  // destroyed).
  explicit RtcEventLogOutput(WebrtcEventLogData& event_log_data)
      : event_log_data_(event_log_data) {}
  ~RtcEventLogOutput() override = default;

  RtcEventLogOutput(const RtcEventLogOutput&) = delete;
  RtcEventLogOutput& operator=(const RtcEventLogOutput&) = delete;

  // webrtc::RtcEventLogOutput interface
  bool IsActive() const override { return true; }
  bool Write(std::string_view output) override {
    event_log_data_->Write(output);
    return true;
  }

 private:
  // Holds the recorded event log data. This buffer is owned by the caller.
  const raw_ref<WebrtcEventLogData> event_log_data_;
};

}  // namespace

class WebrtcTransport::PeerConnectionWrapper
    : public webrtc::PeerConnectionObserver {
 public:
  PeerConnectionWrapper(
      webrtc::Thread* worker_thread,
      std::unique_ptr<webrtc::VideoEncoderFactory> encoder_factory,
      std::unique_ptr<webrtc::PortAllocator> port_allocator,
      base::WeakPtr<WebrtcTransport> transport)
      : transport_(transport) {
    audio_module_ = new webrtc::RefCountedObject<WebrtcAudioModule>();

    webrtc::PeerConnectionFactoryDependencies pcf_deps;
    pcf_deps.network_thread = worker_thread;
    pcf_deps.worker_thread = worker_thread;
    pcf_deps.signaling_thread = webrtc::Thread::Current();
    pcf_deps.env = WebRtcEnvironment();
    pcf_deps.event_log_factory = std::make_unique<webrtc::RtcEventLogFactory>();
    pcf_deps.adm = audio_module_;
    pcf_deps.audio_encoder_factory =
        webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus>();
    pcf_deps.audio_decoder_factory =
        webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus>();
    pcf_deps.video_encoder_factory = std::move(encoder_factory);
    pcf_deps.video_decoder_factory = webrtc::CreateBuiltinVideoDecoderFactory();
    pcf_deps.audio_processing_builder =
        std::make_unique<webrtc::BuiltinAudioProcessingBuilder>();
    webrtc::EnableMedia(pcf_deps);
    peer_connection_factory_ =
        webrtc::CreateModularPeerConnectionFactory(std::move(pcf_deps));

    webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;

    // Set bundle_policy and rtcp_mux_policy to ensure that all channels are
    // multiplexed over a single channel.
    rtc_config.bundle_policy =
        webrtc::PeerConnectionInterface::kBundlePolicyMaxBundle;
    rtc_config.rtcp_mux_policy =
        webrtc::PeerConnectionInterface::kRtcpMuxPolicyRequire;

    rtc_config.media_config.video.periodic_alr_bandwidth_probing = true;

    rtc_config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;

    webrtc::PeerConnectionDependencies dependencies(this);
    dependencies.allocator = std::move(port_allocator);
    auto result = peer_connection_factory_->CreatePeerConnectionOrError(
        rtc_config, std::move(dependencies));
    if (!result.ok()) {
      LOG(ERROR) << "CreatePeerConnection() failed: "
                 << result.error().message();
      return;
    }
    peer_connection_ = result.MoveValue();
  }

  PeerConnectionWrapper(const PeerConnectionWrapper&) = delete;
  PeerConnectionWrapper& operator=(const PeerConnectionWrapper&) = delete;

  ~PeerConnectionWrapper() override {
    {
      // |peer_connection_| creates threads internally, which are joined when
      // the connection is closed. See crbug.com/660081.
      ScopedAllowThreadJoinForWebRtcTransport allow_thread_join;
      peer_connection_->Close();
      peer_connection_ = nullptr;
      peer_connection_factory_ = nullptr;
    }

    audio_module_ = nullptr;
  }

  WebrtcAudioModule* audio_module() { return audio_module_.get(); }

  webrtc::PeerConnectionInterface* peer_connection() {
    return peer_connection_.get();
  }

  webrtc::PeerConnectionFactoryInterface* peer_connection_factory() {
    return peer_connection_factory_.get();
  }

  // webrtc::PeerConnectionObserver interface.
  void OnSignalingChange(
      webrtc::PeerConnectionInterface::SignalingState new_state) override {
    if (transport_) {
      transport_->OnSignalingChange(new_state);
    }
  }
  void OnAddStream(
      webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override {
    if (transport_) {
      transport_->OnAddStream(stream);
    }
  }
  void OnRemoveStream(
      webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override {
    if (transport_) {
      transport_->OnRemoveStream(stream);
    }
  }
  void OnDataChannel(webrtc::scoped_refptr<webrtc::DataChannelInterface>
                         data_channel) override {
    if (transport_) {
      transport_->OnDataChannel(data_channel);
    }
  }
  void OnRenegotiationNeeded() override {
    if (transport_) {
      transport_->OnRenegotiationNeeded();
    }
  }
  void OnIceConnectionChange(
      webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
    if (transport_) {
      transport_->OnIceConnectionChange(new_state);
    }
  }
  void OnIceGatheringChange(
      webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
    if (transport_) {
      transport_->OnIceGatheringChange(new_state);
    }
  }
  void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
    if (transport_) {
      transport_->OnIceCandidate(candidate);
    }
  }
  void OnIceSelectedCandidatePairChanged(
      const webrtc::CandidatePairChangeEvent& event) override {
    if (transport_) {
      transport_->OnIceSelectedCandidatePairChanged(event);
    }
  }

 private:
  webrtc::scoped_refptr<WebrtcAudioModule> audio_module_;
  webrtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
      peer_connection_factory_;
  webrtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;

  base::WeakPtr<WebrtcTransport> transport_;
};

WebrtcTransport::WebrtcTransport(
    webrtc::Thread* worker_thread,
    scoped_refptr<TransportContext> transport_context,
    std::unique_ptr<webrtc::VideoEncoderFactory> video_encoder_factory,
    EventHandler* event_handler)
    : transport_context_(transport_context),
      event_handler_(event_handler),
      handshake_hmac_(crypto::HMAC::SHA256) {
  auto create_port_allocator_result =
      transport_context_->port_allocator_factory()->CreatePortAllocator(
          transport_context_, weak_factory_.GetWeakPtr());

  apply_network_settings_ =
      std::move(create_port_allocator_result.apply_network_settings);
  peer_connection_wrapper_ = std::make_unique<PeerConnectionWrapper>(
      worker_thread, std::move(video_encoder_factory),
      std::move(create_port_allocator_result.allocator),
      weak_factory_.GetWeakPtr());

  StartRtcEventLogging();
}

WebrtcTransport::~WebrtcTransport() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  Close(ErrorCode::OK, /* error_details= */ {}, FROM_HERE);
}

webrtc::PeerConnectionInterface* WebrtcTransport::peer_connection() {
  return peer_connection_wrapper_ ? peer_connection_wrapper_->peer_connection()
                                  : nullptr;
}

webrtc::PeerConnectionFactoryInterface*
WebrtcTransport::peer_connection_factory() {
  return peer_connection_wrapper_
             ? peer_connection_wrapper_->peer_connection_factory()
             : nullptr;
}

WebrtcAudioModule* WebrtcTransport::audio_module() {
  return peer_connection_wrapper_ ? peer_connection_wrapper_->audio_module()
                                  : nullptr;
}

std::unique_ptr<MessagePipe> WebrtcTransport::CreateOutgoingChannel(
    const std::string& name) {
  webrtc::DataChannelInit config;
  config.reliable = true;
  auto result = peer_connection()->CreateDataChannelOrError(name, &config);
  if (!result.ok()) {
    LOG(ERROR) << "CreateDataChannelOrError() failed: "
               << result.error().message();
    return nullptr;
  }
  auto data_channel = result.MoveValue();
  if (name == kControlChannelName) {
    DCHECK(!control_data_channel_);
    control_data_channel_ = data_channel;
  } else if (name == kEventChannelName) {
    DCHECK(!event_data_channel_);
    event_data_channel_ = data_channel;
  }
  return std::make_unique<WebrtcDataStreamAdapter>(data_channel);
}

void WebrtcTransport::ApplyNetworkSettings(
    const NetworkSettings& network_settings) {
  std::move(apply_network_settings_).Run(network_settings);
}

void WebrtcTransport::Start(
    Authenticator* authenticator,
    SendTransportInfoCallback send_transport_info_callback) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(send_transport_info_callback_.is_null());

  webrtc::ThreadWrapper::EnsureForCurrentMessageLoop();

  // TODO(sergeyu): Investigate if it's possible to avoid Send().
  webrtc::ThreadWrapper::current()->set_send_allowed(true);

  send_transport_info_callback_ = std::move(send_transport_info_callback);

  if (!handshake_hmac_.Init(authenticator->GetAuthKey())) {
    LOG(FATAL) << "HMAC::Init() failed.";
  }

  event_handler_->OnWebrtcTransportConnecting();

  if (transport_context_->role() == TransportRole::SERVER) {
    RequestNegotiation();
  }
}

bool WebrtcTransport::ProcessTransportInfo(XmlElement* transport_info) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (transport_info->Name() != QName(kTransportNamespace, "transport")) {
    return false;
  }

  if (!peer_connection()) {
    return false;
  }

  XmlElement* session_description = transport_info->FirstNamed(
      QName(kTransportNamespace, "session-description"));
  if (session_description) {
    webrtc::PeerConnectionInterface::SignalingState expected_state =
        transport_context_->role() == TransportRole::CLIENT
            ? webrtc::PeerConnectionInterface::kStable
            : webrtc::PeerConnectionInterface::kHaveLocalOffer;
    if (peer_connection()->signaling_state() != expected_state) {
      LOG(ERROR) << "Received unexpected WebRTC session_description.";
      return false;
    }

    std::string type_string =
        session_description->Attr(QName(std::string(), "type"));
    std::optional<webrtc::SdpType> maybe_type =
        webrtc::SdpTypeFromString(type_string);
    std::string raw_sdp = session_description->BodyText();
    if (!maybe_type.has_value() ||
        !IsValidSessionDescriptionType(*maybe_type) || raw_sdp.empty()) {
      LOG(ERROR) << "Incorrect session description format.";
      return false;
    }

    SdpMessage sdp_message(raw_sdp);

    std::string signature_base64 =
        session_description->Attr(QName(std::string(), "signature"));
    std::string signature;
    if (!base::Base64Decode(signature_base64, &signature) ||
        !handshake_hmac_.Verify(
            type_string + " " + sdp_message.NormalizedForSignature(),
            signature)) {
      static constexpr char kErrorDetails[] =
          "Received session-description with invalid signature.";
      bool ignore_error = false;
#if !defined(NDEBUG)
      ignore_error = base::CommandLine::ForCurrentProcess()->HasSwitch(
          kDisableAuthenticationSwitchName);
#endif
      if (!ignore_error) {
        Close(ErrorCode::AUTHENTICATION_FAILED, kErrorDetails, FROM_HERE);
        return true;
      } else {
        LOG(WARNING) << kErrorDetails;
      }
    }

    UpdateCodecParameters(sdp_message, /*incoming=*/true);

    webrtc::SdpParseError error;
    std::unique_ptr<webrtc::SessionDescriptionInterface>
        webrtc_session_description(webrtc::CreateSessionDescription(
            *maybe_type, sdp_message.ToString(), &error));
    if (!webrtc_session_description) {
      LOG(ERROR) << "Failed to parse the session description: "
                 << error.description << " line: " << error.line;
      return false;
    }

    {
      ScopedAllowThreadJoinForWebRtcTransport allow_wait;
      peer_connection()->SetRemoteDescription(
          SetSessionDescriptionObserver::Create(
              base::BindOnce(&WebrtcTransport::OnRemoteDescriptionSet,
                             weak_factory_.GetWeakPtr(),
                             *maybe_type == webrtc::SdpType::kOffer)),
          webrtc_session_description.release());
    }

    // SetRemoteDescription() might overwrite any bitrate caps previously set,
    // so (re)apply them here. This might happen if ICE state were already
    // connected and OnIceSelectedCandidatePairChanged() had already set the
    // caps.
    UpdateBitrates();
  }

  XmlElement* candidate_element;
  QName candidate_qname(kTransportNamespace, "candidate");
  for (candidate_element = transport_info->FirstNamed(candidate_qname);
       candidate_element;
       candidate_element = candidate_element->NextNamed(candidate_qname)) {
    std::string candidate_str = candidate_element->BodyText();
    std::string sdp_mid =
        candidate_element->Attr(QName(std::string(), "sdpMid"));
    std::string sdp_mlineindex_str =
        candidate_element->Attr(QName(std::string(), "sdpMLineIndex"));
    int sdp_mlineindex;
    if (candidate_str.empty() || sdp_mid.empty() ||
        !base::StringToInt(sdp_mlineindex_str, &sdp_mlineindex)) {
      LOG(ERROR) << "Failed to parse incoming candidates.";
      return false;
    }

    webrtc::SdpParseError error;
    std::unique_ptr<webrtc::IceCandidateInterface> candidate(
        webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate_str,
                                   &error));
    if (!candidate) {
      LOG(ERROR) << "Failed to parse incoming candidate: " << error.description
                 << " line: " << error.line;
      return false;
    }

    if (peer_connection()->signaling_state() ==
        webrtc::PeerConnectionInterface::kStable) {
      if (!peer_connection()->AddIceCandidate(candidate.get())) {
        LOG(ERROR) << "Failed to add incoming ICE candidate.";
        return false;
      }
    } else {
      pending_incoming_candidates_.push_back(std::move(candidate));
    }
  }

  return true;
}

const SessionOptions& WebrtcTransport::session_options() const {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return session_options_;
}

void WebrtcTransport::SetPreferredBitrates(std::optional<int> min_bitrate_bps,
                                           std::optional<int> max_bitrate_bps) {
  preferred_min_bitrate_bps_ = min_bitrate_bps;
  preferred_max_bitrate_bps_ = max_bitrate_bps;
  if (connected_) {
    UpdateBitrates();
  }
}

void WebrtcTransport::RequestIceRestart() {
  if (transport_context_->role() != TransportRole::SERVER) {
    NOTIMPLEMENTED()
        << "ICE restart only implemented for TransportRole::SERVER";
    return;
  }

  if (!connected_) {
    LOG(WARNING) << "Not connected, ignoring ICE restart request.";
    return;
  }

  VLOG(0) << "Restarting ICE due to client request.";
  connected_ = false;
  want_ice_restart_ = true;
  RequestNegotiation();
}

void WebrtcTransport::RequestSdpRestart() {
  if (transport_context_->role() != TransportRole::SERVER) {
    NOTIMPLEMENTED()
        << "SDP restart only implemented for TransportRole::SERVER";
    return;
  }

  if (!connected_) {
    LOG(WARNING) << "Not connected, ignoring SDP restart request.";
    return;
  }

  VLOG(0) << "Restarting SDP due to client request.";
  RequestNegotiation();
}

// static
void WebrtcTransport::SetDataChannelPollingIntervalForTests(
    base::TimeDelta new_polling_interval) {
  data_channel_state_polling_interval = new_polling_interval;
}

// static
void WebrtcTransport::ClosePeerConnection(
    webrtc::scoped_refptr<webrtc::DataChannelInterface> control_data_channel,
    webrtc::scoped_refptr<webrtc::DataChannelInterface> event_data_channel,
    std::unique_ptr<PeerConnectionWrapper> peer_connection_wrapper,
    base::Time start_time = base::Time::Now()) {
  DCHECK(peer_connection_wrapper);

  if (!control_data_channel || !event_data_channel) {
    LOG(WARNING) << "One or more data channels were not initialized, "
                 << "destroying PeerConnection.";
    base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon(
        FROM_HERE, peer_connection_wrapper.release());
    return;
  }

  if ((base::Time::Now() - start_time) > kWaitForDataChannelsClosedTimeout) {
    LOG(ERROR) << "Timed out waiting for data channels to close, "
               << "destroying PeerConnection.";
    base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon(
        FROM_HERE, peer_connection_wrapper.release());
    return;
  }

  // The data channels should have started the closing process before this
  // function was called.
  DCHECK(control_data_channel->state() == DataChannelState::kClosed ||
         control_data_channel->state() == DataChannelState::kClosing);
  DCHECK(event_data_channel->state() == DataChannelState::kClosed ||
         event_data_channel->state() == DataChannelState::kClosing);

  if (event_data_channel->state() == DataChannelState::kClosed &&
      control_data_channel->state() == DataChannelState::kClosed) {
    VLOG(0) << "Data channels closed, destroying PeerConnection.";
    base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon(
        FROM_HERE, peer_connection_wrapper.release());
    return;
  }

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&ClosePeerConnection, std::move(control_data_channel),
                     std::move(event_data_channel),
                     std::move(peer_connection_wrapper), start_time),
      data_channel_state_polling_interval);
}

void WebrtcTransport::Close(ErrorCode error,
                            std::string_view error_details,
                            const base::Location& error_location) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!peer_connection_wrapper_) {
    return;
  }

  weak_factory_.InvalidateWeakPtrs();

  // Stop recording into the buffer, otherwise WebRTC might try to record
  // events into the buffer while closing the connection, after |this| has been
  // destroyed.
  StopRtcEventLogging();
  ClosePeerConnection(std::move(control_data_channel_),
                      std::move(event_data_channel_),
                      std::move(peer_connection_wrapper_));

  if (error != ErrorCode::OK) {
    event_handler_->OnWebrtcTransportError(error, error_details,
                                           error_location);
  }
}

void WebrtcTransport::ApplySessionOptions(const SessionOptions& options) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  session_options_ = options;
}

void WebrtcTransport::OnAudioTransceiverCreated(
    webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) {}

void WebrtcTransport::OnVideoTransceiverCreated(
    webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) {
  // Sender is always present, regardless of the direction of media
  // (see rtp_transceiver_interface.h).
  auto sender = transceiver->sender();
  auto [min_bitrate_bps, max_bitrate_bps] = BitratesForConnection();
  SetSenderBitrates(sender, min_bitrate_bps, max_bitrate_bps);
  SetDefaultSenderParameters(sender);
}

void WebrtcTransport::OnLocalSessionDescriptionCreated(
    std::unique_ptr<webrtc::SessionDescriptionInterface> description,
    const std::string& error) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (!peer_connection()) {
    return;
  }

  if (!description) {
    Close(ErrorCode::CHANNEL_CONNECTION_ERROR,
          base::StrCat({"PeerConnection offer creation failed: ", error}),
          FROM_HERE);
    return;
  }

  std::string description_sdp;
  if (!description->ToString(&description_sdp)) {
    Close(ErrorCode::CHANNEL_CONNECTION_ERROR,
          "Failed to serialize description.", FROM_HERE);
    return;
  }

  SdpMessage sdp_message(description_sdp);
  UpdateCodecParameters(sdp_message, /*incoming=*/false);
  if (sdp_message.has_video() &&
      transport_context_->preferred_video_format().has_value()) {
    sdp_message.SetPreferredVideoFormat(
        *transport_context_->preferred_video_format());
  }
  description_sdp = sdp_message.ToString();
  webrtc::SdpParseError parse_error;
  description = webrtc::CreateSessionDescription(description->GetType(),
                                                 description_sdp, &parse_error);
  if (!description) {
    Close(ErrorCode::CHANNEL_CONNECTION_ERROR,
          base::StrCat({"Failed to parse the session description: ",
                        parse_error.description, " line: ", parse_error.line}),
          FROM_HERE);
    return;
  }

  // Format and send the session description to the peer.
  std::unique_ptr<XmlElement> transport_info(
      new XmlElement(QName(kTransportNamespace, "transport"), true));
  XmlElement* offer_tag =
      new XmlElement(QName(kTransportNamespace, "session-description"));
  transport_info->AddElement(offer_tag);
  offer_tag->SetAttr(QName(std::string(), "type"), description->type());
  offer_tag->SetBodyText(description_sdp);

  std::string digest;
  digest.resize(handshake_hmac_.DigestLength());
  CHECK(handshake_hmac_.Sign(
      description->type() + " " + sdp_message.NormalizedForSignature(),
      reinterpret_cast<uint8_t*>(&(digest[0])), digest.size()));
  std::string digest_base64 = base::Base64Encode(digest);
  offer_tag->SetAttr(QName(std::string(), "signature"), digest_base64);

  send_transport_info_callback_.Run(std::move(transport_info));

  peer_connection()->SetLocalDescription(
      SetSessionDescriptionObserver::Create(base::BindOnce(
          &WebrtcTransport::OnLocalDescriptionSet, weak_factory_.GetWeakPtr())),
      description.release());
}

void WebrtcTransport::OnLocalDescriptionSet(bool success,
                                            const std::string& error) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (!peer_connection()) {
    return;
  }

  if (!success) {
    Close(ErrorCode::CHANNEL_CONNECTION_ERROR,
          base::StrCat({"Failed to set local description: ", error}),
          FROM_HERE);
    return;
  }

  AddPendingCandidatesIfPossible();

  // The sender "encodings" parameters are initialized after the local
  // description is set. At this point, it is possible to set parameters such as
  // maximum framerate.
  auto senders = peer_connection()->GetSenders();
  for (const auto& sender : senders) {
    SetDefaultSenderParameters(sender);
  }
}

void WebrtcTransport::OnRemoteDescriptionSet(bool send_answer,
                                             bool success,
                                             const std::string& error) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (!peer_connection()) {
    return;
  }

  if (!success) {
    Close(ErrorCode::CHANNEL_CONNECTION_ERROR,
          base::StrCat({"Failed to set remote description: ", error}),
          FROM_HERE);
    return;
  }

  // Create and send answer on the server.
  if (send_answer) {
    if (!apply_network_settings_) {
      SendAnswer();
    } else {
      HOST_LOG << "SendAnswer is delayed until network settings are applied.";
      apply_network_settings_ =
          std::move(apply_network_settings_)
              .Then(base::BindOnce(&WebrtcTransport::SendAnswer,
                                   weak_factory_.GetWeakPtr()));
    }
  }

  AddPendingCandidatesIfPossible();
}

void WebrtcTransport::SendAnswer() {
  const webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
  peer_connection()->CreateAnswer(
      CreateSessionDescriptionObserver::Create(
          base::BindOnce(&WebrtcTransport::OnLocalSessionDescriptionCreated,
                         weak_factory_.GetWeakPtr())),
      options);
}

void WebrtcTransport::OnCloseAfterDisconnectTimeout() {
  // Close() fails DCHECKs if the data channels are not in the kClosing or
  // kClosed state.
  if (control_data_channel_) {
    control_data_channel_->Close();
  }
  if (event_data_channel_) {
    event_data_channel_->Close();
  }
  Close(ErrorCode::PEER_IS_OFFLINE,
        base::StringPrintf(
            "ICE has not reconnected in %ds. Client may be offline.",
            kCloseAfterDisconnectTimeout.InSeconds()),
        FROM_HERE);
}

void WebrtcTransport::OnSignalingChange(
    webrtc::PeerConnectionInterface::SignalingState new_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
}

void WebrtcTransport::OnAddStream(
    webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  event_handler_->OnWebrtcTransportMediaStreamAdded(stream);
}

void WebrtcTransport::OnRemoveStream(
    webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  event_handler_->OnWebrtcTransportMediaStreamRemoved(stream);
}

void WebrtcTransport::OnDataChannel(
    webrtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  std::string data_channel_name = data_channel->label();
  if (data_channel_name == kControlChannelName) {
    DCHECK(!control_data_channel_);
    control_data_channel_ = data_channel;
  } else if (data_channel_name == kEventChannelName) {
    DCHECK(!event_data_channel_);
    event_data_channel_ = data_channel;
  }
  event_handler_->OnWebrtcTransportIncomingDataChannel(
      data_channel_name,
      std::make_unique<WebrtcDataStreamAdapter>(data_channel));
}

void WebrtcTransport::OnRenegotiationNeeded() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (transport_context_->role() == TransportRole::SERVER) {
    RequestNegotiation();
  } else {
    // TODO(sergeyu): Is it necessary to support renegotiation initiated by the
    // client?
    NOTIMPLEMENTED();
  }
}

void WebrtcTransport::OnIceConnectionChange(
    webrtc::PeerConnectionInterface::IceConnectionState new_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (!connected_ &&
      new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) {
    connected_ = true;
    close_after_disconnect_timer_.Stop();
    event_handler_->OnWebrtcTransportConnected();
  } else if (connected_ &&
             new_state ==
                 webrtc::PeerConnectionInterface::kIceConnectionDisconnected &&
             transport_context_->role() == TransportRole::SERVER) {
    connected_ = false;
    want_ice_restart_ = true;
    close_after_disconnect_timer_.Start(
        FROM_HERE, kCloseAfterDisconnectTimeout,
        base::BindOnce(&WebrtcTransport::OnCloseAfterDisconnectTimeout,
                       weak_factory_.GetWeakPtr()));
    RequestNegotiation();
  }
}

void WebrtcTransport::OnIceGatheringChange(
    webrtc::PeerConnectionInterface::IceGatheringState new_state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
}

void WebrtcTransport::OnIceCandidate(
    const webrtc::IceCandidateInterface* candidate) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  std::unique_ptr<XmlElement> candidate_element(
      new XmlElement(QName(kTransportNamespace, "candidate")));
  std::string candidate_str;
  if (!candidate->ToString(&candidate_str)) {
    LOG(ERROR) << "Failed to serialize local candidate.";
    return;
  }
  candidate_element->SetBodyText(candidate_str);
  candidate_element->SetAttr(QName(std::string(), "sdpMid"),
                             candidate->sdp_mid());
  candidate_element->SetAttr(
      QName(std::string(), "sdpMLineIndex"),
      base::NumberToString(candidate->sdp_mline_index()));

  EnsurePendingTransportInfoMessage();
  pending_transport_info_message_->AddElement(candidate_element.release());
}

void WebrtcTransport::OnIceSelectedCandidatePairChanged(
    const webrtc::CandidatePairChangeEvent& event) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  std::string transport_protocol =
      GetTransportProtocol(event.selected_candidate_pair);
  if (transport_protocol != transport_protocol_) {
    transport_protocol_ = transport_protocol;
    event_handler_->OnWebrtcTransportProtocolChanged();
  }

  // Unknown -> direct/relayed is treated as a
  // change, so the correct initial bitrate caps are set.
  std::optional<bool> connection_relayed =
      IsConnectionRelayed(event.selected_candidate_pair);
  if (connection_relayed != connection_relayed_) {
    connection_relayed_ = connection_relayed;
    VLOG(0) << "Relay connection: "
            << (*connection_relayed_ ? "true" : "false");

    // The max-bitrate needs to be applied even for direct (non-TURN)
    // connections. Otherwise the video-sender b/w estimate is capped to a low
    // default value (~600kbps).
    // Set the global bitrate caps in addition to the VideoSender bitrates. The
    // global caps affect the probing configuration used by b/w estimator.
    UpdateBitrates();
  }

  const webrtc::Candidate& local_candidate =
      event.selected_candidate_pair.local_candidate();
  const webrtc::Candidate& remote_candidate =
      event.selected_candidate_pair.remote_candidate();

  TransportRoute route;
  static_assert(TransportRoute::DIRECT < TransportRoute::STUN &&
                    TransportRoute::STUN < TransportRoute::RELAY,
                "Route type enum values are ordered by 'indirectness'");
  route.type = std::max(CandidateTypeToTransportRouteType(local_candidate),
                        CandidateTypeToTransportRouteType(remote_candidate));

  VLOG(0) << "Selected candidate-pair changed, reason = " << event.reason;
  VLOG(0) << "  Local IP = " << local_candidate.address().ToString()
          << ", type = " << local_candidate.type_name()
          << ", protocol = " << local_candidate.protocol();
  VLOG(0) << "  Remote IP = " << remote_candidate.address().ToString()
          << ", type = " << remote_candidate.type_name()
          << ", protocol = " << remote_candidate.protocol();

  // Try to convert local and peer addresses. These may sometimes be invalid,
  // for example, a "relay" or "prflx" candidate from a relay connection
  // might have the IP address stripped away by WebRTC - see
  // http://crbug.com/1128667.
  if (!webrtc::SocketAddressToIPEndPoint(remote_candidate.address(),
                                         &route.remote_address)) {
    VLOG(0) << "Peer IP address is invalid.";
  }
  if (!webrtc::SocketAddressToIPEndPoint(local_candidate.address(),
                                         &route.local_address)) {
    VLOG(0) << "Local IP address is invalid.";
  }

  VLOG(0) << "Sending route-changed notification.";
  event_handler_->OnWebrtcTransportRouteChanged(route);
}

std::tuple<int, int> WebrtcTransport::BitratesForConnection() {
  int max_bitrate_bps = kMaxBitrateBps;
  if (connection_relayed_.value_or(false)) {
    int turn_max_rate_kbps = transport_context_->GetTurnMaxRateKbps();
    if (turn_max_rate_kbps <= 0) {
      VLOG(0) << "No TURN bitrate cap set.";
    } else {
      // Apply the TURN bitrate cap to prevent large amounts of packet loss.
      // The Google TURN/relay server limits the connection speed by dropping
      // packets, which may interact badly with WebRTC's bandwidth-estimation.
      VLOG(0) << "Capping bitrate to " << turn_max_rate_kbps << "kbps.";
      max_bitrate_bps = turn_max_rate_kbps * 1000;
    }
  }

  if (preferred_max_bitrate_bps_.has_value()) {
    if (*preferred_max_bitrate_bps_ >= 0 &&
        *preferred_max_bitrate_bps_ <= max_bitrate_bps) {
      VLOG(0) << "Client sets max bitrate to " << *preferred_max_bitrate_bps_
              << " bps.";
      max_bitrate_bps = *preferred_max_bitrate_bps_;
    } else {
      LOG(WARNING) << "Max bitrate setting  " << *preferred_max_bitrate_bps_
                   << " bps ignored since it's not in the range of "
                   << "[0, " << max_bitrate_bps << "].";
    }
  }

  int min_bitrate_bps = 0;
  if (preferred_min_bitrate_bps_.has_value()) {
    if (preferred_min_bitrate_bps_ >= 0 &&
        preferred_min_bitrate_bps_ <= max_bitrate_bps) {
      VLOG(0) << "Client sets min bitrate to " << *preferred_min_bitrate_bps_
              << " bps.";
      min_bitrate_bps = *preferred_min_bitrate_bps_;
    } else {
      LOG(WARNING) << "Min bitrate setting  " << *preferred_min_bitrate_bps_
                   << " bps ignored since it's not in the range of "
                   << "[0, " << max_bitrate_bps << "].";
    }
  }
  return {min_bitrate_bps, max_bitrate_bps};
}

void WebrtcTransport::UpdateBitrates() {
  auto [min_bitrate_bps, max_bitrate_bps] = BitratesForConnection();
  SetPeerConnectionBitrates(min_bitrate_bps, max_bitrate_bps);
  auto senders = peer_connection()->GetSenders();
  for (auto& sender : senders) {
    if (sender->media_type() == webrtc::MediaType::VIDEO) {
      SetSenderBitrates(sender, min_bitrate_bps, max_bitrate_bps);
    }
  }
}

void WebrtcTransport::SetPeerConnectionBitrates(int min_bitrate_bps,
                                                int max_bitrate_bps) {
  DCHECK_LE(min_bitrate_bps, max_bitrate_bps);
  webrtc::BitrateSettings bitrate;
  if (min_bitrate_bps > 0) {
    bitrate.min_bitrate_bps = min_bitrate_bps;
  } else {
    bitrate.min_bitrate_bps.reset();
  }
  bitrate.max_bitrate_bps = max_bitrate_bps;
  peer_connection()->SetBitrate(bitrate);
}

void WebrtcTransport::SetSenderBitrates(
    webrtc::scoped_refptr<webrtc::RtpSenderInterface> sender,
    int min_bitrate_bps,
    int max_bitrate_bps) {
  DCHECK_LE(min_bitrate_bps, max_bitrate_bps);
  webrtc::RtpParameters parameters = sender->GetParameters();
  if (parameters.encodings.empty()) {
    LOG(ERROR) << "No encodings found for sender " << sender->id();
    return;
  }

  if (parameters.encodings.size() != 1) {
    LOG(ERROR) << "Unexpected number of encodings ("
               << parameters.encodings.size() << ") for sender "
               << sender->id();
  }

  if (min_bitrate_bps > 0) {
    parameters.encodings[0].min_bitrate_bps = min_bitrate_bps;
  } else {
    parameters.encodings[0].min_bitrate_bps.reset();
  }
  parameters.encodings[0].max_bitrate_bps = max_bitrate_bps;

  SetSenderParameters(*sender, parameters);
}

void WebrtcTransport::RequestNegotiation() {
  DCHECK(transport_context_->role() == TransportRole::SERVER);

  if (!negotiation_pending_) {
    negotiation_pending_ = true;
    auto send_offer_cb =
        base::BindOnce(&WebrtcTransport::SendOffer, weak_factory_.GetWeakPtr());

    if (apply_network_settings_) {
      HOST_LOG << "SendOffer is delayed until network settings are applied.";
      apply_network_settings_ =
          std::move(apply_network_settings_).Then(std::move(send_offer_cb));
      return;
    }

    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, std::move(send_offer_cb));
  }
}

void WebrtcTransport::SendOffer() {
  DCHECK(transport_context_->role() == TransportRole::SERVER);

  DCHECK(negotiation_pending_);
  negotiation_pending_ = false;

  webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
  options.offer_to_receive_video = false;
  options.offer_to_receive_audio = false;
  options.ice_restart = want_ice_restart_;
  peer_connection()->CreateOffer(
      CreateSessionDescriptionObserver::Create(
          base::BindOnce(&WebrtcTransport::OnLocalSessionDescriptionCreated,
                         weak_factory_.GetWeakPtr())),
      options);
}

void WebrtcTransport::EnsurePendingTransportInfoMessage() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  // |transport_info_timer_| must be running iff
  // |pending_transport_info_message_| exists.
  DCHECK_EQ(pending_transport_info_message_ != nullptr,
            transport_info_timer_.IsRunning());

  if (!pending_transport_info_message_) {
    pending_transport_info_message_ = std::make_unique<XmlElement>(
        QName(kTransportNamespace, "transport"), true);

    // Delay sending the new candidates in case we get more candidates
    // that we can send in one message.
    transport_info_timer_.Start(FROM_HERE,
                                base::Milliseconds(kTransportInfoSendDelayMs),
                                this, &WebrtcTransport::SendTransportInfo);
  }
}

void WebrtcTransport::SendTransportInfo() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(pending_transport_info_message_);

  send_transport_info_callback_.Run(std::move(pending_transport_info_message_));
}

void WebrtcTransport::AddPendingCandidatesIfPossible() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (peer_connection()->signaling_state() ==
      webrtc::PeerConnectionInterface::kStable) {
    for (const auto& candidate : pending_incoming_candidates_) {
      if (!peer_connection()->AddIceCandidate(candidate.get())) {
        Close(ErrorCode::CHANNEL_CONNECTION_ERROR,
              "Failed to add incoming candidate", FROM_HERE);
        return;
      }
    }
    pending_incoming_candidates_.clear();
  }
}

void WebrtcTransport::StartRtcEventLogging() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!peer_connection()) {
    return;
  }

  // Start recording into |rtc_event_log_|. This is safe because, when |this| is
  // destroyed, it calls Close() which stops recording the RTC event log.
  rtc_event_log_.Clear();
  peer_connection()->StartRtcEventLog(
      std::make_unique<RtcEventLogOutput>(rtc_event_log_));
}

void WebrtcTransport::StopRtcEventLogging() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (peer_connection()) {
    ScopedAllowThreadJoinForWebRtcTransport allow_wait;
    peer_connection()->StopRtcEventLog();
  }
}

}  // namespace remoting::protocol