/*
* Tiny la: A light weight game engine.
* Copyright (C) 2023 Wu Yiming
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"

#include "la_5.h"

extern LA MAIN;

laPropContainer* LA_PC_SYNTH;
laPropContainer* LA_PC_CHANNEL;

laNodeCategory* LA_NODE_CATEGORY_SYNTHESIZER;
laNodeCategory* LA_NODE_CATEGORY_SYSTEM_SOUND;

laBaseNodeType LA_IDN_INPUT;
laBaseNodeType LA_IDN_PULSE;
laBaseNodeType LA_IDN_FM;
laBaseNodeType LA_IDN_VCA;
laBaseNodeType LA_IDN_NOISE;
laBaseNodeType LA_IDN_OUTPUT;
laBaseNodeType LA_IDN_SCOPE;
laBaseNodeType LA_IDN_ENVELOPE;
laBaseNodeType LA_IDN_QUANTIZE;
laBaseNodeType LA_IDN_SYNTH_DRIVER;
laBaseNodeType LA_IDN_SYNTH_TRIGGER;

laPropContainer* LA_PC_IDN_INPUT;
laPropContainer* LA_PC_IDN_PULSE;
laPropContainer* LA_PC_IDN_FM;
laPropContainer* LA_PC_IDN_VCA;
laPropContainer* LA_PC_IDN_NOISE;
laPropContainer* LA_PC_IDN_OUTPUT;
laPropContainer* LA_PC_IDN_SCOPE;
laPropContainer* LA_PC_IDN_ENVELOPE;
laPropContainer* LA_PC_IDN_QUANTIZE;
laPropContainer* LA_PC_IDN_SYNTH_DRIVER;
laPropContainer* LA_PC_IDN_SYNTH_TRIGGER;

#define _2PI 6.283185307

#define VAL2FREQ(val) \
    16.0f*pow(2,val) // 0-10, 16-16384Hz

#define VAL13  -0.218640286
#define VAL27  0.78135971352
#define VAL440 4.78135971352 // 2^FREQC*16=440
#define VALHALF (1.0f/12.0f)

#define WRAPPHASE(p) \
    while(p>_2PI){ p-=_2PI; }

#define INITPACKET(arr) \
    if(!arr){ arr=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN); }

#define INPUTPACKET(ptr,socket) \
    {if(socket->Source && socket->Source->DataType==(LA_PROP_FLOAT|LA_PROP_ARRAY) && socket->Source->ArrLen>=LA_SYNTH_PLEN){ \
        ptr=((real*)socket->Source->Data); }else{ ptr=0; } }

#define FRAME_INTERVAL (MAIN.Audio->AudioFrameInterval)

#define SAMPLE_RATE (MAIN.Audio->AudioSampleRate)

void IDN_InputInit(laSynthNodeInput* n, int NoCreate){
    INITPACKET(n->rTime); INITPACKET(n->rTrigger); //INITPACKET(n->rSamplesL); INITPACKET(n->rSamplesR);
    if(NoCreate){
        if(!n->OutL) n->OutL=laCreateOutSocket(n,"L",LA_PROP_FLOAT|LA_PROP_ARRAY);
        if(!n->OutR) n->OutR=laCreateOutSocket(n,"R",LA_PROP_FLOAT|LA_PROP_ARRAY);
        return;
    }
    n->OutL=laCreateOutSocket(n,"L",LA_PROP_FLOAT|LA_PROP_ARRAY);
    n->OutR=laCreateOutSocket(n,"R",LA_PROP_FLOAT|LA_PROP_ARRAY);
    n->OutTime=laCreateOutSocket(n,"TIME",LA_PROP_FLOAT|LA_PROP_ARRAY);
    n->OutTrigger=laCreateOutSocket(n,"TRIGGER",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"Input");
}
void IDN_InputDestroy(laSynthNodeInput* n){
    laDestroyOutSocket(n->OutTime); laDestroyOutSocket(n->OutTrigger);
    laDestroyOutSocket(n->OutL); laDestroyOutSocket(n->OutR); strSafeDestroy(&n->Base.Name);
    memFree(n->rTime); memFree(n->rTrigger); memFree(n->rSamplesL); memFree(n->rSamplesL);
}
int IDN_InputVisit(laSynthNodeInput* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_InputEval(laSynthNodeInput* n){
    laSynth*ss=MAIN.Audio->AudioEvalSynth;
    real time=ss->EvalTime,target_time=time+(real)LA_SYNTH_PLEN/(real)MAIN.Audio->AudioSampleRate;
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        real fac=(real)i/(real)LA_SYNTH_PLEN;
        n->rTime[i] = tnsLinearItp(time,target_time,fac);
    }
    if(ss->EvalSamples==0){ n->rTrigger[0] = 10; }else{ n->rTrigger[0]=0; }
    n->OutTime->Data=n->rTime; n->OutTrigger->Data=n->rTrigger; n->OutTime->ArrLen=LA_SYNTH_PLEN; n->OutTrigger->ArrLen=LA_SYNTH_PLEN;
    n->OutL->Data=MAIN.Audio->InputSamplesL; n->OutR->Data=MAIN.Audio->InputSamplesR; n->OutL->ArrLen=LA_SYNTH_PLEN; n->OutR->ArrLen=LA_SYNTH_PLEN;
    return 1;
}
void IDN_InputCopy(laSynthNodeInput* new, laSynthNodeInput* old, int DoRematch){
    if(DoRematch){ return; }
    LA_IDN_OLD_DUPL(OutTime); LA_IDN_OLD_DUPL(OutTrigger);
}
void laui_InputNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeInput*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);

    laUiItem* b=laBeginRow(uil,c,0,0);
    laUiItem* ui=laShowLabel(uil,c,"Capture",0,0); ui->Expand=1; ui->Flags|=LA_TEXT_ALIGN_RIGHT;
    laShowNodeSocket(uil,c,This,"out_l",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowNodeSocket(uil,c,This,"out_r",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laEndRow(uil,b);

    b=laBeginRow(uil,c,0,0);
    ui=laShowLabel(uil,c,"Synth",0,0); ui->Expand=1; ui->Flags|=LA_TEXT_ALIGN_RIGHT;
    laShowNodeSocket(uil,c,This,"out_time",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowNodeSocket(uil,c,This,"out_trigger",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laEndRow(uil,b);
}

void IDN_PulseInit(laSynthNodePulse* n, int NoCreate){
    INITPACKET(n->rOut);
    if(NoCreate){ return; }
    n->InTrigger = laCreateInSocket("TRIGGER",0);
    n->InWidth = laCreateInSocket("WIDTH",0);
    n->InGate = laCreateInSocket("GATE",0);
    n->Out=laCreateOutSocket(n,"OUT",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"Pulse");
}
void IDN_PulseDestroy(laSynthNodePulse* n){
    laDestroyOutSocket(n->Out); laDestroyInSocket(n->InWidth); laDestroyInSocket(n->InTrigger); laDestroyInSocket(n->InGate);
    strSafeDestroy(&n->Base.Name); memFree(n->rOut);
}
int IDN_PulseVisit(laSynthNodePulse* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->InTrigger)){ laBaseNode*bn=n->InTrigger->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InWidth)){ laBaseNode*bn=n->InWidth->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InGate)){ laBaseNode*bn=n->InGate->Source->Parent; LA_VISIT_NODE(bn,vi); }
    n->Out->Data = n->rOut; n->Out->ArrLen=LA_SYNTH_PLEN;
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_PulseEval(laSynthNodePulse* n){
    laSynth*ss=MAIN.Audio->AudioEvalSynth;
    real* trigger=0; real trig=n->iTrigger?100:-100; INPUTPACKET(trigger,n->InTrigger); LA_GET_SRC_AS_VALUE(trig,n->InTrigger);
    real* gate=0; real gt=n->rGate; INPUTPACKET(gate,n->InGate); LA_GET_SRC_AS_VALUE(gt,n->InGate);
    real* width=0; real w=n->rWidth; INPUTPACKET(width,n->InWidth);
    real wi=0; LA_GET_SRC_AS_VALUE(wi,n->InWidth); if(!width){ w=n->rWidth+wi*n->rInfluence; }
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        if(trigger){ trig=trigger[i]; } if(gate){ gt=gate[i]; } if(width){ w=n->rWidth+width[i]*n->rInfluence; }
        if(!n->Triggered){ if(trig>gt){ n->Triggered=1; n->EvalSamples=1; } }
        else{ if(trig<=gt){ n->Triggered=0; } }
        int totalsamples=w*MAIN.Audio->AudioSampleRate;
        if(n->EvalSamples) n->EvalSamples++;
        n->rOut[i]= (n->Triggered || (n->EvalSamples > 0 && n->EvalSamples < totalsamples)) ? 10.0f : 0.0f;
        if(n->EvalSamples > totalsamples && !n->Triggered){ n->EvalSamples=0; }
    }
    return 1;
}
void IDN_PulseCopy(laSynthNodePulse* new, laSynthNodePulse* old, int DoRematch){
    if(DoRematch){  LA_IDN_NEW_LINK(InTrigger); LA_IDN_NEW_LINK(InWidth); LA_IDN_NEW_LINK(InGate);  return; }
    LA_IDN_OLD_DUPL(Out); new->rGate = old->rGate; new->rInfluence=old->rInfluence; new->rWidth=old->rWidth;
}
void laui_PulseNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodePulse*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);
    laUiItem* b;

    b=laBeginRow(uil,c,0,0);
    laShowNodeSocket(uil,c,This,"in_width",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laShowItem(uil,c,This,"influence");
    laShowItem(uil,c,This,"width")->Expand=1;
    laEndRow(uil,b);

    b=laBeginRow(uil,c,0,0);
    laShowItem(uil,c,This,"gate")->Expand=1;
    laShowNodeSocket(uil,c,This,"in_gate",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laShowNodeSocket(uil,c,This,"in_trigger",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laEndRow(uil,b);
    b=laBeginRow(uil,c,0,0);
    laShowSeparator(uil,c)->Expand=1; 
    laShowItem(uil,c,This,"trigger")->Flags|=LA_UI_FLAGS_MOMENTARY|LA_UI_FLAGS_HIGHLIGHT;
    laShowItem(uil,c,This,"out")->Flags|=LA_UI_SOCKET_LABEL_W;
    laEndRow(uil,b);
}


void IDN_FMInit(laSynthNodeFM* n, int NoCreate){
    INITPACKET(n->OutSamples);
    if(NoCreate){ return; }
    n->InFrequency=laCreateInSocket("FREQ",0); n->Out=laCreateOutSocket(n,"OUT",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"FM"); n->Frequency=4;
}
void IDN_FMDestroy(laSynthNodeFM* n){
    laDestroyInSocket(n->InFrequency); laDestroyOutSocket(n->Out); strSafeDestroy(&n->Base.Name); memFree(n->OutSamples);
}
int IDN_FMVisit(laSynthNodeFM* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->InFrequency)){ laBaseNode*bn=n->InFrequency->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_FMEval(laSynthNodeFM* n){
    real f=n->Frequency, constf=0; real* inputf;
    INPUTPACKET(inputf,n->InFrequency); LA_GET_SRC_AS_VALUE(constf,n->InFrequency); 
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        real useF=inputf?(inputf[i]*n->rInfluence+f):(f+constf); if(n->Slow) useF-=10;
        n->Phase+=FRAME_INTERVAL*VAL2FREQ(useF)*_2PI;
        WRAPPHASE(n->Phase);
        n->OutSamples[i]=sin(n->Phase)*10;
    }
    n->Out->Data=n->OutSamples; n->Out->ArrLen=LA_SYNTH_PLEN;
    return 1;
}
void IDN_FMCopy(laSynthNodeFM* new, laSynthNodeFM* old, int DoRematch){
    if(DoRematch){ LA_IDN_NEW_LINK(InFrequency) return; }
    LA_IDN_OLD_DUPL(Out); new->Frequency=old->Frequency; new->Slow=old->Slow; new->rInfluence=old->rInfluence;
}
void laui_FMNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeFM*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);

    laUiItem* b=laBeginRow(uil,c,0,0);
    laShowItem(uil,c,This,"slow");
    laShowNodeSocket(uil,c,This,"in_frequency",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowItem(uil,c,This,"influence");
    laShowItem(uil,c,This,"frequency")->Expand=1;
    laShowNodeSocket(uil,c,This,"out",0);
    laEndRow(uil,b);
}

void IDN_VCAInit(laSynthNodeVCA* n, int NoCreate){
    INITPACKET(n->OutSamples);
    if(NoCreate){ return; }
    n->InAmp=laCreateInSocket("AMP",0); n->In=laCreateInSocket("IN",0);
    n->Out=laCreateOutSocket(n,"OUT",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"FM"); n->Amp=10;
}
void IDN_VCADestroy(laSynthNodeVCA* n){
    laDestroyInSocket(n->InAmp); laDestroyInSocket(n->In);
    laDestroyOutSocket(n->Out); strSafeDestroy(&n->Base.Name); memFree(n->OutSamples);
}
int IDN_VCAVisit(laSynthNodeVCA* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->In)){ laBaseNode*bn=n->In->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InAmp)){ laBaseNode*bn=n->InAmp->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_VCAEval(laSynthNodeVCA* n){
    real amp=n->Amp, constamp=amp; real* inputamp=0,*input=0;
    INPUTPACKET(input,n->In); INPUTPACKET(inputamp,n->InAmp);
    if(!inputamp) LA_GET_SRC_AS_VALUE(constamp,n->InAmp); constamp/=10;
    n->Out->Data=n->OutSamples; n->Out->ArrLen=LA_SYNTH_PLEN;
    if(!input){ memset(n->OutSamples,0,sizeof(real)*LA_SYNTH_PLEN); return 0; }
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        real useA= inputamp?tnsInterpolate(1.0f,inputamp[i]/10.0f,n->rInfluence)*constamp:constamp;
        n->OutSamples[i]= input[i]*useA;
    }
    return 1;
}
void IDN_VCACopy(laSynthNodeVCA* new, laSynthNodeVCA* old, int DoRematch){
    if(DoRematch){ LA_IDN_NEW_LINK(InAmp) LA_IDN_NEW_LINK(In) return; }
    LA_IDN_OLD_DUPL(Out); new->Amp=old->Amp; new->rInfluence = old->rInfluence;
}
void laui_VCANode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeVCA*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);
    laColumn* cl,*cr; laSplitColumn(uil,c,0.3); cl=laLeftColumn(c,0); cr=laRightColumn(c,0);

    laUiItem* b=laBeginRow(uil,c,0,0);
    laShowNodeSocket(uil,c,This,"in",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowNodeSocket(uil,c,This,"in_amp",0);
    laShowItem(uil,c,This,"influence");
    laShowItem(uil,c,This,"amp")->Expand=1;
    laShowNodeSocket(uil,cr,This,"out",0);
    laEndRow(uil,b);
}

void IDN_NoiseInit(laSynthNodeNoise* n, int NoCreate){
    INITPACKET(n->OutWhiteSamples); INITPACKET(n->OutPinkSamples);
    n->PinkA[0]=0.02109238; n->PinkA[1]=0.07113478; n->PinkA[2]=0.68873558;
    n->PinkP[0]=0.3190; n->PinkP[1]=0.7756; n->PinkP[2]=0.9613;
    if(NoCreate){ return; }
    n->OutWhite=laCreateOutSocket(n,"WHITE",LA_PROP_FLOAT|LA_PROP_ARRAY);
    n->OutPink=laCreateOutSocket(n,"PINK",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"Noise");
}
void IDN_NoiseDestroy(laSynthNodeNoise* n){
    laDestroyOutSocket(n->OutWhite); laDestroyOutSocket(n->OutPink); strSafeDestroy(&n->Base.Name);
    memFree(n->OutWhiteSamples); memFree(n->OutPinkSamples);
}
int IDN_NoiseVisit(laSynthNodeNoise* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi); LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_NoiseEval(laSynthNodeNoise* n){
    real RMI2 = 2.0 / (real)RAND_MAX; // + 1.0; // change for range [0,1)
    real offset = n->PinkA[0] + n->PinkA[1] + n->PinkA[2];
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        real R1=(real)rand()/(real)RAND_MAX;
        real R2=(real)rand()/(real)RAND_MAX;
        real X=(real)sqrt(-2.0f*log(R1))*cos(2.0f*TNS_PI*R2);
        n->OutWhiteSamples[i]=X*2.5;

        real temp; for(int i=0;i<3;i++){ temp=(real)rand();
            n->PinkStates[i] = n->PinkP[i] * (n->PinkStates[i] - temp) + temp;
        }
        n->OutPinkSamples[i]=(n->PinkA[0]*n->PinkStates[0]+
                              n->PinkA[1]*n->PinkStates[1]+
                              n->PinkA[2]*n->PinkStates[2])*RMI2-offset;
        n->OutPinkSamples[i]*=40;
    }
    n->OutWhite->Data=n->OutWhiteSamples; n->OutWhite->ArrLen=LA_SYNTH_PLEN;
    n->OutPink->Data=n->OutPinkSamples; n->OutPink->ArrLen=LA_SYNTH_PLEN;
    return 1;
}
void IDN_NoiseCopy(laSynthNodeNoise* new, laSynthNodeNoise* old, int DoRematch){
    if(DoRematch){ return; }
    LA_IDN_OLD_DUPL(OutWhite);
}
void laui_NoiseNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeNoise*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);

    laUiItem* b=laBeginRow(uil,c,0,0);
    laShowNodeSocket(uil,c,This,"out_white",0)->Flags|=LA_UI_SOCKET_LABEL_N;
    laShowNodeSocket(uil,c,This,"out_pink",0)->Flags|=LA_UI_SOCKET_LABEL_N;
    laEndRow(uil,b);
}

void IDN_ScopeInit(laSynthNodeScope* n, int NoCreate){
    if(!n->Display1){ n->Display1=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN*2); }
    if(!n->Display2){ n->Display2=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN*2); }
    laSpinInit(&n->Lock);
    if(NoCreate){ return; }
    n->In1=laCreateInSocket("CH1",0); n->In2=laCreateInSocket("CH2",0);
    strSafeSet(&n->Base.Name,"SCOPE"); n->Time=5; n->Brightness1=0.7f; n->Brightness2=0.4f;
    n->Gain1=1; n->Gain2=1;
}
void IDN_ScopeDestroy(laSynthNodeScope* n){
    laDestroyInSocket(n->In1); laDestroyOutSocket(n->In2); strSafeDestroy(&n->Base.Name);
    memFree(n->Display1); memFree(n->Display2);
    laSpinDestroy(&n->Lock);
}
int IDN_ScopeVisit(laSynthNodeScope* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->In1)){ laBaseNode*bn=n->In1->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->In2)){ laBaseNode*bn=n->In2->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_ScopeEval(laSynthNodeScope* n){
    if(!n->Display1){ n->Display1=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN*2); }
    if(!n->Display2){ n->Display2=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN*2); }
    real* ch1,*ch2; INPUTPACKET(ch1,n->In1); INPUTPACKET(ch2,n->In2);
    int Frame=1<<(n->Time-1); TNS_CLAMP(Frame,1,LA_SYNTH_PLEN);
    int Times=LA_SYNTH_PLEN/Frame; int sp=0; laSpinLock(&n->Lock);
    for(int t=0;t<Times;t++){
        real smin1=FLT_MAX,smax1=-FLT_MAX,smin2=FLT_MAX,smax2=-FLT_MAX;
        for(int i=0;i<Frame;i++){
            if(ch1){ smin1=TNS_MIN2(smin1,ch1[sp]); smax1=TNS_MAX2(smax1,ch1[sp]); }
            if(ch2){ smin2=TNS_MIN2(smin2,ch2[sp]); smax2=TNS_MAX2(smax2,ch2[sp]); }
            sp++;
        }
        if(!ch1){smin1=smax1=0; LA_GET_SRC_AS_VALUE(smin1,n->In1); smax1=smin1; }
        if(!ch2){smin2=smax2=0; LA_GET_SRC_AS_VALUE(smin2,n->In2); smax2=smin2; }
        int ns=n->NextSample;
        n->Display1[ns]=smin1; n->Display1[ns+LA_SYNTH_PLEN]=smax1;
        n->Display2[ns]=smin2; n->Display2[ns+LA_SYNTH_PLEN]=smax2;
        n->NextSample++; if(n->NextSample>=LA_SYNTH_PLEN) n->NextSample=0;
    }
    n->FromSynth=MAIN.Audio->AudioEvalSynth;
    laSpinUnlock(&n->Lock);
    return 1;
}
void IDN_ScopeCopy(laSynthNodeScope* new, laSynthNodeScope* old, int DoRematch){
    if(DoRematch){ LA_IDN_NEW_LINK(In1)  LA_IDN_NEW_LINK(In2) return; }
    new->Brightness1=old->Brightness1; new->Brightness2=old->Brightness2;
    new->Gain1=old->Gain1; new->Gain2=old->Gain2;
    new->Offset1=old->Offset1; new->Offset2=old->Offset2;
    new->Time=old->Time;
}
void laui_ScopeNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeScope*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);
    laColumn* cl,*cr; laSplitColumn(uil,c,0.5); cl=laLeftColumn(c,0); cr=laRightColumn(c,0);

    laUiItem* b=laBeginRow(uil,c,0,0);
    laUiItem* u=laShowItem(uil,c,This,"gain1");u->Flags|=LA_UI_FLAGS_EXPAND; u->Expand=1;
    laShowNodeSocket(uil,c,This,"in1",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laEndRow(uil,b);

    b=laBeginRow(uil,c,0,0);
    u=laShowItem(uil,c,This,"gain2");u->Flags|=LA_UI_FLAGS_EXPAND; u->Expand=1;
    laShowNodeSocket(uil,c,This,"in2",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laEndRow(uil,b);

    laShowItem(uil,c,This,"scope")->Extra->HeightCoeff=6;

    laShowLabel(uil,cl,"CH1",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cl,This,"bright1"); laShowItem(uil,cl,This,"offset1");
    laShowLabel(uil,cr,"CH2",0,0)->Flags|=LA_TEXT_ALIGN_CENTER;
    laShowItem(uil,cr,This,"bright2"); laShowItem(uil,cr,This,"offset2");

    laShowItem(uil,c,This,"time")->Flags|=LA_UI_FLAGS_EXPAND;
}

void IDN_OutputInit(laSynthNodeOutput* n, int NoCreate){
    if(NoCreate){
        laAudioChannel* outchannel = laGetAudioChannel(SSTR(n->SendName));
        if(outchannel) memAssignRef(n,&n->Send,outchannel);
        if(!n->InL) n->InL=laCreateInSocket("L/M",0);
        if(!n->InR) n->InR=laCreateInSocket("R",0);
        return;
    }
    n->InL=laCreateInSocket("L/M",0); n->InR=laCreateInSocket("R",0); strSafeSet(&n->Base.Name,"Output");
}
void IDN_OutputDestroy(laSynthNodeOutput* n){
    laDestroyInSocket(n->InL); laDestroyInSocket(n->InR); strSafeDestroy(&n->Base.Name);
}
int IDN_OutputVisit(laSynthNodeOutput* n, laNodeVisitInfo* vi){
    if(LA_SRC_AND_PARENT(n->InL)){ laBaseNode*bn=n->InL->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InR)){ laBaseNode*bn=n->InR->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    laAudioChannel* outchannel = laGetAudioChannel(SSTR(n->SendName));
    memAssignRef(n,&n->Send,outchannel);
    return LA_DAG_FLAG_PERM;
}
int IDN_OutputEval(laSynthNodeOutput* n){
    if(!n->Send)return 1;
    real* inputL; INPUTPACKET(inputL,n->InL); real* inputR; INPUTPACKET(inputR,n->InR); if(!inputL && !inputR) return 1;
    real Samples[LA_SYNTH_PLEN];
    if(inputL){
        for(int i=0;i<LA_SYNTH_PLEN;i++){ n->Send->SamplesL[i] += inputL[i]; }
        if(n->Send){ n->Send->IsMono=1; }
    }
    if(inputR){
        for(int i=0;i<LA_SYNTH_PLEN;i++){ n->Send->SamplesR[i] += inputR[i]; }
        if(n->Send){ n->Send->IsMono=0; }
    }
    return 1;
}
void IDN_OutputCopy(laSynthNodeOutput* new, laSynthNodeOutput* old, int DoRematch){
    if(DoRematch){ LA_IDN_NEW_LINK(InL) return; }
    if(DoRematch){ LA_IDN_NEW_LINK(InR) return; }
    strSafeSet(&new->SendName,SSTR(old->SendName)); new->Send=old->Send;
}
void laui_OutputNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeOutput*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);
    laColumn* cl,*cr; laSplitColumn(uil,c,0.3); cl=laLeftColumn(c,0); cr=laRightColumn(c,0);

    laUiItem* b=laBeginRow(uil,c,0,0);
    laShowNodeSocket(uil,c,This,"in_l",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowNodeSocket(uil,c,This,"in_r",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowLabel(uil,c,"🕪",0,0);
    laShowItemFull(uil,c,This,"send_channel_selector",LA_WIDGET_COLLECTION_SELECTOR,0,laui_IdentifierOnly,0)->Flags|=LA_UI_COLLECTION_SIMPLE_SELECTOR;
    laShowItem(uil,c,This,"send_channel_name")->Expand = 1;
    laEndRow(uil,b);
}

void IDN_EnvelopeInit(laSynthNodeEnvelope* n, int NoCreate){
    if(!NoCreate){ strSafeSet(&n->Base.Name,"Envelope");
        n->Attack=laCreateInSocket("ATTACK",0); n->Delay=laCreateInSocket("DELAY",0);
        n->Sustain=laCreateInSocket("SUSTAIN",0); n->Release=laCreateInSocket("RELEASE",0);
        n->Trigger=laCreateInSocket("TRIGGER",0); n->Out=laCreateOutSocket(n, "OUT",0);
        n->Time=20; n->rAttack=1; n->rDelay=5; n->rSustain=5; n->rRelease=7; n->rGate=5;
    }
    if(!n->Gate){ n->Gate=laCreateInSocket("GATE",0); }
    if(!n->Restart){ n->Restart=laCreateInSocket("RESTART",0); }
    if(!n->OutSamples){ n->OutSamples=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN); }
    n->Out->Data = n->OutSamples; n->Out->DataType = LA_PROP_FLOAT|LA_PROP_ARRAY; n->Out->ArrLen=LA_SYNTH_PLEN;
}
void IDN_EnvelopeDestroy(laSynthNodeEnvelope* n){
    laDestroyInSocket(n->Attack); laDestroyInSocket(n->Delay); laDestroyInSocket(n->Gate);
    laDestroyInSocket(n->Sustain); laDestroyInSocket(n->Release);
    laDestroyInSocket(n->Trigger); laDestroyOutSocket(n->Out);
    memFree(n->OutSamples);
    strSafeDestroy(&n->Base.Name);
}
int IDN_EnvelopeVisit(laSynthNodeEnvelope* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->Attack)){ laBaseNode*bn=n->Attack->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->Delay)){ laBaseNode*bn=n->Delay->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->Sustain)){ laBaseNode*bn=n->Sustain->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->Release)){ laBaseNode*bn=n->Release->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->Trigger)){ laBaseNode*bn=n->Trigger->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->Restart)){ laBaseNode*bn=n->Restart->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_EnvelopeEval(laSynthNodeEnvelope* n){
    int trigger_at=-1; real trig=n->bTrigger?n->bTrigger*100:-100; real res=0;
    real* trigger; INPUTPACKET(trigger,n->Trigger); if(!trigger){ LA_GET_SRC_AS_VALUE(trig,n->Trigger); }
    real* restart; INPUTPACKET(restart,n->Restart); if(!restart){ LA_GET_SRC_AS_VALUE(res,n->Restart); }
    real *att,*del,*sus,*rel,*gat;
    real attack=n->rAttack,delay=n->rDelay,sustain=n->rSustain,release=n->rRelease;
    real gate = n->rGate; INPUTPACKET(gat,n->Gate); if(!gat) LA_GET_SRC_AS_VALUE(gate,n->Gate);
    INPUTPACKET(att,n->Attack); if(!att) LA_GET_SRC_AS_VALUE(attack,n->Attack);
    INPUTPACKET(del,n->Delay); if(!del) LA_GET_SRC_AS_VALUE(delay,n->Delay);
    INPUTPACKET(sus,n->Sustain); if(!sus) LA_GET_SRC_AS_VALUE(sustain,n->Sustain);
    INPUTPACKET(rel,n->Release); if(!rel) LA_GET_SRC_AS_VALUE(release,n->Release);
    attack=attack?pow(attack/10,2):0; delay=delay?pow(delay/10,2):0; release=release?pow(release/10,2):0;
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        if(trigger){ trig=trigger[i]; } if(gat){ gate=gat[i]; } if(restart){ res=restart[i]; }
        if(att){ attack=att[i]*n->iAttack+n->rAttack; }
        if(del){ delay=del[i]*n->iDelay+n->rDelay; }
        if(sus){ sustain=sus[i]*n->iSustain+n->rSustain; }
        if(rel){ release=rel[i]*n->iRelease+n->rRelease; }
        if(res){ n->Time=0; n->ReleaseTime=-10000; n->Triggered=0;}
        if(!n->Triggered){ if(trig > gate){ n->Triggered = 1; n->Time = 0; n->ReleaseTime=10000; n->AtLevel=0; } }
        else{ if(trig < gate-0.0001f){ n->Triggered = 0; n->ReleaseTime = n->Time; } }
        if(n->Time < n->ReleaseTime){
            if(n->Time<=attack){
                n->OutSamples[i]=10.0f*pow(n->Time/attack,0.3);
            }elif(n->Time<=delay + attack){
                real fac=pow((n->Time-attack)/delay,0.3);
                n->OutSamples[i]= tnsLinearItp(10.0f, sustain, fac);
            }else{
                n->OutSamples[i]=sustain;
            }
            n->AtLevel=n->OutSamples[i];
        }else{
            if(n->Time - n->ReleaseTime < release){
                real fac=pow((n->Time - n->ReleaseTime)/release,0.3);
                n->OutSamples[i]= tnsLinearItp(n->AtLevel,0.0f, fac);
            }else{
                n->OutSamples[i]=0;
            }
        }
        n->Time+=FRAME_INTERVAL;
    }
    return 1;
}
void IDN_EnvelopeCopy(laSynthNodeEnvelope* new, laSynthNodeEnvelope* old, int DoRematch){
    if(DoRematch){
        LA_IDN_NEW_LINK(Attack) LA_IDN_NEW_LINK(Delay)
        LA_IDN_NEW_LINK(Sustain) LA_IDN_NEW_LINK(Release) LA_IDN_NEW_LINK(Trigger) return;
    }
    LA_IDN_OLD_DUPL(Out);
    new->rGate=old->rGate;
    new->rAttack=old->rAttack;new->rSustain=old->rSustain;new->rDelay=old->rDelay;new->rRelease=old->rRelease;
    new->iAttack=old->iAttack;new->iSustain=old->iSustain;new->iDelay=old->iDelay;new->iRelease=old->rRelease;
}
void laui_EnvelopeNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeEnvelope*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);

    laUiItem* b,*b1;
#define ADSR_ROW(what) \
    b=laBeginRow(uil,c,0,0);{ \
    laShowNodeSocket(uil,c,This,"in_" what,0)->Flags|=LA_UI_SOCKET_LABEL_E; \
    laUiItem* value=laShowItem(uil,c,This,"i" what); \
    value=laShowItem(uil,c,This,what);value->Expand=1; \
    }laEndRow(uil,b);

    ADSR_ROW("attack") ADSR_ROW("delay") ADSR_ROW("sustain") ADSR_ROW("release")
    
    b=laBeginRow(uil,c,0,0);
    laShowItem(uil,c,This,"gate")->Expand=1;
    laShowNodeSocket(uil,c,This,"in_gate",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laShowNodeSocket(uil,c,This,"in_trigger",0)->Flags|=LA_UI_SOCKET_LABEL_E;
    laEndRow(uil,b);
    b=laBeginRow(uil,c,0,0);
    laShowSeparator(uil,c)->Expand=1; 
    laShowItem(uil,c,This,"in_restart")->Flags|=LA_UI_SOCKET_LABEL_E;
    laShowItem(uil,c,This,"trigger")->Flags|=LA_UI_FLAGS_MOMENTARY|LA_UI_FLAGS_HIGHLIGHT;
    laShowItem(uil,c,This,"out")->Flags|=LA_UI_SOCKET_LABEL_W;
    laEndRow(uil,b);
}

void IDN_QuantizeInit(laSynthNodeQuantize* n, int NoCreate){
    if(!NoCreate){ strSafeSet(&n->Base.Name,"Envelope");
        n->In=laCreateInSocket("IN",0); n->Out=laCreateOutSocket(n, "OUT",0);
    }
    if(!n->OutSamples){ n->OutSamples=memAcquireSimple(sizeof(real)*LA_SYNTH_PLEN); }
    n->Out->Data = n->OutSamples; n->Out->DataType = LA_PROP_FLOAT|LA_PROP_ARRAY; n->Out->ArrLen=LA_SYNTH_PLEN;
    int Enabled[12]={1,0,1,0,1,1,0,1,0,1,0,1};
    memcpy(n->EnabledBits,Enabled,sizeof(Enabled));
}
void IDN_QuantizeDestroy(laSynthNodeQuantize* n){
    laDestroyInSocket(n->In); laDestroyOutSocket(n->Out);
    memFree(n->OutSamples);
    strSafeDestroy(&n->Base.Name);
}
int IDN_QuantizeVisit(laSynthNodeQuantize* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->In)){ laBaseNode*bn=n->In->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
static const real QTABLE[12]={ VAL13-VALHALF*9, VAL13-VALHALF*8, VAL13-VALHALF*7, VAL13-VALHALF*6,
    VAL13-VALHALF*5, VAL13-VALHALF*4, VAL13-VALHALF*3, VAL13-VALHALF*2,
    VAL13-VALHALF*1, VAL13, VAL13+VALHALF*1, VAL13+VALHALF*2 };
static void set_quantize_out_bit(laSynthNodeQuantize* n, int which){
    for(int i=0;i<12;i++){
        if(n->EnabledBits[i]){ n->EnabledBits[i]=1; }
        if(i==which && n->EnabledBits){ n->EnabledBits[i]=3; }
    }
}
int IDN_QuantizeEval(laSynthNodeQuantize* n){ real cv0=QTABLE[0]+5; /*C4*/ LA_GET_SRC_AS_VALUE(cv0, n->In);
    real* cv; INPUTPACKET(cv,n->In); real dists[12];
    for(int i=0;i<LA_SYNTH_PLEN;i++){
        int octave = (int)(cv0-QTABLE[0]); int minkey=0;
        if(cv){ cv0=cv[i]; }
        real use_cv = cv0 - octave;
        for(int j=0;j<12;j++){ dists[j] = fabs(use_cv - QTABLE[j]); }
        for(int j=1;j<12;j++){ if(n->EnabledBits[j] && dists[j] < dists[minkey]){ minkey=j; } }
        set_quantize_out_bit(n,minkey);
        n->OutSamples[i] = QTABLE[minkey]+octave;
    }
    return 1;
}
void IDN_QuantizeCopy(laSynthNodeQuantize* new, laSynthNodeQuantize* old, int DoRematch){
    if(DoRematch){
        LA_IDN_NEW_LINK(In) return;
    }
    LA_IDN_OLD_DUPL(Out);
    memcpy(new->EnabledBits,old->EnabledBits,sizeof(int)*12);
}
void laui_QuantizeNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSynthNodeQuantize*n=This->EndInstance;
    LA_BASE_NODE_HEADER(uil,c,This);

    laUiItem* b;
    
    b=laBeginRow(uil,c,0,0);
    laUiItem* ui=laShowItem(uil,c,This,"enabled_keys");
    ui->Flags|=LA_UI_FLAGS_CYCLE|LA_UI_FLAGS_HIGHLIGHT|LA_UI_FLAGS_TRANSPOSE|LA_UI_FLAGS_ICON; ui->Expand=1;
    laShowNodeSocket(uil,c,This,"in",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laShowNodeSocket(uil,c,This,"out",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laEndRow(uil,b);
}

void IDN_SynthDriverInit(laSynthNodeDriver* n, int NoCreate){
    if(NoCreate){ return; }
    n->Prev=laCreateInSocket("PREV",0); n->Next=laCreateOutSocket(n,"NEXT",0);
    n->InTransport=laCreateInSocket("TRANSPORT",LA_PROP_FLOAT|LA_PROP_ARRAY);
    n->InReset=laCreateInSocket("RESET",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"Sound Player");
}
void IDN_SynthDriverDestroy(laSynthNodeDriver* n){
    laDestroyInSocket(n->InTransport); laDestroyInSocket(n->InReset); strSafeDestroy(&n->Base.Name);
    laDestroyInSocket(n->Prev); laDestroyOutSocket(n->Next);
}
int IDN_SynthDriverVisit(laSynthNodeDriver* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->Prev)){ laBaseNode*bn=n->Prev->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InTransport)){ laBaseNode*bn=n->InTransport->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InReset)){ laBaseNode*bn=n->InReset->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_SynthDriverEval(laSynthNodeDriver* n){
    laSynth*ss=n->Target; if(!ss){ return 0; }
    int trans=n->iTransport; LA_GET_SRC_AS_VALUE(trans,n->InTransport);
    int res=n->iReset; LA_GET_SRC_AS_VALUE(res,n->InReset); int dif=0;
    if(n->AlreadyReset && res==0){ n->AlreadyReset=0; res=0; }
    elif(!n->AlreadyReset && res!=0){ n->AlreadyReset=1; }
    else{ res=0; }

    laSpinLock(&ss->Lock);
    if(ss->Playing!=trans){ dif=1; }
    ss->Playing = trans; if(res){ ss->EvalSamples=0; ss->EvalTime=0; }
    laSpinUnlock(&ss->Lock);
    
    if(dif){ laNotifyInstanceUsers(ss); }
    
    return 1;
}
void IDN_SynthDriverCopy(laSynthNodeDriver* new, laSynthNodeDriver* old, int DoRematch){
    if(DoRematch){ LA_IDN_NEW_LINK(InTransport); LA_IDN_NEW_LINK(InReset); return; }
    new->iTransport = old->iTransport; new->iReset = old->iReset;
    memAssignRef(new,&new->Target,old->Target);
}
void laui_SynthDriverNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil),*cl,*cr,*cll,*clr;
    LA_BASE_NODE_HEADER(uil,c,This);
    laSplitColumn(uil,c,0.6); cl=laLeftColumn(c,0); cr=laRightColumn(c,3);
    //laSplitColumn(uil,cl,0.4); cll=laLeftColumn(cl,3); clr=laRightColumn(cl,0);
    laUiItem* b2, *rui;

    laShowNodeSocket(uil,cr,This,"prev",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laShowNodeSocket(uil,cr,This,"next",0)->Flags|=LA_UI_SOCKET_LABEL_W;

    laUiItem* b=laBeginRow(uil,cl,0,0);
    laShowNodeSocket(uil,cl,This,"in_transport",0); b2=laOnConditionThat(uil,c,laNot(laPropExpression(This,"in_transport.source")));{
        laShowItemFull(uil,cl,This,"transport",0,"text=Transport",0,0)->Expand=1;
    }laElse(uil,b2);{
        laShowLabel(uil,cl,"Transport",0,0)->Expand=1;
    }laEndCondition(uil,b2);
    laShowNodeSocket(uil,cl,This,"in_reset",0); b2=laOnConditionThat(uil,c,laNot(laPropExpression(This,"in_reset.source")));{
        laUiItem* u=laShowItemFull(uil,cl,This,"reset",0,"text=Reset",0,0);u->Expand=1;u->Flags|=LA_UI_FLAGS_MOMENTARY;
    }laElse(uil,b2);{
        laShowLabel(uil,cl,"Reset",0,0)->Expand=1;
    }laEndCondition(uil,b2);
    laEndRow(uil,b);

    laShowItemFull(uil,cl,This,"target",LA_WIDGET_COLLECTION_SELECTOR,0,laui_IdentifierOnly,0);
}

void IDN_SynthTriggerInit(laSynthNodeTrigger* n, int NoCreate){
    if(NoCreate){ return; }
    n->Prev=laCreateInSocket("PREV",0); n->Next=laCreateOutSocket(n,"NEXT",0);
    n->InTrigger=laCreateInSocket("TRIGGER",LA_PROP_FLOAT|LA_PROP_ARRAY);
    strSafeSet(&n->Base.Name,"Sound Trigger"); n->TriggerEdge=1;
}
void IDN_SynthTriggerDestroy(laSynthNodeTrigger* n){
    laDestroyInSocket(n->InTrigger); strSafeDestroy(&n->Base.Name);
    laDestroyInSocket(n->Prev); laDestroyOutSocket(n->Next);
}
int IDN_SynthTriggerVisit(laSynthNodeTrigger* n, laNodeVisitInfo* vi){
    LA_GUARD_THIS_NODE(n,vi);
    if(LA_SRC_AND_PARENT(n->Prev)){ laBaseNode*bn=n->Prev->Source->Parent; LA_VISIT_NODE(bn,vi); }
    if(LA_SRC_AND_PARENT(n->InTrigger)){ laBaseNode*bn=n->InTrigger->Source->Parent; LA_VISIT_NODE(bn,vi); }
    LA_ADD_THIS_NODE(n,vi);
    return LA_DAG_FLAG_PERM;
}
int IDN_SynthTriggerEval(laSynthNodeTrigger* n){
    laSynth*ss=n->Target; if(!ss){ return 0; }
    real trig=0; real* trigger=0; INPUTPACKET(trigger,n->InTrigger); LA_GET_SRC_AS_VALUE(trig,n->InTrigger);
    if(MAIN.Audio->AudioEvalSynth == ss){ return 0; }
    if(trigger){
        for(int i=0;i<LA_SYNTH_PLEN;i++){
            if(trigger[i]>=5){
                if(n->TriggerEdge){ if(!n->Triggered){ n->Triggered=1; laSynthTriggerLater(ss); } }
                else{ laSynthTriggerLater(ss); }
            }else{ n->Triggered=0; }
        }
    }else{
        if(trig>=0.5){
            if(n->TriggerEdge){ if(!n->Triggered){ n->Triggered=1; laSynthTriggerLater(ss); } }
            else{ laSynthTriggerLater(ss); }
        }else{ n->Triggered=0; }
    }
    return 1;
}
void IDN_SynthTriggerCopy(laSynthNodeTrigger* new, laSynthNodeTrigger* old, int DoRematch){
    if(DoRematch){ LA_IDN_NEW_LINK(InTrigger); return; }
    new->TriggerEdge = old->TriggerEdge;
    memAssignRef(new,&new->Target,old->Target);
}
void laui_SynthTriggerNode(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil),*cl,*cr,*cll,*clr;
    LA_BASE_NODE_HEADER(uil,c,This);
    laSplitColumn(uil,c,0.6); cl=laLeftColumn(c,0); cr=laRightColumn(c,3);
    //laSplitColumn(uil,cl,0.4); cll=laLeftColumn(cl,3); clr=laRightColumn(cl,0);
    laUiItem* b2, *rui;

    laShowNodeSocket(uil,cr,This,"prev",0)->Flags|=LA_UI_SOCKET_LABEL_W;
    laShowNodeSocket(uil,cr,This,"next",0)->Flags|=LA_UI_SOCKET_LABEL_W;

    laUiItem* b=laBeginRow(uil,cl,0,0);
    laShowItemFull(uil,cl,This,"trigger_edge",0,0,0,0)->Flags|=LA_UI_FLAGS_ICON;
    laShowNodeSocket(uil,cl,This,"in_trigger",0);
    laShowItemFull(uil,cl,This,"trigger",0,"text=Trigger",0,0)->Flags|=LA_UI_FLAGS_MOMENTARY|LA_UI_FLAGS_HIGHLIGHT;
    laShowSeparator(uil,cl)->Expand=1;
    laEndRow(uil,b);

    laShowItemFull(uil,cl,This,"target",LA_WIDGET_COLLECTION_SELECTOR,0,laui_IdentifierOnly,0);
}

void laRebuildSynthGraphs(int current_only){
    if(MAIN.Audio->CurrentSynth && current_only){
        laSpinLock(&MAIN.Audio->CurrentSynth->Lock);
        laRebuildPageEval(MAIN.Audio->CurrentSynth->Page);
        laSpinUnlock(&MAIN.Audio->CurrentSynth->Lock);
    }else{
        for(laSynth* s=MAIN.Audio->Synths.pFirst;s;s=s->Item.pNext){
            laSpinLock(&s->Lock);
            laRebuildPageEval(s->Page);
            laSpinUnlock(&s->Lock);
        }
    }
}
int laEvalSingleSynth(laSynth* ss){
    laSynth* FirstInst=0; int any=0;
    laSpinLock(&ss->Lock);
    if(ss->Playing){
        MAIN.Audio->AudioEvalSynth=ss;
        laRunPage(ss->Page,1);
        ss->EvalSamples += LA_SYNTH_PLEN;
        ss->EvalTime = (real)ss->EvalSamples/MAIN.Audio->AudioSampleRate;
        any=1;
    }
    FirstInst=ss->PolyphonicInstances.pFirst;
    laSpinUnlock(&ss->Lock);

    laSpinLock(&MAIN.Audio->AudioStatusLock);
    laSynth* pending; while(pending=lstPopPointer(&MAIN.Audio->PolyLaterTrigger)){ laSynthTriggerNew(pending); }
    laSpinUnlock(&MAIN.Audio->AudioStatusLock);
    
    laListHandle to_remove={0}; int count=0;
    for(laSynth* inst=FirstInst;inst;inst=inst->Item.pNext){
        any+=laEvalSingleSynth(inst); count++;
        if(inst->EvalTime > ss->Length || count>ss->MaxPoly){ lstAppendPointer(&to_remove,inst); }
    }

    laSynth* inst; while(inst=lstPopPointer(&to_remove)){
        la_SynthRemovePolyInstance(ss,inst);
    }

    return any;
}
int laEvalSynthGraphs(){
    laSynth* ss; int any=0;
    memset(MAIN.Audio->OutputSamplesL,0,sizeof(real)*LA_SYNTH_PLEN);
    memset(MAIN.Audio->OutputSamplesR,0,sizeof(real)*LA_SYNTH_PLEN);
    for(laAudioChannel* ac=MAIN.Audio->Channels.pFirst;ac;ac=ac->Item.pNext){
        memset(ac->SamplesL,0,sizeof(real)*LA_SYNTH_PLEN);
        memset(ac->SamplesR,0,sizeof(real)*LA_SYNTH_PLEN);
    }

    for(ss=MAIN.Audio->Synths.pFirst;ss;ss=ss->Item.pNext){
        if(laEvalSingleSynth(ss)){ any=1; }
    }

    for(laAudioChannel* ac=MAIN.Audio->Channels.pFirst;ac;ac=ac->Item.pNext){
        real *RSamples = ac->IsMono?ac->SamplesL:ac->SamplesR;
        for(int i=0;i<LA_SYNTH_PLEN;i++){
            MAIN.Audio->OutputSamplesL[i] += ac->SamplesL[i]*(ac->Volume/10);
            MAIN.Audio->OutputSamplesR[i] += RSamples[i]*(ac->Volume/10);
        }
    }
    return any;
}

void laSetAudioCallback(laAudioCallbackF Callback){
    MAIN.Audio->Callback = Callback;
}

void laaudio_DataCallback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount){
    float* out=pOutput; const float *in=pInput; int Paused; int any=0;
    laSpinLock(&MAIN.Audio->AudioStatusLock);
    Paused = MAIN.Audio->Paused;
    laSpinUnlock(&MAIN.Audio->AudioStatusLock);
    
    if(MAIN.Audio->Callback){
        if(MAIN.Audio->Callback(Paused, pInput, pOutput, frameCount)) return;
    }

    if(Paused){ memset(out,0,sizeof(float)*LA_SYNTH_PLEN);
        memset(MAIN.Audio->InputSamplesL,0,sizeof(float)*LA_SYNTH_PLEN);
        memset(MAIN.Audio->InputSamplesR,0,sizeof(float)*LA_SYNTH_PLEN); return;
    }
    
    for(int i=0;i<frameCount;i++){
        if(MAIN.Audio->NextAudioSample>=LA_SYNTH_PLEN){
            MAIN.Audio->NextAudioSample=0;
            if(laEvalSynthGraphs()){ any=1; }
        }
        int s=i*2;
        out[s]=MAIN.Audio->OutputSamplesL[MAIN.Audio->NextAudioSample]/10;
        out[s+1]=MAIN.Audio->OutputSamplesR[MAIN.Audio->NextAudioSample]/10;
        MAIN.Audio->InputSamplesL[MAIN.Audio->NextAudioSample] = in[s] * 10;
        MAIN.Audio->InputSamplesR[MAIN.Audio->NextAudioSample] = in[s+1] * 10;
        MAIN.Audio->NextAudioSample++;
    }
}


void la_SelectAudioDevice(laAudioDevice* ad){
    memAssignRef(MAIN.Audio, &MAIN.Audio->UsingDevice, ad);
    ma_device_stop(&MAIN.Audio->AudioDevice);
    ma_device_uninit(&MAIN.Audio->AudioDevice);
    if(!ad) return;
    int SampleRate=48000;
    ma_device_config config = ma_device_config_init(ma_device_type_duplex);
    config.capture.pDeviceID = ad->MiniAudioID;
    config.capture.format    = ma_format_f32;
    config.capture.channels  = 2;
    config.playback.pDeviceID= ad->MiniAudioID;
    config.playback.format   = ma_format_f32;
    config.playback.channels = 2;
    config.sampleRate        = SampleRate;
    config.dataCallback      = laaudio_DataCallback;
    config.pUserData         = 0;
    if (ma_device_init(&MAIN.Audio->MiniAudioContext, &config, &MAIN.Audio->AudioDevice) != MA_SUCCESS){ return; }
    MAIN.Audio->AudioSampleRate=SampleRate;
    MAIN.Audio->NextAudioSample=LA_SYNTH_PLEN;
    MAIN.Audio->AudioFrameInterval=1.0f/SampleRate;
}
void la_AddAudioDevice(int id, char* Name){
    laAudioDevice* ad=memAcquire(sizeof(laAudioDevice));
    strSafeSet(&ad->Name,Name); ad->MiniAudioID=id;
    lstAppendItem(&MAIN.Audio->AudioDevices,ad);
}
void la_ClearAudioDevices(){
    laAudioDevice* ad; while(ad=lstPopItem(&MAIN.Audio->AudioDevices)){
        strSafeDestroy(&ad->Name); memFree(ad);
    }
}
void laRefreshAudioDevices(){
    if(!MAIN.Audio) return; la_ClearAudioDevices();
    ma_device_info* pPlaybackInfos;
    ma_uint32 playbackCount;
    ma_device_info* pCaptureInfos;
    ma_uint32 captureCount;
    if (ma_context_get_devices(&MAIN.Audio->MiniAudioContext, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) {
        logPrintNew("Can't get audio devices.\n");
    }
    for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) {
        la_AddAudioDevice(iDevice, pPlaybackInfos[iDevice].name);
    }
}

void laInitMiniAudio(){
    MAIN.Audio->MiniAudioBackend=ma_backend_null;

    if (ma_context_init(NULL, 0, NULL, &MAIN.Audio->MiniAudioContext) != MA_SUCCESS) {
        printf("Can't init miniaudio context\n");
    }

    laRefreshAudioDevices();

    laSpinInit(&MAIN.Audio->AudioStatusLock);
    INITPACKET(MAIN.Audio->InputSamplesL);
    INITPACKET(MAIN.Audio->InputSamplesR);
    INITPACKET(MAIN.Audio->OutputSamplesL);
    INITPACKET(MAIN.Audio->OutputSamplesR);

    la_SelectAudioDevice(MAIN.Audio->AudioDevices.pFirst);
}
void laDeinitAudio(){
    memFree(MAIN.Audio->InputSamplesL);
    memFree(MAIN.Audio->InputSamplesR);
    memFree(MAIN.Audio->OutputSamplesR);
    memFree(MAIN.Audio->OutputSamplesL);
    laSpinDestroy(&MAIN.Audio->AudioStatusLock);
    ma_device_stop(&MAIN.Audio->AudioDevice);
    ma_device_uninit(&MAIN.Audio->AudioDevice);
    ma_context_uninit(&MAIN.Audio->MiniAudioContext);
}

void laStartAudio(){
    laSpinLock(&MAIN.Audio->AudioStatusLock);
    MAIN.Audio->Paused = 0;
    laSpinUnlock(&MAIN.Audio->AudioStatusLock);
    ma_device_start(&MAIN.Audio->AudioDevice);
}
void laStopAudio(){
    ma_device_stop(&MAIN.Audio->AudioDevice);
}
void laPauseAudio(){
    laSpinLock(&MAIN.Audio->AudioStatusLock);
    MAIN.Audio->Paused = 1;
    laSpinUnlock(&MAIN.Audio->AudioStatusLock);
}
void laResetAudio(){
    for(laSynth* s=MAIN.Audio->Synths.pFirst;s;s=s->Item.pNext){
        laSpinLock(&s->Lock);
        s->EvalTime = 0; s->EvalSamples = 0; s->Playing = 0;
        laSpinUnlock(&s->Lock);
    }
}

// Operations

int OPINV_RefreshAudioDevices(laOperator* a, laEvent* e){
    laRefreshAudioDevices(); return LA_FINISHED;
}

laSynth* laFindSynth(const char* Name){
    for(laSynth* ss=MAIN.Audio->Synths.pFirst;ss;ss=ss->Item.pNext){
        if(strSame(SSTR(ss->Name),Name)) return ss;
    }
    return 0;
}
laSynth* laNewSynth(char* Name){
    laSynth* ss=memAcquireHyper(sizeof(laSynth));
    ss->Page=memAcquire(sizeof(laRackPage));
    ss->Page->RackType=LA_RACK_TYPE_AUDIO;
    ss->Length=5; ss->MaxPoly=8;
    strSafeSet(&ss->Name,Name);
    lstAppendItem(&MAIN.Audio->Synths,ss);
    memAssignRef(MAIN.Audio,&MAIN.Audio->CurrentSynth,ss);
    laSpinInit(&ss->Lock);
    return ss;
}
void laRemoveSynth(laSynth* ss){ if(!ss) return;
    strSafeDestroy(&ss->Name);
    if(MAIN.Audio->CurrentSynth==ss){
        laSynth* nss=ss->Item.pNext?ss->Item.pNext:ss->Item.pPrev;
        memAssignRef(MAIN.Audio,&MAIN.Audio->CurrentSynth,nss);
    }laNotifyInstanceUsers(ss);
    while(ss->Page->Racks.pFirst){ laDestroyRack(ss->Page->Racks.pFirst); } memLeave(ss->Page); //ss->Page=0;
    lstRemoveItem(&MAIN.Audio->Synths,ss);
    laSpinDestroy(&ss->Lock);
    memLeave(ss);
}

int OPINV_ShedNewSynth(laOperator* a, laEvent* e){
    laNewSynth("New Synth");
    laNotifyInstanceUsers(MAIN.Audio); laRecordAndPush(0,"la.audio","New synth", 0);
    return LA_FINISHED;
}
int OPCHK_IslaSynth(laPropPack *This, laStringSplitor *ss){
    if (This && This->EndInstance && la_EnsureSubTarget(This->LastPs->p,0) == LA_PC_SYNTH) return 1;
    return 0;
}
int OPINV_ShedRemoveSynth(laOperator* a, laEvent* e){
    laSynth* ss=a->This?a->This->EndInstance:0; if(!ss)return LA_CANCELED;
    if(strSame(strGetArgumentString(a->ExtraInstructionsP,"confirm"),"true")){
        laRemoveSynth(ss);
        laNotifyInstanceUsers(MAIN.Audio); laRecordAndPush(0,"la.audio","Remove synthesizer", 0);
        return LA_FINISHED;
    }
    laEnableOperatorPanel(a,a->This,e->x,e->y,200,200,0,0,0,0,0,0,0,0,e);
    return LA_RUNNING;
}
void laui_RemoveSynth(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil);
    laShowItemFull(uil,c,This,"remove_synth",0,"confirm=true;text=Confirm",0,0);
}

int OPINV_SynthPlay(laOperator* a, laEvent* e){
    laSynth* ss=a->This?a->This->EndInstance:0; if(!ss)return LA_CANCELED;

    char* str=strGetArgumentString(a->ExtraInstructionsP, "mode");
    int play=0; if(str && strSame(str,"PLAY")) play=1;

    laRebuildPageEval(ss->Page);

    laSpinLock(&ss->Lock);
    ss->Playing=play; if(!play){ ss->EvalSamples=0; ss->EvalTime=0; }
    laSpinUnlock(&ss->Lock);
    
    if(play){ laStartAudio(); } laNotifyInstanceUsers(ss);
    return LA_FINISHED;
}
int OPINV_SynthTriggerNew(laOperator* a, laEvent* e){
    laSynth* ss=a->This?a->This->EndInstance:0; if(!ss)return LA_CANCELED;
    laSynthTriggerNew(ss);
    laStartAudio();
    return LA_FINISHED;
}

void la_SynthAddPolyInstance(laSynth* s){
    int count=0;
    laSpinLock(&s->Lock); count = s->PolyCount; laSpinUnlock(&s->Lock);
    if(s->PolyCount>s->MaxPoly){ return; }

    laSpinLock(&s->Lock);

    laSynth* ns=memAcquire(sizeof(laSynth)); ns->Length=s->Length; ns->Playing=1;
    ns->Page = laDuplicateRackPage(0,s->Page);
    laRebuildPageEval(ns->Page);
    laSpinInit(&ns->Lock);

    //laSpinLock(&s->Lock);
    lstPushItem(&s->PolyphonicInstances,ns);
    s->PolyCount++;
    laSpinUnlock(&s->Lock);
}
void la_SynthRemovePolyInstance(laSynth* s, laSynth* inst){
    laSpinLock(&inst->Lock);
    while(inst->Page->Racks.pFirst){ laDestroyRack(inst->Page->Racks.pFirst); } memFree(inst->Page); //ss->Page=0;
    laSpinUnlock(&inst->Lock);
    laSpinDestroy(&inst->Lock);

    laSpinLock(&s->Lock);
    lstRemoveItem(&s->PolyphonicInstances,inst);
    s->PolyCount--;
    laSpinUnlock(&s->Lock);
    memFree(inst);
}
void laSynthTriggerNew(laSynth* s){
    if(!s || !s->Poly){ return; } la_SynthAddPolyInstance(s);
}
void laSynthTriggerLater(laSynth* s){
    if(!s || !s->Poly){ return; } 
    laSpinLock(&MAIN.Audio->AudioStatusLock);
    lstAppendPointer(&MAIN.Audio->PolyLaterTrigger,s);
    laSpinUnlock(&MAIN.Audio->AudioStatusLock);
}

laAudioChannel* laNewAudioChannel(char* Name){
    laAudioChannel* ac=memAcquireHyper(sizeof(laAudioChannel)); lstAppendItem(&MAIN.Audio->Channels,ac);
    strSafeSet(&ac->Name,Name); 
    ac->Volume = 10.0f;
    return ac;
}
void laRemoveAudioChannel(laAudioChannel* ac){
    lstRemoveItem(&MAIN.Audio->Channels,ac); strSafeDestroy(&ac->Name);
    memLeave(ac);
}
laAudioChannel* laGetAudioChannel(char* Name){
    for(laAudioChannel* ac=MAIN.Audio->Channels.pFirst;ac;ac=ac->Item.pNext){
        if(strSame(SSTR(ac->Name),Name)) return ac;
    }
    return 0;
}

int OPCHK_IslaAudioChannel(laPropPack *This, laStringSplitor *ss){
    if (This && This->EndInstance && la_EnsureSubTarget(This->LastPs->p,0) == LA_PC_CHANNEL) return 1;
    return 0;
}
int OPINV_ShedNewAudioChannel(laOperator* a, laEvent* e){
    laNewAudioChannel("Output");
    laNotifyInstanceUsers(MAIN.Audio); laRecordAndPush(0,"la.audio","New channel", 0);
    return LA_FINISHED;
}
int OPINV_ShedRemoveAudioChannel(laOperator* a, laEvent* e){
    laAudioChannel*ac=a->This?a->This->EndInstance:0; if(!ac)return LA_CANCELED;
    if(strSame(strGetArgumentString(a->ExtraInstructionsP,"confirm"),"true")){
        laRemoveAudioChannel(ac); laNotifyInstanceUsers(MAIN.Audio); laRecordAndPush(0,"la.audio","Remove audio channel", 0);
        return LA_FINISHED;
    }
    laEnableOperatorPanel(a,a->This,e->x,e->y,200,200,0,0,0,0,0,0,0,0,e);
    return LA_RUNNING;
}
void laui_RemoveAudioChannel(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil);
    laShowItemFull(uil,c,This,"remove",0,"confirm=true;text=Confirm",0,0);
}


void lauidetached_Synthersizers(laPanel* p){
    la_MakeDetachedProp(p, "la.detached_view_switch", "detached");
    la_MakeDetachedProp(p, "la.audio.current_synth", "page");
}
void laui_Synthersizers(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil),*cl, *cr,*crl,*crr;
    laSplitColumn(uil,c,0.4); cl=laLeftColumn(c,1); cr=laRightColumn(c,0);
    laSplitColumn(uil,cr,0.6); crl=laLeftColumn(cr,0); crr=laRightColumn(cr,2);

    laShowItemFull(uil,cl,Extra,"detached",0,0,0,0)->Flags|=LA_UI_FLAGS_HIGHLIGHT|LA_UI_FLAGS_ICON;

#define ADD_PAGE \
    laUiItem* b=laBeginRow(uil,crl,0,0); \
    laShowItemFull(uil,crl,&rb->PP,"",LA_WIDGET_COLLECTION_SELECTOR,0,laui_IdentifierOnly,0) \
        ->Flags|=LA_UI_COLLECTION_SIMPLE_SELECTOR; \
    laUiItem* b3=laOnConditionThat(uil,cr,laPropExpression(&rb->PP,""));{ \
        laShowItem(uil,crl,&rb->PP,"name"); \
        laShowItem(uil,crl,0,"LA_new_synth")->Flags|=LA_UI_FLAGS_ICON; \
        laShowSeparator(uil,crl); \
        laShowItem(uil,crl,&rb->PP,"remove_synth")->Flags|=LA_UI_FLAGS_ICON; \
        laShowSeparator(uil,crl)->Expand=1; \
        laUiItem* b4=laOnConditionThat(uil,cr,laPropExpression(&rb->PP,"poly"));{ \
            laShowItem(uil,crl,&rb->PP,"max_poly"); \
            laShowItem(uil,crl,&rb->PP,"length"); \
            laShowItemFull(uil,crl,&rb->PP,"trigger",0,"icon=▶;",0,0)->Flags|=LA_UI_FLAGS_ICON; \
        }laEndCondition(uil,b4); \
        laUiItem* poly=laShowItem(uil,crl,&rb->PP,"poly");poly->Flags|=LA_UI_FLAGS_EXPAND; \
    }laElse(uil,b3);{ \
        laShowItem(uil,crl,0,"LA_new_synth"); \
    }laEndCondition(uil,b3); \
    laEndRow(uil,b); \
    b3=laOnConditionThat(uil,cr,laPropExpression(&rb->PP,""));{ \
        laUiItem* b4=laOnConditionThat(uil,crr,laPropExpression(&rb->PP,"playing"));{ \
            laShowItemFull(uil,crr,&rb->PP,"play",0,"text=❚❚;",0,0) \
                ->Flags|=LA_UI_FLAGS_EXIT_WHEN_TRIGGERED|LA_TEXT_ALIGN_CENTER; \
        }laElse(uil,b4);{ \
            laShowItemFull(uil,crr,&rb->PP,"play",0,"icon=▶;mode=PLAY;",0,0) \
                ->Flags|=LA_UI_FLAGS_ICON|LA_UI_FLAGS_EXIT_WHEN_TRIGGERED; \
        }laEndCondition(uil,b4); \
        laShowItemFull(uil,c,&rb->PP,"page",LA_WIDGET_COLLECTION_SINGLE,0,laui_RackPage,0)->Flags|=LA_UI_FLAGS_NO_DECAL; \
    }laEndCondition(uil,b3); \

    laUiItem* b1=laOnConditionThat(uil,cr,laPropExpression(Extra,"detached"));{
        laUiItem* rb=laShowInvisibleItem(uil,cr,Extra,"page");
        ADD_PAGE
    }laElse(uil,b1);{
        laUiItem* rb=laShowInvisibleItem(uil,cr,0,"la.audio.current_synth");
        ADD_PAGE
    }laEndCondition(uil,b1);

#undef ADD_PAGE
}
void laui_AudioChannel(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil); laSplitColumn(uil,c,0.3); laColumn* c1=laLeftColumn(c,1),*c2=laRightColumn(c,0); laUiItem* b;
    
    laShowHeightAdjuster(uil,c1,This,"__move",0);

    b=laBeginRow(uil,c2,0,0);
    laShowItem(uil,c2,This,"name")->Expand=1;
    laShowItem(uil,c2,This,"remove")->Flags|=LA_UI_FLAGS_ICON;
    laEndRow(uil,b);
    laShowItem(uil,c2,This,"volume");

    laShowSeparator(uil,c);
}
void laui_AudioChannels(laUiList *uil, laPropPack *This, laPropPack *Extra, laColumn *UNUSED, int context){
    laColumn* c=laFirstColumn(uil);  laUiItem* b;

    b=laBeginRow(uil,c,0,0);
    laShowItem(uil,c,0,"LA_new_channel");
    laEndRow(uil,b);
    // if horizontal look:
    // laUiItem* g=laMakeGroup(uil,c,"Racks",0);{ g->Flags|=/*LA_UI_FLAGS_NO_GAP|LA_UI_FLAGS_NO_DECAL|*/LA_UI_FLAGS_NODE_CONTAINER;
    //     laUiList* gu=g->Page; laColumn* gc=laFirstColumn(gu); gu->HeightCoeff=-1; g->State=LA_UI_ACTIVE;
    //     laShowItemFull(gu,gc,0,"la.audio.channels",0,0,laui_AudioChannel,0)->Expand=5;
    // }
    laShowItemFull(uil,c,0,"la.audio.channels",0,0,laui_AudioChannel,0);
}

void* laget_FirstAudioDevice(void* unused1,void* unused2){
    return MAIN.Audio->AudioDevices.pFirst;
}
void* laget_FirstSynth(void* unused1,void* unused2){
    return MAIN.Audio->Synths.pFirst;
}
void* laget_FirstAudioChannel(void* unused1, void* unused2){
    return MAIN.Audio->Channels.pFirst;
}
void lapost_Synth(laSynth* ss){
    laSpinInit(&ss->Lock);
    laRebuildPageEval(ss->Page);
}
int laget_SynthPlaying(laSynth* ss){
    int play=0;
    laSpinLock(&ss->Lock); play=ss->Playing; laSpinUnlock(&ss->Lock);
    return play;
}
void laset_CurrentSynth(laAudio* a,laSynth* s){
    memAssignRef(a,&a->CurrentSynth,s);
}
void laset_CurrentAudioDevice(laAudio* a,laAudioDevice* ad){
    la_SelectAudioDevice(ad);
}
void laset_OutputSendChannel(laSynthNodeOutput* n,laAudioChannel* ac){
    if(ac){ strSafeSet(&n->SendName, SSTR(ac->Name)); } else { strSafeSet(&n->SendName,""); }
    laAudioChannel* outchannel = laGetAudioChannel(SSTR(n->SendName));
    memAssignRef(n,&n->Send,outchannel);
}
void laset_OutputSendName(laSynthNodeOutput* n,char* name){
    strSafeSet(&n->SendName,name);
    laAudioChannel* outchannel = laGetAudioChannel(name);
    memAssignRef(n,&n->Send,outchannel);
}
void laset_QuantizeEnabledKeys(laSynthNodeQuantize* n, int index, int val_UNUSED){
    if(n->EnabledBits[index] & 0x1){ n->EnabledBits[index]=0; }
    else{ n->EnabledBits[index]=1; }
}
void laset_AudioChannelMove(laAudioChannel* ac, int move){
    if(move<0 && ac->Item.pPrev){ lstMoveUp(&MAIN.Audio->Channels, ac); laNotifyUsers("la.audio"); }
    elif(move>0 && ac->Item.pNext){ lstMoveDown(&MAIN.Audio->Channels, ac); laNotifyUsers("la.audio"); }
}
void laset_SynthTriggerTrigger(laSynthNodeTrigger* n, int trig){
    if(trig){ laSynthTriggerNew(n->Target); } n->iTrigger=trig;
}

void laset_MiniAudioBackend(void* unused, int backend){
    laStopAudio();
    ma_device_uninit(&MAIN.Audio->AudioDevice);
    ma_context_uninit(&MAIN.Audio->MiniAudioContext);

    MAIN.Audio->MiniAudioBackend = backend;
    ma_backend _backends[1]; _backends[0] = MAIN.Audio->MiniAudioBackend; ma_backend* backends=_backends;
    int numback=1;
    if(backend==ma_backend_null){ numback=0; backends=0; }
    if (ma_context_init(backends, numback, NULL, &MAIN.Audio->MiniAudioContext) != MA_SUCCESS) {
        printf("Can't init miniaudio context\n"); MAIN.Audio->MiniAudioBackend=ma_backend_null;
    }

    laRefreshAudioDevices();
    la_SelectAudioDevice(MAIN.Audio->AudioDevices.pFirst);
}

void la_AudioPreFrame(){
    if(MAIN.GraphNeedsRebuild){ laRebuildSynthGraphs(1); }
}

void laInitAudio(){
    laPropContainer* pc; laProp* p; laSubProp* sp;

    laInitMiniAudio();

    laRegisterUiTemplate("LAUI_synthesizers","Synthesizers",laui_Synthersizers,lauidetached_Synthersizers,0,"Audio",0,0,0);
    laRegisterUiTemplate("LAUI_audio_channels","Mixer",laui_AudioChannels,0,0,0,0,0,0);

    laCreateOperatorType("LA_new_synth", "New Synthesizer", "Add a synthesizer",0,0,0,OPINV_ShedNewSynth,0,'+',0);
    laCreateOperatorType("LA_remove_synth", "Remove Synthesizer", "Remove a synthesizer",OPCHK_IslaSynth,0,0,OPINV_ShedRemoveSynth,OPMOD_FinishOnData,L'🗴',0)
        ->UiDefine=laui_RemoveSynth;
    laCreateOperatorType("LA_synth_play", "Play Synthesizer", "Play a synthesizer",OPCHK_IslaSynth,0,0,OPINV_SynthPlay,0,0,0);
    laCreateOperatorType("LA_synth_trigger_new", "Trigger New", "Trigger a new polyphonic note",OPCHK_IslaSynth,0,0,OPINV_SynthTriggerNew,0,0,0);
    laCreateOperatorType("LA_refresh_audio_devices", "Refresh Audio Devices", "Enumerate audio devices for selection",0,0,0,OPINV_RefreshAudioDevices,0,U'🗘',0);

    laCreateOperatorType("LA_new_channel", "New Channel", "Add an audio channel",0,0,0,OPINV_ShedNewAudioChannel,0,'+',0);
    laCreateOperatorType("LA_remove_channel", "Remove Channel", "Remove an audio channel",OPCHK_IslaAudioChannel,0,0,OPINV_ShedRemoveAudioChannel,OPMOD_FinishOnData,L'🗴',0)
        ->UiDefine=laui_RemoveAudioChannel;

    pc = laAddPropertyContainer("la_audio_device","LaGUI Audio Device","LaGUI enumerated audio device",0,0,sizeof(laAudioDevice),0,0,1);{
        laAddStringProperty(pc,"name","Name","Name of the audio device",0,0,0,0,1,offsetof(laAudioDevice,Name),0,0,0,0,LA_AS_IDENTIFIER);
    }

    pc = laAddPropertyContainer("la_synth", "LaGUI Synthesizer", "LaGUI synthesizer", 0,0,sizeof(laSynth),lapost_Synth,0,2);{
        LA_PC_SYNTH=pc;
        laAddStringProperty(pc,"name","Name","Name of the synthesizer",0,0,0,0,1,offsetof(laSynth,Name),0,0,0,0,LA_AS_IDENTIFIER);
        laAddSubGroup(pc, "page", "Page", "Rack page","la_rack_page",0,0,0,offsetof(laSynth,Page),0,0,0,0,0,0,0,LA_UDF_SINGLE|LA_HIDE_IN_SAVE);
        p=laAddEnumProperty(pc,"playing","Playing","Synth is playing",0,0,0,0,0,-1,laget_SynthPlaying,0,0,0,0,0,0,0,0,LA_READ_ONLY);
        laAddEnumItemAs(p,"IDLE","Idle","Synth is not playing",0,0);
        laAddEnumItemAs(p,"PLAYING","Playing","Synth is playing",1,0);
        laAddFloatProperty(pc,"length","Length","Length of this sound",0,0,"s",10,0,0,5,0,offsetof(laSynth,Length),0,0,0,0,0,0,0,0,0,0,0);
        p=laAddEnumProperty(pc,"poly","Polyphonic","Whether this synth supports polyphonic triggering",0,0,0,0,0,offsetof(laSynth,Poly),0,0,0,0,0,0,0,0,0,0);
        p->ElementBytes=2;
        laAddEnumItemAs(p,"MONO","Mono","Synth is monophonic",0,0);
        laAddEnumItemAs(p,"POLY","Poly","Synth is polyphonic",1,0);
        laAddIntProperty(pc,"max_poly","Max Poly","Max polyphonic sound count",0,0,0,16,0,0,0,0,offsetof(laSynth,MaxPoly),0,0,0,0,0,0,0,0,0,0,0)->ElementBytes=2;
        laAddOperatorProperty(pc,"remove_synth","Remove Synth", "Remove synth", "LA_remove_synth", L'🗴', 0);
        laAddOperatorProperty(pc,"play","Play Synth", "Play synth", "LA_synth_play", 0, 0);
        laAddOperatorProperty(pc,"trigger","Trigger", "Trigger a new polyphonic node", "LA_synth_trigger_new", 0, 0);
    }

    pc = laAddPropertyContainer("la_audio_channel", "LaGUI Audio Channel", "LaGUI Audio Channel", 0,0,sizeof(laAudioChannel),0,0,2);{
        LA_PC_CHANNEL=pc;
        laAddStringProperty(pc,"name","Name","Name of the channel",0,0,0,0,1,offsetof(laAudioChannel,Name),0,0,0,0,LA_AS_IDENTIFIER);
        laAddFloatProperty(pc,"volume","Volume","Volume of this channel",0,0,0,15,0,0.05,0,0,offsetof(laAudioChannel,Volume),0,0,0,0,0,0,0,0,0,0,0);
        laAddOperatorProperty(pc,"remove","Remove Channel", "Remove this channel", "LA_remove_channel", L'🗴', 0);
        laAddIntProperty(pc,"__move","Move Slider","Move Slider",LA_WIDGET_HEIGHT_ADJUSTER,0,0,0,0,0,0,0,0,0,laset_AudioChannelMove,0,0,0,0,0,0,0,0,LA_UDF_IGNORE);
    }

    pc=laAddPropertyContainer("la_node_synth_input", "Synth Input Node", "Synthesizer time and trigger input",0,laui_InputNode,sizeof(laSynthNodeInput),lapost_Node,0,1);
    LA_PC_IDN_INPUT=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"out_time", "Out Time","Time output","la_out_socket",0,0,0,offsetof(laSynthNodeInput,OutTime),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out_trigger", "Out Trigger","Trigger output","la_out_socket",0,0,0,offsetof(laSynthNodeInput,OutTrigger),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out_l", "Out Left","Capture left","la_out_socket",0,0,0,offsetof(laSynthNodeInput,OutL),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out_r", "Out Right","Capture right","la_out_socket",0,0,0,offsetof(laSynthNodeInput,OutR),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    
    pc=laAddPropertyContainer("la_node_synth_pulse", "Synth Pulse Node", "Pulse generate node for synth",0,laui_PulseNode,sizeof(laSynthNodePulse),lapost_Node,0,1);
    LA_PC_IDN_PULSE=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"out", "Out","Pulse output","la_out_socket",0,0,0,offsetof(laSynthNodePulse,Out),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_trigger", "In Trigger","Trigger input","la_in_socket",0,0,0,offsetof(laSynthNodePulse,InTrigger),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_width", "In Width","Width input","la_in_socket",0,0,0,offsetof(laSynthNodePulse,InWidth),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_gate", "In Gate","Gate input","la_in_socket",0,0,0,offsetof(laSynthNodePulse,InGate),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddFloatProperty(pc,"influence","Influence","Influence of the width input",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodePulse,rInfluence),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"width","Width","Width of the pulse",0,0,0,10,0,0.1,0,0,offsetof(laSynthNodePulse,rWidth),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"gate","Gate","Gate of the trigger",0,0,0,10,-10,0.1,0,0,offsetof(laSynthNodePulse,rGate),0,0,0,0,0,0,0,0,0,0,0);
    p=laAddEnumProperty(pc,"trigger","Trigger","Trigger the envelope",LA_WIDGET_ENUM_CYCLE,0,0,0,0,offsetof(laSynthNodePulse,iTrigger),0,0,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"IDLE","Idle","Trigger idle",0,0);
    laAddEnumItemAs(p,"TRIG","Trigger","Trigger active",1,0);

    pc=laAddPropertyContainer("la_node_synth_fm", "FM OSC Node", "Osilliator node with frequency modulation",0,laui_FMNode,sizeof(laSynthNodeFM),lapost_Node,0,1);
    LA_PC_IDN_FM=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"in_frequency", "In Frequency","Input frequency","la_in_socket",0,0,0,offsetof(laSynthNodeFM,InFrequency),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out", "Out","Output","la_out_socket",0,0,0,offsetof(laSynthNodeFM,Out),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddFloatProperty(pc,"frequency","Frequency","Frequency of the oscilliator",0,0,0,10,0,0.1,0,0,offsetof(laSynthNodeFM,Frequency),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"influence","Influence","Influence of the molulation input",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodeFM,rInfluence),0,0,0,0,0,0,0,0,0,0,0);
    p=laAddEnumProperty(pc,"slow","Slow","Low frequency oscilliator",LA_WIDGET_ENUM_HIGHLIGHT,0,0,0,0,offsetof(laSynthNodeFM,Slow),0,0,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"NONE","None","Regular frequency range",0,0);
    laAddEnumItemAs(p,"SLOW","Slow","Slow frequency range",1,0);

    pc=laAddPropertyContainer("la_node_synth_vca", "VCA Node", "Voltage controlled amplifier",0,laui_VCANode,sizeof(laSynthNodeVCA),lapost_Node,0,1);
    LA_PC_IDN_VCA=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"in_amp", "In Amptitude","Input amptitude","la_in_socket",0,0,0,offsetof(laSynthNodeVCA,InAmp),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in", "Input","Input","la_in_socket",0,0,0,offsetof(laSynthNodeVCA,In),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out", "Out","Output","la_out_socket",0,0,0,offsetof(laSynthNodeVCA,Out),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddFloatProperty(pc,"amp","Amptitude","Amptitude of the output signal",0,0,0,10,0,0.1,0,0,offsetof(laSynthNodeVCA,Amp),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"influence","Influence","Influence of the modulating signal",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodeVCA,rInfluence),0,0,0,0,0,0,0,0,0,0,0);

    pc=laAddPropertyContainer("la_node_synth_noise", "Noise Node", "Noise node",0,laui_NoiseNode,sizeof(laSynthNodeNoise),lapost_Node,0,1);
    LA_PC_IDN_NOISE=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"out_white", "White","White noise output","la_out_socket",0,0,0,offsetof(laSynthNodeNoise,OutWhite),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out_pink", "Pink","Pinknoise output","la_out_socket",0,0,0,offsetof(laSynthNodeNoise,OutPink),0,0,0,0,0,0,0,LA_UDF_SINGLE);

    pc=laAddPropertyContainer("la_node_synth_scope", "Scope Node", "Scope for synthesizer",0,laui_ScopeNode,sizeof(laSynthNodeScope),lapost_Node,0,1);
    LA_PC_IDN_SCOPE=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"scope", "Scope","Synth scope","la_node_synth_scope",0,LA_WIDGET_SCOPE,0,-1,0,laget_InstanceSelf,0,0,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);
    laAddSubGroup(pc,"in1", "In 1","Input Channel 1","la_in_socket",0,0,0,offsetof(laSynthNodeScope,In1),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in2", "In 2","Input Channel 2","la_in_socket",0,0,0,offsetof(laSynthNodeScope,In2),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    p=laAddEnumProperty(pc,"time","Time","Time factor of the scope",0,0,0,5,0,offsetof(laSynthNodeScope,Time),0,0,0,0,0,0,0,0,0,0);
#define _STR(a) #a
#define ADD_TIME_FACTOR(a) laAddEnumItemAs(p,"FAC"_STR(a),_STR(a),"^"_STR(a)" time",a,0);
    ADD_TIME_FACTOR(1) ADD_TIME_FACTOR(2) ADD_TIME_FACTOR(3) ADD_TIME_FACTOR(4) ADD_TIME_FACTOR(5)
    ADD_TIME_FACTOR(6) ADD_TIME_FACTOR(7) ADD_TIME_FACTOR(8) ADD_TIME_FACTOR(9) ADD_TIME_FACTOR(10)
#undef ADD_TIME_FACTOR
    p=laAddEnumProperty(pc,"gain1","Gain 1","Channel 1 Gain",0,0,0,5,0,offsetof(laSynthNodeScope,Gain1),0,0,0,0,0,0,0,0,0,0);
#define ADD_GAIN(a) laAddEnumItemAs(p,"GAIN"_STR(a),_STR(a),"^"_STR(a)" gain",a,0);
#define ADD_GAIN_S(a,s) laAddEnumItemAs(p,"GAIN"_STR(a),s,"^"s" gain",a,0);
    ADD_GAIN_S(-1,"¼") ADD_GAIN_S(0,"½") ADD_GAIN(1) ADD_GAIN(2) ADD_GAIN(3) ADD_GAIN(4) ADD_GAIN(5) ADD_GAIN(6)
    p=laAddEnumProperty(pc,"gain2","Gain 2","Channel 2 Gain",0,0,0,5,0,offsetof(laSynthNodeScope,Gain2),0,0,0,0,0,0,0,0,0,0);
    ADD_GAIN_S(-1,"¼") ADD_GAIN_S(0,"½") ADD_GAIN(1) ADD_GAIN(2) ADD_GAIN(3) ADD_GAIN(4) ADD_GAIN(5) ADD_GAIN(6)
#undef ADD_GAIN
#undef ADD_GAIN_S
    laAddFloatProperty(pc,"offset1","Offset 1","Channel 1 offset",0,0,0,10,-10,0.1,0,0,offsetof(laSynthNodeScope,Offset1),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"offset2","Offset 2","Channel 2 offset",0,0,0,10,-10,0.1,0,0,offsetof(laSynthNodeScope,Offset2),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"bright1","Brightness 1","Channel 1 brightness",0,0,0,1,0,0.1,0,0,offsetof(laSynthNodeScope,Brightness1),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"bright2","Brightness 2","Channel 2 brightness",0,0,0,1,0,0.1,0,0,offsetof(laSynthNodeScope,Brightness2),0,0,0,0,0,0,0,0,0,0,0);

    pc=laAddPropertyContainer("la_node_synth_output", "Output Node", "Sound output to system",0,laui_OutputNode,sizeof(laSynthNodeOutput),lapost_Node,0,1);
    LA_PC_IDN_OUTPUT=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"in_l", "Input Left","Input sound left channel","la_in_socket",0,0,0,offsetof(laSynthNodeOutput,InL),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_r", "Input Right","Input sound right channel","la_in_socket",0,0,0,offsetof(laSynthNodeOutput,InR),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddStringProperty(pc,"send_channel_name","Channel Name","Channel name of this send target",0,0,0,0,1,offsetof(laSynthNodeOutput,SendName),0,0,laset_OutputSendName,0,0);
    laAddSubGroup(pc,"send_channel_selector","Send","Send to channel","la_audio_channel",0,0,0,-1,laget_FirstAudioChannel,0,laget_ListNext,laset_OutputSendChannel,0,0,0,LA_UDF_REFER|LA_UDF_IGNORE);

    pc=laAddPropertyContainer("la_node_synth_envelope", "Envelope Node", "Sound envelope",0,laui_EnvelopeNode,sizeof(laSynthNodeEnvelope),lapost_Node,0,1);
    LA_PC_IDN_ENVELOPE=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"in_gate", "Gate","Gate input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Gate),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_attack", "Attack","Attack input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Attack),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_delay", "Delay","Delay input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Delay),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_sustain", "Sustain","Sustain input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Sustain),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_release", "Release","Release input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Release),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_trigger", "Trigger","Trigger input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Trigger),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_restart", "Restart","Restart input","la_in_socket",0,0,0,offsetof(laSynthNodeEnvelope,Restart),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out", "Output","Envelope output","la_out_socket",0,0,0,offsetof(laSynthNodeEnvelope,Out),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddFloatProperty(pc,"gate","Gate","Gate for the trigger",0,0,0,10,-10,0.01,0,0,offsetof(laSynthNodeEnvelope,rGate),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"attack","Attack","Attack value",0,0,0,10,0,0.01,0,0,offsetof(laSynthNodeEnvelope,rAttack),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"delay","Delay","Delay value",0,0,0,10,0,0.01,0,0,offsetof(laSynthNodeEnvelope,rDelay),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"sustain","Sustain","Sustain value",0,0,0,10,0,0.01,0,0,offsetof(laSynthNodeEnvelope,rSustain),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"release","Release","Release value",0,0,0,10,0,0.01,0,0,offsetof(laSynthNodeEnvelope,rRelease),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"iattack","Attack Influence","Attack modulation influence value",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodeEnvelope,iAttack),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"idelay","Delay Influence","Delay modulation influence value",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodeEnvelope,iDelay),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"isustain","Sustain Influence","Sustain modulation influence value",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodeEnvelope,iSustain),0,0,0,0,0,0,0,0,0,0,0);
    laAddFloatProperty(pc,"irelease","Release Influence","Release modulation influence value",LA_WIDGET_KNOB,0,0,1,-1,0.01,0,0,offsetof(laSynthNodeEnvelope,iRelease),0,0,0,0,0,0,0,0,0,0,0);
    p=laAddEnumProperty(pc,"trigger","Trigger","Trigger the envelope",LA_WIDGET_ENUM_CYCLE,0,0,0,0,offsetof(laSynthNodeEnvelope,bTrigger),0,0,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"IDLE","Idle","Trigger idle",0,0);
    laAddEnumItemAs(p,"TRIG","Trigger","Trigger active",1,0);

    pc=laAddPropertyContainer("la_node_synth_driver", "Synth Driver Node", "Control playing status of the synth",0,laui_SynthDriverNode,sizeof(laSynthNodeDriver),lapost_Node,0,1);
    LA_PC_IDN_SYNTH_DRIVER=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"prev", "Previous","Previous node","la_in_socket",0,0,0,offsetof(laSynthNodeDriver,Prev),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"next", "Next","Next node","la_out_socket",0,0,0,offsetof(laSynthNodeDriver,Next),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_transport", "In Transport","Transport input","la_in_socket",0,0,0,offsetof(laSynthNodeDriver,InTransport),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_reset", "In Reset","Reset input (trigger on rising edge)","la_in_socket",0,0,0,offsetof(laSynthNodeDriver,InReset),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    p=laAddEnumProperty(pc,"transport","Transport","Play or stop the synth playing",LA_WIDGET_ENUM_HIGHLIGHT,0,0,0,0,offsetof(laSynthNodeDriver,iTransport),0,0,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"STOPPED","Stopped","Synth is stopped",0,0);
    laAddEnumItemAs(p,"PLAYING","Playing","Synth is playing",1,0);
    p=laAddEnumProperty(pc,"reset","Reset","Reset Synth",LA_WIDGET_ENUM_HIGHLIGHT,0,0,0,0,offsetof(laSynthNodeDriver,iReset),0,0,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"IDLE","Idle","Trigger idle",0,0);
    laAddEnumItemAs(p,"TRIG","Trigger","Trigger active",1,0);
    laAddSubGroup(pc,"target","Target","Target synth to control","la_synth",0,0,0,offsetof(laSynthNodeDriver,Target),laget_FirstSynth,0,laget_ListNext,0,0,0,0,LA_UDF_REFER);
    
    pc=laAddPropertyContainer("la_node_synth_trigger", "Synth Trigger Node", "Trigger a new polyphonic note",0,laui_SynthTriggerNode,sizeof(laSynthNodeTrigger),lapost_Node,0,1);
    LA_PC_IDN_SYNTH_TRIGGER=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"prev", "Previous","Previous node","la_in_socket",0,0,0,offsetof(laSynthNodeTrigger,Prev),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"next", "Next","Next node","la_out_socket",0,0,0,offsetof(laSynthNodeTrigger,Next),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"in_trigger", "In Trigger","Trigger input","la_in_socket",0,0,0,offsetof(laSynthNodeTrigger,InTrigger),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    p=laAddEnumProperty(pc,"trigger","Trigger","Trigger new note",LA_WIDGET_ENUM_HIGHLIGHT,0,0,0,0,offsetof(laSynthNodeTrigger,iTrigger),0,laset_SynthTriggerTrigger,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"IDLE","Idle","Trigger idle",0,0);
    laAddEnumItemAs(p,"TRIG","Trigger","Trigger active",1,0);
    p=laAddEnumProperty(pc,"trigger_edge","Edge","Trigger on rising edge",LA_WIDGET_ENUM_HIGHLIGHT,0,0,0,0,offsetof(laSynthNodeTrigger,TriggerEdge),0,0,0,0,0,0,0,0,0,0);
    laAddEnumItemAs(p,"LEVEL","Level","Trigger on high level",0,'-');
    laAddEnumItemAs(p,"RISING_EDGE","Rising Edge","Trigger on rising edge",1,U'⮥');
    laAddSubGroup(pc,"target","Target","Target synth to trigger","la_synth",0,0,0,offsetof(laSynthNodeTrigger,Target),laget_FirstSynth,0,laget_ListNext,0,0,0,0,LA_UDF_REFER);

    pc=laAddPropertyContainer("la_node_synth_quantize", "Quantize Node", "Quantize control voltages",0,laui_QuantizeNode,sizeof(laSynthNodeQuantize),lapost_Node,0,1);
    LA_PC_IDN_QUANTIZE=pc; laPropContainerExtraFunctions(pc,0,0,0,0,laui_DefaultNodeOperationsPropUiDefine);
    laAddSubGroup(pc,"base","Base","Base node","la_base_node",0,0,0,0,0,0,0,0,0,0,0,LA_UDF_LOCAL);
    laAddSubGroup(pc,"in", "Input","CV input","la_in_socket",0,0,0,offsetof(laSynthNodeQuantize,In),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    laAddSubGroup(pc,"out", "Output","CV output","la_out_socket",0,0,0,offsetof(laSynthNodeQuantize,Out),0,0,0,0,0,0,0,LA_UDF_SINGLE);
    p=laAddEnumProperty(pc,"enabled_keys","Keys","Enabled keys",LA_WIDGET_ENUM_CYCLE,0,0,0,0,offsetof(laSynthNodeQuantize,EnabledBits),0,0,12,0,laset_QuantizeEnabledKeys,0,0,0,0,0);
    laAddEnumItemAs(p,"DISABLED","Disabled","Key is disabled",0,' ');
    laAddEnumItemAs(p,"ENABLED","Enabled","Key is enabled",1,' ');
    laAddEnumItemAs(p,"OUTPUT","Outputting","Key is Outputting",3,U'🌑');

    LA_IDN_REGISTER("Inputs",U'🔌',LA_IDN_INPUT, LA_PC_IDN_INPUT, IDN_Input, laSynthNodeInput);
    LA_IDN_REGISTER("Pulse",U'⎍',LA_IDN_PULSE, LA_PC_IDN_PULSE, IDN_Pulse, laSynthNodePulse);
    LA_IDN_REGISTER("VCO",'f',LA_IDN_FM, LA_PC_IDN_FM, IDN_FM, laSynthNodeFM);
    LA_IDN_REGISTER("VCA",'a',LA_IDN_VCA, LA_PC_IDN_VCA, IDN_VCA, laSynthNodeVCA);
    LA_IDN_REGISTER("Noise",'~',LA_IDN_NOISE, LA_PC_IDN_NOISE, IDN_Noise, laSynthNodeNoise);
    LA_IDN_REGISTER("Scope",'s',LA_IDN_SCOPE, LA_PC_IDN_SCOPE, IDN_Scope, laSynthNodeScope);
    LA_IDN_REGISTER("Sound Output",U'🕪',LA_IDN_OUTPUT, LA_PC_IDN_OUTPUT, IDN_Output, laSynthNodeOutput);
    LA_IDN_REGISTER("Envelope",U'^',LA_IDN_ENVELOPE, LA_PC_IDN_ENVELOPE, IDN_Envelope, laSynthNodeEnvelope);
    LA_IDN_REGISTER("Quantize",U'#',LA_IDN_QUANTIZE, LA_PC_IDN_QUANTIZE, IDN_Quantize, laSynthNodeQuantize);
    LA_IDN_REGISTER("Sound Player",U'⏯',LA_IDN_SYNTH_DRIVER, LA_PC_IDN_SYNTH_DRIVER, IDN_SynthDriver, laSynthNodeDriver);
    LA_IDN_REGISTER("Sound Trigger",U'🎵',LA_IDN_SYNTH_TRIGGER, LA_PC_IDN_SYNTH_TRIGGER, IDN_SynthTrigger, laSynthNodeTrigger);
    
    LA_NODE_CATEGORY_SYNTHESIZER=laEnsureNodeCategory("OSC",0,LA_RACK_TYPE_AUDIO);
    LA_NODE_CATEGORY_SYSTEM_SOUND=laEnsureNodeCategory("System",0,LA_RACK_TYPE_AUDIO);

    laNodeCategoryAddNodeTypes(LA_NODE_CATEGORY_SYNTHESIZER,
        &LA_IDN_INPUT,&LA_IDN_PULSE,&LA_IDN_FM,&LA_IDN_NOISE,&LA_IDN_VCA,&LA_IDN_ENVELOPE,&LA_IDN_QUANTIZE,&LA_IDN_SCOPE,&LA_IDN_SYNTH_TRIGGER,0LL);
    laNodeCategoryAddNodeTypes(LA_NODE_CATEGORY_SYSTEM_SOUND, &LA_IDN_OUTPUT,0LL);

    LA_NODE_CATEGORY_DRIVER=laEnsureNodeCategory("Driver",0,LA_RACK_TYPE_DRIVER);
    laNodeCategoryAddNodeTypes(LA_NODE_CATEGORY_DRIVER, &LA_IDN_SYNTH_DRIVER, &LA_IDN_SYNTH_TRIGGER,0LL);
}