Java Code Examples for org.mp4parser.IsoFile

The following examples show how to use org.mp4parser.IsoFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: red5-io   Source File: M4AReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates M4A reader from file input stream, sets up metadata generation flag.
 *
 * @param f
 *            File input stream
 * @throws IOException
 *             on IO error
 */
public M4AReader(File f) throws IOException {
    if (null == f) {
        log.warn("Reader was passed a null file");
        log.debug("{}", ToStringBuilder.reflectionToString(this));
    }
    String fileName = f.getName();
    if (fileName.endsWith("m4a") || fileName.endsWith("mp4")) {
        // create a datasource / channel
        dataSource = Files.newByteChannel(Paths.get(f.toURI()));
        // instance an iso file from mp4parser
        isoFile = new IsoFile(dataSource);
        //decode all the info that we want from the atoms
        decodeHeader();
        //analyze the samples/chunks and build the keyframe meta data
        analyzeFrames();
        //add meta data
        firstTags.add(createFileMeta());
        //create / add the pre-streaming (decoder config) tags
        createPreStreamingTags();
    } else {
        log.info("Unsupported file extension: {}", fileName);
    }
}
 
Example 2
Source Project: red5-io   Source File: MP4Reader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates MP4 reader from file input stream, sets up metadata generation flag.
 *
 * @param f
 *            File input stream
 * @throws IOException
 *             on IO exception
 */
public MP4Reader(File f) throws IOException {
    if (null == f) {
        log.warn("Reader was passed a null file");
        log.debug("{}", ToStringBuilder.reflectionToString(this));
    }
    if (f.exists() && f.canRead()) {
        // create a datasource / channel
        dataSource = Files.newByteChannel(Paths.get(f.toURI()));
        // instance an iso file from mp4parser
        isoFile = new IsoFile(dataSource);
        //decode all the info that we want from the atoms
        decodeHeader();
        //analyze the samples/chunks and build the keyframe meta data
        analyzeFrames();
        //add meta data
        firstTags.add(createFileMeta());
        //create / add the pre-streaming (decoder config) tags
        createPreStreamingTags(0, false);
    } else {
        log.warn("Reader was passed an unreadable or non-existant file");
    }
}
 
Example 3
@Override
protected void getContent(ByteBuffer byteBuffer) {
    writeVersionAndFlags(byteBuffer);
    if ((getFlags() & 1) == 1) {
        byteBuffer.put(IsoFile.fourCCtoBytes(auxInfoType));
        byteBuffer.put(IsoFile.fourCCtoBytes(auxInfoTypeParameter));
    }

    IsoTypeWriter.writeUInt32(byteBuffer, offsets.length);
    for (Long offset : offsets) {
        if (getVersion() == 0) {
            IsoTypeWriter.writeUInt32(byteBuffer, offset);
        } else {
            IsoTypeWriter.writeUInt64(byteBuffer, offset);
        }
    }
}
 
Example 4
@Override
protected void getContent(ByteBuffer byteBuffer) {
    writeVersionAndFlags(byteBuffer);
    if ((getFlags() & 1) == 1) {
        byteBuffer.put(IsoFile.fourCCtoBytes(auxInfoType));
        byteBuffer.put(IsoFile.fourCCtoBytes(auxInfoTypeParameter));
    }

    IsoTypeWriter.writeUInt8(byteBuffer, defaultSampleInfoSize);

    if (defaultSampleInfoSize == 0) {
        IsoTypeWriter.writeUInt32(byteBuffer, sampleInfoSizes.length);
        for (short sampleInfoSize : sampleInfoSizes) {
            IsoTypeWriter.writeUInt8(byteBuffer, sampleInfoSize);
        }
    } else {
        IsoTypeWriter.writeUInt32(byteBuffer, sampleCount);
    }
}
 
