All files / src/mod song.ts

100% Statements 90/90
85.71% Branches 6/7
100% Functions 9/9
100% Lines 81/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                         1x     1x 1x 1x 1x 1x 1x 1x 31x   1x   205x   1x       1x 31x 31x   31x   1x       33x 33x 33x 33x 33x 33x 33x 33x   33x 33x   33x 33x     33x 33x     33x 33x 33x               2x 2x 2x 4x 4x 256x 256x     1024x 1024x 1024x 1024x 1024x 1024x     1024x 1024x 1024x 1024x                   256x   4x   2x     1x 1x 1x 128x   1x     1x 1x 1x     1x 1x 1x 1x 4x   1x     1x 1x 1x 1x 10x 1x 9x   1x     1x                                                        
import { BinaryFile } from '../io/file';
import { ModType, Note, NoteTable, Pattern, Row, Sample, Song } from './types';
 
/* =================================================================
https://www.aes.id.au/modformat.html
 
Protracker 1.1B Song/Module Format:
-----------------------------------
 
Offset  Bytes  Description
------  -----  -----------
   0     20    Songname. Remember to put trailing null bytes at the end...
 
Information for sample 1-31:
 
Offset  Bytes  Description
------  -----  -----------
  20     22    Samplename for sample 1. Pad with null bytes.
  42      2    Samplelength for sample 1. Stored as number of words.
               Multiply by two to get real sample length in bytes.
  44      1    Lower four bits are the finetune value, stored as a signed
               four bit number. The upper four bits are not used, and
               should be set to zero.
               Value:  Finetune:
                 0        0
                 1       +1
                 2       +2
                 3       +3
                 4       +4
                 5       +5
                 6       +6
                 7       +7
                 8       -8
                 9       -7
                 A       -6
                 B       -5
                 C       -4
                 D       -3
                 E       -2
                 F       -1
 
  45      1    Volume for sample 1. Range is $00-$40, or 0-64 decimal.
  46      2    Repeat point for sample 1. Stored as number of words offset
               from start of sample. Multiply by two to get offset in bytes.
  48      2    Repeat Length for sample 1. Stored as number of words in
               loop. Multiply by two to get replen in bytes.
 
  Information for the next 30 samples starts here. It's just like the info for
  sample 1.
 
Offset  Bytes  Description
------  -----  -----------
  50     30    Sample 2...
  80     30    Sample 3...
   .
   .
   .
 890     30    Sample 30...
 920     30    Sample 31...
 
Offset  Bytes  Description
------  -----  -----------
 950      1    Songlength. Range is 1-128.
 951      1    Well... this little byte here is set to 127, so that old
               trackers will search through all patterns when loading.
               Noisetracker uses this byte for restart, but we don't.
 952    128    Song positions 0-127. Each hold a number from 0-63 that
               tells the tracker what pattern to play at that position.
1080      4    The four letters "M.K." - This is something Mahoney & Kaktus
               inserted when they increased the number of samples from
               15 to 31. If it's not there, the module/song uses 15 samples
               or the text has been removed to make the module harder to
               rip. Startrekker puts "FLT4" or "FLT8" there instead.
 
Offset  Bytes  Description
------  -----  -----------
1084    1024   Data for pattern 00.
   .
   .
   .
xxxx  Number of patterns stored is equal to the highest patternnumber
      in the song position table (at offset 952-1079).
 
Each note is stored as 4 bytes, and all four notes at each position in
the pattern are stored after each other.
 
00 -  chan1  chan2  chan3  chan4
01 -  chan1  chan2  chan3  chan4
02 -  chan1  chan2  chan3  chan4
etc.
 
Info for each note:
 
 _____byte 1_____   byte2_    _____byte 3_____   byte4_
/                \ /      \  /                \ /      \
0000          0000-00000000  0000          0000-00000000
 
Upper four    12 bits for    Lower four    Effect command.
bits of sam-  note period.   bits of sam-
ple number.                  ple number.
 
Periodtable for Tuning 0, Normal
  C-1 to B-1 : 856,808,762,720,678,640,604,570,538,508,480,453
  C-2 to B-2 : 428,404,381,360,339,320,302,285,269,254,240,226
  C-3 to B-3 : 214,202,190,180,170,160,151,143,135,127,120,113
 
To determine what note to show, scan through the table until you find
the same period as the one stored in byte 1-2. Use the index to look
up in a note names table.
 
This is the data stored in a normal song. A packed song starts with the
four letters "PACK", but i don't know how the song is packed: You can
get the source code for the cruncher/decruncher from us if you need it,
but I don't understand it; I've just ripped it from another tracker...
 
In a module, all the samples are stored right after the patterndata.
To determine where a sample starts and stops, you use the sampleinfo
structures in the beginning of the file (from offset 20). Take a look
at the mt_init routine in the playroutine, and you'll see just how it
is done.
 
- Lars "ZAP" Hamre/Amiga Freelancers
 
~~ After the pattern data ~~
(Data repeated for each sample:)
xxxxxx    The maximum size of a sample is 65535 words. Each sample is
          stored as a collection of bytes (length of a sample was given
          previously in the module). Each byte is a signed value (-128
          ..127) which is the channel data. When a sample is played at a
          pitch of C2 (see below for pitches), about 8287 bytes of
          sample data are sent to the channel per second. Multiply the
          rate by the twelfth root of 2 (=1.0595) for each semitone
          increase in pitch eg. moving the pitch up 1 octave doubles the
          rate. The data is stored in the order it is played (eg. first
          byte is first byte played). The first word of the sample data
          is used to hold repeat information, and will overwrite any
          sample data that is there (but it is probably safer to set it
          to 0).
          The rate given above (8287) conveys an inaccurate picture of
          the module-format - in reality it is different for different
          Amigas. As the routines for playing were written to run off
          certain interrupts, for different Amiga computers the rate to
          send data to the channel will be different. For PAL machines
          the clock rate is 7093789.2 Hz and for NTSC machines it is
          7159090.5 Hz. When the clock rate is divided by twice the
          period number for the pitch it will give the rate to send the
          data to the channel, eg. for a PAL machine sending a note at
          C2 (period 428), the rate is 7093789.2/856 ~= 8287.1369
(Each sample is stored sequentially)
 
---------
M.K. - standard 4-channel, 64-pattern-max MOD.
M!K! - ProTracker will write this if there's more than 64 patterns,
6CHN, 8CHN - 6-channel and 8-channel MODs, respectively. These are common extensions, and many trackers will write these. Basically, you read like a 4 channel mod, but with 6 or 8 channels per row.
CD81, OKTA, OCTA - other 8-channel MOD tags. First two are probably Oktalyzer for the Atari ST, the third is possibly OctaMED.
xxCH - a 10+ channel MOD, xx being a decimal number. FastTracker will deal with these as long as x is an even number no greater than 32.
2CHN - a 2 channel MOD. This is handled by FastTracker.
xxCN - another 10+ channel MOD, xx being a decimal number. Allegedly TakeTracker writes these.
TDZ1, TDZ2, TDZ3 - allegedly this is a TakeTracker extension for 1, 2, and 3 channels respectively.
5CHN, 7CHN, 9CHN - allegedly this is a TakeTracker extension for 5, 7, and 8 channels respectively.
FLT4 - StarTrekker 4-channel MOD.
FLT8 - StarTrekker 8-channel MOD. Load patterns in like a normal 4-channel MOD, and then play two patterns at the same time (e.g. if 8 appears on the order list, play patterns 8 and 9). You'd probably be best to merge the patterns together if you want to be consistent.
M&K! - only sighted on echobea3.mod so far. This is just a standard MOD, but with a weird tag. I (GreaseMonkey) cannot find the tracker it's referring to ("fleg's module train-er"), so it was probably only used once or something, and never released.
- M.K. means 31 samples, blank means 15... others?
================================================================= */
 
export class MOD {
 
  private data: BinaryFile;
 
  constructor(data: ArrayBuffer) {
    this.data = new BinaryFile(data);
  }
 
  song(): Song {
    const s = {} as Song;
 
    s.title = this.name();
    s.length = this.songLength();
    s.type = this.type();
    s.positions = this.positionTable();
    s.samples = [];
    for (let i = 0; i < 31; i++) {
      s.samples.push(this.sample(i));
    }
 
    s.sampleBuffers = [];
    // So lazy...
    const sorted = [...s.positions].sort((a, b) => b - a);
    // Read all the patter data we are using
    s.patterns = this.patterns(sorted[0] + 1);
 
    // After the pattern data is where the sample data is
    // stored
    // The maximum size of a sample is 65535 words. (Played at C2)
    for (let q = 0; q < s.samples.length; q++) {
      const samp = s.samples[q];
      const audioData = this.data.readSBytes(samp.length);
      // console.log(samp, audioData.length.toString(16));
      s.sampleBuffers.push(audioData)
    }
 
    return s;
  }
 
  /** Get sample information (0 based. 0 = sample 1) */
  sample(w: number = 0): Sample {
    const sample = {} as Sample;
 
    const start = 20 + (w * 30);
    this.data.seek(start);
 
    const name = this.data.readCString();
    sample.name = name;
 
    this.data.seek(start + 22);
    const len = this.data.readUInt16(false);
    sample.length = len * 2;
 
    // this.data.seek(start + 24);
    const ft = this.data.readInt8();
    sample.fineTune = (ft & 0x0F) >> 1;
 
    // this.data.seek(start + 25);
    const vol = this.data.readUInt8();
    sample.volume = vol / 64;
 
    // this.data.seek(start + 26);
    // stored as words
    const rptp = this.data.readUInt16(false);
    sample.repeatPoint = rptp * 2;
 
    // this.data.seek(start + 28);
    // stored as words
    const rptl = this.data.readUInt16(false);
    sample.repeatLength = rptl * 2;
 
    return sample;
  }
 
  /**
   * Load all the patterns into the pattern structure. Note you need
   * to know the total number of patters in the file which can be found
   * in the highest number in the pattern table.
   */
  patterns(num: number, patternlen = 64, channels = 4): Pattern[] {
    this.data.seek(1084);
 
    const patterns: Pattern[] = new Array<Pattern>(num);
 
    for (let p = 0; p < num; p++) {
      const pattern = new Array<Row>(patternlen);
 
      for (let rows = 0; rows < patternlen; rows++) {
        const row = new Array<Note>(channels);
 
        for (let channel = 0; channel < channels; channel++) {
          // Each note is stored in 4 bytes
          // flipping endian for ease
          const uf_np = this.data.readUInt16(false);
          const lf_ec = this.data.readUInt16(false);
 
          const upperSample = (uf_np >> 12) & 0xF;
          const period = (uf_np & 0x0FFF);
          const lowerSample = (lf_ec >> 12) & 0xF;
          const sample = (upperSample << 4) | lowerSample;
 
          // The effect is stored [c][x][y] where each part
          // is a nibble
          const effect = (lf_ec & 0x0F00) >> 8;
          const eargX = (lf_ec & 0x00F0) >> 4;
          const eargY = (lf_ec & 0x000F);
 
          row[channel] = {
            note: period ? NoteTable.get(period) : "",
            sample: sample,
            effect: {
              command: effect,
              argX: eargX,
              argY: eargY,
            }
          } as Note;
        }
        pattern[rows] = row;
      }
      patterns[p] = pattern;
    }
 
    return patterns;
  }
 
  private positionTable() {
    const t = [];
    this.data.seek(952);
    for (let i = 0; i < 128; i++) {
      t.push(this.data.readUInt8());
    }
    return t;
  }
 
  private songLength() {
    this.data.seek(950);
    const len = this.data.readUInt8();
    return len;
  }
 
  private type(): ModType {
    this.data.seek(1080);
    const tbytes = this.data.readChars(4);
    const str = [];
    for (let z = 0; z < 4; z++) {
      str.push(String.fromCharCode(tbytes[z]))
    }
    return str.join('') as ModType;
  }
 
  private name(): string {
    this.data.seek(0);
    const bytes = this.data.readChars(20);
    const str = [];
    for (let z = 0; z < bytes.length; z++) {
      if (bytes[z] === 0x0) break;
      str.push(String.fromCharCode(bytes[z]))
    }
    return str.join('');
  }
}