org.webrtc.PeerConnectionFactory Java Examples

The following examples show how to use org.webrtc.PeerConnectionFactory. 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: PCFactoryProxy.java    From owt-client-android with Apache License 2.0 7 votes vote down vote up
static PeerConnectionFactory instance() {
    if (peerConnectionFactory == null) {
        PeerConnectionFactory.InitializationOptions initializationOptions =
                PeerConnectionFactory.InitializationOptions.builder(context)
                        .setFieldTrials(fieldTrials)
                        .createInitializationOptions();
        PeerConnectionFactory.initialize(initializationOptions);
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        options.networkIgnoreMask = networkIgnoreMask;
        peerConnectionFactory = PeerConnectionFactory.builder()
                .setOptions(options)
                .setAudioDeviceModule(adm == null ? JavaAudioDeviceModule.builder(context).createAudioDeviceModule() : adm)
                .setVideoEncoderFactory(
                        encoderFactory == null
                                ? new DefaultVideoEncoderFactory(localContext, true, true)
                                : encoderFactory)
                .setVideoDecoderFactory(
                        decoderFactory == null
                                ? new DefaultVideoDecoderFactory(remoteContext)
                                : decoderFactory)
                .createPeerConnectionFactory();
    }
    return peerConnectionFactory;
}
 
Example #3
Source File: MainActivity.java    From webrtc-android-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // create PeerConnectionFactory
    PeerConnectionFactory.InitializationOptions initializationOptions =
            PeerConnectionFactory.InitializationOptions.builder(this).createInitializationOptions();
    PeerConnectionFactory.initialize(initializationOptions);
    PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory();

    // create AudioSource
    AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
    AudioTrack audioTrack = peerConnectionFactory.createAudioTrack("101", audioSource);

    EglBase.Context eglBaseContext = EglBase.create().getEglBaseContext();

    SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread", eglBaseContext);
    // create VideoCapturer
    VideoCapturer videoCapturer = createCameraCapturer();
    VideoSource videoSource = peerConnectionFactory.createVideoSource(videoCapturer.isScreencast());
    videoCapturer.initialize(surfaceTextureHelper, getApplicationContext(), videoSource.getCapturerObserver());
    videoCapturer.startCapture(480, 640, 30);

    SurfaceViewRenderer localView = findViewById(R.id.localView);
    localView.setMirror(true);
    localView.init(eglBaseContext, null);

    // create VideoTrack
    VideoTrack videoTrack = peerConnectionFactory.createVideoTrack("100", videoSource);
    // display in localView
    videoTrack.addSink(localView);
}
 
Example #4
Source File: PeerConnectionClient.java    From voip_android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public PeerConnectionClient(Context appContext, EglBase eglBase,
                            PeerConnectionParameters peerConnectionParameters, PeerConnectionEvents events) {
    this.rootEglBase = eglBase;
    this.appContext = appContext;
    this.events = events;
    this.peerConnectionParameters = peerConnectionParameters;

    Log.d(TAG, "Preferred video codec: " + peerConnectionParameters.videoCodec);

    final String fieldTrials = getFieldTrials(peerConnectionParameters);
    executor.execute(() -> {
        Log.d(TAG, "Initialize WebRTC. Field trials: " + fieldTrials);
        PeerConnectionFactory.initialize(
                PeerConnectionFactory.InitializationOptions.builder(appContext)
                        .setFieldTrials(fieldTrials)
                        .setEnableInternalTracer(true)
                        .createInitializationOptions());
    });
}
 
Example #5
Source File: WebRtcCallService.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void initializeVideo() {
    Util.runOnMainSync(() -> {
        eglBase = EglBase.create();
        localRenderer = new SurfaceViewRenderer(WebRtcCallService.this);
        remoteRenderer = new SurfaceViewRenderer(WebRtcCallService.this);

        localRenderer.init(eglBase.getEglBaseContext(), null);
        remoteRenderer.init(eglBase.getEglBaseContext(), null);

        VideoEncoderFactory encoderFactory = new DefaultVideoEncoderFactory(eglBase.getEglBaseContext(), true, true);
        VideoDecoderFactory decoderFactory = new DefaultVideoDecoderFactory(eglBase.getEglBaseContext());

        peerConnectionFactory = PeerConnectionFactory.builder()
                .setOptions(new PeerConnectionFactoryOptions())
                .setVideoEncoderFactory(encoderFactory)
                .setVideoDecoderFactory(decoderFactory)
                .createPeerConnectionFactory();
    });

}
 
Example #6
Source File: NBMWebRTCPeer.java    From webrtcpeer-android with Apache License 2.0 6 votes vote down vote up
private void createPeerConnectionFactoryInternal(Context context) {
        Log.d(TAG, "Create peer connection peerConnectionFactory. Use video: " + peerConnectionParameters.videoCallEnabled);
//        isError = false;
        // Initialize field trials.
        String field_trials = FIELD_TRIAL_AUTOMATIC_RESIZE;
        // Check if VP9 is used by default.
        if (peerConnectionParameters.videoCallEnabled && peerConnectionParameters.videoCodec != null &&
                peerConnectionParameters.videoCodec.equals(NBMMediaConfiguration.NBMVideoCodec.VP9.toString())) {
            field_trials += FIELD_TRIAL_VP9;
        }
        PeerConnectionFactory.initializeFieldTrials(field_trials);

        if (!PeerConnectionFactory.initializeAndroidGlobals(context, true, true, peerConnectionParameters.videoCodecHwAcceleration)) {
            observer.onPeerConnectionError("Failed to initializeAndroidGlobals");
        }
        peerConnectionFactory = new PeerConnectionFactory();
        // ToDo: What about these options?
//        if (options != null) {
//            Log.d(TAG, "Factory networkIgnoreMask option: " + options.networkIgnoreMask);
//            peerConnectionFactory.setOptions(options);
//        }
        Log.d(TAG, "Peer connection peerConnectionFactory created.");
    }
 
Example #7
Source File: WebRtcClient.java    From imsdk-android with MIT License 6 votes vote down vote up
/**
     * Call this method in Activity.onDestroy()
     */
    public void onDestroy() {
        if (peer != null && peer.pc != null) peer.pc.dispose();
        if (videoSource != null) {
            videoSource.stop();
//            videoSource.dispose();
        }
        if (videoCapturer != null) {
            videoCapturer.dispose();
        }
        if (audioSource != null) {
            audioSource.dispose();
        }
        if (factory != null) factory.dispose();
        PeerConnectionFactory.stopInternalTracingCapture();
        PeerConnectionFactory.shutdownInternalTracer();
        mListener = null;
    }
 
Example #8
Source File: WebRTCActivity.java    From voip_android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void startStream() {
    logAndToast("Creating peer connection");

    peerConnectionClient = new PeerConnectionClient(getApplicationContext(), rootEglBase, peerConnectionParameters, this);

    PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();

    peerConnectionClient.createPeerConnectionFactory(options);

    PeerConnection.IceServer server = new PeerConnection.IceServer("stun:stun.counterpath.net:3478");

    String username = turnUserName;
    String password = turnPassword;
    PeerConnection.IceServer server2 = new PeerConnection.IceServer("turn:turn.gobelieve.io:3478?transport=udp", username, password);

    peerConnectionClient.clearIceServer();
    peerConnectionClient.addIceServer(server);
    peerConnectionClient.addIceServer(server2);

    VideoCapturer videoCapturer = null;
    if (peerConnectionParameters.videoCallEnabled) {
        videoCapturer = createVideoCapturer();
    }
    peerConnectionClient.createPeerConnection(localRender,
            remoteRender, videoCapturer);

    if (this.isCaller) {
        logAndToast("Creating OFFER...");
        // Create offer. Offer SDP will be sent to answering client in
        // PeerConnectionEvents.onLocalDescription event.
        peerConnectionClient.createOffer();
    }
}
 
