Advertisement
rokney

Untitled

Feb 19th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.27 KB | None | 0 0
  1. package com.appzzdd.searchmusic.converter;
  2.  
  3. import android.app.Activity;
  4. import android.app.Application;
  5. import android.content.Context;
  6. import android.content.pm.PackageInfo;
  7. import android.content.pm.PackageManager;
  8. import android.net.Uri;
  9. import android.os.Environment;
  10.  
  11. import androidx.annotation.NonNull;
  12. import androidx.documentfile.provider.DocumentFile;
  13.  
  14. import com.appzzdd.searchmusic.ApplicationPrefrences;
  15. import com.appzzdd.searchmusic.R;
  16. import com.appzzdd.searchmusic.converter.libffmpeg.CpuArchHelper;
  17. import com.appzzdd.searchmusic.utils.Constants;
  18. import com.appzzdd.searchmusic.CustomApplication;
  19. import com.appzzdd.searchmusic.converter.encoder.AbstractEncoder;
  20. import com.appzzdd.searchmusic.converter.encoder.MP3Encoder;
  21. import com.appzzdd.searchmusic.converter.libffmpeg.CommandResult;
  22. import com.appzzdd.searchmusic.converter.libffmpeg.FFmpeg;
  23. import com.appzzdd.searchmusic.converter.libffmpeg.MultimediaFramework;
  24. import com.appzzdd.searchmusic.utils.Data;
  25. import com.google.android.exoplayer2.extractor.mp4.Track;
  26.  
  27. import java.io.File;
  28. import java.io.FileInputStream;
  29. import java.io.FileOutputStream;
  30. import java.io.FileReader;
  31. import java.io.IOException;
  32. import java.io.InputStream;
  33. import java.io.OutputStream;
  34. import java.text.SimpleDateFormat;
  35. import java.util.ArrayList;
  36. import java.util.Arrays;
  37. import java.util.Date;
  38. import java.util.Locale;
  39. import java.util.regex.Matcher;
  40. import java.util.regex.Pattern;
  41.  
  42.  
  43. public class AudioConverter {
  44.  
  45. protected File audioFile;
  46.  
  47. @NonNull
  48. protected CustomApplication context;
  49.  
  50. protected ProgressCallback processCallback;
  51.  
  52. @NonNull
  53. protected AbstractEncoder encoder;
  54.  
  55. protected String outputFolder;
  56. protected String outputFilename;
  57.  
  58. protected boolean removeOriginalFileAfterConversion = false;
  59.  
  60. protected Track track;
  61.  
  62. /*Callback from native code for set progress to UI progressbar*/
  63. public void setProgress(int progress) {
  64. setProgress(progress, null);
  65. }
  66.  
  67. public void setProgress(int progress, String message){
  68. //Log.e("TAG 2", "progress " + progress);
  69. if(processCallback != null) {
  70. processCallback.onProgress(progress, message);
  71. }
  72. }
  73.  
  74. static {
  75. System.loadLibrary("transcode");
  76. }
  77.  
  78. public native String transcode(String path, int quality, String library, String container, String output, int duration);
  79.  
  80.  
  81. public AudioConverter() {
  82. this.context = CustomApplication.getApplicationInstance();
  83. this.encoder = new MP3Encoder(); //by default convert to mp3
  84. }
  85.  
  86. public void setTrack( Track track ){
  87. this.track = track;
  88. }
  89.  
  90. public void removeOriginalFileAfterConversion(boolean remove) {
  91. removeOriginalFileAfterConversion = remove;
  92. }
  93.  
  94. public AudioConverter setFFmpegCallback(ProgressCallback callback) {
  95. this.processCallback = callback;
  96. return this;
  97. }
  98.  
  99. public AudioConverter setFormat() {
  100. encoder = new MP3Encoder();
  101. return this;
  102. }
  103.  
  104. public AudioConverter setMP3EncoderLib(String lib) {
  105. if (isMP3EncoderInit()) {
  106. encoder.setLibrary(lib);
  107. }
  108. return this;
  109. }
  110.  
  111. public AudioConverter setOutputFilename(@NonNull String filename) {
  112. if (!filename.isEmpty()) {
  113. if (!filename.endsWith(getExtension())) {
  114. filename += "." + getExtension();
  115. }
  116. this.outputFilename = filename;
  117. }
  118. return this;
  119. }
  120.  
  121. public AudioConverter setOutputFolder(String folder) {
  122. this.outputFolder = folder;
  123. return this;
  124. }
  125.  
  126.  
  127. public String getMP3EncoderLib() {
  128. return encoder.getLibrary();
  129. }
  130.  
  131. /**
  132. * need for init encoder library spinner (only need for mp3)
  133. *
  134. * @return if encoder is MP3encoder
  135. */
  136. public boolean isMP3EncoderInit() {
  137. return encoder.ID == MP3Encoder.ID;
  138. }
  139.  
  140. /**
  141. * method for start convert by included parameters
  142. */
  143.  
  144. public CommandResult convert(File af) {
  145. audioFile = af;
  146. CommandResult result = new CommandResult();
  147. String errorMessage = isValidInputData(audioFile);
  148. try {
  149. if (errorMessage == null) {
  150. result = startConversion();
  151. } else {
  152. result.message = errorMessage;
  153. }
  154. } catch (Exception e) {
  155. e.printStackTrace();
  156. result.message = e.getMessage();
  157. }
  158. return result;
  159. }
  160.  
  161. private String isValidInputData(File audioFile) {
  162.  
  163. if (audioFile == null || !audioFile.exists())
  164. return "FILE DOESN'T EXISTS";
  165.  
  166. if (!audioFile.canRead())
  167. return "FILE IS NOT READABLE";
  168.  
  169. if (outputFolder == null || outputFolder.isEmpty())
  170. return "WRONG OUTPUT FOLDER";
  171.  
  172. if (outputFilename == null || outputFilename.isEmpty())
  173. return "WRONG OUTPUT FILE";
  174.  
  175. return null;
  176. }
  177.  
  178. private File getConvertedFile(String outputFilename) {
  179. String rootDirectory = getApplicationRootDirectory();
  180. if (rootDirectory == null) {
  181. return null;
  182. }
  183. String filePath = rootDirectory + Constants.getInstance().PATH_DELIMITER + outputFilename;
  184. return new File(filePath);
  185. }
  186.  
  187. private String getApplicationRootDirectory() {
  188. PackageManager packageManager = context.getPackageManager();
  189. String packageName = context.getPackageName();
  190. try {
  191. PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
  192. return packageInfo.applicationInfo.dataDir;
  193. } catch (PackageManager.NameNotFoundException e) {
  194. e.printStackTrace();
  195. }
  196. return null;
  197. }
  198.  
  199. private DocumentFile getDocumentFileFromTree(String path) {
  200. try {
  201. String[] paths = path.split(Constants.getInstance().PATH_DELIMITER);
  202. Uri treeUri = Uri.parse(ApplicationPrefrences.getInstance().getTreeUri());
  203. DocumentFile root = DocumentFile.fromTreeUri(context, treeUri);
  204. for (String s : paths) {
  205. DocumentFile tempDoc = root.findFile(s);
  206. if (tempDoc != null) {
  207. if (tempDoc.isDirectory()) {
  208. root = tempDoc;
  209. } else if (tempDoc.isFile()) {
  210. return tempDoc;
  211. }
  212. }
  213. }
  214. } catch (Exception e) {
  215. e.printStackTrace();
  216. }
  217. return null;
  218. }
  219.  
  220. public String getExtension() {
  221. return encoder.getExtension();
  222. }
  223.  
  224. public void debugLog() {
  225.  
  226. }
  227.  
  228. protected CommandResult startConversion() {
  229.  
  230. CommandResult result = new CommandResult();
  231. String outputPath = outputFolder + outputFilename;
  232.  
  233. if (audioFile.getAbsolutePath().equals(outputPath) || new File(outputPath).exists()) {
  234. int i = 1;
  235. Pattern pattern = Pattern.compile("(^\\(\\d+\\))");
  236. Matcher matcher = pattern.matcher(outputFilename);
  237. if(matcher.find()){
  238. try{
  239. String s = matcher.group(1);
  240. int length = s.length();
  241. i = Integer.parseInt(s.substring(1, length-1));
  242. i++;
  243. outputFilename = outputFilename.substring(length);
  244. }catch (Exception e){
  245.  
  246. }
  247. }
  248.  
  249. File f = new File(outputFolder + "(" + i + ")" + outputFilename);
  250. while(f.exists()){
  251. i++;
  252. f = new File(outputFolder + "(" + i + ")" + outputFilename);
  253. }
  254. outputPath = f.getPath();
  255. }
  256.  
  257. String tempOutputPath = outputPath;
  258. if (!outputPath.contains(Constants.getInstance().INTERNAL_STORAGE_FOLDER)) {
  259. tempOutputPath = context.getCacheDir() + "/" + outputFilename;
  260. }
  261.  
  262. long sessionId = System.currentTimeMillis();
  263. /*
  264. long size = audioFile.length();
  265. String msg = "abi: " + new CpuArchHelper().getCpuArch() +
  266. ", original_path: " + audioFile.getPath() + ", destination_path: " + outputPath +
  267. ", temp_path: " + tempOutputPath + ", encoder: " + encoder.getExtension() +
  268. ", quality: " + encoder.getQuality() + ", library: " + encoder.getLibrary() + ", filesize: " + size;
  269. if ( size==10000000 ){
  270. msg+= " ?1?1?:"+track.getPath();
  271. } else if ( size<1024 ) {
  272. msg += " ?2?2?:" + track.getPath();
  273. try{
  274. FileReader reader = new FileReader(audioFile);
  275. char[] charBuffer = new char[(int)size];
  276. reader.read(charBuffer);
  277. String s = new String(charBuffer);
  278. msg+="\n"+s;
  279. } catch (Exception e){
  280.  
  281. }
  282. }
  283. */
  284. long size = audioFile.length();
  285. String msg = "abi: " + new CpuArchHelper().getCpuArch() +
  286. ", original_path: " + audioFile.getPath() + ", destination_path: " + outputPath +
  287. ", encoder: " + encoder.getExtension() +
  288. ", library: " + encoder.getLibrary() + ", filesize: " + size;
  289. if ( size==10000000 ){
  290. msg+= " ?1?1?:"+audioFile.getPath();
  291. } else if ( size<1024 ) {
  292. msg += " ?2?2?:" + audioFile.getPath();
  293. try{
  294. FileReader reader = new FileReader(audioFile);
  295. char[] charBuffer = new char[(int)size];
  296. reader.read(charBuffer);
  297. String s = new String(charBuffer);
  298. msg+="\n"+s;
  299. } catch (Exception e){
  300.  
  301. }
  302. }
  303.  
  304. String res = transcode(audioFile.getPath(), encoder.getMinQuality(), encoder.getLibrary(), encoder.getExtension(), tempOutputPath, -1);
  305.  
  306. try {
  307. String[] ss = res.split("__,__");
  308. result.commandResult = Integer.parseInt(ss[0]) >= 0 ? CommandResult.COMMAND_SUCCEDED : CommandResult.COMMAND_FAILED;
  309. result.message = ss[1];
  310. if (result.commandResult < 0) {
  311. if ( result.message==null )
  312. result.message = "";
  313. result.message += ", " + msg;
  314. } else {
  315. if (!outputPath.contains(Constants.getInstance().INTERNAL_STORAGE_FOLDER)) {
  316. Activity a = context.getCurrentActivity();
  317. Context c = a==null?context:a;
  318. setProgress(100, "");
  319. String reservePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/" + outputFilename;
  320. DocumentFile df = getDocumentFileFromTree(outputPath);
  321. if (df != null) {
  322. DocumentFile df2 = null;
  323. if (df.isDirectory()) {
  324. df2 = df.createFile(Constants.getInstance().AUDIO_TYPE, Data.getFileNameFromPath(outputPath, null));
  325. }
  326. if (copy(new File(tempOutputPath), df2 != null ? df2 : df, null) > 0) {
  327. result.message = outputPath;
  328. } else if (copy(new File(tempOutputPath), null, new File(reservePath)) > 0) {
  329. result.message = reservePath;
  330. } else {
  331. result.commandResult = CommandResult.COMMAND_FAILED;
  332. result.message = "PERMISSION DENIED";
  333. }
  334. } else {
  335. if (copy(new File(tempOutputPath), null, new File(reservePath)) > 0) {
  336. result.message = reservePath;
  337. } else {
  338. result.commandResult = CommandResult.COMMAND_FAILED;
  339. result.message = "PERMISSION DENIED";
  340. }
  341. }
  342. }
  343.  
  344. if (removeOriginalFileAfterConversion)
  345. audioFile.delete();
  346. outputFilename = null;
  347. }
  348. } catch (Exception e) {
  349. e.printStackTrace();
  350. }
  351.  
  352. return result;
  353. }
  354.  
  355. public int copy(File src, DocumentFile documentFile, File dst) throws IOException {
  356. int result = -1;
  357. InputStream in = new FileInputStream(src);
  358. try {
  359. OutputStream out = null;
  360. if (documentFile != null) {
  361. out = CustomApplication.getApplicationInstance().getContentResolver().openOutputStream(documentFile.getUri());
  362. } else if (dst != null) {
  363. out = new FileOutputStream(dst);
  364. }
  365. if (out != null) {
  366. try {
  367. byte[] buf = new byte[1024];
  368. int len;
  369. while ((len = in.read(buf)) > 0) {
  370. out.write(buf, 0, len);
  371. }
  372. result = 1;
  373. } finally {
  374. out.close();
  375. }
  376. }
  377. } finally {
  378. in.close();
  379. }
  380. return result;
  381. }
  382. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement