compressVideo method

Future<MediaInfo?> compressVideo(
  1. String path, {
  2. VideoQuality quality = VideoQuality.DefaultQuality,
  3. bool deleteOrigin = false,
  4. int? startTime,
  5. int? duration,
  6. bool? includeAudio,
  7. int frameRate = 30,
})

Compresses the video at path. startTime and duration are in seconds; frameRate is a cap, a slower video is not sped up.

Returns null when the compression fails or is cancelled, as video_compress did on Android. Progress from 0 to 100 goes to IVideoCompress.compressProgress$.

Implementation

Future<MediaInfo?> compressVideo(
  String path, {
  VideoQuality quality = VideoQuality.DefaultQuality,
  bool deleteOrigin = false,
  int? startTime,
  int? duration,
  bool? includeAudio,
  int frameRate = 30,
}) async {
  if (isCompressing) {
    throw StateError('''VideoCompress Error:
    Method: compressVideo
    Already have a compression process, you need to wait for the process to finish or stop it''');
  }
  if (compressProgress$.notSubscribed) {
    debugPrint('''VideoCompress: You can try to subscribe to the
    compressProgress\$ stream to know the compressing state.''');
  }

  final start = startTime == null ? null : Duration(seconds: startTime);
  final end = duration == null
      ? null
      : (start ?? Duration.zero) + Duration(seconds: duration);
  final options = quality.options.copyWith(
    deleteOrigin: deleteOrigin,
    includeAudio: includeAudio ?? true,
    maxFrameRate: frameRate,
    trimStart: start,
    trimEnd: end,
  );

  StreamSubscription<double>? listening;
  CompressTask? task;
  try {
    // ignore: invalid_use_of_protected_member
    setProcessingStatus(true);
    task = VideoCompressor.compress(path, options: options);
    _task = task;
    // Like video_compress, progress goes to the current instance, a new one
    // after dispose().
    var sent = 0.0;
    void send(double percent) {
      sent = percent;
      _VideoCompressImpl._instance?.compressProgress$.next(percent);
    }

    listening = task.progress.listen((p) => send(p * 100));
    final info = await task.result;
    // video_compress always ended a success with 100; the stream's last
    // event may still be on its way.
    if (sent < 100) send(100);
    return MediaInfo.fromVideoInfo(info, isCancel: false);
  } on VideoCompressException catch (e) {
    if (e.error != VideoCompressError.cancelled) _log('compressVideo', e);
    return null;
  } finally {
    await listening?.cancel();
    if (identical(_task, task)) _task = null;
    // ignore: invalid_use_of_protected_member
    setProcessingStatus(false);
  }
}