File src/remiaudio/cue.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
   793
   794
   795
   796
   797
   798
   799
   800
   801
   802
   803
   804
   805
   806
   807
   808
   809
   810
   811
   812
   813
   814
   815
   816
   817
   818
   819
   820
   821
   822
   823
   824
   825
   826
   827
   828
   829
   830
   831
   832
   833
   834
   835
   836
   837
   838
   839
   840
   841
   842
   843
   844
   845
   846
   847
   848
   849
   850
   851
   852
   853
   854
   855
   856
   857
   858
   859
   860
   861
   862
   863
   864
   865
   866
   867
   868
   869
   870
   871
   872
   873
   874
   875
   876
   877
   878
   879
   880
   881
   882
   883
   884
   885
   886
   887
   888
   889
   890
   891
   892
   893
   894
   895
   896
   897
   898
   899
   900
   901
   902
   903
   904
   905
   906
   907
   908
   909
   910
   911
   912
   913
   914
   915
   916
   917
   918
   919
   920
   921
   922
   923
   924
   925
   926
   927
   928
   929
   930
   931
   932
   933
   934
   935
   936
   937
   938
   939
   940
   941
   942
   943
   944
   945
   946
   947
   948
   949
   950
   951
   952
   953
   954
   955
   956
   957
   958
   959
   960
   961
   962
   963
   964
   965
   966
   967
   968
   969
   970
   971
   972
   973
   974
   975
   976
   977
   978
   979
   980
   981
   982
   983
   984
   985
   986
   987
   988
   989
   990
   991
   992
   993
   994
   995
   996
   997
   998
   999
  1000
  1001
  1002
  1003
  1004
  1005
  1006
  1007
  1008
  1009
  1010
  1011
  1012
  1013
  1014
  1015
  1016
  1017
  1018
  1019
  1020
  1021
  1022
  1023
  1024
  1025
  1026
  1027
  1028
  1029
  1030
  1031
  1032
  1033
  1034
  1035
  1036
  1037
  1038
  1039
  1040
  1041
  1042
  1043
  1044
  1045
  1046
  1047
  1048
  1049
  1050
  1051
  1052
  1053
  1054
  1055
  1056
  1057
  1058
  1059
  1060
  1061
  1062
  1063
  1064
  1065
  1066
  1067
  1068
  1069
  1070
  1071
  1072
  1073
  1074
  1075
  1076
  1077
  1078
  1079
  1080
  1081
  1082
  1083
  1084
  1085
  1086
  1087
  1088
  1089
  1090
  1091
  1092
  1093
  1094
  1095
  1096
  1097
  1098
  1099
  1100
  1101
  1102
  1103
  1104
  1105
  1106
  1107
  1108
  1109
  1110
  1111
  1112
  1113
  1114
  1115
  1116
  1117
  1118
  1119
  1120
  1121
  1122
  1123
  1124
  1125
  1126
  1127
  1128
  1129
  1130
  1131
  1132
  1133
  1134
  1135
  1136
  1137
  1138
  1139
  1140
  1141
  1142
  1143
  1144
  1145
  1146
  1147
  1148
  1149
  1150
  1151
  1152
  1153
  1154
  1155
  1156
  1157
  1158
  1159
  1160
  1161
  1162
  1163
  1164
  1165
  1166
  1167
  1168
  1169
  1170
  1171
  1172
  1173
  1174
  1175
  1176
  1177
  1178
  1179
  1180
  1181
  1182
  1183
  1184
  1185
  1186
  1187
  1188
  1189
  1190
  1191
  1192
  1193
  1194
  1195
  1196
  1197
  1198
  1199
  1200
  1201
  1202
  1203
  1204
  1205
  1206
  1207
  1208
  1209
  1210
  1211
  1212
  1213
  1214
  1215
  1216
  1217
  1218
  1219
  1220
  1221
  1222
  1223
  1224
  1225
  1226
  1227
  1228
  1229
  1230
  1231
  1232
  1233
  1234
  1235
  1236
  1237
  1238
  1239
  1240
  1241
  1242
  1243
  1244
  1245
  1246
  1247
  1248
  1249
  1250
  1251
  1252
  1253
  1254
  1255
  1256
  1257
  1258
  1259
  1260
  1261
  1262
  1263
  1264
  1265
  1266
  1267
  1268
  1269
  1270
  1271
  1272
  1273
  1274
  1275
  1276
  1277
  1278
  1279
  1280
  1281
  1282
  1283
  1284
  1285
  1286
  1287
  1288
  1289
  1290
  1291
  1292
  1293
  1294
  1295
  1296
  1297
  1298
  1299
  1300
  1301
  1302
  1303
  1304
  1305
  1306
  1307
  1308
  1309
  1310
  1311
  1312
  1313
  1314
#### 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 "./common"

module RemiAudio
  # A virtual representation of a
  # [CUE sheet](https://en.wikipedia.org/wiki/Cue_sheet_%28computing%29").
  #
  # Example that lists the files/tracks of a CUE sheet, then saves the CUE sheet
  # to a new file.
  #
  # ```
  # require "remiaudio/cue"
  #
  # cue = RemiAudio::Cue.load("/path/to/file.cue")
  # cue.files.each do |file|
  #   puts "File: #{file.filename}"
  #   file.tracks.each do |track|
  #     if title = track.title
  #       puts "  #{title}"
  #     else
  #       puts "  Unnamed track, number #{track.trackNumber}"
  #     end
  #   end
  # end
  #
  # # Write the CUE to a new file
  # File.open("/path/to/newcue.cue", "w") do |file|
  #   cue.write(file)
  # end
  # ```
  #
  # Documentation for the CUE sheet format can be found at these sources:
  #
  # * [https://web.archive.org/web/20070614044112/http://www.goldenhawk.com/download/cdrwin.pdf]()
  # * [https://wiki.hydrogenaud.io/index.php?title=Cue_sheet]()
  # * [https://github.com/libyal/libodraw/blob/main/documentation/CUE%20sheet%20format.asciidoc]()
  class Cue
    class Error < RemiAudioError
    end

    #===========================================================================

    private ARGS_REGEX = /("[^"]+")|(\S+)/

    private enum NextState
      Normal
      File
      Track
      Catalog
      CdTextFile
    end

    # :nodoc:
    private class Parser
      property line : Int64 = 1
      property column : Int64 = 0
      property io : IO
      property? strict : Bool = false
      property? foundTrack : Bool = false

      def initialize(@io : IO)
      end

      # Advances `#column` by *count*.
      @[AlwaysInline]
      def adv(count : Int32 = 1) : Nil
        @column += count
      end

      # Advances `#line` by 1, and sets `#column` to 0.
      @[AlwaysInline]
      def advLine : Nil
        @column = 0
        @line += 1
      end

      # Splits "str" in a way similar to a shell (that is, quoted items are
      # considered a single string).
      def splitArgs(str : String, dontRemoveQuotes : Bool = false) : Array(String)
        strs = str.split(ARGS_REGEX).reject(&.strip.empty?)
        if dontRemoveQuotes
          strs
        else
          strs.map! do |string|
            if string[0] == '"' && string[-1] == '"'
              string[1..-2]
            else
              string
            end
          end
        end
      end

      # Reads and discards characters until a non-whitespace character is
      # detected.
      @[AlwaysInline]
      def skipWhitespace : Nil
        c : Char? = nil
        while c = @io.peekChar
          if c.whitespace?
            @io.read_char
            adv
          else
            break
          end
        end
      end

      # Reads the next token and returns it, or returns `nil` if there are no
      # more tokens to read.
      def readToken : String?
        skipWhitespace
        return nil if @io.peekChar.nil?

        String.build do |str|
          isQuoted : Bool = @io.peekChar == '"'
          @io.read_char if isQuoted

          c : Char? = nil
          while c = @io.read_char
            case c
            when '\r'
              if @io.peekChar == '\n'
                @io.read_char
                advLine
              else
                raise ParseError.new("\\r without \\n", self)
              end

              earlyOut : String = str.to_s
              return (earlyOut.empty? ? nil : earlyOut)

            when ' ', '\n'
              if isQuoted
                if c == '\n'
                  raise ParseError.new("Quoted string does not end", self)
                else
                  str << c
                end
              else
                advLine if c == '\n'
                break
              end

            when '"'
              unless isQuoted
                raise ParseError.new("Bad quoted string (field did not start with a quote)", self)
              end

              nextC = @io.peekChar
              unless nextC.nil? || nextC == ' ' || nextC == '\n'
                raise ParseError.new("Bad quoted string: quote is not followed by a space or newline", self)
              end

              adv
              isQuoted = false

            else
              str << c
              adv
            end
          end
        end
      end

      # Reads the rest of the current line and returns it, or returns `nil` if
      # there is nothing left to read.
      def readRemainingLine(removeQuotes : Bool = false) : String?
        c : Char? = nil

        skipWhitespace
        return nil if @io.peekChar.nil?
        ret : String? = @io.gets
        unless ret.nil?
          ret = ret.strip
          if removeQuotes && ret[0] == '"' && ret[-1] == '"'
            return ret[1..-2]
          end
        end

        ret
      end

      # Reads the rest of the current line and discards it, then returns.
      def skipToEof : Nil
        unless @column == 1
          c : Char? = nil
          loop do
            c = @io.read_char
            break if c.nil?  || c == '\n'
          end
          advLine
        end
      end
    end

    #===========================================================================

    # Represents an error condition that occured while parsing a CUE sheet.
    class ParseError < Error
      # The line near where the error occurred, or `-1` if it can't be determined.
      getter line : Int64 = -1

      # The column near where the error occurred, or `-1` if it can't be determined.
      getter column : Int64 = -1

      # Creates a new `ParseError` instance, taking line and column information
      # from *parser*.
      def initialize(msg : String, parser : Parser, causedBy : Exception? = nil)
        @line = parser.line
        @column = parser.column
        @message = msg
        @cause = causedBy
      end

      def to_s(io : IO) : Nil
        ln = @line >= 0 ? @line : "??"
        col = @column >= 0 ? @column : "??"
        io << "CUE parsing error near line #{ln} column #{col}: " << message
        io << " (" << self.class << ")\n"
      end

      def inspect_with_backtrace(io : IO) : Nil
        to_s(io)
        io << " (" << self.class << ")\n"

        backtrace?.try &.each do |frame|
          io.print "  from "
          io.puts frame
        end

        if cause = @cause
          io << "Caused by: "
          cause.inspect_with_backtrace(io)
        end

        io.flush
      end
    end

    #===========================================================================

    # Represents a moment or length in time in a CUE sheet.
    class Timestamp
      # The minute value.
      getter minutes : UInt32 = 0

      # The second value.
      getter seconds : UInt32 = 0

      # The number of CD frames.
      getter frames : UInt32 = 0

      # Creates a new `Timestamp`.
      def initialize
      end

      # Creates a new `Timestamp` with the given values.
      def initialize(@minutes : UInt32, @seconds : UInt32, @frames : UInt32)
      end

      def self.fromBytePos(value : Int) : Timestamp
        raise ArgumentError.new("Value cannot be negative") if value < 0
        return Timestamp.new if value == 0

        smp = value / 4
        total = smp / 44100
        frames = (total - total.to_i32!) * 75
        seconds = total.to_i32!
        minutes = seconds.tdiv(60)
        seconds = seconds - (minutes * 60)
        Timestamp.new(minutes.to_u32!, seconds.to_u32!, frames.to_u32!)
      end

      def minutes=(value : UInt32) : Nil
        raise ::ArgumentError.new("Invalid minutes value, must be between 0 and 99, inclusive.") if value > 99
        @minutes = value
      end

      def seconds=(value : UInt32) : Nil
        raise ::ArgumentError.new("Invalid seconds value, must be between 0 and 59, inclusive.") if value > 59
        @seconds = value
      end

      def frames=(value : UInt32) : Nil
        raise ::ArgumentError.new("Invalid frames value, must be between 0 and 74, inclusive.") if value > 74
        @frames = value
      end

      # :nodoc:
      def self.parse(parser : Parser)
        startingAt : Int64 = parser.column
        token : String? = parser.readToken

        raise ParseError.new("Could not read timestamp", parser) if token.nil?
        raise ParseError.new("Timestamp is malformed", parser) unless token.size >= 8
        raise ParseError.new("Malformed timestamp", parser) unless token[2] == ':' && token[5] == ':'

        mm = token[0...2].to_u32? || raise ParseError.new("Bad minute value in timestamp", parser)
        ss = token[3...5].to_u32? || raise ParseError.new("Bad second value in timestamp", parser)
        ff = token[6..].to_u32? || raise ParseError.new("Bad frame value in timestamp", parser)
        unless ff < 75
          raise ParseError.new("Bad timestamp: frame value must be between 0 and 74, inclusive", parser)
        end
        Timestamp.new(mm, ss, ff)
      end

      def to_s(io : IO) : Nil
        io << sprintf("%02d:%02d:%02d", @minutes, @seconds, @frames)
      end

      # Convert this timestamp to a sample number.  This always assumes CD audio
      # (44100 Hz 16-bit, 2 channels).
      def toSampleNum : Int32
        (((self.minutes.to_u64 * 60) + self.seconds + (self.frames / 75)) * 44100).to_i32
      end

      # Convert this timestamp to a byte position.  This always assumes CD audio
      # (44100 Hz 16-bit, 2 channels).
      def toBytePos : Int32
        toSampleNum * 4
      end

      def nanoseconds : Int64
        totalNs : Int64 = (self.minutes.to_i64! * 60) + self.seconds
        totalNs *= 1000000000_i64
        totalNs + ((self.frames / 75) * 1e+9).to_i64
      end

      def -(other : Timestamp) : Time::Span
        Time::Span.new(nanoseconds: self.nanoseconds - other.nanoseconds)
      end
    end

    #===========================================================================

    # A virtual representation of the data for a `TRACK` command within a CUE
    # sheet.  This is a single track for a CD.
    class Track
      # The type of `Track`.
      enum Type
        # Audio track
        Audio

        # CD+G track
        Cdg

        # Cooked CD-ROM Mode 1 data (sector size: 2048)
        Mode1_2048

        # Raw CD-ROM Mode 1 data (sector size: 2352)
        Mode1_2352

        # CD-ROM Mode 2 XA form-1 data (sector size: 2048)
        Mode2_2048

        # CD-ROM Mode 2 XA form-2 data (sector size: 2324)
        Mode2_2324

        # CD-ROM Mode 2 data (sector size: 2336)
        Mode2_2336

        # CD-ROM Mode 2 data (sector size: 2352)
        Mode2_2352

        # CDI Mode 2 data (sector size: 2336)
        Cdi_2336

        # CDI Mode 2 data (sector size: 2352)
        Cdi_2352

        # Similar to `::Enum.parse?`, except that this expects the strings to
        # match those in a CUE file (e.g. `"MODE1/2048"`), and is case
        # insensitive.
        def self.parse?(string : String) : self?
          case string.upcase
          when "AUDIO" then Type::Audio
          when "CDG" then Type::Cdg
          when "MODE1/2048" then Type::Mode1_2048
          when "MODE1/2352" then Type::Mode1_2352
          when "MODE2/2048" then Type::Mode2_2048
          when "MODE2/2324" then Type::Mode2_2324
          when "MODE2/2336" then Type::Mode2_2336
          when "MODE2/2352" then Type::Mode2_2352
          when "CDI/2336" then Type::Cdi_2336
          when "CDI/2352" then Type::Cdi_2352
          else nil
          end
        end

        # Similar to `::Enum#to_s`, except that the returned values are usable in
        # a CUE file.
        def to_s : String
          case self
          in .audio? then "AUDIO"
          in .cdg? then "CDG"
          in .mode1_2048? then "MODE1/2048"
          in .mode1_2352? then "MODE1/2352"
          in .mode2_2048? then "MODE2/2048"
          in .mode2_2324? then "MODE2/2324"
          in .mode2_2336? then "MODE2/2336"
          in .mode2_2352? then "MODE2/2352"
          in .cdi_2336? then "CDI/2336"
          in .cdi_2352? then "CDI/2352"
          end
        end

        # Similar to `::Enum.names`, except that the returned values match those
        # generated with `#to_s`.
        def self.names : Array(String)
          [
            "AUDIO",
            "CDG",
            "MODE1/2048",
            "MODE1/2352",
            "MODE2/2048",
            "MODE2/2324",
            "MODE2/2336",
            "MODE2/2352",
            "CDI/2336",
            "CDI/2352"
          ]
        end
      end

      # A set of `FLAGS` for a `Track` instance.
      @[Flags]
      enum Flags
        # Digital copy permitted
        DigitalCopyPermitted

        # 4-channel audio
        FourChannel

        # Pre-emphasis enabled (for audio tracks only)
        PreEmphasis

        # Serial copy management system
        Scms

        # Similar to `::Enum.parse?`, except that this expects the strings to
        # match those in a CUE file (e.g. `"DCP"`, `"4CH"`, etc.), and is case
        # insensitive.
        def self.parse?(string : String) : self?
          case string.upcase
          when "DCP" then Flags::DigitalCopyPermitted
          when "4CH" then Flags::FourChannel
          when "PRE" then Flags::PreEmphasis
          when "SCMS" then Flags::Scms
          else nil
          end
        end

        # Similar to `::Enum#to_s`, except that the returned values are usable in
        # a CUE file.
        def to_s : String
          case self
          in .digital_copy_permitted? then "DCP"
          in .four_channel? then "4CH"
          in .pre_emphasis? then "PRE"
          in .scms? then "SCMS"
          end
        end

        # Similar to `::Enum.names`, except that the returned values match those
        # generated with `#to_s`.
        def self.names : Array(String)
          [
            "DCP",
            "4CH",
            "PRE",
            "SCMS"
          ]
        end
      end

      # The expected length of the
      # [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
      # field, in bytes.
      ISRC_LEN = 12

      # The maximum length of the TITLE field, in bytes.
      MAX_TITLE_LEN = 80

      # The minimum length of the TITLE field, in bytes.
      MIN_TITLE_LEN = 1

      # The maximum length of the PERFORMER field, in bytes.
      MAX_PERFORMER_LEN = 80

      # The minimum length of the PERFORMER field, in bytes.
      MIN_PERFORMER_LEN = 1

      # The maximum length of the SONGWRITER field, in bytes.
      MAX_SONGWRITER_LEN = 80

      # The minimum length of the SONGWRITER field, in bytes.
      MIN_SONGWRITER_LEN = 1

      # The track number for this track.
      getter trackNumber : UInt32 = 1

      # The `Type` of this track.
      property type : Type = Type::Audio

      # The `Flags` for this track.
      property flags : Flags = Flags::None

      # The [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
      # for this track.
      #
      # For format information, see
      # [here](https://github.com/libyal/libodraw/blob/main/documentation/CUE%20sheet%20format.asciidoc#57-isrc).
      getter isrc : String?

      # The length of the gap before this track, if any.
      property pregap : Timestamp?

      # The length of the gap after this track, if any.
      property postgap : Timestamp?

      # The title of this track.
      getter title : String?

      # The name of the performer of this track.
      getter performer : String?

      # The name of the songwriter of this track.
      getter songwriter : String?

      # The INDEX fields.
      @indices : Hash(UInt32, Timestamp) = {} of UInt32 => Timestamp

      # Creates a new `Track` instance.
      def initialize
      end

      # :nodoc:
      def self.parse(parser : Parser) : Tuple(Track, NextState)
        ret = Track.new

        if tn = parser.readToken
          trackNum = tn.to_u32? || raise ParseError.new("Bad track number", parser)
          if trackNum == 0 || trackNum > 99
            raise ParseError.new("Invalid track number, must be between 1 and 99, inclusive", parser)
          end
          ret.trackNumber = trackNum
        else
          raise ParseError.new("Bad TRACK command", parser)
        end

        if newType = parser.readToken
          ret.type = Type.parse?(newType) || raise ParseError.new("Bad TRACK type", parser)
        else
          raise ParseError.new("TRACK command is missing its type", parser)
        end

        token : String? = nil
        line : String? = nil
        afterTrack : Bool = false
        afterIndex : Bool = false
        lastIndex : Int64 = -1

        while token = parser.readToken
          case token
          when "REM" then parser.skipToEof
          when "CATALOG" then return {ret, NextState::Catalog}
          when "CDTEXTFILE" then return {ret, NextState::CdTextFile}
          when "FILE" then return {ret, NextState::File}
          when "TRACK" then return {ret, NextState::Track}

          when "PREGAP"
            if afterIndex
              raise ParseError.new("PREGAP command must come after a TRACK command and before INDEX commands",
                                   parser)
            end
            ret.pregap = Timestamp.parse(parser)

          when "POSTGAP"
            if afterIndex
              raise ParseError.new("POSTGAP command must come after a TRACK command and before INDEX commands",
                                   parser)
            end
            ret.postgap = Timestamp.parse(parser)

          when "FLAGS"
            if afterIndex
              raise ParseError.new("FLAGS command must come after a TRACK command and before INDEX commands",
                                   parser)
            end

            line = parser.readRemainingLine
            if line
              flagLine : String = line.strip.upcase
              flags = flagLine.split(' ', remove_empty: true)
              if flags.empty?
                raise ParseError.new("FLAGS is missing its flags", parser)
              else
                flags.each do |flag|
                  if flg = Flags.parse?(flag)
                    ret.flags |= flg
                  elsif parser.strict?
                    raise ParseError.new("Unrecognized FLAG: #{flag}", parser)
                  end
                end
              end
            else
              raise ParseError.new("FLAGS line is blank", parser)
            end

          when "ISRC"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize == ISRC_LEN
                if line[0..5].chars.all?(&.ascii_alphanumeric?) && line[6..].chars.all?(&.ascii_number?)
                  ret.isrc = line
                else
                  raise ParseError.new("ISRC is malformed", parser)
                end
              else
                raise ParseError.new("ISRC is not #{ISRC_LEN} bytes long", parser)
              end
            else
              raise ParseError.new("ISRC line is blank", parser)
            end

          when "INDEX"
            token = parser.readToken || raise ParseError.new("Malformed INDEX line", parser)
            num : UInt32 = token.to_u32? || raise ParseError.new("Bad INDEX number", parser)
            timestamp = Timestamp.parse(parser)

            # Check the value.
            if num > 99
              raise ParseError.new("Bad INDEX number, must be between 0 and 99, inclusive", parser)
            elsif ret.index?(num)
              raise ParseError.new("Duplicate INDEX number: #{num}", parser)
            elsif num <= lastIndex
              if num == 0 && lastIndex == -1
                lastIndex = 0
              elsif num == 1 && lastIndex == -1
                lastIndex = 1
              elsif num != lastIndex + 1
                raise ParseError.new("INDEX numbers must be sequential", parser)
              end
            end

            # Store
            ret.setIndex(num, timestamp)
            afterIndex = true
            lastIndex = num.to_i64!

          when "TITLE"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize >= MIN_TITLE_LEN && line.bytesize <= MAX_TITLE_LEN
                ret.title = line
              else
                raise Error.new("TITLE field must be between #{MIN_TITLE_LEN} and " \
                                "#{MAX_TITLE_LEN} bytes, inclusive")
              end
            else
              raise ParseError.new("TITLE line is blank", parser)
            end

          when "PERFORMER"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize >= MIN_PERFORMER_LEN && line.bytesize <= MAX_PERFORMER_LEN
                ret.performer = line
              else
                raise Error.new("PERFORMER field must be between #{MIN_PERFORMER_LEN} and " \
                                "#{MAX_PERFORMER_LEN} bytes, inclusive")
              end
            else
              raise ParseError.new("PERFORMER line is blank", parser)
            end

          when "SONGWRITER"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize >= MIN_SONGWRITER_LEN && line.bytesize <= MAX_SONGWRITER_LEN
                ret.songwriter = line
              else
                raise Error.new("SONGWRITER field must be between #{MIN_SONGWRITER_LEN} and " \
                                "#{MAX_SONGWRITER_LEN} bytes, inclusive")
              end
            else
              raise ParseError.new("SONGWRITER line is blank", parser)
            end

          else
            if parser.strict?
              raise ParseError.new("Unknown CUE sheet command in TRACK section: #{token}", parser)
            else
              parser.skipToEof
            end
          end
        end

        {ret, NextState::Normal}
      end

      # Gets the `Timestamp` for the `INDEX` *num*.
      #
      # If *num* is not within 0 and 99 (inclusive), this will raise an
      # `::ArgumentError`.  If the index has not been set yet, this will raise a
      # `KeyError`.
      def index(num : Int) : Timestamp
        if num < 0 || num > 99
          raise ::ArgumentError.new("Invalid number value for an INDEX (must be between 0 and 99, inclusive)")
        end
        @indices[num.to_u32!]
      end

      # Gets the `Timestamp` for the `INDEX` *num*.
      #
      # If *num* is not within 0 and 99 (inclusive), this will raise an
      # `::ArgumentError`.  If the index has not been set yet, this returns
      # `nil`.
      def index?(num : Int) : Timestamp?
        if num < 0 || num > 99
          raise ::ArgumentError.new("Invalid number value for an INDEX (must be between 0 and 99, inclusive)")
        end
        @indices[num.to_u32!]?
      end

      # Sets the `Timestamp` for the `INDEX` *num*.  Any existing `Timestamp`
      # for that index will be overwritten.
      #
      # If *num* is not within 0 and 99 (inclusive), this will raise an
      # `::ArgumentError`.
      def setIndex(num : Int, ts : Timestamp) : self
        if num < 0 || num > 99
          raise ::ArgumentError.new("Invalid number value for an INDEX (must be between 0 and 99, inclusive)")
        end
        @indices[num.to_u32!] = ts
        self
      end

      def trackNumber=(value : Int) : Nil
        if value == 0 || value > 99
          raise ::ArgumentError.new("Invalid track number, must be between 1 and 99, inclusive")
        end
        @trackNumber = value.to_u32!
      end

      # Sets the
      # [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
      # value.  The value must be exactly `ISRC_LEN` _bytes_ long.
      def isrc=(value : String?) : Nil
        if value && value.bytesize != ISRC_LEN
          raise Error.new("ISRC field must be exactly #{ISRC_LEN} bytes")
        end
        @isrc = value
      end

      # Sets the name of the title for this track.  The value must be
      # between `MIN_TITLE_LEN` and `MAX_TITLE_LEN` _bytes_ long.
      def title=(value : String?) : Nil
        if value
          bsize : Int32 = value.bytesize
          if bsize < 1 || bsize > 80
            raise Error.new("TITLE field must be between #{MIN_TITLE_LEN} and " \
                            "#{MAX_TITLE_LEN} bytes, inclusive")
          end
        end
        @title = value
      end

      # Sets the name of the performer for this track.  The value must be
      # between `MIN_PERFORMER_LEN` and `MAX_PERFORMER_LEN` _bytes_ long.
      def performer=(value : String?) : Nil
        if value
          bsize : Int32 = value.bytesize
          if bsize < 1 || bsize > 80
            raise Error.new("PERFORMER field must be between #{MIN_PERFORMER_LEN} and " \
                            "#{MAX_PERFORMER_LEN} bytes, inclusive")
          end
        end
        @performer = value
      end

      # Sets the name of the songwriter for this track.  The value must be
      # between `MIN_SONGWRITER_LEN` and `MAX_SONGWRITER_LEN` _bytes_ long.
      def songwriter=(value : String?) : Nil
        if value
          bsize : Int32 = value.bytesize
          if bsize < 1 || bsize > 80
            raise Error.new("SONGWRITER field must be between #{MIN_SONGWRITER_LEN} and " \
                            "#{MAX_SONGWRITER_LEN} bytes, inclusive")
          end
        end
        @songwriter = value
      end

      def to_s(io : IO) : Nil
        io << sprintf("TRACK %02d %s", @trackNumber, @type)
      end

      # Similar to `#to_s`, except this is properly indented for a CUE sheet and
      # includes all relevant lines.
      def write(io : IO) : Nil
        io << "  " << self << '\n'
        unless flags.none?
          Flags.values.each do |flg|
            if flags.includes?(flg)
              io << "    FLAGS " << flg << '\n'
            end
          end
        end

        if str = @isrc
          io << "    ISRC " << str << '\n'
        end

        if str = @title
          io << "    TITLE \"" << str << "\"\n"
        end

        if str = @performer
          io << "    PERFORMER \"" << str << "\"\n"
        end

        if str = @songwriter
          io << "    SONGWRITER \"" << str << "\"\n"
        end

        if gap = @pregap
          io << "    PREGAP " << gap << '\n'
        end

        if gap = @postgap
          io << "    PREGAP " << gap << '\n'
        end

        @indices.each do |key, val|
          io << sprintf("    INDEX %02d ", key) << val << '\n'
        end
      end
    end

    #===========================================================================

    # A virtual representation of the data for a `FILE` command within a CUE
    # sheet.  Note that in a CUE sheet, a single file can be used for multiple
    # tracks.
    class File
      # The type of this file.
      enum Type
        # Raw little-endian data.
        Binary

        # Raw big-endian data.
        Motorola

        # 16-bit 44.1 KHz AIFF PCM data.
        Aiff

        # 16-bit 44.1 KHz WAVE PCM data.
        Wave

        # 16-bit stereo 44.1 KHz MP3 data.
        Mp3

        # 16-bit stereo 44.1 KHz FLAC data.
        Flac

        # Similar to `::Enum.parse?`, except that this expects the strings to
        # match those in a CUE file (e.g. `"BINARY"`, `"MOTOROLA"`, etc.), and
        # is case insensitive.
        def self.parse?(string : String) : self?
          case string.upcase
          when "BINARY" then Type::Binary
          when "MOTOROLA" then Type::Binary
          when "AIFF" then Type::Binary
          when "WAVE" then Type::Binary
          when "MP3" then Type::Binary
          when "FLAC" then Type::Binary
          else nil
          end
        end

        # Similar to `::Enum#to_s`, except that the returned values are usable in
        # a CUE file.
        def to_s : String
          case self
          in .binary? then "BINARY"
          in .motorola? then "MOTOROLA"
          in .aiff? then "AIFF"
          in .wave? then "WAVE"
          in .mp3? then "MP3"
          in .flac? then "FLAC"
          end
        end

        # Similar to `::Enum.names`, except that the returned values match those
        # generated with `#to_s`.
        def self.names : Array(String)
          [
            "BINARY",
            "MOTOROLA",
            "AIFF",
            "WAVE",
            "MP3",
            "FLAC"
          ]
        end
      end

      # The associated filename.
      property filename : String = ""

      # The type of file.
      property type : Type = Type::Wave

      # The tracks that this file is used for to define.
      property tracks : Array(Track) = [] of Track

      # Creates a new `RemiAudio::Cue::File` instance.
      def initialize
      end

      # :nodoc:
      def self.parse(parser : Parser) : Tuple(RemiAudio::Cue::File, NextState)
        ret : RemiAudio::Cue::File = RemiAudio::Cue::File.new
        nxtState : NextState = NextState::Normal
        token : String? = nil
        lastTrackNum : Int64 = 0

        fileLine : String? = parser.readRemainingLine || raise ParseError.new("Incomplete FILE line", parser)
        args = parser.splitArgs(fileLine)
        unless args.size == 2
          raise ParseError.new("Bad FILE command, found #{args.size} arg#{args.size == 1 ? "" : "s"}, expected 2", parser)
        end

        ret.filename = args[0]
        ret.type = Type.parse?(args[1]) || raise ParseError.new("Invalid type for FILE command", parser)

        loop do
          token = case nxtState
                  in .normal? then parser.readToken
                  in .file? then "FILE"
                  in .track? then "TRACK"
                  in .catalog?, .cd_text_file? then return {ret, nxtState}
                  end
          break if token.nil?
          nxtState = NextState::Normal

          case token
          when "REM" then parser.skipToEof
          when "FILE" then return {ret, NextState::File}
          when "CATALOG" then return {ret, NextState::Catalog}
          when "CDTEXTFILE" then return {ret, NextState::CdTextFile}

          when "TRACK"
            newTrack, nxtState = Track.parse(parser)
            ret.tracks << newTrack
            lastTrackNum = newTrack.trackNumber.to_i64!
            parser.foundTrack = true

          else
            if parser.strict?
              raise ParseError.new("Unknown CUE sheet command in FILE section: #{token}", parser)
            else
              parser.skipToEof
            end
          end
        end

        {ret, NextState::Normal}
      end

      def to_s(io : IO) : Nil
        io << "FILE \"" << @filename << "\" " << @type
      end

      # Similar to `#to_s`, except this is properly indented for a CUE sheet and
      # includes all relevant lines.
      def write(io : IO) : Nil
        io << self << '\n'
        @tracks.each(&.write(io))
      end

      # Creates a new `Track` and yields it to the block.  When the block exits,
      # the new track is added to this `RemiAudio::Cue::File`.  The new track is returned.
      def addTrack(&) : Track
        trk = Track.new
        yield trk
        @tracks << trk
        trk
      end
    end

    #===========================================================================

    # The "Media Catalog Number" for this CUE sheet.  This is generally a UPC or
    # EAN code.
    getter catalog : String?

    # The path to an external file that contains CD-TEXT information for this
    # CUE sheet.
    property cdTextFile : String?

    # The title of this CUE sheet.
    getter title : String?

    # The performer of this CUE sheet.
    getter performer : String?

    # The songwriter of this CUE sheet.
    getter songwriter : String?

    # The `RemiAudio::Cue::File`s for this CUE sheet.
    property files : Array(RemiAudio::Cue::File) = [] of RemiAudio::Cue::File

    # The expected length of the CATALOG field, in bytes.
    CATALOG_LEN = 13

    # The maximum length of the TITLE field, in bytes.
    MAX_TITLE_LEN = 80

    # The minimum length of the TITLE field, in bytes.
    MIN_TITLE_LEN = 1

    # The maximum length of the PERFORMER field, in bytes.
    MAX_PERFORMER_LEN = 80

    # The minimum length of the PERFORMER field, in bytes.
    MIN_PERFORMER_LEN = 1

    # The maximum length of the SONGWRITER field, in bytes.
    MAX_SONGWRITER_LEN = 80

    # The minimum length of the SONGWRITER field, in bytes.
    MIN_SONGWRITER_LEN = 1

    # Creates a new, blank `Cue` instance.
    def initialize
    end

    # Creates a new `Cue` instance by parsing data from *io*.  If *strict* is
    # `true`, then certain restrictions are in place for the following cases:
    #
    # * Unrecognized commands in the `FILE` section will not be accepted.
    # * Unrecognized commands in the `TRACK` section will not be accepted.
    # * Unrecognized `FLAGS` on a FLAG line within a `TRACK` will not be accepted.
    #
    # When *strict* is `false`, then these cases are silently ignored.
    def self.parse(io : IO, *, strict : Bool = false) : Cue
      ret = Cue.new
      parser = Parser.new(io)
      token : String? = nil
      nxtState : NextState = NextState::Normal

      parser.strict = strict
      loop do
        token = case nxtState
                in .normal? then parser.readToken
                in .file? then "FILE"
                in .track? then "TRACK"
                in .catalog? then "CATALOG"
                in .cd_text_file?  then "CDTEXTFILE"
                end
        break if token.nil?
        nxtState = NextState::Normal

        case token
        when "REM" then parser.skipToEof

        when "FILE"
          # Parse new FILE command
          newFile, nxtState = RemiAudio::Cue::File.parse(parser)
          ret.files << newFile

        when "CATALOG"
          token = parser.readToken
          if token
            unless token.size == CATALOG_LEN
              raise ParseError.new("CATALOG field must be exactly #{CATALOG_LEN} bytes", parser)
            end

            unless token.chars.all?(&.ascii_number?)
              raise ParseError.new("CATALOG field must be all numbers", parser)
            end

            if ret.catalog.nil?
              ret.catalog = token
            else
              raise ParseError.new("CATALOG field can only appear once", parser)
            end
          else
            raise ParseError.new("CATALOG field is blank", parser)
          end

        when "TITLE"
          token = parser.readRemainingLine
          if token
            token = token.strip
            if token.bytesize >= MIN_TITLE_LEN && token.bytesize <= MAX_TITLE_LEN

              ret.title = token
            else
              raise Error.new("TITLE field must be between #{MIN_TITLE_LEN} and " \
                              "#{MAX_TITLE_LEN} bytes, inclusive")
            end
          else
            raise ParseError.new("TITLE line is blank", parser)
          end

        when "PERFORMER"
          token = parser.readRemainingLine
          if token
            token = token.strip
            if token.bytesize >= MIN_PERFORMER_LEN && token.bytesize <= MAX_PERFORMER_LEN

              ret.performer = token
            else
              raise Error.new("PERFORMER field must be between #{MIN_PERFORMER_LEN} and " \
                              "#{MAX_PERFORMER_LEN} bytes, inclusive")
            end
          else
            raise ParseError.new("PERFORMER line is blank", parser)
          end

        when "SONGWRITER"
          token = parser.readRemainingLine
          if token
            token = token.strip
            if token.bytesize >= MIN_SONGWRITER_LEN && token.bytesize <= MAX_SONGWRITER_LEN
              ret.songwriter = token
            else
              raise Error.new("SONGWRITER field must be between #{MIN_SONGWRITER_LEN} and " \
                              "#{MAX_SONGWRITER_LEN} bytes, inclusive")
            end
          else
            raise ParseError.new("SONGWRITER line is blank", parser)
          end

        when "CDTEXTFILE"
          token = parser.readRemainingLine(true) || raise ParseError.new("CDTEXTFILE line is incomplete", parser)
          ret.cdTextFile = token

        else
          raise ParseError.new("Unknown toplevel CUE sheet command: #{token}", parser)
        end
      end

      # There must be at least one track in the CUE sheet.
      unless parser.foundTrack?
        raise ParseError.new("No TRACKs found in the CUE sheet", parser)
      end

      unless ret.sortAndCheckTracks
        raise ParseError.new("Tracks are not sequential or duplicate track numbers found.", parser)
      end

      ret
    end

    # Creates a new `Cue` instance by parsing data from the given string.
    #
    # See `.parse(io : IO, *, strict : Bool = false)` for information about the
    # *strict* parameter.
    def self.parse(string : String, *, strict : Bool = false) : Cue
      io = IO::Memory.new(string, strict: strict)
      parse(io)
    end

    # Creates a new `Cue` instance by loading and parsing the specified file.
    #
    # See `.parse(io : IO, *, strict : Bool = false)` for information about the
    # *strict* parameter.
    def self.load(filename : Path|String, *, strict : Bool = false) : Cue
      ::File.open(filename, "r") { |file| parse(file, strict: strict) }
    end

    # Sets the "Media Catalog Number" for this CUE sheet.  This is generally a
    # UPC or EAN code.  This must be exactly `CATALOG_LEN` _bytes_ in length.
    def catalog=(value : String) : Nil
      unless value.bytesize == CATALOG_LEN
        raise Error.new("CATALOG field must be exactly #{CATALOG_LEN} bytes")
      end
      @catalog = value
    end

    # Sets the name of the title for this track.  The value must be between
    # `MIN_TITLE_LEN` and `MAX_TITLE_LEN` _bytes_ long.
    def title=(value : String?) : Nil
      if value
        bsize : Int32 = value.bytesize
        if bsize < 1 || bsize > 80
          raise Error.new("TITLE field must be between 1 and 80 bytes, inclusive")
        end
      end
      @title = value
    end

    # Sets the name of the performer for this track.  The value must be between
    # `MIN_PERFORMER_LEN` and `MAX_PERFORMER_LEN` _bytes_ long.
    def performer=(value : String?) : Nil
      if value
        bsize : Int32 = value.bytesize
        if bsize < 1 || bsize > 80
          raise Error.new("PERFORMER field must be between 1 and 80 bytes, inclusive")
        end
      end
      @performer = value
    end

    # Sets the name of the songwriter for this track.  The value must be between
    # `MIN_SONGWRITER_LEN` and `MAX_SONGWRITER_LEN` _bytes_ long.
    def songwriter=(value : String?) : Nil
      if value
        bsize : Int32 = value.bytesize
        if bsize < 1 || bsize > 80
          raise Error.new("SONGWRITER field must be between 1 and 80 bytes, inclusive")
        end
      end
      @songwriter = value
    end

    # Writes this CUE sheet to *io*.  This will automatically call
    # `sortAndCheckTracks` before writing any data.
    def write(io : IO) : Nil
      raise Error.new("CUE sheet has no files") if @files.empty?
      unless sortAndCheckTracks
        raise Error.new("Tracks are not sequential or duplicate track numbers found.")
      end

      if str = @catalog
        io << "CATALOG #{str}\n"
      end

      if str = @title
        io << "TITLE \"" << str << "\"\n"
      end

      if str = @performer
        io << "PERFORMER \"" << str << "\"\n"
      end

      if str = @songwriter
        io << "SONGWRITER \"" << str << "\"\n"
      end

      @files.each(&.write(io))
    end

    # Writes this CUE sheet to a string and returns it.  This will automatically
    # call `sortAndCheckTracks` before writing any data.
    def write : String
      String.build { |str| write(str) }
    end

    # Sorts all `RemiAudio::Cue::File#tracks` in all `#files`, then attempts to
    # sort `#files` according to their tracks, then ensures that that all of the
    # tracks are in sequential order.  If the tracks are not sequential after
    # sorting, or there are duplicates, this returns `false`.  Otherwise it
    # returns `true`.
    def sortAndCheckTracks : Bool
      # Sort all tracks in all @files.  We do this separately so that
      # @files.sort! doesn't continuously try to re-sort already sorted arrays
      # of tracks.
      @files.each do |file|
        file.tracks.sort! { |trk1, trk2| trk1.trackNumber <=> trk2.trackNumber }
      end

      # Sort @files according to the tracks for each file.
      @files.sort! do |file1, file2|
        max1 = file1.tracks.max_by(&.trackNumber).trackNumber
        max2 = file2.tracks.max_by(&.trackNumber).trackNumber
        max1 <=> max2
      end

      # Check that all tracks are sequential.
      lastIndex : UInt32 = @files[0].tracks[0].trackNumber - 1
      @files.each do |file|
        file.tracks.each do |trk|
          return false if trk.trackNumber != lastIndex + 1
          lastIndex = trk.trackNumber
        end
      end
      true
    end

    # Creates a new `RemiAudio::Cue::File` and yields it to the block.  When the
    # block exits, the new file is added to this `Cue`.  The new file is
    # returned.
    def addFile(&) : File
      file = File.new
      yield file
      @files << file
      file
      end
  end
end