Voximplant. Blog

Peer-to-peer video chat

Video Chat

VoxImplant is a perfect choice if you need to build real-time web-based video chat application in minutes. VoxImplant Web SDK supports WebRTC and lets developers integrate this functionality with any other web application. Peer-to-peer data transfer capabilities available in WebRTC-enabled browsers (Chrome/Firefox/Opera/other) helps with the quality of communication (law latency) and scalability. All infrastructure required for WebRTC p2p communication is offered by VoxImplant, including signaling built-in the SDK, STUN/TURN/ICE support, etc. Let’s see what steps are required to get simple video chat application up and running.

Creating VoxImplant Application, App Users, App Rule, and VoxEngine Scenario

Before we start building our web app using Web SDK we need to setup VoxImplant account. If you don’t have one you can get it for free at https://voximplant.com/sign-up/. After account activation you will get the access to VoxImplant Control Panel.

Lets open the Applications section of the Control Panel, create a new app and name it videochat. After that go to the Users section and create two users for the application (for example, testuser1 and testuser2), they can be assigned to the app while the process or later (by editing).
Users
Now we need to create the VoxEngine scenario that will process calls between the app users, we can name it User2User:

VoxEngine.forwardCallToUserDirect();

That’s all scenario code we need for peer-to-peer calls between users. But this example doesn’t show call control logic that can be implemented in scenario, so let’s check another example:

  1. var call1, call2;
  2.  
  3. VoxEngine.addEventListener(AppEvents.CallAlerting, function(e) {
  4. call1 = e.call;
  5. call2 = VoxEngine.callUserDirect(e.call, e.destination, e.displayName, e.headers);
  6. VoxEngine.easyProcess(e.call, call2, handleCallConnected, true);
  7. });
  8.  
  9. function handleCallConnected(call1, call2) {
  10. // Disconnect the call from VoxEngine side after 5 seconds
  11. setTimeout(VoxEngine.terminate, 5000);
  12. }

The last thing we need is to create the application Rule that will tell VoxImplant which scenario should be used for which call. Edit the application, open Rules tab and create a new rule. Let’s name it Intercom, put .* in the Pattern input field (it means we will process all calls using the assigned scenario) and drag’n’drop our User2User scenario to the Assigned scenarios list.
Application Rule
Now we have finished our VoxImplant account setup for video chat application.

Building web application using Web SDK

