Non-SFI mode: Clean up macros of base/ and ipc/ libraries for nacl_helper_nonsfi.
[chromium-blink-merge.git] / remoting / test / protocol_perftest.cc
blob86d4bec570b1c12cda01f66a0cef04148c86ff1a
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_scheduler.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 HostStatusObserver {
79 public:
80 ProtocolPerfTest()
81 : host_thread_("host"),
82 capture_thread_("capture"),
83 encode_thread_("encode") {
84 VideoScheduler::EnableTimestampsForTests();
85 host_thread_.StartWithOptions(
86 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
87 capture_thread_.Start();
88 encode_thread_.Start();
91 virtual ~ProtocolPerfTest() {
92 host_thread_.message_loop_proxy()->DeleteSoon(FROM_HERE, host_.release());
93 host_thread_.message_loop_proxy()->DeleteSoon(FROM_HERE,
94 host_signaling_.release());
95 message_loop_.RunUntilIdle();
98 // ClientUserInterface interface.
99 void OnConnectionState(protocol::ConnectionToHost::State state,
100 protocol::ErrorCode error) override {
101 if (state == protocol::ConnectionToHost::CONNECTED) {
102 client_connected_ = true;
103 if (host_connected_)
104 connecting_loop_->Quit();
107 void OnConnectionReady(bool ready) override {}
108 void OnRouteChanged(const std::string& channel_name,
109 const protocol::TransportRoute& route) override {}
110 void SetCapabilities(const std::string& capabilities) override {}
111 void SetPairingResponse(
112 const protocol::PairingResponse& pairing_response) override {}
113 void DeliverHostMessage(const protocol::ExtensionMessage& message) override {}
114 protocol::ClipboardStub* GetClipboardStub() override { return NULL; }
115 protocol::CursorShapeStub* GetCursorShapeStub() override {
116 return &cursor_shape_stub_;
119 // VideoRenderer interface.
120 void Initialize(const protocol::SessionConfig& config) override {}
121 ChromotingStats* GetStats() override { return NULL; }
122 void ProcessVideoPacket(scoped_ptr<VideoPacket> video_packet,
123 const base::Closure& done) override {
124 if (video_packet->data().empty()) {
125 // Ignore keep-alive packets
126 done.Run();
127 return;
130 last_video_packet_ = video_packet.Pass();
132 if (!on_frame_task_.is_null())
133 on_frame_task_.Run();
135 done.Run();
138 // HostStatusObserver interface.
139 void OnClientConnected(const std::string& jid) override {
140 message_loop_.PostTask(
141 FROM_HERE,
142 base::Bind(&ProtocolPerfTest::OnHostConnectedMainThread,
143 base::Unretained(this)));
146 protected:
147 void WaitConnected() {
148 client_connected_ = false;
149 host_connected_ = false;
151 connecting_loop_.reset(new base::RunLoop());
152 connecting_loop_->Run();
154 ASSERT_TRUE(client_connected_ && host_connected_);
157 void OnHostConnectedMainThread() {
158 host_connected_ = true;
159 if (client_connected_)
160 connecting_loop_->Quit();
163 void ReceiveFrame(base::TimeDelta* latency) {
164 waiting_frames_loop_.reset(new base::RunLoop());
165 on_frame_task_ = waiting_frames_loop_->QuitClosure();
166 waiting_frames_loop_->Run();
168 if (latency) {
169 base::TimeTicks timestamp =
170 base::TimeTicks::FromInternalValue(last_video_packet_->timestamp());
171 *latency = base::TimeTicks::Now() - timestamp;
175 void ReceiveFrames(int frames, base::TimeDelta* max_latency) {
176 if (max_latency)
177 *max_latency = base::TimeDelta();
179 for (int i = 0; i < frames; ++i) {
180 base::TimeDelta latency;
182 ReceiveFrame(&latency);
184 if (max_latency && latency > *max_latency) {
185 *max_latency = latency;
190 // Creates test host and client and starts connection between them. Caller
191 // should call WaitConnected() to wait until connection is established. The
192 // host is started on |host_thread_| while the client works on the main
193 // thread.
194 void StartHostAndClient(protocol::ChannelConfig::Codec video_codec) {
195 fake_network_dispatcher_ = new FakeNetworkDispatcher();
197 client_signaling_.reset(new FakeSignalStrategy(kClientJid));
199 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
201 protocol_config_ = protocol::CandidateSessionConfig::CreateDefault();
202 protocol_config_->DisableAudioChannel();
203 protocol_config_->mutable_video_configs()->clear();
204 protocol_config_->mutable_video_configs()->push_back(
205 protocol::ChannelConfig(
206 protocol::ChannelConfig::TRANSPORT_STREAM, 2, video_codec));
208 host_thread_.message_loop_proxy()->PostTask(
209 FROM_HERE,
210 base::Bind(&ProtocolPerfTest::StartHost, base::Unretained(this)));
213 void StartHost() {
214 DCHECK(host_thread_.message_loop_proxy()->BelongsToCurrentThread());
216 jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
218 host_signaling_.reset(new FakeSignalStrategy(kHostJid));
219 host_signaling_->ConnectTo(client_signaling_.get());
221 protocol::NetworkSettings network_settings(
222 protocol::NetworkSettings::NAT_TRAVERSAL_OUTGOING);
224 scoped_ptr<FakePortAllocator> port_allocator(
225 FakePortAllocator::Create(fake_network_dispatcher_));
226 port_allocator->socket_factory()->SetBandwidth(GetParam().bandwidth,
227 GetParam().max_buffers);
228 port_allocator->socket_factory()->SetLatency(GetParam().latency_average,
229 GetParam().latency_stddev);
230 port_allocator->socket_factory()->set_out_of_order_rate(
231 GetParam().out_of_order_rate);
232 scoped_ptr<protocol::TransportFactory> host_transport_factory(
233 new protocol::LibjingleTransportFactory(
234 host_signaling_.get(),
235 port_allocator.Pass(),
236 network_settings));
238 scoped_ptr<protocol::SessionManager> session_manager(
239 new protocol::JingleSessionManager(host_transport_factory.Pass()));
241 // Encoder runs on a separate thread, main thread is used for everything
242 // else.
243 host_.reset(new ChromotingHost(host_signaling_.get(),
244 &desktop_environment_factory_,
245 session_manager.Pass(),
246 host_thread_.message_loop_proxy(),
247 host_thread_.message_loop_proxy(),
248 capture_thread_.message_loop_proxy(),
249 encode_thread_.message_loop_proxy(),
250 host_thread_.message_loop_proxy(),
251 host_thread_.message_loop_proxy()));
253 base::FilePath certs_dir(net::GetTestCertsDirectory());
255 std::string host_cert;
256 ASSERT_TRUE(base::ReadFileToString(
257 certs_dir.AppendASCII("unittest.selfsigned.der"), &host_cert));
259 base::FilePath key_path = certs_dir.AppendASCII("unittest.key.bin");
260 std::string key_string;
261 ASSERT_TRUE(base::ReadFileToString(key_path, &key_string));
262 std::string key_base64;
263 base::Base64Encode(key_string, &key_base64);
264 scoped_refptr<RsaKeyPair> key_pair = RsaKeyPair::FromString(key_base64);
265 ASSERT_TRUE(key_pair.get());
268 protocol::SharedSecretHash host_secret;
269 host_secret.hash_function = protocol::AuthenticationMethod::NONE;
270 host_secret.value = "123456";
271 scoped_ptr<protocol::AuthenticatorFactory> auth_factory =
272 protocol::Me2MeHostAuthenticatorFactory::CreateWithSharedSecret(
273 true, kHostOwner, host_cert, key_pair, host_secret, NULL);
274 host_->SetAuthenticatorFactory(auth_factory.Pass());
276 host_->AddStatusObserver(this);
277 host_->set_protocol_config(protocol_config_->Clone());
278 host_->Start(kHostOwner);
280 message_loop_.PostTask(FROM_HERE,
281 base::Bind(&ProtocolPerfTest::StartClientAfterHost,
282 base::Unretained(this)));
285 void StartClientAfterHost() {
286 client_signaling_->ConnectTo(host_signaling_.get());
288 protocol::NetworkSettings network_settings(
289 protocol::NetworkSettings::NAT_TRAVERSAL_OUTGOING);
291 // Initialize client.
292 client_context_.reset(
293 new ClientContext(base::ThreadTaskRunnerHandle::Get()));
295 scoped_ptr<FakePortAllocator> port_allocator(
296 FakePortAllocator::Create(fake_network_dispatcher_));
297 port_allocator->socket_factory()->SetBandwidth(GetParam().bandwidth,
298 GetParam().max_buffers);
299 port_allocator->socket_factory()->SetLatency(GetParam().latency_average,
300 GetParam().latency_stddev);
301 port_allocator->socket_factory()->set_out_of_order_rate(
302 GetParam().out_of_order_rate);
303 scoped_ptr<protocol::TransportFactory> client_transport_factory(
304 new protocol::LibjingleTransportFactory(
305 client_signaling_.get(),
306 port_allocator.Pass(),
307 network_settings));
309 std::vector<protocol::AuthenticationMethod> auth_methods;
310 auth_methods.push_back(protocol::AuthenticationMethod::Spake2(
311 protocol::AuthenticationMethod::NONE));
312 scoped_ptr<protocol::Authenticator> client_authenticator(
313 new protocol::NegotiatingClientAuthenticator(
314 std::string(), // client_pairing_id
315 std::string(), // client_pairing_secret
316 std::string(), // authentication_tag
317 base::Bind(&ProtocolPerfTest::FetchPin, base::Unretained(this)),
318 nullptr,
319 auth_methods));
320 client_.reset(
321 new ChromotingClient(client_context_.get(), this, this, nullptr));
322 client_->SetProtocolConfigForTests(protocol_config_->Clone());
323 client_->Start(
324 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 DISALLOW_COPY_AND_ASSIGN(ProtocolPerfTest);
367 INSTANTIATE_TEST_CASE_P(
368 NoDelay,
369 ProtocolPerfTest,
370 ::testing::Values(NetworkPerformanceParams(0, 0, 0, 0, 0.0)));
372 INSTANTIATE_TEST_CASE_P(
373 HighLatency,
374 ProtocolPerfTest,
375 ::testing::Values(NetworkPerformanceParams(0, 0, 300, 30, 0.0),
376 NetworkPerformanceParams(0, 0, 30, 10, 0.0)));
378 INSTANTIATE_TEST_CASE_P(
379 OutOfOrder,
380 ProtocolPerfTest,
381 ::testing::Values(NetworkPerformanceParams(0, 0, 2, 0, 0.01),
382 NetworkPerformanceParams(0, 0, 30, 1, 0.01),
383 NetworkPerformanceParams(0, 0, 30, 1, 0.1),
384 NetworkPerformanceParams(0, 0, 300, 20, 0.01),
385 NetworkPerformanceParams(0, 0, 300, 20, 0.1)));
387 INSTANTIATE_TEST_CASE_P(
388 LimitedBandwidth,
389 ProtocolPerfTest,
390 ::testing::Values(
391 // 100 MBps
392 NetworkPerformanceParams(800000000, 800000000, 2, 1, 0.0),
393 // 8 MBps
394 NetworkPerformanceParams(1000000, 300000, 30, 5, 0.01),
395 NetworkPerformanceParams(1000000, 2000000, 30, 5, 0.01),
396 // 800 kBps
397 NetworkPerformanceParams(100000, 30000, 130, 5, 0.01),
398 NetworkPerformanceParams(100000, 200000, 130, 5, 0.01)));
400 TEST_P(ProtocolPerfTest, StreamFrameRate) {
401 StartHostAndClient(protocol::ChannelConfig::CODEC_VP8);
402 ASSERT_NO_FATAL_FAILURE(WaitConnected());
404 base::TimeDelta latency;
406 ReceiveFrame(&latency);
407 LOG(INFO) << "First frame latency: " << latency.InMillisecondsF() << "ms";
408 ReceiveFrames(20, NULL);
410 base::TimeTicks started = base::TimeTicks::Now();
411 ReceiveFrames(40, &latency);
412 base::TimeDelta elapsed = base::TimeTicks::Now() - started;
413 LOG(INFO) << "Frame rate: " << (40.0 / elapsed.InSecondsF());
414 LOG(INFO) << "Maximum latency: " << latency.InMillisecondsF() << "ms";
417 const int kIntermittentFrameSize = 100 * 1000;
419 // Frame generator that rewrites the whole screen every 60th frame. Should only
420 // be used with the VERBATIM codec as the allocated frame may contain arbitrary
421 // data.
422 class IntermittentChangeFrameGenerator
423 : public base::RefCountedThreadSafe<IntermittentChangeFrameGenerator> {
424 public:
425 IntermittentChangeFrameGenerator()
426 : frame_index_(0) {}
428 scoped_ptr<webrtc::DesktopFrame> GenerateFrame(
429 webrtc::DesktopCapturer::Callback* callback) {
430 const int kWidth = 1000;
431 const int kHeight = kIntermittentFrameSize / kWidth / 4;
433 bool fresh_frame = false;
434 if (frame_index_ % 60 == 0 || !current_frame_) {
435 current_frame_.reset(webrtc::SharedDesktopFrame::Wrap(
436 new webrtc::BasicDesktopFrame(webrtc::DesktopSize(kWidth, kHeight))));
437 fresh_frame = true;
439 ++frame_index_;
441 scoped_ptr<webrtc::DesktopFrame> result(current_frame_->Share());
442 result->mutable_updated_region()->Clear();
443 if (fresh_frame) {
444 result->mutable_updated_region()->AddRect(
445 webrtc::DesktopRect::MakeXYWH(0, 0, kWidth, kHeight));
447 return result.Pass();
450 private:
451 ~IntermittentChangeFrameGenerator() {}
452 friend class base::RefCountedThreadSafe<IntermittentChangeFrameGenerator>;
454 int frame_index_;
455 scoped_ptr<webrtc::SharedDesktopFrame> current_frame_;
457 DISALLOW_COPY_AND_ASSIGN(IntermittentChangeFrameGenerator);
460 TEST_P(ProtocolPerfTest, IntermittentChanges) {
461 desktop_environment_factory_.set_frame_generator(
462 base::Bind(&IntermittentChangeFrameGenerator::GenerateFrame,
463 new IntermittentChangeFrameGenerator()));
465 StartHostAndClient(protocol::ChannelConfig::CODEC_VERBATIM);
466 ASSERT_NO_FATAL_FAILURE(WaitConnected());
468 ReceiveFrame(NULL);
470 base::TimeDelta expected = GetParam().latency_average;
471 if (GetParam().bandwidth > 0) {
472 expected += base::TimeDelta::FromSecondsD(kIntermittentFrameSize /
473 GetParam().bandwidth);
475 LOG(INFO) << "Expected: " << expected.InMillisecondsF() << "ms";
477 base::TimeDelta sum;
479 const int kFrames = 5;
480 for (int i = 0; i < kFrames; ++i) {
481 base::TimeDelta latency;
482 ReceiveFrame(&latency);
483 LOG(INFO) << "Latency: " << latency.InMillisecondsF()
484 << "ms Encode: " << last_video_packet_->encode_time_ms()
485 << "ms Capture: " << last_video_packet_->capture_time_ms()
486 << "ms";
487 sum += latency;
490 LOG(INFO) << "Average: " << (sum / kFrames).InMillisecondsF();
493 } // namespace remoting