scp.py 9.4 KB

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