1 /*
   2  * Copyright (c) 1999, 2018, 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.AudioFileFormat.Type;
  43 import javax.sound.sampled.AudioFormat;
  44 import javax.sound.sampled.AudioInputStream;
  45 import javax.sound.sampled.AudioSystem;
  46 
  47 /**
  48  * AU file writer.
  49  *
  50  * @author Jan Borgersen
  51  */
  52 public final class AuFileWriter extends SunFileWriter {
  53 
  54     /**
  55      * Value for length field if length is not known.
  56      */
  57     private static final int UNKNOWN_SIZE = -1;
  58 
  59     /**
  60      * Constructs a new AuFileWriter object.
  61      */
  62     public AuFileWriter() {
  63         super(new Type[]{Type.AU});
  64     }
  65 
  66     @Override
  67     public Type[] getAudioFileTypes(AudioInputStream stream) {
  68 
  69         Type[] filetypes = new Type[types.length];
  70         System.arraycopy(types, 0, filetypes, 0, types.length);
  71 
  72         // make sure we can write this stream
  73         AudioFormat format = stream.getFormat();
  74         AudioFormat.Encoding encoding = format.getEncoding();
  75 
  76         if (AudioFormat.Encoding.ALAW.equals(encoding)
  77                 || AudioFormat.Encoding.ULAW.equals(encoding)
  78                 || AudioFormat.Encoding.PCM_SIGNED.equals(encoding)
  79                 || AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)
  80                 || AudioFormat.Encoding.PCM_FLOAT.equals(encoding)) {
  81             return filetypes;
  82         }
  83 
  84         return new Type[0];
  85     }
  86 
  87     @Override
  88     public int write(AudioInputStream stream, Type fileType, OutputStream out) throws IOException {
  89         Objects.requireNonNull(stream);
  90         Objects.requireNonNull(fileType);
  91         Objects.requireNonNull(out);
  92 
  93         // we must know the total data length to calculate the file length
  94         //$$fb 2001-07-13: fix for bug 4351296: do not throw an exception
  95         //if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) {
  96         //      throw new IOException("stream length not specified");
  97         //}
  98 
  99         // throws IllegalArgumentException if not supported
 100         AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);
 101         return writeAuFile(stream, auFileFormat, out);
 102     }
 103 
 104     @Override
 105     public int write(AudioInputStream stream, Type fileType, File out) throws IOException {
 106         Objects.requireNonNull(stream);
 107         Objects.requireNonNull(fileType);
 108         Objects.requireNonNull(out);
 109 
 110         // throws IllegalArgumentException if not supported
 111         AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);
 112 
 113         // first write the file without worrying about length fields
 114         final int bytesWritten;
 115         try (final FileOutputStream fos = new FileOutputStream(out);
 116              final BufferedOutputStream bos = new BufferedOutputStream(fos)) {
 117             bytesWritten = writeAuFile(stream, auFileFormat, bos);
 118         }
 119 
 120         // now, if length fields were not specified, calculate them,
 121         // open as a random access file, write the appropriate fields,
 122         // close again....
 123         if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
 124 
 125             // $$kk: 10.22.99: jan: please either implement this or throw an exception!
 126             // $$fb: 2001-07-13: done. Fixes Bug 4479981
 127             try (final RandomAccessFile raf = new RandomAccessFile(out, "rw")) {
 128                 if (raf.length() <= 0x7FFFFFFFl) {
 129                     // skip AU magic and data offset field
 130                     raf.skipBytes(8);
 131                     raf.writeInt(bytesWritten - AuFileFormat.AU_HEADERSIZE);
 132                     // that's all
 133                 }
 134             }
 135         }
 136 
 137         return bytesWritten;
 138     }
 139 
 140     // -------------------------------------------------------------
 141 
 142     /**
 143      * Returns the AudioFileFormat describing the file that will be written from this AudioInputStream.
 144      * Throws IllegalArgumentException if not supported.
 145      */
 146     private AudioFileFormat getAudioFileFormat(Type type, AudioInputStream stream) {
 147         if (!isFileTypeSupported(type, stream)) {
 148             throw new IllegalArgumentException("File type " + type + " not supported.");
 149         }
 150 
 151         AudioFormat streamFormat = stream.getFormat();
 152         AudioFormat.Encoding encoding = streamFormat.getEncoding();
 153 
 154         if (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) {
 155             encoding = AudioFormat.Encoding.PCM_SIGNED;
 156         }
 157 
 158         // We always write big endian au files, this is by far the standard
 159         AudioFormat format = new AudioFormat(encoding,
 160                                              streamFormat.getSampleRate(),
 161                                              streamFormat.getSampleSizeInBits(),
 162                                              streamFormat.getChannels(),
 163                                              streamFormat.getFrameSize(),
 164                                              streamFormat.getFrameRate(), true);
 165 
 166         int fileSize;
 167         if (stream.getFrameLength() != AudioSystem.NOT_SPECIFIED) {
 168             fileSize = (int)stream.getFrameLength()*streamFormat.getFrameSize() + AuFileFormat.AU_HEADERSIZE;
 169         } else {
 170             fileSize = AudioSystem.NOT_SPECIFIED;
 171         }
 172 
 173         return new AuFileFormat(Type.AU, fileSize, format,
 174                                 (int) stream.getFrameLength());
 175     }
 176 
 177     private InputStream getFileStream(AuFileFormat auFileFormat, AudioInputStream audioStream) throws IOException {
 178 
 179         // private method ... assumes auFileFormat is a supported file type
 180 
 181         AudioFormat format            = auFileFormat.getFormat();
 182 
 183         int headerSize     = AuFileFormat.AU_HEADERSIZE;
 184         long dataSize       = auFileFormat.getFrameLength();
 185         //$$fb fix for Bug 4351296
 186         //int dataSizeInBytes = dataSize * format.getFrameSize();
 187         long dataSizeInBytes = (dataSize==AudioSystem.NOT_SPECIFIED)?UNKNOWN_SIZE:dataSize * format.getFrameSize();
 188         if (dataSizeInBytes>0x7FFFFFFFl) {
 189             dataSizeInBytes=UNKNOWN_SIZE;
 190         }
 191         int auType = auFileFormat.getAuType();
 192         int sampleRate     = (int)format.getSampleRate();
 193         int channels       = format.getChannels();
 194 
 195         // if we need to do any format conversion, we do it here.
 196         //$$ fb 2001-07-13: Bug 4391108
 197         audioStream = AudioSystem.getAudioInputStream(format, audioStream);
 198 
 199         final byte[] header;
 200         try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
 201              DataOutputStream dos = new DataOutputStream(baos)) {
 202             dos.writeInt(AuFileFormat.AU_SUN_MAGIC);
 203             dos.writeInt(headerSize);
 204             dos.writeInt((int) dataSizeInBytes);
 205             dos.writeInt(auType);
 206             dos.writeInt(sampleRate);
 207             dos.writeInt(channels);
 208             header = baos.toByteArray();
 209         }
 210         // Now create a new InputStream from headerStream and the InputStream
 211         // in audioStream
 212         return new SequenceInputStream(new ByteArrayInputStream(header),
 213                                        new NoCloseInputStream(audioStream));
 214     }
 215 
 216     private int writeAuFile(AudioInputStream in, AuFileFormat auFileFormat,
 217                             OutputStream out) throws IOException {
 218 
 219         int bytesRead = 0;
 220         int bytesWritten = 0;
 221         InputStream fileStream = getFileStream(auFileFormat, in);
 222         byte[] buffer = new byte[bisBufferSize];
 223         int maxLength = auFileFormat.getByteLength();
 224 
 225         while( (bytesRead = fileStream.read( buffer )) >= 0 ) {
 226             if (maxLength>0) {
 227                 if( bytesRead < maxLength ) {
 228                     out.write( buffer, 0, bytesRead );
 229                     bytesWritten += bytesRead;
 230                     maxLength -= bytesRead;
 231                 } else {
 232                     out.write( buffer, 0, maxLength );
 233                     bytesWritten += maxLength;
 234                     maxLength = 0;
 235                     break;
 236                 }
 237             } else {
 238                 out.write( buffer, 0, bytesRead );
 239                 bytesWritten += bytesRead;
 240             }
 241         }
 242 
 243         return bytesWritten;
 244     }
 245 }