Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ios, android): control quality by bitrate/fileLengthLimit #1

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class VideoCompressPlugin : MethodCallHandler, FlutterPlugin {
val duration = call.argument<Int>("duration")
val includeAudio = call.argument<Boolean>("includeAudio") ?: true
val frameRate = if (call.argument<Int>("frameRate")==null) 30 else call.argument<Int>("frameRate")
val bitrate = if (call.argument<Int>("bitrate")==null) DefaultVideoStrategy.BITRATE_UNKNOWN else call.argument<Int>("bitrate")

val tempDir: String = context.getExternalFilesDir("video_compress")!!.absolutePath
val out = SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(Date())
Expand All @@ -94,36 +95,55 @@ class VideoCompressPlugin : MethodCallHandler, FlutterPlugin {
when (quality) {

0 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(720).build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(720)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}

1 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(360).build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(360)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
2 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(640).build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(640)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
3 -> {

assert(value = frameRate != null)
videoTrackStrategy = DefaultVideoStrategy.Builder()
.keyFrameInterval(3f)
.bitRate(1280 * 720 * 4.toLong())
.frameRate(frameRate!!) // will be capped to the input frameRate
.build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(720)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
4 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(480, 640).build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(480, 640)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
5 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(540, 960).build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(540, 960)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
6 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(720, 1280).build()
videoTrackStrategy = DefaultVideoStrategy
.atMost(720, 1280)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
7 -> {
videoTrackStrategy = DefaultVideoStrategy.atMost(1080, 1920).build()
}
videoTrackStrategy = DefaultVideoStrategy
.atMost(1080, 1920)
.bitRate(bitrate!!.toLong())
.frameRate(frameRate!!).build()
}
}

audioTrackStrategy = if (includeAudio) {
Expand Down
8 changes: 6 additions & 2 deletions ios/Classes/SwiftVideoCompressPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ public class SwiftVideoCompressPlugin: NSObject, FlutterPlugin {
let duration = args!["duration"] as? Double
let includeAudio = args!["includeAudio"] as? Bool
let frameRate = args!["frameRate"] as? Int
let fileLengthLimit = args!["fileLengthLimit"] as? Int
compressVideo(path, quality, deleteOrigin, startTime, duration, includeAudio,
frameRate, result)
frameRate, fileLengthLimit, result)
case "cancelCompression":
cancelCompression(result)
case "deleteAllCache":
Expand Down Expand Up @@ -178,7 +179,7 @@ public class SwiftVideoCompressPlugin: NSObject, FlutterPlugin {
}

private func compressVideo(_ path: String,_ quality: NSNumber,_ deleteOrigin: Bool,_ startTime: Double?,
_ duration: Double?,_ includeAudio: Bool?,_ frameRate: Int?,
_ duration: Double?,_ includeAudio: Bool?,_ frameRate: Int?,_ fileLengthLimit: Int?,
_ result: @escaping FlutterResult) {
let sourceVideoUrl = Utility.getPathUrl(path)
let sourceVideoType = "mp4"
Expand Down Expand Up @@ -214,6 +215,9 @@ public class SwiftVideoCompressPlugin: NSObject, FlutterPlugin {
exporter.outputURL = compressionUrl
exporter.outputFileType = AVFileType.mp4
exporter.shouldOptimizeForNetworkUse = true
if let fileLengthLimit = fileLengthLimit {
exporter.fileLengthLimit = Int64(fileLengthLimit)
}

if let frameRate = frameRate, Float(frameRate) <= avController.getNominalFrameRate(sourceVideoTrack) {
let videoComposition = AVMutableVideoComposition(propertiesOf: sourceVideoAsset)
Expand Down
58 changes: 56 additions & 2 deletions lib/src/video_compress/video_compressor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ extension Compress on IVideoCompress {
/// determine whether to delete his source file by [deleteOrigin]
/// optional parameters [startTime] [duration] [includeAudio] [frameRate]
///
/// platform specific options [options]
/// See:
/// [IOSOptions]
/// [AndroidOptions]
///
/// ## example
/// ```dart
/// final info = await _flutterVideoCompress.compressVideo(
Expand All @@ -128,6 +133,7 @@ extension Compress on IVideoCompress {
int? duration,
bool? includeAudio,
int? frameRate = 30,
List<PlatformOptions>? options,
}) async {
if (isCompressing) {
throw StateError('''VideoCompress Error:
Expand Down Expand Up @@ -156,15 +162,24 @@ extension Compress on IVideoCompress {

// ignore: invalid_use_of_protected_member
setProcessingStatus(true);
final jsonStr = await _invoke<String>('compressVideo', {

final arguments = <String, dynamic>{
'path': path,
'quality': quality.index,
'deleteOrigin': deleteOrigin,
'startTime': startTime,
'duration': duration,
'includeAudio': includeAudio,
'frameRate': frameRate,
});
};

if (options != null) {
for (final option in options) {
arguments.addAll(option.toMap());
}
}

final jsonStr = await _invoke<String>('compressVideo', arguments);

// ignore: invalid_use_of_protected_member
setProcessingStatus(false);
Expand Down Expand Up @@ -195,3 +210,42 @@ extension Compress on IVideoCompress {
});
}
}

abstract class PlatformOptions {
Map<String, dynamic> toMap();
}

class IOSOptions extends PlatformOptions {
/// The file length that the output of the session must not exceed.
/// https://developer.apple.com/documentation/avfoundation/avassetexportsession/1622333-filelengthlimit
final int? fileLengthLimit;

IOSOptions({
this.fileLengthLimit,
});

@override
Map<String, dynamic> toMap() {
return {
'fileLengthLimit': fileLengthLimit,
};
}
}

class AndroidOptions extends PlatformOptions {
/// Desired bit rate (bits per second). Can optionally be
/// null, in which case the strategy will try to estimate the bitrate.
/// https://opensource.deepmedia.io/transcoder/track-strategies#other-options
final int? bitrate;

AndroidOptions({
this.bitrate,
});

@override
Map<String, dynamic> toMap() {
return {
'bitrate': bitrate,
};
}
}