Midifile View on GitHub

Fixing track chunk byte counts

home   »   documentation   »   tutorials

Fix Standard MIDI File track chunk byte counts. MIDI track chunk byte counts are often incorrect in Standard MIDI Files. This example program shows how to correct byte counts by reading a MIDI file and then writing it out again, without doing anything else to automatically fix the track chunk sizes. The MidiFile class ignores the byte-count value in track chunk headers when reading a MIDI file, so incorrect byte counts do not affect parsing of the file. When writing a file out again, the byte count for each track is calculated and automatically corrected. Note that the MidiFile class usually expands running-status messages, so the size of the MIDI file may change from the original size. Also note that this example overwrites the old file contents. To ensure that there was not a problem reading the file, the MidiFile::status function is checked to see if the parsing of the input data was successful.
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
#include "MidiFile.h"
#include "Options.h"
#include <iostream>
using namespace std;

int main(int argc, char** argv) {

   Options options;
   options.process(argc, argv);
   if (options.getArgCount() < 1) {
      cerr << "Usage: " << options.getCommand() << " input(s)\n";
      exit(1);
   }

   MidiFile midifile;
   for (int i=1; i<options.getArgCount(); i++ ) {
      midifile.read(options.getArg(i));
      if (midifile.status()) {
         midifile.write(options.getArg(i));
      } else {
         cerr << "Error reading MIDI file: " << options.getArg(i) << endl;
      }
   }

   return 0;
}
Library functions used in this example:
  • MidiFile::read
  • MidiFile::status
  • MidiFile::write
  • Options::getArg
  • Options::getArgCount
  • Options::getCommand
  • Options::process