Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.appzzdd.searchmusic.converter;
- import android.app.Activity;
- import android.app.Application;
- import android.content.Context;
- import android.content.pm.PackageInfo;
- import android.content.pm.PackageManager;
- import android.net.Uri;
- import android.os.Environment;
- import androidx.annotation.NonNull;
- import androidx.documentfile.provider.DocumentFile;
- import com.appzzdd.searchmusic.ApplicationPrefrences;
- import com.appzzdd.searchmusic.R;
- import com.appzzdd.searchmusic.converter.libffmpeg.CpuArchHelper;
- import com.appzzdd.searchmusic.utils.Constants;
- import com.appzzdd.searchmusic.CustomApplication;
- import com.appzzdd.searchmusic.converter.encoder.AbstractEncoder;
- import com.appzzdd.searchmusic.converter.encoder.MP3Encoder;
- import com.appzzdd.searchmusic.converter.libffmpeg.CommandResult;
- import com.appzzdd.searchmusic.converter.libffmpeg.FFmpeg;
- import com.appzzdd.searchmusic.converter.libffmpeg.MultimediaFramework;
- import com.appzzdd.searchmusic.utils.Data;
- import com.google.android.exoplayer2.extractor.mp4.Track;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.Locale;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class AudioConverter {
- protected File audioFile;
- @NonNull
- protected CustomApplication context;
- protected ProgressCallback processCallback;
- @NonNull
- protected AbstractEncoder encoder;
- protected String outputFolder;
- protected String outputFilename;
- protected boolean removeOriginalFileAfterConversion = false;
- protected Track track;
- /*Callback from native code for set progress to UI progressbar*/
- public void setProgress(int progress) {
- setProgress(progress, null);
- }
- public void setProgress(int progress, String message){
- //Log.e("TAG 2", "progress " + progress);
- if(processCallback != null) {
- processCallback.onProgress(progress, message);
- }
- }
- static {
- System.loadLibrary("transcode");
- }
- public native String transcode(String path, int quality, String library, String container, String output, int duration);
- public AudioConverter() {
- this.context = CustomApplication.getApplicationInstance();
- this.encoder = new MP3Encoder(); //by default convert to mp3
- }
- public void setTrack( Track track ){
- this.track = track;
- }
- public void removeOriginalFileAfterConversion(boolean remove) {
- removeOriginalFileAfterConversion = remove;
- }
- public AudioConverter setFFmpegCallback(ProgressCallback callback) {
- this.processCallback = callback;
- return this;
- }
- public AudioConverter setFormat() {
- encoder = new MP3Encoder();
- return this;
- }
- public AudioConverter setMP3EncoderLib(String lib) {
- if (isMP3EncoderInit()) {
- encoder.setLibrary(lib);
- }
- return this;
- }
- public AudioConverter setOutputFilename(@NonNull String filename) {
- if (!filename.isEmpty()) {
- if (!filename.endsWith(getExtension())) {
- filename += "." + getExtension();
- }
- this.outputFilename = filename;
- }
- return this;
- }
- public AudioConverter setOutputFolder(String folder) {
- this.outputFolder = folder;
- return this;
- }
- public String getMP3EncoderLib() {
- return encoder.getLibrary();
- }
- /**
- * need for init encoder library spinner (only need for mp3)
- *
- * @return if encoder is MP3encoder
- */
- public boolean isMP3EncoderInit() {
- return encoder.ID == MP3Encoder.ID;
- }
- /**
- * method for start convert by included parameters
- */
- public CommandResult convert(File af) {
- audioFile = af;
- CommandResult result = new CommandResult();
- String errorMessage = isValidInputData(audioFile);
- try {
- if (errorMessage == null) {
- result = startConversion();
- } else {
- result.message = errorMessage;
- }
- } catch (Exception e) {
- e.printStackTrace();
- result.message = e.getMessage();
- }
- return result;
- }
- private String isValidInputData(File audioFile) {
- if (audioFile == null || !audioFile.exists())
- return "FILE DOESN'T EXISTS";
- if (!audioFile.canRead())
- return "FILE IS NOT READABLE";
- if (outputFolder == null || outputFolder.isEmpty())
- return "WRONG OUTPUT FOLDER";
- if (outputFilename == null || outputFilename.isEmpty())
- return "WRONG OUTPUT FILE";
- return null;
- }
- private File getConvertedFile(String outputFilename) {
- String rootDirectory = getApplicationRootDirectory();
- if (rootDirectory == null) {
- return null;
- }
- String filePath = rootDirectory + Constants.getInstance().PATH_DELIMITER + outputFilename;
- return new File(filePath);
- }
- private String getApplicationRootDirectory() {
- PackageManager packageManager = context.getPackageManager();
- String packageName = context.getPackageName();
- try {
- PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
- return packageInfo.applicationInfo.dataDir;
- } catch (PackageManager.NameNotFoundException e) {
- e.printStackTrace();
- }
- return null;
- }
- private DocumentFile getDocumentFileFromTree(String path) {
- try {
- String[] paths = path.split(Constants.getInstance().PATH_DELIMITER);
- Uri treeUri = Uri.parse(ApplicationPrefrences.getInstance().getTreeUri());
- DocumentFile root = DocumentFile.fromTreeUri(context, treeUri);
- for (String s : paths) {
- DocumentFile tempDoc = root.findFile(s);
- if (tempDoc != null) {
- if (tempDoc.isDirectory()) {
- root = tempDoc;
- } else if (tempDoc.isFile()) {
- return tempDoc;
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- public String getExtension() {
- return encoder.getExtension();
- }
- public void debugLog() {
- }
- protected CommandResult startConversion() {
- CommandResult result = new CommandResult();
- String outputPath = outputFolder + outputFilename;
- if (audioFile.getAbsolutePath().equals(outputPath) || new File(outputPath).exists()) {
- int i = 1;
- Pattern pattern = Pattern.compile("(^\\(\\d+\\))");
- Matcher matcher = pattern.matcher(outputFilename);
- if(matcher.find()){
- try{
- String s = matcher.group(1);
- int length = s.length();
- i = Integer.parseInt(s.substring(1, length-1));
- i++;
- outputFilename = outputFilename.substring(length);
- }catch (Exception e){
- }
- }
- File f = new File(outputFolder + "(" + i + ")" + outputFilename);
- while(f.exists()){
- i++;
- f = new File(outputFolder + "(" + i + ")" + outputFilename);
- }
- outputPath = f.getPath();
- }
- String tempOutputPath = outputPath;
- if (!outputPath.contains(Constants.getInstance().INTERNAL_STORAGE_FOLDER)) {
- tempOutputPath = context.getCacheDir() + "/" + outputFilename;
- }
- long sessionId = System.currentTimeMillis();
- /*
- long size = audioFile.length();
- String msg = "abi: " + new CpuArchHelper().getCpuArch() +
- ", original_path: " + audioFile.getPath() + ", destination_path: " + outputPath +
- ", temp_path: " + tempOutputPath + ", encoder: " + encoder.getExtension() +
- ", quality: " + encoder.getQuality() + ", library: " + encoder.getLibrary() + ", filesize: " + size;
- if ( size==10000000 ){
- msg+= " ?1?1?:"+track.getPath();
- } else if ( size<1024 ) {
- msg += " ?2?2?:" + track.getPath();
- try{
- FileReader reader = new FileReader(audioFile);
- char[] charBuffer = new char[(int)size];
- reader.read(charBuffer);
- String s = new String(charBuffer);
- msg+="\n"+s;
- } catch (Exception e){
- }
- }
- */
- long size = audioFile.length();
- String msg = "abi: " + new CpuArchHelper().getCpuArch() +
- ", original_path: " + audioFile.getPath() + ", destination_path: " + outputPath +
- ", encoder: " + encoder.getExtension() +
- ", library: " + encoder.getLibrary() + ", filesize: " + size;
- if ( size==10000000 ){
- msg+= " ?1?1?:"+audioFile.getPath();
- } else if ( size<1024 ) {
- msg += " ?2?2?:" + audioFile.getPath();
- try{
- FileReader reader = new FileReader(audioFile);
- char[] charBuffer = new char[(int)size];
- reader.read(charBuffer);
- String s = new String(charBuffer);
- msg+="\n"+s;
- } catch (Exception e){
- }
- }
- String res = transcode(audioFile.getPath(), encoder.getMinQuality(), encoder.getLibrary(), encoder.getExtension(), tempOutputPath, -1);
- try {
- String[] ss = res.split("__,__");
- result.commandResult = Integer.parseInt(ss[0]) >= 0 ? CommandResult.COMMAND_SUCCEDED : CommandResult.COMMAND_FAILED;
- result.message = ss[1];
- if (result.commandResult < 0) {
- if ( result.message==null )
- result.message = "";
- result.message += ", " + msg;
- } else {
- if (!outputPath.contains(Constants.getInstance().INTERNAL_STORAGE_FOLDER)) {
- Activity a = context.getCurrentActivity();
- Context c = a==null?context:a;
- setProgress(100, "");
- String reservePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/" + outputFilename;
- DocumentFile df = getDocumentFileFromTree(outputPath);
- if (df != null) {
- DocumentFile df2 = null;
- if (df.isDirectory()) {
- df2 = df.createFile(Constants.getInstance().AUDIO_TYPE, Data.getFileNameFromPath(outputPath, null));
- }
- if (copy(new File(tempOutputPath), df2 != null ? df2 : df, null) > 0) {
- result.message = outputPath;
- } else if (copy(new File(tempOutputPath), null, new File(reservePath)) > 0) {
- result.message = reservePath;
- } else {
- result.commandResult = CommandResult.COMMAND_FAILED;
- result.message = "PERMISSION DENIED";
- }
- } else {
- if (copy(new File(tempOutputPath), null, new File(reservePath)) > 0) {
- result.message = reservePath;
- } else {
- result.commandResult = CommandResult.COMMAND_FAILED;
- result.message = "PERMISSION DENIED";
- }
- }
- }
- if (removeOriginalFileAfterConversion)
- audioFile.delete();
- outputFilename = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- public int copy(File src, DocumentFile documentFile, File dst) throws IOException {
- int result = -1;
- InputStream in = new FileInputStream(src);
- try {
- OutputStream out = null;
- if (documentFile != null) {
- out = CustomApplication.getApplicationInstance().getContentResolver().openOutputStream(documentFile.getUri());
- } else if (dst != null) {
- out = new FileOutputStream(dst);
- }
- if (out != null) {
- try {
- byte[] buf = new byte[1024];
- int len;
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- }
- result = 1;
- } finally {
- out.close();
- }
- }
- } finally {
- in.close();
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement