scp.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. class SCPOpts:
  11. """old_ss: Set to True to generate (incorrect) old-style single-sided
  12. SCP image.
  13. """
  14. def __init__(self):
  15. self.old_ss = False
  16. class SCP:
  17. # 40MHz
  18. sample_freq = 40000000
  19. def __init__(self, start_cyl, nr_sides):
  20. self.opts = SCPOpts()
  21. self.nr_sides = nr_sides
  22. self.nr_revs = None
  23. self.track_list = [(None,None)] * (start_cyl*2)
  24. @classmethod
  25. def to_file(cls, start_cyl, nr_sides):
  26. scp = cls(start_cyl, nr_sides)
  27. return scp
  28. @classmethod
  29. def from_file(cls, dat):
  30. header = struct.unpack("<3s9BI", dat[0:16])
  31. (sig, _, _, nr_revs, _, _, flags, _, single_sided, _, _) = header
  32. error.check(sig == b"SCP", "SCP: Bad signature")
  33. # Some tools generate a short TLUT. We handle this by truncating the
  34. # TLUT at the first Track Data Header.
  35. trk_offs = struct.unpack("<168I", dat[16:0x2b0])
  36. for i in range(168):
  37. try:
  38. off = trk_offs[i]
  39. except IndexError:
  40. break
  41. if off == 0 or off >= 0x2b0:
  42. continue
  43. off = off//4 - 4
  44. error.check(off >= 0, "SCP: Bad Track Table")
  45. trk_offs = trk_offs[:off]
  46. scp = cls(0, 2)
  47. scp.nr_revs = nr_revs
  48. for trknr in range(len(trk_offs)):
  49. trk_off = trk_offs[trknr]
  50. if trk_off == 0:
  51. scp.track_list.append((None, None))
  52. continue
  53. # Parse the SCP track header and extract the flux data.
  54. thdr = dat[trk_off:trk_off+4+12*nr_revs]
  55. sig, tnr, _, _, s_off = struct.unpack("<3sB3I", thdr[:16])
  56. error.check(sig == b"TRK", "SCP: Missing track signature")
  57. error.check(tnr == trknr, "SCP: Wrong track number in header")
  58. _, e_nr, e_off = struct.unpack("<3I", thdr[-12:])
  59. tdat = dat[trk_off+s_off:trk_off+e_off+e_nr*2]
  60. scp.track_list.append((thdr[4:], tdat))
  61. # s[side] is True iff there are non-empty tracks on @side
  62. s = []
  63. for i in range(2):
  64. s.append(functools.reduce(lambda x, y: x or (y[1] is not None),
  65. scp.track_list[i::2], False))
  66. # Some tools produce (or used to produce) single-sided images using
  67. # consecutive entries in the TLUT. This needs fixing up.
  68. if single_sided and functools.reduce(lambda x, y: x and y, s):
  69. new_list = []
  70. for t in scp.track_list[:84]:
  71. if single_sided != 1: # Side 1
  72. new_list.append((None, None))
  73. new_list.append(t)
  74. if single_sided == 1: # Side 0
  75. new_list.append((None, None))
  76. scp.track_list = new_list
  77. print('SCP: Imported old-style single-sided image')
  78. return scp
  79. def get_track(self, cyl, side, writeout=False):
  80. off = cyl*2 + side
  81. if off >= len(self.track_list):
  82. return None
  83. tdh, dat = self.track_list[off]
  84. if dat is None:
  85. return None
  86. # Writeout requires only a single revolution
  87. if writeout:
  88. tdh = tdh[:12]
  89. _, nr, _ = struct.unpack("<3I", tdh)
  90. dat = dat[:nr*2]
  91. index_list = []
  92. while tdh:
  93. ticks, _, _ = struct.unpack("<3I", tdh[:12])
  94. index_list.append(ticks)
  95. tdh = tdh[12:]
  96. # Decode the SCP flux data into a simple list of flux times.
  97. flux_list = []
  98. val = 0
  99. for i in range(0, len(dat), 2):
  100. x = dat[i]*256 + dat[i+1]
  101. if x == 0:
  102. val += 65536
  103. continue
  104. flux_list.append(val + x)
  105. val = 0
  106. return Flux(index_list, flux_list, SCP.sample_freq)
  107. def append_track(self, flux):
  108. """Converts a Flux object into a Supercard Pro Track and appends it to
  109. the current image-in-progress.
  110. """
  111. def _append(self, tdh, dat):
  112. self.track_list.append((tdh, dat))
  113. if self.nr_sides == 1:
  114. self.track_list.append((None, None))
  115. nr_revs = len(flux.index_list)
  116. if not self.nr_revs:
  117. self.nr_revs = nr_revs
  118. else:
  119. assert self.nr_revs == nr_revs
  120. factor = SCP.sample_freq / flux.sample_freq
  121. tdh, dat = bytearray(), bytearray()
  122. len_at_index = rev = 0
  123. to_index = flux.index_list[0]
  124. rem = 0.0
  125. for x in flux.list:
  126. # Does the next flux interval cross the index mark?
  127. while to_index < x:
  128. # Append to the TDH for the previous full revolution
  129. tdh += struct.pack("<III",
  130. int(round(flux.index_list[rev]*factor)),
  131. (len(dat) - len_at_index) // 2,
  132. 4 + nr_revs*12 + len_at_index)
  133. # Set up for the next revolution
  134. len_at_index = len(dat)
  135. rev += 1
  136. if rev >= nr_revs:
  137. # We're done: We simply discard any surplus flux samples
  138. _append(self, tdh, dat)
  139. return
  140. to_index += flux.index_list[rev]
  141. # Process the current flux sample into SCP "bitcell" format
  142. to_index -= x
  143. y = x * factor + rem
  144. val = int(round(y))
  145. if (val & 65535) == 0:
  146. val += 1
  147. rem = y - val
  148. while val >= 65536:
  149. dat.append(0)
  150. dat.append(0)
  151. val -= 65536
  152. dat.append(val>>8)
  153. dat.append(val&255)
  154. # Header for last track(s) in case we ran out of flux timings.
  155. while rev < nr_revs:
  156. tdh += struct.pack("<III",
  157. int(round(flux.index_list[rev]*factor)),
  158. (len(dat) - len_at_index) // 2,
  159. 4 + nr_revs*12 + len_at_index)
  160. len_at_index = len(dat)
  161. rev += 1
  162. _append(self, tdh, dat)
  163. def get_image(self):
  164. single_sided = 1 if self.nr_sides == 1 else 0
  165. track_list = self.track_list
  166. if single_sided and self.opts.old_ss:
  167. print('SCP: Generated old-style single-sided image')
  168. track_list = track_list[::2]
  169. # Generate the TLUT and concatenate all the tracks together.
  170. trk_offs = bytearray()
  171. trk_dat = bytearray()
  172. for trknr in range(len(track_list)):
  173. tdh, dat = track_list[trknr]
  174. if dat is None:
  175. trk_offs += struct.pack("<I", 0)
  176. else:
  177. trk_offs += struct.pack("<I", 0x2b0 + len(trk_dat))
  178. trk_dat += struct.pack("<3sB", b"TRK", trknr) + tdh + dat
  179. trk_offs += bytes(0x2a0 - len(trk_offs))
  180. # Calculate checksum over all data (except 16-byte image header).
  181. csum = 0
  182. for x in trk_offs:
  183. csum += x
  184. for x in trk_dat:
  185. csum += x
  186. # Generate the image header.
  187. header = struct.pack("<3s9BI",
  188. b"SCP", # Signature
  189. 0, # Version
  190. 0x80, # DiskType = Other
  191. self.nr_revs, 0, len(track_list) - 1,
  192. 0x01, # Flags = Index
  193. 0, # 16-bit cell width
  194. single_sided,
  195. 0, # 25ns capture
  196. csum & 0xffffffff)
  197. # Concatenate it all together and send it back.
  198. return header + trk_offs + trk_dat
  199. # Local variables:
  200. # python-indent: 4
  201. # End: