Navaron Bracke

add custom video track settings class for web

  1 +import 'dart:js_interop';
  2 +
  3 +import 'package:web/web.dart';
  4 +
  5 +/// This class defines the settings for a video track.
  6 +///
  7 +/// Since the [MediaTrackSettings] type is the full union of both the base MediaTrackSettings,
  8 +/// the tracks settings for audio tracks, and the tracks settings for video tracks,
  9 +/// this class only keeps track of the video track settings.
  10 +///
  11 +/// See also:
  12 +/// * https://www.w3.org/TR/mediacapture-streams/#media-track-settings
  13 +/// * https://www.w3.org/TR/image-capture/#mediatracksettings-section
  14 +class VideoTrackSettings {
  15 + /// Creates a [VideoTrackSettings] instance from a [MediaStreamTrack].
  16 + ///
  17 + /// Since the actual track settings might not have specify all required properties,
  18 + /// query the capabilities before using specific settings.
  19 + ///
  20 + /// Unsupported values fall back to their defaults.
  21 + factory VideoTrackSettings(MediaStreamTrack videoTrack) {
  22 + assert(videoTrack.kind == 'video', 'The given track is not a video track.');
  23 +
  24 + final MediaTrackSettings settings = videoTrack.getSettings();
  25 + final MediaTrackCapabilities capabilities = videoTrack.getCapabilities();
  26 +
  27 + final JSAny? facingModeCapability = capabilities.facingMode as JSAny?;
  28 + final JSAny? focusDistanceCapability = capabilities.focusDistance as JSAny?;
  29 + final JSAny? focusModeCapability = capabilities.focusMode as JSAny?;
  30 + final JSAny? torchCapability = capabilities.torch as JSAny?;
  31 + final JSAny? zoomCapability = capabilities.zoom as JSAny?;
  32 +
  33 + // The width and height are always supported.
  34 + return VideoTrackSettings._(
  35 + width: settings.width,
  36 + height: settings.height,
  37 + facingMode:
  38 + facingModeCapability.isDefinedAndNotNull ? settings.facingMode : '',
  39 + focusDistance: focusDistanceCapability.isDefinedAndNotNull
  40 + ? settings.focusDistance.toDouble()
  41 + : -1.0,
  42 + focusMode:
  43 + focusModeCapability.isDefinedAndNotNull ? settings.focusMode : 'none',
  44 + torch: torchCapability.isDefinedAndNotNull && settings.torch,
  45 + zoom: zoomCapability.isDefinedAndNotNull ? settings.zoom.toDouble() : 1.0,
  46 + );
  47 + }
  48 +
  49 + /// The private constructor.
  50 + const VideoTrackSettings._({
  51 + required this.facingMode,
  52 + required this.focusDistance,
  53 + required this.focusMode,
  54 + required this.height,
  55 + required this.torch,
  56 + required this.width,
  57 + required this.zoom,
  58 + });
  59 +
  60 + final String facingMode;
  61 + final double focusDistance;
  62 + final String focusMode;
  63 + final int height;
  64 + final bool torch;
  65 + final int width;
  66 + final double zoom;
  67 +}