track.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # greaseweazle/track.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 binascii
  8. import itertools as it
  9. from bitarray import bitarray
  10. from greaseweazle.flux import WriteoutFlux
  11. from greaseweazle import optimised
  12. # Precompensation to apply to a MasterTrack for writeout.
  13. class Precomp:
  14. MFM = 0
  15. FM = 1
  16. GCR = 2
  17. TYPESTRING = [ 'MFM', 'FM', 'GCR' ]
  18. def __str__(self):
  19. return "Precomp: %s, %dns" % (Precomp.TYPESTRING[self.type], self.ns)
  20. def __init__(self, type, ns):
  21. self.type = type
  22. self.ns = ns
  23. def apply(self, bits, bit_ticks, scale):
  24. t = self.ns * scale
  25. if self.type == Precomp.MFM:
  26. for i in bits.itersearch(bitarray('10100', endian='big')):
  27. bit_ticks[i+2] -= t
  28. bit_ticks[i+3] += t
  29. for i in bits.itersearch(bitarray('00101', endian='big')):
  30. bit_ticks[i+2] += t
  31. bit_ticks[i+3] -= t
  32. # This is primarily for GCR and FM which permit adjacent 1s (and
  33. # have correspondingly slower bit times). However it may be useful
  34. # for illegal MFM sequences too, especially on Amiga (custom syncwords,
  35. # 4us-bitcell tracks). Normal MFM should not trigger these patterns.
  36. for i in bits.itersearch(bitarray('110', endian='big')):
  37. bit_ticks[i+1] -= t
  38. bit_ticks[i+2] += t
  39. for i in bits.itersearch(bitarray('011', endian='big')):
  40. bit_ticks[i+1] += t
  41. bit_ticks[i+2] -= t
  42. # A pristine representation of a track, from a codec and/or a perfect image.
  43. class MasterTrack:
  44. @property
  45. def bitrate(self):
  46. return len(self.bits) / self.time_per_rev
  47. # bits: Track bitcell data, aligned to the write splice (bitarray or bytes)
  48. # time_per_rev: Time per revolution, in seconds (float)
  49. # bit_ticks: Per-bitcell time values, in unitless 'ticks'
  50. # splice: Location of the track splice, in bitcells, after the index
  51. # weak: List of (start, length) weak ranges
  52. def __init__(self, bits, time_per_rev, bit_ticks=None, splice=0, weak=[]):
  53. if isinstance(bits, bytes):
  54. self.bits = bitarray(endian='big')
  55. self.bits.frombytes(bits)
  56. else:
  57. self.bits = bits
  58. self.time_per_rev = time_per_rev
  59. self.bit_ticks = bit_ticks
  60. self.splice = splice
  61. self.weak = weak
  62. self.precomp = None
  63. def __str__(self):
  64. s = "\nMaster Track: splice @ %d\n" % self.splice
  65. s += (" %d bits, %.1f kbit/s"
  66. % (len(self.bits), self.bitrate))
  67. if self.bit_ticks:
  68. s += " (variable)"
  69. s += ("\n %.1f ms / rev (%.1f rpm)"
  70. % (self.time_per_rev * 1000, 60 / self.time_per_rev))
  71. if len(self.weak) > 0:
  72. s += "\n %d weak range" % len(self.weak)
  73. if len(self.weak) > 1: s += "s"
  74. s += ": " + ", ".join(str(n) for _,n in self.weak) + " bits"
  75. #s += str(binascii.hexlify(self.bits.tobytes()))
  76. return s
  77. def flux_for_writeout(self, cue_at_index=True):
  78. return self.flux(for_writeout=True, cue_at_index=cue_at_index)
  79. def flux(self, for_writeout=False, cue_at_index=True):
  80. # We're going to mess with the track data, so take a copy.
  81. bits = self.bits.copy()
  82. bitlen = len(bits)
  83. # Also copy the bit_ticks array (or create a dummy one), and remember
  84. # the total ticks that it contains.
  85. bit_ticks = self.bit_ticks.copy() if self.bit_ticks else [1] * bitlen
  86. ticks_to_index = sum(bit_ticks)
  87. # Weak regions need special processing for correct flux representation.
  88. for s,n in self.weak:
  89. e = s + n
  90. assert 0 < s < e < bitlen
  91. pattern = bitarray(endian="big")
  92. if n < 400:
  93. # Short weak regions are written with no flux transitions.
  94. # Actually we insert a flux transition every 32 bitcells, else
  95. # we risk triggering Greaseweazle's No Flux Area generator.
  96. pattern.frombytes(b"\x80\x00\x00\x00")
  97. bits[s:e] = (pattern * (n//32+1))[:n]
  98. else:
  99. # Long weak regions we present a fuzzy clock bit in an
  100. # otherwise normal byte (16 bits MFM). The byte may be
  101. # interpreted as
  102. # MFM 0001001010100101 = 12A5 = byte 0x43, or
  103. # MFM 0001001010010101 = 1295 = byte 0x47
  104. pattern.frombytes(b"\x12\xA5")
  105. bits[s:e] = (pattern * (n//16+1))[:n]
  106. for i in range(0, n-10, 16):
  107. x, y = bit_ticks[s+i+10], bit_ticks[s+i+11]
  108. bit_ticks[s+i+10], bit_ticks[s+i+11] = x+y*0.5, y*0.5
  109. # To prevent corrupting a preceding sync word by effectively
  110. # starting the weak region early, we start with a 1 if we just
  111. # clocked out a 0.
  112. bits[s] = not bits[s-1]
  113. # Similarly modify the last bit of the weak region.
  114. bits[e-1] = not(bits[e-2] or bits[e])
  115. if cue_at_index:
  116. # Rotate data to start at the index.
  117. index = -self.splice % bitlen
  118. if index != 0:
  119. bits = bits[index:] + bits[:index]
  120. bit_ticks = bit_ticks[index:] + bit_ticks[:index]
  121. splice_at_index = index < 4 or bitlen - index < 4
  122. else:
  123. splice_at_index = False
  124. if not for_writeout:
  125. # Do not extend the track for reliable writeout to disk.
  126. pass
  127. elif not cue_at_index:
  128. # We write the track wherever it may fall (uncued).
  129. # We stretch the track with extra header gap bytes, in case the
  130. # drive spins slow and we need more length to create an overlap.
  131. # Thus if the drive spins slow, the track gets a longer header.
  132. pos = 4
  133. # We stretch by 10 percent, which is way more than enough.
  134. rep = bitlen // (10 * 32)
  135. bit_ticks = bit_ticks[pos:pos+32] * rep + bit_ticks[pos:]
  136. bits = bits[pos:pos+32] * rep + bits[pos:]
  137. elif splice_at_index:
  138. # Splice is at the index (or within a few bitcells of it).
  139. # We stretch the track with extra footer gap bytes, in case the
  140. # drive motor spins slower than expected and we need more filler
  141. # to get us to the index pulse (where the write will terminate).
  142. # Thus if the drive spins slow, the track gets a longer footer.
  143. pos = (self.splice - 4) % bitlen
  144. # We stretch by 10 percent, which is way more than enough.
  145. rep = bitlen // (10 * 32)
  146. bit_ticks = bit_ticks[:pos] + bit_ticks[pos-32:pos] * rep
  147. bits = bits[:pos] + bits[pos-32:pos] * rep
  148. else:
  149. # Splice is not at the index. We will write more than one
  150. # revolution, and terminate the second revolution at the splice.
  151. # For the first revolution we repeat the track header *backwards*
  152. # to the very start of the write. This is in case the drive motor
  153. # spins slower than expected and the write ends before the original
  154. # splice position.
  155. # Thus if the drive spins slow, the track gets a longer header.
  156. bit_ticks += bit_ticks[:self.splice-4]
  157. bits += bits[:self.splice-4]
  158. pos = self.splice+4
  159. fill_pattern = bits[pos:pos+32]
  160. while pos >= 32:
  161. pos -= 32
  162. bits[pos:pos+32] = fill_pattern
  163. if for_writeout and self.precomp is not None:
  164. self.precomp.apply(bits, bit_ticks,
  165. ticks_to_index / (self.time_per_rev*1e9))
  166. # Convert the stretched track data into flux.
  167. bit_ticks_i = iter(bit_ticks)
  168. flux_list = []
  169. flux_ticks = 0
  170. for bit in bits:
  171. flux_ticks += next(bit_ticks_i)
  172. if bit:
  173. flux_list.append(flux_ticks)
  174. flux_ticks = 0
  175. if flux_ticks and for_writeout:
  176. flux_list.append(flux_ticks)
  177. # Package up the flux for return.
  178. flux = WriteoutFlux(ticks_to_index, flux_list,
  179. ticks_to_index / self.time_per_rev,
  180. index_cued = cue_at_index,
  181. terminate_at_index = splice_at_index)
  182. return flux
  183. # Track data generated from flux.
  184. class RawTrack:
  185. def __init__(self, clock, data):
  186. self.clock = clock
  187. self.clock_max_adj = 0.10
  188. self.pll_period_adj = 0.05
  189. self.pll_phase_adj = 0.60
  190. self.bitarray = bitarray(endian='big')
  191. self.timearray = []
  192. self.revolutions = []
  193. self.import_flux_data(data)
  194. def __str__(self):
  195. s = "\nRaw Track: %d revolutions\n" % len(self.revolutions)
  196. for rev in range(len(self.revolutions)):
  197. b, _ = self.get_revolution(rev)
  198. s += "Revolution %u (%u bits): " % (rev, len(b))
  199. s += str(binascii.hexlify(b.tobytes())) + "\n"
  200. b = self.bitarray[sum(self.revolutions):]
  201. s += "Tail (%u bits): " % (len(b))
  202. s += str(binascii.hexlify(b.tobytes())) + "\n"
  203. return s[:-1]
  204. def get_revolution(self, nr):
  205. start = sum(self.revolutions[:nr])
  206. end = start + self.revolutions[nr]
  207. return self.bitarray[start:end], self.timearray[start:end]
  208. def get_all_data(self):
  209. return self.bitarray, self.timearray
  210. def import_flux_data(self, data):
  211. flux = data.flux()
  212. freq = flux.sample_freq
  213. clock = self.clock
  214. clock_min = self.clock * (1 - self.clock_max_adj)
  215. clock_max = self.clock * (1 + self.clock_max_adj)
  216. index_iter = it.chain(iter(map(lambda x: x/freq, flux.index_list)),
  217. [float('inf')])
  218. # Make sure there's enough time in the flux list to cover all
  219. # revolutions by appending a "large enough" final flux value.
  220. tail = max(0, sum(flux.index_list) - sum(flux.list) + clock*freq*2)
  221. flux_iter = it.chain(flux.list, [tail])
  222. try:
  223. optimised.flux_to_bitcells(
  224. self.bitarray, self.timearray, self.revolutions,
  225. index_iter, flux_iter,
  226. freq, clock, clock_min, clock_max,
  227. self.pll_period_adj, self.pll_phase_adj)
  228. except AttributeError:
  229. flux_to_bitcells(
  230. self.bitarray, self.timearray, self.revolutions,
  231. index_iter, flux_iter,
  232. freq, clock, clock_min, clock_max,
  233. self.pll_period_adj, self.pll_phase_adj)
  234. def flux_to_bitcells(bit_array, time_array, revolutions,
  235. index_iter, flux_iter,
  236. freq, clock_centre, clock_min, clock_max,
  237. pll_period_adj, pll_phase_adj):
  238. nbits = 0
  239. ticks = 0.0
  240. clock = clock_centre
  241. to_index = next(index_iter)
  242. for x in flux_iter:
  243. # Gather enough ticks to generate at least one bitcell.
  244. ticks += x / freq
  245. if ticks < clock/2:
  246. continue
  247. # Clock out zero or more 0s, followed by a 1.
  248. zeros = 0
  249. while True:
  250. # Check if we cross the index mark.
  251. to_index -= clock
  252. if to_index < 0:
  253. revolutions.append(nbits)
  254. nbits = 0
  255. to_index += next(index_iter)
  256. nbits += 1
  257. ticks -= clock
  258. time_array.append(clock)
  259. if ticks >= clock/2:
  260. zeros += 1
  261. bit_array.append(False)
  262. else:
  263. bit_array.append(True)
  264. break
  265. # PLL: Adjust clock frequency according to phase mismatch.
  266. if zeros <= 3:
  267. # In sync: adjust clock by a fraction of the phase mismatch.
  268. clock += ticks * pll_period_adj
  269. else:
  270. # Out of sync: adjust clock towards centre.
  271. clock += (clock_centre - clock) * pll_period_adj
  272. # Clamp the clock's adjustment range.
  273. clock = min(max(clock, clock_min), clock_max)
  274. # PLL: Adjust clock phase according to mismatch.
  275. new_ticks = ticks * (1 - pll_phase_adj)
  276. time_array[-1] += ticks - new_ticks
  277. ticks = new_ticks
  278. # Local variables:
  279. # python-indent: 4
  280. # End: