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