Debian Codegraph @

scripts/misc/ipf_align.py

raw symbols SCIP
1 # ipf_align.py
2 #
3 # Align all tracks in an IPF image to the same offset from index mark.
4 #
5 # Written & released by Keir Fraser <[email protected]>
6 #
7 # This is free and unencumbered software released into the public domain.
8 # See the file COPYING for more details, or visit <http://unlicense.org>.
9
10 import struct, sys, crcmod.predefined
11
12 def main(argv):
13 crc32 = crcmod.predefined.Crc('crc-32')
14 offset = 1024
15 if len(argv) == 4:
16 offset = int(argv[3])
17 elif len(argv) != 3:
18 print("%s <input_file> <output_file> [<offset>]" % argv[0])
19 return
20 with open(argv[1], "rb") as f:
21 in_dat = bytearray(f.read())
22 out_dat = bytearray()
23 while in_dat:
24 # Decode the common record header
25 id, length, crc = struct.unpack(">4s2I", in_dat[:12])
26 # Consume the record from the input array
27 record = in_dat[:length]
28 in_dat = in_dat[length:]
29 # Check the CRC
30 record[8:12] = bytes(4)
31 assert crc == crc32.new(record).crcValue, "CRC mismatch"
32 # Modify the record as necessary
33 if id == b'IMGE':
34 trkbits, = struct.unpack(">I", record[48:52])
35 if trkbits > offset:
36 record[32:40] = struct.pack(">2I", offset//8, offset)
37 # Re-calculate the CRC
38 record[8:12] = struct.pack(">I", crc32.new(record).crcValue)
39 # DATA chunk has extra data to copy
40 if id == b'DATA':
41 size, bsize, dcrc, datchunk = struct.unpack(">4I", record[12:28])
42 record += in_dat[:size]
43 in_dat = in_dat[size:]
44 # Write the full modified record into the output array
45 out_dat += record
46 with open(argv[2], "wb") as f:
47 f.write(out_dat)
48
49 if __name__ == "__main__":
50 main(sys.argv)