1 /*
   2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.sound.sampled;
  27 
  28 import java.io.InputStream;
  29 import java.io.PushbackInputStream;
  30 import java.io.IOException;
  31 
  32 
  33 /**
  34  * An audio input stream is an input stream with a specified audio format and
  35  * length.  The length is expressed in sample frames, not bytes.
  36  * Several methods are provided for reading a certain number of bytes from
  37  * the stream, or an unspecified number of bytes.
  38  * The audio input stream keeps track  of the last byte that was read.
  39  * You can skip over an arbitrary number of bytes to get to a later position
  40  * for reading. An audio input stream may support marks.  When you set a mark,
  41  * the current position is remembered so that you can return to it later.
  42  * <p>
  43  * The <code>AudioSystem</code> class includes many methods that manipulate
  44  * <code>AudioInputStream</code> objects.
  45  * For example, the methods let you:
  46  * <ul>
  47  * <li> obtain an
  48  * audio input stream from an external audio file, stream, or URL
  49  * <li> write an external file from an audio input stream
  50  * <li> convert an audio input stream to a different audio format
  51  * </ul>
  52  *
  53  * @author David Rivas
  54  * @author Kara Kytle
  55  * @author Florian Bomers
  56  *
  57  * @see AudioSystem
  58  * @see Clip#open(AudioInputStream) Clip.open(AudioInputStream)
  59  * @since 1.3
  60  */
  61 public class AudioInputStream extends InputStream {
  62 
  63     /**
  64      * The <code>InputStream</code> from which this <code>AudioInputStream</code>
  65      * object was constructed.
  66      */
  67     private InputStream stream;
  68 
  69     /**
  70      * The format of the audio data contained in the stream.
  71      */
  72     protected AudioFormat format;
  73 
  74     /**
  75      * This stream's length, in sample frames.
  76      */
  77     protected long frameLength;
  78 
  79     /**
  80      * The size of each frame, in bytes.
  81      */
  82     protected int frameSize;
  83 
  84     /**
  85      * The current position in this stream, in sample frames (zero-based).
  86      */
  87     protected long framePos;
  88 
  89     /**
  90      * The position where a mark was set.
  91      */
  92     private long markpos;
  93 
  94     /**
  95      * When the underlying stream could only return
  96      * a non-integral number of frames, store
  97      * the remainder in a temporary buffer
  98      */
  99     private byte[] pushBackBuffer = null;
 100 
 101     /**
 102      * number of valid bytes in the pushBackBuffer
 103      */
 104     private int pushBackLen = 0;
 105 
 106     /**
 107      * MarkBuffer at mark position
 108      */
 109     private byte[] markPushBackBuffer = null;
 110 
 111     /**
 112      * number of valid bytes in the markPushBackBuffer
 113      */
 114     private int markPushBackLen = 0;
 115 
 116 
 117     /**
 118      * Constructs an audio input stream that has the requested format and length in sample frames,
 119      * using audio data from the specified input stream.
 120      * @param stream the stream on which this <code>AudioInputStream</code>
 121      * object is based
 122      * @param format the format of this stream's audio data
 123      * @param length the length in sample frames of the data in this stream
 124      */
 125     public AudioInputStream(InputStream stream, AudioFormat format, long length) {
 126 
 127         super();
 128 
 129         this.format = format;
 130         this.frameLength = length;
 131         this.frameSize = format.getFrameSize();
 132 
 133         // any frameSize that is not well-defined will
 134         // cause that this stream will be read in bytes
 135         if( this.frameSize == AudioSystem.NOT_SPECIFIED || frameSize <= 0) {
 136             this.frameSize = 1;
 137         }
 138 
 139         this.stream = stream;
 140         framePos = 0;
 141         markpos = 0;
 142     }
 143 
 144 
 145     /**
 146      * Constructs an audio input stream that reads its data from the target
 147      * data line indicated.  The format of the stream is the same as that of
 148      * the target data line, and the length is AudioSystem#NOT_SPECIFIED.
 149      * @param line the target data line from which this stream obtains its data.
 150      * @see AudioSystem#NOT_SPECIFIED
 151      */
 152     public AudioInputStream(TargetDataLine line) {
 153 
 154         TargetDataLineInputStream tstream = new TargetDataLineInputStream(line);
 155         format = line.getFormat();
 156         frameLength = AudioSystem.NOT_SPECIFIED;
 157         frameSize = format.getFrameSize();
 158 
 159         if( frameSize == AudioSystem.NOT_SPECIFIED || frameSize <= 0) {
 160             frameSize = 1;
 161         }
 162         this.stream = tstream;
 163         framePos = 0;
 164         markpos = 0;
 165     }
 166 
 167 
 168     /**
 169      * Obtains the audio format of the sound data in this audio input stream.
 170      * @return an audio format object describing this stream's format
 171      */
 172     public AudioFormat getFormat() {
 173         return format;
 174     }
 175 
 176 
 177     /**
 178      * Obtains the length of the stream, expressed in sample frames rather than bytes.
 179      * @return the length in sample frames
 180      */
 181     public long getFrameLength() {
 182         return frameLength;
 183     }
 184 
 185 
 186     /**
 187      * Reads the next byte of data from the audio input stream.  The audio input
 188      * stream's frame size must be one byte, or an <code>IOException</code>
 189      * will be thrown.
 190      *
 191      * @return the next byte of data, or -1 if the end of the stream is reached
 192      * @throws IOException if an input or output error occurs
 193      * @see #read(byte[], int, int)
 194      * @see #read(byte[])
 195      * @see #available
 196      */
 197     public int read() throws IOException {
 198         if( frameSize != 1 ) {
 199             throw new IOException("cannot read a single byte if frame size > 1");
 200         }
 201 
 202         byte[] data = new byte[1];
 203         int temp = read(data);
 204         if (temp <= 0) {
 205             // we have a weird situation if read(byte[]) returns 0!
 206             return -1;
 207         }
 208         return data[0] & 0xFF;
 209     }
 210 
 211 
 212     /**
 213      * Reads some number of bytes from the audio input stream and stores them into
 214      * the buffer array <code>b</code>. The number of bytes actually read is
 215      * returned as an integer. This method blocks until input data is
 216      * available, the end of the stream is detected, or an exception is thrown.
 217      * <p>This method will always read an integral number of frames.
 218      * If the length of the array is not an integral number
 219      * of frames, a maximum of <code>b.length - (b.length % frameSize)
 220      * </code> bytes will be read.
 221      *
 222      * @param b the buffer into which the data is read
 223      * @return the total number of bytes read into the buffer, or -1 if there
 224      * is no more data because the end of the stream has been reached
 225      * @throws IOException if an input or output error occurs
 226      * @see #read(byte[], int, int)
 227      * @see #read()
 228      * @see #available
 229      */
 230     public int read(byte[] b) throws IOException {
 231         return read(b,0,b.length);
 232     }
 233 
 234 
 235     /**
 236      * Reads up to a specified maximum number of bytes of data from the audio
 237      * stream, putting them into the given byte array.
 238      * <p>This method will always read an integral number of frames.
 239      * If <code>len</code> does not specify an integral number
 240      * of frames, a maximum of <code>len - (len % frameSize)
 241      * </code> bytes will be read.
 242      *
 243      * @param b the buffer into which the data is read
 244      * @param off the offset, from the beginning of array <code>b</code>, at which
 245      * the data will be written
 246      * @param len the maximum number of bytes to read
 247      * @return the total number of bytes read into the buffer, or -1 if there
 248      * is no more data because the end of the stream has been reached
 249      * @throws IOException if an input or output error occurs
 250      * @see #read(byte[])
 251      * @see #read()
 252      * @see #skip
 253      * @see #available
 254      */
 255     public int read(byte[] b, int off, int len) throws IOException {
 256 
 257         // make sure we don't read fractions of a frame.
 258         if( (len%frameSize) != 0 ) {
 259             len -= (len%frameSize);
 260             if (len == 0) {
 261                 return 0;
 262             }
 263         }
 264 
 265         if( frameLength != AudioSystem.NOT_SPECIFIED ) {
 266             if( framePos >= frameLength ) {
 267                 return -1;
 268             } else {
 269 
 270                 // don't try to read beyond our own set length in frames
 271                 if( (len/frameSize) > (frameLength-framePos) ) {
 272                     len = (int) (frameLength-framePos) * frameSize;
 273                 }
 274             }
 275         }
 276 
 277         int bytesRead = 0;
 278         int thisOff = off;
 279 
 280         // if we've bytes left from last call to read(),
 281         // use them first
 282         if (pushBackLen > 0 && len >= pushBackLen) {
 283             System.arraycopy(pushBackBuffer, 0,
 284                              b, off, pushBackLen);
 285             thisOff += pushBackLen;
 286             len -= pushBackLen;
 287             bytesRead += pushBackLen;
 288             pushBackLen = 0;
 289         }
 290 
 291         int thisBytesRead = stream.read(b, thisOff, len);
 292         if (thisBytesRead == -1) {
 293             return -1;
 294         }
 295         if (thisBytesRead > 0) {
 296             bytesRead += thisBytesRead;
 297         }
 298         if (bytesRead > 0) {
 299             pushBackLen = bytesRead % frameSize;
 300             if (pushBackLen > 0) {
 301                 // copy everything we got from the beginning of the frame
 302                 // to our pushback buffer
 303                 if (pushBackBuffer == null) {
 304                     pushBackBuffer = new byte[frameSize];
 305                 }
 306                 System.arraycopy(b, off + bytesRead - pushBackLen,
 307                                  pushBackBuffer, 0, pushBackLen);
 308                 bytesRead -= pushBackLen;
 309             }
 310             // make sure to update our framePos
 311             framePos += bytesRead/frameSize;
 312         }
 313         return bytesRead;
 314     }
 315 
 316 
 317     /**
 318      * Skips over and discards a specified number of bytes from this
 319      * audio input stream.
 320      * @param n the requested number of bytes to be skipped
 321      * @return the actual number of bytes skipped
 322      * @throws IOException if an input or output error occurs
 323      * @see #read
 324      * @see #available
 325      */
 326     public long skip(long n) throws IOException {
 327 
 328         // make sure not to skip fractional frames
 329         if( (n%frameSize) != 0 ) {
 330             n -= (n%frameSize);
 331         }
 332 
 333         if( frameLength != AudioSystem.NOT_SPECIFIED ) {
 334             // don't skip more than our set length in frames.
 335             if( (n/frameSize) > (frameLength-framePos) ) {
 336                 n = (frameLength-framePos) * frameSize;
 337             }
 338         }
 339         long temp = stream.skip(n);
 340 
 341         // if no error, update our position.
 342         if( temp%frameSize != 0 ) {
 343 
 344             // Throw an IOException if we've skipped a fractional number of frames
 345             throw new IOException("Could not skip an integer number of frames.");
 346         }
 347         if( temp >= 0 ) {
 348             framePos += temp/frameSize;
 349         }
 350         return temp;
 351 
 352     }
 353 
 354 
 355     /**
 356      * Returns the maximum number of bytes that can be read (or skipped over) from this
 357      * audio input stream without blocking.  This limit applies only to the next invocation of
 358      * a <code>read</code> or <code>skip</code> method for this audio input stream; the limit
 359      * can vary each time these methods are invoked.
 360      * Depending on the underlying stream,an IOException may be thrown if this
 361      * stream is closed.
 362      * @return the number of bytes that can be read from this audio input stream without blocking
 363      * @throws IOException if an input or output error occurs
 364      * @see #read(byte[], int, int)
 365      * @see #read(byte[])
 366      * @see #read()
 367      * @see #skip
 368      */
 369     public int available() throws IOException {
 370 
 371         int temp = stream.available();
 372 
 373         // don't return greater than our set length in frames
 374         if( (frameLength != AudioSystem.NOT_SPECIFIED) && ( (temp/frameSize) > (frameLength-framePos)) ) {
 375             return (int) (frameLength-framePos) * frameSize;
 376         } else {
 377             return temp;
 378         }
 379     }
 380 
 381 
 382     /**
 383      * Closes this audio input stream and releases any system resources associated
 384      * with the stream.
 385      * @throws IOException if an input or output error occurs
 386      */
 387     public void close() throws IOException {
 388         stream.close();
 389     }
 390 
 391 
 392     /**
 393      * Marks the current position in this audio input stream.
 394      * @param readlimit the maximum number of bytes that can be read before
 395      * the mark position becomes invalid.
 396      * @see #reset
 397      * @see #markSupported
 398      */
 399 
 400     public void mark(int readlimit) {
 401 
 402         stream.mark(readlimit);
 403         if (markSupported()) {
 404             markpos = framePos;
 405             // remember the pushback buffer
 406             markPushBackLen = pushBackLen;
 407             if (markPushBackLen > 0) {
 408                 if (markPushBackBuffer == null) {
 409                     markPushBackBuffer = new byte[frameSize];
 410                 }
 411                 System.arraycopy(pushBackBuffer, 0, markPushBackBuffer, 0, markPushBackLen);
 412             }
 413         }
 414     }
 415 
 416 
 417     /**
 418      * Repositions this audio input stream to the position it had at the time its
 419      * <code>mark</code> method was last invoked.
 420      * @throws IOException if an input or output error occurs.
 421      * @see #mark
 422      * @see #markSupported
 423      */
 424     public void reset() throws IOException {
 425 
 426         stream.reset();
 427         framePos = markpos;
 428         // re-create the pushback buffer
 429         pushBackLen = markPushBackLen;
 430         if (pushBackLen > 0) {
 431             if (pushBackBuffer == null) {
 432                 pushBackBuffer = new byte[frameSize - 1];
 433             }
 434             System.arraycopy(markPushBackBuffer, 0, pushBackBuffer, 0, pushBackLen);
 435         }
 436     }
 437 
 438 
 439     /**
 440      * Tests whether this audio input stream supports the <code>mark</code> and
 441      * <code>reset</code> methods.
 442      * @return <code>true</code> if this stream supports the <code>mark</code>
 443      * and <code>reset</code> methods; <code>false</code> otherwise
 444      * @see #mark
 445      * @see #reset
 446      */
 447     public boolean markSupported() {
 448 
 449         return stream.markSupported();
 450     }
 451 
 452 
 453     /**
 454      * Private inner class that makes a TargetDataLine look like an InputStream.
 455      */
 456     private class TargetDataLineInputStream extends InputStream {
 457 
 458         /**
 459          * The TargetDataLine on which this TargetDataLineInputStream is based.
 460          */
 461         TargetDataLine line;
 462 
 463 
 464         TargetDataLineInputStream(TargetDataLine line) {
 465             super();
 466             this.line = line;
 467         }
 468 
 469 
 470         public int available() throws IOException {
 471             return line.available();
 472         }
 473 
 474         //$$fb 2001-07-16: added this method to correctly close the underlying TargetDataLine.
 475         // fixes bug 4479984
 476         public void close() throws IOException {
 477             // the line needs to be flushed and stopped to avoid a dead lock...
 478             // Probably related to bugs 4417527, 4334868, 4383457
 479             if (line.isActive()) {
 480                 line.flush();
 481                 line.stop();
 482             }
 483             line.close();
 484         }
 485 
 486         public int read() throws IOException {
 487 
 488             byte[] b = new byte[1];
 489 
 490             int value = read(b, 0, 1);
 491 
 492             if (value == -1) {
 493                 return -1;
 494             }
 495 
 496             value = (int)b[0];
 497 
 498             if (line.getFormat().getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED)) {
 499                 value += 128;
 500             }
 501 
 502             return value;
 503         }
 504 
 505 
 506         public int read(byte[] b, int off, int len) throws IOException {
 507             try {
 508                 return line.read(b, off, len);
 509             } catch (IllegalArgumentException e) {
 510                 throw new IOException(e.getMessage());
 511             }
 512         }
 513     }
 514 }