Follow-up to #15.

- Removed the temporary directory (Options.TMP_DIR), which is no longer needed.
- Excluded original Slick2D classes that were overridden in pom.xml.
- Formatting changes and documentation.

Signed-off-by: Jeffrey Han <itdelatrisu@gmail.com>
This commit is contained in:
Jeffrey Han 2015-02-12 03:52:19 -05:00
parent 800014ed4c
commit f6eec5cd6c
11 changed files with 321 additions and 267 deletions

1
.gitignore vendored
View File

@ -1,4 +1,3 @@
/.opsu_tmp/
/Screenshots/ /Screenshots/
/Skins/ /Skins/
/SongPacks/ /SongPacks/

12
pom.xml
View File

@ -93,6 +93,18 @@
</excludes> </excludes>
</artifactSet> </artifactSet>
--> -->
<filters>
<filter>
<!-- Overwritten classes -->
<artifact>org.slick2d:slick2d-core</artifact>
<excludes>
<exclude>org/newdawn/slick/Music.*</exclude>
<exclude>org/newdawn/slick/openal/AudioInputStream*</exclude>
<exclude>org/newdawn/slick/openal/OpenALStreamPlayer*</exclude>
<exclude>org/newdawn/slick/openal/SoundStore*</exclude>
</excludes>
</filter>
</filters>
<createDependencyReducedPom>false</createDependencyReducedPom> <createDependencyReducedPom>false</createDependencyReducedPom>
</configuration> </configuration>
<executions> <executions>

View File

@ -134,13 +134,6 @@ public class Opsu extends StateBasedGame {
ResourceLoader.addResourceLocation(new FileSystemLocation(new File("."))); ResourceLoader.addResourceLocation(new FileSystemLocation(new File(".")));
ResourceLoader.addResourceLocation(new FileSystemLocation(new File("./res/"))); ResourceLoader.addResourceLocation(new FileSystemLocation(new File("./res/")));
// clear the cache
if (!Options.TMP_DIR.mkdir()) {
for (File tmp : Options.TMP_DIR.listFiles())
tmp.delete();
}
Options.TMP_DIR.deleteOnExit();
// initialize score database // initialize score database
ScoreDB.init(); ScoreDB.init();

View File

@ -42,9 +42,6 @@ import org.newdawn.slick.util.Log;
* Handles all user options. * Handles all user options.
*/ */
public class Options { public class Options {
/** Temporary folder for file conversions, auto-deleted upon successful exit. */
public static final File TMP_DIR = new File(".opsu_tmp/");
/** File for logging errors. */ /** File for logging errors. */
public static final File LOG_FILE = new File(".opsu.log"); public static final File LOG_FILE = new File(".opsu.log");

View File

@ -27,8 +27,6 @@ import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.IntBuffer; import java.nio.IntBuffer;
import javazoom.jl.converter.Converter;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.lwjgl.openal.AL; import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10; import org.lwjgl.openal.AL10;
@ -48,9 +46,6 @@ public class MusicController {
/** The last OsuFile passed to play(). */ /** The last OsuFile passed to play(). */
private static OsuFile lastOsu; private static OsuFile lastOsu;
/** Temporary WAV file for file conversions (to be deleted). */
private static File wavFile;
/** Thread for loading tracks. */ /** Thread for loading tracks. */
private static Thread trackLoader; private static Thread trackLoader;
@ -79,14 +74,6 @@ public class MusicController {
switch (OsuParser.getExtension(osu.audioFilename.getName())) { switch (OsuParser.getExtension(osu.audioFilename.getName())) {
case "ogg": case "ogg":
trackLoader = new Thread() {
@Override
public void run() {
loadTrack(osu.audioFilename, osu.previewTime, loop);
}
};
trackLoader.start();
break;
case "mp3": case "mp3":
trackLoader = new Thread() { trackLoader = new Thread() {
@Override @Override
@ -108,7 +95,7 @@ public class MusicController {
*/ */
private static void loadTrack(File file, int previewTime, boolean loop) { private static void loadTrack(File file, int previewTime, boolean loop) {
try { // create a new player try { // create a new player
player = new Music(file.getPath(),true); player = new Music(file.getPath(), true);
player.addListener(new MusicListener() { player.addListener(new MusicListener() {
@Override @Override
public void musicEnded(Music music) { trackEnded = true; } public void musicEnded(Music music) { trackEnded = true; }
@ -135,27 +122,9 @@ public class MusicController {
else else
player.play(); player.play();
player.setPosition(position / 1000f); player.setPosition(position / 1000f);
} }
} }
/**
* Converts an MP3 file to a temporary WAV file.
*/
private static File convertMp3(File file) {
try {
wavFile = File.createTempFile(".osu", ".wav", Options.TMP_DIR);
wavFile.deleteOnExit();
Converter converter = new Converter();
converter.convert(file.getPath(), wavFile.getPath());
return wavFile;
} catch (Exception e) {
ErrorHandler.error(String.format("Failed to play file '%s'.", file.getAbsolutePath()), e, false);
}
return wavFile;
}
/** /**
* Returns true if a track is being loaded. * Returns true if a track is being loaded.
*/ */
@ -269,12 +238,9 @@ public class MusicController {
/** /**
* Plays the current track. * Plays the current track.
*/ */
public static boolean play() { public static void play() {
if (trackExists()){ if (trackExists())
player.play(); player.play();
return true;
}
return false;
} }
/** /**
@ -328,17 +294,14 @@ public class MusicController {
* Stops the current track, cancels track conversions, erases * Stops the current track, cancels track conversions, erases
* temporary files, releases OpenAL sources, and resets state. * temporary files, releases OpenAL sources, and resets state.
*/ */
@SuppressWarnings("deprecation")
public static void reset() { public static void reset() {
stop(); stop();
// TODO: properly interrupt instead of using deprecated Thread.stop(); // interrupt the track loading
// interrupt the conversion/track loading // TODO: Not sure if the interrupt does anything, and the join kind of
// Not sure if the interrupt does anything // defeats the purpose of threading it, but it is needed since bad things
// And the join kind of defeats the purpose of threading it. // likely happen when OpenALStreamPlayer source is released asynchronously.
// But is needed since bad things happen when OpenALStreamPlayer source is released asynchronously I think.
if (isTrackLoading()){ if (isTrackLoading()){
//trackLoader.stop();
trackLoader.interrupt(); trackLoader.interrupt();
try { try {
trackLoader.join(); trackLoader.join();
@ -348,12 +311,6 @@ public class MusicController {
} }
trackLoader = null; trackLoader = null;
// delete temporary WAV file
if (wavFile != null) {
wavFile.delete();
wavFile = null;
}
// reset state // reset state
lastOsu = null; lastOsu = null;
trackEnded = false; trackEnded = false;

View File

@ -696,8 +696,7 @@ public class Game extends BasicGameState {
// reset game data // reset game data
resetGameData(); resetGameData();
//needs to play before we can set position // needs to play before setting position to resume without lag later
//so we can resume without lag later
MusicController.play(); MusicController.play();
MusicController.setPosition(0); MusicController.setPosition(0);
MusicController.pause(); MusicController.pause();

View File

@ -1,15 +1,29 @@
/* /*
Copyright (c) 2013, Slick2D * Copyright (c) 2013, Slick2D
* All rights reserved.
All rights reserved. *
* Redistribution and use in source and binary forms, with or without
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * - Redistributions in binary form must reproduce the above copyright notice,
* Neither the name of the Slick2D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <EFBFBD>gAS IS<EFBFBD>h AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - Neither the name of the Slick2D nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/ */
package org.newdawn.slick; package org.newdawn.slick;
@ -45,7 +59,7 @@ public class Music {
if (currentMusic != null) { if (currentMusic != null) {
SoundStore.get().poll(delta); SoundStore.get().poll(delta);
if (!SoundStore.get().isMusicPlaying()) { if (!SoundStore.get().isMusicPlaying()) {
if (!currentMusic.positioning&&!currentMusic.playing) { if (!currentMusic.positioning && !currentMusic.playing) {
Music oldMusic = currentMusic; Music oldMusic = currentMusic;
currentMusic = null; currentMusic = null;
oldMusic.fireMusicEnded(); oldMusic.fireMusicEnded();
@ -138,8 +152,7 @@ public class Music {
String ref = url.getFile(); String ref = url.getFile();
try { try {
if (ref.toLowerCase().endsWith(".ogg") if (ref.toLowerCase().endsWith(".ogg") || ref.toLowerCase().endsWith(".mp3")) {
||ref.toLowerCase().endsWith(".mp3")) {
if (streamingHint) { if (streamingHint) {
sound = SoundStore.get().getOggStream(url); sound = SoundStore.get().getOggStream(url);
} else { } else {
@ -171,8 +184,7 @@ public class Music {
SoundStore.get().init(); SoundStore.get().init();
try { try {
if (ref.toLowerCase().endsWith(".ogg") if (ref.toLowerCase().endsWith(".ogg") || ref.toLowerCase().endsWith(".mp3")) {
||ref.toLowerCase().endsWith(".mp3")) {
if (streamingHint) { if (streamingHint) {
sound = SoundStore.get().getOggStream(ref); sound = SoundStore.get().getOggStream(ref);
} else { } else {

View File

@ -1,16 +1,31 @@
/* /*
Copyright (c) 2013, Slick2D * Copyright (c) 2013, Slick2D
* All rights reserved.
All rights reserved. *
* Redistribution and use in source and binary forms, with or without
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * - Redistributions in binary form must reproduce the above copyright notice,
* Neither the name of the Slick2D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <EFBFBD>gAS IS<EFBFBD>h AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - Neither the name of the Slick2D nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/ */
package org.newdawn.slick.openal; package org.newdawn.slick.openal;
import java.io.IOException; import java.io.IOException;
@ -82,6 +97,13 @@ interface AudioInputStream {
*/ */
public void close() throws IOException; public void close() throws IOException;
public long skip(long l) throws IOException; /**
* Skips over and discards n bytes of data from this input stream.
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @throws IOException
* @see java.io.InputStream#skip(long)
*/
public long skip(long n) throws IOException;
} }

View File

@ -1,176 +1,202 @@
/* /*
Copyright (c) 2013, Slick2D * Copyright (c) 2013, Slick2D
* All rights reserved.
All rights reserved. *
* Redistribution and use in source and binary forms, with or without
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * - Redistributions in binary form must reproduce the above copyright notice,
* Neither the name of the Slick2D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <EFBFBD>gAS IS<EFBFBD>h AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - Neither the name of the Slick2D nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/ */
package org.newdawn.slick.openal; package org.newdawn.slick.openal;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import sun.font.EAttribute; import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.*; import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Decoder;
import javazoom.jl.decoder.DecoderException;
import javazoom.jl.decoder.Header;
import javazoom.jl.decoder.SampleBuffer;
import org.newdawn.slick.util.Log;
/**
* An input stream that can extract MP3 data.
*
* @author fluddokt (https://github.com/fluddokt)
*/
public class Mp3InputStream extends InputStream implements AudioInputStream { public class Mp3InputStream extends InputStream implements AudioInputStream {
/** The MPEG audio bitstream. */
private Bitstream bitstream;
Bitstream bitstream; /** The MPEG decoder. */
Decoder decoder; private Decoder decoder;
Header header;
SampleBuffer buf; /** The frame header extractor. */
private Header header;
int channels;
int sampleRate; /** The buffer. */
private SampleBuffer buf;
int bufLen = 0;
boolean atEnd=false; /** The number of channels. */
int bpos; //byte pos private int channels;
public Mp3InputStream(InputStream resourceAsStream) { /** The sample rate. */
private int sampleRate;
/** The buffer length. */
private int bufLen = 0;
/** True if we've reached the end of the available data. */
private boolean endOfStream = false;
/** The byte position. */
private int bpos;
/**
* Create a new stream to decode MP3 data.
* @param input the input stream from which to read the MP3 file
*/
public Mp3InputStream(InputStream input) {
decoder = new Decoder(); decoder = new Decoder();
bitstream = new Bitstream(resourceAsStream); bitstream = new Bitstream(input);
try { try {
header = bitstream.readFrame(); header = bitstream.readFrame();
} catch (BitstreamException e) { } catch (BitstreamException e) {
e.printStackTrace(); Log.error(e);
} }
channels = header.mode()==Header.SINGLE_CHANNEL?1:2; channels = (header.mode() == Header.SINGLE_CHANNEL) ? 1 : 2;
sampleRate = header.frequency(); sampleRate = header.frequency();
buf = new SampleBuffer(sampleRate, channels); buf = new SampleBuffer(sampleRate, channels);
decoder.setOutputBuffer(buf); decoder.setOutputBuffer(buf);
//*
try { try {
decoder.decodeFrame(header, bitstream); decoder.decodeFrame(header, bitstream);
} catch (DecoderException e) { } catch (DecoderException e) {
e.printStackTrace(); Log.error(e);
} }
//*/
bufLen = buf.getBufferLength(); bufLen = buf.getBufferLength();
bitstream.closeFrame(); bitstream.closeFrame();
} }
@Override @Override
public int read() throws IOException { public int read() throws IOException {
if(atEnd()) if (atEnd())
return -1; return -1;
while(bpos/2>=bufLen){ while (bpos / 2 >= bufLen) {
try { try {
header = bitstream.readFrame(); header = bitstream.readFrame();
if(header == null){ if (header == null) {
buf.clear_buffer(); buf.clear_buffer();
atEnd = true; endOfStream = true;
return -1; return -1;
} }
buf.clear_buffer(); buf.clear_buffer();
decoder.decodeFrame(header, bitstream); decoder.decodeFrame(header, bitstream);
bufLen = buf.getBufferLength(); bufLen = buf.getBufferLength();
bitstream.closeFrame(); bitstream.closeFrame();
} catch (DecoderException e) { } catch (DecoderException | BitstreamException e) {
e.printStackTrace(); Log.error(e);
} catch (BitstreamException e) {
e.printStackTrace();
} }
bpos=0; bpos = 0;
} }
int npos = bpos/2; int npos = bpos / 2;
bpos++; bpos++;
if(bpos%2==0) if (bpos % 2 == 0)
return (buf.getBuffer()[npos]>>8)&0xff; return (buf.getBuffer()[npos] >> 8) & 0xff;
else else
return (buf.getBuffer()[npos])&0xff; return (buf.getBuffer()[npos]) & 0xff;
} }
@Override @Override
public boolean atEnd() { public boolean atEnd() { return endOfStream; }
return atEnd;
}
@Override @Override
public int getChannels() { public int getChannels() { return channels; }
return channels;
} @Override
public int getRate() { return sampleRate; }
@Override @Override
public int getRate() {
return sampleRate;
}
/**
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException { public int read(byte[] b, int off, int len) throws IOException {
for (int i=0;i<len;i++) { for (int i = 0; i < len; i++) {
try { try {
int value = read(); int value = read();
if (value >= 0) { if (value >= 0)
b[i] = (byte) value; b[i] = (byte) value;
} else { else
if (i == 0) { return (i == 0) ? -1 : i;
return -1;
} else {
return i;
}
}
} catch (IOException e) { } catch (IOException e) {
//Log.error(e); Log.error(e);
e.printStackTrace();
return i; return i;
} }
} }
return len; return len;
} }
/** @Override
* @see java.io.InputStream#read(byte[]) public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
*/
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override @Override
public long skip(long length) { public long skip(long length) {
//System.out.println("skip"+length); if (bufLen <= 0)
int skiped = 0; Log.warn("Mp3InputStream: skip: bufLen not yet determined.");
if(bufLen<=0){
System.out.println("We don't know buf Length yet"); int skipped = 0;
//throw new Error("We don't know buf Length yet"); while (skipped + bufLen * 2 < length) {
}
while(skiped+bufLen*2<length){
try { try {
header = bitstream.readFrame(); header = bitstream.readFrame();
if(header == null){ if (header == null) {
//System.out.println("Header is null"); // Log.warn("Mp3InputStream: skip: header is null.");
atEnd = true; endOfStream = true;
return -1; return -1;
} }
//last frame that won't be skiped so better read it
if(skiped+bufLen*2*4 >=length || bufLen<=0){ // last frame that won't be skipped so better read it
if (skipped + bufLen * 2 * 4 >= length || bufLen <= 0) {
buf.clear_buffer(); buf.clear_buffer();
decoder.decodeFrame(header, bitstream); decoder.decodeFrame(header, bitstream);
bufLen = buf.getBufferLength(); bufLen = buf.getBufferLength();
} }
skiped+=bufLen*2-bpos; skipped += bufLen * 2 - bpos;
bitstream.closeFrame(); bitstream.closeFrame();
bpos=0; bpos = 0;
} catch (BitstreamException e) { } catch (BitstreamException | DecoderException e) {
e.printStackTrace(); Log.error(e);
}catch (DecoderException e) {
e.printStackTrace();
} }
} }
if(bufLen*2-bpos>length-skiped){ if (bufLen * 2 - bpos > length - skipped) {
bpos+=length-skiped; bpos += length - skipped;
skiped+=length-skiped; skipped += length - skipped;
} }
return skiped; return skipped;
} }
} }

View File

@ -1,15 +1,29 @@
/* /*
Copyright (c) 2013, Slick2D * Copyright (c) 2013, Slick2D
* All rights reserved.
All rights reserved. *
* Redistribution and use in source and binary forms, with or without
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * - Redistributions in binary form must reproduce the above copyright notice,
* Neither the name of the Slick2D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <EFBFBD>gAS IS<EFBFBD>h AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - Neither the name of the Slick2D nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/ */
package org.newdawn.slick.openal; package org.newdawn.slick.openal;
@ -35,9 +49,9 @@ import org.newdawn.slick.util.ResourceLoader;
*/ */
public class OpenALStreamPlayer { public class OpenALStreamPlayer {
/** The number of buffers to maintain */ /** The number of buffers to maintain */
public static final int BUFFER_COUNT = 20; public static final int BUFFER_COUNT = 20; // 3
/** The size of the sections to stream from the stream */ /** The size of the sections to stream from the stream */
private static final int sectionSize = 4096; private static final int sectionSize = 4096; // 4096 * 20
/** The buffer read from the data stream */ /** The buffer read from the data stream */
private byte[] buffer = new byte[sectionSize]; private byte[] buffer = new byte[sectionSize];
@ -64,16 +78,29 @@ public class OpenALStreamPlayer {
/** The pitch of the music */ /** The pitch of the music */
private float pitch; private float pitch;
/** Position in seconds of the previously played buffers */ /** Position in seconds of the previously played buffers */
//private float positionOffset; // private float positionOffset;
/** The stream position. */
long streamPos = 0; long streamPos = 0;
/** The sample rate. */
int sampleRate; int sampleRate;
/** The sample size. */
int sampleSize; int sampleSize;
/** The play position. */
long playedPos; long playedPos;
/** The music length. */
long musicLength = -1; long musicLength = -1;
/** The time of the last update, in ms. */
long lastUpdateTime = System.currentTimeMillis(); long lastUpdateTime = System.currentTimeMillis();
/** The offset time. */
long offsetTime = 0;
/** /**
* Create a new player to work on an audio stream * Create a new player to work on an audio stream
* *
@ -111,13 +138,13 @@ public class OpenALStreamPlayer {
if (audio != null) { if (audio != null) {
audio.close(); audio.close();
} }
AudioInputStream audio; AudioInputStream audio;
if (url != null) { if (url != null) {
audio = new OggInputStream(url.openStream()); audio = new OggInputStream(url.openStream());
} else { } else {
if(ref.toLowerCase().endsWith(".mp3")) if (ref.toLowerCase().endsWith(".mp3"))
audio = new Mp3InputStream(ResourceLoader.getResourceAsStream(ref)); audio = new Mp3InputStream(ResourceLoader.getResourceAsStream(ref));
else else
audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref));
@ -125,12 +152,11 @@ public class OpenALStreamPlayer {
this.audio = audio; this.audio = audio;
sampleRate = audio.getRate(); sampleRate = audio.getRate();
if (audio.getChannels() > 1) { if (audio.getChannels() > 1)
sampleSize = 4; // AL10.AL_FORMAT_STEREO16 sampleSize = 4; // AL10.AL_FORMAT_STEREO16
} else { else
sampleSize = 2; // AL10.AL_FORMAT_MONO16 sampleSize = 2; // AL10.AL_FORMAT_MONO16
} // positionOffset = 0;
//positionOffset = 0;
streamPos = 0; streamPos = 0;
} }
@ -150,14 +176,11 @@ public class OpenALStreamPlayer {
private synchronized void removeBuffers() { private synchronized void removeBuffers() {
AL10.alSourceStop(source); AL10.alSourceStop(source);
IntBuffer buffer = BufferUtils.createIntBuffer(1); IntBuffer buffer = BufferUtils.createIntBuffer(1);
while (AL10.alGetSourcei(source, AL10.AL_BUFFERS_QUEUED) > 0) {
while (AL10.alGetSourcei(source, AL10.AL_BUFFERS_QUEUED) > 0)
{
AL10.alSourceUnqueueBuffers(source, buffer); AL10.alSourceUnqueueBuffers(source, buffer);
buffer.clear(); buffer.clear();
} }
} }
/** /**
@ -213,16 +236,16 @@ public class OpenALStreamPlayer {
AL10.alSourceUnqueueBuffers(source, unqueued); AL10.alSourceUnqueueBuffers(source, unqueued);
int bufferIndex = unqueued.get(0); int bufferIndex = unqueued.get(0);
int bufferLength = AL10.alGetBufferi(bufferIndex, AL10.AL_SIZE); int bufferLength = AL10.alGetBufferi(bufferIndex, AL10.AL_SIZE);
playedPos += bufferLength; playedPos += bufferLength;
lastUpdateTime = System.currentTimeMillis(); lastUpdateTime = System.currentTimeMillis();
if(musicLength>0 && playedPos>musicLength) if (musicLength > 0 && playedPos > musicLength)
playedPos -= musicLength; playedPos -= musicLength;
if (stream(bufferIndex)) { if (stream(bufferIndex)) {
AL10.alSourceQueueBuffers(source, unqueued); AL10.alSourceQueueBuffers(source, unqueued);
} else { } else {
remainingBufferCount--; remainingBufferCount--;
@ -289,21 +312,18 @@ public class OpenALStreamPlayer {
*/ */
public synchronized boolean setPosition(float position) { public synchronized boolean setPosition(float position) {
try { try {
long samplePos = (long) (position * sampleRate) * sampleSize;
long samplePos = (long) (position*sampleRate)*sampleSize;
if (streamPos > samplePos)
if(streamPos > samplePos){
initStreams(); initStreams();
}
long skipped = audio.skip(samplePos - streamPos);
long skiped = audio.skip(samplePos - streamPos); if (skipped >= 0)
if(skiped>=0) streamPos += skipped;
streamPos+=skiped; else
else{ Log.warn("OpenALStreamPlayer: setPosition: failed to skip.");
System.out.println("Failed to skip?");
} while (streamPos + buffer.length < samplePos) {
while(streamPos+buffer.length < samplePos){
int count = audio.read(buffer); int count = audio.read(buffer);
if (count != -1) { if (count != -1) {
streamPos += count; streamPos += count;
@ -316,9 +336,9 @@ public class OpenALStreamPlayer {
return false; return false;
} }
} }
playedPos = streamPos; playedPos = streamPos;
startPlayback(); startPlayback();
return true; return true;
@ -345,7 +365,6 @@ public class OpenALStreamPlayer {
AL10.alSourceQueueBuffers(source, bufferNames); AL10.alSourceQueueBuffers(source, bufferNames);
AL10.alSourcePlay(source); AL10.alSourcePlay(source);
lastUpdateTime = System.currentTimeMillis(); lastUpdateTime = System.currentTimeMillis();
} }
/** /**
@ -354,20 +373,24 @@ public class OpenALStreamPlayer {
* @return The current position in seconds. * @return The current position in seconds.
*/ */
public float getPosition() { public float getPosition() {
float playedTime = ((float)playedPos/(float)sampleSize)/(float)sampleRate; float playedTime = ((float) playedPos / (float) sampleSize) / sampleRate;
float timePosition = playedTime float timePosition = playedTime + (System.currentTimeMillis() - lastUpdateTime) / 1000f;
+ (System.currentTimeMillis()-lastUpdateTime)/1000f; // + AL10.alGetSourcef(source, AL11.AL_SEC_OFFSET);
//+ AL10.alGetSourcef(source, AL11.AL_SEC_OFFSET);
return timePosition; return timePosition;
} }
long offsetTime = 0; /**
* Processes a track pause.
*/
public void pausing() { public void pausing() {
offsetTime = System.currentTimeMillis()-lastUpdateTime; offsetTime = System.currentTimeMillis() - lastUpdateTime;
} }
/**
* Processes a track resume.
*/
public void resuming() { public void resuming() {
lastUpdateTime = System.currentTimeMillis()-offsetTime; lastUpdateTime = System.currentTimeMillis() - offsetTime;
} }
} }

View File

@ -1,16 +1,31 @@
/* /*
Copyright (c) 2013, Slick2D * Copyright (c) 2013, Slick2D
* All rights reserved.
All rights reserved. *
* Redistribution and use in source and binary forms, with or without
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * - Redistributions in binary form must reproduce the above copyright notice,
* Neither the name of the Slick2D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <EFBFBD>gAS IS<EFBFBD>h AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - Neither the name of the Slick2D nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/ */
package org.newdawn.slick.openal; package org.newdawn.slick.openal;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
@ -529,7 +544,7 @@ public class SoundStore {
public void pauseLoop() { public void pauseLoop() {
if ((soundWorks) && (currentMusic != -1)){ if ((soundWorks) && (currentMusic != -1)){
paused = true; paused = true;
if(stream!=null) if (stream != null)
stream.pausing(); stream.pausing();
AL10.alSourcePause(currentMusic); AL10.alSourcePause(currentMusic);
} }
@ -542,9 +557,8 @@ public class SoundStore {
if ((music) && (soundWorks) && (currentMusic != -1)){ if ((music) && (soundWorks) && (currentMusic != -1)){
paused = false; paused = false;
AL10.alSourcePlay(currentMusic); AL10.alSourcePlay(currentMusic);
if(stream!=null) if (stream != null)
stream.resuming(); stream.resuming();
} }
} }