Skip to content

Commit

Permalink
simple shorten example
Browse files Browse the repository at this point in the history
  • Loading branch information
sannies committed May 8, 2015
1 parent e9c8e69 commit d2d3b07
Showing 1 changed file with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.googlecode.mp4parser;

import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.CroppedTrack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
* Shortens/Crops a track
*/
public class SingleTrackShortenExample {


public static void main(String[] args) throws IOException {
//Movie movie = new MovieCreator().build(new RandomAccessFile("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov", "r").getChannel());
Movie movie = MovieCreator.build("C:\\content\\843D111F-E839-4597-B60C-3B8114E0AA72_ABR05.mp4");

List<Track> tracks = movie.getTracks();
assert tracks.size() == 1;
Track track = movie.getTracks().get(0);

movie.setTracks(new LinkedList<Track>());
// remove all tracks we will create new tracks from the old

double startTime = 10;
double endTime = 20;

long startSample = findNextSyncSample(track, startTime);
long endSample = findNextSyncSample(track, endTime);

movie.addTrack(new CroppedTrack(track, startSample, endSample));

Container out = new DefaultMp4Builder().build(movie);
FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime));
FileChannel fc = fos.getChannel();
out.writeContainer(fc);
fc.close();
fos.close();
}


private static long findNextSyncSample(Track track, double cutHere) {
long currentSample = 0;
double currentTime = 0;
long[] durations = track.getSampleDurations();
long[] syncSamples = track.getSyncSamples();
for (int i = 0; i < durations.length; i++) {
long delta = durations[i];

if ((syncSamples == null || syncSamples.length > 0 || Arrays.binarySearch(syncSamples, currentSample + 1) >= 0)
&& currentTime > cutHere) {
return i;
}
currentTime += (double) delta / (double) track.getTrackMetaData().getTimescale();
currentSample++;
}
return currentSample;
}


}

0 comments on commit d2d3b07

Please sign in to comment.