First
This commit is contained in:
commit
02b3cb867a
24 files changed
+2629
No files matched your search
@@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- You may freely edit this file. See commented blocks below for -->
|
||||
<!-- some examples of how to customize the build. -->
|
||||
<!-- (If you delete it and reopen the project it will be recreated.) -->
|
||||
<!-- By default, only the Clean and Build commands use this build script. -->
|
||||
<!-- Commands such as Run, Debug, and Test only use this build script if -->
|
||||
<!-- the Compile on Save feature is turned off for the project. -->
|
||||
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
|
||||
<!-- in the project's Project Properties dialog box.-->
|
||||
<project name="pitiupi.audioStream" default="default" basedir=".">
|
||||
<description>Builds, tests, and runs the project pitiupi.audioStream.</description>
|
||||
<import file="nbproject/build-impl.xml"/>
|
||||
<!--
|
||||
|
||||
There exist several targets which are by default empty and which can be
|
||||
used for execution of your tasks. These targets are usually executed
|
||||
before and after some main targets. They are:
|
||||
|
||||
-pre-init: called before initialization of project properties
|
||||
-post-init: called after initialization of project properties
|
||||
-pre-compile: called before javac compilation
|
||||
-post-compile: called after javac compilation
|
||||
-pre-compile-single: called before javac compilation of single file
|
||||
-post-compile-single: called after javac compilation of single file
|
||||
-pre-compile-test: called before javac compilation of JUnit tests
|
||||
-post-compile-test: called after javac compilation of JUnit tests
|
||||
-pre-compile-test-single: called before javac compilation of single JUnit test
|
||||
-post-compile-test-single: called after javac compilation of single JUunit test
|
||||
-pre-jar: called before JAR building
|
||||
-post-jar: called after JAR building
|
||||
-post-clean: called after cleaning build products
|
||||
|
||||
(Targets beginning with '-' are not intended to be called on their own.)
|
||||
|
||||
Example of inserting an obfuscator after compilation could look like this:
|
||||
|
||||
<target name="-post-compile">
|
||||
<obfuscate>
|
||||
<fileset dir="${build.classes.dir}"/>
|
||||
</obfuscate>
|
||||
</target>
|
||||
|
||||
For list of available properties check the imported
|
||||
nbproject/build-impl.xml file.
|
||||
|
||||
|
||||
Another way to customize the build is by overriding existing main targets.
|
||||
The targets of interest are:
|
||||
|
||||
-init-macrodef-javac: defines macro for javac compilation
|
||||
-init-macrodef-junit: defines macro for junit execution
|
||||
-init-macrodef-debug: defines macro for class debugging
|
||||
-init-macrodef-java: defines macro for class execution
|
||||
-do-jar: JAR building
|
||||
run: execution of project
|
||||
-javadoc-build: Javadoc generation
|
||||
test-report: JUnit report generation
|
||||
|
||||
An example of overriding the target for project execution could look like this:
|
||||
|
||||
<target name="run" depends="pitiupi.audioStream-impl.jar">
|
||||
<exec dir="bin" executable="launcher.exe">
|
||||
<arg file="${dist.jar}"/>
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
Notice that the overridden target depends on the jar target and not only on
|
||||
the compile target as the regular run target does. Again, for a list of available
|
||||
properties which you can use, check the target you are overriding in the
|
||||
nbproject/build-impl.xml file.
|
||||
|
||||
-->
|
||||
</project>
|
||||
@@ -0,0 +1,6 @@
|
||||
#Mon, 16 Nov 2026 11:10:39 -0300
|
||||
|
||||
|
||||
/home/samuel/Documentos/UFSJ/Trabalho\ Redes/pitiupi/plugins/radio-mixxx=
|
||||
|
||||
/home/samuel/Documentos/UFSJ/Trabalho\ Redes/pitiupi/pitiupi=
|
||||
@@ -0,0 +1 @@
|
||||
pitiupi.audioStream.plugin.AudioStreamPlugin
|
||||
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,8 @@
|
||||
build.xml.data.CRC32=96758119
|
||||
build.xml.script.CRC32=70726a23
|
||||
build.xml.stylesheet.CRC32=f85dc8f2@1.119.0.48
|
||||
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
|
||||
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
|
||||
nbproject/build-impl.xml.data.CRC32=96758119
|
||||
nbproject/build-impl.xml.script.CRC32=0f906282
|
||||
nbproject/build-impl.xml.stylesheet.CRC32=12e0a6c2@1.119.0.48
|
||||
@@ -0,0 +1,98 @@
|
||||
annotation.processing.enabled=true
|
||||
annotation.processing.enabled.in.editor=false
|
||||
annotation.processing.processor.options=
|
||||
annotation.processing.processors.list=
|
||||
annotation.processing.run.all.processors=true
|
||||
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
|
||||
build.classes.dir=${build.dir}/classes
|
||||
build.classes.excludes=**/*.java,**/*.form
|
||||
# This directory is removed when the project is cleaned:
|
||||
build.dir=build
|
||||
build.generated.dir=${build.dir}/generated
|
||||
build.generated.sources.dir=${build.dir}/generated-sources
|
||||
# Only compile against the classpath explicitly listed here:
|
||||
build.sysclasspath=ignore
|
||||
build.test.classes.dir=${build.dir}/test/classes
|
||||
build.test.results.dir=${build.dir}/test/results
|
||||
# Uncomment to specify the preferred debugger connection transport:
|
||||
#debug.transport=dt_socket
|
||||
debug.classpath=\
|
||||
${run.classpath}
|
||||
debug.modulepath=\
|
||||
${run.modulepath}
|
||||
debug.test.classpath=\
|
||||
${run.test.classpath}
|
||||
debug.test.modulepath=\
|
||||
${run.test.modulepath}
|
||||
# Files in build.classes.dir which should be excluded from distribution jar
|
||||
dist.archive.excludes=
|
||||
# This directory is removed when the project is cleaned:
|
||||
dist.dir=dist
|
||||
dist.jar=${dist.dir}/pitiupi.audioStream.jar
|
||||
dist.javadoc.dir=${dist.dir}/javadoc
|
||||
dist.jlink.dir=${dist.dir}/jlink
|
||||
dist.jlink.output=${dist.jlink.dir}/pitiupi.audioStream
|
||||
excludes=
|
||||
includes=**
|
||||
jar.compress=false
|
||||
javac.classpath=\
|
||||
${reference.pitiupi.jar}
|
||||
# Space-separated list of extra javac options
|
||||
javac.compilerargs=
|
||||
javac.deprecation=false
|
||||
javac.external.vm=true
|
||||
javac.modulepath=
|
||||
javac.processormodulepath=
|
||||
javac.processorpath=\
|
||||
${javac.classpath}
|
||||
javac.source=17
|
||||
javac.target=17
|
||||
javac.test.classpath=\
|
||||
${javac.classpath}:\
|
||||
${build.classes.dir}
|
||||
javac.test.modulepath=\
|
||||
${javac.modulepath}
|
||||
javac.test.processorpath=\
|
||||
${javac.test.classpath}
|
||||
javadoc.additionalparam=
|
||||
javadoc.author=false
|
||||
javadoc.encoding=${source.encoding}
|
||||
javadoc.html5=false
|
||||
javadoc.noindex=false
|
||||
javadoc.nonavbar=false
|
||||
javadoc.notree=false
|
||||
javadoc.private=false
|
||||
javadoc.splitindex=true
|
||||
javadoc.use=true
|
||||
javadoc.version=false
|
||||
javadoc.windowtitle=
|
||||
# The jlink additional root modules to resolve
|
||||
jlink.additionalmodules=
|
||||
# The jlink additional command line parameters
|
||||
jlink.additionalparam=
|
||||
jlink.launcher=true
|
||||
jlink.launcher.name=pitiupi.audioStream
|
||||
main.class=
|
||||
manifest.file=manifest.mf
|
||||
meta.inf.dir=${src.dir}/META-INF
|
||||
mkdist.disabled=false
|
||||
platform.active=default_platform
|
||||
project.pitiupi=../../pitiupi
|
||||
reference.pitiupi.jar=${project.pitiupi}/dist/pitiupi.jar
|
||||
run.classpath=\
|
||||
${javac.classpath}:\
|
||||
${build.classes.dir}
|
||||
# Space-separated list of JVM arguments used when running the project.
|
||||
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
|
||||
# To set system properties for unit tests define test-sys-prop.name=value:
|
||||
run.jvmargs=
|
||||
run.modulepath=\
|
||||
${javac.modulepath}
|
||||
run.test.classpath=\
|
||||
${javac.test.classpath}:\
|
||||
${build.test.classes.dir}
|
||||
run.test.modulepath=\
|
||||
${javac.test.modulepath}
|
||||
source.encoding=UTF-8
|
||||
src.dir=src
|
||||
test.src.dir=test
|
||||
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://www.netbeans.org/ns/project/1">
|
||||
<type>org.netbeans.modules.java.j2seproject</type>
|
||||
<configuration>
|
||||
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
|
||||
<name>pitiupi.audioStream</name>
|
||||
<source-roots>
|
||||
<root id="src.dir"/>
|
||||
</source-roots>
|
||||
<test-roots>
|
||||
<root id="test.src.dir"/>
|
||||
</test-roots>
|
||||
</data>
|
||||
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
|
||||
<reference>
|
||||
<foreign-project>pitiupi</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
</references>
|
||||
</configuration>
|
||||
</project>
|
||||
@@ -0,0 +1 @@
|
||||
pitiupi.audioStream.plugin.AudioStreamPlugin
|
||||
@@ -0,0 +1,190 @@
|
||||
package pitiupi.audioStream.GUI;
|
||||
|
||||
import pitiupi.application.messaging.MessageDispatcher;
|
||||
import pitiupi.application.messaging.SendTarget;
|
||||
import pitiupi.application.messaging.TransportMode;
|
||||
import pitiupi.audioStream.control.AudioCapture;
|
||||
import pitiupi.audioStream.control.AudioFormatConfig;
|
||||
import pitiupi.audioStream.control.AudioPlayer;
|
||||
import pitiupi.control.ConnectionManager;
|
||||
|
||||
import javax.sound.sampled.AudioSystem;
|
||||
import javax.sound.sampled.DataLine;
|
||||
import javax.sound.sampled.Mixer;
|
||||
import javax.sound.sampled.TargetDataLine;
|
||||
import javax.swing.BorderFactory;
|
||||
import javax.swing.Box;
|
||||
import javax.swing.BoxLayout;
|
||||
import javax.swing.JCheckBox;
|
||||
import javax.swing.JComboBox;
|
||||
import javax.swing.JLabel;
|
||||
import javax.swing.JPanel;
|
||||
import javax.swing.JTextField;
|
||||
import javax.swing.JToggleButton;
|
||||
import javax.swing.Timer;
|
||||
import java.awt.BorderLayout;
|
||||
import java.awt.FlowLayout;
|
||||
import java.net.InetAddress;
|
||||
|
||||
|
||||
public class AudioStreamPanel extends JPanel {
|
||||
|
||||
private static final class DeviceItem {
|
||||
private final Mixer.Info info;
|
||||
private final String label;
|
||||
|
||||
DeviceItem(Mixer.Info info, String label) {
|
||||
this.info = info;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
private final ConnectionManager connectionManager;
|
||||
private final AudioPlayer player;
|
||||
|
||||
private final JComboBox<DeviceItem> deviceCombo = new JComboBox<>();
|
||||
private final JTextField destinationField = new JTextField(14);
|
||||
private final JToggleButton transmitToggle = new JToggleButton("Transmitir (desligado)");
|
||||
private final JCheckBox receiveCheck = new JCheckBox("Tocar áudio recebido", true);
|
||||
private final JLabel statusLabel = new JLabel(" ");
|
||||
|
||||
private AudioCapture capture;
|
||||
|
||||
private volatile String lastSender;
|
||||
private volatile long lastReceiveMillis;
|
||||
|
||||
public AudioStreamPanel(ConnectionManager connectionManager, AudioPlayer player) {
|
||||
this.connectionManager = connectionManager;
|
||||
this.player = player;
|
||||
buildLayout();
|
||||
loadDevices();
|
||||
|
||||
transmitToggle.addActionListener(e -> {
|
||||
if (transmitToggle.isSelected()) {
|
||||
startTransmitting();
|
||||
} else {
|
||||
stopTransmitting();
|
||||
}
|
||||
});
|
||||
|
||||
new Timer(1000, e -> refreshStatus()).start();
|
||||
}
|
||||
|
||||
//layout
|
||||
private void buildLayout() {
|
||||
setLayout(new BorderLayout());
|
||||
setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
|
||||
|
||||
JPanel form = new JPanel();
|
||||
form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS));
|
||||
|
||||
form.add(row(new JLabel("Dispositivo de entrada (saída do Mixxx):"), deviceCombo));
|
||||
form.add(row(new JLabel("Destino (IP; vazio = todos, multicast):"), destinationField));
|
||||
form.add(row(transmitToggle));
|
||||
form.add(Box.createVerticalStrut(8));
|
||||
form.add(row(receiveCheck));
|
||||
form.add(Box.createVerticalStrut(8));
|
||||
form.add(row(statusLabel));
|
||||
|
||||
add(form, BorderLayout.NORTH);
|
||||
}
|
||||
|
||||
private static JPanel row(java.awt.Component... components) {
|
||||
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 4));
|
||||
for (java.awt.Component c : components) {
|
||||
p.add(c);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
//dispositivos
|
||||
private void loadDevices() {
|
||||
deviceCombo.removeAllItems();
|
||||
deviceCombo.addItem(new DeviceItem(null, "Padrão do sistema"));
|
||||
|
||||
DataLine.Info info = new DataLine.Info(TargetDataLine.class, AudioFormatConfig.create());
|
||||
for (Mixer.Info mi : AudioSystem.getMixerInfo()) {
|
||||
if (AudioSystem.getMixer(mi).isLineSupported(info)) {
|
||||
deviceCombo.addItem(new DeviceItem(mi, mi.getName()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//transmissão
|
||||
private void startTransmitting() {
|
||||
try {
|
||||
//Decide o destino e transporte a partir do IP.
|
||||
String ip = destinationField.getText().trim();
|
||||
final SendTarget target;
|
||||
final TransportMode mode;
|
||||
if (ip.isEmpty()) {
|
||||
target = SendTarget.broadcastAll(); // sala inteira
|
||||
mode = TransportMode.MULTICAST_UDP; // 1 datagrama para todos
|
||||
} else {
|
||||
target = SendTarget.singlePeer(InetAddress.getByName(ip));
|
||||
mode = TransportMode.UNICAST_UDP; // direto para o IP
|
||||
}
|
||||
|
||||
//Dispositivo escolhido.
|
||||
DeviceItem item = (DeviceItem) deviceCombo.getSelectedItem();
|
||||
Mixer.Info mixer = (item == null) ? null : item.info;
|
||||
|
||||
//Cria a captura: cada bloco vira uma mensagem enviada pelo núcleo.
|
||||
capture = new AudioCapture(mixer, connectionManager.getUserName(),
|
||||
message -> MessageDispatcher.send(connectionManager, message, target, mode));
|
||||
capture.start();
|
||||
|
||||
transmitToggle.setText("Transmitir (ligado)");
|
||||
} catch (Exception ex) {
|
||||
transmitToggle.setSelected(false);
|
||||
transmitToggle.setText("Transmitir (desligado)");
|
||||
statusLabel.setText("Erro: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
//Parar transmissão.
|
||||
public void stopTransmitting() {
|
||||
if (capture != null) {
|
||||
capture.stop();
|
||||
capture = null;
|
||||
}
|
||||
transmitToggle.setSelected(false);
|
||||
transmitToggle.setText("Transmitir (desligado)");
|
||||
}
|
||||
|
||||
//Recepção
|
||||
|
||||
//Consulta pra ver se eu to recebendo
|
||||
public boolean isReceiveEnabled() {
|
||||
return receiveCheck.isSelected();
|
||||
}
|
||||
|
||||
public void reportReceived(String sender) {
|
||||
lastSender = sender;
|
||||
lastReceiveMillis = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void setDestinationIp(String ip) {
|
||||
destinationField.setText(ip == null ? "" : ip);
|
||||
}
|
||||
|
||||
//Status
|
||||
private void refreshStatus() {
|
||||
StringBuilder sb = new StringBuilder("<html>");
|
||||
if (capture != null && capture.isRunning()) {
|
||||
sb.append("Enviando: ").append(capture.getSentPackets()).append(" pacotes<br>");
|
||||
}
|
||||
boolean receiving = System.currentTimeMillis() - lastReceiveMillis < 2000;
|
||||
if (receiving) {
|
||||
sb.append("Recebendo de ").append(lastSender)
|
||||
.append(" (perdidos: ").append(player.getLostPackets()).append(")");
|
||||
}
|
||||
sb.append("</html>");
|
||||
statusLabel.setText(sb.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package pitiupi.audioStream.control;
|
||||
|
||||
import pitiupi.audioStream.net.AudioStreamMessage;
|
||||
|
||||
import javax.sound.sampled.AudioSystem;
|
||||
import javax.sound.sampled.DataLine;
|
||||
import javax.sound.sampled.LineUnavailableException;
|
||||
import javax.sound.sampled.Mixer;
|
||||
import javax.sound.sampled.TargetDataLine;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
public final class AudioCapture {
|
||||
|
||||
public interface PacketSink {
|
||||
void send(AudioStreamMessage message);
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AudioCapture.class.getName());
|
||||
|
||||
private final Mixer.Info mixerInfo;
|
||||
private final String senderName;
|
||||
private final PacketSink sink;
|
||||
|
||||
private volatile boolean running;
|
||||
private volatile long sentPackets;
|
||||
private TargetDataLine line;
|
||||
|
||||
public AudioCapture(Mixer.Info mixerInfo, String senderName, PacketSink sink) {
|
||||
this.mixerInfo = mixerInfo;
|
||||
this.senderName = senderName;
|
||||
this.sink = sink;
|
||||
}
|
||||
|
||||
// Abre o dispositivo e inicia a thread de captura.
|
||||
public synchronized void start() throws LineUnavailableException {
|
||||
if (running) {
|
||||
return;
|
||||
}
|
||||
DataLine.Info info = new DataLine.Info(TargetDataLine.class, AudioFormatConfig.create());
|
||||
line = (mixerInfo == null)
|
||||
? (TargetDataLine) AudioSystem.getLine(info)
|
||||
: (TargetDataLine) AudioSystem.getMixer(mixerInfo).getLine(info);
|
||||
|
||||
line.open(AudioFormatConfig.create(), AudioFormatConfig.PAYLOAD_SIZE * 4); //4 pacotes = baixa latência.
|
||||
line.start();
|
||||
|
||||
sentPackets = 0;
|
||||
running = true;
|
||||
|
||||
final TargetDataLine localLine = line;
|
||||
Thread thread = new Thread(() -> captureLoop(localLine), "pitiupi-audio-capture");
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
// Para a captura acorda a thread bloqueada em read
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
if (line != null) {
|
||||
line.stop();
|
||||
line.close();
|
||||
line = null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
public long getSentPackets() {
|
||||
return sentPackets;
|
||||
}
|
||||
|
||||
private void captureLoop(TargetDataLine localLine) {
|
||||
int sequence = 0;
|
||||
|
||||
while (running) {
|
||||
byte[] block = new byte[AudioFormatConfig.PAYLOAD_SIZE];
|
||||
|
||||
int n = localLine.read(block, 0, block.length);
|
||||
if (n != block.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
sink.send(new AudioStreamMessage(senderName, sequence++, block));
|
||||
sentPackets++;
|
||||
} catch (Exception ex) {
|
||||
LOG.log(Level.WARNING, "Falha ao enviar pacote de áudio", ex);
|
||||
}
|
||||
}
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package pitiupi.audioStream.control;
|
||||
|
||||
import javax.sound.sampled.AudioFormat;
|
||||
|
||||
public final class AudioFormatConfig {
|
||||
|
||||
public static final float SAMPLE_RATE = 44100f; //Taxa de amostragem
|
||||
|
||||
public static final int SAMPLE_SIZE_BITS = 16; //Bits por amostra
|
||||
|
||||
public static final int CHANNELS = 2; //Canal estério
|
||||
|
||||
public static final int FRAME_SIZE = (SAMPLE_SIZE_BITS / 8) * CHANNELS; //Bytes por frame = 2*2 = 4
|
||||
|
||||
public static final int FRAMES_PER_PACKET = 128; //Frames por pacote. 128 frames @ 44,1 kHz ≈ 2,9 ms de áudio.
|
||||
|
||||
public static final int PAYLOAD_SIZE = FRAMES_PER_PACKET * FRAME_SIZE; //Tamanho do bloco de áudio
|
||||
|
||||
private AudioFormatConfig() {
|
||||
}
|
||||
|
||||
public static AudioFormat create() {
|
||||
return new AudioFormat(SAMPLE_RATE, SAMPLE_SIZE_BITS, CHANNELS, true, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package pitiupi.audioStream.control;
|
||||
|
||||
import javax.sound.sampled.AudioSystem;
|
||||
import javax.sound.sampled.LineUnavailableException;
|
||||
import javax.sound.sampled.SourceDataLine;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public final class AudioPlayer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AudioPlayer.class.getName());
|
||||
|
||||
private static final int QUEUE_CAPACITY = 128; // ~370 ms de áudio no máximo
|
||||
private static final int PREBUFFER_PACKETS = 24; // ~70 ms antes de começar
|
||||
private static final int MAX_GAP_FILL = 16; // máx. de silêncio inserido
|
||||
private static final int RESYNC_THRESHOLD = 500; // salto que indica reinício
|
||||
private static final long SENDER_TIMEOUT_MS = 3000; // sem pacotes = acabou
|
||||
|
||||
private final BlockingQueue<byte[]> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
|
||||
|
||||
private String activeSender;
|
||||
private boolean first = true;
|
||||
private int expected;
|
||||
private long lastPacketMillis;
|
||||
private long lostPackets;
|
||||
private Thread playbackThread;
|
||||
|
||||
public synchronized void push(String sender, int seq, byte[] audio) {
|
||||
if (sender == null || audio == null || audio.length != AudioFormatConfig.PAYLOAD_SIZE) {
|
||||
return; // pacote malformado
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
boolean expired = activeSender != null && now - lastPacketMillis > SENDER_TIMEOUT_MS;
|
||||
if (activeSender == null || expired) {
|
||||
activeSender = sender;
|
||||
first = true;
|
||||
lostPackets = 0;
|
||||
queue.clear();
|
||||
ensurePlaybackThread();
|
||||
}
|
||||
if (!sender.equals(activeSender)) {
|
||||
return; //"Transmissor reserva"
|
||||
}
|
||||
lastPacketMillis = now;
|
||||
|
||||
if (first) {
|
||||
expected = seq;
|
||||
first = false;
|
||||
}
|
||||
|
||||
int diff = seq - expected;
|
||||
|
||||
if (Math.abs((long) diff) > RESYNC_THRESHOLD) {
|
||||
queue.clear();
|
||||
expected = seq;
|
||||
diff = 0;
|
||||
}
|
||||
if (diff < 0) {
|
||||
return; //atrasado ou duplicado
|
||||
}
|
||||
if (diff > 0) {
|
||||
//Tapa perda de pacotes com silêncio
|
||||
lostPackets += diff;
|
||||
int fill = Math.min(diff, MAX_GAP_FILL);
|
||||
for (int i = 0; i < fill; i++) {
|
||||
enqueue(new byte[AudioFormatConfig.PAYLOAD_SIZE]);
|
||||
}
|
||||
}
|
||||
enqueue(audio);
|
||||
expected = seq + 1;
|
||||
}
|
||||
|
||||
/** Total de pacotes perdidos na sessão atual (para exibir na interface). */
|
||||
public synchronized long getLostPackets() {
|
||||
return lostPackets;
|
||||
}
|
||||
|
||||
public synchronized void shutdown() {
|
||||
activeSender = null;
|
||||
if (playbackThread != null) {
|
||||
playbackThread.interrupt();
|
||||
playbackThread = null;
|
||||
}
|
||||
queue.clear();
|
||||
}
|
||||
|
||||
private void enqueue(byte[] data) {
|
||||
while (!queue.offer(data)) {
|
||||
queue.poll();
|
||||
}
|
||||
}
|
||||
|
||||
// Cria a thread de reprodução se ainda não existir
|
||||
private void ensurePlaybackThread() {
|
||||
if (playbackThread != null) {
|
||||
return;
|
||||
}
|
||||
Thread t = new Thread(this::playbackLoop, "pitiupi-audio-playback");
|
||||
t.setDaemon(true);
|
||||
playbackThread = t;
|
||||
t.start();
|
||||
}
|
||||
|
||||
// Tira blocos da fila e escreve na placa de som.
|
||||
private void playbackLoop() {
|
||||
try (SourceDataLine out = AudioSystem.getSourceDataLine(AudioFormatConfig.create())) {
|
||||
|
||||
out.open(AudioFormatConfig.create(), AudioFormatConfig.PAYLOAD_SIZE * 8);
|
||||
out.start();
|
||||
|
||||
//Pré-buffer
|
||||
long waitStart = System.currentTimeMillis();
|
||||
while (queue.size() < PREBUFFER_PACKETS
|
||||
&& System.currentTimeMillis() - waitStart < 2000) {
|
||||
Thread.sleep(5);
|
||||
}
|
||||
|
||||
byte[] silence = new byte[AudioFormatConfig.PAYLOAD_SIZE];
|
||||
|
||||
//Reprodução contínua.
|
||||
while (true) {
|
||||
byte[] block = queue.poll(20, TimeUnit.MILLISECONDS);
|
||||
|
||||
//Fila vazia = silêncio
|
||||
if (block == null) {
|
||||
block = silence;
|
||||
}
|
||||
|
||||
out.write(block, 0, block.length);
|
||||
|
||||
synchronized (this) {
|
||||
if (System.currentTimeMillis() - lastPacketMillis > SENDER_TIMEOUT_MS) {
|
||||
activeSender = null;
|
||||
playbackThread = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (LineUnavailableException | IllegalArgumentException e) {
|
||||
LOG.log(Level.WARNING, "Saída de áudio indisponível", e);
|
||||
synchronized (this) {
|
||||
activeSender = null;
|
||||
playbackThread = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package pitiupi.audioStream.net;
|
||||
|
||||
import pitiupi.models.Messages.Message;
|
||||
|
||||
public class AudioStreamMessage extends Message {
|
||||
|
||||
private String name;
|
||||
|
||||
private int sequence;
|
||||
|
||||
private byte[] audio;
|
||||
|
||||
public AudioStreamMessage() {
|
||||
}
|
||||
|
||||
public AudioStreamMessage(String name, int sequence, byte[] audio) {
|
||||
this.name = name;
|
||||
this.sequence = sequence;
|
||||
this.audio = audio;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getSequence() {
|
||||
return sequence;
|
||||
}
|
||||
|
||||
public void setSequence(int sequence) {
|
||||
this.sequence = sequence;
|
||||
}
|
||||
|
||||
public byte[] getAudio() {
|
||||
return audio;
|
||||
}
|
||||
|
||||
public void setAudio(byte[] audio) {
|
||||
this.audio = audio;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package pitiupi.audioStream.plugin;
|
||||
|
||||
import pitiupi.api.plugin.PeerActionsRegistrar;
|
||||
import pitiupi.api.plugin.PluginWorkspace;
|
||||
import pitiupi.application.peeractions.PeerAction;
|
||||
import pitiupi.application.peeractions.PeerActionTarget;
|
||||
import pitiupi.application.peeractions.PeerTarget;
|
||||
import pitiupi.audioStream.GUI.AudioStreamPanel;
|
||||
import pitiupi.audioStream.control.AudioPlayer;
|
||||
import pitiupi.audioStream.net.AudioStreamMessage;
|
||||
import pitiupi.control.ConnectionManager;
|
||||
import pitiupi.models.Messages.Message;
|
||||
import pitiupi.models.Plugin;
|
||||
import pitiupi.presentation.shell.PeerIpv4;
|
||||
|
||||
import java.util.List;
|
||||
public class AudioStreamPlugin extends Plugin {
|
||||
|
||||
private AudioStreamPanel panel;
|
||||
private PluginWorkspace workspace;
|
||||
private ConnectionManager connectionManager;
|
||||
|
||||
private final AudioPlayer player = new AudioPlayer();
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "AudioStream";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return "Transmitir áudio";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthor() {
|
||||
return "Trabalho de faculdade";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return "0.1";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdentifier() {
|
||||
return "Pitiupi.AudioStream";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createPlugin(ConnectionManager connectionManager, PluginWorkspace workspace) {
|
||||
this.connectionManager = connectionManager;
|
||||
this.workspace = workspace;
|
||||
this.panel = new AudioStreamPanel(connectionManager, player);
|
||||
|
||||
// Entrega o painel à shell (o PitiUPi não usa JFrame próprio por plugin).
|
||||
bindShellWorkspaceContent(panel);
|
||||
installPeerActions(workspace.peerActions());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShellTabClosed() {
|
||||
if (panel != null) {
|
||||
panel.stopTransmitting();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void installPeerActions(PeerActionsRegistrar registrar) {
|
||||
registrar.register(PeerAction.of(
|
||||
"audiostream.all",
|
||||
"Transmitir áudio para todos",
|
||||
PeerActionTarget.ALL_PEERS,
|
||||
target -> {
|
||||
workspace.openOrFocusTab(getIdentifier(), getDisplayName());
|
||||
panel.setDestinationIp("");
|
||||
}
|
||||
));
|
||||
|
||||
registrar.register(PeerAction.of(
|
||||
"audiostream.peer",
|
||||
"Transmitir áudio para esta pessoa",
|
||||
PeerActionTarget.SINGLE_PEER,
|
||||
target -> {
|
||||
workspace.openOrFocusTab(getIdentifier(), getDisplayName());
|
||||
if (target instanceof PeerTarget.Single single) {
|
||||
single.peer().getInetAddress()
|
||||
.ifPresent(addr -> panel.setDestinationIp(PeerIpv4.fromInetAddress(addr)));
|
||||
}
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
//Recepção
|
||||
@Override
|
||||
public List<Class<? extends Message>> getMessages() {
|
||||
return List.of(AudioStreamMessage.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveMessage(Message message) {
|
||||
if (!(message instanceof AudioStreamMessage audioMsg) || panel == null) {
|
||||
return;
|
||||
}
|
||||
// Ignora o próprio áudio (eco): o multicast pode voltar para quem enviou.
|
||||
String localName = connectionManager.getUserName();
|
||||
if (localName != null && localName.equals(audioMsg.getName())) {
|
||||
return;
|
||||
}
|
||||
panel.reportReceived(audioMsg.getName());
|
||||
|
||||
if (panel.isReceiveEnabled()) {
|
||||
player.push(audioMsg.getName(), audioMsg.getSequence(), audioMsg.getAudio());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user