bpm.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /*
  2. LICENSE
  3. -------
  4. Copyright 2005 Nullsoft, Inc.
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without modification,
  7. are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. * Neither the name of Nullsoft nor the names of its contributors may be used to
  14. endorse or promote products derived from this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
  16. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  18. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  21. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  22. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. #include <windows.h>
  25. #include <commctrl.h>
  26. #include <math.h>
  27. #include <stdio.h>
  28. #include "draw.h"
  29. #include "wnd.h"
  30. #include "r_defs.h"
  31. #include "render.h"
  32. #include "vis.h"
  33. #include "cfgwnd.h"
  34. #include "resource.h"
  35. #include "bpm.h"
  36. #include "../Agave/Language/api_language.h"
  37. int refineBeat(int isBeat);
  38. BOOL TCHistStep(BeatType *t, DWORD _Avg, int *_halfDiscriminated, int *_hdPos, DWORD *_lastTC, DWORD TC, int Type);
  39. void InsertHistStep(BeatType *t, DWORD TC, int Type, int i);
  40. void CalcBPM(void);
  41. BOOL ReadyToLearn(void);
  42. BOOL ReadyToGuess(void);
  43. void doubleBeat(void);
  44. void halfBeat(void);
  45. void ResetAdapt(void);
  46. void SliderStep(int Ctl, int *slide);
  47. void initBpm(void);
  48. extern int g_fakeinit;
  49. int cfg_smartbeat=0;
  50. int cfg_smartbeatsticky=1;
  51. int cfg_smartbeatresetnewsong=1;
  52. int cfg_smartbeatonlysticky=0;
  53. int sticked=0;
  54. int arbVal, skipVal; // Values of arbitrary beat and beat skip
  55. int Bpm, Confidence, Confidence1, Confidence2; // Calculated BPM (realtime), Confidence computation
  56. DWORD lastTC; // Last beat Tick count
  57. DWORD lastTC2; // Last beat tick count 2
  58. BeatType TCHist[8]; // History of last 8 beats
  59. BeatType TCHist2[8]; // History of last 8 beats
  60. int Smoother[8]; // History of last 8 Bpm values, used to smooth changes
  61. int halfDiscriminated[8]; // Discriminated beats table
  62. int halfDiscriminated2[8]; // Discriminated beats table
  63. int hdPos; // Position in discrimination table
  64. int hdPos2; // Position in discrimination table
  65. int smPtr, smSize; // Smoother pointer and size
  66. int TCHistPtr; // Tick count history pointer
  67. int TCHistSize; // Tick count history size
  68. int offIMax; // Max divisor/multiplier used to guess/discriminate beats
  69. int lastBPM; // Last calculated BPM, used by the smoother to detect new entry
  70. int insertionCount; // Remembers how many beats were guessed
  71. DWORD predictionLastTC; // Last tick count of guessed/accepted beat
  72. DWORD Avg; // Average tick count interval between beats
  73. DWORD Avg2; // Average tick count interval between beats
  74. int skipCount; // Beat counter used by beat skipper
  75. int inInc, outInc; // +1/-1, Used by the nifty beatsynced sliders
  76. int inSlide, outSlide; // Positions of sliders
  77. int oldInSlide, oldOutSlide; // Used by timer to detect changes in sliders
  78. int oldsticked; // Used by timer to detect changes in sticked state
  79. char txt[256]; // Contains txt about current BPM and confidence
  80. int halfCount, doubleCount; // Counter used to autodetect if double/half beat needed
  81. int TCUsed; // Remembers how many beats in the history were actually used for computation
  82. int predictionBpm; // Contains BPM actually used to prediction (eliminates Bpm driftings)
  83. int oldDisplayBpm, oldDisplayConfidence; // Detects stuff to redraw
  84. int bestConfidence; // Best confidence we had so far
  85. char lastSongName[256]; // Last song name, used to detect song changes in winamp
  86. HWND winampWnd; // Winamp window
  87. int forceNewBeat; // Force new bpm adoption
  88. int betterConfidenceCount; // Used to decide when to adpot new beat
  89. int topConfidenceCount; // Used to decide when to adpot new beat
  90. int stickyConfidenceCount; // Used to decided when to go sticky
  91. BOOL doResyncBpm=FALSE;
  92. // configuration dialog stuff
  93. BOOL CALLBACK DlgProc_Bpm(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam)
  94. {
  95. switch (uMsg)
  96. {
  97. case WM_INITDIALOG:
  98. inInc = 1;
  99. outInc = 1;
  100. inSlide = 0;
  101. outSlide = 0;
  102. oldDisplayBpm=-1;
  103. oldDisplayConfidence=-1;
  104. oldInSlide=-1;
  105. oldOutSlide=-1;
  106. if (cfg_smartbeat) CheckDlgButton(hwndDlg,IDC_BPMADV,BST_CHECKED); else CheckDlgButton(hwndDlg,IDC_BPMSTD,BST_CHECKED);
  107. if (cfg_smartbeatsticky) CheckDlgButton(hwndDlg,IDC_STICKY,BST_CHECKED);
  108. if (cfg_smartbeatresetnewsong) CheckDlgButton(hwndDlg,IDC_NEWRESET,BST_CHECKED); else CheckDlgButton(hwndDlg,IDC_NEWADAPT,BST_CHECKED);
  109. if (cfg_smartbeatonlysticky) CheckDlgButton(hwndDlg,IDC_ONLYSTICKY,BST_CHECKED);
  110. SendDlgItemMessage(hwndDlg, IDC_IN, TBM_SETTICFREQ, 1, 0);
  111. SendDlgItemMessage(hwndDlg, IDC_IN, TBM_SETRANGE, TRUE, MAKELONG(0, 8));
  112. SendDlgItemMessage(hwndDlg, IDC_OUT, TBM_SETTICFREQ, 1, 0);
  113. SendDlgItemMessage(hwndDlg, IDC_OUT, TBM_SETRANGE, TRUE, MAKELONG(0, 8));
  114. if (predictionBpm)
  115. {
  116. ShowWindow(GetDlgItem(hwndDlg, IDC_STICK), sticked ? SW_HIDE : SW_NORMAL);
  117. ShowWindow(GetDlgItem(hwndDlg, IDC_UNSTICK), sticked ? SW_NORMAL : SW_HIDE);
  118. }
  119. else
  120. {
  121. ShowWindow(GetDlgItem(hwndDlg, IDC_STICK), SW_HIDE);
  122. ShowWindow(GetDlgItem(hwndDlg, IDC_UNSTICK), SW_HIDE);
  123. }
  124. /* ShowWindow(GetDlgItem(hwndDlg, IDC_CURBPM), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  125. ShowWindow(GetDlgItem(hwndDlg, IDC_CURCONF), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  126. ShowWindow(GetDlgItem(hwndDlg, IDC_BPM), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  127. ShowWindow(GetDlgItem(hwndDlg, IDC_CONFIDENCE), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  128. ShowWindow(GetDlgItem(hwndDlg, IDC_RESET), cfg_smartbeat ? SW_NORMAL : SW_HIDE);*/
  129. SetTimer(hwndDlg, 0, 50, NULL);
  130. return 1;
  131. case WM_TIMER:
  132. {
  133. if (oldInSlide != inSlide) {
  134. SendDlgItemMessage(hwndDlg, IDC_IN, TBM_SETPOS, TRUE, inSlide); oldInSlide=inSlide; }
  135. if (oldOutSlide != outSlide) {
  136. SendDlgItemMessage(hwndDlg, IDC_OUT, TBM_SETPOS, TRUE, outSlide); oldOutSlide=outSlide; }
  137. if (oldDisplayBpm != predictionBpm || oldsticked != sticked) {
  138. char lBuf[16];
  139. wsprintf(txt, predictionBpm ? "%d%s"/*/%d"*/ : WASABI_API_LNGSTRING_BUF(IDS_LEARNING,lBuf,16), predictionBpm, cfg_smartbeatsticky && sticked ? WASABI_API_LNGSTRING(IDS_GOT_IT) : ""/*, Bpm*/);
  140. SetDlgItemText(hwndDlg, IDC_BPM, txt);
  141. oldDisplayBpm=predictionBpm;
  142. oldsticked=sticked;
  143. if (predictionBpm)
  144. {
  145. ShowWindow(GetDlgItem(hwndDlg, IDC_STICK), sticked ? SW_HIDE : SW_NORMAL);
  146. ShowWindow(GetDlgItem(hwndDlg, IDC_UNSTICK), sticked ? SW_NORMAL : SW_HIDE);
  147. }
  148. else
  149. {
  150. ShowWindow(GetDlgItem(hwndDlg, IDC_STICK), SW_HIDE);
  151. ShowWindow(GetDlgItem(hwndDlg, IDC_UNSTICK), SW_HIDE);
  152. }
  153. }
  154. if (oldDisplayConfidence != Confidence) {
  155. wsprintf(txt, "%d%%"/* (%d%%/%d%% - %d)"*/, Confidence/*, Confidence1, Confidence2, TCUsed*/);
  156. SetDlgItemText(hwndDlg, IDC_CONFIDENCE, txt);
  157. oldDisplayConfidence=Confidence;
  158. }
  159. }
  160. return 0;
  161. case WM_COMMAND:
  162. if ((LOWORD(wParam) == IDC_BPMSTD) ||
  163. (LOWORD(wParam) == IDC_BPMADV) ||
  164. (LOWORD(wParam) == IDC_NEWRESET) ||
  165. (LOWORD(wParam) == IDC_NEWADAPT) ||
  166. (LOWORD(wParam) == IDC_ONLYSTICKY) ||
  167. (LOWORD(wParam) == IDC_STICKY))
  168. {
  169. cfg_smartbeat=IsDlgButtonChecked(hwndDlg,IDC_BPMADV)?1:0;
  170. cfg_smartbeatsticky=IsDlgButtonChecked(hwndDlg,IDC_STICKY)?1:0;
  171. cfg_smartbeatresetnewsong=IsDlgButtonChecked(hwndDlg,IDC_NEWRESET)?1:0;
  172. cfg_smartbeatonlysticky=IsDlgButtonChecked(hwndDlg,IDC_ONLYSTICKY)?1:0;
  173. oldsticked=-1;
  174. /* ShowWindow(GetDlgItem(hwndDlg, IDC_CURBPM), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  175. ShowWindow(GetDlgItem(hwndDlg, IDC_CURCONF), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  176. ShowWindow(GetDlgItem(hwndDlg, IDC_BPM), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  177. ShowWindow(GetDlgItem(hwndDlg, IDC_CONFIDENCE), cfg_smartbeat ? SW_NORMAL : SW_HIDE);
  178. ShowWindow(GetDlgItem(hwndDlg, IDC_RESET), cfg_smartbeat ? SW_NORMAL : SW_HIDE);*/
  179. }
  180. if (LOWORD(wParam) == IDC_2X)
  181. doubleBeat();
  182. if (LOWORD(wParam) == IDC_DIV2)
  183. halfBeat();
  184. if (LOWORD(wParam) == IDC_RESET)
  185. ResetAdapt();
  186. if (LOWORD(wParam) == IDC_STICK)
  187. {
  188. sticked=1;
  189. stickyConfidenceCount=0;
  190. }
  191. if (LOWORD(wParam) == IDC_UNSTICK)
  192. {
  193. sticked=0;
  194. stickyConfidenceCount=0;
  195. }
  196. return 0;
  197. case WM_DESTROY:
  198. KillTimer(hwndDlg, 0);
  199. return 0;
  200. }
  201. return 0;
  202. }
  203. void initBpm(void)
  204. {
  205. if (g_fakeinit) return;
  206. TCUsed=0;
  207. *txt=0;
  208. betterConfidenceCount=0;
  209. topConfidenceCount=0;
  210. forceNewBeat=0;
  211. hdPos=0;
  212. hdPos2=0;
  213. inSlide=0;
  214. outSlide=0;
  215. oldDisplayBpm=-1;
  216. oldDisplayConfidence=-1;
  217. oldInSlide=0;
  218. oldOutSlide=0;
  219. Bpm = 0;
  220. Avg = 0;
  221. Avg2 = 0;
  222. smPtr = 0;
  223. smSize = 8;
  224. offIMax = 8;
  225. insertionCount = 0;
  226. predictionLastTC = 0;
  227. Confidence = 0;
  228. Confidence1 = 0;
  229. Confidence2 = 0;
  230. halfCount=0;
  231. doubleCount=0;
  232. TCHistSize = 8;
  233. predictionBpm=0;
  234. lastTC=GetTickCount();
  235. stickyConfidenceCount=0;
  236. memset(TCHist, 0, TCHistSize*sizeof(BeatType));
  237. memset(Smoother, 0, smSize*sizeof(int));
  238. memset(halfDiscriminated, 0, TCHistSize*sizeof(int));
  239. memset(halfDiscriminated2, 0, TCHistSize*sizeof(int));
  240. winampWnd = FindWindow("Winamp v1.x", NULL);
  241. *lastSongName=0;
  242. sticked=0;
  243. oldsticked=-1;
  244. }
  245. BOOL songChanged(DWORD TCNow)
  246. {
  247. static DWORD lastCheck=0;
  248. if (TCNow > lastCheck+1000)
  249. {
  250. char songName[256];
  251. lastCheck=TCNow;
  252. GetWindowText(winampWnd, songName, 255);
  253. if (strcmp(songName, lastSongName))
  254. {
  255. strcpy(lastSongName, songName);
  256. return TRUE;
  257. }
  258. }
  259. return FALSE;
  260. }
  261. void ResetAdapt(void)
  262. {
  263. // Reset adaptive learning
  264. *txt=0;
  265. TCUsed=0;
  266. hdPos=0;
  267. Avg = 0;
  268. Confidence=0;
  269. Confidence1=0;
  270. Confidence2=0;
  271. betterConfidenceCount=0;
  272. topConfidenceCount=0;
  273. Bpm = 0;
  274. smPtr = 0;
  275. smSize = 8;
  276. offIMax = 8;
  277. insertionCount = 0;
  278. predictionLastTC = 0;
  279. halfCount=0;
  280. doubleCount=0;
  281. TCHistSize = 8;
  282. predictionBpm=0;
  283. bestConfidence=0;
  284. lastTC=GetTickCount();
  285. sticked=0;
  286. oldsticked=-1;
  287. stickyConfidenceCount=0;
  288. memset(TCHist, 0, TCHistSize*sizeof(BeatType));
  289. memset(TCHist2, 0, TCHistSize*sizeof(BeatType));
  290. memset(Smoother, 0, smSize*sizeof(int));
  291. memset(halfDiscriminated, 0, TCHistSize*sizeof(int));
  292. }
  293. // Insert a beat in history table. May be either real beat or guessed
  294. void InsertHistStep(BeatType *t, DWORD TC, int Type, int i)
  295. {
  296. if (i >= TCHistSize) return;
  297. if (t == TCHist && insertionCount < TCHistSize*2) insertionCount++;
  298. memmove(t+i+1, t+i, sizeof(BeatType)*(TCHistSize-(i+1)));
  299. t[0].TC = TC;
  300. t[0].Type = Type;
  301. }
  302. // Doubles current beat
  303. void doubleBeat(void)
  304. {
  305. int i;
  306. int iv[8];
  307. if (sticked && Bpm > MIN_BPM) return;
  308. for (i=0;i<TCHistSize-1;i++)
  309. iv[i] = TCHist[i].TC - TCHist[i+1].TC;
  310. for (i=1;i<TCHistSize;i++)
  311. TCHist[i].TC = TCHist[i-1].TC-iv[i-1]/2;
  312. Avg /= 2;
  313. Bpm *= 2;
  314. doubleCount=0;
  315. memset(Smoother, 0, smSize*sizeof(int));
  316. memset(halfDiscriminated, 0, TCHistSize*sizeof(int));
  317. //forceNewBeat=1;
  318. }
  319. // Halfs current beat
  320. void halfBeat(void)
  321. {
  322. int i;
  323. int iv[8];
  324. if (sticked && Bpm < MIN_BPM) return;
  325. for (i=0;i<TCHistSize-1;i++)
  326. iv[i] = TCHist[i].TC - TCHist[i+1].TC;
  327. for (i=1;i<TCHistSize;i++)
  328. TCHist[i].TC = TCHist[i-1].TC-iv[i-1]*2;
  329. Avg *= 2;
  330. Bpm /= 2;
  331. halfCount=0;
  332. memset(Smoother, 0, smSize*sizeof(int));
  333. memset(halfDiscriminated, 0, TCHistSize*sizeof(int));
  334. }
  335. // Called whenever isBeat was true in render
  336. BOOL TCHistStep(BeatType *t, DWORD _Avg, int *_halfDiscriminated, int *_hdPos, DWORD *_lastTC, DWORD TC, int Type)
  337. {
  338. int i=0;
  339. int offI;
  340. DWORD thisLen;
  341. BOOL learning = ReadyToLearn();
  342. thisLen = TC-lastTC;
  343. // If this beat is sooner than half the average - 20%, throw it away
  344. if (thisLen < Avg/2 - Avg*0.2)
  345. {
  346. if (learning)
  347. {
  348. if (labs(Avg - (TC - t[1].TC)) < labs(Avg - (t[0].TC - t[1].TC)))
  349. {
  350. /* if (predictionLastTC && t[0].Type == BEAT_GUESSED && Type == BEAT_REAL)
  351. predictionLastTC += (TC - t[0].TC)/2;*/
  352. t[0].TC = TC;
  353. t[0].Type = Type;
  354. return TRUE;
  355. }
  356. }
  357. return FALSE;
  358. }
  359. if (learning)
  360. for (offI=2;offI<offIMax;offI++) // Try to see if this beat is in the middle of our current Bpm, or maybe 1/3, 1/4 etc... to offIMax
  361. if ((float)labs((Avg/offI)-thisLen) < (float)(Avg/offI)*0.2)
  362. {
  363. _halfDiscriminated[(*_hdPos)++]=1; // Should test if offI==2 before doing that, but seems to have better results ? I'll have to investigate this
  364. (*_hdPos)%=8;
  365. return FALSE;
  366. }
  367. // This beat is accepted, so set this discrimination entry to false
  368. _halfDiscriminated[hdPos++]=0;
  369. (*_hdPos)%=8;
  370. // Check if we missed some beats
  371. /*if (learning && thisLen > 1000 || (float)abs(Avg-thisLen) > (float)Avg*0.3)
  372. for (offI=2;offI<offIMax;offI++)
  373. {
  374. if ((float)abs((Avg*offI)-thisLen) < (float)Avg*0.2)
  375. {
  376. for (j=1;j<offI;j++) // Oh yeah we definitly did, add one!
  377. InsertHistStep(TC - (Avg*j), BEAT_GUESSED, offI-1); // beat has been guessed so report it so confidence can be calculated
  378. break;
  379. }
  380. }*/
  381. // Remember this tick count
  382. *_lastTC = TC;
  383. // Insert this beat.
  384. InsertHistStep(t, TC, Type, 0);
  385. return TRUE;
  386. }
  387. // Am i ready to learn ?
  388. BOOL ReadyToLearn(void)
  389. {
  390. int i;
  391. for (i=0;i<TCHistSize;i++)
  392. if (TCHist[i].TC==0) return FALSE;
  393. return TRUE;
  394. }
  395. // Am i ready to guess ?
  396. BOOL ReadyToGuess(void)
  397. {
  398. return insertionCount == TCHistSize*2;
  399. }
  400. void newBpm(int thisBpm)
  401. {
  402. Smoother[smPtr++] = thisBpm;
  403. smPtr %= smSize;
  404. }
  405. int GetBpm(void)
  406. {
  407. int i;
  408. int smN=0;
  409. int smSum=0;
  410. // Calculate smoothed Bpm
  411. for (i=0;i<smSize;i++)
  412. if (Smoother[i] > 0) {
  413. smSum += Smoother[i];
  414. smN++;
  415. }
  416. if (smN) return smSum / smN;
  417. return 0;
  418. }
  419. // Calculate BPM according to beat history
  420. void CalcBPM(void)
  421. {
  422. int i;
  423. int hdCount=0;
  424. int r=0;
  425. int totalTC=0, totalN=0;
  426. float rC, etC;
  427. int v;
  428. double sc=0;
  429. int mx=0;
  430. float et;
  431. int smSum=0, smN=0;
  432. if (!ReadyToLearn())
  433. return;
  434. // First calculate average beat
  435. for (i=0;i<TCHistSize-1;i++)
  436. totalTC += TCHist[i].TC - TCHist[i+1].TC;
  437. Avg = totalTC/(TCHistSize-1);
  438. // Count how many of then are real as opposed to guessed
  439. for (i=0;i<TCHistSize;i++)
  440. if (TCHist[i].Type == BEAT_REAL)
  441. r++;
  442. // Calculate part 1 of confidence
  443. rC = (float)min((float)((float)r / (float)TCHistSize) * 2, 1);
  444. // Calculate typical drift
  445. for (i=0;i<TCHistSize-1;i++)
  446. {
  447. v = TCHist[i].TC - TCHist[i+1].TC;
  448. mx = max(mx, v);
  449. sc += v*v;
  450. }
  451. et = (float)sqrt(sc / (TCHistSize-1) - Avg*Avg);
  452. // Calculate confidence based on typical drift and max derivation
  453. etC = 1 - ((float)et / (float)mx);
  454. // Calculate confidence
  455. Confidence = max(0, (int)(((rC * etC) * 100.0) - 50) * 2);
  456. Confidence1 = (int)(rC * 100);
  457. Confidence2 = (int)(etC * 100);
  458. // Now apply second layer, recalculate average using only beats within range of typical drift
  459. // Also, count how many of them we are keeping
  460. totalTC=0;
  461. for (i=0;i<TCHistSize-1;i++)
  462. {
  463. v += TCHist[i].TC - TCHist[i+1].TC;
  464. if (labs(Avg-v) < et)
  465. {
  466. totalTC += v;
  467. totalN++;
  468. v = 0;
  469. }
  470. else
  471. if ((float)v > Avg)
  472. v = 0;
  473. }
  474. TCUsed = totalN;
  475. // If no beat was within typical drift (how would it be possible? well lets cover our ass) then keep the simple
  476. // average calculated earlier, else recalculate average of beats within range
  477. if (totalN)
  478. Avg = totalTC/totalN;
  479. if (ReadyToGuess())
  480. {
  481. if (Avg) // Avg = 0 ? Ahem..
  482. Bpm = 60000 / Avg;
  483. if (Bpm != lastBPM)
  484. {
  485. newBpm(Bpm); // If realtime Bpm has changed since last time, then insert it in the smoothing tab;e
  486. lastBPM = Bpm;
  487. if (cfg_smartbeatsticky && predictionBpm && Confidence >= ((predictionBpm < 90) ? STICKY_THRESHOLD_LOW : STICKY_THRESHOLD))
  488. {
  489. stickyConfidenceCount++;
  490. if (stickyConfidenceCount >= MIN_STICKY)
  491. sticked=1;
  492. }
  493. else
  494. stickyConfidenceCount=0;
  495. }
  496. Bpm = GetBpm();
  497. // Count how many beats we discriminated
  498. for (i=0;i<TCHistSize;i++)
  499. if (halfDiscriminated[i]) hdCount++;
  500. if (hdCount >= TCHistSize/2) // If we removed at least half of our beats, then we are off course. We should double our bpm
  501. {
  502. if (Bpm * 2 < MAX_BPM) // Lets do so only if the doubled bpm is < MAX_BPM
  503. {
  504. doubleBeat();
  505. memset(halfDiscriminated, 0, TCHistSize*sizeof(int)); // Reset discrimination table
  506. }
  507. }
  508. if (Bpm > 500 || Bpm < 0)
  509. {
  510. ResetAdapt();
  511. }
  512. if (Bpm < MIN_BPM)
  513. {
  514. if (++doubleCount > 4) // We're going too slow, lets double our bpm
  515. doubleBeat();
  516. }
  517. else
  518. doubleCount=0;
  519. if (Bpm > MAX_BPM) // We're going too fast, lets slow our bpm by a factor of 2
  520. {
  521. if (++halfCount > 4)
  522. halfBeat();
  523. }
  524. else
  525. halfCount=0;
  526. }
  527. }
  528. void SliderStep(int Ctl, int *slide)
  529. {
  530. *slide += Ctl == IDC_IN ? inInc : outInc;
  531. if (!*slide || *slide == 8) (Ctl == IDC_IN ? inInc : outInc) *= -1;
  532. }
  533. // render function
  534. // render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout. this is
  535. // used when you want to do something that you'd otherwise need to make a copy of the framebuffer.
  536. // w and h are the width and height of the screen, in pixels.
  537. // isBeat is 1 if a beat has been detected.
  538. // visdata is in the format of [spectrum:0,wave:1][channel][band].
  539. int refineBeat(int isBeat)
  540. {
  541. BOOL accepted=FALSE;
  542. BOOL predicted=FALSE;
  543. BOOL resyncin=FALSE;
  544. BOOL resyncout=FALSE;
  545. if (isBeat) // Show the beat received from AVS
  546. SliderStep(IDC_IN, &inSlide);
  547. DWORD TCNow = GetTickCount();
  548. if (songChanged(TCNow))
  549. {
  550. bestConfidence=(int)((float)bestConfidence*0.5);
  551. sticked=0;
  552. stickyConfidenceCount=0;
  553. if (cfg_smartbeatresetnewsong)
  554. ResetAdapt();
  555. }
  556. // Try to predict if this frame should be a beat
  557. if (Bpm && TCNow > predictionLastTC + (60000 / Bpm))
  558. predicted = TRUE;
  559. if (isBeat) // If it is a real beat, do discrimination/guessing and computations, then see if it is accepted
  560. accepted = TCHistStep(TCHist, Avg, halfDiscriminated, &hdPos, &lastTC, TCNow, BEAT_REAL);
  561. // Calculate current Bpm
  562. CalcBPM();
  563. // If prediction Bpm has not yet been set
  564. // or if prediction bpm is too high or too low
  565. // or if 3/4 of our history buffer contains beats within the range of typical drift
  566. // the accept the calculated Bpm as the new prediction Bpm
  567. // This allows keeping the beat going on when the music fades out, and readapt to the new beat as soon as
  568. // the music fades in again
  569. if ((accepted || predicted) && !sticked && (!predictionBpm || predictionBpm > MAX_BPM || predictionBpm < MIN_BPM))
  570. {
  571. if (Confidence >= bestConfidence)
  572. {
  573. /* betterConfidenceCount++;
  574. if (!predictionBpm || betterConfidenceCount == BETTER_CONF_ADOPT)
  575. {*/
  576. forceNewBeat=1;
  577. /* betterConfidenceCount=0;
  578. }*/
  579. }
  580. if (Confidence >= 50)
  581. {
  582. topConfidenceCount++;
  583. if (topConfidenceCount == TOP_CONF_ADOPT)
  584. {
  585. forceNewBeat=1;
  586. topConfidenceCount=0;
  587. }
  588. }
  589. if (forceNewBeat)
  590. {
  591. forceNewBeat=0;
  592. bestConfidence = Confidence;
  593. predictionBpm=Bpm;
  594. }
  595. }
  596. if (!sticked) predictionBpm = Bpm;
  597. Bpm=predictionBpm;
  598. /* resync = (predictionBpm &&
  599. (predictionLastTC < TCNow - (30000/predictionBpm) - (60000/predictionBpm)*0.2) ||
  600. (predictionLastTC < TCNow - (30000/predictionBpm) - (60000/predictionBpm)*0.2));*/
  601. if (predictionBpm && accepted && !predicted)
  602. {
  603. int b=0;
  604. if (TCNow > predictionLastTC + (60000 / predictionBpm)*0.7)
  605. {
  606. resyncin = TRUE;
  607. b = (int)((float)predictionBpm * 1.01);
  608. }
  609. if (TCNow < predictionLastTC + (60000 / predictionBpm)*0.3)
  610. {
  611. resyncout = TRUE;
  612. b = (int)((float)predictionBpm * 0.98);
  613. }
  614. if (!sticked && doResyncBpm && (resyncin || resyncout))
  615. {
  616. newBpm(b);
  617. predictionBpm = GetBpm();
  618. }
  619. }
  620. if (resyncin)
  621. {
  622. predictionLastTC = TCNow;
  623. SliderStep(IDC_OUT, &outSlide);
  624. doResyncBpm=TRUE;
  625. return ((cfg_smartbeat && !cfg_smartbeatonlysticky) || (cfg_smartbeat && cfg_smartbeatonlysticky && sticked)) ? 1 : isBeat;
  626. }
  627. if (predicted)
  628. {
  629. predictionLastTC = TCNow;
  630. if (Confidence > 25) TCHistStep(TCHist, Avg, halfDiscriminated, &hdPos, &lastTC, TCNow, BEAT_GUESSED);
  631. SliderStep(IDC_OUT, &outSlide);
  632. doResyncBpm=FALSE;
  633. return ((cfg_smartbeat && !cfg_smartbeatonlysticky) || (cfg_smartbeat && cfg_smartbeatonlysticky && sticked)) ? 1 : isBeat;
  634. }
  635. if (resyncout)
  636. {
  637. predictionLastTC = TCNow;
  638. doResyncBpm=TRUE;
  639. return ((cfg_smartbeat && !cfg_smartbeatonlysticky) || (cfg_smartbeat && cfg_smartbeatonlysticky && sticked)) ? 0 : isBeat;
  640. }
  641. return ((cfg_smartbeat && !cfg_smartbeatonlysticky) || (cfg_smartbeat && cfg_smartbeatonlysticky && sticked)) ? (predictionBpm ? 0 : isBeat) : isBeat;
  642. }