move everything out of subdirectory

This commit is contained in:
Aaron Neyer
2013-12-15 14:12:57 -05:00
parent 71aacf1305
commit fed46a2a49
151 changed files with 191 additions and 2359 deletions

View File

@@ -0,0 +1,199 @@
package com.limelight;
import java.lang.reflect.Constructor;
import java.util.LinkedList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import com.limelight.binding.PlatformBinding;
import com.limelight.gui.MainFrame;
import com.limelight.gui.StreamFrame;
import com.limelight.input.GamepadHandler;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.NvConnectionListener;
import com.limelight.nvstream.av.video.VideoDecoderRenderer;
public class Limelight implements NvConnectionListener {
public static final double VERSION = 1.0;
private String host;
private StreamFrame streamFrame;
private NvConnection conn;
private boolean connectionFailed;
private static JFrame limeFrame;
private Thread controllerListenerThread;
public Limelight(String host) {
this.host = host;
}
private void startUp(boolean fullscreen) {
streamFrame = new StreamFrame();
conn = new NvConnection(host, this);
streamFrame.build(conn, fullscreen);
conn.start(PlatformBinding.getDeviceName(), streamFrame,
VideoDecoderRenderer.FLAG_PREFER_QUALITY,
PlatformBinding.getAudioRenderer(),
PlatformBinding.getVideoDecoderRenderer());
}
private void startControllerListener() {
controllerListenerThread = new Thread() {
@Override
public void run() {
/*
* This is really janky, but it is currently the only way to rescan for controllers.
* The DefaultControllerEnvironment class caches the results of scanning and if a controller is
* unplugged or plugged in, it will not detect it. Since DefaultControllerEnvironment is package-protected
* we have to use reflections in order to manually instantiate a new instance to ensure there is no caching.
* Supposedly Aaron is going to fix JInput and we will have the ability to rescan soon!
*/
try {
//#allthejank
Constructor<? extends ControllerEnvironment> construct = null;
Class<? extends ControllerEnvironment> defEnv = ControllerEnvironment.getDefaultEnvironment().getClass();
construct = defEnv.getDeclaredConstructor();
construct.setAccessible(true);
while(!isInterrupted()) {
ControllerEnvironment defaultEnv = null;
defaultEnv = (ControllerEnvironment)construct.newInstance();
Controller[] ca = defaultEnv.getControllers();
LinkedList<Controller> gamepads = new LinkedList<Controller>();
/*
* iterates through the controllers and adds gamepads and ps3 controller to the list
* NOTE: JInput does not consider a PS3 controller to be a gamepad (it thinks it's a "STICK") so we must use the
* name of it.
*/
for(int i = 0; i < ca.length; i++){
if (ca[i].getType() == Controller.Type.GAMEPAD) {
gamepads.add(ca[i]);
} else if (ca[i].getName().contains("PLAYSTATION")) {
gamepads.add(ca[i]);
}
}
GamepadHandler.addGamepads(gamepads, conn);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
controllerListenerThread.start();
}
private static void createFrame() {
MainFrame main = new MainFrame();
main.build();
limeFrame = main.getLimeFrame();
}
public static void createInstance(String host, boolean fullscreen) {
Limelight limelight = new Limelight(host);
limelight.startUp(fullscreen);
}
public static void main(String args[]) {
//fix the menu bar if we are running in osx
if (System.getProperty("os.name").contains("Mac OS X")) {
// take the menu bar off the jframe
System.setProperty("apple.laf.useScreenMenuBar", "true");
// set the name of the application menu item
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Limelight");
} else {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Unable to set cross platform look and feel.");
e.printStackTrace();
System.exit(2);
}
}
createFrame();
}
@Override
public void stageStarting(Stage stage) {
System.out.println("Starting "+stage.getName());
streamFrame.showSpinner(stage);
}
@Override
public void stageComplete(Stage stage) {
}
@Override
public void stageFailed(Stage stage) {
streamFrame.dispose();
conn.stop();
displayError("Connection Error", "Starting " + stage.getName() + " failed");
}
@Override
public void connectionStarted() {
streamFrame.hideSpinner();
startControllerListener();
}
@Override
public void connectionTerminated(Exception e) {
e.printStackTrace();
if (!connectionFailed) {
connectionFailed = true;
// Kill the connection to the target
conn.stop();
// Kill the controller rescanning thread
if (controllerListenerThread != null) {
controllerListenerThread.interrupt();
try {
controllerListenerThread.join();
} catch (InterruptedException e1) {}
}
// Spin off a new thread to update the UI since
// this thread has been interrupted and will terminate
// shortly
new Thread(new Runnable() {
@Override
public void run() {
streamFrame.dispose();
displayError("Connection Terminated", "The connection failed unexpectedly");
}
}).start();
}
}
@Override
public void displayMessage(String message) {
JOptionPane.showMessageDialog(limeFrame, message, "Limelight", JOptionPane.INFORMATION_MESSAGE);
}
public void displayError(String title, String message) {
JOptionPane.showMessageDialog(limeFrame, message, title, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,27 @@
package com.limelight.binding;
import java.net.InetAddress;
import java.net.UnknownHostException;
import com.limelight.binding.audio.JavaxAudioRenderer;
import com.limelight.binding.video.SwingCpuDecoderRenderer;
import com.limelight.nvstream.av.audio.AudioRenderer;
import com.limelight.nvstream.av.video.VideoDecoderRenderer;
public class PlatformBinding {
public static VideoDecoderRenderer getVideoDecoderRenderer() {
return new SwingCpuDecoderRenderer();
}
public static String getDeviceName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "LimelightPC";
}
}
public static AudioRenderer getAudioRenderer() {
return new JavaxAudioRenderer();
}
}

View File

@@ -0,0 +1,52 @@
package com.limelight.binding.audio;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import com.limelight.nvstream.av.audio.AudioRenderer;
import com.limelight.nvstream.av.audio.OpusDecoder;
public class JavaxAudioRenderer implements AudioRenderer {
private SourceDataLine soundLine;
@Override
public void playDecodedAudio(short[] pcmData, int offset, int length) {
if (soundLine != null) {
byte[] pcmDataBytes = new byte[length * 2];
ByteBuffer.wrap(pcmDataBytes).asShortBuffer().put(pcmData, offset, length);
if (soundLine.available() < length) {
soundLine.write(pcmDataBytes, 0, soundLine.available());
}
else {
soundLine.write(pcmDataBytes, 0, pcmDataBytes.length);
}
}
}
@Override
public void streamClosing() {
if (soundLine != null) {
soundLine.close();
}
}
@Override
public void streamInitialized(int channelCount, int sampleRate) {
AudioFormat audioFormat = new AudioFormat(sampleRate, 16, channelCount, true, true);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat, OpusDecoder.getMaxOutputShorts());
try {
soundLine = (SourceDataLine) AudioSystem.getLine(info);
soundLine.open(audioFormat, OpusDecoder.getMaxOutputShorts()*4*2);
soundLine.start();
} catch (LineUnavailableException e) {
soundLine = null;
}
}
}

View File

@@ -0,0 +1,159 @@
package com.limelight.binding.video;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.nio.ByteBuffer;
import javax.swing.JFrame;
import com.limelight.nvstream.av.ByteBufferDescriptor;
import com.limelight.nvstream.av.DecodeUnit;
import com.limelight.nvstream.av.video.VideoDecoderRenderer;
import com.limelight.nvstream.av.video.cpu.AvcDecoder;
public class SwingCpuDecoderRenderer implements VideoDecoderRenderer {
private Thread rendererThread;
private int targetFps;
private int width, height;
private Graphics graphics;
private JFrame frame;
private BufferedImage image;
private static final int DECODER_BUFFER_SIZE = 92*1024;
private ByteBuffer decoderBuffer;
// Only sleep if the difference is above this value
private static final int WAIT_CEILING_MS = 8;
@Override
public void setup(int width, int height, Object renderTarget, int drFlags) {
this.targetFps = 30;
this.width = width;
this.height = height;
// Single threaded low latency decode is ideal
int avcFlags = AvcDecoder.LOW_LATENCY_DECODE;
int threadCount = 1;
// Hack to work around the bad Java native library loader
// which can't resolve native library dependencies
if (System.getProperty("os.name").contains("Windows")) {
System.loadLibrary("avutil-52");
System.loadLibrary("postproc-52");
System.loadLibrary("pthreadVC2");
}
int err = AvcDecoder.init(width, height, avcFlags, threadCount);
if (err != 0) {
throw new IllegalStateException("AVC decoder initialization failure: "+err);
}
frame = (JFrame)renderTarget;
graphics = frame.getGraphics();
image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_BGR);
decoderBuffer = ByteBuffer.allocate(DECODER_BUFFER_SIZE + AvcDecoder.getInputPaddingSize());
System.out.println("Using software decoding");
}
@Override
public void start() {
rendererThread = new Thread() {
@Override
public void run() {
long nextFrameTime = System.currentTimeMillis();
int[] imageBuffer = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
while (!isInterrupted())
{
long diff = nextFrameTime - System.currentTimeMillis();
if (diff < WAIT_CEILING_MS) {
// We must call Thread.sleep in order to be interruptable
diff = 0;
}
try {
Thread.sleep(diff);
} catch (InterruptedException e) {
return;
}
nextFrameTime = computePresentationTimeMs(targetFps);
double widthScale = (double)frame.getWidth() / width;
double heightScale = (double)frame.getHeight() / height;
double lowerScale = Math.min(widthScale, heightScale);
int newWidth = (int)(width * lowerScale);
int newHeight = (int)(height * lowerScale);
int dx1 = 0;
int dy1 = 0;
if (frame.getWidth() > newWidth) {
dx1 = (frame.getWidth()-newWidth)/4;
}
if (frame.getHeight() > newHeight) {
dy1 = (frame.getHeight()-newHeight)/4;
}
if (AvcDecoder.getRgbFrameInt(imageBuffer, imageBuffer.length)) {
graphics.drawImage(image, dx1, dy1, dx1+newWidth, dy1+newHeight, 0, 0, width, height, null);
}
}
}
};
rendererThread.setName("Video - Renderer (CPU)");
rendererThread.start();
}
private long computePresentationTimeMs(int frameRate) {
return System.currentTimeMillis() + (1000 / frameRate);
}
@Override
public void stop() {
rendererThread.interrupt();
try {
rendererThread.join();
} catch (InterruptedException e) { }
}
@Override
public void release() {
AvcDecoder.destroy();
}
@Override
public boolean submitDecodeUnit(DecodeUnit decodeUnit) {
byte[] data;
// Use the reserved decoder buffer if this decode unit will fit
if (decodeUnit.getDataLength() <= DECODER_BUFFER_SIZE) {
decoderBuffer.clear();
for (ByteBufferDescriptor bbd : decodeUnit.getBufferList()) {
decoderBuffer.put(bbd.data, bbd.offset, bbd.length);
}
data = decoderBuffer.array();
}
else {
data = new byte[decodeUnit.getDataLength()+AvcDecoder.getInputPaddingSize()];
int offset = 0;
for (ByteBufferDescriptor bbd : decodeUnit.getBufferList()) {
System.arraycopy(bbd.data, bbd.offset, data, offset, bbd.length);
offset += bbd.length;
}
}
return (AvcDecoder.decode(data, 0, decodeUnit.getDataLength()) == 0);
}
}

View File

@@ -0,0 +1,169 @@
package com.limelight.gui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.xmlpull.v1.XmlPullParserException;
import com.limelight.Limelight;
import com.limelight.binding.PlatformBinding;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.http.NvHTTP;
public class MainFrame {
private JTextField hostField;
private JButton pair;
private JButton stream;
private JCheckBox fullscreen;
private JFrame limeFrame;
public JFrame getLimeFrame() {
return limeFrame;
}
public void build() {
limeFrame = new JFrame("Limelight");
limeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mainPane = limeFrame.getContentPane();
mainPane.setLayout(new BorderLayout());
JPanel centerPane = new JPanel();
centerPane.setLayout(new BoxLayout(centerPane, BoxLayout.Y_AXIS));
hostField = new JTextField();
hostField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 24));
hostField.setToolTipText("Enter host name or IP address");
hostField.setText("GeForce PC host");
hostField.setSelectionStart(0);
hostField.setSelectionEnd(hostField.getText().length());
stream = new JButton("Start Streaming");
stream.addActionListener(createStreamButtonListener());
stream.setToolTipText("Start the GeForce stream");
pair = new JButton("Pair");
pair.addActionListener(createPairButtonListener());
pair.setToolTipText("Send pair request to GeForce PC");
fullscreen = new JCheckBox("Fullscreen", true);
Box streamBox = Box.createHorizontalBox();
streamBox.add(Box.createHorizontalGlue());
streamBox.add(stream);
streamBox.add(Box.createHorizontalGlue());
Box pairBox = Box.createHorizontalBox();
pairBox.add(Box.createHorizontalGlue());
pairBox.add(pair);
pairBox.add(Box.createHorizontalGlue());
Box hostBox = Box.createHorizontalBox();
hostBox.add(Box.createHorizontalStrut(20));
hostBox.add(hostField);
hostBox.add(Box.createHorizontalStrut(20));
Box contentBox = Box.createVerticalBox();
contentBox.add(Box.createVerticalStrut(20));
contentBox.add(hostBox);
contentBox.add(Box.createVerticalStrut(5));
contentBox.add(fullscreen);
contentBox.add(Box.createVerticalStrut(5));
contentBox.add(streamBox);
contentBox.add(Box.createVerticalStrut(10));
contentBox.add(pairBox);
contentBox.add(Box.createVerticalGlue());
centerPane.add(contentBox);
mainPane.add(centerPane, "Center");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
limeFrame.getRootPane().setDefaultButton(stream);
limeFrame.setSize(300, 175);
limeFrame.setLocation(dim.width/2-limeFrame.getSize().width/2, dim.height/2-limeFrame.getSize().height/2);
limeFrame.setResizable(false);
limeFrame.setVisible(true);
}
private ActionListener createStreamButtonListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Limelight.createInstance(hostField.getText(), fullscreen.isSelected());
}
};
}
private ActionListener createPairButtonListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new Thread(new Runnable() {
@Override
public void run() {
String macAddress;
try {
macAddress = NvConnection.getMacAddressString();
} catch (SocketException e) {
e.printStackTrace();
return;
}
if (macAddress == null) {
System.out.println("Couldn't find a MAC address");
return;
}
NvHTTP httpConn;
String message;
try {
httpConn = new NvHTTP(InetAddress.getByName(hostField.getText()),
macAddress, PlatformBinding.getDeviceName());
try {
if (httpConn.getPairState()) {
message = "Already paired";
}
else {
int session = httpConn.getSessionId();
if (session == 0) {
message = "Pairing was declined by the target";
}
else {
message = "Pairing was successful";
}
}
} catch (IOException e) {
message = e.getMessage();
} catch (XmlPullParserException e) {
message = e.getMessage();
}
} catch (UnknownHostException e1) {
message = "Failed to resolve host";
}
JOptionPane.showMessageDialog(limeFrame, message, "Limelight", JOptionPane.INFORMATION_MESSAGE);
}
}).start();
}
};
}
}

