track.py 11 KB

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