1/*
2 * Copyright 2011 Sebastian Annies, Hamburg
3 *
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.googlecode.mp4parser.srt;
17
18import com.googlecode.mp4parser.authoring.tracks.TextTrackImpl;
19
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.InputStreamReader;
23import java.io.LineNumberReader;
24
25/**
26 * Parses a .srt file and creates a Track for it.
27 */
28public class SrtParser {
29    public static TextTrackImpl parse(InputStream is) throws IOException {
30        LineNumberReader r = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
31        TextTrackImpl track = new TextTrackImpl();
32        String numberString;
33        while ((numberString = r.readLine()) != null) {
34            String timeString = r.readLine();
35            String lineString = "";
36            String s;
37            while (!((s = r.readLine()) == null || s.trim().equals(""))) {
38                lineString += s + "\n";
39            }
40
41            long startTime = parse(timeString.split("-->")[0]);
42            long endTime = parse(timeString.split("-->")[1]);
43
44            track.getSubs().add(new TextTrackImpl.Line(startTime, endTime, lineString));
45
46        }
47        return track;
48    }
49
50    private static long parse(String in) {
51        long hours = Long.parseLong(in.split(":")[0].trim());
52        long minutes = Long.parseLong(in.split(":")[1].trim());
53        long seconds = Long.parseLong(in.split(":")[2].split(",")[0].trim());
54        long millies = Long.parseLong(in.split(":")[2].split(",")[1].trim());
55
56        return hours * 60 * 60 * 1000 + minutes * 60 * 1000 + seconds * 1000 + millies;
57
58    }
59}
60