1/*
2 * Copyright 2012 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.authoring.builder;
17
18import com.coremedia.iso.boxes.TimeToSampleBox;
19import com.googlecode.mp4parser.authoring.Movie;
20import com.googlecode.mp4parser.authoring.Track;
21
22import java.util.Arrays;
23import java.util.List;
24
25/**
26 * This <code>FragmentIntersectionFinder</code> cuts the input movie in 2 second
27 * snippets.
28 */
29public class TwoSecondIntersectionFinder implements FragmentIntersectionFinder {
30
31    protected long getDuration(Track track) {
32        long duration = 0;
33        for (TimeToSampleBox.Entry entry : track.getDecodingTimeEntries()) {
34            duration += entry.getCount() * entry.getDelta();
35        }
36        return duration;
37    }
38
39    /**
40     * {@inheritDoc}
41     */
42    public long[] sampleNumbers(Track track, Movie movie) {
43        List<TimeToSampleBox.Entry> entries = track.getDecodingTimeEntries();
44
45        double trackLength = 0;
46        for (Track thisTrack : movie.getTracks()) {
47            double thisTracksLength = getDuration(thisTrack) / thisTrack.getTrackMetaData().getTimescale();
48            if (trackLength < thisTracksLength) {
49                trackLength = thisTracksLength;
50            }
51        }
52
53        int fragmentCount = (int)Math.ceil(trackLength / 2) - 1;
54        if (fragmentCount < 1) {
55            fragmentCount = 1;
56        }
57
58        long fragments[] = new long[fragmentCount];
59        Arrays.fill(fragments, -1);
60        fragments[0] = 1;
61
62        long time = 0;
63        int samples = 0;
64        for (TimeToSampleBox.Entry entry : entries) {
65            for (int i = 0; i < entry.getCount(); i++) {
66                int currentFragment = (int) (time / track.getTrackMetaData().getTimescale() / 2) + 1;
67                if (currentFragment >= fragments.length) {
68                    break;
69                }
70                fragments[currentFragment] = samples++ + 1;
71                time += entry.getDelta();
72            }
73        }
74        long last = samples + 1;
75        // fill all -1 ones.
76        for (int i = fragments.length - 1; i >= 0; i--) {
77            if (fragments[i] == -1) {
78                fragments[i] = last ;
79            }
80            last = fragments[i];
81        }
82        return fragments;
83
84    }
85
86}
87