Coder Social home page Coder Social logo

edguy3 / react-native-webrtc-usb Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 432.73 MB

react-native-webrtc Variants tied together. Grafted sohel-khan / react-native-webrtc-usb-lib onto original fork of [email protected]:jatecl/react-native-webrtc-usb.git

License: MIT License

JavaScript 10.77% Java 49.44% Objective-C 37.02% C 0.25% Ruby 0.30% Python 2.22%

react-native-webrtc-usb's Introduction

Rebuilt commit history in order to see if there was anything useful.

$ git remote -v
origin	[email protected]:edguy3/react-native-webrtc-usb.git (fetch)
origin	[email protected]:edguy3/react-native-webrtc-usb.git (push)
react-native-webrtc-usb-copy	https://github.com/sohel-khan/react-native-webrtc-usb-lib (fetch)
react-native-webrtc-usb-copy	https://github.com/sohel-khan/react-native-webrtc-usb-lib (push)
react-native-webrtc-usb-fork	https://github.com/jatecl/react-native-webrtc-usb (fetch)
react-native-webrtc-usb-fork	https://github.com/jatecl/react-native-webrtc-usb (push)
upstream	[email protected]:react-native-webrtc/react-native-webrtc.git (fetch)
upstream	[email protected]:react-native-webrtc/react-native-webrtc.git (push)

react-native-webrtc-usb-lib

Forked from https://github.com/jatecl/react-native-webrtc-usb and upgraded package versions, solved few Bugs and published my own npm. Credit goes to #jatecl

npm version npm downloads

A WebRTC module for React Native.

Support

  • Currently support for iOS and Android.
  • Support video and audio communication.
  • Supports data channels.
  • You can use it to build an iOS/Android app that can communicate with web browser.

Installation

Android installation:

npm install react-native-webrtc-usb-lib --save

Starting with React Native 0.60 auto-linking works out of the box, so there are no extra steps.

Declaring permissions

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

Add this line to android/gradle.properties:

If you are getting this error:

Fatal Exception: java.lang.UnsatisfiedLinkError: No implementation found for void org.webrtc.PeerConnectionFactory.nativeInitializeAndroidGlobals() (tried Java_org_webrtc_PeerConnectionFactory_nativeInitializeAndroidGlobals and Java_org_webrtc_PeerConnectionFactory_nativeInitializeAndroidGlobals__)
       at org.webrtc.PeerConnectionFactory.nativeInitializeAndroidGlobals(PeerConnectionFactory.java)
       at org.webrtc.PeerConnectionFactory.initialize(PeerConnectionFactory.java:306)
       at com.oney.WebRTCModule.WebRTCModule.initAsync(WebRTCModule.java:79)
       at com.oney.WebRTCModule.WebRTCModule.lambda$new$0(WebRTCModule.java:70)
       at com.oney.WebRTCModule.-$$Lambda$WebRTCModule$CnyHZvkjDxq52UReGHUZlY0JsVw.run(-.java:4)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
       at java.lang.Thread.run(Thread.java:764)

Add this line to android/gradle.properties:

# This one fixes a weird WebRTC runtime problem on some devices.
# https://github.com/jitsi/jitsi-meet/issues/7911#issuecomment-714323255
android.enableDexingArtifactTransform.desugaring=false

Usage

Now, you can use WebRTC like in browser. In your index.ios.js/index.android.js, you can require WebRTC to import RTCPeerConnection, RTCSessionDescription, etc. Anything about using RTCPeerConnection, RTCSessionDescription and RTCIceCandidate is like browser.
Support most WebRTC APIs, please see the Document.

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  Alert,
  TouchableOpacity,
  Dimensions,
  BackHandler
} from 'react-native';

import {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
  MediaStreamTrack,
	getUserMedia,
	
} from "react-native-webrtc-usb-lib";

import io from 'socket.io-client'
import { SOCKET_IO_SERVER} from "./config"

const dimensions = Dimensions.get('window')

class App extends React.Component {
  constructor(props) {
    super(props)

    this.sdp
    this.socket = null
    this.candidates = [];

    this.serviceIP = SOCKET_IO_SERVER

    this.state = {
      localStream: null,
      remoteStream: null,
      disconnected: false,
      isCalling: false,

      pc_config: {
        "iceServers": [
          {
            urls : 'stun:stun.l.google.com:19302'
          }
        ]
      },

      sdpConstraints: {
        'mandatory': {
            'OfferToReceiveAudio': true,
            'OfferToReceiveVideo': true
        }
      },
    }
  }


  componentDidMount = () => {

		const { roomId} = "test";
    
    this.socket = io.connect(
      this.serviceIP,
      {
        path: '/io/webrtc',
        query: {
          room: `/${roomId.toLocaleLowerCase().trim()}`
        }
      }
    )

    this.socket.on('connection-success', success => {
      console.log("connection-success ::", success)
    })

    this.socket.on('offerOrAnswer', (sdp) => {

      this.sdp = JSON.stringify(sdp)

      // set sdp as remote description
      this.pc.setRemoteDescription(new RTCSessionDescription(sdp))
      this.setState({isCalling: true})

    })

    this.socket.on('candidate', (candidate) => {
      // console.log('From Peer... ', JSON.stringify(candidate))
      this.pc.addIceCandidate(new RTCIceCandidate(candidate))

    })


    this.pc = new RTCPeerConnection(this.state.pc_config)

    this.pc.onicecandidate = (e) => {
      // send the candidates to the remote peer
      // see addCandidate below to be triggered on the remote peer
      if (e.candidate) {
        // console.log(JSON.stringify(e.candidate))
        this.sendToPeer('candidate', e.candidate)
      }
    }

    // triggered when there is a change in connection state
    this.pc.oniceconnectionstatechange = (e) => {
      // console.log(e)
    }

    this.pc.onaddstream = (e) => {
      // debugger
      this.setState({
        remoteStream: e.stream
      })
    }

    this.socket.on('peer-disconnected', data => {
      console.log('In peer-disconnected', data)
      console.log('In peer-disconnected--', this.state.remoteStream);

      if(this.state.remoteStream){

        this.stopTracks(this.state.remoteStream);
        // this.pc.close()

        this.setState({
          disconnected: true,
          remoteStream: null,
          isCalling: false,
        })
        Alert.alert(
          'Call Ended',
          'Your friend has ended a call...',
          [
            {
              text: 'OK',
              onPress: () => {
              this.props.navigation.goBack();
                
              },
            },
          ],
          {cancelable: false},
        );

      }

    })
    
    const success = (stream) => {
      // console.log("In getUserMedia success ::", stream)
      this.setState({
        localStream: stream
      })
      this.pc.addStream(stream)
    }

    const failure = (e) => {
      console.log('getUserMedia Error: ', e)
    }

		let isFront = true;
		
		MediaStreamTrack
		.getSources()
		.then(async sourceInfos => {
			// console.log("devices list ::", sourceInfos);
			
			let videoSourceId, device;
			for (let i = 0; i < sourceInfos.length; i++) {
				const sourceInfo = sourceInfos[i];
				if(sourceInfo.kind == "video" || sourceInfo.facing == "usb") {

					videoSourceId = sourceInfo.id;
					device = sourceInfo.facing
				}
			}
			console.log("videoSourceId  ::", videoSourceId, device);

      const constraints = {
        audio: true,
        video: {
          mandatory: {
            minWidth: 1280, // Provide your own width, height and frame rate here
            minHeight: 720,
            minFrameRate: 30
          },
          facingMode: (isFront ? "user" : "environment"),
          optional: (videoSourceId ? [{ sourceId: videoSourceId }] : [])
        }
      }

      return getUserMedia(constraints)
        .then(success)
        .catch(failure);
    });
  }

    sendToPeer = (messageType, payload) => {
      // console.log('=================================')
      
      // console.log('sendToPeer ::', messageType, payload);
      // console.log('=================================')

      this.socket.emit(messageType, {
        socketID: this.socket.id,
        payload
      })
    }

    createOffer = () => {
      console.log('Offer')
  
      // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createOffer
      // initiates the creation of SDP
      this.pc.createOffer(this.state.sdpConstraints)
        .then(sdp => {
          // console.log(JSON.stringify(sdp))
  
          // set offer sdp as local description
          this.pc.setLocalDescription(sdp)
          this.setState({isCalling: true})
  
          this.sendToPeer('offerOrAnswer', sdp)
      })
      .catch(err => console.log("In createOffer catch ::", err))

    }
    
    createAnswer = () => {
      console.log('Answer')
      this.pc.createAnswer(this.state.sdpConstraints)
        .then(sdp => {
          this.pc.setLocalDescription(sdp)
  
          this.sendToPeer('offerOrAnswer', sdp)
      })
      .catch(err => console.log("In answer catch ::", err))
    }

    setRemoteDescription = () => {
      // retrieve and parse the SDP copied from the remote peer
      const desc = JSON.parse(this.sdp)
  
      // set sdp as remote description
      this.pc.setRemoteDescription(new RTCSessionDescription(desc))
    }

    addCandidate = () => {
      this.candidates.forEach(candidate => {
        console.log(JSON.stringify(candidate))
        this.pc.addIceCandidate(new RTCIceCandidate(candidate))
      });
    }

    stopTracks = (stream) => {
      stream.getTracks().forEach(track => track.stop());
    }

    disconnect = ()=>{
      this.stopTracks(this.state.localStream);
      this.socket.close();
      this.pc.close()
      this.props.navigation.goBack();
    }

