scp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 byte Extension Area>
  77. # Extension Area contains consecutive chunks of the form:
  78. # ID, length, <length bytes of ID-specific dat>
  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. if chk_sig == b'WRSP' and chk_len >= 169*4:
  87. # Write-splice positions for writing out SCP tracks
  88. # correctly to disk.
  89. splices = struct.unpack('<168I', dat[pos+4:pos+169*4])
  90. pos += chk_len
  91. scp = cls()
  92. scp.nr_revs = nr_revs
  93. if not index_cued:
  94. scp.nr_revs -= 1
  95. for trknr in range(len(trk_offs)):
  96. trk_off = trk_offs[trknr]
  97. if trk_off == 0:
  98. continue
  99. # Parse the SCP track header and extract the flux data.
  100. thdr = dat[trk_off:trk_off+4+12*nr_revs]
  101. sig, tnr = struct.unpack("<3sB", thdr[:4])
  102. error.check(sig == b"TRK", "SCP: Missing track signature")
  103. error.check(tnr == trknr, "SCP: Wrong track number in header")
  104. thdr = thdr[4:] # Remove TRK header
  105. if not index_cued: # Remove first partial revolution
  106. thdr = thdr[12:]
  107. s_off, = struct.unpack("<I", thdr[8:12])
  108. _, e_nr, e_off = struct.unpack("<3I", thdr[-12:])
  109. e_off += e_nr*2
  110. if s_off == e_off:
  111. # FluxEngine creates dummy TDHs for empty tracks.
  112. # Bail on them here.
  113. continue
  114. tdat = dat[trk_off+s_off:trk_off+e_off]
  115. track = SCPTrack(thdr, tdat)
  116. if splices is not None:
  117. track.splice = splices[trknr]
  118. scp.to_track[trknr] = track
  119. # Some tools produce (or used to produce) single-sided images using
  120. # consecutive entries in the TLUT. This needs fixing up.
  121. s = scp.side_count()
  122. if single_sided and s[0] and s[1]:
  123. new_dict = dict()
  124. for tnr in scp.to_track:
  125. new_dict[tnr*2+single_sided-1] = scp.to_track[tnr]
  126. scp.to_track = new_dict
  127. print('SCP: Imported legacy single-sided image')
  128. return scp
  129. def get_track(self, cyl, side):
  130. tracknr = cyl * 2 + side
  131. if not tracknr in self.to_track:
  132. return None
  133. track = self.to_track[tracknr]
  134. tdh, dat = track.tdh, track.dat
  135. index_list = []
  136. while tdh:
  137. ticks, _, _ = struct.unpack("<3I", tdh[:12])
  138. index_list.append(ticks)
  139. tdh = tdh[12:]
  140. # Decode the SCP flux data into a simple list of flux times.
  141. flux_list = []
  142. val = 0
  143. for i in range(0, len(dat), 2):
  144. x = dat[i]*256 + dat[i+1]
  145. if x == 0:
  146. val += 65536
  147. continue
  148. flux_list.append(val + x)
  149. val = 0
  150. flux = Flux(index_list, flux_list, SCP.sample_freq)
  151. flux.splice = track.splice if track.splice is not None else 0
  152. return flux
  153. def emit_track(self, cyl, side, track):
  154. """Converts @track into a Supercard Pro Track and appends it to
  155. the current image-in-progress.
  156. """
  157. flux = track.flux()
  158. # External tools and emulators generally seem to work best (or only)
  159. # with index-cued SCP image files. So let's make sure we give them
  160. # what they want.
  161. flux.cue_at_index()
  162. if not flux.index_cued:
  163. self.index_cued = False
  164. nr_revs = len(flux.index_list)
  165. if not self.nr_revs:
  166. self.nr_revs = nr_revs
  167. else:
  168. assert self.nr_revs == nr_revs
  169. factor = SCP.sample_freq / flux.sample_freq
  170. tdh, dat = bytearray(), bytearray()
  171. len_at_index = rev = 0
  172. to_index = flux.index_list[0]
  173. rem = 0.0
  174. for x in flux.list:
  175. # Does the next flux interval cross the index mark?
  176. while to_index < x:
  177. # Append to the TDH for the previous full revolution
  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. # Set up for the next revolution
  183. len_at_index = len(dat)
  184. rev += 1
  185. if rev >= nr_revs:
  186. # We're done: We simply discard any surplus flux samples
  187. self.to_track[cyl*2+side] = SCPTrack(tdh, dat)
  188. return
  189. to_index += flux.index_list[rev]
  190. # Process the current flux sample into SCP "bitcell" format
  191. to_index -= x
  192. y = x * factor + rem
  193. val = round(y)
  194. if (val & 65535) == 0:
  195. val += 1
  196. rem = y - val
  197. while val >= 65536:
  198. dat.append(0)
  199. dat.append(0)
  200. val -= 65536
  201. dat.append(val>>8)
  202. dat.append(val&255)
  203. # Header for last track(s) in case we ran out of flux timings.
  204. while rev < nr_revs:
  205. tdh += struct.pack("<III",
  206. round(flux.index_list[rev]*factor),
  207. (len(dat) - len_at_index) // 2,
  208. 4 + nr_revs*12 + len_at_index)
  209. len_at_index = len(dat)
  210. rev += 1
  211. self.to_track[cyl*2+side] = SCPTrack(tdh, dat)
  212. def get_image(self):
  213. # Work out the single-sided byte code
  214. s = self.side_count()
  215. if s[0] and s[1]:
  216. single_sided = 0
  217. elif s[0]:
  218. single_sided = 1
  219. else:
  220. single_sided = 2
  221. to_track = self.to_track
  222. if single_sided and self.opts.legacy_ss:
  223. print('SCP: Generated legacy single-sided image')
  224. to_track = dict()
  225. for tnr in self.to_track:
  226. to_track[tnr//2] = self.to_track[tnr]
  227. ntracks = max(to_track, default=0) + 1
  228. # Generate the TLUT and concatenate all the tracks together.
  229. trk_offs = bytearray()
  230. trk_dat = bytearray()
  231. for tnr in range(ntracks):
  232. if tnr in to_track:
  233. track = to_track[tnr]
  234. trk_offs += struct.pack("<I", 0x2b0 + len(trk_dat))
  235. trk_dat += struct.pack("<3sB", b"TRK", tnr)
  236. trk_dat += track.tdh + track.dat
  237. else:
  238. trk_offs += struct.pack("<I", 0)
  239. error.check(len(trk_offs) <= 0x2a0, "SCP: Too many tracks")
  240. trk_offs += bytes(0x2a0 - len(trk_offs))
  241. # Calculate checksum over all data (except 16-byte image header).
  242. csum = 0
  243. for x in trk_offs:
  244. csum += x
  245. for x in trk_dat:
  246. csum += x
  247. # Generate the image header.
  248. flags = 2 # 96TPI
  249. if self.index_cued:
  250. flags |= 1 # Index-Cued
  251. header = struct.pack("<3s9BI",
  252. b"SCP", # Signature
  253. 0, # Version
  254. self.opts.disktype,
  255. self.nr_revs, 0, ntracks-1,
  256. flags,
  257. 0, # 16-bit cell width
  258. single_sided,
  259. 0, # 25ns capture
  260. csum & 0xffffffff)
  261. # Concatenate it all together and send it back.
  262. return header + trk_offs + trk_dat
  263. # Local variables:
  264. # python-indent: 4
  265. # End: