Merge pull request #122 from cnlohr/code-cleanup

Merge code cleanup branch
This commit is contained in:
Sam Ellicott 2021-05-22 15:50:20 -04:00 committed by GitHub
commit 27ed88b5de
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 395 additions and 441 deletions

View file

@ -1,3 +1,4 @@
# Basic style rules by Charles Lohr
BasedOnStyle: Microsoft BasedOnStyle: Microsoft
AccessModifierOffset: -4 AccessModifierOffset: -4
AlwaysBreakTemplateDeclarations: 'Yes' AlwaysBreakTemplateDeclarations: 'Yes'
@ -14,11 +15,30 @@ MaxEmptyLinesToKeep: 2
PointerAlignment: Right PointerAlignment: Right
SpaceInEmptyParentheses: 'false' SpaceInEmptyParentheses: 'false'
SpacesInAngles: 'true' SpacesInAngles: 'true'
SpacesInCStyleCastParentheses: 'true' # this is just atrocious
#SpacesInCStyleCastParentheses: 'true'
SpacesInContainerLiterals: 'true' SpacesInContainerLiterals: 'true'
SpacesInParentheses: 'true' SpacesInParentheses: 'true'
SpacesInSquareBrackets: 'true' SpacesInSquareBrackets: 'true'
TabWidth: '4' TabWidth: '4'
UseTab: Always UseTab: AlignWithSpaces
FixNamespaceComments: 'true' FixNamespaceComments: 'true'
IndentCaseLabels: 'true' IndentCaseLabels: 'true'
# Additions by Sam Ellicott
ColumnLimit: 100
# From general dislike from Charles and Cai, I am turning these off
#AlignConsecutiveAssignments: true
#AlignConsecutiveMacros: true
#AlignTrailingComments: true
#AlignOperands: AlignAfterOperator
# Turn off alignment
AlignConsecutiveAssignments: false
AlignConsecutiveMacros: false
AlignTrailingComments: false
AlignEscapedNewlines: Left
AlignOperands: AlignAfterOperator
AllowShortBlocksOnASingleLine: Always
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortCaseLabelsOnASingleLine: true
AllowShortLoopsOnASingleLine: true

View file

@ -8,7 +8,7 @@ WINGCCFLAGS:= -g -DICACHE_FLASH_ATTR= -I../embeddedcommon -Icnfa -Irawdraw -I. -
WINLDFLAGS:=-lwinmm -lgdi32 -lws2_32 -lsetupapi WINLDFLAGS:=-lwinmm -lgdi32 -lws2_32 -lsetupapi
#CFLAGS:=-g -O1 -flto -Wall -ffast-math -I../embeddedcommon -I. -Icnfa -Irawdraw -DICACHE_FLASH_ATTR= #CFLAGS:=-g -O1 -flto -Wall -ffast-math -I../embeddedcommon -I. -Icnfa -Irawdraw -DICACHE_FLASH_ATTR=
CFLAGS:=-g -O1 -Wall -ffast-math -I../embeddedcommon -I. -Icnfa -Irawdraw -DICACHE_FLASH_ATTR= CFLAGS:=-g -O2 -Wall -ffast-math -I../embeddedcommon -I. -Icnfa -Irawdraw -DICACHE_FLASH_ATTR=
ifneq ($(OS),Windows_NT) ifneq ($(OS),Windows_NT)
ifneq ($(shell uname),Darwin) ifneq ($(shell uname),Darwin)
@ -23,6 +23,7 @@ EXTRALIBS+=-ludev
EXTRALIBS+=$(shell pkg-config --libs alsa) EXTRALIBS+=$(shell pkg-config --libs alsa)
EXTRALIBS+=$(shell pkg-config --libs libpulse) EXTRALIBS+=$(shell pkg-config --libs libpulse)
EXTRALIBS+=$(shell pkg-config --libs libpulse-simple) EXTRALIBS+=$(shell pkg-config --libs libpulse-simple)
OPENGLLIBS=$(shell pkg-config --cflags --libs glut)
endif endif
OBJS:=main.o dft.o decompose.o filter.o color.o notefinder.o util.o outdrivers.o $(OUTS) parameters.o chash.o hook.o ../embeddedcommon/DFT32.o configs.o OBJS:=main.o dft.o decompose.o filter.o color.o notefinder.o util.o outdrivers.o $(OUTS) parameters.o chash.o hook.o ../embeddedcommon/DFT32.o configs.o
@ -30,6 +31,9 @@ OBJS:=main.o dft.o decompose.o filter.o color.o notefinder.o util.o outdrivers.
colorchord : $(OBJS) colorchord : $(OBJS)
$(CC) -o $@ $^ $(EXTRALIBS) $(RAWDRAWLIBS) $(CC) -o $@ $^ $(EXTRALIBS) $(RAWDRAWLIBS)
colorchord-opengl : $(OBJS)
$(CC) -o $@ $^ -DCNFGOGL $(EXTRALIBS) $(OPENGLLIBS) $(RAWDRAWLIBS)
colorchord.exe : main.c dft.c decompose.c filter.c color.c notefinder.c util.c outdrivers.c parameters.c chash.c OutputVoronoi.c OutputProminent.c DisplayArray.c OutputLinear.c DisplayPie.c DisplayNetwork.c hook.c RecorderPlugin.c ../embeddedcommon/DFT32.c OutputCells.c configs.c hidapi.c DisplayHIDAPI.c colorchord.exe : main.c dft.c decompose.c filter.c color.c notefinder.c util.c outdrivers.c parameters.c chash.c OutputVoronoi.c OutputProminent.c DisplayArray.c OutputLinear.c DisplayPie.c DisplayNetwork.c hook.c RecorderPlugin.c ../embeddedcommon/DFT32.c OutputCells.c configs.c hidapi.c DisplayHIDAPI.c
$(WINGCC) $(WINGCCFLAGS) -o $@ $^ $(WINLDFLAGS) $(WINGCC) $(WINGCCFLAGS) -o $@ $^ $(WINLDFLAGS)

View file