View File

@@ -0,0 +1,197 @@
package com.limelight.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Comparator;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import com.limelight.input.KeyboardHandler;
import com.limelight.input.MouseHandler;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.NvConnectionListener.Stage;
public class StreamFrame extends JFrame {
private static final long serialVersionUID = 1L;
private KeyboardHandler keyboard;
private MouseHandler mouse;
private JProgressBar spinner;
private JLabel spinnerLabel;
private Cursor noCursor;
private NvConnection conn;
private static final int WIDTH = 1280;
private static final int HEIGHT = 720;
public void freeMouse() {
mouse.free();
showCursor();
}
public void captureMouse() {
mouse.capture();
hideCursor();
}
public void build(NvConnection conn, boolean fullscreen) {
this.conn = conn;
keyboard = new KeyboardHandler(conn, this);
mouse = new MouseHandler(conn, this);
this.addKeyListener(keyboard);
this.addMouseListener(mouse);
this.addMouseMotionListener(mouse);
this.setFocusTraversalKeysEnabled(false);
this.setSize(WIDTH, HEIGHT);
this.setBackground(Color.BLACK);
this.getContentPane().setBackground(Color.BLACK);
this.getRootPane().setBackground(Color.BLACK);
if (fullscreen) {
makeFullScreen();
}
hideCursor();
this.setVisible(true);
}
private DisplayMode getBestDisplay(DisplayMode[] configs) {
Arrays.sort(configs, new Comparator<DisplayMode>() {
@Override
public int compare(DisplayMode o1, DisplayMode o2) {
if (o1.getWidth() > o2.getWidth()) {
return -1;
} else if (o2.getWidth() > o1.getWidth()) {
return 1;
} else {
return 0;
}
}
});
DisplayMode bestConfig = null;
for (DisplayMode config : configs) {
if (config.getWidth() >= 1280 && config.getHeight() >= 720) {
bestConfig = config;
}
}
if (bestConfig == null) {
return configs[0];
}
return bestConfig;
}
private void makeFullScreen() {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
this.setUndecorated(true);
gd.setFullScreenWindow(this);
if (gd.isDisplayChangeSupported()) {
DisplayMode config = getBestDisplay(gd.getDisplayModes());
if (config != null) {
gd.setDisplayMode(config);
}
} else {
JOptionPane.showMessageDialog(
this,
"Unable to change display resolution. \nThis may not be the correct resolution",
"Display Resolution",
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(
this,
"Your operating system does not support fullscreen.",
"Fullscreen Unsupported",
JOptionPane.ERROR_MESSAGE);
}
}
public void hideCursor() {
if (noCursor == null) {
// Transparent 16 x 16 pixel cursor image.
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
// Create a new blank cursor.
noCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor");
}
// Set the blank cursor to the JFrame.
this.setCursor(noCursor);
this.getContentPane().setCursor(noCursor);
}
public void showCursor() {
this.setCursor(Cursor.getDefaultCursor());
this.getContentPane().setCursor(Cursor.getDefaultCursor());
}
public void showSpinner(Stage stage) {
if (spinner == null) {
Container c = this.getContentPane();
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
spinner = new JProgressBar();
spinner.setIndeterminate(true);
spinner.setMaximumSize(new Dimension(150, 30));
spinnerLabel = new JLabel();
spinnerLabel.setForeground(Color.white);
Box spinBox = Box.createHorizontalBox();
spinBox.add(Box.createHorizontalGlue());
spinBox.add(spinner);
spinBox.add(Box.createHorizontalGlue());
Box lblBox = Box.createHorizontalBox();
lblBox.add(Box.createHorizontalGlue());
lblBox.add(spinnerLabel);
lblBox.add(Box.createHorizontalGlue());
panel.add(Box.createVerticalGlue());
panel.add(spinBox);
panel.add(Box.createVerticalStrut(10));
panel.add(lblBox);
panel.add(Box.createVerticalGlue());
c.setLayout(new BorderLayout());
c.add(panel, "Center");
}
spinnerLabel.setText("Starting " + stage.getName() + "...");
}
public void hideSpinner() {
spinner.setVisible(false);
spinnerLabel.setVisible(false);
}
public void close() {
dispose();
conn.stop();
}
}

View File

@@ -0,0 +1,128 @@
package com.limelight.input;
import com.limelight.nvstream.NvConnection;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.Event;
import net.java.games.input.EventQueue;
public abstract class Gamepad {
protected Controller pad;
private NvConnection conn;
protected short inputMap = 0x0000;
protected byte leftTrigger = 0x00;
protected byte rightTrigger = 0x00;
protected short rightStickX = 0x0000;
protected short rightStickY = 0x0000;
protected short leftStickX = 0x0000;
protected short leftStickY = 0x0000;
public enum ControllerType { XBOX, PS3 };
public static Gamepad createInstance(NvConnection conn, Controller pad, ControllerType type) {
switch (type) {
case XBOX:
return new XBox360Controller(conn, pad);
case PS3:
return new PS3Controller(conn, pad);
default:
return new XBox360Controller(conn, pad);
}
}
public Gamepad(NvConnection conn, Controller pad) {
this.conn = conn;
this.pad = pad;
for (Component comp : pad.getComponents()) {
initValue(comp);
}
}
private void initValue(Component comp) {
handleComponent(comp, comp.getPollData());
}
public boolean poll() {
return pad.poll();
}
public void sendControllerPacket() {
conn.sendControllerInput(inputMap, leftTrigger, rightTrigger,
leftStickX, leftStickY, rightStickX, rightStickY);
}
public void handleEvents() {
EventQueue queue = pad.getEventQueue();
Event event = new Event();
while(queue.getNextEvent(event)) {
/* uncommented for debugging */
//printInfo(pad, event);
handleEvent(event);
sendControllerPacket();
}
}
/*
* used for debugging, normally unused.
*/
@SuppressWarnings("unused")
private void printInfo(Controller gamepad, Event event) {
Component comp = event.getComponent();
StringBuilder builder = new StringBuilder(gamepad.getName());
builder.append(" at ");
builder.append(event.getNanos()).append(": ");
builder.append(comp.getName()).append(" changed to ");
float value = event.getValue();
if(comp.isAnalog()) {
builder.append(value);
} else {
if(value==1.0f) {
builder.append("On");
} else {
builder.append("Off");
}
}
System.out.println(builder.toString());
}
private void handleEvent(Event event) {
Component comp = event.getComponent();
float value = event.getValue();
handleComponent(comp, value);
}
private void handleComponent(Component comp, float value) {
if (comp.isAnalog()) {
handleAnalog(comp, value);
} else {
handleButtons(comp, value);
}
}
protected void toggle(short button, boolean press) {
if (press) {
inputMap |= button;
} else {
inputMap &= ~button;
}
}
protected abstract void handleAnalog(Component comp, float value);
protected abstract void handleButtons(Component comp, float value);
}

View File

@@ -0,0 +1,59 @@
package com.limelight.input;
import java.util.LinkedList;
import java.util.List;
import com.limelight.input.Gamepad.ControllerType;
import com.limelight.nvstream.NvConnection;
import net.java.games.input.Controller;
public class GamepadHandler {
private static LinkedList<Gamepad> gamepads = new LinkedList<Gamepad>();
private static GamepadHandler singleton;
public static void addGamepads(List<Controller> pads, NvConnection conn) {
if (singleton == null) {
singleton = new GamepadHandler();
singleton.startUp();
}
gamepads.clear();
for (Controller pad : pads) {
gamepads.add(Gamepad.createInstance(conn, pad, getType(pad)));
}
}
private static ControllerType getType(Controller pad) {
if (pad.getType() == Controller.Type.GAMEPAD) {
return ControllerType.XBOX;
}
if (pad.getName().contains("PLAYSTATION")) {
return ControllerType.PS3;
}
return null;
}
private void startUp() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
for (Gamepad gamepad : gamepads) {
if (!gamepad.poll()) {
break;
}
gamepad.handleEvents();
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
}
}
}).start();
}
}

View File

@@ -0,0 +1,87 @@
package com.limelight.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import com.limelight.gui.StreamFrame;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.input.KeyboardPacket;
public class KeyboardHandler implements KeyListener {
private static KeyboardTranslator translator;
private StreamFrame parent;
public KeyboardHandler(NvConnection conn, StreamFrame parent) {
translator = new KeyboardTranslator(conn);
this.parent = parent;
}
@Override
public void keyPressed(KeyEvent event) {
short keyMap = translator.translate(event.getKeyCode());
byte modifier = 0x0;
int modifiers = event.getModifiersEx();
if ((modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0) {
modifier |= KeyboardPacket.MODIFIER_SHIFT;
}
if ((modifiers & KeyEvent.CTRL_DOWN_MASK) != 0) {
modifier |= KeyboardPacket.MODIFIER_CTRL;
}
if ((modifiers & KeyEvent.ALT_DOWN_MASK) != 0) {
modifier |= KeyboardPacket.MODIFIER_ALT;
}
if ((modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0 &&
(modifiers & KeyEvent.ALT_DOWN_MASK) != 0 &&
(modifiers & KeyEvent.CTRL_DOWN_MASK) != 0 &&
event.getKeyCode() == KeyEvent.VK_Q) {
System.out.println("quitting");
parent.close();
} else if (
(modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0 &&
(modifiers & KeyEvent.ALT_DOWN_MASK) != 0 &&
(modifiers & KeyEvent.CTRL_DOWN_MASK) != 0) {
parent.freeMouse();
return;
}
translator.sendKeyDown(keyMap, modifier);
}
@Override
public void keyReleased(KeyEvent event) {
int modifiers = event.getModifiersEx();
if ((modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0 ||
(modifiers & KeyEvent.ALT_DOWN_MASK) != 0 ||
(modifiers & KeyEvent.CTRL_DOWN_MASK) != 0) {
parent.captureMouse();
}
short keyMap = translator.translate(event.getKeyCode());
byte modifier = 0x0;
if ((modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0) {
modifier |= KeyboardPacket.MODIFIER_SHIFT;
}
if ((modifiers & KeyEvent.CTRL_DOWN_MASK) != 0) {
modifier |= KeyboardPacket.MODIFIER_CTRL;
}
if ((modifiers & KeyEvent.ALT_DOWN_MASK) != 0) {
modifier |= KeyboardPacket.MODIFIER_ALT;
}
translator.sendKeyUp(keyMap, modifier);
}
@Override
public void keyTyped(KeyEvent event) {
}
}

View File

@@ -0,0 +1,36 @@
package com.limelight.input;
import java.awt.event.KeyEvent;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.input.KeycodeTranslator;
public class KeyboardTranslator extends KeycodeTranslator {
public static final short KEY_PREFIX = (short) 0x80;
public KeyboardTranslator(NvConnection conn) {
super(conn);
}
@Override
public short translate(int keycode) {
// change newline to carriage return
if (keycode == KeyEvent.VK_ENTER) {
keycode = 0x0d;
}
// period maps to delete by default so we remap it
if (keycode == KeyEvent.VK_PERIOD) {
keycode = 0xbe;
}
// Nvidia maps period to delete
if (keycode == KeyEvent.VK_DELETE) {
keycode = KeyEvent.VK_PERIOD;
}
return (short) ((KEY_PREFIX << 8) | keycode);
}
}

View File

@@ -0,0 +1,171 @@
package com.limelight.input;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.SwingUtilities;
import com.limelight.gui.StreamFrame;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.input.MouseButtonPacket;
public class MouseHandler implements MouseListener, MouseMotionListener {
private NvConnection conn;
private Robot robot;
private Dimension size;
private StreamFrame parent;
private int lastX = 0;
private int lastY = 0;
private boolean captureMouse = true;
private final double mouseThresh = 0.45;
public MouseHandler(NvConnection conn, StreamFrame parent) {
this.conn = conn;
this.parent = parent;
try {
this.robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
size = new Dimension();
}
public void free() {
captureMouse = false;
}
public void capture() {
moveMouse((int)parent.getLocationOnScreen().getX() + (size.width/2),
(int)parent.getLocationOnScreen().getY() + (size.height/2));
captureMouse = true;
}
@Override
public void mouseClicked(MouseEvent e) {
if (captureMouse) {
parent.hideCursor();
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
if (captureMouse) {
checkBoundaries(e);
}
}
@Override
public void mousePressed(MouseEvent e) {
if (captureMouse) {
byte mouseButton = 0x0;
if (SwingUtilities.isLeftMouseButton(e)) {
mouseButton = MouseButtonPacket.BUTTON_1;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
mouseButton = MouseButtonPacket.BUTTON_2;
}
if (SwingUtilities.isRightMouseButton(e)) {
mouseButton = MouseButtonPacket.BUTTON_3;
}
if (mouseButton > 0) {
conn.sendMouseButtonDown(mouseButton);
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (captureMouse) {
byte mouseButton = 0x0;
if (SwingUtilities.isLeftMouseButton(e)) {
mouseButton = MouseButtonPacket.BUTTON_1;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
mouseButton = MouseButtonPacket.BUTTON_2;
}
if (SwingUtilities.isRightMouseButton(e)) {
mouseButton = MouseButtonPacket.BUTTON_3;
}
if (mouseButton > 0) {
conn.sendMouseButtonUp(mouseButton);
}
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (captureMouse) {
mouseMoved(e);
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (captureMouse) {
Point mouse = e.getLocationOnScreen();
int x = (int)mouse.getX();
int y = (int)mouse.getY();
conn.sendMouseMove((short)(x - lastX), (short)(y - lastY));
lastX = x;
lastY = y;
checkBoundaries(e);
}
}
private void checkBoundaries(MouseEvent e) {
parent.getSize(size);
int leftEdge = (int) parent.getLocationOnScreen().getX();
int rightEdge = leftEdge + size.width;
int upperEdge = (int) parent.getLocationOnScreen().getY();
int lowerEdge = upperEdge + size.height;
Point mouse = e.getLocationOnScreen();
double xThresh = (size.width * mouseThresh);
double yThresh = (size.height * mouseThresh);
int newX = (int)mouse.getX();
int newY = (int)mouse.getY();
boolean shouldMoveMouse = false;
if (mouse.getX() < leftEdge + xThresh || mouse.getX() > rightEdge - xThresh) {
newX = (leftEdge + rightEdge) / 2;
shouldMoveMouse = true;
}
if (mouse.getY() < upperEdge + yThresh || mouse.getY() > lowerEdge - yThresh) {
newY = (upperEdge + lowerEdge) / 2;
shouldMoveMouse = true;
}
if (shouldMoveMouse) {
moveMouse(newX, newY);
}
}
private void moveMouse(int x, int y) {
robot.mouseMove(x, y);
lastX = x;
lastY = y;
}
}

View File

@@ -0,0 +1,71 @@
package com.limelight.input;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.input.ControllerPacket;
import net.java.games.input.Component;
import net.java.games.input.Controller;
public class PS3Controller extends Gamepad {
public PS3Controller(NvConnection conn, Controller pad) {
super(conn, pad);
}
@Override
protected void handleAnalog(Component comp, float value) {
Component.Identifier id = comp.getIdentifier();
if (id == Component.Identifier.Axis.Z) {
rightStickX = (short)Math.round(value * 0x7FFF);
} else if (id == Component.Identifier.Axis.RZ) {
rightStickY = (short)Math.round(-value * 0x7FFF);
} else if (id == Component.Identifier.Axis.X) {
leftStickX = (short)Math.round(value * 0x7FFF);
} else if (id == Component.Identifier.Axis.Y) {
leftStickY = (short)Math.round(-value * 0x7FFF);
}
}
@Override
protected void handleButtons(Component comp, float value) {
Component.Identifier id = comp.getIdentifier();
boolean press = value > 0.5F;
if (id == Component.Identifier.Button._7) {
toggle(ControllerPacket.LEFT_FLAG, press);
} else if (id == Component.Identifier.Button._5) {
toggle(ControllerPacket.RIGHT_FLAG, press);
} else if (id == Component.Identifier.Button._4) {
toggle(ControllerPacket.UP_FLAG, press);
} else if (id == Component.Identifier.Button._6) {
toggle(ControllerPacket.DOWN_FLAG, press);
} else if (id == Component.Identifier.Button._14) {
toggle(ControllerPacket.A_FLAG, press);
} else if (id == Component.Identifier.Button._15) {
toggle(ControllerPacket.X_FLAG, press);
} else if (id == Component.Identifier.Button._12) {
toggle(ControllerPacket.Y_FLAG, press);
} else if (id == Component.Identifier.Button._13) {
toggle(ControllerPacket.B_FLAG, press);
} else if (id == Component.Identifier.Button._0) {
toggle(ControllerPacket.BACK_FLAG, press);
} else if (id == Component.Identifier.Button._3) {
toggle(ControllerPacket.PLAY_FLAG, press);
} else if (id == Component.Identifier.Button._2) {
toggle(ControllerPacket.RS_CLK_FLAG, press);
} else if (id == Component.Identifier.Button._1) {
toggle(ControllerPacket.LS_CLK_FLAG, press);
} else if (id == Component.Identifier.Button._10) {
toggle(ControllerPacket.LB_FLAG, press);
} else if (id == Component.Identifier.Button._11) {
toggle(ControllerPacket.RB_FLAG, press);
} else if (id == Component.Identifier.Button._16) {
toggle(ControllerPacket.SPECIAL_BUTTON_FLAG, press);
} else if (id == Component.Identifier.Button._8) {
leftTrigger = (byte)Math.round((press ? 1 : 0) * 0xFF);
} else if (id == Component.Identifier.Button._9) {
rightTrigger = (byte)Math.round((press ? 1 : 0) * 0xFF);
}
}
}

View File

@@ -0,0 +1,73 @@
package com.limelight.input;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import com.limelight.nvstream.NvConnection;
import com.limelight.nvstream.input.ControllerPacket;
public class XBox360Controller extends Gamepad {
public XBox360Controller(NvConnection conn, Controller pad) {
super(conn, pad);
}
@Override
protected void handleButtons(Component comp, float value) {
Component.Identifier id = comp.getIdentifier();
boolean press = value > 0.5F;
if (id == Component.Identifier.Button._13) {
toggle(ControllerPacket.LEFT_FLAG, press);
} else if (id == Component.Identifier.Button._14) {
toggle(ControllerPacket.RIGHT_FLAG, press);
} else if (id == Component.Identifier.Button._11) {
toggle(ControllerPacket.UP_FLAG, press);
} else if (id == Component.Identifier.Button._12) {
toggle(ControllerPacket.DOWN_FLAG, press);
} else if (id == Component.Identifier.Button._0) {
toggle(ControllerPacket.A_FLAG, press);
} else if (id == Component.Identifier.Button._2) {
toggle(ControllerPacket.X_FLAG, press);
} else if (id == Component.Identifier.Button._3) {
toggle(ControllerPacket.Y_FLAG, press);
} else if (id == Component.Identifier.Button._1) {
toggle(ControllerPacket.B_FLAG, press);
} else if (id == Component.Identifier.Button._9) {
toggle(ControllerPacket.BACK_FLAG, press);
} else if (id == Component.Identifier.Button._8) {
toggle(ControllerPacket.PLAY_FLAG, press);
} else if (id == Component.Identifier.Button._7) {
toggle(ControllerPacket.RS_CLK_FLAG, press);
} else if (id == Component.Identifier.Button._6) {
toggle(ControllerPacket.LS_CLK_FLAG, press);
} else if (id == Component.Identifier.Button._4) {
toggle(ControllerPacket.LB_FLAG, press);
} else if (id == Component.Identifier.Button._5) {
toggle(ControllerPacket.RB_FLAG, press);
} else if (id == Component.Identifier.Button._10) {
toggle(ControllerPacket.SPECIAL_BUTTON_FLAG, press);
}
}
@Override
protected void handleAnalog(Component comp, float value) {
Component.Identifier id = comp.getIdentifier();
if (id == Component.Identifier.Axis.RX) {
rightStickX = (short)Math.round(value * 0x7FFF);
} else if (id == Component.Identifier.Axis.RY) {
rightStickY = (short)Math.round(-value * 0x7FFF);
} else if (id == Component.Identifier.Axis.X) {
leftStickX = (short)Math.round(value * 0x7FFF);
} else if (id == Component.Identifier.Axis.Y) {
leftStickY = (short)Math.round(-value * 0x7FFF);
} else if (id == Component.Identifier.Axis.Z) {
leftTrigger = (byte)Math.round((value + 1) / 2 * 0xFF);
} else if (id == Component.Identifier.Axis.RZ) {
rightTrigger = (byte)Math.round((value + 1) / 2 * 0xFF);
}
}
}