001package net.bramp.ffmpeg.progress;
002
003import static com.google.common.base.Preconditions.checkNotNull;
004
005import com.google.common.base.Charsets;
006import java.io.BufferedReader;
007import java.io.IOException;
008import java.io.InputStream;
009import java.io.InputStreamReader;
010import java.io.Reader;
011
012public class StreamProgressParser {
013
014  final ProgressListener listener;
015
016  public StreamProgressParser(ProgressListener listener) {
017    this.listener = checkNotNull(listener);
018  }
019
020  private static BufferedReader wrapInBufferedReader(Reader reader) {
021    checkNotNull(reader);
022
023    if (reader instanceof BufferedReader) {
024      return (BufferedReader) reader;
025    }
026
027    return new BufferedReader(reader);
028  }
029
030  public void processStream(InputStream stream) throws IOException {
031    checkNotNull(stream);
032    processReader(new InputStreamReader(stream, Charsets.UTF_8));
033  }
034
035  public void processReader(Reader reader) throws IOException {
036    final BufferedReader in = wrapInBufferedReader(reader);
037
038    String line;
039    Progress p = new Progress();
040    while ((line = in.readLine()) != null) {
041      if (p.parseLine(line)) {
042        listener.progress(p);
043        p = new Progress();
044      }
045    }
046  }
047}