org.webrtc.DataChannel Java Examples

The following examples show how to use org.webrtc.DataChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: P2PPeerConnectionChannel.java    From owt-client-android with Apache License 2.0 7 votes vote down vote up
void sendData(final String message, ActionCallback<Void> callback) {
    Long msgId = ++messageId;
    final JSONObject messageObj = new JSONObject();
    try {
        messageObj.put("id", msgId);
        messageObj.put("data", message);
    } catch (JSONException e) {
        DCHECK(e);
    }
    if (callback != null) {
        sendMsgCallbacks.put(msgId, callback);
    }

    if (localDataChannel == null || localDataChannel.state() != OPEN) {
        queuedMessage.add(messageObj.toString());
        if (localDataChannel == null) {
            createDataChannel();
        }
        return;
    }

    ByteBuffer byteBuffer =
            ByteBuffer.wrap(messageObj.toString().getBytes(Charset.forName("UTF-8")));
    DataChannel.Buffer buffer = new DataChannel.Buffer(byteBuffer, false);
    localDataChannel.send(buffer);
}
 
Example #2
Source File: WebRtcCallService.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleLocalHangup(Intent intent) {

        CallState currentState = this.callState.get();
        ALog.i(TAG, "handleLocalHangup: " + currentState);

        if (WebRtcCallService.accountContext == null || !WebRtcCallService.accountContext.equals(getAccountContextFromIntent(intent))) {
            ALog.w(TAG, "Account context is null or not equals to the intent's one");
            return;
        }

        if (this.dataChannel != null && this.recipient != null && this.callId != -1L) {

            this.dataChannel.send(new DataChannel.Buffer(ByteBuffer.wrap(Data.newBuilder().setHangup(Hangup.newBuilder().setId(this.callId)).build().toByteArray()), false));
            sendMessage(WebRtcCallService.accountContext, this.recipient, SignalServiceCallMessage.forHangup(new HangupMessage(this.callId)));

        }
        if (recipient != null) {
            sendMessage(WebRtcViewModel.State.CALL_DISCONNECTED, this.recipient, localCameraState, remoteVideoEnabled, bluetoothAvailable, microphoneEnabled);

            if (currentState != CallState.STATE_IDLE && currentState != CallState.STATE_CONNECTED) {
                insertMissedCallFromHangup(WebRtcCallService.accountContext, this.recipient, false);
            }
        }
        terminate();
    }
 
Example #3
Source File: PeerConnectionChannel.java    From owt-client-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onStateChange() {
    if (disposed) {
        return;
    }
    callbackExecutor.execute(() -> {
        if (localDataChannel.state() == DataChannel.State.OPEN) {
            for (int i = 0; i < queuedMessage.size(); i++) {
                ByteBuffer byteBuffer = ByteBuffer.wrap(
                        queuedMessage.get(i).getBytes(Charset.forName("UTF-8")));
                DataChannel.Buffer buffer = new DataChannel.Buffer(byteBuffer, false);
                localDataChannel.send(buffer);
            }
            queuedMessage.clear();
        }
    });
}
 
Example #4
Source File: RespokeDirectConnection.java    From respoke-sdk-android with MIT License 6 votes vote down vote up
/**
 *  Notify the direct connection instance that the peer connection has opened the specified data channel
 *
 *  @param newDataChannel    The DataChannel that has opened
 */
public void peerConnectionDidOpenDataChannel(DataChannel newDataChannel) {
    if (null != dataChannel) {
        // Replacing the previous connection, so disable observer messages from the old instance
        dataChannel.unregisterObserver();
    } else {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            public void run() {
                if (null != listenerReference) {
                    Listener listener = listenerReference.get();
                    if (null != listener) {
                        listener.onStart(RespokeDirectConnection.this);
                    }
                }
            }
        });
    }

    dataChannel = newDataChannel;
    newDataChannel.registerObserver(this);
}
 
Example #5
Source File: RespokeDirectConnection.java    From respoke-sdk-android with MIT License 6 votes vote down vote up
/**
 *  Send a message to the remote client through the direct connection.
 *
 *  @param message             The message to send
 *  @param completionListener  A listener to receive a notification on the success of the asynchronous operation
 */
