track.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. # 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, cue_at_index=True):
  46. return self.flux(for_writeout=True, cue_at_index=cue_at_index)
  47. def flux(self, for_writeout=False, cue_at_index=True):
  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. if cue_at_index:
  84. # Rotate data to start at the index.
  85. index = -self.splice % bitlen
  86. if index != 0:
  87. bits = bits[index:] + bits[:index]
  88. bit_ticks = bit_ticks[index:] + bit_ticks[:index]
  89. splice_at_index = index < 4 or bitlen - index < 4
  90. else:
  91. splice_at_index = False
  92. if not for_writeout:
  93. # Do not extend the track for reliable writeout to disk.
  94. pass
  95. elif not cue_at_index:
  96. # We write the track wherever it may fall (uncued).
  97. # We stretch the track with extra header gap bytes, in case the
  98. # drive spins slow and we need more length to create an overlap.
  99. # Thus if the drive spins slow, the track gets a longer header.
  100. pos = 4
  101. # We stretch by 10 percent, which is way more than enough.
  102. rep = bitlen // (10 * 32)
  103. bit_ticks = bit_ticks[pos:pos+32] * rep + bit_ticks[pos:]
  104. bits = bits[pos:pos+32] * rep + bits[pos:]
  105. elif splice_at_index:
  106. # Splice is at the index (or within a few bitcells of it).
  107. # We stretch the track with extra footer gap bytes, in case the
  108. # drive motor spins slower than expected and we need more filler
  109. # to get us to the index pulse (where the write will terminate).
  110. # Thus if the drive spins slow, the track gets a longer footer.
  111. pos = (self.splice - 4) % bitlen
  112. # We stretch by 10 percent, which is way more than enough.
  113. rep = bitlen // (10 * 32)
  114. bit_ticks = bit_ticks[:pos] + bit_ticks[pos-32:pos] * rep
  115. bits = bits[:pos] + bits[pos-32:pos] * rep
  116. else:
  117. # Splice is not at the index. We will write more than one
  118. # revolution, and terminate the second revolution at the splice.
  119. # For the first revolution we repeat the track header *backwards*
  120. # to the very start of the write. This is in case the drive motor
  121. # spins slower than expected and the write ends before the original
  122. # splice position.
  123. # Thus if the drive spins slow, the track gets a longer header.
  124. bit_ticks += bit_ticks[:self.splice-4]
  125. bits += bits[:self.splice-4]
  126. pos = self.splice+4
  127. fill_pattern = bits[pos:pos+32]
  128. while pos >= 32:
  129. pos -= 32
  130. bits[pos:pos+32] = fill_pattern
  131. # Convert the stretched track data into flux.
  132. bit_ticks_i = iter(bit_ticks)
  133. flux_list = []
  134. flux_ticks = 0
  135. for bit in bits:
  136. flux_ticks += next(bit_ticks_i)
  137. if bit:
  138. flux_list.append(flux_ticks)
  139. flux_ticks = 0
  140. if flux_ticks and for_writeout:
  141. flux_list.append(flux_ticks)
  142. # Package up the flux for return.
  143. flux = WriteoutFlux(ticks_to_index, flux_list,
  144. ticks_to_index / self.time_per_rev,
  145. index_cued = cue_at_index,
  146. terminate_at_index = splice_at_index)
  147. return flux
  148. # Track data generated from flux.
  149. class RawTrack:
  150. def __init__(self, clock, data):
  151. self.clock = clock
  152. self.clock_max_adj = 0.10
  153. self.pll_period_adj = 0.05
  154. self.pll_phase_adj = 0.60
  155. self.bitarray = bitarray(endian='big')
  156. self.timearray = []
  157. self.revolutions = []
  158. self.import_flux_data(data)
  159. def __str__(self):
  160. s = "\nRaw Track: %d revolutions\n" % len(self.revolutions)
  161. for rev in range(len(self.revolutions)):
  162. b, _ = self.get_revolution(rev)
  163. s += "Revolution %u (%u bits): " % (rev, len(b))
  164. s += str(binascii.hexlify(b.tobytes())) + "\n"
  165. b = self.bitarray[sum(self.revolutions):]
  166. s += "Tail (%u bits): " % (len(b))
  167. s += str(binascii.hexlify(b.tobytes())) + "\n"
  168. return s[:-1]
  169. def get_revolution(self, nr):
  170. start = sum(self.revolutions[:nr])
  171. end = start + self.revolutions[nr]
  172. return self.bitarray[start:end], self.timearray[start:end]
  173. def get_all_data(self):
  174. return self.bitarray, self.timearray
  175. def import_flux_data(self, data):
  176. flux = data.flux()
  177. freq = flux.sample_freq
  178. clock = self.clock
  179. clock_min = self.clock * (1 - self.clock_max_adj)
  180. clock_max = self.clock * (1 + self.clock_max_adj)
  181. ticks = 0.0
  182. index_iter = it.chain(iter(map(lambda x: x/freq, flux.index_list)),
  183. [float('inf')])
  184. bits, times = bitarray(endian='big'), []
  185. to_index = next(index_iter)
  186. # Make sure there's enough time in the flux list to cover all
  187. # revolutions by appending a "large enough" final flux value.
  188. tail = max(0, sum(flux.index_list) - sum(flux.list) + clock*freq*2)
  189. for x in it.chain(flux.list, [tail]):
  190. # Gather enough ticks to generate at least one bitcell.
  191. ticks += x / freq
  192. if ticks < clock/2:
  193. continue
  194. # Clock out zero or more 0s, followed by a 1.
  195. zeros = 0
  196. while True:
  197. # Check if we cross the index mark.
  198. to_index -= clock
  199. if to_index < 0:
  200. self.bitarray += bits
  201. self.timearray += times
  202. self.revolutions.append(len(times))
  203. assert len(times) == len(bits)
  204. to_index += next(index_iter)
  205. bits, times = bitarray(endian='big'), []
  206. ticks -= clock
  207. times.append(clock)
  208. if ticks >= clock/2:
  209. zeros += 1
  210. bits.append(False)
  211. else:
  212. bits.append(True)
  213. break
  214. # PLL: Adjust clock frequency according to phase mismatch.
  215. if zeros <= 3:
  216. # In sync: adjust clock by a fraction of the phase mismatch.
  217. clock += ticks * self.pll_period_adj
  218. else:
  219. # Out of sync: adjust clock towards centre.
  220. clock += (self.clock - clock) * self.pll_period_adj
  221. # Clamp the clock's adjustment range.
  222. clock = min(max(clock, clock_min), clock_max)
  223. # PLL: Adjust clock phase according to mismatch.
  224. new_ticks = ticks * (1 - self.pll_phase_adj)
  225. times[-1] += ticks - new_ticks
  226. ticks = new_ticks
  227. # Append trailing bits.
  228. self.bitarray += bits
  229. self.timearray += times
  230. # Local variables:
  231. # python-indent: 4
  232. # End: