Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

Overview

flutter_video_compress

Generate a new path by compressed video, Choose to keep the source video or delete it by a parameter. Get video thumbnail from a video path and provide video information. Easy to deal with compressed video. Considering reduce application size is not using FFmpeg in IOS.

pub version license android min Sdk Version ios min target

flutter compress video

languages

English 简体中文 日本語

Usage

Installing add flutter_video_compress as a dependency in your pubspec.yaml file.

dependencies:
  flutter_video_compress: ^0.3.x

Create an instance

final _flutterVideoCompress = FlutterVideoCompress();

Get thumbnail from video path

final uint8list = await _flutterVideoCompress.getThumbnail(
  file.path,
  quality: 50, // default(100)
  position: -1 // default(-1)
);

Get thumbnail file from video path

final thumbnailFile = await _flutterVideoCompress.getThumbnailWithFile(
  file.path,
  quality: 50, // default(100)
  position: -1 // default(-1)
);

Convert video to a gif

final file = await _flutterVideoCompress.convertVideoToGif(
  videoFile.path,
  startTime: 0, // default(0)
  duration: 5, // default(-1)
  // endTime: -1 // default(-1)
);
debugPrint(file.path);

Get media information

only support video now.

final info = await _flutterVideoCompress.getMediaInfo(file.path);
debugPrint(info.toJson().toString());

Compression Video

Compatible with IOS, Android and Web after compression.

final info = await _flutterVideoCompress.compressVideo(
  file.path,
  quality: VideoQuality.DefaultQuality, // default(VideoQuality.DefaultQuality)
  deleteOrigin: false, // default(false)
);
debugPrint(info.toJson().toString());

Check Compressing state

_flutterVideoCompress.isCompressing

Stop compression

Will print InterruptedException in android, but not affect to use.

await _flutterVideoCompress.cancelCompression()

delete all cache files

Delete all files generated by this will delete all files located at 'flutter_video_compress', you shoule ought to know what are you doing.

await _flutterVideoCompress.deleteAllCache()

Subscribe the compression progress steam

class ... extends State<MyApp> {
  Subscription _subscription;

  @override
  void initState() {
    super.initState();
    _subscription =
        _flutterVideoCompress.compressProgress$.subscribe((progress) {
      debugPrint('progress: $progress');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _subscription.unsubscribe();
  }
}

Methods

Functions Parameters Description Returns
getThumbnail String path[video path], int quality(1-100)[thumbnail quality], int position[Get a thumbnail from video position] get thumbnail from video path Future<Uint8List>
getThumbnailWithFile String path[video path], int quality(1-100)[thumbnail quality], int position[Get a thumbnail from video position] get thumbnail file from video path Future<File>
convertVideoToGif String path[video path], int startTime(from 0 start)[convert video to gif start time], int endTime[convert video to gif end time], int duration[convert video to gif duration from start time] convert video to gif from video path Future<File>
getMediaInfo String path[video path] get media information from video path Future<MediaInfo>
compressVideo String path[video path], VideoQuality quality[compressed video quality], bool deleteOrigin[delete the origin video], int startTime[compression video start time], int duration[compression video duration from start time], bool includeAudio[is include audio in compressed video], int frameRate[compressed video frame rate] compression video at origin video path Future<MediaInfo>
cancelCompression none cancel compressing Future<void>
deleteAllCache none Delete all files generated by 'flutter_video_compress' will delete all files located at 'flutter_video_compress' Future<bool>

Subscriptions

Subscriptions Description Stream
compressProgress$ Subscribe the compression progress steam double progress

Notice

If your application is significantly larger after using the plugin, you can reduce the application size in the following way:

  • exclude x86 related files (./assets)

  • This library not use ffprobe, only used ffmpeg, but the application still has ffprobe, so you will need to exclude (asssets/arm or assets/x86)

add this config in build.gradle:

  • Don't use ignoreAssetsPattern "!x86" in debug mode, will crash on the simulator
android {
 ...
 // Reduce your application size with this configuration
 aaptOptions {
     ignoreAssetsPattern "!x86:!*ffprobe"
 }
 
 buildTypes {
 ...
}

look detail

Questions

If your application is not enabled AndroidX, you will need to add the following code to the last line of the android/build.gradle file.

rootProject.allprojects {
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'androidx.core' && !details.requested.name.contains('androidx')) {
                    details.useVersion "1.0.1"
                }
            }
        }
    }
}

If your application not support swift, you need to add the following code in ios/Podfile.

target 'Runner' do
  use_frameworks! # <--- add this
  ...
end

look detail

If your application never used a swift plugin before, maybe you would meet the error, you need to add the following code in ios/Podfile.

The 'Pods-Runner' target has transitive dependencies that include static binaries

pre_install do |installer|
  # workaround for https://github.com/CocoaPods/CocoaPods/issues/3289
  Pod::Installer::Xcode::TargetValidator.send(:define_method, :verify_no_static_framework_transitive_dependencies) {}
end

If the above method not work, you report bug of the error repository. The reason is「can't support swift」

look detail

if show error of Regift

  • Regift does not specify a Swift version and none of the targets (Runner) integrating it have the SWIFT_VERSION attribute set. Please contact the author or set the SWIFT_VERSION attribute in at least one of the targets that integrate this pod.
pre_install do |installer|
  installer.analysis_result.specifications.each do |s|
      if s.name == 'Regift'
        s.swift_version = '4.0'
      end
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

Contribute

Contributions are always welcome!

Comments
  • Remove videoToGif and instead add creating a short video without sound

    Remove videoToGif and instead add creating a short video without sound

    Description

    Since Gif is lossless format, gifs made from video have are bigger in size than short videos without audio. Also, there is a problem with Regift library since it is targeting iOS 11.1. My suggestion is to remove videoToGif and add a couple of optional parameters to startCompression for creating video preview.

    Platform

    Both

    Code Example (if has)

    void main() {
         _flutterVideoCompress.startCompress(
              file.path,
              deleteOrigin: true,
              quality: VideoQuality.LowQuality,
              startTime: 0,
              duration: 5,
              includeAudio: false,
              frameRate: 24,
            );
    }
    

    Expected solution

    I will implement this by adding parameters to this method if @TenkaiRuri agrees?

    enhancement 
    opened by vlada3003 13
  • [Bug] Cannot run example on iOS with swift version 4.2.1

    [Bug] Cannot run example on iOS with swift version 4.2.1

    Description

    My Swift version:

    Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
    Target: x86_64-apple-darwin18.6.0
    

    Unable to run the example. The error says:

    Launching lib/main.dart on iPhone XR in debug mode...
    Xcode build done.                                            1.7s
    Failed to build iOS app
    Error output from Xcode build:
    ↳
        ** BUILD FAILED **
    Xcode's output:
    ↳
        === BUILD TARGET video_player OF PROJECT Pods WITH CONFIGURATION Debug ===
        The “Swift Language Version” (SWIFT_VERSION) build setting must be set to a supported value for targets which use Swift. Supported values are: 3.0, 4.0, 4.2. This setting can be set in the build settings editor.
    Could not build the application for the simulator.
    Error launching application on iPhone XR.
    Exited (sigterm)
    

    Platform

    iOS

    Backtracking step

    1. clone this repo https://github.com/rurico/flutter_video_compress.git
    2. cd flutter_video_compress/example/
    3. flutter packages get
    4. flutter run

    Expected solution

    Does the plugin support swift 4.2?

    bug 
    opened by VictorUvarov 10
  • [Help/Performance] Video compressing taking too long

    [Help/Performance] Video compressing taking too long

    Description

    I need to take a video from camera/gallery, compress it (lower resolution or quality or width/height) and upload to firebase storage so I can download it later and show it on a VideoPlayer on a ListView.

    Platform

    Android

    Using

    Latest Image Picker

    Expected solution

    I did some tests and the compressing is taking around 1 minute for each video second: A 5 seconds video needs ~5 minutes to compress; A 12 seconds video needs ~12 minutes to compress.

    Is there an easy way to improve performance of compressing? Like using an Isolate or something like.

    Which is the best approach for that? Should I start compressing right after picking video to save time? Should I use camera plugin instead of image picker for taking videos?

    My goal is to make an Instagram-like social network so it can't take so long to upload a small video.

    help wanted optimization 
    opened by GustavoContreiras 9
  • Compressing seems to never stop

    Compressing seems to never stop

    When compressing a second video after compressing the first one, I get following Error:

    Already have a compression process, you need to wait for the process to finish

    It seems that the compression process of the first video is still in progress. Does it not stop automatically? Do I need to stop it manually by calling _stopCompress() ?

    Thanks for your help!

    bug 
    opened by kamami 9
  • Return file instead of path

    Return file instead of path

    Hi, I need to upload the compressed video to firebase. Any possability to return the compressed file instead of the path?

    Good job btw. with the widget!

    enhancement 
    opened by kamami 9
  • Compression hangs

    Compression hangs

    Hi Im having trouble getting a video to compress after I have already compressed one. I compress one video and it works fine but the second seems to hang and never returns from the await. I'm doing it like this

    final String newPath = await _flutterVideoCompress.compressVideo(path: file.path, deleteOrigin: true);

    Would you please be able to help me

    Thanks Jawad

    bug 
    opened by jawadt1 9
  • [Bug] this happens when I subscribe to compressor

    [Bug] this happens when I subscribe to compressor

    Code Example (if has)

    void main() {
    final _flutterVideoCompress = FlutterVideoCompress();
                _conpressSubscription = _flutterVideoCompress.compressProgress$.subscribe((progress) {
                      debugPrint('progress: $progress');
                    });
                File myFile = _file;
                debugPrint(_file.lengthSync().toString());
                final info = await _flutterVideoCompress.getMediaInfo(_file.path);
                print(info.toJson());
                if (info.duration > 120 || _file.lengthSync() > 5000000) {
                  Fluttertoast.showToast(msg: 'در حال کم کردن حجم....');
                  VideoQuality quality = VideoQuality.HighestQuality;
                  if (_file.lengthSync() > 5000000) {
                    quality = VideoQuality.MediumQuality;
                  }
                  final info2 = await _flutterVideoCompress.compressVideo(
                    _file.path,
                    startTime: 0,
                    duration: 120,
                    quality: quality, // default(VideoQuality.DefaultQuality)
                    deleteOrigin: false, // default(false)
                  );
                  debugPrint(info2.toJson().toString());
                  myFile = info2.file;
                }
    }
    

    this is the log : I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): progress: 0.0 I/flutter ( 6520): {path: /storage/emulated/0/Android/data/netonote.ir.netonote/files/flutter_video_compress/VID_20191221_010843_056.mp4, title: , author: , width: 2700, ......

    bug 
    opened by sepehr13494 8
  • [Bug]编译iOS的时候报The 'Pods-Runner' target has transitive dependencies that include statically linked binaries

    [Bug]编译iOS的时候报The 'Pods-Runner' target has transitive dependencies that include statically linked binaries

    编译iOS的时候报: [!] The 'Pods-Runner' target has transitive dependencies that include statically linked binaries: (/Users/siwen/MyProject/viiapp/ios/Pods/AlipaySDK-iOS/AlipaySDK.framework, /Users/siwen/MyProject/viiapp/ios/Pods/UMCAnalytics/UMAnalytics.framework, and /Users/siwen/MyProject/viiapp/ios/Pods/UMCCommon/UMCommon.framework)

    请问如何解决?感谢

    bug 
    opened by goodsiwen 8
  • [Bug] Pod install problems with latest version

    [Bug] Pod install problems with latest version

    Description

    Build breaks when use_frameworks! is added to a Podfile. When a library that has s.static_framework = true is added to a project that has flutter_video_compress, '$pod install' fails with a message "[!] The 'Pods-Runner' target has transitive dependencies that include statically linked binaries: (image_cropper)" image_cropper is a library that has s.static_framework = true if use_frameworks! isn't set then Regift won't compile.

    Platform

    IOS

    Proposed solution

    Is to fork Regift and to reduce the ios minimum supported version and remove the use_frameworks! flag. However, this is just a guess since I'm unfamiliar with iOS build system.

    bug 
    opened by vlada3003 7
  • compressed video is null

    compressed video is null

    I am trying to compress a video file and return the new compressed file, but following code prints NULL both times:

       final MediaInfo newPath = await _flutterVideoCompress.startCompress(
        widget.videoFile.path,
        deleteOrigin: true,
      );
    
      setState(() {
        video = newPath.file;
      });
    
       print("${newPath.file}");
       print("$video");
    
    bug 
    opened by kamami 5
  • [Suggestion] Rename methods

    [Suggestion] Rename methods

    I saw that you owners are not americans and maybe thats the reason the methods don't have a intuitive name.

    My suggestions for rename: startCompress -> compressVideo convertVideoToGif -> compressVideoToGif stopCompress -> cancelCompress getThumbnail -> getThumbnailBytesList getThumbnailWithFile -> getThumbnail

    enhancement 
    opened by GustavoContreiras 3
  • Null check operator used on a null value

    Null check operator used on a null value

    Description

    .mp4 file compression is pretty good but when i pick .mov file to compress it's couldn't able to compress and file path throwing null exception.

    Platform

    IOS|Android|Both|Other

    Code Example (if has)

    
    for (var element in dto.media) {
          var file = await PhotoGallery.getFile(mediumId: element.id);
          Uint8List? data;
          if (element.mediumType == MediumType.image) {
            data = await AppUtils.compressToUint8List(
                file.path, element.height, element.width, 50);
            files.add(MultipartFile.fromBytes(data!,
                filename: getFileName(element.filename!)));
          } else {
            log("File name ===========> ${file.path}");
            log("Compress Start ===========> ${DateTime.now()}");
            try {
              showProgressDialogStatus(0);
              final response = await vc.VideoCompress.compressVideo(
                file.path,
                quality: vc.VideoQuality.MediumQuality,
                // deleteOrigin: false, // It's false by default
              );
              log("File path ===========> ${response!.path}");
              log("Compress end ===========> ${DateTime.now()}");
    
              var multipart = await MultipartFile.fromFile(response.path!,
                  filename: getFileName(response.path!));
              files.add(multipart);
            } catch (e) {
              log("compress error ===========> $e");
            }
          }
        }
     
    
    bug 
    opened by hmbadhon 0
  • [Bug]could not access /data/user/0/com.example.app/app_flutter/Trimmer/file.mp4

    [Bug]could not access /data/user/0/com.example.app/app_flutter/Trimmer/file.mp4

    Description

    i tried to compress the trimmed video by video_trimmer package but I gets an error. it happens only on android.

    Platform

    Android

    Unexpected error while transcoding. E/TranscodeEngine(32461): java.lang.IllegalArgumentException: could not access /data/user/0/com.example.app/app_flutter/Trimmer/image_picker9113914114815938940_trimmed:Sep20,2022-14:59:48.mp4 E/TranscodeEngine(32461): at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:370) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.source.UriDataSource.initializeRetriever(UriDataSource.java:33) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.source.DefaultDataSource.initialize(DefaultDataSource.java:57) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.internal.DataSources.init(DataSources.kt:22) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.internal.DataSources.init(DataSources.kt:26) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.internal.DataSources.(DataSources.kt:35) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.internal.DataSources.(DataSources.kt:17) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.internal.transcode.TranscodeEngine$Companion.transcode(TranscodeEngine.kt:33) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.internal.transcode.TranscodeEngine.transcode(Unknown Source:2) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.Transcoder$1.call(Transcoder.java:102) E/TranscodeEngine(32461): at com.otaliastudios.transcoder.Transcoder$1.call(Transcoder.java:99) E/TranscodeEngine(32461): at java.util.concurrent.FutureTask.run(FutureTask.java:264) E/TranscodeEngine(32461): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137) E/TranscodeEngine(32461): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637) E/TranscodeEngine(32461): at java.lang.Thread.run(Thread.java:1012)

    bug 
    opened by ParhaMDeF 0
  • [Bug] Compress tiktok downloaded video

    [Bug] Compress tiktok downloaded video

    Description

    When im trying to compress tiktok downloaded video the default size 7mb after the compressing done the compressed video has size 22 mb.

    Platform

    IOS|Android|Both|Other

    bug 
    opened by mcleaw 0
  • [Feature]flutter_video_compress uses a deprecated version of the Android embedding

    [Feature]flutter_video_compress uses a deprecated version of the Android embedding

    Description

    While building under Flutter v2.10.*, there's a warning below, please take care, thanks in advance!

    The plugin `flutter_video_compress` uses a deprecated version of the Android embedding.
    To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding.
    Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
    If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding:
    https://flutter.dev/go/android-plugin-migration.
    

    Platform

    Android

    Code Example (if has)

    flutter build apk
    

    Expected solution

    Improvement.

    enhancement 
    opened by michael-towify 1
Owner
天海るり
why you touch my skirt.
天海るり
Munem Sarker 1 Jan 25, 2022
A flutter ffmpeg kit example

flutter-ffmpeg-kit-lts-repro Steps to reproduce: git clone [email protected]:jozsefsallai/flutter-ffmpeg-kit-lts-repro.git cd flutter-ffmpeg-kit-lts-repr

József Sallai 1 Mar 5, 2022
Fluttex is useful package for reduce coding time and coding simplicity.

Easy and Fast coding using Fluttex Fluttex is a package that developed for flutter framework. flutter developers can use this package to reduce their

AmirHosien Hasan zadeh 3 Feb 19, 2022
Playify is a Flutter plugin for play/pause/seek songs, fetching music metadata, and browsing music library.

Playify Playify is a Flutter plugin for play/pause/seek songs, fetching music metadata, and browsing music library. Playify was built using iOS's Medi

Ibrahim Berat Kaya 32 Dec 14, 2022
With Bloc - Path Provider - Hydrated Bloc

Intro Custom Default Counter App on Flutter. The updated : Flutter Bloc / Cubit + Path Provider + Hydrated Bloc + Store Data using Hive Check the scre

Ihab Zaidi 1 Oct 30, 2021
A Flutter plugin for handling Connectivity and REAL Connection state in the mobile, web and desktop platforms. Supports iOS, Android, Web, Windows, Linux and macOS.

