Sync Android AppRTCDemo with internal repo.

- Fixed some Lint warnings.
- Switch to OPUS by default.
- Add check to WebSocket connection that public methods are called
on correct thread.

R=jiayl@webrtc.org, wzh@webrtc.org

Review URL: https://webrtc-codereview.appspot.com/36669004

git-svn-id: http://webrtc.googlecode.com/svn/trunk@8032 4adac7df-926f-26a2-2b94-8c16560cd09d
This commit is contained in:
glaznev@webrtc.org
2015-01-09 19:34:06 +00:00
parent 9657265f39
commit 80452d70cb
8 changed files with 96 additions and 64 deletions

View File

@@ -116,6 +116,7 @@ public class AppRTCDemoActivity extends Activity
Thread.setDefaultUncaughtExceptionHandler( Thread.setDefaultUncaughtExceptionHandler(
new UnhandledExceptionHandler(this)); new UnhandledExceptionHandler(this));
iceConnected = false; iceConnected = false;
signalingParameters = null;
rootView = findViewById(android.R.id.content); rootView = findViewById(android.R.id.content);
encoderStatView = (TextView) findViewById(R.id.encoder_stat); encoderStatView = (TextView) findViewById(R.id.encoder_stat);
@@ -277,6 +278,10 @@ public class AppRTCDemoActivity extends Activity
pc.createPeerConnectionFactory( pc.createPeerConnectionFactory(
thisCopy, hwCodec, VideoRendererGui.getEGLContext(), thisCopy); thisCopy, hwCodec, VideoRendererGui.getEGLContext(), thisCopy);
} }
if (signalingParameters != null) {
Log.w(TAG, "EGL context is ready after room connection.");
onConnectedToRoomInternal(signalingParameters);
}
} }
}); });
} }
@@ -487,14 +492,11 @@ public class AppRTCDemoActivity extends Activity
// are routed to UI thread. // are routed to UI thread.
private void onConnectedToRoomInternal(final SignalingParameters params) { private void onConnectedToRoomInternal(final SignalingParameters params) {
signalingParameters = params; signalingParameters = params;
logAndToast("Creating peer connection...");
if (pc == null) { if (pc == null) {
// Create peer connection factory if render EGL context ready event Log.w(TAG, "Room is connected, but EGL context is not ready yet.");
// has not been fired yet. return;
pc = new PeerConnectionClient();
pc.createPeerConnectionFactory(
this, hwCodec, VideoRendererGui.getEGLContext(), this);
} }
logAndToast("Creating peer connection...");
pc.createPeerConnection( pc.createPeerConnection(
localRender, remoteRender, signalingParameters, startBitrate); localRender, remoteRender, signalingParameters, startBitrate);
if (pc.isHDVideo()) { if (pc.isHDVideo()) {

View File

@@ -63,6 +63,7 @@ import java.util.regex.Pattern;
*/ */
public class PeerConnectionClient { public class PeerConnectionClient {
private static final String TAG = "PCRTCClient"; private static final String TAG = "PCRTCClient";
private static final boolean PREFER_ISAC = false;
public static final String VIDEO_TRACK_ID = "ARDAMSv0"; public static final String VIDEO_TRACK_ID = "ARDAMSv0";
public static final String AUDIO_TRACK_ID = "ARDAMSa0"; public static final String AUDIO_TRACK_ID = "ARDAMSa0";
@@ -178,7 +179,8 @@ public class PeerConnectionClient {
Context context, Context context,
boolean vp8HwAcceleration, boolean vp8HwAcceleration,
EGLContext renderEGLContext) { EGLContext renderEGLContext) {
Log.d(TAG, "Create peer connection factory."); Log.d(TAG, "Create peer connection factory with EGLContext "
+ renderEGLContext);
isError = false; isError = false;
if (!PeerConnectionFactory.initializeAndroidGlobals( if (!PeerConnectionFactory.initializeAndroidGlobals(
context, true, true, vp8HwAcceleration, renderEGLContext)) { context, true, true, vp8HwAcceleration, renderEGLContext)) {
@@ -292,6 +294,7 @@ public class PeerConnectionClient {
@Override @Override
public void run() { public void run() {
if (pc != null && !isError) { if (pc != null && !isError) {
Log.d(TAG, "PC Create OFFER");
isInitiator = true; isInitiator = true;
pc.createOffer(sdpObserver, sdpMediaConstraints); pc.createOffer(sdpObserver, sdpMediaConstraints);
} }
@@ -304,6 +307,7 @@ public class PeerConnectionClient {
@Override @Override
public void run() { public void run() {
if (pc != null && !isError) { if (pc != null && !isError) {
Log.d(TAG, "PC create ANSWER");
isInitiator = false; isInitiator = false;
pc.createAnswer(sdpObserver, sdpMediaConstraints); pc.createAnswer(sdpObserver, sdpMediaConstraints);
} }
@@ -333,7 +337,10 @@ public class PeerConnectionClient {
if (pc == null || isError) { if (pc == null || isError) {
return; return;
} }
String sdpDescription = preferISAC(sdp.description); String sdpDescription = sdp.description;
if (PREFER_ISAC) {
sdpDescription = preferISAC(sdpDescription);
}
if (startBitrate > 0) { if (startBitrate > 0) {
sdpDescription = setStartBitrate(sdpDescription, startBitrate); sdpDescription = setStartBitrate(sdpDescription, startBitrate);
} }
@@ -672,8 +679,12 @@ public class PeerConnectionClient {
reportError("Multiple SDP create."); reportError("Multiple SDP create.");
return; return;
} }
String sdpDescription = origSdp.description;
if (PREFER_ISAC) {
sdpDescription = preferISAC(sdpDescription);
}
final SessionDescription sdp = new SessionDescription( final SessionDescription sdp = new SessionDescription(
origSdp.type, preferISAC(origSdp.description)); origSdp.type, sdpDescription);
localSdp = sdp; localSdp = sdp;
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override

View File

@@ -82,22 +82,22 @@ public class RoomParametersFetcher {
this.events = events; this.events = events;
httpConnection = new AsyncHttpURLConnection("POST", registerUrl, null, httpConnection = new AsyncHttpURLConnection("POST", registerUrl, null,
new AsyncHttpEvents() { new AsyncHttpEvents() {
@Override @Override
public void OnHttpError(String errorMessage) { public void onHttpError(String errorMessage) {
Log.e(TAG, "Room connection error: " + errorMessage); Log.e(TAG, "Room connection error: " + errorMessage);
events.onSignalingParametersError(errorMessage); events.onSignalingParametersError(errorMessage);
} }
@Override @Override
public void OnHttpComplete(String response) { public void onHttpComplete(String response) {
RoomHttpResponseParse(response); roomHttpResponseParse(response);
} }
}); });
httpConnection.send(); httpConnection.send();
} }
private void RoomHttpResponseParse(String response) { private void roomHttpResponseParse(String response) {
Log.d(TAG, "Room response: " + response); Log.d(TAG, "Room response: " + response);
try { try {
LinkedList<IceCandidate> iceCandidates = null; LinkedList<IceCandidate> iceCandidates = null;

View File

@@ -26,6 +26,10 @@
*/ */
package org.appspot.apprtc; package org.appspot.apprtc;
import org.appspot.apprtc.util.AsyncHttpURLConnection;
import org.appspot.apprtc.util.AsyncHttpURLConnection.AsyncHttpEvents;
import org.appspot.apprtc.util.LooperExecutor;
import android.util.Log; import android.util.Log;
import de.tavendo.autobahn.WebSocket.WebSocketConnectionObserver; import de.tavendo.autobahn.WebSocket.WebSocketConnectionObserver;
@@ -39,15 +43,12 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.LinkedList; import java.util.LinkedList;
import org.appspot.apprtc.util.AsyncHttpURLConnection;
import org.appspot.apprtc.util.AsyncHttpURLConnection.AsyncHttpEvents;
import org.appspot.apprtc.util.LooperExecutor;
/** /**
* WebSocket client implementation. * WebSocket client implementation.
* All public methods should be called from a looper executor thread *
* passed in constructor. * <p>All public methods should be called from a looper executor thread
* All events are issued on the same thread. * passed in a constructor, otherwise exception will be thrown.
* All events are dispatched on the same thread.
*/ */
public class WebSocketChannelClient { public class WebSocketChannelClient {
@@ -66,10 +67,10 @@ public class WebSocketChannelClient {
private boolean closeEvent; private boolean closeEvent;
// WebSocket send queue. Messages are added to the queue when WebSocket // WebSocket send queue. Messages are added to the queue when WebSocket
// client is not registered and are consumed in register() call. // client is not registered and are consumed in register() call.
private LinkedList<String> wsSendQueue; private final LinkedList<String> wsSendQueue;
/** /**
* WebSocketConnectionState is the names of possible WS connection states. * Possible WebSocket connection states.
*/ */
public enum WebSocketConnectionState { public enum WebSocketConnectionState {
NEW, CONNECTED, REGISTERED, CLOSED, ERROR NEW, CONNECTED, REGISTERED, CLOSED, ERROR
@@ -77,7 +78,7 @@ public class WebSocketChannelClient {
/** /**
* Callback interface for messages delivered on WebSocket. * Callback interface for messages delivered on WebSocket.
* All events are invoked from UI thread. * All events are dispatched from a looper executor thread.
*/ */
public interface WebSocketChannelEvents { public interface WebSocketChannelEvents {
public void onWebSocketOpen(); public void onWebSocketOpen();
@@ -102,6 +103,7 @@ public class WebSocketChannelClient {
public void connect(final String wsUrl, final String postUrl, public void connect(final String wsUrl, final String postUrl,
final String roomID, final String clientID) { final String roomID, final String clientID) {
checkIfCalledOnValidThread();
if (state != WebSocketConnectionState.NEW) { if (state != WebSocketConnectionState.NEW) {
Log.e(TAG, "WebSocket is already connected."); Log.e(TAG, "WebSocket is already connected.");
return; return;
@@ -125,6 +127,7 @@ public class WebSocketChannelClient {
} }
public void register() { public void register() {
checkIfCalledOnValidThread();
if (state != WebSocketConnectionState.CONNECTED) { if (state != WebSocketConnectionState.CONNECTED) {
Log.w(TAG, "WebSocket register() in state " + state); Log.w(TAG, "WebSocket register() in state " + state);
return; return;
@@ -138,28 +141,25 @@ public class WebSocketChannelClient {
ws.sendTextMessage(json.toString()); ws.sendTextMessage(json.toString());
state = WebSocketConnectionState.REGISTERED; state = WebSocketConnectionState.REGISTERED;
// Send any previously accumulated messages. // Send any previously accumulated messages.
synchronized (wsSendQueue) { for (String sendMessage : wsSendQueue) {
for (String sendMessage : wsSendQueue) { send(sendMessage);
send(sendMessage);
}
wsSendQueue.clear();
} }
wsSendQueue.clear();
} catch (JSONException e) { } catch (JSONException e) {
reportError("WebSocket register JSON error: " + e.getMessage()); reportError("WebSocket register JSON error: " + e.getMessage());
} }
} }
public void send(String message) { public void send(String message) {
checkIfCalledOnValidThread();
switch (state) { switch (state) {
case NEW: case NEW:
case CONNECTED: case CONNECTED:
// Store outgoing messages and send them after websocket client // Store outgoing messages and send them after websocket client
// is registered. // is registered.
Log.d(TAG, "WS ACC: " + message); Log.d(TAG, "WS ACC: " + message);
synchronized (wsSendQueue) { wsSendQueue.add(message);
wsSendQueue.add(message); return;
return;
}
case ERROR: case ERROR:
case CLOSED: case CLOSED:
Log.e(TAG, "WebSocket send() in error or closed state : " + message); Log.e(TAG, "WebSocket send() in error or closed state : " + message);
@@ -181,15 +181,14 @@ public class WebSocketChannelClient {
} }
// This call can be used to send WebSocket messages before WebSocket // This call can be used to send WebSocket messages before WebSocket
// connection is opened. However for now this way of sending messages // connection is opened.
// is not used until possible race condition of arriving ice candidates
// send through websocket before SDP answer sent through http post will be
// resolved.
public void post(String message) { public void post(String message) {
checkIfCalledOnValidThread();
sendWSSMessage("POST", message); sendWSSMessage("POST", message);
} }
public void disconnect(boolean waitForComplete) { public void disconnect(boolean waitForComplete) {
checkIfCalledOnValidThread();
Log.d(TAG, "Disonnect WebSocket. State: " + state); Log.d(TAG, "Disonnect WebSocket. State: " + state);
if (state == WebSocketConnectionState.REGISTERED) { if (state == WebSocketConnectionState.REGISTERED) {
send("{\"type\": \"bye\"}"); send("{\"type\": \"bye\"}");
@@ -209,9 +208,10 @@ public class WebSocketChannelClient {
// sending any pending messages to deleted looper thread. // sending any pending messages to deleted looper thread.
if (waitForComplete) { if (waitForComplete) {
synchronized (closeEventLock) { synchronized (closeEventLock) {
if (!closeEvent) { while (!closeEvent) {
try { try {
closeEventLock.wait(CLOSE_TIMEOUT); closeEventLock.wait(CLOSE_TIMEOUT);
break;
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.e(TAG, "Wait error: " + e.toString()); Log.e(TAG, "Wait error: " + e.toString());
} }
@@ -242,17 +242,26 @@ public class WebSocketChannelClient {
AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection( AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection(
method, postUrl, message, new AsyncHttpEvents() { method, postUrl, message, new AsyncHttpEvents() {
@Override @Override
public void OnHttpError(String errorMessage) { public void onHttpError(String errorMessage) {
reportError("WS " + method + " error: " + errorMessage); reportError("WS " + method + " error: " + errorMessage);
} }
@Override @Override
public void OnHttpComplete(String response) { public void onHttpComplete(String response) {
} }
}); });
httpConnection.send(); httpConnection.send();
} }
// Helper method for debugging purposes. Ensures that WebSocket method is
// called on a looper thread.
private void checkIfCalledOnValidThread() {
if (!executor.checkOnLooperThread()) {
throw new IllegalStateException(
"WebSocket method is not called on valid thread");
}
}
private class WebSocketObserver implements WebSocketConnectionObserver { private class WebSocketObserver implements WebSocketConnectionObserver {
@Override @Override
public void onOpen() { public void onOpen() {

View File

@@ -26,14 +26,15 @@
*/ */
package org.appspot.apprtc; package org.appspot.apprtc;
import android.util.Log;
import org.appspot.apprtc.util.AsyncHttpURLConnection;
import org.appspot.apprtc.util.AsyncHttpURLConnection.AsyncHttpEvents;
import org.appspot.apprtc.util.LooperExecutor;
import org.appspot.apprtc.RoomParametersFetcher.RoomParametersFetcherEvents; import org.appspot.apprtc.RoomParametersFetcher.RoomParametersFetcherEvents;
import org.appspot.apprtc.WebSocketChannelClient.WebSocketChannelEvents; import org.appspot.apprtc.WebSocketChannelClient.WebSocketChannelEvents;
import org.appspot.apprtc.WebSocketChannelClient.WebSocketConnectionState; import org.appspot.apprtc.WebSocketChannelClient.WebSocketConnectionState;
import org.appspot.apprtc.util.AsyncHttpURLConnection;
import org.appspot.apprtc.util.AsyncHttpURLConnection.AsyncHttpEvents;
import org.appspot.apprtc.util.LooperExecutor;
import android.util.Log;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.webrtc.IceCandidate; import org.webrtc.IceCandidate;
@@ -64,7 +65,6 @@ public class WebSocketRTCClient implements AppRTCClient,
private boolean initiator; private boolean initiator;
private SignalingEvents events; private SignalingEvents events;
private WebSocketChannelClient wsClient; private WebSocketChannelClient wsClient;
private RoomParametersFetcher fetcher;
private ConnectionState roomState; private ConnectionState roomState;
private String postMessageUrl; private String postMessageUrl;
private String byeMessageUrl; private String byeMessageUrl;
@@ -109,7 +109,7 @@ public class WebSocketRTCClient implements AppRTCClient,
// Create WebSocket client. // Create WebSocket client.
wsClient = new WebSocketChannelClient(executor, this); wsClient = new WebSocketChannelClient(executor, this);
// Get room parameters. // Get room parameters.
fetcher = new RoomParametersFetcher(loopback, url, new RoomParametersFetcher(loopback, url,
new RoomParametersFetcherEvents() { new RoomParametersFetcherEvents() {
@Override @Override
public void onSignalingParametersReady( public void onSignalingParametersReady(
@@ -371,12 +371,12 @@ public class WebSocketRTCClient implements AppRTCClient,
AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection( AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection(
"POST", url, message, new AsyncHttpEvents() { "POST", url, message, new AsyncHttpEvents() {
@Override @Override
public void OnHttpError(String errorMessage) { public void onHttpError(String errorMessage) {
reportError("GAE POST error: " + errorMessage); reportError("GAE POST error: " + errorMessage);
} }
@Override @Override
public void OnHttpComplete(String response) { public void onHttpComplete(String response) {
if (messageType == MessageType.MESSAGE) { if (messageType == MessageType.MESSAGE) {
try { try {
JSONObject roomJson = new JSONObject(response); JSONObject roomJson = new JSONObject(response);

View File

@@ -29,8 +29,10 @@ package org.appspot.apprtc.util;
import android.os.Build; import android.os.Build;
import android.util.Log; import android.util.Log;
import java.lang.Thread;
/**
* AppRTCUtils provides helper functions for managing thread safety.
*/
public final class AppRTCUtils { public final class AppRTCUtils {
private AppRTCUtils() { private AppRTCUtils() {

View File

@@ -45,9 +45,12 @@ public class AsyncHttpURLConnection {
private final String message; private final String message;
private final AsyncHttpEvents events; private final AsyncHttpEvents events;
/**
* Http requests callbacks.
*/
public interface AsyncHttpEvents { public interface AsyncHttpEvents {
public void OnHttpError(String errorMessage); public void onHttpError(String errorMessage);
public void OnHttpComplete(String response); public void onHttpComplete(String response);
} }
public AsyncHttpURLConnection(String method, String url, String message, public AsyncHttpURLConnection(String method, String url, String message,
@@ -99,18 +102,18 @@ public class AsyncHttpURLConnection {
// Get response. // Get response.
int responseCode = connection.getResponseCode(); int responseCode = connection.getResponseCode();
if (responseCode != 200) { if (responseCode != 200) {
events.OnHttpError("Non-200 response to " + method + " to URL: " events.onHttpError("Non-200 response to " + method + " to URL: "
+ url + " : " + connection.getHeaderField(null)); + url + " : " + connection.getHeaderField(null));
return; return;
} }
InputStream responseStream = connection.getInputStream(); InputStream responseStream = connection.getInputStream();
String response = drainStream(responseStream); String response = drainStream(responseStream);
responseStream.close(); responseStream.close();
events.OnHttpComplete(response); events.onHttpComplete(response);
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
events.OnHttpError("HTTP " + method + " to " + url + " timeout"); events.onHttpError("HTTP " + method + " to " + url + " timeout");
} catch (IOException e) { } catch (IOException e) {
events.OnHttpError("HTTP " + method + " to " + url + " error: " events.onHttpError("HTTP " + method + " to " + url + " error: "
+ e.getMessage()); + e.getMessage());
} }
} }

View File

@@ -82,7 +82,7 @@ public class LooperExecutor extends Thread implements Executor {
return; return;
} }
running = false; running = false;
handler.post( new Runnable() { handler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
Looper.myLooper().quitSafely(); Looper.myLooper().quitSafely();
@@ -91,6 +91,11 @@ public class LooperExecutor extends Thread implements Executor {
}); });
} }
// Checks if current thread is a looper thread.
public boolean checkOnLooperThread() {
return (Thread.currentThread().getId() == threadId);
}
@Override @Override
public synchronized void execute(final Runnable runnable) { public synchronized void execute(final Runnable runnable) {
if (!running) { if (!running) {