Example #9
Source File: PnPeerConnectionClient.java    From android-webrtc-api with MIT License 5 votes vote down vote up
public PnPeerConnectionClient(Pubnub pubnub, PnSignalingParams signalingParams, PnRTCListener rtcListener){
    this.mPubNub = pubnub;
    this.signalingParams = signalingParams;
    this.mRtcListener = rtcListener;
    this.pcFactory = new PeerConnectionFactory(); // TODO: Check it allowed, else extra param
    this.peers = new HashMap<String, PnPeer>();
    init();
}
 
Example #10
Source File: PeerConnectionResourceManager.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
PeerConnectionResourceManager(NBMPeerConnectionParameters peerConnectionParameters,
                                     LooperExecutor executor, PeerConnectionFactory factory) {

    this.peerConnectionParameters = peerConnectionParameters;
    this.executor = executor;
    this.factory = factory;
    videoCallEnabled = peerConnectionParameters.videoCallEnabled;

    // Check if H.264 is used by default.
    preferH264 = videoCallEnabled && peerConnectionParameters.videoCodec != null && peerConnectionParameters.videoCodec.equals(NBMMediaConfiguration.NBMVideoCodec.H264.toString());
    // Check if ISAC is used by default.
    preferIsac = peerConnectionParameters.audioCodec != null && peerConnectionParameters.audioCodec.equals(NBMMediaConfiguration.NBMAudioCodec.ISAC.toString());
    connections = new HashMap<>();
}
 
Example #11
Source File: MediaResourceManager.java    From webrtcpeer-android with Apache License 2.0 5 votes vote down vote up
MediaResourceManager(NBMWebRTCPeer.NBMPeerConnectionParameters peerConnectionParameters,
                            LooperExecutor executor, PeerConnectionFactory factory){
    this.peerConnectionParameters = peerConnectionParameters;
    this.localMediaStream = null;
    this.executor = executor;
    this.factory = factory;
    renderVideo = true;
    remoteVideoTracks = new HashMap<>();
    remoteVideoRenderers = new HashMap<>();
    remoteVideoMediaStreams = new HashMap<>();
    videoCallEnabled = peerConnectionParameters.videoCallEnabled;
}
 
Example #12
Source File: PnPeerConnectionClient.java    From AndroidRTC with MIT License 5 votes vote down vote up
public PnPeerConnectionClient(Pubnub pubnub, PnSignalingParams signalingParams, PnRTCListener rtcListener){
    this.mPubNub = pubnub;
    this.signalingParams = signalingParams;
    this.mRtcListener = rtcListener;
    this.pcFactory = new PeerConnectionFactory(); // TODO: Check it allowed, else extra param
    this.peers = new HashMap<String, PnPeer>();
    init();
}
 
Example #13
Source File: PeerConnectionClient.java    From voip_android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This function should only be called once.
 */
public void createPeerConnectionFactory(PeerConnectionFactory.Options options) {
    if (factory != null) {
        throw new IllegalStateException("PeerConnectionFactory has already been constructed");
    }
    executor.execute(() -> createPeerConnectionFactoryInternal(options));
}
 
Example #14
Source File: WebRTC.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * First, we initiate the PeerConnectionFactory with our application context and some options.
 */
private PeerConnectionFactory peerConnectionFactoryInstance() {
    if (peerConnectionFactory == null) {

        Set<String> HARDWARE_AEC_WHITELIST = new HashSet<String>() {{
            add("D5803");
            add("FP1");
            add("SM-A500FU");
            add("XT1092");
        }};

        Set<String> OPEN_SL_ES_WHITELIST = new HashSet<String>() {{
        }};

        if (Build.VERSION.SDK_INT >= 11) {
            if (HARDWARE_AEC_WHITELIST.contains(Build.MODEL)) {
                WebRtcAudioUtils.setWebRtcBasedAcousticEchoCanceler(false);
            } else {
                WebRtcAudioUtils.setWebRtcBasedAcousticEchoCanceler(true);
            }

            if (OPEN_SL_ES_WHITELIST.contains(Build.MODEL)) {
                WebRtcAudioManager.setBlacklistDeviceForOpenSLESUsage(false);
            } else {
                WebRtcAudioManager.setBlacklistDeviceForOpenSLESUsage(true);
            }
        }


        PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(G.context).createInitializationOptions());
        peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory();

    }
    return peerConnectionFactory;
}
 
Example #15
Source File: Respoke.java    From respoke-sdk-android with MIT License 5 votes vote down vote up
/**
 *  Notify the shared SDK instance that the specified client has connected. This is for internal use only, and should never be called by your client application.
 *
 *  @param client  The client that just connected
 */
public void clientConnected(RespokeClient client) {
    if (null != pushToken) {
        registerPushServices();
    }

    if (!factoryStaticInitialized) {
        // Perform a one-time WebRTC global initialization
        PeerConnectionFactory.initializeAndroidGlobals(context, true, true, true, VideoRendererGui.getEGLContext());
        factoryStaticInitialized = true;
    }
}
 
Example #16
Source File: RTCCall.java    From Meshenger with GNU General Public License v3.0 5 votes vote down vote up
private void initRTC(Context c) {
    log("initializing");
    PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(c).createInitializationOptions());
    log("initialized");
    factory = PeerConnectionFactory.builder().createPeerConnectionFactory();
    log("created");
    constraints = new MediaConstraints();
    constraints.optional.add(new MediaConstraints.KeyValuePair("offerToReceiveAudio", "true"));
    constraints.optional.add(new MediaConstraints.KeyValuePair("offerToReceiveVideo", "false"));
    constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));

    //initVideoTrack();
}
 
Example #17
Source File: RTCCall.java    From meshenger-android with GNU General Public License v3.0 5 votes vote down vote up
private void initRTC(Context c) {
    PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(c).createInitializationOptions());
    factory = PeerConnectionFactory.builder().createPeerConnectionFactory();

    constraints = new MediaConstraints();
    constraints.optional.add(new MediaConstraints.KeyValuePair("offerToReceiveAudio", "true"));
    constraints.optional.add(new MediaConstraints.KeyValuePair("offerToReceiveVideo", "false"));
    constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));

    //initVideoTrack();
}
 
Example #18
Source File: PeersManager.java    From WebRTCapp with Apache License 2.0 5 votes vote down vote up
public void start() {
    PeerConnectionFactory.initializeAndroidGlobals(activity, true);

    PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
    peerConnectionFactory = new PeerConnectionFactory(options);

    videoGrabberAndroid = createVideoGrabber();
    MediaConstraints constraints = new MediaConstraints();

    VideoSource videoSource = peerConnectionFactory.createVideoSource(videoGrabberAndroid);
    localVideoTrack = peerConnectionFactory.createVideoTrack("100", videoSource);

    AudioSource audioSource = peerConnectionFactory.createAudioSource(constraints);
    localAudioTrack = peerConnectionFactory.createAudioTrack("101", audioSource);

    if (videoGrabberAndroid != null) {
        videoGrabberAndroid.startCapture(1000, 1000, 30);
    }

    localRenderer = new VideoRenderer(localVideoView);
    localVideoTrack.addRenderer(localRenderer);

    MediaConstraints sdpConstraints = new MediaConstraints();
    sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("offerToReceiveAudio", "true"));
    sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("offerToReceiveVideo", "true"));

    createLocalPeerConnection(sdpConstraints);
}
 
Example #19
Source File: Peer.java    From webrtc_android with MIT License 5 votes vote down vote up
public Peer(PeerConnectionFactory factory, List<PeerConnection.IceServer> list, String userId, IPeerEvent event) {
    mFactory = factory;
    mIceLis = list;
    mEvent = event;
    mUserId = userId;
    queuedRemoteCandidates = new ArrayList<>();
    this.pc = createPeerConnection();
    Log.d("dds_test", "create Peer:" + mUserId);

}
 
Example #20
Source File: PeerConnectionWrapper.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public void reInitAudioTrack(@NonNull PeerConnectionFactory factory) {
    this.peerConnection.removeStream(this.mediaStream);
    this.mediaStream.removeTrack(audioTrack);

    MediaConstraints audioConstraints = new MediaConstraints();
    audioConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
    this.audioSource = factory.createAudioSource(audioConstraints);
    this.audioTrack = factory.createAudioTrack("ARDAMSa0", audioSource);
    this.audioTrack.setEnabled(false);

    this.mediaStream.addTrack(audioTrack);
    this.peerConnection.addStream(this.mediaStream);
}
 
