2 * Copyright © 2010-2011 Amichai Rothman
\r
4 * This file is part of JFLVStream - the Java FLV Pseudostreaming package.
\r
6 * JFLVStream is free software: you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation, either version 3 of the License, or
\r
9 * (at your option) any later version.
\r
11 * JFLVStream is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with JFLVStream. If not, see <http://www.gnu.org/licenses/>.
\r
19 * For additional info see http://www.freeutils.net/source/jflvstream/
\r
22 package com.pentila.entSavoie.servlet;
\r
25 import javax.servlet.http.HttpServletRequest;
\r
26 import javax.servlet.http.HttpServletResponse;
\r
29 * The {@code FLVPseudoStreamer} class provides a server-side FLV pseudostreaming implementation.
\r
31 * An FLV stream consists of a header, followed by a series of tag blocks.
\r
32 * A description of the format can be found <a href="http://osflash.org/flv">here</a>,
\r
33 * however it requires clarification: each block begins with an 11-byte header, followed
\r
34 * by the block data, followed by a 4-byte total block size value (the data size,
\r
35 * as it appears in the 3-byte header field, plus 11). The FLV header itself is reminiscent
\r
36 * of the tag blocks, as it also contains a header size field (although it's 4 bytes and at
\r
37 * a different offset than within tags), and followed by a 4-byte total block size value
\r
38 * (although for the header, it's always zero).
\r
40 * The pseudostreaming works by having the client ask for a specific start position
\r
41 * within the FLV stream, which corresponds to the first byte of a tag containing a key
\r
42 * frame. The server then sends an FLV stream header followed by the data starting at this
\r
43 * position, which effectively looks to the client like a new, valid, FLV stream which
\r
44 * contains the video starting at the requested key frame.
\r
46 * See the {@link #service service} method for a usage example.
\r
48 * @author Amichai Rothman
\r
51 public class FLVPseudoStreamer {
\r
53 protected static final int HEADER_LENGTH = 13;
\r
54 protected static final byte[] SIGNATURE = { 'F', 'L', 'V', 0x01 };
\r
56 protected File basedir;
\r
57 protected InputStream flvStream;
\r
58 protected String filename;
\r
59 protected long length;
\r
61 protected boolean allowCaching;
\r
62 protected boolean allowDynamicBandwidthLimit;
\r
63 protected int packetInterval;
\r
64 protected int packetSize;
\r
67 * Constructs a streamer which allows dynamic bandwidth limiting.
\r
69 public FLVPseudoStreamer() {
\r
70 setAllowDynamicBandwidthLimit(true);
\r
71 setBandwidthLimit(-1, -1);
\r
75 * Sets the base directory where the files to be streamed reside.
\r
77 * @param dir the base directory
\r
78 * @throws IOException if the given directory is invalid
\r
80 public void setBaseDirectory(String dir) throws IOException {
\r
81 File basedir = new File(dir);
\r
82 if (!basedir.isDirectory())
\r
83 throw new IOException("directory not found: " + dir);
\r
84 this.basedir = basedir.getCanonicalFile();
\r
88 * Sets the filename of the file to stream, relative
\r
89 * to the {@link #setBaseDirectory base directory}.
\r
91 * @param filename the filename of the file to stream, relative to
\r
92 * the base directory
\r
93 * @throws IOException if the filename is invalid, the file cannot
\r
94 * be read or it is not under the base directory
\r
96 public void setFLVFile(String filename) throws IOException {
\r
97 if (filename == null)
\r
98 throw new IOException("missing file name");
\r
99 File file = new File(basedir, filename);
\r
100 if (!file.canRead())
\r
101 throw new IOException("can't read file: " + filename);
\r
102 file = file.getCanonicalFile();
\r
103 if (!file.getCanonicalPath().startsWith(basedir.getCanonicalPath()))
\r
104 throw new IOException("access denied");
\r
105 setFLVStream(new BufferedInputStream(
\r
106 new FileInputStream(file)), file.getName(), file.length());
\r
110 * Sets the data for the FLV stream.
\r
112 * @param flvStream the full FLV data stream
\r
113 * @param filename the FLV file name (only the base name, without path)
\r
114 * @param length the total FLV stream length
\r
116 public void setFLVStream(InputStream flvStream, String filename, long length) {
\r
117 this.flvStream = flvStream;
\r
118 this.filename = filename;
\r
119 this.length = length;
\r
123 * Sets the bandwidth limit for the streamed data. The limit is actually an average,
\r
124 * defined in terms of packet size and time interval: after a packet of the
\r
125 * given size is sent (at maximum burst speed), the next packet will not be sent
\r
126 * until the interval (starting at the beginning of the packet) has passed.
\r
128 * The effective average limit in kilobytes per second is thus<br>
\r
129 * {@code (packetSize / 1024 ) / (packetInterval / 1000)}<br>
\r
131 * {@code 1000 * (packetSize / 1024) / packetInterval}<br>
\r
133 * {@code 0.9765625 * packetSize / packetInterval}.
\r
135 * If either of the parameters is set to a non-positive value,
\r
136 * the bandwidth is effectively unlimited.
\r
138 * @param packetInterval the interval between beginnings of packets in milliseconds
\r
139 * @param packetSize the packet size in bytes
\r
141 public void setBandwidthLimit(int packetInterval, int packetSize) {
\r
142 if (packetInterval < 1 || packetSize < 1) {
\r
143 packetInterval = 1000;
\r
144 packetSize = Integer.MAX_VALUE; // effectively unlimited
\r
146 this.packetInterval = packetInterval;
\r
147 this.packetSize = packetSize;
\r
151 * Sets the bandwidth limits for the streamed data.
\r
153 * The following are the valid values, and their interpretation:
\r
154 * <table border="1">
\r
155 * <tr><th>Value</th><th>Packet Size (b)</th><th>Packet Interval (ms)</th><th>Effective limit (kb/s)</tr>
\r
156 * <tr><td>Any integer {@code n}</td><td>{@code n} * 256</td><td>250</td><td>{@code n}</td></tr>
\r
157 * <tr><td>"low"</td><td>10 * 1024</td><td>1000</td><td>10</td></tr>
\r
158 * <tr><td>"mid"</td><td>40 * 1024</td><td>500</td><td>80</td></tr>
\r
159 * <tr><td>"high"</td><td>90 * 1024</td><td>300</td><td>300</td></tr>
\r
160 * <tr><td>Anything else</td><td>90 * 1024</td><td>300</td><td>300</td></tr>
\r
163 * @param limit the bandwidth limit
\r
165 public void setBandwidthLimit(String limit) {
\r
168 if ("low".equals(limit)) {
\r
171 } else if ("mid".equals(limit)) {
\r
174 } else if ("high".equals(limit)) {
\r
179 int kbps = Integer.parseInt(limit);
\r
180 interval = 1000 / 4;
\r
181 size = kbps * 1024 / 4;
\r
182 } catch (NumberFormatException nfe) {
\r
187 setBandwidthLimit(interval, size);
\r
191 * Sets whether the client is allowed to request a specified bandwidth limit.
\r
193 * @param allow true if dynamic bandwidth limit is allowed, false otherwise
\r
195 public void setAllowDynamicBandwidthLimit(boolean allow) {
\r
196 this.allowDynamicBandwidthLimit = allow;
\r
200 * Sets whether client caching of the streamed FLV data is allowed. If not,
\r
201 * the appropriate HTTP headers are sent to prevent caching.
\r
203 * @param allow true if caching is allowed, false otherwise
\r
205 public void setAllowCaching(boolean allow) {
\r
206 this.allowCaching = allow;
\r
210 * Returns the full length of the stream (in bytes).
\r
212 * @return the full length of the stream (in bytes)
\r
214 public long length() {
\r
219 * Returns the length of the streamed data when starting at the given
\r
220 * position in the stream (in bytes). This includes the header that will
\r
221 * be prepended to the data if necessary, and the data itself.
\r
223 * @param pos the position within the file from which the data
\r
224 * will be streamed. If non-positive, the full length of the
\r
225 * file is returned.
\r
226 * @return the length of the streamed data when starting at the given position
\r
228 public long length(long pos) {
\r
229 return pos <= 0 ? length : HEADER_LENGTH + length - pos;
\r
233 * Reads the header from the given FLV stream.
\r
235 * @param in an FLV stream
\r
236 * @return the FLV header
\r
237 * @throws IOException if an I/O error occurs, or if the
\r
238 * given stream does not begin with a valid FLV header
\r
240 protected byte[] readHeader(InputStream in) throws IOException {
\r
241 byte[] header = new byte[HEADER_LENGTH];
\r
243 int len = HEADER_LENGTH;
\r
245 len -= in.read(header, HEADER_LENGTH - len, len);
\r
247 for (int i = 0; i < SIGNATURE.length; i++)
\r
248 if (header[i] != SIGNATURE[i])
\r
249 throw new IOException("invalid FLV signature");
\r
254 * Writes a valid FLV stream to the given output stream, with the data starting
\r
255 * at the given position in the FLV stream. Both streams are closed by this method.
\r
257 * @param out the stream to write to
\r
258 * @param pos the position within the FLV stream where the requested data starts
\r
259 * (this should be either the first byte of the data, or the first byte of
\r
260 * a tag containing a key frame)
\r
261 * @throws IOException if an error occurs or the data stream does not begin with a
\r
263 * @throws InterruptedIOException if transfer is interrupted in the middle, e.g. when
\r
264 * the client seeks to a different position in the stream
\r
266 public void stream(OutputStream out, long pos) throws IOException, InterruptedIOException {
\r
268 pos = HEADER_LENGTH; // data starts at first tag after header
\r
269 long len = length - pos;
\r
270 byte[] buf = new byte[16384];
\r
273 // write FLV header
\r
274 byte[] header = readHeader(flvStream);
\r
275 out.write(header, 0, HEADER_LENGTH);
\r
276 // skip to start position
\r
277 pos -= HEADER_LENGTH; // header has already been read from stream
\r
279 pos -= flvStream.skip(pos);
\r
282 // write full packet
\r
283 long packetStartTime = System.currentTimeMillis();
\r
284 int remaining = (int)Math.min(len, packetSize);
\r
286 while ((count = flvStream.read(buf, 0, Math.min(buf.length, remaining))) > 0) {
\r
288 out.write(buf, 0, count);
\r
289 } catch (IOException ioe) {
\r
290 // when client seeks to new position within stream, the previous stream is
\r
291 // broken, so we treat it as a special interrupt and not regular IOException
\r
292 throw new InterruptedException("streaming interrupted");
\r
294 remaining -= count;
\r
297 long remainingTime = packetStartTime + packetInterval - System.currentTimeMillis();
\r
298 if (remainingTime > 0)
\r
299 Thread.sleep(remainingTime);
\r
301 } catch (InterruptedException ie) {
\r
302 InterruptedIOException iioe = new InterruptedIOException("streaming interrupted");
\r
303 iioe.bytesTransferred = (int)(length - len);
\r
308 } catch (IOException ignore) {}
\r
311 } catch (IOException ignore) {
\r
312 // client may close the stream when data ends, causing a broken pipe exception
\r
313 // so we just ignore it
\r
319 * Sets headers in the given response to prevent it from being cached.
\r
321 * @param response the response which should not be cached
\r
323 public static void preventCaching(HttpServletResponse response) {
\r
324 response.setHeader("Pragma", "no-cache");
\r
325 response.setHeader("Cache-Control", "no-cache");
\r
326 response.addHeader("Cache-Control", "no-store");
\r
327 response.addHeader("Cache-Control", "private");
\r
328 response.addHeader("Cache-Control", "max-stale=0");
\r
329 response.addHeader("Cache-Control", "max-age=0");
\r
330 response.setDateHeader("Expires", 0);
\r
334 * Serves a request to stream an FLV file.
\r
336 * This method can either be called directly from a servlet, or just viewed as an
\r
337 * example of how this class might be used by a servlet or other communications
\r
338 * framework (the rest of this class is independent of the Servlet API).
\r
340 * The supported request parameters are:
\r
342 * <li>{@code file} - the name of the file to stream, relative to the base directory.
\r
343 * <li>{@code start} - the position within the FLV file where the data starts (this
\r
344 * should be either the first byte of the file, or the first byte of a tag
\r
345 * containing a key frame). If omitted, the file is streamed from its beginning.
\r
346 * <li>{@code bw} - a bandwidth limit string, passed to the
\r
347 * {@link #setBandwidthLimit(String) setBandwidthLimit} method. If dynamic bandwidth
\r
348 * is not allowed or this parameter is omitted, the previously set limit is used.
\r
351 * The HTTP response headers are set as follows:
\r
353 * <li>Content-Type is set to "video/x-flv".
\r
354 * <li>Content-Disposition is set to "attachment" with the original filename.
\r
355 * <li>Content-Length is set to the appropriate (full or partial) stream length.
\r
356 * <li>If caching is not allowed, the appropriate HTTP headers are set to prevent caching.
\r
357 * <li>If an error occurs, an appropriate HTTP response code is sent.
\r
359 * @param request the request containing the streaming parameters
\r
360 * @param response the response to which the file is streamed
\r
361 * @throws IOException if an error occurs
\r
362 * @throws InterruptedIOException if transfer is interrupted in the middle,
\r
363 * e.g. when the client seeks to a different position in the streams
\r
365 public void service(HttpServletRequest request, HttpServletResponse response)
\r
366 throws IOException, InterruptedIOException {
\r
368 // parse parameters
\r
369 String filename = request.getParameter("file");
\r
370 setFLVFile(filename);
\r
371 if (allowDynamicBandwidthLimit)
\r
372 setBandwidthLimit(request.getParameter("bw"));
\r
373 String ppos = request.getParameter("start");
\r
374 long pos = ppos == null || ppos.length() == 0 ? 0 : Long.parseLong(ppos);
\r
375 // prepare response headers
\r
376 response.setStatus(HttpServletResponse.SC_OK);
\r
377 response.setContentType("video/x-flv");
\r
378 response.setHeader("Content-Disposition", "attachment; filename=\"" + this.filename + "\"");
\r
379 response.setHeader("Content-Length", Long.toString(length(pos))); // setContentLength() is limited to 2GB
\r
381 preventCaching(response);
\r
382 stream(response.getOutputStream(), pos);
\r
383 } catch (IllegalArgumentException iae) {
\r
384 iae.printStackTrace();
\r
385 response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
\r
386 } catch (InterruptedIOException iioe) {
\r
387 // this is ok, client likely seeked to new position within stream
\r
388 } catch (IOException ioe) {
\r
389 ioe.printStackTrace();
\r
390 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error streaming file");
\r
391 } catch (Throwable t) {
\r
392 t.printStackTrace();
\r
393 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error processing request");
\r
397 public void service(HttpServletRequest request,
\r
398 HttpServletResponse response,
\r
402 String contentType)
\r
403 throws IOException, InterruptedIOException {
\r
405 setFLVStream(new BufferedInputStream(is), fileName, contentLength);
\r
407 if (allowDynamicBandwidthLimit)
\r
408 setBandwidthLimit(request.getParameter("bw"));
\r
409 String ppos = request.getParameter("start");
\r
410 long pos = ppos == null || ppos.length() == 0 ? 0 : Long.parseLong(ppos);
\r
411 // prepare response headers
\r
412 response.setStatus(HttpServletResponse.SC_OK);
\r
413 response.setContentType("video/x-flv");
\r
414 response.setHeader("Content-Disposition", "attachment; filename=\"" + this.filename + "\"");
\r
415 response.setHeader("Content-Length", Long.toString(length(pos))); // setContentLength() is limited to 2GB
\r
417 preventCaching(response);
\r
418 stream(response.getOutputStream(), pos);
\r
419 } catch (IllegalArgumentException iae) {
\r
420 iae.printStackTrace();
\r
421 response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
\r
422 } catch (InterruptedIOException iioe) {
\r
423 // this is ok, client likely seeked to new position within stream
\r
424 } catch (IOException ioe) {
\r
425 ioe.printStackTrace();
\r
426 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error streaming file");
\r
427 } catch (Throwable t) {
\r
428 t.printStackTrace();
\r
429 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error processing request");
\r