
net.freeutils.web.FLVPseudoStreamer Maven / Gradle / Ivy
Show all versions of jflvstream Show documentation
/*
* Copyright © 2010-2015 Amichai Rothman
*
* This file is part of JFLVStream - the Java FLV Pseudostreaming package.
*
* JFLVStream is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JFLVStream is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JFLVStream. If not, see .
*
* For additional info see http://www.freeutils.net/source/jflvstream/
*/
package net.freeutils.web;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The {@code FLVPseudoStreamer} class provides a server-side FLV pseudostreaming implementation.
*
* An FLV stream consists of a header, followed by a series of tag blocks.
* A description of the format can be found here,
* however it requires clarification: each block begins with an 11-byte header, followed
* by the block data, followed by a 4-byte total block size value (the data size,
* as it appears in the 3-byte header field, plus 11). The FLV header itself is reminiscent
* of the tag blocks, as it also contains a header size field (although it's 4 bytes and at
* a different offset than within tags), and followed by a 4-byte total block size value
* (although for the header, it's always zero).
*
* The pseudostreaming works by having the client ask for a specific start position
* within the FLV stream, which corresponds to the first byte of a tag containing a key
* frame. The server then sends an FLV stream header followed by the data starting at this
* position, which effectively looks to the client like a new, valid, FLV stream which
* contains the video starting at the requested key frame.
*
* See the {@link #service service} method for a usage example.
*
* @author Amichai Rothman
* @since 2010-06-23
*/
public class FLVPseudoStreamer {
protected static final int HEADER_LENGTH = 13;
protected static final byte[] SIGNATURE = { 'F', 'L', 'V', 0x01 };
protected File basedir;
protected InputStream flvStream;
protected String filename;
protected long length;
protected boolean allowCaching;
protected boolean allowDynamicBandwidthLimit;
protected int packetInterval;
protected int packetSize;
/**
* Constructs a streamer which allows dynamic bandwidth limiting.
*/
public FLVPseudoStreamer() {
setAllowDynamicBandwidthLimit(true);
setBandwidthLimit(-1, -1);
}
/**
* Sets the base directory where the files to be streamed reside.
*
* @param dir the base directory
* @throws IOException if the given directory is invalid
*/
public void setBaseDirectory(String dir) throws IOException {
File basedir = new File(dir);
if (!basedir.isDirectory())
throw new IOException("directory not found: " + dir);
this.basedir = basedir.getCanonicalFile();
}
/**
* Sets the filename of the file to stream, relative
* to the {@link #setBaseDirectory base directory}.
*
* @param filename the filename of the file to stream, relative to
* the base directory
* @throws IOException if the filename is invalid, the file cannot
* be read or it is not under the base directory
*/
public void setFLVFile(String filename) throws IOException {
if (filename == null)
throw new FileNotFoundException("filename is null");
File file = new File(basedir, filename).getCanonicalFile();
if (!file.getCanonicalPath().startsWith(basedir.getCanonicalPath()))
throw new IOException("access denied");
if (!file.canRead())
throw new FileNotFoundException(filename);
setFLVStream(new BufferedInputStream(new FileInputStream(file)),
file.getName(), file.length());
}
/**
* Sets the data for the FLV stream.
*
* @param flvStream the full FLV data stream
* @param filename the FLV file name (only the base name, without path)
* @param length the total FLV stream length
*/
public void setFLVStream(InputStream flvStream, String filename, long length) {
this.flvStream = flvStream;
this.filename = filename;
this.length = length;
}
/**
* Sets the bandwidth limit for the streamed data. The limit is actually an average,
* defined in terms of packet size and time interval: after a packet of the
* given size is sent (at maximum burst speed), the next packet will not be sent
* until the interval (starting at the beginning of the packet) has passed.
*
* The effective average limit in kilobytes per second is thus
* {@code (packetSize / 1024 ) / (packetInterval / 1000)}
* or
* {@code 1000 * (packetSize / 1024) / packetInterval}
* or
* {@code 0.9765625 * packetSize / packetInterval}.
*
* If either of the parameters is set to a non-positive value,
* the bandwidth is effectively unlimited.
*
* @param packetInterval the interval between beginnings of packets in milliseconds
* @param packetSize the packet size in bytes
*/
public void setBandwidthLimit(int packetInterval, int packetSize) {
if (packetInterval < 1 || packetSize < 1) {
packetInterval = 1000;
packetSize = Integer.MAX_VALUE; // effectively unlimited
}
this.packetInterval = packetInterval;
this.packetSize = packetSize;
}
/**
* Sets the bandwidth limits for the streamed data.
*
* The following are the valid values, and their interpretation:
*
* Value Packet Size (b) Packet Interval (ms) Effective limit (kb/s)
* Any integer {@code n} {@code n} * 256 250 {@code n}
* "low" 10 * 1024 1000 10
* "mid" 40 * 1024 500 80
* "high" 90 * 1024 300 300
* Anything else 90 * 1024 300 300
*
*
* @param limit the bandwidth limit
*/
public void setBandwidthLimit(String limit) {
int interval;
int size;
if ("low".equals(limit)) {
interval = 1000;
size = 10 * 1024;
} else if ("mid".equals(limit)) {
interval = 500;
size = 40 * 1024;
} else if ("high".equals(limit)) {
interval = 300;
size = 90 * 1024;
} else {
try {
int kbps = Integer.parseInt(limit);
interval = 1000 / 4;
size = kbps * 1024 / 4;
} catch (NumberFormatException nfe) {
interval = 300;
size = 90 * 1024;
}
}
setBandwidthLimit(interval, size);
}
/**
* Sets whether the client is allowed to request a specified bandwidth limit.
*
* @param allow true if dynamic bandwidth limit is allowed, false otherwise
*/
public void setAllowDynamicBandwidthLimit(boolean allow) {
this.allowDynamicBandwidthLimit = allow;
}
/**
* Sets whether client caching of the streamed FLV data is allowed. If not,
* the appropriate HTTP headers are sent to prevent caching.
*
* @param allow true if caching is allowed, false otherwise
*/
public void setAllowCaching(boolean allow) {
this.allowCaching = allow;
}
/**
* Returns the full length of the stream (in bytes).
*
* @return the full length of the stream (in bytes)
*/
public long length() {
return length;
}
/**
* Returns the length of the streamed data when starting at the given
* position in the stream (in bytes). This includes the header that will
* be prepended to the data if necessary, and the data itself.
*
* @param pos the position within the file from which the data
* will be streamed. If non-positive, the full length of the
* file is returned.
* @return the length of the streamed data when starting at the given position
*/
public long length(long pos) {
return pos <= 0 ? length : HEADER_LENGTH + length - pos;
}
/**
* Reads the header from the given FLV stream.
*
* @param in an FLV stream
* @return the FLV header
* @throws IOException if an I/O error occurs, or if the
* given stream does not begin with a valid FLV header
*/
protected byte[] readHeader(InputStream in) throws IOException {
byte[] header = new byte[HEADER_LENGTH];
// read header
int len = HEADER_LENGTH;
while (len > 0) {
int count = in.read(header, HEADER_LENGTH - len, len);
if (count == -1)
throw new EOFException("invalid FLV header"); // too short
len -= count;
}
// validate it
for (int i = 0; i < SIGNATURE.length; i++)
if (header[i] != SIGNATURE[i])
throw new IOException("invalid FLV signature");
return header;
}
/**
* Writes a valid FLV stream to the given output stream, with the data starting
* at the given position in the FLV stream. Both streams are closed by this method.
*
* @param out the stream to write to
* @param pos the position within the FLV stream where the requested data starts
* (this should be either the first byte of the data, or the first byte of
* a tag containing a key frame)
* @throws IOException if an error occurs or the data stream does not begin with a
* valid FLV header
* @throws InterruptedIOException if transfer is interrupted in the middle, e.g. when
* the client seeks to a different position in the stream
*/
public void stream(OutputStream out, long pos) throws IOException, InterruptedIOException {
if (pos <= 0)
pos = HEADER_LENGTH; // data starts at first tag after header
long len = length - pos;
byte[] buf = new byte[16384];
try {
// write FLV header
byte[] header = readHeader(flvStream);
out.write(header, 0, HEADER_LENGTH);
// skip to start position
pos -= HEADER_LENGTH; // header has already been read from stream
while (pos > 0)
pos -= flvStream.skip(pos);
// stream the data
while (len > 0) {
// write full packet
long packetStartTime = System.currentTimeMillis();
int remaining = (int)Math.min(len, packetSize);
int count;
while ((count = flvStream.read(buf, 0, Math.min(buf.length, remaining))) > 0) {
try {
out.write(buf, 0, count);
} catch (IOException ioe) {
// when client seeks to new position within stream, the previous stream is
// broken, so we treat it as a special interrupt and not regular IOException
throw new InterruptedException("streaming interrupted");
}
remaining -= count;
len -= count;
}
if (remaining > 0)
throw new EOFException("unexpected end of stream");
long remainingTime = packetStartTime + packetInterval - System.currentTimeMillis();
if (remainingTime > 0)
Thread.sleep(remainingTime);
}
} catch (InterruptedException ie) {
InterruptedIOException iioe = new InterruptedIOException("streaming interrupted");
iioe.bytesTransferred = (int)(length - len);
throw iioe;
} finally {
try {
flvStream.close();
} catch (IOException ignore) {}
try {
out.close();
} catch (IOException ignore) {
// client may close the stream when data ends, causing a broken pipe exception
// so we just ignore it
}
}
}
/**
* Sets headers in the given response to prevent it from being cached.
*
* @param response the response which should not be cached
*/
public static void preventCaching(HttpServletResponse response) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.addHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "private");
response.addHeader("Cache-Control", "max-stale=0");
response.addHeader("Cache-Control", "max-age=0");
response.setDateHeader("Expires", 0);
}
/**
* Serves a request to stream an FLV file.
*
* This method can either be called directly from a servlet, or just viewed as an
* example of how this class might be used by a servlet or other communications
* framework (the rest of this class is independent of the Servlet API).
*
* The supported request parameters are:
*
* - {@code file} - the name of the file to stream, relative to the base directory.
*
- {@code start} - the position within the FLV file where the data starts (this
* should be either the first byte of the file, or the first byte of a tag
* containing a key frame). If omitted, the file is streamed from its beginning.
*
- {@code bw} - a bandwidth limit string, passed to the
* {@link #setBandwidthLimit(String) setBandwidthLimit} method. If dynamic bandwidth
* is not allowed or this parameter is omitted, the previously set limit is used.
*
*
* The HTTP response headers are set as follows:
*
* - Content-Type is set to "video/x-flv".
*
- Content-Disposition is set to "attachment" with the original filename.
*
- Content-Length is set to the appropriate (full or partial) stream length.
*
- If caching is not allowed, the appropriate HTTP headers are set to prevent caching.
*
- If an error occurs, an appropriate HTTP response code is sent.
*
*
* @param request the request containing the streaming parameters
* @param response the response to which the file is streamed
* @throws IOException if an error occurs
* @throws InterruptedIOException if transfer is interrupted in the middle,
* e.g. when the client seeks to a different position in the streams
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, InterruptedIOException {
try {
// parse parameters
String filename = request.getParameter("file");
setFLVFile(filename);
if (allowDynamicBandwidthLimit)
setBandwidthLimit(request.getParameter("bw"));
String ppos = request.getParameter("start");
long pos = ppos == null || ppos.length() == 0 ? 0 : Long.parseLong(ppos);
// prepare response headers
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("video/x-flv");
response.setHeader("Content-Disposition", "attachment; filename=\"" + this.filename + "\"");
response.setHeader("Content-Length", Long.toString(length(pos))); // setContentLength() is limited to 2GB
if (!allowCaching)
preventCaching(response);
stream(response.getOutputStream(), pos);
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
} catch (InterruptedIOException iioe) {
// this is ok, client likely seeked to new position within stream
} catch (IOException ioe) {
ioe.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error streaming file");
} catch (Throwable t) {
t.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error processing request");
}
}
}