Example 5
public void testRoundtrip(int sizeOfSampleNum, int lengthSizeOfTrafNum, int lengthSizeOfTrunNum) throws IOException {
    TrackFragmentRandomAccessBox traf = new TrackFragmentRandomAccessBox();
    traf.setLengthSizeOfSampleNum(sizeOfSampleNum);
    traf.setLengthSizeOfTrafNum(lengthSizeOfTrafNum);
    traf.setLengthSizeOfTrunNum(lengthSizeOfTrunNum);
    List<TrackFragmentRandomAccessBox.Entry> entries = new LinkedList<TrackFragmentRandomAccessBox.Entry>();
    entries.add(new TrackFragmentRandomAccessBox.Entry(1, 2, 3, 4, 5));

    traf.setEntries(entries);

    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.deleteOnExit();
    FileChannel fc = new FileOutputStream(f).getChannel();
    traf.getBox(fc);
    fc.close();


    IsoFile isoFile = new IsoFile(new FileInputStream(f).getChannel());
    TrackFragmentRandomAccessBox traf2 = (TrackFragmentRandomAccessBox) isoFile.getBoxes().get(0);
    Assert.assertEquals(traf.getNumberOfEntries(), traf2.getNumberOfEntries());
    Assert.assertEquals(traf.getReserved(), traf2.getReserved());
    Assert.assertEquals(traf.getTrackId(), traf2.getTrackId());
    //System.err.println("" + sizeOfSampleNum + " " + lengthSizeOfTrafNum + " " + lengthSizeOfTrunNum);
    Assert.assertEquals(traf.getEntries(), traf2.getEntries());

}
 
Example 6
public void testParse() throws Exception {
    CompositionToDecodeBox clsg = new CompositionToDecodeBox();
    clsg.setCompositionOffsetToDisplayOffsetShift(2);
    clsg.setDisplayEndTime(3);
    clsg.setDisplayStartTime(4);
    clsg.setGreatestDisplayOffset(-2);
    clsg.setLeastDisplayOffset(-4);


    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    clsg.getBox(Channels.newChannel(baos));
    IsoFile isoFile = new IsoFile(new ByteBufferByteChannel(baos.toByteArray()));

    CompositionToDecodeBox clsg2 = isoFile.getBoxes(CompositionToDecodeBox.class).get(0);
    Assert.assertEquals(baos.toByteArray().length, clsg2.getSize());
    Assert.assertEquals(clsg.getCompositionOffsetToDisplayOffsetShift(), clsg2.getCompositionOffsetToDisplayOffsetShift());
    Assert.assertEquals(clsg.getGreatestDisplayOffset(), clsg2.getGreatestDisplayOffset());
    Assert.assertEquals(clsg.getDisplayEndTime(), clsg2.getDisplayEndTime());
    Assert.assertEquals(clsg.getDisplayStartTime(), clsg2.getDisplayStartTime());
    Assert.assertEquals(clsg.getLeastDisplayOffset(), clsg2.getLeastDisplayOffset());


}
 
Example 7
Source Project: mp4parser   Source File: FreeBoxTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tesAddAndReplace() throws IOException {

    FreeBox fb = new FreeBox(1000);
    long startSize = fb.getSize();
    ByteBuffer data = fb.getData();
    ((Buffer)data).position(994);
    data.put(new byte[]{1, 2, 3, 4, 5, 6});
    FreeSpaceBox fsb = new FreeSpaceBox();
    fsb.setData(new byte[100]);
    fb.addAndReplace(fsb);
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.deleteOnExit();
    FileChannel fc = new FileOutputStream(f).getChannel();
    fb.getBox(fc);
    fc.close();

    IsoFile isoFile = new IsoFile(new FileInputStream(f).getChannel());
    Assert.assertEquals(2, isoFile.getBoxes().size());
    Assert.assertEquals(FreeSpaceBox.TYPE, isoFile.getBoxes().get(0).getType());
    Assert.assertEquals(FreeBox.TYPE, isoFile.getBoxes().get(1).getType());
    Assert.assertEquals(startSize, isoFile.getBoxes().get(0).getSize() + isoFile.getBoxes().get(1).getSize());
}
 
Example 8
@Test
public void roundTripFlags0() throws IOException {
    SampleAuxiliaryInformationSizesBox saiz1 = new SampleAuxiliaryInformationSizesBox();
    short[] ss = new short[]{1, 11, 10, 100};
    saiz1.setSampleInfoSizes(ss);
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    FileChannel fc = new FileOutputStream(f).getChannel();
    saiz1.getBox(fc);
    fc.close();

    IsoFile isoFile = new IsoFile(new FileInputStream(f).getChannel());
    SampleAuxiliaryInformationSizesBox saiz2 = (SampleAuxiliaryInformationSizesBox) isoFile.getBoxes().get(0);

    Assert.assertEquals(saiz1.getDefaultSampleInfoSize(), saiz2.getDefaultSampleInfoSize());
    Assert.assertArrayEquals(saiz1.getSampleInfoSizes(), saiz2.getSampleInfoSizes());


}
 
Example 9
@Test
public void roundTripFlags1() throws IOException {
    SampleAuxiliaryInformationSizesBox saiz1 = new SampleAuxiliaryInformationSizesBox();
    saiz1.setFlags(1);
    saiz1.setAuxInfoType("piff");
    saiz1.setAuxInfoTypeParameter("trak");
    short[] ss = new short[]{1, 11, 10, 100};
    saiz1.setSampleInfoSizes(ss);
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.deleteOnExit();
    FileChannel fc = new FileOutputStream(f).getChannel();
    saiz1.getBox(fc);
    fc.close();

    IsoFile isoFile = new IsoFile(new FileInputStream(f).getChannel());
    SampleAuxiliaryInformationSizesBox saiz2 = (SampleAuxiliaryInformationSizesBox) isoFile.getBoxes().get(0);

    Assert.assertEquals(saiz1.getDefaultSampleInfoSize(), saiz2.getDefaultSampleInfoSize());
    Assert.assertArrayEquals(saiz1.getSampleInfoSizes(), saiz2.getSampleInfoSizes());
    Assert.assertEquals(saiz1.getAuxInfoType(), saiz2.getAuxInfoType());
    Assert.assertEquals(saiz1.getAuxInfoTypeParameter(), saiz2.getAuxInfoTypeParameter());


}
 
Example 10
Source Project: mp4parser   Source File: ItemLocationBoxTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSimpleRoundWithEntriesTrip(int baseOffsetSize, int indexSize, int lengthSize, int offsetSize) throws IOException {
    ItemLocationBox ilocOrig = new ItemLocationBox();
    ilocOrig.setVersion(1);
    ilocOrig.setBaseOffsetSize(baseOffsetSize);
    ilocOrig.setIndexSize(indexSize);
    ilocOrig.setLengthSize(lengthSize);
    ilocOrig.setOffsetSize(offsetSize);
    ItemLocationBox.Item item = ilocOrig.createItem(12, 0, 13, 123, Collections.<ItemLocationBox.Extent>emptyList());
    ilocOrig.setItems(Collections.singletonList(item));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ilocOrig.getBox(Channels.newChannel(baos));

    IsoFile isoFile = new IsoFile(new ByteBufferByteChannel(baos.toByteArray()));

    ItemLocationBox iloc = (ItemLocationBox) isoFile.getBoxes().get(0);

    Assert.assertEquals(ilocOrig.getBaseOffsetSize(), iloc.getBaseOffsetSize());
    Assert.assertEquals(ilocOrig.getContentSize(), iloc.getContentSize());
    Assert.assertEquals(ilocOrig.getIndexSize(), iloc.getIndexSize());
    Assert.assertEquals(ilocOrig.getLengthSize(), iloc.getLengthSize());
    Assert.assertEquals(ilocOrig.getOffsetSize(), iloc.getOffsetSize());
    Assert.assertEquals(ilocOrig.getItems(), iloc.getItems());


}
 
Example 11
Source Project: mp4parser   Source File: AbstractTrackEncryptionBoxTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRoundTrip() throws IOException {
    tenc.setDefault_KID(UUIDConverter.convert(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}));
    tenc.setDefaultAlgorithmId(0x0a0b0c);
    tenc.setDefaultIvSize(8);


    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.deleteOnExit();
    FileChannel fc = new FileOutputStream(f).getChannel();
    tenc.getBox(fc);
    fc.close();

    IsoFile iso = new IsoFile(new FileInputStream(f).getChannel());
    Assert.assertTrue(iso.getBoxes().get(0) instanceof AbstractTrackEncryptionBox);
    AbstractTrackEncryptionBox tenc2 = (AbstractTrackEncryptionBox) iso.getBoxes().get(0);
    Assert.assertEquals(0, tenc2.getFlags());
    Assert.assertTrue(tenc.equals(tenc2));
    Assert.assertTrue(tenc2.equals(tenc));
    iso.close();

}
 
