File: webrtc_connection_to_client.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 (322 lines) | stat: -rw-r--r-- 11,402 bytes parent folder | download | duplicates (5)
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
// 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_connection_to_client.h"

#include <utility>

#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_runner.h"
#include "components/webrtc/thread_wrapper.h"
#include "net/base/io_buffer.h"
#include "remoting/base/logging.h"
#include "remoting/codec/video_encoder.h"
#include "remoting/codec/webrtc_video_encoder_vpx.h"
#include "remoting/protocol/audio_source.h"
#include "remoting/protocol/audio_stream.h"
#include "remoting/protocol/authenticator.h"
#include "remoting/protocol/clipboard_stub.h"
#include "remoting/protocol/desktop_capturer.h"
#include "remoting/protocol/host_control_dispatcher.h"
#include "remoting/protocol/host_event_dispatcher.h"
#include "remoting/protocol/host_stub.h"
#include "remoting/protocol/input_stub.h"
#include "remoting/protocol/message_pipe.h"
#include "remoting/protocol/transport_context.h"
#include "remoting/protocol/webrtc_audio_stream.h"
#include "remoting/protocol/webrtc_transport.h"
#include "remoting/protocol/webrtc_video_encoder_factory.h"
#include "remoting/protocol/webrtc_video_stream.h"
#include "third_party/webrtc/api/media_stream_interface.h"
#include "third_party/webrtc/api/peer_connection_interface.h"
#include "third_party/webrtc/api/sctp_transport_interface.h"

namespace remoting::protocol {

namespace {

const char kVideoStatsStreamLabel[] = "screen_stream";

}  // namespace

// Currently the network thread is also used as the worker thread for webrtc.
//
// TODO(sergeyu): Figure out if we would benefit from using a separate thread as
// a worker thread.
WebrtcConnectionToClient::WebrtcConnectionToClient(
    std::unique_ptr<protocol::Session> session,
    scoped_refptr<protocol::TransportContext> transport_context,
    scoped_refptr<base::SingleThreadTaskRunner> audio_task_runner)
    : session_(std::move(session)),
      video_stats_dispatcher_(kVideoStatsStreamLabel),
      audio_task_runner_(audio_task_runner),
      control_dispatcher_(new HostControlDispatcher()),
      event_dispatcher_(new HostEventDispatcher()) {
  auto video_encoder_factory = std::make_unique<WebrtcVideoEncoderFactory>();
  video_encoder_factory_ = video_encoder_factory.get();
  transport_ = std::make_unique<WebrtcTransport>(
      webrtc::ThreadWrapper::current(), transport_context,
      std::move(video_encoder_factory), this);
  session_->SetEventHandler(this);
  session_->SetTransport(transport_.get());
}

WebrtcConnectionToClient::~WebrtcConnectionToClient() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
}

void WebrtcConnectionToClient::SetEventHandler(
    ConnectionToClient::EventHandler* event_handler) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  event_handler_ = event_handler;
}

protocol::Session* WebrtcConnectionToClient::session() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return session_.get();
}

void WebrtcConnectionToClient::Disconnect(
    ErrorCode error,
    std::string_view error_details,
    const SourceLocation& error_location) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  // This should trigger OnConnectionClosed() event and this object
  // may be destroyed as the result.
  session_->Close(error, error_details, error_location);
}

std::unique_ptr<VideoStream> WebrtcConnectionToClient::StartVideoStream(
    webrtc::ScreenId screen_id,
    std::unique_ptr<DesktopCapturer> desktop_capturer) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(transport_);

  auto stream = std::make_unique<WebrtcVideoStream>(session_options_);
  stream->set_video_stats_dispatcher(video_stats_dispatcher_.GetWeakPtr());
  stream->Start(screen_id, std::move(desktop_capturer), transport_.get(),
                video_encoder_factory_);
  stream->SetEventTimestampsSource(
      event_dispatcher_->event_timestamps_source());
  return std::move(stream);
}

std::unique_ptr<AudioStream> WebrtcConnectionToClient::StartAudioStream(
    std::unique_ptr<AudioSource> audio_source) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(transport_);

  std::unique_ptr<WebrtcAudioStream> stream(new WebrtcAudioStream());
  stream->Start(audio_task_runner_, std::move(audio_source), transport_.get());
  return std::move(stream);
}

// Return pointer to ClientStub.
ClientStub* WebrtcConnectionToClient::client_stub() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return control_dispatcher_.get();
}

void WebrtcConnectionToClient::set_clipboard_stub(
    protocol::ClipboardStub* clipboard_stub) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  control_dispatcher_->set_clipboard_stub(clipboard_stub);
}

void WebrtcConnectionToClient::set_host_stub(protocol::HostStub* host_stub) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  control_dispatcher_->set_host_stub(host_stub);
}

void WebrtcConnectionToClient::set_input_stub(protocol::InputStub* input_stub) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  event_dispatcher_->set_input_stub(input_stub);
}

void WebrtcConnectionToClient::ApplySessionOptions(
    const SessionOptions& options) {
  session_options_ = options;
  transport_->ApplySessionOptions(options);
  video_encoder_factory_->ApplySessionOptions(options);
}

void WebrtcConnectionToClient::ApplyNetworkSettings(
    const NetworkSettings& settings) {
  transport_->ApplyNetworkSettings(settings);
}

PeerConnectionControls* WebrtcConnectionToClient::peer_connection_controls() {
  return transport_.get();
}

WebrtcEventLogData* WebrtcConnectionToClient::rtc_event_log() {
  return transport_->rtc_event_log();
}

void WebrtcConnectionToClient::OnSessionStateChange(Session::State state) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  DCHECK(event_handler_);
  switch (state) {
    case Session::INITIALIZING:
    case Session::CONNECTING:
    case Session::ACCEPTING:
    case Session::ACCEPTED:
      // Don't care about these events.
      break;

    case Session::AUTHENTICATING:
      event_handler_->OnConnectionAuthenticating();
      break;

    case Session::AUTHENTICATED: {
      base::WeakPtr<WebrtcConnectionToClient> self = weak_factory_.GetWeakPtr();
      event_handler_->OnConnectionAuthenticated(
          session_->authenticator().GetSessionPolicies());

      // OnConnectionAuthenticated() call above may result in the connection
      // being torn down.
      if (self) {
        event_handler_->CreateMediaStreams();
      }
      break;
    }

    case Session::CLOSED:
    case Session::FAILED:
      control_dispatcher_.reset();
      event_dispatcher_.reset();
      transport_->Close(
          state == Session::CLOSED ? ErrorCode::OK : session_->error(),
          /* error_details= */ {}, FROM_HERE);
      transport_.reset();
      event_handler_->OnConnectionClosed(
          state == Session::CLOSED ? ErrorCode::OK : session_->error());
      break;
  }
}

void WebrtcConnectionToClient::OnWebrtcTransportConnecting() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  // Create outgoing control channel. |event_dispatcher_| is initialized later
  // because event channel is expected to be created by the client.
  control_dispatcher_->Init(
      transport_->CreateOutgoingChannel(control_dispatcher_->channel_name()),
      this);

  // Create channel for sending per-frame statistics. The video-stream will
  // only try to send any stats after this channel is connected.
  video_stats_dispatcher_.Init(
      transport_->CreateOutgoingChannel(video_stats_dispatcher_.channel_name()),
      this);
}

void WebrtcConnectionToClient::OnWebrtcTransportConnected() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  auto sctp_transport = transport_->peer_connection()->GetSctpTransport();
  if (sctp_transport) {
    std::optional<double> max_message_size =
        sctp_transport->Information().MaxMessageSize();
    if (max_message_size && *max_message_size > 0) {
      control_dispatcher_->set_max_message_size(*max_message_size);
    }
  }
}

void WebrtcConnectionToClient::OnWebrtcTransportError(
    ErrorCode error,
    std::string_view error_details,
    const base::Location& error_location) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  Disconnect(error, error_details, error_location);
}

void WebrtcConnectionToClient::OnWebrtcTransportProtocolChanged() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  // If not all channels are connected, this call will be deferred to
  // OnChannelInitialized() when all channels are connected.
  if (allChannelsConnected()) {
    event_handler_->OnTransportProtocolChange(transport_->transport_protocol());
  }
}

void WebrtcConnectionToClient::OnWebrtcTransportIncomingDataChannel(
    const std::string& name,
    std::unique_ptr<MessagePipe> pipe) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(event_handler_);

  if (name == event_dispatcher_->channel_name() &&
      !event_dispatcher_->is_connected()) {
    event_dispatcher_->Init(std::move(pipe), this);
    return;
  }

  event_handler_->OnIncomingDataChannel(name, std::move(pipe));
}

void WebrtcConnectionToClient::OnWebrtcTransportMediaStreamAdded(
    webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  LOG(WARNING) << "The client created an unexpected media stream.";
}

void WebrtcConnectionToClient::OnWebrtcTransportMediaStreamRemoved(
    webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
}

void WebrtcConnectionToClient::OnWebrtcTransportRouteChanged(
    const TransportRoute& route) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  DCHECK(event_handler_);

  // WebRTC route-change events are triggered at the transport level, so the
  // channel name is not meaningful here.
  std::string channel_name;
  event_handler_->OnRouteChange(channel_name, route);
}

void WebrtcConnectionToClient::OnChannelInitialized(
    ChannelDispatcherBase* channel_dispatcher) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (allChannelsConnected()) {
    event_handler_->OnConnectionChannelsConnected();
    if (!transport_->transport_protocol().empty()) {
      event_handler_->OnTransportProtocolChange(
          transport_->transport_protocol());
    }
  }
}

void WebrtcConnectionToClient::OnChannelClosed(
    ChannelDispatcherBase* channel_dispatcher) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (channel_dispatcher == &video_stats_dispatcher_) {
    HOST_LOG << "video_stats channel was closed.";
    return;
  }

  // The control channel is closed when the user clicks disconnect on the client
  // or the client page is closed normally. If the client goes offline then the
  // channel will remain open. Hence it should be safe to report ErrorCode::OK
  // here.
  std::string details = base::StringPrintf(
      "Channel %s was closed.", channel_dispatcher->channel_name().c_str());
  HOST_LOG << details;
  Disconnect(ErrorCode::OK, details, FROM_HERE);
}

bool WebrtcConnectionToClient::allChannelsConnected() {
  return control_dispatcher_ && control_dispatcher_->is_connected() &&
         event_dispatcher_ && event_dispatcher_->is_connected();
}

}  // namespace remoting::protocol