annotate src/midiEventHolder.cpp @ 20:7bb9ab04ee89

real-time and offline version working well
author Andrew N Robertson <andrew.robertson@eecs.qmul.ac.uk>
date Fri, 25 Nov 2011 16:52:33 +0000
parents 2e17f0fdeaef
children 11e3119ce6b4
rev   line source
andrew@0 1 /*
andrew@0 2 * midiEventHolder.cpp
andrew@0 3 * midiCannamReader3
andrew@0 4 *
andrew@0 5 * Created by Andrew on 19/07/2011.
andrew@0 6 * Copyright 2011 QMUL. All rights reserved.
andrew@0 7 *
andrew@0 8 */
andrew@0 9
andrew@0 10 #include "midiEventHolder.h"
andrew@0 11
andrew@0 12 midiEventHolder::midiEventHolder(){
andrew@0 13 // recordedNoteOnIndex = 0;
andrew@0 14
andrew@20 15 runningInRealTime = false;
andrew@20 16 bayesStruct.realTimeMode = &runningInRealTime;
andrew@20 17
andrew@0 18 width = ofGetWidth();
andrew@0 19 height = ofGetHeight();
andrew@0 20 screenWidth= &width;
andrew@0 21 screenHeight = &height;
andrew@0 22
andrew@0 23 ticksPerScreen = 4000;
andrew@0 24 tickLocation = 0;
andrew@0 25 pulsesPerQuarternote = 240;
andrew@0 26 noteArrayIndex = 0;
andrew@0 27 noteMinimum = 30;
andrew@0 28 noteMaximum = 96;
andrew@0 29
andrew@4 30 minimumMatchSpeed = 0.0;
andrew@4 31 maximumMatchSpeed = 2.0;
andrew@2 32
andrew@0 33 likelihoodWidth = 100;
andrew@20 34 likelihoodToNoiseRatio = 0.08;//was 0.02 on 18/11/11, changing to give more weight to observations
andrew@0 35
andrew@9 36 bayesStruct.speedLikelihoodNoise = 0.1;//was 0.05
andrew@2 37 bayesStruct.speedDecayWidth = 20;
andrew@2 38 bayesStruct.speedDecayAmount = 10;
andrew@2 39
andrew@20 40
andrew@14 41
andrew@3 42 speedPriorValue = 1.0;
andrew@2 43
andrew@2 44 matchWindowWidth = 8000;//window size for matching in ms
andrew@0 45
andrew@1 46 bayesStruct.resetSize(matchWindowWidth);
andrew@2 47 bayesStruct.setPositionDistributionScalar(1);
andrew@2 48
andrew@0 49 bayesStruct.resetSpeedSize(200);
andrew@0 50 bayesStruct.setRelativeSpeedScalar(0.01);
andrew@0 51 bayesStruct.relativeSpeedPrior.getMaximum();
andrew@2 52 //bayesStruct.simpleExample();
andrew@2 53
andrew@6 54
andrew@6 55 speedWindowWidthMillis = 4000;
andrew@3 56 speedPriorValue = 1.0;
andrew@0 57 noteHeight = (*screenHeight) / (float)(noteMaximum - noteMinimum);
andrew@4 58
andrew@6 59 confidenceWeightingUsed = false;
andrew@6 60
andrew@9 61 drawPhaseMode = true;
andrew@9 62
andrew@4 63 printf("lookup index %f value %f\n", bayesStruct.prior.getLookupIndex(100, 30., 10.0), bayesStruct.prior.gaussianLookupTable[(int)bayesStruct.prior.getLookupIndex(100, 30., 10.0)]);
andrew@0 64 }
andrew@0 65
andrew@0 66
andrew@0 67
andrew@0 68 void midiEventHolder::reset(){
andrew@2 69 //called when we start playing
andrew@2 70
andrew@0 71 noteArrayIndex = 0;
andrew@0 72 tickLocation = 0;
andrew@14 73 lastPeriodUpdateTime = getTimeNow(0);//ofGetElapsedTimeMillis();
andrew@14 74 bayesStruct.lastEventTime = getTimeNow(0);//ofGetElapsedTimeMillis();
andrew@0 75 numberOfScreensIn = 0;
andrew@0 76 // recordedNoteOnIndex = 0;
andrew@0 77 bayesStruct.setNewDistributionOffsets(0);
andrew@0 78 bayesStruct.posterior.offset = 0;
andrew@0 79
andrew@0 80 playedEventTimes.clear();
andrew@0 81 playedNoteOnMatrix.clear();
andrew@0 82 matchMatrix.clear();
andrew@5 83 bestMatchIndex = 0;
andrew@0 84
andrew@0 85 bayesStruct.resetSpeedToOne();
andrew@3 86 bayesStruct.setSpeedPrior(speedPriorValue);
andrew@5 87 setMatchedNotesBackToFalse();
andrew@5 88 }
andrew@5 89
andrew@5 90 void midiEventHolder::setMatchedNotesBackToFalse(){
andrew@5 91 for (int i = 0;i < noteOnMatches.size();i++)
andrew@5 92 noteOnMatches[i] = false;
andrew@0 93 }
andrew@0 94
andrew@1 95 void midiEventHolder::clearAllEvents(){
andrew@1 96 recordedNoteOnMatrix.clear();
andrew@1 97 matchesFound.clear();
andrew@1 98 noteOnMatches.clear();
andrew@1 99 recordedEventTimes.clear();
andrew@1 100
andrew@1 101 //played events:
andrew@1 102 playedEventTimes.clear();
andrew@1 103 playedNoteOnMatrix.clear();
andrew@1 104 matchMatrix.clear();
andrew@1 105 }
andrew@1 106
andrew@0 107 void midiEventHolder::printNotes(){
andrew@14 108 printf("RECORDED MATRIX\n");
andrew@0 109 for (int i = 0;i < recordedNoteOnMatrix.size();i++){
andrew@14 110 printf("ticktime %i :: pitch %i @ millis %f\n", recordedNoteOnMatrix[i][0], recordedNoteOnMatrix[i][1], recordedEventTimes[i]);
andrew@0 111 }
andrew@0 112 }
andrew@0 113
andrew@0 114
andrew@0 115 double midiEventHolder::getEventTimeTicks(double millis){
andrew@0 116 return (millis * pulsesPerQuarternote / period);
andrew@0 117 }
andrew@0 118
andrew@0 119 double midiEventHolder::getEventTimeMillis(double ticks){
andrew@0 120 return (period * ticks / (double) pulsesPerQuarternote);
andrew@0 121 }
andrew@0 122
andrew@0 123 void midiEventHolder::newNoteOnEvent(int pitch, int velocity, double timePlayed){
andrew@0 124
andrew@0 125 //MOVE INTO BAYESSTRUCT?? XXX
andrew@0 126 //bayesStruct.copyPriorToPosterior();
andrew@0 127 //why was this here??
andrew@0 128 bayesStruct.prior.copyFromDynamicVector(bayesStruct.posterior);//try the otehr way
andrew@0 129 //bayesStruct.copyPriorToPosterior();
andrew@0 130 //need to get new MAP position and set the offset of the arrays
andrew@0 131 //currently bestEstimate is the approx for the new MAP position
andrew@0 132
andrew@0 133
andrew@0 134 //add the new event to our played information matrix
andrew@0 135 IntVector v;
andrew@0 136 v.push_back(pitch);
andrew@0 137 v.push_back(velocity);
andrew@0 138 playedNoteOnMatrix.push_back(v);
andrew@0 139
andrew@0 140
andrew@0 141 //would update the arrays at this point to show where out current location (phase) and tempo is.
andrew@2 142 // double timeNow = ofGetElapsedTimeMillis() - startTime;
andrew@2 143 double timeNow = timePlayed;// - startTime;
andrew@2 144 recentNoteOnTime = timePlayed;
andrew@0 145
andrew@2 146 // printf("Max time %f OF time %f \n", timePlayed, timeNow);
andrew@0 147
andrew@0 148 playedEventTimes.push_back(timePlayed);
andrew@0 149
andrew@2 150 // double timeDifference = ofGetElapsedTimeMillis() - bayesStruct.lastEventTime;
andrew@2 151 double timeDifference = timePlayed - bayesStruct.lastEventTime;
andrew@0 152
andrew@15 153
andrew@15 154
andrew@15 155 printf("note %i played at %f and last event %f time difference %f and current best estmate %f\n", pitch, timePlayed, bayesStruct.lastEventTime, timeDifference, bayesStruct.bestEstimate);
andrew@0 156 //addnoise to the tempo distribution
andrew@2 157 //bayesStruct.decaySpeedDistribution(timeDifference);
andrew@2 158 if (timeDifference > 50){
andrew@2 159 bayesStruct.addGaussianNoiseToSpeedPosterior(timeDifference * 10 / 100.);
andrew@2 160 // bayesStruct.addTriangularNoiseToSpeedPosterior(timeDifference * 10 / 100.);
andrew@2 161 }
andrew@2 162
andrew@2 163 bayesStruct.updateTmpBestEstimate(timeDifference);// debug - didnt work bayesStruct.bestEstimate = bayesStruct.tmpBestEstimate;
andrew@14 164 bayesStruct.updateBestEstimate(timeDifference);
andrew@14 165 bayesStruct.lastBestEstimateUpdateTime = getTimeNow(timePlayed);
andrew@0 166
andrew@0 167 // double newMAPestimateTime = bayesStruct.posterior.getIndexInRealTerms(bayesStruct.posterior.MAPestimate);
andrew@0 168 //was offset + bayesStruct.posterior.MAPestimate; but this doesnt include scalar to convert to millis
andrew@0 169
andrew@0 170 timeString = "Pitch:"+ofToString(pitch);
andrew@0 171 timeString += ", time now:"+ofToString(timeNow, 1);
andrew@0 172 timeString += " TD "+ofToString(timeDifference, 1);
andrew@0 173 timeString += " offset "+ofToString(bayesStruct.posterior.offset , 0);
andrew@0 174 timeString += " map Est: "+ofToString(bayesStruct.posterior.MAPestimate, 0);
andrew@0 175 // timeString += " Previous time" + ofToString(newMAPestimateTime,0);
andrew@9 176 timeString += " speedMap "+ofToString(bayesStruct.relativeSpeedPosterior.integratedEstimate, 2);
andrew@9 177 timeString += " :: "+ofToString(bayesStruct.relativeSpeedPosterior.getIndexInRealTerms(bayesStruct.relativeSpeedPosterior.integratedEstimate), 2);
andrew@0 178
andrew@0 179 // newMAPestimateTime += (timeDifference * bayesStruct.relativeSpeedPosterior.getIndexInRealTerms(bayesStruct.relativeSpeedPosterior.MAPestimate));
andrew@0 180 // timeString += " : Predicted MAP time" + ofToString(newMAPestimateTime,0);
andrew@0 181
andrew@0 182 //then we recalculate the window start based on MAP being central
andrew@0 183 //then we do the matches on these and the likelihood on these.
andrew@0 184
andrew@0 185 bayesStruct.setNewDistributionOffsets(max(0., bayesStruct.bestEstimate - (bayesStruct.prior.scalar*bayesStruct.prior.arraySize/2)));
andrew@0 186 // bayesStruct.prior.offset = max(0.,newMAPestimateTime - (bayesStruct.prior.scalar*bayesStruct.prior.arraySize/2));
andrew@0 187
andrew@0 188 timeString += " \n : new offset " + ofToString(bayesStruct.prior.offset , 0);
andrew@0 189 timeString += " \n best estimate "+ofToString(bayesStruct.bestEstimate, 1);
andrew@10 190 timeString += " error "+ofToString(minimumMatchError, 0);
andrew@9 191 timeString += " map "+ofToString(bayesStruct.relativeSpeedPosterior.integratedEstimate, 1);
andrew@11 192 timeString += " rel speed "+ofToString(bayesStruct.relativeSpeedPosterior.getIndexInRealTerms(bayesStruct.relativeSpeedPosterior.integratedEstimate), 2);
andrew@0 193
andrew@0 194
andrew@0 195 //be able to draw the prior in correct location relative to the midi notes
andrew@2 196 //this calculates the cross update of all possible speeds and all possible positions
andrew@0 197 bayesStruct.crossUpdateArrays(bayesStruct.posterior, bayesStruct.relativeSpeedPosterior, timeDifference);
andrew@0 198
andrew@0 199
andrew@0 200 timeString += " new OFF "+ofToString(bayesStruct.bestEstimate - (bayesStruct.prior.scalar*bayesStruct.prior.arraySize/2), 1);
andrew@0 201 timeString += " notearrayindex "+ofToString(noteArrayIndex, 0);
andrew@0 202 //when this is off teh screen there is a problem somehow XXX
andrew@0 203 bayesStruct.posterior.offset = max(0., bayesStruct.bestEstimate - (bayesStruct.prior.scalar*bayesStruct.prior.arraySize/2));
andrew@0 204 // bayesStruct.prior.offset = max(0., bayesStruct.bestEstimate - (bayesStruct.prior.scalar*bayesStruct.prior.arraySize/2));
andrew@0 205 //trying to switch to prior
andrew@0 206
andrew@2 207 //bayesStruct.lastEventTime = ofGetElapsedTimeMillis();
andrew@2 208 bayesStruct.lastEventTime = timePlayed;
andrew@0 209
andrew@0 210 //do the cross update to find current posterior for location
andrew@1 211 // totalConfidence= 0;
andrew@0 212 int numberOfMatchesFound = findLocalMatches(pitch);
andrew@0 213 setMatchLikelihoods(numberOfMatchesFound);
andrew@0 214 bayesStruct.calculatePosterior();
andrew@0 215
andrew@0 216 //having found matches we have matches for new note and matches for previous notes
andrew@12 217 //if (!confidenceWeightingUsed)
andrew@0 218 findLocalTempoPairs();
andrew@12 219 //else
andrew@12 220 //findLocalTempoPairsWeightedForConfidence();
andrew@0 221
andrew@2 222 //bayesStruct.addGaussianNoiseToSpeedPosterior(10);
andrew@0 223
andrew@0 224 }
andrew@0 225
andrew@14 226 double midiEventHolder::getTimeNow(double eventTime){
andrew@14 227 double timeNow = eventTime;
andrew@14 228 if (runningInRealTime)
andrew@14 229 timeNow = ofGetElapsedTimeMillis();
andrew@14 230 return timeNow;
andrew@14 231 }
andrew@14 232
andrew@0 233 int midiEventHolder::findLocalMatches(int notePitch){
andrew@0 234
andrew@0 235 //here we find the matches to the new note within appropriate range
andrew@0 236
andrew@1 237 matchString = "";
andrew@0 238
andrew@0 239 windowStartTime = max(0.0,(bayesStruct.bestEstimate - matchWindowWidth/2));//was playPositionInMillis
andrew@15 240 cout << "best estimate is " << bayesStruct.bestEstimate << endl;
andrew@0 241 int numberOfMatches = findMatch(notePitch, windowStartTime, windowStartTime + matchWindowWidth);
andrew@5 242
andrew@0 243
andrew@1 244 matchString += " pitch: "+ofToString(notePitch)+" matches "+ofToString(numberOfMatches)+" win start "+ofToString(windowStartTime);
andrew@1 245
andrew@0 246 return numberOfMatches;
andrew@0 247
andrew@0 248
andrew@0 249 }
andrew@0 250
andrew@0 251
andrew@0 252 void midiEventHolder::setMatchLikelihoods(int numberOfMatches){
andrew@0 253 //reset the offset to match the prior
andrew@0 254 bayesStruct.likelihood.offset = bayesStruct.prior.offset;
andrew@0 255 bayesStruct.likelihood.zero();//set to zero
andrew@0 256
andrew@2 257 double quantity = likelihoodToNoiseRatio / numberOfMatches;
andrew@0 258
andrew@0 259 for (int i = 0;i < numberOfMatches && matchesFound[i] >= 0 && matchesFound[i] < recordedEventTimes.size();i++){
andrew@0 260 // printf("match times %i of %i::%f adding likelihood to %f\n", i, numberOfMatches, recordedEventTimes[matchesFound[i]], recordedEventTimes[matchesFound[i]] - bayesStruct.likelihood.offset);
andrew@0 261 //this is the vent time since start of file
andrew@0 262 if (recordedEventTimes[matchesFound[i]] - bayesStruct.likelihood.offset < bayesStruct.likelihood.arraySize){
andrew@1 263 // double confidenceMeasure = 0;
andrew@1 264 // if (totalConfidence > 0)
andrew@6 265 // confidenceMeasure = bayesStruct.posterior.getValueAtMillis(recordedEventTimes[matchesFound[i]])/totalConfidence;
andrew@2 266
andrew@2 267 bayesStruct.likelihood.addGaussianShape(recordedEventTimes[matchesFound[i]] - bayesStruct.likelihood.offset, likelihoodWidth, quantity);//* confidenceMeasure
andrew@0 268 }//end if
andrew@0 269 }
andrew@2 270 bayesStruct.likelihood.addConstant((1-likelihoodToNoiseRatio)/bayesStruct.likelihood.length);
andrew@0 271 }
andrew@0 272
andrew@0 273 int midiEventHolder::findMatch(const int& notePitch, const int& startTime, const int& endTime){
andrew@0 274
andrew@0 275 matchesFound.clear();
andrew@0 276 int startIndex = 0;
andrew@10 277
andrew@0 278 if (recordedEventTimes.size() > 0){
andrew@0 279
andrew@0 280 //get to the right range of events to check in
andrew@0 281 while (startIndex < recordedEventTimes.size() && recordedEventTimes[startIndex] < startTime)
andrew@0 282 startIndex++;
andrew@0 283
andrew@0 284 }
andrew@0 285
andrew@6 286 IntVector v;
andrew@6 287 DoubleVector d;
andrew@10 288 double tmpError = 100000.;//v high error
andrew@6 289
andrew@5 290 double minimumConfidence = 0;
andrew@0 291 while (startIndex < recordedEventTimes.size() && recordedEventTimes[startIndex] < endTime){
andrew@0 292 if (recordedNoteOnMatrix[startIndex][1] == notePitch){
andrew@6 293
andrew@0 294 matchesFound.push_back(startIndex);
andrew@6 295 v.push_back(startIndex);
andrew@5 296 double eventConfidence = bayesStruct.posterior.getValueAtMillis(recordedEventTimes[startIndex]);
andrew@5 297 if (eventConfidence > minimumConfidence){
andrew@5 298 minimumConfidence = eventConfidence;
andrew@5 299 bestMatchIndex = startIndex;
andrew@5 300 }
andrew@6 301 d.push_back(eventConfidence);
andrew@5 302
andrew@6 303 double confidence = eventConfidence;//bayesStruct.posterior.getValueAtMillis(mouseX);
andrew@1 304 // recordedEventTimes[startIndex]);
andrew@1 305 matchString += "["+ofToString(startIndex)+"] = "+ofToString(confidence, 3)+" .";
andrew@10 306
andrew@10 307 if (abs(recordedEventTimes[startIndex] - bayesStruct.bestEstimate) < tmpError){
andrew@10 308 //record the error between expected and observed times
andrew@10 309 tmpError = abs(recordedEventTimes[startIndex] - bayesStruct.bestEstimate);
andrew@12 310 minimumMatchError = tmpError;//recordedEventTimes[startIndex] - bayesStruct.bestEstimate;
andrew@10 311 }
andrew@10 312
andrew@0 313 }
andrew@0 314 startIndex++;
andrew@0 315 }
andrew@5 316
andrew@5 317
andrew@0 318 // printf("%i MATCHES TO Note %i found\n", (int)matchesFound.size(), notePitch);
andrew@0 319 int size = matchesFound.size();
andrew@5 320 if (size > 0)
andrew@5 321 noteOnMatches[bestMatchIndex] = true;
andrew@5 322
andrew@6 323 v.insert(v.begin() , (int)size);
andrew@6 324 d.insert(d.begin() , (double)size);
andrew@6 325
andrew@6 326 //v.push_back(size);
andrew@6 327 //d.push_back(size);
andrew@6 328 //for (int i = 0;i < matchesFound.size()+1;i++){
andrew@6 329 // v.push_back(matchesFound[i]);
andrew@6 330 // printf("match %i,[%i] is %i\n", startIndex, i, v[i]);
andrew@6 331 //}
andrew@6 332
andrew@0 333
andrew@0 334 matchMatrix.push_back(v);
andrew@6 335 matchConfidence.push_back(d);
andrew@0 336
andrew@15 337 printf("BEST MATCH TO note %i, start time %i, endtime %i, time %i is recorded time %i, confidence %0.2f\n", notePitch, startTime, endTime, (int) recordedEventTimes[bestMatchIndex], minimumConfidence);
andrew@14 338
andrew@0 339 return size;
andrew@0 340 }
andrew@0 341
andrew@0 342 bool midiEventHolder::checkIfMatchedNote(const int& tmpIndex){
andrew@0 343 for (int i = 0;i < matchesFound.size();i++){
andrew@0 344 if (matchesFound[i] == tmpIndex)
andrew@0 345 return true;
andrew@0 346 }
andrew@0 347 return false;
andrew@0 348 }
andrew@0 349
andrew@0 350
andrew@0 351
andrew@0 352 void midiEventHolder::findLocalTempoPairs(){
andrew@6 353
andrew@0 354 int currentPlayedIndex = playedNoteOnMatrix.size()-1;
andrew@6 355 // printf("played %i : %i, vel %i\n", currentPlayedIndex, playedNoteOnMatrix[currentPlayedIndex][0], playedNoteOnMatrix[currentPlayedIndex][1]);
andrew@6 356 // printMatchesFound();
andrew@6 357 // printMatchMatrix();
andrew@6 358 // printf("possible notes \n");
andrew@9 359 bool needToUpdate = false;
andrew@9 360 bayesStruct.setLikelihoodToConstant();
andrew@0 361
andrew@0 362
andrew@0 363 for (int i = 0;i < matchMatrix[currentPlayedIndex][0];i++){
andrew@6 364 //iterate through the recently matched events - even dodgy matches included
andrew@6 365 //size, index of match0, index of match1, ....
andrew@9 366
andrew@9 367
andrew@0 368 int recordedCurrentIndex = matchMatrix[currentPlayedIndex][i+1];
andrew@0 369
andrew@0 370 int previousIndex = currentPlayedIndex-1;
andrew@9 371
andrew@0 372
andrew@6 373 while (previousIndex >= 0 && playedEventTimes[previousIndex] + speedWindowWidthMillis > playedEventTimes[currentPlayedIndex]) {
andrew@0 374 double playedTimeDifference = playedEventTimes[currentPlayedIndex] - playedEventTimes[previousIndex];
andrew@6 375
andrew@0 376 for (int k = 0;k < matchMatrix[previousIndex][0];k++){
andrew@0 377 int recordedPreviousIndex = matchMatrix[previousIndex][k+1];
andrew@0 378
andrew@6 379
andrew@0 380 double recordedTimeDifference = recordedEventTimes[recordedCurrentIndex] - recordedEventTimes[recordedPreviousIndex];
andrew@6 381
andrew@0 382
andrew@0 383 //we want the speed of the recording relative to that of the playing live
andrew@0 384
andrew@0 385 double speedRatio = recordedTimeDifference / playedTimeDifference;
andrew@0 386 if (speedRatio <= maximumMatchSpeed && speedRatio >= minimumMatchSpeed){
andrew@12 387 //adding in a prior that prefers 1
andrew@12 388 double priorWeighting = sin(speedRatio * PI/2);
andrew@12 389
andrew@12 390
andrew@6 391 /*
andrew@6 392 printf("(%i)", matchMatrix[currentPlayedIndex][i+1]);
andrew@6 393 printf("[%i] :: ", recordedPreviousIndex);
andrew@6 394 printf(" rec{%f} vs play(%f) ", recordedTimeDifference, playedTimeDifference);
andrew@6 395 printf("update on speed ratio %f\n", speedRatio);
andrew@6 396 */
andrew@1 397 // matchString += " speed: "+ofToString(speedRatio, 3);
andrew@6 398 // commented for debug
andrew@2 399
andrew@9 400 //bayesStruct.updateTempoDistribution(speedRatio, 0.1);//second paramter is confidence in the match
andrew@9 401 double amount = (1-bayesStruct.speedLikelihoodNoise)/10;
andrew@12 402 amount *= priorWeighting;
andrew@9 403 bayesStruct.updateTempoLikelihood(speedRatio, amount);
andrew@9 404 needToUpdate = true;
andrew@0 405 }
andrew@6 406 // printf("\n");
andrew@0 407 }
andrew@0 408
andrew@0 409 previousIndex--;
andrew@0 410 }//end while previousindex countdown
andrew@0 411 }//end for loop through possible current matches
andrew@0 412
andrew@9 413 if (needToUpdate)
andrew@9 414 bayesStruct.updateTempoDistribution();
andrew@9 415
andrew@2 416 //printf("current speed is %f\n", bayesStruct.relativeSpeedPosterior.getIndexInRealTerms(bayesStruct.relativeSpeedPosterior.MAPestimate));
andrew@0 417 }
andrew@0 418
andrew@0 419
andrew@6 420 void midiEventHolder::findLocalTempoPairsWeightedForConfidence(){
andrew@9 421 bool needToUpdate = false;
andrew@6 422
andrew@6 423 int currentPlayedIndex = playedNoteOnMatrix.size()-1;
andrew@6 424 // printf("played %i : %i, vel %i\n", currentPlayedIndex, playedNoteOnMatrix[currentPlayedIndex][0], playedNoteOnMatrix[currentPlayedIndex][1]);
andrew@6 425 // printMatchesFound();
andrew@6 426 // printMatchMatrix();
andrew@6 427 // printf("possible notes \n");
andrew@6 428
andrew@9 429 bayesStruct.setLikelihoodToConstant();
andrew@6 430
andrew@6 431 for (int i = 0;i < matchMatrix[currentPlayedIndex][0];i++){
andrew@6 432 //iterate through the recently matched events - even dodgy matches included
andrew@6 433 //size, index of match0, index of match1, ....
andrew@6 434 int recordedCurrentIndex = matchMatrix[currentPlayedIndex][i+1];
andrew@6 435
andrew@6 436 double currentMatchConfidence = matchConfidence[currentPlayedIndex][i+1];//new confidence
andrew@6 437
andrew@6 438 int previousIndex = currentPlayedIndex-1;
andrew@6 439
andrew@6 440 while (previousIndex >= 0 && playedEventTimes[previousIndex] + speedWindowWidthMillis > playedEventTimes[currentPlayedIndex]) {
andrew@6 441 double playedTimeDifference = playedEventTimes[currentPlayedIndex] - playedEventTimes[previousIndex];
andrew@6 442
andrew@6 443 for (int k = 0;k < matchMatrix[previousIndex][0];k++){
andrew@6 444 int recordedPreviousIndex = matchMatrix[previousIndex][k+1];
andrew@6 445
andrew@6 446 double previousMatchConfidence = matchConfidence[previousIndex][k+1];
andrew@6 447
andrew@6 448
andrew@6 449 double recordedTimeDifference = recordedEventTimes[recordedCurrentIndex] - recordedEventTimes[recordedPreviousIndex];
andrew@6 450
andrew@6 451
andrew@6 452 //we want the speed of the recording relative to that of the playing live
andrew@6 453
andrew@6 454 double speedRatio = recordedTimeDifference / playedTimeDifference;
andrew@6 455 if (speedRatio <= maximumMatchSpeed && speedRatio >= minimumMatchSpeed){
andrew@6 456
andrew@6 457 printf("(%i)", matchMatrix[currentPlayedIndex][i+1]);
andrew@6 458 printf("[%i] :: ", recordedPreviousIndex);
andrew@6 459 printf(" conf %f & %f ", currentMatchConfidence, previousMatchConfidence);
andrew@6 460 printf(" rec{%f} vs play(%f) ", recordedTimeDifference, playedTimeDifference);
andrew@6 461 printf("update on speed ratio %f\n", speedRatio);
andrew@6 462
andrew@6 463 // matchString += " speed: "+ofToString(speedRatio, 3);
andrew@6 464 // commented for debug
andrew@9 465 double weighting = previousMatchConfidence * currentMatchConfidence ;
andrew@9 466 double amount = (1-bayesStruct.speedLikelihoodNoise)*weighting/10;
andrew@9 467 bayesStruct.updateTempoLikelihood(speedRatio, amount);//second paramter is confidence in the match
andrew@9 468 needToUpdate = true;
andrew@6 469 }
andrew@6 470 // printf("\n");
andrew@6 471 }
andrew@6 472
andrew@6 473 previousIndex--;
andrew@6 474 }//end while previousindex countdown
andrew@6 475 }//end for loop through possible current matches
andrew@6 476
andrew@9 477 if (needToUpdate)
andrew@9 478 bayesStruct.updateTempoDistribution();
andrew@6 479 //printf("current speed is %f\n", bayesStruct.relativeSpeedPosterior.getIndexInRealTerms(bayesStruct.relativeSpeedPosterior.MAPestimate));
andrew@6 480 }
andrew@6 481
andrew@6 482
andrew@6 483
andrew@0 484 void midiEventHolder::updatePlayPosition(){
andrew@0 485
andrew@0 486 //in actual fact if we are changing the speed of the play position
andrew@0 487 //we will need to update this via the file
andrew@0 488
andrew@14 489 //actually time since beginning of file i think
andrew@14 490
andrew@15 491 double timeDifference = 0;
andrew@15 492 if (runningInRealTime)
andrew@15 493 timeDifference = ofGetElapsedTimeMillis() - lastPeriodUpdateTime;//elpased - lastperiodupdatetime
andrew@15 494
andrew@0 495 //this is time diff in milliseconds
andrew@0 496 //then we have
andrew@0 497 double quarterNoteIntervals = (timeDifference / period);
andrew@0 498 tickLocation = quarterNoteIntervals * pulsesPerQuarternote;
andrew@0 499
andrew@0 500 playPositionInMillis = timeDifference;//based on updating from when we change period
andrew@0 501 //this to be added
andrew@0 502
andrew@14 503 if (runningInRealTime)
andrew@14 504 bayesStruct.updateBestEstimate(timeDifference);
andrew@0 505
andrew@0 506 }
andrew@0 507
andrew@0 508
andrew@9 509 void midiEventHolder::drawMidiFile(){
andrew@9 510
andrew@0 511 //draws midi file on scrolling screen
andrew@0 512 int size = recordedNoteOnMatrix.size();
andrew@0 513 if (size > 0){
andrew@0 514
andrew@0 515 numberOfScreensIn = floor(bayesStruct.bestEstimate / getEventTimeMillis(ticksPerScreen));//rpounds down on no screens in
andrew@0 516
andrew@9 517 // numberOfScreensIn = tickLocation / ticksPerScreen;//rounds down
andrew@0 518 timeOffsetForScreen = getEventTimeMillis(numberOfScreensIn * ticksPerScreen);
andrew@0 519
andrew@11 520 while (noteArrayIndex < recordedNoteOnMatrix.size()-1 && tickLocation > recordedNoteOnMatrix[noteArrayIndex][0] )
andrew@0 521 noteArrayIndex++;
andrew@0 522
andrew@0 523
andrew@0 524 while (noteArrayIndex > 0 && noteArrayIndex < size && tickLocation < recordedNoteOnMatrix[noteArrayIndex][0])
andrew@0 525 noteArrayIndex--;
andrew@0 526
andrew@0 527 //need to start where we currently are in file
andrew@0 528 int maxNoteIndexToPrint = noteArrayIndex;
andrew@11 529 int minNoteIndexToPrint = min(size-1,noteArrayIndex);//not needed as changed above
andrew@0 530
andrew@0 531 while (maxNoteIndexToPrint < recordedNoteOnMatrix.size() && recordedNoteOnMatrix[maxNoteIndexToPrint][0] < (numberOfScreensIn+1)*ticksPerScreen )
andrew@0 532 maxNoteIndexToPrint++;
andrew@0 533
andrew@11 534 while (minNoteIndexToPrint > 0 && recordedNoteOnMatrix[minNoteIndexToPrint][0] > numberOfScreensIn*ticksPerScreen)//&& minNoteIndexToPrint < size
andrew@0 535 minNoteIndexToPrint--;
andrew@0 536
andrew@0 537 for (int tmpIndex = max(0,minNoteIndexToPrint);tmpIndex < min(maxNoteIndexToPrint, (int)recordedNoteOnMatrix.size());tmpIndex++){
andrew@0 538
andrew@0 539 if (checkIfMatchedNote(tmpIndex))
andrew@0 540 ofSetColor(0,0,255);
andrew@5 541 else if(noteOnMatches[tmpIndex]){
andrew@9 542 ofSetColor(255,0,255);
andrew@5 543 }else{
andrew@0 544 ofSetColor(255,255,255);
andrew@5 545 }
andrew@5 546
andrew@14 547 if (tmpIndex == bestMatchIndex)
andrew@14 548 ofSetColor(255,0,0);//best recent match is in red
andrew@9 549
andrew@9 550 // XXX replace ofgetwidth below
andrew@0 551 //if (tmpIndex >= 0 && tmpIndex < size)
andrew@0 552 int xLocation = (float)(recordedNoteOnMatrix[tmpIndex][0] - numberOfScreensIn*ticksPerScreen)*(*screenWidth)/(float)ticksPerScreen;
andrew@0 553 int duration = (float)(recordedNoteOnMatrix[tmpIndex][3]*(*screenWidth))/(float)ticksPerScreen;
andrew@0 554
andrew@0 555
andrew@0 556 int yLocation = (*screenHeight) - ((recordedNoteOnMatrix[tmpIndex][1] - noteMinimum )*(*screenHeight)/ (float)(noteMaximum - noteMinimum));
andrew@0 557 ofRect(xLocation,yLocation, duration, noteHeight);
andrew@0 558
andrew@0 559 }
andrew@0 560
andrew@0 561
andrew@0 562 int xLocation;// = getLocationFromTicks(tickLocation);
andrew@9 563 // ofLine(xLocation, 0, xLocation, (*screenHeight));
andrew@0 564
andrew@0 565 //orange line at best estimate
andrew@0 566 xLocation = getLocationFromMillis(bayesStruct.bestEstimate);
andrew@0 567 ofSetColor(250,100,0);
andrew@0 568 ofLine(xLocation, 0, xLocation, (*screenHeight));
andrew@0 569
andrew@2 570 xLocation = getLocationFromMillis(bayesStruct.tmpBestEstimate);
andrew@2 571 ofSetColor(250,100,0);
andrew@2 572 ofLine(xLocation, 0, xLocation, (*screenHeight));
andrew@2 573
andrew@0 574
andrew@0 575 //lines where matching window start and end are
andrew@0 576 ofSetColor(0,100,255);
andrew@0 577 xLocation = getLocationFromMillis(windowStartTime);
andrew@0 578 ofLine(xLocation, 0, xLocation, (*screenHeight));
andrew@0 579 xLocation = getLocationFromMillis(windowStartTime+matchWindowWidth);
andrew@0 580 ofLine(xLocation, 0, xLocation, (*screenHeight));
andrew@9 581
andrew@0 582
andrew@11 583 int maxSize = recordedNoteOnMatrix[size-1][0];
andrew@11 584
andrew@11 585 string indexString = "num screens in "+ofToString(numberOfScreensIn)+"; min index to print "+ofToString(minNoteIndexToPrint)+", max index to print "+ofToString(maxNoteIndexToPrint);
andrew@11 586 indexString += " size "+ofToString(size)+" tick loc "+ofToString(tickLocation)+" max size "+ofToString(maxSize);
andrew@11 587 ofDrawBitmapString(indexString, 20, 40);
andrew@11 588
andrew@0 589 }
andrew@0 590
andrew@0 591 ofDrawBitmapString(ofToString(timeOffsetForScreen, 1), 20,20);
andrew@0 592
andrew@0 593 ofDrawBitmapString(timeString, 20, 60);
andrew@0 594
andrew@11 595
andrew@9 596 }
andrew@9 597
andrew@9 598 void midiEventHolder::drawFile(){
andrew@9 599 drawMidiFile();
andrew@9 600
andrew@9 601
andrew@0 602 // bayesStruct.drawArrays();
andrew@0 603
andrew@0 604 // ofSetColor(200,200,0);
andrew@0 605 // bayesStruct.prior.drawConstrainedVector(0, bayesStruct.prior.arraySize, 400, 800);
andrew@0 606
andrew@0 607 //need to draw arrays within correct timescope
andrew@9 608 if (drawPhaseMode)
andrew@0 609 bayesStruct.drawArraysRelativeToTimeframe(timeOffsetForScreen, timeOffsetForScreen + getEventTimeMillis(ticksPerScreen));
andrew@0 610
andrew@1 611 if (drawTempoMode)
andrew@1 612 bayesStruct.drawTempoArrays();
andrew@0 613
andrew@1 614
andrew@1 615 ofSetColor(0, 0, 0);
andrew@0 616 ofDrawBitmapString(matchString, 20, ofGetHeight() - 20);
andrew@0 617
andrew@1 618 double confidence = bayesStruct.posterior.getValueAtMillis(mouseX);
andrew@2 619 /*
andrew@2 620 string mouseString = "mouseX "+ofToString(confidence, 3)+" .";
andrew@1 621 ofDrawBitmapString(mouseString, 20 , ofGetHeight() - 40);
andrew@2 622 */
andrew@2 623 string mouseString = "updateCounter "+ofToString(bayesStruct.updateCounter);
andrew@2 624 ofDrawBitmapString(mouseString, 20 , ofGetHeight() - 40);
andrew@2 625
andrew@2 626 string infostring = "speed "+ofToString(bayesStruct.relativeSpeedPosterior.getIndexInRealTerms(bayesStruct.relativeSpeedPosterior.MAPestimate), 3);
andrew@2 627 ofDrawBitmapString(infostring, 20 , ofGetHeight() - 60);
andrew@0 628 }
andrew@0 629
andrew@0 630 int midiEventHolder::getLocationFromTicks(double tickPosition){
andrew@0 631 return (int)((float)(tickPosition - numberOfScreensIn*ticksPerScreen)*(*screenWidth)/(float)ticksPerScreen);
andrew@0 632 }
andrew@0 633
andrew@0 634 int midiEventHolder::getLocationFromMillis(double millisPosition){
andrew@0 635 //(getEventTimeTicks(windowStartTime+matchWindowWidth) - numberOfScreensIn*ticksPerScreen)*(*screenWidth) / (double)ticksPerScreen
andrew@0 636 return (millisPosition - timeOffsetForScreen)*(*screenWidth)/getEventTimeMillis(ticksPerScreen);
andrew@0 637 }
andrew@0 638
andrew@0 639
andrew@0 640 void midiEventHolder::exampleCrossUpdate(){
andrew@0 641
andrew@0 642 bayesStruct.crossUpdateArrays(bayesStruct.posterior, bayesStruct.relativeSpeedPosterior, 200);
andrew@0 643
andrew@0 644 }
andrew@0 645
andrew@0 646
andrew@0 647 void midiEventHolder::setStartPlayingTimes(){
andrew@14 648 lastPeriodUpdateTime = getTimeNow(0);//ofGetElapsedTimeMillis();
andrew@0 649 startTime = lastPeriodUpdateTime;
andrew@0 650
andrew@2 651 /*
andrew@2 652 bayesStruct.lastEventTime = 0;//ofGetElapsedTimeMillis();
andrew@2 653 bayesStruct.bestEstimate = 0;
andrew@0 654 bayesStruct.resetArrays();
andrew@2 655 bayesStruct.lastBestEstimateUpdateTime = ofGetElapsedTimeMillis();
andrew@2 656 */
andrew@2 657 bayesStruct.setStartPlaying();
andrew@0 658 matchString = "";
andrew@0 659 }
andrew@0 660
andrew@0 661
andrew@0 662 void midiEventHolder::printMatchMatrix(){
andrew@0 663 printf("match matrix:\n");
andrew@0 664 for (int i = 0;i < matchMatrix.size();i++){
andrew@0 665 for (int k = 0;k < matchMatrix[i].size();k++){
andrew@0 666 printf("%i , ", matchMatrix[i][k]);
andrew@0 667 }
andrew@0 668 printf("\n");
andrew@0 669 }
andrew@0 670
andrew@16 671 }
andrew@16 672
andrew@16 673
andrew@16 674
andrew@16 675 void midiEventHolder::printRecordedEvents(){
andrew@16 676 printf("Recorded Events:\n");
andrew@17 677 for (int i = 0;i < recordedNoteOnMatrix.size();i++){
andrew@16 678 for (int k = 0;k < recordedNoteOnMatrix[i].size();k++){
andrew@16 679 printf("[%i] = %i ,", i, recordedNoteOnMatrix[i][k]);
andrew@16 680 }
andrew@17 681 if (i < recordedEventTimes.size())
andrew@17 682 printf("time %f \n", recordedEventTimes[i]);
andrew@17 683 else
andrew@17 684 printf("\n");
andrew@16 685 }
andrew@0 686
andrew@16 687 }
andrew@16 688
andrew@16 689
andrew@16 690
andrew@16 691 void midiEventHolder::reorderMatrixFromNoteTimes(IntMatrix& noteOnMatrix){
andrew@16 692 double currentTime = -19999.;
andrew@16 693 for (int i = 0;i < noteOnMatrix.size();i++){
andrew@16 694 int nextIndex = getIndexOfMinimumAboveTime(currentTime, noteOnMatrix);
andrew@16 695 cout << "index of min time " << currentTime << " is " << nextIndex << " at time " << noteOnMatrix[nextIndex][0] << endl;
andrew@16 696 // cout << "next index " << nextIndex << " time " << noteOnMatrix[nextIndex][0] << endl;
andrew@16 697 if (nextIndex >= 0 && nextIndex > i && noteOnMatrix[nextIndex][0] < noteOnMatrix[i][0] ){
andrew@16 698 //which it should be
andrew@16 699 cout << " index " << nextIndex << " at time " << noteOnMatrix[nextIndex][0] << " swaps with inex " << i << " at time " << noteOnMatrix[i][0] << endl;
andrew@16 700 noteOnMatrix[i].swap(noteOnMatrix[nextIndex]);
andrew@16 701 currentTime = noteOnMatrix[i][0];
andrew@16 702 }
andrew@16 703
andrew@16 704 }
andrew@17 705
andrew@17 706 printRecordedEvents();
andrew@16 707
andrew@16 708 }
andrew@16 709
andrew@17 710
andrew@17 711
andrew@17 712
andrew@17 713 void midiEventHolder::doublecheckOrder(IntMatrix& noteOnMatrix){
andrew@17 714
andrew@17 715 for (int i = 0;i < noteOnMatrix.size();i++){
andrew@17 716 int nextIndex = getIndexOfMinimumAboveIndex(i, noteOnMatrix);
andrew@17 717 if (nextIndex > i){
andrew@17 718 noteOnMatrix[i].swap(noteOnMatrix[nextIndex]);
andrew@17 719 }
andrew@17 720 }
andrew@17 721 }
andrew@17 722
andrew@17 723 int midiEventHolder::getIndexOfMinimumAboveIndex(const int& index, IntMatrix& noteOnMatrix){
andrew@17 724 int returnIndex = index;
andrew@17 725 int min = noteOnMatrix[index][0];
andrew@17 726 for (int i = index;i < noteOnMatrix.size();i++){
andrew@17 727 if (noteOnMatrix[i][0] < min){
andrew@17 728 returnIndex = i;
andrew@17 729 min = noteOnMatrix[i][0];
andrew@17 730 }
andrew@17 731 }
andrew@17 732 return returnIndex;
andrew@17 733 }
andrew@17 734
andrew@17 735
andrew@16 736 int midiEventHolder::getIndexOfMinimumAboveTime(const double& time, IntMatrix& noteOnMatrix){
andrew@16 737 int index = 0;
andrew@16 738 double minimumTime = 100000000.;
andrew@16 739 int bestIndex = -1;
andrew@16 740 while (index < noteOnMatrix.size()){
andrew@16 741
andrew@16 742 if (noteOnMatrix[index][0] > time && noteOnMatrix[index][0] < minimumTime){
andrew@16 743 bestIndex = index;
andrew@16 744 minimumTime = noteOnMatrix[index][0];
andrew@16 745 }
andrew@16 746 index++;
andrew@16 747 }
andrew@16 748 return bestIndex;
andrew@16 749 }
andrew@16 750
andrew@16 751
andrew@16 752 void midiEventHolder::correctTiming(IntMatrix& noteOnMatrix){
andrew@16 753
andrew@16 754 if (noteOnMatrix.size() > 0 && noteOnMatrix[0][0] < 0) {
andrew@16 755 int offset = noteOnMatrix[0][0];
andrew@16 756 for (int i = 0;i < noteOnMatrix.size();i++){
andrew@16 757 noteOnMatrix[i][0] -= offset;
andrew@16 758 }
andrew@16 759 }
andrew@16 760
andrew@16 761 }