1 /*
   2  * Copyright (c) 1999, 2014, 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 com.sun.media.sound;
  27 
  28 import java.io.IOException;
  29 
  30 import java.util.Vector;
  31 
  32 import javax.sound.sampled.AudioFormat;
  33 import javax.sound.sampled.AudioSystem;
  34 import javax.sound.sampled.AudioInputStream;
  35 
  36 
  37 /**
  38  * U-law encodes linear data, and decodes u-law data to linear data.
  39  *
  40  * @author Kara Kytle
  41  */
  42 public final class UlawCodec extends SunCodec {
  43 
  44     /* Tables used for U-law decoding */
  45 
  46     private final static byte[] ULAW_TABH = new byte[256];
  47     private final static byte[] ULAW_TABL = new byte[256];
  48 
  49     private static final AudioFormat.Encoding[] ulawEncodings = {AudioFormat.Encoding.ULAW,
  50                                                                  AudioFormat.Encoding.PCM_SIGNED};
  51 
  52     private static final short seg_end [] = {0xFF, 0x1FF, 0x3FF,
  53                                              0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF};
  54 
  55     /**
  56      * Initializes the decode tables
  57      */
  58     static {
  59         for (int i=0;i<256;i++) {
  60             int ulaw = ~i;
  61             int t;
  62 
  63             ulaw &= 0xFF;
  64             t = ((ulaw & 0xf)<<3) + 132;
  65             t <<= ((ulaw & 0x70) >> 4);
  66             t = ( (ulaw&0x80) != 0 ) ? (132-t) : (t-132);
  67 
  68             ULAW_TABL[i] = (byte) (t&0xff);
  69             ULAW_TABH[i] = (byte) ((t>>8) & 0xff);
  70         }
  71     }
  72 
  73 
  74     /**
  75      * Constructs a new ULAW codec object.
  76      */
  77     public UlawCodec() {
  78         super(ulawEncodings, ulawEncodings);
  79     }
  80 
  81     /**
  82      */
  83     public AudioFormat.Encoding[] getTargetEncodings(AudioFormat sourceFormat){
  84         if( AudioFormat.Encoding.PCM_SIGNED.equals(sourceFormat.getEncoding()) ) {
  85             if( sourceFormat.getSampleSizeInBits() == 16 ) {
  86                 AudioFormat.Encoding enc[] = new AudioFormat.Encoding[1];
  87                 enc[0] = AudioFormat.Encoding.ULAW;
  88                 return enc;
  89             } else {
  90                 return new AudioFormat.Encoding[0];
  91             }
  92         } else if (AudioFormat.Encoding.ULAW.equals(sourceFormat.getEncoding())) {
  93             if (sourceFormat.getSampleSizeInBits() == 8) {
  94                 AudioFormat.Encoding enc[] = new AudioFormat.Encoding[1];
  95                 enc[0] = AudioFormat.Encoding.PCM_SIGNED;
  96                 return enc;
  97             } else {
  98                 return new AudioFormat.Encoding[0];
  99             }
 100         } else {
 101             return new AudioFormat.Encoding[0];
 102         }
 103     }
 104 
 105 
 106     /**
 107      */
 108     public AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat){
 109         if( (AudioFormat.Encoding.PCM_SIGNED.equals(targetEncoding)
 110              && AudioFormat.Encoding.ULAW.equals(sourceFormat.getEncoding()))
 111             ||
 112             (AudioFormat.Encoding.ULAW.equals(targetEncoding)
 113              && AudioFormat.Encoding.PCM_SIGNED.equals(sourceFormat.getEncoding()))) {
 114                 return getOutputFormats(sourceFormat);
 115             } else {
 116                 return new AudioFormat[0];
 117             }
 118     }
 119 
 120     /**
 121      */
 122     public AudioInputStream getAudioInputStream(AudioFormat.Encoding targetEncoding, AudioInputStream sourceStream){
 123         AudioFormat sourceFormat = sourceStream.getFormat();
 124         AudioFormat.Encoding sourceEncoding = sourceFormat.getEncoding();
 125 
 126         if (sourceEncoding.equals(targetEncoding)) {
 127             return sourceStream;
 128         } else {
 129             AudioFormat targetFormat = null;
 130             if (!isConversionSupported(targetEncoding,sourceStream.getFormat())) {
 131                 throw new IllegalArgumentException("Unsupported conversion: " + sourceStream.getFormat().toString() + " to " + targetEncoding.toString());
 132             }
 133             if (AudioFormat.Encoding.ULAW.equals(sourceEncoding) &&
 134                 AudioFormat.Encoding.PCM_SIGNED.equals(targetEncoding) ) {
 135                 targetFormat = new AudioFormat( targetEncoding,
 136                                                 sourceFormat.getSampleRate(),
 137                                                 16,
 138                                                 sourceFormat.getChannels(),
 139                                                 2*sourceFormat.getChannels(),
 140                                                 sourceFormat.getSampleRate(),
 141                                                 sourceFormat.isBigEndian());
 142             } else if (AudioFormat.Encoding.PCM_SIGNED.equals(sourceEncoding) &&
 143                        AudioFormat.Encoding.ULAW.equals(targetEncoding)) {
 144                 targetFormat = new AudioFormat( targetEncoding,
 145                                                 sourceFormat.getSampleRate(),
 146                                                 8,
 147                                                 sourceFormat.getChannels(),
 148                                                 sourceFormat.getChannels(),
 149                                                 sourceFormat.getSampleRate(),
 150                                                 false);
 151             } else {
 152                 throw new IllegalArgumentException("Unsupported conversion: " + sourceStream.getFormat().toString() + " to " + targetEncoding.toString());
 153             }
 154 
 155             return getAudioInputStream( targetFormat, sourceStream );
 156         }
 157     }
 158 
 159     /**
 160      * use old code...
 161      */
 162     public AudioInputStream getAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream){
 163         return getConvertedStream(targetFormat, sourceStream);
 164     }
 165 
 166 
 167     // OLD CODE
 168 
 169     /**
 170      * Opens the codec with the specified parameters.
 171      * @param stream stream from which data to be processed should be read
 172      * @param outputFormat desired data format of the stream after processing
 173      * @return stream from which processed data may be read
 174      * @throws IllegalArgumentException if the format combination supplied is
 175      * not supported.
 176      */
 177     /*  public AudioInputStream getConvertedStream(AudioFormat outputFormat, AudioInputStream stream) { */
 178     private AudioInputStream getConvertedStream(AudioFormat outputFormat, AudioInputStream stream) {
 179         AudioInputStream cs = null;
 180 
 181         AudioFormat inputFormat = stream.getFormat();
 182 
 183         if( inputFormat.matches(outputFormat) ) {
 184             cs = stream;
 185         } else {
 186             cs = (AudioInputStream) (new UlawCodecStream(stream, outputFormat));
 187         }
 188         return cs;
 189     }
 190 
 191     /**
 192      * Obtains the set of output formats supported by the codec
 193      * given a particular input format.
 194      * If no output formats are supported for this input format,
 195      * returns an array of length 0.
 196      * @return array of supported output formats.
 197      */
 198     /*  public AudioFormat[] getOutputFormats(AudioFormat inputFormat) { */
 199     private AudioFormat[] getOutputFormats(AudioFormat inputFormat) {
 200 
 201         Vector formats = new Vector();
 202         AudioFormat format;
 203 
 204         if ((inputFormat.getSampleSizeInBits() == 16)
 205             && AudioFormat.Encoding.PCM_SIGNED.equals(inputFormat.getEncoding())) {
 206             format = new AudioFormat(AudioFormat.Encoding.ULAW,
 207                                      inputFormat.getSampleRate(),
 208                                      8,
 209                                      inputFormat.getChannels(),
 210                                      inputFormat.getChannels(),
 211                                      inputFormat.getSampleRate(),
 212                                      false );
 213             formats.addElement(format);
 214         }
 215 
 216         if (AudioFormat.Encoding.ULAW.equals(inputFormat.getEncoding())) {
 217             format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
 218                                      inputFormat.getSampleRate(),
 219                                      16,
 220                                      inputFormat.getChannels(),
 221                                      inputFormat.getChannels()*2,
 222                                      inputFormat.getSampleRate(),
 223                                      false );
 224             formats.addElement(format);
 225 
 226             format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
 227                                      inputFormat.getSampleRate(),
 228                                      16,
 229                                      inputFormat.getChannels(),
 230                                      inputFormat.getChannels()*2,
 231                                      inputFormat.getSampleRate(),
 232                                      true );
 233             formats.addElement(format);
 234         }
 235 
 236         AudioFormat[] formatArray = new AudioFormat[formats.size()];
 237         for (int i = 0; i < formatArray.length; i++) {
 238             formatArray[i] = (AudioFormat)(formats.elementAt(i));
 239         }
 240         return formatArray;
 241     }
 242 
 243 
 244     class UlawCodecStream extends AudioInputStream {
 245 
 246         private static final int tempBufferSize = 64;
 247         private byte tempBuffer [] = null;
 248 
 249         /**
 250          * True to encode to u-law, false to decode to linear
 251          */
 252         boolean encode = false;
 253 
 254         AudioFormat encodeFormat;
 255         AudioFormat decodeFormat;
 256 
 257         byte tabByte1[] = null;
 258         byte tabByte2[] = null;
 259         int highByte = 0;
 260         int lowByte  = 1;
 261 
 262         UlawCodecStream(AudioInputStream stream, AudioFormat outputFormat) {
 263             super(stream, outputFormat, AudioSystem.NOT_SPECIFIED);
 264 
 265             AudioFormat inputFormat = stream.getFormat();
 266 
 267             // throw an IllegalArgumentException if not ok
 268             if (!(isConversionSupported(outputFormat, inputFormat))) {
 269                 throw new IllegalArgumentException("Unsupported conversion: " + inputFormat.toString() + " to " + outputFormat.toString());
 270             }
 271 
 272             //$$fb 2002-07-18: fix for 4714846: JavaSound ULAW (8-bit) encoder erroneously depends on endian-ness
 273             boolean PCMIsBigEndian;
 274 
 275             // determine whether we are encoding or decoding
 276             if (AudioFormat.Encoding.ULAW.equals(inputFormat.getEncoding())) {
 277                 encode = false;
 278                 encodeFormat = inputFormat;
 279                 decodeFormat = outputFormat;
 280                 PCMIsBigEndian = outputFormat.isBigEndian();
 281             } else {
 282                 encode = true;
 283                 encodeFormat = outputFormat;
 284                 decodeFormat = inputFormat;
 285                 PCMIsBigEndian = inputFormat.isBigEndian();
 286                 tempBuffer = new byte[tempBufferSize];
 287             }
 288 
 289             // setup tables according to byte order
 290             if (PCMIsBigEndian) {
 291                 tabByte1 = ULAW_TABH;
 292                 tabByte2 = ULAW_TABL;
 293                 highByte = 0;
 294                 lowByte  = 1;
 295             } else {
 296                 tabByte1 = ULAW_TABL;
 297                 tabByte2 = ULAW_TABH;
 298                 highByte = 1;
 299                 lowByte  = 0;
 300             }
 301 
 302             // set the AudioInputStream length in frames if we know it
 303             if (stream instanceof AudioInputStream) {
 304                 frameLength = stream.getFrameLength();
 305             }
 306             // set framePos to zero
 307             framePos = 0;
 308             frameSize = inputFormat.getFrameSize();
 309             if (frameSize == AudioSystem.NOT_SPECIFIED) {
 310                 frameSize = 1;
 311             }
 312         }
 313 
 314 
 315         /*
 316          * $$jb 2/23/99
 317          * Used to determine segment number in uLaw encoding
 318          */
 319         private short search(short val, short table[], short size) {
 320             for(short i = 0; i < size; i++) {
 321                 if (val <= table[i]) { return i; }
 322             }
 323             return size;
 324         }
 325 
 326         /**
 327          * Note that this won't actually read anything; must read in
 328          * two-byte units.
 329          */
 330         public int read() throws IOException {
 331             byte[] b = new byte[1];
 332             if (read(b, 0, b.length) == 1) {
 333                 return b[1] & 0xFF;
 334             }
 335             return -1;
 336         }
 337 
 338         public int read(byte[] b) throws IOException {
 339             return read(b, 0, b.length);
 340         }
 341 
 342         public int read(byte[] b, int off, int len) throws IOException {
 343             // don't read fractional frames
 344             if( len%frameSize != 0 ) {
 345                 len -= (len%frameSize);
 346             }
 347             if (encode) {
 348                 short BIAS = 0x84;
 349                 short mask;
 350                 short seg;
 351                 int i;
 352 
 353                 short sample;
 354                 byte enc;
 355 
 356                 int readCount = 0;
 357                 int currentPos = off;
 358                 int readLeft = len*2;
 359                 int readLen = ( (readLeft>tempBufferSize) ? tempBufferSize : readLeft );
 360 
 361                 while ((readCount = super.read(tempBuffer,0,readLen))>0) {
 362                     for(i = 0; i < readCount; i+=2) {
 363                         /* Get the sample from the tempBuffer */
 364                         sample = (short)(( (tempBuffer[i + highByte]) << 8) & 0xFF00);
 365                         sample |= (short)( (short) (tempBuffer[i + lowByte]) & 0xFF);
 366 
 367                         /* Get the sign and the magnitude of the value. */
 368                         if(sample < 0) {
 369                             sample = (short) (BIAS - sample);
 370                             mask = 0x7F;
 371                         } else {
 372                             sample += BIAS;
 373                             mask = 0xFF;
 374                         }
 375                         /* Convert the scaled magnitude to segment number. */
 376                         seg = search(sample, seg_end, (short) 8);
 377                         /*
 378                          * Combine the sign, segment, quantization bits;
 379                          * and complement the code word.
 380                          */
 381                         if (seg >= 8) {  /* out of range, return maximum value. */
 382                             enc = (byte) (0x7F ^ mask);
 383                         } else {
 384                             enc = (byte) ((seg << 4) | ((sample >> (seg+3)) & 0xF));
 385                             enc ^= mask;
 386                         }
 387                         /* Now put the encoded sample where it belongs */
 388                         b[currentPos] = enc;
 389                         currentPos++;
 390                     }
 391                     /* And update pointers and counters for next iteration */
 392                     readLeft -= readCount;
 393                     readLen = ( (readLeft>tempBufferSize) ? tempBufferSize : readLeft );
 394                 }
 395                 if( currentPos==off && readCount<0 ) {  // EOF or error on read
 396                     return readCount;
 397                 }
 398                 return (currentPos - off);  /* Number of bytes written to new buffer */
 399             } else {
 400                 int i;
 401                 int readLen = len/2;
 402                 int readOffset = off + len/2;
 403                 int readCount = super.read(b, readOffset, readLen);
 404 
 405                 if(readCount<0) {               // EOF or error
 406                     return readCount;
 407                 }
 408                 for (i = off; i < (off + (readCount*2)); i+=2) {
 409                     b[i]        = tabByte1[b[readOffset] & 0xFF];
 410                     b[i+1]      = tabByte2[b[readOffset] & 0xFF];
 411                     readOffset++;
 412                 }
 413                 return (i - off);
 414             }
 415         }
 416     } // end class UlawCodecStream
 417 
 418 } // end class ULAW