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