track.py 12 KB

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