public void sendMessage(String message, final Respoke.TaskCompletionListener completionListener) {
    if (isActive()) {
        JSONObject jsonMessage = new JSONObject();
        try {
            jsonMessage.put("message", message);
            byte[] rawMessage = jsonMessage.toString().getBytes(Charset.forName("UTF-8"));
            ByteBuffer directData = ByteBuffer.allocateDirect(rawMessage.length);
            directData.put(rawMessage);
            directData.flip();
            DataChannel.Buffer data = new DataChannel.Buffer(directData, false);

            if (dataChannel.send(data)) {
                Respoke.postTaskSuccess(completionListener);
            } else {
                Respoke.postTaskError(completionListener, "Error sending message");
            }
        } catch (JSONException e) {
            Respoke.postTaskError(completionListener, "Unable to encode message to JSON");
        }
    } else {
        Respoke.postTaskError(completionListener, "DataChannel not in an open state");
    }
}
 
Example #6
Source File: WebRtcCallService.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDataChannel(DataChannel dataChannel) {
    ALog.logForSecret(TAG, "onDataChannel:" + dataChannel.label());

    if (dataChannel.label().equals(DATA_CHANNEL_NAME)) {
        this.dataChannel = dataChannel;
        this.dataChannel.registerObserver(this);
    }
}
 
Example #7
Source File: WebRtcCallService.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleSetMuteVideo(Intent intent) {

        if (!PermissionUtil.INSTANCE.checkCamera(this)) {
            return;
        }

        boolean muted = intent.getBooleanExtra(EXTRA_MUTE, false);

        if (this.peerConnection != null) {
            this.peerConnection.setVideoEnabled(!muted);
        }

        if (this.callId != -1L && this.dataChannel != null) {
            this.dataChannel.send(new DataChannel.Buffer(ByteBuffer.wrap(Data.newBuilder()
                    .setVideoStreamingStatus(WebRtcDataProtos.VideoStreamingStatus.newBuilder()
                            .setId(this.callId)
                            .setEnabled(!muted))
                    .build().toByteArray()), false));
        }

        if (muted) {
            sCurrentCallType = CameraState.Direction.NONE;
            localCameraState = new CameraState(CameraState.Direction.NONE, localCameraState.getCameraCount());
        } else {
            sCurrentCallType = CameraState.Direction.FRONT;
            localCameraState = new CameraState(CameraState.Direction.FRONT, localCameraState.getCameraCount());
        }

        if (this.callState.get() == CallState.STATE_CONNECTED) {
            if (localCameraState.isEnabled()) {
                this.lockManager.updatePhoneState(LockManager.PhoneState.IN_VIDEO);
            } else {
                this.lockManager.updatePhoneState(LockManager.PhoneState.IN_CALL);
            }
        }

        if (this.recipient != null) {
            sendMessage(viewModelStateFor(callState.get()), this.recipient, localCameraState, remoteVideoEnabled, bluetoothAvailable, microphoneEnabled);
        }
    }
 
Example #8
Source File: WebRtcCallService.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleDenyCall(Intent intent) {
    try {
        CallState currentState = this.callState.get();
        if (currentState != CallState.STATE_LOCAL_RINGING) {
            ALog.w(TAG, "handleDenyCall fail, current state is not local ringing");
            return;
        }

        if (recipient == null || callId == -1L || dataChannel == null || WebRtcCallService.accountContext == null) {
            ALog.i(TAG, "handleDenyCall fail, recipient or callId or dataChannel is null");
            return;
        }

        if (!WebRtcCallService.accountContext.equals(getAccountContextFromIntent(intent))) {
            ALog.w(TAG, "Not current major user.");
            return;
        }

        this.dataChannel.send(new DataChannel.Buffer(ByteBuffer.wrap(Data.newBuilder().setHangup(Hangup.newBuilder().setId(this.callId)).build().toByteArray()), false));
        sendMessage(WebRtcCallService.accountContext, recipient, SignalServiceCallMessage.forHangup(new HangupMessage(this.callId)));

        if (currentState != CallState.STATE_IDLE && currentState != CallState.STATE_CONNECTED) {
            insertMissedCallFromHangup(WebRtcCallService.accountContext, this.recipient, true);
        }
    } finally {
        this.terminate();
    }
}
 
