1 /*
   2  * Copyright (c) 1999, 2016, 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.BufferedOutputStream;
  29 import java.io.ByteArrayInputStream;
  30 import java.io.ByteArrayOutputStream;
  31 import java.io.DataOutputStream;
  32 import java.io.File;
  33 import java.io.FileOutputStream;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.OutputStream;
  37 import java.io.RandomAccessFile;
  38 import java.io.SequenceInputStream;
  39 import java.util.Objects;
  40 
  41 import javax.sound.sampled.AudioFileFormat;
  42 import javax.sound.sampled.AudioFormat;
  43 import javax.sound.sampled.AudioInputStream;
  44 import javax.sound.sampled.AudioSystem;
  45 
  46 //$$fb this class is buggy. Should be replaced in future.
  47 
  48 /**
  49  * WAVE file writer.
  50  *
  51  * @author Jan Borgersen
  52  */
  53 public final class WaveFileWriter extends SunFileWriter {
  54 
  55     /**
  56      * Constructs a new WaveFileWriter object.
  57      */
  58     public WaveFileWriter() {
  59         super(new AudioFileFormat.Type[]{AudioFileFormat.Type.WAVE});
  60     }
  61 
  62     @Override
  63     public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) {
  64 
  65         AudioFileFormat.Type[] filetypes = new AudioFileFormat.Type[types.length];
  66         System.arraycopy(types, 0, filetypes, 0, types.length);
  67 
  68         // make sure we can write this stream
  69         AudioFormat format = stream.getFormat();
  70         AudioFormat.Encoding encoding = format.getEncoding();
  71 
  72         if( AudioFormat.Encoding.ALAW.equals(encoding) ||
  73             AudioFormat.Encoding.ULAW.equals(encoding) ||
  74             AudioFormat.Encoding.PCM_SIGNED.equals(encoding) ||
  75             AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding) ) {
  76 
  77             return filetypes;
  78         }
  79 
  80         return new AudioFileFormat.Type[0];
  81     }
  82 
  83     @Override
  84     public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException {
  85         Objects.requireNonNull(stream);
  86         Objects.requireNonNull(fileType);
  87         Objects.requireNonNull(out);
  88 
  89         //$$fb the following check must come first ! Otherwise
  90         // the next frame length check may throw an IOException and
  91         // interrupt iterating File Writers. (see bug 4351296)
  92 
  93         // throws IllegalArgumentException if not supported
  94         WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);
  95 
  96         //$$fb when we got this far, we are committed to write this file
  97 
  98         // we must know the total data length to calculate the file length
  99         if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) {
 100             throw new IOException("stream length not specified");
 101         }
 102 
 103         return writeWaveFile(stream, waveFileFormat, out);
 104     }
 105 
 106     @Override
 107     public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
 108         Objects.requireNonNull(stream);
 109         Objects.requireNonNull(fileType);
 110         Objects.requireNonNull(out);
 111 
 112         // throws IllegalArgumentException if not supported
 113         WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);
 114 
 115         // first write the file without worrying about length fields
 116         FileOutputStream fos = new FileOutputStream( out );     // throws IOException
 117         BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
 118         int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
 119         bos.close();
 120 
 121         // now, if length fields were not specified, calculate them,
 122         // open as a random access file, write the appropriate fields,
 123         // close again....
 124         if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
 125 
 126             int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
 127             int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;
 128 
 129             RandomAccessFile raf=new RandomAccessFile(out, "rw");
 130             // skip RIFF magic
 131             raf.skipBytes(4);
 132             raf.writeInt(big2little( riffLength ));
 133             // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
 134             raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
 135             raf.writeInt(big2little( dataLength ));
 136             // that's all
 137             raf.close();
 138         }
 139 
 140         return bytesWritten;
 141     }
 142 
 143     //--------------------------------------------------------------------
 144 
 145     /**
 146      * Returns the AudioFileFormat describing the file that will be written from this AudioInputStream.
 147      * Throws IllegalArgumentException if not supported.
 148      */
 149     private AudioFileFormat getAudioFileFormat(AudioFileFormat.Type type, AudioInputStream stream) {
 150         if (!isFileTypeSupported(type, stream)) {
 151             throw new IllegalArgumentException("File type " + type + " not supported.");
 152         }
 153         AudioFormat format = null;
 154         WaveFileFormat fileFormat = null;
 155         AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
 156 
 157         AudioFormat streamFormat = stream.getFormat();
 158         AudioFormat.Encoding streamEncoding = streamFormat.getEncoding();
 159 
 160         float sampleRate;
 161         int sampleSizeInBits;
 162         int channels;
 163         int frameSize;
 164         float frameRate;
 165         int fileSize;
 166 
 167         int waveType = WaveFileFormat.WAVE_FORMAT_PCM;
 168 
 169         if( AudioFormat.Encoding.ALAW.equals(streamEncoding) ||
 170             AudioFormat.Encoding.ULAW.equals(streamEncoding) ) {
 171 
 172             encoding = streamEncoding;
 173             sampleSizeInBits = streamFormat.getSampleSizeInBits();
 174             if (streamEncoding.equals(AudioFormat.Encoding.ALAW)) {
 175                 waveType = WaveFileFormat.WAVE_FORMAT_ALAW;
 176             } else {
 177                 waveType = WaveFileFormat.WAVE_FORMAT_MULAW;
 178             }
 179         } else if ( streamFormat.getSampleSizeInBits()==8 ) {
 180             encoding = AudioFormat.Encoding.PCM_UNSIGNED;
 181             sampleSizeInBits=8;
 182         } else {
 183             encoding = AudioFormat.Encoding.PCM_SIGNED;
 184             sampleSizeInBits=streamFormat.getSampleSizeInBits();
 185         }
 186 
 187 
 188         format = new AudioFormat( encoding,
 189                                   streamFormat.getSampleRate(),
 190                                   sampleSizeInBits,
 191                                   streamFormat.getChannels(),
 192                                   streamFormat.getFrameSize(),
 193                                   streamFormat.getFrameRate(),
 194                                   false);       // WAVE is little endian
 195 
 196         if( stream.getFrameLength()!=AudioSystem.NOT_SPECIFIED ) {
 197             fileSize = (int)stream.getFrameLength()*streamFormat.getFrameSize()
 198                 + WaveFileFormat.getHeaderSize(waveType);
 199         } else {
 200             fileSize = AudioSystem.NOT_SPECIFIED;
 201         }
 202 
 203         fileFormat = new WaveFileFormat( AudioFileFormat.Type.WAVE,
 204                                          fileSize,
 205                                          format,
 206                                          (int)stream.getFrameLength() );
 207 
 208         return fileFormat;
 209     }
 210 
 211 
 212     private int writeWaveFile(InputStream in, WaveFileFormat waveFileFormat, OutputStream out) throws IOException {
 213 
 214         int bytesRead = 0;
 215         int bytesWritten = 0;
 216         InputStream fileStream = getFileStream(waveFileFormat, in);
 217         byte buffer[] = new byte[bisBufferSize];
 218         int maxLength = waveFileFormat.getByteLength();
 219 
 220         while( (bytesRead = fileStream.read( buffer )) >= 0 ) {
 221 
 222             if (maxLength>0) {
 223                 if( bytesRead < maxLength ) {
 224                     out.write( buffer, 0, bytesRead );
 225                     bytesWritten += bytesRead;
 226                     maxLength -= bytesRead;
 227                 } else {
 228                     out.write( buffer, 0, maxLength );
 229                     bytesWritten += maxLength;
 230                     maxLength = 0;
 231                     break;
 232                 }
 233             } else {
 234                 out.write( buffer, 0, bytesRead );
 235                 bytesWritten += bytesRead;
 236             }
 237         }
 238 
 239         return bytesWritten;
 240     }
 241 
 242     private InputStream getFileStream(WaveFileFormat waveFileFormat, InputStream audioStream) throws IOException {
 243         // private method ... assumes audioFileFormat is a supported file type
 244 
 245         // WAVE header fields
 246         AudioFormat audioFormat = waveFileFormat.getFormat();
 247         int headerLength       = waveFileFormat.getHeaderSize();
 248         int riffMagic          = WaveFileFormat.RIFF_MAGIC;
 249         int waveMagic          = WaveFileFormat.WAVE_MAGIC;
 250         int fmtMagic           = WaveFileFormat.FMT_MAGIC;
 251         int fmtLength          = WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType());
 252         short wav_type         = (short) waveFileFormat.getWaveType();
 253         short channels         = (short) audioFormat.getChannels();
 254         short sampleSizeInBits = (short) audioFormat.getSampleSizeInBits();
 255         int sampleRate         = (int) audioFormat.getSampleRate();
 256         int frameSizeInBytes   = audioFormat.getFrameSize();
 257         int frameRate              = (int) audioFormat.getFrameRate();
 258         int avgBytesPerSec     = channels * sampleSizeInBits * sampleRate / 8;
 259         short blockAlign       = (short) ((sampleSizeInBits / 8) * channels);
 260         int dataMagic              = WaveFileFormat.DATA_MAGIC;
 261         int dataLength             = waveFileFormat.getFrameLength() * frameSizeInBytes;
 262         int length                         = waveFileFormat.getByteLength();
 263         int riffLength = dataLength + headerLength - 8;
 264 
 265         byte header[] = null;
 266         ByteArrayInputStream headerStream = null;
 267         ByteArrayOutputStream baos = null;
 268         DataOutputStream dos = null;
 269         SequenceInputStream waveStream = null;
 270 
 271         AudioFormat audioStreamFormat = null;
 272         AudioFormat.Encoding encoding = null;
 273         InputStream codedAudioStream = audioStream;
 274 
 275         // if audioStream is an AudioInputStream and we need to convert, do it here...
 276         if(audioStream instanceof AudioInputStream) {
 277             audioStreamFormat = ((AudioInputStream)audioStream).getFormat();
 278 
 279             encoding = audioStreamFormat.getEncoding();
 280 
 281             if(AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) {
 282                 if( sampleSizeInBits==8 ) {
 283                     wav_type = WaveFileFormat.WAVE_FORMAT_PCM;
 284                     // plug in the transcoder to convert from PCM_SIGNED to PCM_UNSIGNED
 285                     codedAudioStream = AudioSystem.getAudioInputStream( new AudioFormat(
 286                                                                                         AudioFormat.Encoding.PCM_UNSIGNED,
 287                                                                                         audioStreamFormat.getSampleRate(),
 288                                                                                         audioStreamFormat.getSampleSizeInBits(),
 289                                                                                         audioStreamFormat.getChannels(),
 290                                                                                         audioStreamFormat.getFrameSize(),
 291                                                                                         audioStreamFormat.getFrameRate(),
 292                                                                                         false),
 293                                                                         (AudioInputStream)audioStream);
 294                 }
 295             }
 296             if( (AudioFormat.Encoding.PCM_SIGNED.equals(encoding) && audioStreamFormat.isBigEndian()) ||
 297                 (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding) && !audioStreamFormat.isBigEndian()) ||
 298                 (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding) && audioStreamFormat.isBigEndian()) ) {
 299                 if( sampleSizeInBits!=8) {
 300                     wav_type = WaveFileFormat.WAVE_FORMAT_PCM;
 301                     // plug in the transcoder to convert to PCM_SIGNED_LITTLE_ENDIAN
 302                     codedAudioStream = AudioSystem.getAudioInputStream( new AudioFormat(
 303                                                                                         AudioFormat.Encoding.PCM_SIGNED,
 304                                                                                         audioStreamFormat.getSampleRate(),
 305                                                                                         audioStreamFormat.getSampleSizeInBits(),
 306                                                                                         audioStreamFormat.getChannels(),
 307                                                                                         audioStreamFormat.getFrameSize(),
 308                                                                                         audioStreamFormat.getFrameRate(),
 309                                                                                         false),
 310                                                                         (AudioInputStream)audioStream);
 311                 }
 312             }
 313         }
 314 
 315 
 316         // Now push the header into a stream, concat, and return the new SequenceInputStream
 317 
 318         baos = new ByteArrayOutputStream();
 319         dos = new DataOutputStream(baos);
 320 
 321         // we write in littleendian...
 322         dos.writeInt(riffMagic);
 323         dos.writeInt(big2little( riffLength ));
 324         dos.writeInt(waveMagic);
 325         dos.writeInt(fmtMagic);
 326         dos.writeInt(big2little(fmtLength));
 327         dos.writeShort(big2littleShort(wav_type));
 328         dos.writeShort(big2littleShort(channels));
 329         dos.writeInt(big2little(sampleRate));
 330         dos.writeInt(big2little(avgBytesPerSec));
 331         dos.writeShort(big2littleShort(blockAlign));
 332         dos.writeShort(big2littleShort(sampleSizeInBits));
 333         //$$fb 2002-04-16: Fix for 4636355: RIFF audio headers could be _more_ spec compliant
 334         if (wav_type != WaveFileFormat.WAVE_FORMAT_PCM) {
 335             // add length 0 for "codec specific data length"
 336             dos.writeShort(0);
 337         }
 338 
 339         dos.writeInt(dataMagic);
 340         dos.writeInt(big2little(dataLength));
 341 
 342         dos.close();
 343         header = baos.toByteArray();
 344         headerStream = new ByteArrayInputStream( header );
 345         waveStream = new SequenceInputStream(headerStream,
 346                             new NoCloseInputStream(codedAudioStream));
 347 
 348         return waveStream;
 349     }
 350 }