scp.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # greaseweazle/image/scp.py
  2. #
  3. # Written & released by Keir Fraser <keir.xen@gmail.com>
  4. #
  5. # This is free and unencumbered software released into the public domain.
  6. # See the file COPYING for more details, or visit <http://unlicense.org>.
  7. import struct, functools
  8. from greaseweazle import error
  9. from greaseweazle.flux import Flux
  10. from .image import Image
  11. class SCPOpts:
  12. """legacy_ss: Set to True to generate (incorrect) legacy single-sided
  13. SCP image.
  14. """
  15. def __init__(self):
  16. self.legacy_ss = False
  17. class SCPTrack:
  18. def __init__(self, tdh, dat, splice=None):
  19. self.tdh = tdh
  20. self.dat = dat
  21. self.splice = splice
  22. class SCP(Image):
  23. # 40MHz
  24. sample_freq = 40000000
  25. def __init__(self):
  26. self.opts = SCPOpts()
  27. self.nr_revs = None
  28. self.to_track = dict()
  29. def side_count(self):
  30. s = [0,0] # non-empty tracks on each side
  31. for tnr in self.to_track:
  32. s[tnr&1] += 1
  33. return s
  34. @classmethod
  35. def from_file(cls, name):
  36. splices = None
  37. with open(name, "rb") as f:
  38. dat = f.read()
  39. header = struct.unpack("<3s9BI", dat[0:16])
  40. (sig, _, _, nr_revs, _, _, flags, _, single_sided, _, _) = header
  41. error.check(sig == b"SCP", "SCP: Bad signature")
  42. index_cued = flags & 1 or nr_revs == 1
  43. if not index_cued:
  44. nr_revs -= 1
  45. # Some tools generate a short TLUT. We handle this by truncating the
  46. # TLUT at the first Track Data Header.
  47. trk_offs = struct.unpack("<168I", dat[16:0x2b0])
  48. for i in range(168):
  49. try:
  50. off = trk_offs[i]
  51. except IndexError:
  52. break
  53. if off == 0 or off >= 0x2b0:
  54. continue
  55. off = off//4 - 4
  56. error.check(off >= 0, "SCP: Bad Track Table")
  57. trk_offs = trk_offs[:off]
  58. # Parse the extension block introduced by github:markusC64/g64conv.
  59. # b'EXTS', length, <length byte Extension Area>
  60. # Extension Area contains consecutive chunks of the form:
  61. # ID, length, <length bytes of ID-specific dat>
  62. ext_sig, ext_len = struct.unpack('<4sI', dat[0x2b0:0x2b8])
  63. min_tdh = min(filter(lambda x: x != 0, trk_offs), default=0)
  64. if ext_sig == b'EXTS' and 0x2b8 + ext_len <= min_tdh:
  65. pos, end = 0x2b8, 0x2b8 + ext_len
  66. while end - pos >= 8:
  67. chk_sig, chk_len = struct.unpack('<4sI', dat[pos:pos+8])
  68. pos += 8
  69. if chk_sig == b'WRSP' and chk_len >= 169*4:
  70. # Write-splice positions for writing out SCP tracks
  71. # correctly to disk.
  72. splices = struct.unpack('<168I', dat[pos+4:pos+169*4])
  73. pos += chk_len
  74. scp = cls()
  75. scp.nr_revs = nr_revs
  76. for trknr in range(len(trk_offs)):
  77. trk_off = trk_offs[trknr]
  78. if trk_off == 0:
  79. continue
  80. # Parse the SCP track header and extract the flux data.
  81. thdr = dat[trk_off:trk_off+4+12*nr_revs]
  82. sig, tnr = struct.unpack("<3sB", thdr[:4])
  83. error.check(sig == b"TRK", "SCP: Missing track signature")
  84. error.check(tnr == trknr, "SCP: Wrong track number in header")
  85. _off = 12 if index_cued else 24 # skip first partial rev
  86. s_off, = struct.unpack("<I", thdr[_off:_off+4])
  87. _, e_nr, e_off = struct.unpack("<3I", thdr[-12:])
  88. e_off += e_nr*2
  89. if s_off == e_off:
  90. # FluxEngine creates dummy TDHs for empty tracks.
  91. # Bail on them here.
  92. continue
  93. tdat = dat[trk_off+s_off:trk_off+e_off]
  94. track = SCPTrack(thdr[4:], tdat)
  95. if splices is not None:
  96. track.splice = splices[trknr]
  97. scp.to_track[trknr] = track
  98. # Some tools produce (or used to produce) single-sided images using
  99. # consecutive entries in the TLUT. This needs fixing up.
  100. s = scp.side_count()
  101. if single_sided and s[0] and s[1]:
  102. new_dict = dict()
  103. for tnr in scp.to_track:
  104. new_dict[tnr*2+single_sided-1] = scp.to_track[tnr]
  105. scp.to_track = new_dict
  106. print('SCP: Imported legacy single-sided image')
  107. return scp
  108. def get_track(self, cyl, side):
  109. tracknr = cyl * 2 + side
  110. if not tracknr in self.to_track:
  111. return None
  112. track = self.to_track[tracknr]
  113. tdh, dat = track.tdh, track.dat
  114. index_list = []
  115. while tdh:
  116. ticks, _, _ = struct.unpack("<3I", tdh[:12])
  117. index_list.append(ticks)
  118. tdh = tdh[12:]
  119. # Decode the SCP flux data into a simple list of flux times.
  120. flux_list = []
  121. val = 0
  122. for i in range(0, len(dat), 2):
  123. x = dat[i]*256 + dat[i+1]
  124. if x == 0:
  125. val += 65536
  126. continue
  127. flux_list.append(val + x)
  128. val = 0
  129. flux = Flux(index_list, flux_list, SCP.sample_freq)
  130. flux.splice = track.splice if track.splice is not None else 0
  131. return flux
  132. def emit_track(self, cyl, side, track):
  133. """Converts @track into a Supercard Pro Track and appends it to
  134. the current image-in-progress.
  135. """
  136. flux = track.flux()
  137. nr_revs = len(flux.index_list)
  138. if not self.nr_revs:
  139. self.nr_revs = nr_revs
  140. else:
  141. assert self.nr_revs == nr_revs
  142. factor = SCP.sample_freq / flux.sample_freq
  143. tdh, dat = bytearray(), bytearray()
  144. len_at_index = rev = 0
  145. to_index = flux.index_list[0]
  146. rem = 0.0
  147. for x in flux.list:
  148. # Does the next flux interval cross the index mark?
  149. while to_index < x:
  150. # Append to the TDH for the previous full revolution
  151. tdh += struct.pack("<III",
  152. round(flux.index_list[rev]*factor),
  153. (len(dat) - len_at_index) // 2,
  154. 4 + nr_revs*12 + len_at_index)
  155. # Set up for the next revolution
  156. len_at_index = len(dat)
  157. rev += 1
  158. if rev >= nr_revs:
  159. # We're done: We simply discard any surplus flux samples
  160. self.to_track[cyl*2+side] = SCPTrack(tdh, dat)
  161. return
  162. to_index += flux.index_list[rev]
  163. # Process the current flux sample into SCP "bitcell" format
  164. to_index -= x
  165. y = x * factor + rem
  166. val = round(y)
  167. if (val & 65535) == 0:
  168. val += 1
  169. rem = y - val
  170. while val >= 65536:
  171. dat.append(0)
  172. dat.append(0)
  173. val -= 65536
  174. dat.append(val>>8)
  175. dat.append(val&255)
  176. # Header for last track(s) in case we ran out of flux timings.
  177. while rev < nr_revs:
  178. tdh += struct.pack("<III",
  179. round(flux.index_list[rev]*factor),
  180. (len(dat) - len_at_index) // 2,
  181. 4 + nr_revs*12 + len_at_index)
  182. len_at_index = len(dat)
  183. rev += 1
  184. self.to_track[cyl*2+side] = SCPTrack(tdh, dat)
  185. def get_image(self):
  186. # Work out the single-sided byte code
  187. s = self.side_count()
  188. if s[0] and s[1]:
  189. single_sided = 0
  190. elif s[0]:
  191. single_sided = 1
  192. else:
  193. single_sided = 2
  194. to_track = self.to_track
  195. if single_sided and self.opts.legacy_ss:
  196. print('SCP: Generated legacy single-sided image')
  197. to_track = dict()
  198. for tnr in self.to_track:
  199. to_track[tnr//2] = self.to_track[tnr]
  200. ntracks = max(to_track, default=0) + 1
  201. # Generate the TLUT and concatenate all the tracks together.
  202. trk_offs = bytearray()
  203. trk_dat = bytearray()
  204. for tnr in range(ntracks):
  205. if tnr in to_track:
  206. track = to_track[tnr]
  207. trk_offs += struct.pack("<I", 0x2b0 + len(trk_dat))
  208. trk_dat += struct.pack("<3sB", b"TRK", tnr)
  209. trk_dat += track.tdh + track.dat
  210. else:
  211. trk_offs += struct.pack("<I", 0)
  212. error.check(len(trk_offs) <= 0x2a0, "SCP: Too many tracks")
  213. trk_offs += bytes(0x2a0 - len(trk_offs))
  214. # Calculate checksum over all data (except 16-byte image header).
  215. csum = 0
  216. for x in trk_offs:
  217. csum += x
  218. for x in trk_dat:
  219. csum += x
  220. # Generate the image header.
  221. header = struct.pack("<3s9BI",
  222. b"SCP", # Signature
  223. 0, # Version
  224. 0x80, # DiskType = Other
  225. self.nr_revs, 0, ntracks-1,
  226. 0x03, # Flags = Index, 96TPI
  227. 0, # 16-bit cell width
  228. single_sided,
  229. 0, # 25ns capture
  230. csum & 0xffffffff)
  231. # Concatenate it all together and send it back.
  232. return header + trk_offs + trk_dat
  233. # Local variables:
  234. # python-indent: 4
  235. # End: