├── .gitignore
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── idv
│ │ └── luchafang
│ │ └── videotrimmerexample
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── idv
│ │ │ └── luchafang
│ │ │ └── videotrimmerexample
│ │ │ └── MainActivity.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── idv
│ └── luchafang
│ └── videotrimmerexample
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── screenshots
├── screenshot_1.png
└── screenshot_2.png
├── settings.gradle
└── videotrimmer
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── idv
│ └── luchafang
│ └── videotrimmer
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── idv
│ │ └── luchafang
│ │ └── videotrimmer
│ │ ├── Injection.kt
│ │ ├── VideoTrimmerContract.kt
│ │ ├── VideoTrimmerPresenter.kt
│ │ ├── VideoTrimmerView.kt
│ │ ├── data
│ │ └── TrimmerDraft.kt
│ │ ├── slidingwindow
│ │ └── SlidingWindowView.kt
│ │ ├── tools
│ │ ├── SetVideoThumbnailAsyncTask.kt
│ │ └── Utils.kt
│ │ └── videoframe
│ │ ├── VideoFramesAdaptor.kt
│ │ ├── VideoFramesDecoration.kt
│ │ └── VideoFramesScrollListener.kt
└── res
│ ├── drawable
│ ├── trimmer_left_bar.xml
│ └── trimmer_right_bar.xml
│ ├── layout
│ └── layout_video_trimmer.xml
│ └── values
│ ├── attrs.xml
│ └── strings.xml
└── test
└── java
└── idv
└── luchafang
└── videotrimmer
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | app/.DS_Store
3 | app/release/*
4 | app/release/output.json
5 | # Built application files
6 | *.apk
7 | *.ap_
8 | *.aab
9 |
10 | # Files for the ART/Dalvik VM
11 | *.dex
12 |
13 | # Java class files
14 | *.class
15 |
16 | # Generated files
17 | bin/
18 | gen/
19 | out/
20 |
21 | # Gradle files
22 | .gradle/
23 | build/
24 |
25 | # Local configuration file (sdk path, etc)
26 | local.properties
27 |
28 | # Proguard folder generated by Eclipse
29 | proguard/
30 |
31 | # Log Files
32 | *.log
33 |
34 | # Android Studio Navigation editor temp files
35 | .navigation/
36 |
37 | # Android Studio captures folder
38 | captures/
39 |
40 | # IntelliJ
41 | .idea/*
42 | *.iml
43 |
44 | # Keystore files
45 | # Uncomment the following lines if you do not want to check your keystore files in.
46 | #*.jks
47 | #*.keystore
48 |
49 | # External native build folder generated in Android Studio 2.2 and later
50 | .externalNativeBuild
51 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android Video Trimmer View
2 |
3 |
4 |
5 | Note that this is only the PURE android view. Consider using ffmpeg to actually trim the video.
6 |
7 | ## Import to your project
8 | Add this to project level build.gradle
9 | ```
10 | allprojects {
11 | repositories {
12 | maven { url 'https://jitpack.io' }
13 | }
14 | }
15 | ```
16 |
17 | And then in app level build.gradle
18 | ```
19 | implementation 'com.github.freddyfang:android-video-trimmer:v1.0.0'
20 | ```
21 |
22 | ## How to Use
23 | ***Layout xml***
24 | ```
25 |
34 | ```
35 |
36 | ***Display it***
37 | ```
38 | videoTrimmerView
39 | .setVideo(File(path))
40 | .setMaxDuration(30_000) // millis
41 | .setMinDuration(3_000) // millis
42 | .setFrameCountInWindow(8)
43 | .setExtraDragSpace(10) // pixels
44 | .setOnSelectedRangeChangedListener(this)
45 | .show()
46 | ```
47 |
48 | ***OnSelectedRangeChangedListener***
49 | ```
50 | override fun onSelectRangeStart() {
51 | // Start to drag range bar or start to scroll the video frame list
52 | }
53 |
54 | override fun onSelectRange(startMillis: Long, endMillis: Long) {
55 | // Range is changing
56 | }
57 |
58 | override fun onSelectRangeEnd(startMillis: Long, endMillis: Long) {
59 | // Range selected, play the video here
60 | }
61 | ```
62 |
63 | Also, you can save the current UI state by calling
64 | ```
65 | val draft = videoTrimmerView.getTrimmerDraft()
66 | // draft is a parcelable object
67 | ```
68 | and restore it when necessary.
69 | ```
70 | videoTrimmerView.restoreTrimmer(draft)
71 | ```
72 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 28
7 |
8 | defaultConfig {
9 | applicationId "idv.luchafang.videotrimmerexample"
10 | minSdkVersion 19
11 | targetSdkVersion 28
12 | versionCode 1
13 | versionName "1.0"
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | compileOptions {
25 | sourceCompatibility JavaVersion.VERSION_1_8
26 | targetCompatibility JavaVersion.VERSION_1_8
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 |
33 | testImplementation 'junit:junit:4.12'
34 | androidTestImplementation 'androidx.test:runner:1.2.0'
35 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
36 |
37 | implementation 'androidx.appcompat:appcompat:1.0.2'
38 | implementation 'androidx.core:core-ktx:1.0.2'
39 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
40 | implementation "androidx.recyclerview:recyclerview:1.1.0-beta01"
41 |
42 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
43 |
44 | implementation 'com.google.android.exoplayer:exoplayer:2.10.1'
45 |
46 | implementation project(':videotrimmer')
47 | }
48 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/idv/luchafang/videotrimmerexample/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmerexample
2 |
3 | import androidx.test.InstrumentationRegistry
4 | import androidx.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("idv.luchafang.videotrimmerexample", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/java/idv/luchafang/videotrimmerexample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmerexample
2 |
3 | import android.Manifest
4 | import android.app.Activity
5 | import android.content.Intent
6 | import android.content.pm.PackageManager
7 | import android.database.Cursor
8 | import android.net.Uri
9 | import android.os.Bundle
10 | import android.provider.MediaStore
11 | import androidx.appcompat.app.AppCompatActivity
12 | import androidx.core.app.ActivityCompat
13 | import com.google.android.exoplayer2.ExoPlayerFactory
14 | import com.google.android.exoplayer2.SimpleExoPlayer
15 | import com.google.android.exoplayer2.source.ClippingMediaSource
16 | import com.google.android.exoplayer2.source.ProgressiveMediaSource
17 | import com.google.android.exoplayer2.upstream.DataSource
18 | import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
19 | import idv.luchafang.videotrimmer.VideoTrimmerView
20 | import kotlinx.android.synthetic.main.activity_main.*
21 | import java.io.File
22 |
23 |
24 | class MainActivity : AppCompatActivity(), VideoTrimmerView.OnSelectedRangeChangedListener {
25 |
26 | private val REQ_PICK_VIDEO = 100
27 | private val REQ_PERMISSION = 200
28 |
29 | private val player: SimpleExoPlayer by lazy {
30 | ExoPlayerFactory.newSimpleInstance(this).also {
31 | it.repeatMode = SimpleExoPlayer.REPEAT_MODE_ALL
32 | playerView.player = it
33 | }
34 | }
35 |
36 | private val dataSourceFactory: DataSource.Factory by lazy {
37 | DefaultDataSourceFactory(this, "VideoTrimmer")
38 | }
39 |
40 | private var videoPath: String = ""
41 |
42 | /* -------------------------------------------------------------------------------------------*/
43 | /* Activity */
44 | override fun onCreate(savedInstanceState: Bundle?) {
45 | super.onCreate(savedInstanceState)
46 | setContentView(R.layout.activity_main)
47 |
48 | pickVideoBtn.setOnClickListener {
49 | Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
50 | .apply {
51 | type = "video/*"
52 | }
53 | .also { startActivityForResult(it, REQ_PICK_VIDEO) }
54 | }
55 | }
56 |
57 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
58 | super.onActivityResult(requestCode, resultCode, data)
59 |
60 | when (requestCode) {
61 | REQ_PICK_VIDEO -> {
62 | if (resultCode == Activity.RESULT_OK) {
63 | videoPath = getRealPathFromMediaData(data?.data)
64 | displayTrimmerView(videoPath)
65 | }
66 | }
67 | }
68 | }
69 |
70 | override fun onStart() {
71 | super.onStart()
72 |
73 | ActivityCompat.requestPermissions(
74 | this,
75 | arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
76 | REQ_PERMISSION
77 | )
78 | }
79 |
80 | override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
81 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
82 |
83 | if (requestCode == REQ_PERMISSION && grantResults.firstOrNull() != PackageManager.PERMISSION_GRANTED) {
84 | finish()
85 | }
86 | }
87 |
88 | /* -------------------------------------------------------------------------------------------*/
89 | /* VideoTrimmerView.OnSelectedRangeChangedListener */
90 | override fun onSelectRangeStart() {
91 | player.playWhenReady = false
92 | }
93 |
94 | override fun onSelectRange(startMillis: Long, endMillis: Long) {
95 | showDuration(startMillis, endMillis)
96 | }
97 |
98 | override fun onSelectRangeEnd(startMillis: Long, endMillis: Long) {
99 | showDuration(startMillis, endMillis)
100 | playVideo(videoPath, startMillis, endMillis)
101 | }
102 |
103 | /* -------------------------------------------------------------------------------------------*/
104 | /* VideoTrimmer */
105 | private fun displayTrimmerView(path: String) {
106 | videoTrimmerView
107 | .setVideo(File(path))
108 | .setMaxDuration(30_000)
109 | .setMinDuration(3_000)
110 | .setFrameCountInWindow(8)
111 | .setExtraDragSpace(dpToPx(2f))
112 | .setOnSelectedRangeChangedListener(this)
113 | .show()
114 | }
115 |
116 | /* -------------------------------------------------------------------------------------------*/
117 | /* ExoPlayer2 */
118 | private fun playVideo(path: String, startMillis: Long, endMillis: Long) {
119 | if (path.isBlank()) return
120 |
121 | val source = ProgressiveMediaSource.Factory(dataSourceFactory)
122 | .createMediaSource(Uri.parse(path))
123 | .let {
124 | ClippingMediaSource(
125 | it,
126 | startMillis * 1000L,
127 | endMillis * 1000L
128 | )
129 | }
130 |
131 | player.playWhenReady = true
132 | player.prepare(source)
133 | }
134 |
135 | /* -------------------------------------------------------------------------------------------*/
136 | /* Internal helpers */
137 | private fun getRealPathFromMediaData(data: Uri?): String {
138 | data ?: return ""
139 |
140 | var cursor: Cursor? = null
141 | try {
142 | cursor = contentResolver.query(
143 | data,
144 | arrayOf(MediaStore.Video.Media.DATA),
145 | null, null, null
146 | )
147 |
148 | val col = cursor.getColumnIndex(MediaStore.Video.Media.DATA)
149 | cursor.moveToFirst()
150 |
151 | return cursor.getString(col)
152 | } finally {
153 | cursor?.close()
154 | }
155 | }
156 |
157 | private fun showDuration(startMillis: Long, endMillis: Long) {
158 | val duration = (endMillis - startMillis) / 1000L
159 | durationView.text = "$duration seconds selected"
160 | }
161 |
162 | private fun dpToPx(dp: Float): Float {
163 | val density = resources.displayMetrics.density
164 | return dp * density
165 | }
166 | }
167 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
21 |
22 |
32 |
33 |
43 |
44 |
57 |
58 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | VideoTrimmer
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/idv/luchafang/videotrimmerexample/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmerexample
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.31'
5 | repositories {
6 | google()
7 | jcenter()
8 | mavenCentral()
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:3.4.2'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Jul 23 14:02:51 EDT 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/screenshots/screenshot_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/screenshots/screenshot_1.png
--------------------------------------------------------------------------------
/screenshots/screenshot_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/freddyfang/android-video-trimmer/94c73f63b1df20e46e120ffeeef874a7df763a39/screenshots/screenshot_2.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':videotrimmer'
2 |
--------------------------------------------------------------------------------
/videotrimmer/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/videotrimmer/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 28
7 |
8 | defaultConfig {
9 | minSdkVersion 19
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | kotlinOptions {
26 | freeCompilerArgs = ['-Xjvm-default=compatibility']
27 | jvmTarget = '1.8'
28 | }
29 |
30 | androidExtensions {
31 | experimental = true
32 | }
33 | }
34 |
35 | dependencies {
36 | implementation fileTree(dir: 'libs', include: ['*.jar'])
37 |
38 | testImplementation 'junit:junit:4.12'
39 | androidTestImplementation 'androidx.test:runner:1.2.0'
40 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
41 |
42 | implementation 'androidx.appcompat:appcompat:1.0.2'
43 | implementation 'androidx.core:core-ktx:1.0.2'
44 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
45 | implementation "androidx.recyclerview:recyclerview:1.1.0-beta01"
46 |
47 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
48 | }
49 |
--------------------------------------------------------------------------------
/videotrimmer/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/videotrimmer/src/androidTest/java/idv/luchafang/videotrimmer/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer;
2 |
3 | import android.content.Context;
4 | import androidx.test.InstrumentationRegistry;
5 | import androidx.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("idv.luchafang.videotrimmer.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/videotrimmer/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/Injection.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer
2 |
3 | internal fun obtainVideoTrimmerPresenter() = VideoTrimmerPresenter()
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/VideoTrimmerContract.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer
2 |
3 | import idv.luchafang.videotrimmer.data.TrimmerDraft
4 | import java.io.File
5 |
6 | internal interface VideoTrimmerContract {
7 | interface View {
8 | fun getSlidingWindowWidth(): Int
9 | fun setupAdaptor(video: File, frames: List, frameWidth: Int)
10 | fun setupSlidingWindow()
11 |
12 | fun restoreSlidingWindow(left: Float, right: Float)
13 | fun restoreVideoFrameList(framePosition: Int, frameOffset: Int)
14 | }
15 |
16 | interface Presenter {
17 | fun onViewAttached(view: View)
18 | fun onViewDetached()
19 |
20 | fun setVideo(video: File)
21 | fun setMaxDuration(millis: Long)
22 | fun setMinDuration(millis: Long)
23 | fun setFrameCountInWindow(count: Int)
24 | fun setOnSelectedRangeChangedListener(listener: VideoTrimmerView.OnSelectedRangeChangedListener)
25 |
26 | fun isValidState(): Boolean
27 | fun show()
28 |
29 | fun getTrimmerDraft(): TrimmerDraft
30 | fun restoreTrimmer(draft: TrimmerDraft)
31 | }
32 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/VideoTrimmerPresenter.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer
2 |
3 | import idv.luchafang.videotrimmer.data.TrimmerDraft
4 | import idv.luchafang.videotrimmer.slidingwindow.SlidingWindowView
5 | import idv.luchafang.videotrimmer.tools.extractVideoLength
6 | import idv.luchafang.videotrimmer.videoframe.VideoFramesScrollListener
7 | import java.io.File
8 | import kotlin.math.ceil
9 | import kotlin.math.min
10 | import kotlin.math.roundToLong
11 |
12 | internal class VideoTrimmerPresenter : VideoTrimmerContract.Presenter,
13 | SlidingWindowView.Listener,
14 | VideoFramesScrollListener.Callback {
15 |
16 | private var view: VideoTrimmerContract.View? = null
17 |
18 | private var video: File? = null
19 | private var maxDuration = 30_000L
20 | private var minDuration = 3_000L
21 | private var frameCountInWindow = 10
22 |
23 | private var onSelectedRangeChangedListener: VideoTrimmerView.OnSelectedRangeChangedListener? = null
24 |
25 | private var videoLength = 0L
26 | private var videoWindowLength = 0L
27 |
28 | private var rawStartMillis = 0L
29 | private var rawEndMillis = 0L
30 | private var offsetMillis = 0L
31 |
32 | private var framePosition = 0
33 | private var frameOffset = 0
34 |
35 | private val startMillis
36 | get() = min(rawStartMillis + offsetMillis, videoLength)
37 | private val endMillis
38 | get() = min(rawEndMillis + offsetMillis, videoLength)
39 |
40 | /* -------------------------------------------------------------------------------------------*/
41 | /* Presenter */
42 | override fun onViewAttached(view: VideoTrimmerContract.View) {
43 | this.view = view
44 | }
45 |
46 | override fun onViewDetached() {
47 | this.view = null
48 | }
49 |
50 | /* -------------------------------------------------------------------------------------------*/
51 | /* Builder */
52 | override fun setVideo(video: File) {
53 | this.video = video
54 | }
55 |
56 | override fun setMaxDuration(millis: Long) {
57 | this.maxDuration = millis
58 | }
59 |
60 | override fun setMinDuration(millis: Long) {
61 | this.minDuration = millis
62 | }
63 |
64 | override fun setFrameCountInWindow(count: Int) {
65 | this.frameCountInWindow = count
66 | }
67 |
68 | override fun setOnSelectedRangeChangedListener(listener: VideoTrimmerView.OnSelectedRangeChangedListener) {
69 | this.onSelectedRangeChangedListener = listener
70 | }
71 |
72 | override fun isValidState(): Boolean {
73 | return video != null
74 | && maxDuration > 0L
75 | && minDuration > 0L
76 | && maxDuration >= minDuration
77 | }
78 |
79 | override fun show() {
80 | if (!isValidState()) {
81 | return
82 | }
83 |
84 | val video = this.video ?: return
85 | videoLength = extractVideoLength(video.path)
86 |
87 | if (videoLength < minDuration) {
88 | // TODO
89 | return
90 | }
91 |
92 | videoWindowLength = min(
93 | videoLength,
94 | maxDuration
95 | )
96 |
97 | val step = videoWindowLength / frameCountInWindow
98 | val frames = mutableListOf()
99 | for (i in 0 until videoLength step step) {
100 | frames.add(i)
101 |
102 | if (videoLength == videoWindowLength
103 | && frames.size == frameCountInWindow
104 | ) {
105 | break
106 | }
107 | }
108 |
109 | val windowWidth = view?.getSlidingWindowWidth() ?: return
110 | val frameWidth = windowWidth.toFloat() / frameCountInWindow
111 |
112 | rawStartMillis = 0L
113 | rawEndMillis = videoWindowLength
114 |
115 | view?.setupSlidingWindow()
116 | view?.setupAdaptor(video, frames, ceil(frameWidth).toInt())
117 |
118 | onSelectedRangeChangedListener?.onSelectRangeEnd(rawStartMillis, rawEndMillis)
119 | }
120 |
121 | /* -------------------------------------------------------------------------------------------*/
122 | /* Trimmer Draft */
123 | override fun getTrimmerDraft(): TrimmerDraft = TrimmerDraft(
124 | video?.path ?: "",
125 | rawStartMillis,
126 | rawEndMillis,
127 | offsetMillis,
128 | framePosition,
129 | frameOffset
130 | )
131 |
132 | override fun restoreTrimmer(draft: TrimmerDraft) {
133 | if (draft.rawStartMillis < 0L
134 | || draft.rawEndMillis <= 0L
135 | || draft.rawEndMillis - draft.rawStartMillis < minDuration
136 | ) {
137 | return
138 | }
139 |
140 | restoreRangeBar(draft)
141 | restoreFrameListOffset(draft)
142 | }
143 |
144 | private fun restoreRangeBar(draft: TrimmerDraft) {
145 | this.rawStartMillis = draft.rawStartMillis
146 | this.rawEndMillis = draft.rawEndMillis
147 |
148 | val left = draft.rawStartMillis / videoWindowLength.toFloat()
149 | val right = draft.rawEndMillis / videoWindowLength.toFloat()
150 |
151 | view?.restoreSlidingWindow(left, right)
152 | }
153 |
154 | private fun restoreFrameListOffset(draft: TrimmerDraft) {
155 | this.offsetMillis = draft.offsetMillis
156 | this.framePosition = draft.framePosition
157 | this.frameOffset = draft.frameOffset
158 |
159 | view?.restoreVideoFrameList(framePosition, frameOffset)
160 | }
161 |
162 | /* -------------------------------------------------------------------------------------------*/
163 | /* SlidingWindowView.Listener */
164 | override fun onDragRangeBarStart() {
165 | onSelectedRangeChangedListener?.onSelectRangeStart()
166 | }
167 |
168 | override fun onDragRangeBar(left: Float, right: Float): Boolean {
169 | calculateSelectedArea(left, right)
170 | val duration = rawEndMillis - rawStartMillis
171 |
172 | if (duration < minDuration) {
173 | return false
174 | }
175 |
176 | onSelectedRangeChangedListener?.onSelectRange(rawStartMillis, rawEndMillis)
177 |
178 | return true
179 | }
180 |
181 | override fun onDragRangeBarEnd(left: Float, right: Float) {
182 | calculateSelectedArea(left, right)
183 | onSelectedRangeChangedListener?.onSelectRangeEnd(rawStartMillis, rawEndMillis)
184 | }
185 |
186 | /* -------------------------------------------------------------------------------------------*/
187 | /* VideoFramesScrollListener.Callback */
188 | override fun onScrollVideoFramesStart() {
189 | if (videoWindowLength == videoLength) {
190 | return
191 | }
192 |
193 | onSelectedRangeChangedListener?.onSelectRangeStart()
194 | }
195 |
196 | override fun onScrollVideoFrames(offsetPercentage: Float, framePosition: Int, frameOffset: Int) {
197 | if (videoWindowLength == videoLength) {
198 | return
199 | }
200 |
201 | offsetMillis = (videoLength * offsetPercentage).roundToLong()
202 | onSelectedRangeChangedListener?.onSelectRange(startMillis, endMillis)
203 |
204 | this.framePosition = framePosition
205 | this.frameOffset = frameOffset
206 | }
207 |
208 | override fun onScrollVideoFramesEnd() {
209 | if (videoWindowLength == videoLength) {
210 | return
211 | }
212 |
213 | onSelectedRangeChangedListener?.onSelectRangeEnd(startMillis, endMillis)
214 | }
215 |
216 | /* -------------------------------------------------------------------------------------------*/
217 | /* Internal helpers */
218 | private fun calculateSelectedArea(left: Float, right: Float) {
219 | rawStartMillis = (left * videoWindowLength).roundToLong()
220 | rawEndMillis = (right * videoWindowLength).roundToLong()
221 | }
222 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/VideoTrimmerView.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.util.AttributeSet
6 | import android.widget.LinearLayout.HORIZONTAL
7 | import androidx.annotation.ColorInt
8 | import androidx.annotation.DrawableRes
9 | import androidx.constraintlayout.widget.ConstraintLayout
10 | import androidx.recyclerview.widget.LinearLayoutManager
11 | import idv.luchafang.videotrimmer.data.TrimmerDraft
12 | import idv.luchafang.videotrimmer.slidingwindow.SlidingWindowView
13 | import idv.luchafang.videotrimmer.tools.dpToPx
14 | import idv.luchafang.videotrimmer.videoframe.VideoFramesAdaptor
15 | import idv.luchafang.videotrimmer.videoframe.VideoFramesDecoration
16 | import idv.luchafang.videotrimmer.videoframe.VideoFramesScrollListener
17 | import kotlinx.android.synthetic.main.layout_video_trimmer.view.*
18 | import java.io.File
19 | import kotlin.math.roundToInt
20 |
21 | class VideoTrimmerView @JvmOverloads constructor(
22 | context: Context,
23 | attrs: AttributeSet? = null,
24 | defStyle: Int = 0
25 | ) : ConstraintLayout(context, attrs, defStyle), VideoTrimmerContract.View {
26 |
27 | @DrawableRes
28 | private var leftBarRes: Int = R.drawable.trimmer_left_bar
29 | @DrawableRes
30 | private var rightBarRes: Int = R.drawable.trimmer_right_bar
31 |
32 | private var barWidth: Float = dpToPx(context, 10f)
33 | private var borderWidth: Float = 0f
34 |
35 | @ColorInt
36 | private var borderColor: Int = Color.BLACK
37 | @ColorInt
38 | private var overlayColor: Int = Color.argb(120, 183, 191, 207)
39 |
40 | private var presenter: VideoTrimmerContract.Presenter? = null
41 | private var adaptor: VideoFramesAdaptor? = null
42 |
43 | /* -------------------------------------------------------------------------------------------*/
44 | /* Initialize */
45 | init {
46 | inflate(context, R.layout.layout_video_trimmer, this)
47 | obtainAttributes(attrs)
48 | initViews()
49 | }
50 |
51 | private fun obtainAttributes(attrs: AttributeSet?) {
52 | attrs ?: return
53 |
54 | val array = resources.obtainAttributes(attrs, R.styleable.VideoTrimmerView)
55 | try {
56 | leftBarRes = array.getResourceId(R.styleable.VideoTrimmerView_vtv_window_left_bar, leftBarRes)
57 | slidingWindowView.leftBarRes = leftBarRes
58 |
59 | rightBarRes = array.getResourceId(R.styleable.VideoTrimmerView_vtv_window_right_bar, rightBarRes)
60 | slidingWindowView.rightBarRes = rightBarRes
61 |
62 | barWidth = array.getDimension(R.styleable.VideoTrimmerView_vtv_window_bar_width, barWidth)
63 | slidingWindowView.barWidth = barWidth
64 |
65 | borderWidth = array.getDimension(R.styleable.VideoTrimmerView_vtv_window_border_width, borderWidth)
66 | slidingWindowView.borderWidth = borderWidth
67 |
68 | borderColor = array.getColor(R.styleable.VideoTrimmerView_vtv_window_border_color, borderColor)
69 | slidingWindowView.borderColor = borderColor
70 |
71 | overlayColor = array.getColor(R.styleable.VideoTrimmerView_vtv_overlay_color, overlayColor)
72 | slidingWindowView.overlayColor = overlayColor
73 | } finally {
74 | array.recycle()
75 | }
76 | }
77 |
78 | private fun initViews() {
79 | videoFrameListView.layoutManager = LinearLayoutManager(context, HORIZONTAL, false)
80 | }
81 |
82 | /* -------------------------------------------------------------------------------------------*/
83 | /* Attach / Detach */
84 | override fun onAttachedToWindow() {
85 | super.onAttachedToWindow()
86 | presenter = obtainVideoTrimmerPresenter()
87 | .apply { onViewAttached(this@VideoTrimmerView) }
88 | onPresenterCreated()
89 | }
90 |
91 | override fun onDetachedFromWindow() {
92 | super.onDetachedFromWindow()
93 | presenter?.onViewDetached()
94 | presenter = null
95 | }
96 |
97 | private fun onPresenterCreated() {
98 | presenter?.let {
99 | slidingWindowView.listener = presenter as SlidingWindowView.Listener
100 |
101 | val horizontalMargin = (dpToPx(context, 11f) + barWidth).roundToInt()
102 | val decoration = VideoFramesDecoration(horizontalMargin, overlayColor)
103 | val scrollListener = VideoFramesScrollListener(
104 | horizontalMargin,
105 | presenter as VideoFramesScrollListener.Callback
106 | )
107 |
108 | videoFrameListView.addItemDecoration(decoration)
109 | videoFrameListView.addOnScrollListener(scrollListener)
110 | }
111 | }
112 |
113 | /* -------------------------------------------------------------------------------------------*/
114 | /* Public APIs */
115 | fun setVideo(video: File): VideoTrimmerView {
116 | presenter?.setVideo(video)
117 | return this
118 | }
119 |
120 | fun setMaxDuration(millis: Long): VideoTrimmerView {
121 | presenter?.setMaxDuration(millis)
122 | return this
123 | }
124 |
125 | fun setMinDuration(millis: Long): VideoTrimmerView {
126 | presenter?.setMinDuration(millis)
127 | return this
128 | }
129 |
130 | fun setFrameCountInWindow(count: Int): VideoTrimmerView {
131 | presenter?.setFrameCountInWindow(count)
132 | return this
133 | }
134 |
135 | fun setOnSelectedRangeChangedListener(listener: OnSelectedRangeChangedListener): VideoTrimmerView {
136 | presenter?.setOnSelectedRangeChangedListener(listener)
137 | return this
138 | }
139 |
140 | fun setExtraDragSpace(spaceInPx: Float): VideoTrimmerView {
141 | slidingWindowView.extraDragSpace = spaceInPx
142 | return this
143 | }
144 |
145 | fun show() {
146 | presenter?.show()
147 | }
148 |
149 | fun getTrimmerDraft(): TrimmerDraft? = presenter?.getTrimmerDraft()
150 |
151 | fun restoreTrimmer(draft: TrimmerDraft) {
152 | presenter?.restoreTrimmer(draft)
153 | }
154 |
155 | /* -------------------------------------------------------------------------------------------*/
156 | /* VideoTrimmerContract.View */
157 | override fun getSlidingWindowWidth(): Int {
158 | val screenWidth = resources.displayMetrics.widthPixels
159 | val margin = dpToPx(context, 11f)
160 | return screenWidth - 2 * (margin + barWidth).roundToInt()
161 | }
162 |
163 | override fun setupAdaptor(video: File, frames: List, frameWidth: Int) {
164 | adaptor = VideoFramesAdaptor(video, frames, frameWidth).also {
165 | videoFrameListView.adapter = it
166 | }
167 | }
168 |
169 | override fun setupSlidingWindow() {
170 | slidingWindowView.reset()
171 | }
172 |
173 | override fun restoreSlidingWindow(left: Float, right: Float) {
174 | slidingWindowView.setBarPositions(left, right)
175 | }
176 |
177 | override fun restoreVideoFrameList(framePosition: Int, frameOffset: Int) {
178 | val layoutManager = videoFrameListView.layoutManager as? LinearLayoutManager ?: return
179 | layoutManager.scrollToPositionWithOffset(framePosition, frameOffset)
180 | }
181 |
182 | /* -------------------------------------------------------------------------------------------*/
183 | /* Listener */
184 | interface OnSelectedRangeChangedListener {
185 | fun onSelectRangeStart()
186 | fun onSelectRange(startMillis: Long, endMillis: Long)
187 | fun onSelectRangeEnd(startMillis: Long, endMillis: Long)
188 | }
189 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/data/TrimmerDraft.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.data
2 |
3 | import android.os.Parcelable
4 | import kotlinx.android.parcel.Parcelize
5 |
6 | @Parcelize
7 | data class TrimmerDraft(
8 | val path: String,
9 | val rawStartMillis: Long,
10 | val rawEndMillis: Long,
11 | val offsetMillis: Long,
12 | val framePosition: Int = 0,
13 | val frameOffset: Int = 0,
14 | val createdTime: Long = System.currentTimeMillis()
15 | ): Parcelable, Comparable {
16 |
17 | override fun equals(other: Any?): Boolean {
18 | if (this === other) return true
19 | if (javaClass != other?.javaClass) return false
20 |
21 | other as TrimmerDraft
22 |
23 | return path == other.path
24 | }
25 |
26 | override fun hashCode(): Int {
27 | return path.hashCode()
28 | }
29 |
30 | override fun compareTo(other: TrimmerDraft): Int {
31 | return when {
32 | this === other -> 0
33 | this.createdTime == other.createdTime -> 0
34 | this.createdTime < other.createdTime -> 1
35 | else -> -1
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/slidingwindow/SlidingWindowView.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.slidingwindow
2 |
3 | import android.content.Context
4 | import android.graphics.Canvas
5 | import android.graphics.Paint
6 | import android.util.AttributeSet
7 | import android.view.MotionEvent
8 | import android.view.MotionEvent.*
9 | import android.view.View
10 | import androidx.annotation.ColorInt
11 | import androidx.annotation.DrawableRes
12 | import androidx.core.content.ContextCompat
13 | import kotlin.math.max
14 | import kotlin.math.min
15 | import kotlin.math.roundToInt
16 |
17 | internal class SlidingWindowView @JvmOverloads constructor(
18 | context: Context,
19 | attrs: AttributeSet? = null,
20 | defStyle: Int = 0
21 | ) : View(context, attrs, defStyle) {
22 |
23 | private val HOLD_LEFT_BAR = 0
24 | private val HOLD_RIGHT_BAR = 1
25 | private val HOLD_NOTHING = 2
26 |
27 | @DrawableRes
28 | var leftBarRes: Int = 0
29 | set(value) {
30 | field = value
31 | invalidate()
32 | }
33 |
34 | @DrawableRes
35 | var rightBarRes: Int = 0
36 | set(value) {
37 | field = value
38 | invalidate()
39 | }
40 |
41 | var barWidth: Float = 0f
42 | set(value) {
43 | field = value
44 | invalidate()
45 | }
46 |
47 | var borderWidth: Float = 0f
48 | set(value) {
49 | field = value
50 | invalidate()
51 | }
52 |
53 | @ColorInt
54 | var borderColor: Int = 0
55 | set(value) {
56 | field = value
57 | invalidate()
58 | }
59 |
60 | @ColorInt
61 | var overlayColor: Int = 0
62 | set(value) {
63 | field = value
64 | invalidate()
65 | }
66 |
67 | var listener: Listener? = null
68 | var extraDragSpace: Float = 0f
69 |
70 | private val borderPaint: Paint = Paint().apply { isAntiAlias = true }
71 | private val overlayPaint: Paint = Paint().apply { isAntiAlias = true }
72 |
73 | private var leftBarX = -1f // Left-Top
74 | private var rightBarX = -1f // Left-Top
75 |
76 | private var leftBarXPercentage = -1f
77 | private var rightBarXPercentage = -1f
78 |
79 | private var hold = HOLD_NOTHING
80 |
81 | /* -------------------------------------------------------------------------------------------*/
82 | /* Public APIs */
83 | fun setBarPositions(leftPercentage: Float, rightPercentage: Float) {
84 | this.leftBarXPercentage = leftPercentage
85 | this.rightBarXPercentage = rightPercentage
86 | postInvalidate()
87 | }
88 |
89 | fun reset() {
90 | leftBarX = -1f
91 | rightBarX = -1f
92 | leftBarXPercentage = -1f
93 | rightBarXPercentage = -1f
94 | invalidate()
95 | }
96 |
97 | /* -------------------------------------------------------------------------------------------*/
98 | /* Draw */
99 | override fun onDraw(canvas: Canvas) {
100 | super.onDraw(canvas)
101 |
102 | if (leftBarXPercentage >= 0f && rightBarXPercentage > 0f) {
103 | restoreBarPositions()
104 | }
105 |
106 | if (leftBarX < 0) {
107 | leftBarX = 0f
108 | }
109 |
110 | if (rightBarX < 0) {
111 | rightBarX = width - barWidth
112 | }
113 |
114 | drawBorder(canvas)
115 | drawLeftBar(canvas)
116 | drawRightBar(canvas)
117 | drawOverlay(canvas)
118 | }
119 |
120 | private fun drawLeftBar(canvas: Canvas) {
121 | ContextCompat.getDrawable(context, leftBarRes)?.apply {
122 | setBounds(0, 0, barWidth.roundToInt(), height)
123 |
124 | canvas.save()
125 |
126 | canvas.translate(leftBarX, 0f)
127 | draw(canvas)
128 |
129 | canvas.restore()
130 | }
131 | }
132 |
133 | private fun drawRightBar(canvas: Canvas) {
134 | ContextCompat.getDrawable(context, rightBarRes)?.apply {
135 | setBounds(0, 0, barWidth.roundToInt(), height)
136 |
137 | canvas.save()
138 |
139 | canvas.translate(rightBarX, 0f)
140 | draw(canvas)
141 |
142 | canvas.restore()
143 | }
144 | }
145 |
146 | private fun drawBorder(canvas: Canvas) {
147 | borderPaint.strokeWidth = borderWidth
148 | borderPaint.color = borderColor
149 |
150 | val fromX = leftBarX + barWidth - 1
151 | val toX = rightBarX + 1
152 |
153 | drawTopBorder(canvas, fromX, toX)
154 | drawBottomBorder(canvas, fromX, toX)
155 | }
156 |
157 | private fun drawTopBorder(canvas: Canvas, fromX: Float, toX: Float) {
158 | val y = borderWidth / 2f
159 | canvas.drawLine(fromX, y, toX, y, borderPaint)
160 | }
161 |
162 | private fun drawBottomBorder(canvas: Canvas, fromX: Float, toX: Float) {
163 | val y = height - (borderWidth / 2f)
164 | canvas.drawLine(fromX, y, toX, y, borderPaint)
165 | }
166 |
167 | private fun drawOverlay(canvas: Canvas) {
168 | overlayPaint.color = overlayColor
169 |
170 | // Left side overlay
171 | if (leftBarX > barWidth) {
172 | canvas.drawRect(
173 | barWidth,
174 | borderWidth,
175 | leftBarX,
176 | height - borderWidth,
177 | overlayPaint
178 | )
179 | }
180 |
181 | // Right side overlay
182 | if (rightBarX < width - 2 * barWidth) {
183 | canvas.drawRect(
184 | rightBarX + barWidth,
185 | borderWidth,
186 | width - barWidth,
187 | height - borderWidth,
188 | overlayPaint
189 | )
190 | }
191 | }
192 |
193 | /* -------------------------------------------------------------------------------------------*/
194 | /* OnTouch */
195 | override fun onTouchEvent(event: MotionEvent): Boolean {
196 | return when (event.action) {
197 | ACTION_DOWN -> onDown(event.x, event.y)
198 | ACTION_MOVE -> onMove(event.x, event.y)
199 | ACTION_UP -> onUp(event.x, event.y)
200 | else -> super.onTouchEvent(event)
201 | }
202 | }
203 |
204 | private fun onDown(x: Float, y: Float): Boolean {
205 | hold = when {
206 | isLeftBarTouched(x, y) -> HOLD_LEFT_BAR
207 | isRightBarTouched(x, y) -> HOLD_RIGHT_BAR
208 | else -> HOLD_NOTHING
209 | }
210 |
211 | when (hold) {
212 | HOLD_LEFT_BAR, HOLD_RIGHT_BAR ->
213 | listener?.onDragRangeBarStart()
214 | }
215 |
216 | return hold != HOLD_NOTHING
217 | }
218 |
219 | private fun onMove(x: Float, y: Float): Boolean {
220 | when (hold) {
221 | HOLD_LEFT_BAR -> moveLeftBar(x, y)
222 | HOLD_RIGHT_BAR -> moveRightBar(x, y)
223 | else -> return false
224 | }
225 |
226 | return true
227 | }
228 |
229 | private fun onUp(x: Float, y: Float): Boolean {
230 | when (hold) {
231 | HOLD_LEFT_BAR, HOLD_RIGHT_BAR -> {
232 | val percentage = calculateXPercentage(leftBarX, rightBarX)
233 | listener?.onDragRangeBarEnd(percentage[0], percentage[1])
234 | }
235 | }
236 |
237 | hold = HOLD_NOTHING
238 | return true
239 | }
240 |
241 | /* -------------------------------------------------------------------------------------------*/
242 | /* Internal helpers */
243 | private fun isLeftBarTouched(x: Float, y: Float): Boolean {
244 | return x in (leftBarX - extraDragSpace)..(leftBarX + barWidth + extraDragSpace)
245 | && y in 0f..height.toFloat()
246 | }
247 |
248 | private fun isRightBarTouched(x: Float, y: Float): Boolean {
249 | return x in (rightBarX - extraDragSpace)..(rightBarX + barWidth + extraDragSpace)
250 | && y in 0f..height.toFloat()
251 | }
252 |
253 | private fun moveLeftBar(x: Float, y: Float) {
254 | var predictedLeftBarX = x - (barWidth / 2f)
255 | predictedLeftBarX = max(predictedLeftBarX, 0f)
256 | predictedLeftBarX = min(predictedLeftBarX, rightBarX - barWidth - 1)
257 |
258 | val percentage = calculateXPercentage(predictedLeftBarX, rightBarX)
259 | if (listener?.onDragRangeBar(percentage[0], percentage[1]) != false) {
260 | leftBarX = predictedLeftBarX
261 | postInvalidate()
262 | }
263 | }
264 |
265 | private fun moveRightBar(x: Float, y: Float) {
266 | var predictedRightBarX = x - (barWidth / 2f)
267 | predictedRightBarX = max(predictedRightBarX, leftBarX + barWidth + 1)
268 | predictedRightBarX = min(predictedRightBarX, width.toFloat() - barWidth)
269 |
270 | val percentage = calculateXPercentage(leftBarX, predictedRightBarX)
271 | if (listener?.onDragRangeBar(percentage[0], percentage[1]) != false) {
272 | rightBarX = predictedRightBarX
273 | postInvalidate()
274 | }
275 | }
276 |
277 | private fun calculateXPercentage(leftBarX: Float, rightBarX: Float): FloatArray {
278 | val totalLength = width - barWidth
279 | val left = leftBarX / totalLength
280 | val right = rightBarX / totalLength
281 | return floatArrayOf(left, right)
282 | }
283 |
284 | private fun restoreBarPositions() {
285 | val totalLength = width - barWidth
286 |
287 | this.leftBarX = leftBarXPercentage * totalLength
288 | this.rightBarX = rightBarXPercentage * totalLength
289 |
290 | this.leftBarXPercentage = -1f
291 | this.rightBarXPercentage = -1f
292 | }
293 |
294 | /* -------------------------------------------------------------------------------------------*/
295 | /* Listener */
296 | interface Listener {
297 | fun onDragRangeBarStart()
298 | fun onDragRangeBar(left: Float, right: Float): Boolean
299 | fun onDragRangeBarEnd(left: Float, right: Float)
300 | }
301 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/tools/SetVideoThumbnailAsyncTask.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.tools
2 |
3 | import android.animation.Animator
4 | import android.animation.AnimatorListenerAdapter
5 | import android.animation.AnimatorSet
6 | import android.graphics.Bitmap
7 | import android.media.MediaMetadataRetriever
8 | import android.os.AsyncTask
9 | import android.widget.ImageView
10 | import java.io.File
11 | import java.lang.ref.WeakReference
12 |
13 | internal class SetVideoThumbnailAsyncTask @JvmOverloads constructor(
14 | view: ImageView,
15 | private val timeMs: Long = 0L,
16 | private val size: Int = 512,
17 | private val fadeDuration: Long = 0L
18 | ) : AsyncTask() {
19 |
20 | private val viewRef = WeakReference(view)
21 |
22 | override fun doInBackground(vararg files: File?): Bitmap? {
23 | val filePath = files.takeIf { files.isNotEmpty() }
24 | ?.get(0)?.path
25 | ?: return null
26 |
27 | val retriever = MediaMetadataRetriever()
28 |
29 | return try {
30 | retriever.setDataSource(filePath)
31 |
32 | val timeUs = if (timeMs == 0L) -1 else timeMs * 1000
33 | val bitmap = retriever.getFrameAtTime(timeUs)
34 | scaleBitmap(bitmap, size)
35 | } catch (e: Exception) {
36 | null
37 | } finally {
38 | runCatching { retriever.release() }
39 | }
40 | }
41 |
42 | override fun onPostExecute(result: Bitmap?) {
43 | val view = viewRef.get() ?: return
44 |
45 | result?.let {
46 | if (fadeDuration == 0L) {
47 | view.setImageBitmap(it)
48 | return@let
49 | }
50 |
51 | val fadeOut = animateAlpha(view, 1f, 0f, fadeDuration, autoPlay = false, listener = fadeOutEndListener(view, result))
52 | val fadeIn = animateAlpha(view, 0f, 1f, fadeDuration, autoPlay = false)
53 |
54 | val animators = AnimatorSet()
55 | animators.playSequentially(fadeOut, fadeIn)
56 | animators.start()
57 | }
58 | }
59 |
60 | private fun fadeOutEndListener(view: ImageView, result: Bitmap): AnimatorListenerAdapter = object : AnimatorListenerAdapter() {
61 | override fun onAnimationEnd(animation: Animator?) {
62 | view.setImageBitmap(result)
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/tools/Utils.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.tools
2 |
3 | import android.animation.Animator
4 | import android.animation.ObjectAnimator
5 | import android.content.Context
6 | import android.graphics.Bitmap
7 | import android.media.MediaMetadataRetriever
8 | import android.view.View
9 | import android.view.animation.Interpolator
10 | import android.view.animation.LinearInterpolator
11 | import kotlin.math.max
12 | import kotlin.math.roundToInt
13 |
14 | internal fun dpToPx(context: Context, dp: Float): Float {
15 | val density = context.resources.displayMetrics.density
16 | return dp * density
17 | }
18 |
19 | internal fun scaleBitmap(bitmap: Bitmap, size: Int): Bitmap {
20 | val width = bitmap.width
21 | val height = bitmap.height
22 | val max = max(width, height)
23 |
24 | return if (max > size) {
25 | val scale = size.toFloat() / max
26 | val scaledWidth = (width * scale).roundToInt()
27 | val scaledHeight = (height * scale).roundToInt()
28 | Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true)
29 | } else bitmap
30 | }
31 |
32 | internal fun animateAlpha(
33 | view: View,
34 | from: Float = view.alpha,
35 | to: Float,
36 | duration: Long,
37 | interpolator: Interpolator = LinearInterpolator(),
38 | listener: Animator.AnimatorListener? = null,
39 | repeatMode: Int? = null,
40 | repeatCount: Int = 0,
41 | autoPlay: Boolean = true
42 | ): Animator = ObjectAnimator.ofFloat(view, "alpha", from, to).apply {
43 | this.duration = duration
44 | this.interpolator = interpolator
45 | listener?.let { this.addListener(it) }
46 |
47 | repeatMode?.let { mode ->
48 | this.repeatMode = mode
49 | this.repeatCount = repeatCount
50 | }
51 |
52 | if (autoPlay) {
53 | start()
54 | }
55 | }
56 |
57 | internal fun extractVideoLength(videoPath: String): Long {
58 | val retriever = try {
59 | MediaMetadataRetriever()
60 | .apply { setDataSource(videoPath) }
61 | } catch (e: IllegalArgumentException) {
62 | return 0L
63 | }
64 |
65 | val length = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
66 | retriever.release()
67 |
68 | return length?.toLong() ?: 0L
69 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/videoframe/VideoFramesAdaptor.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.videoframe
2 |
3 | import android.os.AsyncTask
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import android.view.ViewGroup.LayoutParams.MATCH_PARENT
7 | import android.widget.ImageView
8 | import androidx.recyclerview.widget.RecyclerView
9 | import idv.luchafang.videotrimmer.tools.SetVideoThumbnailAsyncTask
10 | import java.io.File
11 |
12 | internal class VideoFramesAdaptor(
13 | private val video: File,
14 | private val frames: List,
15 | private val frameWidth: Int
16 | ) : RecyclerView.Adapter() {
17 |
18 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
19 | val imageView = ImageView(parent.context).apply {
20 | layoutParams = ViewGroup.LayoutParams(frameWidth, MATCH_PARENT)
21 | scaleType = ImageView.ScaleType.CENTER_CROP
22 | }
23 |
24 | return ViewHolder(imageView)
25 | }
26 |
27 | override fun onBindViewHolder(holder: ViewHolder, position: Int) {
28 | val view = holder.itemView as ImageView
29 | val frame = frames[position]
30 |
31 | SetVideoThumbnailAsyncTask(view, frame)
32 | .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, video)
33 | }
34 |
35 | override fun getItemCount(): Int = frames.size
36 |
37 | class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
38 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/videoframe/VideoFramesDecoration.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.videoframe
2 |
3 | import android.graphics.Canvas
4 | import android.graphics.Paint
5 | import android.graphics.Rect
6 | import android.view.View
7 | import androidx.annotation.ColorInt
8 | import androidx.recyclerview.widget.LinearLayoutManager
9 | import androidx.recyclerview.widget.RecyclerView
10 |
11 | internal class VideoFramesDecoration(
12 | private val horizontalMargin: Int,
13 | @ColorInt private val overlayColor: Int
14 | ) : RecyclerView.ItemDecoration() {
15 |
16 | private val overlayPaint = Paint().apply {
17 | color = overlayColor
18 | isAntiAlias = true
19 | }
20 |
21 | /* -------------------------------------------------------------------------------------------*/
22 | /* ItemDecoration */
23 | override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
24 | super.getItemOffsets(outRect, view, parent, state)
25 |
26 | val adaptor = parent.adapter ?: return
27 | when (parent.getChildAdapterPosition(view)) {
28 | 0 ->
29 | outRect.left = horizontalMargin
30 | adaptor.itemCount - 1 ->
31 | outRect.right = horizontalMargin
32 | }
33 | }
34 |
35 | override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
36 | super.onDraw(canvas, parent, state)
37 |
38 | val layoutManager = parent.layoutManager as? LinearLayoutManager ?: return
39 | drawStartOverlay(canvas, parent, layoutManager)
40 | drawEndOverlay(canvas, parent, layoutManager)
41 | }
42 |
43 | /* -------------------------------------------------------------------------------------------*/
44 | /* Draw */
45 | private fun drawStartOverlay(canvas: Canvas, parent: RecyclerView, layoutManager: LinearLayoutManager) {
46 | val firstViewPos = layoutManager.findFirstVisibleItemPosition()
47 | val firstView = layoutManager.findViewByPosition(firstViewPos) ?: return
48 |
49 | val start = firstView.left
50 | val end = horizontalMargin
51 |
52 | drawOverlay(canvas, parent, start.toFloat(), end.toFloat())
53 | }
54 |
55 | private fun drawEndOverlay(canvas: Canvas, parent: RecyclerView, layoutManager: LinearLayoutManager) {
56 | val lastViewPos = layoutManager.findLastVisibleItemPosition()
57 | val lastView = layoutManager.findViewByPosition(lastViewPos) ?: return
58 |
59 | val start = parent.width - horizontalMargin
60 | val end = lastView.right
61 |
62 | drawOverlay(canvas, parent, start.toFloat(), end.toFloat())
63 | }
64 |
65 | private fun drawOverlay(canvas: Canvas, parent: RecyclerView, start: Float, end: Float) {
66 | if (end > start) {
67 | canvas.drawRect(
68 | start,
69 | parent.paddingTop.toFloat(),
70 | end,
71 | parent.height.toFloat() - parent.paddingBottom,
72 | overlayPaint
73 | )
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/java/idv/luchafang/videotrimmer/videoframe/VideoFramesScrollListener.kt:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer.videoframe
2 |
3 | import androidx.recyclerview.widget.LinearLayoutManager
4 | import androidx.recyclerview.widget.RecyclerView
5 |
6 | internal class VideoFramesScrollListener(
7 | private val horizontalMargin: Int,
8 | private val callback: Callback
9 | ) : RecyclerView.OnScrollListener() {
10 |
11 | private var isIdle = true
12 |
13 | override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
14 | super.onScrolled(recyclerView, dx, dy)
15 |
16 | val adaptor = recyclerView.adapter ?: return
17 | val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return
18 | val itemWidth = recyclerView.getChildAt(0)?.width ?: return
19 |
20 | val firstViewPos = layoutManager.findFirstCompletelyVisibleItemPosition()
21 | val firstView = layoutManager.findViewByPosition(firstViewPos) ?: return
22 |
23 | val offset = horizontalMargin + firstViewPos * itemWidth - firstView.left
24 | val contentWidth = itemWidth * adaptor.itemCount
25 |
26 | callback.onScrollVideoFrames(
27 | offset / contentWidth.toFloat(),
28 | firstViewPos,
29 | firstView.left
30 | )
31 | }
32 |
33 | override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
34 | super.onScrollStateChanged(recyclerView, newState)
35 |
36 | when (newState) {
37 | RecyclerView.SCROLL_STATE_IDLE -> {
38 | isIdle = true
39 | callback.onScrollVideoFramesEnd()
40 | }
41 |
42 | RecyclerView.SCROLL_STATE_DRAGGING -> {
43 | if (isIdle) {
44 | callback.onScrollVideoFramesStart()
45 | isIdle = false
46 | }
47 | }
48 | }
49 | }
50 |
51 | interface Callback {
52 | fun onScrollVideoFramesStart()
53 | fun onScrollVideoFrames(offsetPercentage: Float, framePosition: Int, frameOffset: Int)
54 | fun onScrollVideoFramesEnd()
55 | }
56 | }
--------------------------------------------------------------------------------
/videotrimmer/src/main/res/drawable/trimmer_left_bar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | -
5 |
6 |
7 |
10 |
13 |
14 |
15 |
16 | -
17 |
18 |
19 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/videotrimmer/src/main/res/drawable/trimmer_right_bar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | -
5 |
6 |
7 |
10 |
13 |
14 |
15 |
16 | -
17 |
18 |
19 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/videotrimmer/src/main/res/layout/layout_video_trimmer.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
22 |
23 |
33 |
34 |
--------------------------------------------------------------------------------
/videotrimmer/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/videotrimmer/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | videotrimmer
3 |
4 |
--------------------------------------------------------------------------------
/videotrimmer/src/test/java/idv/luchafang/videotrimmer/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package idv.luchafang.videotrimmer;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------