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