summaryrefslogtreecommitdiffstats
path: root/remoting/client/chromoting_client.cc
blob: ff926a2402d3d2814722477a2150ba821e12e5da (plain)
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
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/client/chromoting_client.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "remoting/base/logger.h"
#include "remoting/base/tracer.h"
#include "remoting/client/chromoting_view.h"
#include "remoting/client/client_context.h"
#include "remoting/client/input_handler.h"
#include "remoting/client/rectangle_update_decoder.h"
#include "remoting/protocol/connection_to_host.h"
#include "remoting/protocol/session_config.h"

namespace remoting {

ChromotingClient::ChromotingClient(const ClientConfig& config,
                                   ClientContext* context,
                                   protocol::ConnectionToHost* connection,
                                   ChromotingView* view,
                                   RectangleUpdateDecoder* rectangle_decoder,
                                   InputHandler* input_handler,
                                   Logger* logger,
                                   Task* client_done)
    : config_(config),
      context_(context),
      connection_(connection),
      view_(view),
      rectangle_decoder_(rectangle_decoder),
      input_handler_(input_handler),
      logger_(logger),
      client_done_(client_done),
      state_(CREATED),
      packet_being_processed_(false),
      last_sequence_number_(0) {
}

ChromotingClient::~ChromotingClient() {
}

void ChromotingClient::Start(scoped_refptr<XmppProxy> xmpp_proxy) {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewRunnableMethod(this, &ChromotingClient::Start, xmpp_proxy));
    return;
  }

  connection_->Connect(xmpp_proxy, config_.local_jid, config_.host_jid,
                       config_.host_public_key, config_.access_code,
                       this, this, this);

  if (!view_->Initialize()) {
    ClientDone();
  }
}

void ChromotingClient::Stop(const base::Closure& shutdown_task) {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE, base::Bind(&ChromotingClient::Stop,
                              base::Unretained(this), shutdown_task));
    return;
  }

  connection_->Disconnect(base::Bind(&ChromotingClient::OnDisconnected,
                                     base::Unretained(this), shutdown_task));
}

void ChromotingClient::OnDisconnected(const base::Closure& shutdown_task) {
  view_->TearDown();

  shutdown_task.Run();
}

void ChromotingClient::ClientDone() {
  if (client_done_ != NULL) {
    message_loop()->PostTask(FROM_HERE, client_done_);
  }
}

ChromotingStats* ChromotingClient::GetStats() {
  return &stats_;
}

void ChromotingClient::Repaint() {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewRunnableMethod(this, &ChromotingClient::Repaint));
    return;
  }

  view_->Paint();
}

void ChromotingClient::SetViewport(int x, int y, int width, int height) {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewRunnableMethod(this, &ChromotingClient::SetViewport,
                          x, y, width, height));
    return;
  }

  view_->SetViewport(x, y, width, height);
}

void ChromotingClient::ProcessVideoPacket(const VideoPacket* packet,
                                          Task* done) {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewRunnableMethod(this, &ChromotingClient::ProcessVideoPacket,
                          packet, done));
    return;
  }

  // Record size of the packet for statistics.
  stats_.video_bandwidth()->Record(packet->data().size());

  // Record statistics received from host.
  if (packet->has_capture_time_ms())
    stats_.video_capture_ms()->Record(packet->capture_time_ms());
  if (packet->has_encode_time_ms())
    stats_.video_encode_ms()->Record(packet->encode_time_ms());
  if (packet->has_client_sequence_number() &&
      packet->client_sequence_number() > last_sequence_number_) {
    last_sequence_number_ = packet->client_sequence_number();
    base::TimeDelta round_trip_latency =
        base::Time::Now() -
        base::Time::FromInternalValue(packet->client_sequence_number());
    stats_.round_trip_ms()->Record(round_trip_latency.InMilliseconds());
  }

  received_packets_.push_back(QueuedVideoPacket(packet, done));
  if (!packet_being_processed_)
    DispatchPacket();
}

int ChromotingClient::GetPendingPackets() {
  return received_packets_.size();
}

void ChromotingClient::DispatchPacket() {
  DCHECK_EQ(message_loop(), MessageLoop::current());
  CHECK(!packet_being_processed_);

  if (received_packets_.empty()) {
    // Nothing to do!
    return;
  }

  const VideoPacket* packet = received_packets_.front().packet;
  packet_being_processed_ = true;

  ScopedTracer tracer("Handle video packet");

  // Measure the latency between the last packet being received and presented.
  bool last_packet = (packet->flags() & VideoPacket::LAST_PACKET) != 0;
  base::Time decode_start;
  if (last_packet)
    decode_start = base::Time::Now();

  rectangle_decoder_->DecodePacket(
      packet, NewTracedMethod(this, &ChromotingClient::OnPacketDone,
                              last_packet, decode_start));
}

void ChromotingClient::OnConnectionOpened(protocol::ConnectionToHost* conn) {
  logger_->VLog(1, "ChromotingClient::OnConnectionOpened");
  Initialize();
  SetConnectionState(CONNECTED);
}

void ChromotingClient::OnConnectionClosed(protocol::ConnectionToHost* conn) {
  logger_->VLog(1, "ChromotingClient::OnConnectionClosed");
  SetConnectionState(DISCONNECTED);
}

void ChromotingClient::OnConnectionFailed(protocol::ConnectionToHost* conn) {
  logger_->VLog(1, "ChromotingClient::OnConnectionFailed");
  SetConnectionState(FAILED);
}

MessageLoop* ChromotingClient::message_loop() {
  return context_->jingle_thread()->message_loop();
}

void ChromotingClient::SetConnectionState(ConnectionState s) {
  // TODO(ajwong): We actually may want state to be a shared variable. Think
  // through later.
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewRunnableMethod(this, &ChromotingClient::SetConnectionState, s));
    return;
  }

  state_ = s;
  view_->SetConnectionState(s);

  Repaint();
}

void ChromotingClient::OnPacketDone(bool last_packet,
                                    base::Time decode_start) {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewTracedMethod(this, &ChromotingClient::OnPacketDone,
                        last_packet, decode_start));
    return;
  }

  TraceContext::tracer()->PrintString("Packet done");

  // Record the latency between the final packet being received and
  // presented.
  if (last_packet) {
    stats_.video_decode_ms()->Record(
        (base::Time::Now() - decode_start).InMilliseconds());
  }

  received_packets_.front().done->Run();
  delete received_packets_.front().done;
  received_packets_.pop_front();

  packet_being_processed_ = false;

  // Process the next video packet.
  DispatchPacket();
}

void ChromotingClient::Initialize() {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewTracedMethod(this, &ChromotingClient::Initialize));
    return;
  }

  TraceContext::tracer()->PrintString("Initializing client.");

  const protocol::SessionConfig* config = connection_->config();

  // Resize the window.
  int width = config->initial_resolution().width;
  int height = config->initial_resolution().height;
  logger_->VLog(1, "Initial screen geometry: %dx%d", width, height);

  // TODO(ajwong): What to do here?  Does the decoder actually need to request
  // the right frame size?  This is mainly an optimization right?
  // rectangle_decoder_->SetOutputFrameSize(width, height);
  view_->SetViewport(0, 0, width, height);

  // Initialize the decoder.
  rectangle_decoder_->Initialize(config);

  // Schedule the input handler to process the event queue.
  input_handler_->Initialize();
}

////////////////////////////////////////////////////////////////////////////
// ClientStub control channel interface.
void ChromotingClient::NotifyResolution(
    const protocol::NotifyResolutionRequest* msg, Task* done) {
  logger_->Log(logging::LOG_INFO, "NotifyResolution change");
  NOTIMPLEMENTED();
  done->Run();
  delete done;
}

void ChromotingClient::BeginSessionResponse(
    const protocol::LocalLoginStatus* msg, Task* done) {
  if (message_loop() != MessageLoop::current()) {
    message_loop()->PostTask(
        FROM_HERE,
        NewRunnableMethod(this, &ChromotingClient::BeginSessionResponse,
                          msg, done));
    return;
  }

  logger_->Log(logging::LOG_INFO, "BeginSessionResponse received");

  // Inform the connection that the client has been authenticated. This will
  // enable the communication channels.
  if (msg->success()) {
    connection_->OnClientAuthenticated();
  }

  view_->UpdateLoginStatus(msg->success(), msg->error_info());
  done->Run();
  delete done;
}

}  // namespace remoting