@@ -383,16 +383,25 @@ module.exports = function(RED) {
383
383
$scope . $watch ( 'msg' , function ( msg ) {
384
384
if ( ! msg ) { return ; }
385
385
if ( msg . camera !== undefined ) {
386
- if ( ! isNaN ( parseInt ( msg . camera ) ) ) {
387
- var c = parseInt ( msg . camera ) ;
388
- if ( c >= 0 || c < 16 ) {
389
- oldActiveCamera = activeCamera ;
390
- $scope . disableCamera ( ) ;
391
- activeCamera = null ;
392
- window . localStorage . setItem ( "node-red-node-ui-webcam-activeCam" , c ) ;
393
- if ( active !== false ) {
394
- $scope . enableCamera ( ) ;
395
- }
386
+ let c = parseInt ( msg . camera ) ;
387
+ if ( ! isNaN ( c ) ) {
388
+ // Check if cameras array is populated
389
+ if ( $scope . data . cameras && $scope . data . cameras . length > c ) {
390
+ $scope . changeCamera ( c ) ;
391
+ } else {
392
+ // Enumerate devices first, then change camera
393
+ navigator . mediaDevices . enumerateDevices ( ) . then ( function ( devices ) {
394
+ $scope . data . cameras = devices . filter ( function ( device ) {
395
+ return device . kind === "videoinput" ;
396
+ } ) ;
397
+ if ( c >= 0 && c < $scope . data . cameras . length ) {
398
+ $scope . changeCamera ( c ) ;
399
+ } else {
400
+ console . warn ( "Camera index out of range:" , c ) ;
401
+ }
402
+ } ) . catch ( function ( err ) {
403
+ console . error ( "Error enumerating devices:" , err ) ;
404
+ } ) ;
396
405
}
397
406
}
398
407
}
0 commit comments