Example 12
Source Project: mp4parser   Source File: VTTCueBox.java    License: Apache License 2.0 6 votes vote down vote up
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
    ByteBuffer header = ByteBuffer.allocate(8);
    IsoTypeWriter.writeUInt32(header, getSize());
    header.put(IsoFile.fourCCtoBytes(getType()));
    writableByteChannel.write((ByteBuffer) ((Buffer)header).rewind());
    if (cueSourceIDBox != null) {
        cueSourceIDBox.getBox(writableByteChannel);
    }
    if (cueIDBox != null) {
        cueIDBox.getBox(writableByteChannel);
    }
    if (cueTimeBox != null) {
        cueTimeBox.getBox(writableByteChannel);
    }
    if (cueSettingsBox != null) {
        cueSettingsBox.getBox(writableByteChannel);
    }
    if (cuePayloadBox != null) {
        cuePayloadBox.getBox(writableByteChannel);
    }
}
 
Example 13
Source Project: mp4parser   Source File: Avc1ToAvc3TrackImpl.java    License: Apache License 2.0 6 votes vote down vote up
public Avc1ToAvc3TrackImpl(Track parent) throws IOException {
    super(parent);
    for (SampleEntry sampleEntry : parent.getSampleEntries()) {
        if (sampleEntry.getType().equals("avc1")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                // This creates a copy cause I can't change the original instance
                sampleEntry.getBox(Channels.newChannel(baos));
                VisualSampleEntry avc3SampleEntry = (VisualSampleEntry) new IsoFile(new ByteBufferByteChannel(ByteBuffer.wrap(baos.toByteArray()))).getBoxes().get(0);
                avc3SampleEntry.setType("avc3");
                avc1toavc3.put(sampleEntry, avc3SampleEntry);
            } catch (IOException e) {
                throw new RuntimeException("Dumping sample entry to memory failed");
            }
        } else {
            avc1toavc3.put(sampleEntry, sampleEntry);
        }

    }

    samples = new ReplaceSyncSamplesList(parent.getSamples());
}
 
Example 14
Source Project: mp4parser   Source File: MovieCreator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates <code>Movie</code> object from a <code>ReadableByteChannel</code>.
 *
 * @param name                track name to identify later
 * @param readableByteChannel the box structure is read from this channel
 * @param randomAccessSource  the samples or read from this randomAccessSource
 * @return a representation of the movie
 * @throws IOException in case of I/O error during IsoFile creation
 */
