Java Code Examples for org.webrtc.PeerConnectionFactory#createPeerConnection()

The following examples show how to use org.webrtc.PeerConnectionFactory#createPeerConnection() . 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: WebRTCNativeMgr.java    From appinventor-extensions with Apache License 2.0 7 votes vote down vote up
public void initiate(ReplForm form, Context context, String code) {

    this.form = form;
    rCode = code;
    /* Initialize WebRTC globally */
    PeerConnectionFactory.initializeAndroidGlobals(context, false);
    /* Setup factory options */
    PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
    /* Create the factory */
    PeerConnectionFactory factory = new PeerConnectionFactory(options);
    /* Create the peer connection using the iceServers we received in the constructor */
    RTCConfiguration rtcConfig = new RTCConfiguration(iceServers);
    rtcConfig.continualGatheringPolicy = ContinualGatheringPolicy.GATHER_CONTINUALLY;
    peerConnection = factory.createPeerConnection(rtcConfig, new MediaConstraints(),
      observer);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
          Poller();
        }
      }, 0, 1000);              // Start the Poller now and then every second
  }
 
Example 2
Source File: PeerConnectionWrapper.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
public PeerConnectionWrapper(@NonNull Context context,
                             @NonNull PeerConnectionFactory factory,
                             @NonNull PeerConnection.Observer observer,
                             @NonNull VideoSink localRenderer,
                             @NonNull List<PeerConnection.IceServer> turnServers,
                             @NonNull CameraEventListener cameraEventListener,
                             @NonNull EglBase eglBase,
                             boolean hideIp) {
    List<PeerConnection.IceServer> iceServers = new LinkedList<>();
    iceServers.add(STUN_SERVER);
    iceServers.addAll(turnServers);

    this.iceServers = iceServers;

    MediaConstraints constraints = new MediaConstraints();
    MediaConstraints audioConstraints = new MediaConstraints();
    PeerConnection.RTCConfiguration configuration = new PeerConnection.RTCConfiguration(iceServers);

    configuration.bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE;
    configuration.rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE;

    if (hideIp) {
        configuration.iceTransportsType = PeerConnection.IceTransportsType.RELAY;
    }

    constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
    audioConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));

    this.peerConnection = factory.createPeerConnection(configuration, constraints, observer);
    this.peerConnection.setAudioPlayout(false);
    this.peerConnection.setAudioRecording(false);

    this.mediaStream = factory.createLocalMediaStream("ARDAMS");
    this.audioSource = factory.createAudioSource(audioConstraints);
    this.audioTrack = factory.createAudioTrack("ARDAMSa0", audioSource);
    this.audioTrack.setEnabled(false);
    mediaStream.addTrack(audioTrack);

    this.camera = new Camera(context, cameraEventListener);

    if (camera.capturer != null) {
        this.videoSource = factory.createVideoSource(false);
        this.videoTrack = factory.createVideoTrack("ARDAMSv0", videoSource);

        camera.capturer.initialize(SurfaceTextureHelper.create("WebRTC-SurfaceTextureHelper", eglBase.getEglBaseContext()), context, videoSource.getCapturerObserver());

        this.videoTrack.addSink(localRenderer);
        this.videoTrack.setEnabled(false);
        mediaStream.addTrack(videoTrack);
    } else {
        this.videoSource = null;
        this.videoTrack = null;
    }

    this.peerConnection.addStream(mediaStream);
}
 
Example 3
Source File: WebRTCWrapper.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
synchronized void initializePeerConnection(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws InitializationException {
    Preconditions.checkState(this.eglBase != null);
    Preconditions.checkNotNull(media);
    Preconditions.checkArgument(media.size() > 0, "media can not be empty when initializing peer connection");
    final boolean setUseHardwareAcousticEchoCanceler = WebRtcAudioEffects.canUseAcousticEchoCanceler() && !HARDWARE_AEC_BLACKLIST.contains(Build.MODEL);
    Log.d(Config.LOGTAG, String.format("setUseHardwareAcousticEchoCanceler(%s) model=%s", setUseHardwareAcousticEchoCanceler, Build.MODEL));
    PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder()
            .setVideoDecoderFactory(new DefaultVideoDecoderFactory(eglBase.getEglBaseContext()))
            .setVideoEncoderFactory(new DefaultVideoEncoderFactory(eglBase.getEglBaseContext(), true, true))
            .setAudioDeviceModule(JavaAudioDeviceModule.builder(context)
                    .setUseHardwareAcousticEchoCanceler(setUseHardwareAcousticEchoCanceler)
                    .createAudioDeviceModule()
            )
            .createPeerConnectionFactory();


    final MediaStream stream = peerConnectionFactory.createLocalMediaStream("my-media-stream");

    final Optional<CapturerChoice> optionalCapturerChoice = media.contains(Media.VIDEO) ? getVideoCapturer() : Optional.absent();

    if (optionalCapturerChoice.isPresent()) {
        this.capturerChoice = optionalCapturerChoice.get();
        final CameraVideoCapturer capturer = this.capturerChoice.cameraVideoCapturer;
        final VideoSource videoSource = peerConnectionFactory.createVideoSource(false);
        SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("webrtc", eglBase.getEglBaseContext());
        capturer.initialize(surfaceTextureHelper, requireContext(), videoSource.getCapturerObserver());
        Log.d(Config.LOGTAG, String.format("start capturing at %dx%d@%d", capturerChoice.captureFormat.width, capturerChoice.captureFormat.height, capturerChoice.getFrameRate()));
        capturer.startCapture(capturerChoice.captureFormat.width, capturerChoice.captureFormat.height, capturerChoice.getFrameRate());

        this.localVideoTrack = peerConnectionFactory.createVideoTrack("my-video-track", videoSource);

        stream.addTrack(this.localVideoTrack);
    }


    if (media.contains(Media.AUDIO)) {
        //set up audio track
        final AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
        this.localAudioTrack = peerConnectionFactory.createAudioTrack("my-audio-track", audioSource);
        stream.addTrack(this.localAudioTrack);
    }


    final PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers);
    rtcConfig.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED; //XEP-0176 doesn't support tcp
    rtcConfig.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY;
    final PeerConnection peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, peerConnectionObserver);
    if (peerConnection == null) {
        throw new InitializationException("Unable to create PeerConnection");
    }
    peerConnection.addStream(stream);
    peerConnection.setAudioPlayout(true);
    peerConnection.setAudioRecording(true);
    this.peerConnection = peerConnection;
}
 
