File src/remiaudio/formats/wav.cr from the latest check-in


     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
   100
   101
   102
   103
   104
   105
   106
   107
   108
   109
   110
   111
   112
   113
   114
   115
   116
   117
   118
   119
   120
   121
   122
   123
   124
   125
   126
   127
   128
   129
   130
   131
   132
   133
   134
   135
   136
   137
   138
   139
   140
   141
   142
   143
   144
   145
   146
   147
   148
   149
   150
   151
   152
   153
   154
   155
   156
   157
   158
   159
   160
   161
   162
   163
   164
   165
   166
   167
   168
   169
   170
   171
   172
   173
   174
   175
   176
   177
   178
   179
   180
   181
   182
   183
   184
   185
   186
   187
   188
   189
   190
   191
   192
   193
   194
   195
   196
   197
   198
   199
   200
   201
   202
   203
   204
   205
   206
   207
   208
   209
   210
   211
   212
   213
   214
   215
   216
   217
   218
   219
   220
   221
   222
   223
   224
   225
   226
   227
   228
   229
   230
   231
   232
   233
   234
   235
   236
   237
   238
   239
   240
   241
   242
   243
   244
   245
   246
   247
   248
   249
   250
   251
   252
   253
   254
   255
   256
   257
   258
   259
   260
   261
   262
   263
   264
   265
   266
   267
   268
   269
   270
   271
   272
   273
   274
   275
   276
   277
   278
   279
   280
   281
   282
   283
   284
   285
   286
   287
   288
   289
   290
   291
   292
   293
   294
   295
   296
   297
   298
   299
   300
   301
   302
   303
   304
   305
   306
   307
   308
   309
   310
   311
   312
   313
   314
   315
   316
   317
   318
   319
   320
   321
   322
   323
   324
   325
   326
   327
   328
   329
   330
   331
   332
   333
   334
   335
   336
   337
   338
   339
   340
   341
   342
   343
   344
   345
   346
   347
   348
   349
   350
   351
   352
   353
   354
   355
   356
   357
   358
   359
   360
   361
   362
   363
   364
   365
   366
   367
   368
   369
   370
   371
   372
   373
   374
   375
   376
   377
   378
   379
   380
   381
   382
   383
   384
   385
   386
   387
   388
   389
   390
   391
   392
   393
   394
   395
   396
   397
   398
   399
   400
   401
   402
   403
   404
   405
   406
   407
   408
   409
   410
   411
   412
   413
   414
   415
   416
   417
   418
   419
   420
   421
   422
   423
   424
   425
   426
   427
   428
   429
   430
   431
   432
   433
   434
   435
   436
   437
   438
   439
   440
   441
   442
   443
   444
   445
   446
   447
   448
   449
   450
   451
   452
   453
   454
   455
   456
   457
   458
   459
   460
   461
   462
   463
   464
   465
   466
   467
   468
   469
   470
   471
   472
   473
   474
   475
   476
   477
   478
   479
   480
   481
   482
   483
   484
   485
   486
   487
   488
   489
   490
   491
   492
   493
   494
   495
   496
   497
   498
   499
   500
   501
   502
   503
   504
   505
   506
   507
   508
   509
   510
   511
   512
   513
   514
   515
   516
   517
   518
   519
   520
   521
   522
   523
   524
   525
   526
   527
   528
   529
   530
   531
   532
   533
   534
   535
   536
   537
   538
   539
   540
   541
   542
   543
   544
   545
   546
   547
   548
   549
   550
   551
   552
   553
   554
   555
   556
   557
   558
   559
   560
   561
   562
   563
   564
   565
   566
   567
   568
   569
   570
   571
   572
   573
   574
   575
   576
   577
   578
   579
   580
   581
   582
   583
   584
   585
   586
   587
   588
   589
   590
   591
   592
   593
   594
   595
   596
   597
   598
   599
   600
   601
   602
   603
   604
   605
   606
   607
   608
   609
   610
   611
   612
   613
   614
   615
   616
   617
   618
   619
   620
   621
   622
   623
   624
   625
   626
   627
   628
   629
   630
   631
   632
   633
   634
   635
   636
   637
   638
   639
   640
   641
   642
   643
   644
   645
   646
   647
   648
   649
   650
   651
   652
   653
   654
   655
   656
   657
   658
   659
   660
   661
   662
   663
   664
   665
   666
   667
   668
   669
   670
   671
   672
   673
   674
   675
   676
   677
   678
   679
   680
   681
   682
   683
   684
   685
   686
   687
   688
   689
   690
   691
   692
   693
   694
   695
   696
   697
   698
   699
   700
   701
   702
   703
   704
   705
   706
   707
   708
   709
   710
   711
   712
   713
   714
   715
   716
   717
   718
   719
   720
   721
   722
   723
   724
   725
   726
   727
   728
   729
   730
   731
   732
   733
   734
   735
   736
   737
   738
   739
   740
   741
   742
   743
   744
   745
   746
   747
   748
   749
   750
   751
   752
   753
   754
   755
   756
   757
   758
   759
   760
   761
   762
   763
   764
   765
   766
   767
   768
   769
   770
   771
   772
   773
   774
   775
   776
   777
   778
   779
   780
   781
   782
   783
   784
   785
   786
   787
   788
   789
   790
   791
   792
#### 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