all files / addon/mixins/ device-enumeration.js

53.51% Statements 61/114
47.37% Branches 36/76
45.83% Functions 11/24
50.47% Lines 54/107
1 statement Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/* global _ */
 
import Ember from 'ember';
 
const { Mixin, RSVP, computed, run } = Ember;
 
const UA = window.navigator.userAgent.toLowerCase();
const IS_CHROME = !!window && !!window.chrome && !!window.chrome.webstore;
const IS_FIREFOX = window && typeof InstallTrigger !== 'undefined';
let BROWSER_VERSION;
Eif (IS_CHROME) {
  BROWSER_VERSION = UA.match(/chrom(e|ium)/) && parseInt(UA.match(/chrom(e|ium)\/([0-9]+)\./)[2], 10);
} else if (IS_FIREFOX) {
  BROWSER_VERSION = parseInt(UA.match(/firefox\/([0-9]+)\./)[1], 10);
}
 
export default Mixin.create({
  // options
  fullHd: false,
 
  canListDevices: false,
 
  // camera and video stuff
  hasCameraPermission: false,
  cameraList: Ember.A(),
  hasCamera: computed('cameraList.[]', function () {
    return !!_.find(this.get('cameraList'), (camera) => camera.deviceId !== 'default');
  }),
 
  // mic and audio stuff
  hasMicPermission: false,
  microphoneList: Ember.A(),
  hasMicrophone: computed.notEmpty('microphoneList'),
 
  callCapable: computed.and('audioCallCapable', 'videoCallCapable'),
 
  audioCallCapable: computed(function () {
    const PC = window.RTCPeerConnection;
    const gUM = window.navigator && window.navigator.mediaDevices && window.navigator.mediaDevices.getUserMedia;
    const supportWebAudio = window.AudioContext && window.AudioContext.prototype.createMediaStreamSource;
    const support = !!(PC && gUM && supportWebAudio);
 
    return support;
  }),
 
  videoCallCapable: computed('audioCallCapable', function () {
    const audioCallCapable = this.get('audioCallCapable');
    Iif (!audioCallCapable) {
      return false;
    }
 
    const videoEl = document.createElement('video');
    const supportVp8 = videoEl && videoEl.canPlayType && videoEl.canPlayType('video/webm; codecs="vp8", vorbis') === 'probably';
    Iif (!supportVp8) {
      return false;
    }
    return true;
  }),
 
  outputDeviceList: Ember.A(),
  resolutionList: Ember.A(),
 
  canShareScreen: computed.reads('callCapable'),
 
  enumerationTimer: null,
 
  // Returns a promise which resolves when all devices have been enumerated and loaded
  init () {
    this._super(...arguments);
    const timer = run.next(this, function () {
      this.enumerateDevices();
      this.enumerateResolutions();
    });
    this.set('enumerationTimer', timer);
 
    this.lookup = this.lookup || ((key) => key);
  },
 
  willDestroy () {
    const timer = this.get('enumerationTimer');
    if (timer) {
      run.cancel(timer);
    }
 
    this._super(...arguments);
  },
 
  updateDefaultDevices (/* devices */) {
    throw new Error('updateDefaultDevices should be overridden - do you need to save preferences or change video stream?');
  },
 
  enumerateResolutions () {
    const resolutions = this.get('resolutionList');
    resolutions.pushObject(Ember.Object.create({
      label: this.lookup('webrtcDevices.resolutions.low').toString(),
      presetId: 1,
      constraints: {
        video: {
          width: { max: 320 },
          height: { max: 240 }
        }
      }
    }));
 
    resolutions.pushObject(Ember.Object.create({
      label: this.lookup('webrtcDevices.resolutions.medium').toString(),
      presetId: 2,
      constraints: {
        video: {
          width: { max: 640 },
          height: { max: 480 }
        }
      }
    }));
 
    const hd = Ember.Object.create({
      label: this.lookup('webrtcDevices.resolutions.high').toString(),
      presetId: 3,
      constraints: {
        video: {
          width: {
            min: 640,
            ideal: 1280,
            max: 1920
          },
          height: {
            min: 480,
            ideal: 720,
            max: 1080
          }
        }
      }
    });
    resolutions.pushObject(hd);
 
    // full hd is disabled by default because very few computers actually support this
    Iif (this.get('fullHd')) {
      resolutions.pushObject(Ember.Object.create({
        label: this.lookup('webrtcDevices.resolutions.fullHd').toString(),
        presetId: 4,
        constraints: {
          video: {
            width: { exact: 1920 },
            height: { exact: 1080 }
          }
        }
      }));
    }
    return resolutions;
  },
 
  enumerateDevices () {
    Iif (!window.navigator.mediaDevices || !window.navigator.mediaDevices.enumerateDevices) {
      return;
    }
    let cameraCount = 0;
    let microphoneCount = 0;
    let outputDeviceCount = 0;
    const cameras = [];
    const microphones = [];
    const outputDevices = [];
    const defaultDevice = {
      deviceId: 'default',
      label: this.lookup('webrtcDevices.default').toString()
    };
 
    const addCamera = (device, hasBrowserLabel) => {
      Eif (!hasBrowserLabel) {
        device.label = device.label || this.lookup('webrtcDevices.cameraLabel', {number: ++cameraCount}).toString();
      }
      this.set('hasCameraPermission', this.get('hasCameraPermission') || hasBrowserLabel);
      cameras.push(Ember.Object.create(device));
    };
    const addMicrophone = (device, hasBrowserLabel) => {
      if (!hasBrowserLabel) {
        device.label = device.label || this.lookup('webrtcDevices.microphoneLabel', {number: ++microphoneCount}).toString();
      }
      this.set('hasMicPermission', this.get('hasMicPermission') || hasBrowserLabel);
      microphones.push(Ember.Object.create(device));
    };
    const addOutputDevice = (device, hasLabel) => {
      if (!window.HTMLMediaElement.prototype.hasOwnProperty('setSinkId')) {
        return;
      }
      if (!hasLabel) {
        device.label = this.lookup('webrtcDevices.outputDeviceLabel', {number: ++outputDeviceCount}).toString();
      }
      outputDevices.push(Ember.Object.create(device));
    };
 
    // always add a dummy default for video, since the browser doesn't give us one like microphone
    Eif (this.get('callCapable')) {
      addCamera(defaultDevice, false);
    }
    return window.navigator.mediaDevices.enumerateDevices().then((devices) => {
      if (IS_FIREFOX && BROWSER_VERSION < 42) {
        this.set('canListDevices', false);
        addMicrophone(defaultDevice);
      } else {
        this.set('canListDevices', true);
        this.setProperties({
          hasCameraPermission: false,
          hasMicPermission: false
        });
 
        devices.forEach((device) => {
          const deviceInfo = {
            deviceId: device.deviceId,
            label: device.label
          };
          const hasLabel = !_.isEmpty(device.label);
 
          if (device.kind === 'audioinput') {
            addMicrophone(deviceInfo, hasLabel);
          } else if (device.kind === 'audiooutput') {
            addOutputDevice(deviceInfo, hasLabel);
          } else if (device.kind === 'videoinput') {
            addCamera(deviceInfo, hasLabel);
          }
        });
      }
 
      this.setProperties({
        cameraList: Ember.A(cameras),
        microphoneList: Ember.A(microphones),
        outputDeviceList: Ember.A(outputDevices)
      });
    }).catch(err => {
      Ember.Logger.error(err);
      this.set('canListDevices', false);
      addMicrophone(defaultDevice);
    });
  },
 
  setOutputDevice (el, device) {
    Iif (!(device && device.deviceId)) {
      return RSVP.Promise.reject('Cannot set null device');
    }
 
    const outputDevice = this.get('outputDeviceList').findBy('deviceId', device.deviceId);
    Eif (!outputDevice) {
      return RSVP.Promise.reject('Cannot set output device: device not found');
    }
 
    if (typeof el.setSinkId !== 'undefined') {
      return new RSVP.Promise(function (resolve) {
        if (el.paused) {
          el.onplay = () => resolve();
        } else {
          resolve();
        }
      }).then(function () {
        el.setSinkId(device.deviceId);
      }).then(() => {
        Ember.Logger.log('successfully set audio output device');
      }).catch((err) => {
        Ember.Logger.error('failed to set audio output device', err);
      });
    } else {
      Ember.Logger.error('attempted to set sink id in unsupported browser');
      return RSVP.Promise.reject('Not supported');
    }
  },
 
  setDefaultOutputDevice (el) {
    const device = this.get('defaultOutputDevice');
    if (device) {
      return this.setOutputDevice(el, this.get('defaultOutputDevice'));
    }
    return RSVP.Promise.resolve();
  }
});