Example 4
Source File: AppRTCDemoActivity.java    From WebRTCDemo with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void onIceServers(List<PeerConnection.IceServer> iceServers) {
  factory = new PeerConnectionFactory();

  MediaConstraints pcConstraints = appRtcClient.pcConstraints();
  pcConstraints.optional.add(
      new MediaConstraints.KeyValuePair("RtpDataChannels", "true"));
  pc = factory.createPeerConnection(iceServers, pcConstraints, pcObserver);

  createDataChannelToRegressionTestBug2302(pc);  // See method comment.

  // Uncomment to get ALL WebRTC tracing and SENSITIVE libjingle logging.
  // NOTE: this _must_ happen while |factory| is alive!
  // Logging.enableTracing(
  //     "logcat:",
  //     EnumSet.of(Logging.TraceLevel.TRACE_ALL),
  //     Logging.Severity.LS_SENSITIVE);

  {
    final PeerConnection finalPC = pc;
    final Runnable repeatedStatsLogger = new Runnable() {
        public void run() {
          synchronized (quit[0]) {
            if (quit[0]) {
              return;
            }
            final Runnable runnableThis = this;
            if (hudView.getVisibility() == View.INVISIBLE) {
              vsv.postDelayed(runnableThis, 1000);
              return;
            }
            boolean success = finalPC.getStats(new StatsObserver() {
                public void onComplete(final StatsReport[] reports) {
                  runOnUiThread(new Runnable() {
                      public void run() {
                        updateHUD(reports);
                      }
                    });
                  for (StatsReport report : reports) {
                    Log.d(TAG, "Stats: " + report.toString());
                  }
                  vsv.postDelayed(runnableThis, 1000);
                }
              }, null);
            if (!success) {
              throw new RuntimeException("getStats() return false!");
            }
          }
        }
      };
    vsv.postDelayed(repeatedStatsLogger, 1000);
  }

  {
    logAndToast("Creating local video source...");
    MediaStream lMS = factory.createLocalMediaStream("ARDAMS");
    if (appRtcClient.videoConstraints() != null) {
      VideoCapturer capturer = getVideoCapturer();
      videoSource = factory.createVideoSource(
          capturer, appRtcClient.videoConstraints());
      VideoTrack videoTrack =
          factory.createVideoTrack("ARDAMSv0", videoSource);
      videoTrack.addRenderer(new VideoRenderer(localRender));
      lMS.addTrack(videoTrack);
    }
    if (appRtcClient.audioConstraints() != null) {
      lMS.addTrack(factory.createAudioTrack(
          "ARDAMSa0",
          factory.createAudioSource(appRtcClient.audioConstraints())));
    }
    pc.addStream(lMS, new MediaConstraints());
  }
  logAndToast("Waiting for ICE candidates...");
}
 
Example 5
Source File: AppRTCDemoActivity.java    From droidkit-webrtc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void onIceServers(List<PeerConnection.IceServer> iceServers) {
  factory = new PeerConnectionFactory();

  MediaConstraints pcConstraints = appRtcClient.pcConstraints();
  pcConstraints.optional.add(
      new MediaConstraints.KeyValuePair("RtpDataChannels", "true"));
  pc = factory.createPeerConnection(iceServers, pcConstraints, pcObserver);

  createDataChannelToRegressionTestBug2302(pc);  // See method comment.

  // Uncomment to get ALL WebRTC tracing and SENSITIVE libjingle logging.
  // NOTE: this _must_ happen while |factory| is alive!
  // Logging.enableTracing(
  //     "logcat:",
  //     EnumSet.of(Logging.TraceLevel.TRACE_ALL),
  //     Logging.Severity.LS_SENSITIVE);

  {
    final PeerConnection finalPC = pc;
    final Runnable repeatedStatsLogger = new Runnable() {
        public void run() {
          synchronized (quit[0]) {
            if (quit[0]) {
              return;
            }
            final Runnable runnableThis = this;
            if (hudView.getVisibility() == View.INVISIBLE) {
              vsv.postDelayed(runnableThis, 1000);
              return;
            }
            boolean success = finalPC.getStats(new StatsObserver() {
                public void onComplete(final StatsReport[] reports) {
                  runOnUiThread(new Runnable() {
                      public void run() {
                        updateHUD(reports);
                      }
                    });
                  for (StatsReport report : reports) {
                    Log.d(TAG, "Stats: " + report.toString());
                  }
                  vsv.postDelayed(runnableThis, 1000);
                }
              }, null);
            if (!success) {
              throw new RuntimeException("getStats() return false!");
            }
          }
        }
      };
    vsv.postDelayed(repeatedStatsLogger, 1000);
  }

  {
    logAndToast("Creating local video source...");
    MediaStream lMS = factory.createLocalMediaStream("ARDAMS");
    if (appRtcClient.videoConstraints() != null) {
      VideoCapturer capturer = getVideoCapturer();
      videoSource = factory.createVideoSource(
          capturer, appRtcClient.videoConstraints());
      VideoTrack videoTrack =
          factory.createVideoTrack("ARDAMSv0", videoSource);
      videoTrack.addRenderer(new VideoRenderer(localRender));
      lMS.addTrack(videoTrack);
    }
    if (appRtcClient.audioConstraints() != null) {
      lMS.addTrack(factory.createAudioTrack(
          "ARDAMSa0",
          factory.createAudioSource(appRtcClient.audioConstraints())));
    }
    pc.addStream(lMS, new MediaConstraints());
  }
  logAndToast("Waiting for ICE candidates...");
}
 
Example 6
Source File: WebRTCWrapper.java    From Conversations with GNU General Public License v3.0 4 votes vote down vote up
synchronized void initializePeerConnection(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws InitializationException {
    Preconditions.checkState(this.eglBase != null);
    Preconditions.checkNotNull(media);
    Preconditions.checkArgument(media.size() > 0, "media can not be empty when initializing peer connection");
    final boolean setUseHardwareAcousticEchoCanceler = WebRtcAudioEffects.canUseAcousticEchoCanceler() && !HARDWARE_AEC_BLACKLIST.contains(Build.MODEL);
    Log.d(Config.LOGTAG, String.format("setUseHardwareAcousticEchoCanceler(%s) model=%s", setUseHardwareAcousticEchoCanceler, Build.MODEL));
    PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder()
            .setVideoDecoderFactory(new DefaultVideoDecoderFactory(eglBase.getEglBaseContext()))
            .setVideoEncoderFactory(new DefaultVideoEncoderFactory(eglBase.getEglBaseContext(), true, true))
            .setAudioDeviceModule(JavaAudioDeviceModule.builder(context)
                    .setUseHardwareAcousticEchoCanceler(setUseHardwareAcousticEchoCanceler)
                    .createAudioDeviceModule()
            )
            .createPeerConnectionFactory();


    final MediaStream stream = peerConnectionFactory.createLocalMediaStream("my-media-stream");

    final Optional<CapturerChoice> optionalCapturerChoice = media.contains(Media.VIDEO) ? getVideoCapturer() : Optional.absent();

    if (optionalCapturerChoice.isPresent()) {
        this.capturerChoice = optionalCapturerChoice.get();
        final CameraVideoCapturer capturer = this.capturerChoice.cameraVideoCapturer;
        final VideoSource videoSource = peerConnectionFactory.createVideoSource(false);
        SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("webrtc", eglBase.getEglBaseContext());
        capturer.initialize(surfaceTextureHelper, requireContext(), videoSource.getCapturerObserver());
        Log.d(Config.LOGTAG, String.format("start capturing at %dx%d@%d", capturerChoice.captureFormat.width, capturerChoice.captureFormat.height, capturerChoice.getFrameRate()));
        capturer.startCapture(capturerChoice.captureFormat.width, capturerChoice.captureFormat.height, capturerChoice.getFrameRate());

        this.localVideoTrack = peerConnectionFactory.createVideoTrack("my-video-track", videoSource);

        stream.addTrack(this.localVideoTrack);
    }


    if (media.contains(Media.AUDIO)) {
        //set up audio track
        final AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
        this.localAudioTrack = peerConnectionFactory.createAudioTrack("my-audio-track", audioSource);
        stream.addTrack(this.localAudioTrack);
    }


    final PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers);
    rtcConfig.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED; //XEP-0176 doesn't support tcp
    rtcConfig.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY;
    final PeerConnection peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, peerConnectionObserver);
    if (peerConnection == null) {
        throw new InitializationException("Unable to create PeerConnection");
    }
    peerConnection.addStream(stream);
    peerConnection.setAudioPlayout(true);
    peerConnection.setAudioRecording(true);
    this.peerConnection = peerConnection;
}