interface Size {
  width?: number;
  height?: number;
  aspectRatio?: number;
}


export async function getMediaStream(constraints?: MediaTrackConstraints & Size) {
  const stream = await navigator.mediaDevices.getUserMedia({ video: constraints ?? true });
  if ( constraints?.width != null && constraints?.height != null ) {
    // 修正宽高
    const track = stream.getVideoTracks()[ 0 ];
    const { width: CW = 1, height: CH = 1, aspectRatio: CAR = CW / CH, ..._constraints } = constraints;
    const { width: SW = 1, height: SH = 1, aspectRatio: SAR = SW / SH } = track.getSettings();
    if ( SAR > CAR || (
      CW === SH && CH === SW
    ) ) {
      await track.applyConstraints({ ..._constraints, height: CW, width: CH });
    }
  }
  return stream;
}