  render() {
    const {
      localStream,
      remoteStream,
    } = this.state

    const remoteVideo = remoteStream ?
      (
        <RTCView
              // key={1}
              // zOrder={0}
              objectFit='cover'
              style={{ ...styles.rtcView }}
              streamURL={remoteStream && remoteStream.toURL()}
              />
      ) :
      (
        <View style={{ padding: 15, }}>
          <Text style={{ fontSize:22, textAlign: 'center', color: 'white' }}>Waiting for Peer connection ...</Text>
        </View>
      )

    return (
      
      <SafeAreaView style={{ flex: 1, }}>
          <View style={{...styles.buttonsContainer}}>
            { this.state.remoteStream == null &&
            <View style={{ flex: 1, }}>
              <TouchableOpacity onPress={this.createOffer}>
                  <View style={styles.button}>
                  <Text style={{ ...styles.textContent, }}>{ this.state.isCalling ? "Calling..." :"Call"}</Text>
                </View>
              </TouchableOpacity>
            </View>
            }

            { this.state.isCalling && this.state.remoteStream != null && 
            <View style={{ flex: 1, }}>
              <TouchableOpacity onPress={this.createAnswer}>
                <View style={styles.button}>
                  <Text style={{ ...styles.textContent, }}>Answer</Text>
                </View>
              </TouchableOpacity>
            </View>
            }

          { this.state.remoteStream != null &&

            <View style={{ flex: 1, }}>
              <TouchableOpacity onPress={this.disconnect}>
                <View style={styles.button}>
                  <Text style={{ ...styles.textContent, color: 'red'}}>Disconnect</Text>
                </View>
              </TouchableOpacity>
            </View>
           }

          </View>
          <View style={{ ...styles.videosContainer, }}>
          
              <View style={{flex: 1 }}>
                  <View>
                  <RTCView
                    objectFit='cover'
                    style={{ ...styles.rtcView }}
                    streamURL={this.state.localStream && this.state.localStream.toURL()}
                    />
                  </View>
              </View>
          </View>

          <ScrollView style={{ ...styles.scrollView }}>
            <View style={{
              flex: 1,
              width: '100%',
              backgroundColor: 'black',
              justifyContent: 'center',
              alignItems: 'center',
            }}>
              { remoteVideo }
            </View>
          </ScrollView>
        </SafeAreaView>
      );
  }
};

const styles = StyleSheet.create({
  buttonsContainer: {
    flexDirection: 'row',
  },
  button: {
    margin: 5,
    paddingVertical: 10,
    backgroundColor: 'lightgrey',
    borderRadius: 5,
  },
  textContent: {
    fontFamily: 'Avenir',
    fontSize: 20,
    textAlign: 'center',
  },
  videosContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginLeft: 20
  },
  rtcView: {
    width: 300, //dimensions.width,
    height: 250,//dimensions.height / 2,
    backgroundColor: 'black',
    justifyContent: 'center',
    alignItems: 'center',
  },
  scrollView: {
    flex: 1,
    // flexDirection: 'row',
    backgroundColor: 'teal',
    padding: 15,
  },
  rtcViewRemote: {
    width: dimensions.width - 30,
    height: 300,//dimensions.height / 2,
    backgroundColor: 'black',
  }
});

export default App;

react-native-webrtc-usb's People

Contributors

zxcpoiu avatar oney avatar saghul avatar lyubomir avatar philikon avatar paweldomas avatar jatecl avatar edguy3 avatar jd20 avatar stwiname avatar 1mike12 avatar markthom-as avatar kenny-house avatar cristiantx avatar kensakukomatsu avatar ianlin avatar dguillamot avatar thoqbk avatar snoronha avatar sagivo avatar rub8n avatar petrbela avatar brunsy avatar mrap avatar micronxd avatar maxhawkins avatar matthieulemoine avatar markacola avatar mahmoud-adam85 avatar vespakoen avatar

Stargazers

enfpdev avatar Alex Sojda avatar

Watchers

 avatar

react-native-webrtc-usb's Issues

Not able to install this library

Hello,
Someone still maintaining this library
i need to use this library but i am not able to install this
npx react-native run-android fails and it get me this

Could not determine the dependencies of task ':app:processDebugResources'.

Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
Could not find org.webrtc:google-webrtc:1.0.22920.
Searched in the following locations:
- https://oss.sonatype.org/content/repositories/snapshots/org/webrtc/google-webrtc/1.0.22920/google-webrtc-1.0.22920.pom
- https://repo.maven.apache.org/maven2/org/webrtc/google-webrtc/1.0.22920/google-webrtc-1.0.22920.pom
- file:/Users/huzaifaazim/Desktop/livekit-tests/livekitTest/node_modules/jsc-android/dist/org/webrtc/google-webrtc/1.0.22920/google-webrtc-1.0.22920.pom
- https://dl.google.com/dl/android/maven2/org/webrtc/google-webrtc/1.0.22920/google-webrtc-1.0.22920.pom
- https://www.jitpack.io/org/webrtc/google-webrtc/1.0.22920/google-webrtc-1.0.22920.pom
Required by:
project :app > project :react-native-webrtc-usb
Could not find :libuvccommon-release:.
Required by:
project :app > project :react-native-webrtc-usb
Could not find :libuvccamera-release:.
Required by:
project :app > project :react-native-webrtc-usb

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.