rlm@10: /** rlm@10: * @(#)AVIOutputStream.java 1.5.1 2011-01-17 rlm@10: * rlm@10: * Copyright (c) 2008-2011 Werner Randelshofer, Immensee, Switzerland. rlm@10: * All rights reserved. rlm@10: * rlm@10: * You may not use, copy or modify this file, except in compliance with the rlm@10: * license agreement you entered into with Werner Randelshofer. rlm@10: * For details see accompanying license terms. rlm@10: */ rlm@10: package ca.randelshofer; rlm@10: rlm@10: import java.awt.Dimension; rlm@10: import java.awt.image.BufferedImage; rlm@10: import java.awt.image.DataBufferByte; rlm@10: import java.awt.image.IndexColorModel; rlm@10: import java.awt.image.WritableRaster; rlm@10: import java.io.File; rlm@10: import java.io.FileInputStream; rlm@10: import java.io.IOException; rlm@10: import java.io.InputStream; rlm@10: import java.io.OutputStream; rlm@10: import java.util.Arrays; rlm@10: import java.util.Date; rlm@10: import java.util.LinkedList; rlm@10: rlm@10: import javax.imageio.IIOImage; rlm@10: import javax.imageio.ImageIO; rlm@10: import javax.imageio.ImageWriteParam; rlm@10: import javax.imageio.ImageWriter; rlm@10: import javax.imageio.stream.FileImageOutputStream; rlm@10: import javax.imageio.stream.ImageOutputStream; rlm@10: import javax.imageio.stream.MemoryCacheImageOutputStream; rlm@10: rlm@10: /** rlm@10: * This class supports writing of images into an AVI 1.0 video file. rlm@10: *

rlm@10: * The images are written as video frames. rlm@10: *

rlm@10: * Video frames can be encoded with one of the following formats: rlm@10: *

rlm@10: * All frames must have the same format. rlm@10: * When JPG is used each frame can have an individual encoding quality. rlm@10: *

rlm@10: * All frames in an AVI file must have the same duration. The duration can rlm@10: * be set by setting an appropriate pair of values using methods rlm@10: * {@link #setFrameRate} and {@link #setTimeScale}. rlm@10: *

rlm@10: * The length of an AVI 1.0 file is limited to 1 GB. rlm@10: * This class supports lengths of up to 4 GB, but such files may not work on rlm@10: * all players. rlm@10: *

rlm@10: * For detailed information about the AVI RIFF file format see:
rlm@10: * msdn.microsoft.com AVI RIFF
rlm@10: * www.microsoft.com FOURCC for Video Compression
rlm@10: * www.saettler.com RIFF
rlm@10: * rlm@10: * @author Werner Randelshofer rlm@10: * @version 1.5.1 2011-01-17 Fixes unintended closing of output stream.. rlm@10: *
1.5 2011-01-06 Adds support for RLE 8-bit video format. rlm@10: *
1.4 2011-01-04 Adds support for RAW 4-bit and 8-bit video format. Fixes offsets rlm@10: * in "idx1" chunk. rlm@10: *
1.3.2 2010-12-27 File size limit is 1 GB. rlm@10: *
1.3.1 2010-07-19 Fixes seeking and calculation of offsets. rlm@10: *
1.3 2010-07-08 Adds constructor with ImageOutputStream. rlm@10: * Added method getVideoDimension(). rlm@10: *
1.2 2009-08-29 Adds support for RAW video format. rlm@10: *
1.1 2008-08-27 Fixes computation of dwMicroSecPerFrame in avih rlm@10: * chunk. Changed the API to reflect that AVI works with frame rates instead of rlm@10: * with frame durations. rlm@10: *
1.0.1 2008-08-13 Uses FourCC "MJPG" instead of "jpg " for JPG rlm@10: * encoded video. rlm@10: *
1.0 2008-08-11 Created. rlm@10: */ rlm@10: public class AVIOutputStream { rlm@10: rlm@10: /** rlm@10: * Underlying output stream. rlm@10: */ rlm@10: private ImageOutputStream out; rlm@10: /** The offset of the QuickTime stream in the underlying ImageOutputStream. rlm@10: * Normally this is 0 unless the underlying stream already contained data rlm@10: * when it was passed to the constructor. rlm@10: */ rlm@10: private long streamOffset; rlm@10: /** Previous frame for delta compression. */ rlm@10: rlm@10: /** rlm@10: * Supported video encodings. rlm@10: */ rlm@10: public static enum VideoFormat { rlm@10: rlm@10: RAW, RLE, JPG, PNG; rlm@10: } rlm@10: /** rlm@10: * Current video formats. rlm@10: */ rlm@10: private VideoFormat videoFormat; rlm@10: /** rlm@10: * Quality of JPEG encoded video frames. rlm@10: */ rlm@10: private float quality = 0.9f; rlm@10: /** rlm@10: * Width of the video frames. All frames must have the same width. rlm@10: * The value -1 is used to mark unspecified width. rlm@10: */ rlm@10: private int imgWidth = -1; rlm@10: /** rlm@10: * Height of the video frames. All frames must have the same height. rlm@10: * The value -1 is used to mark unspecified height. rlm@10: */ rlm@10: private int imgHeight = -1; rlm@10: /** Number of bits per pixel. */ rlm@10: private int imgDepth = 24; rlm@10: /** Index color model for RAW_RGB4 and RAW_RGB8 formats. */ rlm@10: private IndexColorModel palette; rlm@10: private IndexColorModel previousPalette; rlm@10: /** Video encoder. */ rlm@10: rlm@10: /** rlm@10: * The timeScale of the movie. rlm@10: *

rlm@10: * Used with frameRate to specify the time scale that this stream will use. rlm@10: * Dividing frameRate by timeScale gives the number of samples per second. rlm@10: * For video streams, this is the frame rate. For audio streams, this rate rlm@10: * corresponds to the time needed to play nBlockAlign bytes of audio, which rlm@10: * for PCM audio is the just the sample rate. rlm@10: */ rlm@10: private int timeScale = 1; rlm@10: /** rlm@10: * The frameRate of the movie in timeScale units. rlm@10: *

rlm@10: * @see timeScale rlm@10: */ rlm@10: private int frameRate = 30; rlm@10: /** rlm@10: * The states of the movie output stream. rlm@10: */ rlm@10: private static enum States { rlm@10: rlm@10: STARTED, FINISHED, CLOSED; rlm@10: } rlm@10: /** rlm@10: * The current state of the movie output stream. rlm@10: */ rlm@10: private States state = States.FINISHED; rlm@10: rlm@10: /** rlm@10: * AVI stores media data in samples. rlm@10: * A sample is a single element in a sequence of time-ordered data. rlm@10: */ rlm@10: private static class Sample { rlm@10: rlm@10: String chunkType; rlm@10: /** Offset of the sample relative to the start of the AVI file. rlm@10: */ rlm@10: long offset; rlm@10: /** Data length of the sample. */ rlm@10: long length; rlm@10: /** Whether the sample is a sync-sample. */ rlm@10: boolean isSync; rlm@10: rlm@10: /** rlm@10: * Creates a new sample. rlm@10: * @param duration rlm@10: * @param offset rlm@10: * @param length rlm@10: */ rlm@10: public Sample(String chunkId, int duration, long offset, long length, boolean isSync) { rlm@10: this.chunkType = chunkId; rlm@10: this.offset = offset; rlm@10: this.length = length; rlm@10: this.isSync = isSync; rlm@10: } rlm@10: } rlm@10: /** rlm@10: * List of video frames. rlm@10: */ rlm@10: private LinkedList videoFrames; rlm@10: /** rlm@10: * This chunk holds the whole AVI content. rlm@10: */ rlm@10: private CompositeChunk aviChunk; rlm@10: /** rlm@10: * This chunk holds the movie frames. rlm@10: */ rlm@10: private CompositeChunk moviChunk; rlm@10: /** rlm@10: * This chunk holds the AVI Main Header. rlm@10: */ rlm@10: FixedSizeDataChunk avihChunk; rlm@10: /** rlm@10: * This chunk holds the AVI Stream Header. rlm@10: */ rlm@10: FixedSizeDataChunk strhChunk; rlm@10: /** rlm@10: * This chunk holds the AVI Stream Format Header. rlm@10: */ rlm@10: FixedSizeDataChunk strfChunk; rlm@10: rlm@10: /** rlm@10: * Chunk base class. rlm@10: */ rlm@10: private abstract class Chunk { rlm@10: rlm@10: /** rlm@10: * The chunkType of the chunk. A String with the length of 4 characters. rlm@10: */ rlm@10: protected String chunkType; rlm@10: /** rlm@10: * The offset of the chunk relative to the start of the rlm@10: * ImageOutputStream. rlm@10: */ rlm@10: protected long offset; rlm@10: rlm@10: /** rlm@10: * Creates a new Chunk at the current position of the ImageOutputStream. rlm@10: * @param chunkType The chunkType of the chunk. A string with a length of 4 characters. rlm@10: */ rlm@10: public Chunk(String chunkType) throws IOException { rlm@10: this.chunkType = chunkType; rlm@10: offset = getRelativeStreamPosition(); rlm@10: } rlm@10: rlm@10: /** rlm@10: * Writes the chunk to the ImageOutputStream and disposes it. rlm@10: */ rlm@10: public abstract void finish() throws IOException; rlm@10: rlm@10: /** rlm@10: * Returns the size of the chunk including the size of the chunk header. rlm@10: * @return The size of the chunk. rlm@10: */ rlm@10: public abstract long size(); rlm@10: } rlm@10: rlm@10: /** rlm@10: * A CompositeChunk contains an ordered list of Chunks. rlm@10: */ rlm@10: private class CompositeChunk extends Chunk { rlm@10: rlm@10: /** rlm@10: * The type of the composite. A String with the length of 4 characters. rlm@10: */ rlm@10: protected String compositeType; rlm@10: private LinkedList children; rlm@10: private boolean finished; rlm@10: rlm@10: /** rlm@10: * Creates a new CompositeChunk at the current position of the rlm@10: * ImageOutputStream. rlm@10: * @param compositeType The type of the composite. rlm@10: * @param chunkType The type of the chunk. rlm@10: */ rlm@10: public CompositeChunk(String compositeType, String chunkType) throws IOException { rlm@10: super(chunkType); rlm@10: this.compositeType = compositeType; rlm@10: //out.write rlm@10: out.writeLong(0); // make room for the chunk header rlm@10: out.writeInt(0); // make room for the chunk header rlm@10: children = new LinkedList(); rlm@10: } rlm@10: rlm@10: public void add(Chunk child) throws IOException { rlm@10: if (children.size() > 0) { rlm@10: children.getLast().finish(); rlm@10: } rlm@10: children.add(child); rlm@10: } rlm@10: rlm@10: /** rlm@10: * Writes the chunk and all its children to the ImageOutputStream rlm@10: * and disposes of all resources held by the chunk. rlm@10: * @throws java.io.IOException rlm@10: */ rlm@10: @Override rlm@10: public void finish() throws IOException { rlm@10: if (!finished) { rlm@10: if (size() > 0xffffffffL) { rlm@10: throw new IOException("CompositeChunk \"" + chunkType + "\" is too large: " + size()); rlm@10: } rlm@10: rlm@10: long pointer = getRelativeStreamPosition(); rlm@10: seekRelative(offset); rlm@10: rlm@10: DataChunkOutputStream headerData = new DataChunkOutputStream(new ImageOutputStreamAdapter(out),false); rlm@10: headerData.writeType(compositeType); rlm@10: headerData.writeUInt(size() - 8); rlm@10: headerData.writeType(chunkType); rlm@10: for (Chunk child : children) { rlm@10: child.finish(); rlm@10: } rlm@10: seekRelative(pointer); rlm@10: if (size() % 2 == 1) { rlm@10: out.writeByte(0); // write pad byte rlm@10: } rlm@10: finished = true; rlm@10: } rlm@10: } rlm@10: rlm@10: @Override rlm@10: public long size() { rlm@10: long length = 12; rlm@10: for (Chunk child : children) { rlm@10: length += child.size() + child.size() % 2; rlm@10: } rlm@10: return length; rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Data Chunk. rlm@10: */ rlm@10: private class DataChunk extends Chunk { rlm@10: rlm@10: private DataChunkOutputStream data; rlm@10: private boolean finished; rlm@10: rlm@10: /** rlm@10: * Creates a new DataChunk at the current position of the rlm@10: * ImageOutputStream. rlm@10: * @param chunkType The chunkType of the chunk. rlm@10: */ rlm@10: public DataChunk(String name) throws IOException { rlm@10: super(name); rlm@10: out.writeLong(0); // make room for the chunk header rlm@10: data = new DataChunkOutputStream(new ImageOutputStreamAdapter(out), false); rlm@10: } rlm@10: rlm@10: public DataChunkOutputStream getOutputStream() { rlm@10: if (finished) { rlm@10: throw new IllegalStateException("DataChunk is finished"); rlm@10: } rlm@10: return data; rlm@10: } rlm@10: rlm@10: @Override rlm@10: public void finish() throws IOException { rlm@10: if (!finished) { rlm@10: long sizeBefore = size(); rlm@10: rlm@10: if (size() > 0xffffffffL) { rlm@10: throw new IOException("DataChunk \"" + chunkType + "\" is too large: " + size()); rlm@10: } rlm@10: rlm@10: long pointer = getRelativeStreamPosition(); rlm@10: seekRelative(offset); rlm@10: rlm@10: DataChunkOutputStream headerData = new DataChunkOutputStream(new ImageOutputStreamAdapter(out),false); rlm@10: headerData.writeType(chunkType); rlm@10: headerData.writeUInt(size() - 8); rlm@10: seekRelative(pointer); rlm@10: if (size() % 2 == 1) { rlm@10: out.writeByte(0); // write pad byte rlm@10: } rlm@10: finished = true; rlm@10: long sizeAfter = size(); rlm@10: if (sizeBefore != sizeAfter) { rlm@10: System.err.println("size mismatch " + sizeBefore + ".." + sizeAfter); rlm@10: } rlm@10: } rlm@10: } rlm@10: rlm@10: @Override rlm@10: public long size() { rlm@10: return 8 + data.size(); rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * A DataChunk with a fixed size. rlm@10: */ rlm@10: private class FixedSizeDataChunk extends Chunk { rlm@10: rlm@10: private DataChunkOutputStream data; rlm@10: private boolean finished; rlm@10: private long fixedSize; rlm@10: rlm@10: /** rlm@10: * Creates a new DataChunk at the current position of the rlm@10: * ImageOutputStream. rlm@10: * @param chunkType The chunkType of the chunk. rlm@10: */ rlm@10: public FixedSizeDataChunk(String chunkType, long fixedSize) throws IOException { rlm@10: super(chunkType); rlm@10: this.fixedSize = fixedSize; rlm@10: data = new DataChunkOutputStream(new ImageOutputStreamAdapter(out),false); rlm@10: data.writeType(chunkType); rlm@10: data.writeUInt(fixedSize); rlm@10: data.clearCount(); rlm@10: rlm@10: // Fill fixed size with nulls rlm@10: byte[] buf = new byte[(int) Math.min(512, fixedSize)]; rlm@10: long written = 0; rlm@10: while (written < fixedSize) { rlm@10: data.write(buf, 0, (int) Math.min(buf.length, fixedSize - written)); rlm@10: written += Math.min(buf.length, fixedSize - written); rlm@10: } rlm@10: if (fixedSize % 2 == 1) { rlm@10: out.writeByte(0); // write pad byte rlm@10: } rlm@10: seekToStartOfData(); rlm@10: } rlm@10: rlm@10: public DataChunkOutputStream getOutputStream() { rlm@10: /*if (finished) { rlm@10: throw new IllegalStateException("DataChunk is finished"); rlm@10: }*/ rlm@10: return data; rlm@10: } rlm@10: rlm@10: public void seekToStartOfData() throws IOException { rlm@10: seekRelative(offset + 8); rlm@10: data.clearCount(); rlm@10: } rlm@10: rlm@10: public void seekToEndOfChunk() throws IOException { rlm@10: seekRelative(offset + 8 + fixedSize + fixedSize % 2); rlm@10: } rlm@10: rlm@10: @Override rlm@10: public void finish() throws IOException { rlm@10: if (!finished) { rlm@10: finished = true; rlm@10: } rlm@10: } rlm@10: rlm@10: @Override rlm@10: public long size() { rlm@10: return 8 + fixedSize; rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Creates a new AVI file with the specified video format and rlm@10: * frame rate. The video has 24 bits per pixel. rlm@10: * rlm@10: * @param file the output file rlm@10: * @param format Selects an encoder for the video format. rlm@10: * @param bitsPerPixel the number of bits per pixel. rlm@10: * @exception IllegalArgumentException if videoFormat is null or if rlm@10: * frame rate is <= 0 rlm@10: */ rlm@10: public AVIOutputStream(File file, VideoFormat format) throws IOException { rlm@10: this(file,format,24); rlm@10: } rlm@10: /** rlm@10: * Creates a new AVI file with the specified video format and rlm@10: * frame rate. rlm@10: * rlm@10: * @param file the output file rlm@10: * @param format Selects an encoder for the video format. rlm@10: * @param bitsPerPixel the number of bits per pixel. rlm@10: * @exception IllegalArgumentException if videoFormat is null or if rlm@10: * frame rate is <= 0 rlm@10: */ rlm@10: public AVIOutputStream(File file, VideoFormat format, int bitsPerPixel) throws IOException { rlm@10: if (format == null) { rlm@10: throw new IllegalArgumentException("format must not be null"); rlm@10: } rlm@10: rlm@10: if (file.exists()) { rlm@10: file.delete(); rlm@10: } rlm@10: this.out = new FileImageOutputStream(file); rlm@10: this.streamOffset = 0; rlm@10: this.videoFormat = format; rlm@10: this.videoFrames = new LinkedList(); rlm@10: this.imgDepth = bitsPerPixel; rlm@10: if (imgDepth == 4) { rlm@10: byte[] gray = new byte[16]; rlm@10: for (int i = 0; i < gray.length; i++) { rlm@10: gray[i] = (byte) ((i << 4) | i); rlm@10: } rlm@10: palette = new IndexColorModel(4, 16, gray, gray, gray); rlm@10: } else if (imgDepth == 8) { rlm@10: byte[] gray = new byte[256]; rlm@10: for (int i = 0; i < gray.length; i++) { rlm@10: gray[i] = (byte) i; rlm@10: } rlm@10: palette = new IndexColorModel(8, 256, gray, gray, gray); rlm@10: } rlm@10: rlm@10: } rlm@10: rlm@10: /** rlm@10: * Creates a new AVI output stream with the specified video format and rlm@10: * framerate. rlm@10: * rlm@10: * @param out the underlying output stream rlm@10: * @param format Selects an encoder for the video format. rlm@10: * @exception IllegalArgumentException if videoFormat is null or if rlm@10: * framerate is <= 0 rlm@10: */ rlm@10: public AVIOutputStream(ImageOutputStream out, VideoFormat format) throws IOException { rlm@10: if (format == null) { rlm@10: throw new IllegalArgumentException("format must not be null"); rlm@10: } rlm@10: this.out = out; rlm@10: this.streamOffset = out.getStreamPosition(); rlm@10: this.videoFormat = format; rlm@10: this.videoFrames = new LinkedList(); rlm@10: } rlm@10: rlm@10: /** rlm@10: * Used with frameRate to specify the time scale that this stream will use. rlm@10: * Dividing frameRate by timeScale gives the number of samples per second. rlm@10: * For video streams, this is the frame rate. For audio streams, this rate rlm@10: * corresponds to the time needed to play nBlockAlign bytes of audio, which rlm@10: * for PCM audio is the just the sample rate. rlm@10: *

rlm@10: * The default value is 1. rlm@10: * rlm@10: * @param newValue rlm@10: */ rlm@10: public void setTimeScale(int newValue) { rlm@10: if (newValue <= 0) { rlm@10: throw new IllegalArgumentException("timeScale must be greater 0"); rlm@10: } rlm@10: this.timeScale = newValue; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Returns the time scale of this media. rlm@10: * rlm@10: * @return time scale rlm@10: */ rlm@10: public int getTimeScale() { rlm@10: return timeScale; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Sets the rate of video frames in time scale units. rlm@10: *

rlm@10: * The default value is 30. Together with the default value 1 of timeScale rlm@10: * this results in 30 frames pers second. rlm@10: * rlm@10: * @param newValue rlm@10: */ rlm@10: public void setFrameRate(int newValue) { rlm@10: if (newValue <= 0) { rlm@10: throw new IllegalArgumentException("frameDuration must be greater 0"); rlm@10: } rlm@10: if (state == States.STARTED) { rlm@10: throw new IllegalStateException("frameDuration must be set before the first frame is written"); rlm@10: } rlm@10: this.frameRate = newValue; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Returns the frame rate of this media. rlm@10: * rlm@10: * @return frame rate rlm@10: */ rlm@10: public int getFrameRate() { rlm@10: return frameRate; rlm@10: } rlm@10: rlm@10: /** Sets the global color palette. */ rlm@10: public void setPalette(IndexColorModel palette) { rlm@10: this.palette = palette; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Sets the compression quality of the video track. rlm@10: * A value of 0 stands for "high compression is important" a value of rlm@10: * 1 for "high image quality is important". rlm@10: *

rlm@10: * Changing this value affects frames which are subsequently written rlm@10: * to the AVIOutputStream. Frames which have already been written rlm@10: * are not changed. rlm@10: *

rlm@10: * This value has only effect on videos encoded with JPG format. rlm@10: *

rlm@10: * The default value is 0.9. rlm@10: * rlm@10: * @param newValue rlm@10: */ rlm@10: public void setVideoCompressionQuality(float newValue) { rlm@10: this.quality = newValue; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Returns the video compression quality. rlm@10: * rlm@10: * @return video compression quality rlm@10: */ rlm@10: public float getVideoCompressionQuality() { rlm@10: return quality; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Sets the dimension of the video track. rlm@10: *

rlm@10: * You need to explicitly set the dimension, if you add all frames from rlm@10: * files or input streams. rlm@10: *

rlm@10: * If you add frames from buffered images, then AVIOutputStream rlm@10: * can determine the video dimension from the image width and height. rlm@10: * rlm@10: * @param width Must be greater than 0. rlm@10: * @param height Must be greater than 0. rlm@10: */ rlm@10: public void setVideoDimension(int width, int height) { rlm@10: if (width < 1 || height < 1) { rlm@10: throw new IllegalArgumentException("width and height must be greater zero."); rlm@10: } rlm@10: this.imgWidth = width; rlm@10: this.imgHeight = height; rlm@10: } rlm@10: rlm@10: /** rlm@10: * Gets the dimension of the video track. rlm@10: *

rlm@10: * Returns null if the dimension is not known. rlm@10: */ rlm@10: public Dimension getVideoDimension() { rlm@10: if (imgWidth < 1 || imgHeight < 1) { rlm@10: return null; rlm@10: } rlm@10: return new Dimension(imgWidth, imgHeight); rlm@10: } rlm@10: rlm@10: /** rlm@10: * Sets the state of the QuickTimeOutpuStream to started. rlm@10: *

rlm@10: * If the state is changed by this method, the prolog is rlm@10: * written. rlm@10: */ rlm@10: private void ensureStarted() throws IOException { rlm@10: if (state != States.STARTED) { rlm@10: new Date(); rlm@10: writeProlog(); rlm@10: state = States.STARTED; rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Writes a frame to the video track. rlm@10: *

rlm@10: * If the dimension of the video track has not been specified yet, it rlm@10: * is derived from the first buffered image added to the AVIOutputStream. rlm@10: * rlm@10: * @param image The frame image. rlm@10: * rlm@10: * @throws IllegalArgumentException if the duration is less than 1, or rlm@10: * if the dimension of the frame does not match the dimension of the video rlm@10: * track. rlm@10: * @throws IOException if writing the image failed. rlm@10: */ rlm@10: public void writeFrame(BufferedImage image) throws IOException { rlm@10: ensureOpen(); rlm@10: ensureStarted(); rlm@10: rlm@10: // Get the dimensions of the first image rlm@10: if (imgWidth == -1) { rlm@10: imgWidth = image.getWidth(); rlm@10: imgHeight = image.getHeight(); rlm@10: } else { rlm@10: // The dimension of the image must match the dimension of the video track rlm@10: if (imgWidth != image.getWidth() || imgHeight != image.getHeight()) { rlm@10: throw new IllegalArgumentException("Dimensions of image[" + videoFrames.size() rlm@10: + "] (width=" + image.getWidth() + ", height=" + image.getHeight() rlm@10: + ") differs from image[0] (width=" rlm@10: + imgWidth + ", height=" + imgHeight); rlm@10: } rlm@10: } rlm@10: rlm@10: DataChunk videoFrameChunk; rlm@10: long offset = getRelativeStreamPosition(); rlm@10: boolean isSync = true; rlm@10: switch (videoFormat) { rlm@10: case RAW: { rlm@10: switch (imgDepth) { rlm@10: case 4: { rlm@10: IndexColorModel imgPalette = (IndexColorModel) image.getColorModel(); rlm@10: int[] imgRGBs = new int[16]; rlm@10: imgPalette.getRGBs(imgRGBs); rlm@10: int[] previousRGBs = new int[16]; rlm@10: if (previousPalette == null) { rlm@10: previousPalette = palette; rlm@10: } rlm@10: previousPalette.getRGBs(previousRGBs); rlm@10: if (!Arrays.equals(imgRGBs, previousRGBs)) { rlm@10: previousPalette = imgPalette; rlm@10: DataChunk paletteChangeChunk = new DataChunk("00pc"); rlm@10: /* rlm@10: int first = imgPalette.getMapSize(); rlm@10: int last = -1; rlm@10: for (int i = 0; i < 16; i++) { rlm@10: if (previousRGBs[i] != imgRGBs[i] && i < first) { rlm@10: first = i; rlm@10: } rlm@10: if (previousRGBs[i] != imgRGBs[i] && i > last) { rlm@10: last = i; rlm@10: } rlm@10: }*/ rlm@10: int first = 0; rlm@10: int last = imgPalette.getMapSize() - 1; rlm@10: /* rlm@10: * typedef struct { rlm@10: BYTE bFirstEntry; rlm@10: BYTE bNumEntries; rlm@10: WORD wFlags; rlm@10: PALETTEENTRY peNew[]; rlm@10: } AVIPALCHANGE; rlm@10: * rlm@10: * typedef struct tagPALETTEENTRY { rlm@10: BYTE peRed; rlm@10: BYTE peGreen; rlm@10: BYTE peBlue; rlm@10: BYTE peFlags; rlm@10: } PALETTEENTRY; rlm@10: */ rlm@10: DataChunkOutputStream pOut = paletteChangeChunk.getOutputStream(); rlm@10: pOut.writeByte(first);//bFirstEntry rlm@10: pOut.writeByte(last - first + 1);//bNumEntries rlm@10: pOut.writeShort(0);//wFlags rlm@10: rlm@10: for (int i = first; i <= last; i++) { rlm@10: pOut.writeByte((imgRGBs[i] >>> 16) & 0xff); // red rlm@10: pOut.writeByte((imgRGBs[i] >>> 8) & 0xff); // green rlm@10: pOut.writeByte(imgRGBs[i] & 0xff); // blue rlm@10: pOut.writeByte(0); // reserved*/ rlm@10: } rlm@10: rlm@10: moviChunk.add(paletteChangeChunk); rlm@10: paletteChangeChunk.finish(); rlm@10: long length = getRelativeStreamPosition() - offset; rlm@10: videoFrames.add(new Sample(paletteChangeChunk.chunkType, 0, offset, length - 8, false)); rlm@10: offset = getRelativeStreamPosition(); rlm@10: } rlm@10: rlm@10: videoFrameChunk = new DataChunk("00db"); rlm@10: byte[] rgb8 = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); rlm@10: byte[] rgb4 = new byte[imgWidth / 2]; rlm@10: for (int y = (imgHeight - 1) * imgWidth; y >= 0; y -= imgWidth) { // Upside down rlm@10: for (int x = 0, xx = 0, n = imgWidth; x < n; x += 2, ++xx) { rlm@10: rgb4[xx] = (byte) (((rgb8[y + x] & 0xf) << 4) | (rgb8[y + x + 1] & 0xf)); rlm@10: } rlm@10: videoFrameChunk.getOutputStream().write(rgb4); rlm@10: } rlm@10: break; rlm@10: } rlm@10: case 8: { rlm@10: IndexColorModel imgPalette = (IndexColorModel) image.getColorModel(); rlm@10: int[] imgRGBs = new int[256]; rlm@10: imgPalette.getRGBs(imgRGBs); rlm@10: int[] previousRGBs = new int[256]; rlm@10: if (previousPalette == null) { rlm@10: previousPalette = palette; rlm@10: } rlm@10: previousPalette.getRGBs(previousRGBs); rlm@10: if (!Arrays.equals(imgRGBs, previousRGBs)) { rlm@10: previousPalette = imgPalette; rlm@10: DataChunk paletteChangeChunk = new DataChunk("00pc"); rlm@10: /* rlm@10: int first = imgPalette.getMapSize(); rlm@10: int last = -1; rlm@10: for (int i = 0; i < 16; i++) { rlm@10: if (previousRGBs[i] != imgRGBs[i] && i < first) { rlm@10: first = i; rlm@10: } rlm@10: if (previousRGBs[i] != imgRGBs[i] && i > last) { rlm@10: last = i; rlm@10: } rlm@10: }*/ rlm@10: int first = 0; rlm@10: int last = imgPalette.getMapSize() - 1; rlm@10: /* rlm@10: * typedef struct { rlm@10: BYTE bFirstEntry; rlm@10: BYTE bNumEntries; rlm@10: WORD wFlags; rlm@10: PALETTEENTRY peNew[]; rlm@10: } AVIPALCHANGE; rlm@10: * rlm@10: * typedef struct tagPALETTEENTRY { rlm@10: BYTE peRed; rlm@10: BYTE peGreen; rlm@10: BYTE peBlue; rlm@10: BYTE peFlags; rlm@10: } PALETTEENTRY; rlm@10: */ rlm@10: DataChunkOutputStream pOut = paletteChangeChunk.getOutputStream(); rlm@10: pOut.writeByte(first);//bFirstEntry rlm@10: pOut.writeByte(last - first + 1);//bNumEntries rlm@10: pOut.writeShort(0);//wFlags rlm@10: rlm@10: for (int i = first; i <= last; i++) { rlm@10: pOut.writeByte((imgRGBs[i] >>> 16) & 0xff); // red rlm@10: pOut.writeByte((imgRGBs[i] >>> 8) & 0xff); // green rlm@10: pOut.writeByte(imgRGBs[i] & 0xff); // blue rlm@10: pOut.writeByte(0); // reserved*/ rlm@10: } rlm@10: rlm@10: moviChunk.add(paletteChangeChunk); rlm@10: paletteChangeChunk.finish(); rlm@10: long length = getRelativeStreamPosition() - offset; rlm@10: videoFrames.add(new Sample(paletteChangeChunk.chunkType, 0, offset, length - 8, false)); rlm@10: offset = getRelativeStreamPosition(); rlm@10: } rlm@10: rlm@10: videoFrameChunk = new DataChunk("00db"); rlm@10: byte[] rgb8 = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); rlm@10: for (int y = (imgHeight - 1) * imgWidth; y >= 0; y -= imgWidth) { // Upside down rlm@10: videoFrameChunk.getOutputStream().write(rgb8, y, imgWidth); rlm@10: } rlm@10: break; rlm@10: } rlm@10: default: { rlm@10: videoFrameChunk = new DataChunk("00db"); rlm@10: WritableRaster raster = image.getRaster(); rlm@10: int[] raw = new int[imgWidth * 3]; // holds a scanline of raw image data with 3 channels of 32 bit data rlm@10: byte[] bytes = new byte[imgWidth * 3]; // holds a scanline of raw image data with 3 channels of 8 bit data rlm@10: for (int y = imgHeight - 1; y >= 0; --y) { // Upside down rlm@10: raster.getPixels(0, y, imgWidth, 1, raw); rlm@10: for (int x = 0, n = imgWidth * 3; x < n; x += 3) { rlm@10: bytes[x + 2] = (byte) raw[x]; // Blue rlm@10: bytes[x + 1] = (byte) raw[x + 1]; // Green rlm@10: bytes[x] = (byte) raw[x + 2]; // Red rlm@10: } rlm@10: videoFrameChunk.getOutputStream().write(bytes); rlm@10: } rlm@10: break; rlm@10: } rlm@10: } rlm@10: break; rlm@10: } rlm@10: rlm@10: case JPG: { rlm@10: videoFrameChunk = new DataChunk("00dc"); rlm@10: ImageWriter iw = (ImageWriter) ImageIO.getImageWritersByMIMEType("image/jpeg").next(); rlm@10: ImageWriteParam iwParam = iw.getDefaultWriteParam(); rlm@10: iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); rlm@10: iwParam.setCompressionQuality(quality); rlm@10: MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(videoFrameChunk.getOutputStream()); rlm@10: iw.setOutput(imgOut); rlm@10: IIOImage img = new IIOImage(image, null, null); rlm@10: iw.write(null, img, iwParam); rlm@10: iw.dispose(); rlm@10: break; rlm@10: } rlm@10: case PNG: rlm@10: default: { rlm@10: videoFrameChunk = new DataChunk("00dc"); rlm@10: ImageWriter iw = (ImageWriter) ImageIO.getImageWritersByMIMEType("image/png").next(); rlm@10: ImageWriteParam iwParam = iw.getDefaultWriteParam(); rlm@10: MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(videoFrameChunk.getOutputStream()); rlm@10: iw.setOutput(imgOut); rlm@10: IIOImage img = new IIOImage(image, null, null); rlm@10: iw.write(null, img, iwParam); rlm@10: iw.dispose(); rlm@10: break; rlm@10: } rlm@10: } rlm@10: long length = getRelativeStreamPosition() - offset; rlm@10: moviChunk.add(videoFrameChunk); rlm@10: videoFrameChunk.finish(); rlm@10: rlm@10: videoFrames.add(new Sample(videoFrameChunk.chunkType, frameRate, offset, length - 8, isSync)); rlm@10: if (getRelativeStreamPosition() > 1L << 32) { rlm@10: throw new IOException("AVI file is larger than 4 GB"); rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Writes a frame from a file to the video track. rlm@10: *

rlm@10: * This method does not inspect the contents of the file. rlm@10: * For example, Its your responsibility to only add JPG files if you have rlm@10: * chosen the JPEG video format. rlm@10: *

rlm@10: * If you add all frames from files or from input streams, then you rlm@10: * have to explicitly set the dimension of the video track before you rlm@10: * call finish() or close(). rlm@10: * rlm@10: * @param file The file which holds the image data. rlm@10: * rlm@10: * @throws IllegalStateException if the duration is less than 1. rlm@10: * @throws IOException if writing the image failed. rlm@10: */ rlm@10: public void writeFrame(File file) throws IOException { rlm@10: FileInputStream in = null; rlm@10: try { rlm@10: in = new FileInputStream(file); rlm@10: writeFrame(in); rlm@10: } finally { rlm@10: if (in != null) { rlm@10: in.close(); rlm@10: } rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Writes a frame to the video track. rlm@10: *

rlm@10: * This method does not inspect the contents of the file. rlm@10: * For example, its your responsibility to only add JPG files if you have rlm@10: * chosen the JPEG video format. rlm@10: *

rlm@10: * If you add all frames from files or from input streams, then you rlm@10: * have to explicitly set the dimension of the video track before you rlm@10: * call finish() or close(). rlm@10: * rlm@10: * @param in The input stream which holds the image data. rlm@10: * rlm@10: * @throws IllegalArgumentException if the duration is less than 1. rlm@10: * @throws IOException if writing the image failed. rlm@10: */ rlm@10: public void writeFrame(InputStream in) throws IOException { rlm@10: ensureOpen(); rlm@10: ensureStarted(); rlm@10: rlm@10: DataChunk videoFrameChunk = new DataChunk( rlm@10: videoFormat == VideoFormat.RAW ? "00db" : "00dc"); rlm@10: moviChunk.add(videoFrameChunk); rlm@10: OutputStream mdatOut = videoFrameChunk.getOutputStream(); rlm@10: long offset = getRelativeStreamPosition(); rlm@10: byte[] buf = new byte[512]; rlm@10: int len; rlm@10: while ((len = in.read(buf)) != -1) { rlm@10: mdatOut.write(buf, 0, len); rlm@10: } rlm@10: long length = getRelativeStreamPosition() - offset; rlm@10: videoFrameChunk.finish(); rlm@10: videoFrames.add(new Sample(videoFrameChunk.chunkType, frameRate, offset, length - 8, true)); rlm@10: if (getRelativeStreamPosition() > 1L << 32) { rlm@10: throw new IOException("AVI file is larger than 4 GB"); rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Closes the movie file as well as the stream being filtered. rlm@10: * rlm@10: * @exception IOException if an I/O error has occurred rlm@10: */ rlm@10: public void close() throws IOException { rlm@10: if (state == States.STARTED) { rlm@10: finish(); rlm@10: } rlm@10: if (state != States.CLOSED) { rlm@10: out.close(); rlm@10: state = States.CLOSED; rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Finishes writing the contents of the AVI output stream without closing rlm@10: * the underlying stream. Use this method when applying multiple filters rlm@10: * in succession to the same output stream. rlm@10: * rlm@10: * @exception IllegalStateException if the dimension of the video track rlm@10: * has not been specified or determined yet. rlm@10: * @exception IOException if an I/O exception has occurred rlm@10: */ rlm@10: public void finish() throws IOException { rlm@10: ensureOpen(); rlm@10: if (state != States.FINISHED) { rlm@10: if (imgWidth == -1 || imgHeight == -1) { rlm@10: throw new IllegalStateException("image width and height must be specified"); rlm@10: } rlm@10: rlm@10: moviChunk.finish(); rlm@10: writeEpilog(); rlm@10: state = States.FINISHED; rlm@10: imgWidth = imgHeight = -1; rlm@10: } rlm@10: } rlm@10: rlm@10: /** rlm@10: * Check to make sure that this stream has not been closed rlm@10: */ rlm@10: private void ensureOpen() throws IOException { rlm@10: if (state == States.CLOSED) { rlm@10: throw new IOException("Stream closed"); rlm@10: } rlm@10: } rlm@10: rlm@10: /** Gets the position relative to the beginning of the QuickTime stream. rlm@10: *

rlm@10: * Usually this value is equal to the stream position of the underlying rlm@10: * ImageOutputStream, but can be larger if the underlying stream already rlm@10: * contained data. rlm@10: * rlm@10: * @return The relative stream position. rlm@10: * @throws IOException rlm@10: */ rlm@10: private long getRelativeStreamPosition() throws IOException { rlm@10: return out.getStreamPosition() - streamOffset; rlm@10: } rlm@10: rlm@10: /** Seeks relative to the beginning of the QuickTime stream. rlm@10: *

rlm@10: * Usually this equal to seeking in the underlying ImageOutputStream, but rlm@10: * can be different if the underlying stream already contained data. rlm@10: * rlm@10: */ rlm@10: private void seekRelative(long newPosition) throws IOException { rlm@10: out.seek(newPosition + streamOffset); rlm@10: } rlm@10: rlm@10: private void writeProlog() throws IOException { rlm@10: // The file has the following structure: rlm@10: // rlm@10: // .RIFF AVI rlm@10: // ..avih (AVI Header Chunk) rlm@10: // ..LIST strl rlm@10: // ...strh (Stream Header Chunk) rlm@10: // ...strf (Stream Format Chunk) rlm@10: // ..LIST movi rlm@10: // ...00dc (Compressed video data chunk in Track 00, repeated for each frame) rlm@10: // ..idx1 (List of video data chunks and their location in the file) rlm@10: rlm@10: // The RIFF AVI Chunk holds the complete movie rlm@10: aviChunk = new CompositeChunk("RIFF", "AVI "); rlm@10: CompositeChunk hdrlChunk = new CompositeChunk("LIST", "hdrl"); rlm@10: rlm@10: // Write empty AVI Main Header Chunk - we fill the data in later rlm@10: aviChunk.add(hdrlChunk); rlm@10: avihChunk = new FixedSizeDataChunk("avih", 56); rlm@10: avihChunk.seekToEndOfChunk(); rlm@10: hdrlChunk.add(avihChunk); rlm@10: rlm@10: CompositeChunk strlChunk = new CompositeChunk("LIST", "strl"); rlm@10: hdrlChunk.add(strlChunk); rlm@10: rlm@10: // Write empty AVI Stream Header Chunk - we fill the data in later rlm@10: strhChunk = new FixedSizeDataChunk("strh", 56); rlm@10: strhChunk.seekToEndOfChunk(); rlm@10: strlChunk.add(strhChunk); rlm@10: strfChunk = new FixedSizeDataChunk("strf", palette == null ? 40 : 40 + palette.getMapSize() * 4); rlm@10: strfChunk.seekToEndOfChunk(); rlm@10: strlChunk.add(strfChunk); rlm@10: rlm@10: moviChunk = new CompositeChunk("LIST", "movi"); rlm@10: aviChunk.add(moviChunk); rlm@10: rlm@10: rlm@10: } rlm@10: rlm@10: private void writeEpilog() throws IOException { rlm@10: rlm@10: long bufferSize = 0; rlm@10: for (Sample s : videoFrames) { rlm@10: if (s.length > bufferSize) { rlm@10: bufferSize = s.length; rlm@10: } rlm@10: } rlm@10: rlm@10: rlm@10: DataChunkOutputStream d; rlm@10: rlm@10: /* Create Idx1 Chunk and write data rlm@10: * ------------- rlm@10: typedef struct _avioldindex { rlm@10: FOURCC fcc; rlm@10: DWORD cb; rlm@10: struct _avioldindex_entry { rlm@10: DWORD dwChunkId; rlm@10: DWORD dwFlags; rlm@10: DWORD dwOffset; rlm@10: DWORD dwSize; rlm@10: } aIndex[]; rlm@10: } AVIOLDINDEX; rlm@10: */ rlm@10: DataChunk idx1Chunk = new DataChunk("idx1"); rlm@10: aviChunk.add(idx1Chunk); rlm@10: d = idx1Chunk.getOutputStream(); rlm@10: long moviListOffset = moviChunk.offset + 8; rlm@10: //moviListOffset = 0; rlm@10: for (Sample f : videoFrames) { rlm@10: rlm@10: d.writeType(f.chunkType); // dwChunkId rlm@10: // Specifies a FOURCC that identifies a stream in the AVI file. The rlm@10: // FOURCC must have the form 'xxyy' where xx is the stream number and yy rlm@10: // is a two-character code that identifies the contents of the stream: rlm@10: // rlm@10: // Two-character code Description rlm@10: // db Uncompressed video frame rlm@10: // dc Compressed video frame rlm@10: // pc Palette change rlm@10: // wb Audio data rlm@10: rlm@10: d.writeUInt((f.chunkType.endsWith("pc") ? 0x100 : 0x0)// rlm@10: | (f.isSync ? 0x10 : 0x0)); // dwFlags rlm@10: // Specifies a bitwise combination of zero or more of the following rlm@10: // flags: rlm@10: // rlm@10: // Value Name Description rlm@10: // 0x10 AVIIF_KEYFRAME The data chunk is a key frame. rlm@10: // 0x1 AVIIF_LIST The data chunk is a 'rec ' list. rlm@10: // 0x100 AVIIF_NO_TIME The data chunk does not affect the timing of the rlm@10: // stream. For example, this flag should be set for rlm@10: // palette changes. rlm@10: rlm@10: d.writeUInt(f.offset - moviListOffset); // dwOffset rlm@10: // Specifies the location of the data chunk in the file. The value rlm@10: // should be specified as an offset, in bytes, from the start of the rlm@10: // 'movi' list; however, in some AVI files it is given as an offset from rlm@10: // the start of the file. rlm@10: rlm@10: d.writeUInt(f.length); // dwSize rlm@10: // Specifies the size of the data chunk, in bytes. rlm@10: } rlm@10: idx1Chunk.finish(); rlm@10: rlm@10: /* Write Data into AVI Main Header Chunk rlm@10: * ------------- rlm@10: * The AVIMAINHEADER structure defines global information in an AVI file. rlm@10: * see http://msdn.microsoft.com/en-us/library/ms779632(VS.85).aspx rlm@10: typedef struct _avimainheader { rlm@10: FOURCC fcc; rlm@10: DWORD cb; rlm@10: DWORD dwMicroSecPerFrame; rlm@10: DWORD dwMaxBytesPerSec; rlm@10: DWORD dwPaddingGranularity; rlm@10: DWORD dwFlags; rlm@10: DWORD dwTotalFrames; rlm@10: DWORD dwInitialFrames; rlm@10: DWORD dwStreams; rlm@10: DWORD dwSuggestedBufferSize; rlm@10: DWORD dwWidth; rlm@10: DWORD dwHeight; rlm@10: DWORD dwReserved[4]; rlm@10: } AVIMAINHEADER; */ rlm@10: avihChunk.seekToStartOfData(); rlm@10: d = avihChunk.getOutputStream(); rlm@10: rlm@10: d.writeUInt((1000000L * (long) timeScale) / (long) frameRate); // dwMicroSecPerFrame rlm@10: // Specifies the number of microseconds between frames. rlm@10: // This value indicates the overall timing for the file. rlm@10: rlm@10: d.writeUInt(0); // dwMaxBytesPerSec rlm@10: // Specifies the approximate maximum data rate of the file. rlm@10: // This value indicates the number of bytes per second the system rlm@10: // must handle to present an AVI sequence as specified by the other rlm@10: // parameters contained in the main header and stream header chunks. rlm@10: rlm@10: d.writeUInt(0); // dwPaddingGranularity rlm@10: // Specifies the alignment for data, in bytes. Pad the data to multiples rlm@10: // of this value. rlm@10: rlm@10: d.writeUInt(0x10); // dwFlags (0x10 == hasIndex) rlm@10: // Contains a bitwise combination of zero or more of the following rlm@10: // flags: rlm@10: // rlm@10: // Value Name Description rlm@10: // 0x10 AVIF_HASINDEX Indicates the AVI file has an index. rlm@10: // 0x20 AVIF_MUSTUSEINDEX Indicates that application should use the rlm@10: // index, rather than the physical ordering of the rlm@10: // chunks in the file, to determine the order of rlm@10: // presentation of the data. For example, this flag rlm@10: // could be used to create a list of frames for rlm@10: // editing. rlm@10: // 0x100 AVIF_ISINTERLEAVED Indicates the AVI file is interleaved. rlm@10: // 0x1000 AVIF_WASCAPTUREFILE Indicates the AVI file is a specially rlm@10: // allocated file used for capturing real-time rlm@10: // video. Applications should warn the user before rlm@10: // writing over a file with this flag set because rlm@10: // the user probably defragmented this file. rlm@10: // 0x20000 AVIF_COPYRIGHTED Indicates the AVI file contains copyrighted rlm@10: // data and software. When this flag is used, rlm@10: // software should not permit the data to be rlm@10: // duplicated. rlm@10: rlm@10: d.writeUInt(videoFrames.size()); // dwTotalFrames rlm@10: // Specifies the total number of frames of data in the file. rlm@10: rlm@10: d.writeUInt(0); // dwInitialFrames rlm@10: // Specifies the initial frame for interleaved files. Noninterleaved rlm@10: // files should specify zero. If you are creating interleaved files, rlm@10: // specify the number of frames in the file prior to the initial frame rlm@10: // of the AVI sequence in this member. rlm@10: // To give the audio driver enough audio to work with, the audio data in rlm@10: // an interleaved file must be skewed from the video data. Typically, rlm@10: // the audio data should be moved forward enough frames to allow rlm@10: // approximately 0.75 seconds of audio data to be preloaded. The rlm@10: // dwInitialRecords member should be set to the number of frames the rlm@10: // audio is skewed. Also set the same value for the dwInitialFrames rlm@10: // member of the AVISTREAMHEADER structure in the audio stream header rlm@10: rlm@10: d.writeUInt(1); // dwStreams rlm@10: // Specifies the number of streams in the file. For example, a file with rlm@10: // audio and video has two streams. rlm@10: rlm@10: d.writeUInt(bufferSize); // dwSuggestedBufferSize rlm@10: // Specifies the suggested buffer size for reading the file. Generally, rlm@10: // this size should be large enough to contain the largest chunk in the rlm@10: // file. If set to zero, or if it is too small, the playback software rlm@10: // will have to reallocate memory during playback, which will reduce rlm@10: // performance. For an interleaved file, the buffer size should be large rlm@10: // enough to read an entire record, and not just a chunk. rlm@10: rlm@10: rlm@10: d.writeUInt(imgWidth); // dwWidth rlm@10: // Specifies the width of the AVI file in pixels. rlm@10: rlm@10: d.writeUInt(imgHeight); // dwHeight rlm@10: // Specifies the height of the AVI file in pixels. rlm@10: rlm@10: d.writeUInt(0); // dwReserved[0] rlm@10: d.writeUInt(0); // dwReserved[1] rlm@10: d.writeUInt(0); // dwReserved[2] rlm@10: d.writeUInt(0); // dwReserved[3] rlm@10: // Reserved. Set this array to zero. rlm@10: rlm@10: /* Write Data into AVI Stream Header Chunk rlm@10: * ------------- rlm@10: * The AVISTREAMHEADER structure contains information about one stream rlm@10: * in an AVI file. rlm@10: * see http://msdn.microsoft.com/en-us/library/ms779638(VS.85).aspx rlm@10: typedef struct _avistreamheader { rlm@10: FOURCC fcc; rlm@10: DWORD cb; rlm@10: FOURCC fccType; rlm@10: FOURCC fccHandler; rlm@10: DWORD dwFlags; rlm@10: WORD wPriority; rlm@10: WORD wLanguage; rlm@10: DWORD dwInitialFrames; rlm@10: DWORD dwScale; rlm@10: DWORD dwRate; rlm@10: DWORD dwStart; rlm@10: DWORD dwLength; rlm@10: DWORD dwSuggestedBufferSize; rlm@10: DWORD dwQuality; rlm@10: DWORD dwSampleSize; rlm@10: struct { rlm@10: short int left; rlm@10: short int top; rlm@10: short int right; rlm@10: short int bottom; rlm@10: } rcFrame; rlm@10: } AVISTREAMHEADER; rlm@10: */ rlm@10: strhChunk.seekToStartOfData(); rlm@10: d = strhChunk.getOutputStream(); rlm@10: d.writeType("vids"); // fccType - vids for video stream rlm@10: // Contains a FOURCC that specifies the type of the data contained in rlm@10: // the stream. The following standard AVI values for video and audio are rlm@10: // defined: rlm@10: // rlm@10: // FOURCC Description rlm@10: // 'auds' Audio stream rlm@10: // 'mids' MIDI stream rlm@10: // 'txts' Text stream rlm@10: // 'vids' Video stream rlm@10: rlm@10: switch (videoFormat) { rlm@10: case RAW: rlm@10: d.writeType("DIB "); // fccHandler - DIB for Raw RGB rlm@10: break; rlm@10: case RLE: rlm@10: d.writeType("RLE "); // fccHandler - Microsoft RLE rlm@10: break; rlm@10: case JPG: rlm@10: d.writeType("MJPG"); // fccHandler - MJPG for Motion JPEG rlm@10: break; rlm@10: case PNG: rlm@10: default: rlm@10: d.writeType("png "); // fccHandler - png for PNG rlm@10: break; rlm@10: } rlm@10: // Optionally, contains a FOURCC that identifies a specific data rlm@10: // handler. The data handler is the preferred handler for the stream. rlm@10: // For audio and video streams, this specifies the codec for decoding rlm@10: // the stream. rlm@10: rlm@10: if (imgDepth <= 8) { rlm@10: d.writeUInt(0x00010000); // dwFlags - AVISF_VIDEO_PALCHANGES rlm@10: } else { rlm@10: d.writeUInt(0); // dwFlags rlm@10: } rlm@10: rlm@10: // Contains any flags for the data stream. The bits in the high-order rlm@10: // word of these flags are specific to the type of data contained in the rlm@10: // stream. The following standard flags are defined: rlm@10: // rlm@10: // Value Name Description rlm@10: // AVISF_DISABLED 0x00000001 Indicates this stream should not rlm@10: // be enabled by default. rlm@10: // AVISF_VIDEO_PALCHANGES 0x00010000 rlm@10: // Indicates this video stream contains rlm@10: // palette changes. This flag warns the playback rlm@10: // software that it will need to animate the rlm@10: // palette. rlm@10: rlm@10: d.writeUShort(0); // wPriority rlm@10: // Specifies priority of a stream type. For example, in a file with rlm@10: // multiple audio streams, the one with the highest priority might be rlm@10: // the default stream. rlm@10: rlm@10: d.writeUShort(0); // wLanguage rlm@10: // Language tag. rlm@10: rlm@10: d.writeUInt(0); // dwInitialFrames rlm@10: // Specifies how far audio data is skewed ahead of the video frames in rlm@10: // interleaved files. Typically, this is about 0.75 seconds. If you are rlm@10: // creating interleaved files, specify the number of frames in the file rlm@10: // prior to the initial frame of the AVI sequence in this member. For rlm@10: // more information, see the remarks for the dwInitialFrames member of rlm@10: // the AVIMAINHEADER structure. rlm@10: rlm@10: d.writeUInt(timeScale); // dwScale rlm@10: // Used with dwRate to specify the time scale that this stream will use. rlm@10: // Dividing dwRate by dwScale gives the number of samples per second. rlm@10: // For video streams, this is the frame rate. For audio streams, this rlm@10: // rate corresponds to the time needed to play nBlockAlign bytes of rlm@10: // audio, which for PCM audio is the just the sample rate. rlm@10: rlm@10: d.writeUInt(frameRate); // dwRate rlm@10: // See dwScale. rlm@10: rlm@10: d.writeUInt(0); // dwStart rlm@10: // Specifies the starting time for this stream. The units are defined by rlm@10: // the dwRate and dwScale members in the main file header. Usually, this rlm@10: // is zero, but it can specify a delay time for a stream that does not rlm@10: // start concurrently with the file. rlm@10: rlm@10: d.writeUInt(videoFrames.size()); // dwLength rlm@10: // Specifies the length of this stream. The units are defined by the rlm@10: // dwRate and dwScale members of the stream's header. rlm@10: rlm@10: d.writeUInt(bufferSize); // dwSuggestedBufferSize rlm@10: // Specifies how large a buffer should be used to read this stream. rlm@10: // Typically, this contains a value corresponding to the largest chunk rlm@10: // present in the stream. Using the correct buffer size makes playback rlm@10: // more efficient. Use zero if you do not know the correct buffer size. rlm@10: rlm@10: d.writeInt(-1); // dwQuality rlm@10: // Specifies an indicator of the quality of the data in the stream. rlm@10: // Quality is represented as a number between 0 and 10,000. rlm@10: // For compressed data, this typically represents the value of the rlm@10: // quality parameter passed to the compression software. If set to –1, rlm@10: // drivers use the default quality value. rlm@10: rlm@10: d.writeUInt(0); // dwSampleSize rlm@10: // Specifies the size of a single sample of data. This is set to zero rlm@10: // if the samples can vary in size. If this number is nonzero, then rlm@10: // multiple samples of data can be grouped into a single chunk within rlm@10: // the file. If it is zero, each sample of data (such as a video frame) rlm@10: // must be in a separate chunk. For video streams, this number is rlm@10: // typically zero, although it can be nonzero if all video frames are rlm@10: // the same size. For audio streams, this number should be the same as rlm@10: // the nBlockAlign member of the WAVEFORMATEX structure describing the rlm@10: // audio. rlm@10: rlm@10: d.writeUShort(0); // rcFrame.left rlm@10: d.writeUShort(0); // rcFrame.top rlm@10: d.writeUShort(imgWidth); // rcFrame.right rlm@10: d.writeUShort(imgHeight); // rcFrame.bottom rlm@10: // Specifies the destination rectangle for a text or video stream within rlm@10: // the movie rectangle specified by the dwWidth and dwHeight members of rlm@10: // the AVI main header structure. The rcFrame member is typically used rlm@10: // in support of multiple video streams. Set this rectangle to the rlm@10: // coordinates corresponding to the movie rectangle to update the whole rlm@10: // movie rectangle. Units for this member are pixels. The upper-left rlm@10: // corner of the destination rectangle is relative to the upper-left rlm@10: // corner of the movie rectangle. rlm@10: rlm@10: /* Write BITMAPINFOHEADR Data into AVI Stream Format Chunk rlm@10: /* ------------- rlm@10: * see http://msdn.microsoft.com/en-us/library/ms779712(VS.85).aspx rlm@10: typedef struct tagBITMAPINFOHEADER { rlm@10: DWORD biSize; rlm@10: LONG biWidth; rlm@10: LONG biHeight; rlm@10: WORD biPlanes; rlm@10: WORD biBitCount; rlm@10: DWORD biCompression; rlm@10: DWORD biSizeImage; rlm@10: LONG biXPelsPerMeter; rlm@10: LONG biYPelsPerMeter; rlm@10: DWORD biClrUsed; rlm@10: DWORD biClrImportant; rlm@10: } BITMAPINFOHEADER; rlm@10: */ rlm@10: strfChunk.seekToStartOfData(); rlm@10: d = strfChunk.getOutputStream(); rlm@10: d.writeUInt(40); // biSize rlm@10: // Specifies the number of bytes required by the structure. This value rlm@10: // does not include the size of the color table or the size of the color rlm@10: // masks, if they are appended to the end of structure. rlm@10: rlm@10: d.writeInt(imgWidth); // biWidth rlm@10: // Specifies the width of the bitmap, in pixels. rlm@10: rlm@10: d.writeInt(imgHeight); // biHeight rlm@10: // Specifies the height of the bitmap, in pixels. rlm@10: // rlm@10: // For uncompressed RGB bitmaps, if biHeight is positive, the bitmap is rlm@10: // a bottom-up DIB with the origin at the lower left corner. If biHeight rlm@10: // is negative, the bitmap is a top-down DIB with the origin at the rlm@10: // upper left corner. rlm@10: // For YUV bitmaps, the bitmap is always top-down, regardless of the rlm@10: // sign of biHeight. Decoders should offer YUV formats with postive rlm@10: // biHeight, but for backward compatibility they should accept YUV rlm@10: // formats with either positive or negative biHeight. rlm@10: // For compressed formats, biHeight must be positive, regardless of rlm@10: // image orientation. rlm@10: rlm@10: d.writeShort(1); // biPlanes rlm@10: // Specifies the number of planes for the target device. This value must rlm@10: // be set to 1. rlm@10: rlm@10: d.writeShort(imgDepth); // biBitCount rlm@10: // Specifies the number of bits per pixel (bpp). For uncompressed rlm@10: // formats, this value is the average number of bits per pixel. For rlm@10: // compressed formats, this value is the implied bit depth of the rlm@10: // uncompressed image, after the image has been decoded. rlm@10: rlm@10: switch (videoFormat) { rlm@10: case RAW: rlm@10: default: rlm@10: d.writeInt(0); // biCompression - BI_RGB for uncompressed RGB rlm@10: break; rlm@10: case RLE: rlm@10: if (imgDepth == 8) { rlm@10: d.writeInt(1); // biCompression - BI_RLE8 rlm@10: } else if (imgDepth == 4) { rlm@10: d.writeInt(2); // biCompression - BI_RLE4 rlm@10: } else { rlm@10: throw new UnsupportedOperationException("RLE only supports 4-bit and 8-bit images"); rlm@10: } rlm@10: break; rlm@10: case JPG: rlm@10: d.writeType("MJPG"); // biCompression - MJPG for Motion JPEG rlm@10: break; rlm@10: case PNG: rlm@10: d.writeType("png "); // biCompression - png for PNG rlm@10: break; rlm@10: } rlm@10: // For compressed video and YUV formats, this member is a FOURCC code, rlm@10: // specified as a DWORD in little-endian order. For example, YUYV video rlm@10: // has the FOURCC 'VYUY' or 0x56595559. For more information, see FOURCC rlm@10: // Codes. rlm@10: // rlm@10: // For uncompressed RGB formats, the following values are possible: rlm@10: // rlm@10: // Value Description rlm@10: // BI_RGB 0x00000000 Uncompressed RGB. rlm@10: // BI_BITFIELDS 0x00000003 Uncompressed RGB with color masks. rlm@10: // Valid for 16-bpp and 32-bpp bitmaps. rlm@10: // rlm@10: // Note that BI_JPG and BI_PNG are not valid video formats. rlm@10: // rlm@10: // For 16-bpp bitmaps, if biCompression equals BI_RGB, the format is rlm@10: // always RGB 555. If biCompression equals BI_BITFIELDS, the format is rlm@10: // either RGB 555 or RGB 565. Use the subtype GUID in the AM_MEDIA_TYPE rlm@10: // structure to determine the specific RGB type. rlm@10: rlm@10: switch (videoFormat) { rlm@10: case RAW: rlm@10: d.writeInt(0); // biSizeImage rlm@10: break; rlm@10: case RLE: rlm@10: case JPG: rlm@10: case PNG: rlm@10: default: rlm@10: if (imgDepth == 4) { rlm@10: d.writeInt(imgWidth * imgHeight / 2); // biSizeImage rlm@10: } else { rlm@10: int bytesPerPixel = Math.max(1, imgDepth / 8); rlm@10: d.writeInt(imgWidth * imgHeight * bytesPerPixel); // biSizeImage rlm@10: } rlm@10: break; rlm@10: } rlm@10: // Specifies the size, in bytes, of the image. This can be set to 0 for rlm@10: // uncompressed RGB bitmaps. rlm@10: rlm@10: d.writeInt(0); // biXPelsPerMeter rlm@10: // Specifies the horizontal resolution, in pixels per meter, of the rlm@10: // target device for the bitmap. rlm@10: rlm@10: d.writeInt(0); // biYPelsPerMeter rlm@10: // Specifies the vertical resolution, in pixels per meter, of the target rlm@10: // device for the bitmap. rlm@10: rlm@10: d.writeInt(palette == null ? 0 : palette.getMapSize()); // biClrUsed rlm@10: // Specifies the number of color indices in the color table that are rlm@10: // actually used by the bitmap. rlm@10: rlm@10: d.writeInt(0); // biClrImportant rlm@10: // Specifies the number of color indices that are considered important rlm@10: // for displaying the bitmap. If this value is zero, all colors are rlm@10: // important. rlm@10: rlm@10: if (palette != null) { rlm@10: for (int i = 0, n = palette.getMapSize(); i < n; ++i) { rlm@10: /* rlm@10: * typedef struct tagRGBQUAD { rlm@10: BYTE rgbBlue; rlm@10: BYTE rgbGreen; rlm@10: BYTE rgbRed; rlm@10: BYTE rgbReserved; // This member is reserved and must be zero. rlm@10: } RGBQUAD; rlm@10: */ rlm@10: d.write(palette.getBlue(i)); rlm@10: d.write(palette.getGreen(i)); rlm@10: d.write(palette.getRed(i)); rlm@10: d.write(0); rlm@10: } rlm@10: } rlm@10: rlm@10: rlm@10: // ----------------- rlm@10: aviChunk.finish(); rlm@10: } rlm@10: }