Fix wrong camera picked when toggling cameras.

This fix is for 59 only. It won't work for 58 and older.

TEST=Tested manually.
BUG=b:36535939

Change-Id: Id1c454af7f57a046d46887033a0654eb060e1cbd
Reviewed-on: https://chromium-review.googlesource.com/459158
Reviewed-by: Daichi Hirono <hirono@chromium.org>
Tested-by: Tomasz Mikolajewski <mtomasz@chromium.org>
diff --git a/src/js/views/camera.js b/src/js/views/camera.js
index 5430e50..c3c1899 100644
--- a/src/js/views/camera.js
+++ b/src/js/views/camera.js
@@ -2135,7 +2135,22 @@
     this.startWithConstraints_(
         constraintsCandidates[index],
         function() {
-          this.videoDeviceId_ = constraintsCandidates[index].video.deviceId;
+          if (constraintsCandidates[index].video.deviceId) {
+            // For non-default cameras fetch the deviceId from constraints.
+            // Works on all supported Chrome versions.
+            this.videoDeviceId_ = constraintsCandidates[index].video.deviceId;
+          } else {
+            // For default camera, obtain the deviceId from settings, which is
+            // a feature available only from 59. For older Chrome versions,
+            // it's impossible to detect the device id. As a result, if the
+            // default camera was changed to rear in chrome://settings, then
+            // toggling the camera may not work when pressed for the first time
+            // (the same camera would be opened).
+            var track = this.stream_.getVideoTracks()[0];
+            var trackSettings = track.getSettings && track.getSettings();
+            this.videoDeviceId_ = trackSettings && trackSettings.deviceId ||
+                null;
+          }
           this.updateMirroring_();
           onSuccess();
         }.bind(this),