commit 17daad154c81ae409fd8ed240984f601a2836883 Author: Victor Date: Thu Mar 29 18:46:37 2018 +0300 Hello, world diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..05c5d3c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.gradle/ +.nb-gradle/ +build/ +private/ +.nb-gradle-properties \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..09ccc7d --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Victor Melnik + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..acb031c --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# Voicyanski + +JavaFX application for easy cut and send audio to Telegram chat as voice messages. + + +## Requirements + + - JavaFX 8 + - `ffmpeg` with libopus encoder + + +## Building and running + +1. Build jar with dependencies: `./gradlew shadowJar` +2. Edit `app.properties` in `build/libs/Voicyanski-all.jar` archive +3. Set `telegram-bot-token` and `telegram-chat-id` properties +4. Run application: + `java -jar Voicyanski-all.jar` and drop your audio file window + or run `java -jar Voicyanski-all.jar path-to-audio-file.mp3` \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..398c08c --- /dev/null +++ b/build.gradle @@ -0,0 +1,55 @@ +plugins { + id "java" + id "com.github.johnrengelman.shadow" version "2.0.3" +} + +sourceCompatibility = '1.8' +[compileJava, compileTestJava]*.options*.encoding = 'UTF-8' + +if (!hasProperty('mainClass')) { + ext.mainClass = 'com.annimon.voicyanski.Main' +} + +repositories { + mavenCentral() +} + +jar { + manifest.attributes( + 'Main-Class': project.mainClass + ) +} + +shadowJar { + exclude 'META-INF/maven/**' + exclude 'META-INF/resources/materialdesignicons/*/fonts/*.eot' + exclude 'META-INF/resources/materialdesignicons/*/fonts/*.svg' + exclude 'META-INF/resources/materialdesignicons/*/fonts/*.woff' + exclude 'META-INF/versions/**' + exclude 'controlsfx*.properties' + exclude 'org/controlsfx/dialog/**' + exclude 'org/controlsfx/glyphfont/**' + exclude 'org/controlsfx/control/spreadsheet/**' + exclude 'org/controlsfx/control/table/**' + exclude 'org/controlsfx/control/textfield/**' + exclude 'org/controlsfx/control/worldmap-small.properties' + exclude 'impl/org/controlsfx/spreadsheet/**' + exclude 'impl/org/controlsfx/table/**' + exclude 'impl/org/controlsfx/tools/**' + exclude 'impl/org/controlsfx/worldmap/**' +} + +task run(dependsOn: classes, type: JavaExec) { + main = project.mainClass + classpath = sourceSets.main.runtimeClasspath + standardInput = System.in + ignoreExitValue = true +} + +dependencies { + implementation 'org.controlsfx:controlsfx:8.40.14' + implementation 'com.squareup.okhttp3:okhttp:3.10.0' + implementation 'org.kordamp.ikonli:ikonli-javafx:2.1.1' + implementation 'org.kordamp.ikonli:ikonli-materialdesign-pack:2.1.1' + testImplementation 'junit:junit:4.10' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b979729 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..71c8d45 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Sep 21 13:08:26 CEST 2013 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=http\://services.gradle.org/distributions/gradle-4.6-bin.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..91a7e26 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b126f39 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Voicyanski' diff --git a/src/main/java/com/annimon/voicyanski/Main.java b/src/main/java/com/annimon/voicyanski/Main.java new file mode 100644 index 0000000..410a3e9 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/Main.java @@ -0,0 +1,48 @@ +package com.annimon.voicyanski; + +import java.io.File; +import java.util.Locale; +import java.util.ResourceBundle; +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.stage.Stage; + +public class Main extends Application { + + private static ResourceBundle resources, config; + + public static ResourceBundle getResources() { + return resources; + } + + public static ResourceBundle getConfig() { + return config; + } + + @Override + public void start(Stage stage) throws Exception { + Main.config = ResourceBundle.getBundle("app"); + if (Main.config.containsKey("locale")) { + Locale.setDefault(new Locale(Main.config.getString("locale"))); + } + Main.resources = ResourceBundle.getBundle("locales.Language", Locale.getDefault()); + + final FXMLLoader loader = new FXMLLoader( + getClass().getResource("/fxml/Main.fxml"), Main.resources); + + Scene scene = new Scene(loader.load()); + scene.getStylesheets().add("/styles/main.css"); + + MainController controller = (MainController) loader.getController(); + controller.setParameters(getParameters()); + controller.setPrimaryStage(stage); + + stage.setScene(scene); + stage.show(); + } + + public static void main(String[] args) { + launch(args); + } +} diff --git a/src/main/java/com/annimon/voicyanski/MainController.java b/src/main/java/com/annimon/voicyanski/MainController.java new file mode 100644 index 0000000..32c77d7 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/MainController.java @@ -0,0 +1,193 @@ +package com.annimon.voicyanski; + +import com.annimon.voicyanski.audio.Waveform; +import com.annimon.voicyanski.controls.AudioClipView; +import com.annimon.voicyanski.tasks.BuildWaveformTask; +import com.annimon.voicyanski.tasks.ClipPartData; +import com.annimon.voicyanski.tasks.FFmpegCheckTask; +import com.annimon.voicyanski.tasks.FetchMetadataTask; +import com.annimon.voicyanski.tasks.OpusConvertTask; +import com.annimon.voicyanski.tasks.SendTelegramVoiceTask; +import java.io.File; +import java.net.URL; +import java.util.Arrays; +import java.util.ResourceBundle; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.stream.Stream; +import javafx.application.Application; +import javafx.application.Platform; +import javafx.beans.binding.Bindings; +import javafx.beans.binding.BooleanBinding; +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.control.Alert; +import javafx.scene.control.Alert.AlertType; +import javafx.scene.control.Button; +import javafx.scene.input.Dragboard; +import javafx.scene.input.TransferMode; +import javafx.stage.Stage; +import org.kordamp.ikonli.javafx.FontIcon; + +public class MainController implements Initializable { + + @FXML + private Button btnMarkStart, btnMarkEnd, btnBackward, btnPlay, btnForward, btnSend; + + @FXML + private FontIcon iconPlay; + + @FXML + private AudioClipView clipView; + + public void setParameters(Application.Parameters parameters) { + if (hasValidFilenames(parameters.getRaw().stream())) { + final Stream stream = parameters.getRaw().stream() + .map(File::new) + .filter(File::isFile) + .filter(File::canRead); + processFiles(stream, () -> {}); + } + } + + public void setPrimaryStage(Stage stage) { + stage.titleProperty().bind(Bindings + .when(clipView.metadataProperty().isNull()) + .then(Main.getResources().getString("voicyanski")) + .otherwise(clipView.metadataProperty().asString()) + ); + } + + @Override + public void initialize(URL url, ResourceBundle rb) { + checkFFmpegExists(); + initDragDropEvents(); + initButtonsBinding(); + clipView.initMarkButtons(btnMarkStart, btnMarkEnd); + clipView.initPlayButtons(btnBackward, btnPlay, btnForward); + clipView.setIconPlay(iconPlay); + btnSend.setOnAction(event -> { + btnSend.setDisable(true); + final ClipPartData data = new ClipPartData(); + data.metadata = clipView.getMetadata(); + data.startTime = clipView.getClipPartStart(); + data.endTime = clipView.getClipPartEnd(); + CompletableFuture.completedFuture(data) + .thenApplyAsync(new OpusConvertTask()) + .thenApplyAsync(new SendTelegramVoiceTask()) + .handleAsync(this::handleVoiceSend); + }); + } + + private void checkFFmpegExists() { + CompletableFuture.supplyAsync(new FFmpegCheckTask()) + .handle(this::handleFFmpegCheck); + } + + private Boolean handleFFmpegCheck(Boolean result, Throwable ex) { + Platform.runLater(() -> { + if (ex != null) { + alertError(ex); + } + }); + return result; + } + + private void initDragDropEvents() { + clipView.setOnDragOver(event -> { + final Dragboard db = event.getDragboard(); + boolean status = db.hasFiles(); + status &= hasValidFilenames(db.getFiles().stream().map(File::getName)); + if (status) { + event.acceptTransferModes(TransferMode.COPY); + } else { + event.consume(); + } + }); + clipView.setOnDragDropped(event -> { + final Dragboard db = event.getDragboard(); + if (!db.hasFiles()) { + event.setDropCompleted(false); + event.consume(); + return; + } + + clipView.reset(); + processFiles(db.getFiles().stream(), () -> event.setDropCompleted(true)); + event.consume(); + }); + } + + private boolean hasValidFilenames(Stream stream) { + final String[] supportedExts = {".mp3", ".wav", ".aac"}; + return stream + .map(String::toLowerCase) + .allMatch(name -> Arrays.stream(supportedExts) + .anyMatch(ext -> name.endsWith(ext))); + } + + private void processFiles(Stream stream, Runnable action) { + stream.findAny() + .ifPresent(f -> { + CompletableFuture.completedFuture(f) + .thenApplyAsync(new FetchMetadataTask()) + .thenApplyAsync(metadata -> { + Platform.runLater(() -> clipView.setMetadata(metadata)); + return metadata; + }) + .thenApplyAsync(new BuildWaveformTask()) + .handleAsync(this::handleFile); + action.run(); + }); + } + + private void initButtonsBinding() { + final BooleanBinding waveformExistsProperty = clipView.waveformProperty().isNotNull(); + for (Button btn : Arrays.asList(btnMarkStart, btnMarkEnd, + btnBackward, btnPlay, btnForward, btnSend)) { + btn.visibleProperty().bind(waveformExistsProperty); + } + } + + private Waveform handleFile(Waveform waveform, Throwable ex) { + Platform.runLater(() -> { + if (waveform == null || ex != null) { + alertError(ex); + clipView.reset(); + } else { + clipView.onLoad(waveform); + } + }); + return waveform; + } + + private Boolean handleVoiceSend(Boolean result, Throwable ex) { + Platform.runLater(() -> { + btnSend.setDisable(false); + if (ex != null) { + alertError(ex); + } else if (result) { + Alert alert = new Alert(AlertType.INFORMATION); + alert.setTitle(Main.getResources().getString("sent")); + alert.setHeaderText(null); + alert.setContentText(Main.getResources().getString("voice_sent_successfully")); + alert.showAndWait(); + } + }); + return result; + } + + private void alertError(Throwable ex) { + Alert alert = new Alert(AlertType.ERROR); + alert.setTitle(Main.getResources().getString("error")); + alert.setHeaderText(null); + final String message; + if ((ex instanceof CompletionException) && (ex.getCause() != null)) { + message = ex.getCause().getLocalizedMessage(); + } else { + message = ex.getLocalizedMessage(); + } + alert.setContentText(message); + alert.showAndWait(); + } +} diff --git a/src/main/java/com/annimon/voicyanski/audio/Rms.java b/src/main/java/com/annimon/voicyanski/audio/Rms.java new file mode 100644 index 0000000..fd6436e --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/audio/Rms.java @@ -0,0 +1,31 @@ +package com.annimon.voicyanski.audio; + +public final class Rms { + + private final int frame; + private final double ptsTime; + private final double level; + + public Rms(int frame, double ptsTime, double level) { + this.frame = frame; + this.ptsTime = ptsTime; + this.level = level; + } + + public int getFrame() { + return frame; + } + + public double getPtsTime() { + return ptsTime; + } + + public double getLevel() { + return level; + } + + @Override + public String toString() { + return "Rms{" + "frame=" + frame + ", ptsTime=" + ptsTime + ", level=" + level + '}'; + } +} diff --git a/src/main/java/com/annimon/voicyanski/audio/Waveform.java b/src/main/java/com/annimon/voicyanski/audio/Waveform.java new file mode 100644 index 0000000..0b78b24 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/audio/Waveform.java @@ -0,0 +1,42 @@ +package com.annimon.voicyanski.audio; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +public final class Waveform { + + private final List waveform; + + public Waveform() { + waveform = new ArrayList<>(); + } + + public Waveform(List waveform) { + this.waveform = waveform; + } + + public double getMaxTime() { + final int size = size(); + if (size == 0) { + return 0; + } + return waveform.get(size - 1).getPtsTime(); + } + + public void addRms(Rms rms) { + waveform.add(rms); + } + + public boolean isEmpty() { + return waveform.isEmpty(); + } + + public int size() { + return waveform.size(); + } + + public Stream rms() { + return waveform.stream(); + } +} diff --git a/src/main/java/com/annimon/voicyanski/audio/WaveformFileReader.java b/src/main/java/com/annimon/voicyanski/audio/WaveformFileReader.java new file mode 100644 index 0000000..3beea9e --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/audio/WaveformFileReader.java @@ -0,0 +1,44 @@ +package com.annimon.voicyanski.audio; + +import com.annimon.voicyanski.exceptions.WaveformBuildException; +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class WaveformFileReader implements WaveformReader { + + private final Path filePath; + + public WaveformFileReader(Path filePath) { + this.filePath = filePath; + } + + @Override + public Waveform read() { + final Waveform waveform = new Waveform(); + try (BufferedReader br = Files.newBufferedReader(filePath)) { + final Pattern pattern = Pattern.compile("frame:(\\d+).*pts_time:([\\d.]+).*RMS_level=(-?[\\d.]+)"); + while (true) { + String line1 = br.readLine(); + if (line1 == null) break; + String line2 = br.readLine(); + if (line2 == null) break; + + Matcher m = pattern.matcher(line1 + line2); + if (m.find()) { + int frame = Integer.parseInt(m.group(1), 10); + double time = Double.parseDouble(m.group(2)); + double level = Double.parseDouble(m.group(3)); + level = Math.signum(level) * Math.log(Math.abs(level)); + waveform.addRms(new Rms(frame, time, level)); + } + } + } catch (IOException ex) { + throw new WaveformBuildException(ex); + } + return waveform; + } +} diff --git a/src/main/java/com/annimon/voicyanski/audio/WaveformReader.java b/src/main/java/com/annimon/voicyanski/audio/WaveformReader.java new file mode 100644 index 0000000..3f726cf --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/audio/WaveformReader.java @@ -0,0 +1,6 @@ +package com.annimon.voicyanski.audio; + +public interface WaveformReader { + + Waveform read(); +} diff --git a/src/main/java/com/annimon/voicyanski/controls/AudioClipView.java b/src/main/java/com/annimon/voicyanski/controls/AudioClipView.java new file mode 100644 index 0000000..76aae7c --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/controls/AudioClipView.java @@ -0,0 +1,205 @@ +package com.annimon.voicyanski.controls; + +import com.annimon.voicyanski.Main; +import com.annimon.voicyanski.audio.Waveform; +import com.annimon.voicyanski.tasks.Metadata; +import java.io.IOException; +import javafx.beans.binding.Bindings; +import javafx.beans.binding.ObjectBinding; +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.layout.VBox; +import javafx.scene.media.Media; +import javafx.scene.media.MediaPlayer; +import javafx.util.Duration; +import org.controlsfx.control.RangeSlider; +import org.kordamp.ikonli.Ikon; +import org.kordamp.ikonli.javafx.FontIcon; +import org.kordamp.ikonli.materialdesign.MaterialDesign; + +public final class AudioClipView extends VBox { + + @FXML + private Label lblInfo; + + @FXML + private RangeSlider rangeClip; + + @FXML + private WaveformView waveform; + + private final ObjectProperty metadataProperty = new SimpleObjectProperty<>(); + private MediaPlayer mediaPlayer; + private FontIcon iconPlay; + + public AudioClipView() { + final FXMLLoader fxmlLoader = new FXMLLoader( + getClass().getResource("/fxml/controls/AudioClipView.fxml")); + fxmlLoader.setRoot(AudioClipView.this); + fxmlLoader.setController(AudioClipView.this); + try { + fxmlLoader.load(); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + initialize(); + } + + public Metadata getMetadata() { + return metadataProperty.get(); + } + + public void setMetadata(Metadata value) { + metadataProperty.set(value); + } + + public ObjectProperty metadataProperty() { + return metadataProperty; + } + + public Waveform getWaveform() { + return waveform.getWaveform(); + } + + public void setWaveform(Waveform waveform) { + this.waveform.setWaveform(waveform); + } + + public ObjectProperty waveformProperty() { + return waveform.waveformProperty(); + } + + public double getClipPartStart() { + return rangeClip.getLowValue(); + } + + public double getClipPartEnd() { + return rangeClip.getHighValue(); + } + + public void setIconPlay(FontIcon iconPlay) { + this.iconPlay = iconPlay; + } + + public void reset() { + setMetadata(null); + setWaveform(null); + stop(); + } + + public void playFrom(Duration d) { + if (mediaPlayer == null) { + return; + } + mediaPlayer.seek(d); + mediaPlayer.play(); + } + + public void stop() { + if (mediaPlayer == null) { + return; + } + mediaPlayer.stop(); + } + + public void onLoad(Waveform wf) { + setWaveform(wf); + if (wf != null) { + rangeClip.setLowValue(0); + rangeClip.setMax(wf.getMaxTime()); + rangeClip.setHighValue(wf.getMaxTime()); + + final Media media = new Media(getMetadata().file.toURI().toString()); + mediaPlayer = new MediaPlayer(media); + mediaPlayer.startTimeProperty().bind(new ObjectBinding() { + { + bind(rangeClip.lowValueProperty()); + } + @Override + protected Duration computeValue() { + return Duration.seconds(rangeClip.getLowValue()); + } + }); + mediaPlayer.stopTimeProperty().bind(new ObjectBinding() { + { + bind(rangeClip.highValueProperty()); + } + @Override + protected Duration computeValue() { + return Duration.seconds(rangeClip.getHighValue()); + } + }); + waveform.currentPlayTimeProperty().bind(Bindings + .when(mediaPlayer.statusProperty().isEqualTo(MediaPlayer.Status.PLAYING) + .or(mediaPlayer.statusProperty().isEqualTo(MediaPlayer.Status.PAUSED)) ) + .then(mediaPlayer.currentTimeProperty()) + .otherwise(Duration.INDEFINITE) + ); + waveform.setCustomCurrentTimeListener((observable, oldValue, newValue) -> { + playFrom(newValue); + }); + mediaPlayer.statusProperty().addListener((observable, oldValue, newValue) -> { + final Ikon ikon = (newValue == MediaPlayer.Status.PLAYING) + ? MaterialDesign.MDI_PAUSE + : MaterialDesign.MDI_PLAY; + iconPlay.setIconCode(ikon); + }); + } + } + + private void initialize() { + rangeClip.managedProperty().bind(rangeClip.visibleProperty()); + rangeClip.visibleProperty().bind(waveformProperty().isNotNull()); + waveform.startProperty().bind(rangeClip.lowValueProperty()); + waveform.endProperty().bind(rangeClip.highValueProperty()); + + lblInfo.managedProperty().bind(lblInfo.visibleProperty()); + lblInfo.visibleProperty().bind(waveformProperty().isNull()); + lblInfo.textProperty().bind(Bindings + .when(metadataProperty.isNull()) + .then(Main.getResources().getString("drop_your_music_here")) + .otherwise(Main.getResources().getString("processing_file")) + ); + + waveform.visibleProperty().bind(waveformProperty().isNotNull()); + } + + public void initMarkButtons(Button markStart, Button markEnd) { + markStart.setOnAction(event -> { + if (mediaPlayer == null) return; + final double time = mediaPlayer.currentTimeProperty().get().toSeconds(); + if (time < getClipPartEnd()) { + rangeClip.setLowValue(time); + } + }); + markEnd.setOnAction(event -> { + if (mediaPlayer == null) return; + final double time = mediaPlayer.currentTimeProperty().get().toSeconds(); + if (time > getClipPartStart()) { + rangeClip.setHighValue(time); + } + }); + } + + public void initPlayButtons(Button backward, Button playPause, Button forward) { + backward.setOnAction(event -> playFrom(Duration.seconds(rangeClip.getLowValue()))); + forward.setOnAction(event -> { + if (mediaPlayer == null) return; + final double endTime = rangeClip.getHighValue(); + final double fromTime = Math.max(0, endTime - 3); + playFrom(Duration.seconds(fromTime)); + }); + playPause.setOnAction(event -> { + if (mediaPlayer == null) return; + if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) { + mediaPlayer.pause(); + } else { + playFrom(mediaPlayer.getCurrentTime()); + } + }); + } +} diff --git a/src/main/java/com/annimon/voicyanski/controls/WaveformView.java b/src/main/java/com/annimon/voicyanski/controls/WaveformView.java new file mode 100644 index 0000000..8e044b1 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/controls/WaveformView.java @@ -0,0 +1,162 @@ +package com.annimon.voicyanski.controls; + +import com.annimon.voicyanski.audio.Rms; +import com.annimon.voicyanski.audio.Waveform; +import java.util.DoubleSummaryStatistics; +import javafx.beans.property.DoubleProperty; +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleDoubleProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.beans.value.ChangeListener; +import javafx.scene.canvas.Canvas; +import javafx.scene.canvas.GraphicsContext; +import javafx.scene.control.Control; +import javafx.scene.control.Skin; +import javafx.scene.control.SkinBase; +import javafx.scene.input.MouseEvent; +import javafx.scene.paint.Color; +import javafx.util.Duration; + +public final class WaveformView extends Control { + + private final ObjectProperty waveformProperty = new SimpleObjectProperty<>(); + private final DoubleProperty startProperty = new SimpleDoubleProperty(0); + private final DoubleProperty endProperty = new SimpleDoubleProperty(15); + private final ObjectProperty currentPlayTimeProperty = new SimpleObjectProperty<>(); + private ChangeListener customCurrentTimeListener; + + public Waveform getWaveform() { + return waveformProperty.get(); + } + + public void setCustomCurrentTimeListener(ChangeListener customCurrentTimeListener) { + this.customCurrentTimeListener = customCurrentTimeListener; + } + + public void setWaveform(Waveform waveform) { + waveformProperty.set(waveform); + } + + public ObjectProperty waveformProperty() { + return waveformProperty; + } + + public double getStart() { + return startProperty.get(); + } + + public void setStart(double start) { + startProperty.set(start); + } + + public DoubleProperty startProperty() { + return startProperty; + } + + public double getEnd() { + return startProperty.get(); + } + + public void setEnd(double end) { + endProperty.set(end); + } + + public DoubleProperty endProperty() { + return endProperty; + } + + public Duration getCurrentPlayTime() { + return currentPlayTimeProperty.get(); + } + + public void setCurrentPlayTime(Duration time) { + currentPlayTimeProperty.set(time); + } + + public ObjectProperty currentPlayTimeProperty() { + return currentPlayTimeProperty; + } + + @Override + protected Skin createDefaultSkin() { + return new WaveformViewSkin(this); + } + + class WaveformViewSkin extends SkinBase { + + private final Canvas canvas; + + @SuppressWarnings("unchecked") + public WaveformViewSkin(WaveformView control) { + super(control); + canvas = new Canvas(); + canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, this::onMouseEvent); + canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::onMouseEvent); + ChangeListener listener = (observable, oldValue, newValue) -> { + redraw(canvas.getWidth(), canvas.getHeight()); + }; + getChildren().add(canvas); + startProperty.addListener(listener); + endProperty.addListener(listener); + currentPlayTimeProperty.addListener(listener); + } + + private void onMouseEvent(MouseEvent event) { + final Waveform wf = waveformProperty.getValue(); + if (wf == null) return; + + final double maxTime = wf.getMaxTime(); + final double seconds = event.getX() * maxTime / canvas.getWidth(); + Duration time = Duration.seconds(seconds); + if (customCurrentTimeListener != null) { + customCurrentTimeListener.changed(currentPlayTimeProperty, getCurrentPlayTime(), time); + } + } + + @Override + protected void layoutChildren(double cx, double cy, double width, double height) { + canvas.setWidth(width); + canvas.setHeight(height); + redraw(width, height); + } + + private void redraw(double width, double height) { + final Waveform wf = waveformProperty.getValue(); + final double halfHeight = height / 2; + final GraphicsContext g = canvas.getGraphicsContext2D(); + g.setFill(Color.WHITE); + g.fillRect(0, 0, width, height); + g.setStroke(Color.LIGHTGREEN); + g.setLineWidth(2); + if (wf == null || wf.isEmpty()) { + g.strokeLine(0, halfHeight, width, halfHeight); + } else { + final double maxTime = wf.getMaxTime(); + final double xStep = width / maxTime; + final DoubleSummaryStatistics stat = wf.rms() + .mapToDouble(Rms::getLevel) + .summaryStatistics(); + final double yStep = halfHeight / (stat.getMax() - stat.getMin()); + wf.rms().forEach(rms -> { + double x = rms.getPtsTime() * xStep; + double level = (rms.getLevel() - stat.getMin()) * yStep; + g.strokeLine(x, halfHeight - level, x, halfHeight + level); + }); + + final double start = startProperty.get() * xStep; + final double end = endProperty.get() * xStep; + g.setFill(Color.grayRgb(0, 0.15)); + g.fillRect(0, 0, start, height); + g.fillRect(end, 0, width - end, height); + + final Duration time = getCurrentPlayTime(); + if (time != null && !time.isUnknown()) { + final double timeX = time.toSeconds() * xStep; + g.setLineWidth(1); + g.setStroke(Color.RED); + g.strokeLine(timeX, 0, timeX, height); + } + } + } + } +} diff --git a/src/main/java/com/annimon/voicyanski/exceptions/AudioConvertException.java b/src/main/java/com/annimon/voicyanski/exceptions/AudioConvertException.java new file mode 100644 index 0000000..840605c --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/exceptions/AudioConvertException.java @@ -0,0 +1,15 @@ +package com.annimon.voicyanski.exceptions; + +import com.annimon.voicyanski.Main; + +public class AudioConvertException extends RuntimeException { + + public AudioConvertException() { + super("Unable to convert audio file"); + } + + @Override + public String getLocalizedMessage() { + return Main.getResources().getString("unable_convert_audio"); + } +} diff --git a/src/main/java/com/annimon/voicyanski/exceptions/FFmpegNotFoundException.java b/src/main/java/com/annimon/voicyanski/exceptions/FFmpegNotFoundException.java new file mode 100644 index 0000000..31f8429 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/exceptions/FFmpegNotFoundException.java @@ -0,0 +1,15 @@ +package com.annimon.voicyanski.exceptions; + +import com.annimon.voicyanski.Main; + +public class FFmpegNotFoundException extends RuntimeException { + + public FFmpegNotFoundException() { + super("Unable to access FFmpeg. Please install it or add to PATH environment variable"); + } + + @Override + public String getLocalizedMessage() { + return Main.getResources().getString("unable_access_ffmpeg"); + } +} diff --git a/src/main/java/com/annimon/voicyanski/exceptions/FetchMetadataException.java b/src/main/java/com/annimon/voicyanski/exceptions/FetchMetadataException.java new file mode 100644 index 0000000..28ff648 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/exceptions/FetchMetadataException.java @@ -0,0 +1,15 @@ +package com.annimon.voicyanski.exceptions; + +import com.annimon.voicyanski.Main; + +public class FetchMetadataException extends RuntimeException { + + public FetchMetadataException() { + super("Unable to fetch metadata"); + } + + @Override + public String getLocalizedMessage() { + return Main.getResources().getString("unable_fetch_metadata"); + } +} diff --git a/src/main/java/com/annimon/voicyanski/exceptions/TelegramSendingException.java b/src/main/java/com/annimon/voicyanski/exceptions/TelegramSendingException.java new file mode 100644 index 0000000..d16bfaf --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/exceptions/TelegramSendingException.java @@ -0,0 +1,15 @@ +package com.annimon.voicyanski.exceptions; + +import com.annimon.voicyanski.Main; + +public class TelegramSendingException extends RuntimeException { + + public TelegramSendingException(Throwable cause) { + super("Unable to send message", cause); + } + + @Override + public String getLocalizedMessage() { + return Main.getResources().getString("unable_send_message"); + } +} diff --git a/src/main/java/com/annimon/voicyanski/exceptions/WaveformBuildException.java b/src/main/java/com/annimon/voicyanski/exceptions/WaveformBuildException.java new file mode 100644 index 0000000..99920fc --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/exceptions/WaveformBuildException.java @@ -0,0 +1,15 @@ +package com.annimon.voicyanski.exceptions; + +import com.annimon.voicyanski.Main; + +public class WaveformBuildException extends RuntimeException { + + public WaveformBuildException(Throwable cause) { + super("Unable to build waveform", cause); + } + + @Override + public String getLocalizedMessage() { + return Main.getResources().getString("unable_build_waveform"); + } +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/BuildWaveformTask.java b/src/main/java/com/annimon/voicyanski/tasks/BuildWaveformTask.java new file mode 100644 index 0000000..c691201 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/BuildWaveformTask.java @@ -0,0 +1,43 @@ +package com.annimon.voicyanski.tasks; + +import com.annimon.voicyanski.audio.Waveform; +import com.annimon.voicyanski.audio.WaveformFileReader; +import com.annimon.voicyanski.exceptions.WaveformBuildException; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +public final class BuildWaveformTask implements Function { + + private static final int PROCESS_WAIT_TIME = 30; + + @Override + public Waveform apply(Metadata metadata) { + File tmpLogFile = new File("log" + System.currentTimeMillis() +".txt"); + try { + final ProcessBuilder pb = new ProcessBuilder( + "ffmpeg", + "-v", "error", + "-i", metadata.file.getAbsolutePath(), + "-af", "astats=metadata=1:reset=1,ametadata=print" + + ":key=lavfi.astats.Overall.RMS_level" + + ":file=" + tmpLogFile.getName(), + "-f", "null", "-" + ); + final Process ffmpeg = pb.start(); + boolean status = ffmpeg.waitFor(PROCESS_WAIT_TIME, TimeUnit.SECONDS); + status &= ffmpeg.exitValue() == 0; + if (status) { + return new WaveformFileReader(tmpLogFile.toPath()).read(); + } + } catch (InterruptedException | IOException ex) { + throw new WaveformBuildException(ex); + } finally { + if (tmpLogFile.exists()) { + tmpLogFile.delete(); + } + } + return null; + } +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/ClipPartData.java b/src/main/java/com/annimon/voicyanski/tasks/ClipPartData.java new file mode 100644 index 0000000..7cf7985 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/ClipPartData.java @@ -0,0 +1,9 @@ +package com.annimon.voicyanski.tasks; + +import java.io.File; + +public final class ClipPartData { + public Metadata metadata; + public File outputAudioFile; + public double startTime, endTime; +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/FFmpegCheckTask.java b/src/main/java/com/annimon/voicyanski/tasks/FFmpegCheckTask.java new file mode 100644 index 0000000..666dbd7 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/FFmpegCheckTask.java @@ -0,0 +1,21 @@ +package com.annimon.voicyanski.tasks; + +import com.annimon.voicyanski.exceptions.FFmpegNotFoundException; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +public final class FFmpegCheckTask implements Supplier { + + private static final int PROCESS_WAIT_TIME = 5; + + @Override + public Boolean get() { + try { + Process ffmpeg = Runtime.getRuntime().exec("ffmpeg -version"); + return ffmpeg.waitFor(PROCESS_WAIT_TIME, TimeUnit.SECONDS); + } catch (InterruptedException | IOException ex) { + throw new FFmpegNotFoundException(); + } + } +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/FetchMetadataTask.java b/src/main/java/com/annimon/voicyanski/tasks/FetchMetadataTask.java new file mode 100644 index 0000000..4247a2a --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/FetchMetadataTask.java @@ -0,0 +1,52 @@ +package com.annimon.voicyanski.tasks; + +import com.annimon.voicyanski.exceptions.FetchMetadataException; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class FetchMetadataTask implements Function { + + private static final int PROCESS_WAIT_TIME = 20; + private static final Pattern ARTIST_PATTERN = Pattern.compile("^artist=(.*)$"); + private static final Pattern TITLE_PATTERN = Pattern.compile("^title=(.*)$"); + + @Override + public Metadata apply(File file) { + final Metadata metadata = new Metadata(); + metadata.file = file; + try { + final ProcessBuilder pb = new ProcessBuilder( + "ffmpeg", + "-v", "error", + "-i", file.getAbsolutePath(), + "-f", "ffmetadata", + "-" + ); + final Process ffmpeg = pb.start(); + final Scanner out = new Scanner(ffmpeg.getInputStream(), StandardCharsets.UTF_8.name()); + while (out.hasNextLine()) { + final String line = out.nextLine(); + Matcher m; + m = ARTIST_PATTERN.matcher(line); + if (m.find()) { + metadata.artist = m.group(1); + continue; + } + m = TITLE_PATTERN.matcher(line); + if (m.find()) { + metadata.title = m.group(1); + } + } + ffmpeg.waitFor(PROCESS_WAIT_TIME, TimeUnit.SECONDS); + } catch (InterruptedException | IOException ex) { + throw new FetchMetadataException(); + } + return metadata; + } +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/Metadata.java b/src/main/java/com/annimon/voicyanski/tasks/Metadata.java new file mode 100644 index 0000000..ee97533 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/Metadata.java @@ -0,0 +1,24 @@ +package com.annimon.voicyanski.tasks; + +import java.io.File; + +public final class Metadata { + + public File file; + public String artist; + public String title; + + public boolean hasTrackInfo() { + return (artist != null) || (title != null); + } + + @Override + public String toString() { + if (!hasTrackInfo()) { + return file.getName(); + } + return String.format("%s - %s", + (artist != null) ? artist : "Unknown", + (title != null) ? title : "Unknown"); + } +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/OpusConvertTask.java b/src/main/java/com/annimon/voicyanski/tasks/OpusConvertTask.java new file mode 100644 index 0000000..75cf96c --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/OpusConvertTask.java @@ -0,0 +1,46 @@ +package com.annimon.voicyanski.tasks; + +import com.annimon.voicyanski.Main; +import com.annimon.voicyanski.exceptions.AudioConvertException; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import java.util.function.UnaryOperator; + +public final class OpusConvertTask implements UnaryOperator { + + private static final int PROCESS_WAIT_TIME = 30; + + @Override + public ClipPartData apply(ClipPartData data) { + data.outputAudioFile = new File("clip" + System.currentTimeMillis() +".ogg"); + data.outputAudioFile.deleteOnExit(); + try { + final ProcessBuilder pb = new ProcessBuilder( + "ffmpeg", + "-v", "error", + "-ss", Double.toString(data.startTime), + "-i", data.metadata.file.getAbsolutePath(), + "-t", Double.toString(data.endTime - data.startTime), + "-ac", Main.getConfig().getString("encode-stereo").equalsIgnoreCase("true") ? "2" : "1", + "-map", "0:a", + "-codec:a", "libopus", + "-b:a", Main.getConfig().getString("encode-bitrate"), + "-vbr", "off", + "-ar", Main.getConfig().getString("encode-samplerate"), + data.outputAudioFile.getAbsolutePath() + ); + final Process ffmpeg = pb.start(); + boolean status = ffmpeg.waitFor(PROCESS_WAIT_TIME, TimeUnit.SECONDS); + status &= ffmpeg.exitValue() == 0; + status &= data.outputAudioFile.exists(); + status &= data.outputAudioFile.length() > 0; + if (status) { + return data; + } + } catch (InterruptedException | IOException ex) { + throw new AudioConvertException(); + } + return null; + } +} diff --git a/src/main/java/com/annimon/voicyanski/tasks/SendTelegramVoiceTask.java b/src/main/java/com/annimon/voicyanski/tasks/SendTelegramVoiceTask.java new file mode 100644 index 0000000..5397fc9 --- /dev/null +++ b/src/main/java/com/annimon/voicyanski/tasks/SendTelegramVoiceTask.java @@ -0,0 +1,47 @@ +package com.annimon.voicyanski.tasks; + +import com.annimon.voicyanski.Main; +import com.annimon.voicyanski.exceptions.TelegramSendingException; +import java.io.IOException; +import java.util.function.Function; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public final class SendTelegramVoiceTask implements Function { + + private static final String URL_FORMAT = "https://api.telegram.org/bot%s/%s"; + private static final MediaType MEDIA_TYPE_OGG = MediaType.parse("audio/ogg"); + + private final OkHttpClient client = new OkHttpClient(); + + @Override + public Boolean apply(ClipPartData data) { + final MultipartBody.Builder builder = new MultipartBody.Builder(); + builder.setType(MultipartBody.FORM); + if (data.metadata.hasTrackInfo()) { + builder.addFormDataPart("caption", data.metadata.toString()); + } + builder.addFormDataPart("chat_id", Main.getConfig().getString("telegram-chat-id")); + builder.addFormDataPart("voice", data.metadata.file.getName(), + RequestBody.create(MEDIA_TYPE_OGG, data.outputAudioFile)); + final RequestBody requestBody = builder.build(); + + final Request request = new Request.Builder() + .url(String.format(URL_FORMAT, Main.getConfig().getString("telegram-bot-token"), "sendVoice")) + .post(requestBody) + .build(); + + try (final Response response = client.newCall(request).execute()) { + if (!response.isSuccessful()) { + throw new IOException("Unexpected code " + response); + } + return true; + } catch (IOException ex) { + throw new TelegramSendingException(ex); + } + } +} diff --git a/src/main/resources/app.properties b/src/main/resources/app.properties new file mode 100644 index 0000000..d4f031b --- /dev/null +++ b/src/main/resources/app.properties @@ -0,0 +1,8 @@ +locale=en + +telegram-bot-token=111111111:ABCDEFGHIJKLMNOPQRSTUVWXYZ12345-678 +telegram-chat-id=-3333333333333 + +encode-stereo=false +encode-bitrate=128k +encode-samplerate=24000 diff --git a/src/main/resources/fxml/Main.fxml b/src/main/resources/fxml/Main.fxml new file mode 100644 index 0000000..9889db8 --- /dev/null +++ b/src/main/resources/fxml/Main.fxml @@ -0,0 +1,74 @@ + + + + + + + + + + + + +
+ +
+ + + + + + +
diff --git a/src/main/resources/fxml/controls/AudioClipView.fxml b/src/main/resources/fxml/controls/AudioClipView.fxml new file mode 100644 index 0000000..d92d7ad --- /dev/null +++ b/src/main/resources/fxml/controls/AudioClipView.fxml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/locales/Language.properties b/src/main/resources/locales/Language.properties new file mode 100644 index 0000000..73174e6 --- /dev/null +++ b/src/main/resources/locales/Language.properties @@ -0,0 +1,19 @@ +voicyanski=Voicyanski +mark_start=Mark start +mark_end=Mark end +to_start=To start +to_end=To end +play_pause=Play / pause +send=Send + +error=Error +sent=Sent +voice_sent_successfully=Audio message successfully sent to chat +drop_your_music_here=Drop your music here +processing_file=Processing file + +unable_convert_audio=Unable to convert audio file +unable_access_ffmpeg=Unable to access FFmpeg. Please install it or add to PATH environment variable +unable_fetch_metadata=Unable to fetch metadata +unable_send_message=Unable to send message +unable_build_waveform=Unable to build waveform diff --git a/src/main/resources/locales/Language_ru.properties b/src/main/resources/locales/Language_ru.properties new file mode 100644 index 0000000..095b8c0 --- /dev/null +++ b/src/main/resources/locales/Language_ru.properties @@ -0,0 +1,19 @@ +voicyanski=\u0412\u043e\u0439\u0441\u044f\u043d\u0441\u043a\u0438\u0439 +mark_start=\u041e\u0442\u043c\u0435\u0442\u0438\u0442\u044c \u043d\u0430\u0447\u0430\u043b\u043e +mark_end=\u041e\u0442\u043c\u0435\u0442\u0438\u0442\u044c \u043a\u043e\u043d\u0435\u0446 +to_start=\u041a \u043d\u0430\u0447\u0430\u043b\u0443 +to_end=\u0412 \u043a\u043e\u043d\u0435\u0446 +play_pause=\u0418\u0433\u0440\u0430\u0442\u044c / \u043f\u0430\u0443\u0437\u0430 +send=\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c + +error=\u041e\u0448\u0438\u0431\u043a\u0430 +sent=\u041e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e +voice_sent_successfully=\u0410\u0443\u0434\u0438\u043e\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u0443\u0441\u043f\u0435\u0448\u043d\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e \u0432 \u0447\u0430\u0442 +drop_your_music_here=\u041f\u0435\u0440\u0435\u0442\u0430\u0449\u0438 \u0441\u044e\u0434\u0430 \u043c\u0443\u0437\u044b\u0447\u043a\u0443 +processing_file=\u041e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u044e \u0444\u0430\u0439\u043b + +unable_convert_audio=\u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0442\u044c \u0430\u0443\u0434\u0438\u043e\u0444\u0430\u0439\u043b +unable_access_ffmpeg=\u041d\u0435\u0442 \u0434\u043e\u0441\u0442\u0443\u043f\u0430 \u043a FFmpeg. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438\u043b\u0438 \u0434\u043e\u0431\u0430\u0432\u044c\u0442\u0435 \u043f\u0443\u0442\u044c \u043a \u043d\u0435\u0439 \u0432 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e \u043e\u043a\u0440\u0443\u0436\u0435\u043d\u0438\u044f PATH +unable_fetch_metadata=\u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u043c\u0435\u0442\u0430\u0434\u0430\u043d\u043d\u044b\u0435 +unable_send_message=\u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 +unable_build_waveform=\u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u0442\u044c \u043e\u0441\u0446\u0438\u043b\u043e\u0433\u0440\u0430\u043c\u043c\u0443 diff --git a/src/main/resources/styles/main.css b/src/main/resources/styles/main.css new file mode 100644 index 0000000..b79a5dc --- /dev/null +++ b/src/main/resources/styles/main.css @@ -0,0 +1,51 @@ +.root-pane { + -fx-background-color: #f1f1f1; +} + +.header { + -fx-background-color: #44e; + -fx-padding: 0 15 0 15; +} +.header-title { + -fx-text-fill: #fefefe; + -fx-font-family: 'Roboto Condensed'; + -fx-font-size: 30px; +} + +.icon-button { + -fx-background-color: transparent; +} +.icon-button:hover { + -fx-background-color: rgba(0,0,0,0.1); +} +.icon-button:pressed { + -fx-background-color: rgba(0,0,0,0.2); +} +.icon-button > .font-icon { + -fx-icon-color: #ddd; + -fx-icon-size: 28px; +} +.icon-button:hover > .font-icon { + -fx-icon-color: #8aed8a; + -fx-icon-size: 28px; +} + +.waveform-pane { + -fx-padding: 10; +} +.waveform-info { + -fx-text-fill: #4a4a4a; + -fx-font-family: 'Roboto Regular'; + -fx-font-size: 18px; +} +.waveform-range { + -fx-padding: 0 5 10 5; +} + +.range-slider .low-thumb, +.range-slider .high-thumb { + -fx-background-color: #44e; +} +.range-slider .range-bar { + -fx-background-color: #66e; +} \ No newline at end of file