file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Main.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav-player/src/pav/player/Main.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.player; import java.io.ByteArrayInputStream; import java.util.logging.LogManager; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import processing.core.PApplet; /** * Entry point of the program. * * @author christopher */ final class Main { /** * Entry point of the program. * * @param args Startup arguments */ public static void main(String[] args) { System.out.println("----------"); System.out.println("PAV Player"); System.out.println("----------\n"); _initConfig(args); try { LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level = OFF".getBytes())); } catch (Exception e) { Console.error("Error while disabling jAudioTagger logging: " + e.getMessage()); } PApplet.main(new String[] { "pav.player.Player" }); } private static void _initConfig(String[] args) { Options options = new Options(); options.addOption("nopav", false, "Do not try to send audio data to PAV."); options.addOption("pavhost", true, "The host PAV is running on."); options.addOption("pavport", true, "The port PAV is running on."); options.addOption("renderer", true, "The Processing render mode to use."); options.addOption("framesize", true, "The size of the audio frames. Must be 512, 1024 or 2048."); options.addOption("width", true, "The player width."); options.addOption("height", true, "The player height."); options.addOption("resizable", false, "Make the player resizable."); CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if(cmd.hasOption("nopav")) { Config.usePav = false; Console.out("PAV support disabled."); } if(cmd.hasOption("renderer")) { Config.renderer = cmd.getOptionValue("renderer"); } else { Console.out("No render mode specified, using " + Config.renderer + "."); } if(cmd.hasOption("width")) { String option = cmd.getOptionValue("width"); try { int width = Integer.parseInt(option); if(width > 0) { Config.width = width; } else { Console.error("Window width must be positive."); } } catch (NumberFormatException e) { Console.error("Invalid window width specified."); } } else { Console.out("No window width specified, using " + Config.width + "."); } if(cmd.hasOption("height")) { String option = cmd.getOptionValue("height"); try { int height = Integer.parseInt(option); if(height > 0) { Config.height = height; } else { Console.error("Window height must be positive."); } } catch (NumberFormatException e) { Console.error("Invalid window height specified."); } } else { Console.out("No window height specified, using " + Config.height + "."); } if(cmd.hasOption("resizable")) { Config.resizable = true; } if(Config.usePav) { if(cmd.hasOption("pavhost")) { Config.pavHost = cmd.getOptionValue("pavhost"); } else { Console.out("No PAV host specified, using " + Config.pavHost + "."); } if(cmd.hasOption("pavport")) { String option = cmd.getOptionValue("pavport"); try { int port = Integer.parseInt(option); if(port > 1023 && port < 65536) { Config.pavPort = port; } else { Console.error("PAV port must be between 1024 and 65535."); } } catch (NumberFormatException e) { Console.error("Invalid PAV port specified."); } } else { Console.out("No PAV port specified, using " + Config.pavPort + "."); } if(cmd.hasOption("framesize")) { String option = cmd.getOptionValue("framesize"); try { int frameSize = Integer.parseInt(option); if(frameSize == 512 || frameSize == 1024 || frameSize == 2048) { Config.frameSize = frameSize; } else { Console.error("Frame size must be 512, 1024 or 2048."); } } catch(NumberFormatException e) { Console.error("Invalid frame size specified."); } } else { Console.out("No frame size specified, using " + Config.frameSize + "."); } } } catch(ParseException e) { Console.error("Error while parsing command line arguments: " + e.getMessage()); new HelpFormatter().printHelp("pav-player", options); } } private Main() { } }
5,425
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Player.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav-player/src/pav/player/Player.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.player; import java.awt.FileDialog; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.TreeMap; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import processing.core.PApplet; import processing.core.PFont; import processing.core.PGraphics; import ddf.minim.AudioListener; import ddf.minim.AudioPlayer; import ddf.minim.Minim; /** * A simple audio player based on Processing with PAV support. * * @author christopher */ public class Player extends PApplet { /** * Player status - Unknown status */ public static final int STATUS_UNKNOWN = 0; /** * Player status - Playback is stopped. */ public static final int STATUS_STOPPED = 1; /** * Player status - Playback is currently paused. */ public static final int STATUS_PAUSED = 2; /** * Player status - The player is currently playing, PAV support is active. */ public static final int STATUS_PLAYING_PAV = 3; /** * Player status - The player is currently playing, PAV support is inactive. */ public static final int STATUS_PLAYING_NOPAV = 4; private static final long serialVersionUID = -4078221446680493121L; private final Menu _menu; private final Playlist _playlist; private final StatusBar _statusBar; private final PAVControl _pavControl; private final SongFilenameFilter _filter; private final Thread _pavControlThread; private final BlockingDeque<float[]> _sampleQueue; private Minim _minim; private AudioPlayer _player; private MusicListener _listener; private File _songPath; private Integer _playing; private boolean _playbackPausedByUser; private final TreeMap<Integer, Song> _songs; private final TreeMap<String, Album> _albums; private boolean _forceRedraw; private int _lastWidth, _lastHeight; /** * Ctor. */ public Player() { _filter = new SongFilenameFilter(); _menu = new Menu(); _playlist = new Playlist(); _statusBar = new StatusBar(); _pavControl = new PAVControl(); _sampleQueue = new LinkedBlockingDeque<float[]>(5); _pavControlThread = new Thread(_pavControl, "PAVControl"); _songs = new TreeMap<Integer, Player.Song>(); _albums = new TreeMap<String, Player.Album>(); _setSongPath(new File(System.getProperty("user.dir"))); _pavControlThread.start(); } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void setup() { size(Config.width, Config.height, Config.renderer); frameRate(15); smooth(); frame.setTitle("PAV Player"); frame.setResizable(Config.resizable); WindowListener[] listeners = frame.getWindowListeners(); for(int i = 0; i < listeners.length; i++) { frame.removeWindowListener(listeners[i]); } frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { exit(); } }); _minim = new Minim(this); } /** * Closes the player. */ @Override public void exit() { Console.out("Shutting down ..."); stopPlayback(); _minim.stop(); _pavControlThread.interrupt(); try { _pavControlThread.join(500); } catch (InterruptedException e) { } super.exit(); } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void draw() { _menu.draw(); _playlist.draw(); _statusBar.draw(); // the player length and position methods are very inaccurate, so we are using this "hack" if(_player != null && ! _playbackPausedByUser && ! _player.isPlaying()) { playNext(); } _lastWidth = width; _lastHeight = height; } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void mousePressed() { int button = _menu.onMousePressed(); switch(button) { case 0 : break; case Menu.BUTTON_OPEN : _selectSongPath(); break; case Menu.BUTTON_PREV : playPrevious(); break; case Menu.BUTTON_NEXT : playNext(); break; case Menu.BUTTON_STOP : stopPlayback(); break; case Menu.BUTTON_PLAY : _togglePlayback(); break; } _playlist.onMousePressed(); } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void mouseReleased() { _playlist.onMouseReleased(); } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void mouseDragged() { _playlist.onMouseDragged(); } /** * Returns true if the player is currently playing music. * * @return True if playing music */ public boolean isPlaying() { return _player != null && _player.isPlaying(); } /** * Returns true if there is a queued song, but playback has been paused by the user. * * @return True if playback is paused */ public boolean isPlaybackPaused() { return _playbackPausedByUser; } /** * Returns true if there is no song playing or queued. * * @return True if playback is stopped */ public boolean isPlaybackStopped() { return ! isPlaying() && ! _playbackPausedByUser; } /** * Returns the playback status. See STATUS constants of this class. * * @return The playback status */ public int getStatus() { if(isPlaying()) { return (_pavControl.isActive()) ? STATUS_PLAYING_PAV : STATUS_PLAYING_NOPAV; } if(isPlaybackPaused()) { return STATUS_PAUSED; } if(isPlaybackStopped()) { return STATUS_STOPPED; } return STATUS_UNKNOWN; } /** * Plays the next song on the playlist. Does nothing if the playlist is empty. */ public void playNext() { if(_songs.isEmpty()) { return; } if(_playing == null) { _play(_songs.firstKey()); } else { Integer next = _songs.higherKey(_playing); if(next != null) { _play(next); } else { _play(_songs.firstKey()); } } } /** * Plays the previous song on the playlist. Does nothing if the playlist is empty. */ public void playPrevious() { if(_songs.isEmpty()) { return; } if(_playing == null) { _play(_songs.lastKey()); } else { Integer next = _songs.lowerKey(_playing); if(next != null) { _play(next); } else { _play(_songs.lastKey()); } } } /** * Stops playback and dequeues the playing song, if any. */ public void stopPlayback() { _playing = null; _playbackPausedByUser = false; if(_player != null) { _player.removeListener(_listener); _player.close(); _player = null; _listener = null; // icetea's pulseaudio threads sometimes crashes when closing the player } } private void _selectSongPath() { FileDialog dialog = new FileDialog(this.frame, "Select Folder"); dialog.setDirectory(_songPath.getAbsolutePath()); // filters in file dialog are bugged noLoop(); dialog.setVisible(true); loop(); String dir = dialog.getDirectory(); dialog.dispose(); if(dir == null) { return; } File f = new File(dir); if(f.isDirectory()) { _setSongPath(f); } else { if(f.getParentFile() != null) { _setSongPath(f.getParentFile()); } } } private void _togglePlayback() { if(isPlaying()) { _player.pause(); _playbackPausedByUser = true; } else if(isPlaybackPaused()) { _player.play(); _playbackPausedByUser = false; } else { playNext(); } } private void _play(int id) { if(! _songs.containsKey(id)) { return; } stopPlayback(); _player = _minim.loadFile(_songs.get(id).path.getAbsolutePath(), Config.frameSize); _player.play(); _listener = new MusicListener(); _player.addListener(_listener); _playing = id; } private void _setSongPath(File path) { stopPlayback(); _songPath = path; _update(); } private void _findSongs(File path, LinkedList<Song> addTo) { File[] songPaths = path.listFiles(_filter); for(File p : songPaths) { Song song = new Song(); song.path = p; try { AudioFile f = AudioFileIO.read(p); Tag tag = f.getTag(); song.artist = tag.getFirst(FieldKey.ARTIST); song.album = tag.getFirst(FieldKey.ALBUM); song.title = tag.getFirst(FieldKey.TITLE); song.track = tag.getFirst(FieldKey.TRACK); } catch(Exception e) { } finally { if(song.artist == null || song.artist.isEmpty()) { song.artist = "Unknown"; } if(song.album == null || song.album.isEmpty()) { song.album = "Unknown"; } if(song.title == null || song.title.isEmpty()) { song.title = p.getName(); } if(song.track == null || song.track.isEmpty()) { song.track = "?"; } addTo.add(song); } } } private void _update() { _songs.clear(); _albums.clear(); LinkedList<Song> songs = new LinkedList<Song>(); _findSongs(_songPath, songs); for(File s : _songPath.listFiles()) { if(s.isDirectory()) { _findSongs(s, songs); } } Collections.sort(songs); int i = 1; for(Song s : songs) { String hash = s.artist + "-" + s.album; Album album; if(! _albums.containsKey(hash)) { album = new Album(); album.artist = s.artist; album.title = s.album; _albums.put(hash, album); } else { album = _albums.get(hash); } album.songs.add(i); _songs.put(i, s); i++; } } private boolean _sizeChanged() { return !(width == _lastWidth && height == _lastHeight); } /** * Filename filter for supported encodings. * * @author christopher */ private class SongFilenameFilter implements FilenameFilter { @Override public boolean accept(File file, String name) { File f = new File(file, name); String n = name.toLowerCase(); if(!f.isFile()) { return false; } if(n.endsWith(".mp3")) { return true; } if(n.endsWith(".wav")) { return true; } if(n.endsWith(".aiff")) { return true; } if(n.endsWith(".au")) { return true; } if(n.endsWith(".snd")) { return true; } return false; } } /** * Listens to music played via Minims AudioPlayer and queues received frames for PAV. * * @author christopher */ private class MusicListener implements AudioListener { private float[] _samples = {}; @Override public void samples(float[] samples) { if(!_pavControl.isActive()) return; if(! _sampleQueue.offerLast(samples)) { Console.out("Failed to add frame to PAV queue."); } } @Override public void samples(float[] left, float[] right) { if(!_pavControl.isActive()) return; int len = left.length; if(_samples.length != len) { _samples = new float[len]; } for(int i = 0; i < len; i++) { _samples[i] = (left[i] + right[i]) / 2; } samples(_samples); } } /** * PAV control. * * @author christopher */ private class PAVControl implements Runnable { private volatile boolean _active; @Override public void run() { if(! Config.usePav) { return; } _active = true; DatagramSocket socket = null; try { int fs = Config.frameSize; int fs2 = Config.frameSize * 2; int smax = Short.MAX_VALUE; byte[] bb = new byte[fs2]; InetAddress address = InetAddress.getByName(Config.pavHost); socket = new DatagramSocket(); DatagramPacket packet = new DatagramPacket(bb, fs2, address, Config.pavPort); while(! Thread.interrupted()) { int bi = 0; float[] frame = _sampleQueue.takeLast(); if(_sampleQueue.remainingCapacity() == 1) { _sampleQueue.clear(); Console.out("Dropped frames."); } for(int i = 0; i < fs; i++) { short s = (short) (frame[i] * smax); bb[bi] = (byte) (s & 0xFF); bb[bi + 1] = (byte)((s >> 8) & 0xFF); bi += 2; } socket.send(packet); } } catch(IOException e) { Console.error("An error occured while sending data to PAV, disabling PAV support."); Console.error(e); } catch(InterruptedException e) { } finally { _active = false; if(socket != null) socket.close(); } } /** * Whether PAV support is currently active. * * @return True if PAV support is active */ public boolean isActive() { return _active; } } /** * A music album. * * @author christopher */ private class Album { /** * The album artist. */ public String artist; /** * The album title. */ public String title; /** * The ids of all songs of the album. */ public LinkedList<Integer> songs; /** * Ctor. */ public Album() { songs = new LinkedList<Integer>(); } } /** * A song. * * @author christopher */ private class Song implements Comparable<Song> { /** * The song artist. */ public String artist; /** * The song album. */ public String album; /** * The song title. */ public String title; /** * The track number. */ public String track; /** * The path to the song. */ public File path; @Override public int compareTo(Song o) { if(! artist.equals(o.artist)) { return artist.compareTo(o.artist); } if(! album.equals(o.album)) { return album.compareTo(o.album); } try { int tt = Integer.parseInt(track); int to = Integer.parseInt(o.track); return (tt < to) ? -1 : 1; } catch(NumberFormatException e) { return 0; } } } /** * The playlist. * * @author christopher */ private class Playlist { private final PFont _font; private PGraphics _buffer; private Integer _lastPlayed; private File _lastPath; private int _lastNumAlbums; private int _lastNumSongs; private float _dy; private int _space; private float _sliderStart; private float _lastSliderStart; private boolean _sliderDragging; private float _dragLastY; /** * Ctor. */ public Playlist() { _font = createFont("sans", 11); } /** * Draws the playlist. */ public void draw() { if(! _forceRedraw && _sliderStart == _lastSliderStart && _playing == _lastPlayed && _songPath != null && _songPath.equals(_lastPath) && !_sizeChanged()) { return; } fill(0); noStroke(); rectMode(CORNERS); rect(0, 40, width, height - 20); _drawPath(); _drawPlaylist(); _lastPlayed = _playing; _lastPath = _songPath; } /** * Event handler - mouse pressed. */ public void onMousePressed() { if(_dy > 1) { return; } float y1 = 66 + _sliderStart * _space; if(width - 8 <= mouseX && mouseX <= width - 3 && y1 <= mouseY && mouseY <= y1 + _space * _dy) { _sliderDragging = true; _dragLastY = mouseY; } } /** * Event handler - mouse released. */ public void onMouseReleased() { _sliderDragging = false; } /** * Event handler - mouse dragged. */ public void onMouseDragged() { if(_sliderDragging) { float dy = mouseY - _dragLastY; if(dy == 0) { return; } float dyr = dy / _space; float sn = _sliderStart + dyr; if(sn < 0) { sn = 0; } else if(sn > 1 - _dy) { sn = 1 - _dy; } _lastSliderStart = _sliderStart; _sliderStart = sn; _dragLastY = mouseY; } } private void _drawPath() { rectMode(CORNER); noStroke(); fill(50); rect(0, 40, width, 22); textAlign(RIGHT, CENTER); textFont(_font); fill(175); text(_songPath.toString() + "/", width - 6, 49); } private void _drawPlaylist() { int numAlbums = _albums.size(); int numSongs = _songs.size(); int heightPerAlbum = 16; int heightPerSong = 14; if(_buffer == null || numAlbums != _lastNumAlbums || numSongs != _lastNumSongs || _sizeChanged()) { if(_buffer != null) { _buffer.dispose(); } int bufferHeight = numAlbums * heightPerAlbum + numSongs * heightPerSong; if(bufferHeight == 0) { bufferHeight = 1; } _buffer = createGraphics(width, bufferHeight, JAVA2D); _buffer.textAlign(LEFT); _buffer.textFont(_font); _lastNumAlbums = numAlbums; _lastNumSongs = numSongs; _sliderStart = 0; } if(_forceRedraw || _playing != _lastPlayed || (_songPath != null && ! _songPath.equals(_lastPath)) || _sizeChanged()) { int y = 11; _buffer.beginDraw(); _buffer.background(0); for(Album album : _albums.values()) { _buffer.fill(200); _buffer.text(album.artist + " - " + album.title, 5, y); y += heightPerAlbum; for(int id : album.songs) { _buffer.fill(100); if(_playing != null && id == _playing) { _buffer.fill(0xFF00FF00); } Song s = _songs.get(id); String track = (s.track.length() == 1 && !s.track.equals("?")) ? "0" + s.track : s.track; _buffer.text(track + " - " + s.title, 15, y); y += heightPerSong; } } _buffer.endDraw(); } _space = height - 66 - 24; _dy = _space / (float) _buffer.height; if(_buffer.height <= _space) { image(_buffer, 0, 66); return; } else { float yStart = ((_buffer.height - _space) / (1 - _dy)) * _sliderStart; copy(_buffer, 0, Math.round(yStart), width, _space, 0, 66, width, _space); rectMode(CORNER); noStroke(); fill(40); rect(width - 10, 66 + _sliderStart * _space, 7, _space * _dy); } } } /** * The status bar. * * @author christopher */ private class StatusBar { private final PFont _font; private int _lastStatus; /** * Ctor. */ public StatusBar() { _font = createFont("sans", 11); } /** * Draws the status bar. */ public void draw() { int status = getStatus(); if(! _forceRedraw && status == _lastStatus && !_sizeChanged()) { return; } rectMode(CORNER); noStroke(); fill(50); rect(0, height - 20, width, 20); textAlign(LEFT); textFont(_font); fill(175); int x = 5, y = height - 6; switch(status) { case STATUS_PLAYING_PAV : text("Playing. Streaming to " + Config.pavHost + ":" + Config.pavPort + ".", x, y); break; case STATUS_PLAYING_NOPAV : text("Playing. PAV support inactive.", x, y); break; case STATUS_PAUSED : text("Paused.", x, y); break; case STATUS_STOPPED : text("Stopped.", x, y); break; } _lastStatus = status; } } /** * The player menu. * * @author christopher */ private class Menu { /** * The open button. */ public static final int BUTTON_OPEN = 1; /** * The previous button. */ public static final int BUTTON_PREV = 2; /** * The next button. */ public static final int BUTTON_NEXT = 3; /** * The stop button. */ public static final int BUTTON_STOP = 4; /** * The play button. */ public static final int BUTTON_PLAY = 5; private int _lastMouseOverStatus; private final HashMap<Integer, Button> _buttons; private final int _height = 40; private final PFont _font; /** * Ctor. */ public Menu() { _buttons = new HashMap<Integer, Button>(5); _buttons.put(BUTTON_OPEN, new Button()); _buttons.put(BUTTON_PREV, new Button()); _buttons.put(BUTTON_NEXT, new Button()); _buttons.put(BUTTON_STOP, new Button()); _buttons.put(BUTTON_PLAY, new Button()); _buttons.get(BUTTON_OPEN).setLabel("OPEN"); _buttons.get(BUTTON_PREV).setLabel("PREV"); _buttons.get(BUTTON_NEXT).setLabel("NEXT"); _buttons.get(BUTTON_STOP).setLabel("STOP"); _buttons.get(BUTTON_PLAY).setLabel("PLAY"); _font = createFont("sans", 12); } /** * Draws the menu. */ public void draw() { int mouseOverStatus = onMousePressed(); if(! _forceRedraw && mouseOverStatus == _lastMouseOverStatus && !_sizeChanged()) { return; } float xd = width / 5.0f; if(_sizeChanged()) { float x = 0; _buttons.get(BUTTON_OPEN).setArea(x, 0, x + xd, _height); x += xd; _buttons.get(BUTTON_PREV).setArea(x, 0, x + xd, _height); x += xd; _buttons.get(BUTTON_NEXT).setArea(x, 0, x + xd, _height); x += xd; _buttons.get(BUTTON_STOP).setArea(x, 0, x + xd, _height); x += xd; _buttons.get(BUTTON_PLAY).setArea(x, 0, x + xd, _height); x += xd; } for(Button b : _buttons.values()) { b.draw(); } strokeWeight(1); stroke(50); for(int i = 1; i < 5; i++) { line(i * xd, 0, i * xd, _height - 1); } _lastMouseOverStatus = mouseOverStatus; } /** * Mouse pressed event handler. * Returns 0 if the mouse was not pressed over a menu button, * otherwise the id of that button is returned (see constants of this class). * * @return */ public int onMousePressed() { if(mouseY > _height) { return 0; } if(_buttons.get(BUTTON_OPEN).isMouseOver()) { return BUTTON_OPEN; } if(_buttons.get(BUTTON_PREV).isMouseOver()) { return BUTTON_PREV; } if(_buttons.get(BUTTON_NEXT).isMouseOver()) { return BUTTON_NEXT; } if(_buttons.get(BUTTON_STOP).isMouseOver()) { return BUTTON_STOP; } if(_buttons.get(BUTTON_PLAY).isMouseOver()) { return BUTTON_PLAY; } return 0; } /** * A menu button. * * @author christopher */ private class Button { private String _label; private float _x1, _y1, _x2, _y2; /** * Sets the label to use. * * @param label The label */ public void setLabel(String label) { _label = label; } /** * Sets the button area. * * @param x1 The x1 position * @param y1 The y1 position * @param x2 The x2 position. Must be > x1 * @param y2 The y2 position. Must be > y2 */ public void setArea(float x1, float y1, float x2, float y2) { _x1 = x1; _y1 = y1; _x2 = x2; _y2 = y2; } /** * Draws the button. */ public void draw() { if(isMouseOver()) { fill(25); } else { fill(40); } rectMode(CORNER); noStroke(); rect(_x1, _y1, _x2, _y2); if(_label != null) { fill(255); textFont(_font); textAlign(CENTER, CENTER); text(_label, _x1 + (_x2 - _x1) / 2, (_y2 - _y1) / 2); } } /** * Whether the mouse is currently over the button. * * @return True if the mouse is over the button, otherwise false */ public boolean isMouseOver() { return _x1 <= mouseX && mouseX <= _x2 && _y1 <= mouseY && mouseY <= _y2; } } } }
23,907
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Config.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/Config.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav; import java.nio.ByteOrder; import processing.core.PConstants; /** * Configuration used by PAV. This is a static class. * * @author christopher */ public final class Config { /** * Use FIFO audio source. */ public static final String AUDIO_SOURCE_FIFO = "fifo"; /** * Use socket audio source. */ public static final String AUDIO_SOURCE_UDP = "udp"; /** * Audio data are transfered as little-endian byte stream. */ public static final String BYTE_ORDER_LE = "le"; /** * Audio data are transfered as big-endian byte stream. */ public static final String BYTE_ORDER_BE = "be"; /** * The audio source to use. */ public static String audioSource = AUDIO_SOURCE_UDP; /** * The sample size. Must be 512, 1024 or 2048. */ public static int sampleSize = 1024; /** * The sample rate. */ public static int sampleRate = 44100; /** * The byte order. */ public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; /** * The port the udp audio source should listen to. */ public static int udpPort = 2198; /** * The path to the fifo the fifo audio source should use. */ public static String fifoPath = ""; /** * The width of the display window. */ public static int windowWidth = 1024; /** * The height of the display window. */ public static int windowHeight = 768; /** * The renderer to use. */ public static String renderer = PConstants.P2D; private Config() { } }
2,225
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Console.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/Console.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav; /** * Convenience functions for working with the console. * * @author christopher */ public class Console { /** * Sends a message to the console. * * @param message The message to send. Must not be null */ public static void out(String message) { System.out.println(" " + message); } /** * Sends an error message to the console. * * @param message The message to send. Must not be null */ public static void error(String message) { System.out.println("\n !!! " + message); } /** * Generates an error message and sends it to the console. * * @param cause The error */ public static void error(Throwable cause) { System.out.println("\n !!! Error: " + cause.getMessage()); System.out.println(" ----- TRACE START -----"); for(StackTraceElement e : cause.getStackTrace()) { System.out.println(" " + e.toString()); } System.out.println(" ----- TRACE END -----"); } }
1,692
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Main.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/Main.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav; import java.io.File; import java.nio.ByteOrder; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import processing.core.PApplet; public class Main { /** * @param args */ public static void main(String[] args) { System.out.println("------------------------------"); System.out.println("Processing Audio Visualization"); System.out.println("------------------------------\n"); Options options = new Options(); options.addOption("renderer", true, "The Processing render mode to use."); options.addOption("width", true, "The width of the visualization window."); options.addOption("height", true, "The height of the visualization window."); options.addOption("audiosource", true, "Audio source to use (udp or fifo)."); options.addOption("samplesize", true, "Number of samples per frame (512, 1024 or 2048)"); options.addOption("samplerate", true, "The sample rate of the audio data."); options.addOption("byteorder", true, "Byte order of the samples (le or be)"); options.addOption("path", true, "Path to the fifo the fifo audio source should use."); options.addOption("port", true, "Port the udp audio source should listen to."); CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if(cmd.hasOption("renderer")) { Config.renderer = cmd.getOptionValue("renderer"); } else { Console.out("No render mode specified, using " + Config.renderer + "."); } if(cmd.hasOption("width")) { String option = cmd.getOptionValue("width"); try { Config.windowWidth = Integer.parseInt(option); } catch (NumberFormatException e) { Console.error("Error while parsing command line arguments: width is not a valid integer."); } } else { Console.out("No window width specified, using " + Config.windowWidth + "."); } if(cmd.hasOption("height")) { String option = cmd.getOptionValue("height"); try { Config.windowHeight = Integer.parseInt(option); } catch (NumberFormatException e) { Console.error("Error while parsing command line arguments: height is not a valid integer."); } } else { Console.out("No window height specified, using " + Config.windowHeight + "."); } if(cmd.hasOption("audiosource")) { if(cmd.getOptionValue("audiosource").equals(Config.AUDIO_SOURCE_FIFO)) { Config.audioSource = Config.AUDIO_SOURCE_FIFO; } else if(cmd.getOptionValue("audiosource").equals(Config.AUDIO_SOURCE_UDP)) { Config.audioSource = Config.AUDIO_SOURCE_UDP; } else { Console.error("Invalid audio source specified."); } } else { Console.out("No audio source specified, using " + Config.audioSource + "."); } if(cmd.hasOption("samplesize")) { try { int sampleSize = Integer.parseInt(cmd.getOptionValue("samplesize")); if(sampleSize == 512 || sampleSize == 1024 || sampleSize == 2048) { Config.sampleSize = sampleSize; } else { Console.error("Invalid sample size specified."); } } catch (NumberFormatException e) { Console.error("Error while parsing command line arguments: samplesize is not a valid integer."); } } else { Console.out("No sample size specified, using " + Config.sampleSize + "."); } if(cmd.hasOption("samplerate")) { try { Config.sampleRate = Integer.parseInt(cmd.getOptionValue("samplerate")); } catch (NumberFormatException e) { Console.error("Error while parsing command line arguments: samplerate is not a valid integer."); } } else { Console.out("No sample rate specified, using " + Config.sampleRate + "."); } if(cmd.hasOption("byteorder")) { if(cmd.getOptionValue("byteorder").equals(Config.BYTE_ORDER_LE)) { Config.byteOrder = ByteOrder.LITTLE_ENDIAN; } else if(cmd.getOptionValue("byteorder").equals(Config.BYTE_ORDER_BE)) { Config.byteOrder = ByteOrder.BIG_ENDIAN; } else { Console.error("Invalid byte order specified."); } } else { Console.out("No byte order specified, using " + Config.BYTE_ORDER_LE + "."); } if(Config.audioSource.equals(Config.AUDIO_SOURCE_FIFO)) { if(cmd.hasOption("path")) { if(! (new File(cmd.getOptionValue("path"))).canRead()) { Console.error("Unable to read the specified FIFO, aborting."); return; } Config.fifoPath = cmd.getOptionValue("path"); } else { Console.error("No fifo path specified, aborting."); return; } } if(Config.audioSource.equals(Config.AUDIO_SOURCE_UDP)) { if(cmd.hasOption("port")) { try { Config.udpPort = Integer.parseInt(cmd.getOptionValue("port")); } catch(NumberFormatException e) { Console.error("Error while parsing command line arguments: port is not a valid integer."); } } else { Console.out("No port specified, using " + Config.udpPort + "."); } } } catch (ParseException e) { Console.error("Error while parsing command line arguments: " + e.getMessage()); new HelpFormatter().printHelp("pav", options); } PApplet.main(new String[] { "pav.PAV" }); } }
6,212
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
PAV.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/PAV.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import pav.audiosource.AudioCallback; import pav.audiosource.AudioSource; import pav.configurator.Configurator; import pav.configurator.ConfiguratorFactory; import pav.lib.PAVException; import pav.lib.ShaderManager; import pav.lib.Visualization; import pav.lib.VisualizationImpl; import pav.lib.visualizer.Boxes; import pav.lib.visualizer.Bubbles; import pav.lib.visualizer.MelSpectrum; import pav.lib.visualizer.Phasor; import pav.lib.visualizer.Rainbow; import pav.lib.visualizer.Spectogram; import pav.lib.visualizer.Spectrum; import pav.lib.visualizer.Visualizer; import pav.lib.visualizer.Waveform; import pav.lib.visualizer.Wavering; import processing.core.PApplet; import processing.core.PFont; import codeanticode.glgraphics.GLGraphics; /** * Processing Audio Visualization. * * @author christopher */ public class PAV extends PApplet implements AudioCallback { private static final int _frameDropUpdateInterval = 200; private static final long serialVersionUID = 1525235544995508743L; private StringBuilder _inputBuffer; private Visualization _visualization; private final AudioSource _audioSource; private PFont _statusFont; private boolean _drawStatus; private int _inputHistoryPosition; private final ArrayList<String> _inputHistory; private final ArrayList<Configurator> _configurators; private final BlockingDeque<float[]> _sampleQueue; private float _frameDropPercentage; private int _numFramesVisualized; private volatile int _numFramesReceived; /** * Ctor. * * @throws PAVException If an error occured while initializing the audio source */ public PAV() throws PAVException { _drawStatus = true; _inputBuffer = new StringBuilder(); _inputHistory = new ArrayList<String>(); _configurators = new ArrayList<Configurator>(); _configurators.add(ConfiguratorFactory.generic()); _sampleQueue = new LinkedBlockingDeque<float[]>(); _audioSource = AudioSource.factory(this); } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void setup() { size(Config.windowWidth, Config.windowHeight, Config.renderer); background(0); frameRate(100); _statusFont = createFont("sans", 12, true); textFont(_statusFont); textSize(12); frame.setTitle("PAV"); WindowListener[] listeners = frame.getWindowListeners(); for(int i = 0; i < listeners.length; i++) { frame.removeWindowListener(listeners[i]); } frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { exit(); } }); _visualization = new VisualizationImpl(this); _visualization.setSampleRate(Config.sampleRate); if(g instanceof GLGraphics) { try { ShaderManager.initialize(this); } catch(PAVException e) { Console.error("Could not initialize shaders: " + e.getMessage()); } } else { frame.setResizable(true); } _audioSource.read(); } /** * Internal method called by Processing. Not to be called from outside. */ @Override public void draw() { background(0); try { float[] frame = _sampleQueue.pollLast(66, TimeUnit.MILLISECONDS); if(frame != null) { int len = _sampleQueue.size(); if(len > 0) { _sampleQueue.clear(); } _numFramesReceived += len + 1; _numFramesVisualized++; _visualization.process(frame); } } catch(InterruptedException e) { System.out.println("Interrupted while waiting for new data ... aborting."); return; } catch (PAVException e) { Console.error("An error occured while drawing the visualization:"); Console.error(e.getMessage()); exit(); } if(frameCount % _frameDropUpdateInterval == 0) { _frameDropPercentage = (_numFramesReceived - _numFramesVisualized) / 2f; _numFramesVisualized = 0; _numFramesReceived = 0; } _drawInput(); if(_drawStatus) { _drawStatus(); } } /** * Closes the program. */ @Override public void exit() { Console.out("Shutting down ..."); try { _audioSource.close(); } catch(InterruptedException e) { } super.exit(); } @Override public void keyPressed() { if(_inputBuffer.length() == 0 && key == 's') { _drawStatus = !_drawStatus; return; } if(_inputBuffer.length() == 0 && key == 'p') { saveFrame("pav-####.png"); return; } if(keyCode == 38) { if(! _inputHistory.isEmpty()) { if(_inputHistoryPosition == -1) { _inputHistoryPosition = _inputHistory.size() - 1; _inputBuffer = new StringBuilder(_inputHistory.get(_inputHistoryPosition)); } else if(_inputHistoryPosition > 0) { _inputHistoryPosition--; _inputBuffer = new StringBuilder(_inputHistory.get(_inputHistoryPosition)); } } return; } if(keyCode == 40) { if(! _inputHistory.isEmpty()) { if (_inputHistoryPosition == -1) { } else if(_inputHistoryPosition == _inputHistory.size() - 1) { _inputBuffer = new StringBuilder(); _inputHistoryPosition = -1; } else { _inputHistoryPosition++; _inputBuffer = new StringBuilder(_inputHistory.get(_inputHistoryPosition)); } } return; } if(keyCode == 8) { if(_inputBuffer.length() > 0) { _inputBuffer.deleteCharAt(_inputBuffer.length() - 1); } return; } if(keyCode != 10) { _inputBuffer.append(key); return; } boolean valid = false; String[] in = _inputBuffer.toString().split(" "); if(in[0].equals("add") && in.length >= 2) { valid = _addVisualizer(Util.removeFirst(in)); } else if(in[0].equals("rem") && in.length == 2) { valid = _removeVisualizer(in[1]); } else if(in[0].equals("c") && _inputBuffer.length() > 2) { valid = _configureVisualizer(_inputBuffer.substring(2, _inputBuffer.length())); } if(valid) { _inputHistory.add(_inputBuffer.toString()); _inputHistoryPosition = -1; } _inputBuffer = new StringBuilder(); } @Override public void onNewFrame(float[] frame) { _sampleQueue.add(frame); } @Override public void onError(Throwable error) { Console.error("AudioSource error: " + error.getMessage()); Console.error(error); } private void _drawInput() { if(_inputBuffer.length() == 0) { return; } textAlign(RIGHT, BOTTOM); fill(0xFF00FF00); text("Input: '" + _inputBuffer.toString() + "'", width - 10, height - 10); } private void _drawStatus() { textAlign(RIGHT, TOP); int x = width - 10; int y = 10; fill(0xFFAAAA00); text("Frames dropped: " + _frameDropPercentage + "%", x, y); y += 20; if(_visualization.numVisualizers() == 0) { fill(0xFFFF0000); text("No visualizers active.", x, y); y += 20; } else { fill(200); for(Map.Entry<Integer, Visualizer> v : _visualization.getVisualizers().entrySet()) { text("[" + v.getKey() + "] - " + v.getValue(), x, y); y += 18; } } fill(0xFF00FF00); text("Type in this window to execute commands.", x, y); y += 20; fill(255); text("Type 'p' to save a screenshot.", x, y); y += 18; text("Type 's' to toggle this information.", x, y); } private boolean _addVisualizer(String[] in) { String name = in[0]; Integer level = null; if(in.length == 2) { try { level = new Integer(Integer.parseInt(in[1])); } catch(NumberFormatException e) { } } try { Configurator configurator = null; if(name.equals("waveform")) { _addVisualizer(new Waveform(), level); configurator = ConfiguratorFactory.waveform(); } else if(name.equals("boxes")) { if(! (g instanceof GLGraphics)) { System.out.println("Visualizer requires GLGraphics mode."); return false; } _addVisualizer(new Boxes(), level); configurator = ConfiguratorFactory.boxes(); } else if(name.equals("bubbles")) { if(! (g instanceof GLGraphics)) { System.out.println("Visualizer requires GLGraphics mode."); return false; } _addVisualizer(new Bubbles(), level); configurator = ConfiguratorFactory.bubbles(); } else if(name.equals("phasor")) { _addVisualizer(new Phasor(), level); configurator = ConfiguratorFactory.phasor(); } else if(name.equals("rainbow")) { _addVisualizer(new Rainbow(), level); configurator = ConfiguratorFactory.rainbow(); } else if(name.equals("spectogram")) { _addVisualizer(new Spectogram(), level); configurator = ConfiguratorFactory.spectogram(); } else if(name.equals("spectrum")) { _addVisualizer(new Spectrum(), level); configurator = ConfiguratorFactory.spectrum(); } else if(name.equals("melspectrum")) { _addVisualizer(new MelSpectrum(), level); configurator = ConfiguratorFactory.melSpectrum(); } else if(name.equals("wavering")) { _addVisualizer(new Wavering(), level); configurator = ConfiguratorFactory.wavering(); } else { return false; } if(configurator != null && ! (_configurators.contains(configurator))) { _configurators.add(configurator); } return true; } catch (PAVException e) { Console.error("An error occured while adding a visualizer:"); Console.error(e); return false; } } private void _addVisualizer(Visualizer v, Integer level) throws PAVException { if(level == null) { _visualization.addVisualizer(v); } else { _visualization.addVisualizer(v, level); } } private boolean _removeVisualizer(String level) { try { _visualization.removeVisualizerAt(Integer.parseInt(level)); return true; } catch (NumberFormatException e) { return false; } } private boolean _configureVisualizer(String query) { String[] q = query.split(" "); if(q.length < 3) return false; Visualizer subject = null; try { subject = _visualization.getVisualizer(Integer.parseInt(q[0])); } catch(NumberFormatException e) { return false; } if(subject == null) return false; query = query.substring(q[0].length() + 1); for(Configurator c : _configurators) { if(c.process(subject, query) == true) { return true; } } return false; } }
11,185
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Util.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/Util.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav; import java.util.Arrays; import processing.core.PApplet; /** * Misc utility functionality. This is a static class. * * @author christopher */ public class Util { /** * Returns a copy of in, but without the first element. * * @param in The array to copy. Must not be null * @return The copy */ public static String[] removeFirst(String[] in) { if(in.length == 0) { return new String[0]; } return Arrays.copyOfRange(in, 1, in.length); } /** * Parses an array of integers. * * @param in The input array. Must not be null * @return The result * @throws NumberFormatException If any element in in is not parsable */ public static int[] parseInts(String[] in) { int[] out = new int[in.length]; for(int i = 0; i < in.length; i++) { out[i] = Integer.parseInt(in[i]); } return out; } /** * Parses an array of floats. * * @param in The input array. Must not be null * @return The result * @throws NumberFormatException If any element in in is not parsable */ public static float[] parseFloats(String[] in) { float[] out = new float[in.length]; for(int i = 0; i < in.length; i++) { out[i] = Float.parseFloat(in[i]); } return out; } /** * Parses an array of colors (RRGGBB or AARRGGBB). * * @param in The input array. Must not be null * @return The result * @throws NumberFormatException If any element in in is not parsable */ public static int[] parseColors(String[] in) { int[] out = new int[in.length]; for(int i = 0; i < in.length; i++) { String c = (in[i].length() == 6) ? "FF" + in[i] : in[i]; if(c.length() != 8) throw new NumberFormatException(); out[i] = PApplet.unhex(c); } return out; } /** * Parses an array of booleans. * * 1 or true (ignoring case) will result in true, everything else in false. * * @param in The input array. Must not be null * @return The result */ public static boolean[] parseBools(String[] in) { boolean[] out = new boolean[in.length]; for(int i = 0; i < in.length; i++) { String b = in[i]; if(b.equals("0")) b = "false"; if(b.equals("1")) b = "true"; out[i] = Boolean.parseBoolean(b); } return out; } /** * Tries to parse an array of integers. * * Returns the parsed version of in or an empty array on any parse errors. * * @param in The input array. Must not be null * @return The result */ public static int[] tryParseInts(String[] in) { try { return parseInts(in); } catch(NumberFormatException e) { return new int[0]; } } /** * Tries to parse an array of floats. * * Returns the parsed version of in or an empty array on any parse errors. * * @param in The input array. Must not be null * @return The result */ public static float[] tryParseFloats(String[] in) { try { return parseFloats(in); } catch(NumberFormatException e) { return new float[0]; } } /** * Tries to parse an array of colors (RRGGBB or AARRGGBB). * * Returns the parsed version of in or an empty array on any parse errors. * * @param in The input array. Must not be null * @return The result */ public static int[] tryParseColors(String[] in) { try { return parseColors(in); } catch(NumberFormatException e) { return new int[0]; } } private Util() { } }
4,131
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Spectrum.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Spectrum.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Spectrum visualizer. * * @author christopher */ public class Spectrum extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Spectrum)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("mode")) { return _processMode((pav.lib.visualizer.Spectrum) subject, Util.removeFirst(q)); } if(q[0].equals("freq")) { return _processFreq((pav.lib.visualizer.Spectrum) subject, Util.removeFirst(q)); } if(q[0].equals("sw")) { return _processStrokeWeight((pav.lib.visualizer.Spectrum) subject, Util.removeFirst(q)); } return false; } private boolean _processMode(pav.lib.visualizer.Spectrum subject, String[] query) { if(query[0].equals("bins")) { subject.setMode(pav.lib.visualizer.Waveform.MODE_BINS); return true; } else if(query[0].equals("dots")) { subject.setMode(pav.lib.visualizer.Waveform.MODE_DOTS); return true; } else if(query[0].equals("shape")) { subject.setMode(pav.lib.visualizer.Waveform.MODE_SHAPE); return true; } return false; } private boolean _processFreq(pav.lib.visualizer.Spectrum subject, String[] query) { int[] freqs = Util.tryParseInts(query); if(freqs.length == 1) { if(freqs[0] == 0) { subject.noCutoffFrequencies(); return true; } else if(freqs[0] > 0) { subject.setCutoffFrequencies(0, freqs[0]); return true; } } else if(freqs.length == 2) { if(freqs[1] > freqs[0] && freqs[0] >= 0) { subject.setCutoffFrequencies(freqs[0], freqs[1]); return true; } } return false; } private boolean _processStrokeWeight(pav.lib.visualizer.Spectrum subject, String[] query) { try { float sw = Float.parseFloat(query[0]); if(sw > 0) { subject.setStrokeWeight(sw); return true; } return false; } catch(NumberFormatException e) { return false; } } }
2,857
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Generic.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Generic.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; import processing.core.PApplet; /** * Configurator for all visualizers. * * @author christopher */ public class Generic extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("color")) { return _processColor(subject, Util.removeFirst(q)); } if(q[0].equals("area")) { return _processArea(subject, Util.removeFirst(q)); } return false; } private boolean _processColor(Visualizer subject, String[] query) { int[] colors = Util.tryParseColors(query); if(colors.length == 0) return false; if(colors.length == 1) { subject.setColor(colors[0]); } else if(colors.length == 2) { subject.setColor(colors[0], colors[1], PApplet.RGB); } else { float[] thresholds = new float[colors.length]; float delta = (float) (1.0 / (thresholds.length - 1)); for(int i = 0; i < thresholds.length; i++) { thresholds[i] = i * delta; } subject.setColor(thresholds, colors, PApplet.RGB); } return true; } private boolean _processArea(Visualizer subject, String[] query) { float[] coords = Util.tryParseFloats(query); if(coords.length != 4) return false; for(float v : coords) { if(v < 0 || v > 1) return false; } if(coords[2] <= coords[0]) return false; if(coords[3] <= coords[1]) return false; subject.setArea(coords[0], coords[1], coords[2], coords[3], true); return true; } }
2,355
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Waveform.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Waveform.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Waveform visualizer. * * @author christopher */ public class Waveform extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Waveform)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("mode")) { return _processMode((pav.lib.visualizer.Waveform) subject, Util.removeFirst(q)); } if(q[0].equals("sw")) { return _processStrokeWeight((pav.lib.visualizer.Waveform) subject, Util.removeFirst(q)); } return false; } private boolean _processMode(pav.lib.visualizer.Waveform subject, String[] query) { if(query[0].equals("bins")) { subject.setMode(pav.lib.visualizer.Waveform.MODE_BINS); return true; } else if(query[0].equals("dots")) { subject.setMode(pav.lib.visualizer.Waveform.MODE_DOTS); return true; } else if(query[0].equals("shape")) { subject.setMode(pav.lib.visualizer.Waveform.MODE_SHAPE); return true; } return false; } private boolean _processStrokeWeight(pav.lib.visualizer.Waveform subject, String[] query) { try { float sw = Float.parseFloat(query[0]); if(sw > 0) { subject.setStrokeWeight(sw); return true; } return false; } catch(NumberFormatException e) { return false; } } }
2,219
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Spectogram.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Spectogram.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Spectogram visualizer. * * @author christopher */ public class Spectogram extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Spectogram)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("hightop")) { return _processHightop((pav.lib.visualizer.Spectogram) subject, Util.removeFirst(q)); } if(q[0].equals("freq")) { return _processFreq((pav.lib.visualizer.Spectogram) subject, Util.removeFirst(q)); } return false; } private boolean _processHightop(pav.lib.visualizer.Spectogram subject, String[] query) { subject.setHighOnTop(Util.parseBools(query)[0]); return true; } private boolean _processFreq(pav.lib.visualizer.Spectogram subject, String[] query) { int[] freqs = Util.tryParseInts(query); if(freqs.length == 1) { if(freqs[0] == 0) { subject.noCutoffFrequencies(); return true; } else if(freqs[0] > 0) { subject.setCutoffFrequencies(0, freqs[0]); return true; } } else if(freqs.length == 2) { if(freqs[1] > freqs[0] && freqs[0] >= 0) { subject.setCutoffFrequencies(freqs[0], freqs[1]); return true; } } return false; } }
2,155
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
ConfiguratorAbstract.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/ConfiguratorAbstract.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; /** * A configurator. * * @author christopher */ public abstract class ConfiguratorAbstract implements Configurator { }
898
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
ConfiguratorFactory.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/ConfiguratorFactory.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; /** * Factory for retreiving Configurator objects. This is a static class. * * @author christopher */ public class ConfiguratorFactory { private static Generic _generic; private static Waveform _waveform; private static Spectrum _spectrum; private static Spectogram _spectogram; private static MelSpectrum _melSpectrum; private static Rainbow _rainbow; private static Phasor _phasor; private static Boxes _boxes; private static Bubbles _bubbles; private static Wavering _wavering; /** * Returns the generic configurator. * * @return Generic configurator */ public static Generic generic() { if(_generic == null) { _generic = new Generic(); } return _generic; } /** * Returns the waveform configurator. * * @return Waveform configurator */ public static Waveform waveform() { if(_waveform == null) { _waveform = new Waveform(); } return _waveform; } /** * Returns the spectrum configurator. * * @return Spectrum configurator */ public static Spectrum spectrum() { if(_spectrum == null) { _spectrum = new Spectrum(); } return _spectrum; } /** * Returns the spectogram configurator. * * @return Spectogram configurator */ public static Spectogram spectogram() { if(_spectogram == null) { _spectogram = new Spectogram(); } return _spectogram; } /** * Returns the melspectrum configurator. * * @return Melspectrum configurator */ public static MelSpectrum melSpectrum() { if(_melSpectrum == null) { _melSpectrum = new MelSpectrum(); } return _melSpectrum; } /** * Returns the rainbow configurator. * * @return Rainbow configurator */ public static Rainbow rainbow() { if(_rainbow == null) { _rainbow = new Rainbow(); } return _rainbow; } /** * Returns the phasor configurator. * * @return Phasor configurator */ public static Phasor phasor() { if(_phasor == null) { _phasor = new Phasor(); } return _phasor; } /** * Returns the boxes configurator. * * @return Boxes configurator */ public static Boxes boxes() { if(_boxes == null) { _boxes = new Boxes(); } return _boxes; } /** * Returns the bubbles configurator. * * @return Bubbles configurator */ public static Bubbles bubbles() { if(_bubbles == null) { _bubbles = new Bubbles(); } return _bubbles; } /** * Returns the wavering configurator. * * @return Wavering configurator */ public static Wavering wavering() { if(_wavering == null) { _wavering = new Wavering(); } return _wavering; } private ConfiguratorFactory() { } }
3,434
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Bubbles.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Bubbles.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Bubbles visualizer. * * @author christopher */ public class Bubbles extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Bubbles)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("darken")) { return _processDarken((pav.lib.visualizer.Bubbles) subject, Util.removeFirst(q)); } if(q[0].equals("size")) { return _processSize((pav.lib.visualizer.Bubbles) subject, Util.removeFirst(q)); } if(q[0].equals("bloom")) { return _processBloom((pav.lib.visualizer.Bubbles) subject, Util.removeFirst(q)); } if(q[0].equals("rate")) { return _processRate((pav.lib.visualizer.Bubbles) subject, Util.removeFirst(q)); } return false; } private boolean _processDarken(pav.lib.visualizer.Bubbles subject, String[] query) { float[] darken = Util.tryParseFloats(query); if(darken.length != 1 || darken[0] <= 0) return false; subject.setDarkenFactor(darken[0]); return true; } private boolean _processSize(pav.lib.visualizer.Bubbles subject, String[] query) { float[] size = Util.tryParseFloats(query); if(size.length != 2 || size[0] <= 0 || size[0] > size[1] || size[1] > 0.5f) return false; subject.setBubbleSize(size[0], size[1]); return true; } private boolean _processBloom(pav.lib.visualizer.Bubbles subject, String[] query) { boolean[] bloom = Util.parseBools(query); if(bloom.length != 1) return false; subject.useBloom(bloom[0]); return true; } private boolean _processRate(pav.lib.visualizer.Bubbles subject, String[] query) { float[] rate = Util.tryParseFloats(query); if(rate.length != 2 || rate[0] <= 0 || rate[0] > rate[1] || rate[1] > 5) return false; subject.setSpawnRate(rate[0], rate[1]); return true; } }
2,751
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Configurator.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Configurator.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.lib.visualizer.Visualizer; /** * Allows runtime configuration of a visualizer via a query entered by the user. */ public interface Configurator { /** * Processes a configuration request. * * @param subject The visualizer to configure. Must not be null * @param query The user query. Must not be null * @return Whether this configurator was able to handle the configuration request */ boolean process(Visualizer subject, String query); }
1,239
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Phasor.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Phasor.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Phasor visualizer. * * @author christopher */ public class Phasor extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Phasor)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("mode")) { return _processMode((pav.lib.visualizer.Phasor) subject, Util.removeFirst(q)); } else if(q[0].equals("sw")) { return _processStrokeWeight((pav.lib.visualizer.Phasor) subject, Util.removeFirst(q)); } return false; } private boolean _processMode(pav.lib.visualizer.Phasor subject, String[] query) { if(query[0].equals("dots")) { subject.setMode(pav.lib.visualizer.Phasor.MODE_DOTS); } else if(query[0].equals("lines")) { subject.setMode(pav.lib.visualizer.Phasor.MODE_LINES); } else if(query[0].equals("curves")) { subject.setMode(pav.lib.visualizer.Phasor.MODE_CURVES); } else { return false; } return true; } private boolean _processStrokeWeight(pav.lib.visualizer.Phasor subject, String[] query) { try { float sw = Float.parseFloat(query[0]); if(sw > 0) { subject.setStrokeWeight(sw); return true; } return false; } catch(NumberFormatException e) { return false; } } }
2,189
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Rainbow.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Rainbow.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Rainbow visualizer. * * @author christopher */ public class Rainbow extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Rainbow)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("mode")) { return _processMode((pav.lib.visualizer.Rainbow) subject, Util.removeFirst(q)); } return false; } private boolean _processMode(pav.lib.visualizer.Rainbow subject, String[] query) { if(query[0].equals("frequency")) { subject.setMode(pav.lib.visualizer.Rainbow.MODE_FREQUENCY); } else if(query[0].equals("intensity")) { subject.setMode(pav.lib.visualizer.Rainbow.MODE_INTENSITY); } else { return false; } return true; } }
1,685
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
MelSpectrum.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/MelSpectrum.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the MelSpectrum visualizer. * * @author christopher */ public class MelSpectrum extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.MelSpectrum)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("num")) { return _processNum((pav.lib.visualizer.MelSpectrum) subject, Util.removeFirst(q)); } if(q[0].equals("bcolor")) { return _processBcolor((pav.lib.visualizer.MelSpectrum) subject, Util.removeFirst(q)); } if(q[0].equals("quantize")) { return _processQuantize((pav.lib.visualizer.MelSpectrum) subject, Util.removeFirst(q)); } return false; } private boolean _processNum(pav.lib.visualizer.MelSpectrum subject, String[] query) { int[] num = Util.tryParseInts(query); if(num.length != 1 || num[0] <= 0) return false; subject.setNumBands(num[0]); return true; } private boolean _processBcolor(pav.lib.visualizer.MelSpectrum subject, String[] query) { int[] c = Util.tryParseColors(query); if(c.length != 1) return false; subject.setBorderColor(c[0]); return true; } private boolean _processQuantize(pav.lib.visualizer.MelSpectrum subject, String[] query) { int[] q = Util.tryParseInts(query); if(q.length != 1) return false; subject.quantize(q[0]); return true; } }
2,280
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Wavering.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Wavering.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; /** * Configurator for the Wavering visualizer. * * @author christopher */ public class Wavering extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Wavering)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("sw")) { return _processStrokeWeight((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("radius")) { return _processRadius((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("displace")) { return _processDisplace((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("rcolor")) { return _processRcolor((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("darken")) { return _processDarken((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("brightthresh")) { return _processBrightthresh((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("bloomintensity")) { return _processBloomintensity((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("exposure")) { return _processExposure((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } if(q[0].equals("maxbright")) { return _processMaxbright((pav.lib.visualizer.Wavering) subject, Util.removeFirst(q)); } return false; } private boolean _processStrokeWeight(pav.lib.visualizer.Wavering subject, String[] query) { try { float sw = Float.parseFloat(query[0]); if(sw > 0) { subject.setStrokeWeight(sw); return true; } return false; } catch(NumberFormatException e) { return false; } } private boolean _processRadius(pav.lib.visualizer.Wavering subject, String[] query) { float[] radius = Util.tryParseFloats(query); switch(radius.length) { case 1 : if(radius[0] > 0) { subject.setRadius(radius[0], radius[0]); return true; } else { return false; } case 2 : if(radius[0] > 0 && radius[1] > 0) { subject.setRadius(radius[0], radius[1]); return true; } else { return false; } default : return false; } } private boolean _processDisplace(pav.lib.visualizer.Wavering subject, String[] query) { float[] displace = Util.tryParseFloats(query); switch(displace.length) { case 1 : if(displace[0] > 0) { subject.setDisplacement(displace[0], displace[0]); return true; } else { return false; } case 2 : if(displace[0] > 0 && displace[1] > 0) { subject.setDisplacement(displace[0], displace[1]); return true; } else { return false; } default : return false; } } private boolean _processRcolor(pav.lib.visualizer.Wavering subject, String[] query) { if(! (subject.getImplementation() instanceof pav.lib.visualizer.Wavering.Fancy)) { return false; } pav.lib.visualizer.Wavering.Fancy impl = (pav.lib.visualizer.Wavering.Fancy) subject.getImplementation(); int[] color = Util.tryParseColors(query); if(color.length == 1) { impl.setRingColor(color[0]); return true; } return false; } private boolean _processDarken(pav.lib.visualizer.Wavering subject, String[] query) { if(! (subject.getImplementation() instanceof pav.lib.visualizer.Wavering.Fancy)) { return false; } pav.lib.visualizer.Wavering.Fancy impl = (pav.lib.visualizer.Wavering.Fancy) subject.getImplementation(); float[] darken = Util.tryParseFloats(query); if(darken.length == 1 && darken[0] > 0 && darken[0] <= 1) { impl.setDarkenFactor(darken[0]); return true; } return false; } private boolean _processBrightthresh(pav.lib.visualizer.Wavering subject, String[] query) { if(! (subject.getImplementation() instanceof pav.lib.visualizer.Wavering.Fancy)) { return false; } pav.lib.visualizer.Wavering.Fancy impl = (pav.lib.visualizer.Wavering.Fancy) subject.getImplementation(); float[] brightthresh = Util.tryParseFloats(query); if(brightthresh.length == 1 && brightthresh[0] > 0 && brightthresh[0] < 1) { impl.setBrightnessThreshold(brightthresh[0]); return true; } return false; } private boolean _processBloomintensity(pav.lib.visualizer.Wavering subject, String[] query) { if(! (subject.getImplementation() instanceof pav.lib.visualizer.Wavering.Fancy)) { return false; } pav.lib.visualizer.Wavering.Fancy impl = (pav.lib.visualizer.Wavering.Fancy) subject.getImplementation(); float[] intensity = Util.tryParseFloats(query); if(intensity.length == 1 && intensity[0] >= 0) { impl.setBloomIntensity(intensity[0]); return true; } return false; } private boolean _processExposure(pav.lib.visualizer.Wavering subject, String[] query) { if(! (subject.getImplementation() instanceof pav.lib.visualizer.Wavering.Fancy)) { return false; } pav.lib.visualizer.Wavering.Fancy impl = (pav.lib.visualizer.Wavering.Fancy) subject.getImplementation(); float[] exposure = Util.tryParseFloats(query); if(exposure.length == 1 && exposure[0] > 0) { impl.setTonemapExposure(exposure[0]); return true; } return false; } private boolean _processMaxbright(pav.lib.visualizer.Wavering subject, String[] query) { if(! (subject.getImplementation() instanceof pav.lib.visualizer.Wavering.Fancy)) { return false; } pav.lib.visualizer.Wavering.Fancy impl = (pav.lib.visualizer.Wavering.Fancy) subject.getImplementation(); float[] maxbright = Util.tryParseFloats(query); if(maxbright.length == 1 && maxbright[0] > 0) { impl.setTonemapMaxBrightness(maxbright[0]); return true; } return false; } }
6,715
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Boxes.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/configurator/Boxes.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.configurator; import pav.Util; import pav.lib.visualizer.Visualizer; import processing.core.PApplet; /** * Configurator for the Boxes visualizer. * * @author christopher */ public class Boxes extends ConfiguratorAbstract { @Override public boolean process(Visualizer subject, String query) { if(! (subject instanceof pav.lib.visualizer.Boxes)) { return false; } String[] q = query.split(" "); if(q.length < 2) { return false; } if(q[0].equals("rotate")) { return _processRotate((pav.lib.visualizer.Boxes) subject, Util.removeFirst(q)); } if(q[0].equals("bcolor")) { return _processBcolor((pav.lib.visualizer.Boxes) subject, Util.removeFirst(q)); } if(q[0].equals("quantize")) { return _processQuantize((pav.lib.visualizer.Boxes) subject, Util.removeFirst(q)); } if(q[0].equals("maxheight")) { return _processMaxHeight((pav.lib.visualizer.Boxes) subject, Util.removeFirst(q)); } return false; } private boolean _processRotate(pav.lib.visualizer.Boxes subject, String[] query) { float[] factor = Util.tryParseFloats(query); if(factor.length != 1 || Math.abs(factor[0]) > 5) return false; subject.rotate(factor[0] * PApplet.PI / 360); return true; } private boolean _processBcolor(pav.lib.visualizer.Boxes subject, String[] query) { int[] c = Util.tryParseColors(query); if(c.length != 1) return false; subject.setEdgeColor(c[0]); return true; } private boolean _processQuantize(pav.lib.visualizer.Boxes subject, String[] query) { int[] q = Util.tryParseInts(query); if(q.length != 1) return false; subject.quantize(q[0]); return true; } private boolean _processMaxHeight(pav.lib.visualizer.Boxes subject, String[] query) { int[] q = Util.tryParseInts(query); if(q.length != 1 || q[0] <= 0) return false; subject.setMaxHeight(q[0]); return true; } }
2,657
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
UDPAudioSource.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/audiosource/UDPAudioSource.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import pav.Config; /** * UDP audio source. * * @author christopher */ public class UDPAudioSource extends AudioSource implements Runnable { private final AudioCallback _callback; private final DatagramSocket _socket; private final Thread _thread; private boolean _closed; /** * Ctor. * * @param callback The callback to use. Must not be null * @throws SocketException If the socket could not be created */ public UDPAudioSource(AudioCallback callback) throws SocketException { _callback = callback; _socket = new DatagramSocket(Config.udpPort); _thread = new Thread(this, "UDPAudioSource"); } @Override public void read() { _thread.start(); } @Override public void run() { int ss2 = Config.sampleSize * 2; byte[] bb = new byte[ss2]; DatagramPacket packet = new DatagramPacket(bb, bb.length); AudioStream stream = null; PipedOutputStream os = null; PipedInputStream is = null; try { os = new PipedOutputStream(); is = new PipedInputStream(os); stream = new AudioStream(is, _callback); stream.read(); while(! Thread.interrupted()) { _socket.receive(packet); os.write(bb); packet.setLength(ss2); } } catch(IOException e) { if(! _closed) _callback.onError(e); } finally { _socket.close(); try { if(stream != null) stream.close(); if(os != null) os.close(); if(is != null) is.close(); } catch(Exception e) { } } } @Override public void close() throws InterruptedException { _closed = true; _thread.interrupt(); _socket.close(); _thread.join(250); } }
2,578
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
AudioSource.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/audiosource/AudioSource.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; import pav.Config; import pav.lib.PAVException; /** * An audio source. * * @author christopher */ public abstract class AudioSource { /** * Creates an audio source based on the configuration. * * @param callback The callback to use. Must not be null * @return The audio source * @throws PAVException On errors */ public static AudioSource factory(AudioCallback callback) throws PAVException { try { if(Config.audioSource.equals(Config.AUDIO_SOURCE_FIFO)) { return new FIFOAudioSource(callback); } else if(Config.audioSource.equals(Config.AUDIO_SOURCE_UDP)) { return new UDPAudioSource(callback); } else { throw new PAVException("Invalid audio source specified."); } } catch(Exception e) { throw new PAVException("Error while initializing audio source.", e); } } /** * Starts reading (in a new thread). */ public abstract void read(); /** * Stops reading. * * @throws InterruptedException If the thread was interrupted while waiting for the source to close */ public abstract void close() throws InterruptedException; }
1,876
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
FIFOAudioSource.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/audiosource/FIFOAudioSource.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; import java.io.FileInputStream; import java.io.FileNotFoundException; import pav.Config; /** * FIFO audio source. * * @author christopher */ public class FIFOAudioSource extends AudioSource { private final AudioStream _stream; /** * Ctor. * * @param callback The callback. Must not be null * @throws FileNotFoundException If the fifo does not exist */ public FIFOAudioSource(AudioCallback callback) throws FileNotFoundException { _stream = new AudioStream(new FileInputStream(Config.fifoPath), callback); } @Override public void read() { _stream.read(); } @Override public void close() throws InterruptedException { _stream.close(); } }
1,451
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
AudioCallback.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/audiosource/AudioCallback.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * Audio Callback used by audio sources. * * @author christopher */ public interface AudioCallback { /** * Called on new audio frames. * * @param frame The frame. Must not be null */ void onNewFrame(float[] frame); /** * Called on errors. * * @param error The error */ void onError(Throwable error); }
1,107
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
AudioStream.java
/FileExtraction/Java_unseen/skpdvdd_PAV/pav/src/pav/audiosource/AudioStream.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import pav.Config; /** * An audio stream. * * @author christopher */ public class AudioStream implements Runnable { private final Thread _thread; private final DataInputStream _is; private final AudioCallback _callback; private boolean _closed; /** * Ctor. * * @param source The input to read from. Must not be null and readable * @param callback The callback to send new frames to. Must not be null */ public AudioStream(InputStream source, AudioCallback callback) { _callback = callback; _is = new DataInputStream(source); _thread = new Thread(this, "AudioStream"); } /** * Starts reading (in a new thread). */ public void read() { _thread.start(); } @Override public void run() { try { int ss = Config.sampleSize; short[] sb = new short[ss]; byte[] bb = new byte[ss * 2]; float[] frame = new float[ss]; float normalize = (float) Short.MAX_VALUE; ByteBuffer bbuf = ByteBuffer.wrap(bb); bbuf.order(Config.byteOrder); ShortBuffer sbuf = bbuf.asShortBuffer(); while(! Thread.interrupted()) { _is.readFully(bb); sbuf.clear(); sbuf.get(sb); for(int i = 0; i < ss; i++) { frame[i] = sb[i] / normalize; } _callback.onNewFrame(frame); } } catch(IOException e) { if(! _closed) _callback.onError(e); } finally { try { _is.close(); } catch(IOException e) { } } } /** * Closes the audio stream. * * @throws InterruptedException If the thread was interrupted while waiting for the stream to close */ public void close() throws InterruptedException { _closed = true; try { _is.close(); } catch(IOException e) { } _thread.interrupt(); _thread.join(250); } }
2,646
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
StreamingBuffer.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/StreamingBuffer.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; import processing.core.PApplet; import processing.core.PImage; import processing.opengl.PGraphicsOpenGL; import codeanticode.glgraphics.GLGraphics; import codeanticode.glgraphics.GLGraphicsOffScreen; import codeanticode.glgraphics.GLTexture; /** * A streaming image buffer, useful in some visualizations such as spectogram. * * This Uses GLGraphics if available. The Processing version supports alpha channel * transparency but is rather slow. The GLGraphics version is optimized for speed. * It does not support transparency. Also, the GLGraphics implementation currently ignores * the width argument of the draw method for implementation reasons. This does however * not affect the result if the buffer is drawn to occupy the full area of the host PApplet. * * @author christopher */ public class StreamingBuffer { private final int _width; private final int _height; private final PApplet _p; private final StreamingBufferImpl _impl; /** * Ctor. * * @param p The PApplet this buffer should draw itself to. Must not be null * @param width The width of the buffer. Must be positive * @param height The height of the buffer. Must be positive */ public StreamingBuffer(PApplet p, int width, int height) { _p = p; _width = width; _height = height; _impl = (p.g instanceof GLGraphics) ? new StreamingBufferGLGraphics() : new StreamingBufferPImage(); } /** * Gets the buffer width * * @return Buffer width */ public int getWidth() { return _width; } /** * Gets the buffer height * * @return Buffer height */ public int getHeight() { return _height; } /** * Adds a new data sample to the buffer. This is equal to add(data, true). * * @param data The data sample to add. The array length must be equal to the buffer height * @throws PAVException If the array length is not equal to the buffer height */ public void add(int[] data) throws PAVException { add(data, true); } /** * Adds a new data sample to the buffer. * * @param data The data sample to add. The array length must be equal to the buffer height * @param startOnTop Whether to fill the buffer column from top to bottom or vice versa * @throws PAVException If the array length is not equal to the buffer height */ public void add(int[] data, boolean startOnTop) throws PAVException { if(_height != data.length) { throw new PAVException("Length of the data argument does not match the buffer height."); } _impl.add(data, startOnTop); } /** * Draws this buffer to a given area of the host PApplet. * * @param xStart The first x-coordinate of the display area * @param yStart The first y-coordinate of the display area * @param width The width of the display area. Must be > 0. Ignored under GLGraphics * @param height The height of the display area. Must be > 0 */ public void draw(int xStart, int yStart, int width, int height) { _impl.draw(xStart, yStart, width, height); } /** * Disposes this buffer. * * Subsequent calls to other methods of this class might throw an exception. */ public void dispose() { _impl.dispose(); } /** * Buffer implementation. * * @author christopher */ private abstract class StreamingBufferImpl { /** * Adds a new data sample to the buffer. * * @param data The data sample to add. The array length must be equal to the buffer height * @param startOnTop Whether to fill the buffer column from top to bottom or vice versa */ public abstract void add(int[] data, boolean startOnTop); /** * Draws this buffer to a given area of the host PApplet. * * @param xStart The first x-coordinate of the display area * @param yStart The first y-coordinate of the display area * @param width The width of the display area. Must be > 0 * @param height The height of the display area. Must be > 0 */ public abstract void draw(int xStart, int yStart, int width, int height); /** * Disposes this buffer. * * Subsequent calls to other methods of this class might throw an exception. */ public abstract void dispose(); } /** * Buffer implementation using a single PImage object. * * This implementation uses only a single PImage object and * supports alpha channel transparency. It is however rather slow. * * @author christopher */ private class StreamingBufferPImage extends StreamingBufferImpl { private int _counter, _x; private boolean _switch; private final PImage _buffer; /** * Ctor. */ public StreamingBufferPImage() { _buffer = new PImage(_width, _height, PApplet.ARGB); } @Override public void add(int[] data, boolean startOnTop) { int len = data.length; int k = _counter % _width; _x = _width - k - 1; _buffer.loadPixels(); for(int i = 0; i < len; i++) { if(startOnTop) { _buffer.pixels[i * _width + _x] = data[i]; } else { _buffer.pixels[(len - i - 1) * _width + _x] = data[i]; } } _buffer.updatePixels(); _counter++; if(! _switch && _counter == _width) { _switch = true; } } @Override public void draw(int xStart, int yStart, int width, int height) { _p.blend(_buffer, _x, 0, _width - _x, _height, xStart, yStart, width - _x, height, PApplet.BLEND); if(_switch) { _p.blend(_buffer, 0, 0, _x, _height, xStart + width - _x, yStart, _x, height, PApplet.BLEND); } } @Override public void dispose() { } } /** * Buffer implementation using GLGraphics. * * This implementation is very fast, but it does not support alpha * channel transparency for the sake of speed. Also, the width argument * of the draw() method is currently ignored. * * @author christopher */ private class StreamingBufferGLGraphics extends StreamingBufferImpl { private int _counter, _x, _numBufferSwaps; private final GLTexture _column; private final GLGraphicsOffScreen _buffer1, _buffer2; /** * Ctor. */ public StreamingBufferGLGraphics() { _buffer1 = new GLGraphicsOffScreen(_p, _width, _height); _buffer1.beginDraw(); _buffer1.clear(0, 0); _buffer1.noStroke(); _buffer1.endDraw(); _buffer2 = new GLGraphicsOffScreen(_p, _width, _height); _buffer2.beginDraw(); _buffer2.clear(0, 0); _buffer2.noStroke(); _buffer2.endDraw(); _column = new GLTexture(_p, 1, _height); } @Override public void add(int[] data, boolean startOnTop) { int k = _counter % _width; GLGraphicsOffScreen active, passive; _x = _width - k - 1; if(_numBufferSwaps % 2 == 0) { active = _buffer1; passive = _buffer2; } else { active = _buffer2; passive = _buffer1; } int[] in; if(startOnTop) { in = data; } else { int len = data.length; int lenm1 = len - 1; int max = len / 2; in = new int[len]; for(int i = 0; i < max; i++) { in[i] = data[lenm1 - i]; in[lenm1 - i] = data[i]; } if(len % 2 == 1) { in[max] = data[max]; } } _column.putBuffer(in, PApplet.RGB, GLTexture.TEX_BYTE); active.beginDraw(); active.image(_column, _x, 0); active.endDraw(); if(k == 0 && _counter != 0) { passive.beginDraw(); passive.clear(0, 0); passive.endDraw(); _numBufferSwaps++; } _counter++; } /** * Draws this buffer to a given area of the host PApplet. * * @param xStart The first x-coordinate of the display area * @param yStart The first y-coordinate of the display area * @param width The width of the display area. Must be > 0. Ignored in this implementation * @param height The height of the display area. Must be > 0 */ @Override public void draw(int xStart, int yStart, int width, int height) { PGraphicsOpenGL p = (PGraphicsOpenGL) _p.g; GLGraphicsOffScreen active, passive; if(_numBufferSwaps % 2 == 0) { active = _buffer1; passive = _buffer2; } else { active = _buffer2; passive = _buffer1; } p.image(active.getTexture(), xStart -_x, yStart, width, height); p.image(passive.getTexture(), xStart -_x + _width - 1, yStart, width, height); } @Override public void dispose() { _buffer1.dispose(); _buffer2.dispose(); _column.delete(); } } }
9,116
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
ShaderManager.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/ShaderManager.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; import java.io.File; import java.io.FilenameFilter; import java.util.HashMap; import processing.core.PApplet; import codeanticode.glgraphics.GLGraphics; import codeanticode.glgraphics.GLTextureFilter; /** * Manages GLGraphics shaders. * * @author christopher */ public class ShaderManager { private static HashMap<String, GLTextureFilter> _textureFilters; /** * Initializes the shaders. Must be called before initializing any visualizers. * * @param p The PApplet to use. Must not be null * @throws PAVException On errors */ public static void initialize(PApplet p) throws PAVException { _textureFilters = new HashMap<String, GLTextureFilter>(); if(! (p.g instanceof GLGraphics)) { throw new PAVException("Shaders are only supported under the GLGraphics renderer."); } File s = new File("data/shaders"); if(s.canRead()) { String[] shaders = s.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return new File(dir, name).isFile() && name.toLowerCase().endsWith(".xml"); } }); for(String shader : shaders) { _textureFilters.put(shader.substring(0, shader.length() - 4), new GLTextureFilter(p, "shaders/" + shader)); } } else { throw new PAVException("No shaders found."); } } /** * Returns a texture filter. * * Texture filters are shared by all visualizers, therefore settings might be changed by other visualizers. * * @param name The name of the texture filter. Must not be null * @return The filter * @throws PAVException If the filter name is unknown */ public static GLTextureFilter getTextureFilter(String name) throws PAVException { if(! _textureFilters.containsKey(name)) { throw new PAVException("Texture filter '" + name + "' not found."); } return _textureFilters.get(name); } private ShaderManager() { } }
2,692
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Util.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/Util.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; import processing.core.PApplet; /** * Misc utility functions. This is a static class. * * @author christopher */ public class Util { /** * Quantizes values to a number of integers, e.g. if data is {3,4,5,6} and steps * is 2 the result will be {1.0,1.0,2.0,2.0}. The lowest value in data will always map to 1.0, * the largest to steps. * * @param data The data to quantize. Must not be null * @param steps The number of steps. Must be > 0 * @return The quantized data */ public static float[] quantize(float[] data, int steps) { float[] mm = calcMinMax(data); return quantize(data, steps, mm[0], mm[1]); } /** * Quantizes values to a number of integers, e.g. if data is {3,4,5,6} and steps * is 2 the result will be {1.0,1.0,2.0,2.0}. The lowest value in data will always map to 1, * the largest to steps. Use this version if you know the min and max values of the data set. * * @param data The data to quantize. Must not be null * @param steps The number of steps. Must be > 0 * @param dataMin The minimum value in data * @param dataMax The maximum value in data * @return The quantized data */ public static float[] quantize(float[] data, int steps, float dataMin, float dataMax) { int len = data.length; float[] out = new float[len]; for(int i = 0; i < len; i++) { out[i] = Math.round(PApplet.map(data[i], dataMin, dataMax, 1, steps)); } return out; } /** * Calculates the minimum and maximum of a data set. * * @param data The data set. Must not be null * @return An array of the form { min, max } */ public static float[] calcMinMax(float[] data) { int len = data.length; float min = Float.MAX_VALUE; float max = Float.MIN_VALUE; for(int i = 0; i < len; i++) { float v = data[i]; if(v < min) min = v; if(v > max) max = v; } return new float[] { min, max }; } private Util() { } }
2,678
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
VisualizationImpl.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/VisualizationImpl.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import pav.lib.frame.Frame; import pav.lib.visualizer.Visualizer; import processing.core.PApplet; /** * Visualization implementation. * * @author christopher */ public class VisualizationImpl implements Visualization { private final PApplet _p; private final TreeMap<Integer, Visualizer> _visualizers; private final HashMap<String, Integer> _visualizerNames; /** * Ctor. * * @param target Where to visualize to. Must not be null */ public VisualizationImpl(PApplet target) { _p = target; _visualizers = new TreeMap<Integer, Visualizer>(); _visualizerNames = new HashMap<String, Integer>(); } /** * Adds a new visualizer. The new visualizer will be drawn last. * This method automatically tells the visualizer to draw to the applet of this visualization. * * @param visualizer The visualizer to add. Must not be null * @throws PAVException If an error occured while adding the visualizer */ @Override public void addVisualizer(Visualizer visualizer) throws PAVException { int level = 0; try { level = _visualizers.lastKey() + 1; } catch(NoSuchElementException e) { } addVisualizer(visualizer, level, visualizer + " [" + level + "]"); } /** * Adds a new visualizer. The new visualizer will be drawn last. * This method automatically tells the visualizer to draw to the applet of this visualization. * * @param visualizer The visualizer to add. Must not be null * @param name The name of the visualizer. Must be unique * @throws PAVException If an error occured while adding the visualizer */ @Override public void addVisualizer(Visualizer visualizer, String name) throws PAVException { int level = 0; try { level = _visualizers.lastKey() + 1; } catch(NoSuchElementException e) { } addVisualizer(visualizer, level, name); } /** * Adds a new visualizer with a given level. The level specifies then the visualizer * will be told to draw itself relative to the other visualizers. Visualizers with lower * levels will be drawn first. If a visualizer with the given level already exists, it will be replaced. * This method automatically tells the visualizer to draw to the applet of this visualization. * * @param visualizer The visualizer to add. Must not be null * @param level The level * @throws PAVException If an error occured while adding the visualizer */ @Override public void addVisualizer(Visualizer visualizer, int level) throws PAVException { addVisualizer(visualizer, level, visualizer + " [" + level + "]"); } /** * Adds a new visualizer with a given level. The level specifies then the visualizer * will be told to draw itself relative to the other visualizers. Visualizers with lower * levels will be drawn first. If a visualizer with the given level already exists, it will be replaced. * This method automatically tells the visualizer to draw to the applet of this visualization. * * @param visualizer The visualizer to add. Must not be null * @param level The level * @param name The name of the visualizer. Must be unique * @throws PAVException If an error occured while adding the visualizer */ @Override public void addVisualizer(Visualizer visualizer, int level, String name) throws PAVException { visualizer.drawTo(_p); if(_visualizers.containsKey(level)) { removeVisualizerAt(level); } _visualizers.put(level, visualizer); _visualizerNames.put(name, level); } @Override public void removeVisualizer(Visualizer visualizer) { Integer key = null; for(Map.Entry<Integer, Visualizer> e : _visualizers.entrySet()) { if(e.getValue().equals(visualizer)) { key = e.getKey(); break; } } if(key != null) { removeVisualizerAt(key); } } @Override public void removeVisualizer(String name) { if(_visualizerNames.containsKey(name)) { removeVisualizerAt(_visualizerNames.get(name)); } } @Override public void removeVisualizerAt(int level) { Visualizer remove = _visualizers.remove(level); if(remove != null) { remove.dispose(); } String key = null; for(Map.Entry<String, Integer> e : _visualizerNames.entrySet()) { if(e.getValue().equals(level)) { key = e.getKey(); break; } } if(key != null) { _visualizerNames.remove(key); } } @Override public Visualizer getVisualizer(String name) { if(_visualizerNames.containsKey(name)) { return getVisualizer(_visualizerNames.get(name)); } return null; } @Override public Visualizer getVisualizer(int level) { return _visualizers.get(level); } @Override public Map<Integer, Visualizer> getVisualizers() { return _visualizers; } @Override public int numVisualizers() { return _visualizers.size(); } @Override public void setSampleRate(float rate) { Frame.setSampleRate(rate); } @Override public void process(float[] frame) throws PAVException { Frame.update(frame); for(Visualizer v : visualizers()) { v.process(); } } /** * Returns a sorted list of the visualizers to draw to or an empty * set if no visualizers are added. * * @return A list of visualizers */ protected List<Visualizer> visualizers() { LinkedList<Visualizer> vis = new LinkedList<Visualizer>(); for(Visualizer v : _visualizers.values()) { vis.add(v); } return vis; } }
6,299
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
PAVException.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/PAVException.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; /** * Base class of all PAV-specific exceptions. * * @author christopher */ public class PAVException extends Exception { private static final long serialVersionUID = 4985787077612555714L; /** * Ctor. */ public PAVException() { super(); } /** * Ctor. * * @param message The error message */ public PAVException(String message) { super(message); } /** * Ctor. * * @param cause The cause of the error */ public PAVException(Throwable cause) { super(cause); } /** * Ctor. * * @param message The error message * @param cause The cause of the error */ public PAVException(String message, Throwable cause) { super(message, cause); } }
1,464
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
ColorMapper.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/ColorMapper.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; import java.io.Serializable; import processing.core.PApplet; /** * Maps values to colors. * * @author christopher */ public class ColorMapper implements Serializable { private static final long serialVersionUID = -2737277542090976648L; private ColorMapperImpl _mapper; private int _mode; private float _vMin, _vMax; /** * Sets the static color to use. * * @param color The color */ public void setColor(int color) { Constant c = new Constant(); c.setColor(color); _mapper = c; } /** * Sets two colors to interpolate between. * * @param a The color to start from * @param b The color to interpolate to * @param mode The color mode to use. Must be either PApplet.RGB or PApplet.HSB */ public void setColor(int a, int b, int mode) { TwoColors c = new TwoColors(); c.setColor(a, b); _mode = mode; _mapper = c; } /** * Sets the colors to interpolate between. * * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors * @param colors The The colors to use. Must be of same length as thresholds * @param mode The color mode to use. Must be either PApplet.RGB or PApplet.HSB */ public void setColor(float[] thresholds, int[] colors, int mode) { Colors c = new Colors(); c.setColor(thresholds, colors); _mode = mode; _mapper = c; } /** * Sets the minimum and maximum value. * * @param min The minimum value * @param max The maximum value */ public void setRange(float min, float max) { _vMin = min; _vMax = max; } /** * Maps a value to a color. * * @param value The value * @return The color */ public int map(float value) { return _mapper.map(value); } /** * A color mapper. * * @author christopher */ private abstract class ColorMapperImpl implements Serializable { private static final long serialVersionUID = -1018124658424277468L; /** * Maps a value to a color. * * @param value The value * @return The color */ public abstract int map(float value); } /** * A constant color mapper. * * @author christopher */ private class Constant extends ColorMapperImpl { private static final long serialVersionUID = 7034468912657552137L; private int _color; /** * Sets the static color to use. * * @param color The color */ public void setColor(int color) { _color = color; } /** * Maps a value to a color. * * @param value The value * @return The color */ @Override public int map(float value) { return _color; } } /** * Interpolates between two colors. * * @author christopher */ private class TwoColors extends ColorMapperImpl { private static final long serialVersionUID = -5054720378481970404L; private int _a, _b; /** * Sets two colors to interpolate between. * * @param a The color to start from * @param b The color to interpolate to */ public void setColor(int a, int b) { _a = a; _b = b; } /** * Maps a value to a color. * * @param value The value * @return The color */ @Override public int map(float value) { float f = PApplet.map(value, _vMin, _vMax, 0, 1); return PApplet.lerpColor(_a, _b, f, _mode); } } /** * Interpolates between an arbitrary number of colors. * * @author christopher */ private class Colors extends ColorMapperImpl { private static final long serialVersionUID = -2672613831235217060L; private float[] _thresholds; private int[] _colors; /** * Sets the colors to interpolate between. * * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors * @param colors The The colors to use. Must be of same length as thresholds */ public void setColor(float[] thresholds, int[] colors) { _thresholds = thresholds; _colors = colors; } /** * Maps a value to a color. * * @param value The value * @return The color */ @Override public int map(float value) { int cA = 0, cB = 0, l = _thresholds.length - 1; float tA = 0, tB = 0; for(int i = 0; i < l; i++) { cA = _colors[i]; cB = _colors[i + 1]; tA = _vMax * _thresholds[i]; tB = _vMax * _thresholds[i + 1]; if(value < tB) { break; } } float f = PApplet.map(value, tA, tB, 0, 1); return PApplet.lerpColor(cA, cB, f, _mode); } } }
5,366
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Visualization.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/Visualization.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; import java.util.Map; import pav.lib.visualizer.Visualizer; /** * A visualization, comprised of a number of visualizers. * * @author christopher */ public interface Visualization { /** * Adds a new visualizer. The new visualizer will be drawn last. * * @param visualizer The visualizer to add. Must not be null * @throws PAVException If an error occured while adding the visualizer */ void addVisualizer(Visualizer visualizer) throws PAVException; /** * Adds a new visualizer. The new visualizer will be drawn last. * * @param visualizer The visualizer to add. Must not be null * @param name The name of the visualizer. Must be unique * @throws PAVException If an error occured while adding the visualizer */ void addVisualizer(Visualizer visualizer, String name) throws PAVException; /** * Adds a new visualizer with a given level. The level specifies then the visualizer * will be told to draw itself relative to the other visualizers. Visualizers with lower * levels will be drawn first. If a visualizer with the given level already exists, it will be replaced. * * @param visualizer The visualizer to add. Must not be null * @param level The level * @throws PAVException If an error occured while adding the visualizer */ void addVisualizer(Visualizer visualizer, int level) throws PAVException; /** * Adds a new visualizer with a given level. The level specifies then the visualizer * will be told to draw itself relative to the other visualizers. Visualizers with lower * levels will be drawn first. If a visualizer with the given level already exists, it will be replaced. * * @param visualizer The visualizer to add. Must not be null * @param level The level * @param name The name of the visualizer. Must be unique * @throws PAVException If an error occured while adding the visualizer */ void addVisualizer(Visualizer visualizer, int level, String name) throws PAVException; /** * Removes a visualizer. Does nothing if the visualizer does not exist. * * @param visualizer The visualizer. Must not be null */ void removeVisualizer(Visualizer visualizer); /** * Removes the visualizer with the given name. Does nothing if the visualizer does not exist. * * @param name The name of the visualizer. Must not be null */ void removeVisualizer(String name); /** * Removes the visualizer at the specified level if it exists, otherwise does nothing. * * @param level The level */ void removeVisualizerAt(int level); /** * Returns the visualizer that is located at the specified level. Returns null if * no visualizer exists at that level. * * @param level The level * @return The visualizer or null */ Visualizer getVisualizer(int level); /** * Returns the visualizer with the given name or null if no such visualizer exists. * * @param level The visualizer name * @return The visualizer or null */ Visualizer getVisualizer(String name); /** * Gets all visualizers that are currently part of this visualization along * with their associated level. The Map is be sorted, the visualizer with the * lowest level is the first item in the list. The returned map must not be modified. * * @return A map containing all visualizers */ Map<Integer, Visualizer> getVisualizers(); /** * Returns the number of visualizers this visualization contains. * * @return Number of visualizers */ int numVisualizers(); /** * Sets the audio sample rate. * * @param rate The sample rate. Must be > 0 */ void setSampleRate(float rate); /** * Tells the visualization to process. * * @param frame The next frame of the audio signal. Must not be null * @throws PAVException On any errors */ void process(float[] frame) throws PAVException; }
4,590
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Spectrum.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Spectrum.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.frame.Frame; import pav.lib.frame.TransformResult; import processing.core.PApplet; /** * Draws the logarithm of the frequency spectrum of the currently playing audio data. * * @author christopher */ public class Spectrum extends VisualizerAbstract { private static final long serialVersionUID = -7118841157652718274L; /** * Draw lines. */ public static final int MODE_BINS = 1; /** * Draw dots. */ public static final int MODE_DOTS = 2; /** * Draw a shape. */ public static final int MODE_SHAPE = 3; private transient float _vMax; private int _mode; private float _strokeWeight; private boolean _rememberMax; private Integer _minFrequency, _maxFrequency; /** * Ctor. */ public Spectrum() { rememberMax(true); setMode(MODE_BINS); setStrokeWeight(1); noCutoffFrequencies(); setColor(new float[] { 0, 0.2f, 0.6f, 1 }, new int[] { 0xFF0000FF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 }, PApplet.RGB); } @Override public void process() throws PAVException { p.strokeWeight(_strokeWeight); float max; int from, to; TransformResult spectrum = Frame.Transform.spectrum(); float[] bands = spectrum.frame(); if(_minFrequency == null || _maxFrequency == null) { max = spectrum.max(); from = 0; to = bands.length - 1; } else { max = 0; from = Frame.Transform.Util.frequencyToBand(_minFrequency); to = Frame.Transform.Util.frequencyToBand(_maxFrequency); float sMax = spectrum.max(); for(int i = from; i <= to; i++) { float v = bands[i]; if(v == sMax) { max = v; break; } if(v > max) { max = v; } } } if(_rememberMax) { if(_vMax > max) { max = _vMax; } else { _vMax = max; } } cm.setRange(0, max); float[] area = getArea(); if(_mode == MODE_SHAPE) { p.noFill(); p.beginShape(); } for(int i = from; i <= to; i++) { float v = bands[i]; float x = PApplet.map(i, from, to, area[0], area[2]); float y = PApplet.map(v, 0, max, area[3], area[1]); p.stroke(cm.map(v)); switch(_mode) { case MODE_BINS : p.line(x, area[3], x, y); break; case MODE_DOTS : p.point(x, y); break; case MODE_SHAPE : p.vertex(x, y); break; } } if(_mode == MODE_SHAPE) { p.endShape(); } } /** * Sets the stroke weight to use when drawing. * * @param weight The stroke weight. Must be > 0 */ public void setStrokeWeight(float weight) { _strokeWeight = weight; } /** * Sets the cutoff frequencies. This will cut all frequency bands with lower * frequencies, the first used band will be the one with the frequency min in it. * The same counts for max. This means that the cutoff is not very precise. * * @param min The minimum frequency. Must be >= 0 * @param max The maximum frequency. Must be <= 22050 and > min */ public void setCutoffFrequencies(int min, int max) { _minFrequency = min; _maxFrequency = max; } /** * Tells the visualizer not to use cutoff frequencies. See cutoffFrequencies(). */ public void noCutoffFrequencies() { _minFrequency = null; _maxFrequency = null; } /** * Sets the visualization mode. Must be a valid mode according * to the MODE_ constants of this class. * * @param mode */ public void setMode(int mode) { _mode = mode; } /** * Before drawing the maximum intensity of the frequency data is calculated so that the output * can be scaled properly. This method sets whether the maximum will be saved and reused. * * @param remember Whether to remember the max intensity */ public void rememberMax(boolean remember) { _rememberMax = remember; } @Override public String toString() { switch(_mode) { case MODE_BINS : return "Spectrum (bin mode)"; case MODE_DOTS : return "Spectrum (dot mode)"; case MODE_SHAPE : return "Spectrum (shape mode)"; default : return "Spectrum"; } } @Override public void dispose() { } }
4,854
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Visualizer.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Visualizer.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import java.io.Serializable; import pav.lib.PAVException; import processing.core.PApplet; /** * A audio visualizer. * * @author christopher */ public interface Visualizer extends Serializable { /** * Sets the PApplet to draw to. Must be called before process(). * * @param applet Where to draw to. Must not be null * @throws PAVException If the visualizer does not work with this applet */ void drawTo(PApplet applet) throws PAVException; /** * Sets the area that can be used by this visualizer. If relative is set to false * the visualizer will use the given values as its boundary, independent of the * size of the PApplet. If relative is true, the values must be in the range [0,1] * and represent an area relative to the size of the PApplet. Processings coordinate * system is used, so (0,0) is the top left pixel. * * @param x1 Must be >= 0 and <= 1 if relative is true * @param y1 Must be >= 0 and <= 1 if relative is true * @param x2 Must be > x1 and <= 1 if relative is true * @param y2 Must be > y1 and <= 1 if relative is true * @param relative Whether or not the values are relative */ void setArea(float x1, float y1, float x2, float y2, boolean relative); /** * Draws to the PApplet specified by drawTo. * * @throws PAVException If an error occures while drawing */ void process() throws PAVException; /** * Sets the color to use when drawing this visualizer. How a visualizer uses the color * specified is not defined. It might not be used at all. * * @param color The color to use */ void setColor(int color); /** * Sets two colors to interpolate between when drawing this visualizer. How a visualizer uses the colors * specified is not defined. They might not be used at all. * * @param a The color to start from * @param b The color to interpolate to * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB */ void setColor(int a, int b, int mode); /** * Sets the colors to interpolate between when drawing this visualizer. How a visualizer uses the colors * specified is not defined. They might not be used at all. * * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors * @param colors The The colors to use. Must be of same length as thresholds * @param mode The color mode to use. Must be either PApplet.RGB or PApplet.HSB */ void setColor(float[] thresholds, int[] colors, int mode); /** * Returns a short string representation of this visualizer. * * @return visualizer info */ String toString(); /** * Disposes this visualizer, releasing all resources that were used exclusively * by this visualizer. Subsequent calls to any methods of the visualizer might cause exceptions. */ void dispose(); }
3,673
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Waveform.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Waveform.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.frame.Frame; import processing.core.PApplet; /** * Draws a waveform of the currently playing audio data. * * @author christopher */ public class Waveform extends VisualizerAbstract { private static final long serialVersionUID = -9219616480317414260L; /** * Draw lines. */ public static final int MODE_BINS = 1; /** * Draw dots. */ public static final int MODE_DOTS = 2; /** * Draw a shape. */ public static final int MODE_SHAPE = 3; private int _mode; private float _strokeWeight; private boolean _colorAbsolute; /** * Ctor. */ public Waveform() { setMode(MODE_BINS); colorAbsolute(true); setStrokeWeight(1); setColor(0xFFFF0000, 0xFFFFFF00, PApplet.RGB); } @Override public void process() throws PAVException { p.strokeWeight(_strokeWeight); float[] frame = Frame.samples(); float[] area = getArea(); int len = frame.length; if(_mode == MODE_SHAPE) { p.noFill(); p.beginShape(); } for(int i = 0; i < len; i++) { float v = frame[i]; float x = PApplet.map(i, 0, len - 1, area[0], area[2]); float y = PApplet.map(v, -1, 1, area[1], area[3]); if(_colorAbsolute && v < 0) { p.stroke(cm.map(v * -1)); } else { p.stroke(cm.map(v)); } switch(_mode) { case MODE_BINS : p.line(x, (area[1] + area[3]) / 2, x, y); break; case MODE_DOTS : p.point(x, y); break; case MODE_SHAPE : p.vertex(x, y); break; } } if(_mode == MODE_SHAPE) { p.endShape(); } } /** * Sets the visualization mode. Must be a valid mode according * to the MODE_ constants of this class. * * @param mode The visualization mode */ public void setMode(int mode) { _mode = mode; } /** * Whether to use the absolute values for coloring, i.e. whether -1 gets the same color as 1 or not. * * @param absolute Whether to use absolute coloring */ public void colorAbsolute(boolean absolute) { if(absolute) { _colorAbsolute = true; cm.setRange(0, 1); } else { _colorAbsolute = false; cm.setRange(-1, 1); } } /** * Sets the stroke weight to use when drawing. * * @param weight The stroke weight. Must be > 0 */ public void setStrokeWeight(float weight) { _strokeWeight = weight; } @Override public String toString() { switch(_mode) { case MODE_BINS : return "Waveform (bin mode)"; case MODE_DOTS : return "Waveform (dot mode)"; case MODE_SHAPE : return "Waveform (shape mode)"; default : return "Waveform"; } } @Override public void dispose() { } }
3,420
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Spectogram.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Spectogram.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.StreamingBuffer; import pav.lib.frame.Frame; import pav.lib.frame.TransformResult; import processing.core.PApplet; /** * A two dimensional spectogram. * * @author christopher */ public class Spectogram extends VisualizerAbstract { private static final long serialVersionUID = 3765068172167986718L; private transient float _vMax; private transient StreamingBuffer _buffer; private boolean _rememberMax, _highOnTop; private Integer _minFrequency, _maxFrequency; /** * Ctor. */ public Spectogram() { rememberMax(true); noCutoffFrequencies(); setHighOnTop(false); setColor(new float[] { 0, 0.1f, 0.5f, 1 }, new int[] { 0x00000000, 0xFF0000FF, 0xFF33FF33, 0xFFFF0000 }, PApplet.RGB); } @Override public void process() throws PAVException { float max; int from, to; TransformResult spectrum = Frame.Transform.spectrum(); float[] bands = spectrum.frame(); if(_minFrequency == null || _maxFrequency == null) { max = spectrum.max(); from = 0; to = bands.length - 1; } else { max = 0; from = Frame.Transform.Util.frequencyToBand(_minFrequency); to = Frame.Transform.Util.frequencyToBand(_maxFrequency); float sMax = spectrum.max(); for(int i = from; i <= to; i++) { float v = bands[i]; if(v == sMax) { max = v; break; } if(v > max) { max = v; } } } int numBands = (to - from) + 1; if(_rememberMax) { if(_vMax > max) { max = _vMax; } else { _vMax = max; } } cm.setRange(0, max); float[] area = getArea(); int width = (int) Math.floor(area[2] - area[0]); int height = (int) Math.floor(area[3] - area[1]); if(_buffer == null || width != _buffer.getWidth() || numBands != _buffer.getHeight()) { if(_buffer != null) { _buffer.dispose(); } _buffer = new StreamingBuffer(p, width, numBands); } cm.setRange(0, _vMax); int[] colors = new int[numBands]; for(int i = from; i <= to; i++) { colors[i - from] = cm.map(bands[i]); } _buffer.add(colors, ! _highOnTop); _buffer.draw((int) area[0], (int) area[1], width, height); } /** * Before drawing the maximum intensity of the frequency data is calculated so that the output * can be scaled properly. By default this information is stored and reused if the maximum of the * current frame is lower. if set to false, a new maximum will be calculated for every new frame. * * @param remember Whether or not to remember the max intensity */ public void rememberMax(boolean remember) { _rememberMax = remember; } /** * Sets the cutoff frequencies. This will cut all frequency bands with lower * frequencies, the first used band will be the one with the frequency min in it. * The same counts for max. This means that the cutoff is not very precise. * * @param min The minimum frequency. Must be >= 0 * @param max The maximum frequency. Must be <= 22050 and > min */ public void setCutoffFrequencies(int min, int max) { _minFrequency = min; _maxFrequency = max; } /** * Tells the visualizer not to use cutoff frequencies. See cutoffFrequencies(). */ public void noCutoffFrequencies() { _minFrequency = null; _maxFrequency = null; } /** * Whether to draw high frequencies at the top of the visualization or not. * * @param onTop Whether to draw high frequencies on top. */ public void setHighOnTop(boolean onTop) { _highOnTop = onTop; } @Override public String toString() { return "Spectogram"; } @Override public void dispose() { if(_buffer != null) _buffer.dispose(); } }
4,442
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Bubbles.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Bubbles.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import java.util.Arrays; import java.util.LinkedList; import java.util.Random; import pav.lib.PAVException; import pav.lib.ShaderManager; import pav.lib.frame.Frame; import processing.core.PApplet; import codeanticode.glgraphics.GLGraphics; import codeanticode.glgraphics.GLGraphicsOffScreen; import codeanticode.glgraphics.GLTexture; import codeanticode.glgraphics.GLTextureFilter; /** * Generates bubbles based on sound. Requires GLGraphics render mode. * * @author christopher */ public class Bubbles extends VisualizerAbstract { private static final long serialVersionUID = 4343458995928287150L; private Generator _generator; private GLGraphicsOffScreen _active, _done; private GLTexture _history, _age, _temp, _temp2; private GLTextureFilter _blur, _blend, _ageUpdate, _bloom; private final Random _random; private final LinkedList<Bubble> _bubbles, _finished; private boolean _useBloom; private final LinkedList<Integer> _spawnHistory; private int _spawnSum, _spawnHistorySize, _width, _height; private float _spawnRateMin, _spawnRateMax, _rMin, _rMax, _darkenFactor, _spawnAvg; /** * Ctor. */ public Bubbles() { _spawnAvg = 1; _spawnHistorySize = 130; _spawnHistory = new LinkedList<Integer>(); _random = new Random(); _bubbles = new LinkedList<Bubble>(); _finished = new LinkedList<Bubble>(); _generator = new Intensity(); useBloom(true); setDarkenFactor(13); setBubbleSize(0.02f, 0.06f); setSpawnRate(0.3f, 1.6f); setColor(new float[] { 0, 0.33f, 0.66f, 1 }, new int[] { 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000, 0xFFFF00FF }, PApplet.RGB); } /** * Sets the darken factor. This factor will influence how fast drawn bubbles will disappear. * * Fitting values are based on many variables, mainly on the spawn rate (see setSpawnRateTargets()). * Default is 12. * * @param factor The darken factor. Must be positive */ public void setDarkenFactor(float factor) { _darkenFactor = factor; } /** * Sets the minimum and maximum size of the bubbles. * The values are relative, f.i. 0.2 means 0.2 times display area width. * * @param min The minimum bubble size. Must be positive * @param max The maximum bubble size. Must be > min */ public void setBubbleSize(float min, float max) { _rMin = min; _rMax = max; } /** * Whether to use a bloom postprocessing filter. * * @param bloom Whether to use bloom postprocessing */ public void useBloom(boolean bloom) { _useBloom = bloom; } /** * Sets the spawn rate. The visualization will try to spawn * at least min bubbles and at the most max bubbles per call to process(). * * @param min The min number of bubbles to spawn. Must be > 0 * @param max The max number of bubbles to spawn. Must be > min */ public void setSpawnRate(float min, float max) { _spawnRateMin = min; _spawnRateMax = max; } @Override public void drawTo(PApplet applet) throws PAVException { if(! (applet.g instanceof GLGraphics)) { throw new PAVException("Bubbles visualizer requires GLGraphics renderer."); } super.drawTo(applet); dispose(); _done = null; _active = null; _blur = ShaderManager.getTextureFilter("BubblesBlur"); _blend = ShaderManager.getTextureFilter("BubblesBlend"); _blend.setParameterValue("EmphBase", 0.1f); _blend.setParameterValue("EmphBlend", 0.15f); _ageUpdate = ShaderManager.getTextureFilter("AgeUpdate"); _ageUpdate.setParameterValue("Add", 0.05f); _bloom = ShaderManager.getTextureFilter("BubblesBloom"); _bloom.setParameterValue("T1", 1.5f); _bloom.setParameterValue("T2", 2.5f); _bloom.setParameterValue("Intensity", 0.6f); _bloom.setParameterValue("LumaCoeffs", new float[] { 0.5f, 0.5f, 0.5f, 1f }); } @Override public void process() throws PAVException { float[] area = getArea(); int width = (int) (area[2] - area[0]); int height = (int) (area[3] - area[1]); if(_active == null || _done == null || _width != width || _height != height) { _width = width; _height = height; _init(); } int num = _generator.generate(); _spawnHistory.add(num); _spawnSum += num; if(_spawnHistory.size() > _spawnHistorySize) { _spawnSum -= _spawnHistory.removeFirst(); } _spawnAvg = _spawnSum / (float) _spawnHistory.size(); _active.beginDraw(); _active.clear(0, 0); _active.endDraw(); _finished.clear(); for(Bubble b : _bubbles) { if(b.draw()) { _finished.add(b); } } for(Bubble b : _finished) { _bubbles.remove(b); } _ageUpdate.apply(new GLTexture[] { _age, _done.getTexture() }, _age); if(! _finished.isEmpty()) { GLTexture d = _done.getTexture(); _blend.apply(new GLTexture[] { _history, d }, _history); _done.beginDraw(); _done.clear(0, 0); _done.endDraw(); } _blur.setParameterValue("DarkenFactor", PApplet.map(_spawnAvg, 0, _darkenFactor, 0, 0.025f) + 0.0002f); _blur.apply(new GLTexture[] { _history, _age }, _history); GLTexture a = _active.getTexture(); _blend.apply(new GLTexture[] { _history, a }, _temp); if(_useBloom) { _temp2.clear(0, 0); _temp.filter(_bloom, _temp2); p.image(_temp2, area[0], area[1]); } else { p.image(_temp, area[0], area[1]); } } @Override public String toString() { return "Bubbles"; } private float _cx() { float f = (float) _random.nextGaussian(); return PApplet.map(f, -1.25f, 1.25f, 0, _width); } private float _cy() { float f = (float) _random.nextGaussian(); return PApplet.map(f, -1.8f, 1.8f, 0, _height); } private void _init() throws PAVException { if(! (p.g instanceof GLGraphics)) { throw new PAVException("Bubbles visualizer requires GLGraphics renderer."); } if(_active != null) _active.dispose(); if(_done != null) _done.dispose(); _active = new GLGraphicsOffScreen(p, _width, _height); _active.beginDraw(); _active.ellipseMode(PApplet.RADIUS); _active.endDraw(); _done = new GLGraphicsOffScreen(p, _width, _height); _done.beginDraw(); _done.ellipseMode(PApplet.RADIUS); _done.endDraw(); _history = new GLTexture(p, _width, _height); _history.clear(0, 0); _age = new GLTexture(p, _width, _height); _age.clear(0); _temp = new GLTexture(p, _width, _height); _temp.clear(0, 0); _temp2 = new GLTexture(p, _width, _height); _temp2.clear(0, 0); cm.setRange(0, _width); } /** * A bubble generator. * * @author christopher */ private abstract class Generator { /** * Generates bubbles. * * @return The number of generated bubbles */ public abstract int generate(); } /** * Generates bubbles based on the intensity of the playing sound. * * @author christopher */ private class Intensity extends Generator { private int _seq; private float _align; private final int[] _lutMin, _lutMax; private float _rmsMin, _rmsMax, _srtMin, _srtMax; /** * Ctor. */ public Intensity() { _lutMin = new int[10]; _lutMax = new int[10]; _rmsMin = Float.MAX_VALUE; _rmsMax = Float.MIN_VALUE; setAlignmentFactor(0.0002f); } /** * Sets the alignment factor. Must be a small value, default is 0.0002. * * @param align The alignment factor. Must be > 0 */ public void setAlignmentFactor(float align) { _align = align; } @Override public int generate() { if(_srtMin != _spawnRateMin || _srtMax != _spawnRateMax) { _updateLuts(); } float rms = Frame.Descriptor.rms(); if(rms < 0.001) return 0; if(rms < _rmsMin) _rmsMin = rms; _rmsMin += _align; if(rms > _rmsMax) _rmsMax = rms; else _rmsMax -= _align;; int idx = _seq % 10; float t = PApplet.constrain(PApplet.map(rms, _rmsMin, _rmsMax, 0, 1), 0, 1); float spawn = PApplet.map(t, 0, 1, _lutMin[idx], _lutMax[idx]); int num = (int) spawn; float rem = spawn - num; if(_random.nextFloat() < rem) num++; float rt = 1; if(rms < 0.1f) rt = PApplet.map(rms, 0, 0.1f, 0.25f, 1f); for(int i = 0; i < num; i++) { float r = PApplet.map(t * rt, 0, 1, _width * _rMin, _width * _rMax); float x = _cx(); float y = _cy(); float co = ((float) _random.nextGaussian()) * _width / 8f; int c = cm.map(x + co); int cr = c >> 16 & 0xFF; int cg = c >> 8 & 0xFF; int cb = c & 0xFF; int ca = (int) PApplet.map(t, 0, 1, 100, 175); _bubbles.add(new Bubble(x, y, r, ca, cr, cg, cb, t + 0.75f, 6)); } _seq++; return num; } private void _updateLuts() { _srtMin = _spawnRateMin; _srtMax = _spawnRateMax; int numMin = Math.round(_srtMin * 10); int numMax = Math.round(_srtMax * 10); _lutFill(_lutMin, numMin); _lutFill(_lutMax, numMax); } private void _lutFill(int[] lut, int num) { int min = num / 10; int rem = num - min * 10; Arrays.fill(lut, min); if(rem == 0) { return; } int step = 10 / rem; int p = 0; while(p < rem) { lut[p * step] += 1; p++; } } } /** * A spawning bubble. * * @author christopher */ private class Bubble { private int _st; private final float _cx, _cy, _r, _sw; private final int _c, _ca, _cr, _cg, _cb, _sd; /** * Ctor. * * @param cx The center x coordinate of the bubble * @param cy The center y coordinate of the bubble * @param r The radius of the bubble * @param ca The alpha of the bubble color * @param cr The red part of the bubble color * @param cg The green part of the bubble color * @param sw The stroke weight of the bubble border * @param cb The blue part of the bubble color * @param sd The spawn duration in frames. Must be > 0 */ public Bubble(float cx, float cy, float r, int ca, int cr, int cg, int cb, float sw, int sd) { _cx = cx; _cy = cy; _r = r; _ca = ca; _cr = cr; _cg = cg; _cb = cb; _sw = sw; _sd = sd; _c = p.color(cr, cg, cb, ca); } /** * Draws the bubble and returns true if the spawn process has been completed. * If called called with an already completely spawned bubble, this method does nothing and returns true. * * @return Whether the bubble is spawned completely */ public boolean draw() { _st++; if(_st > _sd) { return true; } if(_st == _sd) { _done.beginDraw(); _done.fill(_c); _done.strokeWeight(_sw); _done.stroke(p.color(_cr, _cg, _cb, Math.min(_ca + 100, 255))); _done.ellipse(_cx, _cy, _r, _r); _done.endDraw(); return true; } else { float r = PApplet.map(_st, 1, _sd, _r / 1.25f, _r); float ca = PApplet.map(_st, 1, _sd, _ca + 75, Math.min(_ca + 100, 255)); _active.beginDraw();; _active.fill(_c); _active.strokeWeight(_sw); _active.stroke(p.color(_cr, _cg, _cb, ca)); _active.ellipse(_cx, _cy, r, r); _active.endDraw(); return false; } } } @Override public void dispose() { if(_active != null) _active.dispose(); if(_done != null) _active.dispose(); if(_history != null) _history.delete(); if(_age != null) _age.delete(); if(_temp != null) _temp.delete(); if(_temp2 != null) _temp2.delete(); } }
12,016
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Phasor.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Phasor.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.frame.Frame; import processing.core.PApplet; /** * Phasor draws the amplitude of the frame samples versus their rate of change (first derivate). * * @author christopher */ public class Phasor extends VisualizerAbstract { /** * Draw dots. */ public static final int MODE_DOTS = 1; /** * Draw a a shape (connect dots with lines). */ public static final int MODE_LINES = 2; /** * Draw a shape (connect dots with curves). * * This offers the best quality at the cost of speed. */ public static final int MODE_CURVES = 3; private static final long serialVersionUID = 4412875346457402076L; private int _mode; private float _strokeWeight; private transient float _vMin, _vMax, _dMin, _dMax; /** * Ctor. */ public Phasor() { _vMin = Float.MAX_VALUE; _vMax = Float.MIN_VALUE; _dMin = Float.MAX_VALUE; _dMax = Float.MIN_VALUE; setMode(MODE_CURVES); setStrokeWeight(1); setColor(0xFFFF0000, 0xFFFFFF00, PApplet.RGB); } @Override public void process() throws PAVException { p.strokeWeight(_strokeWeight); float[] frame = Frame.samples(); int len = frame.length; int len1 = len - 1; float[] frameDeriv = new float[len]; float dMin = Float.MAX_VALUE; float dMax = Float.MIN_VALUE; for(int i = 1; i < len1; i++) { float v = frame[i + 1] - frame[i - 1]; frameDeriv[i] = v; if(v > dMax) dMax = v; if(v < dMin) dMin = v; } float vMin = Float.MAX_VALUE; float vMax = Float.MIN_VALUE; for(int i = 0; i < len; i++) { float v = frame[i]; if(v > vMax) vMax = v; if(v < vMin) vMin = v; } if(dMax > _dMax) _dMax = dMax; if(vMax > _vMax) _vMax = vMax; if(dMin < _dMin) _dMin = dMin; if(vMin < _vMin) _vMin = vMin; float[] area = getArea(); float width2 = (area[2] - area[0]) / 2f; float height2 = (area[3] - area[1]) / 2f; cm.setRange(0, len - 1); if(_mode != MODE_DOTS) { p.noFill(); p.beginShape(); } for(int i = 1; i < len1; i++) { float x = frameDeriv[i]; float y = frame[i]; x = (x < 0) ? PApplet.map(x, _dMin, 0, - width2, 0) : PApplet.map(x, 0, _dMax, 0, width2); y = (y < 0) ? PApplet.map(y, _vMin, 0, height2, 0) : PApplet.map(y, 0, _vMax, 0, - height2); p.stroke(cm.map(i)); if(_mode == MODE_LINES) { p.curveVertex(area[0] + width2 + x, area[1] + height2 + y); } else if(_mode == MODE_CURVES) { p.curveVertex(area[0] + width2 + x, area[1] + height2 + y); } else { p.point(area[0] + width2 + x, area[1] + height2 + y); } } if(_mode != MODE_DOTS) { p.endShape(); } } /** * Sets the visualization mode. Must be a valid mode according * to the MODE_ constants of this class. * * @param mode The visualization mode */ public void setMode(int mode) { _mode = mode; } /** * Sets the stroke weight to use when drawing. * * @param weight The stroke weight. Must be > 0 */ public void setStrokeWeight(float weight) { _strokeWeight = weight; } @Override public String toString() { switch(_mode) { case MODE_DOTS : return "Phasor (dot mode)"; case MODE_LINES : return "Phasor (line mode)"; case MODE_CURVES : return "Phasor (curve mode)"; default : return "Phasor"; } } @Override public void dispose() { } }
4,127
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
VisualizerAbstract.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/VisualizerAbstract.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.ColorMapper; import pav.lib.PAVException; import processing.core.PApplet; /** * A audio visualizer. * * @author christopher */ public abstract class VisualizerAbstract implements Visualizer { private static final long serialVersionUID = 4237957722212363983L; /** * The PApplet to draw to. */ protected transient PApplet p; /** * The (primary) color mapper of this visualizer. */ protected final ColorMapper cm; private float _x1, _y1, _x2, _y2; private boolean _relative; /** * Ctor. */ public VisualizerAbstract() { cm = new ColorMapper(); setArea(0, 0, 1, 1, true); setColor(0xFFFFFFFF); } @Override public void setArea(float x1, float y1, float x2, float y2, boolean relative) { _x1 = x1; _y1 = y1; _x2 = x2; _y2 = y2; _relative = relative; } @Override public void setColor(int color) { cm.setColor(color); } @Override public void setColor(int a, int b, int mode) { cm.setColor(a, b, mode); } @Override public void setColor(float[] thresholds, int[] colors, int mode) { cm.setColor(thresholds, colors, mode); } @Override public void drawTo(PApplet applet) throws PAVException { p = applet; } /** * Returns the area this visualizer may use. The area is specified by * and array containing 4 values: * * [0] - Low x-coordinate * [1] - Low y-coordinate * [2] - High x-coordinate * [3] - High y-coordinate * * If the area is specified relative (see setArea()) but no PApplet * object is available, all values will be 0. * * @return The erea */ protected float[] getArea() { float x1 = 0, y1 = 0, x2 = 0, y2 = 0; if(_relative) { if(p != null) { x1 = _x1 * p.width; y1 = _y1 * p.height; x2 = _x2 * p.width; y2 = _y2 * p.height; } } else { x1 = _x1; y1 = _y1; x2 = _x2; y2 = _y2; } return new float[] { x1, y1, x2, y2 }; } }
2,694
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Rainbow.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Rainbow.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.StreamingBuffer; import pav.lib.frame.Frame; import processing.core.PApplet; /** * Draws colored stripes based on the frequency or the intenstiy of the playing music. * In frequency mode (MODE_FREQUENCY) the colors are chosen based on the frequency distribution * of the sound (spectral centroid). In intensity mode (MODE_INTENSITY) the colors are based * on the sound intensity (rms). * * @author christopher */ public class Rainbow extends VisualizerAbstract { /** * Choose colors based on the frequency distribution. */ public static final int MODE_FREQUENCY = 1; /** * Choose colors based on the sound intensity. */ public static final int MODE_INTENSITY = 2; private static final long serialVersionUID = 3758005144794379244L; private transient StreamingBuffer _buffer; private int _mode; private boolean _auto; private float _vMin, _vMax; /** * Ctor. */ public Rainbow() { float[] thresholds = { 0, 0.143f, 0.286f, 0.429f, 0.572f, 0.702f, 0.845f, 1 }; int[] colors = { 0xFF000000, 0xFFFF0000, 0xFFFFFF00, 0xFF00FF00, 0xFF00FFFF, 0xFF0000FF, 0xFF8800FF, 0xFFAA00FF }; setMode(MODE_FREQUENCY); cm.setColor(thresholds, colors, PApplet.RGB); } @Override public void process() throws PAVException { float v = 0; if(_mode == MODE_FREQUENCY) { v = Frame.Descriptor.spectralCentroid(); } else if(_mode == MODE_INTENSITY) { v = Frame.Descriptor.rms(); } float[] area = getArea(); int width = (int) (area[2] - area[0]); int height = (int) (area[3] - area[1]); if(_buffer == null || width != _buffer.getWidth()) { if(_buffer != null) { _buffer.dispose(); } _buffer = new StreamingBuffer(p, width, 1); } if(_auto) { if(v < _vMin) { _vMin = v; cm.setRange(_vMin, _vMax); } if(v > _vMax) { _vMax = v; cm.setRange(_vMin, _vMax); } } else { if(v < _vMin) v = _vMin; if(v > _vMax) v = _vMax; } int c = cm.map(v); _buffer.add(new int[] { c }); _buffer.draw((int) area[0], (int) area[1], width, height); } /** * Sets the range to map colors to. For instance, if set to 500, 5000 (the default) the color * mapping will be done based on values between these values, any values lower than 500 will * be mapped to 500, and higher than 5000 to 5000. In intensity mode values are between 0 and 1. * * @param min The min value to use for color mapping. Must be >= 0 * @param max The max value to use for color mapping. Must be > min */ public void setRange(float min, float max) { _vMin = min; _vMax = max; _auto = false; cm.setRange(min, max); } /** * Tells the visualizer not to use a static range (see setRange()), * but to calculate the range automatically. */ public void setAutoRange() { _auto = true; _vMin = 0; _vMax = 0; } /** * Sets the color mode. Must be a valid mode according * to the MODE_ constants of this class. This will automatically set the range * to values that make sense for the chosen mode (see setRange()). * * @param mode The mode to use. Must be valid (see MODE_ constants) */ public void setMode(int mode) { _mode = mode; if(_mode == MODE_FREQUENCY) { setRange(500, 5000); } else if(_mode == MODE_INTENSITY) { setAutoRange(); } } @Override public String toString() { switch(_mode) { case MODE_FREQUENCY : return "Rainbow (frequency mode)"; case MODE_INTENSITY : return "Rainbow (intensity mode)"; default : return "Rainbow"; } } @Override public void dispose() { if(_buffer != null) _buffer.dispose(); } }
4,426
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
MelSpectrum.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/MelSpectrum.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.Util; import pav.lib.frame.Frame; import pav.lib.frame.TransformResult; import processing.core.PApplet; /** * Draws a MEL spectrum of the currently playing audio data. * * @author christopher */ public class MelSpectrum extends VisualizerAbstract { private static final long serialVersionUID = 5375994108922066833L; private transient float _vMax; private int _borderColor, _numBands, _quantizationSteps; private float[] _filter; private boolean _rememberMax; /** * Ctor. */ public MelSpectrum() { rememberMax(true); setNumBands(40); setColor(new float[] { 0, 0.2f, 0.6f, 1 }, new int[] { 0xFF0000FF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 }, PApplet.RGB); } @Override public void process() throws PAVException { TransformResult spectrum = Frame.Transform.melSpectrum(_numBands); float[] freq = spectrum.frame(); float vMax = spectrum.max(); if(_filter != null) { int len = _filter.length; freq = (float[]) freq.clone(); // changes to TransformResults are not allowed for(int i = 0; i < len; i++) { freq[i] = freq[i] * _filter[i]; if(freq[i] > vMax) { vMax = freq[i]; } } } if(! _rememberMax) { _vMax = 0; } boolean quantize = _quantizationSteps > 0; if(vMax > _vMax) { _vMax = vMax; if(quantize) { cm.setRange(1, _quantizationSteps); } else { cm.setRange(0, _vMax); } } if(_quantizationSteps > 0) { freq = Util.quantize(freq, _quantizationSteps, 0, _vMax); } int len = freq.length; float[] area = getArea(); float tn = (area[2] - area[0]) / len; float min = (quantize) ? 1 : 0; float max = (quantize) ? _quantizationSteps : _vMax; for(int i = 0; i < len; i++) { float v = freq[i]; float y = PApplet.map(v, min, max, area[3], area[1]); float x = PApplet.map(i, 0, len - 1, area[0], area[2] - tn); p.stroke(_borderColor); p.fill(cm.map(v)); p.rect(x, y, tn, area[3] - y); } } /** * Sets the number of mel bands to compute. Must be > 0. * * @param num The number of mel bands */ public void setNumBands(int num) { _numBands = num; _vMax = 0; } /** * Sets the color to use when drawing the borders of the frequency bands. * * @param color The color to use when drawing */ public void setBorderColor(int color) { _borderColor = color; } /** * Sets the number of steps to use for quantization of the spectrum values or disables quantization. * * @param steps The number of quantization steps. Set to <= 0 to disable quantization */ public void quantize(int steps) { _quantizationSteps = (steps < 0) ? 0 : steps; _vMax = 0; } /** * Filters the calculated spectrum intensities before displaying them. * The process is simply carried out by multiplying the i-th spectrum intensity * with the i-th value in the filter. Thus, the filter length must not be longer * than the number of calculated bands, but it can be lower. * * @param filter The filter to use or null to disable filtering. Filter length must not be larger than numBands. */ public void filter(float[] filter) { _filter = filter; _vMax = 0; } /** * Before drawing the maximum intensity of the spectrum data is calculated so that the output * can be scaled properly. This method sets whether the maximum will be saved and reused. * * @param remember Whether or not to remember the max intensity */ public void rememberMax(boolean remember) { _rememberMax = remember; } @Override public String toString() { return "MelSpectrum (" + _numBands + ")"; } @Override public void dispose() { } }
4,452
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Wavering.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Wavering.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import pav.lib.PAVException; import pav.lib.ShaderManager; import pav.lib.frame.Frame; import processing.core.PApplet; import processing.core.PGraphics; import codeanticode.glgraphics.GLGraphics; import codeanticode.glgraphics.GLGraphicsOffScreen; import codeanticode.glgraphics.GLTexture; import codeanticode.glgraphics.GLTextureFilter; /** * Creates a bright ring based on the waveform of the audio signal. * * @author christopher */ public class Wavering extends VisualizerAbstract { private static final long serialVersionUID = 7540082043727857258L; private float _strokeWeight; private boolean _colorAbsolute; private float _rx, _ry, _dx, _dy; private WaveringImpl _implementation; private int _interpolate, _width, _height; /** * Ctor. */ public Wavering() { autosize(); interpolate(200); setStrokeWeight(2); colorAbsolute(true); setColor(0xFF0077AA, 0xFFFFAA00, PApplet.RGB); } @Override public void drawTo(PApplet applet) throws PAVException { super.drawTo(applet); _implementation = (p.g instanceof GLGraphics) ? new Fancy() : new Simple(); } @Override public void process() throws PAVException { _implementation.process(); } @Override public String toString() { return "Wavering"; } @Override public void dispose() { } /** * The number of samples to use when interpolating between start and end value of the frame. * * @param num Number of interpolated samples. Must be >= 0 */ public void interpolate(int num) { _interpolate = num / 2; } /** * Sets the relative base radius of the wavering. * * @param rx Radius in x direction * @param ry Radius in y direction */ public void setRadius(float rx, float ry) { _rx = rx; _ry = ry; } /** * Sets the realtive maximum displacement of the ring coordinates. * * @param dx Maximum displacement in x direction * @param dy Maximum displacement in y direction */ public void setDisplacement(float dx, float dy) { _dx = dx; _dy = dy; } /** * Automatically sets the radius and displacement based on the available display area. */ public void autosize() { setRadius(0.6f, 0.6f); setDisplacement(0.4f, 0.4f); } /** * Sets the stroke weight to use when drawing. * * @param weight The stroke weight. Must be > 0 */ public void setStrokeWeight(float weight) { _strokeWeight = weight; } /** * Whether to use the absolute values for coloring, i.e. whether -1 gets the same color as 1 or not. * * @param absolute Whether to use absolute coloring */ public void colorAbsolute(boolean absolute) { if(absolute) { _colorAbsolute = true; cm.setRange(0, 1); } else { _colorAbsolute = false; cm.setRange(-1, 1); } } /** * Returns the implementation used by this wavering. * * @return The implementation */ public WaveringImpl getImplementation() { return _implementation; } private void _drawRing(PGraphics target) { target.beginDraw(); target.noFill(); target.beginShape(); target.strokeWeight(_strokeWeight); float[] frame = Frame.samples(); float[] area = getArea(); int len = frame.length; int len1 = len - 1; float ox = (area[2] - area[0]) / 2; float oy = (area[3] - area[1]) / 2; float as = -(PApplet.PI * 1.5f); float ae = as + PApplet.TWO_PI; int j = (- len) + _interpolate; float diff = 0, ddiff = 0; if(_interpolate > 0) { diff = (frame[len - 1] - frame[0]) / 2; ddiff = diff / _interpolate; } float rx = _rx * ox; float ry = _ry * oy; float dx = _dx * ox; float dy = _dy * oy; for(int i = 0; i < len; i++, j++) { float v = frame[i]; if(_interpolate > 0) { if(i < _interpolate) v += diff - i * ddiff; else if(j >= 0) v -= j * ddiff; } float angle = PApplet.map(i, 0, len1, as, ae); float x = ox + (rx + v * dx) * PApplet.cos(angle); float y = oy + (ry + v * dy) * PApplet.sin(angle); if(_colorAbsolute && v < 0) target.stroke(cm.map(v * -1)); else target.stroke(cm.map(v)); target.vertex(x, y); } target.endShape(PApplet.CLOSE); target.endDraw(); } /** * Wavering implementation. * * @author christopher */ public abstract class WaveringImpl { /** * Draws the implementation. * * @throws PAVException On errors */ public abstract void process() throws PAVException; /** * Disposes the imlementation. */ public abstract void dispose(); } /** * Simple implementation with software renderer support. * * @author christopher */ public class Simple extends WaveringImpl { @Override public void process() throws PAVException { _drawRing(p.g); } @Override public void dispose() { } } /** * Fancy implementation, requires GLGraphics renderer. * * @author christopher */ public class Fancy extends WaveringImpl { private GLTexture _history, _bloomMap, _bloomMask, _bloom0, _bloom2, _bloom4, _bloom8, _bloom16, _out; private GLTextureFilter _fblur, _fcolorize, _freplace, _fblend4, _fextractBloom, _ftoneMap; private GLGraphicsOffScreen _off; /** * Ctor. */ public Fancy() throws PAVException { _fblur = ShaderManager.getTextureFilter("Blur"); _fcolorize = ShaderManager.getTextureFilter("Colorize"); _freplace = ShaderManager.getTextureFilter("Replace"); _fblend4 = ShaderManager.getTextureFilter("Blend4"); _fextractBloom = ShaderManager.getTextureFilter("ExtractBloom"); _ftoneMap = ShaderManager.getTextureFilter("ToneMap"); setRingColor(0xFFFFFFFF); setDarkenFactor(0.015f); setBrightnessThreshold(0.3f); setBloomIntensity(0.5f); setTonemapExposure(1.6f); setTonemapMaxBrightness(0.9f); } /** * Sets the color to use when drawing the ring. * * @param color The ring color */ public void setRingColor(int color) { float r = p.red(color) / 255f; float g = p.green(color) / 255f; float b = p.green(color) / 255f; float a = p.alpha(color) / 255f; _fcolorize.setParameterValue("Color", new float[] { r, g, b, a }); } /** * Sets how fast old data disappears. Must be a small value (default is 0.005). * * @param factor The darken factor */ public void setDarkenFactor(float factor) { _fblur.setParameterValue("DarkenFactor", factor); } /** * Sets the brightness threshold to use when calculating the bloom map. * * @param threshold The brightness threshold. Must be between 0 and 1 */ public void setBrightnessThreshold(float threshold) { _fextractBloom.setParameterValue("bright_threshold", threshold); } /** * Sets the intensity of the bloom effect. * * @param intensity The bloom intensity. Must be >= 0 */ public void setBloomIntensity(float intensity) { _ftoneMap.setParameterValue("bloom", intensity); } /** * Sets the exposure to use for tone mapping. * * @param exposure The exposure. Must be > 0 */ public void setTonemapExposure(float exposure) { _ftoneMap.setParameterValue("exposure", exposure); } /** * Sets the maximum brightness to use for tone mapping. * * @param brightness The max brightness. Must be > 0 */ public void setTonemapMaxBrightness(float brightness) { _ftoneMap.setParameterValue("bright", brightness); } @Override public void process() throws PAVException { float[] area = getArea(); int width = (int) (area[2] - area[0]); int height = (int) (area[3] - area[1]); if(_off == null || _width != width || _height != height) { _width = width; _height = height; dispose(); _init(); } _off.beginDraw(); _off.clear(0); _off.endDraw(); _drawRing(_off); _fblur.apply(_history, _history); _fcolorize.apply(_off.getTexture(), _bloomMap); _freplace.apply(new GLTexture[] { _history, _off.getTexture() }, _history); _freplace.apply(new GLTexture[] { _history, _bloomMap }, _out); _fextractBloom.apply(_out, _bloom0); _bloom0.filter(_fblur, _bloom2); _bloom2.filter(_fblur, _bloom4); _bloom4.filter(_fblur, _bloom8); _bloom8.filter(_fblur, _bloom16); _fblend4.apply(new GLTexture[] { _bloom2, _bloom4, _bloom8, _bloom16}, new GLTexture[] { _bloomMask }); _ftoneMap.apply(new GLTexture[] { _out, _bloomMask }, new GLTexture[] { _out }); p.image(_out, area[0], area[1]); } @Override public void dispose() { if(_history != null) _history.delete(); if(_bloomMap != null) _bloomMap.delete(); if(_bloomMask != null) _bloomMask.delete(); if(_bloom0 != null) _bloom0.delete(); if(_bloom2 != null) _bloom2.delete(); if(_bloom4 != null) _bloom4.delete(); if(_bloom8 != null) _bloom8.delete(); if(_bloom16 != null) _bloom16.delete(); if(_out != null) _out.delete(); if(_off != null) _off.dispose(); } private void _init() { float[] area = getArea(); _width = (int) (area[2] - area[0]); _height = (int) (area[3] - area[1]); _history = new GLTexture(p, _width, _height); _bloomMap = new GLTexture(p, _width, _height); _bloomMask = new GLTexture(p, _width, _height); _bloom0 = new GLTexture(p, _width, _height); _bloom2 = new GLTexture(p, _width / 2, _height / 2); _bloom4 = new GLTexture(p, _width / 4, _height / 4); _bloom8 = new GLTexture(p, _width / 8, _height / 8); _bloom16 = new GLTexture(p, _width / 16, _height / 16); _out = new GLTexture(p, _width, _height); _off = new GLGraphicsOffScreen(p, _width, _height); } } }
10,340
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Boxes.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/visualizer/Boxes.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.visualizer; import java.io.Serializable; import pav.lib.PAVException; import pav.lib.Util; import pav.lib.frame.Frame; import pav.lib.frame.TransformResult; import processing.core.PApplet; import codeanticode.glgraphics.GLGraphics; import codeanticode.glgraphics.GLGraphicsOffScreen; /** * Draws a 3D grid of boxes with sizes linked to intensities of frequency bands. * * As of the current version this visualizer only works with the GLGraphics renderer. * * @author christopher */ public class Boxes extends VisualizerAbstract { private static final long serialVersionUID = -2867609623075114719L; /** * Use continuous color interpolation. Every box will have a different color. */ public static final int COLOR_INTERPOLATION_CONTINUOUS = 1; /** * Interpolate colors according to rows. Every row will have a different color. */ public static final int COLOR_INTERPOLATION_ROW = 2; /** * Use linear linking between boxes and frequency ranges. Boxes linked to low * frequencies will be positioned at the far distance with default camera settings. */ public static final int LINK_LINEAR = 1; private final Box[] _boxes; private final int _numRows, _numCols; private final float _gridSizeZ; private final int[] _intensityMap, _colorMap; private float[] _filter; private int _maxHeight, _edgeColor, _quantizationSteps ; private float _rotateAngle, _rotateSpeed; private transient float _vMax; private transient float[] _intensities; private transient GLGraphicsOffScreen _buffer; /** * Ctor. */ public Boxes() { this(64, 30, 3); } /** * Ctor. * * @param num The number of boxes to create. Must be > 0 * @param size The length of the box edges. Must be > 0 * @param spacing The spacing between boxes */ public Boxes(int num, int size, int spacing) { this(num, size, spacing, (int) Math.sqrt(num)); } /** * Ctor. * * @param num The number of boxes to create. Must be > 0 * @param size The length of the box edges. Must be > 0 * @param spacing The spacing between boxes * @param rows The number of box rows to create. Must be > 0 */ public Boxes(int num, int size, int spacing, int rows) { super(); _boxes = new Box[num]; _intensities = new float[num]; _colorMap = new int[num]; _intensityMap = new int[num]; int i = 0; int dx = size + spacing; int dz = size + spacing; _numRows = rows; _numCols = (int) Math.ceil(num / (float) rows); _gridSizeZ = _numCols * size + (_numCols - 1) * spacing; float offsetX = ((_numRows - 1) * size + (_numRows - 1) * spacing) / 2f; float offsetZ = ((_numCols - 1) * size + (_numCols - 1) * spacing) / 2f; for(int x = 0; x < _numRows; x++) { int numMissing = (x == _numRows - 1) ? _numRows * _numCols - num : 0; for(int z = 0; z < _numCols; z++) { if(i == num) { break; } float offsetMissing = (x % 2 == 0) ? dz * numMissing : 0; _boxes[i] = new Box(i, x * dx - offsetX, 0, z * dz - offsetZ + offsetMissing, size, size); i++; } } setMaxHeight(125); setLinkMode(LINK_LINEAR); setEdgeColor(0xFFCCCCCC); setColor(new float[] { 0, 0.2f, 0.6f, 1 }, new int[] { 0xFF0000FF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 }, PApplet.RGB); } /** * Sets the camera to use. See PApplet.camera() for more infos. * * Note that the camera is reset every time the display size changes, therefore * calls to this method before the visualization is drawn for the first time have no effect. * * @param eyeX The eye x position * @param eyeY The eye y position * @param eyeZ The eye z position * @param centerX The center x position * @param centerY The center y position * @param centerZ The center z position * @param upX The up x position * @param upY The up y position * @param upZ The up z position */ public void setCamera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if(_buffer == null) { return; } _buffer.beginDraw(); _buffer.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); _buffer.endDraw(); } /** * Resets the camera position. * * The eyeX position is set to the width of the grid. eyeY is set to h/-5 where h is the * display height. All other position are set to 0 (see setCamera()), with upY being 1. * These settings are fitting only if the grid is nearly rectangular (which it is by default). */ public void resetCamera() { if(_buffer == null) { return; } setCamera(_gridSizeZ, _buffer.height / -5, 0, 0, 0, 0, 0, 1, 0); } /** * Starts or stops rotating. The speed is set via speed, which is a value in radians * that specifies how the angle will change every time process() is called. A fitting value * is Pi/360. If speed is set to 0 the rotation stops. * * @param speed The rotation speed */ public void rotate(float speed) { _rotateSpeed = speed; } /** * Sets the fill color of the boxes. * * @param color The color to use */ @Override public void setColor(int color) { setColor(new float[] { 0, 1 }, new int[] { color, color }, PApplet.RGB, COLOR_INTERPOLATION_CONTINUOUS); } /** * Sets the fill color of the boxes using continuous interpolation mode. * * @param a The color to start from * @param b The color to interpolate to * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB */ @Override public void setColor(int a, int b, int mode) { setColor(a, b, mode, COLOR_INTERPOLATION_CONTINUOUS); } /** * Sets the fill color of the boxes. * * @param a The color to start from * @param b The color to interpolate to * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB * @param interpolation The interpolation used. See COLOR_INTERPOLATION constants of this class. Must be valid */ public void setColor(int a, int b, int mode, int interpolation) { setColor(new float[] { 0, 1 }, new int[] { a, b }, mode, interpolation); } /** * Sets the fill color of the boxes. * * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors * @param colors The The colors to use. Must be of same length as thresholds * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB */ @Override public void setColor(float[] thresholds, int[] colors, int mode) { setColor(thresholds, colors, mode, COLOR_INTERPOLATION_CONTINUOUS); } /** * Sets the fill color of the boxes. * * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors * @param colors The The colors to use. Must be of same length as thresholds * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB * @param interpolation The interpolation used. See COLOR_INTERPOLATION constants of this class. Must be valid */ public void setColor(float[] thresholds, int[] colors, int mode, int interpolation) { if(_colorMap == null) { return; // can occur only on initialization } int numColors = _colorMap.length; super.setColor(thresholds, colors, mode); switch(interpolation) { case COLOR_INTERPOLATION_CONTINUOUS : cm.setRange(0, numColors - 1); for(int i = 0; i < _numRows; i++) { int offset = (i == _numRows - 1) ? _numRows * _numCols - _boxes.length : 0; for(int j = 0; j < _numCols - offset; j++) { int index = _numCols * i + j; if(i % 2 == 0) { if(j <= _numCols / 2) { int swap = _numCols * i + _numCols - j - offset - 1; _colorMap[index] = cm.map(swap); _colorMap[swap] = cm.map(index); } } else { _colorMap[index] = cm.map(index); } } } break; case COLOR_INTERPOLATION_ROW : cm.setRange(0, _numCols - 1); for(int i = 0; i < numColors; i++) { _colorMap[i] = cm.map(i / _numRows); } break; } } /** * Sets the color of the box edges. * * @param color Box edge color */ public void setEdgeColor(int color) { _edgeColor = color; } /** * Sets the maximum height of the boxes. * * @param height The maximum box height */ public void setMaxHeight(int height) { _maxHeight = height; } /** * Sets the number of steps to use for quantization of the spectrum values or disables quantization. * * @param steps The number of quantization steps. Set to <= 0 to disable quantization */ public void quantize(int steps) { _quantizationSteps = (steps < 0) ? 0 : steps; _vMax = 0; } /** * Filters the calculated spectrum intensities before displaying them. * The process is simply carried out by multiplying the i-th spectrum intensity * with the i-th value in the filter. Thus, the filter length must not be longer * than the number of calculated bands (that is the number of boxes), but it can be lower. * The link mode (see setLinkMode()) determines what box will be modified by what filter value. * * @param filter The filter to use or null to disable filtering. Filter length must not be larger than the number of boxes */ public void filter(float[] filter) { _filter = filter; } /** * Sets the link mode. See LINK_ constants of this class. * * Currently only linear linking mode is supported. * * @param mode The link mode to use. Must be valid */ public void setLinkMode(int mode) { switch(mode) { case LINK_LINEAR : for(int i = 0; i < _numRows; i++) { int offset = (i == _numRows - 1) ? _numRows * _numCols - _boxes.length : 0; for(int j = 0; j < _numCols - offset; j++) { int index = _numCols * i + j; if(i % 2 == 0) { if(j <= _numCols / 2) { int swap = _numCols * i + _numCols - j - offset - 1; _intensityMap[index] = swap; _intensityMap[swap] = index; } } else { _intensityMap[index] = index; } } } break; } } @Override public void process() throws PAVException { float[] area = getArea(); int width = (int) (area[2] - area[0]); int height = (int) (area[3] - area[1]); if(_buffer == null || _buffer.width != width || _buffer.height != height) { if(_buffer != null) { _buffer.dispose(); } _buffer = new GLGraphicsOffScreen(p, width, height, true); resetCamera(); } if(_rotateSpeed != 0) { _rotateAngle += _rotateSpeed; setCamera(PApplet.cos(_rotateAngle) * _gridSizeZ, p.height / -5, PApplet.sin(_rotateAngle) * _gridSizeZ, 0, 0, 0, 0, 1, 0); } TransformResult spectrum = Frame.Transform.melSpectrum(_boxes.length); _intensities = spectrum.frame(); float vMax = spectrum.max(); if(_filter != null) { int len = _filter.length; _intensities = (float[]) _intensities.clone(); // changes to TransformResults are not allowed for(int i = 0; i < len; i++) { _intensities[i] = _intensities[i] * _filter[i]; if(_intensities[i] > vMax) { vMax = _intensities[i]; } } } if(vMax > _vMax) { _vMax = vMax; } if(_quantizationSteps > 0) { _intensities = Util.quantize(_intensities, _quantizationSteps, 0, _vMax); } _buffer.beginDraw(); _buffer.clear(0); _buffer.strokeWeight(1); _buffer.stroke(_edgeColor); for(Box b : _boxes) { b.draw(); } _buffer.endDraw(); p.image(_buffer.getTexture(), area[0], area[1]); } @Override public void drawTo(PApplet applet) throws PAVException { if(! (applet.g instanceof GLGraphics)) { throw new PAVException("Boxes visualizer requires GLGraphics renderer."); } super.drawTo(applet); } @Override public String toString() { return "Boxes (" + _numCols + "x" + _numRows + ")"; } /** * A box. * * @author christopher */ private class Box implements Serializable { private static final long serialVersionUID = 546482976109598332L; private float _x, _y, _z; private float _dx, _dz; private final int _id; /** * Ctor. * * @param id The id of this box. Must be unique, > -1 and < _boxes.length * @param x The x position * @param y The y position * @param z The z position * @param sx The x size * @param sz The z size */ public Box(int id, float x, float y, float z, float sx, float sz) { _id = id; size(sx, sz); translate(x, y, z); } /** * Sets the box size. * * @param x The x size * @param z The z size */ public void size(float x, float z) { _dx = x; _dz = z; } /** * Sets the position of the box. * * @param x The x position * @param y The y position * @param z The z position */ public void translate(float x, float y, float z) { _x = x; _y = y; _z = z; } /** * Draws the box. Buffer drawing must be enabled. */ public void draw() { float min = (_quantizationSteps > 0) ? 1 : 0; float max = (_quantizationSteps > 0) ? _quantizationSteps : _vMax; float height = PApplet.map(_intensities[_intensityMap[_id]], min, max, 1, _maxHeight); _buffer.fill(_colorMap[_id]); _buffer.pushMatrix(); _buffer.translate(_x, _y - height / 2, _z); _buffer.box(_dx, height, _dz); _buffer.popMatrix(); } } @Override public void dispose() { if(_buffer != null) _buffer.dispose(); } }
14,299
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
TransformResult.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/frame/TransformResult.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.frame; /** * A transformation result. The values must not be modified. * * @author christopher */ public class TransformResult { private final float[] _frame; private final float _min; private final float _max; /** * Ctor. * * @param frame The transformed frame * @param min The min of the frame values * @param max The max of the frame values */ public TransformResult(float[] frame, float min, float max) { _frame = frame; _min = min; _max = max; } /** * The transformed frame. Must not be modified. * * @return The result */ public float[] frame() { return _frame; } /** * The minimum of the frame values. * * @return The min value */ public float min() { return _min; } /** * The maximum of the frame values. * * @return The max value */ public float max() { return _max; } }
1,625
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
MelFilterBank.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/frame/MelFilterBank.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.frame; /** * A MEL filter bank. * * @author christopher */ public class MelFilterBank { private final int _minFrequency, _maxFrequency, _numFilters; private final float _minMel, _maxMel, _melDelta; private final MelFilter[] _filters; /** * Ctor. * * @param minFrequency The minimum frequency (in Hz) the bank should process. Must be >= 0 * @param maxFrequency The maximum frequency (in Hz) the bank should process. Must be > minFrequency * @param numFilters The number of filters to use. Must be > 0 */ public MelFilterBank(int minFrequency, int maxFrequency, int numFilters) { _minFrequency = minFrequency; _maxFrequency = maxFrequency; _numFilters = numFilters; _filters = new MelFilter[numFilters]; _minMel = freqToMel(_minFrequency); _maxMel = freqToMel(_maxFrequency); _melDelta = (_maxMel - _minMel) / (_numFilters + 1); float minMel = _minMel; float centerMel = _minMel + _melDelta; float maxMel = centerMel + _melDelta; for(int i = 0; i < numFilters; i++) { _filters[i] = new MelFilter(minMel, centerMel, maxMel); minMel += _melDelta; centerMel += _melDelta; maxMel += _melDelta; } } /** * Filters a given spectrum. * * @param spectrum The input spectrum. Must not be null * @param sampleRate The sample rate of the audio data. Must be > 0 * @return The filtered values */ public float[] filter(float[] spectrum, float sampleRate) { int l = spectrum.length; int fl = _filters.length; float fDelta = (sampleRate / 2) / l; float fDelta2 = fDelta / 2; float[] mel = new float[l]; float[] out = new float[fl]; for(int i = 0; i < l; i++) { mel[i] = freqToMel(i * fDelta + fDelta2); } for(int i = 0; i < fl; i++) { out[i] = _filters[i].filter(mel, spectrum); } return out; } /** * Calculates the Mel out of a frequency in Hz. * * @param freq The input frequency. Must be >= 0 * @return The Mel */ public static float freqToMel(float freq) { return (float) (1127 * Math.log(1 + freq / 700)); } /** * Calculates the frequency in Hz out of a given Mel. * * @param mel The mel. Must be > 0 * @return The frequency */ public static float melToFreq(float mel) { return (float) (700 * (Math.exp(mel / 1127) - 1)); } /** * A Mel filter. * * @author christopher */ private class MelFilter { private final float _melMin, _melCenter, _melMax, _vMax; /** * Ctor. * * @param melMin The min mel this filter should process. Must be >= 0 * @param melCenter The center mel this filter should process. Must be > melMin * @param melMax The max mel this filter should process. Must be > melCenter */ public MelFilter(float melMin, float melCenter, float melMax) { _melMin = melMin; _melCenter = melCenter; _melMax = melMax; _vMax = 2 / (melToFreq(melMax) - melToFreq(melMin)); } /** * Processes a number of given mel frequencies. * * @param mels A number of mel frequencies. Must not be null * @param intensities The intensities of the mel frequencies. Must not be null and of same length as mels * @return The accumulated intensity of this filter */ public float filter(float[] mels, float[] intensities) { float intensity = 0; int l = mels.length; for(int i = 0; i < l; i++) { float v = mels[i]; if(v < _melMin) continue; if(v > _melMax) break; float k = (v <= _melCenter) ? (_melCenter - v) / (_melCenter - _melMin) : 1 - ((v - _melCenter) / (_melMax - _melCenter)); intensity += intensities[i] * k * _vMax; } return intensity; } } }
4,411
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
Frame.java
/FileExtraction/Java_unseen/skpdvdd_PAV/libpav/src/pav/lib/frame/Frame.java
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib.frame; import java.util.HashMap; import processing.core.PApplet; import ddf.minim.analysis.FFT; /** * Provides access to the current signal frame aswell as * descriptors and transform functionality. This is a static class. * * @author christopher */ public class Frame { private static float _sampleRate; private static float[] _samples; private static float[] _samplesWindowed; /** * Updates the current frame. * * @param samples The samples that make up the new frame. Must not be null */ public static void update(float[] samples) { _samples = samples; _samplesWindowed = null; Descriptor._reset(); Transform._reset(); } /** * Sets the rate the frame was sampled with. * * @param rate The sample rate. Must be > 0 */ public static void setSampleRate(float rate) { _sampleRate = rate; } /** * Gets the sample rate the frame was sampled with. * * @return The sample rate */ public static float getSampleRate() { return _sampleRate; } /** * Gets the samples of the frame. Must not be modified. * * @return The samples */ public static float[] samples() { return _samples; } /** * Gets the samples of the frame, windowed with a Hamming window. * * @return The windowed samples */ public static float[] samplesWindowed() { if(_samplesWindowed != null) { return _samplesWindowed; } int len = _samples.length; int lenDec = len - 1; _samplesWindowed = new float[len]; for(int i = 0; i < len; i++) { _samplesWindowed[i] = _samples[i] * (0.54f - 0.46f * (float) Math.cos(PApplet.TWO_PI * i / lenDec)); } return _samplesWindowed; } /** * Frame descriptors. * * All descriptors are calculated based on the windows version of the current frame. * * @author christopher */ public static class Descriptor { private static Float _amplitudeMax; private static Float _rms; private static Integer _zeroCrossings; private static Float _zeroCrossingRate; private static Float _spectralCentroid; /** * Calculates the amplitude maximum, that is the maximum of the * absolutes of the values of the frame. Values range from 0 to 1. * * @return The amplitude maximum */ public static float amplitudeMax() { if(_amplitudeMax != null) { return _amplitudeMax; } float[] samples = samplesWindowed(); int l = samples.length; float max = Float.MIN_VALUE; for(int i = 0; i < l; i++) { float v = Math.abs(samples[i]); if(v > max) { max = v; if(max == 1) { break; } } } _amplitudeMax = max; return _amplitudeMax; } /** * Calculates the root mean square (RMS). * * @return The RMS value */ public static float rms() { if(_rms != null) { return _rms; } float[] samples = samplesWindowed(); float v = 0; float l = samples.length; for(int i = 0; i < l; i++) { v += samples[i] * samples[i]; } v = v / l; _rms = (float) Math.sqrt(v); return _rms; } /** * Calculates the number of sign changes. * * @return The number of sign changes */ public static int zeroCrossings() { if(_zeroCrossings != null) { return _zeroCrossings; } int n = 0; int l = _samples.length; boolean p = (_samples[0] > 0); for(int i = 1; i < l; i++) { float v = _samples[i]; boolean c = v > 0; if(v == 0) { continue; } if(c != p) { n++; } p = c; } _zeroCrossings = n; return _zeroCrossings; } /** * Calculates the zero crossing rate (ZCR). * * @return The ZCR */ public static float zeroCrossingRate() { if(_zeroCrossingRate != null) { return _zeroCrossingRate; } _zeroCrossingRate = (zeroCrossings() * _sampleRate) / (2 * _samples.length); return _zeroCrossingRate; } /** * Calculates the spectral centroid. * * @return The spectral centroid */ public static float spectralCentroid() { if(_spectralCentroid != null) { return _spectralCentroid; } FFT fft = Transform._fft(); int l = fft.specSize(); float sum = 0, centroid = 0; for(int i = 0; i < l; i++) { centroid += fft.indexToFreq(i) * fft.getBand(i); sum += fft.getBand(i); } _spectralCentroid = (sum > 0) ? centroid / sum : 0; return _spectralCentroid; } /** * Resets all descriptors calculated. This must be called immediately after the * frame was updated. */ private static void _reset() { _amplitudeMax = null; _rms = null; _zeroCrossings = null; _zeroCrossingRate = null; _spectralCentroid = null; } } /** * Frame transforms. * * All transforms are based on the spectrum of the windowed version of the current frame. * * @author christopher */ public static class Transform { private static FFT _fft; private static float _fftSampleRate; private static boolean _fftForwarded; private static HashMap<String, MelFilterBank> _melFilterBanks; private static TransformResult _spectrum; private static HashMap<Integer, TransformResult> _melSpectrums; /** * Returns the logarithm of the frequency intensity distribution of the frame. * The result must not be modified. * * @return The transformed frame */ public static TransformResult spectrum() { if(_spectrum != null) { return _spectrum; } FFT fft = _fft(); int l = fft.specSize(); float min = Float.MAX_VALUE; float max = Float.MIN_VALUE; float[] transform = new float[l]; for(int i = 0; i < l; i++) { float v = (float) Math.log10(fft.getBand(i) + 1); if(v < min) min = v; if(v > max) max = v; transform[i] = v; } _spectrum = new TransformResult(transform, min, max); return _spectrum; } /** * Calculates the mel spectrum of the current frame. * The result must not be modified. * * @param numBands The number of mel scale bands to use. Must be > 0 * @return The transformed frame */ public static TransformResult melSpectrum(int numBands) { if(_melSpectrums == null) { _melSpectrums = new HashMap<Integer, TransformResult>(); } if(_melFilterBanks == null) { _melFilterBanks = new HashMap<String, MelFilterBank>(); } if(_melSpectrums.containsKey(numBands)) { return _melSpectrums.get(numBands); } int fMax = Math.round(_sampleRate / 2); String hash = numBands + "-0-" + fMax; if(! _melFilterBanks.containsKey(hash)) { _melFilterBanks.put(hash, new MelFilterBank(0, fMax, numBands)); } float[] mels = _melFilterBanks.get(hash).filter(spectrum().frame(), _sampleRate); float min = Float.MAX_VALUE; float max = Float.MIN_VALUE; for(int i = 0; i < numBands; i++) { float v = mels[i]; if(v < min) min = v; if(v > max) max = v; } TransformResult result = new TransformResult(mels, min, max); _melSpectrums.put(numBands, result); return result; } /** * Returns an FFT based on the settings of the song and frame currently played. * The FFT already has the updated data, that is forward() was already called. * By default, no averages are calculated by this fft. If averages are needed, * set noAverages() again after calculation. * * @return */ private static FFT _fft() { if(_fft != null) { if(_fft.timeSize() != _samples.length || _fftSampleRate != _sampleRate) { _fft = null; } else { if(! _fftForwarded) { _fft.forward(samplesWindowed()); _fftForwarded = true; } return _fft; } } _fft = new FFT(_samples.length, _sampleRate); _fft.noAverages(); _fft.forward(samplesWindowed()); _fftSampleRate = _sampleRate; _fftForwarded = true; return _fft; } /** * Resets all calculated transforms. This must be called immediately after * the frame was updated. */ private static void _reset() { _spectrum = null; _fftForwarded = false; if(_melSpectrums != null) _melSpectrums.clear(); } /** * Frame transform related utility methods. * * @author christopher */ public static class Util { /** * Returns the center frequency of the frequency band with the specified index. * * @param band The index of the frequency band * @return The center frequency */ public static float bandToFrequency(int band) { return _fft().indexToFreq(band); } /** * Returns the frequency band the given frequency would belong to. * * @param frequency The frequency * @return The band the frequency belongs to */ public static int frequencyToBand(float frequency) { return _fft().freqToIndex(frequency); } } } private Frame() { } }
9,691
Java
.java
skpdvdd/PAV
20
4
3
2011-02-02T23:31:54Z
2011-04-18T11:26:05Z
SettingsActivity.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/SettingsActivity.java
package me.kr328.nevo.decorators.smscaptcha; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import me.kr328.nevo.decorators.smscaptcha.utils.PackageUtils; /** * A {@link PreferenceActivity} that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * <p> * See <a href="http://developer.android.com/design/patterns/settings.html"> * Android Design: Settings</a> for design guidelines and the <a * href="http://developer.android.com/guide/topics/ui/settings.html">Settings * API Guide</a> for more information on developing a Settings UI. */ public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupWindowOreo(); new Thread(this::detectedNevolution).start(); } private void setupWindowOreo() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return; View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR); getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary ,getTheme())); } private void detectedNevolution() { if ( !PackageUtils.hasPackageInstalled(this ,Global.NEVOLUTION_PACKAGE_NAME) ) { runOnUiThread(() -> new AlertDialog.Builder(this). setTitle(R.string.missing_nevolution_dialog_title). setMessage(R.string.missing_nevolution_dialog_message). setOnDismissListener(dialog -> this.finish()). setPositiveButton(R.string.missing_nevolution_dialog_button ,(dialog ,i) -> startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("market://details?id=" + Global.NEVOLUTION_PACKAGE_NAME)))). show()); } else { runOnUiThread(() -> setContentView(R.layout.main_layout)); } } }
2,357
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
BaseSmsDecoratorService.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/BaseSmsDecoratorService.java
package me.kr328.nevo.decorators.smscaptcha; import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Icon; import android.os.Parcelable; import android.util.Log; import com.oasisfeng.nevo.sdk.NevoDecoratorService; public abstract class BaseSmsDecoratorService extends NevoDecoratorService { public static final String TAG = BaseSmsDecoratorService.class.getSimpleName(); public static final String INTENT_ACTION_CLICKED_ACTION = Global.PREFIX_INTENT_ACTION + ".clicked.action"; public static final String INTENT_ACTION_PROXY_ACTION = Global.PREFIX_INTENT_ACTION + ".proxy.action"; public static final String INTENT_EXTRA_NOTIFICATION_KEY = Global.PREFIX_INTENT_EXTRA + ".notification.key"; public static final String INTENT_EXTRA_PROXY_INTENT = Global.PREFIX_INTENT_EXTRA + ".proxy.intent"; public static final String INTENT_EXTRA_COOKIES = Global.PREFIX_INTENT_EXTRA + ".cookies"; private BroadcastReceiver mOnActionClickedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String key = intent.getStringExtra(INTENT_EXTRA_NOTIFICATION_KEY); Parcelable cookies = intent.getParcelableExtra(INTENT_EXTRA_COOKIES); BaseSmsDecoratorService.this.onActionClicked(key ,cookies); cancelNotification(key); } }; private BroadcastReceiver mActionProxyReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { PendingIntent originalIntent = intent.getParcelableExtra(INTENT_EXTRA_PROXY_INTENT); String key = intent.getStringExtra(INTENT_EXTRA_NOTIFICATION_KEY); try { cancelNotification(key); originalIntent.send(context, 0, intent.setPackage(originalIntent.getCreatorPackage())); } catch (PendingIntent.CanceledException e) { Log.e(TAG, "Proxy failure.", e); } } }; private BroadcastReceiver mUserUnlockedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { BaseSmsDecoratorService.this.onUserUnlocked(); } }; @Override protected void onNotificationRemoved(String key, int reason) { super.onNotificationRemoved(key, reason); } @Override protected void onConnected() { super.onConnected(); registerReceiver(mOnActionClickedReceiver, new IntentFilter(INTENT_ACTION_CLICKED_ACTION)); registerReceiver(mActionProxyReceiver, new IntentFilter(INTENT_ACTION_PROXY_ACTION)); registerReceiver(mUserUnlockedReceiver, new IntentFilter(Intent.ACTION_USER_UNLOCKED)); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mOnActionClickedReceiver); unregisterReceiver(mActionProxyReceiver); unregisterReceiver(mUserUnlockedReceiver); } public abstract void onUserUnlocked(); public abstract void onActionClicked(String key ,Parcelable cookies); protected Notification.Action createNonIconAction(String key, String title, Parcelable cookies) { Icon icon = Icon.createWithResource(this, R.drawable.ic_empty); Intent intent = new Intent().setAction(INTENT_ACTION_CLICKED_ACTION).putExtra(INTENT_EXTRA_COOKIES, cookies).putExtra(INTENT_EXTRA_NOTIFICATION_KEY, key); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, cookies.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); return new Notification.Action.Builder(icon, title, pendingIntent).build(); } protected void appendActions(Notification notification, String key, Notification.Action[] actions) { Notification.Action[] appliedActions = new Notification.Action[notification.actions.length + actions.length]; for (Notification.Action action : notification.actions) { action.actionIntent = PendingIntent.getBroadcast(this, action.actionIntent.hashCode(), new Intent().setAction(INTENT_ACTION_PROXY_ACTION).putExtra(INTENT_EXTRA_PROXY_INTENT, action.actionIntent).putExtra(INTENT_EXTRA_NOTIFICATION_KEY, key), PendingIntent.FLAG_UPDATE_CURRENT); } System.arraycopy(notification.actions, 0, appliedActions, 0, notification.actions.length); System.arraycopy(actions, 0, appliedActions, notification.actions.length, actions.length); notification.actions = appliedActions; } protected void replaceActions(Notification notification, String key, Notification.Action[] actions) { notification.actions = actions; } }
4,918
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
SettingsReceiver.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/SettingsReceiver.java
package me.kr328.nevo.decorators.smscaptcha; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class SettingsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { context.startActivity(new Intent(context, SettingsActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } }
408
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
SubscribeDecoratorService.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/SubscribeDecoratorService.java
package me.kr328.nevo.decorators.smscaptcha; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.os.UserManager; import android.util.Log; import com.oasisfeng.nevo.sdk.MutableNotification; import com.oasisfeng.nevo.sdk.MutableStatusBarNotification; import net.grandcentrix.tray.AppPreferences; import net.grandcentrix.tray.core.TrayItem; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; public class SubscribeDecoratorService extends BaseSmsDecoratorService { public final static String TAG = SubscribeDecoratorService.class.getSimpleName(); public final static String[] TARGET_PACKAGES = new String[]{"com.android.messaging", "com.google.android.apps.messaging", "com.android.mms" ,"com.sonyericsson.conversations" ,"com.moez.QKSMS"}; public final static String NOTIFICATION_CHANNEL_SUBSCRIBE_DEFAULT = "notification_channel_subscribe_default"; private Settings mSettings; @Override protected void apply(MutableStatusBarNotification evolving) { MutableNotification notification = evolving.getNotification(); Bundle extras = notification.extras; CharSequence message = extras.getCharSequence(Notification.EXTRA_TEXT); if (message == null || extras.getBoolean(Global.NOTIFICATION_EXTRA_APPLIED, false) || !message.toString().matches(mSettings.getSubscribeIdentifyPattern())) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notification.setChannelId(NOTIFICATION_CHANNEL_SUBSCRIBE_DEFAULT); else notification.priority = mSettings.getSubscribePriority(); appendActions(notification ,evolving.getKey() ,new Notification.Action[0]); extras.putBoolean(Global.NOTIFICATION_EXTRA_APPLIED, true); Log.i(TAG, "Applied " + evolving.getKey()); } @Override protected void onConnected() { super.onConnected(); loadSettings(); createNotificationChannels(); } @Override public void onUserUnlocked() { this.loadSettings(); } @Override public void onActionClicked(String key ,Parcelable cookies) { } public void loadSettings() { if ( Objects.requireNonNull(getSystemService(UserManager.class)).isUserUnlocked() ) { AppPreferences mAppPreference = new AppPreferences(this); mSettings = Settings.defaultValueFromContext(this).readFromTrayPreference(mAppPreference); mAppPreference.registerOnTrayPreferenceChangeListener(this::onSettingsChanged); } else { mSettings = Settings.defaultValueFromContext(createDeviceProtectedStorageContext()); } } private void onSettingsChanged(Collection<TrayItem> trayItems) { for (TrayItem item : trayItems) { switch (item.key()) { case Settings.SETTING_SUBSCRIBE_IDENTIFY_PATTERN: mSettings.setSubscribeIdentifyPattern(item.value()); break; case Settings.SETTING_SUBSCRIBE_PRIORITY: mSettings.setSubscribePriority(Integer.parseInt(Objects.requireNonNull(item.value()))); break; } } } private void createNotificationChannels() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return; NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_SUBSCRIBE_DEFAULT, getString(R.string.subscribe_service_notification_channel_name), NotificationManager.IMPORTANCE_MIN); ArrayList<NotificationChannel> notificationChannels = new ArrayList<>(); notificationChannels.add(channel); for (String packageName : TARGET_PACKAGES) createNotificationChannels(packageName, notificationChannels); } }
3,967
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
SettingsFragment.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/SettingsFragment.java
package me.kr328.nevo.decorators.smscaptcha; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.customtabs.CustomTabsIntent; import android.support.v7.app.AlertDialog; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.EditTextPreference; import android.support.v7.preference.ListPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import android.widget.Toast; import net.grandcentrix.tray.AppPreferences; import java.util.Objects; import me.kr328.nevo.decorators.smscaptcha.utils.PatternUtils; public class SettingsFragment extends PreferenceFragmentCompat { public final static String TAG = SettingsFragment.class.getSimpleName(); public final static String KEY_HIDE_IN_LAUNCHER = "setting_hide_in_launcher"; private CheckBoxPreference mCaptchaHideOnLocked; private CheckBoxPreference mCaptchaOverrideDefaultAction; private ListPreference mCaptchaPostCopyAction; private EditTextPreference mCaptchaIdentifyPattern; private EditTextPreference mCaptchaParsePattern; private EditTextPreference mSubscribeIdentityPattern; private Preference mSubscribePriority; private CheckBoxPreference mHideInLauncher; private AppPreferences mAppPreferences; private Settings mSettings; @Override public void onCreatePreferences(Bundle bundle, String s) { addPreferencesFromResource(R.xml.main_setting); getPreferenceScreen().setEnabled(false); mCaptchaHideOnLocked = (CheckBoxPreference) findPreference(Settings.SETTING_CAPTCHA_HIDE_ON_LOCKED); mCaptchaOverrideDefaultAction = (CheckBoxPreference) findPreference(Settings.SETTING_CAPTCHA_OVERRIDE_DEFAULT_ACTION); mCaptchaPostCopyAction = (ListPreference) findPreference(Settings.SETTING_CAPTCHA_POST_COPY_ACTION); mCaptchaIdentifyPattern = (EditTextPreference) findPreference(Settings.SETTING_CAPTCHA_IDENTIFY_PATTERN); mCaptchaParsePattern = (EditTextPreference) findPreference(Settings.SETTING_CAPTCHA_PARSE_PATTERN); mSubscribeIdentityPattern = (EditTextPreference) findPreference(Settings.SETTING_SUBSCRIBE_IDENTIFY_PATTERN); mSubscribePriority = findPreference(Settings.SETTING_SUBSCRIBE_PRIORITY); mHideInLauncher = (CheckBoxPreference) findPreference(KEY_HIDE_IN_LAUNCHER); mCaptchaHideOnLocked.setOnPreferenceChangeListener(this::onPreferenceChange); mCaptchaOverrideDefaultAction.setOnPreferenceChangeListener(this::onPreferenceChange); mCaptchaPostCopyAction.setOnPreferenceChangeListener(this::onPreferenceChange); mCaptchaIdentifyPattern.setOnPreferenceChangeListener(this::onPreferenceChange); mCaptchaParsePattern.setOnPreferenceChangeListener(this::onPreferenceChange); mSubscribeIdentityPattern.setOnPreferenceChangeListener(this::onPreferenceChange); mHideInLauncher.setOnPreferenceChangeListener(this::onPreferenceChange); mSubscribePriority.setOnPreferenceChangeListener(this::onPreferenceChange); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { mSubscribePriority.setOnPreferenceClickListener((Preference p) -> { startActivity( new Intent("android.settings.APP_NOTIFICATION_SETTINGS"). putExtra("android.provider.extra.APP_PACKAGE" , Global.NEVOLUTION_PACKAGE_NAME)); return false; }); } new Thread(this::loadSettingsAndUpdateViews).start(); } private boolean onPreferenceChange(Preference preference, Object value) { String key = preference.getKey(); int valueInteger = 0; switch (key) { case Settings.SETTING_CAPTCHA_HIDE_ON_LOCKED: mSettings.setCaptchaHideOnLocked((Boolean) value); mAppPreferences.put(key, (Boolean) value); break; case Settings.SETTING_CAPTCHA_OVERRIDE_DEFAULT_ACTION : mSettings.setCaptchaOverrideDefaultAction((Boolean) value); mAppPreferences.put(key ,(Boolean) value); break; case Settings.SETTING_CAPTCHA_USE_DEFAULT_PATTERN : mSettings.setCaptchaUseDefaultPattern((Boolean) value); mAppPreferences.put(key ,(Boolean) value); break; case Settings.SETTING_CAPTCHA_POST_COPY_ACTION : valueInteger = Integer.parseInt((String) value); mSettings.setCaptchaPostCopyAction(valueInteger); mAppPreferences.put(key ,valueInteger); showPermissionTips(valueInteger); break; case Settings.SETTING_CAPTCHA_IDENTIFY_PATTERN: if (checkPatternInvalidAndMakeToast((String) value)) return false; mSettings.setCaptchaIdentifyPattern((String) value); mAppPreferences.put(key, (String) value); break; case Settings.SETTING_CAPTCHA_PARSE_PATTERN: if (checkPatternInvalidAndMakeToast((String) value)) return false; mSettings.setCaptchaParsePattern((String) value); mAppPreferences.put(key, (String) value); break; case Settings.SETTING_SUBSCRIBE_IDENTIFY_PATTERN: if (checkPatternInvalidAndMakeToast((String) value)) return false; mSettings.setSubscribeIdentifyPattern((String) value); mAppPreferences.put(key, (String) value); break; case Settings.SETTING_SUBSCRIBE_PRIORITY: valueInteger = Integer.parseInt((String) value); mSettings.setSubscribePriority(valueInteger); mAppPreferences.put(key, valueInteger); break; case KEY_HIDE_IN_LAUNCHER: new Thread(() -> updateMainActivityEnabled(!(Boolean)value)).start(); break; } return true; } private boolean checkPatternInvalidAndMakeToast(String pattern) { if (!PatternUtils.checkPatternValid(pattern)) { Toast.makeText(this.getActivity() ,R.string.setting_pattern_invalid ,Toast.LENGTH_LONG).show(); return true; } return false; } private void loadSettingsAndUpdateViews() { mAppPreferences = new AppPreferences(Objects.requireNonNull(getActivity())); mSettings = Settings.defaultValueFromContext(getActivity()).readFromTrayPreference(mAppPreferences); getActivity().runOnUiThread(this::updateViews); boolean isActivityHidden = getActivity().getPackageManager().getComponentEnabledSetting(new ComponentName(BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID + ".MainActivity")) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED; getActivity().runOnUiThread(() -> mHideInLauncher.setChecked(isActivityHidden)); } private void updateViews() { mCaptchaHideOnLocked.setChecked(mSettings.isCaptchaHideOnLocked()); mCaptchaOverrideDefaultAction.setChecked(mSettings.isCaptchaOverrideDefaultAction()); mCaptchaPostCopyAction.setValue(String.valueOf(mSettings.getCaptchaPostCopyAction())); mCaptchaIdentifyPattern.setText(mSettings.getCaptchaIdentifyPattern()); mCaptchaParsePattern.setText(mSettings.getCaptchaParsePattern()); mSubscribeIdentityPattern.setText(mSettings.getSubscribeIdentifyPattern()); if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.O ) ((ListPreference)mSubscribePriority).setValue(String.valueOf(mSettings.getSubscribePriority())); getPreferenceScreen().setEnabled(true); } private void showPermissionTips(int postAction) { if (postAction == Settings.POST_ACTION_NONE) return; new AlertDialog.Builder(requireContext()). setTitle(R.string.permission_tips_title). setMessage(R.string.permission_tips_content). setPositiveButton(R.string.permission_tips_help ,(dialogInterface, i) -> new CustomTabsIntent.Builder().build().launchUrl(requireContext() ,Uri.parse(getString(R.string.permission_help_page_url)))). create().show(); } private void updateMainActivityEnabled(boolean enabled) { Objects.requireNonNull(getActivity()). getPackageManager(). setComponentEnabledSetting(new ComponentName(BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID + ".MainActivity"), enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } }
9,038
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
CaptchaDecoratorService.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/CaptchaDecoratorService.java
package me.kr328.nevo.decorators.smscaptcha; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.UserManager; import android.util.Log; import android.widget.Toast; import com.oasisfeng.nevo.sdk.MutableNotification; import com.oasisfeng.nevo.sdk.MutableStatusBarNotification; import net.grandcentrix.tray.AppPreferences; import net.grandcentrix.tray.core.TrayItem; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import java.util.TreeSet; import java.util.regex.Pattern; import me.kr328.nevo.decorators.smscaptcha.utils.CaptchaUtils; import me.kr328.nevo.decorators.smscaptcha.utils.MessageUtils; import me.kr328.nevo.decorators.smscaptcha.utils.NotificationUtils; import me.kr328.nevo.decorators.smscaptcha.utils.PackageUtils; import me.kr328.nevo.decorators.smscaptcha.utils.PatternUtils; public class CaptchaDecoratorService extends BaseSmsDecoratorService { public static final String TAG = CaptchaDecoratorService.class.getSimpleName(); public static final String[] TARGET_PACKAGES = new String[]{"com.android.messaging", "com.google.android.apps.messaging", "com.android.mms" ,"com.sonyericsson.conversations" ,"com.moez.QKSMS"}; public static final String NOTIFICATION_CHANNEL_CAPTCHA_NORMAL = "notification_channel_captcha_normal"; public static final String NOTIFICATION_CHANNEL_CAPTCHA_SILENT = "notification_channel_captcha_silent"; public static final String NOTIFICATION_EXTRA_RECAST = Global.PREFIX_NOTIFICATION_EXTRA + ".captcha.notification.recast"; private Settings mSettings; private CaptchaUtils mCaptchaUtils; private TreeSet<String> mAppliedKeys = new TreeSet<>(); private BroadcastReceiver mKeyguardReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle fillBundle = new Bundle(); fillBundle.putBoolean(NOTIFICATION_EXTRA_RECAST, true); recastAllNotifications(fillBundle); } }; @Override protected void apply(MutableStatusBarNotification evolving) { MutableNotification notification = evolving.getNotification(); Bundle extras = notification.extras; boolean recast = extras.getBoolean(NOTIFICATION_EXTRA_RECAST, false); NotificationUtils.Messages messages = NotificationUtils.parseMessages(notification); String[] captchas = mCaptchaUtils.findSmsCaptchas(messages.texts); if (captchas.length == 0) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notification.setChannelId(recast ? NOTIFICATION_CHANNEL_CAPTCHA_SILENT : NOTIFICATION_CHANNEL_CAPTCHA_NORMAL); else notification.priority = recast ? Notification.PRIORITY_LOW : Notification.PRIORITY_HIGH; KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (mSettings.isCaptchaHideOnLocked() && keyguardManager != null && keyguardManager.isKeyguardLocked()) applyKeyguardLocked(notification, evolving.getKey(), messages, captchas); else applyKeyguardUnlocked(notification, evolving.getKey(), messages, captchas); notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE; notification.visibility = Notification.VISIBILITY_PUBLIC; extras.putBoolean(Global.NOTIFICATION_EXTRA_APPLIED, true); mAppliedKeys.add(evolving.getKey()); Log.i(TAG, "Applied " + evolving.getKey()); } private void applyKeyguardLocked(Notification notification, String key, NotificationUtils.Messages messages , String[] captchas) { Notification.Action[] actions = new Notification.Action[] { createNonIconAction(key ,getString(R.string.captcha_service_notification_locked_action_copy_code) ,new CaptchaMessage(messages ,captchas[0])) }; NotificationUtils.replaceMessages(notification ,text -> CaptchaUtils.replaceCaptchaWithChar(text ,captchas ,'*')); if ( mSettings.isCaptchaOverrideDefaultAction() ) replaceActions(notification ,key ,actions); else appendActions(notification ,key ,actions); } private void applyKeyguardUnlocked(Notification notification, String key, NotificationUtils.Messages messages, String[] captchas) { Notification.Action[] actions = Arrays.stream(captchas). map(captcha -> createNonIconAction(key ,getString(R.string.captcha_service_notification_unlocked_action_copy_code_format ,captcha) ,new CaptchaMessage(messages ,captcha))). toArray(Notification.Action[]::new); NotificationUtils.rebuildMessageStyle(notification); if ( mSettings.isCaptchaOverrideDefaultAction() ) replaceActions(notification ,key ,actions); else appendActions(notification ,key ,actions); } private void loadSettings() { if (Objects.requireNonNull(getSystemService(UserManager.class)).isUserUnlocked()) { AppPreferences mAppPreferences = new AppPreferences(this); mSettings = Settings.defaultValueFromContext(this).readFromTrayPreference(mAppPreferences); mAppPreferences.registerOnTrayPreferenceChangeListener(this::onSettingsChanged); } else { mSettings = Settings.defaultValueFromContext(createDeviceProtectedStorageContext()); } } private void createNotificationChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channelNormal = new NotificationChannel(NOTIFICATION_CHANNEL_CAPTCHA_NORMAL, getString(R.string.captcha_service_notification_channel_name), NotificationManager.IMPORTANCE_HIGH); NotificationChannel channelSilent = new NotificationChannel(NOTIFICATION_CHANNEL_CAPTCHA_SILENT, getString(R.string.captcha_service_notification_channel_name), NotificationManager.IMPORTANCE_LOW); ArrayList<NotificationChannel> notificationChannels = new ArrayList<>(); notificationChannels.add(channelNormal); notificationChannels.add(channelSilent); for (String packageName : TARGET_PACKAGES) if (PackageUtils.hasPackageInstalled(this ,packageName)) createNotificationChannels(packageName, notificationChannels); } } private void initCaptchaUtils() { mCaptchaUtils = new CaptchaUtils(mSettings.isCaptchaUseDefaultPattern() , PatternUtils.compilePattern(mSettings.getCaptchaIdentifyPattern(), "" ,Pattern.CASE_INSENSITIVE), PatternUtils.compilePattern(mSettings.getCaptchaParsePattern(), "" ,Pattern.CASE_INSENSITIVE)); Log.d(TAG ,"CaptchaUtils " + mSettings.isCaptchaUseDefaultPattern() + " " + mSettings.getCaptchaIdentifyPattern() + " " + mSettings.getCaptchaParsePattern()); } private void recastAllNotifications(Bundle fillInExtras) { for (String key : mAppliedKeys) recastNotification(key, fillInExtras); mAppliedKeys.clear(); } private void copyCaptcha(String captcha , NotificationUtils.Messages messages) { ((ClipboardManager) Objects.requireNonNull(getSystemService(Context.CLIPBOARD_SERVICE))). setPrimaryClip(ClipData.newPlainText("SmsCaptcha", captcha)); switch (mSettings.getCaptchaPostCopyAction()) { case Settings.POST_ACTION_DELETE : Arrays.stream(messages.texts).forEach(t -> MessageUtils.delete(this , t)); break; case Settings.POST_ACTION_MARK_AS_READ : Arrays.stream(messages.texts).forEach(t -> MessageUtils.markAsRead(this , t)); break; } Toast.makeText(this, getString(R.string.captcha_service_toast_copied_format, captcha), Toast.LENGTH_LONG).show(); } @Override public void onUserUnlocked() { this.loadSettings(); } @Override public void onActionClicked(String key ,Parcelable cookies) { CaptchaMessage captchaMessage = (CaptchaMessage) cookies; if ( captchaMessage == null ) return; copyCaptcha(captchaMessage.captcha ,captchaMessage.messages); } private void registerReceivers() { registerReceiver(mKeyguardReceiver, new IntentFilter() {{ addAction(Intent.ACTION_USER_PRESENT); addAction(Intent.ACTION_SCREEN_OFF); }}); } private void unregisterReceivers() { unregisterReceiver(mKeyguardReceiver); } @Override protected void onNotificationRemoved(String key, int reason) { super.onNotificationRemoved(key ,reason); mAppliedKeys.remove(key); } @Override protected void onConnected() { super.onConnected(); loadSettings(); createNotificationChannels(); initCaptchaUtils(); registerReceivers(); } private void onSettingsChanged(Collection<TrayItem> trayItems) { for (TrayItem item : trayItems) { switch (item.key()) { case Settings.SETTING_CAPTCHA_IDENTIFY_PATTERN: mSettings.setCaptchaIdentifyPattern(item.value()); initCaptchaUtils(); break; case Settings.SETTING_CAPTCHA_PARSE_PATTERN: mSettings.setCaptchaParsePattern(item.value()); initCaptchaUtils(); break; case Settings.SETTING_CAPTCHA_USE_DEFAULT_PATTERN : mSettings.setCaptchaUseDefaultPattern(Boolean.parseBoolean(item.value())); initCaptchaUtils(); break; case Settings.SETTING_CAPTCHA_HIDE_ON_LOCKED : mSettings.setCaptchaHideOnLocked(Boolean.parseBoolean(item.value())); break; case Settings.SETTING_CAPTCHA_OVERRIDE_DEFAULT_ACTION : mSettings.setCaptchaOverrideDefaultAction(Boolean.parseBoolean(item.value())); break; case Settings.SETTING_CAPTCHA_POST_COPY_ACTION : mSettings.setCaptchaPostCopyAction(Integer.parseInt(Objects.requireNonNull(item.value()))); break; } Log.i(TAG ,"Settings Updated " + item.key() + "=" + item.value()); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceivers(); } static class CaptchaMessage implements Parcelable { NotificationUtils.Messages messages; String captcha; CaptchaMessage(NotificationUtils.Messages messages, String captcha) { this.messages = messages; this.captcha = captcha; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(messages.texts.length); for (CharSequence s : messages.texts) dest.writeString(s.toString()); dest.writeString(captcha); } public static final Creator<CaptchaMessage> CREATOR = new Creator<CaptchaMessage>() { @Override public CaptchaMessage createFromParcel(Parcel source) { NotificationUtils.Messages messages = new NotificationUtils.Messages(); messages.texts = new String[source.readInt()]; for ( int i = 0 ; i < messages.texts.length ; i++ ) messages.texts[i] = source.readString(); return new CaptchaMessage(messages ,source.readString()); } @Override public CaptchaMessage[] newArray(int size) { return new CaptchaMessage[size]; } }; } }
12,398
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
Global.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/Global.java
package me.kr328.nevo.decorators.smscaptcha; public class Global { public final static String PREFIX = BuildConfig.APPLICATION_ID; public final static String PREFIX_INTENT = PREFIX + ".intent"; public final static String PREFIX_INTENT_ACTION = PREFIX_INTENT + ".action"; public final static String PREFIX_INTENT_EXTRA = PREFIX_INTENT + ".extra"; public final static String PREFIX_NOTIFICATION = PREFIX + ".notification"; public final static String PREFIX_NOTIFICATION_EXTRA = PREFIX_NOTIFICATION + ".extra"; public final static String NOTIFICATION_EXTRA_APPLIED = PREFIX_NOTIFICATION_EXTRA + ".applied"; public final static String NEVOLUTION_PACKAGE_NAME = "com.oasisfeng.nevo"; }
716
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
Settings.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/Settings.java
package me.kr328.nevo.decorators.smscaptcha; import android.content.Context; import net.grandcentrix.tray.TrayPreferences; public class Settings { public final static String SETTING_CAPTCHA_HIDE_ON_LOCKED = "setting_captcha_hide_on_locked"; public final static String SETTING_CAPTCHA_IDENTIFY_PATTERN = "setting_captcha_identify_pattern"; public final static String SETTING_CAPTCHA_OVERRIDE_DEFAULT_ACTION = "setting_captcha_override_default_action"; public final static String SETTING_CAPTCHA_POST_COPY_ACTION = "setting_captcha_post_copy_action"; public final static String SETTING_CAPTCHA_USE_DEFAULT_PATTERN = "setting_captcha_use_default_pattern"; public final static String SETTING_CAPTCHA_PARSE_PATTERN = "setting_captcha_parse_pattern"; public final static String SETTING_SUBSCRIBE_IDENTIFY_PATTERN = "setting_subscribe_identify_pattern"; public final static String SETTING_SUBSCRIBE_PRIORITY = "setting_subscribe_priority"; public final static int POST_ACTION_NONE = 0; public final static int POST_ACTION_MARK_AS_READ = 1; public final static int POST_ACTION_DELETE = 2; private boolean captchaHideOnLocked; private boolean captchaOverrideDefaultAction; private int captchaPostCopyAction; private boolean captchaUseDefaultPattern; private String captchaIdentifyPattern; private String captchaParsePattern; private String subscribeIdentifyPattern; private int subscribePriority; public Settings(boolean captchaHideOnLocked,boolean captchaOverrideDefaultAction ,int captchaPostCopyAction ,boolean captchaUseDefaultPattern,String captchaIdentifyPattern, String captchaParsePattern, String subscribeIdentifyPattern, int subscribePriority) { this.setCaptchaHideOnLocked(captchaHideOnLocked); this.setCaptchaOverrideDefaultAction(captchaOverrideDefaultAction); this.setCaptchaPostCopyAction(captchaPostCopyAction); this.setCaptchaUseDefaultPattern(captchaUseDefaultPattern); this.setCaptchaIdentifyPattern(captchaIdentifyPattern); this.setCaptchaParsePattern(captchaParsePattern); this.setSubscribeIdentifyPattern(subscribeIdentifyPattern); this.setSubscribePriority(subscribePriority); } public static Settings defaultValueFromContext(Context context) { return new Settings(true, false , 0 , true , "", "", context.getString(R.string.default_value_identify_subscribe_pattern), -2); } public Settings readFromTrayPreference(TrayPreferences preferences) { setCaptchaHideOnLocked(preferences.getBoolean(SETTING_CAPTCHA_HIDE_ON_LOCKED, isCaptchaHideOnLocked())); setCaptchaOverrideDefaultAction(preferences.getBoolean(SETTING_CAPTCHA_OVERRIDE_DEFAULT_ACTION ,isCaptchaOverrideDefaultAction())); setCaptchaPostCopyAction(preferences.getInt(SETTING_CAPTCHA_POST_COPY_ACTION ,getCaptchaPostCopyAction())); setCaptchaUseDefaultPattern(preferences.getBoolean(SETTING_CAPTCHA_USE_DEFAULT_PATTERN ,true)); setCaptchaIdentifyPattern(preferences.getString(SETTING_CAPTCHA_IDENTIFY_PATTERN, getCaptchaIdentifyPattern())); setCaptchaParsePattern(preferences.getString(SETTING_CAPTCHA_PARSE_PATTERN, getCaptchaParsePattern())); setSubscribeIdentifyPattern(preferences.getString(SETTING_SUBSCRIBE_IDENTIFY_PATTERN, getSubscribeIdentifyPattern())); setSubscribePriority(preferences.getInt(SETTING_SUBSCRIBE_PRIORITY, getSubscribePriority())); return this; } public boolean isCaptchaHideOnLocked() { return captchaHideOnLocked; } public void setCaptchaHideOnLocked(boolean captchaHideOnLocked) { this.captchaHideOnLocked = captchaHideOnLocked; } public String getCaptchaIdentifyPattern() { return captchaIdentifyPattern; } public void setCaptchaIdentifyPattern(String captchaIdentifyPattern) { this.captchaIdentifyPattern = captchaIdentifyPattern; } public String getCaptchaParsePattern() { return captchaParsePattern; } public void setCaptchaParsePattern(String captchaParsePattern) { this.captchaParsePattern = captchaParsePattern; } public String getSubscribeIdentifyPattern() { return subscribeIdentifyPattern; } public void setSubscribeIdentifyPattern(String subscribeIdentifyPattern) { this.subscribeIdentifyPattern = subscribeIdentifyPattern; } public int getSubscribePriority() { return subscribePriority; } public void setSubscribePriority(int subscribePriority) { this.subscribePriority = subscribePriority; } public boolean isCaptchaOverrideDefaultAction() { return captchaOverrideDefaultAction; } public void setCaptchaOverrideDefaultAction(boolean captchaOverrideDefaultAction) { this.captchaOverrideDefaultAction = captchaOverrideDefaultAction; } public int getCaptchaPostCopyAction() { return captchaPostCopyAction; } public void setCaptchaPostCopyAction(int captchaPostCopyAction) { this.captchaPostCopyAction = captchaPostCopyAction; } public boolean isCaptchaUseDefaultPattern() { return captchaUseDefaultPattern; } public void setCaptchaUseDefaultPattern(boolean captchaUseDefaultPattern) { this.captchaUseDefaultPattern = captchaUseDefaultPattern; } }
5,591
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
NotificationUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/NotificationUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import android.app.Notification; import android.support.v4.app.NotificationCompat; import java.util.function.Function; public class NotificationUtils { public static class Messages { public CharSequence[] texts; } public static Messages parseMessages(Notification notification) { Messages result = new Messages(); NotificationCompat.MessagingStyle style = NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(notification); if ( style != null ) { result.texts = style.getMessages(). stream(). map(NotificationCompat.MessagingStyle.Message::getText). toArray(CharSequence[]::new); } else { CharSequence message = notification.extras.getCharSequence(Notification.EXTRA_TEXT); if ( message != null ) result.texts = new String[]{message.toString()}; else result.texts = new String[0]; } return result; } public static void replaceMessages(Notification notification , Function<CharSequence ,CharSequence> replacer) { NotificationCompat.MessagingStyle originalStyle = NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(notification); NotificationCompat.MessagingStyle appliedStyle = null; if ( originalStyle != null ) { appliedStyle = new NotificationCompat.MessagingStyle(originalStyle.getUser()); appliedStyle.setConversationTitle(originalStyle.getConversationTitle()); appliedStyle.setGroupConversation(originalStyle.isGroupConversation()); for ( NotificationCompat.MessagingStyle.Message message : originalStyle.getMessages() ) appliedStyle.addMessage(replacer.apply(message.getText()) ,message.getTimestamp() ,message.getPerson()); appliedStyle.addCompatExtras(notification.extras); } else { notification.extras.remove(Notification.EXTRA_TEMPLATE); notification.extras.putCharSequence(Notification.EXTRA_TEXT, replacer.apply(notification.extras.getCharSequence(Notification.EXTRA_TEXT))); } } public static void rebuildMessageStyle(Notification notification) { NotificationCompat.MessagingStyle style = NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(notification); if ( style != null ) style.addCompatExtras(notification.extras); else notification.extras.remove(Notification.EXTRA_TEMPLATE); } }
2,641
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
BroadcastUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/BroadcastUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import android.content.Context; import android.content.Intent; public class BroadcastUtils { public BroadcastUtils(Context context) { } public void registerBroadcastListener() { } public interface BroadcastListener { void onReceiver(Intent intent); } }
342
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
PackageUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/PackageUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import android.content.Context; import android.content.pm.PackageManager; public class PackageUtils { public static boolean hasPackageInstalled(Context context ,String packageName) { try { context.getPackageManager().getApplicationInfo(packageName ,0); } catch (PackageManager.NameNotFoundException e) { return false; } return true; } }
455
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
MessageUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/MessageUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.util.Log; public class MessageUtils { public static final String TAG = MessageUtils.class.getSimpleName(); public static final Uri URI_SMS_INBOX = Uri.parse("content://sms"); public static void markAsRead(Context context, CharSequence text) { ContentValues values = new ContentValues(); values.put("read" ,true); context.getContentResolver(). update(URI_SMS_INBOX ,values ,"body=?" ,new String[]{text.toString()}); } public static void delete(Context context, CharSequence text) { context.getContentResolver(). delete(URI_SMS_INBOX ,"body=?" ,new String[]{text.toString()}); Log.i(TAG ,"Fucking Android " + text); } private static String processAddress(String address) { return address.replaceAll("[()\\s]" ,""); } }
997
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
PatternUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/PatternUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class PatternUtils { @SuppressWarnings("ResultOfMethodCallIgnored") public static boolean checkPatternValid(String pattern) { try { Pattern.compile(pattern); } catch (PatternSyntaxException e) { return false; } return true; } public static Pattern compilePattern(String pattern, String def ,int flags) { try { return Pattern.compile(pattern ,flags); } catch (PatternSyntaxException ignored) { } return Pattern.compile(def ,flags); } }
695
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
ResourceUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/ResourceUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import android.content.Context; import java.io.IOException; import java.io.InputStream; public class ResourceUtils { @SuppressWarnings("ResultOfMethodCallIgnored") public static String readFromResource(Context context , int resId) { try { InputStream inputStream = context.getResources().openRawResource(resId); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer ,0 ,buffer.length); inputStream.close(); return new String(buffer ,"utf-8"); } catch (IOException e) { throw new UnsupportedOperationException("Read raw file"); } } }
716
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
CaptchaUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/CaptchaUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CaptchaUtils { private static final Pattern defaultIdentifyPattern = Pattern.compile(".*((验证|確認|驗證|校验|动态|确认|随机|激活|兑换|认证|交易|授权|操作|提取|安全|登陆|登录|verification |confirmation )(码|碼|代码|代碼|号码|密码|code|コード)|口令|Steam|快递|快件|单号|订单|包裹).*"); private static final Pattern defaultParsePattern = Pattern.compile("((?<!\\d|(联通|尾号|金额|支付|末四位)(为)?)(G-)?\\d{4,8}(?!\\d|年|账|动画))|((?<=(code is|码|碼|コードは)[是为為]?[『「【〖((:: ]?)(?<![a-zA-Z0-9])[a-zA-Z0-9]{4,8}(?![a-zA-Z0-9]))|((?<!\\w)\\w{4,8}(?!\\w)(?= is your))|((?<=(取件码|密码|货码|暗号|凭|号码)[『「【〖((::“\" ]?)(?<![a-zA-Z0-9-])[a-zA-Z0-9-]{4,10}(?![a-zA-Z0-9-]))|货号[0-9]{1,}|(?<=(到|至|速来|地址)[:: ]?)[\\w|-]{3,}?(?=(领取|取件|取货)|[,.),。)])"); private boolean useDefault; private Pattern customIdentifyPattern; private Pattern customParsePattern; public CaptchaUtils(boolean useDefault ,Pattern customIdentifyPattern, Pattern customParsePattern) { this.useDefault = useDefault; this.customIdentifyPattern = customIdentifyPattern; this.customParsePattern = customParsePattern.pattern().isEmpty() ? Pattern.compile("^$") : customParsePattern; } public static String replaceCaptchaWithChar(CharSequence message, String[] captchas, char ch) { String messageString = message.toString(); for (String captcha : captchas) messageString = messageString.replace(captcha, StringUtils.repeat(ch, captcha.length())); return messageString; } public String[] findSmsCaptchas(CharSequence[] messages) { if (messages == null) return new String[0]; ArrayList<String> captchas = new ArrayList<>(); for ( CharSequence message : messages ) { if (!(customIdentifyPattern.matcher(message).matches() || ( useDefault && defaultIdentifyPattern.matcher(message).matches() ))) continue; Matcher customMatcher = customParsePattern.matcher(message); Matcher defaultMatcher = defaultParsePattern.matcher(message); while (customMatcher.find()) captchas.add(customMatcher.group(0)); while (useDefault && defaultMatcher.find()) captchas.add(defaultMatcher.group(0)); } return captchas.toArray(new String[0]); } }
2,678
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
StringUtils.java
/FileExtraction/Java_unseen/Kr328_nevo-decorators-sms-captchas/app/src/main/java/me/kr328/nevo/decorators/smscaptcha/utils/StringUtils.java
package me.kr328.nevo.decorators.smscaptcha.utils; public class StringUtils { public static String repeat(char ch, int count) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < count; i++) builder.append(ch); return builder.toString(); } }
303
Java
.java
Kr328/nevo-decorators-sms-captchas
74
7
3
2018-08-02T07:18:14Z
2020-04-18T13:11:38Z
RtspResponseTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/rtsp/RtspResponseTest.java
package xpertss.rtsp; import org.junit.Test; import static org.junit.Assert.*; public class RtspResponseTest { @Test public void testResponseSplit() { String response = "500 Internal Error"; String[] parts = response.split("\\s+", 2); assertEquals(2, parts.length); assertEquals("500", parts[0]); assertEquals("Internal Error", parts[1]); } }
390
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspMethodTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/rtsp/RtspMethodTest.java
package xpertss.rtsp; import org.junit.Test; import xpertss.lang.Booleans; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.junit.Assert.*; public class RtspMethodTest { @Test public void testBooleansDefaultUnboxedValue() { ConcurrentMap<String,Boolean> map = new ConcurrentHashMap<>(); assertFalse(Booleans.isTrue(map.get("NonExistent"))); assertFalse(Booleans.isTrue(map.remove("NonExistent"))); assertFalse(map.replace("NonExistent", false, true)); //assertFalse(map.replace(null, false, true)); } }
611
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspClientTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/rtsp/RtspClientTest.java
package xpertss.rtsp; import org.junit.Test; import xpertss.lang.Range; import xpertss.media.MediaChannel; import xpertss.media.MediaConsumer; import xpertss.media.MediaType; import xpertss.sdp.MediaDescription; import xpertss.sdp.SessionDescription; import java.net.ConnectException; import java.net.URI; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static xpertss.nio.ReadyState.Closed; import static xpertss.nio.ReadyState.Closing; import static xpertss.nio.ReadyState.Connected; import static xpertss.nio.ReadyState.Connecting; import static xpertss.nio.ReadyState.Open; public class RtspClientTest { @Test public void testClientConnectSequence() { RtspHandler handler = mock(RtspHandler.class); RtspClient client = new RtspClient(); RtspSession session = client.open(handler, URI.create("rtsp://stream.manheim.com:999/AVAIL.sdp")); assertEquals(Open, session.getReadyState()); session.connect(500); assertEquals(Connecting, session.getReadyState()); while(session.getReadyState() == Connecting); verify(handler, times(1)).onConnect(same(session)); assertEquals(Connected, session.getReadyState()); session.close(); assertEquals(Closing, session.getReadyState()); while(session.getReadyState() == Closing); assertEquals(Closed, session.getReadyState()); verify(handler, times(1)).onClose(same(session)); } @Test public void testClientConnectSequenceTimeout() { RtspHandler handler = mock(RtspHandler.class); RtspClient client = new RtspClient(); RtspSession session = client.open(handler, URI.create("rtsp://10.0.0.1:999/AVAIL.sdp")); assertEquals(Open, session.getReadyState()); session.connect(100); assertEquals(Connecting, session.getReadyState()); while(session.getReadyState() == Connecting); verify(handler, times(1)).onFailure(same(session), any(ConnectException.class)); assertEquals(Closed, session.getReadyState()); } @Test public void testClientConnectSequenceUnknownHost() { RtspHandler handler = mock(RtspHandler.class); RtspClient client = new RtspClient(); RtspSession session = client.open(handler, URI.create("rtsp://doesnot.exist.host.com:999/AVAIL.sdp")); assertEquals(Open, session.getReadyState()); session.connect(100); assertEquals(Connecting, session.getReadyState()); while(session.getReadyState() == Connecting); verify(handler, times(1)).onFailure(same(session), any(UnknownHostException.class)); assertEquals(Closed, session.getReadyState()); } @Test public void testRtspPlayer() { RtspClient client = new RtspClient(); RtspPlayer player = new RtspPlayer(client, new MediaConsumer() { private Map<Integer,Consumer<ByteBuffer>> channels = new HashMap<>(); @Override public MediaDescription[] select(SessionDescription sdp) { return sdp.getMediaDescriptions(); } @Override public void createChannel(MediaChannel channel) { final MediaType type = channel.getType(); Range<Integer> range = channel.getChannels(); channels.put(range.getLower(), new Consumer<ByteBuffer>() { long start = System.nanoTime(); @Override public void accept(ByteBuffer data) { long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); int seq = (int) (data.getShort(2) & 0xffff); long ts = (long) (data.getInt(4) & 0xffffffff); System.out.println(String.format("%s: %010d {seq=%05d, ts=%d, size=%04d}", type.name(), millis, seq, ts, data.remaining())); } }); channels.put(range.getUpper(), new Consumer<ByteBuffer>() { @Override public void accept(ByteBuffer byteBuffer) { System.out.println(String.format("%s - RTP Sender Report Received", type.name())); } }); } @Override public void destroyChannels() { System.out.println("destroy called"); channels.clear(); } @Override public void consume(int channelId, ByteBuffer data) { Consumer<ByteBuffer> handler = channels.get(channelId); if(handler == null) System.out.println(String.format("Received packet on unknown channel %d", channelId)); else handler.accept(data); } @Override public void handle(Throwable t) { t.printStackTrace(); } }); player.setReadTimeout(5000); player.start(URI.create("rtsp://stream.manheim.com:999/AVAIL.sdp")); assertEquals(RtspState.Activating, player.getState()); client.await(3, TimeUnit.SECONDS); assertEquals(RtspState.Active, player.getState()); player.pause(); assertEquals(RtspState.Pausing, player.getState()); client.await(3, TimeUnit.SECONDS); assertEquals(RtspState.Paused, player.getState()); player.play(); assertEquals(RtspState.Activating, player.getState()); client.await(3, TimeUnit.SECONDS); assertEquals(RtspState.Active, player.getState()); player.stop(); assertEquals(RtspState.Stopping, player.getState()); client.await(); assertEquals(RtspState.Stopped, player.getState()); } }
5,911
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
UserAgentTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/utils/UserAgentTest.java
package xpertss.utils; import org.junit.Test; import xpertss.util.Version; import static org.junit.Assert.*; public class UserAgentTest { @Test public void testUserAgent() { String userAgent = UserAgent.create("MMP", new Version(2,1)).toString(); assertTrue(userAgent.startsWith("MMP/2.1")); assertTrue(userAgent.contains("XpertRTSP/")); assertTrue(userAgent.contains(System.getProperty("os.arch"))); assertTrue(userAgent.contains("Java")); } @Test public void testUserAgentNoCpu() { UserAgent agent = UserAgent.create("MMP", new Version(2,1)); agent.includeCpu(false); String userAgent = agent.toString(); assertTrue(userAgent.startsWith("MMP/2.1")); assertTrue(userAgent.contains("XpertRTSP/")); assertFalse(userAgent.contains(System.getProperty("os.arch"))); assertTrue(userAgent.contains("Java")); } @Test public void testUserAgentNoJava() { UserAgent agent = UserAgent.create("MMP", new Version(2,1)); agent.includeJava(false); String userAgent = agent.toString(); assertTrue(userAgent.startsWith("MMP/2.1")); assertTrue(userAgent.contains("XpertRTSP/")); assertTrue(userAgent.contains(System.getProperty("os.arch"))); assertFalse(userAgent.contains("Java")); } @Test public void testUserAgentNoLibrary() { UserAgent agent = UserAgent.create("MMP", new Version(2,1)); agent.includeLibrary(false); String userAgent = agent.toString(); assertTrue(userAgent.startsWith("MMP/2.1")); assertFalse(userAgent.contains("XpertRTSP/")); assertTrue(userAgent.contains(System.getProperty("os.arch"))); assertTrue(userAgent.contains("Java")); } }
1,749
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
UtilsTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/utils/UtilsTest.java
package xpertss.utils; import org.junit.Test; import static org.junit.Assert.*; public class UtilsTest { }
115
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HeadersTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/mime/HeadersTest.java
package xpertss.mime; import org.junit.Test; import java.util.Enumeration; import static org.junit.Assert.*; public class HeadersTest { @Test public void testEmpty() { Headers headers = new Headers(Headers.Type.Rtsp); assertNull(headers.getHeader("Content-Type")); assertFalse(headers.headers().hasMoreElements()); } @Test public void testGetSet() { Headers headers = new Headers(Headers.Type.Rtsp); assertNull(headers.getHeader("Content-Length")); headers.setHeader("Content-Length", "200"); assertNotNull(headers.getHeader("Content-Length")); assertEquals("200", Headers.toString(headers.getHeader("Content-Length"))); assertTrue(headers.headers().hasMoreElements()); // should have an element assertTrue(headers.contains("Content-Length")); // should be found assertTrue(headers.contains("Content-length")); // case doesn't matter } @Test public void testOrdering() { Headers headers = new Headers(Headers.Type.Rtsp); headers.setHeader("Connection", "5"); headers.setHeader("CSeq", "1"); headers.setHeader("Content-Base", "3"); headers.setHeader("Vary", "4"); headers.setHeader("User-Agent", "2"); Enumeration<Header> e = headers.headers(); assertEquals("1", Headers.toString(e.nextElement())); assertEquals("2", Headers.toString(e.nextElement())); assertEquals("3", Headers.toString(e.nextElement())); assertEquals("4", Headers.toString(e.nextElement())); assertEquals("5", Headers.toString(e.nextElement())); } @Test public void testMultipleHeaders() { Headers headers = new Headers(Headers.Type.Rtsp); headers.addHeader("Received", "from localhost"); headers.addHeader("Received", "from gateway"); Enumeration<Header> e = headers.headers(); assertEquals("from localhost", Headers.toString(e.nextElement())); assertEquals("from gateway", Headers.toString(e.nextElement())); assertFalse(e.hasMoreElements()); assertEquals(2, headers.getHeaders("Received").length); assertEquals(2, headers.getHeaders("received").length); assertEquals(2, headers.remove("Received")); assertEquals(0, headers.remove("Received")); } @Test public void testSetIfNotSet() { Headers headers = new Headers(Headers.Type.Rtsp); headers.setIfNotSet("User-Agent", "one"); headers.setIfNotSet("User-Agent", "two"); assertEquals("one", Headers.toString(headers.getHeader("User-Agent"))); assertEquals(1, headers.getHeaders("User-Agent").length); assertEquals(1, headers.remove("User-Agent")); } @Test public void testHeaderParameters() { Headers headers = new Headers(Headers.Type.Rtsp); headers.setIfNotSet("Session", "rzRIqDVnQVDRTppy;timeout=60"); Header header = headers.getHeader("Session"); assertEquals("rzRIqDVnQVDRTppy; timeout=60", Headers.toString(header)); assertEquals("rzRIqDVnQVDRTppy", header.getValue(0).getValue()); assertEquals("60", header.getValue(0).getParameter("timeout").getValue()); } }
3,152
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HeaderParserTest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/test/java/xpertss/mime/HeaderParserTest.java
package xpertss.mime; import org.junit.Test; import static org.junit.Assert.*; public class HeaderParserTest { @Test public void testTransport() { Header header = HeaderParser.parse("Transport", "RTP/AVP/TCP;unicast;interleaved=0-1"); assertNotNull(header.getValue(0)); assertNotNull(header.getValue(0).getParameter("interleaved")); assertEquals("unicast", header.getValue(0).getParameter(0).getValue()); } @Test public void testComplexWithEquals() { Header header = HeaderParser.parse("RTP-Info", "url=rtsp://stream.manheim.com:999/AVAIL.sdp/trackID=2,url=rtsp://stream.manheim.com:999/AVAIL.sdp/trackID=5"); assertEquals(2, header.size()); HeaderValue valueOne = header.getValue(0); assertEquals("rtsp://stream.manheim.com:999/AVAIL.sdp/trackID=2", valueOne.getValue()); HeaderValue valueTwo = header.getValue(1); assertEquals("rtsp://stream.manheim.com:999/AVAIL.sdp/trackID=5", valueTwo.getValue()); // TODO How would I access these HeaderValues by name when they both have the same name } @Test public void testSplit() { String[] parts = "url=rtsp://stream.manheim.com:999/AVAIL.sdp/trackID=2".split("=", 2); assertEquals(2, parts.length); } }
1,273
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SourceException.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/SourceException.java
package xpertss; import java.net.ProtocolException; /** * A simple exception to encapsulate a RTSP/HTTP response code and * reason. */ public class SourceException extends ProtocolException { private int code; public SourceException(int code, String reason) { super(reason); this.code = code; } public int getCode() { return code; } }
383
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
MediaChannel.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/media/MediaChannel.java
package xpertss.media; import xpertss.lang.Objects; import xpertss.lang.Range; import xpertss.sdp.Attribute; import xpertss.sdp.MediaDescription; /** * A media channel is a channel setup by the RTSP process to transmit * or receive media data. * <p/> * The media channel is intended to convey information to a consumer * about the channel identifiers used for the media and the type of * media to expect on those channels. */ public class MediaChannel implements Comparable<MediaChannel> { private final MediaDescription desc; private final Range<Integer> channels; public MediaChannel(MediaDescription desc, Range<Integer> channels) { this.desc = Objects.notNull(desc); this.channels = Objects.notNull(channels); } /** * The full media description of the data this channel will * process. */ public MediaDescription getMedia() { return desc; } /** * A control identifier for the channel. */ public String getControl() { Attribute attr = desc.getAttribute("control"); return (attr != null) ? attr.getValue() : null; } /** * The media type this channel will process. */ public MediaType getType() { return MediaType.parse(desc); } /** * The channel identifiers over which this media will be transmitted. * <p/> * The media data is usually transmitted over the lower of the two * channel identifiers while control information for the channel is * transmitted over the higher channel. */ public Range<Integer> getChannels() { return channels; } /** * Compares this media channel to another based on its channel identifiers. */ @Override public int compareTo(MediaChannel o) { return channels.compareTo(o.channels); } }
1,821
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
MediaType.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/media/MediaType.java
package xpertss.media; import xpertss.sdp.MediaDescription; /** * An Enumeration of Standard SDP Media Types. */ public enum MediaType { Audio, Video, Text, Application, Message; public static MediaType parse(MediaDescription desc) { String mediaType = desc.getMedia().getType(); if("Audio".equalsIgnoreCase(mediaType)) { return Audio; } else if("Video".equalsIgnoreCase(mediaType)) { return Video; } else if("Text".equalsIgnoreCase(mediaType)) { return Text; } else if("Application".equalsIgnoreCase(mediaType)) { return Application; } else if("Message".equalsIgnoreCase(mediaType)) { return Message; } return null; } }
733
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
MediaConsumer.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/media/MediaConsumer.java
package xpertss.media; import xpertss.sdp.MediaDescription; import xpertss.sdp.SessionDescription; import java.nio.ByteBuffer; /** * A media consumer is responsible for interfacing with an RtspPlayer and * providing it information about which media streams to setup, and to * actually process the media streams that result from playback. */ public interface MediaConsumer { /** * Given a session description return the media descriptions the * consumer wishes to be setup for playback. */ public MediaDescription[] select(SessionDescription sdp); /** * For each media description desired this will be called by the * player to inform it that the channel has been successfully * setup and to identify the channel identifiers associated with * it. */ public void createChannel(MediaChannel channel); /** * Called to indicate that the previously created channels should * be destroyed as they are no longer valid. */ public void destroyChannels(); /** * Once playback has begun the actual channel data will be delivered * to the consumer via this method. The channelId will be one of the * identifiers previously communicated to the newChannel callback. */ public void consume(int channelId, ByteBuffer data); /** * Called to notify the consumer of an error that has terminated * playback. */ public void handle(Throwable t); }
1,444
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SocketOptions.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/net/SocketOptions.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 4/3/2015 */ package xpertss.net; import xpertss.nio.NioSession; import java.net.SocketOption; public class SocketOptions { public static <T> boolean set(NioSession session, SocketOption<T> option, T value) { try { session.setOption(option, value); } catch(Exception e) { return false; } return true; } }
396
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
OptionalSocketOptions.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/net/OptionalSocketOptions.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 4/3/2015 */ package xpertss.net; import java.net.SocketOption; public final class OptionalSocketOptions { /** * A socket option which gives an implementation hints as to how it would * like it to timeout read operations. This is heavily implementation * dependent. For example a protocol that uses requests and responses may * use this to timeout a request if it is not received quickly enough. */ public static final SocketOption<Integer> SO_TIMEOUT = new StdSocketOption<Integer>("SO_TIMEOUT", Integer.class); /** * A socket option which dictates the maximum number of pending incoming * connections to queue in the backlog before rejecting them outright. * This would in most cases only apply to an Acceptor. */ public static final SocketOption<Integer> TCP_BACKLOG = new StdSocketOption<Integer>("TCP_BACKLOG", Integer.class); private static class StdSocketOption<T> implements SocketOption<T> { private final String name; private final Class<T> type; StdSocketOption(String name, Class<T> type) { this.name = name; this.type = type; } @Override public String name() { return name; } @Override public Class<T> type() { return type; } @Override public String toString() { return name; } } }
1,392
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SslClientAuth.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/net/SslClientAuth.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 2/26/11 11:25 AM */ package xpertss.net; /** * An enumeration of SSL Client Authentication options. */ public enum SslClientAuth { /** * Request client authentication but proceed if it is not provided. */ Want, /** * Request client authentication and terminate negotiation if it is not * provided. */ Need, /** * Do not request client authentication. */ None }
479
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SSLSocketOptions.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/net/SSLSocketOptions.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 4/3/2015 */ package xpertss.net; import java.net.SocketOption; /** * Defines a set socket options useful for sessions that support SSL. * <p/> * The {@link SocketOption#name name} of each socket option defined by this class * is its field name. */ public final class SSLSocketOptions { private SSLSocketOptions() { } /** * Enable or disable client authentication requests. * <p> * The value of this socket option is an SslClientAuth that dictates whether a server * socket is required to request client authentication during the handshake. * <p> * This is only valid on SSL enabled acceptors. */ public static final SocketOption<SslClientAuth> SSL_CLIENT_AUTH = new TlsSocketOption<SslClientAuth>("SSL_CLIENT_AUTH", SslClientAuth.class); /** * Set the cipher suites SSL sockets will support during negotiation. * <p> * The value of this socket option is a String[] that specifies the SSL cipher suites * the socket will accept during handshaking. This list must be supported by the * SSLContext that was configured for use. Only cipher suites in this list will be * negotiated during the handshake. Peers that do not support any of the cipher * suites in this list will not be able to establish a connection. * <p> * This is only valid on SSL enabled connectors and acceptors. */ public static final SocketOption<String[]> SSL_CIPHER_SUITES = new TlsSocketOption<String[]>("SSL_CIPHER_SUITES", String[].class); /** * Set the protocols SSL sockets will support during negotiation. * <p> * The value of this socket option is a String[] that specifies the protocols the * socket will accept. This list must be supported by the SSLContext that was * configured for use. Protocols in this case means SSLv3, TLSv1, SSLv2 as examples. * Peers that do not support any of the protocols in this list will not be able to * establish a connection. * <p> * This is only valid on SSL enabled connectors and acceptors. */ public static final SocketOption<String[]> SSL_PROTOCOLS = new TlsSocketOption<String[]>("SSL_PROTOCOLS", String[].class); private static class TlsSocketOption<T> implements java.net.SocketOption<T> { private final String name; private final Class<T> type; TlsSocketOption(String name, Class<T> type) { this.name = name; this.type = type; } @Override public String name() { return name; } @Override public Class<T> type() { return type; } @Override public String toString() { return name; } } }
2,699
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspMethod.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspMethod.java
package xpertss.rtsp; import java.net.URI; /** */ public enum RtspMethod { /** * The OPTIONS method represents a request for information about the * communication options available on the request/response chain * identified by the Request-URI. This method allows the client to * determine the options and/or requirements associated with a resource, * or the capabilities of a server, without implying a resource action * or initiating a resource retrieval. */ Options(false), /** * When sent from client to server, ANNOUNCE posts the description of a * presentation or media object identified by the request URL to a * server. When sent from server to client, ANNOUNCE updates the session * description in real-time. */ Announce(true) { @Override public RtspRequest createRequest(URI uri) { throw new UnsupportedOperationException("announce is not yet supported"); } }, /** * The DESCRIBE method retrieves the description of a presentation or * media object identified by the request URL from a server. It may use * the Accept header to specify the description formats that the client * understands. The server responds with a description of the requested * resource. The DESCRIBE reply-response pair constitutes the media * initialization phase of RTSP. */ Describe(false), /** * The SETUP request for a URI specifies the transport mechanism to be * used for the streamed media. */ Setup(false), /** * The PLAY method tells the server to start sending data via the * mechanism specified in SETUP. A client MUST NOT issue a PLAY request * until any outstanding SETUP requests have been acknowledged as * successful. */ Play(false), /** * This method initiates recording a range of media data according to * the presentation description. */ Record(false) { @Override public RtspRequest createRequest(URI uri) { throw new UnsupportedOperationException("record not yet supported"); } }, /** * The PAUSE request causes the stream delivery to be interrupted * (halted) temporarily. If the request URL names a stream, only * playback and recording of that stream is halted. For example, for * audio, this is equivalent to muting. If the request URL names a * presentation or group of streams, delivery of all currently active * streams within the presentation or group is halted. */ Pause(false), /** * The TEARDOWN request stops the stream delivery for the given URI, * freeing the resources associated with it. If the URI is the * presentation URI for this presentation, any RTSP session identifier * associated with the session is no longer valid. Unless all transport * parameters are defined by the session description, a SETUP request * has to be issued before the session can be played again. */ Teardown(false); private boolean supportsEntity; private RtspMethod(boolean supportsEntity) { this.supportsEntity = supportsEntity; } /** * Create a request using the current request method to the default uri * specified when the session was opened. */ public RtspRequest createRequest() { return createRequest(null); } /** * Create a request using the current request method to the specified uri. */ public RtspRequest createRequest(URI uri) { return new RtspRequest(this, uri); } /** * Allows an entity to be sent to the server. */ public boolean supportsEntity() { return supportsEntity; } }
3,685
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspStatus.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspStatus.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/9/11 1:37 PM */ package xpertss.rtsp; public enum RtspStatus { Continue(100, "Continue", false), Ok(200, "Ok", true), Created(201, "Created", true), LowOnStorageSpace(250, "Low on Storage Space", true), MultipleChoices(300, "Multiple Choices", true), MovedPermanently(301, "Moved Permanently", true), MovedTemporarily(302, "Moved Temporarily", true), // HTTP/1.0 SeeOther(303, "See Other", true), NotModified(304, "Not Modified", false), UseProxy(305, "Use Proxy", true), BadRequest(400, "Bad Request", true), Unauthorized(401, "Unauthorized", true), PaymentRequired(402, "Payment Required", true), Forbidden(403, "Forbidden", true), NotFound(404, "Not Found", true), MethodNotAllowed(405, "Method Not Allowed", true), NotAcceptable(406, "Not Acceptable", true), ProxyAuthenticationRequired(407, "Proxy Authentication Required", true), RequestTimeout(408, "Request Timeout", true), Gone(410, "Gone", true), LengthRequired(411, "Length Required", true), PreconditionFailed(412, "Precondition Failed", true), RequestEntityTooLarge(413, "Request Entity Too Large", true), RequestUriTooLong(414, "Request-URI Too Long", true), UnsupportedMediaType(415, "Unsupported Media Type", true), ParameterNotUnderstood(451, "Parameter Not Understood", true), ConferenceNotFound(452, "Conference Not Found", true), NotEnoughBandwidth(453, "Not Enough Bandwidth", true), SessionNotFound(454, "Session Not Found", true), MethodNotValidInThisState(455, "Method Not Valid in This State", true), HeaderFieldNotValid(456, "Header Field Not Valid for Resource", true), InvalidRange(457, "Invalid Range", true), ParameterIsReadOnly(458, "Parameter Is Read-Only", true), UnsupportedTransport(461, "Unsupported Transport", true), DestinationUnreachable(462, "Destination Unreachable", true), InternalServerError(500, "Internal Server Error", true), NotImplemented(501, "Not Implemented", true), BadGateway(502, "Bad Gateway", true), ServiceUnavailable(503, "Service Unavailable", true), GatewayTimeout(504, "Gateway Timeout", true), RTSPVersionNotSupported(505, "RTSP Version Not Supported", true), OptionNotSupported(551, "Option Not Supported", true); // WebDav private int code; private String reason; private boolean allowsEntity; private RtspStatus(int code, String reason, boolean allowsEntity) { this.code = code; this.reason = reason; this.allowsEntity = allowsEntity; } public int getCode() { return code; } public String getReason() { return reason; } public boolean allowsEntity() { return allowsEntity; } @Override public String toString() { return String.format("%d %s", getCode(), getReason()); } public boolean isInformational() { return code >= 100 && code < 200; } public boolean isSuccess() { return code >= 200 && code < 300; } public boolean isRedirection() { return code >= 300 && code < 400; } public boolean isClientError() { return code >= 400 && code < 500; } public boolean isServerError() { return code >= 500; } public static RtspStatus valueOf(int code) { for(RtspStatus status : RtspStatus.values()) { if(status.getCode() == code) return status; } throw new IllegalArgumentException("Non existent status code specified: " + code); } }
3,594
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspHandler.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspHandler.java
package xpertss.rtsp; import java.io.IOException; import java.nio.ByteBuffer; /** * A handler receives events associated with the session. It is responsible * for coordinating the connection, the RTSP handshake, and processing or * forwarding data packets. */ public interface RtspHandler { /** * Called to indicate the connection sequence has completed. */ public void onConnect(RtspSession session); /** * Called to indicate the disconnection sequence has completed. */ public void onClose(RtspSession session); /** * Called to indicate a failure on the session and to indicate * its closure. */ public void onFailure(RtspSession session, Exception e); /** * Called to indicate data read from an interleaved channel. */ public void onData(RtspSession session, int channel, ByteBuffer data) throws IOException; }
886
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspSession.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspSession.java
package xpertss.rtsp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xpertss.io.Buffers; import xpertss.io.NIOUtils; import xpertss.lang.Booleans; import xpertss.lang.Integers; import xpertss.lang.Numbers; import xpertss.lang.Objects; import xpertss.lang.Strings; import xpertss.mime.Headers; import xpertss.nio.Checkable; import xpertss.nio.ConnectHandler; import xpertss.nio.DataHandler; import xpertss.nio.NioAction; import xpertss.nio.NioReader; import xpertss.nio.NioService; import xpertss.nio.NioSession; import xpertss.nio.NioStats; import xpertss.nio.NioWriter; import xpertss.nio.ReadyState; import xpertss.nio.Selectable; import xpertss.utils.UserAgent; import xpertss.utils.Utils; import java.io.EOFException; import java.io.IOException; import java.net.ConnectException; import java.net.ProtocolException; import java.net.SocketAddress; import java.net.SocketOption; import java.net.SocketTimeoutException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import static java.nio.channels.SelectionKey.*; import static xpertss.net.OptionalSocketOptions.SO_TIMEOUT; import static xpertss.nio.ReadyState.*; import static xpertss.rtsp.RtspMethod.*; /** * This RtpSession impl is designed to support a streaming player not a * streaming producer. */ public class RtspSession implements NioSession, DataHandler, ConnectHandler, Checkable { private final ConcurrentMap<String,Object> attributes = new ConcurrentHashMap<>(); private final Deque<ResponseReader> readers = new ConcurrentLinkedDeque<>(); private final Queue<NioWriter> writeQueue = new ConcurrentLinkedQueue<>(); private final ByteBuffer writeBuf = ByteBuffer.allocate(8192); private final ByteBuffer readBuf = ByteBuffer.allocate(8192); private final long createTime = System.currentTimeMillis(); private final ReadManager readManager = new ReadManager(); private final Logger log = LoggerFactory.getLogger(getClass()); private final NioStats write = new NioStats(); private final NioStats read = new NioStats(); private final SocketAddress address; private final SocketChannel channel; private final RtspHandler handler; private final NioService service; private final String userAgent; private final URI target; private volatile ReadyState readyState = Open; private Set<SocketOption<?>> valid; private long timeoutConnection; private NioReader lastReader; private int readTimeout= 0; private int sequence = 0; RtspSession(NioService service, RtspHandler handler, URI target, UserAgent userAgent) { this.service = Objects.notNull(service); this.handler = Objects.notNull(handler); this.target = Objects.notNull(target); this.address = Utils.createSocketAddress(target, 554); this.channel = NIOUtils.openTcpSocket(false); this.userAgent = Objects.notNull(userAgent).toString(); } // Rtsp functions public URI getResource() { return target; } public void execute(RtspRequest request, RtspResponseHandler handler) { Headers headers = request.getHeaders(); headers.setHeader("CSeq", Integer.toString(++sequence)); headers.setIfNotSet("User-Agent", userAgent); writeQueue.offer(request.createWriter(target)); readers.offer(new ResponseReader(handler, request.getMethod())); service.execute(new RegisterAction(OP_WRITE)); } public void write(int channelId, ByteBuffer data) { Numbers.within(0, 255, channelId, "channelId outside range 0 - 255"); Numbers.within(0, 65545, data.remaining(), "data buffer is too large"); writeQueue.offer(new ChannelWriter(data, channelId)); service.execute(new RegisterAction(OP_WRITE)); } // Base session functions /** * Connect this session to the target endpoint. Timeout the attempt after * the given timeout period measured in milliseconds has passed. */ public void connect(int timeout) { if(channel.isOpen()) { readyState = Connecting; this.timeoutConnection = Utils.computeTimeout(timeout); service.execute(new ConnectAction(channel, address)); } } /** * Close the session. */ public void close() { if(channel.isOpen()) { readyState = Closing; service.execute(new CloseAction()); } } @Override public ReadyState getReadyState() { return readyState; } @Override public SocketAddress getRemoteAddress() { return channel.socket().getRemoteSocketAddress(); } @Override public SocketAddress getLocalAddress() { return channel.socket().getLocalSocketAddress(); } @Override public SocketAddress getServiceAddress() { return address; } @Override public <T> RtspSession setOption(SocketOption<T> option, T value) throws IOException { if(option == SO_TIMEOUT) { this.readTimeout = Utils.maxIfZero(Numbers.gte(0, (Integer) value, "timeout must not be negative")); } else if(channel.supportedOptions().contains(option)) { channel.setOption(option, value); } return this; } @Override public <T> T getOption(SocketOption<T> option) throws IOException { if(option == SO_TIMEOUT) { return option.type().cast(this.readTimeout); } else if(channel.supportedOptions().contains(option)) { return channel.getOption(option); } throw new UnsupportedOperationException(); } @Override public Set<SocketOption<?>> supportedOptions() { if(valid == null) { Set<SocketOption<?>> set = new HashSet<>(); set.addAll(channel.supportedOptions()); set.add(SO_TIMEOUT); valid = Collections.unmodifiableSet(set); } return valid; } @Override public long getCreationTime() { return createTime; } @Override public long getLastIoTime() { return Math.max(read.getTime(), write.getTime()); } @Override public long getLastReadTime() { return read.getTime(); } @Override public long getLastWriteTime() { return write.getTime(); } @Override public long getBytesWritten() { return write.getCount(); } @Override public long getBytesRead() { return read.getCount(); } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void setAttribute(String key, Object value) { attributes.put(key, value); } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Set<String> getAttributeKeys() { return Collections.unmodifiableSet(attributes.keySet()); } @Override public void handleConnect() throws IOException { channel.finishConnect(); service.execute(new UnregisterAction(OP_CONNECT)); handler.onConnect(this); readyState = Connected; service.execute(new RegisterAction(OP_READ)); } @Override public void handleRead() throws IOException { int result = channel.read(readBuf); if(result < 0) { throw new EOFException("peer closed connection"); } else { read.record(result); readBuf.flip(); while(readBuf.hasRemaining()) { if(lastReader != null) { if(lastReader.readFrom(readBuf)) { lastReader = null; } } else if(readBuf.get(readBuf.position()) == 0x24) { if(readBuf.remaining() < 4) break; lastReader = new DataReader(); if(lastReader.readFrom(readBuf)) { lastReader = null; } } else { // TODO We need to be prepared for a spontaneous RTSP Response block // while reading channelized data. This might for example be the sever // telling us it is timing out our session due to lack of keep alive. lastReader = readers.poll(); if(lastReader != null) { if (lastReader.readFrom(readBuf)) { lastReader = null; } } else { // We probably should have some sort of ResponseReader here String str = Buffers.toHexString(readBuf, readBuf.position(), Math.min(readBuf.remaining(), 10)); log.error("Unexpected data: " + str); throw new ProtocolException("unexpected read received"); } } } readBuf.compact(); } } @Override public void handleWrite() throws IOException { NioWriter writer = writeQueue.peek(); if(writer != null) { if(writer.writeTo(writeBuf)) writeQueue.remove(); } writeBuf.flip(); if(writeBuf.hasRemaining()) { write.record(channel.write(writeBuf)); } else if(writeQueue.isEmpty()) { service.execute(new UnregisterAction(SelectionKey.OP_WRITE)); } writeBuf.compact(); } @Override public void handleCheckup() throws IOException { int timeout = Utils.maxIfZero(readTimeout); if(readyState == Connecting && System.nanoTime() >= timeoutConnection) { throw new ConnectException("connection timed out"); } else if(readyState == Connected) { ResponseReader reader = readers.peek(); if(reader != null && reader.getWaitingTime() >= timeout) { throw new SocketTimeoutException("response timed out"); } else if(readManager.isReaderActive()) { if(System.currentTimeMillis() - read.getTime() >= timeout) { throw new SocketTimeoutException("read timed out"); } } } } @Override public SelectableChannel getChannel() { return channel; } @Override public void shutdown(Exception ex) { NIOUtils.close(channel); try { if (ex == null) handler.onClose(this); else handler.onFailure(this, ex); } finally { readyState = Closed; } } private class ConnectAction implements NioAction { private final SocketAddress address; private final SocketChannel socket; public ConnectAction(SocketChannel socket, SocketAddress address) { this.socket = Objects.notNull(socket, "socket"); this.address = Objects.notNull(address, "address"); } public void execute(Selector selector) throws IOException { SelectableChannel channel = getChannel(); if(channel != null && channel.isOpen()) { SelectionKey sk = channel.keyFor(selector); if(sk == null) { channel.register(selector, OP_CONNECT, RtspSession.this); socket.connect(address); } } } public Selectable getSelectable() { return RtspSession.this; } } private class CloseAction implements NioAction { public void execute(Selector selector) { SelectableChannel channel = getChannel(); if(channel != null && channel.isOpen()) { shutdown(null); } } public Selectable getSelectable() { return RtspSession.this; } } private class RegisterAction implements NioAction { private int ops; private RegisterAction(int ops) { this.ops = ops; } public void execute(Selector selector) throws IOException { SelectableChannel channel = getChannel(); if(channel != null && channel.isOpen()) { SelectionKey sk = channel.keyFor(selector); if(sk == null) { channel.register(selector, ops, RtspSession.this); } else { sk.interestOps(sk.interestOps() | ops); } } } public Selectable getSelectable() { return RtspSession.this; } } private class UnregisterAction implements NioAction { private int ops; private UnregisterAction(int ops) { this.ops = ops; } public void execute(Selector selector) { SelectableChannel channel = getChannel(); if(channel != null) { SelectionKey sk = channel.keyFor(selector); if(sk != null && sk.isValid()) { sk.interestOps(sk.interestOps() & ~ops); } } } public Selectable getSelectable() { return RtspSession.this; } } private class ChannelWriter implements NioWriter { private ByteBuffer data; private ChannelWriter(ByteBuffer src, int channelId) { data = ByteBuffer.allocate(src.remaining() + 4); data.put((byte)0x24).put((byte)channelId).putShort((short)src.remaining()); Buffers.copyTo(src, data); data.flip(); } @Override public boolean writeTo(ByteBuffer dst) throws IOException { Buffers.copyTo(data, dst); return !(data.hasRemaining()); } } private class ResponseReader implements NioReader { private final CharBuffer lineBuffer = CharBuffer.allocate(2048); // limit header/request line length to 2k private final List<String> lines = new ArrayList<>(); private final long createTime = System.nanoTime(); private final RtspResponseHandler handler; private final RtspMethod method; private RtspResponse response; private ByteBuffer entity; public ResponseReader(RtspResponseHandler handler, RtspMethod method) { this.handler = Objects.notNull(handler); this.method = Objects.notNull(method); } public long getWaitingTime() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - createTime); } @Override public boolean readFrom(ByteBuffer src) throws IOException { if(response == null) response = readResponse(src); if (response != null && readEntity(src)) { if(response.getStatus() == RtspStatus.Ok) readManager.eval(method, response.getHeaders()); handler.onResponse(RtspSession.this, response); return true; } return false; } private RtspResponse readResponse(ByteBuffer src) throws IOException { while(readLine(src, lineBuffer)) { if(lineBuffer.position() == 0) { if(lines.isEmpty()) throw new IOException("premature end of response"); return RtspResponse.create(lines); } else if(lines.size() < 30) { lines.add(Utils.consume(lineBuffer, false)); } else { throw new ProtocolException("max number of lines exceeded"); } } return null; } private boolean readEntity(ByteBuffer src) throws IOException { if(entity == null) { long length = response.getHeaders().getContentLength(); if(length > 8196L) throw new ProtocolException("response entity too large"); if(length <= 0) return true; entity = ByteBuffer.allocate(Integers.safeCast(length)); } Buffers.copyTo(src, entity); if (entity.hasRemaining()) return false; response = response.withEntity(Buffers.newInputStream(entity)); return true; } private boolean readLine(ByteBuffer src, CharBuffer dst) { while(src.hasRemaining()) { char c = (char) (src.get() & 0xff); if(c == '\n') { return true; } else if(c != '\r') { dst.append(c); } } return false; } } private class DataReader implements NioReader { private ByteBuffer data; private int channelId; @Override public boolean readFrom(ByteBuffer src) throws IOException { if(data == null) { if (src.get() != 0x24) throw new ProtocolException("expected interleaved data"); channelId = src.get(); int len = src.getShort(); data = ByteBuffer.allocate(len); } Buffers.copyTo(src, data); if (data.hasRemaining()) return false; data.flip(); handler.onData(RtspSession.this, channelId, data.asReadOnlyBuffer()); return true; } } private class ReadManager { private final ConcurrentMap<String, Boolean> channels = new ConcurrentHashMap<>(); private int count; public void eval(RtspMethod method, Headers response) { if(method == Setup) { String transport = Headers.toString(response.getHeader("Transport")); if(Strings.contains(transport, "interleaved")) { String sessionId = Headers.toString(response.getHeader("Session")); if(sessionId != null) channels.put(sessionId, false); } } else if(method == Play) { String sessionId = Headers.toString(response.getHeader("Session")); if(sessionId != null && channels.replace(sessionId, false, true)) count++; } else if(method == Pause) { String sessionId = Headers.toString(response.getHeader("Session")); if(sessionId != null && channels.replace(sessionId, true, false)) count--; } else if(method == Teardown) { String sessionId = Headers.toString(response.getHeader("Session")); if(Booleans.isTrue(channels.remove(sessionId))) count--; } } public boolean isReaderActive() { return count > 0; } } }
18,616
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspResponse.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspResponse.java
package xpertss.rtsp; import xpertss.lang.Objects; import xpertss.lang.Strings; import xpertss.mime.Headers; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; /** */ public class RtspResponse { private InputStream entity = new ByteArrayInputStream(new byte[0]); private final String reason; private final Headers headers; private final RtspStatus status; RtspResponse(RtspStatus status, String reason, Headers headers) { this.status = Objects.notNull(status); this.reason = Strings.notEmpty(reason, "reason mus tbe defined"); this.headers = Objects.notNull(headers); } public RtspStatus getStatus() { return status; } public String getStatusReason() { return reason; } public Headers getHeaders() { return headers; } public InputStream getEntityBody() { return entity; } public String toString() { return String.format("RTSP/1.0 %d %s", status.getCode(), reason); } RtspResponse withEntity(InputStream entity) { this.entity = Objects.ifNull(entity, this.entity); return this; } static RtspResponse create(List<String> lines) { String[] status = lines.remove(0).split("\\s+", 3); return new RtspResponse(RtspStatus.valueOf(Integer.parseInt(status[1])), status[2], Headers.create(lines)); } }
1,380
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspPlayer.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspPlayer.java
package xpertss.rtsp; import xpertss.SourceException; import xpertss.lang.Numbers; import xpertss.lang.Objects; import xpertss.lang.Range; import xpertss.lang.Strings; import xpertss.media.MediaChannel; import xpertss.media.MediaConsumer; import xpertss.mime.Header; import xpertss.mime.HeaderValue; import xpertss.mime.Headers; import xpertss.net.SocketOptions; import xpertss.sdp.MediaDescription; import xpertss.sdp.SessionDescription; import xpertss.sdp.SessionParser; import xpertss.utils.SafeProxy; import xpertss.utils.Utils; import java.io.IOException; import java.net.ProtocolException; import java.net.URI; import java.nio.ByteBuffer; import java.util.TreeSet; import static xpertss.net.OptionalSocketOptions.SO_TIMEOUT; import static xpertss.rtsp.RtspMethod.Describe; import static xpertss.rtsp.RtspMethod.Pause; import static xpertss.rtsp.RtspMethod.Play; import static xpertss.rtsp.RtspMethod.Setup; import static xpertss.rtsp.RtspMethod.Teardown; import static xpertss.rtsp.RtspState.*; import static xpertss.rtsp.RtspStatus.*; public class RtspPlayer { private final TreeSet<MediaChannel> channels = new TreeSet<>(); private final MediaConsumer consumer; private final RtspClient client; private volatile RtspState state = Stopped; private RtspSession session; private int connectTimeout; private int readTimeout; private URI base; public RtspPlayer(RtspClient client, MediaConsumer consumer) { this.client = Objects.notNull(client); this.consumer = SafeProxy.newInstance(MediaConsumer.class, Objects.notNull(consumer)); } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = Numbers.gte(0, connectTimeout, "connectTimeout must not be negative"); } public int getConnectTimeout() { return connectTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = Numbers.gte(0, readTimeout, "readTimeout must not be negative"); } public int getReadTimeout() { return readTimeout; } public SessionDescription getSessionDescription() { return getSessionDescription(session); } public RtspState getState() { return state; } /** * Connect to the remote media server and setup the media streams. */ public void start(URI uri) { if(state == Stopped) { state = Activating; session = client.open(new RtspPlaybackHandler(), uri); SocketOptions.set(session, SO_TIMEOUT, readTimeout); session.connect(connectTimeout); } } /** * Play the configured media streams. */ public void play() { if(state == Paused) { state = Activating; RtspRequest request = Play.createRequest(base); Headers headers = request.getHeaders(); setSessionId(session, headers); headers.setHeader("Range", "npt=0.000-"); session.execute(request, new DefaultResponseHandler() { @Override public void onOkResponse(RtspSession session, RtspResponse response) throws IOException { state = Active; } }); } } /** * Pause the configured media streams. */ public void pause() { if(state == Active) { state = Pausing; RtspRequest request = Pause.createRequest(base); Headers headers = request.getHeaders(); setSessionId(session, headers); session.execute(request, new DefaultResponseHandler() { @Override public void onOkResponse(RtspSession session, RtspResponse response) throws IOException { state = Paused; } }); } } /** * Stop playback, tear down the configured streams and disconnect. */ public void stop() { if(!Objects.isOneOf(state, Stopped, Stopping)) { state = Stopping; RtspRequest request = Teardown.createRequest(base); Headers headers = request.getHeaders(); setSessionId(session, headers); headers.setHeader("Connection", "close"); session.execute(request, new DefaultResponseHandler() { @Override public void onOkResponse(RtspSession session, RtspResponse response) throws IOException { consumer.destroyChannels(); session.close(); } }); session = null; } } private static final String TRANSPORT = "RTP/AVP/TCP;unicast;interleaved=%d-%d"; private void setupChannel(RtspSession session) throws IOException { final MediaChannel channel = channels.pollFirst(); if(channel == null) { startPlayback(session); } else { String control = channel.getControl(); URI target = (Strings.isEmpty(control)) ? base : base.resolve(control); RtspRequest request = Setup.createRequest(target); Headers headers = request.getHeaders(); final Range<Integer> channels = channel.getChannels(); headers.setHeader("Transport", String.format(TRANSPORT, channels.getLower(), channels.getUpper())); setSessionId(session, headers); session.execute(request, new DefaultResponseHandler() { @Override public void onOkResponse(RtspSession session, RtspResponse response) throws IOException { consumer.createChannel(channel); session.setAttribute("session.id", Utils.getBaseHeader(response, "Session")); setupChannel(session); } }); } } private void startPlayback(RtspSession session) throws IOException { RtspRequest request = Play.createRequest(base); Headers headers = request.getHeaders(); setSessionId(session, headers); headers.setHeader("Range", "npt=0.000-"); session.execute(request, new DefaultResponseHandler() { @Override public void onOkResponse(RtspSession session, RtspResponse response) throws IOException { state = Active; } }); } private static void setSessionId(RtspSession session, Headers headers) { String sessionId = (String) session.getAttribute("session.id"); if(!Strings.isEmpty(sessionId)) headers.setHeader("Session", sessionId); } private static SessionDescription getSessionDescription(RtspSession session) { return (session == null) ? null : (SessionDescription) session.getAttribute("session.description"); } private class RtspPlaybackHandler implements RtspHandler { @Override public void onConnect(RtspSession session) { RtspRequest request = Describe.createRequest(); Headers headers = request.getHeaders(); headers.setHeader("Accept", "application/sdp"); session.execute(request, new DefaultResponseHandler() { @Override public void onOkResponse(RtspSession session, RtspResponse response) throws IOException { Headers headers = response.getHeaders(); String baseUri = Headers.toString(headers.getHeader("Content-Base")); base = (Strings.isEmpty(baseUri)) ? session.getResource() : URI.create(baseUri); String contentType = Headers.toString(headers.getHeader("Content-Type")); if (Strings.equal("application/sdp", contentType)) { SessionParser parser = new SessionParser(); SessionDescription sessionDescription = parser.parse(response.getEntityBody()); session.setAttribute("session.description", sessionDescription); MediaDescription[] medias = consumer.select(sessionDescription); if(Objects.isEmpty(medias)) throw new ProtocolException("missing media resource"); channels.clear(); for(int i = 0; i < medias.length; i++) { channels.add(new MediaChannel(medias[i], new Range<>(i * 2, i * 2 + 1))); } setupChannel(session); } else { throw new ProtocolException("unexpected entity type received"); } } }); } @Override public void onClose(RtspSession session) { state = Stopped; } @Override public void onFailure(RtspSession session, Exception e) { state = Stopped; consumer.handle(e); } @Override public void onData(RtspSession session, int channelId, ByteBuffer data) throws IOException { consumer.consume(channelId, data); } } private static class DefaultResponseHandler implements RtspResponseHandler { @Override public void onResponse(RtspSession session, RtspResponse response) throws IOException { if(response.getStatus() != Ok) throw new SourceException(response.getStatus().getCode(), response.getStatusReason()); onOkResponse(session, response); } protected void onOkResponse(RtspSession session, RtspResponse response) throws IOException { } } }
9,326
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspRequest.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspRequest.java
package xpertss.rtsp; import xpertss.io.Buffers; import xpertss.lang.Objects; import xpertss.lang.Strings; import xpertss.mime.Headers; import xpertss.nio.NioWriter; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import static xpertss.io.Charsets.*; import static xpertss.rtsp.RtspMethod.*; /** */ public class RtspRequest { private final Headers headers = new Headers(Headers.Type.Rtsp); private final RtspMethod method; private final URI target; RtspRequest(RtspMethod method, URI target) { if(!Objects.isOneOf(method, Options, Describe, Setup, Play, Pause, Teardown)) throw new UnsupportedOperationException("method not yet supported"); this.method = Objects.notNull(method, "method"); this.target = target; } public RtspMethod getMethod() { return method; } public Headers getHeaders() { return headers; } NioWriter createWriter(URI uri) { // TODO Check that target and uri have same authority return new RequestWriter(uri); } private class RequestWriter implements NioWriter { private final URI uri; private ByteBuffer encoded; private RequestWriter(URI uri) { this.uri = Objects.notNull(uri); } @Override public boolean writeTo(ByteBuffer dst) throws IOException { if(encoded == null) encoded = encode(); Buffers.copyTo(encoded, dst); return !encoded.hasRemaining(); } private ByteBuffer encode() throws IOException { StringBuilder builder = new StringBuilder(); builder.append(Strings.toUpper(method.name())).append(" "); builder.append((target == null) ? uri : target); builder.append(" ").append("RTSP/1.0").append("\r\n"); builder.append(headers); builder.append("\r\n"); return US_ASCII.encode(builder.toString()); } } }
1,963
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspState.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspState.java
package xpertss.rtsp; /** * An enumeration of Rtsp States. */ public enum RtspState { /** * The player or producer is not connected. */ Stopped, /** * The player or producer are in the process of inactivating */ Pausing, /** * The player or producer is connected and setup but not * actively playing or recording media. */ Paused, /** * The player or producer are in the process of starting * playback or recording. */ Activating, /** * The player or producer are actively playing or recording * media content. */ Active, /** * The player or producer is in the process of tearing down * the session and disconnecting. */ Stopping }
742
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspClient.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspClient.java
package xpertss.rtsp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xpertss.lang.Objects; import xpertss.nio.NioProvider; import xpertss.nio.NioReactor; import xpertss.threads.Threads; import xpertss.util.Version; import xpertss.utils.UserAgent; import java.net.URI; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** */ public class RtspClient { private Logger log = LoggerFactory.getLogger(getClass()); // Product name OS/version Java/version private final NioReactor reactor; private ThreadFactory factory; private UserAgent userAgent; public RtspClient() { this.reactor = new NioReactor(new RtspNioProvider()); } /** * Call this to have a configured (and attached to the reactor service) * session. It will not be connected initially. * * @throws NullPointerException if uri is {@code null} * @throws IllegalArgumentException if the uri is invalid */ public RtspSession open(RtspHandler handler, URI uri) { if(!Objects.notNull(uri).getScheme().equals("rtsp")) throw new IllegalArgumentException("only supports rtsp urls"); return new RtspSession(reactor, handler, uri, getUserAgent()); } /** * Set the UserAgent string this client will submit to servers with each * request. */ public void setUserAgent(UserAgent userAgent) { this.userAgent = Objects.notNull(userAgent, "userAgent"); } /** * Get the UserAgent string this client is submitting to servers with each * request. */ public UserAgent getUserAgent() { return (userAgent == null) ? UserAgent.create("Aries", new Version(1,0)) : userAgent; } /** * Set the thread factory this HttpServer will use to obtain threads from. * <p> * It is advised that the thread factory should create daemon threads with * a priority slightly above NORM_PRIORITY. * * @param factory The thread factory this server should obtain threads from * @throws IllegalStateException if this is called on an active server */ public void setThreadFactory(ThreadFactory factory) { if(isActive()) throw new IllegalStateException("server is active"); this.factory = factory; } /** * Returns the thread factory this HttpServer will obtain threads from. */ public ThreadFactory getThreadFactory() { return factory; } /** * Returns true if this server is active, false otherwise. */ public boolean isActive() { return reactor.isActive(); } /** * Waits for this server to shutdown. */ public void await() { reactor.await(); } /** * Wait for the specified amount of time for this server to shutdown. This * will return false if this returned because it timed out before the server * completely shutdown, otherwise it will return true. * * @param timeout the time to wait * @param unit the unit the timeout value is measured with * @return True if the server shutdown within the allotted time */ public boolean await(long timeout, TimeUnit unit) { return reactor.await(timeout, unit); } private class RtspNioProvider implements NioProvider { public Thread newThread(Runnable r) { ThreadFactory factory = getThreadFactory(); if(factory == null) { factory = Threads.newThreadFactory("RtspReactor", Thread.NORM_PRIORITY + 1, true); } return factory.newThread(r); } public void serviceException(Exception error) { log.warn("NIO Error reported", error); } } }
3,708
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspResponseHandler.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspResponseHandler.java
package xpertss.rtsp; import java.io.IOException; /** */ public interface RtspResponseHandler { public void onResponse(RtspSession session, RtspResponse response) throws IOException; }
193
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspException.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/rtsp/RtspException.java
package xpertss.rtsp; import java.net.ProtocolException; /** * */ public class RtspException extends ProtocolException { public enum Type { Url, Network, Source, Carrier, Audio, Video, Authentication } }
223
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
UserAgent.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/utils/UserAgent.java
package xpertss.utils; import xpertss.lang.Objects; import xpertss.lang.Strings; import xpertss.util.Config; import xpertss.util.Platform; import xpertss.util.Version; import java.util.BitSet; /** * The UserAgent class encapsulates the process creating a UserAgent string from * the underlying platform. * <p/> * A typical UserAgent string would look something like this: * <pre> * MMP/1.0 (Windows/6.1; amd64; Java/1.7) XpertRTSP/1.0 * </pre> * In the above example the actual user agent application is identified by MMP/1.0. * The contents in the parenthesis are the OS name/version followed by the CPU * Architecture followed by the version of Java the client is running on. Finally, * the last portion represents this RTSP library and version. * <p/> * This class allows the user some control over the user agent sent to the server * with each request. For full control you may set the User-Agent header yourself * for each call or you may extend this class and override the {@link #toString} * method.. */ public class UserAgent { private final BitSet bitset = new BitSet(3); private String appName; private Version appVersion; /** * Accessible zero argument constructor for class wishing to extend and * override this implementation. */ protected UserAgent() { } private UserAgent(String appName, Version appVersion) { this.appName = Strings.notEmpty(appName, "appName must be defined"); this.appVersion = Objects.notNull(appVersion, "appVersion"); } /** * Include the name of this RTSP library and its version in the user * agent header sent to the server with each request. */ public void includeLibrary(boolean value) { bitset.set(0, !value); } /** * Returns {@code true} if the library portion is included in the user * agent string sent to the server with each request. */ public boolean isLibraryIncluded() { return !bitset.get(0); } /** * Include the version of Java this library is running on in the user * agent header sent to the server with each request. */ public void includeJava(boolean value) { bitset.set(1, !value); } /** * Returns {@code true} if the Java portion is included in the user * agent string sent to the server with each request. */ public boolean isJavaIncluded() { return !bitset.get(1); } /** * Include the type of CPU this user agent is running on in the user * agent header sent to the server with each request. */ public void includeCpu(boolean value) { bitset.set(2, !value); } /** * Returns {@code true} if the cpu portion is included in the user * agent string sent to the server with each request. */ public boolean isCpuIncluded() { return !bitset.get(2); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format("%s/%s", appName, appVersion)); String osName = System.getProperty("os.name").split("\\s+")[0]; Version osVersion = Platform.osVersion(); builder.append(String.format(" (%s/%s", osName, osVersion)); if(!bitset.get(2)) { String osArch = System.getProperty("os.arch"); builder.append(String.format("; %s", osArch)); } if(!bitset.get(1)) { Version vmVersion = Platform.javaVersion(); builder.append(String.format("; Java/%s", vmVersion)); } builder.append(")"); if(!bitset.get(0)) { Config config = Config.load("version.properties", false); String libVersion = config.getProperty("version"); builder.append(String.format(" XpertRTSP/%s", libVersion)); } return builder.toString(); } /** * Create a default UserAgent object with the specified application * name and version. * * @param appName The application name * @param appVersion The application version */ public static UserAgent create(String appName, Version appVersion) { return new UserAgent(appName, appVersion); } }
4,157
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SafeProxy.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/utils/SafeProxy.java
/** * Copyright 2015 XpertSoftware * * Created By: cfloersch * Date: 4/17/2015 */ package xpertss.utils; import xpertss.threads.Threads; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * This class will wrap a given class and proxy calls to it catching any runtime * exceptions that may be thrown. Those exceptions will be sent to the calling * thread's uncaught exception handler and null will be returned. * <p/> * This is principally to be used with classes who's members do not return values * such as event listeners. * * @param <T> */ public class SafeProxy<T> implements InvocationHandler { /** * Construct an instance of the SafeDispatcher compatible with the given listener class. */ public static <T> T newInstance(Class<T> proxiedClass, T proxied) { return proxiedClass.cast(Proxy.newProxyInstance(proxiedClass.getClassLoader(), new Class[] { proxiedClass }, new SafeProxy<T>(proxied))); } private final T proxied; private SafeProxy(T proxied) { this.proxied = proxied; } @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { if ("equals".equals(method.getName())) { return (args[0] == proxy); } else if("hashCode".equals(method.getName())) { return hashCode(); } else if("toString".equals(method.getName())) { return toString(); } else { try { return method.invoke(proxied, args); } catch(InvocationTargetException e) { Threads.report(e.getTargetException()); } catch(Throwable t) { Threads.report(t); } return null; } } @Override public String toString() { return "SafeProxy<" + proxied.toString() + ">"; } }
2,044
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
Utils.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/utils/Utils.java
package xpertss.utils; import xpertss.lang.Integers; import xpertss.lang.Numbers; import xpertss.lang.Strings; import xpertss.mime.Header; import xpertss.mime.Headers; import xpertss.rtsp.RtspResponse; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.concurrent.TimeUnit; /** * Useful utilities */ public class Utils { /** * Creates and returns an {@link InetSocketAddress} that represents the authority * of the given {@link java.net.URI}. If the {@link java.net.URI} does not define * a port then the specified default port is used instead. * * @throws NullPointerException if uri is {@code null} * @throws IllegalArgumentException if the port is outside the range 1 - 65545 */ public static SocketAddress createSocketAddress(URI uri, int defPort) { String authority = uri.getAuthority(); if(Strings.isEmpty(authority)) throw new IllegalArgumentException("uri does not define an authority"); String[] parts = authority.split(":"); int port = defPort; if(parts.length == 2) { port = Integers.parse(parts[1], defPort); Numbers.within(1, 65545, port, String.format("%d is an invalid port", port)); } return new InetSocketAddress(parts[0], port); } public static <T> T get(T[] items, int index) { if(items == null || index < 0) return null; return (items.length > index) ? items[index] : null; } public static String trimAndClear(StringBuilder buf) { return getAndClear(buf).trim(); } public static String getAndClear(StringBuilder buf) { try { return buf.toString(); } finally { buf.setLength(0); } } public static long computeTimeout(int millis) { if(millis == 0) millis = 60000; // default timeout of 60 seconds return System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis); } public static String consume(CharBuffer buf, boolean trim) { buf.flip(); int offset = 0; int end = buf.limit(); if(trim) { while(offset < end && buf.get(offset) == ' ') offset++; while(end > offset && buf.get(end - 1) == ' ') end--; } char[] result = new char[end-offset]; buf.position(offset); buf.get(result).clear(); return new String(result); } public static boolean isWhiteSpace(char c) { return (c == '\t' || c == '\r' || c == '\n' || c == ' '); } public static int maxIfZero(int value) { return (value == 0) ? Integer.MAX_VALUE : value; } public static String getHeader(RtspResponse response, String name) { return Headers.toString(response.getHeaders().getHeader(name)); } public static String getBaseHeader(RtspResponse response, String name) { Header header = response.getHeaders().getHeader(name); return header.getValue(0).getValue(); } }
3,045
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
MimeFlavor.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/MimeFlavor.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 4/7/11 12:19 PM */ package xpertss.mime; import org.w3c.dom.Document; import xpertss.lang.Objects; import java.io.File; import java.io.InputStream; import java.io.Reader; public class MimeFlavor<T> { public static final MimeFlavor<String> stringFlavor = new MimeFlavor<String>(String.class); public static final MimeFlavor<Reader> textFlavor = new MimeFlavor<Reader>(Reader.class); public static final MimeFlavor<Document> domFlavor = new MimeFlavor<Document>(Document.class); public static final MimeFlavor<String> jsonFlavor = new MimeFlavor<String>(String.class); // TODO Is there a better type (application/json) public static final MimeFlavor<InputStream> byteFlavor = new MimeFlavor<InputStream>(InputStream.class); public static final MimeFlavor<File> fileFlavor = new MimeFlavor<File>(File.class); private Class<T> cls; public MimeFlavor(Class<T> cls) { this.cls = Objects.notNull(cls, "cls"); } public Class<T> getRepresentation() { return cls; } public boolean equals(Object o) { if(o instanceof MimeFlavor) { MimeFlavor f = (MimeFlavor) o; return cls.equals(f); } return false; } public int hashCode() { return cls.hashCode(); } public String toString() { return "MimeFlavor<" + cls.getSimpleName() + ">"; } }
1,425
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
Header.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/Header.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/15/11 1:08 PM */ package xpertss.mime; /** * Represents a Mime header field. * <p/> * The Mime header fields follow the format defined by Section 3.1 of RFC 822. * Each header field consists of a name followed by a colon (":") and the field * value. Field names are case-insensitive. The field value MAY be preceded by * any amount of LWS, though a single SP is preferred. * *<pre> * message-header = field-name ":" [ field-value ] * field-name = token * field-value = *( field-content | LWS ) * field-content = &lt;the OCTETs making up the field-value * and consisting of either *TEXT or combinations * of token, separators, and quoted-string&gt; *</pre><p> * A Header may represent a single value or multiple values. Each value may be * either named or simple. Additionally, each value may or may not have associated * parameters which themselves may be named or not. This interface attempts to * define a means to access all of the various header parts. */ public interface Header { /** * Http defines four types of headers. All headers not specifically * defined to be general, request, or response are treated as entity * headers. */ public enum Type { /** * A general header is one that may be included in either the request or * response and is applied to the overall message itself. */ General, /** * A request header is applied only to impl requests and applies to the * message overall. */ Request, /** * A response header is applied only to impl responses and applies to the * message overall. */ Response, /** * An entity header defines the entity contained within the message. */ Entity, /** * A raw header is any header for which a defined parser was not found. * These are typically non-standard headers and will always return an * unparsed raw string when getValue is called. */ Raw } /** * Returns the header name as a String. */ public String getName(); /** * Returns a fully formatted value line including all values and their * associated parameters. This method provides an easier means of access * to simple values. */ public String getValue(); /** * Returns the header type this header represents. */ public Type getType(); /** * Returns the number of values this header contains. */ public int size(); /** * Returns the header value at the specified index. */ public HeaderValue getValue(int index); /** * Returns the specified named header value if it exists. */ public HeaderValue getValue(String name); /** * Return a formatted string representation of this header and its values * and parameters. */ public String toString(); }
3,028
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
Headers.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/Headers.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 4/6/11 2:50 PM */ package xpertss.mime; import xpertss.function.Predicates; import xpertss.lang.Integers; import xpertss.lang.Objects; import xpertss.lang.Strings; import xpertss.utils.Utils; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.NoSuchElementException; import java.util.function.Predicate; /** * Headers is a utility class that manages RFC822 style headers. * <p/> * <hr> <strong>A note on RFC822 and MIME headers</strong><p> * <p/> * RFC822 and MIME header fields <strong>must</strong> contain only * US-ASCII characters. If a header contains non US-ASCII characters, * it must be encoded as per the rules in RFC 2047. Callers of the * <code>setHeader</code> and <code>addHeader</code> methods are * responsible for enforcing the MIME requirements for the specified * header. */ public class Headers { public enum Type { Http, Rtsp, Mail } private List<Header> headers; private boolean readOnly; public Headers(Type type) { headers = new ArrayList<Header>(); if (Type.Mail == type) { headers.add(new PositionHeader("Return-Path")); headers.add(new PositionHeader("Received")); headers.add(new PositionHeader("Message-ID")); headers.add(new PositionHeader("Resent-Date")); headers.add(new PositionHeader("Date")); headers.add(new PositionHeader("Resent-From")); headers.add(new PositionHeader("From")); headers.add(new PositionHeader("Sender")); headers.add(new PositionHeader("Reply-To")); headers.add(new PositionHeader("To")); headers.add(new PositionHeader("Subject")); headers.add(new PositionHeader("Cc")); headers.add(new PositionHeader("In-Reply-To")); headers.add(new PositionHeader("Resent-Message-ID")); headers.add(new PositionHeader("Errors-To")); headers.add(new PositionHeader("Mime-Version")); headers.add(new PositionHeader("Content-Type")); headers.add(new PositionHeader("Content-Transfer-Encoding")); headers.add(new PositionHeader("Content-MD5")); headers.add(new PositionHeader(":")); headers.add(new PositionHeader("Content-Length")); headers.add(new PositionHeader("Status")); } else if(type == Type.Http) { headers.add(new PositionHeader("Host")); headers.add(new PositionHeader("User-Agent")); headers.add(new PositionHeader("Date")); headers.add(new PositionHeader("Accept")); headers.add(new PositionHeader("Accept-Language")); headers.add(new PositionHeader("Accept-Encoding")); headers.add(new PositionHeader("Accept-Charset")); headers.add(new PositionHeader("Authorization")); headers.add(new PositionHeader("Proxy-Authorization")); headers.add(new PositionHeader("Referer")); headers.add(new PositionHeader("If-Modified-Since")); headers.add(new PositionHeader("If-None-Match")); headers.add(new PositionHeader("Transfer-Encoding")); headers.add(new PositionHeader("Content-Disposition")); headers.add(new PositionHeader("Content-Type")); headers.add(new PositionHeader("Content-Location")); headers.add(new PositionHeader("Content-MD5")); headers.add(new PositionHeader("Content-Language")); headers.add(new PositionHeader("Content-Encoding")); headers.add(new PositionHeader("Content-Length")); headers.add(new PositionHeader(":")); headers.add(new PositionHeader("Proxy-Connection")); headers.add(new PositionHeader("Connection")); headers.add(new PositionHeader("Pragma")); headers.add(new PositionHeader("Cache-Control")); } else if(type == Type.Rtsp) { headers.add(new PositionHeader("Server")); headers.add(new PositionHeader("CSeq")); headers.add(new PositionHeader("User-Agent")); headers.add(new PositionHeader("Date")); headers.add(new PositionHeader("Expires")); headers.add(new PositionHeader("Accept")); headers.add(new PositionHeader("Accept-Language")); headers.add(new PositionHeader("Accept-Encoding")); headers.add(new PositionHeader("Authorization")); headers.add(new PositionHeader("Referer")); headers.add(new PositionHeader("If-Modified-Since")); headers.add(new PositionHeader("If-Match")); headers.add(new PositionHeader("Last-Modified")); headers.add(new PositionHeader("Transport")); headers.add(new PositionHeader("Session")); headers.add(new PositionHeader("RTP-Info")); headers.add(new PositionHeader("Location")); headers.add(new PositionHeader("Range")); headers.add(new PositionHeader("Content-Base")); headers.add(new PositionHeader("Content-Type")); headers.add(new PositionHeader("Content-Location")); headers.add(new PositionHeader("Content-Language")); headers.add(new PositionHeader("Content-Encoding")); headers.add(new PositionHeader("Content-Length")); headers.add(new PositionHeader(":")); headers.add(new PositionHeader("Connection")); headers.add(new PositionHeader("Cache-Control")); } } private Headers(List<Header> headers) { this.headers = Objects.notNull(headers); this.readOnly = true; } /** * Return an enumeration of the headers in their predefined order. */ public Enumeration<Header> headers() { Predicate<Object> filter = Predicates.instanceOf(PositionHeader.class); return new FilteringEnumeration(headers, filter); } public boolean contains(String name) { return getHeader(name) != null; } /** * This will return the first header with the given name. */ public Header getHeader(String name) { for(Header header : headers) { if(Strings.equalIgnoreCase(header.getName(), name)) { if(!(header instanceof PositionHeader)) return header; } } return null; } /** * This will return all the header with the given name in the order they * were found. */ public Header[] getHeaders(String name) { List<Header> results = new ArrayList<Header>(); for(Header header : headers) { if(Strings.equalIgnoreCase(header.getName(), name)) { if(!(header instanceof PositionHeader)) results.add(header); } } return results.toArray(new Header[results.size()]); } /** * This will add the named header to the end of the set of existing * headers with the same name or its default position within the set * if no header with the same name pre-exists. * * @throws MalformedException If the header name or value are malformed */ public void addHeader(String name, String value) throws MalformedException { if(readOnly) throw new IllegalStateException("src are readonly"); Header newHeader = HeaderParser.parse(name, value); int pos = 0; for(int i = headers.size() - 1; i >= 0; i--) { Header header = headers.get(i); if(Strings.equalIgnoreCase(header.getName(), name)) { headers.add(i + 1, newHeader); return; } else if(header.getName().equals(":")) { pos = i; } } headers.add(pos + 1, newHeader); } /** * This will add the named header to its default position within the set * removing any previously existing headers with the same name. * * @throws MalformedException If the header name or value are malformed */ public void setHeader(String name, String value) throws MalformedException { if(readOnly) throw new IllegalStateException("src are readonly"); Header newHeader = HeaderParser.parse(name, value); int pos = 0; for(int i = headers.size() - 1; i >= 0; i--) { Header header = headers.get(i); if(Strings.equalIgnoreCase(header.getName(), name)) { if(header instanceof PositionHeader) { headers.add(i + 1, newHeader); return; } else { headers.remove(i); } } else if(Strings.equal(header.getName(), ":")) { pos = i; } } headers.add(pos + 1, newHeader); } /** * This will add the named header to its default position within the set * if and only if there are no existing headers with the given name. * * @throws MalformedException If the header name or value are malformed */ public boolean setIfNotSet(String name, String value) throws MalformedException { if(readOnly) throw new IllegalStateException("src are readonly"); Header newHeader = HeaderParser.parse(name, value); int pos = 0; for(int i = headers.size() - 1; i >= 0; i--) { Header header = headers.get(i); if(Strings.equalIgnoreCase(header.getName(), name)) { if(header instanceof PositionHeader) { headers.add(i + 1, newHeader); return true; } else{ return false; } } else if(Strings.equal(header.getName(), ":")) { pos = i; } } headers.add(pos + 1, newHeader); return true; } /** * This will remove all src with the given name returning the number * removed. */ public int remove(String name) { int count = 0; for(int i = headers.size() - 1; i >= 0; i--) { Header header = headers.get(i); if(Strings.equalIgnoreCase(header.getName(), name)) { if(header instanceof PositionHeader) { return count; } else { headers.remove(i); count++; } } else if(count > 0) { return count; } } return count; } // Helpers /** * Helper method to retrieve the Content-Length header value as a long. * <p/> * This will return -1 if the Content-Header header is not defined. */ public long getContentLength() { Header contentLength = getHeader("Content-Length"); return Integers.parse(toString(contentLength), -1); } @Override public boolean equals(Object obj) { if(obj instanceof Headers) { Headers o = (Headers) obj; return Objects.equal(headers, o.headers); } return false; } @Override public int hashCode() { return Objects.hash(headers); } /** * Returns the set of headers with one header per line */ @Override public String toString() { StringBuilder builder = new StringBuilder(); for(Enumeration<Header> e = headers(); e.hasMoreElements(); ) { builder.append(e.nextElement()).append("\r\n"); } return builder.toString(); } public static Headers create(List<String> raw) { List<Header> headers = new ArrayList<Header>(); StringBuilder header = new StringBuilder(); for(int i = raw.size() - 1; i >= 0; i--) { header.insert(0, raw.get(i)); if(!Utils.isWhiteSpace(header.charAt(0))) { headers.add(0, HeaderParser.parse(Utils.getAndClear(header))); } } return new Headers(headers); } public static String toString(Header header) { return (header == null) ? null : header.getValue(); } private static class FilteringEnumeration implements Enumeration<Header> { private final List<Header> src; private final Predicate<Object> filter; private Header next; private int i; private FilteringEnumeration(List<Header> headers, Predicate<Object> filter) { this.src = Objects.notNull(headers); this.filter = Objects.notNull(filter); this.next = findNext(); } @Override public boolean hasMoreElements() { return next != null; } @Override public Header nextElement() { if(next == null) { throw new NoSuchElementException("enumeration exhausted"); } Header result = next; next = findNext(); return result; } private Header findNext() { while(i < src.size()) { Header header = src.get(i++); if(!filter.test(header)) return header; } return null; } } private static class PositionHeader implements Header { private final String name; private PositionHeader(String name) { this.name = Objects.notNull(name); } @Override public String getName() { return name; } @Override public String getValue() { return null; } @Override public Type getType() { return Type.Raw; } @Override public int size() { return 0; } @Override public HeaderValue getValue(int index) { return null; } @Override public HeaderValue getValue(String name) { return null; } } }
13,465
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HeaderTokenizer.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/HeaderTokenizer.java
/* * Copyright XpertSoftware All rights reserved. * * Created on Mar 6, 2006 */ package xpertss.mime; import xpertss.lang.Objects; /** * This class tokenizes RFC822 and MIME headers into the basic symbols specified * by RFC822 and MIME. * <p/> * This class handles folded headers (ie headers with embedded CRLF SPACE sequences). * The folds are removed in the returned tokens. * * @author cfloersch */ public class HeaderTokenizer { /** * The Token class represents tokens returned by the * HeaderTokenizer. */ public static class Token { private int type; private CharSequence value; /** * Token type indicating an ATOM. */ public static final int ATOM = -1; /** * Token type indicating a quoted string. The value * field contains the string without the quotes. */ public static final int QUOTEDSTRING = -2; /** * Token type indicating a comment. The value field * contains the comment string without the comment * start and end symbols. */ public static final int COMMENT = -3; /** * Token type indicating linear whitespace. */ public static final int LWS = -4; /** * Token type indicating end of input. */ public static final int EOF = -5; /** * Constructor. * * @param type Token type * @param value Token value */ public Token(int type, CharSequence value) { this.type = type; this.value = value; } /** * Return the type of the token. If the token represents a * delimiter or a control character, the type is that character * itself, converted to an integer. Otherwise, it's value is * one of the following: * <ul> * <li><code>ATOM</code> A sequence of ASCII characters * delimited by either SPACE, CTL, "(", <"> or the * specified SPECIALS * <li><code>QUOTEDSTRING</code> A sequence of ASCII characters * within quotes * <li><code>COMMENT</code> A sequence of ASCII characters * within "(" and ")". * <li><code>EOF</code> End of header * </ul> */ public int getType() { return type; } /** * Returns the value of the token just read. When the current * token is a quoted string, this field contains the body of the * string, without the quotes. When the current token is a comment, * this field contains the body of the comment. * * @return token value */ public String getValue() { return value.toString(); } public boolean equals(Object obj) { if(obj instanceof Token) { Token other = (Token) obj; return type == other.type && eq(value, other.value); } return false; } public int hashCode() { int valHash = (value != null) ? value.hashCode() : 0; return type ^ valHash; } private boolean eq(Object one, Object two) { return (one == null) ? two == null : one.equals(two); } } private CharSequence string; // the string to be tokenized private String delimiters; // delimiter string private int currentPos; // current parse position private int maxPos; // string length private int nextPos; // track start of next Token for next() private int peekPos; // track start of next Token for peek() /** * RFC822 specials */ public final static String RFC822 = "()<>@,;:\\\"\t .[]"; /** * MIME specials */ public final static String MIME = "()<>@,;:\\\"\t []/?="; // The EOF Token private final static Token EOFToken = new Token(Token.EOF, null); /** * Constructor that takes a rfc822 style header. * * @param header The rfc822 header to be tokenized * @param delimiters Set of delimiter characters * to be used to delimit ATOMS. These * are usually <code>RFC822</code> or * <code>MIME</code> */ public HeaderTokenizer(CharSequence header, String delimiters) { string = Objects.ifNull(header, ""); this.delimiters = Objects.ifNull(delimiters, RFC822); currentPos = nextPos = peekPos = 0; maxPos = string.length(); } /** * Constructor. The RFC822 defined delimiters - RFC822 - are * used to delimit ATOMS. Also comments are skipped and not * returned as tokens */ public HeaderTokenizer(String header) { this(header, RFC822); } public int position() { return currentPos; } /** * Parses the next token from this String. <p> * <p/> * Clients sit in a loop calling next() to parse successive * tokens until an EOF Token is returned. * * @return the next Token * @throws MalformedException if the parse fails */ public Token next() throws MalformedException { currentPos = nextPos; // setup currentPos Token tk = getNext(); nextPos = peekPos = currentPos; // update currentPos and peekPos return tk; } /** * Peek at the next token, without actually removing the token * from the parse stream. Invoking this method multiple times * will return successive tokens, until <code>next()</code> is * called. <p> * * @return the next Token * @throws MalformedException if the parse fails */ public Token peek() throws MalformedException { currentPos = peekPos; // setup currentPos Token tk = getNext(); peekPos = currentPos; // update peekPos return tk; } /** * Return the rest of the Header. * * @return String rest of header. null is returned if we are * already at end of header */ public String getRemainder() { return string.subSequence(nextPos, string.length()).toString(); } /* * Return the next token starting from 'currentPos'. After the * parse, 'currentPos' is updated to point to the start of the * next token. */ private Token getNext() throws MalformedException { // If we're already at end of string, return EOF if(currentPos >= maxPos) return EOFToken; char c; int start; boolean filter = false; c = string.charAt(currentPos); // Check for whitespace if(isWhiteSpace(c)) { for(start = currentPos; currentPos < maxPos; currentPos++) { c = string.charAt(currentPos); if(!isWhiteSpace(c)) break; } return new Token(Token.LWS, string.subSequence(start, currentPos)); } // Check for comments and position currentPos // beyond the comment if(c == '(') { // Parsing comment .. int nesting; for(start = ++currentPos, nesting = 1; nesting > 0 && currentPos < maxPos; currentPos++) { c = string.charAt(currentPos); if(c == '\\') { // Escape sequence currentPos++; // skip the escaped character filter = true; } else if(c == '\r') { filter = true; } else if(c == '(') { nesting++; } else if(c == ')') { nesting--; } } if(nesting != 0) throw new MalformedException("Unbalanced comments"); // Return the comment, if we are asked to. // Note that the comment start & end markers are ignored. CharSequence s; if(filter) s = filterToken(string, start, currentPos - 1); else s = string.subSequence(start, currentPos - 1); return new Token(Token.COMMENT, s); } // Check for quoted-string and position currentPos // beyond the terminating quote if(c == '"') { for(start = ++currentPos; currentPos < maxPos; currentPos++) { c = string.charAt(currentPos); if(c == '\\') { // Escape sequence currentPos++; filter = true; } else if(c == '\r') { filter = true; } else if(c == '"') { currentPos++; CharSequence s; if(filter) s = filterToken(string, start, currentPos - 1); else s = string.subSequence(start, currentPos - 1); return new Token(Token.QUOTEDSTRING, s); } } throw new MalformedException("Unbalanced quoted string"); } // Check for SPECIAL or CTL if(c < 040 || c >= 0177 || delimiters.indexOf(c) >= 0) { currentPos++; // re-position currentPos char[] ch = new char[1]; ch[0] = c; return new Token((int) c, new String(ch)); } // Check for ATOM for(start = currentPos; currentPos < maxPos; currentPos++) { c = string.charAt(currentPos); // ATOM is delimited by either SPACE, CTL, "(", <"> // or the specified SPECIALS if(c < 040 || c >= 0177 || c == '(' || c == ' ' || c == '"' || delimiters.indexOf(c) >= 0) break; } return new Token(Token.ATOM, string.subSequence(start, currentPos)); } // Skip SPACE, HT, CR and NL private int skipWhiteSpace() { char c; for(; currentPos < maxPos; currentPos++) { if(((c = string.charAt(currentPos)) != '\t') && (c != ' ') && (c != '\r') && (c != '\n')) return currentPos; } return Token.EOF; } private boolean isWhiteSpace(char c) { return (c == '\t' || c == '\r' || c == '\n' || c == ' '); } /* Process escape sequences and embedded LWSPs from a comment or * quoted string. */ private static CharSequence filterToken(CharSequence s, int start, int end) { StringBuffer sb = new StringBuffer(); char c; boolean gotEscape = false; boolean gotCR = false; for(int i = start; i < end; i++) { c = s.charAt(i); if(c == '\n' && gotCR) { // This LF is part of an unescaped // CRLF sequence (i.e, LWSP). Skip it. gotCR = false; continue; } gotCR = false; if(!gotEscape) { // Previous character was NOT '\' if(c == '\\') // skip this character gotEscape = true; else if(c == '\r') // skip this character gotCR = true; else // append this character sb.append(c); } else { // Previous character was '\'. So no need to // bother with any special processing, just // append this character sb.append(c); gotEscape = false; } } return sb; } }
10,985
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
Parameter.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/Parameter.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/15/11 1:15 PM */ package xpertss.mime; /** * This class holds a MIME parameter (attribute-value pair) as defined in RFC-2231. * <p/> * Parameters may be either simple or named. A simple parameter will have a {@code null} * name. */ public interface Parameter { /** * Returns the parameter name as a String or {@code null} if this is a simple * parameter. */ public String getName(); /** * Returns the parameter value as a String. */ public String getValue(); /** * Returns this parameter as a fully formatted string. */ public String toString(); }
673
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HeaderParser.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/HeaderParser.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 11:09 AM */ package xpertss.mime; import xpertss.mime.spi.HeaderParserProvider; import java.util.ServiceLoader; /** * HeaderParser will parse MIME headers into Header objects. * <p/> * This utilizes a ServiceProvider framework where a parser for each header * is loaded to actually parse the header contents. This class simply parses * the header name so that it may be used to locate a suitable value parser. * * @see xpertss.mime.spi.HeaderParserProvider */ public abstract class HeaderParser { private static ServiceLoader<HeaderParserProvider> loader = ServiceLoader.load(HeaderParserProvider.class, HeaderParserProvider.class.getClassLoader()); /** * Parse a raw header and return an appropriate Header object representation. * * @param raw The raw header string from a request or response * @return A header object instance * @throws MalformedException If the header was malformed or incomplete * @throws NullPointerException If the raw header is {@code null} */ public static Header parse(CharSequence raw) throws MalformedException { if(raw == null) throw new NullPointerException("raw can not be null"); HeaderTokenizer h = new HeaderTokenizer(raw, HeaderTokenizer.MIME); HeaderTokenizer.Token token = h.next(); if(token.getType() != HeaderTokenizer.Token.ATOM) throw new MalformedException("expected header name"); String name = token.getValue(); if((token = h.next()).getType() != ':') throw new MalformedException("expected header delimiter"); if((token = h.next()).getType() != HeaderTokenizer.Token.LWS) throw new MalformedException("expected header separator"); return parse(name, h.getRemainder()); } /** * Parse the given header value for the specified header name and return an * appropriate Header objects representation. * * @param name The name of the header * @param rawValue A string representing the raw value to be parsed * @return A header object instance * @throws MalformedException If the header value was malformed or incomplete * @throws NullPointerException If either the header or rawValue values are {@code null} */ public static Header parse(String name, CharSequence rawValue) throws MalformedException { if(name == null) throw new NullPointerException("name can not be null"); if(rawValue == null) throw new NullPointerException("rawValue can not be null"); // revert to the service providers. for(HeaderParserProvider provider: loader) { HeaderParser parser = provider.create(name); if(parser != null) return parser.doParse(rawValue); } return new RawHeader(name, rawValue); // default to a RawHeader as nothing knows how to parse it } /** * Service provider implementations should implement this method to parse a * raw header value into a Header object. * * @param raw The raw header value to parse. * @return A header object representing the parsed header value * @throws MalformedException If the header value was malformed or incomplete */ protected abstract Header doParse(CharSequence raw) throws MalformedException; private static class RawHeader implements Header { private String name; private String value; private RawHeader(String name, CharSequence value) { this.name = name; this.value = value.toString(); } public String getName() { return name; } public String getValue() { return value; } public Type getType() { return Type.Raw; } public int size() { return 0; } public HeaderValue getValue(int index) { return null; } public HeaderValue getValue(String name) { return null; } public String toString() { return name + ": " + value; } } }
4,073
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HeaderValue.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/HeaderValue.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/17/11 10:19 AM */ package xpertss.mime; /** * Many HTTP headers support the concept of multiple values separated by commas. * A HeaderValue represents just one of those values along with its associated * parameters. * <p> * Example of simple multi-valued headers: * <p><pre> * If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" * Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 * </pre><p> * An individual header value may be simple as shown above or it may be a named * value as in the following example: * <p><pre> * Cache-Control: max-age=0 * </pre><p> * Additionally, a header may combine simple and named values as follows: * <p><pre> * Cache-Control: private, max-age=0 * </pre><p> * In the example the simple header value will have a {@code null} name field and * the value field will have the value private. The named value will have a name * field of max-age and a value field of 0. * */ public interface HeaderValue { /** * Ths will return the value's name or {@code null} if it is not a * named value. */ public String getName(); /** * This will return the value's value. */ public String getValue(); /** * Returns the number of parameters this header value contains. */ public int size(); /** * Returns the parameter at the specified index. */ public Parameter getParameter(int index); /** * Returns the specified named parameter if it exists. */ public Parameter getParameter(String name); /** * Return a formatted string representation of this header value and its * parameters. */ public String toString(); }
1,724
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
MalformedException.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/MalformedException.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/21/11 11:09 AM */ package xpertss.mime; /** * Thrown to indicate that a header was Malformed and could not be parsed. */ public class MalformedException extends RuntimeException { /** * No message constructor. */ public MalformedException() { super(); } public MalformedException(String message) { super(message); } public MalformedException(String message, Throwable cause) { super(message, cause); } public MalformedException(Throwable cause) { super(cause); } }
611
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SingleValueHeader.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/SingleValueHeader.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 11:53 PM */ package xpertss.mime.impl; import xpertss.mime.Header; import xpertss.mime.HeaderValue; import xpertss.lang.Objects; public class SingleValueHeader implements Header { private final Type type; private final String name; private final HeaderValue[] value; public SingleValueHeader(String name, Type type, HeaderValue value) { this.name = Objects.notNull(name, "name"); this.type = Objects.notNull(type, "type"); this.value = new HeaderValue[] { value }; } public String getName() { return name; } public String getValue() { return value[0].toString(); } public Type getType() { return type; } public int size() { return 1; } public HeaderValue getValue(int index) { return value[index]; } public HeaderValue getValue(String name) { return null; } public String toString() { return String.format("%s: %s", getName(), getValue()); } }
1,070
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z