For web client we will need voximplant.min.js library (Web SDK), it’s available from our CDN and basic understanding of the SDK. We won’t put the whole application code here, but you can always grab it from our GitHub page.

  1. // Load the SDK
  2. <script type="text/javascript" src="//cdn.voximplant.com/voximplant.min.js"></script>
  3.  
  4. // Create VoxImplant instance
  5. var voxAPI = VoxImplant.getInstance();
  6. // Add event listeners
  7. voxAPI.addEventListener(VoxImplant.Events.SDKReady, onSdkReady);
  8. voxAPI.addEventListener(VoxImplant.Events.ConnectionEstablished, onConnectionEstablished);
  9. voxAPI.addEventListener(VoxImplant.Events.ConnectionFailed, onConnectionFailed);
  10. voxAPI.addEventListener(VoxImplant.Events.ConnectionClosed, onConnectionClosed);
  11. voxAPI.addEventListener(VoxImplant.Events.AuthResult, onAuthResult);
  12. voxAPI.addEventListener(VoxImplant.Events.IncomingCall, onIncomingCall);
  13. voxAPI.addEventListener(VoxImplant.Events.MicAccessResult, onMicAccessResult);
  14.  
  15. // Initialize the SDK
  16. try {
  17. voxAPI.init({
  18. useRTCOnly: true, // force usage of WebRTC
  19. micRequired: true, // ask mic/cam access before connection to VoxImplant
  20. videoSupport: true // enable video support
  21. });
  22. } catch(e) {
  23. // showing the message if browser doesn't support WebRTC
  24. if (e.message == "NO_WEBRTC_SUPPORT") alert("WebRTC support isn't available");
  25. }
  26.  
  27. // Now we can use SDK functions - establish connection with VoxImplant
  28. function onSdkReady(){
  29. voxAPI.connect(); // mic/cam access dialog will be shown after the function call
  30. }
  31.  
  32. // Process mic/cam dialog input result
  33. function onMicAccessResult(e) {
  34. if (e.result) {
  35. // access was allowed
  36. } else {
  37. // access was denined - no connection will happen
  38. }
  39. }
  40.  
  41. // Establishing connection with VoxImplant
  42. function onConnectionEstablished() {
  43. // Authorization - show the dialog for user to let enter username/password and use login function
  44. // Change application_user, application_name, account_name and application_user_password to your data for testing
  45. voxAPI.login(application_user+"@"+application_name+"."+account_name+".voximplant.com", application_user_password);
  46. }
  47.  
  48. // Couldn't establish connection with VoxImplant
  49. function onConnectionFailed() {
  50. // Websockets or UDP connection is unavailable
  51. }
  52.  
  53. // Connection with VoxImplant was closed
  54. function onConnectionClosed() {
  55. // Can call connect here to reconnect
  56. }
  57.  
  58. function onAuthResult(e) {
  59. if (e.result) {
  60. // authorization was successful - can make/receive calls now
  61. } else {
  62. // authorization failed - check e.code to see the error code
  63. }
  64. }
  65.  
  66. var currentCall = null; // current call
  67.  
  68. // handle incoming call
  69. function onIncomingCall(e) {
  70. currentCall = e.call;
  71. // add event listeners
  72. currentCall.addEventListener(VoxImplant.CallEvents.Connected, onCallConnected);
  73. currentCall.addEventListener(VoxImplant.CallEvents.Disconnected, onCallDisconnected);
  74. currentCall.addEventListener(VoxImplant.CallEvents.Failed, onCallFailed);
  75. // Answer automatically. It's better to show the dialog to let answer/reject the call in real app.
  76. currentCall.answer();
  77. }
  78.  
  79. // Make outbound call
  80. function createCall() {
  81. // application_username - app username that will be dialed (with video)
  82. currentCall = voxAPI.call(application_username, true, null, {"X-DirectCall": "true"});
  83. // add event listeners
  84. currentCall.addEventListener(VoxImplant.CallEvents.Connected, onCallConnected);
  85. currentCall.addEventListener(VoxImplant.CallEvents.Disconnected, onCallDisconnected);
  86. currentCall.addEventListener(VoxImplant.CallEvents.Failed, onCallFailed);
  87. }
  88.  
  89. // Call connected
  90. function onCallConnected(e) {
  91. // Start sending video and show incoming video
  92. voxAPI.sendVideo(true);
  93. currentCall.showRemoteVideo(true);
  94. }
  95.  
  96. // Call disconnected
  97. function onCallDisconnected(e) {
  98. currentCall = null;
  99. }
  100.  
  101. // Call failed
  102. function onCallFailed(e) {
  103. // Error code - e.code, error reason - e.reason
  104. }

That’s all events and functions we need. Of course, it’s just plain JS, we need to add HTML/CSS. The app available on our GitHub account looks this way:
Mic/cam access dialog
UI idle state
UI call state

Project files (GitHub)

Comments

  • Max Lyulyush

    А с Флешом работает? Я пробовал, отключить WEB-RTC, но вроде как не получается созвониться testuser1 и testuser2, ошибка простая – Not Acceptable. Хотя flash подгружается, и я вижу свое лицо.
    В чем тут может быть проблема?

    • Alexey Aylarov

      Flash работает только через сервер, поэтому нужен другой сценарий и немного другой код на клиенте.

  • Roman Solomashenko

    Сколько одновременно http запросов можно слать. Какие ограничения сколько людей одновременно может находится в видео чате?

    • Alexey Aylarov

      http-запросов куда? для видео-чата они не особенно нужны.. В одном чате 2 человека, на то он и чат.

      • Roman Solomashenko

        А в одной комнате сколько может находится людей? Видеоконференция сколько людей может быть? Я видел что 10 http запросов

        • Alexey Aylarov

          Про конференции надо смотреть другой tutorial – Video Conference, так как это p2p, то больше 5 не стоит подключать по видео. По аудио сколько угодно.

          • Roman Solomashenko

            Спасибо за помощь