blob: fd0fcc5545b890c9e7fdc9afbb9f6c81d5ab9509 [file] [log] [blame]
Jeff Browncbad9762012-09-04 21:57:59 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.display;
18
19import com.android.internal.util.DumpUtils;
20
21import android.content.BroadcastReceiver;
Jeff Brown89d55462012-09-19 11:33:42 -070022import android.content.ContentResolver;
Jeff Browncbad9762012-09-04 21:57:59 -070023import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
Jeff Brown89d55462012-09-19 11:33:42 -070026import android.database.ContentObserver;
Jeff Browne08ae382012-09-07 20:36:36 -070027import android.hardware.display.WifiDisplay;
Jeff Brown89d55462012-09-19 11:33:42 -070028import android.hardware.display.WifiDisplayStatus;
Jeff Brown88469e52012-09-12 16:01:45 -070029import android.media.AudioManager;
Jeff Brownf8f0edd2012-09-11 17:05:11 -070030import android.media.RemoteDisplay;
Jeff Browncbad9762012-09-04 21:57:59 -070031import android.net.NetworkInfo;
Jeff Brown89d55462012-09-19 11:33:42 -070032import android.net.Uri;
Jeff Browncbad9762012-09-04 21:57:59 -070033import android.net.wifi.p2p.WifiP2pConfig;
34import android.net.wifi.p2p.WifiP2pDevice;
35import android.net.wifi.p2p.WifiP2pDeviceList;
36import android.net.wifi.p2p.WifiP2pGroup;
37import android.net.wifi.p2p.WifiP2pManager;
38import android.net.wifi.p2p.WifiP2pWfdInfo;
39import android.net.wifi.p2p.WifiP2pManager.ActionListener;
40import android.net.wifi.p2p.WifiP2pManager.Channel;
41import android.net.wifi.p2p.WifiP2pManager.GroupInfoListener;
42import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
43import android.os.Handler;
Jeff Brown89d55462012-09-19 11:33:42 -070044import android.provider.Settings;
Jeff Browncbad9762012-09-04 21:57:59 -070045import android.util.Slog;
Jeff Brownf8f0edd2012-09-11 17:05:11 -070046import android.view.Surface;
Jeff Browncbad9762012-09-04 21:57:59 -070047
48import java.io.PrintWriter;
49import java.net.Inet4Address;
50import java.net.InetAddress;
51import java.net.NetworkInterface;
52import java.net.SocketException;
53import java.util.ArrayList;
54import java.util.Enumeration;
55
56/**
57 * Manages all of the various asynchronous interactions with the {@link WifiP2pManager}
58 * on behalf of {@link WifiDisplayAdapter}.
59 * <p>
60 * This code is isolated from {@link WifiDisplayAdapter} so that we can avoid
61 * accidentally introducing any deadlocks due to the display manager calling
62 * outside of itself while holding its lock. It's also way easier to write this
63 * asynchronous code if we can assume that it is single-threaded.
64 * </p><p>
65 * The controller must be instantiated on the handler thread.
66 * </p>
67 */
68final class WifiDisplayController implements DumpUtils.Dump {
69 private static final String TAG = "WifiDisplayController";
Jeff Brownc5df37c2012-09-13 11:45:07 -070070 private static final boolean DEBUG = false;
Jeff Browncbad9762012-09-04 21:57:59 -070071
72 private static final int DEFAULT_CONTROL_PORT = 7236;
73 private static final int MAX_THROUGHPUT = 50;
74 private static final int CONNECTION_TIMEOUT_SECONDS = 30;
Jeff Brownf8f0edd2012-09-11 17:05:11 -070075 private static final int RTSP_TIMEOUT_SECONDS = 15;
Jeff Browncbad9762012-09-04 21:57:59 -070076
Jeff Brown0cfebf22012-09-07 17:41:20 -070077 private static final int DISCOVER_PEERS_MAX_RETRIES = 10;
78 private static final int DISCOVER_PEERS_RETRY_DELAY_MILLIS = 500;
79
80 private static final int CONNECT_MAX_RETRIES = 3;
81 private static final int CONNECT_RETRY_DELAY_MILLIS = 500;
82
Jeff Brown88469e52012-09-12 16:01:45 -070083 // A unique token to identify the remote submix that is managed by Wifi display.
84 // It must match what the media server uses when it starts recording the submix
85 // for transmission. We use 0 although the actual value is currently ignored.
86 private static final int REMOTE_SUBMIX_ADDRESS = 0;
87
Jeff Browncbad9762012-09-04 21:57:59 -070088 private final Context mContext;
89 private final Handler mHandler;
90 private final Listener mListener;
Jeff Brown88469e52012-09-12 16:01:45 -070091
Jeff Browncbad9762012-09-04 21:57:59 -070092 private final WifiP2pManager mWifiP2pManager;
93 private final Channel mWifiP2pChannel;
94
Jeff Brown88469e52012-09-12 16:01:45 -070095 private final AudioManager mAudioManager;
96
Jeff Browncbad9762012-09-04 21:57:59 -070097 private boolean mWifiP2pEnabled;
98 private boolean mWfdEnabled;
99 private boolean mWfdEnabling;
100 private NetworkInfo mNetworkInfo;
101
Jeff Brown89d55462012-09-19 11:33:42 -0700102 private final ArrayList<WifiP2pDevice> mAvailableWifiDisplayPeers =
Jeff Browncbad9762012-09-04 21:57:59 -0700103 new ArrayList<WifiP2pDevice>();
104
Jeff Brown89d55462012-09-19 11:33:42 -0700105 // True if Wifi display is enabled by the user.
106 private boolean mWifiDisplayOnSetting;
107
Jeff Brown0cfebf22012-09-07 17:41:20 -0700108 // True if there is a call to discoverPeers in progress.
109 private boolean mDiscoverPeersInProgress;
110
111 // Number of discover peers retries remaining.
112 private int mDiscoverPeersRetriesLeft;
113
Jeff Browncbad9762012-09-04 21:57:59 -0700114 // The device to which we want to connect, or null if we want to be disconnected.
115 private WifiP2pDevice mDesiredDevice;
116
117 // The device to which we are currently connecting, or null if we have already connected
118 // or are not trying to connect.
119 private WifiP2pDevice mConnectingDevice;
120
121 // The device to which we are currently connected, which means we have an active P2P group.
122 private WifiP2pDevice mConnectedDevice;
123
124 // The group info obtained after connecting.
125 private WifiP2pGroup mConnectedDeviceGroupInfo;
126
Jeff Brown0cfebf22012-09-07 17:41:20 -0700127 // Number of connection retries remaining.
128 private int mConnectionRetriesLeft;
129
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700130 // The remote display that is listening on the connection.
131 // Created after the Wifi P2P network is connected.
132 private RemoteDisplay mRemoteDisplay;
133
134 // The remote display interface.
135 private String mRemoteDisplayInterface;
136
137 // True if RTSP has connected.
138 private boolean mRemoteDisplayConnected;
139
Jeff Brownc9bd4ca2012-09-17 12:20:29 -0700140 // True if the remote submix is enabled.
141 private boolean mRemoteSubmixOn;
142
Jeff Browncbad9762012-09-04 21:57:59 -0700143 public WifiDisplayController(Context context, Handler handler, Listener listener) {
144 mContext = context;
145 mHandler = handler;
146 mListener = listener;
147
148 mWifiP2pManager = (WifiP2pManager)context.getSystemService(Context.WIFI_P2P_SERVICE);
149 mWifiP2pChannel = mWifiP2pManager.initialize(context, handler.getLooper(), null);
150
Jeff Brown88469e52012-09-12 16:01:45 -0700151 mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
152
Jeff Browncbad9762012-09-04 21:57:59 -0700153 IntentFilter intentFilter = new IntentFilter();
154 intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
155 intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
156 intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
Jeff Brown89d55462012-09-19 11:33:42 -0700157 context.registerReceiver(mWifiP2pReceiver, intentFilter, null, mHandler);
158
159 ContentObserver settingsObserver = new ContentObserver(mHandler) {
160 @Override
161 public void onChange(boolean selfChange, Uri uri) {
162 updateSettings();
163 }
164 };
165
166 final ContentResolver resolver = mContext.getContentResolver();
167 resolver.registerContentObserver(Settings.Global.getUriFor(
168 Settings.Global.WIFI_DISPLAY_ON), false, settingsObserver);
169 updateSettings();
170 }
171
172 private void updateSettings() {
173 final ContentResolver resolver = mContext.getContentResolver();
174 mWifiDisplayOnSetting = Settings.Global.getInt(resolver,
175 Settings.Global.WIFI_DISPLAY_ON, 0) != 0;
176
177 updateWfdEnableState();
Jeff Browncbad9762012-09-04 21:57:59 -0700178 }
179
180 public void dump(PrintWriter pw) {
Jeff Brown89d55462012-09-19 11:33:42 -0700181 pw.println("mWifiDisplayOnSetting=" + mWifiDisplayOnSetting);
Jeff Browncbad9762012-09-04 21:57:59 -0700182 pw.println("mWifiP2pEnabled=" + mWifiP2pEnabled);
183 pw.println("mWfdEnabled=" + mWfdEnabled);
184 pw.println("mWfdEnabling=" + mWfdEnabling);
185 pw.println("mNetworkInfo=" + mNetworkInfo);
Jeff Brown0cfebf22012-09-07 17:41:20 -0700186 pw.println("mDiscoverPeersInProgress=" + mDiscoverPeersInProgress);
187 pw.println("mDiscoverPeersRetriesLeft=" + mDiscoverPeersRetriesLeft);
Jeff Browncbad9762012-09-04 21:57:59 -0700188 pw.println("mDesiredDevice=" + describeWifiP2pDevice(mDesiredDevice));
189 pw.println("mConnectingDisplay=" + describeWifiP2pDevice(mConnectingDevice));
190 pw.println("mConnectedDevice=" + describeWifiP2pDevice(mConnectedDevice));
Jeff Brown0cfebf22012-09-07 17:41:20 -0700191 pw.println("mConnectionRetriesLeft=" + mConnectionRetriesLeft);
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700192 pw.println("mRemoteDisplay=" + mRemoteDisplay);
193 pw.println("mRemoteDisplayInterface=" + mRemoteDisplayInterface);
194 pw.println("mRemoteDisplayConnected=" + mRemoteDisplayConnected);
Jeff Brownc9bd4ca2012-09-17 12:20:29 -0700195 pw.println("mRemoteSubmixOn=" + mRemoteSubmixOn);
Jeff Browncbad9762012-09-04 21:57:59 -0700196
Jeff Brown89d55462012-09-19 11:33:42 -0700197 pw.println("mAvailableWifiDisplayPeers: size=" + mAvailableWifiDisplayPeers.size());
198 for (WifiP2pDevice device : mAvailableWifiDisplayPeers) {
Jeff Browncbad9762012-09-04 21:57:59 -0700199 pw.println(" " + describeWifiP2pDevice(device));
200 }
201 }
202
Jeff Browne08ae382012-09-07 20:36:36 -0700203 public void requestScan() {
204 discoverPeers();
205 }
206
207 public void requestConnect(String address) {
Jeff Brown89d55462012-09-19 11:33:42 -0700208 for (WifiP2pDevice device : mAvailableWifiDisplayPeers) {
Jeff Browne08ae382012-09-07 20:36:36 -0700209 if (device.deviceAddress.equals(address)) {
210 connect(device);
211 }
212 }
213 }
214
215 public void requestDisconnect() {
216 disconnect();
217 }
218
Jeff Brown89d55462012-09-19 11:33:42 -0700219 private void updateWfdEnableState() {
220 if (mWifiDisplayOnSetting && mWifiP2pEnabled) {
221 // WFD should be enabled.
222 if (!mWfdEnabled && !mWfdEnabling) {
223 mWfdEnabling = true;
Jeff Browncbad9762012-09-04 21:57:59 -0700224
Jeff Brown89d55462012-09-19 11:33:42 -0700225 WifiP2pWfdInfo wfdInfo = new WifiP2pWfdInfo();
226 wfdInfo.setWfdEnabled(true);
227 wfdInfo.setDeviceType(WifiP2pWfdInfo.WFD_SOURCE);
228 wfdInfo.setSessionAvailable(true);
229 wfdInfo.setControlPort(DEFAULT_CONTROL_PORT);
230 wfdInfo.setMaxThroughput(MAX_THROUGHPUT);
231 mWifiP2pManager.setWFDInfo(mWifiP2pChannel, wfdInfo, new ActionListener() {
232 @Override
233 public void onSuccess() {
234 if (DEBUG) {
235 Slog.d(TAG, "Successfully set WFD info.");
236 }
237 if (mWfdEnabling) {
238 mWfdEnabling = false;
239 mWfdEnabled = true;
240 reportFeatureState();
241 }
Jeff Browncbad9762012-09-04 21:57:59 -0700242 }
Jeff Brown89d55462012-09-19 11:33:42 -0700243
244 @Override
245 public void onFailure(int reason) {
246 if (DEBUG) {
247 Slog.d(TAG, "Failed to set WFD info with reason " + reason + ".");
248 }
Jeff Browncbad9762012-09-04 21:57:59 -0700249 mWfdEnabling = false;
Jeff Browncbad9762012-09-04 21:57:59 -0700250 }
Jeff Brown89d55462012-09-19 11:33:42 -0700251 });
252 }
253 } else {
254 // WFD should be disabled.
255 mWfdEnabling = false;
256 mWfdEnabled = false;
257 reportFeatureState();
258 disconnect();
Jeff Browncbad9762012-09-04 21:57:59 -0700259 }
260 }
261
Jeff Brown89d55462012-09-19 11:33:42 -0700262 private void reportFeatureState() {
263 final int featureState = computeFeatureState();
264 mHandler.post(new Runnable() {
265 @Override
266 public void run() {
267 mListener.onFeatureStateChanged(featureState);
268 }
269 });
270 }
271
272 private int computeFeatureState() {
273 if (!mWifiP2pEnabled) {
274 return WifiDisplayStatus.FEATURE_STATE_DISABLED;
Jeff Browne08ae382012-09-07 20:36:36 -0700275 }
Jeff Brown89d55462012-09-19 11:33:42 -0700276 return mWifiDisplayOnSetting ? WifiDisplayStatus.FEATURE_STATE_ON :
277 WifiDisplayStatus.FEATURE_STATE_OFF;
Jeff Browne08ae382012-09-07 20:36:36 -0700278 }
279
Jeff Browncbad9762012-09-04 21:57:59 -0700280 private void discoverPeers() {
Jeff Brown0cfebf22012-09-07 17:41:20 -0700281 if (!mDiscoverPeersInProgress) {
282 mDiscoverPeersInProgress = true;
283 mDiscoverPeersRetriesLeft = DISCOVER_PEERS_MAX_RETRIES;
Jeff Browne08ae382012-09-07 20:36:36 -0700284 handleScanStarted();
Jeff Brown0cfebf22012-09-07 17:41:20 -0700285 tryDiscoverPeers();
286 }
287 }
288
289 private void tryDiscoverPeers() {
Jeff Browncbad9762012-09-04 21:57:59 -0700290 mWifiP2pManager.discoverPeers(mWifiP2pChannel, new ActionListener() {
291 @Override
292 public void onSuccess() {
293 if (DEBUG) {
294 Slog.d(TAG, "Discover peers succeeded. Requesting peers now.");
295 }
296
Jeff Brown0cfebf22012-09-07 17:41:20 -0700297 mDiscoverPeersInProgress = false;
Jeff Browncbad9762012-09-04 21:57:59 -0700298 requestPeers();
299 }
300
301 @Override
302 public void onFailure(int reason) {
303 if (DEBUG) {
304 Slog.d(TAG, "Discover peers failed with reason " + reason + ".");
305 }
Jeff Brown0cfebf22012-09-07 17:41:20 -0700306
307 if (mDiscoverPeersInProgress) {
308 if (reason == 0 && mDiscoverPeersRetriesLeft > 0 && mWfdEnabled) {
309 mHandler.postDelayed(new Runnable() {
310 @Override
311 public void run() {
312 if (mDiscoverPeersInProgress) {
313 if (mDiscoverPeersRetriesLeft > 0 && mWfdEnabled) {
314 mDiscoverPeersRetriesLeft -= 1;
315 if (DEBUG) {
316 Slog.d(TAG, "Retrying discovery. Retries left: "
317 + mDiscoverPeersRetriesLeft);
318 }
319 tryDiscoverPeers();
320 } else {
Jeff Browne08ae382012-09-07 20:36:36 -0700321 handleScanFinished();
Jeff Brown0cfebf22012-09-07 17:41:20 -0700322 mDiscoverPeersInProgress = false;
323 }
324 }
325 }
326 }, DISCOVER_PEERS_RETRY_DELAY_MILLIS);
327 } else {
Jeff Browne08ae382012-09-07 20:36:36 -0700328 handleScanFinished();
Jeff Brown0cfebf22012-09-07 17:41:20 -0700329 mDiscoverPeersInProgress = false;
330 }
331 }
Jeff Browncbad9762012-09-04 21:57:59 -0700332 }
333 });
334 }
335
336 private void requestPeers() {
337 mWifiP2pManager.requestPeers(mWifiP2pChannel, new PeerListListener() {
338 @Override
339 public void onPeersAvailable(WifiP2pDeviceList peers) {
340 if (DEBUG) {
341 Slog.d(TAG, "Received list of peers.");
342 }
343
Jeff Brown89d55462012-09-19 11:33:42 -0700344 mAvailableWifiDisplayPeers.clear();
Jeff Browncbad9762012-09-04 21:57:59 -0700345 for (WifiP2pDevice device : peers.getDeviceList()) {
346 if (DEBUG) {
347 Slog.d(TAG, " " + describeWifiP2pDevice(device));
348 }
349
350 if (isWifiDisplay(device)) {
Jeff Brown89d55462012-09-19 11:33:42 -0700351 mAvailableWifiDisplayPeers.add(device);
Jeff Browncbad9762012-09-04 21:57:59 -0700352 }
353 }
354
Jeff Browne08ae382012-09-07 20:36:36 -0700355 handleScanFinished();
356 }
357 });
358 }
Jeff Browncbad9762012-09-04 21:57:59 -0700359
Jeff Browne08ae382012-09-07 20:36:36 -0700360 private void handleScanStarted() {
361 mHandler.post(new Runnable() {
362 @Override
363 public void run() {
364 mListener.onScanStarted();
365 }
366 });
367 }
Jeff Browncbad9762012-09-04 21:57:59 -0700368
Jeff Browne08ae382012-09-07 20:36:36 -0700369 private void handleScanFinished() {
Jeff Brown89d55462012-09-19 11:33:42 -0700370 final int count = mAvailableWifiDisplayPeers.size();
Jeff Browne08ae382012-09-07 20:36:36 -0700371 final WifiDisplay[] displays = WifiDisplay.CREATOR.newArray(count);
372 for (int i = 0; i < count; i++) {
Jeff Brown89d55462012-09-19 11:33:42 -0700373 displays[i] = createWifiDisplay(mAvailableWifiDisplayPeers.get(i));
Jeff Browne08ae382012-09-07 20:36:36 -0700374 }
375
376 mHandler.post(new Runnable() {
377 @Override
378 public void run() {
379 mListener.onScanFinished(displays);
Jeff Browncbad9762012-09-04 21:57:59 -0700380 }
381 });
382 }
383
384 private void connect(final WifiP2pDevice device) {
385 if (mDesiredDevice != null
386 && !mDesiredDevice.deviceAddress.equals(device.deviceAddress)) {
387 if (DEBUG) {
388 Slog.d(TAG, "connect: nothing to do, already connecting to "
389 + describeWifiP2pDevice(device));
390 }
391 return;
392 }
393
394 if (mConnectedDevice != null
395 && !mConnectedDevice.deviceAddress.equals(device.deviceAddress)
396 && mDesiredDevice == null) {
397 if (DEBUG) {
398 Slog.d(TAG, "connect: nothing to do, already connected to "
399 + describeWifiP2pDevice(device) + " and not part way through "
400 + "connecting to a different device.");
401 }
Jeff Brown0cfebf22012-09-07 17:41:20 -0700402 return;
Jeff Browncbad9762012-09-04 21:57:59 -0700403 }
404
405 mDesiredDevice = device;
Jeff Brown0cfebf22012-09-07 17:41:20 -0700406 mConnectionRetriesLeft = CONNECT_MAX_RETRIES;
Jeff Browncbad9762012-09-04 21:57:59 -0700407 updateConnection();
408 }
409
410 private void disconnect() {
411 mDesiredDevice = null;
412 updateConnection();
413 }
414
Jeff Brown0cfebf22012-09-07 17:41:20 -0700415 private void retryConnection() {
Jeff Brown89d55462012-09-19 11:33:42 -0700416 // Cheap hack. Make a new instance of the device object so that we
417 // can distinguish it from the previous connection attempt.
418 // This will cause us to tear everything down before we try again.
419 mDesiredDevice = new WifiP2pDevice(mDesiredDevice);
420 updateConnection();
Jeff Brown0cfebf22012-09-07 17:41:20 -0700421 }
422
Jeff Browncbad9762012-09-04 21:57:59 -0700423 /**
424 * This function is called repeatedly after each asynchronous operation
425 * until all preconditions for the connection have been satisfied and the
426 * connection is established (or not).
427 */
428 private void updateConnection() {
429 // Step 1. Before we try to connect to a new device, tell the system we
430 // have disconnected from the old one.
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700431 if (mRemoteDisplay != null && mConnectedDevice != mDesiredDevice) {
432 Slog.i(TAG, "Stopped listening for RTSP connection on " + mRemoteDisplayInterface
433 + " from Wifi display: " + mConnectedDevice.deviceName);
434
435 mRemoteDisplay.dispose();
436 mRemoteDisplay = null;
437 mRemoteDisplayInterface = null;
438 mRemoteDisplayConnected = false;
439 mHandler.removeCallbacks(mRtspTimeout);
440
Jeff Brownc9bd4ca2012-09-17 12:20:29 -0700441 setRemoteSubmixOn(false);
442
Jeff Browncbad9762012-09-04 21:57:59 -0700443 mHandler.post(new Runnable() {
444 @Override
445 public void run() {
446 mListener.onDisplayDisconnected();
447 }
448 });
Jeff Browncbad9762012-09-04 21:57:59 -0700449
450 // continue to next step
451 }
452
453 // Step 2. Before we try to connect to a new device, disconnect from the old one.
454 if (mConnectedDevice != null && mConnectedDevice != mDesiredDevice) {
455 Slog.i(TAG, "Disconnecting from Wifi display: " + mConnectedDevice.deviceName);
456
457 final WifiP2pDevice oldDevice = mConnectedDevice;
458 mWifiP2pManager.removeGroup(mWifiP2pChannel, new ActionListener() {
459 @Override
460 public void onSuccess() {
461 Slog.i(TAG, "Disconnected from Wifi display: " + oldDevice.deviceName);
462 next();
463 }
464
465 @Override
466 public void onFailure(int reason) {
467 Slog.i(TAG, "Failed to disconnect from Wifi display: "
468 + oldDevice.deviceName + ", reason=" + reason);
469 next();
470 }
471
472 private void next() {
473 if (mConnectedDevice == oldDevice) {
474 mConnectedDevice = null;
475 updateConnection();
476 }
477 }
478 });
479 return; // wait for asynchronous callback
480 }
481
482 // Step 3. Before we try to connect to a new device, stop trying to connect
483 // to the old one.
484 if (mConnectingDevice != null && mConnectingDevice != mDesiredDevice) {
485 Slog.i(TAG, "Canceling connection to Wifi display: " + mConnectingDevice.deviceName);
486
487 mHandler.removeCallbacks(mConnectionTimeout);
488
489 final WifiP2pDevice oldDevice = mConnectingDevice;
490 mWifiP2pManager.cancelConnect(mWifiP2pChannel, new ActionListener() {
491 @Override
492 public void onSuccess() {
493 Slog.i(TAG, "Canceled connection to Wifi display: " + oldDevice.deviceName);
494 next();
495 }
496
497 @Override
498 public void onFailure(int reason) {
499 Slog.i(TAG, "Failed to cancel connection to Wifi display: "
500 + oldDevice.deviceName + ", reason=" + reason);
501 next();
502 }
503
504 private void next() {
505 if (mConnectingDevice == oldDevice) {
506 mConnectingDevice = null;
507 updateConnection();
508 }
509 }
510 });
511 return; // wait for asynchronous callback
512 }
513
514 // Step 4. If we wanted to disconnect, then mission accomplished.
515 if (mDesiredDevice == null) {
516 return; // done
517 }
518
519 // Step 5. Try to connect.
520 if (mConnectedDevice == null && mConnectingDevice == null) {
521 Slog.i(TAG, "Connecting to Wifi display: " + mDesiredDevice.deviceName);
522
523 mConnectingDevice = mDesiredDevice;
524 WifiP2pConfig config = new WifiP2pConfig();
525 config.deviceAddress = mConnectingDevice.deviceAddress;
Irfan Sheriffe0c28d52012-09-18 12:05:31 -0700526 // Helps with STA & P2P concurrency
527 config.groupOwnerIntent = WifiP2pConfig.MAX_GROUP_OWNER_INTENT;
Jeff Browncbad9762012-09-04 21:57:59 -0700528
Jeff Browne08ae382012-09-07 20:36:36 -0700529 final WifiDisplay display = createWifiDisplay(mConnectingDevice);
530 mHandler.post(new Runnable() {
531 @Override
532 public void run() {
533 mListener.onDisplayConnecting(display);
534 }
535 });
536
Jeff Browncbad9762012-09-04 21:57:59 -0700537 final WifiP2pDevice newDevice = mDesiredDevice;
538 mWifiP2pManager.connect(mWifiP2pChannel, config, new ActionListener() {
539 @Override
540 public void onSuccess() {
541 // The connection may not yet be established. We still need to wait
542 // for WIFI_P2P_CONNECTION_CHANGED_ACTION. However, we might never
543 // get that broadcast, so we register a timeout.
544 Slog.i(TAG, "Initiated connection to Wifi display: " + newDevice.deviceName);
545
546 mHandler.postDelayed(mConnectionTimeout, CONNECTION_TIMEOUT_SECONDS * 1000);
547 }
548
549 @Override
550 public void onFailure(int reason) {
Jeff Browncbad9762012-09-04 21:57:59 -0700551 if (mConnectingDevice == newDevice) {
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700552 Slog.i(TAG, "Failed to initiate connection to Wifi display: "
553 + newDevice.deviceName + ", reason=" + reason);
Jeff Brown89d55462012-09-19 11:33:42 -0700554 mHandler.post(new Runnable() {
555 @Override
556 public void run() {
557 mListener.onDisplayDisconnected();
558 }
559 });
560
Jeff Browncbad9762012-09-04 21:57:59 -0700561 mConnectingDevice = null;
Jeff Brown0cfebf22012-09-07 17:41:20 -0700562 handleConnectionFailure(false);
Jeff Browncbad9762012-09-04 21:57:59 -0700563 }
564 }
565 });
566 return; // wait for asynchronous callback
567 }
568
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700569 // Step 6. Listen for incoming connections.
570 if (mConnectedDevice != null && mRemoteDisplay == null) {
Jeff Browncbad9762012-09-04 21:57:59 -0700571 Inet4Address addr = getInterfaceAddress(mConnectedDeviceGroupInfo);
572 if (addr == null) {
573 Slog.i(TAG, "Failed to get local interface address for communicating "
574 + "with Wifi display: " + mConnectedDevice.deviceName);
Jeff Brown0cfebf22012-09-07 17:41:20 -0700575 handleConnectionFailure(false);
Jeff Browncbad9762012-09-04 21:57:59 -0700576 return; // done
577 }
578
Jeff Brownc9bd4ca2012-09-17 12:20:29 -0700579 setRemoteSubmixOn(true);
580
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700581 final WifiP2pDevice oldDevice = mConnectedDevice;
Jeff Brown0f68d162012-09-11 12:18:15 -0700582 final int port = getPortNumber(mConnectedDevice);
Jeff Browncbad9762012-09-04 21:57:59 -0700583 final String iface = addr.getHostAddress() + ":" + port;
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700584 mRemoteDisplayInterface = iface;
Jeff Browncbad9762012-09-04 21:57:59 -0700585
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700586 Slog.i(TAG, "Listening for RTSP connection on " + iface
587 + " from Wifi display: " + mConnectedDevice.deviceName);
588
589 mRemoteDisplay = RemoteDisplay.listen(iface, new RemoteDisplay.Listener() {
Jeff Browncbad9762012-09-04 21:57:59 -0700590 @Override
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700591 public void onDisplayConnected(final Surface surface,
592 final int width, final int height, final int flags) {
593 if (mConnectedDevice == oldDevice && !mRemoteDisplayConnected) {
594 Slog.i(TAG, "Opened RTSP connection with Wifi display: "
595 + mConnectedDevice.deviceName);
596 mRemoteDisplayConnected = true;
597 mHandler.removeCallbacks(mRtspTimeout);
598
599 final WifiDisplay display = createWifiDisplay(mConnectedDevice);
600 mHandler.post(new Runnable() {
601 @Override
602 public void run() {
603 mListener.onDisplayConnected(display,
604 surface, width, height, flags);
605 }
606 });
607 }
Jeff Browncbad9762012-09-04 21:57:59 -0700608 }
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700609
610 @Override
611 public void onDisplayDisconnected() {
612 if (mConnectedDevice == oldDevice) {
613 Slog.i(TAG, "Closed RTSP connection with Wifi display: "
614 + mConnectedDevice.deviceName);
615 mHandler.removeCallbacks(mRtspTimeout);
616 disconnect();
617 }
618 }
619
620 @Override
621 public void onDisplayError(int error) {
622 if (mConnectedDevice == oldDevice) {
623 Slog.i(TAG, "Lost RTSP connection with Wifi display due to error "
624 + error + ": " + mConnectedDevice.deviceName);
625 mHandler.removeCallbacks(mRtspTimeout);
626 handleConnectionFailure(false);
627 }
628 }
629 }, mHandler);
630
631 mHandler.postDelayed(mRtspTimeout, RTSP_TIMEOUT_SECONDS * 1000);
Jeff Browncbad9762012-09-04 21:57:59 -0700632 }
633 }
634
Jeff Brownc9bd4ca2012-09-17 12:20:29 -0700635 private void setRemoteSubmixOn(boolean on) {
636 if (mRemoteSubmixOn != on) {
637 mRemoteSubmixOn = on;
638 mAudioManager.setRemoteSubmixOn(on, REMOTE_SUBMIX_ADDRESS);
639 }
640 }
641
Jeff Browncbad9762012-09-04 21:57:59 -0700642 private void handleStateChanged(boolean enabled) {
Jeff Brown89d55462012-09-19 11:33:42 -0700643 mWifiP2pEnabled = enabled;
644 updateWfdEnableState();
Jeff Browncbad9762012-09-04 21:57:59 -0700645 }
646
647 private void handlePeersChanged() {
Jeff Brown89d55462012-09-19 11:33:42 -0700648 if (mWfdEnabled) {
649 requestPeers();
Jeff Browncbad9762012-09-04 21:57:59 -0700650 }
651 }
652
653 private void handleConnectionChanged(NetworkInfo networkInfo) {
654 mNetworkInfo = networkInfo;
Jeff Brown180bbc72012-09-08 23:15:00 -0700655 if (mWfdEnabled && networkInfo.isConnected()) {
Jeff Browncbad9762012-09-04 21:57:59 -0700656 if (mDesiredDevice != null) {
657 mWifiP2pManager.requestGroupInfo(mWifiP2pChannel, new GroupInfoListener() {
658 @Override
659 public void onGroupInfoAvailable(WifiP2pGroup info) {
660 if (DEBUG) {
661 Slog.d(TAG, "Received group info: " + describeWifiP2pGroup(info));
662 }
663
664 if (mConnectingDevice != null && !info.contains(mConnectingDevice)) {
665 Slog.i(TAG, "Aborting connection to Wifi display because "
666 + "the current P2P group does not contain the device "
Jeff Brown89d55462012-09-19 11:33:42 -0700667 + "we expected to find: " + mConnectingDevice.deviceName
668 + ", group info was: " + describeWifiP2pGroup(info));
Jeff Brown0cfebf22012-09-07 17:41:20 -0700669 handleConnectionFailure(false);
Jeff Browncbad9762012-09-04 21:57:59 -0700670 return;
671 }
672
673 if (mDesiredDevice != null && !info.contains(mDesiredDevice)) {
674 disconnect();
675 return;
676 }
677
678 if (mConnectingDevice != null && mConnectingDevice == mDesiredDevice) {
Jeff Brown0cfebf22012-09-07 17:41:20 -0700679 Slog.i(TAG, "Connected to Wifi display: "
680 + mConnectingDevice.deviceName);
Jeff Browncbad9762012-09-04 21:57:59 -0700681
682 mHandler.removeCallbacks(mConnectionTimeout);
683 mConnectedDeviceGroupInfo = info;
684 mConnectedDevice = mConnectingDevice;
685 mConnectingDevice = null;
686 updateConnection();
687 }
688 }
689 });
690 }
691 } else {
692 disconnect();
Jeff Brown180bbc72012-09-08 23:15:00 -0700693
694 // After disconnection for a group, for some reason we have a tendency
695 // to get a peer change notification with an empty list of peers.
696 // Perform a fresh scan.
697 if (mWfdEnabled) {
698 requestPeers();
699 }
Jeff Browncbad9762012-09-04 21:57:59 -0700700 }
701 }
702
703 private final Runnable mConnectionTimeout = new Runnable() {
704 @Override
705 public void run() {
706 if (mConnectingDevice != null && mConnectingDevice == mDesiredDevice) {
707 Slog.i(TAG, "Timed out waiting for Wifi display connection after "
708 + CONNECTION_TIMEOUT_SECONDS + " seconds: "
709 + mConnectingDevice.deviceName);
Jeff Brown0cfebf22012-09-07 17:41:20 -0700710 handleConnectionFailure(true);
Jeff Browncbad9762012-09-04 21:57:59 -0700711 }
712 }
713 };
714
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700715 private final Runnable mRtspTimeout = new Runnable() {
716 @Override
717 public void run() {
718 if (mConnectedDevice != null
719 && mRemoteDisplay != null && !mRemoteDisplayConnected) {
720 Slog.i(TAG, "Timed out waiting for Wifi display RTSP connection after "
721 + RTSP_TIMEOUT_SECONDS + " seconds: "
722 + mConnectedDevice.deviceName);
723 handleConnectionFailure(true);
724 }
725 }
726 };
727
Jeff Brown0cfebf22012-09-07 17:41:20 -0700728 private void handleConnectionFailure(boolean timeoutOccurred) {
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700729 Slog.i(TAG, "Wifi display connection failed!");
730
731 mHandler.post(new Runnable() {
732 @Override
733 public void run() {
734 mListener.onDisplayConnectionFailed();
735 }
736 });
737
Jeff Browncbad9762012-09-04 21:57:59 -0700738 if (mDesiredDevice != null) {
Jeff Brown0cfebf22012-09-07 17:41:20 -0700739 if (mConnectionRetriesLeft > 0) {
Jeff Brown89d55462012-09-19 11:33:42 -0700740 final WifiP2pDevice oldDevice = mDesiredDevice;
Jeff Brown0cfebf22012-09-07 17:41:20 -0700741 mHandler.postDelayed(new Runnable() {
742 @Override
743 public void run() {
Jeff Brown89d55462012-09-19 11:33:42 -0700744 if (mDesiredDevice == oldDevice && mConnectionRetriesLeft > 0) {
745 mConnectionRetriesLeft -= 1;
746 Slog.i(TAG, "Retrying Wifi display connection. Retries left: "
747 + mConnectionRetriesLeft);
748 retryConnection();
749 }
Jeff Brown0cfebf22012-09-07 17:41:20 -0700750 }
751 }, timeoutOccurred ? 0 : CONNECT_RETRY_DELAY_MILLIS);
752 } else {
753 disconnect();
754 }
Jeff Browncbad9762012-09-04 21:57:59 -0700755 }
756 }
757
758 private static Inet4Address getInterfaceAddress(WifiP2pGroup info) {
759 NetworkInterface iface;
760 try {
761 iface = NetworkInterface.getByName(info.getInterface());
762 } catch (SocketException ex) {
763 Slog.w(TAG, "Could not obtain address of network interface "
764 + info.getInterface(), ex);
765 return null;
766 }
767
768 Enumeration<InetAddress> addrs = iface.getInetAddresses();
769 while (addrs.hasMoreElements()) {
770 InetAddress addr = addrs.nextElement();
771 if (addr instanceof Inet4Address) {
772 return (Inet4Address)addr;
773 }
774 }
775
776 Slog.w(TAG, "Could not obtain address of network interface "
777 + info.getInterface() + " because it had no IPv4 addresses.");
778 return null;
779 }
780
Jeff Brown0f68d162012-09-11 12:18:15 -0700781 private static int getPortNumber(WifiP2pDevice device) {
782 if (device.deviceName.startsWith("DIRECT-")
783 && device.deviceName.endsWith("Broadcom")) {
784 // These dongles ignore the port we broadcast in our WFD IE.
785 return 8554;
786 }
787 return DEFAULT_CONTROL_PORT;
788 }
789
Jeff Browncbad9762012-09-04 21:57:59 -0700790 private static boolean isWifiDisplay(WifiP2pDevice device) {
Jeff Brown0f68d162012-09-11 12:18:15 -0700791 return device.wfdInfo != null
792 && device.wfdInfo.isWfdEnabled()
793 && isPrimarySinkDeviceType(device.wfdInfo.getDeviceType());
794 }
795
796 private static boolean isPrimarySinkDeviceType(int deviceType) {
797 return deviceType == WifiP2pWfdInfo.PRIMARY_SINK
798 || deviceType == WifiP2pWfdInfo.SOURCE_OR_PRIMARY_SINK;
Jeff Browncbad9762012-09-04 21:57:59 -0700799 }
800
801 private static String describeWifiP2pDevice(WifiP2pDevice device) {
802 return device != null ? device.toString().replace('\n', ',') : "null";
803 }
804
805 private static String describeWifiP2pGroup(WifiP2pGroup group) {
806 return group != null ? group.toString().replace('\n', ',') : "null";
807 }
808
Jeff Browne08ae382012-09-07 20:36:36 -0700809 private static WifiDisplay createWifiDisplay(WifiP2pDevice device) {
Jeff Brown89d55462012-09-19 11:33:42 -0700810 return new WifiDisplay(device.deviceAddress, device.deviceName, null);
Jeff Browne08ae382012-09-07 20:36:36 -0700811 }
812
Jeff Browncbad9762012-09-04 21:57:59 -0700813 private final BroadcastReceiver mWifiP2pReceiver = new BroadcastReceiver() {
814 @Override
815 public void onReceive(Context context, Intent intent) {
816 final String action = intent.getAction();
817 if (action.equals(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)) {
Jeff Brown89d55462012-09-19 11:33:42 -0700818 // This broadcast is sticky so we'll always get the initial Wifi P2P state
819 // on startup.
Jeff Browncbad9762012-09-04 21:57:59 -0700820 boolean enabled = (intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,
821 WifiP2pManager.WIFI_P2P_STATE_DISABLED)) ==
822 WifiP2pManager.WIFI_P2P_STATE_ENABLED;
823 if (DEBUG) {
824 Slog.d(TAG, "Received WIFI_P2P_STATE_CHANGED_ACTION: enabled="
825 + enabled);
826 }
827
828 handleStateChanged(enabled);
829 } else if (action.equals(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)) {
830 if (DEBUG) {
831 Slog.d(TAG, "Received WIFI_P2P_PEERS_CHANGED_ACTION.");
832 }
833
834 handlePeersChanged();
835 } else if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
836 NetworkInfo networkInfo = (NetworkInfo)intent.getParcelableExtra(
837 WifiP2pManager.EXTRA_NETWORK_INFO);
838 if (DEBUG) {
839 Slog.d(TAG, "Received WIFI_P2P_CONNECTION_CHANGED_ACTION: networkInfo="
840 + networkInfo);
841 }
842
843 handleConnectionChanged(networkInfo);
844 }
845 }
846 };
847
848 /**
849 * Called on the handler thread when displays are connected or disconnected.
850 */
851 public interface Listener {
Jeff Brown89d55462012-09-19 11:33:42 -0700852 void onFeatureStateChanged(int featureState);
Jeff Browne08ae382012-09-07 20:36:36 -0700853
854 void onScanStarted();
Jeff Brown89d55462012-09-19 11:33:42 -0700855 void onScanFinished(WifiDisplay[] availableDisplays);
Jeff Browne08ae382012-09-07 20:36:36 -0700856
857 void onDisplayConnecting(WifiDisplay display);
858 void onDisplayConnectionFailed();
Jeff Brownf8f0edd2012-09-11 17:05:11 -0700859 void onDisplayConnected(WifiDisplay display,
860 Surface surface, int width, int height, int flags);
Jeff Browncbad9762012-09-04 21:57:59 -0700861 void onDisplayDisconnected();
862 }
863}