#### RemiAudio
#### Copyright (C) 2022-2024 Remilia Scarlet <remilia@posteo.jp>
####
#### This program is free software: you can redistribute it and/or modify it
#### under the terms of the GNU Affero General Public License as published by
#### the Free Software Foundation, either version 3 of the License, or (at your
#### option) any later version.
####
#### This program is distributed in the hope that it will be useful, but WITHOUT
#### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#### FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
#### License for more details.
####
#### You should have received a copy of the GNU Affero General Public License
#### along with this program.  If not, see <https://www.gnu.org/licenses/>.
require "libremiliacr"
require "../common"
require "./audiofile"

module RemiAudio::Formats
  ###
  ### Constants
  ###

  # The lowest sample rate in RIFF WAVE files supported by this library.
  WAV_MIN_SAMPLE_RATE = 8000

  # The highest sample rate in RIFF WAVE files supported by this library.
  WAV_MAX_SAMPLE_RATE = 352800

  # The lowest number of channels in RIFF WAVE files supported by this library.
  WAV_MIN_CHANNELS = 1

  # The highest number of channels in RIFF WAVE files supported by this library.
  WAV_MAX_CHANNELS = 24

  # An array of all the bit depths in RIFF WAVE files that are supported by this
  # library for integer samples.
  WAV_SUPPORTED_INT_BIT_DEPTHS = [8, 16, 24, 32, 64]

  # An array of all the bit depths in RIFF WAVE files that are supported by this
  # library for float samples.
  WAV_SUPPORTED_FLOAT_BIT_DEPTHS = [32, 64]

  ###
  ### Enumerations
  ###

  # The supported encodings for a RIFF WAVE file.
  enum WavEncoding
    # Linear PCM samples.
    Lpcm = 1

    # IEEE floating point samples.
    Float = 3

    # ALaw encoded samples.
    ALaw = 6

    # µLaw encoded samples.
    MuLaw = 7

    def self.from_value(value : Int) : self
      from_value?(value) || raise UnsupportedEncodingError.new("Unsupported WAVE encoding")
    end

    # Gets the `SampleFormat` that describes this encoding.  If this is an
    # encoding that does not describe a PCM/Float encoding, or an encoding not
    # directly supported by RemiAudio, this raises a `RemiAudioError`.
    def toSampleFormat(bitDepth : Int) : SampleFormat
      self.toSampleFormat?(bitDepth) ||
        raise UnsupportedEncodingError.new("Cannot represents #{self} as a SampleFormat")
    end

    # Attempts to get the `SampleFormat` that describes this encoding, or
    # `nil` if it's a non PCM/Float encoding, or an encoding not directly
    # supported by RemiAudio.
    def toSampleFormat?(bitDepth : Int) : SampleFormat?
      case self
      when .lpcm?
        case bitDepth
        when 8 then SampleFormat::U8
        #when 12 then SampleFormat::I12
        when 16 then SampleFormat::I16
        when 24 then SampleFormat::I24
        when 32 then SampleFormat::I32
        when 64 then SampleFormat::I64
        else nil
        end
      when .float?
        case bitDepth
        when 32 then SampleFormat::F32
        when 64 then SampleFormat::F64
        else nil
        end
      when .mu_law?, .a_law?
        bitDepth == 8 ? SampleFormat::U8 : nil
      else nil
      end
    end

    # Returns the size in bytes for a single sample using this encoding.
    def getByteSize(bitDepth : Int) : Int32
      case self
      in .lpcm?
        case bitDepth
        when 8 then 1
        when 16 then 2
        when 24 then 3
        when 32 then 4
        when 64 then 8
        else raise AudioFileError.new("Unsupported WAV bit depth for LPCM: #{bitDepth}")
        end
      in .float?
        case bitDepth
        when 32 then 4
        when 64 then 8
        else raise AudioFileError.new("Unsupported WAV bit depth for Float: #{bitDepth}")
        end
      in .mu_law?, .a_law?
        case bitDepth
        when 8 then 1
        else raise AudioFileError.new("Unsupported WAV bit depth for #{self}: #{bitDepth}")
        end
      end
    end

    # Returns the value to use when converting a value in this encoding to a
    # `::Float64`, or `nil` if converting from this encoding is not supported.
    def getFloat64Div?(bitDepth : Int) : Float64?
      {% begin %}
        case self
        in .lpcm?
          case bitDepth
          when 8 then Int8::MAX.to_f64! # Note: you first have to subtract 128
                                        # from the sample, which may make it
                                        # negative.
          when 16 then Int16::MAX.to_f64!
          when 24 then ({{ (2.0 ** 23) - 1 }}).to_f64!
          when 32 then Int32::MAX.to_f64!
          when 64 then Int64::MAX.to_f64!
          else nil
          end
        in .float? then 1.0
        else nil
        end
      {% end %}
    end

    # Returns the value to use when converting a value in this encoding to a
    # `::Float32`, or `nil` if converting from this encoding is not supported.
    def getFloat32Div?(bitDepth : Int) : Float32?
      {% begin %}
        case self
        in .lpcm?
          case bitDepth
          when 8 then Int8::MAX.to_f32! # Note: you first have to subtract 128
                                        # from the sample, which may make it
                                        # negative.
          when 16 then Int16::MAX.to_f32!
          when 24 then ({{ (2.0 ** 23) - 1 }}).to_f32!
          when 32 then Int32::MAX.to_f32!
          when 64 then Int64::MAX.to_f32!
          else nil
          end
        in .float? then 1.0f32
        else nil
        end
      {% end %}
    end

    # Returns the value to use when converting a value in this encoding to a
    # `::Float64`.  This will raise an `UnsupportedEncodingError` if converting
    # from this encoding is not supported.
    @[AlwaysInline]
    def getFloat64Div(bitDepth : Int) : Float64
      getFloat64Div? ||
        raise UnsupportedEncodingError.new("This WAVE encoding at bit depth #{bitDepth} is currently unsupported " \
                                           "by this library: #{self}")
    end

    # Returns the value to use when converting a value in this encoding to a
    # `::Float32`.  This will raise an `UnsupportedEncodingError` if converting
    # from this encoding is not supported.
    @[AlwaysInline]
    def getFloat32Div(bitDepth : Int) : Float32
      getFloat32Div? ||
        raise UnsupportedEncodingError.new("This WAVE encoding at bit depth #{bitDepth} is currently unsupported " \
                                           "by this library: #{self}")
    end

    # Checks that *array* is the correct type for this encoding.  If it is, this
    # returns `true`, otherwise it returns `false`.
    @[AlwaysInline]
    def checkArray(array : SampleData, bitDepth : Int) : Bool
      case self
      in .lpcm?
        case bitDepth
        when 8 then array.is_a?(Array(::UInt8))
        when 16 then array.is_a?(Array(::Int16))
        when 24 then array.is_a?(Array(::Int32))
        when 32 then array.is_a?(Array(::Int32))
        when 64 then array.is_a?(Array(::Int64))
        else raise AudioFileError.new("Unsupported WAV bit depth for LPCM: #{bitDepth}")
        end
      in .float?
        case bitDepth
        when 32 then array.is_a?(Array(::Float32))
        when 64 then array.is_a?(Array(::Float64))
        else raise AudioFileError.new("Unsupported WAV bit depth for Float: #{bitDepth}")
        end
      in .mu_law?, .a_law?
        case bitDepth
        when 8 then array.is_a?(Array(::UInt8))
        else raise AudioFileError.new("Unsupported WAV bit depth for #{self}: #{bitDepth}")
        end
      end
    end

    # Creates a new array of the given size that is appropriate for this
    # encoding.
    @[AlwaysInline]
    def makeArray(size : Int32, bitDepth : Int) : SampleData
      case self
      when .lpcm?
        case bitDepth
        when 8 then Array(UInt8).new(size, 0u8).as(SampleData)
        when 16 then Array(Int16).new(size, 0i16).as(SampleData)
        when 24 then Array(Int32).new(size, 0i32).as(SampleData)
        when 32 then Array(Int32).new(size, 0i32).as(SampleData)
        when 64 then Array(Int64).new(size, 0i64).as(SampleData)
        else raise AudioFileError.new("Unsupported WAV bit depth for LPCM: #{bitDepth}")
        end
      when .float?
        case bitDepth
        when 32 then Array(Float32).new(size, 0.0f32).as(SampleData)
        when 64 then Array(Float64).new(size, 0.0).as(SampleData)
        else raise AudioFileError.new("Unsupported WAV bit depth for Float: #{bitDepth}")
        end
      when .mu_law?, .a_law?
        case bitDepth
        when 8 then Array(UInt8).new(size, 0u8).as(SampleData)
        else raise AudioFileError.new("Unsupported WAV bit depth for #{self}: #{bitDepth}")
        end
      else raise UnsupportedEncodingError.new("This WAVE encoding is currently unsupported by this library")
      end
    end
  end

  ##############################################################################
  ###
  ### WavFile Class
  ###

  # A virtual representation of a RIFF WAVE file (.wav).
  #
  # RIFF WAVE (usually just called "wave") is, as the name suggests, based on
  # the RIFF file format.  It is an extremely common format that originated with
  # IBM and Microsoft.
  #
  # The official specification supports more encodings, as well as "extensible
  # WAVEs".  This library does not support these.  See `WavEncoding` for a list
  # of supported encodings, and `WAV_SUPPORTED_INT_BIT_DEPTHS` and
  # `WAV_SUPPORTED_FLOAT_BIT_DEPTHS` for supported bit depths.
  class WavFile < AudioFile
    # The `WavEncoding` that the samples in this instance uses.
    getter encoding : WavEncoding = WavEncoding::Lpcm

    @blockSize : UInt16 = 0u16
    @stereoBlockSize : UInt16 = 0u16
    @dataSizePos : UInt64 = 0

    # Creates a new `WavFile` that is backed by a fresh `::IO::Memory`.
    def initialize(*, @sampleRate : UInt32 = 44100u32, @bitDepth : UInt8 = 16u8, @channels : UInt32 = 2u32,
                   @encoding : WavEncoding = WavEncoding::Lpcm)
      checkInternalValues
      @blockSize = @encoding.getByteSize(@bitDepth).to_u16
      @stereoBlockSize = @blockSize * @channels
      assignFuncs

      @io = IO::Memory
      @origIoPos = 0

      # Write the header
      writeHeader
    end

    # Creates a new `WavFile` that is backed by the given `::IO`.
    def initialize(@io : IO, *, @sampleRate : UInt32 = 44100u32, @bitDepth : UInt8 = 16u8, @channels : UInt32 = 2u32,
                   @encoding : WavEncoding = WavEncoding::Lpcm)
      checkInternalValues
      @blockSize = @encoding.getByteSize(@bitDepth).to_u16
      @stereoBlockSize = @blockSize * @channels
      assignFuncs

      @origIoPos = @io.pos.to_u64!

      # Write the header
      startWav
    end

    protected def initialize(*, _fromIo : IO)
      @io = _fromIo
      @io.flush # Needed for the pos below to work correctly
      @origIoPos = @io.pos.to_u64
      readWav
      checkInternalValues
      assignFuncs
      @io.pos = @dataStartsAt
    end

    # Creates a new `WavFile` by reading the existing RIFF WAVE data from *io*.
    # Samples will be streamed from *io* as needed.
    def self.open(io : IO) : WavFile
      WavFile.new(_fromIo: io)
    end

    # Creates a new `WavFile` by reading the existing RIFF WAVE data from *io*,
    # then yields it to the block.  Samples will be streamed from *io* as
    # needed.  This will **NOT** automatically close the `WavFile` before
    # returning in case you have passed an *io* that cannot does not support
    # writing.
    def self.open(io : IO, &)
      au = WavFile.open(io)
      yield au
    end

    # Creates a new `WavFile` by reading the existing RIFF WAVE data from the
    # given file.  The file is always opened with the mode `"r+b"`.  Samples
    # will be streamed from the file as needed.
    def self.open(filename : Path|String) : WavFile
      WavFile.new(_fromIo: File.open(filename, "r+b"))
    end

    # Creates a new `WavFile` by reading the existing RIFF WAVE data from the
    # file, then yields it to the block.  The file is always opened with the
    # mode `"r+b"`.  Samples will be streamed from *io* as needed.  This
    # **will** automatically close the `WavFile` and underlying `::IO` before
    # returning.
    def self.open(filename : Path|String, &)
      au = WavFile.open(filename)
      yield au
    ensure
      au.try &.close
    end

    # Creates a new `WavFile` that that is backed by *io* and returns the new
    # instance.  Skeleton RIFF file data is immediately written into *io*.
    def self.create(io : IO, *, sampleRate : Int = 44100, bitDepth : Int = 16, channels : Int32 = 2,
                    encoding : WavEncoding = WavEncoding::Lpcm) : WavFile
      WavFile.new(io, sampleRate: sampleRate.to_u32, bitDepth: bitDepth.to_u8, channels: channels.to_u32,
                  encoding: encoding)
    end

    # Creates a new `WavFile` that that is backed by *io* and yields the new
    # instance to the block.  Skeleton RIFF file data is immediately written
    # into *io*.  The `WavFile` instance will be flushed and closed once the
    # block exits.
    def self.create(io : IO, *, sampleRate : Int = 44100, bitDepth : Int = 16, channels : Int32 = 2,
                    encoding : WavEncoding = WavEncoding::Lpcm, &)
      wav = WavFile.new(io, sampleRate: sampleRate.to_u32, bitDepth: bitDepth.to_u8, channels: channels.to_u32,
                        encoding: encoding)
      yield wav
    ensure
      wav.try &.flush
      wav.try &.close
    end

    # Creates a new `WavFile` that is backed by a new file on disk.
    #
    # This always opens the file with the mode `"w+b"` (i.e. existing files are
    # overwritten/truncated).  Skeleton RIFF file data is immediately written
    # into the file.
    def self.create(filename : Path|String, *, sampleRate : Int = 44100, bitDepth : Int = 16, channels : Int = 2,
                    encoding : WavEncoding = WavEncoding::Lpcm) : WavFile
      file = File.open(filename, "w+b")
      begin
        WavFile.new(file, sampleRate: sampleRate.to_u32, bitDepth: bitDepth.to_u8, channels: channels.to_u32,
                    encoding: encoding)
      rescue err : Exception
        file.try &.close
        raise err
      end
    end

    # Creates a new `WavFile` that is backed by a new file on disk, then yields
    # it to the block.  This automatically closes the `AuFile` and the
    # underlying file before the block returns.
    #
    # This always opens the file with the mode `"w+b"` (i.e. existing files are
    # overwritten/truncated).  Skeleton RIFF file data is immediately written
    # into the file.
    def self.create(filename : Path|String, *, sampleRate : Int = 44100, bitDepth : Int = 16, channels : Int = 2,
                    encoding : WavEncoding = WavEncoding::Lpcm, &)
      file = File.open(filename, "w+b")
      begin
        au = WavFile.new(file, sampleRate: sampleRate.to_u32, bitDepth: bitDepth.to_u8, channels: channels.to_u32,
                         encoding: encoding)
        begin
          yield au
        ensure
          au.close
        end
      rescue err : Exception
        file.try &.close
        raise err
      end
    end

    ##############################################################################

    protected def checkInternalValues
      # Check bit depth
      case @encoding
      in .lpcm?
        unless WAV_SUPPORTED_INT_BIT_DEPTHS.includes?(@bitDepth)
          raise AudioFileError.new("Unsupported bit depth for LPCM WAVE files")
        end
      in .float?
        unless WAV_SUPPORTED_FLOAT_BIT_DEPTHS.includes?(@bitDepth)
          raise AudioFileError.new("Unsupported bit depth for float WAVE files")
        end
      in .mu_law?, .a_law?
        unless @bitDepth == 8
          raise AudioFileError.new("Unsupported bit depth for µLaw/ALaw WAVE files")
        end
      end

      # Check sample rate
      unless @sampleRate >= WAV_MIN_SAMPLE_RATE && @sampleRate <= WAV_MAX_SAMPLE_RATE
        raise AudioFileError.new("Unsupported sample rate: #{@sampleRate}")
      end

      # Check the number of channels
      unless @channels >= WAV_MIN_CHANNELS && @channels <= WAV_MAX_CHANNELS
        raise AudioFileError.new("Unsupported number of channels: #{@channels}")
      end
    end

    # Assigns the internal functions according to our encoding.
    protected def assignFuncs : Nil
      case @encoding
      in .lpcm?
        case @bitDepth
        when 8
          @sampleReadFn = ->fastReadSampleUInt8
          @samplesReadFn = ->fastReadSamplesUInt8(SampleData)
          @sampleWriteFn = ->fastWriteSampleUInt8(Sample)
          @samplesWriteFn = ->fastWriteSamplesUInt8(SampleData)
          @sampleToF64Fn = ->uint8ToF64(Sample)
          @f64ToSampleFn = ->f64ToUInt8(Float64)
          @sampleToF32Fn = ->uint8ToF32(Sample)
          @f32ToSampleFn = ->f32ToUInt8(Float32)
        when 16
          @sampleReadFn = ->fastReadSampleInt16
          @samplesReadFn = ->fastReadSamplesInt16(SampleData)
          @sampleWriteFn = ->fastWriteSampleInt16(Sample)
          @samplesWriteFn = ->fastWriteSamplesInt16(SampleData)
          @sampleToF64Fn = ->int16ToF64(Sample)
          @f64ToSampleFn = ->f64ToInt16(Float64)
          @sampleToF32Fn = ->int16ToF32(Sample)
          @f32ToSampleFn = ->f32ToInt16(Float32)
        when 24
          @sampleReadFn = ->fastReadSampleInt24
          @samplesReadFn = ->fastReadSamplesInt24(SampleData)
          @sampleWriteFn = ->fastWriteSampleInt24(Sample)
          @samplesWriteFn = ->fastWriteSamplesInt24(SampleData)
          @sampleToF64Fn = ->int24ToF64(Sample)
          @f64ToSampleFn = ->f64ToInt24(Float64)
          @sampleToF32Fn = ->int24ToF32(Sample)
          @f32ToSampleFn = ->f32ToInt24(Float32)
        when 32
          @sampleReadFn = ->fastReadSampleInt32
          @samplesReadFn = ->fastReadSamplesInt32(SampleData)
          @sampleWriteFn = ->fastWriteSampleInt32(Sample)
          @samplesWriteFn = ->fastWriteSamplesInt32(SampleData)
          @sampleToF64Fn = ->int32ToF64(Sample)
          @f64ToSampleFn = ->f64ToInt32(Float64)
          @sampleToF32Fn = ->int32ToF32(Sample)
          @f32ToSampleFn = ->f32ToInt32(Float32)
        when 64
          @sampleReadFn = ->fastReadSampleInt64
          @samplesReadFn = ->fastReadSamplesInt64(SampleData)
          @sampleWriteFn = ->fastWriteSampleInt64(Sample)
          @samplesWriteFn = ->fastWriteSamplesInt64(SampleData)
          @sampleToF64Fn = ->int64ToF64(Sample)
          @f64ToSampleFn = ->f64ToInt64(Float64)
          @sampleToF32Fn = ->int64ToF32(Sample)
          @f32ToSampleFn = ->f32ToInt64(Float32)
        else raise "Unexpected LPCM bit depth"
        end

      in .float?
        case @bitDepth
        when 32
          @sampleReadFn = ->fastReadSampleFloat32
          @samplesReadFn = ->fastReadSamplesFloat32(SampleData)
          @sampleWriteFn = ->fastWriteSampleFloat32(Sample)
          @samplesWriteFn = ->fastWriteSamplesFloat32(SampleData)
          @sampleToF64Fn = ->float32ToF64(Sample)
          @f64ToSampleFn = ->f64ToFloat32(Float64)
          @sampleToF32Fn = ->float32ToF32(Sample)
          @f32ToSampleFn = ->f32ToFloat32(Float32)
        when 64
          @sampleReadFn = ->fastReadSampleFloat64
          @samplesReadFn = ->fastReadSamplesFloat64(SampleData)
          @sampleWriteFn = ->fastWriteSampleFloat64(Sample)
          @samplesWriteFn = ->fastWriteSamplesFloat64(SampleData)
          @sampleToF64Fn = ->float64ToF64(Sample)
          @f64ToSampleFn = ->f64ToFloat64(Float64)
          @sampleToF32Fn = ->float32ToF32(Sample)
          @f32ToSampleFn = ->f32ToFloat32(Float32)
        else raise "Unexpected float bit depth"
        end

      in .mu_law?, .a_law?
        case @bitDepth
        when 8
          @sampleReadFn = ->fastReadSampleUInt8
          @samplesReadFn = ->fastReadSamplesUInt8(SampleData)
          @sampleWriteFn = ->fastWriteSampleUInt8(Sample)
          @samplesWriteFn = ->fastWriteSamplesUInt8(SampleData)
          @sampleToF64Fn = ->AudioFile.cannotConvertToFloat64(Sample)
          @f64ToSampleFn = ->AudioFile.cannotConvertToSample(Float64)
          @sampleToF32Fn = ->AudioFile.cannotConvertToFloat32(Sample)
          @f32ToSampleFn = ->AudioFile.cannotConvertToSample(Float32)
        else raise "Unexpected #{@encoding} bit depth"
        end
      end
    end

    protected def readWavFmtChunkSize : UInt32
      chunkSize = @io.readUInt32
      unless chunkSize == 16 || chunkSize == 18 || chunkSize == 40
        raise AudioFileError.new("Invalid 'fmt ' chunk size: #{chunkSize}")
      end
      chunkSize
    end

    protected def readWavFmtChunk : Nil
      chunkSize = readWavFmtChunkSize

      # Determine the format
      formatCode = @io.readUInt16
      @encoding = WavEncoding.from_value?(formatCode) ||
                  raise RemiAudioError.new("Unsupported WAV format code: $#{sprintf("%04x", formatCode)}")

      # Check chunk size against the format.
      case @encoding
      when .lpcm?
        nil
      when .float?
        unless chunkSize == 18 || chunkSize == 40
          raise AudioFileError.new("The 'fmt ' chunk is incomplete for IEEE Floating Point format")
        end

      when .mu_law?, .a_law?
        unless chunkSize == 18 || chunkSize == 40
          raise AudioFileError.new("The 'fmt ' chunk is incomplete for G.711 format")
        end

      else
        unless chunkSize == 40
          raise AudioFileError.new("The 'fmt ' chunk does not contain enough data for the #{@encoding} format")
        end
      end

      # Read some more of the chunk
      @channels = @io.readUInt16.to_u32!
      @sampleRate = @io.readUInt32
      @io.pos += 4 # Skip the dataRate field
      @stereoBlockSize = @io.readUInt16
      raise AudioFileError.new("Bad block size in WAVE file") unless @stereoBlockSize % @channels == 0
      @blockSize = @stereoBlockSize.tdiv(@channels)

      begin
        @bitDepth = @io.readUInt16.to_u8
      rescue OverflowError
        raise AudioFileError.new("Unsupported bit depth: over 256bit")
      end

      # See if we have more to read
      extensionSize = @io.readUInt16
      if extensionSize == 22
        # We have an extension to read
        raise AudioFileError.new("Extensible RIFF WAVE files not supported")
      elsif extensionSize != 0
        # Might be other data... skip it
        @io.pos -= 2
      end
    end

    protected def readWavFactChunk : Nil
      chunkSize = @io.readUInt32
      @io.pos += 4 # Skip four bytes, we don't use the samplesPerChannel field.

      # Skip any remaining data if there's more in the fact chunk
      @io.pos += chunkSize - 4 unless chunkSize == 4
    end

    protected def readWav : Nil
      expectChunkType("RIFF")
      @io.flush
      @io.pos += 4 # Number of chunks containing format info and sampled data.  We don't use this.
      expectChunkType("WAVE")

      foundFmt = false
      foundData = false

      begin
        loop do
          cc = readFourCC
          case cc
          when nil then break
          when "fmt "
            readWavFmtChunk
            foundFmt = true
          when "fact"
            readWavFactChunk
          when "data"
            # We don't actually read the data, but we do need to note where it's
            # at and the size.
            @io.flush
            @dataSizePos = @io.pos.to_u64!
            @dataSizeInBytes = @io.readUInt32.to_u64!
            @dataStartsAt = @io.pos.to_u64
            @io.pos += @dataSizeInBytes - 4
            foundData = true
          end
        end
      rescue IO::EOFError
      end

      # All the chunks should be read by now, so we can correctly set this.
      @numSamples = @dataSizeInBytes.tdiv(@encoding.getByteSize(@bitDepth))
      raise AudioFileError.new("Bad number of samples, some are missing") unless @numSamples % @channels == 0
    end

    # Writes most of the RIFF chunk metadata data.
    protected def startWav : Nil
      @io << "RIFF"
      @io.writeUInt32(69u32) # Temporary value
      @io << "WAVE" # No size for this chunk
      @io << "fmt " # Extra space is required

      # The size of the "fmt " chunk changes depending on the encoding, but we
      # still know it ahead of time since the @encoding can't be changed.
      case @encoding
      when .lpcm? then @io.writeUInt32(16u32)
      when .float?, .mu_law?, .a_law? then @io.writeUInt32(18u32)
      else raise UnsupportedEncodingError.new("This WAVE encoding is currently unsupported by this library")
      end

      @io.writeUInt16(@encoding.value.to_u16!)
      @io.writeUInt16(@channels.to_u16)
      @io.writeUInt32(@sampleRate)

      begin
        # Temporarily upconvert to a larger integer size so we avoid possible
        # overflows.
        dataRate : UInt32 = (@sampleRate.to_u64! * @channels.to_u64! * @bitDepth.to_u64!.tdiv(8)).to_u32
      rescue OverflowError
        raise AudioFileError.new("Resulting WAVE data rate is too large and won't fit in 32 bits")
      end
      @io.writeUInt32(dataRate)

      @io.writeUInt16((@bitDepth.to_u32!.tdiv(8) * @channels).to_u16) # Byte rate
      @io.writeUInt16(@bitDepth.to_u16!)

      if @encoding.float? || @encoding.mu_law? || @encoding.a_law?
        @io.writeUInt16(0) # Extension size, always zero for us
      end

      @io << "data"
      @io.flush # Needed for the pos on the next line
      @dataSizePos = @io.pos.to_u64!
      @io.writeUInt32(0u32)
      @io.flush # Same, needed for the pos on the next line
      @dataStartsAt = @io.pos.to_u64
    end

    protected def calculateRiffSizes : Tuple(Int64, Int64)
      calculatedSize : Int64 = 4i64 + # "WAVE"
                               4 +    # "fmt "
                               4      # "fmt " chunk size

      case @encoding
      when .lpcm?
        calculatedSize += 2 + # Format
                          2 + # Num channels
                          4 + # Sample rate
                          4 + # Data rate
                          2 + # Block alignment
                          2   # Bit depth
      when .float?, .mu_law?, .a_law?
        calculatedSize += 2 + # Format
                          2 + # Num channels
                          4 + # Sample rate
                          4 + # Data rate
                          2 + # Block alignment
                          2 + # Bit depth
                          2 # Extension size
      else raise UnsupportedEncodingError.new("This WAVE encoding is currently unsupported by this library")
      end

      calculatedSize += 8 # "data" + data size
      dataSize : Int64 = @numSamples.to_i64! * @encoding.getByteSize(@bitDepth)
      calculatedSize += dataSize

      # Do some checks. -8 because "RIFF" and the RIFF chunk size is not
      # included in this.
      if (calculatedSize - 8) > UInt32::MAX
        raise AudioFileError.new("Total size of the sample data + RIFF chunks is too large")
      elsif calculatedSize - 8 < 0
        raise "Calculated size is somehow negative O_o"
      end

      if dataSize > UInt32::MAX
        raise AudioFileError.new("Size of the sample data + RIFF chunks is too large")
      elsif dataSize < 0
        raise "Data size is somehow negative O_o"
      end

      {calculatedSize, dataSize}
    end

    # Flushes the stream, then adjusts the "fmt " fields with the correct
    # information.
    protected def finishWav : Nil
      raise AudioFileError.new("Bad number of samples, some are missing") unless @numSamples % @channels == 0
      calculatedSize, dataSize = calculateRiffSizes

      @io.flush # Needed for pos to work
      @io.withExcursion(@origIoPos + 4) do # Right after "RIFF"
        @io.writeUInt32(calculatedSize.to_u32)
      end
      @io.withExcursion(@dataSizePos.to_i32) do
        @io.writeUInt32(dataSize.to_u32)
      end
    end

    ##############################################################################

    # :inherited:
    def sampleFormat : SampleFormat
      @encoding.toSampleFormat(@bitDepth)
    end

    # :inherited:
    def read(dest : Array(Float64)) : Int32
      temp : SampleData = @encoding.makeArray(dest.size, @bitDepth)
      num : Int32 = readSamples(temp)
      num.times do |i|
        dest[i] = @sampleToF64Fn.call(temp[i])
      end
      num
    end

    # :inherited:
    def read(dest : Array(Float32)) : Int32
      temp : SampleData = @encoding.makeArray(dest.size, @bitDepth)
      num : Int32 = readSamples(temp)
      num.times do |i|
        dest[i] = @sampleToF32Fn.call(temp[i])
      end
      num
    end

    # :inherited:
    def readSamplesToEnd : SampleData
      curSample = self.pos
      toRead : UInt64 = @numSamples - curSample
      ret : SampleData = @encoding.makeArray(toRead.to_i32, @bitDepth)
      @samplesReadFn.call(ret)
      ret
    end

    # :inherited:
    def flush : Nil
      return unless @changed
      finishWav
      @io.flush
    end

    def copyTo(dest : IO) : Nil
      flush
      @io.withExcursion(@origIoPos) do
        IO.copy(@io, dest)
      end
    end
  end
end