Example #21
Source File: CallActivity.java    From RTCStartupDemo with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();
    doEndCall();
    mLocalSurfaceView.release();
    mRemoteSurfaceView.release();
    mVideoCapturer.dispose();
    mSurfaceTextureHelper.dispose();
    PeerConnectionFactory.stopInternalTracingCapture();
    PeerConnectionFactory.shutdownInternalTracer();
    RTCSignalClient.getInstance().leaveRoom();
}
 
Example #22
Source File: WebRtcClient.java    From imsdk-android with MIT License 5 votes vote down vote up
public void setPeerConnectionFactoryOptions(PeerConnectionFactory.Options options) {
    this.options = options;
    if (options != null) {
        LogUtil.d(TAG, "Factory networkIgnoreMask option: " + options.networkIgnoreMask);
        factory.setOptions(options);
    }
}
 
Example #23
Source File: PeerConnectionClient.java    From voip_android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setPeerConnectionFactoryOptions(PeerConnectionFactory.Options options) {
    this.options = options;
}
 
Example #24
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;
}
 
Example #25
Source File: MainActivity.java    From webrtc-android-tutorial with Apache License 2.0 4 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EglBase.Context eglBaseContext = EglBase.create().getEglBaseContext();

        // create PeerConnectionFactory
        PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions
                .builder(this)
                .createInitializationOptions());
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        DefaultVideoEncoderFactory defaultVideoEncoderFactory =
                new DefaultVideoEncoderFactory(eglBaseContext, true, true);
        DefaultVideoDecoderFactory defaultVideoDecoderFactory =
                new DefaultVideoDecoderFactory(eglBaseContext);
        peerConnectionFactory = PeerConnectionFactory.builder()
                .setOptions(options)
                .setVideoEncoderFactory(defaultVideoEncoderFactory)
                .setVideoDecoderFactory(defaultVideoDecoderFactory)
                .createPeerConnectionFactory();

        SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread", eglBaseContext);
        // create VideoCapturer
        VideoCapturer videoCapturer = createCameraCapturer(true);
        VideoSource videoSource = peerConnectionFactory.createVideoSource(videoCapturer.isScreencast());
        videoCapturer.initialize(surfaceTextureHelper, getApplicationContext(), videoSource.getCapturerObserver());
        videoCapturer.startCapture(480, 640, 30);

        localView = findViewById(R.id.localView);
        localView.setMirror(true);
        localView.init(eglBaseContext, null);

        // create VideoTrack
        VideoTrack videoTrack = peerConnectionFactory.createVideoTrack("100", videoSource);
//        // display in localView
//        videoTrack.addSink(localView);




        SurfaceTextureHelper remoteSurfaceTextureHelper = SurfaceTextureHelper.create("RemoteCaptureThread", eglBaseContext);
        // create VideoCapturer
        VideoCapturer remoteVideoCapturer = createCameraCapturer(false);
        VideoSource remoteVideoSource = peerConnectionFactory.createVideoSource(remoteVideoCapturer.isScreencast());
        remoteVideoCapturer.initialize(remoteSurfaceTextureHelper, getApplicationContext(), remoteVideoSource.getCapturerObserver());
        remoteVideoCapturer.startCapture(480, 640, 30);

        remoteView = findViewById(R.id.remoteView);
        remoteView.setMirror(false);
        remoteView.init(eglBaseContext, null);

        // create VideoTrack
        VideoTrack remoteVideoTrack = peerConnectionFactory.createVideoTrack("102", remoteVideoSource);
//        // display in remoteView
//        remoteVideoTrack.addSink(remoteView);



        mediaStreamLocal = peerConnectionFactory.createLocalMediaStream("mediaStreamLocal");
        mediaStreamLocal.addTrack(videoTrack);

        mediaStreamRemote = peerConnectionFactory.createLocalMediaStream("mediaStreamRemote");
        mediaStreamRemote.addTrack(remoteVideoTrack);

        call(mediaStreamLocal, mediaStreamRemote);
    }
 
