001package net.bramp.ffmpeg.progress;
002
003import java.io.IOException;
004import java.net.InetAddress;
005import java.net.ServerSocket;
006import java.net.URI;
007import java.net.URISyntaxException;
008import java.util.concurrent.CountDownLatch;
009
010public class TcpProgressParser extends AbstractSocketProgressParser {
011
012  final ServerSocket server;
013  final URI address;
014
015  public TcpProgressParser(ProgressListener listener) throws IOException, URISyntaxException {
016    this(listener, 0, InetAddress.getLoopbackAddress());
017  }
018
019  public TcpProgressParser(ProgressListener listener, int port, InetAddress addr)
020      throws IOException, URISyntaxException {
021    super(listener);
022    this.server = new ServerSocket(port, 0, addr);
023    this.address = createUri("tcp", server.getInetAddress(), server.getLocalPort());
024  }
025
026  @Override
027  public synchronized void stop() throws IOException {
028    if (server.isClosed()) {
029      // Allow double stop, and ignore
030      return;
031    }
032
033    server.close(); // This unblocks server.accept();
034    super.stop();
035  }
036
037  @Override
038  protected String getThreadName() {
039    return "TcpProgressParser";
040  }
041
042  @Override
043  protected Runnable getRunnable(CountDownLatch startSignal) {
044    return new TcpProgressParserRunnable(parser, server, startSignal);
045  }
046
047  @Override
048  public URI getUri() {
049    return address;
050  }
051}