Example #9
Source File: WebRtcCallService.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleAnswerCall(Intent intent) {
    ALog.d(TAG, "handleAnswerCall");
    if (callState.get() != CallState.STATE_LOCAL_RINGING) {
        ALog.w(TAG, "handleAnswerCall fail, current state is not local ringing");
        return;
    }

    if (peerConnection == null || dataChannel == null || recipient == null || WebRtcCallService.accountContext == null || callId == -1L) {
        ALog.i(TAG, "handleAnswerCall fail, peerConnection or dataChannel or recipient callId is null");
        terminate();
        return;
    }
    if (!WebRtcCallService.accountContext.equals(getAccountContextFromIntent(intent))) {
        ALog.w(TAG, "Not current major user.");
        return;
    }

    setCallInProgressNotification(TYPE_ESTABLISHED, recipient);

    this.peerConnection.setAudioEnabled(true);
    this.peerConnection.setVideoEnabled(localCameraState.isEnabled());
    this.dataChannel.send(new DataChannel.Buffer(ByteBuffer.wrap(Data.newBuilder().setConnected(Connected.newBuilder().setId(this.callId)).build().toByteArray()), false));

    intent.putExtra(EXTRA_CALL_ID, callId);
    intent.putExtra(EXTRA_REMOTE_ADDRESS, recipient.getAddress());
    handleCallConnected(intent);
}
 
Example #10
Source File: RespokeDirectConnection.java    From respoke-sdk-android with MIT License 5 votes vote down vote up
/**
 *  Establish a new direct connection instance with the peer connection for the call. This is used internally to the SDK and should not be called directly by your client application.
 */
public void createDataChannel() {
    if (null != callReference) {
        RespokeCall call = callReference.get();
        if (null != call) {
            PeerConnection peerConnection = call.getPeerConnection();
            dataChannel = peerConnection.createDataChannel("respokeDataChannel", new DataChannel.Init());
            dataChannel.registerObserver(this);
        }
    }
}
 
Example #11
Source File: AppRTCDemoActivity.java    From droidkit-webrtc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void createDataChannelToRegressionTestBug2302(
    PeerConnection pc) {
  DataChannel dc = pc.createDataChannel("dcLabel", new DataChannel.Init());
  abortUnless("dcLabel".equals(dc.label()), "Unexpected label corruption?");
  dc.close();
  dc.dispose();
}
 
Example #12
Source File: AppRTCDemoActivity.java    From droidkit-webrtc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override public void onDataChannel(final DataChannel dc) {
  runOnUiThread(new Runnable() {
      public void run() {
        throw new RuntimeException(
            "AppRTC doesn't use data channels, but got: " + dc.label() +
            " anyway!");
      }
    });
}
 
Example #13
Source File: PeerConnectionClient.java    From sample-videoRTC with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChannel(final DataChannel dc) {
  Log.d(TAG, "New Data channel " + dc.label());

  if (!dataChannelEnabled)
    return;

  dc.registerObserver(new DataChannel.Observer() {
    @Override
    public void onBufferedAmountChange(long previousAmount) {
      Log.d(TAG, "Data channel buffered amount changed: " + dc.label() + ": " + dc.state());
    }

    @Override
    public void onStateChange() {
      Log.d(TAG, "Data channel state changed: " + dc.label() + ": " + dc.state());
    }

    @Override
    public void onMessage(final DataChannel.Buffer buffer) {
      if (buffer.binary) {
        Log.d(TAG, "Received binary msg over " + dc);
        return;
      }
      ByteBuffer data = buffer.data;
      final byte[] bytes = new byte[data.capacity()];
      data.get(bytes);
      String strData = new String(bytes, Charset.forName("UTF-8"));
      Log.d(TAG, "Got msg: " + strData + " over " + dc);
    }
  });
}
 
Example #14
Source File: PeerConnectionChannel.java    From owt-client-android with Apache License 2.0 5 votes vote down vote up
protected void createDataChannel() {
    DCHECK(pcExecutor);
    DCHECK(localDataChannel == null);
    pcExecutor.execute(() -> {
        if (disposed()) {
            return;
        }
        DataChannel.Init init = new DataChannel.Init();
        localDataChannel = peerConnection.createDataChannel("message", init);
        localDataChannel.registerObserver(PeerConnectionChannel.this);
    });
}
 
Example #15
Source File: AppRTCDemoActivity.java    From WebRTCDemo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void createDataChannelToRegressionTestBug2302(
    PeerConnection pc) {
  DataChannel dc = pc.createDataChannel("dcLabel", new DataChannel.Init());
  abortUnless("dcLabel".equals(dc.label()), "Unexpected label corruption?");
  dc.close();
  dc.dispose();
}
 