public static Movie build(ReadableByteChannel readableByteChannel, RandomAccessSource randomAccessSource, String name) throws IOException {
    IsoFile isoFile = new IsoFile(readableByteChannel);
    Movie m = new Movie();
    List<TrackBox> trackBoxes = isoFile.getMovieBox().getBoxes(TrackBox.class);
    for (TrackBox trackBox : trackBoxes) {
        SchemeTypeBox schm = Path.getPath(trackBox, "mdia[0]/minf[0]/stbl[0]/stsd[0]/enc.[0]/sinf[0]/schm[0]");
        if (schm != null && (schm.getSchemeType().equals("cenc") || schm.getSchemeType().equals("cbc1"))) {
            m.addTrack(new CencMp4TrackImplImpl(
                    trackBox.getTrackHeaderBox().getTrackId(), isoFile,
                    randomAccessSource, name + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]"));
        } else if (schm != null && (schm.getSchemeType().equals("piff"))) {
            m.addTrack(new PiffMp4TrackImpl(
                    trackBox.getTrackHeaderBox().getTrackId(), isoFile,
                    randomAccessSource, name + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]"));
        } else {
            m.addTrack(new Mp4TrackImpl(
                    trackBox.getTrackHeaderBox().getTrackId(), isoFile,
                    randomAccessSource, name + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]"));
        }
    }
    m.setMatrix(isoFile.getMovieBox().getMovieHeaderBox().getMatrix());
    return m;
}
 
Example 15
Source Project: mp4parser   Source File: H264TrackImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void freeze() throws IOException {
    DataSource fc = new FileDataSourceImpl(getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + "/org/mp4parser/muxer/tracks/h264-sample.h264");
    H264TrackImpl.BUFFER = 65535; // make sure we are not just in one buffer
    Track t = new H264TrackImpl(fc);
    Movie m = new Movie();
    m.addTrack(t);

    DefaultMp4Builder mp4Builder = new DefaultMp4Builder();
    Container c = mp4Builder.build(m);

  // c.writeContainer(new FileOutputStream("/Users/sannies/dev/mp4parser/muxer/src/test/resources/org/mp4parser/muxer/tracks/h264-sample.mp4").getChannel());


    IsoFile isoFileReference = new IsoFile(getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + "org/mp4parser/muxer/tracks/h264-sample.mp4");
    BoxComparator.check(c, isoFileReference, "moov[0]/mvhd[0]", "moov[0]/trak[0]/tkhd[0]", "moov[0]/trak[0]/mdia[0]/mdhd[0]", "moov[0]/trak[0]/mdia[0]/minf[0]/stbl[0]/stco[0]");
}
 
Example 16
Source Project: mp4parser   Source File: DTSTrackImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void checkOutputIsStable() throws Exception {
    Movie m = new Movie();
    DTSTrackImpl dts = new DTSTrackImpl(new FileDataSourceImpl(DTSTrackImplTest.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/org/mp4parser/muxer/tracks/dts-sample.dtshd"));
    m.addTrack(dts);
    Fragmenter fif = new StaticFragmentIntersectionFinderImpl(Collections.singletonMap((Track) dts, new long[]{1}));
    DefaultMp4Builder mp4Builder = new DefaultMp4Builder();
    mp4Builder.setFragmenter(fif);
    Container c = mp4Builder.build(m);

    // c.writeContainer(new FileOutputStream("C:\\dev\\mp4parser\\isoparser\\src\\test\\resources\\com\\googlecode\\mp4parser\\authoring\\tracks\\dts-sample.mp4").getChannel());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    c.writeContainer(Channels.newChannel(baos));
    IsoFile ref = new IsoFile(
            new FileInputStream(DTSTrackImplTest.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/org/mp4parser/muxer/tracks/dts-sample.mp4").getChannel());
    BoxComparator.check(ref, c, "moov[0]/mvhd[0]", "moov[0]/trak[0]/tkhd[0]", "moov[0]/trak[0]/mdia[0]/mdhd[0]");


}
 
Example 17
Source Project: mp4parser   Source File: SequenceParameterSetRbspTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test1() throws IOException {
    byte[] hecCBytes = Hex.decodeHex("0000009068766343010220000000B0000000000096F000FCFDFAFA00000F03200001002040010C01FFFF022000000300B0000003000003009698903000003E900005DC052100010039420101022000000300B00000030000030096A001E020021C4D94626491B6BC05A84880482000007D20000BB80C25BDEFC0006C948000BEBC1022000100094401C1625B162C1ED9");
    HevcConfigurationBox hvcC = (HevcConfigurationBox) new IsoFile(Channels.newChannel(new ByteArrayInputStream(hecCBytes))).getBoxes().get(0);
    for (HevcDecoderConfigurationRecord.Array array : hvcC.getArrays()) {
        if (array.nal_unit_type == 33) {
            for (byte[] nalUnit : array.nalUnits) {
                InputStream bais = new CleanInputStream(new ByteArrayInputStream(nalUnit));
                bais.read(); // nal unit header
                bais.read(); // nal unit header
                SequenceParameterSetRbsp sps = new SequenceParameterSetRbsp(bais);
                Assert.assertTrue(sps.vuiParameters.colour_description_present_flag);
                Assert.assertEquals(9,sps.vuiParameters.colour_primaries);
                Assert.assertEquals(16,sps.vuiParameters.transfer_characteristics);
                Assert.assertEquals(9,sps.vuiParameters.matrix_coeffs);
            }
        }
    }

}
 
Example 18
Source Project: mp4parser   Source File: MetaDataInsert.java    License: Apache License 2.0 6 votes vote down vote up
private boolean needsOffsetCorrection(IsoFile isoFile) {
    if (Path.getPath(isoFile, "moov[0]/mvex[0]") != null) {
        // Fragmented files don't need a correction
        return false;
    } else {
        // no correction needed if mdat is before moov as insert into moov want change the offsets of mdat
        for (Box box : isoFile.getBoxes()) {
            if ("moov".equals(box.getType())) {
                return true;
            }
            if ("mdat".equals(box.getType())) {
                return false;
            }
        }
        throw new RuntimeException("I need moov or mdat. Otherwise all this doesn't make sense");
    }
}
 
Example 19
Source Project: mp4parser   Source File: MetaDataRead.java    License: Apache License 2.0 6 votes vote down vote up
public String read(String videoFilePath) throws IOException {

        File videoFile = new File(videoFilePath);
        if (!videoFile.exists()) {
            throw new FileNotFoundException("File " + videoFilePath + " not exists");
        }

        if (!videoFile.canRead()) {
            throw new IllegalStateException("No read permissions to file " + videoFilePath);
        }
        IsoFile isoFile = new IsoFile(new FileInputStream(videoFilePath).getChannel());

        AppleNameBox nam = Path.getPath(isoFile, "/moov[0]/udta[0]/meta[0]/ilst/©nam");
        String xml = nam.getValue();
        isoFile.close();
        return xml;
    }
 
Example 20
Source Project: mp4parser   Source File: Avc1ToAvc3Example.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    String f = Avc1ToAvc3Example.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/1365070268951.mp4";
    Movie m = MovieCreator.build(new FileInputStream(f).getChannel(), new FileRandomAccessSourceImpl(new RandomAccessFile(f, "r")), "inmem");

    Movie m2 = new Movie();

    for (Track track : m.getTracks()) {
        if (track.getSampleEntries().get(0).getType().equals("avc1")) {
            m2.addTrack(new Avc1ToAvc3TrackImpl(track));
        } else {
            m2.addTrack(track);
        }
    }

    new FragmentedMp4Builder().build(m2).writeContainer(new FileOutputStream("output.mp4").getChannel());

    IsoFile i = new IsoFile("output.mp4");
    for (Box box : i.getBoxes()) {
        System.err.println(box + "@-nooffsets");
    }
}
 
Example 21
Source Project: mp4parser   Source File: VideoAudioChecker.java    License: Apache License 2.0 6 votes vote down vote up
public static TYPE getType(IsoFile isoFile) {

        List<HandlerBox> handlerBoxes =
                isoFile.getBoxes(HandlerBox.class, true);
        for (HandlerBox handlerBox : handlerBoxes) {
            if ("vide".equals(handlerBox.getHandlerType())) {
                return TYPE.VIDEO;
            } else if ("soun".equals(handlerBox.getHandlerType())) {
                return TYPE.AUDIO;
            } else {
                System.err.println("unknown");
            }

        }
        return TYPE.AUDIO;
    }
 
Example 22
Source Project: mp4parser   Source File: MetaDataTool.java    License: Apache License 2.0 6 votes vote down vote up
public MetaDataTool(String path) throws IOException {

        //The source I copied this from created 2 new files, a temp file and a target file
        //I'm not sure this is necessary, but maybe when you make changes it's edited in-place?
        //Anyway, just to be safe I'm keeping it so no operations are done on original file
        File videoFile = new File(path);
        if (!videoFile.exists())
            throw new FileNotFoundException("File " + path + " not exists");

        if (!videoFile.canWrite())
            throw new IllegalStateException("No write permissions to file " + path);

        File tempFile = File.createTempFile("ChangeMetaData", "");
        FileUtils.copyFile(videoFile, tempFile);
        tempFile.deleteOnExit();

        isoFile = new IsoFile(tempFile.getAbsolutePath());
        userDataBox = Path.getPath(isoFile, "/moov/udta");
        if (userDataBox != null) {
            originalUserDataSize = userDataBox.getSize();
        }

    }
 
Example 23
Source Project: mp4parser   Source File: MetaDataTool.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean needsOffsetCorrection(IsoFile isoFile) {

        if (Path.getPaths(isoFile, "mdat").size() > 1) {
            throw new RuntimeException("There might be the weird case that a file has two mdats. One before" +
                    " moov and one after moov. That would need special handling therefore I just throw an " +
                    "exception here. ");
        }

        if (Path.getPaths(isoFile, "moof").size() > 0) {
            throw new RuntimeException("Fragmented MP4 files need correction, too. (But I would need to look where)");
        }

        for (Box box : isoFile.getBoxes()) {
            if ("mdat".equals(box.getType())) {
                return false;
            }
            if ("moov".equals(box.getType())) {
                return true;
            }
        }
        throw new RuntimeException("Hmmm - shouldn't happen");
    }
 
Example 24
Source Project: mp4parser   Source File: MetaDataTool.java    License: Apache License 2.0 6 votes vote down vote up
private static void correctChunkOffsets(IsoFile tempIsoFile, long correction) {
    List<SampleTableBox> sampleTableBoxes = Path.getPaths(tempIsoFile, "/moov[0]/trak/mdia[0]/minf[0]/stbl[0]");

    for (SampleTableBox sampleTableBox : sampleTableBoxes) {

        List<Box> stblChildren = new ArrayList<Box>(sampleTableBox.getBoxes());
        ChunkOffsetBox chunkOffsetBox = Path.getPath(sampleTableBox, "stco");
        if (chunkOffsetBox == null) {
            stblChildren.remove(Path.getPath(sampleTableBox, "co64"));
        }
        stblChildren.remove(chunkOffsetBox);

        assert chunkOffsetBox != null;
        long[] cOffsets = chunkOffsetBox.getChunkOffsets();
        for (int i = 0; i < cOffsets.length; i++) {
            cOffsets[i] += correction;
        }

        StaticChunkOffsetBox cob = new StaticChunkOffsetBox();
        cob.setChunkOffsets(cOffsets);
        stblChildren.add(cob);
        sampleTableBox.setBoxes(stblChildren);
    }
}
 
Example 25
Source Project: mp4parser   Source File: MostSimpleDashExample.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    String basePath = GetDuration.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/dash/";

    Movie m = new Movie();
    IsoFile baseIsoFile = new IsoFile(basePath + "redbull_100kbit_dash.mp4");
    List<IsoFile> fragments = new LinkedList<IsoFile>();
    for (int i = 1; i < 9; i++) {
        fragments.add(new IsoFile(basePath + "redbull_10sec" + i + ".m4s"));
    }

    m.addTrack(new Mp4TrackImpl(1, new IsoFile("redbull_100kbit_dash.mp4"), new FileRandomAccessSourceImpl(new RandomAccessFile("redbull_100kbit_dash.mp4", "r")), "test"));


    DefaultMp4Builder builder = new DefaultMp4Builder();
    Container stdMp4 = builder.build(m);
    FileOutputStream fos = new FileOutputStream("out.mp4");
    stdMp4.writeContainer(fos.getChannel());
    fos.close();
}
 
Example 26
Source Project: mp4parser   Source File: MjpegTest.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    IsoFile isofile = new IsoFile("C:\\content\\bbb-small\\output_320x180-mjpeg.mp4");
    ESDescriptorBox esDescriptorBox = Path.getPath(isofile, "/moov[0]/trak[0]/mdia[0]/minf[0]/stbl[0]/stsd[0]/mp4v[0]/esds[0]");
    byte[] d = new byte[((Buffer)esDescriptorBox.getData()).rewind().remaining()];
    esDescriptorBox.getData().get(d);
    System.err.println(Hex.encodeHex(d));

    Movie mRef = MovieCreator.build("C:\\content\\bbb-small\\output_320x180_150.mp4");
    Track refTrack = mRef.getTracks().get(0);

    File baseDir = new File("C:\\content\\bbb-small");
    File[] iFrameJpegs = baseDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jpg");
        }
    });
    Arrays.sort(iFrameJpegs);

    Movie mRes = new Movie();
    mRes.addTrack(new OneJpegPerIframe("iframes", iFrameJpegs, refTrack));

    new DefaultMp4Builder().build(mRes).writeContainer(new FileOutputStream("output-mjpeg.mp4").getChannel());
}
 
Example 27
Source Project: mp4parser   Source File: AdtsAacStreamingTrackTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMuxing() throws Exception {
    AdtsAacStreamingTrack b = new AdtsAacStreamingTrack(AdtsAacStreamingTrackTest.class.getResourceAsStream("/org/mp4parser/streaming/input/aac/somesound.aac"), 65000, 80000);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new FragmentedMp4Writer(Collections.<StreamingTrack>singletonList(b), Channels.newChannel(baos));
    //MultiTrackFragmentedMp4Writer writer = new MultiTrackFragmentedMp4Writer(new StreamingTrack[]{b}, new ByteArrayOutputStream());
    b.call();
    IsoFile isoFile = new IsoFile(Channels.newChannel(new ByteArrayInputStream(baos.toByteArray())));
    new FileOutputStream("output.mp4").write(baos.toByteArray());
    Walk.through(isoFile);
    List<Sample> s = new Mp4SampleList(1, isoFile, new InMemRandomAccessSourceImpl(baos.toByteArray()));
    for (Sample sample : s) {
        //System.err.println("s: " + sample.getSize());
        sample.asByteBuffer();
    }


}
 
Example 28
Source Project: mp4parser   Source File: H264AnnexBTrackTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void testMuxing() throws Exception {
        H264AnnexBTrack b = new H264AnnexBTrack(H264AnnexBTrackTest.class.getResourceAsStream("/org/mp4parser/streaming/input/h264/tos.h264"));
        //H264AnnexBTrack b = new H264AnnexBTrack(new FileInputStream("C:\\dev\\mp4parser\\out.264"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FragmentedMp4Writer writer = new FragmentedMp4Writer(Collections.<StreamingTrack>singletonList(b), Channels.newChannel(baos));
        //MultiTrackFragmentedMp4Writer writer = new MultiTrackFragmentedMp4Writer(new StreamingTrack[]{b}, new ByteArrayOutputStream());
        b.call();
        writer.close();
        IsoFile isoFile = new IsoFile(Channels.newChannel(new ByteArrayInputStream(baos.toByteArray())));
        Walk.through(isoFile);
        List<Sample> s = new Mp4SampleList(1, isoFile, new InMemRandomAccessSourceImpl(baos.toByteArray()));
        for (Sample sample : s) {
//            System.err.println("s: " + sample.getSize());
            sample.asByteBuffer();
        }
    }
 
Example 29
Source Project: dashencrypt   Source File: DumpBox.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public int run() {
    try (IsoFile isoFile = new IsoFile(inputFile)){
        List<Box> boxes = Path.getPaths(isoFile, path);
        for (Box box : boxes) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            box.getBox(Channels.newChannel(baos));
            System.out.println(Hex.encodeHex(baos.toByteArray()));
            System.out.println();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return 6482;
    }
    return 0;
}
 
Example 30
Source Project: dashencrypt   Source File: DashHelperTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public void testGetChannelConfiguration() throws Exception {
    byte[] ec3_1 = Hex.decodeHex("0000003265632D33000000000000000100000000000000000002001000000000BB8000000000000E646563330868200F0084");
    byte[] ec3_2 = Hex.decodeHex("0000003265632D33000000000000000100000000000000000002001000000000BB8000000000000E646563330C00200F0202");

    IsoFile isoFile1 = new IsoFile(Channels.newChannel(new ByteArrayInputStream(ec3_1)));
    DashHelper2.ChannelConfiguration channelConfiguration1 = DashHelper2.getChannelConfiguration((AudioSampleEntry) isoFile1.getBoxes().get(0));
    Assert.assertEquals("urn:dolby:dash:audio_channel_configuration:2011", channelConfiguration1.schemeIdUri);
    Assert.assertEquals("F801", channelConfiguration1.value);

    IsoFile isoFile2 = new IsoFile(Channels.newChannel(new ByteArrayInputStream(ec3_2)));
    DashHelper2.ChannelConfiguration channelConfiguration2 = DashHelper2.getChannelConfiguration((AudioSampleEntry) isoFile2.getBoxes().get(0));
    Assert.assertEquals("urn:dolby:dash:audio_channel_configuration:2011", channelConfiguration2.schemeIdUri);
    Assert.assertEquals("FA01", channelConfiguration2.value);
}