chooseBestQualityForInternet method

Future<int> chooseBestQualityForInternet(
  1. StreamManifest manifest
)

Select the best quality for the estimated network speed.

Implementation

Future<int> chooseBestQualityForInternet(exp.StreamManifest manifest) async {
  // Use the highest quality as default
  final videoStreams = manifest.videoOnly.toList();
  if (videoStreams.isEmpty) return 0;

  // Pick a mid-quality stream for speed test
  final testStream = videoStreams[videoStreams.length ~/ 2];
  final testUrl = testStream.url.toString();
  final estimatedBps = await _estimateNetworkSpeed(testUrl);

  if (estimatedBps == null) return 0; // fallback to auto

  // Find the highest quality whose bitrate is <= 80% of estimated bandwidth
  final safeBps = (estimatedBps * 0.8).toInt();
  videoStreams.sort((a, b) => a.bitrate.compareTo(b.bitrate));
  int chosenHeight = 0;
  for (final stream in videoStreams) {
    if (stream.bitrate.bitsPerSecond <= safeBps) {
      chosenHeight = max(chosenHeight, stream.videoResolution.height);
    }
  }
  return chosenHeight == 0 ? 0 : chosenHeight;
}