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 |
---|---|---|---|---|---|---|---|---|---|---|---|
Microphone.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/Microphone.java | /*
* Microphone.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.media.AudioFormat;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.OptionList;
/**
* Audio Sensor - "connects" to the audio interface
* Created by Johnny on 05.03.2015.
*/
public class Microphone extends Sensor {
public Microphone()
{
_name = "Microphone";
}
@Override
public boolean connect() throws SSJFatalException
{
return true;
}
@Override
public void disconnect() throws SSJFatalException
{
}
public static int audioFormatSampleBytes(int f)
{
switch (f)
{
case AudioFormat.ENCODING_PCM_8BIT:
return 1;
case AudioFormat.ENCODING_PCM_16BIT:
case AudioFormat.ENCODING_DEFAULT:
return 2;
case AudioFormat.ENCODING_PCM_FLOAT:
return 4;
case AudioFormat.ENCODING_INVALID:
default:
return 0;
}
}
public static Cons.Type audioFormatSampleType(int f)
{
switch (f)
{
case AudioFormat.ENCODING_PCM_8BIT:
return Cons.Type.CHAR;
case AudioFormat.ENCODING_PCM_16BIT:
case AudioFormat.ENCODING_DEFAULT:
return Cons.Type.SHORT;
case AudioFormat.ENCODING_PCM_FLOAT:
return Cons.Type.FLOAT;
case AudioFormat.ENCODING_INVALID:
default:
return Cons.Type.UNDEF;
}
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 2,986 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioConvert.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/AudioConvert.java | /*
* AudioConvert.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Converts audio stream from float to short or short to float
* Created by Johnny on 15.06.2015.
*/
public class AudioConvert extends Transformer {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public AudioConvert()
{
_name = "AudioConvert";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream audio = null;
for(Stream s : stream_in) {
if (s.findDataClass("Audio") >= 0)
{
audio = s;
}
}
if(audio == null) {
Log.w("invalid input stream");
return;
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
switch(stream_in[0].type)
{
case SHORT:
{
short[] data = stream_in[0].ptrS();
float[] out = stream_out.ptrF();
for (int i = 0; i < data.length; ++i)
{
out[i] = data[i] / 32768.0f;
}
}
break;
case FLOAT:
{
float[] data = stream_in[0].ptrF();
short[] out = stream_out.ptrS();
for (int i = 0; i < data.length; ++i)
{
out[i] = (short)(data[i] * 32768);
}
}
break;
}
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return stream_in[0].dim;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
switch(stream_in[0].bytes)
{
case 4:
return 2;
case 2:
return 4;
default:
Log.e("Unsupported input stream type");
return 0;
}
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
switch(stream_in[0].type)
{
case FLOAT:
return Cons.Type.SHORT;
case SHORT:
return Cons.Type.FLOAT;
default:
Log.e("Unsupported input stream type");
return Cons.Type.UNDEF;
}
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
for(int i = 0; i < stream_out.dim; ++i)
stream_out.desc[i] = stream_in[0].desc[i];
}
}
| 4,525 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PlaybackThread.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/PlaybackThread.java | /*
* PlaybackThread.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Background thread for audio playback.
*/
public class PlaybackThread
{
private final static int INITIAL_PLAYBACK_DELAY = 0;
private final static int MARKER_UPDATE_INTERVAL = 1000 / 60;
private PlaybackListener playbackListener;
private MediaPlayer mediaPlayer;
private Context context;
private File audioFile;
private ScheduledExecutorService executor;
private Runnable markerUpdateTask;
private boolean finishedPlaying = false;
public PlaybackThread(Context c, File file)
{
context = c.getApplicationContext();
audioFile = file;
loadMedia();
}
/**
* Plays the loaded audio file and starts updating marker's position.
*/
public void play()
{
if (mediaPlayer != null && !mediaPlayer.isPlaying() && !finishedPlaying)
{
mediaPlayer.start();
startUpdatingMarkerPosition();
}
}
/**
* Pauses the playback of the loaded audio file.
*/
public void pause()
{
if (mediaPlayer != null && mediaPlayer.isPlaying())
{
mediaPlayer.pause();
}
}
/**
* Stops and resets the playback of the loaded audio file and repositions the marker's
* position to the origin.
*/
public void reset()
{
if (mediaPlayer != null)
{
mediaPlayer.reset();
}
loadMedia();
stopUpdatingMarkerPosition();
}
public void resetFinishedPlaying()
{
finishedPlaying = false;
}
/**
* Sets the listener for the current thread. Only one such thread is allowed to have
* a {@link hcm.ssj.audio.PlaybackListener}.
* @param listener {@link hcm.ssj.audio.PlaybackListener}.
*/
public void setPlaybackListener(PlaybackListener listener)
{
playbackListener = listener;
}
/**
* Removes the listener of the current thread.
*/
public void removePlaybackListener()
{
playbackListener = null;
}
/**
* Returns true if the current thread is currently playing audio.
* @return True if audio is being played back, false otherwise.
*/
public boolean isPlaying()
{
return mediaPlayer != null && mediaPlayer.isPlaying();
}
/**
* Skips the playback of the current thread to the selected time.
* @param progress Time in milliseconds to skip forward or backward to.
*/
public void seekTo(int progress)
{
if (mediaPlayer != null)
{
mediaPlayer.seekTo(progress);
play();
}
}
/**
* Loads audio file and sets up OnCompletionListener.
*/
private void loadMedia()
{
if (context != null && audioFile != null)
{
mediaPlayer = MediaPlayer.create(context.getApplicationContext(), Uri.fromFile(audioFile));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
finishedPlaying = true;
if (playbackListener != null)
{
playbackListener.onCompletion();
}
}
});
}
}
/**
* Starts updating playback marker's progress at a specified time interval.
*/
private void startUpdatingMarkerPosition()
{
if (executor == null)
{
executor = Executors.newSingleThreadScheduledExecutor();
}
if (markerUpdateTask == null)
{
markerUpdateTask = new Runnable()
{
@Override
public void run()
{
updateMarkerProgress();
}
};
}
executor.scheduleAtFixedRate(
markerUpdateTask,
INITIAL_PLAYBACK_DELAY,
MARKER_UPDATE_INTERVAL,
TimeUnit.MILLISECONDS
);
}
/**
* Stops updating playback marker's progress.
*/
private void stopUpdatingMarkerPosition()
{
if (executor != null)
{
executor.shutdown();
executor = null;
markerUpdateTask = null;
if (playbackListener != null)
{
playbackListener.onCompletion();
}
}
}
/**
* Updates playback marker's progress.
*/
private void updateMarkerProgress()
{
if (mediaPlayer != null && mediaPlayer.isPlaying())
{
int currentPosition = mediaPlayer.getCurrentPosition();
if (playbackListener != null)
{
playbackListener.onProgress(currentPosition);
}
}
}
}
| 5,541 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/AudioWriter.java | /*
* AudioWriter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.annotation.TargetApi;
import android.media.AudioFormat;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Build;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.Mp4Writer;
/**
* Audio writer for SSJ to create mp4-audio-files.<br>
* Created by Frank Gaibler on 21.01.2016.
*/
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class AudioWriter extends Mp4Writer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the audio writer
*/
public class Options extends Mp4Writer.Options
{
public final Option<String> mimeType = new Option<>("mimeType", "audio/mp4a-latm", String.class, "");
public final Option<Cons.AudioFormat> audioFormat = new Option<>("audioFormat", Cons.AudioFormat.ENCODING_DEFAULT, Cons.AudioFormat.class, "");
/**
*
*/
private Options()
{
super();
addOptions();
}
}
/**
*
*/
private enum DataFormat
{
BYTE(Microphone.audioFormatSampleBytes(AudioFormat.ENCODING_PCM_8BIT)),
SHORT(Microphone.audioFormatSampleBytes(AudioFormat.ENCODING_PCM_16BIT)),
FLOAT_8(BYTE.size),
FLOAT_16(SHORT.size);
private int size;
/**
* @param i int
*/
DataFormat(int i)
{
size = i;
}
}
public final Options options = new Options();
//
private int iSampleRate;
private int iSampleNumber;
private int iSampleDimension;
//
private DataFormat dataFormat = null;
/**
*
*/
public AudioWriter()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length != 1)
{
Log.e("Stream count not supported");
return;
}
switch (stream_in[0].type)
{
case BYTE:
{
dataFormat = DataFormat.BYTE;
break;
}
case SHORT:
{
dataFormat = DataFormat.SHORT;
break;
}
case FLOAT:
{
if (options.audioFormat.get() == Cons.AudioFormat.ENCODING_DEFAULT || options.audioFormat.get() == Cons.AudioFormat.ENCODING_PCM_16BIT)
{
dataFormat = DataFormat.FLOAT_16;
} else if (options.audioFormat.get() == Cons.AudioFormat.ENCODING_PCM_8BIT)
{
dataFormat = DataFormat.FLOAT_8;
} else
{
Log.e("Audio format not supported");
}
break;
}
default:
{
Log.e("Stream type not supported");
return;
}
}
initFiles(stream_in[0], options);
Log.d("Format: " + dataFormat.toString());
iSampleRate = (int) stream_in[0].sr;
iSampleDimension = stream_in[0].dim;
iSampleNumber = iSampleRate * dataFormat.size * iSampleDimension;
//recalculate frame rate
dFrameRate = stream_in[0].sr / stream_in[0].num;
aByShuffle = new byte[(int) (iSampleNumber / dFrameRate + 0.5)];
lFrameIndex = 0;
try
{
prepareEncoder();
}
catch (IOException e)
{
throw new SSJFatalException("error preparing encoder", e);
}
bufferInfo = new MediaCodec.BufferInfo();
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
protected final void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
try
{
switch (dataFormat)
{
case BYTE:
{
byte[] in = stream_in[0].ptrB();
for (int i = 0; i < in.length; i += aByShuffle.length)
{
System.arraycopy(in, i, aByShuffle, 0, aByShuffle.length);
encode(aByShuffle);
save(false);
}
break;
}
case SHORT:
{
short[] in = stream_in[0].ptrS();
for (int i = 0; i < in.length; i += aByShuffle.length)
{
ByteBuffer.wrap(aByShuffle).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(in, i / 2, aByShuffle.length / 2);
encode(aByShuffle);
save(false);
}
break;
}
case FLOAT_8:
float[] in = stream_in[0].ptrF();
for (int i = 0; i < in.length; )
{
for (int j = 0; j < aByShuffle.length; j++, i += aByShuffle.length)
{
aByShuffle[j] = (byte) (in[i] * 128);
}
encode(aByShuffle);
save(false);
}
break;
case FLOAT_16:
{
float[] in16 = stream_in[0].ptrF();
for (int i = 0; i < in16.length; )
{
for (int j = 0; j < aByShuffle.length; i++, j += 2)
{
short value = (short) (in16[i] * 32768);
aByShuffle[j] = (byte) (value & 0xff);
aByShuffle[j + 1] = (byte) ((value >> 8) & 0xff);
}
encode(aByShuffle);
save(false);
}
break;
}
default:
{
Log.e("Data format not supported");
break;
}
}
}
catch (IOException e)
{
throw new SSJFatalException("error writing audio data", e);
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream stream_in[]) throws SSJFatalException
{
super.flush(stream_in);
dataFormat = null;
}
/**
* Configures the encoder
*/
private void prepareEncoder() throws IOException
{
//set format properties
MediaFormat audioFormat = new MediaFormat();
audioFormat.setString(MediaFormat.KEY_MIME, options.mimeType.get());
audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
audioFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, iSampleRate);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, iSampleDimension);
audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, iSampleNumber);
audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, aByShuffle.length);
//prepare encoder
super.prepareEncoder(audioFormat, options.mimeType.get(), file.getPath());
}
/**
* @param inputBuf ByteBuffer
* @param frameData byte[]
*/
protected final void fillBuffer(ByteBuffer inputBuf, byte[] frameData)
{
inputBuf.put(frameData);
}
}
| 9,267 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Pitch.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/Pitch.java | /*
* Pitch.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import be.tarsos.dsp.pitch.AMDF;
import be.tarsos.dsp.pitch.DynamicWavelet;
import be.tarsos.dsp.pitch.FFTPitch;
import be.tarsos.dsp.pitch.FastYin;
import be.tarsos.dsp.pitch.McLeodPitchMethod;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchDetector;
import be.tarsos.dsp.pitch.Yin;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Computes the pitch (F0) of the input signal
* - uses TarsosDSP
* Created by Johnny on 05.03.2015.
*/
public class Pitch extends Transformer {
public final static int DETECTOR_MPM = 0;
public final static int DYNAMIC_WAVELET = 1;
public final static int FFT_YIN = 2;
public final static int AMDF = 3;
public final static int FFT_PITCH = 4;
public final static int YIN = 5;
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> detector = new Option<>("detector", YIN, Integer.class, "");
public final Option<Boolean> computePitch = new Option<>("computePitch", true, Boolean.class, "output the pitch value");
public final Option<Boolean> computePitchEnvelope = new Option<>("computePitchEnvelope", false, Boolean.class, "output envelope which provides old pitch value again whenever pitch is invalid");
public final Option<Boolean> computeVoicedProb = new Option<>("computeVoicedProb", false, Boolean.class, "output the probability of the sample being voiced");
public final Option<Boolean> computePitchedState = new Option<>("computePitchedState", false, Boolean.class, "output the probability of the sample being pitched");
public final Option<Float> minPitch = new Option<>("minPitch", 52.0f, Float.class, "ignore any sample with pitch below value");
public final Option<Float> maxPitch = new Option<>("maxPitch", 620.0f, Float.class, "ignore any sample with pitch above value");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected PitchDetector _detector;
protected float _lastPitch = 0;
public Pitch()
{
_name = "Pitch";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream audio = null;
for(Stream s : stream_in) {
if (s.findDataClass("Audio") >= 0)
{
audio = s;
}
}
if(audio == null) {
Log.w("invalid input stream");
return;
}
switch(options.detector.get())
{
case DETECTOR_MPM:
_detector = new McLeodPitchMethod((float)audio.sr, audio.num * audio.dim);
break;
case DYNAMIC_WAVELET:
_detector = new DynamicWavelet((float)audio.sr, audio.num * audio.dim);
break;
case FFT_YIN:
_detector = new FastYin((float)audio.sr, audio.num * audio.dim);
break;
case AMDF:
_detector = new AMDF((float)audio.sr, audio.num * audio.dim);
break;
case FFT_PITCH:
_detector = new FFTPitch((int)audio.sr, audio.num * audio.dim);
break;
case YIN:
default:
_detector = new Yin((float)audio.sr, audio.num * audio.dim);
break;
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] data = stream_in[0].ptrF();
float[] out = stream_out.ptrF();
PitchDetectionResult result = _detector.getPitch(data);
float pitch = result.getPitch();
if (pitch > options.maxPitch.get() || pitch < options.minPitch.get())
{
pitch = -1;
}
int dim = 0;
if (options.computePitch.get())
{
out[dim++] = pitch;
}
if (options.computePitchEnvelope.get()) {
if (pitch < 0) {
out[dim++] = _lastPitch;
} else {
out[dim++] = pitch;
_lastPitch = pitch;
}
}
if (options.computeVoicedProb.get())
{
out[dim++] = result.getProbability();
}
if (options.computePitchedState.get())
{
out[dim++] = (result.isPitched() && pitch > 0) ? 1.0f : 0.0f;
}
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{}
@Override
public int getSampleDimension(Stream[] stream_in)
{
int dim = 0;
if(options.computePitch.get()) dim++;
if(options.computePitchEnvelope.get()) dim++;
if(options.computeVoicedProb.get()) dim++;
if(options.computePitchedState.get()) dim++;
return dim;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if(stream_in[0].bytes != 2 && stream_in[0].bytes != 4)
Log.e("Unsupported input stream type");
return 4;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.SHORT && stream_in[0].type != Cons.Type.FLOAT)
Log.e("Unsupported input stream type");
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
int i = 0;
if(options.computePitch.get()) stream_out.desc[i++] = "Pitch";
if(options.computePitchEnvelope.get()) stream_out.desc[i++] = "Pitch";
if(options.computeVoicedProb.get()) stream_out.desc[i++] = "VoicedProb";
if(options.computePitchedState.get()) stream_out.desc[i++] = "PitchedState";
}
}
| 7,539 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Intensity.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/Intensity.java | /*
* Intensity.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Computes audio intensity.
* Based on code from the PRAAT Toolbox by Paul Boersma and David Weenink.
* http://www.fon.hum.uva.nl/praat/
*/
public class Intensity extends Transformer {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Double> minPitch = new Option<>("minPitch", 50., Double.class, "");
public final Option<Double> timeStep = new Option<>("timeStep", 0., Double.class, "");
public final Option<Boolean> subtractMeanPressure = new Option<>("subtractMeanPressure", true, Boolean.class, "");
public final Option<Boolean> mean = new Option<>("mean", false, Boolean.class, "output mean intensity over entire window");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
private double myDuration, windowDuration, halfWindowDuration, outStep;
private int halfWindowSamples, numberOfFrames;
double[] amplitude = null;
double[] window = null;
public Intensity()
{
_name = "Intensity";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream audio = null;
for(Stream s : stream_in) {
if (s.findDataClass("Audio") >= 0)
{
audio = s;
}
}
if(audio == null || audio.type != Cons.Type.FLOAT) {
Log.e("invalid input stream");
return;
}
/*
* Preconditions.
*/
if (options.timeStep.get() < 0.0) throw new IllegalArgumentException("(Sound-to-Intensity:) Time step should be zero or positive instead of " + options.timeStep.get() + ".");
if (options.minPitch.get() <= 0.0) throw new IllegalArgumentException("(Sound-to-Intensity:) Minimum pitch should be positive.");
if (audio.step <= 0.0) throw new IllegalArgumentException ("(Sound-to-Intensity:) The Sound's time step should be positive.");
/*
* Defaults.
*/
halfWindowDuration = 0.5 * windowDuration;
halfWindowSamples = (int)(halfWindowDuration / audio.step);
amplitude = new double[2 * halfWindowSamples +1];
window = new double[2 * halfWindowSamples +1];
double x, root;
for (int i = - halfWindowSamples; i <= halfWindowSamples; i ++) {
x = i * audio.step / halfWindowDuration;
root = 1 - x * x;
window [i + halfWindowSamples] = root <= 0.0 ? 0.0 : AudioUtil.bessel_i0_f((2 * Math.PI * Math.PI + 0.5) * Math.sqrt(root));
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream in = stream_in[0];
Stream out = stream_out;
float[] data = in.ptrF();
float[] outf = out.ptrF();
double intensitySum = 0;
for (int iframe = 0; iframe < numberOfFrames; iframe++)
{
double midTime = in.time + iframe * outStep;
int midSample = (int) (Math.round((midTime - in.time) / in.step + 1.0));
int leftSample = midSample - halfWindowSamples, rightSample = midSample + halfWindowSamples;
double sumxw = 0.0, sumw = 0.0, intensity;
if (leftSample < 0) leftSample = 0;
if (rightSample >= in.num) rightSample = in.num - 1;
for (int channel = 0; channel < in.dim; channel++)
{
for (int i = leftSample; i <= rightSample; i++)
{
amplitude[i - midSample + halfWindowSamples] = data[i * in.dim + channel];
}
if (options.subtractMeanPressure.get())
{
double sum = 0.0;
for (int i = leftSample; i <= rightSample; i++)
{
sum += amplitude[i - midSample + halfWindowSamples];
}
double mean = sum / (rightSample - leftSample + 1);
for (int i = leftSample; i <= rightSample; i++)
{
amplitude[i - midSample + halfWindowSamples] -= mean;
}
}
for (int i = leftSample; i <= rightSample; i++)
{
sumxw += amplitude[i - midSample + halfWindowSamples] * amplitude[i - midSample + halfWindowSamples] * window[i - midSample + halfWindowSamples];
sumw += window[i - midSample + halfWindowSamples];
}
}
intensity = sumxw / sumw;
if (intensity != 0.0) intensity /= 4e-10;
intensity = intensity < 1e-30 ? -300 : 10 * Math.log10(intensity);
if(!options.mean.get())
outf[iframe] = (float) intensity;
else
intensitySum += intensity;
}
if(options.mean.get())
outf[0] = (float)(intensitySum / numberOfFrames);
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return 1;
}
@Override
public void init(double frame, double delta)
{
if(options.timeStep.get() == 0)
options.timeStep.set(0.8 / options.minPitch.get()); // default: four times oversampling Hanning-wise
myDuration = frame + delta;
windowDuration = computeWindowDuration(options.minPitch.get());
if (windowDuration <= 0.0 || windowDuration > myDuration) Log.e("invalid processing window duration");
numberOfFrames = computeNumberOfFrames(myDuration, windowDuration, options.timeStep.get());
if (numberOfFrames < 1) Log.e("The duration of the sound in an intensity analysis should be at least 6.4 divided by the minimum pitch (" + options.minPitch.get() + " Hz), " +
"i.e. at least " + 6.4 / options.minPitch.get() + " s, instead of " + myDuration + " s.");
outStep = frame / numberOfFrames;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return (options.mean.get()) ? 1 : numberOfFrames;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if(stream_in[0].bytes != 4) //float
Log.e("Unsupported input stream type");
return 4;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.FLOAT)
Log.e("Unsupported input stream type");
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Intensity";
}
public static double computeWindowDuration(double minimumPitch)
{
return 6.4 / minimumPitch;
}
public static int computeNumberOfFrames(double frameDuration, double windowDuration, double timeStep)
{
return (int)(Math.floor ((frameDuration - windowDuration) / timeStep) + 1);
}
}
| 8,881 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Energy.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/Energy.java | /*
* Energy.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Audio energy algorithms extracted from TarsosDSP
* Created by Johnny on 05.03.2015.
*/
public class Energy extends Transformer {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Boolean> computeRMS = new Option<>("computeRMS", false, Boolean.class, "");
public final Option<Boolean> computeSPL = new Option<>("computeSPL", true, Boolean.class, "");
public final Option<Boolean> computeSilence = new Option<>("computeSilence", false, Boolean.class, "");
public final Option<Double> silenceThreshold = new Option<>("silenceThreshold", -70.0, Double.class, "in DB, default of -70 defined in TarsosDSP: be.tarsos.dsp.SilenceDetector");
public final Option<Boolean> inputIsSigned = new Option<>("inputIsSigned", true, Boolean.class, "");
public final Option<Boolean> inputIsBigEndian = new Option<>("inputIsBigEndian", false, Boolean.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public Energy()
{
_name = "Energy";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream audio = null;
for(Stream s : stream_in) {
if (s.findDataClass("Audio") >= 0)
{
audio = s;
}
}
if(audio == null) {
Log.w("invalid input stream");
return;
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] data = stream_in[0].ptrF();
float[] out = stream_out.ptrF();
int dim = 0;
if(options.computeRMS.get()) {
out[dim++] = (float)calculateRMS(data);
}
if(options.computeSPL.get() || options.computeSilence.get())
{
double SPL = soundPressureLevel(data);
out[dim++] = (float)SPL;
if(options.computeSilence.get())
{
float silence = ((SPL < options.silenceThreshold.get()) ? 1 : 0);
out[dim++] = silence;
}
}
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{}
@Override
public int getSampleDimension(Stream[] stream_in)
{
int dim = 0;
if(options.computeRMS.get()) dim++;
if(options.computeSPL.get()) dim++;
if(options.computeSilence.get()) dim++;
return dim;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if(stream_in[0].bytes != 4)
Log.e("Unsupported input stream type");
return 4;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.FLOAT)
Log.e("Unsupported input stream type");
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
int i = 0;
if(options.computeRMS.get()) stream_out.desc[i++] = "RMS";
if(options.computeSPL.get()) stream_out.desc[i++] = "SPL";
if(options.computeSilence.get()) stream_out.desc[i++] = "Silence";
}
/****************************************************
* Original code taken from TarsosDSP
* file: be.tarsos.dsp.AudioEvent
*
* TarsosDSP is developed by Joren Six at IPEM, University Ghent
*
* Info: http://0110.be/tag/TarsosDSP
* Github: https://github.com/JorenSix/TarsosDSP
* Releases: http://0110.be/releases/TarsosDSP/
****************************************************/
/**
* Calculates and returns the root mean square of the signal. Please
* cache the result since it is calculated every time.
* @param floatBuffer The audio buffer to calculate the RMS for.
* @return The <a
* href="http://en.wikipedia.org/wiki/Root_mean_square">RMS</a> of
* the signal present in the current buffer.
*/
public static double calculateRMS(float[] floatBuffer){
double rms = 0.0;
for (int i = 0; i < floatBuffer.length; i++) {
rms += floatBuffer[i] * floatBuffer[i];
}
rms = rms / Double.valueOf(floatBuffer.length);
rms = Math.sqrt(rms);
return rms;
}
/**
* Returns the dBSPL for a buffer.
*
* @param buffer
* The buffer with audio information.
* @return The dBSPL level for the buffer.
*/
private double soundPressureLevel(float[] buffer) {
double value = Math.pow(localEnergy(buffer), 0.5);
value = value / buffer.length;
return linearToDecibel(value);
}
/**
* Calculates the local (linear) energy of an audio buffer.
*
* @param buffer
* The audio buffer.
* @return The local (linear) energy of an audio buffer.
*/
private double localEnergy(float[] buffer) {
double power = 0.0D;
for (float element : buffer) {
power += element * element;
}
return power;
}
/**
* Converts a linear to a dB value.
*
* @param value
* The value to convert.
* @return The converted value.
*/
private double linearToDecibel(double value) {
return 20.0 * Math.log10(value);
}
}
| 7,268 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
InfraredChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/glass/InfraredChannel.java | /*
* InfraredChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.glass;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Infrared provider for google glass.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
public class InfraredChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the sensor provider
*/
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "The rate in which the provider samples data from the sensor");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private static final int DIMENSION = 1;
InfraredSensor _irSensor;
public InfraredChannel()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_out Stream
*/
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (_sensor instanceof InfraredSensor)
{
_irSensor = (InfraredSensor)_sensor;
} else
{
throw new RuntimeException(this.getClass() + ": " + _name + ": No Infrared sensor found");
}
}
/**
* @param stream_out Stream
*/
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _irSensor.getData();
return true;
}
/**
* @return double
*/
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
/**
* @return int
*/
@Override
final public int getSampleDimension()
{
return DIMENSION;
}
/**
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
/**
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream stream_out)
{
int dimension = getSampleDimension();
stream_out.desc = new String[dimension];
if (dimension == 1)
{
stream_out.desc[0] = "Infrared";
} else
{
for (int i = 0; i < dimension; i++)
{
stream_out.desc[i] = "Infrared" + i;
}
}
}
}
| 3,933 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BlinkDetection.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/glass/BlinkDetection.java | /*
* BlinkDetection.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.glass;
import java.util.LinkedList;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Blink detection for the infrared sensor of google glass.<br>
* Returns a high signal every time a blink is detected.<br>
* <b>Warning!</b> The nature of the algorithm delays the output by 3 input values.<br>
* Created by Frank Gaibler on 24.08.2015.
*
* @see <a href="https://www.d2.mpi-inf.mpg.de/sites/default/files/ishimaru14_ah.pdf">In the Blink of an Eye</a>
*/
public class BlinkDetection extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
/**
* Peak threshold for blink detection.<br>
* A lower value will detect more alleged blinks.
*/
public final Option<Float> blinkThreshold = new Option<>("blinkThreshold", 3.5f, Float.class, "Peak threshold for blink detection");
/**
* Variance between left and right value of the peak value.<br>
* If the threshold is reached, the blink will not be counted,
* because it is assumed to be a false blink due to high movement.
*/
public final Option<Float> varianceThreshold = new Option<>("varianceThreshold", 25.f, Float.class, "Variance between left and right value of the peak value");
/**
* Count the blinks and return the additive result instead of giving a high signal when a blink occurs.
*/
public final Option<Boolean> countBlink = new Option<>("countBlink", false, Boolean.class, "Count the blinks and return the additive result instead of giving a high signal when a blink occurs");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//constants
private static final int DIMENSION = 1;
//helper variables
private final float timeThreshold = 500;
private float timeSave = timeThreshold + 1;
private final int maxSize = 7;
private int count = 0;
private final LimitedQueue<Float> values = new LimitedQueue<>(maxSize);
/**
*
*/
public BlinkDetection()
{
_name = this.getClass().getSimpleName();
}
/**
* The input stream should consist of 1-dimensional float values
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//no check for a specific type to allow for different providers
if (stream_in.length < 1 || stream_in[0].dim < DIMENSION)
{
Log.e("invalid input stream");
}
//init values
count = 0;
timeSave = timeThreshold + 1;
values.clear();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] dataAcc = stream_in[0].ptrF();
float[] out = stream_out.ptrF();
for (int i = 0; i < stream_in[0].num; i++)
{
//add to fifo
values.add(dataAcc[i]);
//write to output
out[i] = detectBlink(stream_in[0].sr);
}
}
/**
* Detect blinks by comparing the last 7 values.<br>
* The nature of the algorithm delays the output by 3 input values.<br>
* The code is slightly modified to improve computation and to fix obvious mistakes.
*
* @param sampleRate double
* @return float
* @see <a href="https://github.com/shoya140/GlassLogger/blob/master/src/com/mrk1869/glasslogger/MonitoringActivity.java">blink detection github link</a>
*/
private float detectBlink(double sampleRate)
{
if (values.size() == maxSize && timeSave > timeThreshold)
{
float left = (values.get(0) + values.get(1) + values.get(2)) / 3.0f; //average range of values before the probable peak
float right = (values.get(4) + values.get(5) + values.get(6)) / 3.0f; //average range of values after the probable peak
float peak = values.get(3); //the probable peak
if ((left >= peak || peak >= right) && (left <= peak || peak <= right))
{
float left_to_right = Math.abs(right - left);
//check for high variance which indicates unfeasible sensor data
if (left_to_right < options.varianceThreshold.get())
{
float peak_to_left = Math.abs(peak - left);
float peak_to_right = Math.abs(peak - right);
if (peak_to_left >= left_to_right && peak_to_right >= left_to_right)
{
float diff = Math.abs(peak - ((left + right) / 2.0f));
if (diff > options.blinkThreshold.get())
{
timeSave = 0;
return options.countBlink.get() ? ++count : 1;
}
}
}
}
}
timeSave += 1000 / sampleRate;
return options.countBlink.get() ? count : 0;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public final int getSampleDimension(Stream[] stream_in)
{
return DIMENSION;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[DIMENSION];
stream_out.desc[0] = options.countBlink.get() ? "blnkCnt" : "blnk";
}
/**
* Simple fifo implementation.
*
* @param <E> queue type
*/
private class LimitedQueue<E> extends LinkedList<E>
{
private int limit;
/**
* @param limit int
*/
public LimitedQueue(int limit)
{
this.limit = limit;
}
/**
* @param o E
* @return boolean
*/
@Override
public boolean add(E o)
{
super.add(o);
while (size() > limit)
{
super.remove();
}
return true;
}
}
}
| 8,565 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
InfraredSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/glass/InfraredSensor.java | /*
* InfraredSensor.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.glass;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.option.OptionList;
/**
* Infrared sensor for google glass.<br>
* A feature like wink or head detection needs to be enabled for the sensor to work.
* To get IR-Sensor permission on glass, go to console and type in the following commands:
* $ adb root (start adb anew with root permissions)
* $ adb shell (open shell on glass)
* cd sys/bus/i2c/devices/4-0035 (go to infrared sensor)
* chmod 664 proxraw (change file permissions)
* ls -l proxraw (inspect file permissions (-rw-rw-r--))
* exit (exit shell)
* Created by Frank Gaibler on 13.08.2015.
*/
public class InfraredSensor extends hcm.ssj.core.Sensor
{
private static final float ERROR = -1;
private boolean report = true; //prevent message flooding
/**
*
*/
public InfraredSensor()
{
_name = this.getClass().getSimpleName();
}
/**
*
*/
@Override
protected boolean connect() throws SSJFatalException
{
report = true;
return true;
}
/**
*
*/
@Override
protected void disconnect() throws SSJFatalException
{
}
/**
* @return float
*/
protected float getData()
{
try
{
Process process = Runtime.getRuntime().exec("cat /sys/bus/i2c/devices/4-0035/proxraw");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[8];
StringBuilder output = new StringBuilder();
while ((read = reader.read(buffer)) > 0)
{
output.append(buffer, 0, read);
}
reader.close();
String result = output.toString();
if (result.length() > 0)
{
return Float.valueOf(result);
}
} catch (IOException e)
{
e.printStackTrace();
}
if (report)
{
report = false;
Log.e("Check permissions on glass");
}
return ERROR;
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 3,765 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BeaconChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/estimote/BeaconChannel.java | /*
* BeaconChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.estimote;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 08.03.2017.
*/
public class BeaconChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 5, Integer.class, "");
public final Option<String> identifier = new Option<>("identifier", "", String.class, "MAC address or UUID:Major:Minor");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
BeaconListener listener;
public BeaconChannel()
{
_name = "BeaconChannel";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
listener = ((EstimoteBeacon) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = (float) listener.getDistance(options.identifier.get());
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Distance";
}
}
| 2,930 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BeaconListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/estimote/BeaconListener.java | /*
* BeaconListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.estimote;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import com.estimote.sdk.Utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Michael Dietz on 08.03.2017.
*/
public class BeaconListener implements BeaconManager.RangingListener
{
private static final int TIMEOUT = 60 * 1000; //in ms
private long lastDataTimestamp;
private Map<String, Double> beaconDistances;
private EstimoteBeacon.IdentificationMode idMode;
public BeaconListener()
{
reset();
}
public void reset()
{
lastDataTimestamp = 0;
beaconDistances = new HashMap<>();
}
@Override
public void onBeaconsDiscovered(Region region, List<Beacon> list)
{
dataReceived();
for (Beacon beacon : list)
{
beaconDistances.put(getIdentifier(beacon), calculateDistance(beacon));
}
}
private String getIdentifier(Beacon beacon)
{
String key = beacon.getMacAddress().toStandardString();
if (idMode == EstimoteBeacon.IdentificationMode.UUID_MAJOR_MINOR)
{
key = beacon.getProximityUUID() + ":" + beacon.getMajor() + ":" + beacon.getMinor();
}
return key;
}
public double getDistance(String beaconIdentifier)
{
double distance = -1;
if (beaconDistances.containsKey(beaconIdentifier.toLowerCase()))
{
distance = beaconDistances.get(beaconIdentifier.toLowerCase());
}
return distance;
}
private double calculateDistance(Beacon beacon)
{
double calculatedDistance = Math.pow(10d, ((double) beacon.getMeasuredPower() - beacon.getRssi()) / (10 * 4));
double estimoteDistance = Utils.computeAccuracy(beacon);
return (calculatedDistance + estimoteDistance) / 2.0;
}
private void dataReceived()
{
lastDataTimestamp = System.currentTimeMillis();
}
public boolean isConnected()
{
return System.currentTimeMillis() - lastDataTimestamp < TIMEOUT;
}
public boolean hasReceivedData()
{
return lastDataTimestamp != 0;
}
public void setIdMode(EstimoteBeacon.IdentificationMode idMode)
{
this.idMode = idMode;
}
}
| 3,470 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EstimoteBeacon.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/estimote/EstimoteBeacon.java | /*
* EstimoteBeacon.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.estimote;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import java.util.UUID;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Michael Dietz on 08.03.2017.
*/
public class EstimoteBeacon extends Sensor implements BeaconManager.ServiceReadyCallback
{
@Override
public OptionList getOptions()
{
return options;
}
public enum IdentificationMode
{
MAC_ADDRESS,
UUID_MAJOR_MINOR
}
public class Options extends OptionList
{
public final Option<String> region = new Option<>("region", "beacon region", String.class, "");
public final Option<String> uuid = new Option<>("uuid", "", String.class, "");
public final Option<Integer> major = new Option<>("major", null, Integer.class, "");
public final Option<Integer> minor = new Option<>("minor", null, Integer.class, "");
public final Option<IdentificationMode> idMode = new Option<>("idMode", IdentificationMode.UUID_MAJOR_MINOR, IdentificationMode.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BeaconManager beaconManager;
protected BeaconListener listener;
protected Region region;
protected boolean connected;
public EstimoteBeacon()
{
_name = "EstimoteBeacon";
listener = new BeaconListener();
}
@Override
protected boolean connect() throws SSJFatalException
{
Log.i("Connecting to estimote beacons");
connected = false;
listener.reset();
listener.setIdMode(options.idMode.get());
region = new Region(options.region.get(), options.uuid.get() != null ? UUID.fromString(options.uuid.get()) : null, options.major.get(), options.minor.get());
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
beaconManager = new BeaconManager(SSJApplication.getAppContext());
beaconManager.connect(EstimoteBeacon.this);
beaconManager.setRangingListener(listener);
beaconManager.setForegroundScanPeriod(200, 0);
//beaconManager.setBackgroundScanPeriod(200, 0);
}
}, 1);
long time = SystemClock.elapsedRealtime();
while (!_terminate && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException e)
{
}
}
if (!connected)
{
Log.e("Unable to connect to estimote beacons");
}
return connected;
}
@Override
public void onServiceReady()
{
Log.i("Estimote service ready, starting ranging");
connected = true;
beaconManager.startRanging(region);
}
@Override
protected void disconnect() throws SSJFatalException
{
connected = false;
if (beaconManager != null && region != null)
{
beaconManager.stopRanging(region);
beaconManager.disconnect();
}
}
}
| 4,513 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileCons.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileCons.java | /*
* FileCons.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import android.os.Build;
import android.os.Environment;
import java.io.File;
import hcm.ssj.core.SSJApplication;
/**
* Constants used for the file operations<br>
* Created by Frank Gaibler on 31.08.2015.
*/
public class FileCons
{
public static final String DELIMITER_DIMENSION = " ";
public static final String DELIMITER_LINE = "\r\n"; //works on android and windows, System.getProperty("line.separator") might not
public static final String TAG_DATA_FILE = "~";
public static final String DELIMITER_ANNOTATION = ";";
public static final String FILE_EXTENSION_STREAM = "stream";
public static final String FILE_EXTENSION_EVENT = "events";
public static final String FILE_EXTENSION_ANNO_PLAIN = "anno";
public static final String FILE_EXTENSION_ANNO = "annotation";
public static final String FILE_EXTENSION_TRAINER = "trainer";
public static final String FILE_EXTENSION_MODEL = "model";
public static final String FILE_EXTENSION_OPTION= "option";
public static final String SSJ_EXTERNAL_STORAGE = new File(Environment.getExternalStorageDirectory(), "SSJ").getPath();
public static final String SSJ_DATA = SSJ_EXTERNAL_STORAGE + File.separator + "Data";
public static final String DOWNLOAD_DIR = SSJ_EXTERNAL_STORAGE + File.separator + "download";
public static final String MODELS_DIR = SSJ_EXTERNAL_STORAGE + File.separator + "models";
public static final String CONFIGS_DIR = SSJ_EXTERNAL_STORAGE + File.separator + "configs";
public static final String INTERNAL_LIB_DIR = SSJApplication.getAppContext().getApplicationInfo().nativeLibraryDir + File.separator; //getFilesDir().toString() + "/lib";
public static final String REMOTE_LIB_PATH = "https://hcm-lab.de/downloads/ssj/lib/" + Build.CPU_ABI;
public static final String REMOTE_MODEL_PATH = "https://hcm-lab.de/downloads/ssj/model";
}
| 3,244 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SimpleXmlParser.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/SimpleXmlParser.java | /*
* SimpleXmlParser.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* A generic XML-Parser for one tag and its attributes.<br>
* Created by Frank Gaibler on 23.09.2015.
*/
public class SimpleXmlParser
{
private static final String namespace = null;
private String[] searchPath = null;
private String[] searchAttributes = null;
private XmlValues xmlValues;
/**
* @param in InputStream
* @param searchPath String[]
* @param searchAttributes String[]
* @return XmlValues
* @throws XmlPullParserException XML Exception
* @throws IOException IO Exception
*/
public XmlValues parse(InputStream in, String[] searchPath, String[] searchAttributes) throws XmlPullParserException, IOException
{
this.searchPath = searchPath;
this.searchAttributes = searchAttributes;
xmlValues = new XmlValues();
try
{
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
search(parser, 0);
return xmlValues;
} finally
{
in.close();
}
}
/**
* @param parser XmlPullParser
* @param depth int
* @throws XmlPullParserException
* @throws IOException
*/
private void search(XmlPullParser parser, int depth) throws XmlPullParserException, IOException
{
parser.require(XmlPullParser.START_TAG, namespace, searchPath[depth]);
if (searchPath.length - 1 == depth)
{
readValues(parser, depth);
} else
{
while (parser.next() != XmlPullParser.END_TAG)
{
if (parser.getEventType() == XmlPullParser.START_TAG)
{
if (parser.getName().equals(searchPath[depth + 1]))
{
search(parser, depth + 1);
} else
{
skip(parser);
}
}
}
}
}
/**
* @param parser XmlPullParser
* @param depth int
* @throws IOException
* @throws XmlPullParserException
*/
private void readValues(XmlPullParser parser, int depth) throws IOException, XmlPullParserException
{
String name = searchPath[depth];
parser.require(XmlPullParser.START_TAG, namespace, name);
if (searchAttributes == null)
{
xmlValues.foundTag.add(readText(parser));
} else
{
String tag = parser.getName();
if (tag.equals(name))
{
String[] attributes = new String[searchAttributes.length];
for (int i = 0; i < searchAttributes.length; i++)
{
attributes[i] = parser.getAttributeValue(null, searchAttributes[i]);
}
xmlValues.foundAttributes.add(attributes);
parser.nextTag();
}
}
}
/**
* @param parser XmlPullParser
* @return String
* @throws IOException
* @throws XmlPullParserException
*/
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException
{
String result = "";
if (parser.next() == XmlPullParser.TEXT)
{
result = parser.getText();
parser.nextTag();
}
return result;
}
/**
* @param parser XmlPullParser
* @throws XmlPullParserException
* @throws IOException
*/
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException
{
if (parser.getEventType() != XmlPullParser.START_TAG)
{
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0)
{
switch (parser.next())
{
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
/**
* To return the found values.
*/
public class XmlValues
{
public ArrayList<String> foundTag = new ArrayList<>();
public ArrayList<String[]> foundAttributes = new ArrayList<>();
private XmlValues()
{
}
}
}
| 6,024 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileReaderChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileReaderChannel.java | /*
* FileReaderChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Monitor;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* File reader provider for SSJ.<br>
* Created by Frank Gaibler on 20.08.2015.
*/
public class FileReaderChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
/**
*
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<String> separator = new Option<>("separator", FileCons.DELIMITER_DIMENSION, String.class, "Attribute separator of the file");
public final Option<Double> offset = new Option<>("offset", 0.0, Double.class, "start reading from indicated time (in seconds)");
public final Option<Double> chunk = new Option<>("chunk", 0.1, Double.class, "how many samples to read at once (in seconds)");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private FileReader fileReader;
private byte[] buffer;
private double sampleRate;
private int dimension;
private int num;
private int bytes;
private Cons.Type type;
private Cons.FileType ftype;
/**
*
*/
public FileReaderChannel()
{
super();
_name = this.getClass().getSimpleName();
}
/**
*
*/
@Override
protected void init() throws SSJException
{
fileReader = (FileReader) _sensor;
SimpleHeader simpleHeader;
try
{
fileReader.readerInit();
simpleHeader = fileReader.getSimpleHeader();
}
catch (IOException | XmlPullParserException e)
{
throw new SSJException("error initializing file reader", e);
}
sampleRate = Double.parseDouble(simpleHeader._sr);
dimension = Integer.parseInt(simpleHeader._dim);
bytes = Integer.parseInt(simpleHeader._byte);
double minChunk = 1.0 / sampleRate;
if(options.chunk.get() < minChunk) {
Log.w("chunk size too small, setting to " + minChunk + "s");
options.chunk.set(minChunk);
}
num = (int)(sampleRate * options.chunk.get() + 0.5);
type = Cons.Type.valueOf(simpleHeader._type);
ftype = Cons.FileType.valueOf(simpleHeader._ftype);
buffer = new byte[num*dimension*bytes];
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (options.offset.get() > 0)
{
fileReader.skip((int) (stream_out.sr * options.offset.get()));
}
}
/**
* @param stream_out Stream
*/
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if(ftype == Cons.FileType.ASCII)
{
for(int i = 0; i < num; ++i) {
switch (type) {
case BOOL: {
boolean[] out = stream_out.ptrBool();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Boolean.valueOf(separated[k]);
}
break;
}
case BYTE: {
byte[] out = stream_out.ptrB();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Byte.valueOf(separated[k]);
}
break;
}
case CHAR: {
char[] out = stream_out.ptrC();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = separated[k].charAt(0);
}
break;
}
case SHORT: {
short[] out = stream_out.ptrS();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Short.valueOf(separated[k]);
}
break;
}
case INT: {
int[] out = stream_out.ptrI();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Integer.valueOf(separated[k]);
}
break;
}
case LONG: {
long[] out = stream_out.ptrL();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Long.valueOf(separated[k]);
}
break;
}
case FLOAT: {
float[] out = stream_out.ptrF();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Float.parseFloat(separated[k]);
}
break;
}
case DOUBLE: {
double[] out = stream_out.ptrD();
String[] separated = getData();
for (int k = 0; k < dimension; k++) {
out[i * dimension + k] = Double.valueOf(separated[k]);
}
break;
}
default:
Log.w("unsupported data type");
return false;
}
}
}
else if(ftype == Cons.FileType.BINARY)
{
int numBytes = num * dimension * bytes;
fileReader.getDataBinary(buffer, numBytes);
Util.arraycopy(buffer, 0, stream_out.ptr(), 0, numBytes);
}
return true;
}
/**
* @return String[]
*/
private String[] getData()
{
String data = fileReader.getDataASCII();
String[] result;
if (data != null)
{
result = data.split(options.separator.get());
}
else
{
//notify listeners
Monitor.notifyMonitor();
result = new String[dimension];
Arrays.fill(result, "0");
}
return result;
}
/**
* @return double
*/
@Override
public double getSampleRate()
{
return sampleRate;
}
/**
* @return int
*/
@Override
final public int getSampleDimension()
{
return dimension;
}
/**
* @return int
*/
@Override
final public int getSampleNumber()
{
return num;
}
/**
* @return int
*/
@Override
public int getSampleBytes()
{
return Util.sizeOf(type);
}
/**
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType()
{
return type;
}
/**
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[dimension];
if (options.outputClass.get() != null)
{
if (dimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0; i < dimension; i++)
{
stream_out.desc[i] = "SFRP" + i;
}
}
}
| 10,023 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileReader.java | /*
* FileReader.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.FilePath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* File reader for SSJ.<br>
* Created by Frank Gaibler on 20.08.2015.
*/
public class FileReader extends Sensor
{
@Override
public OptionList getOptions()
{
return options;
}
/**
*
*/
public class Options extends OptionList
{
public final Option<FilePath> file = new Option<>("file", null, FilePath.class, "file path");
public final Option<Boolean> loop = new Option<>("loop", true, Boolean.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private File fileHeader;
private File fileReal;
private BufferedInputStream inputBinary = null;
private BufferedReader inputASCII = null;
private int pos;
private SimpleHeader simpleHeader = null;
private boolean initialized = false;
/**
*
*/
public FileReader()
{
_name = this.getClass().getSimpleName();
}
/**
* Initialize reader
*
* @throws IOException IO Exception
*/
protected final void readerInit() throws IOException
{
if (!initialized)
{
initialized = true;
if (options.file.get() == null)
{
throw new IOException("file not specified");
}
this.fileHeader = new File(options.file.get().value);
setFiles();
}
}
/**
*
*/
@Override
protected boolean connect() throws SSJFatalException
{
try
{
readerInit();
simpleHeader = getSimpleHeader();
}
catch (IOException | XmlPullParserException e)
{
throw new SSJFatalException("unable to initialize file reader", e);
}
if (simpleHeader._ftype.equals("BINARY"))
{
inputBinary = getFileConnection(fileReal, inputBinary);
}
else if (simpleHeader._ftype.equals("ASCII"))
{
inputASCII = getFileConnection(fileReal, inputASCII);
}
pos = 0;
return true;
}
/**
* Get simple header
*
* @return SimpleHeader
* @throws IOException IO Exception
* @throws XmlPullParserException XML Exception
*/
protected SimpleHeader getSimpleHeader() throws IOException, XmlPullParserException
{
if (simpleHeader == null)
{
SimpleXmlParser simpleXmlParser = new SimpleXmlParser();
SimpleXmlParser.XmlValues xmlValues = simpleXmlParser.parse(
new FileInputStream(fileHeader),
new String[]{"stream", "info"},
new String[]{"ftype", "sr", "dim", "byte", "type"}
);
simpleHeader = new SimpleHeader();
simpleHeader._ftype = xmlValues.foundAttributes.get(0)[0];
simpleHeader._sr = xmlValues.foundAttributes.get(0)[1];
simpleHeader._dim = xmlValues.foundAttributes.get(0)[2];
simpleHeader._byte = xmlValues.foundAttributes.get(0)[3];
simpleHeader._type = xmlValues.foundAttributes.get(0)[4];
xmlValues = simpleXmlParser.parse(
new FileInputStream(fileHeader),
new String[]{"stream", "chunk"},
new String[]{"from", "to", "num"}
);
simpleHeader._from = xmlValues.foundAttributes.get(0)[0];
simpleHeader._to = xmlValues.foundAttributes.get(0)[1];
simpleHeader._num = xmlValues.foundAttributes.get(0)[2];
}
return simpleHeader;
}
/**
*
*/
private void setFiles()
{
String path = fileHeader.getPath();
if (path.endsWith(FileCons.TAG_DATA_FILE))
{
fileReal = fileHeader;
fileHeader = new File(path.substring(0, path.length() - 1));
} else if (fileHeader.getName().contains("."))
{
fileReal = new File(path + FileCons.TAG_DATA_FILE);
} else
{
fileHeader = new File(path + "." + FileCons.FILE_EXTENSION_STREAM);
fileReal = new File(path + "." + FileCons.FILE_EXTENSION_STREAM + FileCons.TAG_DATA_FILE);
}
}
/**
* @param reader BufferedReader
* @return BufferedReader
*/
private BufferedInputStream closeStream(BufferedInputStream reader)
{
if (reader != null)
{
try
{
reader.close();
reader = null;
} catch (IOException e)
{
Log.e("could not close reader", e);
}
}
return reader;
}
/**
* @param reader BufferedReader
* @return BufferedReader
*/
private BufferedReader closeStream(BufferedReader reader)
{
if (reader != null)
{
try
{
reader.close();
reader = null;
} catch (IOException e)
{
Log.e("could not close reader", e);
}
}
return reader;
}
/**
*
*/
@Override
protected void disconnect() throws SSJFatalException
{
inputBinary = closeStream(inputBinary);
inputASCII = closeStream(inputASCII);
initialized = false;
}
/**
* @param file File
* @param stream BufferedInputStream
* @return BufferedInputStream
*/
private BufferedInputStream getFileConnection(File file, BufferedInputStream stream)
{
if (stream != null)
{
stream = closeStream(stream);
}
try
{
InputStream inputStream = new FileInputStream(file);
stream = new BufferedInputStream(inputStream);
} catch (FileNotFoundException e)
{
Log.e("file not found", e);
}
return stream;
}
/**
* @param file File
* @param reader BufferedReader
* @return BufferedReader
*/
private BufferedReader getFileConnection(File file, BufferedReader reader)
{
if (reader != null)
{
reader = closeStream(reader);
}
try
{
InputStream inputStream = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(inputStream));
} catch (FileNotFoundException e)
{
Log.e("file not found", e);
}
return reader;
}
/**
* @param reader BufferedReader
* @return String
*/
private String readLine(BufferedReader reader)
{
String line = null;
if (reader != null)
{
try
{
line = reader.readLine();
} catch (IOException e)
{
Log.e("could not read line", e);
}
}
return line;
}
/**
* @param stream BufferedInputStream
* @return String
*/
private int read(BufferedInputStream stream, byte[] buffer, int numBytes)
{
int ret = 0;
if (stream != null)
{
try
{
ret = stream.read(buffer, 0, numBytes);
} catch (IOException e)
{
Log.e("could not read line", e);
}
}
return ret;
}
/**
* @return String
*/
protected String getDataASCII()
{
String data = readLine(inputASCII);
if (data == null && options.loop.get())
{
Log.d("end of file reached, looping");
inputASCII = getFileConnection(fileReal, inputASCII);
data = readLine(inputASCII);
}
return data;
}
protected int getDataBinary(byte[] buffer, int numBytes)
{
int ret = read(inputBinary, buffer, numBytes);
if(ret == -1 && options.loop.get())
{
Log.d("end of file reached, looping");
inputBinary = getFileConnection(fileReal, inputBinary);
ret = read(inputBinary, buffer, numBytes);
if(ret <= 0)
Log.e("unexpected error reading from file");
}
if(numBytes != ret)
Log.e("unexpected amount of bytes read from file");
return ret;
}
protected void skip(int bytes)
{
try {
inputBinary.skip(bytes);
} catch (IOException e) {
Log.e("exception while skipping bytes", e);
}
}
}
| 10,381 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileDownloader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileDownloader.java | /*
* FileDownloader.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.LinkedList;
import java.util.Locale;
import hcm.ssj.core.Log;
/**
* Created by Ionut Damian on 08.09.2017.
*/
public class FileDownloader extends Thread
{
private static final int BUFFER_SIZE = 4096;
private static final int BYTES_IN_MEGABYTE = 1000000;
private static final int EOF = -1;
private static final int LOG_STEP = 200;
private boolean terminate = false;
private LinkedList<Task> queue = new LinkedList<>();
public class Task
{
String filename;
String from;
String to;
Boolean result = false;
final Object token = new Object();
public Task(String filename, String from, String to)
{
this.filename = filename;
this.from = from;
this.to = to;
}
}
@Override
public void run()
{
while(!terminate)
{
if(!queue.isEmpty())
{
Task t = queue.removeFirst();
try
{
t.result = downloadFile(t.filename, t.from, t.to);
}
catch (IOException | NullPointerException e)
{
Log.e("Error while downloading file", e);
}
synchronized (t.token)
{
t.token.notify();
}
}
else
{
//wait to see if something new comes
try { Thread.sleep(3000); }
catch (InterruptedException e){}
//if not, terminate
if(queue.isEmpty())
terminate();
}
}
}
public Task addToQueue(String fileName, String from, String to)
{
if(isTerminating())
return null;
Task t = new Task(fileName, from, to);
queue.addLast(t);
return t;
}
public boolean wait(Task t)
{
try
{
synchronized (t.token)
{
t.token.wait();
}
}
catch (InterruptedException e) {}
return t.result;
}
/**
* Downloads file from a given URL and saves it on the SD card with a given file name.
*
* @param fileName Name of the file.
* @param from Folder URL where file is located.
* @param to Folder to where to download the file
* @return Instance of the downloaded file.
*/
private boolean downloadFile(String fileName, String from, String to) throws IOException, NullPointerException
{
File destinationDir = new File(to);
// Create folders on the SD card if not already created.
destinationDir.mkdirs();
File downloadedFile = new File(destinationDir.getAbsolutePath(), fileName);
if (!downloadedFile.exists() || downloadedFile.length() == 0)
{
Log.i("Starting to download '" + fileName + "'...");
URL fileURL = new URL(from + File.separator + fileName);
InputStream input = fileURL.openStream();
FileOutputStream output = new FileOutputStream(downloadedFile);
byte[] buffer = new byte[BUFFER_SIZE];
int numberOfBytesRead;
int totalBytesDownloaded = 0;
int counter = 0;
while ((numberOfBytesRead = input.read(buffer)) != EOF)
{
if (terminate)
{
Log.i("Download interrupted.");
downloadedFile.delete();
return false;
}
output.write(buffer, 0, numberOfBytesRead);
totalBytesDownloaded += numberOfBytesRead;
if (counter % LOG_STEP == 0)
{
String progress = String.format(Locale.US, "%.2f", (float)totalBytesDownloaded / (float)BYTES_IN_MEGABYTE);
Log.i("File '" + fileName + "' " + progress + " Mb downloaded.");
}
counter++;
}
input.close();
output.close();
String progress = String.format(Locale.US, "%.2f", (float)totalBytesDownloaded / BYTES_IN_MEGABYTE);
Log.i("File '" + fileName + "' " + progress + " Mb downloaded.");
Log.i("File '" + fileName + "' downloaded successfully.");
}
return true;
}
public void terminate()
{
terminate = true;
}
public boolean isTerminating()
{
return terminate;
}
}
| 5,107 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SimpleHeader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/SimpleHeader.java | /*
* SimpleHeader.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
/**
* Simple header file.<br>
* Created by Frank Gaibler on 31.08.2015.
*/
class SimpleHeader
{
protected final static String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS";
private final static String _version = "1.0";
private final static String _ssi_v = "2";
protected String _ftype = "ASCII";
protected String _sr = "50.0";
protected String _dim = "1";
protected String _byte = "4";
protected String _type = "FLOAT";
protected String _ms = "0";
protected String _local = "00/00/00 00:00:00:0";
protected String _system = "00/00/00 00:00:00:0";
protected String _from = "0.0";
protected String _to = "0.0";
private final static String _byte2 = "0";
protected String _num = "0";
/**
* @return String
*/
protected String getLine1()
{
return "<?xml version=\"" + _version + "\" ?>";
}
/**
* @return String
*/
protected String getLine2()
{
return "<stream ssi-v=\"" + _ssi_v + "\">";
}
/**
* @return String
*/
protected String getLine3()
{
return "<info ftype=\"" + _ftype + "\" sr=\"" + _sr + "\" dim=\"" + _dim + "\" byte=\"" + _byte + "\" type=\"" + _type + "\" />";
}
/**
* @return String
*/
protected String getLine4()
{
return "<time ms=\"" + _ms + "\" local=\"" + _local + "\" system=\"" + _system + "\"/>";
}
/**
* @return String
*/
protected String getLine5()
{
return "<chunk from=\"" + _from + "\" to=\"" + _to + "\" byte=\"" + _byte2 + "\" num=\"" + _num + "\"/>";
}
/**
* @return String
*/
protected String getLine6()
{
return "</stream>";
}
}
| 3,095 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Mp4Writer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/Mp4Writer.java | /*
* Mp4Writer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import android.annotation.TargetApi;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Build;
import android.text.TextUtils;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.FolderPath;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Parent class to create mp4-files.<br>
* Created by Frank Gaibler on 18.02.2016.
*/
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public abstract class Mp4Writer extends Consumer implements IFileWriter
{
private static final int SENDEND_TIMEOUT = 2000;
private static final int SENDEND_SLEEP = 100;
//encoder
protected double dFrameRate;
protected MediaCodec mediaCodec;
//muxer
protected MediaMuxer mediaMuxer;
protected int iTrackIndex;
protected boolean bMuxerStarted;
protected MediaCodec.BufferInfo bufferInfo;
//
protected byte[] aByShuffle;
protected long lFrameIndex;
protected final static int TIMEOUT_USEC = 10000;
//
private ByteBuffer[] aByteBufferInput = null;
//
protected File file = null;
/**
* @param inputBuf ByteBuffer
* @param frameData byte[]
* @throws IOException IO Exception
*/
protected abstract void fillBuffer(ByteBuffer inputBuf, byte[] frameData) throws IOException;
/**
* @param stream_in Stream[]
*/
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{
releaseEncoder();
aByShuffle = null;
bufferInfo = null;
}
/**
* Checks for file consistency
*
* @param in Input stream
* @param options Options
*/
protected final void initFiles(Stream in, Options options)
{
if (options.filePath.get() == null)
{
Log.w("file path not set, setting to default " + FileCons.SSJ_EXTERNAL_STORAGE);
options.filePath.set(new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE));
}
File fileDirectory = Util.createDirectory(options.filePath.parseWildcards());
if (options.fileName.get() == null)
{
String defaultName = TextUtils.join("_", in.desc) + ".mp4";
Log.w("file name not set, setting to " + defaultName);
options.fileName.set(defaultName);
}
file = new File(fileDirectory, options.fileName.get());
}
/**
* Configures the encoder
*
* @param mediaFormat MediaFormat
* @param mimeType String
* @param filePath String
* @throws IOException IO Exception
*/
protected final void prepareEncoder(MediaFormat mediaFormat, String mimeType, String filePath) throws IOException
{
//create and start encoder
try
{
mediaCodec = MediaCodec.createEncoderByType(mimeType);
mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();
aByteBufferInput = mediaCodec.getInputBuffers();
} catch (IOException ex)
{
throw new IOException("MediaCodec creation failed", ex);
}
//create muxer
try
{
mediaMuxer = new MediaMuxer(filePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
} catch (IOException ex)
{
throw new IOException("MediaMuxer creation failed", ex);
}
iTrackIndex = -1;
bMuxerStarted = false;
}
/**
* Releases encoder resources
*/
protected final void releaseEncoder()
{
if (mediaCodec != null)
{
sendEnd();
mediaCodec.release();
mediaCodec = null;
}
if (mediaMuxer != null)
{
if (bMuxerStarted)
{
mediaMuxer.stop();
}
mediaMuxer.release();
mediaMuxer = null;
}
aByteBufferInput = null;
}
/**
* @param frameData byte[]
* @throws IOException IO Exception
*/
protected final void encode(byte[] frameData) throws IOException
{
int inputBufIndex = mediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
if (inputBufIndex >= 0)
{
long ptsUsec = computePresentationTime(lFrameIndex);
ByteBuffer inputBuf = aByteBufferInput[inputBufIndex];
//the buffer should be sized to hold one full frame
if (inputBuf.capacity() < frameData.length)
{
throw new IOException("Buffer capacity too small: " + inputBuf.capacity() + "\tdata: " + frameData.length);
}
else
{
inputBuf.clear();
fillBuffer(inputBuf, frameData);
mediaCodec.queueInputBuffer(inputBufIndex, 0, frameData.length, ptsUsec, 0);
}
} else
{
//either all in use, time out during initial setup
Log.w("Input buffer not available. Skipped frame: " + lFrameIndex);
}
lFrameIndex++;
}
/**
* @param last boolean
*/
protected final synchronized void save(boolean last)
{
//save data until none is available
while (true)
{
ByteBuffer[] encoderOutputBuffers = mediaCodec.getOutputBuffers();
int encoderStatus = mediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);
if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER)
{
//no output available yet
if (last)
{
//try again until buffer sends the end event flag
try
{
//small timeout to ease CPU usage
wait(0, 10000);
} catch (InterruptedException ex)
{
Log.e(ex.getMessage());
ex.printStackTrace();
}
} else
{
break;
}
} else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED)
{
//not expected for an encoder
Log.d("Encoder output buffers changed: " + lFrameIndex);
break;
} else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED)
{
//should happen before receiving buffers and should only happen once
if (bMuxerStarted)
{
Log.e("image format changed unexpectedly");
return;
}
MediaFormat newFormat = mediaCodec.getOutputFormat();
Log.d("Encoder output format changed: " + newFormat);
//start muxer
iTrackIndex = mediaMuxer.addTrack(newFormat);
mediaMuxer.start();
bMuxerStarted = true;
} else if (encoderStatus < 0)
{
Log.e("Unexpected result from encoder.dequeueOutputBuffer: " + encoderStatus);
break;
} else if (encoderStatus >= 0)
{
//get data from encoder and send it to muxer
ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
if (encodedData == null)
{
Log.e("EncoderOutputBuffer " + encoderStatus + " was null" + ": " + lFrameIndex);
return;
}
encodedData.position(bufferInfo.offset);
encodedData.limit(bufferInfo.offset + bufferInfo.size);
mediaMuxer.writeSampleData(iTrackIndex, encodedData, bufferInfo);
mediaCodec.releaseOutputBuffer(encoderStatus, false);
//check for end of stream
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0)
{
break;
}
}
}
}
/**
* Send end of stream to encoder
*/
private void sendEnd()
{
int inputBufIndex = -1;
double time = _frame.getTime();
//try to get a valid input buffer to close the writer
while (inputBufIndex < 0)
{
inputBufIndex = mediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
if (_frame.getTime() > time + SENDEND_TIMEOUT)
{
break;
}
try
{
Thread.sleep(SENDEND_SLEEP);
} catch (InterruptedException ex)
{
Log.e("Thread interrupted: " + lFrameIndex);
}
}
if (inputBufIndex >= 0)
{
long ptsUsec = computePresentationTime(lFrameIndex);
//send an empty frame with the end-of-stream flag set
mediaCodec.queueInputBuffer(inputBufIndex, 0, 0, ptsUsec, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
//save every frame still unprocessed
save(true);
} else
{
//either all in use, time out during initial setup
Log.w("Input buffer not available for last frame: " + lFrameIndex);
}
}
/**
* Generates the presentation time for frame N, in microseconds
*/
private long computePresentationTime(long frameIndex)
{
return (long) (132L + frameIndex * 1000000L / dFrameRate);
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 11,109 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IFileWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/IFileWriter.java | /*
* IFileWriter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import java.io.File;
import hcm.ssj.core.option.FolderPath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Standard file options.<br>
* Created by Frank Gaibler on 22.09.2016.
*/
public interface IFileWriter
{
/**
* Standard options
*/
class Options extends OptionList
{
public final Option<FolderPath> filePath = new Option<>("path", new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "[time]"), FolderPath.class, "where to save the file");
public final Option<String> fileName = new Option<>("fileName", null, String.class, "file name");
/**
*
*/
protected Options()
{
addOptions();
}
}
}
| 2,119 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileUtils.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileUtils.java | /*
* FileUtils.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
/**
* Allows to download files from a valid URL and saves them in a predetermined folder on
* the SD card.
*
* @author Vitaly
*/
public class FileUtils
{
/**
* @param dirPath Directory
* @param fileName Filename
* @return File
* @throws IOException IO Exception
*/
public static File getFile(String dirPath, String fileName) throws IOException
{
boolean isURL = dirPath.startsWith("http://") || dirPath.startsWith("https://");
if (isURL)
{
Pipeline.getInstance().download(fileName, dirPath, FileCons.DOWNLOAD_DIR, true);
dirPath = FileCons.DOWNLOAD_DIR;
}
if (dirPath == null)
{
Log.w("file path not set, setting to default " + FileCons.SSJ_EXTERNAL_STORAGE);
dirPath = FileCons.SSJ_EXTERNAL_STORAGE;
}
File fileDirectory = new File(dirPath);
if (fileName == null)
{
Log.e("file name not set");
return null;
}
return new File(fileDirectory, fileName);
}
/**
* Copy file from source to target
*
* @param filename File name
* @param from Source directory
* @param to Target directory
* @throws IOException IO Exception
*/
public static void copyFile(String filename, String from, String to) throws IOException
{
InputStream in = new FileInputStream(new File(from, filename));
File dir = new File(to);
if (!dir.exists())
dir.mkdirs();
OutputStream out = new FileOutputStream(new File(dir, filename));
copyFile(in, out);
}
/**
* Copy input stream to output stream
*
* @param in Input stream
* @param out Output stream
* @throws IOException IO Exception
*/
public static void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
/**
* Copies an asset to a target location
*
* @param context Context
* @param sourcePath Source path
* @param targetPath Target path
*/
public static void copyAsset(Context context, String sourcePath, String targetPath)
{
try
{
InputStream in = context.getAssets().open(sourcePath);
File targetFile = new File(targetPath);
if(!targetFile.exists())
{
new File(targetFile.getParent()).mkdirs();
}
OutputStream out = new FileOutputStream(targetFile);
// Copy files
copyFile(in, out);
// Close streams
in.close();
out.flush();
out.close();
}
catch (IOException e)
{
Log.e("Failed to copy asset " + sourcePath, e);
}
}
/**
* Copies all assets from source folder to target folder
*
* @param context Context
* @param sourcePath Source path
* @param targetPath Target path
*/
public static void copyAssets(Context context, String sourcePath, String targetPath)
{
List<String> assetList = new ArrayList<>();
listAssetFiles(context, sourcePath, assetList);
for (String file : assetList)
{
copyAsset(context, file, targetPath + File.separator + file);
}
}
public static void listAssetFiles(Context context, String path, List<String> assetList)
{
try
{
String[] list = context.getAssets().list(path);
if (list != null && list.length > 0)
{
// This is a folder
for (String file : list)
{
listAssetFiles(context, path + File.separator + file, assetList);
}
}
else
{
// This is a single file
assetList.add(path);
}
}
catch (IOException e)
{
Log.e("Error while listing assets in path " + path, e);
}
}
/**
* Returns the extension of a given file.
* @param file File to identify.
* @return Extension of the file without the preceding dot.
* Example: example-file.stream: "stream"
*/
public static String getFileType(File file)
{
String filename = file.getName();
int dotPosition = filename.lastIndexOf('.');
return filename.substring(dotPosition + 1);
}
}
| 5,602 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileEventWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileEventWriter.java | /*
* FileEventWriter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import hcm.ssj.core.Cons;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Util;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.FolderPath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import static hcm.ssj.file.FileCons.FILE_EXTENSION_ANNO_PLAIN;
import static hcm.ssj.file.FileCons.FILE_EXTENSION_EVENT;
/**
* writes events to file
* Created by Johnny on 05.03.2015.
*/
public class FileEventWriter extends EventHandler implements IFileWriter
{
@Override
public OptionList getOptions()
{
return options;
}
public enum Format
{
EVENT,
ANNO_PLAIN
}
public class Options extends IFileWriter.Options
{
public final Option<Format> format = new Option<>("format", Format.EVENT, Format.class, "format of event file");
}
public Options options = new Options();
StringBuilder _builder = new StringBuilder();
byte[] _buffer;
ArrayList<Event> unprocessedEvents = new ArrayList<>();
private File file;
private FileOutputStream fileOutputStream = null;
private boolean headerWritten = false;
public FileEventWriter()
{
_name = "FileEventWriter";
}
@Override
public void enter() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new RuntimeException("no incoming event channels defined");
}
_buffer = new byte[Cons.MAX_EVENT_SIZE];
_builder.delete(0, _builder.length());
//create file
if (options.filePath.get() == null)
{
Log.w("file path not set, setting to default " + FileCons.SSJ_EXTERNAL_STORAGE);
options.filePath.set(new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE));
}
File fileDirectory = Util.createDirectory(options.filePath.parseWildcards());
if (options.fileName.get() == null)
{
String defaultName = "events";
switch(options.format.get())
{
case EVENT:
defaultName += "." + FILE_EXTENSION_EVENT;
break;
case ANNO_PLAIN:
defaultName += "." + FILE_EXTENSION_ANNO_PLAIN;
break;
}
Log.w("file name not set, setting to " + defaultName);
options.fileName.set(defaultName);
}
file = new File(fileDirectory, options.fileName.get());
fileOutputStream = getFileConnection(file, fileOutputStream);
headerWritten = false;
unprocessedEvents.clear();
}
@Override
public synchronized void notify(Event event)
{
//write header
if(!headerWritten && options.format.get() == Format.EVENT)
{
_builder.delete(0, _builder.length());
_builder.append("<events ssi-v=\"2\" ssj-v=\"");
_builder.append(_frame.getVersion());
_builder.append("\">");
_builder.append(FileCons.DELIMITER_LINE);
SimpleDateFormat sdf = new SimpleDateFormat(SimpleHeader.DATE_FORMAT, Locale.getDefault());
Date date = new Date(_frame.getStartTimeMs());
String local = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String system = sdf.format(date);
_builder.append("<time ms=\"").append(_frame.getStartTimeMs()).append("\" local=\"").append(local).append("\" system=\"").append(system).append("\"/>");
_builder.append(FileCons.DELIMITER_LINE);
write(_builder.toString(), fileOutputStream);
headerWritten = true;
}
_builder.delete(0, _builder.length());
if(options.format.get() == Format.EVENT)
{
Util.eventToXML(_builder, event);
_builder.append(FileCons.DELIMITER_LINE);
write(_builder.toString(), fileOutputStream);
}
else if(options.format.get() == Format.ANNO_PLAIN)
{
if(event.state == Event.State.CONTINUED) {
unprocessedEvents.add(event);
}
else
{
//search for event start
Event start = null;
for(int j = 0; j < unprocessedEvents.size(); j++)
{
if(unprocessedEvents.get(j).name.equals(event.name))
{
start = unprocessedEvents.get(j);
unprocessedEvents.remove(j);
break;
}
}
double to = (event.time + event.dur) / 1000.0;
double from = (start != null) ? start.time / 1000.0 : event.time / 1000.0;
_builder.append(from).append(" ").append(to).append(" ").append(event.name);
writeLine(_builder.toString(), fileOutputStream);
}
}
}
public void flush() throws SSJFatalException
{
//write footer
if(options.format.get() == Format.EVENT) {
_builder.delete(0, _builder.length());
_builder.append("</events>");
writeLine(_builder.toString(), fileOutputStream);
}
fileOutputStream = closeStream(fileOutputStream);
}
/**
* @param stream FileOutputStream
* @return FileOutputStream
*/
private FileOutputStream closeStream(FileOutputStream stream)
{
if (stream != null)
{
try
{
stream.close();
stream = null;
} catch (IOException e)
{
Log.e("could not close writer");
}
}
return stream;
}
/**
* @param file File
* @param stream FileOutputStream
* @return FileOutputStream
*/
private FileOutputStream getFileConnection(File file, FileOutputStream stream)
{
try
{
stream = new FileOutputStream(file);
} catch (FileNotFoundException e)
{
Log.e("file not found");
}
return stream;
}
/**
* @param line String
* @param stream FileOutputStream
*/
private void write(String line, FileOutputStream stream)
{
if (stream != null)
{
try
{
stream.write(line.getBytes());
} catch (IOException e)
{
Log.e("could not write data");
}
}
}
/**
* @param line String
* @param stream FileOutputStream
*/
private void writeLine(String line, FileOutputStream stream)
{
if (stream != null)
{
try
{
line += FileCons.DELIMITER_LINE;
stream.write(line.getBytes());
} catch (IOException e)
{
Log.e("could not write line");
}
}
}
}
| 8,663 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/file/FileWriter.java | /*
* FileWriter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.file;
import android.text.TextUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Util;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.FolderPath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.signal.Merge;
import static hcm.ssj.file.FileCons.FILE_EXTENSION_STREAM;
/**
* File writer for SSJ.<br>
* Created by Frank Gaibler on 20.08.2015.
*/
public class FileWriter extends Consumer implements IFileWriter
{
@Override
public OptionList getOptions()
{
return options;
}
/**
*
*/
public class Options extends IFileWriter.Options
{
public final Option<String> separator = new Option<>("separator", FileCons.DELIMITER_DIMENSION, String.class, "");
public final Option<Cons.FileType> type = new Option<>("type", Cons.FileType.ASCII, Cons.FileType.class, "file type (ASCII or BINARY)");
public final Option<Boolean> merge = new Option<>("merge", true, Boolean.class, "merge multiple input streams");
/**
*
*/
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private Cons.FileType fileType;
private FileOutputStream fileOutputStream = null;
private FileOutputStream fileOutputStreamHeader = null;
private BufferedOutputStream byteStream;
private byte[] buffer;
private int sampleCount = 0;
private SimpleHeader simpleHeader;
private StringBuilder stringBuilder;
private File file;
private Merge merge = null;
private Stream stream_merged;
public FileWriter()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in[0].type == Cons.Type.EMPTY || stream_in[0].type == Cons.Type.UNDEF)
{
throw new SSJFatalException("stream type not supported");
}
Stream input = stream_in[0];
if (options.merge.get() && stream_in.length > 1)
{
merge = new Merge();
stream_merged = Stream.create(stream_in[0].num, merge.getSampleDimension(stream_in), stream_in[0].sr, stream_in[0].type);
merge.enter(stream_in, stream_merged);
input = stream_merged;
}
//create file
if (options.filePath.get() == null)
{
Log.w("file path not set, setting to default " + FileCons.SSJ_EXTERNAL_STORAGE);
options.filePath.set(new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE));
}
File fileDirectory = Util.createDirectory(options.filePath.parseWildcards());
if (options.fileName.get() == null)
{
String defaultName = TextUtils.join("_", input.desc) + "." + FILE_EXTENSION_STREAM;
Log.w("file name not set, setting to " + defaultName);
options.fileName.set(defaultName);
}
file = new File(fileDirectory, options.fileName.get());
fileType = options.type.get();
start(input);
}
/**
* @param stream Stream
*/
private void start(Stream stream)
{
File fileHeader = file;
File fileReal;
String path = fileHeader.getPath();
if (path.endsWith(FileCons.TAG_DATA_FILE))
{
fileReal = fileHeader;
fileHeader = new File(path.substring(0, path.length() - 1));
}
else if (fileHeader.getName().contains("."))
{
fileReal = new File(path + FileCons.TAG_DATA_FILE);
}
else
{
fileHeader = new File(path + "." + FILE_EXTENSION_STREAM);
fileReal = new File(path + "." + FILE_EXTENSION_STREAM + FileCons.TAG_DATA_FILE);
}
fileOutputStreamHeader = getFileConnection(fileHeader, fileOutputStreamHeader);
sampleCount = 0;
fileOutputStream = getFileConnection(fileReal, fileOutputStream);
if (fileType == Cons.FileType.BINARY)
{
byteStream = new BufferedOutputStream(fileOutputStream);
buffer = new byte[stream.tot];
}
else if (fileType == Cons.FileType.ASCII)
{
stringBuilder = new StringBuilder();
}
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
protected final void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
Stream input = stream_in[0];
if (options.merge.get() && stream_in.length > 1)
{
merge.transform(stream_in, stream_merged);
input = stream_merged;
}
if (fileType == Cons.FileType.ASCII)
{
stringBuilder.delete(0, stringBuilder.length());
}
if (fileType == Cons.FileType.ASCII)
{
switch (input.type)
{
case BOOL:
{
boolean[] in = input.ptrBool();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case BYTE:
{
byte[] in = input.ptrB();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case CHAR:
{
char[] in = input.ptrC();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case SHORT:
{
short[] in = input.ptrS();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case INT:
{
int[] in = input.ptrI();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case LONG:
{
long[] in = input.ptrL();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case FLOAT:
{
float[] in = input.ptrF();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
case DOUBLE:
{
double[] in = input.ptrD();
for (int i = 0, j = 0; i < input.num; i++)
{
for (int k = 0; k < input.dim; k++, j++)
{
stringBuilder.append(in[j]);
stringBuilder.append(options.separator.get());
}
stringBuilder.append(FileCons.DELIMITER_LINE);
}
sampleCount += input.num;
write(stringBuilder.toString(), fileOutputStream);
break;
}
default:
Log.w("unsupported data type");
break;
}
}
else if (fileType == Cons.FileType.BINARY)
{
sampleCount += input.num;
Util.arraycopy(input.ptr(), 0, buffer, 0, input.tot);
write(buffer, byteStream);
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream stream_in[]) throws SSJFatalException
{
Stream input = stream_in[0];
if (options.merge.get() && stream_in.length > 1)
{
merge.flush(stream_in, stream_merged);
stream_merged.time = stream_in[0].time;
input = stream_merged;
}
if (fileType == Cons.FileType.BINARY)
{
byteStream = (BufferedOutputStream) closeStream(byteStream);
}
fileOutputStream = (FileOutputStream) closeStream(fileOutputStream);
writeHeader(input);
fileOutputStreamHeader = (FileOutputStream) closeStream(fileOutputStreamHeader);
}
private void writeHeader(Stream stream)
{
simpleHeader = new SimpleHeader();
simpleHeader._ftype = fileType.name();
simpleHeader._sr = String.valueOf(stream.sr);
simpleHeader._dim = String.valueOf(stream.dim);
simpleHeader._byte = String.valueOf(stream.bytes);
simpleHeader._type = stream.type.name();
simpleHeader._from = "0";
simpleHeader._ms = String.valueOf(_frame.getStartTimeMs());
SimpleDateFormat sdf = new SimpleDateFormat(SimpleHeader.DATE_FORMAT, Locale.getDefault());
Date date = new Date(_frame.getStartTimeMs());
simpleHeader._local = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
simpleHeader._system = sdf.format(date);
writeLine(simpleHeader.getLine1(), fileOutputStreamHeader);
writeLine(simpleHeader.getLine2(), fileOutputStreamHeader);
writeLine(simpleHeader.getLine3(), fileOutputStreamHeader);
writeLine(simpleHeader.getLine4(), fileOutputStreamHeader);
simpleHeader._num = String.valueOf(sampleCount);
simpleHeader._to = String.valueOf(stream.time + stream.num / stream.sr);
writeLine(simpleHeader.getLine5(), fileOutputStreamHeader);
writeLine(simpleHeader.getLine6(), fileOutputStreamHeader);
}
/**
* @param stream FileOutputStream
* @return FileOutputStream
*/
private OutputStream closeStream(OutputStream stream)
{
if (stream != null)
{
try
{
stream.close();
stream = null;
}
catch (IOException e)
{
Log.e("could not close writer", e);
}
}
return stream;
}
/**
* @param file File
* @param stream FileOutputStream
* @return FileOutputStream
*/
private FileOutputStream getFileConnection(File file, FileOutputStream stream)
{
try
{
stream = new FileOutputStream(file);
}
catch (FileNotFoundException e)
{
Log.e("file not found", e);
}
return stream;
}
/**
* @param data byte[]
* @param stream BufferedOutputStream
*/
private void write(byte[] data, BufferedOutputStream stream)
{
if (data != null)
{
try
{
stream.write(data);
}
catch (IOException e)
{
Log.e("could not write data", e);
}
}
}
/**
* @param line String
* @param stream FileOutputStream
*/
private void write(String line, FileOutputStream stream)
{
if (stream != null)
{
try
{
stream.write(line.getBytes());
}
catch (IOException e)
{
Log.e("could not write data", e);
}
}
}
/**
* @param line String
* @param stream FileOutputStream
*/
private void writeLine(String line, FileOutputStream stream)
{
if (stream != null)
{
try
{
line += FileCons.DELIMITER_LINE;
stream.write(line.getBytes());
}
catch (IOException e)
{
Log.e("could not write line", e);
}
}
}
}
| 13,093 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Polar.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/Polar.java | /*
* Polar.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import android.os.SystemClock;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.PolarBleApiDefaultImpl;
import polar.com.sdk.api.errors.PolarInvalidArgument;
/**
* Created by Michael Dietz on 08.04.2021.
*
* H10:
* HR, ACC, ECG
* OH1:
* HR, ACC, PPI, PPG
*/
public class Polar extends Sensor
{
public class Options extends OptionList
{
public final Option<String> deviceIdentifier = new Option<>("deviceIdentifier", "", String.class, "Polar device id found printed on the sensor/device (in format '12345678') or bt address (in format '00:11:22:33:44:55')");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
PolarListener listener;
PolarBleApi api;
public Polar()
{
_name = "Polar";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
protected boolean connect() throws SSJFatalException
{
Log.d("Connecting to: " + options.deviceIdentifier.get());
api = PolarBleApiDefaultImpl.defaultImplementation(SSJApplication.getAppContext(), PolarBleApi.FEATURE_HR | PolarBleApi.FEATURE_DEVICE_INFO | PolarBleApi.FEATURE_BATTERY_INFO | PolarBleApi.FEATURE_POLAR_SENSOR_STREAMING);
listener = new PolarListener(api, options.deviceIdentifier.get());
api.setApiCallback(listener);
try
{
api.connectToDevice(options.deviceIdentifier.get());
}
catch (PolarInvalidArgument polarInvalidArgument)
{
throw new SSJFatalException(polarInvalidArgument);
}
// Wait until sensor is connected
long time = SystemClock.elapsedRealtime();
while (!listener.connected && !_terminate && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException e)
{
}
}
if (!listener.connected)
{
Log.w("Unable to connect to polar sensor. Make sure it is on and NOT paired to your smartphone.");
disconnect();
return false;
}
return true;
}
@Override
protected void disconnect() throws SSJFatalException
{
Log.i("Disconnecting Polar Sensor");
if (api != null)
{
try
{
api.disconnectFromDevice(options.deviceIdentifier.get());
api.cleanup();
}
catch (PolarInvalidArgument polarInvalidArgument)
{
throw new SSJFatalException(polarInvalidArgument);
}
}
}
@Override
protected boolean checkConnection()
{
boolean connected = false;
if (listener != null)
{
connected = listener.connected;
}
return connected;
}
}
| 4,115 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarHRChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarHRChannel.java | /*
* PolarChannel.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.model.PolarHrData;
import polar.com.sdk.api.model.PolarOhrData;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarHRChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
PolarListener _listener;
PolarHrData currentSample;
public PolarHRChannel()
{
_name = "Polar_HR";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Polar) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (_listener.hrReady)
{
// Get current sample values
currentSample = _listener.hrData;
// Check if queue is empty
if (currentSample != null)
{
// Assign output values
out[0] = currentSample.hr;
if (currentSample.rrAvailable)
{
out[1] = currentSample.rrs.get(0);
out[2] = currentSample.rrsMs.get(0);
}
else
{
out[1] = 0;
out[2] = 0;
}
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 3;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "HR BPM";
stream_out.desc[1] = "RR"; // R is the peak of the QRS complex in the ECG wave and RR is the interval between successive Rs. In 1/1024 format.
stream_out.desc[2] = "RR ms"; // RRs in milliseconds.
}
}
| 3,513 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarPPGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarPPGChannel.java | /*
* PolarChannel.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.model.PolarOhrData;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarPPGChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 135, Integer.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
PolarListener _listener;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
PolarOhrData.PolarOhrSample currentSample;
public PolarPPGChannel()
{
_name = "Polar_PPG";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Polar) _sensor).listener;
_listener.streamingFeatures.add(PolarBleApi.DeviceStreamingFeature.PPG);
samplingRatio = -1;
lastIndex = 0;
currentIndex = 0;
maxQueueSize = -1;
minQueueSize = -1;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (_listener.sampleRatePPG > 0)
{
if (samplingRatio == -1)
{
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = _listener.sampleRatePPG / (float) options.sampleRate.get();
maxQueueSize = (int) (_listener.sampleRatePPG * (_frame.options.bufferSize.get() + 120));
minQueueSize = (int) (_listener.sampleRatePPG * _frame.options.bufferSize.get());
}
// Get current sample values
currentSample = _listener.ppgQueue.peek();
// Check if queue is empty
if (currentSample != null)
{
// Assign output values
for (int i = 0; i < 4; i++)
{
out[i] = currentSample.channelSamples.get(i);
}
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
_listener.ppgQueue.poll();
}
// Reset counters
if (currentIndex >= _listener.sampleRatePPG)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = _listener.ppgQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
_listener.ppgQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 4;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "PPG LED 0";
stream_out.desc[1] = "PPG LED 1";
stream_out.desc[2] = "PPG LED 2";
stream_out.desc[3] = "Ambient light";
}
}
| 4,652 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarECGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarECGChannel.java | /*
* PolarChannel.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.model.PolarOhrData;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarECGChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 130, Integer.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
PolarListener _listener;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
Integer currentSample;
public PolarECGChannel()
{
_name = "Polar_ECG";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Polar) _sensor).listener;
_listener.streamingFeatures.add(PolarBleApi.DeviceStreamingFeature.ECG);
samplingRatio = -1;
lastIndex = 0;
currentIndex = 0;
maxQueueSize = -1;
minQueueSize = -1;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (_listener.sampleRateECG > 0)
{
if (samplingRatio == -1)
{
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = _listener.sampleRateECG / (float) options.sampleRate.get();
maxQueueSize = (int) (_listener.sampleRateECG * (_frame.options.bufferSize.get() + 120));
minQueueSize = (int) (_listener.sampleRateECG * _frame.options.bufferSize.get());
}
// Get current sample values
currentSample = _listener.ecgQueue.peek();
// Check if queue is empty
if (currentSample != null)
{
// Assign output values
out[0] = currentSample;
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
_listener.ecgQueue.poll();
}
// Reset counters
if (currentIndex >= _listener.sampleRateECG)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = _listener.ecgQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
_listener.ecgQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "ECG µV"; // in microvolts
}
}
| 4,468 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarACCChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarACCChannel.java | /*
* PolarChannel.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.model.PolarAccelerometerData;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarACCChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
PolarListener _listener;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
PolarAccelerometerData.PolarAccelerometerDataSample currentSample;
public PolarACCChannel()
{
_name = "Polar_ACC";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Polar) _sensor).listener;
_listener.streamingFeatures.add(PolarBleApi.DeviceStreamingFeature.ACC);
samplingRatio = -1;
lastIndex = 0;
currentIndex = 0;
maxQueueSize = -1;
minQueueSize = -1;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (_listener.sampleRateACC > 0)
{
if (samplingRatio == -1)
{
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = _listener.sampleRateACC / (float) options.sampleRate.get();
maxQueueSize = (int) (_listener.sampleRateACC * (_frame.options.bufferSize.get() + 120));
minQueueSize = (int) (_listener.sampleRateACC * _frame.options.bufferSize.get());
}
// Get current sample values
currentSample = _listener.accQueue.peek();
// Check if queue is empty
if (currentSample != null)
{
// Assign output values
out[0] = currentSample.x;
out[1] = currentSample.y;
out[2] = currentSample.z;
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
_listener.accQueue.poll();
}
// Reset counters
if (currentIndex >= _listener.sampleRateACC)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = _listener.accQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
_listener.accQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 3;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "ACC X";
stream_out.desc[1] = "ACC Y";
stream_out.desc[2] = "ACC Z";
/*
Polar H10:
Accelerometer data with sample rates of 25Hz, 50Hz, 100Hz and 200Hz and range of 2G, 4G and 8G. Axis specific acceleration data in mG.
Polar OH1 / Verity Sense:
Accelerometer data with sample rate of 52Hz and range of 8G. Axis specific acceleration data in mG.
*/
}
}
| 4,921 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarGYRChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarGYRChannel.java | /*
* PolarChannel.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.model.PolarGyroData;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarGYRChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
PolarListener _listener;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
PolarGyroData.PolarGyroDataSample currentSample;
public PolarGYRChannel()
{
_name = "Polar_GYR";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Polar) _sensor).listener;
_listener.streamingFeatures.add(PolarBleApi.DeviceStreamingFeature.GYRO);
samplingRatio = -1;
lastIndex = 0;
currentIndex = 0;
maxQueueSize = -1;
minQueueSize = -1;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (_listener.sampleRateGYR > 0)
{
if (samplingRatio == -1)
{
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = _listener.sampleRateGYR / (float) options.sampleRate.get();
maxQueueSize = (int) (_listener.sampleRateGYR * (_frame.options.bufferSize.get() + 120));
minQueueSize = (int) (_listener.sampleRateGYR * _frame.options.bufferSize.get());
}
// Get current sample values
currentSample = _listener.gyrQueue.peek();
// Check if queue is empty
if (currentSample != null)
{
// Assign output values
out[0] = currentSample.x;
out[1] = currentSample.y;
out[2] = currentSample.z;
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
_listener.gyrQueue.poll();
}
// Reset counters
if (currentIndex >= _listener.sampleRateGYR)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = _listener.gyrQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
_listener.gyrQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 3;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "GYR X";
stream_out.desc[1] = "GYR Y";
stream_out.desc[2] = "GYR Z";
}
}
| 4,577 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarMAGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarMAGChannel.java | /*
* PolarChannel.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.model.PolarMagnetometerData;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarMAGChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
PolarListener _listener;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
PolarMagnetometerData.PolarMagnetometerDataSample currentSample;
public PolarMAGChannel()
{
_name = "Polar_MAG";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Polar) _sensor).listener;
_listener.streamingFeatures.add(PolarBleApi.DeviceStreamingFeature.MAGNETOMETER);
samplingRatio = -1;
lastIndex = 0;
currentIndex = 0;
maxQueueSize = -1;
minQueueSize = -1;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (_listener.sampleRateMAG > 0)
{
if (samplingRatio == -1)
{
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = _listener.sampleRateMAG / (float) options.sampleRate.get();
maxQueueSize = (int) (_listener.sampleRateMAG * (_frame.options.bufferSize.get() + 120));
minQueueSize = (int) (_listener.sampleRateMAG * _frame.options.bufferSize.get());
}
// Get current sample values
currentSample = _listener.magQueue.peek();
// Check if queue is empty
if (currentSample != null)
{
// Assign output values
out[0] = currentSample.x;
out[1] = currentSample.y;
out[2] = currentSample.z;
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
_listener.magQueue.poll();
}
// Reset counters
if (currentIndex >= _listener.sampleRateMAG)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = _listener.magQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
_listener.magQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 3;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "MAG X";
stream_out.desc[1] = "MAG Y";
stream_out.desc[2] = "MAG Z";
}
}
| 4,609 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PolarListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/polar/PolarListener.java | /*
* PolarListener.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.polar;
import org.reactivestreams.Publisher;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import androidx.annotation.NonNull;
import hcm.ssj.core.Log;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import polar.com.sdk.api.PolarBleApi;
import polar.com.sdk.api.PolarBleApiCallback;
import polar.com.sdk.api.model.PolarAccelerometerData;
import polar.com.sdk.api.model.PolarDeviceInfo;
import polar.com.sdk.api.model.PolarEcgData;
import polar.com.sdk.api.model.PolarGyroData;
import polar.com.sdk.api.model.PolarHrData;
import polar.com.sdk.api.model.PolarMagnetometerData;
import polar.com.sdk.api.model.PolarOhrData;
import polar.com.sdk.api.model.PolarSensorSetting;
import static polar.com.sdk.api.model.PolarOhrData.OHR_DATA_TYPE.PPG3_AMBIENT1;
/**
* Created by Michael Dietz on 08.04.2021.
*/
public class PolarListener extends PolarBleApiCallback
{
public static final int ACC_SR_OFFSET = 1;
final String DEVICE_ID;
final PolarBleApi api;
boolean connected;
Set<PolarBleApi.DeviceStreamingFeature> streamingFeatures;
List<Disposable> disposables;
int sampleRatePPG;
int sampleRateACC;
int sampleRateECG;
int sampleRateGYR;
int sampleRateMAG;
ArrayDeque<PolarOhrData.PolarOhrSample> ppgQueue;
ArrayDeque<PolarAccelerometerData.PolarAccelerometerDataSample> accQueue;
ArrayDeque<Integer> ecgQueue;
ArrayDeque<PolarGyroData.PolarGyroDataSample> gyrQueue;
ArrayDeque<PolarMagnetometerData.PolarMagnetometerDataSample> magQueue;
PolarHrData hrData;
boolean hrReady;
public PolarListener(PolarBleApi polarApi, String deviceIdentifier)
{
DEVICE_ID = deviceIdentifier;
api = polarApi;
streamingFeatures = new LinkedHashSet<>();
disposables = new ArrayList<>();
ppgQueue = new ArrayDeque<>();
accQueue = new ArrayDeque<>();
ecgQueue = new ArrayDeque<>();
gyrQueue = new ArrayDeque<>();
magQueue = new ArrayDeque<>();
reset();
}
private void reset()
{
connected = false;
streamingFeatures.clear();
disposables.clear();
ppgQueue.clear();
accQueue.clear();
ecgQueue.clear();
gyrQueue.clear();
magQueue.clear();
sampleRatePPG = -1;
sampleRateACC = -1;
sampleRateECG = -1;
sampleRateGYR = -1;
sampleRateMAG = -1;
hrData = null;
hrReady = false;
}
public void deviceConnected(@NonNull PolarDeviceInfo polarDeviceInfo)
{
Log.d("Connected to device: " + polarDeviceInfo.deviceId + " (" + DEVICE_ID + ")");
connected = true;
}
public void deviceConnecting(@NonNull PolarDeviceInfo polarDeviceInfo)
{
Log.d("Connecting to device: " + polarDeviceInfo.deviceId + " (" + DEVICE_ID + ")");
}
public void deviceDisconnected(@NonNull PolarDeviceInfo polarDeviceInfo)
{
Log.d("Disconnected from device: " + polarDeviceInfo.deviceId + " (" + DEVICE_ID + ")");
for (Disposable disposable : disposables)
{
disposable.dispose();
}
connected = false;
}
public void streamingFeaturesReady(@NonNull String identifier, @NonNull Set<PolarBleApi.DeviceStreamingFeature> features)
{
for (PolarBleApi.DeviceStreamingFeature feature : features)
{
Log.d("Streaming feature " + feature.toString() + " is ready (" + DEVICE_ID + ")");
if (streamingFeatures.contains(feature))
{
switch (feature)
{
case ACC:
disposables.add(streamACC());
break;
case PPG:
disposables.add(streamPPG());
break;
case ECG:
disposables.add(streamECG());
break;
case GYRO:
disposables.add(streamGYR());
break;
case MAGNETOMETER:
disposables.add(streamMAG());
break;
case PPI:
break;
}
}
}
}
public void hrFeatureReady(@NonNull String identifier)
{
hrReady = true;
}
public void disInformationReceived(@NonNull String identifier, @NonNull UUID uuid, @NonNull String value)
{
// Log.d("UUID: " + uuid + " Value: " + value);
Log.d("Device: " + DEVICE_ID + " Value: " + value);
}
public void batteryLevelReceived(@NonNull String identifier, int level)
{
Log.d("Device: " + DEVICE_ID + " Battery level: " + level);
}
public void hrNotificationReceived(@NonNull String identifier, @NonNull PolarHrData data)
{
hrData = data;
}
private Disposable streamPPG()
{
return api.requestStreamSettings(DEVICE_ID, PolarBleApi.DeviceStreamingFeature.PPG)
.toFlowable()
.flatMap((Function<PolarSensorSetting, Publisher<PolarOhrData>>) polarPPGSettings -> {
PolarSensorSetting sensorSetting = polarPPGSettings.maxSettings();
Set<Integer> values = sensorSetting.settings.get(PolarSensorSetting.SettingType.SAMPLE_RATE);
if (values != null && !values.isEmpty())
{
sampleRatePPG = values.iterator().next();
/*
* Fix for known issue:
* https://github.com/polarofficial/polar-ble-sdk/blob/master/technical_documentation/KnownIssues.md
*
* Problem: PPG stream settings returns incorrect sampling rate when read with requestStreamSettings().
* The returned value for sampling rate is 130Hz. The correct sampling rate is 135Hz.
*/
if (sampleRatePPG == 130)
{
sampleRatePPG = 135;
}
Log.i("Registered PPG stream with " + sampleRatePPG + "Hz (" + DEVICE_ID + ")");
}
return api.startOhrStreaming(DEVICE_ID, sensorSetting);
})
.subscribe(
polarOhrPPGData -> {
if (polarOhrPPGData.type == PPG3_AMBIENT1)
{
ppgQueue.addAll(polarOhrPPGData.samples);
}
},
throwable -> Log.e("Error with PPG stream: " + throwable),
() -> Log.d("complete")
);
}
private Disposable streamECG()
{
return api.requestStreamSettings(DEVICE_ID, PolarBleApi.DeviceStreamingFeature.ECG)
.toFlowable()
.flatMap((Function<PolarSensorSetting, Publisher<PolarEcgData>>) polarEcgSettings -> {
PolarSensorSetting sensorSetting = polarEcgSettings.maxSettings();
Set<Integer> values = sensorSetting.settings.get(PolarSensorSetting.SettingType.SAMPLE_RATE);
if (values != null && !values.isEmpty())
{
sampleRateECG = values.iterator().next();
Log.i("Registered ECG stream with " + sampleRateECG + "Hz (" + DEVICE_ID + ")");
}
return api.startEcgStreaming(DEVICE_ID, sensorSetting);
}).subscribe(
polarEcgData -> {
ecgQueue.addAll(polarEcgData.samples);
},
throwable -> Log.e("Error with ECG stream: " + throwable),
() -> Log.d("complete")
);
}
private Disposable streamACC()
{
return api.requestStreamSettings(DEVICE_ID, PolarBleApi.DeviceStreamingFeature.ACC)
.toFlowable()
.flatMap((Function<PolarSensorSetting, Publisher<PolarAccelerometerData>>) settings -> {
PolarSensorSetting sensorSetting = settings.maxSettings();
Set<Integer> values = sensorSetting.settings.get(PolarSensorSetting.SettingType.SAMPLE_RATE);
if (values != null && !values.isEmpty())
{
sampleRateACC = values.iterator().next() + ACC_SR_OFFSET;
Log.i("Registered ACC stream with " + sampleRateACC + "Hz (" + DEVICE_ID + ")");
}
return api.startAccStreaming(DEVICE_ID, sensorSetting);
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
polarAccelerometerData -> {
accQueue.addAll(polarAccelerometerData.samples);
},
throwable -> Log.e("Error with ACC stream: " + throwable),
() -> Log.d("complete")
);
}
private Disposable streamGYR()
{
return api.requestStreamSettings(DEVICE_ID, PolarBleApi.DeviceStreamingFeature.GYRO)
.toFlowable()
.flatMap((Function<PolarSensorSetting, Publisher<PolarGyroData>>) settings -> {
PolarSensorSetting sensorSetting = settings.maxSettings();
Set<Integer> values = sensorSetting.settings.get(PolarSensorSetting.SettingType.SAMPLE_RATE);
if (values != null && !values.isEmpty())
{
sampleRateGYR = values.iterator().next();
Log.i("Registered GYR stream with " + sampleRateGYR + "Hz (" + DEVICE_ID + ")");
}
return api.startGyroStreaming(DEVICE_ID, sensorSetting);
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
polarGyroData -> {
gyrQueue.addAll(polarGyroData.samples);
},
throwable -> Log.e("Error with GYR stream: " + throwable),
() -> Log.d("complete")
);
}
private Disposable streamMAG()
{
return api.requestStreamSettings(DEVICE_ID, PolarBleApi.DeviceStreamingFeature.MAGNETOMETER)
.toFlowable()
.flatMap((Function<PolarSensorSetting, Publisher<PolarMagnetometerData>>) settings -> {
PolarSensorSetting sensorSetting = settings.maxSettings();
Set<Integer> values = sensorSetting.settings.get(PolarSensorSetting.SettingType.SAMPLE_RATE);
if (values != null && !values.isEmpty())
{
sampleRateMAG = values.iterator().next();
Log.i("Registered MAG stream with " + sampleRateMAG + "Hz (" + DEVICE_ID + ")");
}
return api.startMagnetometerStreaming(DEVICE_ID, sensorSetting);
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
polarMagData -> {
magQueue.addAll(polarMagData.samples);
},
throwable -> Log.e("Error with MAG stream: " + throwable),
() -> Log.d("complete")
);
}
}
| 10,772 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FaceCrop.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/face/FaceCrop.java | /*
* FaceCrop.java
* Copyright (c) 2019
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.face;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.gpu.CompatibilityList;
import org.tensorflow.lite.gpu.GpuDelegate;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.List;
import hcm.ssj.camera.CameraUtil;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.ml.TFLiteWrapper;
import hcm.ssj.ssd.Detection;
import hcm.ssj.ssd.SingleShotMultiBoxDetector;
import hcm.ssj.file.FileCons;
/**
* Created by Michael Dietz on 30.10.2019.
*/
public class FaceCrop extends Transformer
{
private static final String MODEL_NAME = "face_detection_front.tflite";
private static final String MODEL_PATH = FileCons.MODELS_DIR + File.separator + MODEL_NAME;
private static final int MODEL_INPUT_SIZE = 128;
private static final int MODEL_INPUT_CHANNELS = 3;
public class Options extends OptionList
{
public final Option<Integer> outputWidth = new Option<>("outputWidth", 224, Integer.class, "width of the output image");
public final Option<Integer> outputHeight = new Option<>("outputHeight", 224, Integer.class, "height of the output image");
public final Option<Integer> rotation = new Option<>("rotation", 270, Integer.class, "rotation of the resulting image, use 270 for front camera and 90 for back camera");
public final Option<Integer> paddingHorizontal = new Option<>("paddingHorizontal", 0, Integer.class, "increase horizontal face crop by custom number of pixels on each side");
public final Option<Integer> paddingVertical = new Option<>("paddingVertical", 0, Integer.class, "increase vertical face crop by custom number of pixels on each side");
public final Option<Boolean> outputPositionEvents = new Option<>("outputPositionEvents", false, Boolean.class, "if true outputs face position as events");
public final Option<Boolean> squeeze = new Option<>("squeeze", true, Boolean.class, "if true squeezes face area to output size");
public final Option<Boolean> useGPU = new Option<>("useGPU", true, Boolean.class, "if true tries to use GPU for better performance");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
// Helper class to postprocess classifier results
private SingleShotMultiBoxDetector ssd;
private TFLiteWrapper tfLiteWrapper;
// ByteBuffer to hold image data, to be feed into Tensorflow Lite as inputs.
private ByteBuffer imgData = null;
private int[] originalInputArray;
private int[] modelInputArray;
private int[] outputArray;
// Create bitmap for the original image
private Bitmap inputBitmap;
// Rotated bitmap for original image
private Bitmap rotatedBitmap;
private Bitmap modelInputBitmap;
private Bitmap faceBitmap;
private Bitmap outputBitmap;
private Matrix rotationMatrix;
private int rotatedWidth = -1;
private int rotatedHeight = -1;
private List<Detection> detectionList;
private Detection currentDetection;
private int width;
private int height;
private File modelFile;
@Override
public OptionList getOptions()
{
return options;
}
public FaceCrop()
{
_name = this.getClass().getSimpleName();
}
@Override
public void init(double frame, double delta) throws SSJException
{
// Download blazeface model
modelFile = new File(MODEL_PATH);
if (!modelFile.exists())
{
try
{
Pipeline.getInstance().download(MODEL_NAME, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true);
}
catch (IOException e)
{
throw new SSJException("Error while downloading face detection model!", e);
}
}
}
@Override
public synchronized void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Get image dimensions
width = ((ImageStream) stream_in[0]).width;
height = ((ImageStream) stream_in[0]).height;
tfLiteWrapper = new TFLiteWrapper(options.useGPU.get());
tfLiteWrapper.loadModel(modelFile);
// Initialize model input buffer: size = width * height * channels * bytes per pixel (e.g., 4 for float)
imgData = ByteBuffer.allocateDirect(MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * MODEL_INPUT_CHANNELS * Util.sizeOf(Cons.Type.FLOAT));
imgData.order(ByteOrder.nativeOrder());
// Initialize model input and output integer arrays
modelInputArray = new int[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE];
outputArray = new int[options.outputWidth.get() * options.outputHeight.get()];
// Create bitmap for the original image
inputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
rotationMatrix = new Matrix();
rotationMatrix.postRotate(options.rotation.get());
// Create SSD helper class
ssd = new SingleShotMultiBoxDetector();
}
@Override
public synchronized void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Fixed output of blazeface model
float[][][] boxesResult = new float[1][896][16];
float[][][] scoresResult = new float[1][896][1];
HashMap<Integer, Object> outputs = new HashMap<>();
outputs.put(0, boxesResult);
outputs.put(1, scoresResult);
// Convert byte array to integer array
originalInputArray = CameraUtil.decodeBytes(stream_in[0].ptrB(), width, height);
// Create bitmap from byte array
inputBitmap.setPixels(originalInputArray, 0, width, 0, 0, width, height);
// Rotate original input
rotatedBitmap = Bitmap.createBitmap(inputBitmap, 0, 0, inputBitmap.getWidth(), inputBitmap.getHeight(), rotationMatrix, true);
// Resize rotated original input to model input size
modelInputBitmap = Bitmap.createScaledBitmap(rotatedBitmap, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, true);
// Convert and normalize [-1, 1] bitmap to model input
tfLiteWrapper.convertBitmapToInputArray(modelInputBitmap, modelInputArray, imgData);
// Run inference
tfLiteWrapper.runMultiInputOutput(new Object[] { imgData }, outputs);
// Calculate detections from model results
detectionList = ssd.process(boxesResult, scoresResult);
if (detectionList.size() > 0)
{
currentDetection = detectionList.get(0);
// Cache width and height of rotated input image
if (rotatedWidth < 0)
{
rotatedWidth = rotatedBitmap.getWidth();
rotatedHeight = rotatedBitmap.getHeight();
}
// Scale relative detection values to input size
int faceX = (int) Math.floor(currentDetection.xMin * rotatedWidth) - options.paddingHorizontal.get();
int faceY = (int) Math.floor(currentDetection.yMin * rotatedHeight) - options.paddingVertical.get();
int faceWidth = (int) Math.ceil(currentDetection.width * rotatedWidth) + options.paddingHorizontal.get() * 2;
int faceHeight = (int) Math.ceil(currentDetection.height * rotatedHeight) + options.paddingVertical.get() * 2;
if (!options.squeeze.get())
{
int centerX = faceX + faceWidth / 2;
int centerY = faceY + faceHeight / 2;
float widthRatio = options.outputWidth.get() / (float) faceWidth;
float heightRatio = options.outputHeight.get() / (float) faceHeight;
float scaleRatio = Math.min(widthRatio, heightRatio);
float scaledWidth = faceWidth * scaleRatio;
float scaledHeight = faceHeight * scaleRatio;
if (scaledWidth < options.outputWidth.get())
{
scaledWidth = options.outputWidth.get();
}
if (scaledHeight < options.outputWidth.get())
{
scaledHeight = options.outputHeight.get();
}
faceWidth = (int) (scaledWidth / scaleRatio);
faceHeight = (int) (scaledHeight / scaleRatio);
faceX = centerX - faceWidth / 2;
faceY = centerY - faceHeight / 2;
}
// Limit face coordinates to input size
if (faceX < 0)
{
faceWidth += faceX;
faceX = 0;
}
if (faceY < 0)
{
faceHeight += faceY;
faceY = 0;
}
if (faceX + faceWidth > rotatedWidth)
{
faceX = rotatedWidth - faceWidth - 1;
// faceWidth = rotatedWidth - faceX - 1;
}
if (faceY + faceHeight > rotatedHeight)
{
faceY = rotatedHeight - faceHeight - 1;
// faceHeight = rotatedHeight - faceY - 1;
}
faceBitmap = Bitmap.createBitmap(rotatedBitmap, faceX, faceY, faceWidth, faceHeight);
if (options.outputPositionEvents.get())
{
Event ev = Event.create(Cons.Type.FLOAT);
ev.name = "position";
ev.sender = "face";
ev.time = (int) (1000 * stream_in[0].time + 0.5);
ev.dur = (int) (1000 * (stream_in[0].num / stream_in[0].sr) + 0.5);
ev.state = Event.State.COMPLETED;
// Set center of face to (0, 0), scale to [-1, 1]
float[] facePosData = new float[2];
facePosData[0] = (currentDetection.xMin + 0.5f * currentDetection.width) * 2 - 1f;
facePosData[1] = 1f - (currentDetection.yMin + 0.5f * currentDetection.height) * 2;
// Clamp to [-1, 1]
facePosData[0] = Math.max(-1.0f, Math.min(1.0f, facePosData[0]));
facePosData[1] = Math.max(-1.0f, Math.min(1.0f, facePosData[1]));
ev.setData(facePosData);
_evchannel_out.pushEvent(ev);
}
}
else
{
faceBitmap = rotatedBitmap;
}
// Resize to fixed output size
outputBitmap = Bitmap.createScaledBitmap(faceBitmap, options.outputWidth.get(), options.outputHeight.get(), true);
// Convert bitmap to byte stream
CameraUtil.convertBitmapToByteArray(outputBitmap, outputArray, stream_out.ptrB());
// Free bitmap memory
rotatedBitmap.recycle();
modelInputBitmap.recycle();
faceBitmap.recycle();
outputBitmap.recycle();
}
@Override
public synchronized void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Clean up
if (tfLiteWrapper != null)
{
tfLiteWrapper.close();
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return options.outputWidth.get() * options.outputHeight.get() * MODEL_INPUT_CHANNELS;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.IMAGE)
{
Log.e("unsupported input type");
}
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.IMAGE;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[] { "Detected face image" };
((ImageStream) stream_out).width = options.outputWidth.get();
((ImageStream) stream_out).height = options.outputHeight.get();
((ImageStream) stream_out).format = Cons.ImageFormat.FLEX_RGB_888.val;
}
}
| 12,202 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GSRChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/GSRChannel.java | /*
* GSRChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class GSRChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 4, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaticaListener _listener;
public GSRChannel()
{
_name = "Empatica_GSR";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Empatica)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.getGsr();
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 1;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "GSR";
}
}
| 2,766 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Empatica.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/Empatica.java | /*
* Empatica.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import android.bluetooth.BluetoothDevice;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Base64;
import com.empatica.empalink.EmpaDeviceManager;
import com.empatica.empalink.config.EmpaSensorStatus;
import com.empatica.empalink.config.EmpaSensorType;
import com.empatica.empalink.config.EmpaStatus;
import com.empatica.empalink.delegate.EmpaStatusDelegate;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class Empatica extends Sensor implements EmpaStatusDelegate
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> apiKey = new Option<>("apiKey", null, String.class, "the api key from your empatica developer page");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaDeviceManager deviceManager;
protected EmpaticaListener listener;
protected boolean empaticaInitialized;
public Empatica()
{
_name = "Empatica";
empaticaInitialized = false;
}
@Override
public boolean connect() throws SSJFatalException
{
if (options.apiKey.get() == null || options.apiKey.get().length() == 0)
{
throw new SSJFatalException("invalid apiKey - you need to set the apiKey in the sensor options");
}
// Create data listener
listener = new EmpaticaListener();
//pre-validate empatica to avoid the certificate being bound to one app
try
{
getCertificate();
applyCertificate();
}
catch (IOException e)
{
throw new SSJFatalException("error in applying certificates - empatica needs to connect to the server once a month to validate", e);
}
// Empatica device manager must be initialized in the main ui thread
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
try
{
// Create device manager
deviceManager = new EmpaDeviceManager(SSJApplication.getAppContext(), listener, Empatica.this);
// Register the device manager using your API key. You need to have Internet access at this point.
deviceManager.authenticateWithAPIKey(options.apiKey.get());
}
catch(Exception e)
{
Log.e("unable to create empatica device manager, is your api key correct?", e);
}
}
}, 1);
long time = SystemClock.elapsedRealtime();
while (!_terminate && !listener.receivedData && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {}
}
if(!listener.receivedData) {
Log.w("Unable to connect to empatica. Make sure it is on and NOT paired to your smartphone.");
disconnect();
return false;
}
return true;
}
private void applyCertificate() throws IOException
{
copyFile(new File(Environment.getExternalStorageDirectory(), "SSJ/empatica/profile"),
new File(SSJApplication.getAppContext().getFilesDir(), "profile"));
copyFile(new File(Environment.getExternalStorageDirectory(), "SSJ/empatica/signature"),
new File(SSJApplication.getAppContext().getFilesDir(), "signature"));
}
private void getCertificate()
{
try
{
HashMap<String, String> p = new HashMap<>();
p.put("api_key", options.apiKey.get());
p.put("api_version", "AND_1.3");
String json = (new GsonBuilder()).create().toJson(p, Map.class);
//execute json
URL url = new URL("https://www.empatica.com/connect/empalink/api_login.php");
HttpURLConnection urlConn;
DataOutputStream printout;
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
//send request
printout = new DataOutputStream(urlConn.getOutputStream());
printout.write(json.getBytes("UTF-8"));
printout.flush();
printout.close();
int HttpResult = urlConn.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
//get response
BufferedReader r = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null)
{
response.append(line);
}
//check status
JsonElement jelement = (new JsonParser()).parse(response.toString());
JsonObject jobject = jelement.getAsJsonObject();
String status = jobject.get("status").getAsString();
if (!status.equals("ok"))
throw new IOException("status check failed");
//save certificate
if (jobject.has("empaconf") && jobject.has("empasign"))
{
String empaconf = jobject.get("empaconf").getAsString();
String empasign = jobject.get("empasign").getAsString();
byte[] empaconfBytes = Base64.decode(empaconf, 0);
byte[] empasignBytes = Base64.decode(empasign, 0);
saveFile("profile", empaconfBytes);
saveFile("signature", empasignBytes);
Log.i("Successfully retrieved and saved new Empatica certificates");
}
else
{
throw new IOException("Failed loading certificates. Empaconf and Empasign missing from http response.");
}
}
}
catch (IOException e)
{
Log.w("Failed to retrieve certificate", e);
}
}
private void saveFile(String name, byte[] data) throws IOException
{
File dir = new File(Environment.getExternalStorageDirectory(), "SSJ/empatica");
if (!dir.exists())
{
dir.mkdirs();
}
File file = new File(dir, name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
}
public void copyFile(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
@Override
public void disconnect() throws SSJFatalException
{
Log.i("disconnecting...");
deviceManager.disconnect();
deviceManager.cleanUp();
}
@Override
public void didUpdateStatus(EmpaStatus empaStatus)
{
Log.i("Empatica status: " + empaStatus);
try
{
switch (empaStatus)
{
case READY:
// Start scanning
deviceManager.startScanning();
break;
case DISCONNECTED:
listener.reset();
break;
case CONNECTING:
break;
case CONNECTED:
break;
case DISCONNECTING:
break;
case DISCOVERING:
break;
}
}
catch(Exception e)
{
Log.w("error reacting to status update", e);
}
}
@Override
public void didUpdateSensorStatus(EmpaSensorStatus empaSensorStatus, EmpaSensorType empaSensorType)
{
// Sensor status update
}
@Override
public void didDiscoverDevice(BluetoothDevice bluetoothDevice, String deviceName, int rssi, boolean allowed)
{
// Stop scanning. The first allowed device will do.
if (allowed)
{
try
{
deviceManager.stopScanning();
// Connect to the device
Log.i("Connecting to device: " + bluetoothDevice.getName() + "(MAC: " + bluetoothDevice.getAddress() + ")");
deviceManager.connectDevice(bluetoothDevice);
// Depending on your configuration profile, you might be unable to connect to a device.
// This should happen only if you try to connect when allowed == false.
empaticaInitialized = true;
}
catch (Exception e)
{
Log.e("Can't connect to device: " + bluetoothDevice.getName() + "(MAC: " + bluetoothDevice.getAddress() + ")");
}
}
else
{
Log.w("Device " + deviceName + " not linked to specified api key");
}
}
@Override
public void didRequestEnableBluetooth()
{
Log.e("Bluetooth not enabled!");
}
}
| 10,102 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EmpaticaListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/EmpaticaListener.java | /*
* EmpaticaListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import com.empatica.empalink.delegate.EmpaDataDelegate;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class EmpaticaListener implements EmpaDataDelegate
{
private float gsr;
private float bvp;
private float ibi;
private float temperature;
private float battery;
private int x;
private int y;
private int z;
public boolean receivedData;
public EmpaticaListener()
{
reset();
}
public void reset()
{
gsr = 0;
bvp = 0;
ibi = 0;
temperature = 0;
battery = 0;
x = 0;
y = 0;
z = 0;
receivedData = false;
}
@Override
public void didReceiveGSR(float gsr, double timestamp)
{
receivedData = true;
this.gsr = gsr;
}
@Override
public void didReceiveBVP(float bvp, double timestamp)
{
receivedData = true;
this.bvp = bvp;
}
@Override
public void didReceiveIBI(float ibi, double timestamp)
{
receivedData = true;
this.ibi = ibi;
}
@Override
public void didReceiveTemperature(float temperature, double timestamp)
{
receivedData = true;
this.temperature = temperature;
}
@Override
public void didReceiveBatteryLevel(float battery, double timestamp)
{
receivedData = true;
this.battery = battery;
}
@Override
public void didReceiveAcceleration(int x, int y, int z, double timestamp)
{
receivedData = true;
this.x = x;
this.y = y;
this.z = z;
}
public float getGsr()
{
return gsr;
}
public float getBvp()
{
return bvp;
}
public float getIbi()
{
return ibi;
}
public float getTemperature()
{
return temperature;
}
public float getBattery()
{
return battery;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getZ()
{
return z;
}
}
| 3,083 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AccelerationChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/AccelerationChannel.java | /*
* AccelerationChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class AccelerationChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 32, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaticaListener _listener;
public AccelerationChannel()
{
_name = "Empatica_Acc";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Empatica)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.getX();
out[1] = _listener.getY();
out[2] = _listener.getZ();
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 3;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "AccX";
stream_out.desc[1] = "AccY";
stream_out.desc[2] = "AccZ";
}
}
| 2,916 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IBIChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/IBIChannel.java | /*
* IBIChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class IBIChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 30, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaticaListener _listener;
public IBIChannel()
{
_name = "Empatica_IBI";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Empatica)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.getIbi();
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 1;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "IBI";
}
}
| 2,767 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BatteryChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/BatteryChannel.java | /*
* BatteryChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class BatteryChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaticaListener _listener;
public BatteryChannel()
{
_name = "Empatica_Battery";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Empatica)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.getBattery();
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 1;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Battery";
}
}
| 2,792 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BVPChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/BVPChannel.java | /*
* BVPChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class BVPChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 64, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaticaListener _listener;
public BVPChannel()
{
_name = "Empatica_BVP";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Empatica)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.getBvp();
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 1;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "BVP";
}
}
| 2,768 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TemperatureChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/empatica/TemperatureChannel.java | /*
* TemperatureChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.empatica;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class TemperatureChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 4, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected EmpaticaListener _listener;
public TemperatureChannel()
{
_name = "Empatica_Temp";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Empatica)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.getTemperature();
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 1;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Temperature";
}
}
| 2,807 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FaceLandmarks.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/FaceLandmarks.java | /*
* FaceLandmarks.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import com.tzutalin.dlib.FaceDet;
import com.tzutalin.dlib.VisionDetRet;
import org.tensorflow.lite.Interpreter;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import hcm.ssj.camera.CameraUtil;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.FileCons;
import hcm.ssj.landmark.utils.LandmarkSmoothingCalculator;
import hcm.ssj.ml.TFLiteWrapper;
import hcm.ssj.ssd.CalculatorOptions;
import hcm.ssj.ssd.Detection;
import hcm.ssj.ssd.Keypoint;
import hcm.ssj.ssd.Landmark;
import hcm.ssj.ssd.SingleShotMultiBoxDetector;
/**
* Created by Michael Dietz on 08.01.2021.
*
* Lip landmarks
* 61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291 // Outer lip lower half (61 left, 17 center, 291 right)
* 61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291 // Outer lip upper half (61 left, 0 center 291 right)
* 78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308 // Inner lip lower half (78 left, 14 center, 308 right)
* 78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308 // Inner lip upper half (78 left, 13 center, 308 right)
*
* Left eye. (outer to inner)
* 33, 7, 163, 144, 145, 153, 154, 155, 133 // Left eye lower half (33 left, 145 center, 133 right)
* 33, 246, 161, 160, 159, 158, 157, 173, 133 // Left eye upper half (33 left, 159 center, 133 right)
*
* Left eyebrow. (outer to inner)
* 46, 53, 52, 65, 55 // Left eyebrow lower bounds (46 left, 55 right)
* 70, 63, 105, 66, 107 // left eyebrow upper bounds (70 left, 107 right)
*
* Right eye. (outer to inner)
* 263, 249, 390, 373, 374, 380, 381, 382, 362 // Right eye lower half (362 left, 374 center, 263 right)
* 263, 466, 388, 387, 386, 385, 384, 398, 362 // Right eye upper half (362 left, 386 center, 263 right)
*
* Right eyebrow (outer to inner)
* 276, 283, 282, 295, 285 // Right eyebrow lower bounds (285 left, 276 right)
* 300, 293, 334, 296, 336 // Right eyebrow upper bounds (336 left, 300 right)
*
* Face oval (clockwise, 10 top center, 152 bottom center)
* 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109
*
*/
public class FaceLandmarks extends Transformer
{
private static final String LEGACY_MODEL_NAME = "shape_predictor_68_face_landmarks.dat";
private static final String LEGACY_MODEL_PATH = FileCons.MODELS_DIR + File.separator + LEGACY_MODEL_NAME;
private static final int LEGACY_MODEL_INPUT_SIZE = 224;
private static final int LEGACY_LANDMARK_NUM = 68;
private static final int LEGACY_OUTPUT_DIM = LEGACY_LANDMARK_NUM * 2; // x, y for each landmark
private static final String DETECTION_MODEL_NAME = "face_detection_front.tflite";
private static final String DETECTION_MODEL_PATH = FileCons.MODELS_DIR + File.separator + DETECTION_MODEL_NAME;
private static final int DETECTION_MODEL_INPUT_SIZE = 128;
private static final int DETECTION_MODEL_INPUT_CHANNELS = 3;
private static final String LANDMARK_MODEL_NAME = "face_landmark.tflite";
private static final String LANDMARK_MODEL_PATH = FileCons.MODELS_DIR + File.separator + LANDMARK_MODEL_NAME;
private static final int LANDMARK_MODEL_INPUT_SIZE = 192;
private static final int LANDMARK_MODEL_INPUT_CHANNELS = 3;
private static final int LANDMARK_NUM = 468;
private static final int LANDMARK_DIM = LANDMARK_NUM * 3; // x, y, z for each landmark
private static final int LANDMARK_OUTPUT_DIM = LANDMARK_NUM * 2; // x, y for each landmark
private static final double SCALE_FACTOR = 1.5;
public class Options extends OptionList
{
public final Option<Integer> rotation = new Option<>("rotation", 0, Integer.class, "rotation of the input image, use 270 for front camera and 90 for back camera");
public final Option<Float> faceConfidenceThreshold = new Option<>("faceConfidenceThreshold", 0.5f, Float.class, "threshold for the face confidence score to determine whether a face is present");
public final Option<Boolean> useGPU = new Option<>("useGPU", true, Boolean.class, "if true tries to use GPU for better performance");
public final Option<Boolean> useLegacyModel = new Option<>("useLegacyModel", false, Boolean.class, "if true uses old landmark detection model");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
// Helper class to postprocess classifier results
private SingleShotMultiBoxDetector ssd;
private TFLiteWrapper detectionWrapper;
private TFLiteWrapper landmarkWrapper;
// ByteBuffer to hold image data, to be feed into Tensorflow Lite as inputs.
private ByteBuffer detectionImgData = null;
private ByteBuffer landmarkImgData = null;
private int[] originalInputArray;
private int[] detectionModelInputArray;
private int[] landmarkModelInputArray;
// Create bitmap for the original image
private Bitmap inputBitmap;
// Rotated bitmap for original image
private Bitmap rotatedBitmap;
private Bitmap detectionModelInputBitmap;
private Bitmap landmarkModelInputBitmap;
private Bitmap faceBitmap;
private Matrix rotationMatrix;
private int rotatedWidth;
private int rotatedHeight;
private Detection currentDetection;
private double targetAngleRad;
private int width;
private int height;
private File detectionModelFile;
private File landmarkModelFile;
private List<Landmark> landmarkList;
private List<Landmark> smoothedLandmarkList;
private LandmarkSmoothingCalculator landmarkSmoother;
private double rotationRad;
private float faceCenterX;
private float faceCenterY;
private int boxSize;
private boolean faceDetected;
private boolean landmarksDetected;
private Keypoint leftKeypoint;
private Keypoint rightKeypoint;
private FaceDet legacyLandmarkDetector;
private List<VisionDetRet> legacyResults;
private int outputDim;
@Override
public OptionList getOptions()
{
return options;
}
public FaceLandmarks()
{
_name = this.getClass().getSimpleName();
}
@Override
public void init(double frame, double delta) throws SSJException
{
// Download face detection model
detectionModelFile = new File(DETECTION_MODEL_PATH);
if (!detectionModelFile.exists())
{
try
{
Pipeline.getInstance().download(DETECTION_MODEL_NAME, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true);
}
catch (IOException e)
{
throw new SSJException("Error while downloading face detection model!", e);
}
}
// Download face landmark model
landmarkModelFile = new File(LANDMARK_MODEL_PATH);
if (!landmarkModelFile.exists())
{
try
{
Pipeline.getInstance().download(LANDMARK_MODEL_NAME, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true);
}
catch (IOException e)
{
throw new SSJException("Error while downloading landmark detection model (" + LANDMARK_MODEL_NAME + ")!", e);
}
}
if (options.useLegacyModel.get())
{
outputDim = LEGACY_OUTPUT_DIM;
// Download legacy detection model
if (!new File(LEGACY_MODEL_PATH).exists())
{
try
{
Pipeline.getInstance().download(LEGACY_MODEL_NAME, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true);
}
catch (IOException e)
{
throw new SSJException("Error while downloading legacy face landmark model!", e);
}
}
}
else
{
outputDim = LANDMARK_OUTPUT_DIM;
}
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Get image dimensions
width = ((ImageStream) stream_in[0]).width;
height = ((ImageStream) stream_in[0]).height;
// Create bitmap for the original image
inputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
if (options.useLegacyModel.get())
{
legacyLandmarkDetector = new FaceDet(LEGACY_MODEL_PATH);
}
// Create TFLite Wrappers
detectionWrapper = new TFLiteWrapper(options.useGPU.get());
landmarkWrapper = new TFLiteWrapper(options.useGPU.get());
// Get TFLite interpreter options
Interpreter.Options interpreterOptions = detectionWrapper.getInterpreterOptions();
// Load TFLite models
detectionWrapper.loadModel(detectionModelFile, interpreterOptions);
landmarkWrapper.loadModel(landmarkModelFile, interpreterOptions);
// Initialize model input buffer: size = width * height * channels * bytes per pixel (e.g., 4 for float)
detectionImgData = ByteBuffer.allocateDirect(DETECTION_MODEL_INPUT_SIZE * DETECTION_MODEL_INPUT_SIZE * DETECTION_MODEL_INPUT_CHANNELS * Util.sizeOf(Cons.Type.FLOAT));
detectionImgData.order(ByteOrder.nativeOrder());
landmarkImgData = ByteBuffer.allocateDirect(LANDMARK_MODEL_INPUT_SIZE * LANDMARK_MODEL_INPUT_SIZE * LANDMARK_MODEL_INPUT_CHANNELS * Util.sizeOf(Cons.Type.FLOAT));
landmarkImgData.order(ByteOrder.nativeOrder());
// Initialize model input and output integer arrays
detectionModelInputArray = new int[DETECTION_MODEL_INPUT_SIZE * DETECTION_MODEL_INPUT_SIZE];
landmarkModelInputArray = new int[LANDMARK_MODEL_INPUT_SIZE * LANDMARK_MODEL_INPUT_SIZE];
rotationMatrix = new Matrix();
rotationMatrix.postRotate(options.rotation.get());
// Create SSD helper class
CalculatorOptions calculatorOptions = new CalculatorOptions();
calculatorOptions.minScoreThresh = 0.5;
ssd = new SingleShotMultiBoxDetector(calculatorOptions);
targetAngleRad = degreesToRadians(0);
landmarkList = new ArrayList<>();
smoothedLandmarkList = new ArrayList<>();
rotatedWidth = -1;
rotatedHeight = -1;
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Convert byte array to integer array
originalInputArray = CameraUtil.decodeBytes(stream_in[0].ptrB(), width, height);
// Create bitmap from byte array
inputBitmap.setPixels(originalInputArray, 0, width, 0, 0, width, height);
// Rotate original input
rotatedBitmap = Bitmap.createBitmap(inputBitmap, 0, 0, inputBitmap.getWidth(), inputBitmap.getHeight(), rotationMatrix, true);
// Cache width and height of rotated input image
if (rotatedWidth < 0)
{
rotatedWidth = rotatedBitmap.getWidth();
rotatedHeight = rotatedBitmap.getHeight();
landmarkSmoother = new LandmarkSmoothingCalculator(5, 10.0f, LANDMARK_NUM, rotatedWidth, rotatedHeight);
}
// Reset variables
faceDetected = false;
landmarksDetected = false;
// Resize rotated original input to model input size
detectionModelInputBitmap = Bitmap.createScaledBitmap(rotatedBitmap, DETECTION_MODEL_INPUT_SIZE, DETECTION_MODEL_INPUT_SIZE, true);
// Convert and normalize bitmap to model input
detectionWrapper.convertBitmapToInputArray(detectionModelInputBitmap, detectionModelInputArray, detectionImgData);
// Perform face detection
List<Detection> detectionList = detectFaceRegion(detectionImgData);
// Recycle landmark input image
detectionModelInputBitmap.recycle();
// Set detection result
faceDetected = detectionList.size() > 0;
// Face detected
if (faceDetected)
{
currentDetection = detectionList.get(0);
// Face detection contains two key points: left eye and right eye
leftKeypoint = currentDetection.keypoints.get(0);
rightKeypoint = currentDetection.keypoints.get(1);
// These keypoints will be used for rotation and scaling of the input image
faceBitmap = rotateAndScaleImage(rotatedBitmap, currentDetection, leftKeypoint, rightKeypoint);
if (options.useLegacyModel.get())
{
// Resize rotated and scaled input to model input size
landmarkModelInputBitmap = Bitmap.createScaledBitmap(faceBitmap, LEGACY_MODEL_INPUT_SIZE, LEGACY_MODEL_INPUT_SIZE, true);
// Perform legacy landmark detection
landmarksDetected = detectLegacyLandmarks(landmarkModelInputBitmap, landmarkList);
}
else
{
// Resize rotated and scaled input to model input size
landmarkModelInputBitmap = Bitmap.createScaledBitmap(faceBitmap, LANDMARK_MODEL_INPUT_SIZE, LANDMARK_MODEL_INPUT_SIZE, true);
// Convert and normalize bitmap to model input
landmarkWrapper.convertBitmapToInputArray(landmarkModelInputBitmap, landmarkModelInputArray, landmarkImgData, 0, 255.0f);
// Perform landmark detection
landmarksDetected = detectLandmarks(landmarkImgData, landmarkList);
}
// Recycle landmark input image
landmarkModelInputBitmap.recycle();
faceBitmap.recycle();
}
// Output stream
float[] out = stream_out.ptrF();
if (landmarksDetected)
{
// Smooth landmarks
// landmarkSmoother.process(landmarkList, smoothedLandmarkList);
int outputIndex = 0;
for (Landmark landmark : landmarkList)
{
out[outputIndex++] = landmark.x / rotatedWidth;
out[outputIndex++] = landmark.y / rotatedHeight;
// out[outputIndex++] = landmark.visibility;
}
}
else
{
// Send zeroes if no face has been recognized
Util.fillZeroes(out, 0, outputDim);
}
// Free bitmap memory
rotatedBitmap.recycle();
}
private List<Detection> detectFaceRegion(ByteBuffer modelInputBuffer)
{
// Fixed output of blazeface model
float[][][] boxesResult = new float[1][896][16];
float[][][] scoresResult = new float[1][896][1];
HashMap<Integer, Object> detectionOutputs = new HashMap<>();
detectionOutputs.put(0, boxesResult);
detectionOutputs.put(1, scoresResult);
// Run inference
detectionWrapper.runMultiInputOutput(new Object[]{modelInputBuffer}, detectionOutputs);
// Calculate detections from model results
return ssd.process(boxesResult, scoresResult);
}
private Bitmap rotateAndScaleImage(Bitmap rotatedBitmap, Detection currentDetection, Keypoint leftKeypoint, Keypoint rightKeypoint)
{
// Calculate rotation from keypoints
rotationRad = normalizeRadians(targetAngleRad - Math.atan2(-(rightKeypoint.y - leftKeypoint.y), rightKeypoint.x - leftKeypoint.x));
faceCenterX = currentDetection.xMin + currentDetection.width / 2.0f;
faceCenterY = currentDetection.yMin + currentDetection.height / 2.0f;
double xCenter = faceCenterX * rotatedWidth;
double yCenter = faceCenterY * rotatedHeight;
double boxRadius = Math.max(currentDetection.width * rotatedWidth, currentDetection.height * rotatedHeight) / 2.0f;
boxSize = (int) (2 * boxRadius);
int boxSizeScaled = (int) (SCALE_FACTOR * boxSize);
Bitmap faceBitmap = Bitmap.createBitmap(boxSizeScaled, boxSizeScaled, Bitmap.Config.ARGB_8888);
// Fill background white
Paint paintColor = new Paint();
paintColor.setColor(Color.WHITE);
paintColor.setStyle(Paint.Style.FILL);
Canvas canvas = new Canvas(faceBitmap);
canvas.drawPaint(paintColor);
// Set center point to (0,0) then rotate and translate back
Matrix matrix = new Matrix();
matrix.postTranslate((float) -xCenter, (float) -yCenter);
matrix.postRotate((float) -radiansToDegrees(rotationRad));
matrix.postTranslate((float) (boxRadius * SCALE_FACTOR), (float) (boxRadius * SCALE_FACTOR));
canvas.drawBitmap(rotatedBitmap, matrix, null);
return faceBitmap;
}
private boolean detectLandmarks(ByteBuffer landmarkImgData, List<Landmark> landmarkList)
{
boolean detected = false;
// Fixed output of landmark detection model
float[][][][] landmarkResult = new float[1][1][1][LANDMARK_DIM];
float[][][][] faceFlagResult = new float[1][1][1][1];
HashMap<Integer, Object> landmarkOutputs = new HashMap<>();
landmarkOutputs.put(0, landmarkResult);
landmarkOutputs.put(1, faceFlagResult);
// Run inference
landmarkWrapper.runMultiInputOutput(new Object[] {landmarkImgData}, landmarkOutputs);
// Set confidence that a face is present
float faceConfidence = faceFlagResult[0][0][0][0];
if (faceConfidence >= options.faceConfidenceThreshold.get())
{
detected = true;
// Convert landmarks
float landmarkX;
float landmarkY;
float landmarkZ;
float rotationSin = (float) Math.sin(rotationRad);
float rotationCos = (float) Math.cos(rotationRad);
landmarkList.clear();
// Based on: https://github.com/google/mediapipe/blob/master/mediapipe/calculators/util/landmark_projection_calculator.cc
for (int i = 0; i < landmarkResult[0][0][0].length; i += 3)
{
// Create relative landmark
landmarkX = landmarkResult[0][0][0][i] / LANDMARK_MODEL_INPUT_SIZE;
landmarkY = landmarkResult[0][0][0][i + 1] / LANDMARK_MODEL_INPUT_SIZE;
// Subtract pivot point
landmarkX = landmarkX - 0.5f;
landmarkY = landmarkY - 0.5f;
// Rotate point
float newX = rotationCos * landmarkX - rotationSin * landmarkY;
float newY = rotationSin * landmarkX + rotationCos * landmarkY;
newX *= SCALE_FACTOR;
newY *= SCALE_FACTOR;
landmarkX = newX * boxSize + faceCenterX * rotatedWidth;
landmarkY = newY * boxSize + faceCenterY * rotatedHeight;
// Ignore landmark z for now
landmarkZ = landmarkResult[0][0][0][i + 2] / LANDMARK_MODEL_INPUT_SIZE * boxSize;
landmarkList.add(new Landmark(landmarkX, landmarkY, landmarkZ));
}
}
return detected;
}
private boolean detectLegacyLandmarks(Bitmap landmarkModelInputBitmap, List<Landmark> landmarkList)
{
boolean detected = false;
// Call landmark detection with jni
// Based on https://github.com/tzutalin/dlib-android-app
legacyResults = legacyLandmarkDetector.detect(landmarkModelInputBitmap);
if (legacyResults != null && legacyResults.size() > 0)
{
detected = true;
// Convert landmarks
float landmarkX;
float landmarkY;
float rotationSin = (float) Math.sin(rotationRad);
float rotationCos = (float) Math.cos(rotationRad);
landmarkList.clear();
List<Point> landmarks = legacyResults.get(0).getFaceLandmarks();
for (Point landmark : landmarks)
{
// Create relative landmark
landmarkX = landmark.x / (float) LEGACY_MODEL_INPUT_SIZE;
landmarkY = landmark.y / (float) LEGACY_MODEL_INPUT_SIZE;
// Subtract pivot point
landmarkX = landmarkX - 0.5f;
landmarkY = landmarkY - 0.5f;
// Rotate point
float newX = rotationCos * landmarkX - rotationSin * landmarkY;
float newY = rotationSin * landmarkX + rotationCos * landmarkY;
newX *= SCALE_FACTOR;
newY *= SCALE_FACTOR;
landmarkX = newX * boxSize + faceCenterX * rotatedWidth;
landmarkY = newY * boxSize + faceCenterY * rotatedHeight;
landmarkList.add(new Landmark(landmarkX, landmarkY));
}
}
return detected;
}
public double degreesToRadians(double degrees)
{
return degrees * Math.PI / 180.0;
}
public double radiansToDegrees(double radians)
{
return radians * 180.0 / Math.PI;
}
public double normalizeRadians(double angleRad)
{
return angleRad - 2 * Math.PI * Math.floor((angleRad - (-Math.PI)) / (2 * Math.PI));
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Clean up
if (detectionWrapper != null)
{
detectionWrapper.close();
}
if (landmarkWrapper != null)
{
landmarkWrapper.close();
}
if (legacyLandmarkDetector != null)
{
legacyLandmarkDetector.release();
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return outputDim;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.IMAGE)
{
Log.e("unsupported input type");
}
return Util.sizeOf(Cons.Type.FLOAT);
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
// TODO set description
stream_out.desc[0] = "Landmark X";
stream_out.desc[1] = "Landmark Y";
}
} | 21,581 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LandmarkPainter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/LandmarkPainter.java | /*
* LandmarkPainter.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hcm.ssj.camera.CameraUtil;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 30.01.2019.
*/
public class LandmarkPainter extends Consumer
{
/**
* All options for the camera painter
*/
public class Options extends OptionList
{
//values should be the same as in camera
public final Option<Cons.ImageRotation> imageRotation = new Option<>("imageRotation", Cons.ImageRotation.MINUS_90, Cons.ImageRotation.class, "rotation of input picture");
public final Option<Boolean> scale = new Option<>("scale", false, Boolean.class, "scale image to match surface size");
public final Option<Boolean> useVisibility = new Option<>("useVisibility", false, Boolean.class, "use third dimension as landmark visibility");
public final Option<Float> visibilityThreshold = new Option<>("visibilityThreshold", 0.5f, Float.class, "threshold if a landmark should be shown based on visibility value");
public final Option<SurfaceView> surfaceView = new Option<>("surfaceView", null, SurfaceView.class, "the view on which the painter is drawn");
public final Option<Float> landmarkRadius = new Option<>("landmarkRadius", 3.0f, Float.class, "radius of landmark circle");
public final Option<Cons.DrawColor> drawColor = new Option<>("drawColor", Cons.DrawColor.WHITE, Cons.DrawColor.class, "landmark color");
private Options()
{
addOptions();
}
}
public LandmarkPainter()
{
_name = this.getClass().getSimpleName();
}
public final Options options = new Options();
private int imageStreamIndex = -1;
// Buffers
private int[] argbData;
private Bitmap inputBitmap;
private SurfaceView surfaceViewInner;
private SurfaceHolder surfaceHolder;
private Paint landmarkPaint;
@Override
public OptionList getOptions()
{
return options;
}
@Override
protected void init(Stream[] stream_in) throws SSJException
{
if (options.surfaceView.get() == null)
{
Log.w("surfaceView isn't set");
}
else
{
surfaceViewInner = options.surfaceView.get();
}
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length != 2)
{
Log.e("Stream count not supported! Requires 1 image and 1 landmark stream");
return;
}
if (stream_in[0].type == Cons.Type.IMAGE && stream_in[1].type == Cons.Type.FLOAT)
{
imageStreamIndex = 0;
}
else if (stream_in[0].type == Cons.Type.FLOAT && stream_in[1].type == Cons.Type.IMAGE)
{
imageStreamIndex = 1;
}
else
{
Log.e("Stream types not supported, must be IMAGE and FLOAT");
return;
}
synchronized (this)
{
if (surfaceViewInner == null)
{
// Wait for surfaceView creation
try
{
this.wait();
}
catch (InterruptedException e)
{
Log.e("Error while waiting for surfaceView creation", e);
}
}
}
ImageStream in = (ImageStream) stream_in[imageStreamIndex];
surfaceHolder = surfaceViewInner.getHolder();
// Create buffers
argbData = new int[in.width * in.height];
inputBitmap = Bitmap.createBitmap(in.width, in.height, Bitmap.Config.ARGB_8888);
landmarkPaint = new Paint();
landmarkPaint.setColor(options.drawColor.get().color);
landmarkPaint.setStyle(Paint.Style.FILL);
// Fix visibility usage if configured wrong
if (options.useVisibility.get() && stream_in[1 - imageStreamIndex].dim % 3 != 0 && stream_in[1 - imageStreamIndex].dim % 2 == 0)
{
options.useVisibility.set(false);
}
if (!options.useVisibility.get() && stream_in[1 - imageStreamIndex].dim % 2 != 0 && stream_in[1 - imageStreamIndex].dim % 3 == 0)
{
options.useVisibility.set(true);
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
draw(stream_in[imageStreamIndex].ptrB(), stream_in[1 - imageStreamIndex].ptrF(), ((ImageStream) stream_in[imageStreamIndex]).format);
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{
surfaceViewInner = null;
argbData = null;
surfaceHolder = null;
inputBitmap.recycle();
inputBitmap = null;
}
private void draw(final byte[] imageData, final float[] landmarkData, int imageFormat)
{
Canvas canvas = null;
if (surfaceHolder == null)
{
return;
}
try
{
synchronized (surfaceHolder)
{
canvas = surfaceHolder.lockCanvas();
if (canvas != null)
{
// Clear canvas.
canvas.drawColor(Color.BLACK);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int bitmapWidth = inputBitmap.getWidth();
int bitmapHeight = inputBitmap.getHeight();
int finalWidth = bitmapWidth;
int finalHeight = bitmapHeight;
//decode color format
decodeColor(imageData, bitmapWidth, bitmapHeight, imageFormat);
// Fill bitmap with picture
inputBitmap.setPixels(argbData, 0, bitmapWidth, 0, 0, bitmapWidth, bitmapHeight);
// Adjust width/height for rotation
switch (options.imageRotation.get())
{
case PLUS_90:
case MINUS_90:
int tmpWidth = bitmapWidth;
bitmapWidth = bitmapHeight;
bitmapHeight = tmpWidth;
break;
}
// Scale bitmap
if (options.scale.get())
{
float horizontalScale = canvasWidth / (float) bitmapWidth;
float verticalScale = canvasHeight / (float) bitmapHeight;
float scale = Math.min(horizontalScale, verticalScale);
bitmapWidth = (int) (bitmapWidth * scale);
bitmapHeight = (int) (bitmapHeight * scale);
}
finalWidth = bitmapWidth;
finalHeight = bitmapHeight;
// Restore width/height after scaling for rect placement
switch (options.imageRotation.get())
{
case PLUS_90:
case MINUS_90:
int tmpWidth = bitmapWidth;
bitmapWidth = bitmapHeight;
bitmapHeight = tmpWidth;
break;
}
int bitmapLeft = (canvasWidth - bitmapWidth) / 2; // could also do >> 1
int bitmapTop = (canvasHeight - bitmapHeight) / 2;
Rect dest = new Rect(bitmapLeft, bitmapTop, bitmapLeft + bitmapWidth, bitmapTop + bitmapHeight);
// Rotate canvas coordinate system around the center of the image.
canvas.save(); // canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.rotate(options.imageRotation.get().rotation, canvasWidth >> 1, canvasHeight >> 1);
// Draw bitmap into rect
canvas.drawBitmap(inputBitmap, null, dest, null);
canvas.restore();
// Draw landmarks
if (landmarkData.length > 0)
{
float landmarkLeft = (canvas.getWidth() - finalWidth) / 2.0f;
float landmarkTop = (canvas.getHeight() - finalHeight) / 2.0f;
int landmarkDim = 2;
if (options.useVisibility.get())
{
landmarkDim = 3;
}
for (int i = 0; i < landmarkData.length; i += landmarkDim)
{
boolean drawLandmark = true;
if (options.useVisibility.get())
{
drawLandmark = landmarkData[i + 2] >= options.visibilityThreshold.get();
}
if (drawLandmark)
{
canvas.drawCircle(landmarkLeft + landmarkData[i] * finalWidth, landmarkTop + landmarkData[i + 1] * finalHeight, options.landmarkRadius.get(), landmarkPaint);
}
}
}
}
}
}
catch (Exception e)
{
Log.e("Error while drawing on canvas", e);
}
finally
{
// Always try to unlock a locked canvas to keep the surface in a consistent state
if (canvas != null)
{
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
private void decodeColor(final byte[] data, int width, int height, int format)
{
// TODO: implement missing conversions
switch (format)
{
case ImageFormat.YV12:
{
throw new UnsupportedOperationException("Not implemented, yet");
}
case ImageFormat.YUV_420_888: //YV12_PACKED_SEMI
{
CameraUtil.decodeYV12PackedSemi(argbData, data, width, height);
break;
}
case ImageFormat.NV21:
{
CameraUtil.convertNV21ToARGBInt(argbData, data, width, height);
break;
}
case ImageFormat.FLEX_RGB_888:
{
CameraUtil.convertRGBToARGBInt(argbData, data, width, height);
break;
}
default:
{
Log.e("Wrong color format");
throw new RuntimeException();
}
}
}
}
| 10,124 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LandmarkFeatures.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/LandmarkFeatures.java | /*
* LandmarkFeatures.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 21.06.2021.
*/
public class LandmarkFeatures extends Transformer
{
public static final float INVALID_VALUE = -1;
public class Options extends OptionList
{
public final Option<Boolean> mocs = new Option<>("mocs", true, Boolean.class, "calculates the mouth open/close score");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public LandmarkFeatures()
{
_name = this.getClass().getSimpleName();
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] in = stream_in[0].ptrF();
float[] out = stream_out.ptrF();
if (options.mocs.get())
{
// Based on https://ieeexplore.ieee.org/document/5634522
double innerLipDistance = getInnerLipDistance(in);
double outerLipDistance = getOuterLipDistance(in);
if (outerLipDistance > 0)
{
out[0] = (float) (innerLipDistance / outerLipDistance);
}
else
{
out[0] = INVALID_VALUE;
}
}
}
public double getInnerLipDistance(float[] faceLandmarks)
{
// Upper lip center landmark
float x1 = getLandmarkX(13, faceLandmarks);
float y1 = getLandmarkY(13, faceLandmarks);
// Lower lip center landmark
float x2 = getLandmarkX(14, faceLandmarks);
float y2 = getLandmarkY(14, faceLandmarks);
// Return distance
return getDistance(x1, y1, x2, y2);
}
public double getOuterLipDistance(float[] faceLandmarks)
{
// Upper lip center landmark
float x1 = getLandmarkX(0, faceLandmarks);
float y1 = getLandmarkY(0, faceLandmarks);
// Lower lip center landmark
float x2 = getLandmarkX(17, faceLandmarks);
float y2 = getLandmarkY(17, faceLandmarks);
// Return distance
return getDistance(x1, y1, x2, y2);
}
public double getEyeDistance(float[] faceLandmarks)
{
// Left eye outer landmark
float x1 = getLandmarkX(33, faceLandmarks);
float y1 = getLandmarkY(33, faceLandmarks);
// Right eye outer landmark
float x2 = getLandmarkX(263, faceLandmarks);
float y2 = getLandmarkY(363, faceLandmarks);
// Return distance
return getDistance(x1, y1, x2, y2);
}
public float getLandmarkX(int landmarkIndex, float[] faceLandmarks)
{
return faceLandmarks[landmarkIndex * 2];
}
public float getLandmarkY(int landmarkIndex, float[] faceLandmarks)
{
return faceLandmarks[landmarkIndex * 2 + 1];
}
public double getDistance(float x1, float y1, float x2, float y2)
{
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return 1;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(getSampleType(stream_in));
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
if (options.mocs.get())
{
stream_out.desc[0] = "Mouth open";
}
}
}
| 4,782 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PoseLandmarks.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/PoseLandmarks.java | /*
* PoseLandmarks.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.gpu.CompatibilityList;
import org.tensorflow.lite.gpu.GpuDelegate;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import hcm.ssj.camera.CameraUtil;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.landmark.utils.LandmarkSmoothingCalculator;
import hcm.ssj.ml.TFLiteWrapper;
import hcm.ssj.ssd.CalculatorOptions;
import hcm.ssj.ssd.Detection;
import hcm.ssj.ssd.Keypoint;
import hcm.ssj.ssd.Landmark;
import hcm.ssj.ssd.SingleShotMultiBoxDetector;
import hcm.ssj.file.FileCons;
/**
* Created by Michael Dietz on 08.01.2021.
*/
public class PoseLandmarks extends Transformer
{
private static final String DETECTION_MODEL_NAME = "pose_detection.tflite";
private static final String DETECTION_MODEL_PATH = FileCons.MODELS_DIR + File.separator + DETECTION_MODEL_NAME;
private static final int DETECTION_MODEL_INPUT_SIZE = 128;
private static final int DETECTION_MODEL_INPUT_CHANNELS = 3;
private static final String LANDMARK_FULL_MODEL_NAME = "pose_landmark_full_body.tflite";
private static final String LANDMARK_UPPER_MODEL_NAME = "pose_landmark_upper_body.tflite";
private static final int LANDMARK_MODEL_INPUT_SIZE = 256;
private static final int LANDMARK_MODEL_INPUT_CHANNELS = 3;
public static final int LANDMARK_NUM_FULL = 33; // 35
public static final int LANDMARK_NUM_UPPER = 25; // 27
public static final int LANDMARK_DIM_FULL = LANDMARK_NUM_FULL * 3; // x, y, visibility for each landmark
public static final int LANDMARK_DIM_UPPER = LANDMARK_NUM_UPPER * 3;
public static final int AUX_LANDMARK_NUM = 2;
public static final double SCALE_FACTOR = 1.5;
public class Options extends OptionList
{
public final Option<Integer> rotation = new Option<>("rotation", 270, Integer.class, "rotation of the input image, use 270 for front camera and 90 for back camera");
public final Option<Boolean> onlyUpperBody = new Option<>("onlyUpperBody", false, Boolean.class, "only crop to upper body, if false crops to full body");
public final Option<Float> poseConfidenceThreshold = new Option<>("poseConfidenceThreshold", 0.5f, Float.class, "threshold for the pose confidence score to determine whether a pose is present");
public final Option<Boolean> useGPU = new Option<>("useGPU", true, Boolean.class, "if true tries to use GPU for better performance");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
// Helper class to postprocess classifier results
private SingleShotMultiBoxDetector ssd;
private TFLiteWrapper detectionWrapper;
private TFLiteWrapper landmarkWrapper;
// ByteBuffer to hold image data, to be feed into Tensorflow Lite as inputs.
private ByteBuffer detectionImgData = null;
private ByteBuffer landmarkImgData = null;
private int[] originalInputArray;
private int[] detectionModelInputArray;
private int[] landmarkModelInputArray;
// Create bitmap for the original image
private Bitmap inputBitmap;
// Rotated bitmap for original image
private Bitmap rotatedBitmap;
private Bitmap detectionModelInputBitmap;
private Bitmap landmarkModelInputBitmap;
private Bitmap poseBitmap;
private Matrix rotationMatrix;
private int rotatedWidth;
private int rotatedHeight;
private Detection currentDetection;
private double targetAngleRad;
private int width;
private int height;
private File detectionModelFile;
private File landmarkModelFile;
private List<Landmark> landmarkList;
private List<Landmark> smoothedLandmarkList;
private LandmarkSmoothingCalculator landmarkSmoother;
private int landmarkNum;
private double rotationRad;
private float poseCenterX;
private float poseCenterY;
private int boxSize;
private boolean doPoseDetection;
private boolean poseDetected;
private boolean landmarksDetected;
private Keypoint centerKeypoint;
private Keypoint scaleKeypoint;
private int outputDim;
@Override
public OptionList getOptions()
{
return options;
}
public PoseLandmarks()
{
_name = this.getClass().getSimpleName();
}
@Override
public void init(double frame, double delta) throws SSJException
{
// Download pose detection model
detectionModelFile = new File(DETECTION_MODEL_PATH);
if (!detectionModelFile.exists())
{
try
{
Pipeline.getInstance().download(DETECTION_MODEL_NAME, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true);
}
catch (IOException e)
{
throw new SSJException("Error while downloading face detection model!", e);
}
}
// Download pose landmark model
String landmarkModelName = LANDMARK_FULL_MODEL_NAME;
landmarkNum = LANDMARK_NUM_FULL;
outputDim = LANDMARK_DIM_FULL;
if (options.onlyUpperBody.get())
{
landmarkModelName = LANDMARK_UPPER_MODEL_NAME;
landmarkNum = LANDMARK_NUM_UPPER;
outputDim = LANDMARK_DIM_UPPER;
}
landmarkModelFile = new File(FileCons.MODELS_DIR + File.separator + landmarkModelName);
if (!landmarkModelFile.exists())
{
try
{
Pipeline.getInstance().download(landmarkModelName, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true);
}
catch (IOException e)
{
throw new SSJException("Error while downloading landmark detection model (" + landmarkModelName + ")!", e);
}
}
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Get image dimensions
width = ((ImageStream) stream_in[0]).width;
height = ((ImageStream) stream_in[0]).height;
// Create TFLite Wrappers
detectionWrapper = new TFLiteWrapper(options.useGPU.get());
landmarkWrapper = new TFLiteWrapper(options.useGPU.get());
// Get TFLite interpreter options
Interpreter.Options interpreterOptions = detectionWrapper.getInterpreterOptions();
// Load TFLite models
detectionWrapper.loadModel(detectionModelFile, interpreterOptions);
landmarkWrapper.loadModel(landmarkModelFile, interpreterOptions);
// Initialize model input buffer: size = width * height * channels * bytes per pixel (e.g., 4 for float)
detectionImgData = ByteBuffer.allocateDirect(DETECTION_MODEL_INPUT_SIZE * DETECTION_MODEL_INPUT_SIZE * DETECTION_MODEL_INPUT_CHANNELS * Util.sizeOf(Cons.Type.FLOAT));
detectionImgData.order(ByteOrder.nativeOrder());
landmarkImgData = ByteBuffer.allocateDirect(LANDMARK_MODEL_INPUT_SIZE * LANDMARK_MODEL_INPUT_SIZE * LANDMARK_MODEL_INPUT_CHANNELS * Util.sizeOf(Cons.Type.FLOAT));
landmarkImgData.order(ByteOrder.nativeOrder());
// Initialize model input and output integer arrays
detectionModelInputArray = new int[DETECTION_MODEL_INPUT_SIZE * DETECTION_MODEL_INPUT_SIZE];
landmarkModelInputArray = new int[LANDMARK_MODEL_INPUT_SIZE * LANDMARK_MODEL_INPUT_SIZE];
// Create bitmap for the original image
inputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
rotationMatrix = new Matrix();
rotationMatrix.postRotate(options.rotation.get());
// Create SSD helper class
CalculatorOptions calculatorOptions = new CalculatorOptions();
calculatorOptions.numCoords = 12;
calculatorOptions.numKeypoints = 4;
calculatorOptions.minScoreThresh = 0.5;
ssd = new SingleShotMultiBoxDetector(calculatorOptions);
targetAngleRad = degreesToRadians(90);
landmarkList = new ArrayList<>();
smoothedLandmarkList = new ArrayList<>();
doPoseDetection = true;
rotatedWidth = -1;
rotatedHeight = -1;
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Convert byte array to integer array
originalInputArray = CameraUtil.decodeBytes(stream_in[0].ptrB(), width, height);
// Create bitmap from byte array
inputBitmap.setPixels(originalInputArray, 0, width, 0, 0, width, height);
// Rotate original input
rotatedBitmap = Bitmap.createBitmap(inputBitmap, 0, 0, inputBitmap.getWidth(), inputBitmap.getHeight(), rotationMatrix, true);
// Cache width and height of rotated input image
if (rotatedWidth < 0)
{
rotatedWidth = rotatedBitmap.getWidth();
rotatedHeight = rotatedBitmap.getHeight();
landmarkSmoother = new LandmarkSmoothingCalculator(5, 10.0f, landmarkNum + AUX_LANDMARK_NUM, rotatedWidth, rotatedHeight);
}
// Reset variables
poseDetected = false;
landmarksDetected = false;
// Check if pose region should be detected or if previous aux keypoints should be used
if (doPoseDetection)
{
// Resize rotated original input to model input size
detectionModelInputBitmap = Bitmap.createScaledBitmap(rotatedBitmap, DETECTION_MODEL_INPUT_SIZE, DETECTION_MODEL_INPUT_SIZE, true);
// Convert and normalize bitmap to model input
detectionWrapper.convertBitmapToInputArray(detectionModelInputBitmap, detectionModelInputArray, detectionImgData);
// Perform pose detection
List<Detection> detectionList = detectPoseRegion(detectionImgData);
// Recycle landmark input image
detectionModelInputBitmap.recycle();
// Set detection result
poseDetected = detectionList.size() > 0;
// Pose detected
if (poseDetected)
{
currentDetection = detectionList.get(0);
// Pose detection contains four key points: first two for full-body pose and two more for upper-body pose.
int centerIndex = 0;
int scaleIndex = 1;
if (options.onlyUpperBody.get())
{
centerIndex = 2;
scaleIndex = 3;
}
// These keypoints will be used for rotation and scaling of the input image
centerKeypoint = currentDetection.keypoints.get(centerIndex);
scaleKeypoint = currentDetection.keypoints.get(scaleIndex);
}
}
else
{
// Use aux keypoints from previous landmark detection result
poseDetected = true;
}
// Landmark detection on pose region
if (poseDetected)
{
poseBitmap = rotateAndScaleImage(rotatedBitmap, centerKeypoint, scaleKeypoint);
// Resize rotated and scaled input to model input size
landmarkModelInputBitmap = Bitmap.createScaledBitmap(poseBitmap, LANDMARK_MODEL_INPUT_SIZE, LANDMARK_MODEL_INPUT_SIZE, true);
// Convert and normalize bitmap to model input
landmarkWrapper.convertBitmapToInputArray(landmarkModelInputBitmap, landmarkModelInputArray, landmarkImgData);
// Perform landmark detection
landmarksDetected = detectLandmarks(landmarkImgData, landmarkList);
// Recycle landmark input image
landmarkModelInputBitmap.recycle();
poseBitmap.recycle();
}
// Output stream
float[] out = stream_out.ptrF();
if (landmarksDetected)
{
doPoseDetection = false;
// Smooth landmarks
landmarkSmoother.process(landmarkList.subList(0, landmarkNum + AUX_LANDMARK_NUM), smoothedLandmarkList);
int outputIndex = 0;
for (Landmark landmark : smoothedLandmarkList.subList(0, landmarkNum))
{
out[outputIndex++] = landmark.x / rotatedWidth;
out[outputIndex++] = landmark.y / rotatedHeight;
out[outputIndex++] = landmark.visibility;
}
// Use auxiliary landmarks as center and scale keypoints
centerKeypoint = new Keypoint(smoothedLandmarkList.get(landmarkNum).x / rotatedWidth, smoothedLandmarkList.get(landmarkNum).y / rotatedHeight);
scaleKeypoint = new Keypoint(smoothedLandmarkList.get(landmarkNum + 1).x / rotatedWidth, smoothedLandmarkList.get(landmarkNum + 1).y / rotatedHeight);
}
else
{
// No landmarks detected, perform pose region detection in next iteration
doPoseDetection = true;
// Send zeroes if no face has been recognized
Util.fillZeroes(out, 0, outputDim);
}
// Free bitmap memory
rotatedBitmap.recycle();
}
private List<Detection> detectPoseRegion(ByteBuffer modelInputBuffer)
{
// Fixed output of pose detection model
float[][][] boxesResult = new float[1][896][12];
float[][][] scoresResult = new float[1][896][1];
HashMap<Integer, Object> detectionOutputs = new HashMap<>();
detectionOutputs.put(0, boxesResult);
detectionOutputs.put(1, scoresResult);
// Run inference
detectionWrapper.runMultiInputOutput(new Object[]{modelInputBuffer}, detectionOutputs);
// Calculate detections from model results
return ssd.process(boxesResult, scoresResult);
}
private Bitmap rotateAndScaleImage(Bitmap rotatedBitmap, Keypoint centerKeypoint, Keypoint scaleKeypoint)
{
// Calculate rotation from keypoints
rotationRad = normalizeRadians(targetAngleRad - Math.atan2(-(scaleKeypoint.y - centerKeypoint.y), scaleKeypoint.x - centerKeypoint.x));
poseCenterX = centerKeypoint.x;
poseCenterY = centerKeypoint.y;
double xCenter = centerKeypoint.x * rotatedWidth;
double yCenter = centerKeypoint.y * rotatedHeight;
double xScale = scaleKeypoint.x * rotatedWidth;
double yScale = scaleKeypoint.y * rotatedHeight;
double boxRadius = Math.sqrt((xScale - xCenter) * (xScale - xCenter) + (yScale - yCenter) * (yScale - yCenter));
boxSize = (int) (2 * boxRadius);
int boxSizeScaled = (int) (SCALE_FACTOR * boxSize);
Bitmap poseBitmap = Bitmap.createBitmap(boxSizeScaled, boxSizeScaled, Bitmap.Config.ARGB_8888);
// Fill background white
Paint paintColor = new Paint();
paintColor.setColor(Color.WHITE);
paintColor.setStyle(Paint.Style.FILL);
Canvas canvas = new Canvas(poseBitmap);
canvas.drawPaint(paintColor);
// Set center point to (0,0) then rotate and translate back
Matrix matrix = new Matrix();
matrix.postTranslate((float) -xCenter, (float) -yCenter);
matrix.postRotate((float) -radiansToDegrees(rotationRad));
matrix.postTranslate((float) (boxRadius * SCALE_FACTOR), (float) (boxRadius * SCALE_FACTOR));
canvas.drawBitmap(rotatedBitmap, matrix, null);
return poseBitmap;
}
private boolean detectLandmarks(ByteBuffer landmarkImgData, List<Landmark> landmarkList)
{
boolean detected = false;
// Fixed output of landmark detection model
float[][] landmarkResult = new float[1][156];
float[][] poseFlagResult = new float[1][1];
float[][][][] segmentationResult = new float[1][128][128][1];
if (options.onlyUpperBody.get())
{
landmarkResult = new float[1][124];
}
HashMap<Integer, Object> landmarkOutputs = new HashMap<>();
landmarkOutputs.put(0, landmarkResult);
landmarkOutputs.put(1, poseFlagResult);
landmarkOutputs.put(2, segmentationResult);
// Run inference
landmarkWrapper.runMultiInputOutput(new Object[] {landmarkImgData}, landmarkOutputs);
// Set confidence that a pose is present
float poseConfidence = poseFlagResult[0][0];
if (poseConfidence >= options.poseConfidenceThreshold.get())
{
detected = true;
// Convert landmarks
float landmarkX;
float landmarkY;
float landmarkZ;
float landmarkVisibility;
float rotationSin = (float) Math.sin(rotationRad);
float rotationCos = (float) Math.cos(rotationRad);
landmarkList.clear();
// Based on: https://github.com/google/mediapipe/blob/master/mediapipe/calculators/util/landmark_projection_calculator.cc
for (int i = 0; i < landmarkResult[0].length; i += 4)
{
// Create relative landmark
landmarkX = landmarkResult[0][i] / LANDMARK_MODEL_INPUT_SIZE;
landmarkY = landmarkResult[0][i + 1] / LANDMARK_MODEL_INPUT_SIZE;
// Subtract pivot point
landmarkX = landmarkX - 0.5f;
landmarkY = landmarkY - 0.5f;
// Rotate point
float newX = rotationCos * landmarkX - rotationSin * landmarkY;
float newY = rotationSin * landmarkX + rotationCos * landmarkY;
newX *= SCALE_FACTOR;
newY *= SCALE_FACTOR;
landmarkX = newX * boxSize + poseCenterX * rotatedWidth;
landmarkY = newY * boxSize + poseCenterY * rotatedHeight;
// Ignore landmark z for now
landmarkZ = landmarkResult[0][i + 2] / LANDMARK_MODEL_INPUT_SIZE * boxSize;
landmarkVisibility = (float) sigmoid(landmarkResult[0][i + 3]);
landmarkList.add(new Landmark(landmarkX, landmarkY, landmarkZ, landmarkVisibility));
}
}
return detected;
}
public double degreesToRadians(double degrees)
{
return degrees * Math.PI / 180.0;
}
public double radiansToDegrees(double radians)
{
return radians * 180.0 / Math.PI;
}
public double normalizeRadians(double angleRad)
{
return angleRad - 2 * Math.PI * Math.floor((angleRad - (-Math.PI)) / (2 * Math.PI));
}
public double sigmoid(double x)
{
return 1 / (1 + Math.exp(-x));
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Clean up
if (detectionWrapper != null)
{
detectionWrapper.close();
}
if (landmarkWrapper != null)
{
landmarkWrapper.close();
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
int dim = LANDMARK_DIM_FULL;
if (options.onlyUpperBody.get())
{
dim = LANDMARK_DIM_UPPER;
}
return dim;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.IMAGE)
{
Log.e("unsupported input type");
}
return Util.sizeOf(Cons.Type.FLOAT);
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
String[] points = new String[] {"nose", "left eye (inner)", "left eye", "left eye (outer)",
"right eye (inner)", "right eye", "right eye (outer)", "left ear", "right ear",
"mouth (left)", "mouth (right)", "left shoulder", "right shoulder", "left elbow",
"right elbow", "left wrist", "right wrist", "left pinky", "right pinky",
"left index", "right index", "left thumb", "right thumb", "left hip", "right hip",
"left knee", "right knee", "left ankle", "right ankle", "left heel", "right heel",
"left foot index", "right foot index"};
for (int i = 0, j = 0; i < stream_out.dim; i += 3, j++)
{
stream_out.desc[i] = points[j] + " x";
stream_out.desc[i + 1] = points[j] + " y";
stream_out.desc[i + 2] = points[j] + " visibility";
}
}
} | 19,860 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LowPassFilter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/utils/LowPassFilter.java | /*
* LowPassFilter.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark.utils;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 02.02.2021.
*
* Based on:
* https://github.com/google/mediapipe/blob/master/mediapipe/util/filtering/low_pass_filter.h
* https://github.com/google/mediapipe/blob/master/mediapipe/util/filtering/low_pass_filter.cc
*/
public class LowPassFilter
{
float alpha;
float rawValue;
float storedValue;
boolean initialized = false;
public LowPassFilter(float alpha)
{
setAlpha(alpha);
}
public float apply(float value)
{
float result;
if (initialized)
{
result = alpha * value + (1.0f - alpha) * storedValue;
}
else
{
result = value;
initialized = true;
}
rawValue = value;
storedValue = result;
return result;
}
public float applyWithAlpha(float value, float alpha)
{
setAlpha(alpha);
return apply(value);
}
public boolean hasLastRawValue()
{
return initialized;
}
public float lastRawValue()
{
return rawValue;
}
public float lastValue()
{
return storedValue;
}
private void setAlpha(float alpha)
{
if (alpha < 0.0f || alpha > 1.0f)
{
Log.e("Alpha " + alpha + " should be in [0.0, 1.0] range");
}
else
{
this.alpha = alpha;
}
}
}
| 2,568 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LandmarkSmoothingCalculator.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/utils/LandmarkSmoothingCalculator.java | /*
* LandmarkSmoothingCalculator.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark.utils;
import java.util.List;
import hcm.ssj.ssd.Landmark;
/**
* Created by Michael Dietz on 29.01.2021.
*
* Based on:
* https://github.com/google/mediapipe/blob/master/mediapipe/calculators/util/landmarks_smoothing_calculator.proto
* https://github.com/google/mediapipe/blob/master/mediapipe/calculators/util/landmarks_smoothing_calculator.cc
*/
public class LandmarkSmoothingCalculator
{
static final float MIN_ALLOWED_OBJECT_SCALE = 1e-6f;
final int imageWidth;
final int imageHeight;
final int windowSize;
final float velocityScale;
final int nLandmarks;
RelativeVelocityFilter[] xFilters;
RelativeVelocityFilter[] yFilters;
// RelativeVelocityFilter[] zFilters;
// Cache variables
long timestamp;
float objectScale;
float valueScale;
public LandmarkSmoothingCalculator(int windowSize, float velocityScale, int nLandmarks, int imageWidth, int imageHeight)
{
this.windowSize = windowSize;
this.velocityScale = velocityScale;
this.nLandmarks = nLandmarks;
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
initializeFilters(nLandmarks);
}
public void initializeFilters(int nLandmarks)
{
xFilters = new RelativeVelocityFilter[nLandmarks];
yFilters = new RelativeVelocityFilter[nLandmarks];
// zFilters = new RelativeVelocityFilter[nLandmarks];
for (int i = 0; i < nLandmarks; i++)
{
xFilters[i] = new RelativeVelocityFilter(windowSize, velocityScale);
yFilters[i] = new RelativeVelocityFilter(windowSize, velocityScale);
// zFilters[i] = new RelativeVelocityFilter(windowSize, velocityScale);
}
}
public void process(List<Landmark> inLandmarks, List<Landmark> outLandmarks)
{
outLandmarks.clear();
timestamp = System.currentTimeMillis();
objectScale = getObjectScale(inLandmarks);
if (objectScale < MIN_ALLOWED_OBJECT_SCALE)
{
outLandmarks.addAll(inLandmarks);
return;
}
valueScale = 1.0f / objectScale;
for (int i = 0; i < inLandmarks.size(); i++)
{
final Landmark inLandmark = inLandmarks.get(i);
Landmark outLandmark = new Landmark(inLandmark.visibility);
outLandmark.x = xFilters[i].apply(timestamp, valueScale, inLandmark.x * imageWidth) / imageWidth;
outLandmark.y = yFilters[i].apply(timestamp, valueScale, inLandmark.y * imageHeight) / imageHeight;
outLandmark.z = inLandmark.z;
// outLandmark.z = zFilters[i].apply(timestamp, valueScale, inLandmark.z * imageWidth) / imageWidth;
outLandmarks.add(outLandmark);
}
}
public float getObjectScale(List<Landmark> landmarks)
{
float xMin = Float.MAX_VALUE;
float xMax = -Float.MAX_VALUE;
float yMin = Float.MAX_VALUE;
float yMax = -Float.MAX_VALUE;
for (Landmark landmark : landmarks)
{
if (landmark.x < xMin)
{
xMin = landmark.x;
}
if (landmark.x > xMax)
{
xMax = landmark.x;
}
if (landmark.y < yMin)
{
yMin = landmark.y;
}
if (landmark.y > yMax)
{
yMax = landmark.y;
}
}
final float objectWidth = (xMax - xMin) * imageWidth;
final float objectHeight = (yMax - yMin) * imageHeight;
return (objectWidth + objectHeight) / 2.0f;
}
} | 4,497 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
RelativeVelocityFilter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/landmark/utils/RelativeVelocityFilter.java | /*
* RelativeVelocityFilter.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.landmark.utils;
import hcm.ssj.core.LimitedSizeQueue;
import hcm.ssj.core.Log;
/**
* This filter keeps track (on a window of specified size) of
* value changes over time, which as result gives us velocity of how value
* changes over time. With higher velocity it weights new values higher.
* <p>
* Use @window_size and @velocity_scale to tweak this filter for your use case.
* <p>
* higher @window_size adds to lag and to stability
* lower @velocity_scale adds to lag and to stability
* <p>
* Based on:
* https://github.com/google/mediapipe/blob/master/mediapipe/util/filtering/relative_velocity_filter.h
* https://github.com/google/mediapipe/blob/master/mediapipe/util/filtering/relative_velocity_filter.cc
*/
public class RelativeVelocityFilter
{
/**
* Define max cumulative duration assuming 5 frames per second is a good frame rate, so assuming 10 values
* per second or 1 / 5 of a second is a good duration per window element
*/
final long kAssumedMaxDuration = (long) (1e3 / 5);
final double kMicroSecondsToSecond = 1e-3;
float lastValue = 0;
float lastValueScale = 1;
long lastTimestamp = -1;
int maxWindowSize;
float velocityScale;
LimitedSizeQueue<WindowElement> window;
LowPassFilter lowPassFilter;
DistanceEstimationMode distanceMode;
public RelativeVelocityFilter(int windowSize, float velocityScale)
{
this(windowSize, velocityScale, DistanceEstimationMode.kLegacyTransition);
}
public RelativeVelocityFilter(int windowSize, float velocityScale, DistanceEstimationMode distanceMode)
{
this.maxWindowSize = windowSize;
this.velocityScale = velocityScale;
this.distanceMode = distanceMode;
this.window = new LimitedSizeQueue<>(windowSize);
this.lowPassFilter = new LowPassFilter(1.0f);
}
/**
* Applies filter to the value.
*
* @param timestamp Timestamp associated with the value (for instance,
* timestamp of the frame where you got value from)
* @param valueScale Value scale (for instance, if your value is a distance
* detected on a frame, it can look same on different
* devices but have quite different absolute values due
* to different resolution, you should come up with an
* appropriate parameter for your particular use case)
* @param value Value to filter
* @return Filter result
*/
public float apply(long timestamp, float valueScale, float value)
{
if (lastTimestamp >= timestamp)
{
Log.w("New timestamp is equal or less than the last one");
return value;
}
float alpha;
if (lastTimestamp == -1)
{
alpha = 1.0f;
}
else
{
float distance = distanceMode == DistanceEstimationMode.kLegacyTransition
? value * valueScale - lastValue * lastValueScale // Original
: valueScale * (value - lastValue); // Translation invariant
long duration = timestamp - lastTimestamp;
float cumulativeDistance = distance;
long cumulativeDuration = duration;
long maxCumulativeDuration = (1 + window.size()) * kAssumedMaxDuration;
// Iterate through queue in reverse to start with newest elements (newest added at end)
for (int i = window.size() - 1; i > 0; i--)
{
WindowElement element = window.get(i);
if (cumulativeDuration + element.duration > maxCumulativeDuration)
{
/*
This helps in cases when durations are large and outdated
window elements have bad impact on filtering results
*/
break;
}
cumulativeDistance += element.distance;
cumulativeDuration += element.duration;
}
final float velocity = (float) (cumulativeDistance / (cumulativeDuration * kMicroSecondsToSecond));
alpha = 1.0f - 1.0f / (1.0f + velocityScale * Math.abs(velocity));
window.add(new WindowElement(distance, duration));
}
lastValue = value;
lastValueScale = valueScale;
lastTimestamp = timestamp;
return lowPassFilter.applyWithAlpha(value, alpha);
}
static class WindowElement
{
public float distance;
public long duration;
public WindowElement(float distance, long duration)
{
this.distance = distance;
this.duration = duration;
}
}
enum DistanceEstimationMode
{
/**
* When the value scale changes, uses a heuristic
* that is not translation invariant (see the implementation for details).
*/
kLegacyTransition,
/**
* The current (i.e. last) value scale is always used for scale estimation.
* When using this mode, the filter is translation invariant, i.e.
* Filter(Data + Offset) = Filter(Data) + Offset.
*/
kForceCurrentState
}
}
| 5,970 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SignalPainter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/graphic/SignalPainter.java | /*
* SignalPainter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.graphic;
import android.os.Handler;
import android.os.Looper;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.util.ArrayList;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 26.05.2015.
*/
public class SignalPainter extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Double> size = new Option<>("size", 20., Double.class, "size of X-axis in seconds");
public final Option<Boolean> legend = new Option<>("legend", true, Boolean.class, "show legend");
public final Option<Boolean> manualBounds = new Option<>("manualBounds", false, Boolean.class, "set true to use manual min/max Y-axis boundaries");
public final Option<Double> min = new Option<>("min", 0., Double.class, "minimum Y-axis value");
public final Option<Double> max = new Option<>("max", 1., Double.class, "maximum Y-axis value");
public final Option<Integer> secondScaleStream = new Option<>("secondScaleStream", 1, Integer.class, "stream id to put on the secondary scale (use -1 to disable)");
public final Option<Integer> secondScaleDim = new Option<>("secondScaleDim", 0, Integer.class, "dimension id to put on the secondary scale (use -1 to disable)");
public final Option<Double> secondScaleMin = new Option<>("secondScaleMin", 0., Double.class, "minimum Y-axis value of secondary scale");
public final Option<Double> secondScaleMax = new Option<>("secondScaleMax", 1., Double.class, "maximum Y-axis value of secondary scale");
public final Option<Integer> numVLabels = new Option<>("numVLabels", 5, Integer.class, "number of vertical labels");
public final Option<Integer> numHLabels = new Option<>("numHLabels", 2, Integer.class, "number of horizontal labels");
public final Option<Boolean> renderMax = new Option<>("renderMax", true, Boolean.class, "render only the max value of a frame");
public final Option<GraphView> graphView = new Option<>("graphView", null, GraphView.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public Options options = new Options();
private static int color_id = 0;
final private int[] colors = new int[]{0xffffd54f, 0xffed1c24, 0xff0F9D58, 0xff29b6f6, 0xff0077cc, 0xffff9900, 0xff009999, 0xff990000, 0xffff00ff, 0xff000000, 0xff339900};
private ArrayList<LineGraphSeries<DataPoint>> _series = new ArrayList<>();
GraphView _view = null;
int[] _maxPoints;
public SignalPainter()
{
_name = "SignalPainter";
_doWakeLock = false; //since this is a GUI element, disable wakelock to save energy
}
/**
* @param stream_in Stream[]
*/
@Override
protected void init(Stream[] stream_in) throws SSJException
{
super.init(stream_in);
if (options.graphView.get() == null)
{
Log.w("graphView isn't set");
}
else
{
_view = options.graphView.get();
}
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
synchronized (this)
{
if (_view == null)
{
//wait for graphView creation
try
{
this.wait();
} catch (InterruptedException ex)
{
Log.e("graph view not registered");
}
}
}
if(stream_in.length > 2)
{
Log.w("plotting more than 2 streams per graph will not work if streams are not similar");
}
int dimTotal = 0;
for (Stream s : stream_in)
{
dimTotal += s.dim;
}
_maxPoints = new int[dimTotal];
_view.getViewport().setXAxisBoundsManual(true);
_view.getViewport().setMinX(0);
_view.getViewport().setMaxX(options.size.get());
_view.getViewport().setYAxisBoundsManual(options.manualBounds.get());
_view.getViewport().setMaxY(options.max.get());
_view.getViewport().setMinY(options.min.get());
_view.getGridLabelRenderer().setNumHorizontalLabels(options.numHLabels.get());
_view.getGridLabelRenderer().setNumVerticalLabels(options.numVLabels.get());
_view.getLegendRenderer().setVisible(options.legend.get());
_view.getLegendRenderer().setFixedPosition(10, 10);
createSeries(_view, stream_in);
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
int seriesID = 0;
for (int k = 0; k < stream_in.length; k++)
{
for (int i = 0; i < stream_in[k].dim; i++)
{
switch (stream_in[k].type)
{
case CHAR:
{
char[] in = stream_in[k].ptrC();
char max = Character.MIN_VALUE;
char value;
double time = stream_in[k].time;
for (int j = 0; j < stream_in[k].num; j++, time += stream_in[k].step)
{
value = in[j * stream_in[k].dim + i];
if (!options.renderMax.get())
{
pushData(seriesID, value, time);
} else if (value > max)
{
max = value;
}
}
if (options.renderMax.get())
{
pushData(seriesID, max, stream_in[k].time);
}
break;
}
case SHORT:
{
short[] in = stream_in[k].ptrS();
short max = Short.MIN_VALUE;
short value;
double time = stream_in[k].time;
for (int j = 0; j < stream_in[k].num; j++, time += stream_in[k].step)
{
value = in[j * stream_in[k].dim + i];
if (!options.renderMax.get())
{
pushData(seriesID, value, time);
} else if (value > max)
{
max = value;
}
}
if (options.renderMax.get())
{
pushData(seriesID, max, stream_in[k].time);
}
break;
}
case INT:
{
int[] in = stream_in[k].ptrI();
int max = Integer.MIN_VALUE;
int value;
double time = stream_in[k].time;
for (int j = 0; j < stream_in[k].num; j++, time += stream_in[k].step)
{
value = in[j * stream_in[k].dim + i];
if (!options.renderMax.get())
{
pushData(seriesID, value, time);
} else if (value > max)
{
max = value;
}
}
if (options.renderMax.get())
{
pushData(seriesID, max, stream_in[k].time);
}
break;
}
case LONG:
{
long[] in = stream_in[k].ptrL();
long max = Long.MIN_VALUE;
long value;
double time = stream_in[k].time;
for (int j = 0; j < stream_in[k].num; j++, time += stream_in[k].step)
{
value = in[j * stream_in[k].dim + i];
if (!options.renderMax.get())
{
pushData(seriesID, value, time);
} else if (value > max)
{
max = value;
}
}
if (options.renderMax.get())
{
pushData(seriesID, max, stream_in[k].time);
}
break;
}
case FLOAT:
{
float[] in = stream_in[k].ptrF();
float max = -1 * Float.MAX_VALUE;
float value;
double time = stream_in[k].time;
for (int j = 0; j < stream_in[k].num; j++, time += stream_in[k].step)
{
value = in[j * stream_in[k].dim + i];
if (!options.renderMax.get())
{
pushData(seriesID, value, time);
} else if (value > max)
{
max = value;
}
}
if (options.renderMax.get())
{
pushData(seriesID, max, stream_in[k].time);
}
break;
}
case DOUBLE:
{
double[] in = stream_in[k].ptrD();
double max = -1 * Double.MAX_VALUE;
double value;
double time = stream_in[k].time;
for (int j = 0; j < stream_in[k].num; j++, time += stream_in[k].step)
{
value = in[j * stream_in[k].dim + i];
if (!options.renderMax.get())
{
pushData(seriesID, value, time);
} else if (value > max)
{
max = value;
}
}
if (options.renderMax.get())
{
pushData(seriesID, max, stream_in[k].time);
}
break;
}
default:
Log.w("unsupported data type");
return;
}
seriesID++;
}
}
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{
_series.clear();
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
_view.removeAllSeries();
_view.clearSecondScale();
_view = null;
}
}, 1);
}
private void pushData(final int seriesID, double value, double time)
{
//apparently GraphView can't render infinity
if(Double.isNaN(value) || Double.isInfinite(value) || value == -1 * Double.MAX_VALUE || value == Double.MAX_VALUE)
return;
final DataPoint p = new DataPoint(time, value);
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
if(seriesID < _series.size())
_series.get(seriesID).appendData(p, true, _maxPoints[seriesID]);
}
}, 1);
}
private void createSeries(final GraphView view, final Stream[] stream_in)
{
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
for (int i = 0; i < stream_in.length; i++)
{
for (int j = 0; j < stream_in[i].dim; j++)
{
LineGraphSeries<DataPoint> s = new LineGraphSeries<>();
s.setTitle(stream_in[i].desc[j]);
s.setColor(colors[color_id++ % colors.length]);
//define scale length
if(!options.renderMax.get())
_maxPoints[_series.size()] = (int)(options.size.get() * stream_in[i].sr) +1;
else
_maxPoints[_series.size()] = (int)(options.size.get() * (stream_in[i].sr / (double)stream_in[i].num)) +1;
_series.add(s);
if (options.secondScaleStream.get() == i && options.secondScaleDim.get() == j)
{
view.getSecondScale().setMinY(options.secondScaleMin.get());
view.getSecondScale().setMaxY(options.secondScaleMax.get());
view.getSecondScale().addSeries(s);
} else
{
_view.addSeries(s);
}
}
}
}
}, 1);
}
}
| 15,509 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GridPainter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/graphic/GridPainter.java | /*
* DimensionalPainter.java
* Copyright (c) 2020
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.graphic;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 12.02.2020.
*/
public class GridPainter extends Consumer
{
/**
* All options for the camera painter
*/
public class Options extends OptionList
{
public final Option<String> minLabelX = new Option<>("minLabelX", "min x value", String.class, "minimum X-axis label");
public final Option<String> maxLabelX = new Option<>("maxLabelX", "max x value", String.class, "maximum X-axis label");
public final Option<String> minLabelY = new Option<>("minLabelY", "min y value", String.class, "minimum Y-axis label");
public final Option<String> maxLabelY = new Option<>("maxLabelY", "max y value", String.class, "maximum Y-axis label");
public final Option<Double> minValueX = new Option<>("minValueX", -1., Double.class, "minimum X-axis value");
public final Option<Double> maxValueX = new Option<>("maxValueX", 1., Double.class, "maximum X-axis value");
public final Option<Double> minValueY = new Option<>("minValueY", -1., Double.class, "minimum Y-axis value");
public final Option<Double> maxValueY = new Option<>("maxValueY", 1., Double.class, "maximum Y-axis value");
public final Option<Boolean> limitValues = new Option<>("limitValues", true, Boolean.class, "Limit values to defined x and y ranges");
public final Option<SurfaceView> surfaceView = new Option<>("surfaceView", null, SurfaceView.class, "the view on which the painter is drawn");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private class GridPoint
{
private double x;
private double y;
public void set(double x, double y)
{
setX(x);
setY(y);
}
public float getRelativeX()
{
return (float) ((x - options.minValueX.get()) / valueRangeX);
}
public void setX(double x)
{
this.x = x;
}
public float getRelativeY()
{
return (float) ((y - options.minValueY.get()) / valueRangeY);
}
public void setY(double y)
{
this.y = y;
}
public void clip()
{
x = Math.min(Math.max(x, options.minValueX.get()), options.maxValueX.get());
y = Math.min(Math.max(y, options.minValueY.get()), options.maxValueY.get());
}
public boolean inRange()
{
return x >= options.minValueX.get() && x <= options.maxValueX.get() &&
y >= options.minValueY.get() && y <= options.maxValueY.get();
}
}
final private int[] colors = new int[]{0xff0F9D58, 0xffed1c24, 0xffffd54f, 0xff29b6f6, 0xff0077cc, 0xffff9900, 0xff009999, 0xff990000, 0xffff00ff, 0xff000000, 0xff339900};
private static final int TEXT_SIZE = 35;
private static final int INDICATOR_SIZE = 10;
private SurfaceView surfaceViewInner;
private SurfaceHolder surfaceHolder;
private Paint indicatorPaint;
private Paint linePaint;
private int textHeight;
private String[] streamDescription;
private Paint textPaint;
private List<List<GridPoint>> pointList;
private double valueRangeX;
private double valueRangeY;
public GridPainter()
{
_name = this.getClass().getSimpleName();
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
protected void init(Stream[] stream_in) throws SSJException
{
if (options.surfaceView.get() == null)
{
Log.w("surfaceView isn't set");
}
else
{
surfaceViewInner = options.surfaceView.get();
}
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
synchronized (this)
{
if (surfaceViewInner == null)
{
// Wait for surfaceView creation
try
{
this.wait();
}
catch (InterruptedException e)
{
Log.e("Error while waiting for surfaceView creation", e);
}
}
}
surfaceViewInner.setZOrderOnTop(true);
surfaceHolder = surfaceViewInner.getHolder();
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
indicatorPaint = new Paint();
indicatorPaint.setStyle(Paint.Style.FILL);
indicatorPaint.setAntiAlias(true);
linePaint = new Paint();
linePaint.setColor(Color.parseColor("#000000"));
linePaint.setStrokeWidth(3);
linePaint.setStyle(Paint.Style.FILL);
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(TEXT_SIZE);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setAntiAlias(true);
textPaint.setTextAlign(Paint.Align.LEFT);
textHeight = (int) (textPaint.descent() - textPaint.ascent());
pointList = new ArrayList<>();
streamDescription = new String[stream_in.length];
valueRangeX = options.maxValueX.get() - options.minValueX.get();
valueRangeY = options.maxValueY.get() - options.minValueY.get();
for (int i = 0; i < stream_in.length; i++)
{
if (stream_in[i].dim != 2)
{
Log.e("Stream " + i + " does not have two dimensions!");
return;
}
streamDescription[i] = stream_in[i].desc[0] + "/" + stream_in[i].desc[1];
ArrayList<GridPoint> streamPointList = new ArrayList<>();
for (int j = 0; j < stream_in[i].num; j++)
{
streamPointList.add(new GridPoint());
}
pointList.add(streamPointList);
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
for (int i = 0; i < stream_in.length; i++)
{
switch (stream_in[i].type)
{
case CHAR:
{
char[] values = stream_in[i].ptrC();
for (int j = 0; j < stream_in[i].num; j++)
{
pointList.get(i).get(j).set(values[stream_in[i].dim * j], values[stream_in[i].dim * j + 1]);
}
break;
}
case SHORT:
{
short[] values = stream_in[i].ptrS();
for (int j = 0; j < stream_in[i].num; j++)
{
pointList.get(i).get(j).set(values[stream_in[i].dim * j], values[stream_in[i].dim * j + 1]);
}
break;
}
case INT:
{
int[] values = stream_in[i].ptrI();
for (int j = 0; j < stream_in[i].num; j++)
{
pointList.get(i).get(j).set(values[stream_in[i].dim * j], values[stream_in[i].dim * j + 1]);
}
break;
}
case LONG:
{
long[] values = stream_in[i].ptrL();
for (int j = 0; j < stream_in[i].num; j++)
{
pointList.get(i).get(j).set(values[stream_in[i].dim * j], values[stream_in[i].dim * j + 1]);
}
break;
}
case FLOAT:
{
float[] values = stream_in[i].ptrF();
for (int j = 0; j < stream_in[i].num; j++)
{
pointList.get(i).get(j).set(values[stream_in[i].dim * j], values[stream_in[i].dim * j + 1]);
}
break;
}
case DOUBLE:
{
double[] values = stream_in[i].ptrD();
for (int j = 0; j < stream_in[i].num; j++)
{
pointList.get(i).get(j).set(values[stream_in[i].dim * j], values[stream_in[i].dim * j + 1]);
}
break;
}
}
}
draw(pointList);
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{
surfaceViewInner = null;
surfaceHolder = null;
}
private void draw(List<List<GridPoint>> points)
{
Canvas canvas = null;
if (surfaceHolder == null)
{
return;
}
try
{
synchronized (surfaceHolder)
{
canvas = surfaceHolder.lockCanvas();
if (canvas != null)
{
// Clear canvas.
canvas.drawColor(Color.WHITE);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int axisLength = Math.min(canvasWidth, canvasHeight);
float canvasCenterX = canvasWidth / 2f;
float canvasCenterY = canvasHeight / 2f;
float startX = (canvasWidth - axisLength) / 2f;
float endX = startX + axisLength;
float startY = (canvasHeight - axisLength) / 2f;
float endY = startY + axisLength;
float contentStartX = startX + textHeight;
float contentEndX = endX - textHeight;
float contentStartY = startY + textHeight;
float contentEndY = endY - textHeight;
float contentWidth = contentEndX - contentStartX;
float contentHeight = contentEndY - contentStartY;
// Draw horizontal line
canvas.drawLine(contentStartX, canvasCenterY, contentEndX, canvasCenterY, linePaint);
// Draw vertical line
canvas.drawLine(canvasCenterX, contentStartY, canvasCenterX, contentEndY, linePaint);
// Draw y-axis labels
drawTextCentered(canvas, options.maxLabelY.get(), canvasCenterX, startY, true);
drawTextCentered(canvas, options.minLabelY.get(), canvasCenterX, endY, false);
// Draw x-axis labels
canvas.save();
canvas.rotate(-90, canvasCenterX, canvasCenterY);
drawTextCentered(canvas, options.minLabelX.get(), canvasCenterX, startY, true);
drawTextCentered(canvas, options.maxLabelX.get(), canvasCenterX, endY, false);
canvas.restore();
// Draw indicators
for (int i = 0; i < points.size(); i++)
{
indicatorPaint.setColor(colors[i % colors.length]);
for (GridPoint point : points.get(i))
{
if (options.limitValues.get())
{
point.clip();
}
if (point.inRange())
{
canvas.drawCircle(contentStartX + contentWidth * point.getRelativeX(), contentEndY - contentHeight * point.getRelativeY(), INDICATOR_SIZE, indicatorPaint);
}
}
}
}
}
}
catch (Exception e)
{
Log.e("Error while drawing on canvas", e);
}
finally
{
// Always try to unlock a locked canvas to keep the surface in a consistent state
if (canvas != null)
{
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
private void drawTextCentered(Canvas canvas, String text, float x, float y, boolean alignTop)
{
// see https://stackoverflow.com/questions/11120392/android-center-text-on-canvas
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
float posX = x - bounds.width() / 2f - bounds.left;
float posY;
if (alignTop)
{
posY = y + bounds.height() - bounds.bottom;
}
else
{
posY = y - bounds.bottom;
}
canvas.drawText(text, posX, posY, textPaint);
}
}
| 11,769 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EventPainter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/graphic/EventPainter.java | /*
* EventPainter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.graphic;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Johnny on 26.05.2015.
*/
public class EventPainter extends EventHandler
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> title = new Option<>("title", "events", String.class, "");
public final Option<String> color = new Option<>("color", "blue", String.class, "Chart color either as HEX or color name (e.g. blue, red ...)");
public final Option<Integer> numBars = new Option<>("numBars", 2, Integer.class, "");
public final Option<Integer> spacing = new Option<>("spacing", 50, Integer.class, "space between bars");
public final Option<GraphView> graphView = new Option<>("graphView", null, GraphView.class, ""); public final Option<Boolean> manualBounds = new Option<>("manualBounds", false, Boolean.class, "");
public final Option<Double> min = new Option<>("min", 0., Double.class, "");
public final Option<Double> max = new Option<>("max", 1., Double.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public Options options = new Options();
private BarGraphSeries<DataPoint> _series;
GraphView _view = null;
public EventPainter()
{
_name = "EventPainter";
_doWakeLock = false; //since this is a GUI element, disable wakelock to save energy
}
@Override
public void enter() throws SSJFatalException
{
if (options.graphView.get() == null)
{
Log.w("graphView isn't set");
}
else
{
_view = options.graphView.get();
}
synchronized (this)
{
if (_view == null)
{
//wait for graphView creation
try
{
this.wait();
} catch (InterruptedException ex)
{
Log.e("graph view not registered");
}
}
}
_view.getViewport().setXAxisBoundsManual(true);
_view.getViewport().setMinX(0);
_view.getViewport().setMaxX(options.numBars.get()+1);
_view.getViewport().setYAxisBoundsManual(options.manualBounds.get());
_view.getViewport().setMaxY(options.max.get());
_view.getViewport().setMinY(options.min.get());
_view.getGridLabelRenderer().setHorizontalLabelsVisible(false);
_view.getGridLabelRenderer().setHorizontalAxisTitle(options.title.get());
_view.getGridLabelRenderer().setNumVerticalLabels(2);
_view.getGridLabelRenderer().setGridStyle(GridLabelRenderer.GridStyle.HORIZONTAL);
_view.getLegendRenderer().setVisible(false);
createSeries(_view, options.spacing.get());
}
@Override
public void notify(Event event) {
DataPoint[] points = new DataPoint[options.numBars.get()];
for (int i = 0; i < options.numBars.get(); i++) {
switch (event.type) {
case BYTE:
points[i] = new DataPoint(i+1, event.ptrB()[i]);
break;
case SHORT:
points[i] = new DataPoint(i+1, event.ptrShort()[i]);
break;
case INT:
points[i] = new DataPoint(i+1, event.ptrI()[i]);
break;
case LONG:
points[i] = new DataPoint(i+1, event.ptrL()[i]);
break;
case FLOAT:
points[i] = new DataPoint(i+1, event.ptrF()[i]);
break;
case DOUBLE:
points[i] = new DataPoint(i+1, event.ptrD()[i]);
break;
default:
Log.w("unsupported even type");
return;
}
}
pushData(points);
}
@Override
public void flush() throws SSJFatalException
{
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
_view.removeAllSeries();
_view.clearSecondScale();
_view = null;
}
}, 1);
}
private void pushData(final DataPoint[] points)
{
for(DataPoint p : points)
if(Double.isNaN(p.getY()) || Double.isInfinite(p.getY()) || p.getY() == -1 * Double.MAX_VALUE || p.getY() == Double.MAX_VALUE)
return; //apparently GraphView can't render infinity
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
_series.resetData(points);
}
}, 1);
}
private void createSeries(final GraphView view, final int spacing)
{
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
_series = new BarGraphSeries<>();
_series.setColor(Color.parseColor(options.color.get()));
_series.setDrawValuesOnTop(true);
_series.setValuesOnTopColor(Color.BLACK);
_series.setSpacing(spacing);
view.addSeries(_series);
}
}, 1);
}
}
| 7,296 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CameraPainter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/CameraPainter.java | /*
* CameraPainter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.EventChannel;
import hcm.ssj.core.EventListener;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Camera painter for SSJ.<br>
* Created by Frank Gaibler on 21.01.2016.
*/
public class CameraPainter extends Consumer implements EventListener
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the camera painter
*/
public class Options extends OptionList
{
//values should be the same as in camera
public final Option<Integer> orientation = new Option<>("orientation", 90, Integer.class, "orientation of input picture (90 = back, 270 = front camera)");
public final Option<Boolean> scale = new Option<>("scale", false, Boolean.class, "scale picture to match surface size");
public final Option<Boolean> showBestMatch = new Option<>("showBestMatch", false, Boolean.class, "show object label of the best match");
public final Option<SurfaceView> surfaceView = new Option<>("surfaceView", null, SurfaceView.class, "the view on which the painter is drawn");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//buffers
private int[] iaRgbData;
private Bitmap bitmap;
//
private SurfaceView surfaceViewInner = null;
private SurfaceHolder surfaceHolder;
private String event_msg;
private int textSize = 35;
private Paint interiorPaint;
private Paint exteriorPaint;
/**
*
*/
public CameraPainter()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
protected void init(Stream[] stream_in) throws SSJException
{
super.init(stream_in);
if (options.surfaceView.get() == null)
{
Log.w("surfaceView isn't set");
}
else
{
surfaceViewInner = options.surfaceView.get();
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length != 1)
{
Log.e("Stream count not supported");
return;
}
if (stream_in[0].type != Cons.Type.IMAGE)
{
Log.e("Stream type not supported");
return;
}
synchronized (this)
{
if (surfaceViewInner == null)
{
//wait for surfaceView creation
try
{
this.wait();
} catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
ImageStream in = (ImageStream)stream_in[0];
surfaceHolder = surfaceViewInner.getHolder();
iaRgbData = new int[in.width * in.height];
//set bitmap
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
bitmap = Bitmap.createBitmap(in.width, in.height, conf);
//register listener
if (_evchannel_in != null && _evchannel_in.size() != 0)
{
for (EventChannel ch : _evchannel_in)
{
ch.addEventListener(this);
}
}
if (options.showBestMatch.get())
{
interiorPaint = new Paint();
interiorPaint.setTextSize(textSize);
interiorPaint.setColor(Color.WHITE);
interiorPaint.setStyle(Paint.Style.FILL);
interiorPaint.setAntiAlias(false);
interiorPaint.setAlpha(255);
exteriorPaint = new Paint();
exteriorPaint.setTextSize(textSize);
exteriorPaint.setColor(Color.BLACK);
exteriorPaint.setStyle(Paint.Style.FILL_AND_STROKE);
exteriorPaint.setStrokeWidth(textSize / 8);
exteriorPaint.setAntiAlias(false);
exteriorPaint.setAlpha(255);
}
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
protected final void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
//only draw first frame per call, since drawing multiple frames doesn't make sense without delay
draw(stream_in[0].ptrB(), ((ImageStream)stream_in[0]).format);
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream stream_in[]) throws SSJFatalException
{
surfaceViewInner = null;
iaRgbData = null;
surfaceHolder = null;
if (bitmap != null)
{
bitmap.recycle();
bitmap = null;
}
}
/**
* @param data byte[]
*/
private void draw(final byte[] data, int format)
{
Canvas canvas = null;
if (surfaceHolder == null)
{
return;
}
try
{
synchronized (surfaceHolder)
{
canvas = surfaceHolder.lockCanvas();
if (canvas != null)
{
// Clear canvas.
canvas.drawColor(Color.BLACK);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
// Rotate canvas around the center of the image.
canvas.rotate(options.orientation.get(), canvasWidth >> 1, canvasHeight >> 1);
//decode color format
decodeColor(data, bitmapWidth, bitmapHeight, format);
//fill bitmap with picture
bitmap.setPixels(iaRgbData, 0, bitmapWidth, 0, 0, bitmapWidth, bitmapHeight);
if (options.scale.get())
{
float widthScale = canvasWidth / (float) bitmapWidth;
float heightScale = canvasHeight / (float) bitmapHeight;
float scaleFactor = Math.min(widthScale, heightScale);
int scaledWidth = (int) (scaleFactor * bitmapWidth);
int scaledHeight = (int) (scaleFactor * bitmapHeight);
int left = (int) ((canvasWidth - scaledWidth) / 2.0);
int top = (int) ((canvasHeight - scaledHeight) / 2.0);
Rect dest = new Rect(left, top, left + scaledWidth, top + scaledHeight);
// scale picture to surface size
canvas.drawBitmap(bitmap, null, dest, null);
}
else
{
//center picture on canvas
canvas.drawBitmap(bitmap,
canvasWidth - ((bitmapWidth + canvasWidth) >> 1),
canvasHeight - ((bitmapHeight + canvasHeight) >> 1),
null);
}
if (options.showBestMatch.get() && event_msg != null)
{
// Draw label of the best match.
canvas.rotate(-1 * options.orientation.get(), canvasWidth / 2, canvasHeight / 2);
canvas.drawText(event_msg, 25, 50, exteriorPaint);
canvas.drawText(event_msg, 25, 50, interiorPaint);
}
}
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
//always try to unlock a locked canvas to keep the surface in a consistent state
if (canvas != null)
{
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
/**
* @param data byte[]
*/
private void decodeColor(final byte[] data, int width, int height, int format)
{
//@todo implement missing conversions
switch (format)
{
case ImageFormat.YV12:
{
throw new UnsupportedOperationException("Not implemented, yet");
}
case ImageFormat.YUV_420_888: //YV12_PACKED_SEMI
{
CameraUtil.decodeYV12PackedSemi(iaRgbData, data, width, height);
break;
}
case ImageFormat.NV21:
{
CameraUtil.convertNV21ToARGBInt(iaRgbData, data, width, height);
break;
}
case ImageFormat.FLEX_RGB_888:
{
CameraUtil.convertRGBToARGBInt(iaRgbData, data, width, height);
break;
}
default:
{
Log.e("Wrong color format");
throw new RuntimeException();
}
}
}
@Override
public void notify(Event event)
{
event_msg = event.name + "@" + event.sender + ":" + event.ptrStr();
}
} | 10,994 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CameraChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/CameraChannel.java | /*
* CameraChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Camera provider.<br>
* Created by Frank Gaibler on 21.12.2015.
*/
public class CameraChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the camera provider
*/
public class Options extends OptionList
{
/**
* The rate in which the provider samples data from the camera.<br>
* <b>Attention!</b> The camera sensor will provide new data according to its frame rate and min max preview.
*/
public final Option<Double> sampleRate = new Option<>("sampleRate", 20., Double.class, "sample rate for camera pictures");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private int sampleDimension = 0;
private CameraSensor cameraSensor = null;
/**
*
*/
public CameraChannel()
{
super();
_name = this.getClass().getSimpleName();
}
/**
*
*/
@Override
protected void init() throws SSJException
{
cameraSensor = (CameraSensor) _sensor;
//get sample dimension from camera
cameraSensor.prePrepare();
sampleDimension = cameraSensor.getBufferSize();
//return camera resources immediately
cameraSensor.releaseCamera();
}
/**
* @param stream_out Stream
*/
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (stream_out.num != 1)
{
Log.w("unsupported stream format. sample number = " + stream_out.num);
}
}
/**
* @param stream_out Stream
*/
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
byte[] out = stream_out.ptrB();
cameraSensor.swapBuffer(out, false);
return true;
}
/**
* @return double
*/
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
/**
* @return int
*/
@Override
final public int getSampleDimension()
{
return sampleDimension;
}
/*
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType()
{
return Cons.Type.IMAGE;
}
/**
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[]{"video"};
((ImageStream)_stream_out).width = cameraSensor.getImageWidth();
((ImageStream)_stream_out).height = cameraSensor.getImageHeight();
//((ImageStream)_stream_out).format = cameraSensor.getImageFormat();
}
}
| 4,417 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ImageNormalizer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/ImageNormalizer.java | /*
* ImageNormalizer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Normalizes input image and prepares it for the inference with the
* Inception model.
*
* @author Vitaly
*/
public class ImageNormalizer extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Float> imageMean = new Option<>("imageMean", 127.5f, Float.class, "image mean");
public final Option<Float> imageStd = new Option<>("imageStd", 1f, Float.class, "image standard deviation");
private Options()
{
addOptions();
}
}
private int CHANNELS_PER_PIXEL = 3;
private int width;
private int height;
public final Options options = new Options();
public ImageNormalizer()
{
_name = "ImageNormalizer";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Get image dimensions
width = ((ImageStream) stream_in[0]).width;
height = ((ImageStream) stream_in[0]).height;
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Convert byte array to integer array
int[] rgb = CameraUtil.decodeBytes(stream_in[0].ptrB(), width, height);
// Normalize image values and write result to the output buffer
normalizeImageValues(rgb, stream_out.ptrF());
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
ImageStream stream = ((ImageStream) stream_in[0]);
return stream.width * stream.height * CHANNELS_PER_PIXEL;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[] { "Normalized image float values" };
}
/**
* Prepares image for the classification with the Inception model.
*
* @param rgb Pixel values to normalize.
* @param out Output stream.
*/
private void normalizeImageValues(int[] rgb, float[] out)
{
float imageMean = options.imageMean.get();
float imageStd = options.imageStd.get();
for (int i = 0; i < rgb.length; ++i)
{
final int val = rgb[i];
out[i * 3] = (((val >> 16) & 0xFF) - imageMean) / imageStd;
out[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd;
out[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd;
}
}
}
| 4,113 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ImageResizer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/ImageResizer.java | /*
* ImageResizer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Transformer that re-sizes image to necessary dimensions.
* @author Vitaly
*/
public class ImageResizer extends Transformer
{
public static final int IMAGE_CHANNELS = 3;
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> size = new Option<>("size", 0, Integer.class, "size of the image after resizing");
public final Option<Integer> rotation = new Option<>("rotation", 90, Integer.class, "rotation of the resulting image");
public final Option<Boolean> maintainAspect = new Option<>("maintainAspect", true, Boolean.class, "maintain aspect ration");
public final Option<Boolean> savePreview = new Option<>("savePreview", false, Boolean.class, "save preview image");
public final Option<Boolean> cropImage = new Option<>("cropImage", false, Boolean.class, "crop image instead of resizing");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private int width;
private int height;
private int size;
private int[] intValues;
private Bitmap rgbBitmap;
private Bitmap finalBitmap;
private Canvas canvas;
private Matrix frameToCropTransform;
public ImageResizer()
{
_name = "ImageResizer";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Get image dimensions
width = ((ImageStream) stream_in[0]).width;
height = ((ImageStream) stream_in[0]).height;
// Create bitmap for the original image
rgbBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
size = options.size.get();
// Size of the final image can't be larger than that of the original.
if (size <= 0 || size >= width || size >= height)
{
Log.e("Invalid crop size. Crop size must be smaller than width and height.");
return;
}
intValues = new int[size * size];
// Create bitmap for the cropped image
finalBitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
// Transform image to be of a quadratic form as Inception model only
// accepts images with the same width and height
frameToCropTransform = CameraUtil.getTransformationMatrix(
width, height, size, size,
options.rotation.get(), options.maintainAspect.get());
Matrix cropToFrameTransform = new Matrix();
frameToCropTransform.invert(cropToFrameTransform);
canvas = new Canvas(finalBitmap);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (size <= 0 || size >= width || size >= height)
{
Log.e("Invalid crop size. Crop size must be smaller than width and height.");
return;
}
// Convert byte array to integer array
int[] rgb = CameraUtil.decodeBytes(stream_in[0].ptrB(), width, height);
Bitmap bitmap;
if (options.cropImage.get())
{
bitmap = cropImage(rgb);
}
else
{
bitmap = resizeImage(rgb);
}
if (options.savePreview.get())
{
CameraUtil.saveBitmap(bitmap);
}
//bitmapToByteArray(bitmap, stream_out.ptrB());
CameraUtil.convertBitmapToByteArray(bitmap, intValues, stream_out.ptrB());
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
// return stream_in[0].dim;
int size = options.size.get();
return size * size * IMAGE_CHANNELS;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.IMAGE;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[] { "Cropped video" };
int cropSize = options.size.get();
((ImageStream) stream_out).width = cropSize;
((ImageStream) stream_out).height = cropSize;
((ImageStream) stream_out).format = Cons.ImageFormat.FLEX_RGB_888.val; // Android ImageFormat.FLEX_RGB_888;
}
/**
* Converts bitmap to corresponding byte array and writes it
* to the output buffer.
*
* @deprecated Use CameraUtil.convertBitmapToByteArray() instead
*
* @param bitmap Bitmap to convert to byte array.
* @param out Output buffer.
*/
private void bitmapToByteArray(Bitmap bitmap, byte[] out)
{
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int i = 0; i < bitmap.getWidth() * bitmap.getHeight(); ++i)
{
final int pixel = intValues[i];
out[i * 3] = (byte)((pixel >> 16) & 0xFF);
out[i * 3 + 1] = (byte)((pixel >> 8) & 0xFF);
out[i * 3 + 2] = (byte)(pixel & 0xFF);
}
}
/**
* Forces an image to be of the same width and height.
*
* @param rgb RGB integer values.
* @return Cropped image.
*/
public Bitmap resizeImage(int[] rgb)
{
rgbBitmap.setPixels(rgb, 0, width, 0, 0, width, height);
// Resize bitmap to a quadratic form
canvas.drawBitmap(rgbBitmap, frameToCropTransform, null);
return finalBitmap;
}
/**
* Crops out the center of the given image.
*
* @param rgb RGB pixel values of an image.
* @return Cropped bitmap.
*/
public Bitmap cropImage(int[] rgb)
{
// Size of the final image can't be larger than that of the original.
if (size >= width || size >= height)
{
Log.e("Invalid crop size. Crop size must be smaller than width and height.");
return null;
}
// Calculate matrix offsets
int heightMargin = (height - size) / 2;
int widthMargin = (width - size) / 2;
// Cut out the center of the original image.
for (int y = heightMargin, cy = 0; y < height - heightMargin; y++, cy++)
{
for (int x = widthMargin, cx = 0; x < width - widthMargin; x++, cx++)
{
// Copy pixels from the original pixel matrix to the cropped one
intValues[cy * size + cx] = rgb[y * width + x];
}
}
int[] cropped = new int[size * size];
// Rotate the final image 90 degrees.
for (int x = size - 1, destX = 0; x > 0; x--, destX++)
{
for (int y = 0; y < size; y++)
{
cropped[size * y + x] = intValues[size * destX + y];
}
}
// Set pixel values of the cropped image
finalBitmap.setPixels(cropped, 0, size, 0, 0, size, size);
return finalBitmap;
}
}
| 7,962 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CameraUtil.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/CameraUtil.java | /*
* CameraUtil.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import hcm.ssj.core.Log;
import hcm.ssj.file.FileCons;
/**
* Utility class for the camera. <br>
* Created by Frank Gaibler on 26.01.2016.
*/
@SuppressWarnings("deprecation")
public class CameraUtil
{
/**
* Returns the first codec capable of encoding the specified MIME type, or null if no
* match was found.
*
* @param mimeType String
* @return MediaCodecInfo
*/
public static MediaCodecInfo selectCodec(String mimeType)
{
int numCodecs = MediaCodecList.getCodecCount();
for (int i = 0; i < numCodecs; i++)
{
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (!codecInfo.isEncoder())
{
continue;
}
String[] types = codecInfo.getSupportedTypes();
for (String type : types)
{
if (type.equalsIgnoreCase(mimeType))
{
return codecInfo;
}
}
}
return null;
}
/**
* Returns a color format that is supported by the codec and by this code. If no
* match is found, an exception is thrown.
*
* @param codecInfo MediaCodecInfo
* @param mimeType String
* @return int
*/
public static int selectColorFormat(MediaCodecInfo codecInfo, String mimeType)
{
MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
for (int i = 0; i < capabilities.colorFormats.length; i++)
{
int colorFormat = capabilities.colorFormats[i];
if (isRecognizedFormat(colorFormat))
{
return colorFormat;
}
}
Log.e("couldn't find a good color format for " + codecInfo.getName() + " / " + mimeType);
return 0; // not reached
}
/**
* Returns true if this is a common color format.
*
* @param colorFormat int
* @return boolean
*/
private static boolean isRecognizedFormat(int colorFormat)
{
switch (colorFormat)
{
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYCrYCb:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
return true;
default:
return false;
}
}
/**
* Decodes YUVNV21 color space into a regular RGB format.
*
* @param rgb Output array for RGB values.
* @param yuv YUV byte data to decode.
* @param width Width of image in pixels.
* @param height Height of image in pixels.
*/
public static void convertNV21ToRGB_slow(byte[] rgb, byte[] yuv, int width, int height) {
final int frameSize = width * height;
final int ii = 0;
final int ij = 0;
final int di = +1;
final int dj = +1;
int a = 0;
for (int i = 0, ci = ii; i < height; ++i, ci += di) {
for (int j = 0, cj = ij; j < width; ++j, cj += dj) {
int y = (0xff & ((int) yuv[ci * width + cj]));
int v = (0xff & ((int) yuv[frameSize + (ci >> 1) * width + (cj & ~1) + 0]));
int u = (0xff & ((int) yuv[frameSize + (ci >> 1) * width + (cj & ~1) + 1]));
y = y < 16 ? 16 : y;
int r = (int) (1.164f * (y - 16) + 1.596f * (v - 128));
int g = (int) (1.164f * (y - 16) - 0.813f * (v - 128) - 0.391f * (u - 128));
int b = (int) (1.164f * (y - 16) + 2.018f * (u - 128));
rgb[a++] = (byte)(r < 0 ? 0 : (r > 255 ? 255 : r)); // red
rgb[a++] = (byte)(g < 0 ? 0 : (g > 255 ? 255 : g)); // green
rgb[a++] = (byte)(b < 0 ? 0 : (b > 255 ? 255 : b)); // blue
}
}
}
public static void convertNV21ToARGBInt_slow(int[] argb, byte[] yuv, int width, int height)
{
final int frameSize = width * height;
final int ii = 0;
final int ij = 0;
final int di = +1;
final int dj = +1;
int a = 0;
for (int i = 0, ci = ii; i < height; ++i, ci += di) {
for (int j = 0, cj = ij; j < width; ++j, cj += dj) {
int y = (0xff & ((int) yuv[ci * width + cj]));
int v = (0xff & ((int) yuv[frameSize + (ci >> 1) * width + (cj & ~1) + 0]));
int u = (0xff & ((int) yuv[frameSize + (ci >> 1) * width + (cj & ~1) + 1]));
y = y < 16 ? 16 : y;
int r = (int) (1.164f * (y - 16) + 1.596f * (v - 128));
int g = (int) (1.164f * (y - 16) - 0.813f * (v - 128) - 0.391f * (u - 128));
int b = (int) (1.164f * (y - 16) + 2.018f * (u - 128));
r = r < 0 ? 0 : (r > 255 ? 255 : r);
g = g < 0 ? 0 : (g > 255 ? 255 : g);
b = b < 0 ? 0 : (b > 255 ? 255 : b);
argb[a++] = 0xff000000 | (r << 16) | (g << 8) | b;
}
}
}
/**
* Decodes YUVNV21 color space into a regular RGB format.
*
* @param rgb Output array for RGB values.
* @param yuv YUV byte data to decode.
* @param width Width of image in pixels.
* @param height Height of image in pixels.
*/
public static void convertNV21ToRGB(byte[] rgb, byte[] yuv, int width, int height)
{
convertNV21ToRGB(rgb, yuv, width, height, true);
}
/**
* Decodes YUVNV21 color space into a regular RGB format.
*
* @param out Output array for RGB values.
* @param yuv YUV byte data to decode.
* @param width Width of image in pixels.
* @param height Height of image in pixels.
* @param swap swap U with V (default = true)
*/
public static void convertNV21ToRGB(byte[] out, byte[] yuv, int width, int height, boolean swap)
{
int sz = width * height;
int i, j;
int Y, Cr = 0, Cb = 0;
int outPtr = 0;
for (j = 0; j < height; j++)
{
int pixPtr = j * width;
final int jDiv2 = j >> 1;
for (i = 0; i < width; i++)
{
Y = yuv[pixPtr];
if (Y < 0)
Y += 255;
if ((i & 0x1) != 1)
{
final int cOff = sz + jDiv2 * width + (i >> 1) * 2;
Cb = yuv[cOff + (swap ? 0 : 1)];
if (Cb < 0)
{
Cb += 127;
} else
{
Cb -= 128;
}
Cr = yuv[cOff + (swap ? 1 : 0)];
if (Cr < 0)
{
Cr += 127;
} else
{
Cr -= 128;
}
}
int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5);
if (R < 0)
{
R = 0;
} else if (R > 255)
{
R = 255;
}
int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5);
if (G < 0)
{
G = 0;
} else if (G > 255)
{
G = 255;
}
int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6);
if (B < 0)
{
B = 0;
} else if (B > 255)
{
B = 255;
}
pixPtr++;
out[outPtr++] = (byte)R;
out[outPtr++] = (byte)G;
out[outPtr++] = (byte)B;
}
}
}
/**
* Decodes YUVNV21 color space into a regular RGB format.
*
* @param argb Output array for RGB values.
* @param yuv YUV byte data to decode.
* @param width Width of image in pixels.
* @param height Height of image in pixels.
*/
public static void convertNV21ToARGBInt(int[] argb, byte[] yuv, int width, int height)
{
convertNV21ToARGBInt(argb, yuv, width, height, true);
}
/**
* Decodes YUVNV21 color space into a regular RGB format.
*
* @param out Output array for RGB values.
* @param yuv YUV byte data to decode.
* @param width Width of image in pixels.
* @param height Height of image in pixels.
* @param swap swap U with V (default = true)
*/
public static void convertNV21ToARGBInt(int[] out, byte[] yuv, int width, int height, boolean swap)
{
int sz = width * height;
int i, j;
int Y, Cr = 0, Cb = 0;
for (j = 0; j < height; j++)
{
int pixPtr = j * width;
final int jDiv2 = j >> 1;
for (i = 0; i < width; i++)
{
Y = yuv[pixPtr];
if (Y < 0)
Y += 255;
if ((i & 0x1) != 1)
{
final int cOff = sz + jDiv2 * width + (i >> 1) * 2;
Cb = yuv[cOff + (swap ? 0 : 1)];
if (Cb < 0)
{
Cb += 127;
} else
{
Cb -= 128;
}
Cr = yuv[cOff + (swap ? 1 : 0)];
if (Cr < 0)
{
Cr += 127;
} else
{
Cr -= 128;
}
}
int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5);
if (R < 0)
{
R = 0;
} else if (R > 255)
{
R = 255;
}
int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5);
if (G < 0)
{
G = 0;
} else if (G > 255)
{
G = 255;
}
int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6);
if (B < 0)
{
B = 0;
} else if (B > 255)
{
B = 255;
}
out[pixPtr++] = 0xff000000 + (B << 16) + (G << 8) + R;
}
}
}
/**
* Saved bitmap to external storage.
*
* @param bitmap Bitmap to save.
*/
public static void saveBitmap(final Bitmap bitmap) {
final String root =
FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "previews";
final File myDir = new File(root);
if (!myDir.mkdirs()) {
Log.i("Make dir failed");
}
final String fname = new Date().toString().replaceAll(" ", "_").replaceAll(":", "_") + ".png";
final File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
final FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 99, out);
out.flush();
out.close();
} catch (final Exception e) {
Log.e("tf_ssj", "Exception!");
}
}
/**
* Returns a transformation matrix from one reference frame into another.
* Handles cropping (if maintaining aspect ratio is desired) and rotation.
*
* @param srcWidth Width of source frame.
* @param srcHeight Height of source frame.
* @param dstWidth Width of destination frame.
* @param dstHeight Height of destination frame.
* @param applyRotation Amount of rotation to apply from one frame to another.
* Must be a multiple of 90.
* @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant,
* cropping the image if necessary.
* @return The transformation fulfilling the desired requirements.
*/
public static Matrix getTransformationMatrix(
final int srcWidth,
final int srcHeight,
final int dstWidth,
final int dstHeight,
final int applyRotation,
final boolean maintainAspectRatio) {
final Matrix matrix = new Matrix();
if (applyRotation != 0) {
// Translate so center of image is at origin.
matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);
// Rotate around origin.
matrix.postRotate(applyRotation);
}
// Account for the already applied rotation, if any, and then determine how
// much scaling is needed for each axis.
final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;
final int inWidth = transpose ? srcHeight : srcWidth;
final int inHeight = transpose ? srcWidth : srcHeight;
// Apply scaling if necessary.
if (inWidth != dstWidth || inHeight != dstHeight) {
final float scaleFactorX = dstWidth / (float) inWidth;
final float scaleFactorY = dstHeight / (float) inHeight;
if (maintainAspectRatio) {
// Scale by minimum factor so that dst is filled completely while
// maintaining the aspect ratio. Some image may fall off the edge.
final float scaleFactor = Math.max(scaleFactorX, scaleFactorY);
matrix.postScale(scaleFactor, scaleFactor);
} else {
// Scale exactly to fill dst from src.
matrix.postScale(scaleFactorX, scaleFactorY);
}
}
if (applyRotation != 0) {
// Translate back from origin centered reference to destination frame.
matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f);
}
return matrix;
}
/**
* Converts RGB bytes to RGB ints.
*
* @param rgbBytes RGB color bytes.
* @param width width
* @param height height
* @return RGB color integers.
*/
public static int[] decodeBytes(byte[] rgbBytes, int width, int height)
{
int[] rgb = new int[width * height];
for (int i = 0; i < width * height; i++)
{
int r = rgbBytes[i * 3];
int g = rgbBytes[i * 3 + 1];
int b = rgbBytes[i * 3 + 2];
if (r < 0)
r += 256;
if (g < 0)
g += 256;
if (b < 0)
b += 256;
rgb[i] = 0xff000000 | (r << 16) | (g << 8) | b;
}
return rgb;
}
/**
* Converts bitmap to corresponding byte array and writes it
* to the output buffer.
*
* @param bitmap Bitmap to convert to byte array.
* @param intOutput Integer output buffer
* @param byteOutput Byte output buffer.
*/
public static void convertBitmapToByteArray(Bitmap bitmap, int[] intOutput, byte[] byteOutput)
{
bitmap.getPixels(intOutput, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int i = 0; i < bitmap.getWidth() * bitmap.getHeight(); ++i)
{
final int pixel = intOutput[i];
byteOutput[i * 3] = (byte)((pixel >> 16) & 0xFF);
byteOutput[i * 3 + 1] = (byte)((pixel >> 8) & 0xFF);
byteOutput[i * 3 + 2] = (byte)(pixel & 0xFF);
}
}
public static void convertRGBToARGBInt(int[] argb, byte[] rgb, int width, int height)
{
int cnt_out = 0;
int cnt_in = 0;
int r,g,b;
for(int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
r = rgb[cnt_in++];
g = rgb[cnt_in++];
b = rgb[cnt_in++];
if (r < 0) r += 256;
if (g < 0) g += 256;
if (b < 0) b += 256;
argb[cnt_out++] = 0xff000000 | (r << 16) | (g << 8) | b;
}
}
}
/**
* Decodes YUV frame to a RGB buffer
*
* @param rgba int[]
* @param yuv420sp byte[]
* @param width width
* @param height height
*/
public static void decodeYV12PackedSemi(int[] rgba, byte[] yuv420sp, int width, int height)
{
//@todo untested
final int frameSize = width * height;
int r, g, b, y1192, y, i, uvp, u, v;
for (int j = 0, yp = 0; j < height; j++)
{
uvp = frameSize + (j >> 1) * width;
u = 0;
v = 0;
for (i = 0; i < width; i++, yp++)
{
y = (0xff & ((int) yuv420sp[yp])) - 16;
if (y < 0)
y = 0;
if ((i & 1) == 0)
{
v = (0xff & yuv420sp[uvp++]) - 128;
u = (0xff & yuv420sp[uvp++]) - 128;
}
y1192 = 1192 * y;
r = (y1192 + 1634 * v);
g = (y1192 - 833 * v - 400 * u);
b = (y1192 + 2066 * u);
//
r = Math.max(0, Math.min(r, 262143));
g = Math.max(0, Math.min(g, 262143));
b = Math.max(0, Math.min(b, 262143));
// rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) &
// 0xff00) | ((b >> 10) & 0xff);
// rgba, divide 2^10 ( >> 10)
rgba[yp] = ((r << 14) & 0xff000000) | ((g << 6) & 0xff0000)
| ((b >> 2) | 0xff00);
}
}
}
}
| 19,629 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ImageRotator.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/ImageRotator.java | /*
* ImageRotator.java
* Copyright (c) 2022
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 05.12.2022.
*/
public class ImageRotator extends Transformer
{
public class Options extends OptionList
{
public final Option<Integer> rotation = new Option<>("rotation", 270, Integer.class, "rotation of the resulting image, use 270 for front camera and 90 for back camera");
public final Option<Integer> outputWidth = new Option<>("outputWidth", 480, Integer.class, "output width of the rotated image");
public final Option<Integer> outputHeight = new Option<>("outputHeight", 640, Integer.class, "output height of the rotated image");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
// Original sizes
int inputWidth;
int inputHeight;
Matrix rotationMatrix;
int[] originalInputArray;
int[] outputArray;
// Create bitmap for the original image
Bitmap inputBitmap;
// Rotated bitmap for original image
Bitmap rotatedBitmap;
// Cropped bitmap to output sizes
Bitmap outputBitmap;
@Override
public OptionList getOptions()
{
return options;
}
public ImageRotator()
{
_name = this.getClass().getSimpleName();
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Get image dimensions
inputWidth = ((ImageStream) stream_in[0]).width;
inputHeight = ((ImageStream) stream_in[0]).height;
outputArray = new int[options.outputWidth.get() * options.outputHeight.get()];
// Create bitmap for the original image
inputBitmap = Bitmap.createBitmap(inputWidth, inputHeight, Bitmap.Config.ARGB_8888);
rotationMatrix = new Matrix();
rotationMatrix.postRotate(options.rotation.get());
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Convert byte array to integer array
originalInputArray = CameraUtil.decodeBytes(stream_in[0].ptrB(), inputWidth, inputHeight);
// Create bitmap from byte array
inputBitmap.setPixels(originalInputArray, 0, inputWidth, 0, 0, inputWidth, inputHeight);
// Rotate original input
rotatedBitmap = Bitmap.createBitmap(inputBitmap, 0, 0, inputBitmap.getWidth(), inputBitmap.getHeight(), rotationMatrix, true);
// Resize rotated original input to model input size
outputBitmap = Bitmap.createScaledBitmap(rotatedBitmap, options.outputWidth.get(), options.outputHeight.get(), true);
// Convert bitmap to byte stream
CameraUtil.convertBitmapToByteArray(outputBitmap, outputArray, stream_out.ptrB());
// Free bitmap memory
rotatedBitmap.recycle();
outputBitmap.recycle();
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
// width * height * channels
return options.outputWidth.get() * options.outputHeight.get() * 3;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.IMAGE;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = stream_in[0].desc;
((ImageStream) stream_out).width = options.outputWidth.get();
((ImageStream) stream_out).height = options.outputHeight.get();
((ImageStream) stream_out).format = Cons.ImageFormat.FLEX_RGB_888.val; // Android ImageFormat.FLEX_RGB_888;
}
}
| 5,064 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ImageLoaderSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/ImageLoaderSensor.java | /*
* StaticImageLoader.java
* Copyright (c) 2019
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.FolderPath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.file.FileCons;
/**
* Created by Michael Dietz on 13.11.2019.
*/
public class ImageLoaderSensor extends Sensor
{
public class Options extends OptionList
{
public final Option<FolderPath> filePath = new Option<>("path", new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "[time]"), FolderPath.class, "folder containing image file");
public final Option<String> fileName = new Option<>("fileName", "image.jpg", String.class, "image name");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
@Override
public OptionList getOptions()
{
return options;
}
protected Bitmap image;
public ImageLoaderSensor()
{
_name = this.getClass().getSimpleName();
}
@Override
protected boolean connect() throws SSJFatalException
{
loadImage();
return true;
}
protected void loadImage() throws SSJFatalException
{
File imagePath = new File(options.filePath.parseWildcards(), options.fileName.get());
if (imagePath.exists())
{
image = BitmapFactory.decodeFile(imagePath.getAbsolutePath());
}
else
{
throw new SSJFatalException("Image " + imagePath.getAbsolutePath() + " does not exist!");
}
}
protected int getImageWidth()
{
int result = -1;
if (image != null)
{
result = image.getWidth();
}
return result;
}
protected int getImageHeight()
{
int result = -1;
if (image != null)
{
result = image.getHeight();
}
return result;
}
@Override
protected void disconnect() throws SSJFatalException
{
if (image != null)
{
image.recycle();
image = null;
}
}
}
| 3,269 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CameraWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/CameraWriter.java | /*
* CameraWriter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.annotation.TargetApi;
import android.graphics.ImageFormat;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Build;
import java.io.IOException;
import java.nio.ByteBuffer;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.Mp4Writer;
/**
* Camera writer for SSJ to create mp4-video-files.<br>
* Created by Frank Gaibler on 21.01.2016.
*/
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class CameraWriter extends Mp4Writer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the camera writer
*/
public class Options extends Mp4Writer.Options
{
public final Option<Integer> width = new Option<>("width", 640, Integer.class, "should be the same as in camera");
//arbitrary but popular values
public final Option<Integer> height = new Option<>("height", 480, Integer.class, "should be the same as in camera");
public final Option<String> mimeType = new Option<>("mimeType", "video/avc", String.class, "H.264 Advanced Video Coding");
public final Option<Integer> iFrameInterval = new Option<>("iFrameInterval", 15, Integer.class, "Interval between complete frames");
public final Option<Integer> bitRate = new Option<>("bitRate", 100000, Integer.class, "Mbps");
public final Option<Integer> orientation = new Option<>("orientation", 270, Integer.class, "0, 90, 180, 270 (portrait: 90 back, 270 front)");
public final Option<Integer> colorFormat = new Option<>("colorFormat", 0, Integer.class, "MediaCodecInfo.CodecCapabilities");
public final Option<ColorSwitch> colorSwitch = new Option<>("colorSwitch", ColorSwitch.DEFAULT, ColorSwitch.class, "");
/**
*
*/
private Options()
{
super();
addOptions();
}
}
/**
* Switches color before encoding happens
*/
public enum ColorSwitch
{
DEFAULT,
YV12_PLANAR, //MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar
YV12_PACKED_SEMI, //MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar
NV21_UV_SWAPPED
}
public final Options options = new Options();
//
byte[] aByColorChange;
private int planeSize;
private int planeSizeCx;
private ColorSwitch colorSwitch;
/**
*
*/
public CameraWriter()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length != 1)
{
throw new SSJFatalException("Stream count not supported");
}
if(stream_in[0].type != Cons.Type.IMAGE || ((ImageStream)stream_in[0]).format != ImageFormat.NV21)
{
throw new SSJFatalException("invalid input, writer only supports NV21 images");
}
dFrameRate = stream_in[0].sr;
initFiles(stream_in[0], options);
try
{
prepareEncoder(options.width.get(), options.height.get(), options.bitRate.get());
}
catch (IOException e)
{
throw new SSJFatalException("error preparing encoder", e);
}
bufferInfo = new MediaCodec.BufferInfo();
int reqBuffSize = stream_in[0].dim;
aByShuffle = new byte[reqBuffSize];
lFrameIndex = 0;
colorSwitch = options.colorSwitch.get();
switch (colorSwitch)
{
case YV12_PACKED_SEMI:
{
planeSize = options.width.get() * options.height.get();
planeSizeCx = planeSize >> 2;
aByColorChange = new byte[planeSizeCx * 2];
break;
}
case NV21_UV_SWAPPED:
{
planeSize = options.width.get() * options.height.get();
planeSizeCx = planeSize >> 1;
aByColorChange = new byte[planeSizeCx];
break;
}
}
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
protected final void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
byte[] in = stream_in[0].ptrB();
for (int i = 0; i < in.length; i += aByShuffle.length)
{
System.arraycopy(in, i, aByShuffle, 0, aByShuffle.length);
try
{
encode(aByShuffle);
}
catch (IOException e)
{
throw new SSJFatalException("exception during encoding", e);
}
save(false);
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream stream_in[]) throws SSJFatalException
{
super.flush(stream_in);
aByColorChange = null;
}
/**
* Configures the encoder
*/
private void prepareEncoder(int width, int height, int bitRate) throws IOException
{
MediaCodecInfo mediaCodecInfo = CameraUtil.selectCodec(options.mimeType.get());
if (mediaCodecInfo == null)
{
throw new IOException("Unable to find an appropriate codec for " + options.mimeType.get());
}
//set format properties
MediaFormat videoFormat = MediaFormat.createVideoFormat(options.mimeType.get(), width, height);
videoFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, options.colorFormat.get() <= 0
? CameraUtil.selectColorFormat(mediaCodecInfo, options.mimeType.get()) : options.colorFormat.get());
videoFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
videoFormat.setFloat(MediaFormat.KEY_FRAME_RATE, (float) dFrameRate);
videoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, options.iFrameInterval.get());
//prepare encoder
super.prepareEncoder(videoFormat, options.mimeType.get(), file.getPath());
//set video orientation
if (options.orientation.get() % 90 == 0 || options.orientation.get() % 90 == 90)
{
mediaMuxer.setOrientationHint(options.orientation.get());
} else
{
Log.w("Orientation is not valid: " + options.orientation.get());
}
}
/**
* @param inputBuf ByteBuffer
* @param frameData byte[]
*/
protected final void fillBuffer(ByteBuffer inputBuf, byte[] frameData) throws IOException
{
if (colorSwitch == ColorSwitch.DEFAULT)
{
inputBuf.put(frameData);
} else
{
//switch colors
int quarterPlane = frameData.length / 6; //quarterPlane = width * height / 4
inputBuf.put(frameData, 0, quarterPlane * 4);
switch (colorSwitch)
{
case YV12_PLANAR:
{
//swap YV12 to YUV420Planes
inputBuf.put(frameData, quarterPlane * 5, quarterPlane);
inputBuf.put(frameData, quarterPlane * 4, quarterPlane);
break;
}
case YV12_PACKED_SEMI:
{
//swap YV12 to YUV420PackedSemiPlanar
inputBuf.put(swapRestYV12toYUV420PackedSemiPlanar(frameData), 0, quarterPlane + quarterPlane);
break;
}
case NV21_UV_SWAPPED:
{
//swap NV21 U and V
inputBuf.put(swapNV21_UV(frameData), 0, quarterPlane + quarterPlane);
break;
}
default:
{
throw new IOException("Wrong color switch");
}
}
}
}
/**
* @param YV12 byte[]
* @return byte[]
*/
private byte[] swapRestYV12toYUV420PackedSemiPlanar(byte[] YV12)
{
for (int i = 0; i < planeSizeCx; i++)
{
aByColorChange[i * 2] = YV12[planeSize + i + planeSizeCx];
aByColorChange[i * 2 + 1] = YV12[planeSize + i];
}
return aByColorChange;
}
/**
* Swaps UVUV to VUVU and vice versa
*
* @param NV21 byte[]
* @return byte[]
*/
private byte[] swapNV21_UV(byte[] NV21)
{
for (int i = 0; i < planeSizeCx; i += 2)
{
aByColorChange[i] = NV21[planeSize + i + 1];
aByColorChange[i + 1] = NV21[planeSize + i];
}
return aByColorChange;
}
}
| 10,291 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CameraSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/CameraSensor.java | /*
* CameraSensor.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Build;
import java.io.IOException;
import java.util.List;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Camera sensor.<br>
* <b>Hint:</b> Heap size problems can be addressed by setting <code>android:largeHeap="true"</code> in the manifest.<br>
* Created by Frank Gaibler on 21.12.2015.
*/
@SuppressWarnings("deprecation")
public class CameraSensor extends hcm.ssj.core.Sensor implements Camera.PreviewCallback
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the camera
*/
public class Options extends OptionList
{
public final Option<Cons.CameraType> cameraType = new Option<>("cameraType", Cons.CameraType.BACK_CAMERA, Cons.CameraType.class, "which camera to use (front or back)");
//arbitrary but popular values
public final Option<Integer> width = new Option<>("width", 640, Integer.class, "width in pixel");
public final Option<Integer> height = new Option<>("height", 480, Integer.class, "height in pixel");
public final Option<Integer> previewFpsRangeMin = new Option<>("previewFpsRangeMin", 30 * 1000, Integer.class, "min preview rate for camera");
public final Option<Integer> previewFpsRangeMax = new Option<>("previewFpsRangeMax", 30 * 1000, Integer.class, "max preview rate for camera");
public final Option<Cons.ImageFormat> imageFormat = new Option<>("imageFormat", Cons.ImageFormat.NV21, Cons.ImageFormat.class, "image format for camera");
public final Option<Boolean> showSupportedValues = new Option<>("showSupportedValues", false, Boolean.class, "show supported values in log");
/**
*
*/
private Options()
{
addOptions();
}
}
//options
public final Options options = new Options();
//camera
private Camera camera;
//surface
private SurfaceTexture surfaceTexture = null;
//camera supported values
private int iRealWidth = 0;
private int iRealHeight = 0;
//buffer to exchange data
private byte[] byaSwapBuffer = null;
/**
*
*/
public CameraSensor()
{
_name = this.getClass().getSimpleName();
}
/**
* @return int
*/
protected final int getBufferSize()
{
int reqBuffSize = iRealWidth * iRealHeight;
reqBuffSize += reqBuffSize >> 1;
return reqBuffSize;
}
/**
* Exchanges data between byte arrays
*
* @param bytes byte[]
* @param write boolean
*/
public final synchronized void swapBuffer(byte[] bytes, boolean write)
{
if (write)
{
//write into buffer
if (byaSwapBuffer.length < bytes.length)
{
Log.e("Buffer write changed from " + byaSwapBuffer.length + " to " + bytes.length);
byaSwapBuffer = new byte[bytes.length];
}
System.arraycopy(bytes, 0, byaSwapBuffer, 0, bytes.length);
} else
{
//get data from buffer
if (bytes.length < byaSwapBuffer.length)
{
Log.e("Buffer read changed from " + bytes.length + " to " + byaSwapBuffer.length);
bytes = new byte[byaSwapBuffer.length];
}
System.arraycopy(byaSwapBuffer, 0, bytes, 0, byaSwapBuffer.length);
}
}
/**
* Configures camera for video capture. <br>
* Opens a camera and sets parameters. Does not start preview.
*/
private void prepareCamera() throws SSJException
{
//set camera and frame size
Camera.Parameters parameters = prePrepare();
if (options.showSupportedValues.get())
{
//list sizes
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Log.i("Preview size: (n=" + sizes.size() + ")");
for (Camera.Size size : sizes)
{
Log.i("Preview size: " + size.width + "x" + size.height);
}
//list preview formats
List<Integer> formats = parameters.getSupportedPreviewFormats();
Log.i("Preview format (n=" + formats.size() + ")");
for (Integer i : formats)
{
Log.i("Preview format: " + i);
}
}
//set preview format
parameters.setPreviewFormat(options.imageFormat.get().val);
//set preview fps range
choosePreviewFpsRange(parameters, options.previewFpsRangeMin.get(), options.previewFpsRangeMax.get());
//optimizations for more fps
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
parameters.setRecordingHint(true);
}
List<String> FocusModes = parameters.getSupportedFocusModes();
if (FocusModes != null && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
{
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
//set camera parameters
camera.setParameters(parameters);
//display used parameters
Camera.Size size = parameters.getPreviewSize();
Log.d("Camera preview size is " + size.width + "x" + size.height);
int[] range = new int[2];
parameters.getPreviewFpsRange(range);
Log.d("Preview fps range is " + (range[0] / 1000) + " to " + (range[1] / 1000));
}
/**
* Sets camera height and width.<br>
* Will select different parameters, if the ones in options aren't supported.
*
* @return Camera.Parameters
* @throws SSJException exception
*/
protected final Camera.Parameters prePrepare() throws SSJException
{
if (camera != null)
{
throw new SSJException("Camera already initialized");
}
//set camera
chooseCamera();
//
Camera.Parameters parameters = camera.getParameters();
//set preview size
choosePreviewSize(parameters, options.width.get(), options.height.get());
return parameters;
}
/**
* Tries to access the requested camera.<br>
* Will select a different one if the requested one is not supported.
*/
private void chooseCamera() throws SSJException
{
Camera.CameraInfo info = new Camera.CameraInfo();
//search for specified camera
int numCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numCameras; i++)
{
Camera.getCameraInfo(i, info);
if (info.facing == options.cameraType.get().val)
{
camera = Camera.open(i);
break;
}
}
if (camera == null)
{
Log.d("No front-facing camera found; opening default");
camera = Camera.open(); //opens first back-facing camera
}
if (camera == null)
{
throw new SSJException("Unable to open camera");
}
}
/**
* Attempts to find a preview size that matches the provided width and height (which
* specify the dimensions of the encoded video). If it fails to find a match it just
* uses the default preview size.
*/
private void choosePreviewSize(Camera.Parameters parameters, int width, int height)
{
//search for requested size
for (Camera.Size size : parameters.getSupportedPreviewSizes())
{
if (size.width == width && size.height == height)
{
parameters.setPreviewSize(width, height);
iRealWidth = width;
iRealHeight = height;
return;
}
}
Log.w("Unable to set preview size to " + width + "x" + height);
//set to preferred size
Camera.Size ppsfv = parameters.getPreferredPreviewSizeForVideo();
if (ppsfv != null)
{
parameters.setPreviewSize(ppsfv.width, ppsfv.height);
iRealWidth = ppsfv.width;
iRealHeight = ppsfv.height;
}
}
/**
* Attempts to find a preview range that matches the provided min and max.
* If it fails to find a match it uses the closest match or the default preview range.
*/
private void choosePreviewFpsRange(Camera.Parameters parameters, int min, int max)
{
//adjust wrong preview range
if (min > max)
{
Log.w("Preview range max is too small");
max = min;
}
//preview ranges have to be a multiple of 1000
if (min / 1000 <= 0)
{
min *= 1000;
}
if (max / 1000 <= 0)
{
max *= 1000;
}
//search for requested size
List<int[]> ranges = parameters.getSupportedPreviewFpsRange();
if (options.showSupportedValues.get())
{
Log.i("Preview fps range: (n=" + ranges.size() + ")");
for (int[] range : ranges)
{
Log.i("Preview fps range: " + range[0] + "-" + range[1]);
}
}
for (int[] range : ranges)
{
if (range[0] == min && range[1] == max)
{
parameters.setPreviewFpsRange(range[0], range[1]);
return;
}
}
Log.w("Unable to set preview fps range from " + (min / 1000) + " to " + (max / 1000));
//try to set to minimum
for (int[] range : ranges)
{
if (range[0] == min)
{
parameters.setPreviewFpsRange(range[0], range[1]);
return;
}
}
//leave preview range at default
}
/**
* Stops camera preview, and releases the camera to the system.
*/
protected final void releaseCamera()
{
if (camera != null)
{
camera.stopPreview();
camera.release();
camera = null;
}
}
/**
* Configures surface texture for camera preview
*/
private void prepareSurfaceTexture()
{
surfaceTexture = new SurfaceTexture(10);
try
{
camera.setPreviewTexture(surfaceTexture);
} catch (IOException ex)
{
Log.e("Couldn't prepare surface texture: " + ex.getMessage());
}
}
/**
* Set buffer size according to real width and height
*/
private void initBuffer()
{
try
{
int reqBuffSize = getBufferSize();
camera.addCallbackBuffer(new byte[reqBuffSize]);
camera.setPreviewCallbackWithBuffer(this);
byaSwapBuffer = new byte[reqBuffSize];
} catch (Exception ex)
{
Log.e("Couldn't init buffer: " + ex.getMessage());
}
}
/**
* Write data into buffer and return used resources to camera
*
* @param data byte[]
* @param cam Camera
*/
@Override
public void onPreviewFrame(byte[] data, Camera cam)
{
swapBuffer(data, true);
if (camera != null)
{
camera.addCallbackBuffer(data);
}
}
/**
* Release the surface texture
*/
private void releaseSurfaceTexture()
{
if (surfaceTexture != null)
{
surfaceTexture.release();
surfaceTexture = null;
}
}
/**
*
*/
@Override
protected boolean connect() throws SSJFatalException
{
try
{
prepareCamera();
}
catch (SSJException e)
{
throw new SSJFatalException("error preparing camera", e);
}
prepareSurfaceTexture();
initBuffer();
camera.startPreview();
return true;
}
/**
*
*/
@Override
protected void disconnect() throws SSJFatalException
{
releaseCamera();
releaseSurfaceTexture();
}
public int getImageWidth()
{
return iRealWidth;
}
public int getImageHeight()
{
return iRealHeight;
}
public int getImageFormat()
{
return camera.getParameters().getPreviewFormat();
}
}
| 13,833 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
NV21ToRGBDecoder.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/NV21ToRGBDecoder.java | /*
* NV21ToRGBDecoder.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.graphics.ImageFormat;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Transformer that is responsible for decoding of NV21 raw image data into
* RGB color format.
*
* @author Vitaly
*/
public class NV21ToRGBDecoder extends Transformer
{
private static final int CHANNELS_PER_PIXEL = 3;
private int width;
private int height;
public NV21ToRGBDecoder()
{
_name = "NV21ToRGBDecoder";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Initialize image stream size
ImageStream imgstrm = (ImageStream)stream_in[0];
width = imgstrm.width;
height = imgstrm.height;
if(imgstrm.format != ImageFormat.NV21)
{
Log.e("Unsupported input video format. Expecting NV21.");
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Fetch raw NV21 pixel data
byte[] nv21Data = stream_in[0].ptrB();
// Convert NV21 to RGB and save the pixel data to the output stream
byte out[] = stream_out.ptrB();
CameraUtil.convertNV21ToRGB(out, nv21Data, width, height, false);
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
ImageStream imgstrm = (ImageStream)stream_in[0];
return imgstrm.width * imgstrm.height * CHANNELS_PER_PIXEL; //RGB
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.IMAGE)
Log.e("Input stream type (" +stream_in[0].type.toString()+ ") is unsupported. Expecting " + Cons.Type.IMAGE.toString());
return Cons.Type.IMAGE;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[] { "video" };
((ImageStream) stream_out).width = ((ImageStream) stream_in[0]).width;
((ImageStream) stream_out).height = ((ImageStream) stream_in[0]).height;
((ImageStream) stream_out).format = 0x29; //ImageFormat.FLEX_RGB_888;
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 3,748 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ImageLoaderChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/camera/ImageLoaderChannel.java | /*
* ImageLoaderChannel.java
* Copyright (c) 2019
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.camera;
import android.os.SystemClock;
import java.nio.ByteBuffer;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 13.11.2019.
*/
public class ImageLoaderChannel extends SensorChannel
{
public static final int IMAGE_CHANNELS = 3;
public class Options extends OptionList
{
public final Option<Double> sampleRate = new Option<>("sampleRate", 15., Double.class, "sample rate for loaded image");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
@Override
public OptionList getOptions()
{
return options;
}
private ImageLoaderSensor imageSensor;
private int width = -1;
private int height = -1;
private int sampleDimension = 0;
private ByteBuffer byteBuffer;
byte[] byteArray;
public ImageLoaderChannel()
{
_name = this.getClass().getSimpleName();
}
@Override
protected void init() throws SSJException
{
try
{
imageSensor = (ImageLoaderSensor) _sensor;
imageSensor.loadImage();
width = imageSensor.getImageWidth();
height = imageSensor.getImageHeight();
sampleDimension = width * height * IMAGE_CHANNELS;
}
catch (SSJFatalException e)
{
throw new SSJException(e);
}
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
int size = imageSensor.image.getRowBytes() * imageSensor.image.getHeight();
// Copy image to buffer
byteBuffer = ByteBuffer.allocate(size);
imageSensor.image.copyPixelsToBuffer(byteBuffer);
// Contains rgba values in signed byte form [-127, 127], needs to be converted to [0, 255]
byteArray = byteBuffer.array();
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
byte[] out = stream_out.ptrB();
for (int i = 0; i < width * height; i++)
{
out[i * 3] = byteArray[i * 4];
out[i * 3 + 1] = byteArray[i * 4 + 1];
out[i * 3 + 2] = byteArray[i * 4 + 2];
}
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return sampleDimension;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.IMAGE;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[]{"image"};
((ImageStream)_stream_out).width = width;
((ImageStream)_stream_out).height = height;
((ImageStream) stream_out).format = Cons.ImageFormat.FLEX_RGB_888.val;
}
}
| 4,114 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Consumer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Consumer.java | /*
* Consumer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.os.PowerManager;
import java.util.Arrays;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 05.03.2015.
*/
public abstract class Consumer extends Component {
private Stream[] _stream_in;
private int[] _readPos = null;
private int[] _bufferID_in;
private int[] _num_frame;
private int[] _num_delta;
private EventChannel _triggerChannel = null;
private Timer _timer;
protected Pipeline _frame;
protected boolean _doWakeLock = true;
public Consumer()
{
_frame = Pipeline.getInstance();
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
if(!_isSetup) {
_frame.error(_name, "not initialized", null);
_safeToKill = true;
return;
}
android.os.Process.setThreadPriority(threadPriority);
PowerManager mgr = (PowerManager)SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, _name);
Event ev = null;
int eventID = 0;
//clear data
if(_readPos != null)
Arrays.fill(_readPos, 0);
for(int i = 0; i < _stream_in.length; i++)
_stream_in[i].reset();
try {
enter(_stream_in);
} catch(SSJFatalException e) {
_frame.error(_name, "exception in enter", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(_name, "exception in enter", e);
}
//wait for framework
while (!_terminate && !_frame.isRunning()) {
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
//maintain update rate starting from now
if(_triggerChannel == null)
_timer.reset();
while(!_terminate && _frame.isRunning())
{
try {
if(_triggerChannel != null) {
ev = _triggerChannel.getEvent(eventID++, true);
if (ev == null || ev.dur == 0)
continue;
}
if(_doWakeLock) wakeLock.acquire();
//grab data
boolean ok = true;
int pos, numSamples;
for(int i = 0; i < _bufferID_in.length; i++)
{
if(_triggerChannel != null)
{
pos = (int) ((ev.time / 1000.0) * _stream_in[i].sr + 0.5);
numSamples = ((int) (((ev.time + ev.dur) / 1000.0) * _stream_in[i].sr + 0.5)) - pos;
// check if local buffer is large enough and make it larger if necessary
_stream_in[i].adjust(numSamples);
}
else
{
pos = _readPos[i];
_readPos[i] += _num_frame[i];
}
ok &= _frame.getData(_bufferID_in[i], _stream_in[i].ptr(), pos, _stream_in[i].num);
if (ok)
_stream_in[i].time = (double) pos / _stream_in[i].sr;
}
//if we received data from all sources, process it
if(ok) {
consume(_stream_in, ev);
}
//maintain update rate
if(ok && _triggerChannel == null)
_timer.sync();
} catch(SSJFatalException e) {
_frame.error(_name, "exception in loop", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(_name, "exception in loop", e);
} finally {
if(_doWakeLock && wakeLock.isHeld()) wakeLock.release();
}
}
try {
flush(_stream_in);
} catch(Exception e) {
_frame.error(_name, "exception in flush", e);
}
_safeToKill = true;
}
/**
* Initialization specific to sensor implementation (called by framework on instantiation)
*
* @param stream_in Input stream
* @throws SSJException Exception
*/
protected void init(Stream[] stream_in) throws SSJException {}
/**
* Initialization specific to sensor implementation (called by local thread after framework start)
*
* @param stream_in Input stream
* @throws SSJFatalException Causes immediate pipeline termination
*/
public void enter(Stream[] stream_in) throws SSJFatalException {}
/**
* Main processing method
*
* @param stream_in Input stream
* @param trigger Event trigger
* @throws SSJFatalException Exception
*/
protected abstract void consume(Stream[] stream_in, Event trigger) throws SSJFatalException;
/**
* Called once prior to termination
*
* @param stream_in Input stream
* @throws SSJFatalException Exception
*/
public void flush(Stream[] stream_in) throws SSJFatalException {}
public void setEventTrigger(EventChannel channel)
{
_triggerChannel = channel;
}
public EventChannel getEventTrigger()
{
return _triggerChannel;
}
/**
* Initialization for continuous consumer
*
* @param sources Providers
* @param frame Frame size
* @param delta Delta size
* @throws SSJException Exception
*/
public void setup(Provider[] sources, double frame, double delta) throws SSJException
{
for (Provider source : sources)
{
if (!source.isSetup())
{
throw new SSJException("Components must be added in the correct order. Cannot add " + _name + " before its source " + source.getComponentName());
}
}
try
{
_bufferID_in = new int[sources.length];
_readPos = new int[sources.length];
_stream_in = new Stream[sources.length];
_num_frame = new int[sources.length];
_num_delta = new int[sources.length];
//compute window sizes
for(int i = 0; i < sources.length; i++) {
_num_frame[i] = (int)(frame * sources[i].getOutputStream().sr + 0.5);
_num_delta[i] = (int)(delta * sources[i].getOutputStream().sr + 0.5);
}
frame = (double)_num_frame[0] / sources[0].getOutputStream().sr;
delta = (double)_num_delta[0] / sources[0].getOutputStream().sr;
//allocate local input buffer
for(int i = 0; i < sources.length; i++) {
_bufferID_in[i] = sources[i].getBufferID();
_stream_in[i] = Stream.create(sources[i], _num_frame[i], _num_delta[i]);
}
//give implementation a chance to react to window size
init(_stream_in);
// configure update rate
_timer = new Timer(frame);
_timer.setStartOffset(delta);
}
catch(Exception e)
{
throw new SSJException("error configuring component", e);
}
_isSetup = true;
}
/**
* Initialization for event consumer
*
* @param sources Providers
* @throws SSJException Exception
*/
public void setup(Provider[] sources) throws SSJException
{
for (Provider source : sources)
{
if (!source.isSetup())
{
throw new SSJException("Components must be added in the correct order. Cannot add " + _name + " before its source " + source.getComponentName());
}
}
try {
_bufferID_in = new int[sources.length];
_stream_in = new Stream[sources.length];
for(int i = 0; i < sources.length; i++) {
_bufferID_in[i] = sources[i].getBufferID();
//allocate local input buffer and make it one second large too avoid memory allocation at runtime
_stream_in[i] = Stream.create(sources[i], (int)sources[i].getOutputStream().sr);
}
init(_stream_in);
} catch(Exception e) {
throw new SSJException("error configuring component", e);
}
_isSetup = true;
}
@Override
public void close()
{
if(_triggerChannel != null)
_triggerChannel.close();
super.close();
}
@Override
public void reset()
{
if(_triggerChannel != null)
_triggerChannel.reset();
super.reset();
}
}
| 10,217 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Sensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Sensor.java | /*
* Sensor.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.util.ArrayList;
/**
* Handles connection to sensor device
*/
public abstract class Sensor extends Component {
private boolean _isConnected = false;
protected Pipeline _frame;
protected ArrayList<SensorChannel> _provider = new ArrayList<>();
public Sensor()
{
_frame = Pipeline.getInstance();
}
void addChannel(SensorChannel p) throws SSJException {
_provider.add(p);
}
public ArrayList<SensorChannel> getProviders()
{
return _provider;
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
//if user did not specify a custom priority, use low priority
android.os.Process.setThreadPriority( (threadPriority == Cons.THREAD_PRIORITY_NORMAL) ? Cons.THREAD_PRIORIIY_LOW : threadPriority );
_isConnected = false;
while(!_terminate)
{
if(!_isConnected && !_frame.isStopping())
{
try
{
_isConnected = connect();
if (!_isConnected) {
waitCheckConnect();
continue;
}
synchronized (this)
{
this.notifyAll();
}
}
catch (SSJFatalException e) {
_frame.error(this.getComponentName(), "failed to connect to sensor", e);
_safeToKill = true;
return;
} catch (Exception e) {
_frame.error(this.getComponentName(), "failed to connect to sensor", e);
}
}
try {
update();
} catch(SSJFatalException e) {
_frame.error(this.getComponentName(), "exception in sensor update", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in sensor update", e);
}
_isConnected = checkConnection();
}
try {
disconnect();
} catch(Exception e) {
_frame.error(this.getComponentName(), "failed to disconnect from sensor", e);
}
_isConnected = false;
_safeToKill = true;
}
/**
* Early initialization specific to implementation (called by framework on instantiation)
*
* @throws SSJException Exception
*/
protected void init() throws SSJException {}
/**
* Initialization specific to sensor implementation (called by local thread after framework start)
*
* @return True if connection successful
* @throws SSJFatalException Exception
*/
protected abstract boolean connect() throws SSJFatalException;
protected boolean checkConnection() {return true;}
private void waitCheckConnect()
{
try{
Thread.sleep(Cons.SLEEP_ON_COMPONENT_IDLE);
}
catch(InterruptedException e) {
Log.w("thread interrupt");
}
}
/**
* Called once per frame, can be overwritten
*
* @throws SSJFatalException Exception
*/
protected void update() throws SSJFatalException
{
waitCheckConnect();
}
/**
* Called once before termination
*
* @throws SSJFatalException Exception
*/
protected abstract void disconnect() throws SSJFatalException;
public boolean isConnected()
{
return _isConnected;
}
public void waitForConnection()
{
while (!isConnected() && !_terminate)
{
try {
synchronized (this)
{
this.wait();
}
} catch (InterruptedException e) {}
}
}
@Override
public void clear()
{
_provider.clear();
super.reset();
}
}
| 5,387 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Monitor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Monitor.java | /*
* Monitor.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
/**
* Monitor class to synchronize threads.<br>
* Created by Frank Gaibler on 07.10.2015.
*/
public class Monitor
{
private static final Object monitor = new Object();
private static boolean waiting = false;
/**
*
*/
public static void waitMonitor()
{
synchronized (monitor)
{
try
{
waiting = true;
monitor.wait();
} catch (InterruptedException e)
{
waiting = false;
e.printStackTrace();
}
}
}
/**
*
*/
public static void notifyMonitor()
{
if (waiting)
{
synchronized (monitor)
{
monitor.notifyAll();
}
waiting = false;
}
}
}
| 2,195 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EventListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/EventListener.java | /*
* EventListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import hcm.ssj.core.event.Event;
/**
* Created by Michael Dietz on 25.04.2016.
*/
public interface EventListener
{
void notify(Event event);
}
| 1,521 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Timer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Timer.java | /*
* Timer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.os.SystemClock;
import java.util.ArrayList;
/**
* Created by Johnny on 05.03.2015.
*/
public class Timer {
private long _now;
private long _init;
private long _next;
private long _delta;
private long _offset;
private long _tick_start = 0;
private final int HISTORY_SIZE = 10;
private ArrayList<Long> _history = new ArrayList<Long>();
private boolean _syncFailFlag;
public Timer()
{
reset();
}
public Timer (int interval_in_ms)
{
setClockMs(interval_in_ms);
reset();
}
public Timer (double interval_in_s)
{
setClockS(interval_in_s);
reset();
}
public void setClockS(double seconds)
{
_delta = (long)(seconds * 1000 + 0.5);
}
public void setClockMs(long milliseconds)
{
_delta = milliseconds;
}
public void setClockHz(double hz)
{
setClockS(1.0 / hz);
}
public void reset ()
{
_syncFailFlag = false;
_init = SystemClock.elapsedRealtime();
_next = _delta + _offset;
}
//offsets the first tick, requires a "reset"
public void setStartOffset(double seconds)
{
_offset = (long)(seconds * 1000 + 0.5);
}
//offsets the next tick, requires a "reset"
public void setStartOffset(long milliseconds)
{
_offset = milliseconds;
}
//equivalent to SSI's wait()
public void sync ()
{
_now = SystemClock.elapsedRealtime() - _init;
while (_now < _next)
{
try
{
Thread.sleep (_next - _now);
}
catch (InterruptedException e){
Log.w("thread interrupt");
}
_now = SystemClock.elapsedRealtime() - _init;
}
if(_now - _next > _delta + Cons.TIMER_SYNC_ACCURACY) {
if(!_syncFailFlag) {
_syncFailFlag = true;
Log.i(Thread.currentThread().getStackTrace()[3].getClassName().replace("hcm.ssj.", ""),
"thread too slow, missing sync points");
}
} else if(_now - _next <= 1) {
if(_syncFailFlag) {
_syncFailFlag = false;
Log.i(Thread.currentThread().getStackTrace()[3].getClassName().replace("hcm.ssj.", ""),
"thread back in sync");
}
}
_next += _delta;
}
public void tick_start()
{
_tick_start = System.nanoTime();
}
public void tick_end()
{
_history.add(System.nanoTime() - _tick_start);
if(_history.size() > HISTORY_SIZE)
_history.remove(0);
}
public void tick()
{
if(_tick_start != 0)
_history.add(SystemClock.elapsedRealtime() - _tick_start);
_tick_start = SystemClock.elapsedRealtime();
if(_history.size() > HISTORY_SIZE)
_history.remove(0);
}
public double getMax()
{
long max = 0;
for(Long delta : _history) {
if(delta > max)
max = delta;
}
return max / 1000.0;
}
public double getAvgDur()
{
if(_history.size() == 0)
return 0;
long sum = 0;
for(Long delta : _history) {
sum += delta;
}
double avg = (double)sum / (double)_history.size();
return avg / 1000000.0;
}
public long getElapsedMs()
{
return SystemClock.elapsedRealtime() - _init;
}
public double getElapsed()
{
return getElapsedMs() / 1000.0;
}
}
| 5,002 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SensorChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/SensorChannel.java | /*
* SensorChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.os.PowerManager;
import hcm.ssj.core.stream.Stream;
/**
* Component handling data stream of a sensor device.
* Requires a valid sensor instance (to handle the connection to the physical device)
*/
public abstract class SensorChannel extends Provider {
private float _watchInterval = Cons.DFLT_WATCH_INTERVAL; //how often should the watchdog check if the sensor is providing data (in seconds)
private float _syncInterval = Cons.DFLT_SYNC_INTERVAL; //how often should the watchdog sync the buffer with the framework (in seconds)
protected Pipeline _frame;
protected Timer _timer;
protected Sensor _sensor;
public SensorChannel()
{
_frame = Pipeline.getInstance();
}
void setSensor(Sensor s)
{
_sensor = s;
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
if(!_isSetup) {
_frame.error(this.getComponentName(), "not initialized", null);
_safeToKill = true;
return;
}
//if user did not specify a custom priority, use high priority
android.os.Process.setThreadPriority( (threadPriority == Cons.THREAD_PRIORITY_NORMAL) ? Cons.THREAD_PRIORIIY_HIGH : threadPriority );
PowerManager mgr = (PowerManager)SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, _name);
WatchDog dog = new WatchDog(_bufferID, _watchInterval, _syncInterval);
if(_sensor == null)
{
Log.w("provider has not been attached to any sensor");
}
else
{
// wait for sensor to connect
while (!_sensor.isConnected() && !_terminate)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
}
try {
enter(_stream_out);
} catch(SSJFatalException e) {
_frame.error(this.getComponentName(), "exception in enter", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in enter", e);
}
_timer.reset();
while(!_terminate)
{
try {
wakeLock.acquire();
if(process(_stream_out))
{
_frame.pushData(_bufferID, _stream_out.ptr(), _stream_out.tot);
dog.checkIn();
}
_timer.sync();
} catch(SSJFatalException e) {
_frame.error(this.getComponentName(), "exception in loop", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in loop", e);
} finally {
wakeLock.release();
}
}
//dog must be closed as soon as sensor stops providing
try {
dog.close();
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception closing watch dog", e);
}
try {
flush(_stream_out);
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in flush", e);
}
_safeToKill = true;
}
/**
* Early initialization specific to implementation (called by framework on instantiation)
*
* @throws SSJException Exception
*/
protected void init() throws SSJException {}
/**
* Initialization specific to sensor implementation (called by local thread after framework start and after sensor connects)
*
* @param stream_out Output stream
* @throws SSJFatalException Exception
*/
public void enter(Stream stream_out) throws SSJFatalException {}
/**
* Main processing method
*
* @param stream_out Output stream
* @return True if processing was successful
* @throws SSJFatalException Exception
*/
protected abstract boolean process(Stream stream_out) throws SSJFatalException;
/**
* Called once prior to termination
*
* @param stream_out Output stream
* @throws SSJFatalException Exception
*/
public void flush(Stream stream_out) throws SSJFatalException {}
/**
* General sensor initialization
*
* @throws SSJException Exception
*/
public void setup() throws SSJException {
try
{
// figure out properties of output signal
int bytes_out = getSampleBytes();
int dim_out = getSampleDimension();
double sr_out = getSampleRate();
Cons.Type type_out = getSampleType();
int num_out = getSampleNumber();
_stream_out = Stream.create(num_out, dim_out, sr_out, type_out);
describeOutput(_stream_out);
// configure update rate
_timer = new Timer((double)num_out / sr_out);
}
catch(Exception e)
{
throw new SSJException("error configuring component", e);
}
Log.i("Sensor Provider " + _name + " (output)" + '\n' +
"\tbytes=" +_stream_out.bytes+ '\n' +
"\tdim=" +_stream_out.dim+ '\n' +
"\ttype=" +_stream_out.type.toString() + '\n' +
"\tnum=" +_stream_out.num+ '\n' +
"\tsr=" +_stream_out.sr);
_isSetup = true;
}
@Override
public String[] getOutputDescription()
{
if(!_isSetup) {
Log.e("not initialized");
return null;
}
String[] desc = new String[_stream_out.desc.length];
System.arraycopy(_stream_out.desc, 0, desc, 0, _stream_out.desc.length);
return desc;
}
protected abstract double getSampleRate();
protected abstract int getSampleDimension();
protected abstract Cons.Type getSampleType();
protected int getSampleBytes()
{
return Util.sizeOf(getSampleType());
}
/*
* By default, every sensor will push their data to the framework asap one sample at a time.
* If a specific sensor cannot do this, this function can be overriden
*/
protected int getSampleNumber()
{
return 1;
}
protected abstract void describeOutput(Stream stream_out);
//how often should the watchdog check if the sensor is providing data (in seconds)
public void setWatchInterval(float watchInterval)
{
_watchInterval = watchInterval;
}
//how often should the watchdog sync the buffer with the framework (in seconds)
public void setSyncInterval(float syncInterval)
{
_syncInterval = syncInterval;
}
}
| 8,321 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSJApplication.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/SSJApplication.java | /*
* SSJApplication.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
/**
* Created by Michael Dietz on 01.04.2015.
*/
public class SSJApplication extends Application
{
private static Context context;
public void onCreate()
{
super.onCreate();
SSJApplication.context = getApplicationContext();
}
@Override
protected void attachBaseContext(Context base)
{
super.attachBaseContext(base);
MultiDex.install(this);
}
public static Context getAppContext()
{
return SSJApplication.context;
}
}
| 1,919 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Cons.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Cons.java | /*
* Cons.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.graphics.Color;
import hcm.ssj.audio.Microphone;
/**
* Created by Johnny on 05.03.2015.
*/
public class Cons
{
public final static String LOGTAG = "SSJ";
public final static float DFLT_SYNC_INTERVAL = 5.0f; //in seconds
public final static float DFLT_WATCH_INTERVAL = 1.0f; //in seconds
public final static long SLEEP_IN_LOOP = 100; //in ms
public final static long TIMER_SYNC_ACCURACY = 100; //in ms
public final static long SLEEP_ON_COMPONENT_IDLE = 5000; //in ms
public final static long WAIT_BL_CONNECT = 1000; //in ms
public static final long WAIT_BL_DISCONNECT = 1000; //in ms
public final static long WAIT_THREAD_TERMINATION = 5000; //in ms
public final static int MAX_EVENT_SIZE = 4096; //in bytes
public final static int MAX_NUM_EVENTS_PER_CHANNEL = 128; //in bytes
public final static int THREAD_PRIORIIY_LOW = 10; //nice scale, -20 highest priority, 19 lowest priority
public final static int THREAD_PRIORITY_NORMAL = -2; //nice scale, -20 highest priority, 19 lowest priority
public final static int THREAD_PRIORIIY_HIGH = -19; //nice scale, -20 highest priority, 19 lowest priority
public final static String DEFAULT_BL_SERIAL_UUID = "00001101-0000-1000-8000-00805f9b34fb";
public final static String GARBAGE_CLASS = "GARBAGE";
public final static int GARBAGE_CLASS_ID = -1;
public enum Type {
UNDEF,
BYTE,
CHAR,
SHORT,
INT,
LONG,
FLOAT,
DOUBLE,
BOOL,
STRING,
IMAGE,
// Only used for events
EMPTY,
MAP
}
public enum FileType
{
ASCII,
BINARY
}
public enum AudioFormat {
// These values must be kept in sync with core/jni/android_media_AudioFormat.h
// Also sync av/services/audiopolicy/managerdefault/ConfigParsingUtils.h
/** Invalid audio data format */
ENCODING_DEFAULT(android.media.AudioFormat.ENCODING_DEFAULT),
/** Audio data format: PCM 16 bit per sample. Guaranteed to be supported by devices. */
ENCODING_PCM_16BIT(android.media.AudioFormat.ENCODING_PCM_16BIT),
/** Audio data format: PCM 8 bit per sample. Not guaranteed to be supported by devices. */
ENCODING_PCM_8BIT(android.media.AudioFormat.ENCODING_PCM_8BIT),
/** Audio data format: single-precision floating-point per sample */
ENCODING_PCM_FLOAT(android.media.AudioFormat.ENCODING_PCM_FLOAT),
/** Audio data format: AC-3 compressed */
ENCODING_AC3(android.media.AudioFormat.ENCODING_AC3),
/** Audio data format: E-AC-3 compressed */
ENCODING_E_AC3(android.media.AudioFormat.ENCODING_E_AC3);
// /** Audio data format: DTS compressed */
// ENCODING_DTS(android.media.AudioFormat.ENCODING_DTS),
// /** Audio data format: DTS HD compressed */
// ENCODING_DTS_HD(android.media.AudioFormat.ENCODING_DTS_HD);
public int val;
AudioFormat(int value)
{
val = value;
}
}
public enum ChannelFormat {
CHANNEL_IN_DEFAULT(android.media.AudioFormat.CHANNEL_IN_DEFAULT),
CHANNEL_IN_LEFT(android.media.AudioFormat.CHANNEL_IN_LEFT),
CHANNEL_IN_RIGHT(android.media.AudioFormat.CHANNEL_IN_RIGHT),
CHANNEL_IN_FRONT(android.media.AudioFormat.CHANNEL_IN_FRONT),
CHANNEL_IN_BACK(android.media.AudioFormat.CHANNEL_IN_BACK),
CHANNEL_IN_LEFT_PROCESSED(android.media.AudioFormat.CHANNEL_IN_LEFT_PROCESSED),
CHANNEL_IN_RIGHT_PROCESSED(android.media.AudioFormat.CHANNEL_IN_RIGHT_PROCESSED),
CHANNEL_IN_FRONT_PROCESSED(android.media.AudioFormat.CHANNEL_IN_FRONT_PROCESSED),
CHANNEL_IN_BACK_PROCESSED(android.media.AudioFormat.CHANNEL_IN_BACK_PROCESSED),
CHANNEL_IN_PRESSURE(android.media.AudioFormat.CHANNEL_IN_PRESSURE),
CHANNEL_IN_X_AXIS(android.media.AudioFormat.CHANNEL_IN_X_AXIS),
CHANNEL_IN_Y_AXIS(android.media.AudioFormat.CHANNEL_IN_Y_AXIS),
CHANNEL_IN_Z_AXIS(android.media.AudioFormat.CHANNEL_IN_Z_AXIS),
CHANNEL_IN_VOICE_UPLINK(android.media.AudioFormat.CHANNEL_IN_VOICE_UPLINK),
CHANNEL_IN_VOICE_DNLINK(android.media.AudioFormat.CHANNEL_IN_VOICE_DNLINK),
CHANNEL_IN_MONO (android.media.AudioFormat.CHANNEL_IN_MONO),
CHANNEL_IN_STEREO (android.media.AudioFormat.CHANNEL_IN_STEREO);
public int val;
ChannelFormat(int value)
{
val = value;
}
}
public enum AudioDataFormat
{
BYTE(Microphone.audioFormatSampleBytes(android.media.AudioFormat.ENCODING_PCM_8BIT)),
SHORT(Microphone.audioFormatSampleBytes(android.media.AudioFormat.ENCODING_PCM_16BIT)),
FLOAT_8(BYTE.byteCount),
FLOAT_16(SHORT.byteCount);
public final int byteCount;
AudioDataFormat(int i)
{
byteCount = i;
}
}
public enum SocketType
{
UDP,
TCP
}
public enum ImageFormat {
NV21(android.graphics.ImageFormat.NV21),
FLEX_RGBA_8888(0x2A), //android.graphics.ImageFormat.FLEX_RGBA_8888
FLEX_RGB_888(0x29), //android.graphics.ImageFormat.FLEX_RGB_888
YUV_420_888(0x23), //android.graphics.ImageFormat.YUV_420_888)
YV12(android.graphics.ImageFormat.YV12);
public int val;
ImageFormat(int value)
{
val = value;
}
}
public enum CameraType
{
BACK_CAMERA(0),
FRONT_CAMERA(1);
public final int val;
CameraType(int val)
{
this.val = val;
}
}
public enum ImageRotation
{
ZERO(0),
PLUS_90(90),
PLUS_180(180),
MINUS_90(-90),
MINUS_180(-180);
public final int rotation;
ImageRotation(int rotation)
{
this.rotation = rotation;
}
}
public enum DrawColor
{
WHITE(Color.WHITE),
BLACK(Color.BLACK),
RED(Color.RED),
GREEN(Color.GREEN),
BLUE(Color.BLUE),
YELLOW(Color.YELLOW);
public final int color;
DrawColor(int color)
{
this.color = color;
}
}
public enum ClassifierMode
{
CLASSIFICATION(0),
REGRESSION(1);
public final int mode;
ClassifierMode(int mode)
{
this.mode = mode;
}
}
}
| 7,787 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSJException.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/SSJException.java | /*
* SSJException.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
/**
* Created by Johnny on 20.10.2016.
*/
public class SSJException extends Exception {
public SSJException() {}
public SSJException(String detailMessage) {
super(detailMessage);
}
public SSJException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public SSJException(Throwable throwable) {
super(throwable);
}
}
| 1,774 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Pipeline.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Pipeline.java | /*
* Pipeline.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.os.SystemClock;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import hcm.ssj.BuildConfig;
import hcm.ssj.R;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.feedback.Feedback;
import hcm.ssj.feedback.FeedbackCollection;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.FileDownloader;
import hcm.ssj.ml.Model;
import hcm.ssj.mobileSSI.SSI;
/**
* Main class for creating and interfacing with SSJ pipelines.
* Holds logic responsible for the setup and execution of pipelines.
*/
public class Pipeline
{
public class Options extends OptionList
{
/** duration of pipeline start-up phase. Default: 3 */
public final Option<Integer> countdown = new Option<>("countdown", 3, Integer.class, "duration of pipeline start-up phase");
/** size of all inter-component buffers (in seconds). Default: 2.0 */
public final Option<Float> bufferSize = new Option<>("bufferSize", 2.f, Float.class, "size of all inter-component buffers (in seconds)");
/** How long to wait for threads to finish on pipeline shutdown. Default: 30.0 */
public final Option<Float> waitThreadKill = new Option<>("waitThreadKill", 30f, Float.class, "How long to wait for threads to finish on pipeline shutdown");
/** How long to wait for a sensor to connect. Default: 30.0 */
public final Option<Float> waitSensorConnect = new Option<>("waitSensorConnect", 30.f, Float.class, "How long to wait for a sensor to connect");
/** Cross-device synchronization (requires network). Default: NONE */
public final Option<SyncType> sync = new Option<>("sync", SyncType.NONE, SyncType.class, "Cross-device synchronization (requires network).");
/** enter IP address of host pipeline for synchronization (leave empty if this is the host). Default: null */
public final Option<String> syncHost = new Option<>("syncHost", null, String.class, "enter IP address of host pipeline for synchronization (leave empty if this is the host)");
/** set port for synchronizing pipeline over network. Default: 55100 */
public final Option<Integer> syncPort = new Option<>("syncPort", 0, Integer.class, "port for synchronizing pipeline over network");
/** define time between clock sync attempts (requires CONTINUOUS sync). Default: 1.0 */
public final Option<Float> syncInterval = new Option<>("syncInterval", 10.0f, Float.class, "define time between clock sync attempts (requires CONTINUOUS sync)");
/** write system log to file. Default: false */
public final Option<Boolean> log = new Option<>("log", false, Boolean.class, "write system log to file");
/** location of log file. Default: /sdcard/SSJ/[time] */
public final Option<String> logpath = new Option<>("logpath", FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "[time]", String.class, "location of log file");
/** show all logs greater or equal than level. Default: VERBOSE */
public final Option<Log.Level> loglevel = new Option<>("loglevel", Log.Level.VERBOSE, Log.Level.class, "show all logs >= level");
/** repeated log entries with a duration delta smaller than the timeout value are ignored. Default: 1.0 */
public final Option<Double> logtimeout = new Option<>("logtimeout", 1.0, Double.class, "ignore repeated entries < timeout");
/** Shut down pipeline if runtime error is encountered */
public final Option<Boolean> terminateOnError = new Option<>("terminateOnError", false, Boolean.class, "Shut down pipeline if runtime error is encountered");
private Options()
{
addOptions();
}
}
public enum State
{
INACTIVE,
STARTING,
RUNNING,
STOPPING
}
public enum SyncType
{
NONE,
START_STOP,
CONTINUOUS
}
public final Options options = new Options();
protected String name = "SSJ_Framework";
private State state;
private long startTime = 0; //virtual clock
private long startTimeSystem = 0; //real clock
private long createTime = 0; //real clock
private long timeOffset = 0;
private NetworkSync sync = null;
ThreadPool threadPool = null;
ExceptionHandler exceptionHandler = null;
private HashSet<Component> components = new HashSet<>();
private ArrayList<TimeBuffer> buffers = new ArrayList<>();
private List<PipelineStateListener> stateListeners = new ArrayList<>();
private FileDownloader downloader;
protected static Pipeline instance = null;
private Pipeline()
{
setState(State.INACTIVE);
//configure logger
Log.getInstance().setFramework(this);
resetCreateTime();
Log.i(SSJApplication.getAppContext().getString(R.string.name_long) + " v" + getVersion());
}
/**
* Retrieve the SSJ pipeline instance.
* Only one SSJ pipeline instance per application is supported, yet it can contain multiple parallel branches.
*
* @return Pipeline the pipeline instance
*/
public static Pipeline getInstance()
{
if (instance == null)
instance = new Pipeline();
return instance;
}
public OptionList getOptions()
{
return options;
}
/**
* Sets the pipeline state and notifies state listeners
* @param newState target state
*/
private void setState(final State newState)
{
this.state = newState;
for (final PipelineStateListener stateListener : stateListeners)
{
new Thread(new Runnable()
{
@Override
public void run()
{
stateListener.stateUpdated(newState);
}
}).start();
}
}
/**
* Adds a new pipeline state listener
* @param listener listener
*/
public void registerStateListener(PipelineStateListener listener)
{
stateListeners.add(listener);
}
/**
* Removes a pipeline state listener
* @param listener listener
*/
public void unregisterStateListener(PipelineStateListener listener)
{
stateListeners.remove(listener);
}
/**
* Starts the SSJ pipeline.
* Automatically resets buffers and component states.
*/
public void start()
{
setState(State.STARTING);
try
{
Log.i("starting pipeline" + '\n' +
"\tSSJ v" + getVersion() + '\n' +
"\tlocal time: " + Util.getTimestamp(System.currentTimeMillis()));
int coreThreads = Runtime.getRuntime().availableProcessors();
threadPool = new ThreadPool(coreThreads, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
//sync with other pipelines
if (options.sync.get() != SyncType.NONE) {
boolean isMaster = (options.syncHost.get() == null) || (options.syncHost.get().isEmpty());
sync = new NetworkSync(options.sync.get(), isMaster, InetAddress.getByName(options.syncHost.get()), options.syncPort.get(), (int)(options.syncInterval.get() * 1000));
}
Log.i("preparing buffers");
for (TimeBuffer b : buffers)
b.reset();
for (Component c : components)
{
Log.i("starting " + c.getComponentName());
c.reset();
threadPool.execute(c);
}
for (int i = 0; i < options.countdown.get(); i++)
{
Log.i("starting pipeline in " + (options.countdown.get() - i));
Thread.sleep(1000);
}
if (options.sync.get() != SyncType.NONE)
{
if (options.syncHost.get() == null)
NetworkSync.sendStartSignal(options.syncPort.get());
else
{
Log.i("waiting for start signal from host pipeline ...");
sync.waitForStartSignal();
if(state != State.STARTING) //cancel startup if something happened while waiting for sync
return;
}
}
startTimeSystem = System.currentTimeMillis();
startTime = SystemClock.elapsedRealtime();
setState(State.RUNNING);
Log.i("pipeline started");
if (options.sync.get() != SyncType.NONE)
{
if (options.syncHost.get() != null)
{
Runnable stopper = new Runnable() {
@Override
public void run()
{
sync.waitForStopSignal();
Log.i("received stop signal from host pipeline");
stop();
}
};
threadPool.execute(stopper);
}
}
}
catch (Exception e)
{
error(this.getClass().getSimpleName(), "error starting pipeline, shutting down", e);
stop();
}
}
/**
* Adds a sensor with a corresponding channel to the pipeline and sets up the necessary output buffer.
* Calls init method of sensor and channel before setting up buffer.
*
* @param s the Sensor to be added
* @param c the corresponding channel
* @return the same SensorChannel which was passed as parameter
* @throws SSJException thrown is an error occurred when setting up the sensor
*/
public SensorChannel addSensor(Sensor s, SensorChannel c) throws SSJException
{
if(components.contains(c))
{
Log.w("Component already added.");
return c;
}
s.addChannel(c);
c.setSensor(s);
if(!components.contains(s))
{
components.add(s);
s.init();
}
c.init();
int dim = c.getSampleDimension();
double sr = c.getSampleRate();
int bytesPerValue = c.getSampleBytes();
Cons.Type type = c.getSampleType();
//add output buffer
TimeBuffer buf = new TimeBuffer(options.bufferSize.get(), sr, dim, bytesPerValue, type, c);
buffers.add(buf);
int buffer_id = buffers.size() - 1;
c.setBufferID(buffer_id);
c.setup();
components.add(c);
return c;
}
/**
* Adds a transformer to the pipeline and sets up the necessary output buffer.
* init method of transformer is called before setting up buffer.
*
* @param t the Transformer to be added
* @param source the component which will provide data to the transformer
* @return the Transformer which was passed as parameter
* @throws SSJException thrown is an error occurred when setting up the component
*/
public Provider addTransformer(Transformer t, Provider source) throws SSJException
{
Provider[] sources = {source};
return addTransformer(t, sources, source.getOutputStream().num / source.getOutputStream().sr, 0);
}
/**
* Adds a transformer to the pipeline and sets up the necessary output buffer.
* init method of transformer is called before setting up buffer.
*
* @param t the Transformer to be added
* @param source the component which will provide data to the transformer
* @param frame the size of the data window which is provided every iteration to the transformer (in seconds)
* @return the Transformer which was passed as parameter
* @throws SSJException thrown is an error occurred when setting up the component
*/
public Provider addTransformer(Transformer t, Provider source, double frame) throws SSJException
{
Provider[] sources = {source};
return addTransformer(t, sources, frame, 0);
}
/**
* Adds a transformer to the pipeline and sets up the necessary output buffer.
* init method of transformer is called before setting up buffer.
*
* @param t the Transformer to be added
* @param source the component which will provide data to the transformer
* @param frame the size of the data window which is provided every iteration to the transformer (in seconds)
* @param delta the amount of input data which overlaps with the previous window (in seconds). Provided in addition to the primary window ("frame").
* @return the Transformer which was passed as parameter
* @throws SSJException thrown is an error occurred when setting up the component
*/
public Provider addTransformer(Transformer t, Provider source, double frame, double delta) throws SSJException
{
Provider[] sources = {source};
return addTransformer(t, sources, frame, delta);
}
/**
* Adds a transformer to the pipeline and sets up the necessary output buffer.
* init method of transformer is called before setting up buffer.
*
* @param t the Transformer to be added
* @param sources the components which will provide data to the transformer
* @param frame the size of the data window which is provided every iteration to the transformer (in seconds)
* @param delta the amount of input data which overlaps with the previous window (in seconds). Provided in addition to the primary window ("frame").
* @return the Transformer which was passed as parameter
* @throws SSJException thrown is an error occurred when setting up the component
*/
public Provider addTransformer(Transformer t, Provider[] sources, double frame, double delta) throws SSJException
{
if(components.contains(t))
{
Log.w("Component already added.");
return t;
}
t.setup(sources, frame, delta);
int dim = t.getOutputStream().dim;
double sr = t.getOutputStream().sr;
int bytesPerValue = t.getOutputStream().bytes;
Cons.Type type = t.getOutputStream().type;
//add output buffer
TimeBuffer buf = new TimeBuffer(options.bufferSize.get(), sr, dim, bytesPerValue, type, t);
buffers.add(buf);
int buffer_id = buffers.size() - 1;
t.setBufferID(buffer_id);
components.add(t);
return t;
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param source the component which will provide data to the consumer
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider source) throws SSJException
{
Provider[] sources = {source};
addConsumer(c, sources);
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param sources the components which will provide data to the consumer
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider[] sources) throws SSJException
{
addConsumer(c, sources, sources[0].getOutputStream().num / sources[0].getOutputStream().sr, 0);
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param source the component which will provide data to the consumer
* @param frame the size of the data window which is provided every iteration to the transformer (in seconds)
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider source, double frame) throws SSJException {
Provider[] sources = {source};
addConsumer(c, sources, frame, 0);
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param source the component which will provide data to the consumer
* @param frame the size of the data window which is provided every iteration to the transformer (in seconds)
* @param delta the amount of input data which overlaps with the previous window (in seconds). Provided in addition to the primary window ("frame").
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider source, double frame, double delta) throws SSJException {
Provider[] sources = {source};
addConsumer(c, sources, frame, delta);
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param sources the components which will provide data to the consumer
* @param frame the size of the data window which is provided every iteration to the transformer (in seconds)
* @param delta the amount of input data which overlaps with the previous window (in seconds). Provided in addition to the primary window ("frame").
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider[] sources, double frame, double delta) throws SSJException
{
if(components.contains(c))
{
Log.w("Component already added.");
return;
}
c.setup(sources, frame, delta);
components.add(c);
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param source the component which will provide data to the consumer
* @param trigger an event channel which acts as a trigger. The consumer will only process data when an event is received.
* The data window to be processed is defined by the timing information of the event.
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider source, EventChannel trigger) throws SSJException
{
Provider[] sources = {source};
addConsumer(c, sources, trigger);
}
/**
* Adds a consumer to the pipeline.
* init method of consumer is called after setting up internal input buffer.
*
* @param c the Consumer to be added
* @param sources the components which will provide data to the consumer
* @param trigger an event channel which acts as a trigger. The consumer will only process data when an event is received.
* The data window to be processed is defined by the timing information of the event.
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addConsumer(Consumer c, Provider[] sources, EventChannel trigger) throws SSJException
{
if(components.contains(c))
{
Log.w("Component already added.");
return;
}
c.setEventTrigger(trigger);
c.setup(sources);
components.add(c);
}
/**
* Adds a model to the pipeline.
*
* @param m the Model to be added
* @throws SSJException thrown is an error occurred when setting up the component
*/
public void addModel(Model m) throws SSJException {
if(components.contains(m))
{
Log.w("Component already added.");
return;
}
m.setup();
components.add(m);
}
/**
* Registers a component as a listener to another component's events.
* Component is also added to the pipeline (if not already there)
* This component will be notified every time the "source" component pushes an event into its channel
*
* @param c the listener
* @param source the one being listened to
*/
public void registerEventListener(Component c, Component source)
{
registerEventListener(c, source.getEventChannelOut());
}
/**
* Registers a component as a listener to a specific event channel.
* Component is also added to the pipeline (if not already there)
* This component will be notified every time a new event is pushed into the channel.
*
* @param c the listener
* @param channel the channel to be listened to
*/
public void registerEventListener(Component c, EventChannel channel)
{
components.add(c);
c.addEventChannelIn(channel);
}
/**
* Register a component as a listener to multiple event channels.
* Component is also added to the pipeline (if not already there)
* This component will be notified every time a new event is pushed a channel.
*
* @param c the listener
* @param channels the channel to be listened to
*/
public void registerEventListener(Component c, EventChannel[] channels)
{
components.add(c);
for(EventChannel ch : channels)
c.addEventChannelIn(ch);
}
/**
* Register a component as an event provider.
* Component is also added to the pipeline (if not already there)
*
* @param c the event provider
* @return the output channel of the component.
*/
public EventChannel registerEventProvider(Component c)
{
components.add(c);
return c.getEventChannelOut();
}
public void registerInFeedbackCollection(Feedback feedback, FeedbackCollection feedbackCollection, int level, FeedbackCollection.LevelBehaviour levelBehaviour)
{
components.add(feedback);
if(feedback._evchannel_in != null)
feedback._evchannel_in.clear();
for(EventChannel eventChannel : feedbackCollection._evchannel_in)
{
registerEventListener(feedback, eventChannel);
}
feedbackCollection.addFeedback(feedback, level, levelBehaviour);
}
public void registerInFeedbackCollection(FeedbackCollection feedbackCollection, List<Map<Feedback,FeedbackCollection.LevelBehaviour>> feedbackList)
{
feedbackCollection.removeAllFeedbacks();
for (int level = 0; level < feedbackList.size(); level++)
{
for(Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry : feedbackList.get(level).entrySet())
{
registerInFeedbackCollection(feedbackLevelBehaviourEntry.getKey(),
feedbackCollection,
level,
feedbackLevelBehaviourEntry.getValue());
}
}
}
void pushData(int buffer_id, Object data, int numBytes)
{
if (!isRunning())
{
return;
}
if (buffer_id < 0 || buffer_id >= buffers.size())
Log.w("cannot push to buffer " + buffer_id + ". Buffer does not exist.");
buffers.get(buffer_id).push(data, numBytes);
}
void pushZeroes(int buffer_id)
{
if (!isRunning())
{
return;
}
if (buffer_id < 0 || buffer_id >= buffers.size())
Log.w("cannot push to buffer " + buffer_id + ". Buffer does not exist.");
TimeBuffer buf = buffers.get(buffer_id);
double frame_time = getTime();
double buffer_time = buf.getLastWrittenSampleTime();
if (buffer_time < frame_time)
{
int bytes = (int) ((frame_time - buffer_time) * buf.getSampleRate()) * buf.getBytesPerSample();
if (bytes > 0)
buf.pushZeroes(bytes);
}
}
void pushZeroes(int buffer_id, int num)
{
if (!isRunning())
{
return;
}
if (buffer_id < 0 || buffer_id >= buffers.size())
Log.w("cannot push to buffer " + buffer_id + ". Buffer does not exist.");
buffers.get(buffer_id).pushZeroes(num);
}
boolean getData(int buffer_id, Object data, double start_time, double duration)
{
if (!isRunning())
{
return false;
}
if (buffer_id < 0 || buffer_id >= buffers.size())
Log.w("cannot read from buffer " + buffer_id + ". Buffer does not exist.");
TimeBuffer buf = buffers.get(buffer_id);
int res = buf.get(data, start_time, duration);
switch (res)
{
case TimeBuffer.STATUS_INPUT_ARRAY_TOO_SMALL:
Log.w(buf.getOwner().getComponentName(), "input buffer too small");
return false;
case TimeBuffer.STATUS_DATA_EXCEEDS_BUFFER_SIZE:
Log.w(buf.getOwner().getComponentName(), "data exceeds buffers size");
return false;
case TimeBuffer.STATUS_DATA_NOT_IN_BUFFER_YET:
Log.w(buf.getOwner().getComponentName(), "data not in buffer yer");
return false;
case TimeBuffer.STATUS_DATA_NOT_IN_BUFFER_ANYMORE:
Log.w(buf.getOwner().getComponentName(), "data not in buffer anymore");
return false;
case TimeBuffer.STATUS_DURATION_TOO_SMALL:
Log.w(buf.getOwner().getComponentName(), "requested duration too small");
return false;
case TimeBuffer.STATUS_DURATION_TOO_LARGE:
Log.w(buf.getOwner().getComponentName(), "requested duration too large");
return false;
case TimeBuffer.STATUS_ERROR:
if (isRunning()) //this means that either the framework shut down (in this case the behaviour is normal) or some other error occurred
Log.w(buf.getOwner().getComponentName(), "unknown error occurred");
return false;
}
return true;
}
boolean getData(int buffer_id, Object data, int startSample, int numSamples)
{
if (!isRunning())
{
return false;
}
if (buffer_id < 0 || buffer_id >= buffers.size())
Log.w("Invalid buffer");
TimeBuffer buf = buffers.get(buffer_id);
int res = buf.get(data, startSample, numSamples);
switch (res)
{
case TimeBuffer.STATUS_INPUT_ARRAY_TOO_SMALL:
Log.w(buf.getOwner().getComponentName(), "input buffer too small");
return false;
case TimeBuffer.STATUS_DATA_EXCEEDS_BUFFER_SIZE:
Log.w(buf.getOwner().getComponentName(), "data exceeds buffers size");
return false;
case TimeBuffer.STATUS_DATA_NOT_IN_BUFFER_YET:
Log.w(buf.getOwner().getComponentName(), "data not in buffer yet");
return false;
case TimeBuffer.STATUS_DATA_NOT_IN_BUFFER_ANYMORE:
long bufEnd = buf.getPositionAbs() / buf.getBytesPerSample();
long bufStart = bufEnd - buf.getCapacity() / buf.getBytesPerSample();
Log.w(buf.getOwner().getComponentName(), "requested data range (" + (startSample - buf.getOffsetSamples()) + "-" + (startSample + numSamples - buf.getOffsetSamples()) + ") not in buffer (" + bufStart + "-" + bufEnd + ") anymore. Consumer/Transformer is probably too slow");
return false;
case TimeBuffer.STATUS_DURATION_TOO_SMALL:
Log.w(buf.getOwner().getComponentName(), "requested duration too small");
return false;
case TimeBuffer.STATUS_DURATION_TOO_LARGE:
Log.w(buf.getOwner().getComponentName(), "requested duration too large");
return false;
case TimeBuffer.STATUS_UNKNOWN_DATA:
Log.w(buf.getOwner().getComponentName(), "requested data is unknown, probably caused by a delayed sensor start");
return false;
case TimeBuffer.STATUS_ERROR:
if (isRunning()) //this means that either the framework shut down (in this case the behaviour is normal) or some other error occurred
Log.w(buf.getOwner().getComponentName(), "unknown buffer error occurred");
return false;
}
return true;
}
/**
* Stops the pipeline.
* Closes all buffers and shuts down all components.
* Also writes log file to sd card (if configured).
*/
public void stop()
{
if (state == State.STOPPING || state == State.INACTIVE)
return;
setState(State.STOPPING);
Log.i("stopping pipeline" + '\n' +
"\tlocal time: " + Util.getTimestamp(System.currentTimeMillis()));
try
{
if(sync != null)
{
if (options.syncHost.get() == null)
NetworkSync.sendStopSignal(options.syncPort.get());
sync.release();
}
Log.i("closing buffer");
for (TimeBuffer b : buffers)
b.close();
if(downloader != null)
{
Log.i("aborting downloads");
downloader.terminate();
downloader = null;
}
Log.i("closing components");
for (Component c : components)
{
Log.i("closing " + c.getComponentName());
//try to close everything individually to free each sensor
try
{
c.close();
} catch (Exception e)
{
Log.e("closing " + c.getComponentName() + " failed", e);
}
}
threadPool.shutdown();
Log.i("waiting for components to terminate");
if(!threadPool.awaitTermination(Cons.WAIT_THREAD_TERMINATION, TimeUnit.MILLISECONDS))
threadPool.shutdownNow();
Log.i("shut down completed");
}
catch (InterruptedException e)
{
threadPool.shutdownNow();
}
catch (Exception e)
{
Log.e("Exception in closing framework", e);
if (exceptionHandler != null)
{
exceptionHandler.handle("TheFramework.stop()", "Exception in closing framework", e);
}
else
{
setState(State.INACTIVE);
throw new RuntimeException(e);
}
} finally
{
writeLogFile();
setState(State.INACTIVE);
}
}
/**
* Invalidates framework instance and clears all local content
*/
public void release()
{
if (isRunning())
{
Log.w("Cannot release. Framework still active.");
return;
}
clear();
if(downloader != null)
{
downloader.terminate();
downloader = null;
}
instance = null;
}
/**
* Clears all buffers, components and internal pipeline state, but does not invalidate instance.
*/
public void clear()
{
if (isRunning())
{
Log.w("Cannot clear. Framework still active.");
return;
}
setState(State.INACTIVE);
for (Component c : components)
c.clear();
components.clear();
buffers.clear();
stateListeners.clear();
Log.getInstance().clear();
startTime = 0;
if(threadPool != null)
threadPool.purge();
SSI.clear();
}
/**
* Executes a runnable using the pipeline's thread pool
*
* @param r runnable
*/
public void executeRunnable(Runnable r)
{
threadPool.execute(r);
}
/**
* Resets pipeline "create" timestamp
*/
public void resetCreateTime()
{
createTime = System.currentTimeMillis();
}
private void writeLogFile()
{
if (options.log.get())
{
Log.getInstance().saveToFile(options.logpath.parseWildcards());
}
}
/**
* Marks the occurence of an unrecoverable error, reports it and attempts to shut down the pipeline
* @param location where the error occurred
* @param message error message
* @param e exception which caused the error, can be null
*/
void error(String location, String message, Throwable e)
{
Log.e(location, message, e);
writeLogFile();
if (exceptionHandler != null)
{
exceptionHandler.handle(location, message, e);
}
if(options.terminateOnError.get() && isRunning())
stop();
}
void sync(int bufferID)
{
if (!isRunning())
return;
buffers.get(bufferID).sync(getTime());
}
/**
* Downloads multiple files to the sd card
* @param fileNames array containing the names of the files to download
* @param from remote path from which to download files
* @param to path to download to
* @param wait if true, function blocks until download is finished
*/
public void download(String[] fileNames, String from, String to, boolean wait)
{
if(downloader == null || downloader.isTerminating())
downloader = new FileDownloader();
FileDownloader.Task t = null;
for(String fileName : fileNames)
{
t = downloader.addToQueue(fileName, from, to);
if(t == null)
return;
}
if(!downloader.isAlive())
downloader.start();
if(wait) downloader.wait(t);
}
/**
* Downloads a file to the sd card
*
* @param fileName Name of the file
* @param from Remote path from which to download file
* @param to Path to download to
* @param wait If true, function blocks until download is finished
* @throws IOException IO Exception
*/
public void download(String fileName, String from, String to, boolean wait) throws IOException
{
if(fileName == null || fileName.isEmpty()
|| from == null || from.isEmpty()
|| to == null || to.isEmpty())
throw new IOException("download source or destination is empty");
if(downloader == null || downloader.isTerminating())
downloader = new FileDownloader();
FileDownloader.Task t = downloader.addToQueue(fileName, from, to);
if(t == null)
return;
if(!downloader.isAlive())
downloader.start();
if(wait) downloader.wait(t);
}
/**
* @return elapsed time since start of the pipeline (in seconds)
*/
public double getTime()
{
return getTimeMs() / 1000.0;
}
/**
* @return elapsed time since start of the pipeline (in milliseconds)
*/
public long getTimeMs()
{
if (startTime == 0)
return 0;
return SystemClock.elapsedRealtime() - startTime + timeOffset;
}
void adjustTime(long offset)
{
Log.d("adjusting clock by " + offset + " ms");
timeOffset += offset;
}
/**
* @return system time at which the pipeline started
*/
public long getStartTimeMs()
{
return startTimeSystem;
}
/**
* @return system time at which the pipeline instance was created.
* Timestamp can be modified using "resetCreateTime()"
*/
public long getCreateTimeMs()
{
return createTime;
}
/**
* @return true if SSJ has already been instanced, false otherwise
*/
public static boolean isInstanced()
{
return instance != null;
}
/**
* @return current state of the framework
*/
public State getState()
{
return state;
}
/**
* @return true if pipeline is running, false otherwise
*/
public boolean isRunning()
{
return state == State.RUNNING;
}
/**
* @return true if pipeline shut down has been initiated, false otherwise
*/
public boolean isStopping()
{
return state == State.STOPPING;
}
/**
* @return current SSJ version
*/
public static String getVersion()
{
return BuildConfig.VERSION_NAME;
}
/**
* Sets a handler for SSJ errors and crashes.
* The handler is notified every time an SSJException happens at runtime.
*
* @param h a class which implements the ExceptionHandler interface
*/
public void setExceptionHandler(ExceptionHandler h)
{
exceptionHandler = h;
}
}
| 38,711 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSJFatalException.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/SSJFatalException.java | /*
* SSJFatalException.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
/**
* Throwing this causes an immediate pipeline termination
* Created by Johnny on 20.10.2016.
*/
public class SSJFatalException extends Exception {
public SSJFatalException() {}
public SSJFatalException(String detailMessage) {
super(detailMessage);
}
public SSJFatalException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public SSJFatalException(Throwable throwable) {
super(throwable);
}
}
| 1,862 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Annotation.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Annotation.java | /*
* Annotation.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.os.Environment;
import android.util.SparseArray;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.SimpleXmlParser;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* Created by Johnny on 30.03.2017.
*/
public class Annotation
{
public class Entry
{
public String classlabel;
public double from;
public double to;
public float confidence = 1.0f;
public Entry(String classlabel, double from, double to)
{
this.classlabel = classlabel;
this.from = from;
this.to = to;
}
public Entry(String classlabel, double from, double to, float confidence)
{
this.classlabel = classlabel;
this.from = from;
this.to = to;
this.confidence = confidence;
}
}
private SparseArray<String> classes = new SparseArray<>();
private ArrayList<Entry> entries = new ArrayList<>();
private String name;
private String path;
private EventChannel channel = new EventChannel();
public Annotation()
{
clear();
}
public Annotation(Annotation original)
{
this.name = original.name;
this.path = original.path;
for(Entry e : original.getEntries())
{
this.getEntries().add(new Entry(e.classlabel, e.from, e.to));
}
this.classes = original.classes.clone();
}
public SparseArray<String> getClasses()
{
return classes;
}
/**
* @return an array of classes sorted by their IDs
*/
public String[] getClassArray()
{
int max_key = Integer.MIN_VALUE;
for (int i = 0; i < classes.size(); i++)
{
max_key = max(max_key, classes.keyAt(i));
}
String classes_array[] = new String[classes.size()];
for (int i = 0, j = 0; i <= max_key; i++)
{
String cl = classes.get(i);
if(cl != null)
classes_array[j++] = cl;
}
return classes_array;
}
public ArrayList<Entry> getEntries()
{
return entries;
}
public void setClasses(String[] cls)
{
this.classes.clear();
for (int i = 0; i < cls.length; i++)
{
this.classes.put(i, cls[i]);
}
}
public void addClass(int id, String anno)
{
this.classes.put(id, anno);
}
public void appendClass(String anno)
{
int id = 0;
if(classes.size() > 0)
id = classes.keyAt(classes.size()-1) +1; //one more than the id of the last element
this.classes.append(id, anno);
}
public void addEntry(String label, double from, double to)
{
addEntry(new Entry(label, from, to));
}
public void addEntry(Entry e)
{
this.entries.add(e);
}
public void removeClass(String anno)
{
int index = classes.indexOfValue(anno);
classes.removeAt(index);
}
public void clear()
{
name = "anno";
path = (Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "SSJ" + File.separator + "[time]");
entries.clear();
classes.clear();
}
public String getFileName()
{
return name;
}
public void setFileName(String name)
{
this.name = name;
}
public String getFilePath()
{
return path;
}
public void setFilePath(String path)
{
this.path = path;
}
public EventChannel getChannel()
{
return channel;
}
public void sort()
{
Collections.sort(entries, new Comparator<Entry>() {
@Override
public int compare(Entry lhs, Entry rhs)
{
if (lhs.from == rhs.from)
{
if (lhs.to < rhs.to)
return -1;
else if(lhs.to > rhs.to)
return 1;
else
return 0;
}
else
{
if (lhs.from < rhs.from)
return -1;
else if(lhs.from > rhs.from)
return 1;
else
return 0;
}
}
});
}
public boolean convertToFrames(double frame_s, String emptyClassName, double duration, double empty_percent)
{
if(entries == null || entries.size() == 0 || classes == null || classes.size() == 0)
return false;
boolean add_empty = emptyClassName != null;
if (duration <= 0)
{
duration = entries.get(entries.size()-1).to;
}
int n_frames = (int)(duration / frame_s);
double frame_dur = frame_s;
double frame_from = 0;
double frame_to = frame_dur;
HashMap<String, Double> percent_class = new HashMap<>();
double percent_garbage;
// copy labels and clear annotation
Annotation original = new Annotation(this);
original.sort();
entries.clear();
if(add_empty)
classes.put(Cons.GARBAGE_CLASS_ID, emptyClassName);
int iter = 0;
int last_iter = iter;
int clone_end = original.getEntries().size();
for (int i = 0; i < n_frames; i++)
{
Entry new_entry = new Entry(emptyClassName, frame_from, frame_from + frame_dur);
for (int j = 0; j < original.classes.size(); j++)
{
percent_class.put(original.classes.valueAt(j), 0.0);
}
percent_garbage = 0;
// skip labels before the current frame
iter = last_iter;
while (iter != clone_end && original.getEntries().get(iter).to < frame_from)
{
iter++;
last_iter++;
}
if (iter != clone_end)
{
boolean found_at_least_one = false;
// find all classes within the current frame
while (iter != clone_end && original.getEntries().get(iter).from < frame_to)
{
Entry e = original.getEntries().get(iter);
double dur = (min(frame_to, e.to) - max(frame_from, e.from)) / frame_dur;
if (e.classlabel == null)
{
percent_garbage += dur;
}
else
{
percent_class.put(e.classlabel, percent_class.get(e.classlabel) + dur);
}
iter++;
found_at_least_one = true;
}
if (found_at_least_one)
{
// find dominant class
double max_percent = percent_garbage;
double percent_sum = percent_garbage;
String max_class = null;
for (int j = 0; j < original.classes.size(); j++)
{
String cl = original.classes.valueAt(j);
if (max_percent < percent_class.get(cl))
{
max_class = cl;
max_percent = percent_class.get(cl);
}
percent_sum += percent_class.get(cl);
}
// add label
if (percent_sum > empty_percent && max_class != null)
{
new_entry.classlabel = max_class;
addEntry(new_entry);
}
else if (add_empty)
{
addEntry(new_entry);
}
}
else if (add_empty)
{
addEntry(new_entry);
}
}
else if (add_empty) {
addEntry(new_entry);
}
frame_from += frame_s;
frame_to += frame_s;
}
return true;
}
public void load() throws IOException, XmlPullParserException
{
load(path + File.separator + name);
}
public void load(String path) throws IOException, XmlPullParserException
{
if(path.endsWith(FileCons.FILE_EXTENSION_ANNO + FileCons.TAG_DATA_FILE))
{
path = path.substring(0, path.length()-2);
}
else if(!path.endsWith(FileCons.FILE_EXTENSION_ANNO))
{
path += "." + FileCons.FILE_EXTENSION_ANNO;
}
/*
* INFO
*/
SimpleXmlParser simpleXmlParser = new SimpleXmlParser();
SimpleXmlParser.XmlValues xmlValues = simpleXmlParser.parse(
new FileInputStream(new File(path)),
new String[]{"annotation", "info"},
new String[]{"size"}
);
/*
* SCHEME
*/
simpleXmlParser = new SimpleXmlParser();
xmlValues = simpleXmlParser.parse(
new FileInputStream(new File(path)),
new String[]{"annotation", "scheme"},
new String[]{"type"}
);
for(String[] scheme : xmlValues.foundAttributes)
{
if (!scheme[0].equalsIgnoreCase("DISCRETE"))
{
Log.e("unsupported annotation scheme: " + scheme[0]);
return;
}
}
/*
* SCHEME ITEMS
*/
simpleXmlParser = new SimpleXmlParser();
xmlValues = simpleXmlParser.parse(
new FileInputStream(new File(path)),
new String[]{"annotation", "scheme", "item"},
new String[]{"id", "name"}
);
for(String[] item : xmlValues.foundAttributes)
{
classes.put(Integer.valueOf(item[0]), item[1]); //id, name
}
loadData(path + FileCons.TAG_DATA_FILE);
}
private void loadData(String path) throws IOException, XmlPullParserException
{
InputStream inputStream = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while(line != null)
{
String[] tokens = line.split(FileCons.DELIMITER_ANNOTATION);
Entry e = new Entry(classes.get(Integer.valueOf(tokens[2])),
Double.valueOf(tokens[0]),
Double.valueOf(tokens[1]),
Float.valueOf(tokens[3]));
addEntry(e);
line = reader.readLine();
}
}
public void save() throws IOException, XmlPullParserException
{
save(path, name);
}
public void save(String path, String filename) throws IOException, XmlPullParserException
{
if(entries == null || entries.size() == 0 || classes == null || classes.size() == 0)
return;
File dir = Util.createDirectory(Util.parseWildcards(path));
if(dir == null)
return;
if(filename.endsWith(FileCons.FILE_EXTENSION_ANNO + FileCons.TAG_DATA_FILE))
{
filename = filename.substring(0, path.length()-2);
}
else if(!filename.endsWith(FileCons.FILE_EXTENSION_ANNO))
{
filename += "." + FileCons.FILE_EXTENSION_ANNO;
}
StringBuilder builder = new StringBuilder();
builder.append("<annotation ssi-v=\"3\" ssj-v=\"");
builder.append(Pipeline.getVersion());
builder.append("\">").append(FileCons.DELIMITER_LINE);
builder.append("<info ftype=\"ASCII\" size=\"");
builder.append(classes.size());
builder.append("\"/>").append(FileCons.DELIMITER_LINE);
builder.append("<scheme name=\"ssj\" type=\"DISCRETE\">").append(FileCons.DELIMITER_LINE);
for(int i = 0; i < classes.size(); ++i)
{
builder.append("<item name=\"");
builder.append(classes.valueAt(i));
builder.append("\" id=\"");
builder.append(classes.keyAt(i));
builder.append("\"/>").append(FileCons.DELIMITER_LINE);
}
builder.append("</scheme>").append(FileCons.DELIMITER_LINE);
builder.append("</annotation>").append(FileCons.DELIMITER_LINE);
OutputStream ouputStream = new FileOutputStream(new File(dir, filename));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ouputStream));
writer.write(builder.toString());
writer.flush();
writer.close();
saveData(dir.getAbsolutePath() + File.separator + filename + FileCons.TAG_DATA_FILE);
}
private void saveData(String path) throws IOException, XmlPullParserException
{
OutputStream ouputStream = new FileOutputStream(new File(path));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ouputStream));
StringBuilder builder = new StringBuilder();
for(Entry e : entries)
{
builder.delete(0, builder.length());
builder.append(e.from).append(FileCons.DELIMITER_ANNOTATION);
builder.append(e.to).append(FileCons.DELIMITER_ANNOTATION);
int class_index = classes.indexOfValue(e.classlabel);
builder.append(classes.keyAt(class_index)).append(FileCons.DELIMITER_ANNOTATION);
builder.append(e.confidence);
writer.write(builder.toString());
writer.newLine();
}
writer.flush();
writer.close();
}
}
| 12,697 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
NetworkSync.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/NetworkSync.java | /*
* ClockSync.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* Created by Johnny on 25.01.2017.
*/
class NetworkSync {
private final int NUM_REPETITIONS = 10;
private class SyncListener implements Runnable
{
boolean terminate = false;
int port = 0;
long delta, rtt;
byte[] data = new byte[64];
SyncListener(int port)
{
this.port = port;
data = new byte[64];
}
public long getDelta()
{
return delta;
}
public void reset()
{
delta = 0;
rtt = Long.MAX_VALUE;
}
public void terminate()
{
terminate = true;
}
@Override
public void run()
{
long[] tmp = new long[2];
byte[] data = new byte[29];
while(!terminate)
{
try
{
DatagramPacket packet = new DatagramPacket(data, data.length);
recvSocket.receive(packet);
//check data
byte[] msg = packet.getData();
String str = new String(msg, "ASCII");
Log.d("received packet from " + packet.getAddress().toString() + ": " + str);
if (type == Pipeline.SyncType.CONTINUOUS && str.startsWith("SSI:SYNC:TIME")) //SSI format for compatibility
{
Log.d("packet identified as timestamp from master");
Util.arraycopy(msg, 13, tmp, 0, 8);
Util.arraycopy(msg, 21, tmp, 8, 8);
long time_send = tmp[0];
long time_master = tmp[1];
long time_recv = frame.getTimeMs();
Log.d("t_master: " + time_master + "\nt_send: " + time_send + "\nt_recv: " + time_recv);
if(time_recv - time_send < rtt)
{
rtt = time_recv - time_send;
delta = time_master - time_recv + rtt/2;
Log.d("delta: " + delta);
}
}
else if(type == Pipeline.SyncType.CONTINUOUS && isMaster && str.startsWith("SSI:SYNC:RQST"))
{
Log.d("packet identified as time request from slave");
tmp[0] = frame.getTimeMs();
//append local (master) time to message, final form: TAG(13) + slave_time(8) + master_time(8)
System.arraycopy("SSI:SYNC:TIME".getBytes("ASCII"), 0, data, 0, 13);
Util.arraycopy(tmp, 0, data, 21, 8);
Log.d("sending time to slave ("+packet.getAddress().toString()+"): " + tmp[0]);
send(data, packet.getAddress());
}
else if (!isMaster && str.startsWith("SSI:STRT"))
{
if(!str.startsWith("SSI:STRT:RUN1"))
Log.w("Only RUN & QUIT is currently supported.");
Log.d("packet identified as start ping");
synchronized (waitForStartMonitor)
{
waitForStart = false;
waitForStartMonitor.notifyAll();
}
}
else if (!isMaster && str.startsWith("SSI:STOP"))
{
if(str.startsWith("SSI:STOP:RUNN"))
Log.w("Restart is not currently supported, stopping pipeline.");
Log.d("packet identified as stop ping");
synchronized (waitForStopMonitor)
{
waitForStop = false;
waitForStopMonitor.notifyAll();
}
}
}
catch (IOException e) {
Log.e("error in network sync", e);
}
}
}
}
private class SyncSender implements Runnable
{
boolean terminate = false;
private Timer timer;
SyncSender(int interval)
{
timer = new Timer(interval);
}
public void terminate()
{
terminate = true;
}
@Override
public void run() {
byte[] data = new byte[21];
long[] tmp = new long[1];
while(!terminate)
{
if(frame.isRunning())
{
frame.adjustTime(listener.getDelta());
listener.reset();
//request new time
for(int i = 0; i< NUM_REPETITIONS; i++)
{
try
{
//send current time with message
tmp[0] = frame.getTimeMs();
System.arraycopy("SSI:SYNC:RQST".getBytes("ASCII"), 0, data, 0, 13);
Util.arraycopy(tmp, 0, data, 13, 8);
send(data, hostAddr);
}
catch (IOException e)
{
Log.e("error sending sync message", e);
}
}
}
timer.sync();
}
}
}
private Pipeline frame;
private DatagramSocket sendSocket;
private DatagramSocket recvSocket;
private boolean isMaster = true;
private InetAddress hostAddr;
private int port;
private SyncListener listener;
private SyncSender sender;
private Pipeline.SyncType type;
private boolean waitForStart = false;
private boolean waitForStop = false;
final private Object waitForStartMonitor = new Object();
final private Object waitForStopMonitor = new Object();
public NetworkSync(Pipeline.SyncType type, boolean isMaster, InetAddress masterAddr, int port, int interval)
{
frame = Pipeline.getInstance();
this.isMaster = isMaster;
this.hostAddr = masterAddr;
this.port = port;
this.type = type;
try {
sendSocket = new DatagramSocket();
recvSocket = new DatagramSocket(port);
sendSocket.setReuseAddress(true);
recvSocket.setReuseAddress(true);
} catch (SocketException e) {
Log.e("error setting up network sync", e);
}
listener = new SyncListener(port);
new Thread(listener).start();
if(type == Pipeline.SyncType.CONTINUOUS && interval > 0 && !isMaster)
{
sender = new SyncSender(interval);
new Thread(sender).start();
}
}
private void send(byte[] data, InetAddress addr) throws IOException
{
DatagramPacket packet = new DatagramPacket(data, data.length, addr, port);
sendSocket.send(packet);
}
public void waitForStartSignal()
{
synchronized (waitForStartMonitor)
{
waitForStart = true;
while (waitForStart && frame.getState() != Pipeline.State.STOPPING && frame.getState() != Pipeline.State.INACTIVE)
{
try
{
waitForStartMonitor.wait();
}
catch (InterruptedException e)
{
}
}
}
}
public void waitForStopSignal()
{
synchronized (waitForStopMonitor)
{
waitForStop = true;
while (waitForStop && frame.getState() != Pipeline.State.STOPPING && frame.getState() != Pipeline.State.INACTIVE)
{
try
{
waitForStopMonitor.wait();
}
catch (InterruptedException e)
{}
}
}
}
public void release()
{
if(sender != null)
sender.terminate();
listener.terminate();
synchronized (waitForStartMonitor)
{
waitForStart = false;
waitForStartMonitor.notifyAll();
}
synchronized (waitForStopMonitor)
{
waitForStop = false;
waitForStopMonitor.notifyAll();
}
}
static void sendStartSignal(int port)
{
try
{
DatagramSocket syncSocket = new DatagramSocket(null);
syncSocket.setReuseAddress(true);
syncSocket.setBroadcast(true);
String msg = "SSI:STRT:RUN1\0"; //send in SSI format for compatibility
byte[] data = msg.getBytes("ASCII");
DatagramPacket packet = new DatagramPacket(data, data.length, Util.getBroadcastAddress(), port);
syncSocket.send(packet);
Log.i("start signal sent on port " + port);
}
catch(IOException e)
{
Log.e("network sync failed", e);
}
}
static void sendStopSignal(int port)
{
try
{
DatagramSocket syncSocket = new DatagramSocket(null);
syncSocket.setReuseAddress(true);
syncSocket.setBroadcast(true);
String msg = "SSI:STOP:QUIT\0"; //send in SSI format for compatibility
byte[] data = msg.getBytes("ASCII");
DatagramPacket packet = new DatagramPacket(data, data.length, Util.getBroadcastAddress(), port);
syncSocket.send(packet);
Log.i("stop signal sent on port " + port);
}
catch(IOException e)
{
Log.e("network sync failed", e);
}
}
}
| 11,406 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PipelineStateListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/PipelineStateListener.java | /*
* PipelineStateListener.java
* Copyright (c) 2020
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
/**
* Created by Michael Dietz on 25.09.2020.
*/
public interface PipelineStateListener
{
void stateUpdated(Pipeline.State state);
}
| 1,518 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LimitedSizeQueue.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/LimitedSizeQueue.java | /*
* LimitedSizeQueue.java
* Copyright (c) 2020
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.util.ArrayList;
/**
* Custom implementation of a LIFO queue with fixed size.
* Taken from <a href="https://stackoverflow.com/questions/1963806/is-there-a-fixed-sized-queue-which-removes-excessive-elements">here</a>.
*
* Created by Michael Dietz on 09.01.2020.
*/
public class LimitedSizeQueue<K> extends ArrayList<K>
{
private int maxSize;
public LimitedSizeQueue(int size)
{
this.maxSize = size;
}
public boolean add(K k)
{
boolean r = super.add(k);
if (size() > maxSize)
{
removeRange(0, size() - maxSize);
}
return r;
}
public K getYoungest()
{
return get(size() - 1);
}
public K getOldest()
{
return get(0);
}
} | 2,046 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Util.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Util.java | /*
* Util.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 26.03.2015.
*/
public class Util
{
public static int sizeOf(Cons.Type type)
{
switch(type)
{
case CHAR:
return 2;
case SHORT:
return 2;
case INT:
return 4;
case LONG:
return 8;
case FLOAT:
return 4;
case DOUBLE:
return 8;
case IMAGE:
return 1;
case BYTE:
return 1;
case BOOL:
return 1;
}
return 0;
}
public static int sizeOf(byte x)
{
return 1;
}
public static int sizeOf(char x)
{
return 2;
}
public static int sizeOf(short x)
{
return 2;
}
public static int sizeOf(int x)
{
return 4;
}
public static int sizeOf(long x)
{
return 8;
}
public static int sizeOf(float x)
{
return 4;
}
public static int sizeOf(double x)
{
return 8;
}
public static int sizeOf(boolean x)
{
return 1;
}
public static double max(double[] data, int offset, int len)
{
double max = Double.MIN_VALUE;
for (int i = offset; i < offset + len; i++)
if (data[i] > max)
max = data[i];
return max;
}
public static float max(float[] data, int offset, int len)
{
float max = Float.MIN_VALUE;
for (int i = offset; i < offset + len; i++)
if (data[i] > max)
max = data[i];
return max;
}
public static double min(double[] data, int offset, int len)
{
double min = Double.MAX_VALUE;
for (int i = offset; i < offset + len; i++)
if (data[i] < min)
min = data[i];
return min;
}
public static float min(float[] data, int offset, int len)
{
float min = Float.MAX_VALUE;
for (int i = offset; i < offset + len; i++)
if (data[i] < min)
min = data[i];
return min;
}
public static double mean(double[] data, int offset, int len)
{
if (data.length == 0)
return 0;
double sum = 0;
for (int i = offset; i < offset + len; i++)
sum += data[i];
return sum / data.length;
}
public static float mean(float[] data, int offset, int len)
{
if (data.length == 0)
return 0;
float sum = 0;
for (int i = offset; i < offset + len; i++)
sum += data[i];
return sum / data.length;
}
public static double median(double[] data, int offset, int len)
{
Arrays.sort(data, offset, offset + len);
double median;
if (len % 2 == 0)
median = (data[offset + len / 2] + data[offset + len / 2 - 1]) / 2;
else
median = data[offset + len / 2];
return median;
}
public static float median(float[] data, int offset, int len)
{
Arrays.sort(data, offset, offset + len);
float median;
if (len % 2 == 0)
median = (data[offset + len / 2] + data[offset + len / 2 - 1]) / 2;
else
median = data[offset + len / 2];
return median;
}
/**
* Copy an array from src to dst.
* Types do not need to match (currently only BYTE - ANY and ANY - BYTE is supported)
*
* ByteOrder: Little-Endian
*
* @param src source array
* @param srcPosBytes position in source array
* @param dst destination array
* @param dstPosBytes position in destination array
* @param numBytes number of bytes to copy
*/
public static void arraycopy(Object src, int srcPosBytes, Object dst, int dstPosBytes, int numBytes)
{
if (src == null) {
throw new NullPointerException("src == null");
}
if (dst == null) {
throw new NullPointerException("dst == null");
}
if(src instanceof byte[])
{
if(dst instanceof byte[]) System.arraycopy((byte[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof char[]) arraycopy((byte[]) src, srcPosBytes, (char[]) dst, dstPosBytes, numBytes);
else if(dst instanceof short[]) arraycopy((byte[]) src, srcPosBytes, (short[]) dst, dstPosBytes, numBytes);
else if(dst instanceof int[]) arraycopy((byte[]) src, srcPosBytes, (int[]) dst, dstPosBytes, numBytes);
else if(dst instanceof long[]) arraycopy((byte[]) src, srcPosBytes, (long[]) dst, dstPosBytes, numBytes);
else if(dst instanceof float[]) arraycopy((byte[]) src, srcPosBytes, (float[]) dst, dstPosBytes, numBytes);
else if(dst instanceof double[]) arraycopy((byte[]) src, srcPosBytes,(double[]) dst, dstPosBytes, numBytes);
else if(dst instanceof boolean[]) arraycopy((byte[]) src, srcPosBytes, (boolean[]) dst, dstPosBytes, numBytes);
else throw new UnsupportedOperationException();
}
else if(src instanceof char[])
{
if(dst instanceof byte[]) arraycopy((char[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof char[]) System.arraycopy((char[]) src, srcPosBytes / 2, (char[]) dst, dstPosBytes, numBytes / 2);
else throw new UnsupportedOperationException();
}
else if(src instanceof short[])
{
if(dst instanceof byte[]) arraycopy((short[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof short[]) System.arraycopy((short[]) src, srcPosBytes / 2, (short[]) dst, dstPosBytes, numBytes / 2);
else throw new UnsupportedOperationException();
}
else if(src instanceof int[])
{
if(dst instanceof byte[]) arraycopy((int[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof int[]) System.arraycopy((int[]) src, srcPosBytes / 4, (int[]) dst, dstPosBytes, numBytes / 4);
else throw new UnsupportedOperationException();
}
else if(src instanceof long[])
{
if(dst instanceof byte[]) arraycopy((long[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof long[]) System.arraycopy((long[]) src, srcPosBytes / 8, (long[]) dst, dstPosBytes, numBytes / 8);
else throw new UnsupportedOperationException();
}
else if(src instanceof float[])
{
if(dst instanceof byte[]) arraycopy((float[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof float[]) System.arraycopy((float[]) src, srcPosBytes / 4, (float[]) dst, dstPosBytes, numBytes / 4);
else throw new UnsupportedOperationException();
}
else if(src instanceof double[])
{
if(dst instanceof byte[]) arraycopy((double[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof double[]) System.arraycopy((double[]) src, srcPosBytes / 8, (double[]) dst, dstPosBytes, numBytes / 8);
else throw new UnsupportedOperationException();
}
else if(src instanceof boolean[])
{
if(dst instanceof byte[]) arraycopy((boolean[]) src, srcPosBytes, (byte[]) dst, dstPosBytes, numBytes);
else if(dst instanceof boolean[]) System.arraycopy((boolean[]) src, srcPosBytes, (boolean[]) dst, dstPosBytes, numBytes / sizeOf(Cons.Type.BOOL));
else throw new UnsupportedOperationException();
}
else throw new UnsupportedOperationException();
}
private static void arraycopy(byte[] src, int srcPosBytes, char[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || numBytes > dst.length * 2 - dstPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int iter = dstPosBytes / 2;
for (int i = 0; i < numBytes; i += 2) {
dst[iter++] = (char)((src[srcPosBytes++] & 0xFF) | (src[srcPosBytes++] & 0xFF) << 8);
}
}
private static void arraycopy(char[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || dstPosBytes > dst.length - numBytes || numBytes > src.length * 2 - srcPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
char bits;
int iter = srcPosBytes / 2;
for (int i = 0; i < numBytes; i += 2)
{
bits = src[iter++];
dst[dstPosBytes++] = (byte)bits;
dst[dstPosBytes++] = (byte)(bits >> 8);
}
}
private static void arraycopy(byte[] src, int srcPosBytes, float[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || numBytes > dst.length * 4 - dstPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int iter = dstPosBytes / 4;
for (int i = 0; i < numBytes; i += 4) {
dst[iter++] = Float.intBitsToFloat((src[srcPosBytes++] & 0xFF)
| (src[srcPosBytes++] & 0xFF) << 8
| (src[srcPosBytes++] & 0xFF) << 16
| (src[srcPosBytes++] & 0xFF) << 24);
}
}
private static void arraycopy(float[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || dstPosBytes > dst.length - numBytes || numBytes > src.length * 4 - srcPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int bits;
int iter = srcPosBytes / 4;
for (int i = 0; i < numBytes; i += 4)
{
bits = Float.floatToIntBits(src[iter++]);
dst[dstPosBytes++] = (byte)bits;
dst[dstPosBytes++] = (byte)(bits >> 8);
dst[dstPosBytes++] = (byte)(bits >> 16);
dst[dstPosBytes++] = (byte)(bits >> 24);
}
}
private static void arraycopy(byte[] src, int srcPosBytes, double[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || numBytes > dst.length * 8 - dstPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int iter = dstPosBytes / 8;
for (int i = 0; i < numBytes; i += 8) {
dst[iter++] = Double.longBitsToDouble(
(src[srcPosBytes++] & (long) 0xFF)
| (src[srcPosBytes++] & (long) 0xFF) << 8
| (src[srcPosBytes++] & (long) 0xFF) << 16
| (src[srcPosBytes++] & (long) 0xFF) << 24
| (src[srcPosBytes++] & (long) 0xFF) << 32
| (src[srcPosBytes++] & (long) 0xFF) << 40
| (src[srcPosBytes++] & (long) 0xFF) << 48
| (src[srcPosBytes++] & (long) 0xFF) << 56);
}
}
private static void arraycopy(double[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || dstPosBytes > dst.length - numBytes || numBytes > src.length * 8 - srcPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
long bits;
int iter = srcPosBytes / 8;
for (int i = 0; i < numBytes; i += 8)
{
bits = Double.doubleToLongBits(src[iter++]);
dst[dstPosBytes++] = (byte)bits;
dst[dstPosBytes++] = (byte)(bits >> 8);
dst[dstPosBytes++] = (byte)(bits >> 16);
dst[dstPosBytes++] = (byte)(bits >> 24);
dst[dstPosBytes++] = (byte)(bits >> 32);
dst[dstPosBytes++] = (byte)(bits >> 40);
dst[dstPosBytes++] = (byte)(bits >> 48);
dst[dstPosBytes++] = (byte)(bits >> 56);
}
}
private static void arraycopy(byte[] src, int srcPosBytes, short[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || numBytes > dst.length * 2 - dstPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int iter = dstPosBytes / 2;
for (int i = 0; i < numBytes; i += 2) {
dst[iter++] = (short)((src[srcPosBytes++] & 0xFF) | (src[srcPosBytes++] & 0xFF) << 8);
}
}
private static void arraycopy(short[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || dstPosBytes > dst.length - numBytes || numBytes > src.length * 2 - srcPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
short bits;
int iter = srcPosBytes / 2;
for (int i = 0; i < numBytes; i += 2)
{
bits = src[iter++];
dst[dstPosBytes++] = (byte)bits;
dst[dstPosBytes++] = (byte)(bits >> 8);
}
}
private static void arraycopy(byte[] src, int srcPosBytes, int[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || numBytes > dst.length * 4 - dstPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int iter = dstPosBytes / 4;
for (int i = 0; i < numBytes; i += 4) {
dst[iter++] = (src[srcPosBytes++] & 0xFF)
| (src[srcPosBytes++] & 0xFF) << 8
| (src[srcPosBytes++] & 0xFF) << 16
| (src[srcPosBytes++] & 0xFF) << 24;
}
}
private static void arraycopy(int[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || dstPosBytes > dst.length - numBytes || numBytes > src.length * 4 - srcPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int bits;
int iter = srcPosBytes / 4;
for (int i = 0; i < numBytes; i += 4)
{
bits = src[iter++];
dst[dstPosBytes++] = (byte)bits;
dst[dstPosBytes++] = (byte)(bits >> 8);
dst[dstPosBytes++] = (byte)(bits >> 16);
dst[dstPosBytes++] = (byte)(bits >> 24);
}
}
private static void arraycopy(byte[] src, int srcPosBytes, long[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || numBytes > dst.length * 8 - dstPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
int iter = dstPosBytes / 8;
for (int i = 0; i < numBytes; i += 8) {
dst[iter++] = (src[srcPosBytes++] & (long) 0xFF)
| (src[srcPosBytes++] & (long) 0xFF) << 8
| (src[srcPosBytes++] & (long) 0xFF) << 16
| (src[srcPosBytes++] & (long) 0xFF) << 24
| (src[srcPosBytes++] & (long) 0xFF) << 32
| (src[srcPosBytes++] & (long) 0xFF) << 40
| (src[srcPosBytes++] & (long) 0xFF) << 48
| (src[srcPosBytes++] & (long) 0xFF) << 56;
}
}
private static void arraycopy(long[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || dstPosBytes > dst.length - numBytes || numBytes > src.length * 8 - srcPosBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
long bits;
int iter = srcPosBytes / 8;
for (int i = 0; i < numBytes; i += 8)
{
bits = src[iter++];
dst[dstPosBytes++] = (byte)bits;
dst[dstPosBytes++] = (byte)(bits >> 8);
dst[dstPosBytes++] = (byte)(bits >> 16);
dst[dstPosBytes++] = (byte)(bits >> 24);
dst[dstPosBytes++] = (byte)(bits >> 32);
dst[dstPosBytes++] = (byte)(bits >> 40);
dst[dstPosBytes++] = (byte)(bits >> 48);
dst[dstPosBytes++] = (byte)(bits >> 56);
}
}
private static void arraycopy(byte[] src, int srcPosBytes, boolean[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || dstPosBytes > dst.length - numBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
for (int i = 0; i < numBytes; ++i) dst[dstPosBytes + i] = src[srcPosBytes + i] != 0;
}
private static void arraycopy(boolean[] src, int srcPosBytes, byte[] dst, int dstPosBytes, int numBytes)
{
if (srcPosBytes < 0 || dstPosBytes < 0 || numBytes < 0 || srcPosBytes > src.length - numBytes || dstPosBytes > dst.length - numBytes)
throw new ArrayIndexOutOfBoundsException("src.length=" + src.length + " srcPosBytes=" + srcPosBytes +
" dst.length=" + dst.length + " dstPosBytes=" + dstPosBytes + " numBytes=" + numBytes);
for (int i = 0; i < numBytes; ++i) dst[dstPosBytes + i] = src[srcPosBytes + i] ? (byte)1 : 0;
}
/**
* Fill array with zeroes
*
* @param arr source array
* @param posSamples position in samples of first element to be of bytes to copy
* @param numSamples number of zero samples to write
*/
public static void fillZeroes(Object arr, int posSamples, int numSamples)
{
if (arr == null) {
throw new NullPointerException("src == null");
}
if(arr instanceof byte[])
{
for (int i = 0; i < numSamples; ++i) ((byte[])arr)[posSamples + i] = 0;
}
else if(arr instanceof char[])
{
for (int i = 0; i < numSamples; ++i) ((char[])arr)[posSamples + i] = 0;
}
else if(arr instanceof short[])
{
for (int i = 0; i < numSamples; ++i) ((short[])arr)[posSamples + i] = 0;
}
else if(arr instanceof int[])
{
for (int i = 0; i < numSamples; ++i) ((int[])arr)[posSamples + i] = 0;
}
else if(arr instanceof long[])
{
for (int i = 0; i < numSamples; ++i) ((long[])arr)[posSamples + i] = 0;
}
else if(arr instanceof float[])
{
for (int i = 0; i < numSamples; ++i) ((float[])arr)[posSamples + i] = 0;
}
else if(arr instanceof double[])
{
for (int i = 0; i < numSamples; ++i) ((double[])arr)[posSamples + i] = 0;
}
else if(arr instanceof boolean[])
{
for (int i = 0; i < numSamples; ++i) ((boolean[])arr)[posSamples + i] = false;
}
else throw new UnsupportedOperationException();
}
public static byte[] serialize(Object obj) {
try
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static Object deserialize(byte[] bytes) {
try
{
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
catch (IOException | ClassNotFoundException e)
{
throw new RuntimeException(e);
}
}
public static String xmlToString(XmlPullParser parser) throws XmlPullParserException, IOException
{
if (parser.getEventType() == XmlPullParser.TEXT)
{
return parser.getText();
}
int depth = parser.getDepth();
String tag;
StringBuilder str = new StringBuilder();
do
{
if (parser.getEventType() == XmlPullParser.START_TAG)
{
str.append("<").append(parser.getName());
//add attributes
for (int i = 0; i < parser.getAttributeCount(); ++i)
str.append(" ").append(parser.getAttributeName(i)).append("=").append("\"").append(parser.getAttributeValue(i)).append("\"");
str.append(">");
//go deeper
parser.next();
str.append(xmlToString(parser));
}
if (parser.getEventType() == XmlPullParser.END_TAG)
{
str.append("</").append(parser.getName()).append(">");
}
parser.next();
}
while (parser.getEventType() != XmlPullParser.END_DOCUMENT && parser.getDepth() >= depth);
return str.toString();
}
public static float calcSampleRate(Transformer t, Stream stream_in)
{
double dur = stream_in.num * stream_in.step;
return (float)(t.getSampleNumber(stream_in.num) / dur);
}
/**
* Get IP address from first non-localhost interface
*
* @param useIPv4 true=return ipv4, false=return ipv6
* @return Address or empty string
* @throws SocketException Socket exception
*/
public static String getIPAddress(boolean useIPv4) throws SocketException
{
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
//for google glass: interface is named wlan0
String name = intf.getName();
if(!name.contains("wlan"))
continue;
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = addr instanceof Inet4Address;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 port suffix
return delim<0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
return "";
}
public static InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = (WifiManager)SSJApplication.getAppContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
if(dhcp == null)
throw new IOException("dhcp is null");
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
/**
* Casts values from a stream array to a float array.
*
* @param stream Stream
* @param floats float[]
*/
public static void castStreamPointerToFloat(Stream stream, float[] floats)
{
switch (stream.type)
{
case CHAR:
char[] chars = stream.ptrC();
for (int i = 0; i < floats.length; i++)
{
floats[i] = (float) chars[i];
}
break;
case SHORT:
short[] shorts = stream.ptrS();
for (int i = 0; i < floats.length; i++)
{
floats[i] = (float) shorts[i];
}
break;
case INT:
int[] ints = stream.ptrI();
for (int i = 0; i < floats.length; i++)
{
floats[i] = (float) ints[i];
}
break;
case LONG:
long[] longs = stream.ptrL();
for (int i = 0; i < floats.length; i++)
{
floats[i] = (float) longs[i];
}
break;
case FLOAT:
System.arraycopy(stream.ptrF(), 0, floats, 0, floats.length);
break;
case DOUBLE:
double[] doubles = stream.ptrD();
for (int i = 0; i < floats.length; i++)
{
floats[i] = (float) doubles[i];
}
break;
default:
Log.e("invalid input stream type");
break;
}
}
public static String getTimestamp(long time_ms)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault());
Date sessionStart = new Date();
sessionStart.setTime(time_ms);
return dateFormat.format(sessionStart);
}
public static synchronized File createDirectory(String path)
{
File fileDirectory = new File(path);
if (!fileDirectory.exists())
{
if (!fileDirectory.mkdirs())
{
//check again, perhaps another thread created it
Log.e(fileDirectory.getName() + " could not be created");
return null;
}
}
return fileDirectory;
}
public static String parseWildcards(String value)
{
if (value != null)
{
if (value.contains("[time]"))
{
return value.replace("[time]", Util.getTimestamp(Pipeline.getInstance().getCreateTimeMs()));
}
else
{
return value;
}
}
else
{
return null;
}
}
public static void eventToXML(StringBuilder builder, Event ev)
{
eventToXML(builder, ev, false, null);
}
public static void eventToXML(StringBuilder builder, Event ev, boolean sendAsMap, String[] mapKeys)
{
builder.append("<event sender=\"").append(ev.sender).append("\"");
builder.append(" event=\"").append(ev.name).append("\"");
builder.append(" from=\"").append(ev.time).append("\"");
builder.append(" dur=\"").append(ev.dur).append("\"");
builder.append(" prob=\"1.00000\"");
builder.append(" type=\"");
if (sendAsMap && ev.type != Cons.Type.STRING)
{
builder.append("map");
}
else
{
builder.append(ev.type);
}
builder.append("\"");
builder.append(" state=\"").append(ev.state).append("\"");
builder.append(" glue=\"0\">");
switch (ev.type)
{
case BYTE:
{
byte[] data = ev.ptrB();
for (int i = 0; i < data.length; i++)
{
if (sendAsMap)
{
addTupleBefore(builder, mapKeys, i);
}
builder.append(data[i]);
if (sendAsMap)
{
builder.append("\"></tuple>");
}
else
{
if (i < data.length - 1)
{
builder.append(" ");
}
}
}
break;
}
case SHORT:
{
short[] data = ev.ptrShort();
for (int i = 0; i < data.length; i++)
{
if (sendAsMap)
{
addTupleBefore(builder, mapKeys, i);
}
builder.append(data[i]);
if (sendAsMap)
{
builder.append("\"></tuple>");
}
else
{
if (i < data.length - 1)
{
builder.append(" ");
}
}
}
break;
}
case INT:
{
int[] data = ev.ptrI();
for (int i = 0; i < data.length; i++)
{
if (sendAsMap)
{
addTupleBefore(builder, mapKeys, i);
}
builder.append(data[i]);
if (sendAsMap)
{
builder.append("\"></tuple>");
}
else
{
if (i < data.length - 1)
{
builder.append(" ");
}
}
}
break;
}
case LONG:
{
long[] data = ev.ptrL();
for (int i = 0; i < data.length; i++)
{
if (sendAsMap)
{
addTupleBefore(builder, mapKeys, i);
}
builder.append(data[i]);
if (sendAsMap)
{
builder.append("\"></tuple>");
}
else
{
if (i < data.length - 1)
{
builder.append(" ");
}
}
}
break;
}
case FLOAT:
{
float[] data = ev.ptrF();
for (int i = 0; i < data.length; i++)
{
if (sendAsMap)
{
addTupleBefore(builder, mapKeys, i);
}
builder.append(data[i]);
if (sendAsMap)
{
builder.append("\"></tuple>");
}
else
{
if (i < data.length - 1)
{
builder.append(" ");
}
}
}
break;
}
case DOUBLE:
{
double[] data = ev.ptrD();
for (int i = 0; i < data.length; i++)
{
if (sendAsMap)
{
addTupleBefore(builder, mapKeys, i);
}
builder.append(data[i]);
if (sendAsMap)
{
builder.append("\"></tuple>");
}
else
{
if (i < data.length - 1)
{
builder.append(" ");
}
}
}
break;
}
case STRING:
builder.append(ev.ptrStr());
break;
}
builder.append("</event>");
}
private static void addTupleBefore(StringBuilder builder, String[] mapKeys, int i)
{
builder.append("<tuple string=\"");
if (mapKeys != null && i < mapKeys.length)
{
builder.append(mapKeys[i].trim());
}
else
{
builder.append("value-").append(i);
}
builder.append("\" value=\"");
}
/**
* Helper function to format fft values similar to SSI
*
* @param in Input array
* @param out Output array
*/
public static void joinFFT(float[] in, float[] out)
{
for (int i = 0; i < in.length; i += 2)
{
if (i == 0)
{
out[0] = (float) Math.sqrt(Math.pow(in[0], 2));
out[out.length - 1] = (float) Math.sqrt(Math.pow(in[1], 2));
}
else
{
out[i / 2] = (float) Math.sqrt(Math.pow(in[i], 2) + Math.pow(in[i + 1], 2));
}
}
}
/**
* Returns index of element with the highest value in float array.
*
* @param array Float array.
* @return Index of element with the highest value.
*/
public static int maxIndex(float[] array) {
int best = 0;
for (int i = 1; i < array.length; ++i) {
if (array[i] > array[best]) {
best = i;
}
}
return best;
}
}
| 38,047 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Transformer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Transformer.java | /*
* Transformer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.os.PowerManager;
import java.util.Arrays;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 05.03.2015.
*/
public abstract class Transformer extends Provider {
private Stream[] _stream_in;
private int[] _bufferID_in;
private int[] _readPos;
private int[] _num_frame;
private int[] _num_delta;
private Timer _timer;
protected Pipeline _frame;
public Transformer()
{
_frame = Pipeline.getInstance();
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
if(!_isSetup) {
_frame.error(this.getComponentName(), "not initialized", null);
return;
}
android.os.Process.setThreadPriority(threadPriority);
PowerManager mgr = (PowerManager)SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, _name);
//clear data
Arrays.fill(_readPos, 0);
for(int i = 0; i < _stream_in.length; i++)
_stream_in[i].reset();
try {
enter(_stream_in, _stream_out);
} catch(SSJFatalException e) {
_frame.error(this.getComponentName(), "exception in enter", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in enter", e);
}
//wait for framework
while (!_terminate && !_frame.isRunning()) {
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
//maintain update rate starting from now
_timer.reset();
while(!_terminate && _frame.isRunning())
{
try {
wakeLock.acquire();
//grab data
boolean ok = true;
for(int i = 0; i < _bufferID_in.length; i++)
{
ok &= _frame.getData(_bufferID_in[i], _stream_in[i].ptr(), _readPos[i],
_stream_in[i].num);
if(ok)
_stream_in[i].time = (double)_readPos[i] / _stream_in[i].sr;
_readPos[i] += _num_frame[i];
}
//if we received data from all sources, process it
if(ok) {
transform(_stream_in, _stream_out);
_frame.pushData(_bufferID, _stream_out.ptr(), _stream_out.tot);
}
if(ok) {
//maintain update rate
_timer.sync();
}
} catch(SSJFatalException e) {
_frame.error(this.getComponentName(), "exception in loop", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in loop", e);
} finally {
wakeLock.release();
}
}
try {
flush(_stream_in, _stream_out);
} catch(Exception e) {
_frame.error(this.getComponentName(), "exception in flush", e);
}
_safeToKill = true;
}
/**
* Early initialization specific to implementation (called by framework on instantiation)
*
* @param frame frame size
* @param delta delta size
* @throws SSJException exception
*/
public void init(double frame, double delta) throws SSJException {}
/**
* Initialization specific to sensor implementation (called by local thread after framework start)
*
* @param stream_in Input streams
* @param stream_out Output stream
* @throws SSJFatalException Exception
*/
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException {}
/**
* Main processing method
*
* @param stream_in Input streams
* @param stream_out Output stream
* @throws SSJFatalException Exception
*/
public abstract void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException;
/**
* Called once prior to termination
*
* @param stream_in Input streams
* @param stream_out Output stream
* @throws SSJFatalException Exception
*/
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException {}
/**
* General transformer initialization
*
* @param sources Providers
* @param frame Frame size
* @param delta Delta size
* @throws SSJException Exception
*/
public final void setup(Provider[] sources, double frame, double delta) throws SSJException
{
for (Provider source : sources)
{
if (!source.isSetup())
{
throw new SSJException("Components must be added in the correct order. Cannot add " + _name + " before its source " + source.getComponentName());
}
}
try {
_bufferID_in = new int[sources.length];
_stream_in = new Stream[sources.length];
_readPos = new int[sources.length];
_num_frame = new int[sources.length];
_num_delta = new int[sources.length];
//compute window sizes
for (int i = 0; i < sources.length; i++) {
_num_frame[i] = (int) (frame * sources[i].getOutputStream().sr + 0.5);
_num_delta[i] = (int) (delta * sources[i].getOutputStream().sr + 0.5);
}
frame = (double) _num_frame[0] / sources[0].getOutputStream().sr;
delta = (double) _num_delta[0] / sources[0].getOutputStream().sr;
if (frame == 0)
throw new SSJException("frame size too small");
//give implementation a chance to react to window size
init(frame, delta);
//allocate local input buffer
for (int i = 0; i < sources.length; i++) {
_bufferID_in[i] = sources[i].getBufferID();
_stream_in[i] = Stream.create(sources[i], _num_frame[i], _num_delta[i]);
}
// figure out properties of output signal based on first input stream
int bytes_out = getSampleBytes(_stream_in);
int dim_out = getSampleDimension(_stream_in);
Cons.Type type_out = getSampleType(_stream_in);
int num_out = getSampleNumber(_num_frame[0]);
double sr_out = (double) num_out / frame;
if(num_out > 1 && delta != 0)
Log.w("Non-feature transformer called with positive delta. Transformer may not support this.");
_stream_out = Stream.create(num_out, dim_out, sr_out, type_out);
describeOutput(_stream_in, _stream_out);
// configure update rate
_timer = new Timer(frame);
_timer.setStartOffset(delta);
}
catch(Exception e)
{
throw new SSJException("error configuring component", e);
}
Log.i("Transformer " + _name + " (output)" + '\n' +
"\tbytes=" +_stream_out.bytes+ '\n' +
"\tdim=" +_stream_out.dim+ '\n' +
"\ttype=" +_stream_out.type.toString() + '\n' +
"\tnum=" +_stream_out.num+ '\n' +
"\tsr=" +_stream_out.sr);
_isSetup = true;
}
@Override
public String[] getOutputDescription()
{
if(!_isSetup) {
Log.e("not initialized");
return null;
}
String[] desc = new String[_stream_out.desc.length];
System.arraycopy(_stream_out.desc, 0, desc, 0, _stream_out.desc.length);
return desc;
}
public abstract int getSampleDimension(Stream[] stream_in);
public int getSampleBytes(Stream[] stream_in) { return Util.sizeOf(getSampleType(stream_in)); }
public abstract Cons.Type getSampleType(Stream[] stream_in);
public abstract int getSampleNumber(int sampleNumber_in);
protected abstract void describeOutput(Stream[] stream_in, Stream stream_out);
}
| 9,651 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
WatchDog.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/WatchDog.java | /*
* WatchDog.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.os.PowerManager;
/**
* Created by Johnny on 05.03.2015.
*/
public class WatchDog extends Thread {
protected String _name = "WatchDog";
protected boolean _terminate = false;
protected boolean _safeToKill = false;
protected Timer _timer;
protected boolean _targetCheckedIn = false;
protected final Object _lock = new Object();
protected Pipeline _frame;
protected int _bufferID;
protected double _watchInterval;
protected double _syncInterval;
protected int _syncIter;
protected int _watchIter;
public WatchDog(int bufferID, double watchInterval, double syncInterval)
{
_frame = Pipeline.getInstance();
_bufferID = bufferID;
_watchInterval = watchInterval;
_syncInterval = syncInterval;
double sleep = 0;
_syncIter = -1;
_watchIter = -1;
if (watchInterval > 0 && syncInterval > 0)
{
sleep = Math.min (watchInterval, syncInterval);
_syncIter = (int)(syncInterval / sleep) -1;
_watchIter = (int)(watchInterval / sleep) -1;
}
else if (syncInterval > 0)
{
sleep = syncInterval;
_syncIter = (int)(syncInterval / sleep) -1;
}
else if (watchInterval > 0)
{
sleep = watchInterval;
_watchIter = (int)(watchInterval / sleep) -1;
}
if(sleep > 0) {
_timer = new Timer(sleep);
start();
}
else {
_safeToKill = true;
}
}
public void checkIn()
{
synchronized (_lock)
{
_targetCheckedIn = true;
}
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
//wait for framework
while (_frame.getState() == Pipeline.State.STARTING) {
try {
sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
PowerManager mgr = (PowerManager)SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, _name);
int syncIterCnt = _syncIter;
int watchIterCnt = _watchIter;
_timer.reset();
while(!_terminate && _frame.isRunning())
{
try {
wakeLock.acquire();
//check buffer watch
if(_watchIter >= 0) {
if (watchIterCnt == 0) {
synchronized (_lock) {
if (!_targetCheckedIn) {
//provider did not check in, provide zeroes
_frame.pushZeroes(_bufferID);
}
_targetCheckedIn = false;
}
watchIterCnt = _watchIter;
} else watchIterCnt--;
}
//check buffer sync
if(_syncIter >= 0) {
if (syncIterCnt == 0) {
_frame.sync(_bufferID);
syncIterCnt = _syncIter;
} else syncIterCnt--;
}
_timer.sync();
} catch(Exception e) {
_frame.error(this.getClass().getSimpleName(), "exception in loop", e);
} finally {
wakeLock.release();
}
}
_safeToKill = true;
}
public void close() throws InterruptedException
{
Log.i("shutting down");
_terminate = true;
while(!_safeToKill)
sleep(Cons.SLEEP_IN_LOOP);
Log.i("shut down complete");
}
}
| 5,256 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Component.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Component.java | /*
* Component.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.util.ArrayList;
import hcm.ssj.core.option.OptionList;
/**
* Created by Johnny on 05.03.2015.
*/
public abstract class Component implements Runnable
{
protected String _name = "Component";
protected boolean _terminate = false;
protected boolean _safeToKill = false;
protected boolean _isSetup = false;
protected ArrayList<EventChannel> _evchannel_in = null;
protected EventChannel _evchannel_out = null;
public int threadPriority = Cons.THREAD_PRIORIIY_HIGH;
public void close()
{
Pipeline frame = Pipeline.getInstance();
Log.i(_name + " shutting down");
_terminate = true;
if(_evchannel_in != null)
for(EventChannel ch : _evchannel_in)
ch.close();
if(_evchannel_out != null) _evchannel_out.close();
double time = frame.getTime();
while(!_safeToKill)
{
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
if(frame.getTime() > time + frame.options.waitThreadKill.get())
{
Log.w(_name + " force-killed thread");
forcekill();
break;
}
}
Log.i(_name + " shut down completed");
}
public void forcekill()
{
Thread.currentThread().interrupt();
}
public String getComponentName()
{
return _name;
}
void addEventChannelIn(EventChannel channel)
{
if(_evchannel_in == null)
_evchannel_in = new ArrayList<>();
_evchannel_in.add(channel);
}
void setEventChannelOut(EventChannel channel)
{
_evchannel_out = channel;
}
public EventChannel getEventChannelOut()
{
if(_evchannel_out == null)
_evchannel_out = new EventChannel();
return _evchannel_out;
}
/**
* Resets internal state of components, does not alter references with framework or other components
* Called by the framework on start-up
*/
public void reset()
{
_terminate = false;
_safeToKill = false;
if(_evchannel_in != null)
for(EventChannel ch : _evchannel_in)
ch.reset();
if(_evchannel_out != null) _evchannel_out.reset();
}
/**
* Clears component, may alter references with framework or other components
* Called on framework clear()
*/
public void clear()
{
if(_evchannel_in != null)
{
for (EventChannel ch : _evchannel_in)
ch.clear();
_evchannel_in.clear();
}
}
public abstract OptionList getOptions();
public boolean isSetup()
{
return _isSetup;
}
}
| 4,219 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EventHandler.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/EventHandler.java | /*
* EventHandler.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.os.PowerManager;
import hcm.ssj.core.event.Event;
import static hcm.ssj.core.Cons.SLEEP_ON_COMPONENT_IDLE;
/**
* An EventHandler is a general component with no regulated inputs or outputs
* Its only means of communication are events
*
* Created by Johnny on 30.03.2015.
*/
public abstract class EventHandler extends Component implements EventListener {
protected Pipeline _frame;
protected boolean _doWakeLock = false;
public EventHandler()
{
_frame = Pipeline.getInstance();
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
if(_evchannel_in == null && _evchannel_out == null)
{
_frame.error(_name, "no event channel has been registered", null);
return;
}
PowerManager mgr = (PowerManager)SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, _name);
//register listener
if(_evchannel_in != null && _evchannel_in.size() != 0)
for(EventChannel ch : _evchannel_in)
ch.addEventListener(this);
try {
enter();
} catch(SSJFatalException e) {
_frame.error(_name, "exception in enter", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(_name, "exception in enter", e);
}
//wait for framework
while (!_terminate && !_frame.isRunning()) {
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
while(!_terminate && _frame.isRunning())
{
try {
if(_doWakeLock) wakeLock.acquire();
process();
} catch(SSJFatalException e) {
_frame.error(_name, "exception in loop", e);
_safeToKill = true;
return;
} catch(Exception e) {
_frame.error(_name, "exception in loop", e);
} finally {
if(_doWakeLock) wakeLock.release();
}
}
try {
flush();
} catch(Exception e) {
_frame.error(_name, "exception in flush", e);
}
_safeToKill = true;
}
/**
* Initialization specific to sensor implementation
*
* @throws SSJFatalException Exception
*/
protected void enter() throws SSJFatalException {};
/**
* Thread processing method, alternative to notify(), called in loop
*
* @throws SSJFatalException Exception
*/
protected void process() throws SSJFatalException
{
try {
Thread.sleep(SLEEP_ON_COMPONENT_IDLE);
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
/**
* Alternative to process(), called once per received event
*
* @param event Event
*/
public void notify(Event event) {}
/**
* Called once before termination
*
* @throws SSJFatalException Exception
*/
protected void flush() throws SSJFatalException {};
}
| 4,704 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Log.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Log.java | /*
* Log.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import hcm.ssj.BuildConfig;
/**
* Created by Johnny on 17.03.2016.
*/
public class Log
{
private final int RECENT_HISTORY_SIZE = 10;
public enum Level
{
VERBOSE(2), DEBUG(3), INFO(4), WARNING(5), ERROR(6), NONE(99);
Level(int i) {val = i;}
public final int val;
}
/**
* Interface to register listeners to
*/
public interface LogListener {
void msg(int type, String msg);
}
public class Entry
{
double t;
String msg;
public Entry(double t, String msg)
{
this.t = t;
this.msg = msg;
}
}
private LinkedList<Entry> buffer = new LinkedList<>();
private Pipeline frame = null;
private static Log instance = null;
//
private static HashSet<LogListener> hsLogListener = new HashSet<>();
//
private LinkedHashMap<String, Double> recent = new LinkedHashMap<String, Double>()
{
@Override
protected boolean removeEldestEntry(Map.Entry<String,Double> eldest) {
return size() > RECENT_HISTORY_SIZE;
}
};
Log() {}
public void setFramework(Pipeline frame)
{
this.frame = frame;
}
public static Log getInstance()
{
if(instance == null)
instance = new Log();
return instance;
}
public void clear()
{
synchronized (this)
{
buffer.clear();
recent.clear();
}
}
public void invalidate()
{
clear();
instance = null;
}
public void saveToFile(String path)
{
try
{
File fileDirectory = Util.createDirectory(path);
if(fileDirectory == null)
return;
File file = new File(fileDirectory, "ssj.log");
int i = 2;
while(file.exists())
{
file = new File(fileDirectory, "ssj" + (i++) + ".log");
}
FileOutputStream fos = new FileOutputStream(file);
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMaximumFractionDigits(3);
nf.setMinimumFractionDigits(3);
StringBuilder builder = new StringBuilder();
synchronized (this)
{
Iterator<Entry> iter = buffer.iterator();
while (iter.hasNext())
{
Entry e = iter.next();
builder.setLength(0);
builder.append(nf.format(e.t));
builder.append("\t");
builder.append(e.msg);
builder.append("\r\n");
fos.write(builder.toString().getBytes());
}
}
fos.close();
}
catch (IOException e)
{
Log.e("Exception in creating logfile", e);
}
}
private String getCaller()
{
StackTraceElement element = Thread.currentThread().getStackTrace()[5];
return element.getClassName().replace("hcm.ssj.", "");
}
private String buildEntry(String caller, String msg, Throwable tr)
{
StringBuilder builder = new StringBuilder();
builder.append('[').append(caller).append("] ").append(msg);
if(tr != null)
builder.append(":\n").append(android.util.Log.getStackTraceString(tr));
return builder.toString();
}
private void log(int type, String caller, String msg, Throwable tr)
{
if(type < ((frame == null) ? Level.VERBOSE.val : frame.options.loglevel.get().val))
return;
String str;
double time = (frame == null) ? 0 : frame.getTime();
str = buildEntry(caller, msg, tr);
//check if entry is in our recent history
Double lastTime = recent.get(str);
if(lastTime != null && time - lastTime < ((frame == null) ? 1.0 : frame.options.logtimeout.get()))
return;
android.util.Log.println(type, Cons.LOGTAG, str);
//save in recent
recent.put(str, time);
//send message to listeners
if (hsLogListener.size() > 0) {
for (LogListener logListener : hsLogListener) {
logListener.msg(type, str);
}
}
synchronized (this) {
buffer.add(new Entry(time, str));
}
}
private void log(int type, String msg, Throwable tr)
{
log(type, getCaller(), msg, tr);
}
/**
* @param logListener LogListener
*/
public static void addLogListener(LogListener logListener) {
hsLogListener.add(logListener);
}
/**
* @param logListener LogListener
*/
public static void removeLogListener(LogListener logListener) {
hsLogListener.remove(logListener);
}
public static void d(String msg)
{
getInstance().log(android.util.Log.DEBUG, msg, null);
}
public static void d(String msg, Throwable e)
{
getInstance().log(android.util.Log.DEBUG, msg, e);
}
public static void d(String tag, String msg)
{
getInstance().log(android.util.Log.DEBUG, tag, msg, null);
}
public static void d(String tag, String msg, Throwable e)
{
getInstance().log(android.util.Log.DEBUG, tag, msg, e);
}
//selective log variant
public static void ds(String msg)
{
if (BuildConfig.DEBUG)
getInstance().log(android.util.Log.DEBUG, msg, null);
}
public static void ds(String msg, Throwable e)
{
if (BuildConfig.DEBUG)
getInstance().log(android.util.Log.DEBUG, msg, e);
}
public static void ds(String tag, String msg)
{
if (BuildConfig.DEBUG)
getInstance().log(android.util.Log.DEBUG, tag, msg, null);
}
public static void ds(String tag, String msg, Throwable e)
{
if (BuildConfig.DEBUG)
getInstance().log(android.util.Log.DEBUG, tag, msg, e);
}
public static void i(String msg)
{
getInstance().log(android.util.Log.INFO, msg, null);
}
public static void i(String msg, Throwable e)
{
getInstance().log(android.util.Log.INFO, msg, e);
}
public static void i(String tag, String msg)
{
getInstance().log(android.util.Log.INFO, tag, msg, null);
}
public static void i(String tag, String msg, Throwable e)
{
getInstance().log(android.util.Log.INFO, tag, msg, e);
}
public static void e(String msg)
{
getInstance().log(android.util.Log.ERROR, msg, null);
}
public static void e(String msg, Throwable e)
{
getInstance().log(android.util.Log.ERROR, msg, e);
}
public static void e(String tag, String msg)
{
getInstance().log(android.util.Log.ERROR, tag, msg, null);
}
public static void e(String tag, String msg, Throwable e)
{
getInstance().log(android.util.Log.ERROR, tag, msg, e);
}
public static void w(String msg)
{
getInstance().log(android.util.Log.WARN, msg, null);
}
public static void w(String msg, Throwable e)
{
getInstance().log(android.util.Log.WARN, msg, e);
}
public static void w(String tag, String msg)
{
getInstance().log(android.util.Log.WARN, tag, msg, null);
}
public static void w(String tag, String msg, Throwable e)
{
getInstance().log(android.util.Log.WARN, tag, msg, e);
}
public static void v(String msg)
{
getInstance().log(android.util.Log.VERBOSE, msg, null);
}
public static void v(String msg, Throwable e)
{
getInstance().log(android.util.Log.VERBOSE, msg, e);
}
public static void v(String tag, String msg)
{
getInstance().log(android.util.Log.VERBOSE, tag, msg, null);
}
public static void v(String tag, String msg, Throwable e)
{
getInstance().log(android.util.Log.VERBOSE, tag, msg, e);
}
}
| 9,694 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TimeBuffer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/TimeBuffer.java | /*
* TimeBuffer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.util.Arrays;
/**
* Created by Johnny on 16.03.2015.
*/
public class TimeBuffer {
public final static int STATUS_SUCCESS = 0;
public final static int STATUS_INPUT_ARRAY_TOO_SMALL = -1;
public final static int STATUS_DATA_EXCEEDS_BUFFER_SIZE = -2;
public final static int STATUS_DATA_NOT_IN_BUFFER_YET = -3;
public final static int STATUS_DATA_NOT_IN_BUFFER_ANYMORE = -4;
public final static int STATUS_DURATION_TOO_SMALL = -5;
public final static int STATUS_DURATION_TOO_LARGE = -6;
public final static int STATUS_UNKNOWN_DATA = -7;
public final static int STATUS_ERROR = -9; //unknown error, buffer is probably closed
private byte[] _buffer;
private long _position;
private final Object _lock = new Object();
private boolean _terminate = false;
private double _sr;
private int _dim;
private int _bytesPerValue;
private Cons.Type _type;
private int _capacitySamples;
private int _bytesPerSample;
private double _sampleDuration;
private int _offsetSamples;
private int _lastAccessedSample;
private Provider _owner;
public TimeBuffer(double capacity, double sr, int dim, int bytesPerValue, Cons.Type type, Provider owner)
{
_owner = owner;
_sr = sr;
_dim = dim;
_bytesPerValue = bytesPerValue;
_type = type;
_capacitySamples = (int)(capacity * sr);
_bytesPerSample = bytesPerValue * dim;
_sampleDuration = 1.0 / _sr;
_buffer = new byte[_capacitySamples * _bytesPerSample];
reset();
}
public void reset()
{
_position = 0;
_offsetSamples = 0;
_lastAccessedSample = 0;
_terminate = false;
}
public void close()
{
_terminate = true;
synchronized (_lock) {
_lock.notifyAll();
}
}
public void push(Object data, int numBytes)
{
synchronized (_lock) {
//compute actual position of data within buffer
int pos_mod = (int)(_position % _buffer.length);
copy(data, 0, _buffer, pos_mod, numBytes);
_position += numBytes;
_lock.notifyAll();
}
}
private void copy(Object src, int srcpos, byte[] dst, int dstpos, int numBytes)
{
if (dstpos + numBytes <= dst.length) {
// end of buffer not reached
// copy data in one step
Util.arraycopy(src, srcpos, dst, dstpos, numBytes);
} else {
// end of buffer reached
// copy data in two steps:
// 1. copy everything until the end of the buffer is reached
// 2. copy remaining part from the beginning
int size_until_end = dst.length - dstpos;
int size_remaining = numBytes - size_until_end;
Util.arraycopy(src, srcpos, dst, dstpos, size_until_end);
copy(src, size_until_end, dst, 0, size_remaining);
}
}
public void pushZeroes(int numBytes)
{
Log.w(_owner.getComponentName(), "pushing " + numBytes + " bytes of zeroes");
synchronized (_lock) {
//compute actual position of data within buffer
int pos_mod = (int)(_position % _buffer.length);
fillZero(_buffer, pos_mod, numBytes);
_position += numBytes;
_lock.notifyAll();
}
}
private void fillZero(byte[] buffer, int pos, int num)
{
if (pos + num <= buffer.length)
Arrays.fill(buffer, pos, pos + num, (byte)0);
else
{
// end of buffer reached
// copy data in two steps:
// 1. copy everything until the end of the buffer is reached
// 2. copy remaining part from the beginning
int size_until_end = buffer.length - pos;
int size_remaining = num - size_until_end;
Arrays.fill(buffer, pos, pos + size_until_end, (byte)0);
fillZero(buffer, 0, size_remaining);
}
}
private boolean get_(Object dst, long pos, int len)
{
synchronized (_lock) {
//wait for requested data to become available
while (pos + len > _position && !_terminate) {
try {
_lock.wait();
} catch (InterruptedException e) {
Log.w("thread interrupt");
}
}
if(_terminate)
return false;
//compute actual position of data within buffer
int pos_mod = (int)(pos % _buffer.length);
if (pos_mod + len <= _buffer.length) {
// end of buffer not reached
// copy data in one step
Util.arraycopy(_buffer, pos_mod, dst, 0, len);
} else {
// end of buffer reached
// copy data in two steps:
// 1. copy everything until the end of the buffer is reached
// 2. copy remaining part from the beginning
int size_until_end = _buffer.length - pos_mod;
int size_remaining = len - size_until_end;
Util.arraycopy(_buffer, pos_mod, dst, 0, size_until_end);
Util.arraycopy(_buffer, 0, dst, size_until_end, size_remaining);
}
}
return true;
}
public int get(Object dst, int startSample, int numSamples)
{
//correct position for sync
startSample -= _offsetSamples;
// check if requested duration is too small
if (numSamples == 0) {
return STATUS_DURATION_TOO_SMALL;
}
// check if requested duration is too large
if (numSamples > _capacitySamples) {
return STATUS_DURATION_TOO_LARGE;
}
if (startSample < 0) {
return STATUS_UNKNOWN_DATA;
}
// Check if requested data is still available (checks if startSample is older than whole buffer size of samples before current position)
if (startSample + _capacitySamples < _position / _bytesPerSample || startSample < 0) {
return STATUS_DATA_NOT_IN_BUFFER_ANYMORE;
}
boolean ok = get_(dst, (long)startSample * _bytesPerSample, numSamples * _bytesPerSample);
_lastAccessedSample = startSample + numSamples - 1;
if(ok) return STATUS_SUCCESS;
else return STATUS_ERROR;
}
public int get(Object dst, double start_time, double duration)
{
int pos = (int)(start_time * _sr + 0.5);
int pos_stop = (int)((start_time + duration) * _sr + 0.5);
int len = pos_stop - pos;
return get(dst, pos, len);
}
public void sync(double time)
{
setReadTime(time);
}
public double getReadTime()
{
long positionSamples = _position / _bytesPerSample;
return (_offsetSamples + positionSamples) * _sampleDuration;
}
public void setReadTime(double time)
{
double delta = getReadTime() - time;
_offsetSamples -= (int)(delta * _sr + 0.5);
}
public long getPositionAbs()
{
return _position;
}
public int getCapacity()
{
return _buffer.length;
}
public double getLastAccessedSampleTime ()
{
return (_offsetSamples + _lastAccessedSample) * _sampleDuration;
}
public double getLastWrittenSampleTime ()
{
return (_offsetSamples + (_position / _bytesPerSample)) * _sampleDuration;
}
public double getSampleRate ()
{
return _sr;
}
public int getBytesPerSample ()
{
return _bytesPerSample;
}
public int getBytesPerValue ()
{
return _bytesPerValue;
}
public Provider getOwner()
{
return _owner;
}
public int getOffsetSamples()
{
return _offsetSamples;
}
}
| 9,289 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ExceptionHandler.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/ExceptionHandler.java | /*
* ExceptionHandler.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
/**
* Created by damia on 06.04.2016.
*/
public interface ExceptionHandler {
void handle(String location, String msg, Throwable t);
}
| 1,518 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EventChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/EventChannel.java | /*
* EventChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import android.content.Context;
import android.os.PowerManager;
import java.util.ArrayList;
import java.util.LinkedList;
import hcm.ssj.core.event.Event;
/**
* Created by Johnny on 05.03.2015.
*/
public class EventChannel {
protected String _name = "EventChannel";
private ArrayList<EventListener> _listeners = new ArrayList<>();
private LinkedList<Event> _events = new LinkedList<>();
private int _event_id = 0;
final private Object _lock = new Object();
protected boolean _terminate = false;
protected Pipeline _frame;
PowerManager powerManager;
public EventChannel() {
_frame = Pipeline.getInstance();
powerManager = (PowerManager)SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
}
public void reset() {
_terminate = false;
_event_id = 0;
_events.clear();
}
public void clear() {
_listeners.clear();
}
public void addEventListener(EventListener listener) {
if(_listeners.contains(listener))
return;
_listeners.add(listener);
}
public Event getLastEvent(boolean peek, boolean blocking) {
Event ev = null;
synchronized (_lock) {
while (!_terminate && _events.size() == 0) {
if (blocking) {
try {
_lock.wait();
} catch (InterruptedException e) {
}
} else {
return null;
}
}
if (_terminate) {
return null;
}
ev = _events.getLast();
if (!peek) {
_events.removeLast();
}
}
return ev;
}
public Event getEvent(int eventID, boolean blocking) {
synchronized (_lock) {
while (!_terminate && (_events.size() == 0 || eventID > _events.getLast().id)) {
if (blocking) {
try {
_lock.wait();
} catch (InterruptedException e) {
}
} else {
return null;
}
}
if (_terminate) {
return null;
}
if (eventID == _events.getFirst().id) {
return _events.getFirst();
}
if (eventID < _events.getFirst().id) {
Log.w("event " + eventID + " no longer in queue");
return _events.getFirst(); //if event is no longer in queue, return oldest event
}
//search for event
for (Event ev : _events) {
if (ev.id == eventID) {
return ev;
}
}
}
return null;
}
public void pushEvent(final Event ev) {
synchronized (_lock) {
//give event a local-unique ID
ev.id = _event_id++;
_events.addLast(ev);
if (_events.size() > Cons.MAX_NUM_EVENTS_PER_CHANNEL) {
_events.removeFirst();
}
// Notify event listeners
for (final EventListener listener : _listeners) {
_frame.threadPool.execute(new Runnable() {
@Override
public void run() {
if(listener == null)
{
Log.e("error reacting to event: listener == null, listeners = " + _listeners.size());
return;
}
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ev" + ev.id + listener.toString());
wakeLock.acquire();
listener.notify(ev);
wakeLock.release();
}
});
}
_lock.notifyAll();
}
}
public void close() {
Log.i("shutting down");
_terminate = true;
synchronized (_lock) {
_lock.notifyAll();
}
Log.i("shut down complete");
}
}
| 5,600 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ThreadPool.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/ThreadPool.java | /*
* ThreadPool.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Extends java's ThreadPoolExecutor to add uncaught exception handling
*
* Created by Johnny on 06.04.2016.
*/
public class ThreadPool extends java.util.concurrent.ThreadPoolExecutor {
public ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if(t != null)
Pipeline.getInstance().error(r.getClass().getSimpleName(), "uncaught exception", t);
}
}
| 2,086 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Provider.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/Provider.java | /*
* Provider.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 05.03.2015.
*/
public abstract class Provider extends Component {
protected int _bufferID = -1;
protected void setBufferID(int bufferID)
{
_bufferID = bufferID;
}
protected int getBufferID()
{
return _bufferID;
}
protected Stream _stream_out = null;
public Stream getOutputStream()
{
if(_stream_out == null)
Log.e("output stream not initialized");
return _stream_out;
}
public abstract String[] getOutputDescription();
@Override
public void clear()
{
_bufferID = -1;
super.clear();
}
}
| 2,049 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Option.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/option/Option.java | /*
* Option.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.option;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.Util;
/**
* Standard option for SSJ.<br>
* Created by Frank Gaibler on 04.03.2016.
*/
public class Option<T>
{
private final String name;
private T value;
private final Class<T> type;
private final String help;
/**
* @param name String
* @param value T
* @param type Class
* @param help String
*/
public Option(String name, T value, Class<T> type, String help)
{
this.name = name;
this.value = value;
this.type = type;
this.help = help;
}
/**
* @return String
*/
public final String getName()
{
return name;
}
/**
* @return T
*/
public final T get()
{
return value;
}
/**
* @return T
*/
public String parseWildcards()
{
if (value != null && (type == String.class || type == FilePath.class || type == FolderPath.class))
{
String str = "";
if (type == String.class)
str = (String) value;
else if (type == FilePath.class)
str = ((FilePath) value).value;
else if (type == FolderPath.class)
str = ((FolderPath) value).value;
if (str.contains("[time]"))
{
return str.replace("[time]", Util.getTimestamp(Pipeline.getInstance().getCreateTimeMs()));
}
else
{
return str;
}
}
else
{
return null;
}
}
/**
* @param value T
*/
public final void set(T value)
{
this.value = value;
}
/**
* @return Class
*/
public final Class<T> getType()
{
return type;
}
/**
* @return String
*/
public final String getHelp()
{
return help;
}
/**
* Tries to set the value by parsing the String parameter. <br>
* This method will only work with primitives, strings, arrays and enums.
*
* @param value String
* @return boolean
*/
public final boolean setValue(String value)
{
if (value == null || value.isEmpty())
{
set(null);
return true;
}
else
{
if (!value.equals("-"))
{
//number primitives
if (type == Byte.class)
{
return setValue(Byte.valueOf(value));
}
if (type == Short.class)
{
return setValue(Short.valueOf(value));
}
if (type == Integer.class)
{
return setValue(Integer.valueOf(value));
}
if (type == Long.class)
{
return setValue(Long.valueOf(value));
}
if (type == Float.class)
{
return setValue(Float.valueOf(value));
}
if (type == Double.class)
{
return setValue(Double.valueOf(value));
}
//arrays
if (type.isArray())
{
String[] strings = value.replace("[", "").replace("]", "").split("\\s*,\\s*");
//check strings for plausibility
if (strings.length <= 0)
{
return false;
}
Class<?> componentType = type.getComponentType();
if (componentType.isPrimitive())
{
//check strings for plausibility
for (int i = 0; i < strings.length; i++)
{
strings[i] = strings[i].replace(",", "");
if (strings[i].isEmpty())
{
return false;
}
}
if (char.class.isAssignableFrom(componentType))
{
char[] ar = new char[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = strings[i].charAt(0);
}
set((T) ar);
return true;
}
//check strings for plausibility
for (String string : strings)
{
if (string.equals("-"))
{
return false;
}
}
if (boolean.class.isAssignableFrom(componentType))
{
boolean[] ar = new boolean[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Boolean.parseBoolean(strings[i]);
}
set((T) ar);
return true;
}
if (byte.class.isAssignableFrom(componentType))
{
byte[] ar = new byte[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Byte.parseByte(strings[i]);
}
set((T) ar);
return true;
}
if (double.class.isAssignableFrom(componentType))
{
double[] ar = new double[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Double.parseDouble(strings[i]);
}
set((T) ar);
return true;
}
if (float.class.isAssignableFrom(componentType))
{
float[] ar = new float[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Float.parseFloat(strings[i]);
}
set((T) ar);
return true;
}
if (int.class.isAssignableFrom(componentType))
{
int[] ar = new int[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Integer.parseInt(strings[i]);
}
set((T) ar);
return true;
}
if (long.class.isAssignableFrom(componentType))
{
long[] ar = new long[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Long.parseLong(strings[i]);
}
set((T) ar);
return true;
}
if (short.class.isAssignableFrom(componentType))
{
short[] ar = new short[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = Short.parseShort(strings[i]);
}
set((T) ar);
return true;
}
}
else if (FilePath.class.isAssignableFrom(componentType))
{
FilePath[] ar = new FilePath[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = new FilePath(strings[i]);
}
set((T) ar);
return true;
}
else if (FolderPath.class.isAssignableFrom(componentType))
{
FolderPath[] ar = new FolderPath[strings.length];
for (int i = 0; i < strings.length; i++)
{
ar[i] = new FolderPath(strings[i]);
}
set((T) ar);
return true;
}
else if (String.class.isAssignableFrom(componentType))
{
return setValue(strings);
}
}
}
//enums
if (type.isEnum())
{
return setValue(Enum.valueOf((Class<Enum>) type, value));
}
//other primitives
if (type == Character.class)
{
return setValue(value.charAt(0));
}
if (type == String.class)
{
set((T) value);
return true;
}
if (type == FilePath.class)
{
return setValue(new FilePath(value));
}
if (type == FolderPath.class)
{
return setValue(new FolderPath(value));
}
if (type == Boolean.class)
{
return setValue(Boolean.valueOf(value));
}
}
return false;
}
/**
* @param o Object
* @return boolean
*/
private boolean setValue(Object o)
{
try
{
set((T) o);
}
catch (ClassCastException ex)
{
set(null);
return false;
}
return true;
}
/**
* Verifies if the option is assignable by {@link #setValue(String) setValue}
*
* @return boolean
*/
public boolean isAssignableByString()
{
return (type.isEnum()
|| type.isArray()
|| type == Boolean.class
|| type == Character.class
|| type == Byte.class
|| type == Short.class
|| type == Integer.class
|| type == Long.class
|| type == Float.class
|| type == Double.class
|| type == String.class
|| type == FilePath.class
|| type == FolderPath.class);
}
}
| 8,630 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FilePath.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/option/FilePath.java | /*
* FilePath.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.option;
/**
* Created by Ionut Damian on 11.12.2017.
*/
public class FilePath
{
public String value = null;
public FilePath(String value)
{
this.value = value;
}
@Override
public String toString()
{
return value;
}
}
| 1,602 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FolderPath.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/option/FolderPath.java | /*
* FolderPath.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.option;
/**
* Created by Ionut Damian on 11.12.2017.
*/
public class FolderPath
{
public String value = null;
public FolderPath(String value)
{
this.value = value;
}
@Override
public String toString()
{
return value;
}
}
| 1,608 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
OptionList.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/option/OptionList.java | /*
* OptionList.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.option;
import java.lang.reflect.Field;
import java.util.LinkedHashSet;
/**
* Derivable option list for SSJ.<br>
* Created by Frank Gaibler on 04.03.2016.
*/
public abstract class OptionList
{
protected LinkedHashSet<Option> hashSetOptions = new LinkedHashSet<>();
/**
*
*/
protected OptionList()
{
}
/**
* @return Option[]
*/
public final Option[] getOptions()
{
return hashSetOptions.toArray(new Option[hashSetOptions.size()]);
}
/**
* @param name String
* @param value Object
* @return boolean
*/
public final boolean setOptionValue(String name, String value)
{
for (Option option : hashSetOptions)
{
if (option.getName().equals(name))
{
option.setValue(value);
return true;
}
}
return false;
}
/**
* @param name String
* @return Object
*/
public final Object getOptionValue(String name)
{
for (Option option : hashSetOptions)
{
if (option.getName().equals(name))
{
return option.get();
}
}
return null;
}
/**
*
*/
protected final void addOptions()
{
//only add on latest subclass
if (super.getClass().isAssignableFrom(this.getClass()))
{
Field[] fields = this.getClass().getFields();
for (Field field : fields)
{
if (field.getType().isAssignableFrom(Option.class))
{
try
{
Option option = (Option) field.get(this);
//only add instantiated options
if (option != null)
{
add(option);
}
} catch (IllegalAccessException ex)
{
ex.printStackTrace();
}
}
}
}
}
/**
* @param option Option
*/
public void add(Option option)
{
hashSetOptions.add(option);
}
}
| 3,609 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Stream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/Stream.java | /*
* Stream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Provider;
import hcm.ssj.core.Util;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.SimpleXmlParser;
/**
* Created by Johnny on 17.03.2015.
*/
public abstract class Stream implements Serializable
{
public int dim;
public int num;
public int num_frame;
public int num_delta;
public int bytes;
public int tot;
public double sr;
public double time;
public double step;
public Cons.Type type;
public transient Provider source;
public String[] desc = null;
public static Stream create(int num, int dim, double sr, Cons.Type type)
{
switch(type)
{
case BYTE:
return new ByteStream(num, dim, sr);
case CHAR:
return new CharStream(num, dim, sr);
case SHORT:
return new ShortStream(num, dim, sr);
case INT:
return new IntStream(num, dim, sr);
case LONG:
return new LongStream(num, dim, sr);
case FLOAT:
return new FloatStream(num, dim, sr);
case DOUBLE:
return new DoubleStream(num, dim, sr);
case BOOL:
return new BoolStream(num, dim, sr);
case IMAGE:
return new ImageStream(num, dim, sr);
default:
throw new UnsupportedOperationException("Stream type not supported");
}
}
public static Stream create(Provider source, int num_frame, int num_delta)
{
Stream s = create(source, num_frame + num_delta);
s.num_frame = num_frame;
s.num_delta = num_delta;
return s;
}
public static Stream create(Provider source, int num)
{
Stream s;
switch(source.getOutputStream().type)
{
case IMAGE:
ImageStream src = (ImageStream) source.getOutputStream();
s = new ImageStream(num, src.dim, src.sr, src.width, src.height, src.format);
break;
default:
s = create(num, source.getOutputStream().dim, source.getOutputStream().sr, source.getOutputStream().type);
}
s.source = source;
s.desc = source.getOutputDescription();
return s;
}
protected Stream()
{
dim = 0;
bytes = 0;
type = Cons.Type.UNDEF;
sr = 0;
step = 0;
num = 0;
num_frame = 0;
num_delta = 0;
tot = 0;
time = 0;
}
protected Stream(int num, int dim, double sr)
{
this.dim = dim;
this.num = num;
this.num_frame = num;
this.sr = sr;
this.step = 1.0 / sr;
this.num_delta = 0;
this.time = 0;
this.tot = 0;
this.bytes = 0;
this.type = Cons.Type.UNDEF;
}
public void setSource(Provider source)
{
this.source = source;
this.desc = source.getOutputDescription();
}
public abstract Object ptr();
public byte[] ptrB() { throw new UnsupportedOperationException(); }
public char[] ptrC() { throw new UnsupportedOperationException(); }
public short[] ptrS() { throw new UnsupportedOperationException(); }
public int[] ptrI() { throw new UnsupportedOperationException(); }
public long[] ptrL() { throw new UnsupportedOperationException(); }
public float[] ptrF() { throw new UnsupportedOperationException(); }
public double[] ptrD() { throw new UnsupportedOperationException(); }
public boolean[] ptrBool() { throw new UnsupportedOperationException(); }
public abstract void adjust(int num);
public abstract Stream select(int[] new_dims);
public abstract Stream select(int new_dim);
public abstract Stream clone();
/**
* Extracts a subset of the stream. WARNING: may initialize large amounts of memory
* @param from time in seconds pointing to the start of the substream
* @param to time in seconds pointing to the end of the substream
* @return new stream object
*/
public Stream substream(double from, double to)
{
int pos = (int)(from * sr + 0.5);
int pos_stop = (int)(to * sr + 0.5);
int len = pos_stop - pos;
if(len <= 0)
{
Log.e("Duration too small");
return null;
}
Stream out = create(len, dim, sr, type);
int bytesPerSample = dim * bytes;
Util.arraycopy(ptr(), pos * bytesPerSample, out.ptr(), 0, len * bytesPerSample);
return out;
}
public int findDataClass(String name)
{
if(desc == null || desc.length == 0)
return -1;
for(int i = 0; i < desc.length; i++)
if(desc[i].equalsIgnoreCase(name))
return i;
return -1;
}
public void reset()
{
time = 0;
}
public static Stream load(String path) throws IOException, XmlPullParserException
{
if(path.endsWith(FileCons.FILE_EXTENSION_STREAM + FileCons.TAG_DATA_FILE))
{
path = path.substring(0, path.length()-2);
}
else if(!path.endsWith(FileCons.FILE_EXTENSION_STREAM))
{
path += "." + FileCons.FILE_EXTENSION_STREAM;
}
File header = new File(path);
/*
* INFO
*/
SimpleXmlParser simpleXmlParser = new SimpleXmlParser();
SimpleXmlParser.XmlValues xmlValues = simpleXmlParser.parse(
new FileInputStream(header),
new String[]{"stream", "info"},
new String[]{"ftype", "sr", "dim", "byte", "type"}
);
String ftype = xmlValues.foundAttributes.get(0)[0];
double sr = Double.valueOf(xmlValues.foundAttributes.get(0)[1]);
int dim = Integer.valueOf(xmlValues.foundAttributes.get(0)[2]);
int bytes = Integer.valueOf(xmlValues.foundAttributes.get(0)[3]);
Cons.Type type = Cons.Type.valueOf(xmlValues.foundAttributes.get(0)[4]);
/*
* CHUNK
*/
xmlValues = simpleXmlParser.parse(
new FileInputStream(header),
new String[]{"stream", "chunk"},
new String[]{"from", "num"}
);
double time = Double.valueOf(xmlValues.foundAttributes.get(0)[0]);
int num = Integer.valueOf(xmlValues.foundAttributes.get(0)[1]);
Stream stream = create(num, dim, sr, type);
stream.time = time;
if (ftype.equals("ASCII"))
{
loadDataASCII(stream, path + FileCons.TAG_DATA_FILE);
}
else if (ftype.equals("BINARY"))
{
loadDataBinary(stream, path + FileCons.TAG_DATA_FILE);
}
return stream;
}
private static void loadDataASCII(Stream stream, String path) throws IOException, XmlPullParserException
{
InputStream inputStream = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
int cnt = 0;
String line = reader.readLine();
while(line != null)
{
String[] tokens = line.split(FileCons.DELIMITER_DIMENSION);
for(String value : tokens)
{
switch (stream.type)
{
case BYTE:
case IMAGE:
stream.ptrB()[cnt++] = Byte.valueOf(value);
break;
case CHAR:
stream.ptrC()[cnt++] = (char)Byte.valueOf(value).byteValue();
break;
case SHORT:
stream.ptrS()[cnt++] = Short.valueOf(value);
break;
case INT:
stream.ptrI()[cnt++] = Integer.valueOf(value);
break;
case LONG:
stream.ptrL()[cnt++] = Long.valueOf(value);
break;
case FLOAT:
stream.ptrF()[cnt++] = Float.valueOf(value);
break;
case DOUBLE:
stream.ptrD()[cnt++] = Double.valueOf(value);
break;
case BOOL:
stream.ptrBool()[cnt++] = Boolean.valueOf(value);
break;
default:
throw new UnsupportedOperationException("Stream type not supported");
}
}
line = reader.readLine();
}
}
private static void loadDataBinary(Stream stream, String path) throws IOException, XmlPullParserException
{
InputStream inputStream = new FileInputStream(new File(path));
BufferedInputStream reader = new BufferedInputStream(inputStream);
byte buffer[] = new byte[stream.tot];
int len = reader.read(buffer, 0, stream.tot);
while(len != -1)
{
Util.arraycopy(buffer, 0, stream.ptr(),0, len);
len = reader.read(buffer, 0, stream.tot);
}
}
}
| 10,861 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ShortStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/ShortStream.java | /*
* ShortStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class ShortStream extends Stream
{
private short[] _ptr;
public ShortStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 2;
this.type = Cons.Type.SHORT;
tot = num * dim * bytes;
_ptr = new short[num * dim];
}
@Override
public short[] ptr()
{
return _ptr;
}
public short[] ptrS()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new short[num * dim];
}
}
public ShortStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
ShortStream slice = new ShortStream(num, new_dims.length, sr);
slice.source = source;
short[] src = this.ptr();
short[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public ShortStream select(int new_dim)
{
if(dim == 1)
return this;
ShortStream slice = new ShortStream(num, 1, sr);
slice.source = source;
short[] src = this.ptr();
short[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
ShortStream copy = new ShortStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,365 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ImageStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/ImageStream.java | /*
* ImageStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import android.graphics.ImageFormat;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class ImageStream extends ByteStream
{
public int width;
public int height;
public int format;
public ImageStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.type = Cons.Type.IMAGE;
this.width = 0;
this.height = 0;
this.format = ImageFormat.NV21;
}
public ImageStream(int num, int dim, double sr, int width, int height, int format)
{
super(num, dim, sr);
this.type = Cons.Type.IMAGE;
this.width = width;
this.height = height;
this.format = format;
}
public ImageStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
ImageStream slice = new ImageStream(num, new_dims.length, sr, width, height, format);
slice.source = source;
byte[] src = this.ptr();
byte[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public ImageStream select(int new_dim)
{
if(dim == 1)
return this;
ImageStream slice = new ImageStream(num, 1, sr, width, height, format);
slice.source = source;
byte[] src = this.ptr();
byte[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
ImageStream copy = new ImageStream(num, dim, sr, width, height, format);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,335 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IntStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/IntStream.java | /*
* IntStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class IntStream extends Stream
{
private int[] _ptr;
public IntStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 4;
this.type = Cons.Type.INT;
tot = num * dim * bytes;
_ptr = new int[num * dim];
}
@Override
public int[] ptr()
{
return _ptr;
}
public int[] ptrI()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new int[num * dim];
}
}
public IntStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
IntStream slice = new IntStream(num, new_dims.length, sr);
slice.source = source;
int[] src = this.ptr();
int[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public IntStream select(int new_dim)
{
if(dim == 1)
return this;
IntStream slice = new IntStream(num, 1, sr);
slice.source = source;
int[] src = this.ptr();
int[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
IntStream copy = new IntStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,323 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FloatStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/FloatStream.java | /*
* FloatStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class FloatStream extends Stream
{
public float[] _ptr;
public FloatStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 4;
this.type = Cons.Type.FLOAT;
tot = num * dim * bytes;
_ptr = new float[num * dim];
}
@Override
public float[] ptr()
{
return _ptr;
}
public float[] ptrF()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new float[num * dim];
}
}
public FloatStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
FloatStream slice = new FloatStream(num, new_dims.length, sr);
slice.source = source;
float[] src = this.ptr();
float[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public FloatStream select(int new_dim)
{
if(dim == 1)
return this;
FloatStream slice = new FloatStream(num, 1, sr);
slice.source = source;
float[] src = this.ptr();
float[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
FloatStream copy = new FloatStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,376 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ByteStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/ByteStream.java | /*
* ByteStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class ByteStream extends Stream
{
protected byte[] _ptr;
public ByteStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 1;
this.type = Cons.Type.BYTE;
tot = num * dim * bytes;
_ptr = new byte[tot];
}
@Override
public byte[] ptr()
{
return _ptr;
}
public byte[] ptrB()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new byte[tot];
}
}
public ByteStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
ByteStream slice = new ByteStream(num, new_dims.length, sr);
slice.source = source;
byte[] src = this.ptr();
byte[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public ByteStream select(int new_dim)
{
if(dim == 1)
return this;
ByteStream slice = new ByteStream(num, 1, sr);
slice.source = source;
byte[] src = this.ptr();
byte[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
ByteStream copy = new ByteStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,334 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LongStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/LongStream.java | /*
* LongStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class LongStream extends Stream
{
private long[] _ptr;
public LongStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 8;
this.type = Cons.Type.LONG;
tot = num * dim * bytes;
_ptr = new long[num * dim];
}
@Override
public long[] ptr()
{
return _ptr;
}
public long[] ptrL()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new long[num * dim];
}
}
public LongStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
LongStream slice = new LongStream(num, new_dims.length, sr);
slice.source = source;
long[] src = this.ptr();
long[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public LongStream select(int new_dim)
{
if(dim == 1)
return this;
LongStream slice = new LongStream(num, 1, sr);
slice.source = source;
long[] src = this.ptr();
long[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
LongStream copy = new LongStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,344 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
DoubleStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/DoubleStream.java | /*
* DoubleStream.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library 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 any later version.
*
* This library 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 library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class DoubleStream extends Stream
{
private double[] _ptr;
public DoubleStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 8;
this.type = Cons.Type.DOUBLE;
tot = num * dim * bytes;
_ptr = new double[num * dim];
}
@Override
public double[] ptr()
{
return _ptr;
}
public double[] ptrD()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new double[num * dim];
}
}
public DoubleStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
DoubleStream slice = new DoubleStream(num, new_dims.length, sr);
slice.source = source;
double[] src = this.ptr();
double[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public DoubleStream select(int new_dim)
{
if(dim == 1)
return this;
DoubleStream slice = new DoubleStream(num, 1, sr);
slice.source = source;
double[] src = this.ptr();
double[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
DoubleStream copy = new DoubleStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,386 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.