cross_connectivity A Flutter plugin for handling Connectivity and REAL Connection state in the mobile, web and desktop platforms. Supports iOS, Androi

MarchDev Toolkit 29 Nov 15, 2022
A Flutter plugin that supports Pangle SDK on Android and iOS.

Thanks for non-commercial open source development authorization by JetBrains. 穿山甲 Flutter SDK `pangle_flutter`是一款集成了字节跳动穿山甲 Android 和 iOS SDK的 Flutter

null 121 Dec 2, 2022
A robust Flutter plugin for making payments via Paystack Payment Gateway. Completely supports Android and iOS

?? Paystack Plugin for Flutter A Flutter plugin for making payments via Paystack Payment Gateway. Fully supports Android and iOS. ?? Installation To u

Wilberforce Uwadiegwu 165 Jan 4, 2023
A flutter plugin for integrating razorpay payment gateway. Supports Android and iOS.

Flutter Razorpay Plugin A flutter plugin for razorpay integration for both android and ios. If you use this library in your app, please let me know an

Chetan Kaushik 28 Dec 13, 2022
GChat is a chatting application developed using Flutter(Dart) and firebase for 2 users. Trying to Develop an application that does not sell your data with whatsapp rolling out its privacy policy updates.

Gchat - The Chatting Application A Flutter project for chatting. I used Android Studio and you can you any editor of your choice for ex: VS Code, Inte

Sanchaksh Kaul 6 Nov 6, 2022
Video player-2.2.10 - A Flutter plugin for iOS, Android and Web for playing back video on a Widget surface

Video Player plugin for Flutter A Flutter plugin for iOS, Android and Web for pl

null 2 Sep 29, 2022
a software to connect you and your friends and others, are you guys also just tensed over the overuse of social media so we have a solution, appx (name not decided yet)

appx a software to connect you and your friends and others, are you guys also just tensed over the overuse of social media so we have a solution, appx

null 8 Jun 9, 2022
A flutter app face detection and emotion, can detect if you're smiling, big smiley, sad or if there is not face on the screen.

My Emotion A flutter app face detection and emotion, can detect if you're smiling, big smiley, sad or if there is not face on the screen. News feactur

António Nicolau 29 Dec 31, 2022
This is not an app. I made this architecture to build robust and easy-to-maintain products but in a faster way.

simple_architecture_flutter This is not an app. I made this architecture to build robust and easy-to-maintain products but in a faster way. Info I use

Batuhan Karababa 9 Oct 28, 2022
Starter app for Flutter that includes many different production app features; some not typically included in demo apps.

first_app: Starter app for a Flutter production app Maintainer: Greger Wedel, https://github.com/gregertw Listed on: Latest build and artifacts: ** La

Greger Teigre Wedel 373 Jan 8, 2023
Provide easy and flexible way to show SnackBar. Simple text, undo, and error style are supported.

snack_bar_presenter Provide easy and flexible way to show SnackBar. Simple text, undo, and error style are supported. . . . Usage import 'package:exam

Masayuki Ono (mono) 8 Nov 30, 2020
Tubles is a simple applications to provide any tubles in in google maps and we as the user can navigate into the selected tubles location.

Tubles Tubles is a simple applications to provide any tubles place in google maps and we as the user can navigate into the selected tubles location. F

Yusril Rapsanjani 78 Jan 8, 2023
💪 Helm is an app that gamifies stress/anxiety/depression management in an actionable manner to provide relief.

Helm Helm is an app that gamifies stress/anxiety/depression management in an actionable manner to provide relief. To try it out, setup flutter on your

Bing Quan 497 Dec 30, 2022