├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── NOTICE ├── README.md ├── build.gradle ├── example ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── net │ │ └── ypresto │ │ └── androidtranscoder │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── net │ │ └── ypresto │ │ └── androidtranscoder │ │ └── example │ │ └── TranscoderActivity.java │ └── res │ ├── drawable-hdpi │ └── ic_launcher.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-xhdpi │ └── ic_launcher.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── layout │ └── activity_transcoder.xml │ ├── menu │ └── transcoder.xml │ ├── values-w820dp │ └── dimens.xml │ ├── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml │ └── xml │ └── file_paths.xml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lib ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── net │ │ └── ypresto │ │ └── androidtranscoder │ │ ├── ApplicationTest.java │ │ ├── format │ │ └── MediaFormatPresetsTest.java │ │ └── utils │ │ └── ISO6709LocationParserTest.java │ └── main │ ├── AndroidManifest.xml │ └── java │ └── net │ └── ypresto │ └── androidtranscoder │ ├── MediaTranscoder.java │ ├── compat │ ├── MediaCodecBufferCompatWrapper.java │ └── MediaCodecListCompat.java │ ├── engine │ ├── AudioChannel.java │ ├── AudioRemixer.java │ ├── AudioTrackTranscoder.java │ ├── InputSurface.java │ ├── InvalidOutputFormatException.java │ ├── MediaFormatValidator.java │ ├── MediaTranscoderEngine.java │ ├── OutputSurface.java │ ├── PassThroughTrackTranscoder.java │ ├── QueuedMuxer.java │ ├── TextureRender.java │ ├── TrackTranscoder.java │ └── VideoTrackTranscoder.java │ ├── format │ ├── Android16By9FormatStrategy.java │ ├── Android720pFormatStrategy.java │ ├── ExportPreset960x540Strategy.java │ ├── MediaFormatExtraConstants.java │ ├── MediaFormatPresets.java │ ├── MediaFormatStrategy.java │ ├── MediaFormatStrategyPresets.java │ └── OutputFormatUnavailableException.java │ └── utils │ ├── AvcCsdUtils.java │ ├── AvcSpsUtils.java │ ├── ISO6709LocationParser.java │ └── MediaExtractorUtils.java ├── script ├── add-header.sh └── header.txt └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea 4 | .DS_Store 5 | /build 6 | *.iml 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.3.0 2 | - Fix cancel() sometimes not working. (Thanks @strayerM and @PinkFloyded) 3 | - Geolocation support on API>=19. (Thanks @hkurokawa) 4 | 5 | ## 0.2.0 6 | - Experimental audio transcoding support. (Thanks @aaron112) 7 | - Fix transcode does not run on Huawei Ascend P7. (Thanks @spiritedRunning) 8 | - Fix race condition caused by not closing output before callback. (Thanks @ryanwilliams83) 9 | 10 | ## 0.1.10 11 | - `Future` support. (Thanks @MaiKambayashi) 12 | 13 | ## 0.1.X 14 | - Stability updates. (Thanks @ozyozyo) 15 | 16 | ## 0.1.0 17 | - First release. 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | android-transcoder 2 | Copyright (C) 2014-2015 Yuya Tanaka 3 | 4 | This product includes software developed by 5 | Yuya Tanaka (http://ypresto.net/). 6 | 7 | This software contains code derived from 8 | Android Compatibility Test Suite 9 | (https://android.googlesource.com/platform/cts/), which is developed by 10 | The Android Open Source Project (https://source.android.com/) and 11 | is available under a "Apache License 2.0". 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | android-transcoder 2 | ================= 3 | 4 | Hardware accelerated transcoder for Android, written in pure Java. 5 | 6 | ## Why? 7 | 8 | Android does not offer straight forward way to transcode video. 9 | 10 | FFmpeg is the most famous solution for transcoding. But using [FFmpeg binary on Android](https://github.com/WritingMinds/ffmpeg-android) can cause GPL and/or patent issues. Also using native code for Android development can be troublesome because of cross-compiling, architecture compatibility, build time and binary size. 11 | 12 | To transcode without any hassle written above, I created this library to provide hardware accelerated transcoding of H.264 (mp4) video without ffmpeg by using [MediaCodec](https://developer.android.com/intl/ja/reference/android/media/MediaCodec.html). 13 | 14 | ## Requirements 15 | 16 | API Level 18 (Android 4.3, JELLY_BEAN_MR2) or later. 17 | If your app targets older Android, you should add below line to AndroidManifest.xml: 18 | 19 | ```xml 20 | 21 | 22 | ``` 23 | 24 | Please ensure checking Build.VERSION by your self. 25 | 26 | ## Usage 27 | 28 | ```java 29 | @Override 30 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 31 | ParcelFileDescriptor parcelFileDescriptor = resolver.openFileDescriptor(data.getData(), "r"); 32 | FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); 33 | MediaTranscoder.Listener listener = new MediaTranscoder.Listener() { 34 | @Override 35 | public void onTranscodeProgress(double progress) { 36 | ... 37 | } 38 | 39 | @Override 40 | public void onTranscodeCompleted() { 41 | startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file), "video/mp4")); 42 | ... 43 | } 44 | 45 | @Override 46 | public void onTranscodeFailed(Exception exception) { 47 | ... 48 | } 49 | }; 50 | MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), 51 | MediaFormatStrategyPresets.createAndroid720pStrategy(), listener); // or createAndroid720pStrategy([your bitrate here]) 52 | } 53 | ``` 54 | 55 | See `TranscoderActivity.java` in example directory for ready-made transcoder app. 56 | 57 | ## Quick Setup 58 | 59 | ### Gradle 60 | 61 | Available from [JCenter](https://bintray.com/bintray/jcenter), which is default repo of gradle script generated by recent android studio. 62 | 63 | ```groovy 64 | repositories { 65 | jcenter() 66 | } 67 | ``` 68 | 69 | ```groovy 70 | compile 'net.ypresto.androidtranscoder:android-transcoder:0.2.0' 71 | ``` 72 | 73 | ## Note (PLEASE READ FIRST) 74 | 75 | - This library raises `RuntimeException`s (like `IlleagalStateException`) in various situations. Please catch it and provide alternate logics. I know this is bad design according to Effective Java; just is TODO. 76 | - Currently this library does not generate streaming-aware mp4 file. 77 | Use [qtfaststart-java](https://github.com/ypresto/qtfaststart-java) to place moov atom at beginning of file. 78 | - Android does not gurantees that all devices have bug-free codecs/accelerators for your codec parameters (especially, resolution). Refer [supported media formats](http://developer.android.com/guide/appendix/media-formats.html) for parameters guaranteed by [CTS](https://source.android.com/compatibility/cts-intro.html). 79 | - This library does not support video files recorded by other device like digital cameras, iOS (mov files, including non-baseline profile h.264), etc. 80 | 81 | 82 | ## More information about internals 83 | 84 | Seungwon Lee created awesome slide which describes this (and derived) library. 85 | https://speakerdeck.com/line_devday2019/looking-for-a-silver-bullet-to-edit-videos-on-android 86 | 87 | Also there is a blog post about this library written in Japanese. While it is Japanese, diagrams would be useful for understanding internals of this library. 88 | http://qiita.com/yuya_presto/items/d48e29c89109b746d000 89 | 90 | ## References for Android Low-Level Media APIs 91 | 92 | - http://bigflake.com/mediacodec/ 93 | - https://github.com/google/grafika 94 | - https://android.googlesource.com/platform/frameworks/av/+/lollipop-release/media/libstagefright 95 | 96 | ## License 97 | 98 | ``` 99 | Copyright (C) 2014-2016 Yuya Tanaka 100 | 101 | Licensed under the Apache License, Version 2.0 (the "License"); 102 | you may not use this file except in compliance with the License. 103 | You may obtain a copy of the License at 104 | 105 | http://www.apache.org/licenses/LICENSE-2.0 106 | 107 | Unless required by applicable law or agreed to in writing, software 108 | distributed under the License is distributed on an "AS IS" BASIS, 109 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 110 | See the License for the specific language governing permissions and 111 | limitations under the License. 112 | ``` 113 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | maven { 7 | url 'https://maven.google.com/' 8 | name 'Google' 9 | } 10 | } 11 | dependencies { 12 | classpath 'com.android.tools.build:gradle:2.3.3' 13 | 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | jcenter() 22 | maven { 23 | url 'https://maven.google.com/' 24 | name 'Google' 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /example/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion '25.0.0' 6 | 7 | defaultConfig { 8 | applicationId "net.ypresto.androidtranscoder.example" 9 | minSdkVersion 18 10 | targetSdkVersion 24 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile project(':lib') 24 | compile 'com.android.support:support-core-utils:24.2.0' 25 | } 26 | -------------------------------------------------------------------------------- /example/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/yuya.tanaka/devel/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /example/src/androidTest/java/net/ypresto/androidtranscoder/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package net.ypresto.androidtranscoder; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 9 | 14 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 29 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /example/src/main/java/net/ypresto/androidtranscoder/example/TranscoderActivity.java: -------------------------------------------------------------------------------- 1 | package net.ypresto.androidtranscoder.example; 2 | 3 | import android.app.Activity; 4 | import android.content.ContentResolver; 5 | import android.content.Intent; 6 | import android.net.Uri; 7 | import android.os.Bundle; 8 | import android.os.ParcelFileDescriptor; 9 | import android.os.SystemClock; 10 | import android.support.v4.content.FileProvider; 11 | import android.util.Log; 12 | import android.view.Menu; 13 | import android.view.MenuItem; 14 | import android.view.View; 15 | import android.widget.ProgressBar; 16 | import android.widget.Toast; 17 | 18 | import net.ypresto.androidtranscoder.MediaTranscoder; 19 | import net.ypresto.androidtranscoder.format.MediaFormatStrategyPresets; 20 | 21 | import java.io.File; 22 | import java.io.FileDescriptor; 23 | import java.io.FileNotFoundException; 24 | import java.io.IOException; 25 | import java.util.concurrent.Future; 26 | 27 | 28 | public class TranscoderActivity extends Activity { 29 | private static final String TAG = "TranscoderActivity"; 30 | private static final String FILE_PROVIDER_AUTHORITY = "net.ypresto.androidtranscoder.example.fileprovider"; 31 | private static final int REQUEST_CODE_PICK = 1; 32 | private static final int PROGRESS_BAR_MAX = 1000; 33 | private Future mFuture; 34 | 35 | @Override 36 | protected void onCreate(Bundle savedInstanceState) { 37 | super.onCreate(savedInstanceState); 38 | setContentView(R.layout.activity_transcoder); 39 | findViewById(R.id.select_video_button).setOnClickListener(new View.OnClickListener() { 40 | @Override 41 | public void onClick(View v) { 42 | startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("video/*"), REQUEST_CODE_PICK); 43 | } 44 | }); 45 | findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() { 46 | @Override 47 | public void onClick(View view) { 48 | mFuture.cancel(true); 49 | } 50 | }); 51 | } 52 | 53 | @Override 54 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 55 | switch (requestCode) { 56 | case REQUEST_CODE_PICK: { 57 | final File file; 58 | if (resultCode == RESULT_OK) { 59 | try { 60 | File outputDir = new File(getExternalFilesDir(null), "outputs"); 61 | //noinspection ResultOfMethodCallIgnored 62 | outputDir.mkdir(); 63 | file = File.createTempFile("transcode_test", ".mp4", outputDir); 64 | } catch (IOException e) { 65 | Log.e(TAG, "Failed to create temporary file.", e); 66 | Toast.makeText(this, "Failed to create temporary file.", Toast.LENGTH_LONG).show(); 67 | return; 68 | } 69 | ContentResolver resolver = getContentResolver(); 70 | final ParcelFileDescriptor parcelFileDescriptor; 71 | try { 72 | parcelFileDescriptor = resolver.openFileDescriptor(data.getData(), "r"); 73 | } catch (FileNotFoundException e) { 74 | Log.w("Could not open '" + data.getDataString() + "'", e); 75 | Toast.makeText(TranscoderActivity.this, "File not found.", Toast.LENGTH_LONG).show(); 76 | return; 77 | } 78 | final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); 79 | final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar); 80 | progressBar.setMax(PROGRESS_BAR_MAX); 81 | final long startTime = SystemClock.uptimeMillis(); 82 | MediaTranscoder.Listener listener = new MediaTranscoder.Listener() { 83 | @Override 84 | public void onTranscodeProgress(double progress) { 85 | if (progress < 0) { 86 | progressBar.setIndeterminate(true); 87 | } else { 88 | progressBar.setIndeterminate(false); 89 | progressBar.setProgress((int) Math.round(progress * PROGRESS_BAR_MAX)); 90 | } 91 | } 92 | 93 | @Override 94 | public void onTranscodeCompleted() { 95 | Log.d(TAG, "transcoding took " + (SystemClock.uptimeMillis() - startTime) + "ms"); 96 | onTranscodeFinished(true, "transcoded file placed on " + file, parcelFileDescriptor); 97 | Uri uri = FileProvider.getUriForFile(TranscoderActivity.this, FILE_PROVIDER_AUTHORITY, file); 98 | startActivity(new Intent(Intent.ACTION_VIEW) 99 | .setDataAndType(uri, "video/mp4") 100 | .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)); 101 | } 102 | 103 | @Override 104 | public void onTranscodeCanceled() { 105 | onTranscodeFinished(false, "Transcoder canceled.", parcelFileDescriptor); 106 | } 107 | 108 | @Override 109 | public void onTranscodeFailed(Exception exception) { 110 | onTranscodeFinished(false, "Transcoder error occurred.", parcelFileDescriptor); 111 | } 112 | }; 113 | Log.d(TAG, "transcoding into " + file); 114 | mFuture = MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), 115 | MediaFormatStrategyPresets.createAndroid720pStrategy(8000 * 1000, 128 * 1000, 1), listener); 116 | switchButtonEnabled(true); 117 | } 118 | break; 119 | } 120 | default: 121 | super.onActivityResult(requestCode, resultCode, data); 122 | } 123 | } 124 | 125 | @Override 126 | public boolean onCreateOptionsMenu(Menu menu) { 127 | // Inflate the menu; this adds items to the action bar if it is present. 128 | getMenuInflater().inflate(R.menu.transcoder, menu); 129 | return true; 130 | } 131 | 132 | @Override 133 | public boolean onOptionsItemSelected(MenuItem item) { 134 | // Handle action bar item clicks here. The action bar will 135 | // automatically handle clicks on the Home/Up button, so long 136 | // as you specify a parent activity in AndroidManifest.xml. 137 | int id = item.getItemId(); 138 | if (id == R.id.action_settings) { 139 | return true; 140 | } 141 | return super.onOptionsItemSelected(item); 142 | } 143 | 144 | private void onTranscodeFinished(boolean isSuccess, String toastMessage, ParcelFileDescriptor parcelFileDescriptor) { 145 | final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar); 146 | progressBar.setIndeterminate(false); 147 | progressBar.setProgress(isSuccess ? PROGRESS_BAR_MAX : 0); 148 | switchButtonEnabled(false); 149 | Toast.makeText(TranscoderActivity.this, toastMessage, Toast.LENGTH_LONG).show(); 150 | try { 151 | parcelFileDescriptor.close(); 152 | } catch (IOException e) { 153 | Log.w("Error while closing", e); 154 | } 155 | } 156 | 157 | private void switchButtonEnabled(boolean isProgress) { 158 | findViewById(R.id.select_video_button).setEnabled(!isProgress); 159 | findViewById(R.id.cancel_button).setEnabled(isProgress); 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /example/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ypresto/android-transcoder/41068f51b26a28557bcaf55c3e3112f1d9f19d46/example/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ypresto/android-transcoder/41068f51b26a28557bcaf55c3e3112f1d9f19d46/example/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ypresto/android-transcoder/41068f51b26a28557bcaf55c3e3112f1d9f19d46/example/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ypresto/android-transcoder/41068f51b26a28557bcaf55c3e3112f1d9f19d46/example/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/src/main/res/layout/activity_transcoder.xml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 17 | 18 |