Example #26
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 #27
Source File: PeerConnectionClient.java    From restcomm-android-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setPeerConnectionFactoryOptions(PeerConnectionFactory.Options options) {
  this.options = options;
}
 
Example #28
Source File: PeerConnectionClient.java    From voip_android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void closeInternal() {
    if (factory != null && peerConnectionParameters.aecDump) {
        factory.stopAecDump();
    }
    Log.d(TAG, "Closing peer connection.");
    statsTimer.cancel();
    if (peerConnection != null) {
        peerConnection.dispose();
        peerConnection = null;
    }
    Log.d(TAG, "Closing audio source.");
    if (audioSource != null) {
        audioSource.dispose();
        audioSource = null;
    }
    Log.d(TAG, "Stopping capture.");
    if (videoCapturer != null) {
        try {
            videoCapturer.stopCapture();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        videoCapturer.dispose();
        videoCapturer = null;
    }
    Log.d(TAG, "Closing video source.");
    if (videoSource != null) {
        videoSource.dispose();
        videoSource = null;
    }
    if (surfaceTextureHelper != null) {
        surfaceTextureHelper.dispose();
        surfaceTextureHelper = null;
    }
    localRender = null;
    remoteSinks = null;
    Log.d(TAG, "Closing peer connection factory.");
    if (factory != null) {
        factory.dispose();
        factory = null;
    }
    options = null;
    rootEglBase.release();

    Log.d(TAG, "Closing peer connection done.");
    events.onPeerConnectionClosed();
    PeerConnectionFactory.stopInternalTracingCapture();
    PeerConnectionFactory.shutdownInternalTracer();
}
 
Example #29
Source File: JanusServer.java    From janus-gateway-android with MIT License 4 votes vote down vote up
public boolean initializeMediaContext(Context context, boolean audio, boolean video, boolean videoHwAcceleration, EGLContext eglContext) {
    if (!PeerConnectionFactory.initializeAndroidGlobals(context, audio, video, videoHwAcceleration, eglContext))
        return false;
    peerConnectionFactoryInitialized = true;
    return true;
}
 
Example #30
Source File: AppRTCDemoActivity.java    From droidkit-webrtc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  Thread.setDefaultUncaughtExceptionHandler(
      new UnhandledExceptionHandler(this));

  getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  Point displaySize = new Point();
  getWindowManager().getDefaultDisplay().getRealSize(displaySize);

  vsv = new AppRTCGLView(this, displaySize);
  VideoRendererGui.setView(vsv);
  remoteRender = VideoRendererGui.create(0, 0, 100, 100);
  localRender = VideoRendererGui.create(70, 5, 25, 25);

  vsv.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        toggleHUD();
      }
    });
  setContentView(vsv);
  logAndToast("Tap the screen to toggle stats visibility");

  hudView = new TextView(this);
  hudView.setTextColor(Color.BLACK);
  hudView.setBackgroundColor(Color.WHITE);
  hudView.setAlpha(0.4f);
  hudView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 5);
  hudView.setVisibility(View.INVISIBLE);
  addContentView(hudView, hudLayout);

  if (!factoryStaticInitialized) {
    abortUnless(PeerConnectionFactory.initializeAndroidGlobals(
        this, true, true),
      "Failed to initializeAndroidGlobals");
    factoryStaticInitialized = true;
  }

  AudioManager audioManager =
      ((AudioManager) getSystemService(AUDIO_SERVICE));
  // TODO(fischman): figure out how to do this Right(tm) and remove the
  // suppression.
  @SuppressWarnings("deprecation")
  boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
  audioManager.setMode(isWiredHeadsetOn ?
      AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION);
  audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);

  sdpMediaConstraints = new MediaConstraints();
  sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
      "OfferToReceiveAudio", "true"));
  sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
      "OfferToReceiveVideo", "true"));

  final Intent intent = getIntent();
  if ("android.intent.action.VIEW".equals(intent.getAction())) {
    connectToRoom(intent.getData().toString());
    return;
  }
  showGetRoomUI();
}