Example #16
Source File: PeerConnectionClient.java    From restcomm-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onDataChannel(final DataChannel dc) {
  Log.d(TAG, "New Data channel " + dc.label());

  if (!dataChannelEnabled)
    return;

  dc.registerObserver(new DataChannel.Observer() {
    @Override
    public void onBufferedAmountChange(long previousAmount) {
      Log.d(TAG, "Data channel buffered amount changed: " + dc.label() + ": " + dc.state());
    }

    @Override
    public void onStateChange() {
      Log.d(TAG, "Data channel state changed: " + dc.label() + ": " + dc.state());
    }

    @Override
    public void onMessage(final DataChannel.Buffer buffer) {
      if (buffer.binary) {
        Log.d(TAG, "Received binary msg over " + dc);
        return;
      }
      ByteBuffer data = buffer.data;
      final byte[] bytes = new byte[data.capacity()];
      data.get(bytes);
      String strData = new String(bytes, Charset.forName("UTF-8"));
      Log.d(TAG, "Got msg: " + strData + " over " + dc);
    }
  });
}
 
Example #17
Source File: PeerConnectionChannel.java    From owt-client-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChannel(final DataChannel dataChannel) {
    if (disposed) {
        return;
    }
    callbackExecutor.execute(() -> {
        localDataChannel = dataChannel;
        localDataChannel.registerObserver(PeerConnectionChannel.this);
    });
}
 
Example #18
Source File: NBMWebRTCPeer.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
public void run() {
    if (mediaResourceManager.getLocalMediaStream() == null) {
        mediaResourceManager.createMediaConstraints();
        startLocalMediaSync();
    }

    NBMPeerConnection connection = peerConnectionResourceManager.getConnection(connectionId);

    if (connection == null) {
        if (signalingParameters != null) {

            connection = peerConnectionResourceManager.createPeerConnection(
                                                        signalingParameters,
                                                        mediaResourceManager.getPcConstraints(),
                                                        connectionId);
            connection.addObserver(observer);
            connection.addObserver(mediaResourceManager);
            if (includeLocalMedia) {
                connection.getPc().addStream(mediaResourceManager.getLocalMediaStream());
            }

            DataChannel.Init init =  new DataChannel.Init();
            createDataChannel(this.connectionId, "default", init);

            // Create offer. Offer SDP will be sent to answering client in
            // PeerConnectionEvents.onLocalDescription event.
            connection.createOffer(mediaResourceManager.getSdpMediaConstraints());
        }
    }
}
 
Example #19
Source File: PeerConnectionChannel.java    From owt-client-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(final DataChannel.Buffer buffer) {
    if (disposed) {
        return;
    }
    callbackExecutor.execute(() -> {
        ByteBuffer data = buffer.data;
        final byte[] bytes = new byte[data.capacity()];
        data.get(bytes);
        String message = new String(bytes);
        observer.onDataChannelMessage(key, message);
    });
}
 
Example #20
Source File: RespokeCall.java    From respoke-sdk-android with MIT License 5 votes vote down vote up
@Override public void onDataChannel(final DataChannel dc) {
    if (isActive()) {
        if (null != directConnection) {
            directConnection.peerConnectionDidOpenDataChannel(dc);
        } else {
            Log.d(TAG, "Direct connection opened, but no object to handle it!");
        }
    }
}
 
Example #21
Source File: WebRTCNativeMgr.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
public void onCreateSuccess(SessionDescription sessionDescription) {
  try {
    if (DEBUG) {
      Log.d(LOG_TAG, "sdp.type = " + sessionDescription.type.canonicalForm());
      Log.d(LOG_TAG, "sdp.description = " + sessionDescription.description);
    }
    DataChannel.Init init = new DataChannel.Init();
    if (sessionDescription.type == SessionDescription.Type.OFFER) {
      if (DEBUG) {
        Log.d(LOG_TAG, "Got offer, about to set remote description (again?)");
      }
      peerConnection.setRemoteDescription(sdpObserver, sessionDescription);
    } else if (sessionDescription.type == SessionDescription.Type.ANSWER) {
      if (DEBUG) {
        Log.d(LOG_TAG, "onCreateSuccess: type = ANSWER");
      }
      peerConnection.setLocalDescription(sdpObserver, sessionDescription);
      haveLocalDescription = true;
      /* Send to peer */
      JSONObject offer = new JSONObject();
      offer.put("type", "answer");
      offer.put("sdp", sessionDescription.description);
      JSONObject response = new JSONObject();
      response.put("offer", offer);
      sendRendezvous(response);
    }
  } catch (Exception e) {
    Log.e(LOG_TAG, "Exception during onCreateSuccess", e);
  }
}
 
Example #22
Source File: WebRTCNativeMgr.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
public void onDataChannel(DataChannel dataChannel) {
  if (DEBUG) {
    Log.d(LOG_TAG, "Have Data Channel!");
    Log.d(LOG_TAG, "v5");
  }
  WebRTCNativeMgr.this.dataChannel = dataChannel;
  dataChannel.registerObserver(dataObserver);
  keepPolling = false;    // Turn off talking to the rendezvous server
  timer.cancel();
  if (DEBUG) {
    Log.d(LOG_TAG, "Poller() Canceled");
  }
  seenNonces.clear();
}
 
Example #23
Source File: NBMPeerConnection.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChannel(DataChannel dataChannel) {
    Log.i(TAG, "[datachannel] Peer opened data channel");
    for (NBMWebRTCPeer.Observer observer : observers) {
        observer.onDataChannel(dataChannel, NBMPeerConnection.this);
    }
}
 
Example #24
Source File: NBMPeerConnection.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
public DataChannel getDataChannel(String dataChannelId){
    ObservedDataChannel channel = this.observedDataChannels.get(dataChannelId);
    if (channel == null) {
        return null;
    }
    else {
        return channel.getChannel();
    }
}
 
Example #25
Source File: PeerVideoActivity.java    From nubo-test with Apache License 2.0 5 votes vote down vote up
public void sendHelloMessage(DataChannel channel) {
    byte[] rawMessage = "Hello Peer!".getBytes(Charset.forName("UTF-8"));
    ByteBuffer directData = ByteBuffer.allocateDirect(rawMessage.length);
    directData.put(rawMessage);
    directData.flip();
    DataChannel.Buffer data = new DataChannel.Buffer(directData, false);
    channel.send(data);
}
 
Example #26
Source File: PeerVideoActivity.java    From nubo-test with Apache License 2.0 5 votes vote down vote up
@Override
public void onStateChange(NBMPeerConnection connection, DataChannel channel) {
    Log.i(TAG, "[datachannel] DataChannel onStateChange: " + channel.state());
    if (channel.state() == DataChannel.State.OPEN) {
        sendHelloMessage(channel);
        Log.i(TAG, "[datachannel] Datachannel open, sending first hello");
    }
}
 
Example #27
Source File: NBMPeerConnection.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public HashMap<String, DataChannel> getDataChannels(){
    HashMap<String, DataChannel> channels = new HashMap<>();
    for (HashMap.Entry<String, ObservedDataChannel> entry : observedDataChannels.entrySet()) {
        String key = entry.getKey();
        ObservedDataChannel value = entry.getValue();
        channels.put(key, value.getChannel());
    }
    return channels;
}
 
Example #28
Source File: NBMPeerConnection.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(DataChannel.Buffer buffer) {
    Log.i(TAG, "[ObservedDataChannel] NBMPeerConnection onMessage");
    for (NBMWebRTCPeer.Observer observer : observers) {
        observer.onMessage(buffer, NBMPeerConnection.this, channel);
    }
}
 
Example #29
Source File: NBMPeerConnection.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
public ObservedDataChannel(String label, DataChannel.Init init) {
    channel = pc.createDataChannel(label, init);
    if (channel != null) {
        channel.registerObserver(this);
        Log.i(TAG, "Created data channel with Id: " + label);
    }
    else {
        Log.e(TAG, "Failed to create data channel with Id: " + label);
    }
}
 
Example #30
Source File: NBMWebRTCPeer.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
public DataChannel createDataChannel(String connectionId, String dataChannelId, DataChannel.Init init) {
    NBMPeerConnection connection = peerConnectionResourceManager.getConnection(connectionId);
    if (connection!=null) {
        return connection.createDataChannel(dataChannelId, init);
    }
    else {
        Log.e(TAG, "Cannot find connection by id: " + connectionId);
    }
    return null;
}