### CompressionListener Interface Implementation Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt This example demonstrates how to implement the CompressionListener interface to receive and handle compression lifecycle events. ```APIDOC ## CompressionListener Interface Callback interface for receiving compression lifecycle events. Implement all five methods to handle compression start, progress updates, success, failure, and cancellation. ### Methods - **onStart(index: Int)**: Called on the main thread when compression starts for a video. - **onProgress(index: Int, percent: Float)**: Called on a worker thread with progress updates (0-100). UI updates must be performed on the main thread. - **onSuccess(index: Int, size: Long, path: String?)**: Called on the main thread when compression succeeds. Provides the output size and path. - **onFailure(index: Int, failureMessage: String)**: Called on the main thread when compression fails. Includes a message describing the failure. - **onCancelled(index: Int)**: Called on a worker thread when compression is cancelled. ### Request Example ```kotlin import com.abedelazizshe.lightcompressorlibrary.CompressionListener class MyCompressionListener : CompressionListener { // Called on main thread when compression starts for a video override fun onStart(index: Int) { println("Starting compression for video at index: $index") } // Called on worker thread with progress updates (0-100) override fun onProgress(index: Int, percent: Float) { // Must switch to main thread for UI updates runOnUiThread { updateProgressBar(index, percent) } } // Called on main thread when compression succeeds override fun onSuccess(index: Int, size: Long, path: String?) { println("Video $index compressed successfully") println("Output size: ${size / 1024} KB") println("Output path: $path") } // Called on main thread when compression fails override fun onFailure(index: Int, failureMessage: String) { println("Failed to compress video $index: $failureMessage") // Common failures: // - "The provided bitrate is smaller than what is needed for compression" // - "Failed to extract video meta-data" } // Called on worker thread when compression is cancelled override fun onCancelled(index: Int) { println("Compression cancelled for video $index") } } ``` ### Response This interface does not have direct request/response bodies as it's a callback mechanism. The methods receive parameters indicating the status and results of the compression process. ``` -------------------------------- ### LightCompressor Installation Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Instructions for adding the LightCompressor library and its dependencies to your Android project. ```APIDOC ## Installation Add JitPack repository and library dependency to your Android project. ```groovy // Project-level build.gradle or settings.gradle dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url 'https://jitpack.io' } } } // Module-level build.gradle dependencies { implementation 'com.github.AbedElazizShe:LightCompressor:1.3.3' implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4" } ``` ``` -------------------------------- ### Start Video Compression Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Use the VideoCompressor.start method to initiate asynchronous video compression. This snippet demonstrates how to configure compression settings and handle lifecycle events via the CompressionListener. ```kotlin 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.SharedStorageConfiguration import com.abedelazizshe.lightcompressorlibrary.config.SaveLocation val videoUris: List = listOf(selectedVideoUri1, selectedVideoUri2) VideoCompressor.start( context = applicationContext, uris = videoUris, isStreamable = true, storageConfiguration = SharedStorageConfiguration( saveAt = SaveLocation.movies, subFolderName = "compressed-videos" ), configureWith = Configuration( quality = VideoQuality.MEDIUM, videoNames = listOf("video1", "video2"), isMinBitrateCheckEnabled = true, videoBitrateInMbps = null, disableAudio = false ), listener = object : CompressionListener { override fun onStart(index: Int) { Log.d("Compression", "Started compressing video $index") } override fun onProgress(index: Int, percent: Float) { runOnUiThread { progressBar.progress = percent.toInt() } } override fun onSuccess(index: Int, size: Long, path: String?) { Log.d("Compression", "Video $index compressed to $path") } override fun onFailure(index: Int, failureMessage: String) { Log.e("Compression", "Failed: $failureMessage") } override fun onCancelled(index: Int) { Log.d("Compression", "Cancelled $index") } } ) ``` -------------------------------- ### Implement CompressionListener in Kotlin Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt This Kotlin code demonstrates how to implement the CompressionListener interface to handle various stages of the video compression process. It includes methods for tracking compression start, progress updates (requiring UI thread updates), successful completion, failure reasons, and cancellation. Dependencies include the `com.abedelazizshe.lightcompressorlibrary.CompressionListener` class. ```kotlin import com.abedelazizshe.lightcompressorlibrary.CompressionListener class MyCompressionListener : CompressionListener { // Called on main thread when compression starts for a video override fun onStart(index: Int) { println("Starting compression for video at index: $index") } // Called on worker thread with progress updates (0-100) override fun onProgress(index: Int, percent: Float) { // Must switch to main thread for UI updates runOnUiThread { updateProgressBar(index, percent) } } // Called on main thread when compression succeeds override fun onSuccess(index: Int, size: Long, path: String?) { println("Video $index compressed successfully") println("Output size: ${size / 1024} KB") println("Output path: $path") } // Called on main thread when compression fails override fun onFailure(index: Int, failureMessage: String) { println("Failed to compress video $index: $failureMessage") // Common failures: // - "The provided bitrate is smaller than what is needed for compression" // - "Failed to extract video meta-data" } // Called on worker thread when compression is cancelled override fun onCancelled(index: Int) { println("Compression cancelled for video $index") } } ``` -------------------------------- ### Video Compression with LightCompressor in Kotlin Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Shows the primary method for starting video compression using the LightCompressor library. It includes configurations for context, URIs, storage, compression settings, and a listener for progress and status updates. ```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 } } ) ``` -------------------------------- ### Gradle Dependency Setup for LightCompressor Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Instructions for adding the LightCompressor library to an Android project using Gradle. It includes configurations for both project-level and module-level build.gradle files, as well as settings.gradle. ```groovy allprojects { repositories { . . . maven { url 'https://jitpack.io' } } } ``` ```groovy implementation 'com.github.AbedElazizShe:LightCompressor:1.3.3' ``` ```groovy dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url 'https://jitpack.io' } } } ``` -------------------------------- ### GET /VideoCompressor/cancel Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Cancels an ongoing compression job. ```APIDOC ## GET /VideoCompressor/cancel ### Description Cancels the currently running compression job. ### Method GET ### Endpoint VideoCompressor.cancel() ### Response #### Success Response (200) - **onCancelled** (Callback) - Triggers the onCancelled method in the CompressionListener. ``` -------------------------------- ### VideoCompressor.start() Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Initiates the video compression process for a list of video URIs with specified configuration and storage settings. ```APIDOC ## POST VideoCompressor.start() ### Description Starts the asynchronous compression process for one or more video files. The library processes videos based on provided configuration and returns status via callback functions. ### Method POST (Internal Library Method) ### Parameters #### Request Body - **context** (Context) - Required - Android application context. - **uris** (List) - Required - List of content URIs for the videos to be compressed. - **isStreamable** (Boolean) - Required - Flag to optimize output video for streaming. - **configureWith** (Configuration) - Required - Object containing bitrate and resolution settings. - **sharedStorageConfiguration OR appSpecificStorageConfiguration** (StorageConfig) - Required - Defines where the output file should be saved. ### Response #### Success Response (OnSuccess) - **index** (Int) - Index of the processed video. - **path** (String) - File path of the compressed video. #### Callback Events - **OnStart** - Triggered when compression begins. - **OnProgress** - Triggered with current progress percentage. - **OnFailure** - Triggered when an error occurs or video is below minimum bitrate. - **OnCancelled** - Triggered when the compression job is cancelled. ``` -------------------------------- ### POST /VideoCompressor/start Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Initiates the video compression process with specific configuration and storage settings. ```APIDOC ## POST /VideoCompressor/start ### Description Starts the video compression job for a list of provided URIs using the specified configuration and storage strategy. ### Method POST ### Endpoint VideoCompressor.start() ### Parameters #### Request Body - **context** (Context) - Required - Application context. - **uris** (List) - Required - List of source video URIs. - **isStreamable** (Boolean) - Optional - Whether the output should be streamable. - **storageConfiguration** (StorageConfiguration) - Required - Defines where the output file is saved (AppSpecific, Shared, or Custom). - **configureWith** (Configuration) - Required - Compression settings including quality, bitrate, and resizing. - **listener** (CompressionListener) - Required - Callback interface for progress, success, failure, and cancellation events. ### Request Example { "uris": ["content://media/external/video/1"], "quality": "MEDIUM", "isMinBitrateCheckEnabled": true, "videoBitrateInMbps": 5, "disableAudio": false } ### Response #### Success Response (200) - **size** (Long) - The final size of the compressed video. - **path** (String) - The file path of the compressed video. #### Response Example { "status": "success", "path": "/storage/emulated/0/Movies/my-videos/video.mp4", "size": 10485760 } ``` -------------------------------- ### Custom Storage Configuration in Kotlin Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Demonstrates how to create a custom storage configuration by implementing the StorageConfiguration interface. This allows for custom file saving logic within the library. ```kotlin class FullyCustomizedStorageConfiguration( ) : StorageConfiguration { override fun createFileToSave( context: Context, videoFile: File, fileName: String, shouldSave: Boolean ): File = ??? What you need } ``` -------------------------------- ### Implement Custom Storage Configuration Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Allows developers to define custom storage logic by implementing the StorageConfiguration interface. This provides full control over the file creation process. ```kotlin import android.content.Context import com.abedelazizshe.lightcompressorlibrary.config.StorageConfiguration import java.io.File class CustomStorageConfiguration(private val customPath: String) : StorageConfiguration { override fun createFileToSave(context: Context, videoFile: File, fileName: String, shouldSave: Boolean): File { val outputDir = File(customPath) if (!outputDir.exists()) { outputDir.mkdirs() } return File(outputDir, fileName) } } val customStorage = CustomStorageConfiguration("/storage/emulated/0/MyCustomFolder") VideoCompressor.start( context = applicationContext, uris = listOf(videoUri), isStreamable = false, storageConfiguration = customStorage, configureWith = Configuration(videoNames = listOf("custom-video")), listener = compressionListener ) ``` -------------------------------- ### Custom StorageConfiguration Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Interface for implementing custom storage logic for video output. ```APIDOC ## Custom StorageConfiguration ### Description Implement the StorageConfiguration interface to define custom file creation logic for compressed video output. ### Methods - **createFileToSave(context, videoFile, fileName, shouldSave)** - Returns a File object representing the destination path. ### Request Example class CustomStorageConfiguration(private val customPath: String) : StorageConfiguration { ... } ``` -------------------------------- ### POST /video/compress Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Initiates the video compression process for one or more video URIs with specific configuration settings. ```APIDOC ## POST /video/compress ### Description Starts the asynchronous video compression process. This method handles multiple videos and provides a listener for lifecycle events. ### Method POST ### Parameters #### Request Body - **context** (Context) - Required - The application context. - **uris** (List) - Required - List of video URIs to be compressed. - **isStreamable** (Boolean) - Optional - Whether the output video should be optimized for streaming. - **storageConfiguration** (SharedStorageConfiguration) - Required - Defines the save location and subfolder. - **configureWith** (Configuration) - Required - Compression settings including quality, bitrate, and resolution. - **listener** (CompressionListener) - Required - Callback interface for progress, success, and failure events. ### Request Example { "uris": ["content://media/external/video/1"], "quality": "MEDIUM", "saveLocation": "movies", "resizer": "limitSize(1080.0)" } ### Response #### Success Response (200) - **onSuccess** (Callback) - Triggered when compression finishes, providing the file path and size. #### Response Example { "status": "success", "path": "/storage/emulated/0/Movies/CompressedVideos/video_0.mp4", "size": 102400 } ``` -------------------------------- ### Configuration Data Class for Video Compression Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt The `Configuration` data class allows for detailed control over video compression parameters. Options include quality presets, bitrate settings, audio track handling, and resolution resizing. Minimal configuration requires only specifying video names. ```kotlin import com.abedelazizshe.lightcompressorlibrary.VideoQuality import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer // Full configuration with all options val configuration = Configuration( quality = VideoQuality.MEDIUM, // Preset quality level isMinBitrateCheckEnabled = false, // Skip 2Mbps minimum check videoBitrateInMbps = 3, // Custom bitrate: 3 Mbps disableAudio = false, // Keep audio track resizer = VideoResizer.limitSize(720.0), // Max 720p resolution videoNames = listOf("output-video") // Output filename (without extension) ) // Minimal configuration using defaults val simpleConfig = Configuration( videoNames = listOf("compressed-video") // Defaults: MEDIUM quality, min bitrate check enabled, auto bitrate, // audio enabled, auto resize ) ``` -------------------------------- ### CacheStorageConfiguration Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configures saving compressed videos to the temporary app cache directory. ```APIDOC ## CacheStorageConfiguration ### Description Saves files to the app's cache directory. These files are subject to system cleanup when storage space is low. ### Request Example val cacheStorage = CacheStorageConfiguration() ``` -------------------------------- ### Configure Shared Device Storage Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configures the library to save compressed videos to public directories like Movies, Pictures, or Downloads. This allows other applications to access the output files. ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.SharedStorageConfiguration import com.abedelazizshe.lightcompressorlibrary.config.SaveLocation val moviesStorage = SharedStorageConfiguration( saveAt = SaveLocation.movies, subFolderName = "MyApp" ) VideoCompressor.start( context = applicationContext, uris = listOf(videoUri), isStreamable = false, storageConfiguration = moviesStorage, configureWith = Configuration(videoNames = listOf("my-video")), listener = compressionListener ) ``` -------------------------------- ### Runtime Permission Request Logic in Kotlin Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md Demonstrates how to check and request runtime permissions for video access based on the Android API level using Kotlin. It differentiates between requesting READ_MEDIA_VIDEO for newer APIs and WRITE_EXTERNAL_STORAGE for older ones. ```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 } ``` -------------------------------- ### AppSpecificStorageConfiguration Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configures saving compressed videos to private app-specific internal storage. ```APIDOC ## AppSpecificStorageConfiguration ### Description Saves files to the app's private internal storage directory. Files are deleted automatically upon app uninstallation. ### Parameters - **subFolderName** (String?) - Optional - A subfolder name within the app's files directory. ### Request Example val appStorage = AppSpecificStorageConfiguration(subFolderName = "compressed") ``` -------------------------------- ### Configuration Data Class Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Provides comprehensive options for configuring video compression. This includes setting quality, bitrate, audio handling, and resolution resizing. ```APIDOC ## Configuration Data Class ### Description Comprehensive configuration options for controlling video compression parameters including quality, bitrate, audio handling, and resolution resizing. ### Parameters - **quality** (VideoQuality) - Optional - Preset quality level. Defaults to `VideoQuality.MEDIUM`. - **isMinBitrateCheckEnabled** (Boolean) - Optional - Whether to enable the minimum bitrate check. Defaults to `true`. - **videoBitrateInMbps** (Int) - Optional - Custom bitrate in Mbps. If not set, the bitrate is determined by the `quality` setting. - **disableAudio** (Boolean) - Optional - Whether to disable the audio track. Defaults to `false` (audio is kept). - **resizer** (VideoResizer?) - Optional - Configuration for video resizing. If `null`, the original resolution is kept. - **videoNames** (List) - Required - List of output video filenames (without extension). ### Request Example (Full Configuration): ```kotlin import com.abedelazizshe.lightcompressorlibrary.VideoQuality import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val configuration = Configuration( quality = VideoQuality.MEDIUM, // Preset quality level isMinBitrateCheckEnabled = false, // Skip 2Mbps minimum check videoBitrateInMbps = 3, // Custom bitrate: 3 Mbps disableAudio = false, // Keep audio track resizer = VideoResizer.limitSize(720.0), // Max 720p resolution videoNames = listOf("output-video") // Output filename (without extension) ) ``` ### Request Example (Minimal Configuration): ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration val simpleConfig = Configuration( videoNames = listOf("compressed-video") // Defaults: MEDIUM quality, min bitrate check enabled, auto bitrate, // audio enabled, auto resize ) ``` ``` -------------------------------- ### Android Video Compression Activity Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt This Kotlin code implements an Android Activity that allows users to select multiple videos, requests necessary storage permissions, and then compresses the selected videos using the LightCompressor library. It configures compression settings like quality, resolution, and save location, and provides feedback on the compression progress and success/failure. ```kotlin import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat 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.SaveLocation import com.abedelazizshe.lightcompressorlibrary.config.SharedStorageConfiguration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer class VideoCompressionActivity : AppCompatActivity() { private val REQUEST_SELECT_VIDEO = 100 private val selectedUris = mutableListOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestStoragePermission() } private fun requestStoragePermission() { val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.READ_MEDIA_VIDEO } else { Manifest.permission.WRITE_EXTERNAL_STORAGE } if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(permission), 1) } } fun selectVideos() { val intent = Intent(Intent.ACTION_PICK).apply { type = "video/*" putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) } startActivityForResult(Intent.createChooser(intent, "Select Videos"), REQUEST_SELECT_VIDEO) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_SELECT_VIDEO && resultCode == Activity.RESULT_OK) { selectedUris.clear() data?.clipData?.let { clipData -> for (i in 0 until clipData.itemCount) { selectedUris.add(clipData.getItemAt(i).uri) } } ?: data?.data?.let { uri -> selectedUris.add(uri) } if (selectedUris.isNotEmpty()) { compressVideos() } } } private fun compressVideos() { VideoCompressor.start( context = applicationContext, uris = selectedUris, isStreamable = true, storageConfiguration = SharedStorageConfiguration( saveAt = SaveLocation.movies, subFolderName = "CompressedVideos" ), configureWith = Configuration( quality = VideoQuality.MEDIUM, videoNames = selectedUris.mapIndexed { index, _ -> "video_$index" }, isMinBitrateCheckEnabled = false, disableAudio = false, resizer = VideoResizer.limitSize(1080.0) ), listener = object : CompressionListener { override fun onStart(index: Int) { Log.d("Compression", "Started: video $index") } override fun onProgress(index: Int, percent: Float) { runOnUiThread { Log.d("Compression", "Progress: video $index - ${percent.toInt()}%") } } override fun onSuccess(index: Int, size: Long, path: String?) { Log.d("Compression", "Success: video $index saved to $path (${size/1024}KB)") } override fun onFailure(index: Int, failureMessage: String) { Log.e("Compression", "Failed: video $index - $failureMessage") } override fun onCancelled(index: Int) { Log.d("Compression", "Cancelled: video $index") } } ) } fun cancelCompression() { VideoCompressor.cancel() } } ``` -------------------------------- ### Configure LightCompressor Dependencies Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Add the JitPack repository and the library dependency to your Gradle build files to integrate LightCompressor into your Android project. ```groovy dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.AbedElazizShe:LightCompressor:1.3.3' implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4" } ``` -------------------------------- ### SharedStorageConfiguration Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configures saving compressed videos to shared device directories like Movies, Pictures, or Downloads. ```APIDOC ## SharedStorageConfiguration ### Description Configures the library to save compressed videos to public shared storage locations accessible by other applications. ### Parameters - **saveAt** (SaveLocation) - Required - The target directory (movies, pictures, or downloads). - **subFolderName** (String?) - Optional - A subfolder name within the target directory for organization. ### Request Example val moviesStorage = SharedStorageConfiguration(saveAt = SaveLocation.movies, subFolderName = "MyApp") ``` -------------------------------- ### Configure Temporary Cache Storage Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configures the library to save output to the app's cache directory. This is suitable for temporary files that the system may clear when storage is low. ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.CacheStorageConfiguration val cacheStorage = CacheStorageConfiguration() VideoCompressor.start( context = applicationContext, uris = listOf(videoUri), isStreamable = false, storageConfiguration = cacheStorage, configureWith = Configuration(videoNames = listOf("temp-video")), listener = compressionListener ) ``` -------------------------------- ### VideoResizer Strategies for Dimension Control Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt The `VideoResizer` provides various strategies for adjusting video dimensions during compression. These include automatic resizing based on original dimensions, scaling by a percentage, limiting maximum dimensions, matching target sizes, and disabling resizing altogether. ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer import com.abedelazizshe.lightcompressorlibrary.config.Configuration // Auto resize (default) - shrinks based on original dimensions: // - 50% if width/height >= 1920px // - 75% if width/height >= 1280px // - 95% if width/height >= 960px // - 90% if both dimensions < 960px val autoResize = Configuration( resizer = VideoResizer.auto, videoNames = listOf("video") ) // Scale by percentage (e.g., 50% of original dimensions) val scaleResize = Configuration( resizer = VideoResizer.scale(0.5), videoNames = listOf("video") ) // Limit maximum dimension while keeping aspect ratio val limitResize = Configuration( resizer = VideoResizer.limitSize(1280.0), // Max 1280px on any side videoNames = listOf("video") ) // Limit both dimensions independently val limitBothResize = Configuration( resizer = VideoResizer.limitSize(maxWidth = 1920.0, maxHeight = 1080.0), videoNames = listOf("video") ) // Match target size (scale to fit within bounds, keep aspect ratio) val matchResize = Configuration( resizer = VideoResizer.matchSize(width = 640.0, height = 480.0), videoNames = listOf("video") ) // Match target size with stretching (ignore aspect ratio) val stretchResize = Configuration( resizer = VideoResizer.matchSize(width = 640.0, height = 480.0, stretch = true), videoNames = listOf("video") ) // Keep original resolution (no resizing) val noResize = Configuration( resizer = null, videoNames = listOf("video") ) ``` -------------------------------- ### Kotlin Coroutines Dependencies for LightCompressor Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md This snippet provides the Groovy syntax for adding the necessary Kotlin coroutines core and Android extensions dependencies to an Android project, which are required for using LightCompressor's asynchronous operations. ```groovy implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Version.coroutines}" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Version.coroutines}" ``` -------------------------------- ### Android Manifest Permissions Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Required storage permissions for LightCompressor based on the Android API level. ```APIDOC ## Android Manifest Permissions Required storage permissions must be declared in AndroidManifest.xml based on the target API level. ```xml ``` ``` -------------------------------- ### VideoQuality Enum for Compression Settings Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt The `VideoQuality` enum provides preset levels to control the output video's bitrate as a percentage of the original. Higher quality settings result in larger files but better visual fidelity. The default quality is MEDIUM. ```kotlin import com.abedelazizshe.lightcompressorlibrary.VideoQuality // Available quality presets and their bitrate multipliers: // VERY_HIGH: original bitrate * 0.6 (60% of original) // HIGH: original bitrate * 0.4 (40% of original) // MEDIUM: original bitrate * 0.3 (30% of original) - Default // LOW: original bitrate * 0.2 (20% of original) // VERY_LOW: original bitrate * 0.1 (10% of original) val config = Configuration( quality = VideoQuality.HIGH, // Use high quality compression videoNames = listOf("my-video") ) ``` -------------------------------- ### Android Storage Permissions for LightCompressor Source: https://github.com/abedelazizshe/lightcompressor/blob/master/README.md This snippet shows the necessary XML declarations for granting read and write external storage permissions required by LightCompressor, with specific configurations for different Android API levels. ```xml ``` -------------------------------- ### Configure App-Specific Internal Storage Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configures the library to save files in the app's private internal storage directory. Files are inaccessible to other apps and are removed upon uninstallation. ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.AppSpecificStorageConfiguration val appStorage = AppSpecificStorageConfiguration( subFolderName = "compressed" ) VideoCompressor.start( context = applicationContext, uris = listOf(videoUri), isStreamable = false, storageConfiguration = appStorage, configureWith = Configuration(videoNames = listOf("private-video")), listener = compressionListener ) ``` -------------------------------- ### DELETE /video/compress/cancel Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Cancels any currently running compression tasks. ```APIDOC ## DELETE /video/compress/cancel ### Description Immediately stops all active compression operations initiated by the VideoCompressor. ### Method DELETE ### Endpoint VideoCompressor.cancel() ### Response #### Success Response (200) - **onCancelled** (Callback) - Triggered in the listener when the operation is successfully aborted. ``` -------------------------------- ### Declare Storage Permissions in AndroidManifest Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Configure the necessary storage permissions in your AndroidManifest.xml file to ensure the library can access video files across different Android API levels. ```xml ``` -------------------------------- ### VideoResizer Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Defines strategies for resizing video dimensions during compression. Supports various methods like automatic resizing, scaling, limiting dimensions, and matching target sizes. ```APIDOC ## VideoResizer ### Description Functional interface providing multiple strategies for resizing video dimensions during compression. Supports automatic resizing, scaling, limiting dimensions, and matching target sizes while optionally preserving aspect ratio. ### Resizing Strategies: #### `VideoResizer.auto` - **Description**: Automatically resizes based on original dimensions: - 50% if width/height >= 1920px - 75% if width/height >= 1280px - 95% if width/height >= 960px - 90% if both dimensions < 960px - **Usage**: `VideoResizer.auto` #### `VideoResizer.scale(percentage)` - **Description**: Scales video dimensions by a given percentage. - **Parameters**: - **percentage** (Double) - The scaling factor (e.g., 0.5 for 50%). - **Usage**: `VideoResizer.scale(0.5)` #### `VideoResizer.limitSize(maxDimension)` - **Description**: Limits the maximum dimension (width or height) while preserving the aspect ratio. - **Parameters**: - **maxDimension** (Double) - The maximum allowed value for the larger dimension. - **Usage**: `VideoResizer.limitSize(1280.0)` #### `VideoResizer.limitSize(maxWidth, maxHeight)` - **Description**: Limits both the maximum width and maximum height independently, preserving the aspect ratio. - **Parameters**: - **maxWidth** (Double) - The maximum allowed width. - **maxHeight** (Double) - The maximum allowed height. - **Usage**: `VideoResizer.limitSize(maxWidth = 1920.0, maxHeight = 1080.0)` #### `VideoResizer.matchSize(width, height, stretch)` - **Description**: Scales the video to fit within the specified target dimensions, preserving aspect ratio by default. If `stretch` is true, the aspect ratio is ignored. - **Parameters**: - **width** (Double) - The target width. - **height** (Double) - The target height. - **stretch** (Boolean) - Optional. If true, stretches the video to fit the dimensions, ignoring aspect ratio. Defaults to `false`. - **Usage**: - `VideoResizer.matchSize(width = 640.0, height = 480.0)` (preserves aspect ratio) - `VideoResizer.matchSize(width = 640.0, height = 480.0, stretch = true)` (stretches) #### `null` (No Resizing) - **Description**: Keeps the original video resolution. - **Usage**: `resizer = null` ### Usage Examples: **Auto Resize:** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val autoResizeConfig = Configuration( resizer = VideoResizer.auto, videoNames = listOf("video") ) ``` **Scale by Percentage:** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val scaleResizeConfig = Configuration( resizer = VideoResizer.scale(0.5), videoNames = listOf("video") ) ``` **Limit Maximum Dimension:** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val limitResizeConfig = Configuration( resizer = VideoResizer.limitSize(1280.0), // Max 1280px on any side videoNames = listOf("video") ) ``` **Limit Both Dimensions:** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val limitBothResizeConfig = Configuration( resizer = VideoResizer.limitSize(maxWidth = 1920.0, maxHeight = 1080.0), videoNames = listOf("video") ) ``` **Match Target Size (Preserve Aspect Ratio):** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val matchResizeConfig = Configuration( resizer = VideoResizer.matchSize(width = 640.0, height = 480.0), videoNames = listOf("video") ) ``` **Match Target Size (Stretch):** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration import com.abedelazizshe.lightcompressorlibrary.config.VideoResizer val stretchResizeConfig = Configuration( resizer = VideoResizer.matchSize(width = 640.0, height = 480.0, stretch = true), videoNames = listOf("video") ) ``` **No Resizing:** ```kotlin import com.abedelazizshe.lightcompressorlibrary.config.Configuration val noResizeConfig = Configuration( resizer = null, videoNames = listOf("video") ) ``` ``` -------------------------------- ### VideoQuality Enum Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt Defines preset quality levels for video compression. These presets determine the output video bitrate as a percentage of the original bitrate, affecting file size and visual quality. ```APIDOC ## VideoQuality Enum ### Description Defines preset quality levels that determine the output video bitrate as a percentage of the original bitrate. Higher quality settings produce larger files with better visual fidelity. ### Available Quality Presets: - **VERY_HIGH**: original bitrate * 0.6 (60% of original) - **HIGH**: original bitrate * 0.4 (40% of original) - **MEDIUM**: original bitrate * 0.3 (30% of original) - Default - **LOW**: original bitrate * 0.2 (20% of original) - **VERY_LOW**: original bitrate * 0.1 (10% of original) ### Usage Example: ```kotlin import com.abedelazizshe.lightcompressorlibrary.VideoQuality import com.abedelazizshe.lightcompressorlibrary.config.Configuration val config = Configuration( quality = VideoQuality.HIGH, // Use high quality compression videoNames = listOf("my-video") ) ``` ``` -------------------------------- ### VideoCompressor.cancel() Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt This method cancels any ongoing video compression operation. It stops the current process and triggers the onCancelled callback for all videos that were being processed. ```APIDOC ## VideoCompressor.cancel() ### Description Cancels any ongoing video compression operation. This method stops the compression process and triggers the onCancelled callback for all videos currently being processed. ### Method N/A (This is a static method call) ### Endpoint N/A ### Parameters None ### Request Example ```kotlin import com.abedelazizshe.lightcompressorlibrary.VideoCompressor // Cancel button click handler cancelButton.setOnClickListener { VideoCompressor.cancel() // The onCancelled callback will be triggered for each video } ``` ### Response N/A (This method does not return a value, but triggers callbacks) ``` -------------------------------- ### Cancel Video Compression Operation Source: https://context7.com/abedelazizshe/lightcompressor/llms.txt The `VideoCompressor.cancel()` method is used to halt any ongoing video compression process. Calling this method will stop the current compression and invoke the `onCancelled` callback for all videos that were being processed. ```kotlin import com.abedelazizshe.lightcompressorlibrary.VideoCompressor // Cancel button click handler cancelButton.setOnClickListener { VideoCompressor.cancel() // The onCancelled callback will be triggered for each video } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.