track.py 9.5 KB

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