Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / remoting / test / protocol_perftest.cc
bloba87f315d3cd1e3e2630df37b5b9a33ea06cc3298
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/base64.h"
6 #include "base/files/file_util.h"
7 #include "base/message_loop/message_loop.h"
8 #include "base/rand_util.h"
9 #include "base/run_loop.h"
10 #include "base/single_thread_task_runner.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "jingle/glue/thread_wrapper.h"
14 #include "net/base/test_data_directory.h"
15 #include "net/url_request/url_request_context_getter.h"
16 #include "remoting/base/rsa_key_pair.h"
17 #include "remoting/client/audio_player.h"
18 #include "remoting/client/chromoting_client.h"
19 #include "remoting/client/client_context.h"
20 #include "remoting/client/client_user_interface.h"
21 #include "remoting/client/video_renderer.h"
22 #include "remoting/host/chromoting_host.h"
23 #include "remoting/host/chromoting_host_context.h"
24 #include "remoting/host/fake_desktop_environment.h"
25 #include "remoting/host/video_frame_pump.h"
26 #include "remoting/protocol/jingle_session_manager.h"
27 #include "remoting/protocol/libjingle_transport_factory.h"
28 #include "remoting/protocol/me2me_host_authenticator_factory.h"
29 #include "remoting/protocol/negotiating_client_authenticator.h"
30 #include "remoting/protocol/session_config.h"
31 #include "remoting/signaling/fake_signal_strategy.h"
32 #include "remoting/test/fake_network_dispatcher.h"
33 #include "remoting/test/fake_port_allocator.h"
34 #include "remoting/test/fake_socket_factory.h"
35 #include "testing/gtest/include/gtest/gtest.h"
37 namespace remoting {
39 using protocol::ChannelConfig;
41 const char kHostJid[] = "host_jid@example.com/host";
42 const char kHostOwner[] = "jane.doe@example.com";
43 const char kClientJid[] = "jane.doe@example.com/client";
45 struct NetworkPerformanceParams {
46 NetworkPerformanceParams(int bandwidth,
47 int max_buffers,
48 double latency_average_ms,
49 double latency_stddev_ms,
50 double out_of_order_rate)
51 : bandwidth(bandwidth),
52 max_buffers(max_buffers),
53 latency_average(base::TimeDelta::FromMillisecondsD(latency_average_ms)),
54 latency_stddev(base::TimeDelta::FromMillisecondsD(latency_stddev_ms)),
55 out_of_order_rate(out_of_order_rate) {}
57 int bandwidth;
58 int max_buffers;
59 base::TimeDelta latency_average;
60 base::TimeDelta latency_stddev;
61 double out_of_order_rate;
64 class FakeCursorShapeStub : public protocol::CursorShapeStub {
65 public:
66 FakeCursorShapeStub() {}
67 ~FakeCursorShapeStub() override {}
69 // protocol::CursorShapeStub interface.
70 void SetCursorShape(const protocol::CursorShapeInfo& cursor_shape) override{};
73 class ProtocolPerfTest
74 : public testing::Test,
75 public testing::WithParamInterface<NetworkPerformanceParams>,
76 public ClientUserInterface,
77 public VideoRenderer,
78 public protocol::VideoStub,
79 public HostStatusObserver {
80 public:
81 ProtocolPerfTest()
82 : host_thread_("host"),
83 capture_thread_("capture"),
84 encode_thread_("encode") {
85 VideoFramePump::EnableTimestampsForTests();
86 host_thread_.StartWithOptions(
87 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
88 capture_thread_.Start();
89 encode_thread_.Start();
92 virtual ~ProtocolPerfTest() {
93 host_thread_.task_runner()->DeleteSoon(FROM_HERE, host_.release());
94 host_thread_.task_runner()->DeleteSoon(FROM_HERE,
95 host_signaling_.release());
96 message_loop_.RunUntilIdle();
99 // ClientUserInterface interface.
100 void OnConnectionState(protocol::ConnectionToHost::State state,
101 protocol::ErrorCode error) override {
102 if (state == protocol::ConnectionToHost::CONNECTED) {
103 client_connected_ = true;
104 if (host_connected_)
105 connecting_loop_->Quit();
108 void OnConnectionReady(bool ready) override {}
109 void OnRouteChanged(const std::string& channel_name,
110 const protocol::TransportRoute& route) override {}
111 void SetCapabilities(const std::string& capabilities) override {}
112 void SetPairingResponse(
113 const protocol::PairingResponse& pairing_response) override {}
114 void DeliverHostMessage(const protocol::ExtensionMessage& message) override {}
115 protocol::ClipboardStub* GetClipboardStub() override { return nullptr; }
116 protocol::CursorShapeStub* GetCursorShapeStub() override {
117 return &cursor_shape_stub_;
120 // VideoRenderer interface.
121 void OnSessionConfig(const protocol::SessionConfig& config) override {}
122 protocol::VideoStub* GetVideoStub() override { return this; }
124 // protocol::VideoStub interface.
125 void ProcessVideoPacket(scoped_ptr<VideoPacket> video_packet,
126 const base::Closure& done) override {
127 if (video_packet->data().empty()) {
128 // Ignore keep-alive packets
129 done.Run();
130 return;
133 last_video_packet_ = video_packet.Pass();
135 if (!on_frame_task_.is_null())
136 on_frame_task_.Run();
138 done.Run();
141 // HostStatusObserver interface.
142 void OnClientConnected(const std::string& jid) override {
143 message_loop_.PostTask(
144 FROM_HERE,
145 base::Bind(&ProtocolPerfTest::OnHostConnectedMainThread,
146 base::Unretained(this)));
149 protected:
150 void WaitConnected() {
151 client_connected_ = false;
152 host_connected_ = false;
154 connecting_loop_.reset(new base::RunLoop());
155 connecting_loop_->Run();
157 ASSERT_TRUE(client_connected_ && host_connected_);
160 void OnHostConnectedMainThread() {
161 host_connected_ = true;
162 if (client_connected_)
163 connecting_loop_->Quit();
166 void ReceiveFrame(base::TimeDelta* latency) {
167 waiting_frames_loop_.reset(new base::RunLoop());
168 on_frame_task_ = waiting_frames_loop_->QuitClosure();
169 waiting_frames_loop_->Run();
171 if (latency) {
172 base::TimeTicks timestamp =
173 base::TimeTicks::FromInternalValue(last_video_packet_->timestamp());
174 *latency = base::TimeTicks::Now() - timestamp;
178 void ReceiveFrames(int frames, base::TimeDelta* max_latency) {
179 if (max_latency)
180 *max_latency = base::TimeDelta();
182 for (int i = 0; i < frames; ++i) {
183 base::TimeDelta latency;
185 ReceiveFrame(&latency);
187 if (max_latency && latency > *max_latency) {
188 *max_latency = latency;
193 // Creates test host and client and starts connection between them. Caller
194 // should call WaitConnected() to wait until connection is established. The
195 // host is started on |host_thread_| while the client works on the main
196 // thread.
197 void StartHostAndClient(protocol::ChannelConfig::Codec video_codec) {
198 fake_network_dispatcher_ = new FakeNetworkDispatcher();
200 client_signaling_.reset(new FakeSignalStrategy(kClientJid));
202 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
204 protocol_config_ = protocol::CandidateSessionConfig::CreateDefault();
205 protocol_config_->DisableAudioChannel();
206 protocol_config_->mutable_video_configs()->clear();
207 protocol_config_->mutable_video_configs()->push_back(
208 protocol::ChannelConfig(
209 protocol::ChannelConfig::TRANSPORT_STREAM, 2, video_codec));
211 host_thread_.task_runner()->PostTask(
212 FROM_HERE,
213 base::Bind(&ProtocolPerfTest::StartHost, base::Unretained(this)));
216 void StartHost() {
217 DCHECK(host_thread_.task_runner()->BelongsToCurrentThread());
219 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
221 host_signaling_.reset(new FakeSignalStrategy(kHostJid));
222 host_signaling_->ConnectTo(client_signaling_.get());
224 protocol::NetworkSettings network_settings(
225 protocol::NetworkSettings::NAT_TRAVERSAL_OUTGOING);
227 scoped_ptr<FakePortAllocator> port_allocator(
228 FakePortAllocator::Create(fake_network_dispatcher_));
229 port_allocator->socket_factory()->SetBandwidth(GetParam().bandwidth,
230 GetParam().max_buffers);
231 port_allocator->socket_factory()->SetLatency(GetParam().latency_average,
232 GetParam().latency_stddev);
233 port_allocator->socket_factory()->set_out_of_order_rate(
234 GetParam().out_of_order_rate);
235 scoped_ptr<protocol::TransportFactory> host_transport_factory(
236 new protocol::LibjingleTransportFactory(
237 host_signaling_.get(), port_allocator.Pass(), network_settings,
238 protocol::TransportRole::SERVER));
240 scoped_ptr<protocol::SessionManager> session_manager(
241 new protocol::JingleSessionManager(host_transport_factory.Pass()));
242 session_manager->set_protocol_config(protocol_config_->Clone());
244 // Encoder runs on a separate thread, main thread is used for everything
245 // else.
246 host_.reset(new ChromotingHost(host_signaling_.get(),
247 &desktop_environment_factory_,
248 session_manager.Pass(),
249 host_thread_.task_runner(),
250 host_thread_.task_runner(),
251 capture_thread_.task_runner(),
252 encode_thread_.task_runner(),
253 host_thread_.task_runner(),
254 host_thread_.task_runner()));
256 base::FilePath certs_dir(net::GetTestCertsDirectory());
258 std::string host_cert;
259 ASSERT_TRUE(base::ReadFileToString(
260 certs_dir.AppendASCII("unittest.selfsigned.der"), &host_cert));
262 base::FilePath key_path = certs_dir.AppendASCII("unittest.key.bin");
263 std::string key_string;
264 ASSERT_TRUE(base::ReadFileToString(key_path, &key_string));
265 std::string key_base64;
266 base::Base64Encode(key_string, &key_base64);
267 scoped_refptr<RsaKeyPair> key_pair = RsaKeyPair::FromString(key_base64);
268 ASSERT_TRUE(key_pair.get());
271 protocol::SharedSecretHash host_secret;
272 host_secret.hash_function = protocol::AuthenticationMethod::NONE;
273 host_secret.value = "123456";
274 scoped_ptr<protocol::AuthenticatorFactory> auth_factory =
275 protocol::Me2MeHostAuthenticatorFactory::CreateWithSharedSecret(
276 true, kHostOwner, host_cert, key_pair, host_secret, nullptr);
277 host_->SetAuthenticatorFactory(auth_factory.Pass());
279 host_->AddStatusObserver(this);
280 host_->Start(kHostOwner);
282 message_loop_.PostTask(FROM_HERE,
283 base::Bind(&ProtocolPerfTest::StartClientAfterHost,
284 base::Unretained(this)));
287 void StartClientAfterHost() {
288 client_signaling_->ConnectTo(host_signaling_.get());
290 protocol::NetworkSettings network_settings(
291 protocol::NetworkSettings::NAT_TRAVERSAL_OUTGOING);
293 // Initialize client.
294 client_context_.reset(
295 new ClientContext(base::ThreadTaskRunnerHandle::Get()));
297 scoped_ptr<FakePortAllocator> port_allocator(
298 FakePortAllocator::Create(fake_network_dispatcher_));
299 port_allocator->socket_factory()->SetBandwidth(GetParam().bandwidth,
300 GetParam().max_buffers);
301 port_allocator->socket_factory()->SetLatency(GetParam().latency_average,
302 GetParam().latency_stddev);
303 port_allocator->socket_factory()->set_out_of_order_rate(
304 GetParam().out_of_order_rate);
305 scoped_ptr<protocol::TransportFactory> client_transport_factory(
306 new protocol::LibjingleTransportFactory(
307 client_signaling_.get(), port_allocator.Pass(), network_settings,
308 protocol::TransportRole::CLIENT));
310 std::vector<protocol::AuthenticationMethod> auth_methods;
311 auth_methods.push_back(protocol::AuthenticationMethod::Spake2(
312 protocol::AuthenticationMethod::NONE));
313 scoped_ptr<protocol::Authenticator> client_authenticator(
314 new protocol::NegotiatingClientAuthenticator(
315 std::string(), // client_pairing_id
316 std::string(), // client_pairing_secret
317 std::string(), // authentication_tag
318 base::Bind(&ProtocolPerfTest::FetchPin, base::Unretained(this)),
319 nullptr,
320 auth_methods));
321 client_.reset(
322 new ChromotingClient(client_context_.get(), this, this, nullptr));
323 client_->set_protocol_config(protocol_config_->Clone());
324 client_->Start(client_signaling_.get(), client_authenticator.Pass(),
325 client_transport_factory.Pass(), kHostJid, std::string());
328 void FetchPin(
329 bool pairing_supported,
330 const protocol::SecretFetchedCallback& secret_fetched_callback) {
331 secret_fetched_callback.Run("123456");
334 base::MessageLoopForIO message_loop_;
336 scoped_refptr<FakeNetworkDispatcher> fake_network_dispatcher_;
338 base::Thread host_thread_;
339 base::Thread capture_thread_;
340 base::Thread encode_thread_;
341 FakeDesktopEnvironmentFactory desktop_environment_factory_;
343 FakeCursorShapeStub cursor_shape_stub_;
345 scoped_ptr<protocol::CandidateSessionConfig> protocol_config_;
347 scoped_ptr<FakeSignalStrategy> host_signaling_;
348 scoped_ptr<FakeSignalStrategy> client_signaling_;
350 scoped_ptr<ChromotingHost> host_;
351 scoped_ptr<ClientContext> client_context_;
352 scoped_ptr<ChromotingClient> client_;
354 scoped_ptr<base::RunLoop> connecting_loop_;
355 scoped_ptr<base::RunLoop> waiting_frames_loop_;
357 bool client_connected_;
358 bool host_connected_;
360 base::Closure on_frame_task_;
362 scoped_ptr<VideoPacket> last_video_packet_;
364 private:
365 DISALLOW_COPY_AND_ASSIGN(ProtocolPerfTest);
368 INSTANTIATE_TEST_CASE_P(
369 NoDelay,
370 ProtocolPerfTest,
371 ::testing::Values(NetworkPerformanceParams(0, 0, 0, 0, 0.0)));
373 INSTANTIATE_TEST_CASE_P(
374 HighLatency,
375 ProtocolPerfTest,
376 ::testing::Values(NetworkPerformanceParams(0, 0, 300, 30, 0.0),
377 NetworkPerformanceParams(0, 0, 30, 10, 0.0)));
379 INSTANTIATE_TEST_CASE_P(
380 OutOfOrder,
381 ProtocolPerfTest,
382 ::testing::Values(NetworkPerformanceParams(0, 0, 2, 0, 0.01),
383 NetworkPerformanceParams(0, 0, 30, 1, 0.01),
384 NetworkPerformanceParams(0, 0, 30, 1, 0.1),
385 NetworkPerformanceParams(0, 0, 300, 20, 0.01),
386 NetworkPerformanceParams(0, 0, 300, 20, 0.1)));
388 INSTANTIATE_TEST_CASE_P(
389 LimitedBandwidth,
390 ProtocolPerfTest,
391 ::testing::Values(
392 // 100 MBps
393 NetworkPerformanceParams(800000000, 800000000, 2, 1, 0.0),
394 // 8 MBps
395 NetworkPerformanceParams(1000000, 300000, 30, 5, 0.01),
396 NetworkPerformanceParams(1000000, 2000000, 30, 5, 0.01),
397 // 800 kBps
398 NetworkPerformanceParams(100000, 30000, 130, 5, 0.01),
399 NetworkPerformanceParams(100000, 200000, 130, 5, 0.01)));
401 TEST_P(ProtocolPerfTest, StreamFrameRate) {
402 StartHostAndClient(protocol::ChannelConfig::CODEC_VP8);
403 ASSERT_NO_FATAL_FAILURE(WaitConnected());
405 base::TimeDelta latency;
407 ReceiveFrame(&latency);
408 LOG(INFO) << "First frame latency: " << latency.InMillisecondsF() << "ms";
409 ReceiveFrames(20, nullptr);
411 base::TimeTicks started = base::TimeTicks::Now();
412 ReceiveFrames(40, &latency);
413 base::TimeDelta elapsed = base::TimeTicks::Now() - started;
414 LOG(INFO) << "Frame rate: " << (40.0 / elapsed.InSecondsF());
415 LOG(INFO) << "Maximum latency: " << latency.InMillisecondsF() << "ms";
418 const int kIntermittentFrameSize = 100 * 1000;
420 // Frame generator that rewrites the whole screen every 60th frame. Should only
421 // be used with the VERBATIM codec as the allocated frame may contain arbitrary
422 // data.
423 class IntermittentChangeFrameGenerator
424 : public base::RefCountedThreadSafe<IntermittentChangeFrameGenerator> {
425 public:
426 IntermittentChangeFrameGenerator()
427 : frame_index_(0) {}
429 scoped_ptr<webrtc::DesktopFrame> GenerateFrame(
430 webrtc::DesktopCapturer::Callback* callback) {
431 const int kWidth = 1000;
432 const int kHeight = kIntermittentFrameSize / kWidth / 4;
434 bool fresh_frame = false;
435 if (frame_index_ % 60 == 0 || !current_frame_) {
436 current_frame_.reset(webrtc::SharedDesktopFrame::Wrap(
437 new webrtc::BasicDesktopFrame(webrtc::DesktopSize(kWidth, kHeight))));
438 fresh_frame = true;
440 ++frame_index_;
442 scoped_ptr<webrtc::DesktopFrame> result(current_frame_->Share());
443 result->mutable_updated_region()->Clear();
444 if (fresh_frame) {
445 result->mutable_updated_region()->AddRect(
446 webrtc::DesktopRect::MakeXYWH(0, 0, kWidth, kHeight));
448 return result.Pass();
451 private:
452 ~IntermittentChangeFrameGenerator() {}
453 friend class base::RefCountedThreadSafe<IntermittentChangeFrameGenerator>;
455 int frame_index_;
456 scoped_ptr<webrtc::SharedDesktopFrame> current_frame_;
458 DISALLOW_COPY_AND_ASSIGN(IntermittentChangeFrameGenerator);
461 TEST_P(ProtocolPerfTest, IntermittentChanges) {
462 desktop_environment_factory_.set_frame_generator(
463 base::Bind(&IntermittentChangeFrameGenerator::GenerateFrame,
464 new IntermittentChangeFrameGenerator()));
466 StartHostAndClient(protocol::ChannelConfig::CODEC_VERBATIM);
467 ASSERT_NO_FATAL_FAILURE(WaitConnected());
469 ReceiveFrame(nullptr);
471 base::TimeDelta expected = GetParam().latency_average;
472 if (GetParam().bandwidth > 0) {
473 expected += base::TimeDelta::FromSecondsD(kIntermittentFrameSize /
474 GetParam().bandwidth);
476 LOG(INFO) << "Expected: " << expected.InMillisecondsF() << "ms";
478 base::TimeDelta sum;
480 const int kFrames = 5;
481 for (int i = 0; i < kFrames; ++i) {
482 base::TimeDelta latency;
483 ReceiveFrame(&latency);
484 LOG(INFO) << "Latency: " << latency.InMillisecondsF()
485 << "ms Encode: " << last_video_packet_->encode_time_ms()
486 << "ms Capture: " << last_video_packet_->capture_time_ms()
487 << "ms";
488 sum += latency;
491 LOG(INFO) << "Average: " << (sum / kFrames).InMillisecondsF();
494 } // namespace remoting