WebUI generator GN build file fixed.
[chromium-blink-merge.git] / remoting / test / protocol_perftest.cc
blobd08b117fdb1b832d82afed2444d20885d2df528b
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_.message_loop_proxy()->DeleteSoon(FROM_HERE, host_.release());
94 host_thread_.message_loop_proxy()->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 ChromotingStats* GetStats() override { return nullptr; }
123 protocol::VideoStub* GetVideoStub() override { return this; }
125 // protocol::VideoStub interface.
126 void ProcessVideoPacket(scoped_ptr<VideoPacket> video_packet,
127 const base::Closure& done) override {
128 if (video_packet->data().empty()) {
129 // Ignore keep-alive packets
130 done.Run();
131 return;
134 last_video_packet_ = video_packet.Pass();
136 if (!on_frame_task_.is_null())
137 on_frame_task_.Run();
139 done.Run();
142 // HostStatusObserver interface.
143 void OnClientConnected(const std::string& jid) override {
144 message_loop_.PostTask(
145 FROM_HERE,
146 base::Bind(&ProtocolPerfTest::OnHostConnectedMainThread,
147 base::Unretained(this)));
150 protected:
151 void WaitConnected() {
152 client_connected_ = false;
153 host_connected_ = false;
155 connecting_loop_.reset(new base::RunLoop());
156 connecting_loop_->Run();
158 ASSERT_TRUE(client_connected_ && host_connected_);
161 void OnHostConnectedMainThread() {
162 host_connected_ = true;
163 if (client_connected_)
164 connecting_loop_->Quit();
167 void ReceiveFrame(base::TimeDelta* latency) {
168 waiting_frames_loop_.reset(new base::RunLoop());
169 on_frame_task_ = waiting_frames_loop_->QuitClosure();
170 waiting_frames_loop_->Run();
172 if (latency) {
173 base::TimeTicks timestamp =
174 base::TimeTicks::FromInternalValue(last_video_packet_->timestamp());
175 *latency = base::TimeTicks::Now() - timestamp;
179 void ReceiveFrames(int frames, base::TimeDelta* max_latency) {
180 if (max_latency)
181 *max_latency = base::TimeDelta();
183 for (int i = 0; i < frames; ++i) {
184 base::TimeDelta latency;
186 ReceiveFrame(&latency);
188 if (max_latency && latency > *max_latency) {
189 *max_latency = latency;
194 // Creates test host and client and starts connection between them. Caller
195 // should call WaitConnected() to wait until connection is established. The
196 // host is started on |host_thread_| while the client works on the main
197 // thread.
198 void StartHostAndClient(protocol::ChannelConfig::Codec video_codec) {
199 fake_network_dispatcher_ = new FakeNetworkDispatcher();
201 client_signaling_.reset(new FakeSignalStrategy(kClientJid));
203 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
205 protocol_config_ = protocol::CandidateSessionConfig::CreateDefault();
206 protocol_config_->DisableAudioChannel();
207 protocol_config_->mutable_video_configs()->clear();
208 protocol_config_->mutable_video_configs()->push_back(
209 protocol::ChannelConfig(
210 protocol::ChannelConfig::TRANSPORT_STREAM, 2, video_codec));
212 host_thread_.message_loop_proxy()->PostTask(
213 FROM_HERE,
214 base::Bind(&ProtocolPerfTest::StartHost, base::Unretained(this)));
217 void StartHost() {
218 DCHECK(host_thread_.message_loop_proxy()->BelongsToCurrentThread());
220 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
222 host_signaling_.reset(new FakeSignalStrategy(kHostJid));
223 host_signaling_->ConnectTo(client_signaling_.get());
225 protocol::NetworkSettings network_settings(
226 protocol::NetworkSettings::NAT_TRAVERSAL_OUTGOING);
228 scoped_ptr<FakePortAllocator> port_allocator(
229 FakePortAllocator::Create(fake_network_dispatcher_));
230 port_allocator->socket_factory()->SetBandwidth(GetParam().bandwidth,
231 GetParam().max_buffers);
232 port_allocator->socket_factory()->SetLatency(GetParam().latency_average,
233 GetParam().latency_stddev);
234 port_allocator->socket_factory()->set_out_of_order_rate(
235 GetParam().out_of_order_rate);
236 scoped_ptr<protocol::TransportFactory> host_transport_factory(
237 new protocol::LibjingleTransportFactory(
238 host_signaling_.get(),
239 port_allocator.Pass(),
240 network_settings));
242 scoped_ptr<protocol::SessionManager> session_manager(
243 new protocol::JingleSessionManager(host_transport_factory.Pass()));
245 // Encoder runs on a separate thread, main thread is used for everything
246 // else.
247 host_.reset(new ChromotingHost(host_signaling_.get(),
248 &desktop_environment_factory_,
249 session_manager.Pass(),
250 host_thread_.message_loop_proxy(),
251 host_thread_.message_loop_proxy(),
252 capture_thread_.message_loop_proxy(),
253 encode_thread_.message_loop_proxy(),
254 host_thread_.message_loop_proxy(),
255 host_thread_.message_loop_proxy()));
257 base::FilePath certs_dir(net::GetTestCertsDirectory());
259 std::string host_cert;
260 ASSERT_TRUE(base::ReadFileToString(
261 certs_dir.AppendASCII("unittest.selfsigned.der"), &host_cert));
263 base::FilePath key_path = certs_dir.AppendASCII("unittest.key.bin");
264 std::string key_string;
265 ASSERT_TRUE(base::ReadFileToString(key_path, &key_string));
266 std::string key_base64;
267 base::Base64Encode(key_string, &key_base64);
268 scoped_refptr<RsaKeyPair> key_pair = RsaKeyPair::FromString(key_base64);
269 ASSERT_TRUE(key_pair.get());
272 protocol::SharedSecretHash host_secret;
273 host_secret.hash_function = protocol::AuthenticationMethod::NONE;
274 host_secret.value = "123456";
275 scoped_ptr<protocol::AuthenticatorFactory> auth_factory =
276 protocol::Me2MeHostAuthenticatorFactory::CreateWithSharedSecret(
277 true, kHostOwner, host_cert, key_pair, host_secret, nullptr);
278 host_->SetAuthenticatorFactory(auth_factory.Pass());
280 host_->AddStatusObserver(this);
281 host_->set_protocol_config(protocol_config_->Clone());
282 host_->Start(kHostOwner);
284 message_loop_.PostTask(FROM_HERE,
285 base::Bind(&ProtocolPerfTest::StartClientAfterHost,
286 base::Unretained(this)));
289 void StartClientAfterHost() {
290 client_signaling_->ConnectTo(host_signaling_.get());
292 protocol::NetworkSettings network_settings(
293 protocol::NetworkSettings::NAT_TRAVERSAL_OUTGOING);
295 // Initialize client.
296 client_context_.reset(
297 new ClientContext(base::ThreadTaskRunnerHandle::Get()));
299 scoped_ptr<FakePortAllocator> port_allocator(
300 FakePortAllocator::Create(fake_network_dispatcher_));
301 port_allocator->socket_factory()->SetBandwidth(GetParam().bandwidth,
302 GetParam().max_buffers);
303 port_allocator->socket_factory()->SetLatency(GetParam().latency_average,
304 GetParam().latency_stddev);
305 port_allocator->socket_factory()->set_out_of_order_rate(
306 GetParam().out_of_order_rate);
307 scoped_ptr<protocol::TransportFactory> client_transport_factory(
308 new protocol::LibjingleTransportFactory(
309 client_signaling_.get(),
310 port_allocator.Pass(),
311 network_settings));
313 std::vector<protocol::AuthenticationMethod> auth_methods;
314 auth_methods.push_back(protocol::AuthenticationMethod::Spake2(
315 protocol::AuthenticationMethod::NONE));
316 scoped_ptr<protocol::Authenticator> client_authenticator(
317 new protocol::NegotiatingClientAuthenticator(
318 std::string(), // client_pairing_id
319 std::string(), // client_pairing_secret
320 std::string(), // authentication_tag
321 base::Bind(&ProtocolPerfTest::FetchPin, base::Unretained(this)),
322 nullptr,
323 auth_methods));
324 client_.reset(
325 new ChromotingClient(client_context_.get(), this, this, nullptr));
326 client_->SetProtocolConfigForTests(protocol_config_->Clone());
327 client_->Start(
328 client_signaling_.get(), client_authenticator.Pass(),
329 client_transport_factory.Pass(), kHostJid, std::string());
332 void FetchPin(
333 bool pairing_supported,
334 const protocol::SecretFetchedCallback& secret_fetched_callback) {
335 secret_fetched_callback.Run("123456");
338 base::MessageLoopForIO message_loop_;
340 scoped_refptr<FakeNetworkDispatcher> fake_network_dispatcher_;
342 base::Thread host_thread_;
343 base::Thread capture_thread_;
344 base::Thread encode_thread_;
345 FakeDesktopEnvironmentFactory desktop_environment_factory_;
347 FakeCursorShapeStub cursor_shape_stub_;
349 scoped_ptr<protocol::CandidateSessionConfig> protocol_config_;
351 scoped_ptr<FakeSignalStrategy> host_signaling_;
352 scoped_ptr<FakeSignalStrategy> client_signaling_;
354 scoped_ptr<ChromotingHost> host_;
355 scoped_ptr<ClientContext> client_context_;
356 scoped_ptr<ChromotingClient> client_;
358 scoped_ptr<base::RunLoop> connecting_loop_;
359 scoped_ptr<base::RunLoop> waiting_frames_loop_;
361 bool client_connected_;
362 bool host_connected_;
364 base::Closure on_frame_task_;
366 scoped_ptr<VideoPacket> last_video_packet_;
368 DISALLOW_COPY_AND_ASSIGN(ProtocolPerfTest);
371 INSTANTIATE_TEST_CASE_P(
372 NoDelay,
373 ProtocolPerfTest,
374 ::testing::Values(NetworkPerformanceParams(0, 0, 0, 0, 0.0)));
376 INSTANTIATE_TEST_CASE_P(
377 HighLatency,
378 ProtocolPerfTest,
379 ::testing::Values(NetworkPerformanceParams(0, 0, 300, 30, 0.0),
380 NetworkPerformanceParams(0, 0, 30, 10, 0.0)));
382 INSTANTIATE_TEST_CASE_P(
383 OutOfOrder,
384 ProtocolPerfTest,
385 ::testing::Values(NetworkPerformanceParams(0, 0, 2, 0, 0.01),
386 NetworkPerformanceParams(0, 0, 30, 1, 0.01),
387 NetworkPerformanceParams(0, 0, 30, 1, 0.1),
388 NetworkPerformanceParams(0, 0, 300, 20, 0.01),
389 NetworkPerformanceParams(0, 0, 300, 20, 0.1)));
391 INSTANTIATE_TEST_CASE_P(
392 LimitedBandwidth,
393 ProtocolPerfTest,
394 ::testing::Values(
395 // 100 MBps
396 NetworkPerformanceParams(800000000, 800000000, 2, 1, 0.0),
397 // 8 MBps
398 NetworkPerformanceParams(1000000, 300000, 30, 5, 0.01),
399 NetworkPerformanceParams(1000000, 2000000, 30, 5, 0.01),
400 // 800 kBps
401 NetworkPerformanceParams(100000, 30000, 130, 5, 0.01),
402 NetworkPerformanceParams(100000, 200000, 130, 5, 0.01)));
404 TEST_P(ProtocolPerfTest, StreamFrameRate) {
405 StartHostAndClient(protocol::ChannelConfig::CODEC_VP8);
406 ASSERT_NO_FATAL_FAILURE(WaitConnected());
408 base::TimeDelta latency;
410 ReceiveFrame(&latency);
411 LOG(INFO) << "First frame latency: " << latency.InMillisecondsF() << "ms";
412 ReceiveFrames(20, nullptr);
414 base::TimeTicks started = base::TimeTicks::Now();
415 ReceiveFrames(40, &latency);
416 base::TimeDelta elapsed = base::TimeTicks::Now() - started;
417 LOG(INFO) << "Frame rate: " << (40.0 / elapsed.InSecondsF());
418 LOG(INFO) << "Maximum latency: " << latency.InMillisecondsF() << "ms";
421 const int kIntermittentFrameSize = 100 * 1000;
423 // Frame generator that rewrites the whole screen every 60th frame. Should only
424 // be used with the VERBATIM codec as the allocated frame may contain arbitrary
425 // data.
426 class IntermittentChangeFrameGenerator
427 : public base::RefCountedThreadSafe<IntermittentChangeFrameGenerator> {
428 public:
429 IntermittentChangeFrameGenerator()
430 : frame_index_(0) {}
432 scoped_ptr<webrtc::DesktopFrame> GenerateFrame(
433 webrtc::DesktopCapturer::Callback* callback) {
434 const int kWidth = 1000;
435 const int kHeight = kIntermittentFrameSize / kWidth / 4;
437 bool fresh_frame = false;
438 if (frame_index_ % 60 == 0 || !current_frame_) {
439 current_frame_.reset(webrtc::SharedDesktopFrame::Wrap(
440 new webrtc::BasicDesktopFrame(webrtc::DesktopSize(kWidth, kHeight))));
441 fresh_frame = true;
443 ++frame_index_;
445 scoped_ptr<webrtc::DesktopFrame> result(current_frame_->Share());
446 result->mutable_updated_region()->Clear();
447 if (fresh_frame) {
448 result->mutable_updated_region()->AddRect(
449 webrtc::DesktopRect::MakeXYWH(0, 0, kWidth, kHeight));
451 return result.Pass();
454 private:
455 ~IntermittentChangeFrameGenerator() {}
456 friend class base::RefCountedThreadSafe<IntermittentChangeFrameGenerator>;
458 int frame_index_;
459 scoped_ptr<webrtc::SharedDesktopFrame> current_frame_;
461 DISALLOW_COPY_AND_ASSIGN(IntermittentChangeFrameGenerator);
464 TEST_P(ProtocolPerfTest, IntermittentChanges) {
465 desktop_environment_factory_.set_frame_generator(
466 base::Bind(&IntermittentChangeFrameGenerator::GenerateFrame,
467 new IntermittentChangeFrameGenerator()));
469 StartHostAndClient(protocol::ChannelConfig::CODEC_VERBATIM);
470 ASSERT_NO_FATAL_FAILURE(WaitConnected());
472 ReceiveFrame(nullptr);
474 base::TimeDelta expected = GetParam().latency_average;
475 if (GetParam().bandwidth > 0) {
476 expected += base::TimeDelta::FromSecondsD(kIntermittentFrameSize /
477 GetParam().bandwidth);
479 LOG(INFO) << "Expected: " << expected.InMillisecondsF() << "ms";
481 base::TimeDelta sum;
483 const int kFrames = 5;
484 for (int i = 0; i < kFrames; ++i) {
485 base::TimeDelta latency;
486 ReceiveFrame(&latency);
487 LOG(INFO) << "Latency: " << latency.InMillisecondsF()
488 << "ms Encode: " << last_video_packet_->encode_time_ms()
489 << "ms Capture: " << last_video_packet_->capture_time_ms()
490 << "ms";
491 sum += latency;
494 LOG(INFO) << "Average: " << (sum / kFrames).InMillisecondsF();
497 } // namespace remoting