@ -10,24 +10,25 @@
#ifndef CCEMBEDDED #ifndef CCEMBEDDED
void DoDFT( float * outbins, float * frequencies, int bins, float * databuffer, int place_in_data_buffer, int size_of_data_buffer, float q ) void DoDFT( float *outbins, float *frequencies, int bins, float *databuffer,
int place_in_data_buffer, int size_of_data_buffer, float q )
{ {
int i, j; int i, j;
for( i = 0; i < bins; i++ ) for ( i = 0; i < bins; i++ )
{ {
float freq = frequencies[i]; float freq = frequencies[ i ];
float phi = 0; float phi = 0;
int sampleplace = place_in_data_buffer; int sampleplace = place_in_data_buffer;
float advance = 3.14159*2.0/freq; float advance = 3.14159 * 2.0 / freq;
float binqtys = 0; float binqtys = 0;
float binqtyc = 0; float binqtyc = 0;
for( j = 0; j <= freq * q; j++ ) for ( j = 0; j <= freq * q; j++ )
{ {
float sample = databuffer[sampleplace]; float sample = databuffer[ sampleplace ];
sampleplace = (sampleplace-1+size_of_data_buffer)%size_of_data_buffer; sampleplace = ( sampleplace - 1 + size_of_data_buffer ) % size_of_data_buffer;
//printf( "%d\n", sampleplace ); // printf( "%d\n", sampleplace );
float sv = sin( phi ) * sample; float sv = sin( phi ) * sample;
float cv = cos( phi ) * sample; float cv = cos( phi ) * sample;
@ -38,36 +39,37 @@ void DoDFT( float * outbins, float * frequencies, int bins, float * databuffer,
} }
float amp = sqrtf( binqtys * binqtys + binqtyc * binqtyc ); float amp = sqrtf( binqtys * binqtys + binqtyc * binqtyc );
outbins[i] = amp / freq / q; outbins[ i ] = amp / freq / q;
} }
} }
void DoDFTQuick( float * outbins, float * frequencies, int bins, const float * databuffer, int place_in_data_buffer, int size_of_data_buffer, float q, float speedup ) void DoDFTQuick( float *outbins, float *frequencies, int bins, const float *databuffer,
int place_in_data_buffer, int size_of_data_buffer, float q, float speedup )
{ {
int i, j; int i, j;
for( i = 0; i < bins; i++ ) for ( i = 0; i < bins; i++ )
{ {
int flirts = 0; int flirts = 0;
float freq = frequencies[i]; float freq = frequencies[ i ];
float phi = 0; float phi = 0;
int ftq = freq * q; int ftq = freq * q;
int sampleplace = place_in_data_buffer; int sampleplace = place_in_data_buffer;
float advance = 3.14159*2.0/freq; float advance = 3.14159 * 2.0 / freq;
float binqtys = 0; float binqtys = 0;
float binqtyc = 0; float binqtyc = 0;
int skip = floor( ftq / speedup ); int skip = floor( ftq / speedup );
if( skip == 0 ) skip = 1; if ( skip == 0 ) skip = 1;
advance *= skip; advance *= skip;
for( j = 0; j <= ftq; j += skip ) for ( j = 0; j <= ftq; j += skip )
{ {
float sample = databuffer[sampleplace]; float sample = databuffer[ sampleplace ];
sampleplace = (sampleplace-skip+size_of_data_buffer)%size_of_data_buffer; sampleplace = ( sampleplace - skip + size_of_data_buffer ) % size_of_data_buffer;
//printf( "%d\n", sampleplace ); // printf( "%d\n", sampleplace );
float sv = sinf( phi ) * sample; float sv = sinf( phi ) * sample;
float cv = cosf( phi ) * sample; float cv = cosf( phi ) * sample;
@ -79,25 +81,24 @@ void DoDFTQuick( float * outbins, float * frequencies, int bins, const float * d
} }
float amp = sqrtf( binqtys * binqtys + binqtyc * binqtyc ); float amp = sqrtf( binqtys * binqtys + binqtyc * binqtyc );
outbins[i] = amp / freq / q * skip; outbins[ i ] = amp / freq / q * skip;
} }
} }
////////////////////////////DFT Progressive is for embedded systems, primarily. ////////////////////////////DFT Progressive is for embedded systems, primarily.
static float * gbinqtys; static float *gbinqtys;
static float * gbinqtyc; static float *gbinqtyc;
static float * phis; static float *phis;
static float * gfrequencies; static float *gfrequencies;
static float * lastbins; static float *lastbins;
static float * advances; static float *advances;
static float * goutbins; static float *goutbins;
static int gbins; static int gbins;
static float gq; static float gq;
static float gspeedup; static float gspeedup;
#define PROGIIR .005 #define PROGIIR .005
@ -105,53 +106,53 @@ void HandleProgressive( float sample )
{ {
int i; int i;
for( i = 0; i < gbins; i++ ) for ( i = 0; i < gbins; i++ )
{ {
float thiss = sinf( phis[i] ) * sample; float thiss = sinf( phis[ i ] ) * sample;
float thisc = cosf( phis[i] ) * sample; float thisc = cosf( phis[ i ] ) * sample;
float s = gbinqtys[i] = gbinqtys[i] * (1.-PROGIIR) + thiss * PROGIIR; float s = gbinqtys[ i ] = gbinqtys[ i ] * ( 1. - PROGIIR ) + thiss * PROGIIR;
float c = gbinqtyc[i] = gbinqtyc[i] * (1.-PROGIIR) + thisc * PROGIIR; float c = gbinqtyc[ i ] = gbinqtyc[ i ] * ( 1. - PROGIIR ) + thisc * PROGIIR;
phis[i] += advances[i]; phis[ i ] += advances[ i ];
if( phis[i] > 6.283 ) phis[i]-=6.283; if ( phis[ i ] > 6.283 ) phis[ i ] -= 6.283;
goutbins[i] = sqrtf( s * s + c * c ); goutbins[ i ] = sqrtf( s * s + c * c );
} }
} }
void DoDFTProgressive( float * outbins, float * frequencies, int bins, const float * databuffer, int place_in_data_buffer, int size_of_data_buffer, float q, float speedup ) void DoDFTProgressive( float *outbins, float *frequencies, int bins, const float *databuffer,
int place_in_data_buffer, int size_of_data_buffer, float q, float speedup )
{ {
int i; int i;
static int last_place; static int last_place;
if( gbins != bins ) if ( gbins != bins )
{ {
if( gbinqtys ) free( gbinqtys ); if ( gbinqtys ) free( gbinqtys );
if( gbinqtyc ) free( gbinqtyc ); if ( gbinqtyc ) free( gbinqtyc );
if( phis ) free( phis ); if ( phis ) free( phis );
if( lastbins ) free( lastbins ); if ( lastbins ) free( lastbins );
if( advances ) free( advances ); if ( advances ) free( advances );
gbinqtys = malloc( sizeof(float)*bins ); gbinqtys = malloc( sizeof( float ) * bins );
gbinqtyc = malloc( sizeof(float)*bins ); gbinqtyc = malloc( sizeof( float ) * bins );
phis = malloc( sizeof(float)*bins ); phis = malloc( sizeof( float ) * bins );
lastbins = malloc( sizeof(float)*bins ); lastbins = malloc( sizeof( float ) * bins );
advances = malloc( sizeof(float)*bins ); advances = malloc( sizeof( float ) * bins );
memset( gbinqtys, 0, sizeof(float)*bins );
memset( gbinqtyc, 0, sizeof(float)*bins );
memset( phis, 0, sizeof(float)*bins );
memset( lastbins, 0, sizeof(float)*bins );
memset( gbinqtys, 0, sizeof( float ) * bins );
memset( gbinqtyc, 0, sizeof( float ) * bins );
memset( phis, 0, sizeof( float ) * bins );
memset( lastbins, 0, sizeof( float ) * bins );
} }
memcpy( outbins, lastbins, sizeof(float)*bins ); memcpy( outbins, lastbins, sizeof( float ) * bins );
for( i = 0; i < bins; i++ ) for ( i = 0; i < bins; i++ )
{ {
float freq = frequencies[i]; float freq = frequencies[ i ];
advances[i] = 3.14159*2.0/freq; advances[ i ] = 3.14159 * 2.0 / freq;
} }
gbins = bins; gbins = bins;
@ -160,36 +161,28 @@ void DoDFTProgressive( float * outbins, float * frequencies, int bins, const flo
gspeedup = speedup; gspeedup = speedup;
gq = q; gq = q;
place_in_data_buffer = (place_in_data_buffer+1)%size_of_data_buffer; place_in_data_buffer = ( place_in_data_buffer + 1 ) % size_of_data_buffer;
int didrun = 0; int didrun = 0;
for( i = last_place; i != place_in_data_buffer; i = (i+1)%size_of_data_buffer ) for ( i = last_place; i != place_in_data_buffer; i = ( i + 1 ) % size_of_data_buffer )
{ {
float fin = ((float)((int)(databuffer[i] * 127))) / 127.0; //simulate 8-bit input (it looks FINE!) float fin = ( (float)( (int)( databuffer[ i ] * 127 ) ) ) /
127.0; // simulate 8-bit input (it looks FINE!)
HandleProgressive( fin ); HandleProgressive( fin );
didrun = 1; didrun = 1;
} }
last_place = place_in_data_buffer; last_place = place_in_data_buffer;
if( didrun ) if ( didrun ) { memcpy( lastbins, outbins, sizeof( float ) * bins ); }
{
memcpy( lastbins, outbins, sizeof(float)*bins );
}
/* for( i = 0; i < bins; i++ )
{
printf( "%0.2f ", outbins[i]*100 );
}
printf( "\n" );*/
/* for( i = 0; i < bins; i++ )
{
printf( "%0.2f ", outbins[i]*100 );
}
printf( "\n" );*/
} }
/////////////////////////////INTEGER DFT /////////////////////////////INTEGER DFT
@ -223,111 +216,111 @@ void HandleProgressiveInt( int8_t sample1, int8_t sample2 )
//Estimated 78 minimum instructions... So for two pairs each... just over 4ksps, theoretical. //Estimated 78 minimum instructions... So for two pairs each... just over 4ksps, theoretical.
//Running overall at ~2kHz. With GCC: YUCK! 102 cycles!!! //Running overall at ~2kHz. With GCC: YUCK! 102 cycles!!!
for( i = 0; i < gbins; i++ ) //Loop, fixed size = 3 + 2 cycles N/A for( i = 0; i < gbins; i++ ) //Loop, fixed size = 3 + 2 cycles N/A
{ {
//12 cycles MIN //12 cycles MIN
adv = *(ds++); //Read, indirect from RAM (and increment) 2+2 cycles 4 adv = *(ds++); //Read, indirect from RAM (and increment) 2+2 cycles 4
ipl = *(ds++); //Read, indirect from RAM (and increment) 2+2 cycles 4 ipl = *(ds++); //Read, indirect from RAM (and increment) 2+2 cycles 4
//13 cycles MIN //13 cycles MIN
ipl += adv; //Advance, 16bit += 16bit, 1 + 1 cycles 2 ipl += adv; //Advance, 16bit += 16bit, 1 + 1 cycles 2
localipl = (ipl>>8)<<1; //Select upper 8 bits 1 cycles 1 *** AS/IS: 4 localipl = (ipl>>8)<<1; //Select upper 8 bits, 1 cycle 1 *** AS/IS: 4
st = &sintable[localipl]; st = &sintable[localipl];
s1 = *(st++); //Read s1 component out of table. 2+2 cycles 2 s1 = *(st++); //Read s1 component out of table. 2+2 cycles 2
c1 = *st; //Read c1 component out of table. 2 cycles 2 *** AS/IS: 4 c1 = *st; //Read c1 component out of table. 2 cycles 2 *** AS/IS: 4
ts = (s1 * sample1); // 8 x 8 multiply signed + copy R1 out. zero MSB ts 2 ->Deferred ts = (s1 * sample1); // 8 x 8 multiply signed + copy R1 out. zero MSB ts 2 ->Deferred
tc = (c1 * sample1); // 8 x 8 multiply signed + copy R1 out. zero MSB tc 2 ->Deferred tc = (c1 * sample1); // 8 x 8 multiply signed + copy R1 out. zero MSB tc 2 ->Deferred
//15 cycles MIN //15 cycles MIN
ipl += adv; //Advance, 16bit += 16bit, 1 + 1 cycles 2 ipl += adv; //Advance, 16bit += 16bit, 1 + 1 cycles 2
localipl = (ipl>>8)<<1; //Select upper 8 bits 1 cycles 1 *** AS/IS: 4 localipl = (ipl>>8)<<1; //Select upper 8 bits 1 cycles 1 *** AS/IS: 4
// need to load Z with 'sintable' and add localipl 2 // need to load Z with 'sintable' and add localipl 2
st = &sintable[localipl]; st = &sintable[localipl];
s1 = *(st++); //Read s1 component out of table. 2 cycles 2 s1 = *(st++); //Read s1 component out of table. 2 cycles 2
c1 = *st; //Read c1 component out of table. 2 cycles 2 *** AS/IS: 4 c1 = *st; //Read c1 component out of table. 2 cycles 2 *** AS/IS: 4
ts += (s1 * sample2); // 8 x 8 multiply signed + add R1 out. 3 ->Deferred ts += ( s1 * sample2 ); // 8 x 8 multiply signed + add R1 out. 3 ->Deferred
tc += (c1 * sample2); // 8 x 8 multiply signed + add R1 out. 3 ->Deferred tc += ( c1 * sample2 ); // 8 x 8 multiply signed + add R1 out. 3 ->Deferred
//Add TS and TC to the datspace stuff. (24 instructions) // Add TS and TC to the datspace stuff. (24 instructions)
tmp1 = (*ds); //Read out, sin component. 4 Accurate. tmp1 = ( *ds ); // Read out, sin component. 4 Accurate
tmp1 -= tmp1>>7; //Subtract from the MSB (with carry) 2 -> 6 AS/IS: 7+7 = 14 tmp1 -= tmp1 >> 7; // Subtract from the MSB (with carry) 2 -> 6 AS/IS: 7+7 = 14
tmp1 += ts>>7; //Add MSBs with carry 2 -> 6 AS/IS: 6 tmp1 += ts >> 7; // Add MSBs with carry 2 -> 6 AS/IS: 6
*(ds++) = tmp1; //Store values back 4 *( ds++ ) = tmp1; // Store values back 4
tmp1 = *ds; //Read out, sin component. 4 tmp1 = *ds; // Read out, sin component. 4
tmp1 -= tmp1>>7; //Subtract from the MSB (with carry) 2 -> 6 AS/IS: 7+7 = 14 tmp1 -= tmp1 >> 7; // Subtract from the MSB (with carry) 2 -> 6 AS/IS: 7+7 = 14
tmp1 += tc>>7; //Add MSBs with carry 2 -> 6 AS/IS: 6 tmp1 += tc >> 7; // Add MSBs with carry 2 -> 6 AS/IS: 6
*ds++ = tmp1; //Store values back 4 *ds++ = tmp1; // Store values back 4
*(ds-3) = ipl; //Store values back 4 AS/IS: 6 *( ds - 3 ) = ipl; // Store values back 4 AS/IS: 6
//AS-IS: 8 loop overhead. //AS-IS: 8 loop overhead.
} }
} }
void DoDFTProgressiveInteger( float * outbins, float * frequencies, int bins, const float * databuffer, int place_in_data_buffer, int size_of_data_buffer, float q, float speedup ) void DoDFTProgressiveInteger( float *outbins, float *frequencies, int bins, const float *databuffer,
int place_in_data_buffer, int size_of_data_buffer, float q, float speedup )
{ {
int i; int i;
static int last_place; static int last_place;
if( !donefirstrun ) if ( !donefirstrun )
{ {
donefirstrun = 1; donefirstrun = 1;
for( i = 0; i < 256; i++ ) for ( i = 0; i < 256; i++ )
{ {
sintable[i*2+0] = (int8_t)((sinf( i / 256.0 * 6.283 ) * 127.0)); sintable[ i * 2 + 0 ] = ( int8_t )( ( sinf( i / 256.0 * 6.283 ) * 127.0 ) );
sintable[i*2+1] = (int8_t)((cosf( i / 256.0 * 6.283 ) * 127.0)); sintable[ i * 2 + 1 ] = ( int8_t )( ( cosf( i / 256.0 * 6.283 ) * 127.0 ) );
} }
} }
if( gbins != bins ) if ( gbins != bins )
{ {
gbins = bins; gbins = bins;
if( datspace ) free( datspace ); if ( datspace ) free( datspace );
datspace = malloc( bins * 2 * 4 ); datspace = malloc( bins * 2 * 4 );
} }
for( i = 0; i < bins; i++ ) for ( i = 0; i < bins; i++ )
{ {
float freq = frequencies[i]; float freq = frequencies[ i ];
datspace[i*4] = 65536.0/freq; datspace[ i * 4 ] = 65536.0 / freq;
} }
for( i = last_place; i != ( place_in_data_buffer&0xffffe ); i = (i+2)%size_of_data_buffer ) for ( i = last_place; i != ( place_in_data_buffer & 0xffffe );
i = ( i + 2 ) % size_of_data_buffer )
{ {
int8_t ifr1 = (int8_t)( ((databuffer[i+0]) ) * 127 ); int8_t ifr1 = ( int8_t )( ( ( databuffer[ i + 0 ] ) ) * 127 );
int8_t ifr2 = (int8_t)( ((databuffer[i+1]) ) * 127 ); int8_t ifr2 = ( int8_t )( ( ( databuffer[ i + 1 ] ) ) * 127 );
// printf( "%d %d\n", i, place_in_data_buffer&0xffffe ); // printf( "%d %d\n", i, place_in_data_buffer&0xffffe );
HandleProgressiveInt( ifr1, ifr2 ); HandleProgressiveInt( ifr1, ifr2 );
} }
last_place = place_in_data_buffer&0xfffe; last_place = place_in_data_buffer & 0xfffe;
//Extract bins. // Extract bins.
for( i = 0; i < bins; i++ ) for ( i = 0; i < bins; i++ )
{ {
int16_t isps = datspace[i*4+2]; int16_t isps = datspace[ i * 4 + 2 ];
int16_t ispc = datspace[i*4+3]; int16_t ispc = datspace[ i * 4 + 3 ];
int16_t mux = ( (isps/256) * (isps/256)) + ((ispc/256) * (ispc/256)); int16_t mux = ( ( isps / 256 ) * ( isps / 256 ) ) + ( ( ispc / 256 ) * ( ispc / 256 ) );
// printf( "%d (%d %d)\n", mux, isps, ispc ); // printf( "%d (%d %d)\n", mux, isps, ispc );
outbins[i] = sqrt( mux )/100.0; outbins[ i ] = sqrt( mux ) / 100.0;
} }
// printf( "\n"); // printf( "\n");
} }
#endif #endif

View file

@ -1,30 +1,29 @@
//Copyright 2015-2020 <>< Charles Lohr under the ColorChord License. // Copyright 2015-2020 <>< Charles Lohr under the ColorChord License.
#if defined(WINDOWS) || defined(USE_WINDOWS)\ #if defined( WINDOWS ) || defined( USE_WINDOWS ) || defined( WIN32 ) || defined( WIN64 ) || \
|| defined(WIN32) || defined(WIN64) \ defined( _WIN32 ) || defined( _WIN64 )
|| defined(_WIN32) || defined(_WIN64)
#include <winsock2.h>
#include <windows.h> #include <windows.h>
#include <winsock2.h>
#ifndef strdup #ifndef strdup
#define strdup _strdup #define strdup _strdup
#endif #endif
#endif #endif
#include <ctype.h>
#include "color.h" #include "color.h"
#include <math.h> #include "configs.h"
#include <stdio.h> #include "decompose.h"
#include "os_generic.h"
#include "dft.h" #include "dft.h"
#include "filter.h" #include "filter.h"
#include "decompose.h" #include "hook.h"
#include <stdlib.h>
#include <string.h>
#include "notefinder.h" #include "notefinder.h"
#include "os_generic.h"
#include "outdrivers.h" #include "outdrivers.h"
#include "parameters.h" #include "parameters.h"
#include "hook.h" #include <ctype.h>
#include "configs.h" #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CNFG_IMPLEMENTATION #define CNFG_IMPLEMENTATION
@ -34,20 +33,19 @@
#include "CNFA.h" #include "CNFA.h"
// Sound driver.
//Sound driver. struct CNFADriver *sd;
struct CNFADriver * sd;
int bQuitColorChord = 0; int bQuitColorChord = 0;
#ifdef ANDROID #ifdef ANDROID
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <android/log.h> #include <android/log.h>
#include <fcntl.h>
#include <pthread.h> #include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void HandleDestroy() void HandleDestroy()
{ {
@ -60,115 +58,103 @@ void HandleDestroy()
#define GENLINEWIDTH 89 #define GENLINEWIDTH 89
#define GENLINES 67 #define GENLINES 67
int genlinelen = 0; char genlog[ ( GENLINEWIDTH + 1 ) * ( GENLINES + 1 ) + 2 ] = "log";
char genlog[(GENLINEWIDTH+1)*(GENLINES+1)+2] = "log";
int genloglen; int genloglen;
int genloglines; int genloglines;
int genlinelen = 0;
int firstnewline = -1; int firstnewline = -1;
void example_log_function( int readSize, char * buf ) void example_log_function( int readSize, char *buf )
{ {
static og_mutex_t * mt; static og_mutex_t *mt;
if( !mt ) mt = OGCreateMutex(); if ( !mt ) mt = OGCreateMutex();
OGLockMutex( mt ); OGLockMutex( mt );
int i; for ( int i = 0; readSize && i <= readSize && buf[ i ]; i++ )
for( i = 0; (readSize>=0)?(i <= readSize):buf[i]; i++ )
{ {
char c = buf[i]; char c = buf[ i ];
if( c == '\0' ) c = '\n'; if ( c == '\0' ) c = '\n';
if( ( c != '\n' && genlinelen >= GENLINEWIDTH ) || c == '\n' ) if ( ( c != '\n' && genlinelen >= GENLINEWIDTH ) || c == '\n' )
{ {
int k;
genloglines++; genloglines++;
if( genloglines >= GENLINES ) if ( genloglines >= GENLINES )
{ {
genloglen -= firstnewline+1; genloglen -= firstnewline + 1;
int offset = firstnewline; int offset = firstnewline;
firstnewline = -1; firstnewline = -1;
int k;
for( k = 0; k < genloglen; k++ ) for ( k = 0; k < genloglen; k++ )
{ {
if( ( genlog[k] = genlog[k+offset+1] ) == '\n' && firstnewline < 0) if ( ( genlog[ k ] = genlog[ k + offset + 1 ] ) == '\n' && firstnewline < 0 )
{
firstnewline = k; firstnewline = k;
}
} }
genlog[k] = 0; genlog[ k ] = 0;
genloglines--; genloglines--;
} }
genlinelen = 0; genlinelen = 0;
if( c != '\n' ) if ( c != '\n' )
{ {
genlog[genloglen+1] = 0; genlog[ genloglen + 1 ] = 0;
genlog[genloglen++] = '\n'; genlog[ genloglen++ ] = '\n';
} }
if( firstnewline < 0 ) firstnewline = genloglen; if ( firstnewline < 0 ) firstnewline = genloglen;
} }
genlog[genloglen+1] = 0; genlog[ genloglen + 1 ] = 0;
genlog[genloglen++] = c; genlog[ genloglen++ ] = c;
if( c != '\n' ) genlinelen++; if ( c != '\n' ) genlinelen++;
} }
OGUnlockMutex( mt ); OGUnlockMutex( mt );
} }
#if defined( WIN32 ) || defined( USE_WINDOWS )
#if defined(WIN32) || defined(USE_WINDOWS)
#define ESCAPE_KEY 0x1B #define ESCAPE_KEY 0x1B
void HandleDestroy() void HandleDestroy()
{ {
CNFAClose( sd ); CNFAClose( sd );
} }
#else #else
#define ESCAPE_KEY 65307 #define ESCAPE_KEY 65307
#endif #endif
int is_suspended = 0;
float DeltaFrameTime = 0; float DeltaFrameTime = 0;
double Now = 0; double Now = 0;
int is_suspended = 0;
int lastfps; int lastfps;
short screenx, screeny; short screenx, screeny;
struct DriverInstances * outdriver[MAX_OUT_DRIVERS]; struct DriverInstances *outdriver[ MAX_OUT_DRIVERS ];
int headless = 0; REGISTER_PARAM( headless, PAINT );
int headless = 0; REGISTER_PARAM( headless, PAINT ); int set_screenx = 640; REGISTER_PARAM( set_screenx, PAINT );
int set_screenx = 640; REGISTER_PARAM( set_screenx, PAINT ); int set_screeny = 480; REGISTER_PARAM( set_screeny, PAINT );
int set_screeny = 480; REGISTER_PARAM( set_screeny, PAINT ); char sound_source[ 16 ]; REGISTER_PARAM( sound_source, PABUFFER );
char sound_source[16]; REGISTER_PARAM( sound_source, PABUFFER ); int cpu_autolimit = 1; REGISTER_PARAM( cpu_autolimit, PAINT );
int cpu_autolimit = 1; REGISTER_PARAM( cpu_autolimit, PAINT );
float cpu_autolimit_interval = 0.016; REGISTER_PARAM( cpu_autolimit_interval, PAFLOAT ); float cpu_autolimit_interval = 0.016; REGISTER_PARAM( cpu_autolimit_interval, PAFLOAT );
int sample_channel = -1; REGISTER_PARAM( sample_channel, PAINT ); int sample_channel = -1; REGISTER_PARAM( sample_channel, PAINT );
int showfps = 1; REGISTER_PARAM( showfps, PAINT ); int showfps = 1; REGISTER_PARAM( showfps, PAINT );
#if defined(ANDROID) || defined( __android__ ) #if defined( ANDROID ) || defined( __android__ )
float in_amplitude = 2; float in_amplitude = 2;
#else #else
float in_amplitude = 1; float in_amplitude = 1;
#endif #endif
REGISTER_PARAM( in_amplitude, PAFLOAT ); REGISTER_PARAM( in_amplitude, PAFLOAT );
struct NoteFinder * nf; struct NoteFinder *nf;
//Sound circular buffer // Sound circular buffer
#define SOUNDCBSIZE 8096 #define SOUNDCBSIZE 8096
#define MAX_CHANNELS 2 #define MAX_CHANNELS 2
double VisTimeEnd, VisTimeStart; double VisTimeEnd, VisTimeStart;
int soundhead = 0; float sound[ SOUNDCBSIZE ];
float sound[SOUNDCBSIZE]; int soundhead = 0;
int show_debug = 0; int show_debug = 0;
int show_debug_basic = 1; int show_debug_basic = 1;
int gKey = 0; int gKey = 0;
@ -176,53 +162,48 @@ extern int force_white;
void RecalcBaseHz() void RecalcBaseHz()
{ {
nf->base_hz = 55 * pow( 2, gKey / 12.0 ); ChangeNFParameters( nf ); nf->base_hz = 55 * pow( 2, gKey / 12.0 );
ChangeNFParameters( nf );
} }
void HandleKey( int keycode, int bDown ) void HandleKey( int keycode, int bDown )
{ {
char c = toupper( keycode ); char c = toupper( keycode );
#ifdef ANDROID #ifdef ANDROID
if( keycode == 4 && bDown ) if ( keycode == 4 && bDown )
{ {
//Back button. // Back button.
printf( "Back button pressed\n" ); printf( "Back button pressed\n" );
AndroidSendToBack( 0 ); AndroidSendToBack( 0 );
return; return;
} }
#endif #endif
if( c == 'D' && bDown ) show_debug = !show_debug;
if( c == 'W' ) force_white = bDown;
if( c == '9' && bDown ) { gKey--; RecalcBaseHz(); }
if( c == '-' && bDown ) { gKey++; RecalcBaseHz(); }
if( c == '0' && bDown ) { gKey = 0; RecalcBaseHz(); }
if( c == 'E' && bDown ) show_debug_basic = !show_debug_basic;
if( c == 'K' && bDown ) DumpParameters();
if( keycode == ESCAPE_KEY ) exit( 0 ); if( keycode == ESCAPE_KEY ) exit( 0 );
if( c == 'W' ) force_white = bDown;
if( c == 'D' && bDown ) show_debug = !show_debug;
if( c == '9' && bDown ) { gKey--; RecalcBaseHz(); }
if( c == '-' && bDown ) { gKey++; RecalcBaseHz(); }
if( c == '0' && bDown ) { gKey = 0; RecalcBaseHz(); }
if( c == 'E' && bDown ) show_debug_basic = !show_debug_basic;
if( c == 'K' && bDown ) DumpParameters();
printf( "Key: %d -> %d\n", keycode, bDown ); printf( "Key: %d -> %d\n", keycode, bDown );
KeyHappened( keycode, bDown ); KeyHappened( keycode, bDown );
} }
//On Android we want a really basic GUI // On Android we want a really basic GUI
void HandleButton( int x, int y, int button, int bDown ) void HandleButton( int x, int y, int button, int bDown )
{ {
printf( "Button: %d,%d (%d) -> %d\n", x, y, button, bDown ); printf( "Button: %d,%d (%d) -> %d\n", x, y, button, bDown );
if( bDown ) if ( bDown )
{ {
if( y < 800 ) if ( y < 800 )
{ {
if( x < screenx/3 ) if ( x < screenx / 3 )
{ gKey--;
gKey --; else if ( x < ( screenx * 2 / 3 ) )
}
else if( x < (screenx*2/3) )
{
gKey = 0; gKey = 0;
}
else else
{
gKey++; gKey++;
}
printf( "KEY: %d\n", gKey ); printf( "KEY: %d\n", gKey );
RecalcBaseHz(); RecalcBaseHz();
} }
@ -233,72 +214,48 @@ void HandleMotion( int x, int y, int mask )
{ {
} }
void SoundCB( struct CNFADriver * sd, short * out, short * in, int framesp, int framesr ) void SoundCB( struct CNFADriver *sd, short *out, short *in, int framesp, int framesr )
{ {
int channelin = sd->channelsRec; int channelin = sd->channelsRec;
int channelout = sd->channelsPlay; int channelout = sd->channelsPlay;
//*samplesp = 0;
// int process_channels = (MAX_CHANNELS < channelin)?MAX_CHANNELS:channelin;
//Load the samples into a ring buffer. Split the channels from interleved to one per buffer. // Load the samples into a ring buffer. Split the channels from interleved to one per buffer.
if ( in )
int i;
int j;
if( in )
{ {
for( i = 0; i < framesr; i++ ) for ( int i = 0; i < framesr; i++ )
{ {
if( sample_channel < 0 ) if ( sample_channel < 0 )
{ {
float fo = 0; float fo = 0;
for( j = 0; j < channelin; j++ ) for ( int j = 0; j < channelin; j++ )
{ {
float f = in[i*channelin+j] / 32767.; float f = in[ i * channelin + j ] / 32767.;
if( f >= -1 && f <= 1 ) if ( f >= -1 && f <= 1 )
{
fo += f; fo += f;
}
else else
{ fo += ( f > 0 ) ? 1 : -1;
fo += (f>0)?1:-1;
// printf( "Sound fault A %d/%d %d/%d %f\n", j, channelin, i, samplesr, f );
}
} }
fo /= channelin; fo /= channelin;
sound[soundhead] = fo*in_amplitude; sound[ soundhead ] = fo * in_amplitude;
soundhead = (soundhead+1)%SOUNDCBSIZE; soundhead = ( soundhead + 1 ) % SOUNDCBSIZE;
} }
else else
{ {
float f = in[i*channelin+sample_channel] / 32767.; float f = in[ i * channelin + sample_channel ] / 32767.;
if ( f > 1 || f < -1 ) f = ( f > 0 ) ? 1 : -1;
if( f > 1 || f < -1 ) sound[ soundhead ] = f * in_amplitude;
{ soundhead = ( soundhead + 1 ) % SOUNDCBSIZE;
f = (f>0)?1:-1;
}
//printf( "Sound fault B %d/%d\n", i, samplesr );
sound[soundhead] = f*in_amplitude;
soundhead = (soundhead+1)%SOUNDCBSIZE;
} }
} }
SoundEventHappened( framesr, in, 0, channelin ); SoundEventHappened( framesr, in, 0, channelin );
} }
if( out ) if ( out )
{ {
for( j = 0; j < framesp * channelout; j++ ) memset( out, 0, framesp * channelout );
{
out[j] = 0;
}
SoundEventHappened( framesp, out, 1, channelout ); SoundEventHappened( framesp, out, 1, channelout );
} }
} }
#ifdef ANDROID #ifdef ANDROID
@ -315,17 +272,18 @@ void HandleResume()
// function for calling initilization functions if we are using TCC // function for calling initilization functions if we are using TCC
#ifdef TCC #ifdef TCC
void RegisterConstructorFunctions(){ void RegisterConstructorFunctions()
{
// Basic Window stuff // Basic Window stuff
REGISTERheadless(); REGISTERheadless();
REGISTERset_screenx(); REGISTERset_screenx();
REGISTERset_screeny(); REGISTERset_screeny();
REGISTERsound_source(); REGISTERsound_source();
REGISTERcpu_autolimit(); REGISTERcpu_autolimit();
REGISTERcpu_autolimit_interval(); REGISTERcpu_autolimit_interval();
REGISTERsample_channel(); REGISTERsample_channel();
REGISTERshowfps(); REGISTERshowfps();
REGISTERin_amplitude(); REGISTERin_amplitude();
// Audio stuff // Audio stuff
@ -336,59 +294,47 @@ void RegisterConstructorFunctions(){
// Video Stuff // Video Stuff
REGISTERnull(); REGISTERnull();
REGISTERDisplayArray(); REGISTERDisplayArray();
//REGISTERDisplayDMX(); // REGISTERDisplayDMX();
//REGISTERDisplayFileWrite(); // REGISTERDisplayFileWrite();
REGISTERDisplayHIDAPI(); REGISTERDisplayHIDAPI();
REGISTERDisplayNetwork(); REGISTERDisplayNetwork();
REGISTERDisplayOutDriver(); REGISTERDisplayOutDriver();
REGISTERDisplayPie(); REGISTERDisplayPie();
//REGISTERDisplaySHM(); // REGISTERDisplaySHM();
// Output stuff // Output stuff
//REGISTERDisplayUSB2812(); // REGISTERDisplayUSB2812();
REGISTEROutputCells(); REGISTEROutputCells();
REGISTEROutputLinear(); REGISTEROutputLinear();
REGISTEROutputProminent(); REGISTEROutputProminent();
REGISTEROutputVoronoi(); REGISTEROutputVoronoi();
//REGISTERRecorderPlugin();
//void ManuallyRegisterDevices();
//ManuallyRegisterDevices();
} }
#endif #endif
int main(int argc, char ** argv) int main( int argc, char **argv )
{ {
int i;
#ifdef TCC #ifdef TCC
RegisterConstructorFunctions(); RegisterConstructorFunctions();
#endif #endif
printf( "Output Drivers:\n" ); printf( "Output Drivers:\n" );
for( i = 0; i < MAX_OUT_DRIVERS; i++ ) for ( int i = 0; i < MAX_OUT_DRIVERS; i++ )
{ {
if( ODList[i].Name ) printf( "\t%s\n", ODList[i].Name ); if ( ODList[ i ].Name ) printf( "\t%s\n", ODList[ i ].Name );
} }
#if defined(WIN32) || defined(USE_WINDOWS) #if defined( WIN32 ) || defined( USE_WINDOWS )
//In case something needs network access. // In case something needs network access.
WSADATA wsaData; WSADATA wsaData;
WSAStartup(0x202, &wsaData); WSAStartup( 0x202, &wsaData );
#elif defined( ANDROID ) #elif defined( ANDROID )
int hasperm = AndroidHasPermissions( "READ_EXTERNAL_STORAGE" ); int hasperm = AndroidHasPermissions( "READ_EXTERNAL_STORAGE" );
if( !hasperm )
{
AndroidRequestAppPermissions( "READ_EXTERNAL_STORAGE" );
}
int haspermInternet = AndroidHasPermissions( "INTERNET" ); int haspermInternet = AndroidHasPermissions( "INTERNET" );
if( !haspermInternet ) if ( !hasperm ) AndroidRequestAppPermissions( "READ_EXTERNAL_STORAGE" );
{ if ( !haspermInternet ) AndroidRequestAppPermissions( "INTERNET" );
AndroidRequestAppPermissions( "INTERNET" );
}
#else #else
//Linux // Linux
#endif #endif
gargc = argc; gargc = argc;
@ -396,103 +342,90 @@ int main(int argc, char ** argv)
SetupConfigs(); SetupConfigs();
//Initialize Rawdraw // Initialize Rawdraw
int frames = 0; int frames = 0;
double ThisTime; double ThisTime;
double SecToWait;
double LastFPSTime = OGGetAbsoluteTime(); double LastFPSTime = OGGetAbsoluteTime();
double LastFrameTime = OGGetAbsoluteTime(); double LastFrameTime = OGGetAbsoluteTime();
double SecToWait;
CNFGBGColor = 0x800000; CNFGBGColor = 0x800000;
CNFGDialogColor = 0x444444; CNFGDialogColor = 0x444444;
char title[1024]; // Generate the window title
char * tp = title; char title[ 1024 ];
strcpy( title, "Colorchord " );
memcpy( tp, "ColorChord ", strlen( "ColorChord " ) ); for ( int i = 1; i < argc; i++ )
tp += strlen( "ColorChord " );
for( i = 1; i < argc; i++ )
{ {
memcpy( tp, argv[i], strlen( argv[i] ) ); strcat( title, argv[ i ] );
tp += strlen( argv[i] ); strcat( title, " " );
*tp = ' ';
tp++;
} }
*tp = 0; if ( !headless ) CNFGSetup( title, set_screenx, set_screeny );
if( !headless )
CNFGSetup( title, set_screenx, set_screeny );
char * OutDriverNames = strdup( GetParameterS( "outdrivers", "null" ) ); char *OutDriverNames = strdup( GetParameterS( "outdrivers", "null" ) );
char * ThisDriver = OutDriverNames; char *ThisDriver = OutDriverNames;
char * TDStart; char *TDStart;
for( i = 0; i < MAX_OUT_DRIVERS; i++ ) for ( int i = 0; i < MAX_OUT_DRIVERS; i++ )
{ {
while( *ThisDriver == ' ' || *ThisDriver == '\t' ) ThisDriver++; while ( *ThisDriver == ' ' || *ThisDriver == '\t' ) ThisDriver++;
if( !*ThisDriver ) break; if ( !*ThisDriver ) break;
TDStart = ThisDriver; TDStart = ThisDriver;
while( *ThisDriver != 0 && *ThisDriver != ',' ) while ( *ThisDriver != 0 && *ThisDriver != ',' )
{ {
if( *ThisDriver == '\t' || *ThisDriver == ' ' ) *ThisDriver = 0; if ( *ThisDriver == '\t' || *ThisDriver == ' ' ) *ThisDriver = 0;
ThisDriver++; ThisDriver++;
} }
if( *ThisDriver ) if ( *ThisDriver )
{ {
*ThisDriver = 0; *ThisDriver = 0;
ThisDriver++; ThisDriver++;
} }
printf( "Loading: %s\n", TDStart ); printf( "Loading: %s\n", TDStart );
outdriver[i] = SetupOutDriver( TDStart ); outdriver[ i ] = SetupOutDriver( TDStart );
} }
free(OutDriverNames); free( OutDriverNames );
do do {
{ // Initialize Sound
//Initialize Sound sd = CNFAInit( sound_source, "colorchord", &SoundCB, GetParameterI( "samplerate", 44100 ),
sd = CNFAInit( sound_source, "colorchord", &SoundCB, GetParameterI( "samplerate", 44100 ), GetParameterI( "channels", 2 ),
GetParameterI( "samplerate", 44100 ), GetParameterI( "samplerate", 44100 ), GetParameterI( "channels", 2 ), GetParameterI( "buffer", 1024 ),
GetParameterI( "channels", 2 ), GetParameterI( "channels", 2 ),
GetParameterI( "buffer", 1024 ),
GetParameterS( "devplay", 0 ), GetParameterS( "devrecord", 0 ), NULL ); GetParameterS( "devplay", 0 ), GetParameterS( "devrecord", 0 ), NULL );
if( sd ) break; if ( sd ) break;
CNFGColor( 0xffffff ); CNFGColor( 0xffffff );
CNFGPenX = 10; CNFGPenY = 100; CNFGPenX = 10;
CNFGPenY = 100;
CNFGHandleInput(); CNFGHandleInput();
CNFGClearFrame(); CNFGClearFrame();
CNFGDrawText( "Colorchord must be used with sound. Sound not available.", 10 ); CNFGDrawText( "Colorchord must be used with sound. Sound not available.", 10 );
CNFGSwapBuffers(); CNFGSwapBuffers();
OGSleep(1); OGSleep( 1 );
} while( 1 ); } while ( 1 );
nf = CreateNoteFinder( sd->spsRec ); nf = CreateNoteFinder( sd->spsRec );
//Once everything was reinitialized, re-read the ini files. // Once everything was reinitialized, re-read the ini files.
SetEnvValues( 1 ); SetEnvValues( 1 );
printf( "================================================= Set Up\n" ); printf( "================================================= Set Up\n" );
Now = OGGetAbsoluteTime(); Now = OGGetAbsoluteTime();
double Last = Now; double Last = Now;
#ifdef ANDROID while ( !bQuitColorChord )
while(!bQuitColorChord)
#else
while(!bQuitColorChord)
#endif
{ {
char stt[1024]; char stt[ 1024 ];
//Handle Rawdraw frame swappign // Handle Rawdraw frame swappign
Now = OGGetAbsoluteTime(); Now = OGGetAbsoluteTime();
DeltaFrameTime = Now - Last; DeltaFrameTime = Now - Last;
if( !headless ) if ( !headless )
{ {
CNFGHandleInput(); CNFGHandleInput();
CNFGClearFrame(); CNFGClearFrame();
@ -500,188 +433,192 @@ int main(int argc, char ** argv)
CNFGGetDimensions( &screenx, &screeny ); CNFGGetDimensions( &screenx, &screeny );
} }
RunNoteFinder( nf, sound, (soundhead-1+SOUNDCBSIZE)%SOUNDCBSIZE, SOUNDCBSIZE ); RunNoteFinder( nf, sound, ( soundhead - 1 + SOUNDCBSIZE ) % SOUNDCBSIZE, SOUNDCBSIZE );
//Done all ColorChord work. // Done all ColorChord work.
VisTimeStart = OGGetAbsoluteTime(); VisTimeStart = OGGetAbsoluteTime();
for( i = 0; i < MAX_OUT_DRIVERS; i++ ) // call the output drivers with the updated note finder data
for ( int i = 0; i < MAX_OUT_DRIVERS; i++ )
{ {
if ( force_white ) memset( OutLEDs, 0x7f, MAX_LEDS * 3 );
if( force_white ) if ( outdriver[ i ] ) outdriver[ i ]->Func( outdriver[ i ]->id, nf );
{
memset( OutLEDs, 0x7f, MAX_LEDS*3 );
}
if( outdriver[i] )
outdriver[i]->Func( outdriver[i]->id, nf );
} }
VisTimeEnd = OGGetAbsoluteTime(); VisTimeEnd = OGGetAbsoluteTime();
if( !headless ) if ( !headless )
{ {
//Handle outputs. // Handle outputs.
int freqbins = nf->freqbins; int freqbins = nf->freqbins;
int note_peaks = freqbins/2; int note_peaks = freqbins / 2;
int freqs = freqbins * nf->octaves; int freqs = freqbins * nf->octaves;
//int maxdists = freqbins/2;
//Do a bunch of debugging. // Do a bunch of debugging.
if( show_debug_basic && !is_suspended ) if ( show_debug_basic && !is_suspended )
{ {
//char sttdebug[1024]; for ( int i = 0; i < nf->dists_count; i++ )
//char * sttend = sttdebug;
for( i = 0; i < nf->dists_count; i++ )
{ {
CNFGPenX = (nf->dists[i].mean + 0.5) / freqbins * screenx; //Move over 0.5 for visual purposes. The means is correct. // Move over 0.5 for visual purposes. The means is correct.
CNFGPenY = 400-nf->dists[i].amp * 150.0 / nf->dists[i].sigma; CNFGPenX = ( nf->dists[ i ].mean + 0.5 ) / freqbins * screenx;
//printf( "%f %f\n", dists[i].mean, dists[i].amp ); CNFGPenY = 400 - nf->dists[ i ].amp * 150.0 / nf->dists[ i ].sigma;
sprintf( stt, "%f\n%f\n", nf->dists[i].mean, nf->dists[i].amp ); sprintf( stt, "%f\n%f\n", nf->dists[ i ].mean, nf->dists[ i ].amp );
// sttend += sprintf( sttend, "%f/%f ",nf->dists[i].mean, nf->dists[i].amp );
CNFGDrawText( stt, 2 ); CNFGDrawText( stt, 2 );
} }
CNFGColor( 0xffffff ); CNFGColor( 0xffffff );
//Draw the folded bins // Draw the folded bins
for( i = 0; i < freqbins; i++ ) for ( int bin = 0; bin < freqbins; bin++ )
{ {
float x0 = i / (float)freqbins * (float)screenx; const float x0 = bin / (float)freqbins * (float)screenx;
float x1 = (i+1) / (float)freqbins * (float)screenx; const float x1 = ( bin + 1 ) / (float)freqbins * (float)screenx;
float amp = nf->folded_bins[i] * 250.0; const float amp = nf->folded_bins[ bin ] * 250.0;
CNFGDialogColor = CCtoHEX( ((float)(i+0.5) / freqbins), 1.0, 1.0 ); const float note = (float)( bin + 0.5 ) / freqbins;
CNFGDrawBox( x0, 400-amp, x1, 400 ); CNFGDialogColor = CCtoHEX( note, 1.0, 1.0 );
CNFGDrawBox( x0, 400 - amp, x1, 400 );
} }
CNFGDialogColor = 0xf0f000; CNFGDialogColor = 0xf0f000;
for( i = 0; i < note_peaks; i++ ) // Draw the note peaks
for ( int peak = 0; peak < note_peaks; peak++ )
{ {
//printf( "%f %f /", note_positions[i], note_amplitudes[i] ); if ( nf->note_amplitudes_out[ peak ] < 0 ) continue;
if( nf->note_amplitudes_out[i] < 0 ) continue; float note = (float)nf->note_positions[ peak ] / freqbins;
float note = (float) nf->note_positions[i] / freqbins;
CNFGDialogColor = CCtoHEX( note, 1.0, 1.0 ); CNFGDialogColor = CCtoHEX( note, 1.0, 1.0 );
CNFGDrawBox( ((float)i / note_peaks) * screenx, 480 - nf->note_amplitudes_out[i] * 100, ((float)(i+1) / note_peaks) * screenx, 480 ); const int x1 = ( (float)peak / note_peaks ) * screenx;
CNFGPenX = ((float)(i+.4) / note_peaks) * screenx; const int x2 = ( (float)( peak + 1 ) / note_peaks ) * screenx;
const int y1 = 480 - nf->note_amplitudes_out[ peak ] * 100;
const int y2 = 480;
CNFGDrawBox( x1, y1, x2, y2 );
CNFGPenX = ( (float)( peak + .4 ) / note_peaks ) * screenx;
CNFGPenY = screeny - 30; CNFGPenY = screeny - 30;
sprintf( stt, "%d\n%0.0f", nf->enduring_note_id[i], nf->note_amplitudes2[i]*1000.0 ); sprintf( stt, "%d\n%0.0f", nf->enduring_note_id[ peak ],
//sttend += sprintf( sttend, "%5d/%5.0f ", nf->enduring_note_id[i], nf->note_amplitudes2[i]*1000.0 ); nf->note_amplitudes2[ peak ] * 1000.0 );
CNFGDrawText( stt, 2 ); CNFGDrawText( stt, 2 );
} }
//Let's draw the o-scope. // Let's draw the o-scope.
int thissoundhead = soundhead; int thissoundhead = soundhead;
thissoundhead = (thissoundhead-1+SOUNDCBSIZE)%SOUNDCBSIZE; thissoundhead = ( thissoundhead - 1 + SOUNDCBSIZE ) % SOUNDCBSIZE;
int lasty = sound[thissoundhead] * 128 + 128; thissoundhead = (thissoundhead-1+SOUNDCBSIZE)%SOUNDCBSIZE; int lasty = sound[ thissoundhead ] * 128 + 128;
int thisy = sound[thissoundhead] * 128 + 128; thissoundhead = (thissoundhead-1+SOUNDCBSIZE)%SOUNDCBSIZE; thissoundhead = ( thissoundhead - 1 + SOUNDCBSIZE ) % SOUNDCBSIZE;
for( i = 0; i < screenx; i++ ) int thisy = sound[ thissoundhead ] * 128 + 128;
thissoundhead = ( thissoundhead - 1 + SOUNDCBSIZE ) % SOUNDCBSIZE;
for ( int i = 0; i < screenx; i++ )
{ {
CNFGTackSegment( i, lasty, i+1, thisy ); CNFGTackSegment( i, lasty, i + 1, thisy );
lasty = thisy; lasty = thisy;
thisy = sound[thissoundhead] * 128 + 128; thissoundhead = (thissoundhead-1+SOUNDCBSIZE)%SOUNDCBSIZE; thisy = sound[ thissoundhead ] * 128 + 128;
thissoundhead = ( thissoundhead - 1 + SOUNDCBSIZE ) % SOUNDCBSIZE;
} }
//puts( sttdebug );
} }
//Extra debugging? // Extra debugging?
if( show_debug && !is_suspended ) if ( show_debug && !is_suspended )
{ {
//Draw the histogram // Draw the histogram
float lasthistval; float lasthistval;
CNFGColor( 0xffffff ); CNFGColor( 0xffffff );
for( i = -1; i < screenx; i++ ) for ( int x_val = -1; x_val < screenx; x_val++ )
{ {
float thishistval = CalcHistAt( (float)i/(float)screenx*freqbins-0.5, nf->freqbins, nf->dists, nf->dists_count ); // Calculate the value of the histogram at the current screen position
if( i >= 0 ) float hist_point = (float)x_val / (float)screenx * freqbins - 0.5;
CNFGTackSegment( i, 400-lasthistval * 250.0, i+1, 400-thishistval * 250.0 ); float thishistval =
CalcHistAt( hist_point, nf->freqbins, nf->dists, nf->dists_count );
// Display the value on the screen
const short y = 400 - lasthistval * 250.0;
if ( x_val >= 0 ) CNFGTackSegment( x_val, y, x_val + 1, y );
lasthistval = thishistval; lasthistval = thishistval;
} }
CNFGColor( 0xffffff ); CNFGColor( 0xffffff );
//Draw the bins // Draw the bins
for( i = 0; i < freqs; i++ ) for ( int bin = 0; bin < freqs; bin++ )
{ {
float x0 = i / (float)freqs * (float)screenx; float x0 = bin / (float)freqs * (float)screenx;
float x1 = (i+1) / (float)freqs * (float)screenx; float x1 = ( bin + 1 ) / (float)freqs * (float)screenx;
float amp = nf->outbins[i] * 250.0; float amp = nf->outbins[ bin ] * 250.0;
CNFGDialogColor = CCtoHEX( ((float)i / freqbins), 1.0, 1.0 ); float note = (float)bin / freqbins;
CNFGDialogColor = CCtoHEX( note, 1.0, 1.0 );
CNFGDrawBox( x0, 0, x1, amp ); CNFGDrawBox( x0, 0, x1, amp );
} }
CNFGDialogColor = 0x0f0f0f; CNFGDialogColor = 0x0f0f0f;
char stdebug[1024]; char stdebug[ 1024 ];
sprintf( stdebug, "DFT:%8.2fms\nFLT:%8.2f\nDEC:%8.2f\nFNL:%8.2f\nDPY:%8.2f", sprintf( stdebug, "DFT:%8.2fms\nFLT:%8.2f\nDEC:%8.2f\nFNL:%8.2f\nDPY:%8.2f",
(nf->DFTTime - nf->StartTime)*1000, ( nf->DFTTime - nf->StartTime ) * 1000, ( nf->FilterTime - nf->DFTTime ) * 1000,
(nf->FilterTime - nf->DFTTime)*1000, ( nf->DecomposeTime - nf->FilterTime ) * 1000,
(nf->DecomposeTime - nf->FilterTime)*1000, ( nf->FinalizeTime - nf->DecomposeTime ) * 1000,
(nf->FinalizeTime - nf->DecomposeTime)*1000, ( VisTimeEnd - VisTimeStart ) * 1000 );
(VisTimeEnd - VisTimeStart)*1000 );
CNFGPenX = 50; CNFGPenX = 50;
CNFGPenY = 50; CNFGPenY = 50;
CNFGDrawText( stdebug, 2 ); CNFGDrawText( stdebug, 2 );
} }
if( !is_suspended ) if ( !is_suspended )
{ {
CNFGColor( show_debug?0xffffff:0x000000 ); CNFGColor( show_debug ? 0xffffff : 0x000000 );
CNFGPenX = 0; CNFGPenY = screeny-10; CNFGPenX = 0;
CNFGPenY = screeny - 10;
CNFGDrawText( "Extra Debug (D)", 2 ); CNFGDrawText( "Extra Debug (D)", 2 );
CNFGColor( show_debug_basic?0xffffff:0x000000 ); CNFGColor( show_debug_basic ? 0xffffff : 0x000000 );
CNFGPenX = 120; CNFGPenY = screeny-10; CNFGPenX = 120;
CNFGPenY = screeny - 10;
CNFGDrawText( "Basic Debug (E)", 2 ); CNFGDrawText( "Basic Debug (E)", 2 );
CNFGColor( show_debug_basic?0xffffff:0x000000 ); CNFGColor( show_debug_basic ? 0xffffff : 0x000000 );
CNFGPenX = 240; CNFGPenY = screeny-10; CNFGPenX = 240;
CNFGPenY = screeny - 10;
sprintf( stt, "[9] Key: %d [0] (%3.1f) [-]", gKey, nf->base_hz ); sprintf( stt, "[9] Key: %d [0] (%3.1f) [-]", gKey, nf->base_hz );
CNFGDrawText( stt, 2 ); CNFGDrawText( stt, 2 );
CNFGColor( 0xffffff ); CNFGColor( 0xffffff );
CNFGPenX = 440; CNFGPenY = screeny-10; CNFGPenX = 440;
CNFGPenY = screeny - 10;
sprintf( stt, "FPS: %d", lastfps ); sprintf( stt, "FPS: %d", lastfps );
CNFGDrawText( stt, 2 ); CNFGDrawText( stt, 2 );
#ifdef ANDROID #ifdef ANDROID
CNFGColor( 0xffffff ); CNFGColor( 0xffffff );
CNFGPenX = 10; CNFGPenY = 600; CNFGPenX = 10;
CNFGPenY = 600;
CNFGDrawText( genlog, 3 ); CNFGDrawText( genlog, 3 );
#endif #endif
CNFGSwapBuffers(); CNFGSwapBuffers();
} }
} }
//Finish Rawdraw with FPS counter, and a nice delay loop. // Finish Rawdraw with FPS counter, and a nice delay loop.
frames++; frames++;
ThisTime = OGGetAbsoluteTime(); ThisTime = OGGetAbsoluteTime();
if( ThisTime > LastFPSTime + 1 && showfps ) if ( ThisTime > LastFPSTime + 1 && showfps )
{ {
#ifndef ANDROID #ifndef ANDROID
printf( "FPS: %d\n", frames ); printf( "FPS: %d\n", frames );
#endif #endif
lastfps = frames; lastfps = frames;
frames = 0; frames = 0;
LastFPSTime+=1; LastFPSTime += 1;
} }
if( cpu_autolimit ) if ( cpu_autolimit )
{ {
SecToWait = cpu_autolimit_interval - ( ThisTime - LastFrameTime ); SecToWait = cpu_autolimit_interval - ( ThisTime - LastFrameTime );
LastFrameTime += cpu_autolimit_interval; LastFrameTime += cpu_autolimit_interval;
if( SecToWait < -.1 ) LastFrameTime = ThisTime - .1; if ( SecToWait < -.1 ) LastFrameTime = ThisTime - .1;
if( SecToWait > 0 ) if ( SecToWait > 0 ) OGUSleep( (int)( SecToWait * 1000000 ) );
OGUSleep( (int)( SecToWait * 1000000 ) );
} }
if( !is_suspended ) if ( !is_suspended ) SetEnvValues( 0 );
SetEnvValues( 0 );
Last = Now; Last = Now;
} }
} }