Repository: AbedElazizShe/LightCompressor Branch: master Commit: e858e91e0c36 Files: 71 Total size: 189.6 KB Directory structure: gitextract_wb5gjwc9/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .idea/ │ ├── .name │ ├── codeStyles/ │ │ ├── Project.xml │ │ └── codeStyleConfig.xml │ ├── compiler.xml │ ├── dictionaries/ │ │ └── abdsh.xml │ ├── gradle.xml │ ├── inspectionProfiles/ │ │ └── Project_Default.xml │ ├── jarRepositories.xml │ ├── kotlinc.xml │ ├── misc.xml │ └── vcs.xml ├── LICENSE ├── README.md ├── app/ │ ├── build.gradle │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── abedelazizshe/ │ │ └── lightcompressor/ │ │ └── ExampleInstrumentedTest.kt │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── abedelazizshe/ │ │ │ └── lightcompressor/ │ │ │ ├── MainActivity.kt │ │ │ ├── RecyclerViewAdapter.kt │ │ │ ├── Utils.kt │ │ │ ├── VideoDetailsModel.kt │ │ │ └── VideoPlayerActivity.kt │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── ic_launcher_background.xml │ │ │ ├── ic_play_white_24dp.xml │ │ │ └── ic_video_library_white_24dp.xml │ │ ├── drawable-v24/ │ │ │ └── ic_launcher_foreground.xml │ │ ├── layout/ │ │ │ ├── activity_main.xml │ │ │ ├── activity_video_player.xml │ │ │ ├── content_main.xml │ │ │ └── recycler_view_item.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── xml/ │ │ └── media_capabilities.xml │ └── test/ │ └── java/ │ └── com/ │ └── abedelazizshe/ │ └── lightcompressor/ │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle/ │ └── wrapper/ │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml ├── lightcompressor/ │ ├── .idea/ │ │ └── .gitignore │ ├── build.gradle │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── abedelazizshe/ │ │ └── lightcompressorlibrary/ │ │ └── ExampleInstrumentedTest.kt │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── abedelazizshe/ │ │ │ └── lightcompressorlibrary/ │ │ │ ├── CompressionInterface.kt │ │ │ ├── VideoCompressor.kt │ │ │ ├── compressor/ │ │ │ │ └── Compressor.kt │ │ │ ├── config/ │ │ │ │ ├── Configuration.kt │ │ │ │ └── VideoResizer.kt │ │ │ ├── data/ │ │ │ │ └── Atoms.kt │ │ │ ├── utils/ │ │ │ │ ├── CompressorUtils.kt │ │ │ │ ├── FileUtils.kt │ │ │ │ ├── NumbersUtils.kt │ │ │ │ └── StreamableVideo.kt │ │ │ └── video/ │ │ │ ├── InputSurface.kt │ │ │ ├── MP4Builder.kt │ │ │ ├── Mdat.kt │ │ │ ├── Mp4Movie.kt │ │ │ ├── OutputSurface.kt │ │ │ ├── Result.kt │ │ │ ├── Sample.kt │ │ │ ├── TextureRenderer.kt │ │ │ └── Track.kt │ │ └── res/ │ │ └── values/ │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── abedelazizshe/ │ └── lightcompressorlibrary/ │ └── ExampleUnitTest.kt └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: ['https://www.paypal.com/paypalme/abedelazizshehadeh1/USD5'] ================================================ FILE: .gitignore ================================================ .classpath .DS_Store .externalNativeBuild .project .gradle .mtj.tmp .vscode .settings .cxx /.idea/caches /.idea/libraries /.idea/modules.xml /.idea/workspace.xml /.idea/navEditor.xml /.idea/assetWizardSettings.xml local.properties maven-repository mvn-clone build captures gen out target tmpmob *.class *.txt *.ear *.iml *.jar *.keystore *.log *.nar *.rar *.tar.gz *.war *.zip ================================================ FILE: .idea/.name ================================================ VideoCompressor ================================================ FILE: .idea/codeStyles/Project.xml ================================================
xmlns:android ^$
xmlns:.* ^$ BY_NAME
.*:id http://schemas.android.com/apk/res/android
.*:name http://schemas.android.com/apk/res/android
name ^$
style ^$
.* ^$ BY_NAME
.* http://schemas.android.com/apk/res/android ANDROID_ATTRIBUTE_ORDER
.* .* BY_NAME
================================================ FILE: .idea/codeStyles/codeStyleConfig.xml ================================================ ================================================ FILE: .idea/compiler.xml ================================================ ================================================ FILE: .idea/dictionaries/abdsh.xml ================================================ ftyp mdat moov muxer ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/inspectionProfiles/Project_Default.xml ================================================ ================================================ FILE: .idea/jarRepositories.xml ================================================ ================================================ FILE: .idea/kotlinc.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ [![JitPack](https://jitpack.io/v/AbedElazizShe/LightCompressor.svg)](https://jitpack.io/#AbedElazizShe/LightCompressor) # LightCompressor LightCompressor can now be used in Flutter through [light_compressor](https://pub.dev/packages/light_compressor) plugin. A powerful and easy-to-use video compression library for android uses [MediaCodec](https://developer.android.com/reference/android/media/MediaCodec) API. This library generates a compressed MP4 video with a modified width, height, and bitrate (the number of bits per seconds that determines the video and audio files’ size and quality). It is based on Telegram for Android project. The general idea of how the library works is that, extreme high bitrate is reduced while maintaining a good video quality resulting in a smaller size. I would like to mention that the set attributes for size and quality worked just great in my projects and met the expectations. It may or may not meet yours. I’d appreciate your feedback so I can enhance the compression process. **LightCompressor is now available in iOS**, have a look at [LightCompressor_iOS](https://github.com/AbedElazizShe/LightCompressor_iOS). # Change Logs ## What's new in 1.3.3 - Thanks to [LiewJunTung](https://github.com/AbedElazizShe/LightCompressor/pull/181) for improving the error handling. - Thanks to [CristianMG](https://github.com/AbedElazizShe/LightCompressor/pull/182) for improving the storage configuration and making the library testable. - Thanks to [dan3988](https://github.com/AbedElazizShe/LightCompressor/pull/188) for replacing video size with resizer which made using the library way more flexible. - Thanks to [imSzukala](https://github.com/AbedElazizShe/LightCompressor/pull/191) for changing min supported api to 21. - Thanks to [josebraz](https://github.com/AbedElazizShe/LightCompressor/pull/192) for improving codec profile approach. - Thanks to [ryccoatika](https://github.com/AbedElazizShe/LightCompressor/pull/198) for improving exception handling for the coroutines. ## How it works When the video file is called to be compressed, the library checks if the user wants to set a min bitrate to avoid compressing low resolution videos. This becomes handy if you don’t want the video to be compressed every time it is to be processed to avoid having very bad quality after multiple rounds of compression. The minimum is; * Bitrate: 2mbps You can as well pass custom resizer and videoBitrate values if you don't want the library to auto-generate the values for you. These values were tested on a huge set of videos and worked fine and fast with them. They might be changed based on the project needs and expectations. ## Demo ![Demo](/pictures/demo.gif) Usage -------- To use this library, you must add the following permission to allow read and write to external storage. Refer to the sample app for a reference on how to start compression with the right setup. **API < 29** ```xml ``` **API >= 29** ```xml ``` **API >= 33** ```xml ``` ```kotlin if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // request READ_MEDIA_VIDEO run-time permission } else { // request WRITE_EXTERNAL_STORAGE run-time permission } ``` And import the following dependencies to use kotlin coroutines ### Groovy ```groovy implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Version.coroutines}" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Version.coroutines}" ``` Then just call [VideoCompressor.start()] and pass **context**, **uris**, **isStreamable**, **configureWith**, and either **sharedStorageConfiguration OR appSpecificStorageConfiguration**. The method has a callback for 5 functions; 1) OnStart - called when compression started 2) OnSuccess - called when compression completed with no errors/exceptions 3) OnFailure - called when an exception occurred or video bitrate and size are below the minimum required for compression. 4) OnProgress - called with progress new value 5) OnCancelled - called when the job is cancelled ### Important Notes: - All the callback functions returns an index for the video being compressed in the same order of the urls passed to the library. You can use this index to update the UI or retrieve information about the original uri/file. - The source video must be provided as a list of content uris. - OnSuccess returns the path of the stored video. - If you want an output video that is optimised to be streamed, ensure you pass [isStreamable] flag is true. ### Configuration values - VideoQuality: VERY_HIGH (original-bitrate * 0.6) , HIGH (original-bitrate * 0.4), MEDIUM (original-bitrate * 0.3), LOW (original-bitrate * 0.2), OR VERY_LOW (original-bitrate * 0.1) - isMinBitrateCheckEnabled: this means, don't compress if bitrate is less than 2mbps - videoBitrateInMbps: any custom bitrate value in Mbps. - disableAudio: true/false to generate a video without audio. False by default. - resizer: Function to resize the video dimensions. `VideoResizer.auto` by default. ## The StorageConfiguration is an interface which indicate library where will be saved the File #### Library provides some behaviors defined to be more easy to use, specified the next ### AppSpecificStorageConfiguration Configuration values - subFolderName: a subfolder name created in app's specific storage. ### SharedStorageConfiguration Configuration values - saveAt: the directory where the video should be saved in. Must be one of the following; [SaveLocation.pictures], [SaveLocation.movies], or [SaveLocation.downloads]. - subFolderName: a subfolder name created in shared storage. ### CacheStorageConfiguration - There are no configuration values create a file in cache directory as Google defined, to get more info go to [here](https://developer.android.com/training/data-storage/app-specific?hl=es-419) ### Fully custom configuration - If any of these behaviors fit with your needs, you can create your own StorageConfiguration, just implement the interface and pass it to the library ```kotlin class FullyCustomizedStorageConfiguration( ) : StorageConfiguration { override fun createFileToSave( context: Context, videoFile: File, fileName: String, shouldSave: Boolean ): File = ??? What you need } ``` To cancel the compression job, just call [VideoCompressor.cancel()] ### Kotlin ```kotlin VideoCompressor.start( context = applicationContext, // => This is required uris = List, // => Source can be provided as content uris isStreamable = false, // THIS STORAGE storageConfiguration = SharedStorageConfiguration( saveAt = SaveLocation.movies, // => default is movies subFolderName = "my-videos" // => optional ) configureWith = Configuration( videoNames = listOf(), /*list of video names, the size should be similar to the passed uris*/ quality = VideoQuality.MEDIUM, isMinBitrateCheckEnabled = true, videoBitrateInMbps = 5, /*Int, ignore, or null*/ disableAudio = false, /*Boolean, or ignore*/ resizer = VideoResizer.matchSize(360, 480) /*VideoResizer, ignore, or null*/ ), listener = object : CompressionListener { override fun onProgress(index: Int, percent: Float) { // Update UI with progress value runOnUiThread { } } override fun onStart(index: Int) { // Compression start } override fun onSuccess(index: Int, size: Long, path: String?) { // On Compression success } override fun onFailure(index: Int, failureMessage: String) { // On Failure } override fun onCancelled(index: Int) { // On Cancelled } } ) ``` ## Common issues - Sending the video to whatsapp when disableAudio = false, won't succeed [ at least for now ]. Whatsapp's own compression does not work with LightCompressor library. You can send the video as document. - You cannot call Toast.makeText() and other functions dealing with the UI directly in onProgress() which is a worker thread. They need to be called from within the main thread. Have a look at the example code above for more information. ## Reporting issues To report an issue, please specify the following: - Device name - Android version ## Compatibility Minimum Android SDK: LightCompressor requires a minimum API level of 21. ## How to add to your project? #### Gradle Ensure Kotlin version is `1.8.21` Include this in your Project-level build.gradle file: ### Groovy ```groovy allprojects { repositories { . . . maven { url 'https://jitpack.io' } } } ``` Include this in your Module-level build.gradle file: ### Groovy ```groovy implementation 'com.github.AbedElazizShe:LightCompressor:1.3.3' ``` If you're facing problems with the setup, edit settings.gradle by adding this at the beginning of the file: ``` dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url 'https://jitpack.io' } } } ``` ## Getting help For questions, suggestions, or anything else, email elaziz.shehadeh(at)gmail.com ## Credits [Telegram](https://github.com/DrKLO/Telegram) for Android. ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' android { compileSdkVersion 33 defaultConfig { applicationId "com.abedelazizshe.lightcompressor" minSdkVersion 21 targetSdkVersion 33 versionCode 1 versionName "1.0.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8 } buildFeatures { viewBinding true } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':lightcompressor') implementation "org.jetbrains.kotlin:kotlin-stdlib:1.8.21" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4" implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'androidx.core:core-ktx:1.10.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation "com.google.android.material:material:1.9.0" implementation "com.github.bumptech.glide:glide:4.12.0" kapt 'com.github.bumptech.glide:compiler:4.12.0' implementation 'com.google.android.exoplayer:exoplayer:2.16.1' implementation 'androidx.recyclerview:recyclerview:1.3.0' implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.1' testImplementation "junit:junit:4.13.2" androidTestImplementation "androidx.test.ext:junit:1.1.5" androidTestImplementation "androidx.test.espresso:espresso-core:3.5.1" } ================================================ FILE: app/src/androidTest/java/com/abedelazizshe/lightcompressor/ExampleInstrumentedTest.kt ================================================ package com.abedelazizshe.lightcompressor import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.abedelazizshe.lightcompressor", appContext.packageName) } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/abedelazizshe/lightcompressor/MainActivity.kt ================================================ package com.abedelazizshe.lightcompressor import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.content.ClipData import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.abedelazizshe.lightcompressor.databinding.ActivityMainBinding import com.abedelazizshe.lightcompressorlibrary.CompressionListener import com.abedelazizshe.lightcompressorlibrary.VideoCompressor import com.abedelazizshe.lightcompressorlibrary.VideoQuality import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer import com.abedelazizshe.lightcompressorlibrary.config.SaveLocation import com.abedelazizshe.lightcompressorlibrary.config.SharedStorageConfiguration import kotlinx.coroutines.launch /** * Created by AbedElaziz Shehadeh on 26 Jan, 2020 * elaziz.shehadeh@gmail.com */ class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding companion object { const val REQUEST_SELECT_VIDEO = 0 const val REQUEST_CAPTURE_VIDEO = 1 } private val uris = mutableListOf() private val data = mutableListOf() private lateinit var adapter: RecyclerViewAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setReadStoragePermission() binding.pickVideo.setOnClickListener { pickVideo() } binding.recordVideo.setOnClickListener { dispatchTakeVideoIntent() } binding.cancel.setOnClickListener { VideoCompressor.cancel() } val recyclerview = findViewById(R.id.recyclerview) recyclerview.layoutManager = LinearLayoutManager(this) adapter = RecyclerViewAdapter(applicationContext, data) recyclerview.adapter = adapter } //Pick a video file from device private fun pickVideo() { val intent = Intent() intent.apply { type = "video/*" action = Intent.ACTION_PICK } intent.putExtra( Intent.EXTRA_ALLOW_MULTIPLE, true ) startActivityForResult(Intent.createChooser(intent, "Select video"), REQUEST_SELECT_VIDEO) } private fun dispatchTakeVideoIntent() { Intent(MediaStore.ACTION_VIDEO_CAPTURE).also { takeVideoIntent -> takeVideoIntent.resolveActivity(packageManager)?.also { startActivityForResult(takeVideoIntent, REQUEST_CAPTURE_VIDEO) } } } @SuppressLint("SetTextI18n") override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { reset() if (resultCode == Activity.RESULT_OK) if (requestCode == REQUEST_SELECT_VIDEO || requestCode == REQUEST_CAPTURE_VIDEO) { handleResult(intent) } super.onActivityResult(requestCode, resultCode, intent) } private fun handleResult(data: Intent?) { val clipData: ClipData? = data?.clipData if (clipData != null) { for (i in 0 until clipData.itemCount) { val videoItem = clipData.getItemAt(i) uris.add(videoItem.uri) } processVideo() } else if (data != null && data.data != null) { val uri = data.data uris.add(uri!!) processVideo() } } private fun reset() { uris.clear() binding.mainContents.visibility = View.GONE data.clear() adapter.notifyDataSetChanged() } private fun setReadStoragePermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission( this, Manifest.permission.READ_MEDIA_VIDEO, ) != PackageManager.PERMISSION_GRANTED ) { if (!ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.READ_MEDIA_VIDEO ) ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.READ_MEDIA_VIDEO), 1 ) } } } else { if (ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE, ) != PackageManager.PERMISSION_GRANTED ) { if (!ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1 ) } } } } @SuppressLint("SetTextI18n") private fun processVideo() { binding.mainContents.visibility = View.VISIBLE lifecycleScope.launch { VideoCompressor.start( context = applicationContext, uris, isStreamable = false, storageConfiguration = SharedStorageConfiguration( saveAt = SaveLocation.movies, subFolderName = "my-demo-videos" ), configureWith = Configuration( quality = VideoQuality.LOW, videoNames = uris.map { uri -> uri.pathSegments.last() }, isMinBitrateCheckEnabled = false, resizer = VideoResizer.limitSize(1280.0) ), listener = object : CompressionListener { override fun onProgress(index: Int, percent: Float) { //Update UI if (percent <= 100) runOnUiThread { data[index] = VideoDetailsModel( "", uris[index], "", percent ) adapter.notifyDataSetChanged() } } override fun onStart(index: Int) { data.add( index, VideoDetailsModel("", uris[index], "") ) runOnUiThread { adapter.notifyDataSetChanged() } } override fun onSuccess(index: Int, size: Long, path: String?) { data[index] = VideoDetailsModel( path, uris[index], getFileSize(size), 100F ) runOnUiThread { adapter.notifyDataSetChanged() } } override fun onFailure(index: Int, failureMessage: String) { Log.wtf("failureMessage", failureMessage) } override fun onCancelled(index: Int) { Log.wtf("TAG", "compression has been cancelled") // make UI changes, cleanup, etc } }, ) } } } ================================================ FILE: app/src/main/java/com/abedelazizshe/lightcompressor/RecyclerViewAdapter.kt ================================================ package com.abedelazizshe.lightcompressor import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide class RecyclerViewAdapter(private val context: Context, private val list: List) : RecyclerView.Adapter() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.recycler_view_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val itemsViewModel = list[position] val newSize = "Size after compression: ${itemsViewModel.newSize}" val progress = "${itemsViewModel.progress.toLong()}%" if (itemsViewModel.progress > 0 && itemsViewModel.progress < 100) { holder.progress.visibility = View.VISIBLE holder.progress.text = progress holder.progressBar.visibility = View.VISIBLE holder.progressBar.progress = itemsViewModel.progress.toInt() } else { holder.progress.visibility = View.GONE holder.progressBar.visibility = View.GONE } if (itemsViewModel.newSize.isNotBlank()) { holder.newSize.text = newSize holder.newSize.visibility = View.VISIBLE } else { holder.newSize.visibility = View.GONE } Glide.with(context).load(itemsViewModel.uri).into(holder.videoImage) holder.itemView.setOnClickListener { VideoPlayerActivity.start( it.context, itemsViewModel.playableVideoPath ) } } override fun getItemCount(): Int { return list.size } class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) { val videoImage: ImageView = itemView.findViewById(R.id.videoImage) val newSize: TextView = itemView.findViewById(R.id.newSize) val progress: TextView = itemView.findViewById(R.id.progress) val progressBar: ProgressBar = itemView.findViewById(R.id.progressBar) } } ================================================ FILE: app/src/main/java/com/abedelazizshe/lightcompressor/Utils.kt ================================================ package com.abedelazizshe.lightcompressor import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.MediaStore import java.io.* import java.text.DecimalFormat import kotlin.math.log10 import kotlin.math.pow fun getMediaPath(context: Context, uri: Uri): String { val resolver = context.contentResolver val projection = arrayOf(MediaStore.Video.Media.DATA) var cursor: Cursor? = null try { cursor = resolver.query(uri, projection, null, null, null) return if (cursor != null) { val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA) cursor.moveToFirst() cursor.getString(columnIndex) } else "" } catch (e: Exception) { resolver.let { val filePath = (context.applicationInfo.dataDir + File.separator + System.currentTimeMillis()) val file = File(filePath) resolver.openInputStream(uri)?.use { inputStream -> FileOutputStream(file).use { outputStream -> val buf = ByteArray(4096) var len: Int while (inputStream.read(buf).also { len = it } > 0) outputStream.write( buf, 0, len ) } } return file.absolutePath } } finally { cursor?.close() } } fun getFileSize(size: Long): String { if (size <= 0) return "0" val units = arrayOf("B", "KB", "MB", "GB", "TB") val digitGroups = (log10(size.toDouble()) / log10(1024.0)).toInt() return DecimalFormat("#,##0.#").format( size / 1024.0.pow(digitGroups.toDouble()) ) + " " + units[digitGroups] } //The following methods can be alternative to [getMediaPath]. // todo(abed): remove [getPathFromUri], [getVideoExtension], and [copy] fun getPathFromUri(context: Context, uri: Uri): String { var file: File? = null var inputStream: InputStream? = null var outputStream: OutputStream? = null var success = false try { val extension: String = getVideoExtension(uri) inputStream = context.contentResolver.openInputStream(uri) file = File.createTempFile("compressor", extension, context.cacheDir) file.deleteOnExit() outputStream = FileOutputStream(file) if (inputStream != null) { copy(inputStream, outputStream) success = true } } catch (ignored: IOException) { } finally { try { inputStream?.close() } catch (ignored: IOException) { } try { outputStream?.close() } catch (ignored: IOException) { // If closing the output stream fails, we cannot be sure that the // target file was written in full. Flushing the stream merely moves // the bytes into the OS, not necessarily to the file. success = false } } return if (success) file!!.path else "" } /** @return extension of video with dot, or default .mp4 if it none. */ private fun getVideoExtension(uriVideo: Uri): String { var extension: String? = null try { val imagePath = uriVideo.path if (imagePath != null && imagePath.lastIndexOf(".") != -1) { extension = imagePath.substring(imagePath.lastIndexOf(".") + 1) } } catch (e: Exception) { extension = null } if (extension == null || extension.isEmpty()) { //default extension for matches the previous behavior of the plugin extension = "mp4" } return ".$extension" } private fun copy(`in`: InputStream, out: OutputStream) { val buffer = ByteArray(4 * 1024) var bytesRead: Int while (`in`.read(buffer).also { bytesRead = it } != -1) { out.write(buffer, 0, bytesRead) } out.flush() } ================================================ FILE: app/src/main/java/com/abedelazizshe/lightcompressor/VideoDetailsModel.kt ================================================ package com.abedelazizshe.lightcompressor import android.net.Uri data class VideoDetailsModel( val playableVideoPath: String?, val uri: Uri, val newSize: String, val progress: Float = 0F ) ================================================ FILE: app/src/main/java/com/abedelazizshe/lightcompressor/VideoPlayerActivity.kt ================================================ package com.abedelazizshe.lightcompressor import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.abedelazizshe.lightcompressor.databinding.ActivityVideoPlayerBinding import com.google.android.exoplayer2.DefaultLoadControl import com.google.android.exoplayer2.DefaultRenderersFactory import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import java.io.File /** * Created by AbedElaziz Shehadeh on 26 Jan, 2020 * elaziz.shehadeh@gmail.com */ class VideoPlayerActivity : AppCompatActivity() { private lateinit var binding: ActivityVideoPlayerBinding private lateinit var exoPlayer: SimpleExoPlayer private var uri = "" companion object { fun start(context: Context, uri: String?) { val intent = Intent(context, VideoPlayerActivity::class.java) .putExtra("uri", uri) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityVideoPlayerBinding.inflate(layoutInflater) setContentView(binding.root) intent?.extras?.let { uri = it.getString("uri", "") } initializePlayer() } private fun initializePlayer() { val trackSelector = DefaultTrackSelector(this) val loadControl = DefaultLoadControl() val rendererFactory = DefaultRenderersFactory(this) exoPlayer = SimpleExoPlayer.Builder(this, rendererFactory) .setLoadControl(loadControl) .setTrackSelector(trackSelector) .build() } private fun play(uri: Uri) { val userAgent = Util.getUserAgent(this, getString(R.string.app_name)) val mediaSource = ProgressiveMediaSource .Factory(DefaultDataSourceFactory(this, userAgent)) .createMediaSource(uri) binding.epVideoView.player = exoPlayer exoPlayer.prepare(mediaSource) exoPlayer.playWhenReady = true } override fun onStart() { super.onStart() playVideo() } private fun playVideo() { val file = File(uri) val localUri = Uri.fromFile(file) play(localUri) } override fun onStop() { super.onStop() exoPlayer.stop() exoPlayer.release() } } ================================================ FILE: app/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_play_white_24dp.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_video_library_white_24dp.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================