picadae calibration programs
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

calibrate.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import os,types,wave,json,array
  2. import numpy as np
  3. from rms_analysis import rms_analyze_one_rt_note
  4. from plot_seq_1 import get_merged_pulse_db_measurements
  5. class Calibrate:
  6. def __init__( self, cfg, audio, midi, api ):
  7. self.cfg = types.SimpleNamespace(**cfg)
  8. self.audio = audio
  9. self.midi = midi
  10. self.api = api
  11. self.state = "stopped" # stopped | started | note_on | note_off | analyzing
  12. self.playOnlyFl = False
  13. self.startMs = None
  14. self.nextStateChangeMs = None
  15. self.curHoldDutyCyclePctD = None # { pitch:dutyPct}
  16. self.noteAnnotationL = [] # (noteOnMs,noteOffMs,pitch,pulseUs)
  17. self.measD = None # { midi_pitch: [ {pulseUs, db, durMs, targetDb } ] }
  18. self.initPulseDbListD = self._get_init_pulseDbD()
  19. self.curNoteStartMs = None
  20. self.curPitchIdx = None
  21. self.curTargetDbIdx = None
  22. self.successN = None
  23. self.failN = None
  24. self.curTargetDb = None
  25. self.curPulseUs = None
  26. self.curMatchN = None
  27. self.curAttemptN = None
  28. self.lastAudiblePulseUs = None
  29. self.maxTooShortPulseUs = None
  30. self.pulseDbL = None
  31. self.deltaUpMult = None
  32. self.deltaDnMult = None
  33. self.skipMeasFl = None
  34. def start(self,ms):
  35. self.stop(ms)
  36. self.state = 'started'
  37. self.playOnlyFl = False
  38. self.nextStateChangeMs = ms + 500
  39. self.startMs = ms
  40. self.curPitchIdx = 0
  41. self.curPulseUs = self.cfg.initPulseUs
  42. self.lastAudiblePulseUs = None
  43. self.maxTooShortPulseUs = None
  44. self.pulseDbL = []
  45. self.pulseDbL = self.initPulseDbListD[ self.cfg.pitchL[ self.curPitchIdx ] ]
  46. self.deltaUpMult = 1
  47. self.deltaDnMult = 1
  48. self.curTargetDbIdx = -1
  49. self._start_new_db_target()
  50. self.curDutyPctD = {}
  51. self.skipMeasFl = False
  52. self.measD = {}
  53. self.successN = 0
  54. self.failN = 0
  55. self.audio.record_enable(True)
  56. def stop(self,ms):
  57. if self.midi is not None:
  58. self.midi.send_all_notes_off()
  59. self.audio.record_enable(False)
  60. if not self.playOnlyFl:
  61. self._save_results()
  62. def play(self,ms):
  63. if self.measD is None or len(self.measD) == 0:
  64. print("Nothing to play.")
  65. else:
  66. self.startMs = ms
  67. self.state = 'started'
  68. self.playOnlyFl = True
  69. self.nextStateChangeMs = ms + 500
  70. self.curPitchIdx = -1
  71. self.curTargetDbIdx = 0
  72. self.audio.record_enable(True)
  73. self._do_play_only_update()
  74. def tick(self,ms):
  75. if self.nextStateChangeMs is not None and ms > self.nextStateChangeMs:
  76. if self.state == 'stopped':
  77. pass
  78. elif self.state == 'started':
  79. self._do_note_on(ms)
  80. self.nextStateChangeMs += self.cfg.noteOnDurMs
  81. self.state = 'note_on'
  82. elif self.state == 'note_on':
  83. self._do_note_off(ms)
  84. self.nextStateChangeMs += self.cfg.noteOffDurMs
  85. self.state = 'note_off'
  86. elif self.state == 'note_off':
  87. if self.playOnlyFl:
  88. if not self._do_play_only_update():
  89. self.stop(ms)
  90. self.state = 'stopped'
  91. else:
  92. if self._do_analysis(ms):
  93. if not self._start_new_db_target():
  94. self.stop(ms)
  95. self.state = 'stopped'
  96. print("DONE!")
  97. # if the state was not changed to 'stopped'
  98. if self.state == 'note_off':
  99. self.state = 'started'
  100. def _calc_play_only_pulse_us( self, pitch, targetDb ):
  101. pulseDbL = []
  102. for d in self.measD[ pitch ]:
  103. if d['targetDb'] == targetDb and d['matchFl']==True:
  104. pulseDbL.append( ( d['pulse_us'], d[self.cfg.dbSrcLabel]['db']) )
  105. if len(pulseDbL) == 0:
  106. return -1
  107. pulseL,dbL = zip(*pulseDbL)
  108. # TODO: make a weighted average based on db error
  109. return np.mean(pulseL)
  110. def _do_play_only_update( self ):
  111. if self.curPitchIdx >= 0:
  112. self._meas_note( self.cfg.pitchL[self.curPitchIdx], self.curPulseUs )
  113. self.curPitchIdx +=1
  114. if self.curPitchIdx >= len(self.cfg.pitchL):
  115. self.curPitchIdx = 0
  116. self.curTargetDbIdx += 1
  117. if self.curTargetDbIdx >= len(self.cfg.targetDbL):
  118. return False
  119. pitch = self.cfg.pitchL[ self.curPitchIdx ]
  120. targetDb = self.cfg.targetDbL[ self.curTargetDbIdx ]
  121. self.curPulseUs = self._calc_play_only_pulse_us( pitch, targetDb )
  122. self.curTargetDb = targetDb
  123. if self.curPulseUs == -1:
  124. print("Pitch:%i TargetDb:%f not found." % (pitch,targetDb))
  125. return False
  126. print("Target db: %4.1f" % (targetDb))
  127. return True
  128. def _get_init_pulseDbD( self ):
  129. initPulseDbListD = {}
  130. print("Calculating initial calibration search us/db lists ...")
  131. if self.cfg.inDir is not None:
  132. for pitch in self.cfg.pitchL:
  133. print(pitch)
  134. inDir = os.path.expanduser( self.cfg.inDir )
  135. usL,dbL,_,_,_ = get_merged_pulse_db_measurements( inDir, pitch, self.cfg.analysisD )
  136. initPulseDbListD[pitch] = [ (us,db) for us,db in zip(usL,dbL) ]
  137. return initPulseDbListD
  138. def _get_duty_cycle( self, pitch, pulseUsec ):
  139. dutyPct = 50
  140. if pitch in self.cfg.holdDutyPctD:
  141. dutyPct = self.cfg.holdDutyPctD[pitch][0][1]
  142. for refUsec,refDuty in self.cfg.holdDutyPctD[pitch]:
  143. if pulseUsec < refUsec:
  144. break
  145. dutyPct = refDuty
  146. return dutyPct
  147. def _set_duty_cycle( self, pitch, pulseUsec ):
  148. dutyPct = self._get_duty_cycle( pitch, pulseUsec )
  149. if pitch not in self.curDutyPctD or self.curDutyPctD[pitch] != dutyPct:
  150. self.curDutyPctD[pitch] = dutyPct
  151. self.api.set_pwm_duty( pitch, dutyPct )
  152. print("Hold Duty Set:",dutyPct)
  153. self.skipMeasFl = True
  154. return dutyPct
  155. def _do_note_on(self,ms):
  156. self.curNoteStartMs = ms
  157. pitch = self.cfg.pitchL[ self.curPitchIdx]
  158. if self.midi is not None:
  159. self.midi.send_note_on( pitch, 60 )
  160. else:
  161. self._set_duty_cycle( pitch, self.curPulseUs )
  162. self.api.note_on_us( pitch, self.curPulseUs )
  163. print("note-on: ",pitch," ",self.curPulseUs," us")
  164. def _do_note_off(self,ms):
  165. self.noteAnnotationL.append( { 'beg_ms':self.curNoteStartMs-self.startMs, 'end_ms':ms-self.startMs, 'midi_pitch':self.cfg.pitchL[ self.curPitchIdx], 'pulse_us':self.curPulseUs } )
  166. if self.midi is not None:
  167. self.midi.send_note_off( self.cfg.pitchL[ self.curPitchIdx] )
  168. else:
  169. for pitch in self.cfg.pitchL:
  170. self.api.note_off( pitch )
  171. #print("note-off: ",self.cfg.pitchL[ self.curPitchIdx])
  172. def _proportional_step( self, targetDb, dbL, pulseL ):
  173. curPulse,curDb = self.pulseDbL[-1]
  174. # get the point closest to the target db
  175. i = np.argmin( np.array(dbL) - targetDb )
  176. # find the percentage difference to the target - based on the closest point
  177. pd = abs(curDb-targetDb) / abs(curDb - dbL[i])
  178. #
  179. delta_pulse = pd * abs(curPulse - pulseL[i])
  180. print("prop:",pd,"delta_pulse:",delta_pulse)
  181. return int(round(curPulse + np.sign(targetDb - curDb) * delta_pulse))
  182. def _step( self, targetDb ):
  183. # get the last two pulse/db samples
  184. pulse0,db0 = self.pulseDbL[-2]
  185. pulse1,db1 = self.pulseDbL[-1]
  186. # microseconds per decibel for the last two points
  187. us_per_db = abs(pulse0-pulse1) / abs(db0-db1)
  188. if us_per_db == 0:
  189. us_per_db = 10 # ************************************** CONSTANT ***********************
  190. # calcuate the decibels we need to move from the last point
  191. error_db = targetDb - db1
  192. print("us_per_db:",us_per_db," error db:", error_db )
  193. return pulse1 + us_per_db * error_db
  194. def _calc_next_pulse_us( self, targetDb ):
  195. # sort pulseDb ascending on db
  196. pulseDbL = sorted( self.pulseDbL, key=lambda x: x[1] )
  197. # get the set of us/db values tried so far
  198. pulseL,dbL = zip(*pulseDbL)
  199. max_i = np.argmax(dbL)
  200. min_i = np.argmin(dbL)
  201. # if the targetDb is greater than the max. db value achieved so far
  202. if targetDb > dbL[max_i]:
  203. pu = pulseL[max_i] + self.deltaUpMult * 500
  204. self.deltaUpMult += 1
  205. # if the targetDb is less than the min. db value achieved so far
  206. elif targetDb < dbL[min_i]:
  207. pu = pulseL[min_i] - self.deltaDnMult * 500
  208. self.deltaDnMult += 1
  209. if self.maxTooShortPulseUs is not None and pu < self.maxTooShortPulseUs:
  210. # BUG: this is a problem is self.pulseL[min_i] is <= than self.maxTooShortPulseUs
  211. # the abs() covers the problem to prevent decreasing from maxTooShortPulseus
  212. pu = self.maxTooShortPulseUs + (abs(pulseL[min_i] - self.maxTooShortPulseUs))/2
  213. self.deltaDnMult = 1
  214. else:
  215. # the targetDb value is inside the min/max range of the db values acheived so far
  216. self.deltaUpMult = 1
  217. self.deltaDnMult = 1
  218. # interpolate the new pulse value based on the values seen so far
  219. # TODO: use only closest 5 values rather than all values
  220. pu = np.interp([targetDb],dbL,pulseL)
  221. # the selected pulse has already been sampled
  222. if int(pu) in pulseL:
  223. pu = self._step(targetDb )
  224. return max(min(pu,self.cfg.maxPulseUs),self.cfg.minPulseUs)
  225. def _do_analysis(self,ms):
  226. analysisDoneFl = False
  227. midi_pitch = self.cfg.pitchL[self.curPitchIdx]
  228. pulse_us = self.curPulseUs
  229. measD = self._meas_note(midi_pitch,pulse_us)
  230. # if the the 'skip' flag is set then don't analyze this note
  231. if self.skipMeasFl:
  232. self.skipMeasFl = False
  233. print("SKIP")
  234. else:
  235. db = measD[self.cfg.dbSrcLabel]['db']
  236. durMs = measD['hm']['durMs']
  237. # if this note is shorter than the minimum allowable duration
  238. if durMs < self.cfg.minMeasDurMs:
  239. print("SHORT!")
  240. if self.maxTooShortPulseUs is None or self.curPulseUs > self.maxTooShortPulseUs:
  241. self.maxTooShortPulseUs = self.curPulseUs
  242. if self.lastAudiblePulseUs is not None and self.curPulseUs < self.lastAudiblePulseUs:
  243. self.curPulseUs = self.lastAudiblePulseUs
  244. else:
  245. self.curPulseUs = self.cfg.initPulseUs
  246. else:
  247. # this is a valid measurement, store it to the pulse-db table
  248. self.pulseDbL.append( (self.curPulseUs,db) )
  249. # track the most recent audible note (to return to if a successive note is too short)
  250. self.lastAudiblePulseUs = self.curPulseUs
  251. # calc the upper and lower bounds db range
  252. lwr_db = self.curTargetDb * ((100.0 - self.cfg.tolDbPct)/100.0)
  253. upr_db = self.curTargetDb * ((100.0 + self.cfg.tolDbPct)/100.0)
  254. # if this note was inside the db range then set the 'match' flag
  255. if lwr_db <= db and db <= upr_db:
  256. self.curMatchN += 1
  257. measD['matchFl'] = True
  258. print("MATCH!")
  259. # calculate the next pulse length
  260. self.curPulseUs = int(self._calc_next_pulse_us(self.curTargetDb))
  261. # if at least minMatchN matches have been made on this pitch/targetDb
  262. if self.curMatchN >= self.cfg.minMatchN:
  263. analysisDoneFl = True
  264. self.successN += 1
  265. print("Anysis Done: Success")
  266. # if at least maxAttemptN match attempts have been made without success
  267. self.curAttemptN += 1
  268. if self.curAttemptN >= self.cfg.maxAttemptN:
  269. analysisDoneFl = True
  270. self.failN += 1
  271. print("Analysis Done: Fail")
  272. if midi_pitch not in self.measD:
  273. self.measD[ midi_pitch ] = []
  274. self.measD[ midi_pitch ].append( measD )
  275. return analysisDoneFl
  276. def _meas_note(self,midi_pitch,pulse_us):
  277. # get the annotation information for the last note
  278. annD = self.noteAnnotationL[-1]
  279. buf_result = self.audio.linear_buffer()
  280. if buf_result:
  281. sigV = buf_result.value
  282. # get the annotated begin and end of the note as sample indexes into sigV
  283. bi = int(round(annD['beg_ms'] * self.audio.srate / 1000))
  284. ei = int(round(annD['end_ms'] * self.audio.srate / 1000))
  285. # calculate half the length of the note-off duration in samples
  286. noteOffSmp_o_2 = int(round( (self.cfg.noteOffDurMs/2) * self.audio.srate / 1000))
  287. # widen the note analysis space noteOffSmp_o_2 samples pre/post the annotated begin/end of the note
  288. bi = max(0,bi - noteOffSmp_o_2)
  289. ei = min(ei+noteOffSmp_o_2,sigV.shape[0]-1)
  290. ar = types.SimpleNamespace(**self.cfg.analysisD)
  291. # shift the annotatd begin/end of the note to be relative to index bi
  292. begMs = noteOffSmp_o_2 * 1000 / self.audio.srate
  293. endMs = begMs + (annD['end_ms'] - annD['beg_ms'])
  294. #print("MEAS:",begMs,endMs,bi,ei,sigV.shape,self.audio.is_recording_enabled(),ar)
  295. # analyze the note
  296. resD = rms_analyze_one_rt_note( sigV[bi:ei], self.audio.srate, begMs, endMs, midi_pitch, rmsWndMs=ar.rmsWndMs, rmsHopMs=ar.rmsHopMs, dbLinRef=ar.dbLinRef, harmCandN=ar.harmCandN, harmN=ar.harmN, durDecayPct=ar.durDecayPct )
  297. resD["pulse_us"] = pulse_us
  298. resD["midi_pitch"] = midi_pitch
  299. resD["beg_ms"] = annD['beg_ms']
  300. resD['end_ms'] = annD['end_ms']
  301. resD['skipMeasFl'] = self.skipMeasFl
  302. resD['matchFl'] = False
  303. resD['targetDb'] = self.curTargetDb
  304. resD['annIdx'] = len(self.noteAnnotationL)-1
  305. print( "%4.1f hm:%4.1f (%4.1f) %4i td:%4.1f (%4.1f) %4i" % (self.curTargetDb,resD['hm']['db'], resD['hm']['db']-self.curTargetDb, resD['hm']['durMs'], resD['td']['db'], resD['td']['db']-self.curTargetDb, resD['td']['durMs']))
  306. return resD
  307. def _start_new_db_target(self):
  308. self.curTargetDbIdx += 1
  309. # if all db targets have been queried then advance to the next pitch
  310. if self.curTargetDbIdx >= len(self.cfg.targetDbL):
  311. self.curTargetDbIdx = 0
  312. self.curPitchIdx += 1
  313. # if all pitches have been queried then we are done
  314. if self.curPitchIdx >= len(self.cfg.pitchL):
  315. return False
  316. # reset the variables prior to begining the next target search
  317. self.curTargetDb = self.cfg.targetDbL[ self.curTargetDbIdx ]
  318. self.curMatchN = 0
  319. self.curAttemptN = 0
  320. self.lastAudiblePulseUs = None
  321. self.maxTooShortPulseUs = None
  322. self.pulseDbL = []
  323. self.pulseDbL = self.initPulseDbListD[ self.cfg.pitchL[ self.curPitchIdx ] ]
  324. self.deltaUpMult = 1
  325. self.deltaDnMult = 1
  326. return True
  327. def _write_16_bit_wav_file( self, fn ):
  328. srate = int(self.audio.srate)
  329. buf_result = self.audio.linear_buffer()
  330. sigV = buf_result.value
  331. smpN = sigV.shape[0]
  332. chN = 1
  333. sigV = np.squeeze(sigV.reshape( smpN * chN, )) * 0x7fff
  334. sigL = [ int(round(sigV[i])) for i in range(smpN) ]
  335. sigA = array.array('h',sigL)
  336. with wave.open( fn, "wb") as f:
  337. bits = 16
  338. bits_per_byte = 8
  339. f.setparams((chN, bits//bits_per_byte, srate, 0, 'NONE', 'not compressed'))
  340. f.writeframes(sigA)
  341. def _save_results( self ):
  342. if self.measD is None or len(self.measD) == 0:
  343. return
  344. outDir = os.path.expanduser( self.cfg.outDir )
  345. if not os.path.isdir(outDir):
  346. os.mkdir(outDir)
  347. outDir = os.path.join( outDir, self.cfg.outLabel )
  348. if not os.path.isdir(outDir):
  349. os.mkdir(outDir)
  350. i = 0
  351. while( os.path.isdir( os.path.join(outDir,"%i" % i )) ):
  352. i += 1
  353. outDir = os.path.join( outDir, "%i" % i )
  354. os.mkdir(outDir)
  355. self._write_16_bit_wav_file( os.path.join(outDir,"audio.wav"))
  356. d = {'cfg':self.cfg.__dict__, 'measD': self.measD, 'annoteL':self.noteAnnotationL }
  357. with open( os.path.join(outDir,"meas.json"), "w") as f:
  358. json.dump(d,f)