package org.livesub.player;
import javafx.application.Platform;
import org.apache.log4j.Logger;
import org.livesub.input.Caption;
import org.livesub.utils.doublelinkedlist.DoubleLinkedList;
import org.livesub.utils.doublelinkedlist.DoubleLinkedNode;
/**
* This class sets the displayed text at the appropriate moment
* @author vasilis
*/
public class SubtitleTask implements Runnable {
private static final Logger LOG = Logger.getLogger(SubtitleTask.class);
private final Player player;
private long playTime; // time the subs are playing
private DoubleLinkedList<Caption> subtitleList;
private DoubleLinkedNode<Caption> currentCaption;
public SubtitleTask(Player player) {
this.player = player;
}
@Override
public void run() {
try {
Caption current = currentCaption.getElement();
playTime++;
if(playTime > subtitleList.getLast().getElement().getDisappear()) {
stop();
} else if (playTime >= current.getAppear() && playTime <= current.getDisappear()) {
setText(current.getContents());
} else if(playTime > current.getDisappear()) {
currentCaption = currentCaption.getNext();
setText(null);
}
} catch(Exception e) {
LOG.error("SubtitleTask Error!", e);
}
}
/**
* Initialize the subtitles list
* @param subtitleList
*/
public void setSubtitleList(DoubleLinkedList<Caption> subtitleList) {
this.subtitleList = subtitleList;
if(subtitleList.isEmpty()) {
return;
}
currentCaption = subtitleList.getFirst();
}
/**
* Move to caption
* @param captionIndex
*/
public void goTo(int captionIndex){
if(subtitleList == null || subtitleList.isEmpty()) {
LOG.fatal("Uninitialized or empty list");
return;
}
if(!subtitleList.contains(captionIndex)) {
LOG.warn(String.format("No element found with %d index", captionIndex));
return;
}
currentCaption = subtitleList.get(captionIndex);
playTime = currentCaption.getElement().getAppear();
player.setDisplayedText(currentCaption.getElement().getContents());
}
/**
* Jump one caption forward or backward
* @param direction positive to go forward / negative for backward
*/
public void jump(int direction){
if(subtitleList == null || subtitleList.isEmpty()) {
LOG.fatal("Uninitialized or empty list");
return;
}
int newIndex = currentCaption.getIndex();
if (!subtitleList.contains(newIndex)) {
LOG.warn(String.format("No element found with %d index", newIndex));
return;
}
if(direction > 0) {
newIndex = currentCaption.getNext().getIndex();
} else if(direction < 0) {
newIndex = currentCaption.getPrev().getIndex();
}
goTo(newIndex);
}
/**
* Trigger the stop method on the main (javafx) thread
*/
private void stop() {
Platform.runLater(new Runnable() {
@Override
public void run() {
player.stop();
}
});
}
private void setText(final String text) {
Platform.runLater(new Runnable() {
@Override
public void run() {
player.setDisplayedText(text);
}
});
}
/**
* Reset current task
*/
public void reset() {
currentCaption = null;
subtitleList = null;
playTime = 0;
player.setDisplayedText("The End");
}
}