scp.py 11 KB

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